@vellumai/assistant 0.11.9 → 0.11.10-dev.202609091114.7b6342c

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 (433) hide show
  1. package/ARCHITECTURE.md +2 -2
  2. package/Dockerfile +6 -12
  3. package/docs/architecture/memory.md +17 -9
  4. package/docs/guardian-request-flow.md +7 -4
  5. package/docs/runbook-trusted-contacts.md +13 -2
  6. package/node_modules/@vellumai/ces-client/node_modules/@vellumai/service-contracts/package.json +3 -1
  7. package/node_modules/@vellumai/ces-client/node_modules/@vellumai/service-contracts/src/__tests__/plan-credit.test.ts +51 -0
  8. package/node_modules/@vellumai/ces-client/node_modules/@vellumai/service-contracts/src/__tests__/secret-detection.test.ts +2 -0
  9. package/node_modules/@vellumai/ces-client/node_modules/@vellumai/service-contracts/src/desktop-presence.ts +11 -0
  10. package/node_modules/@vellumai/ces-client/node_modules/@vellumai/service-contracts/src/index.ts +1 -0
  11. package/node_modules/@vellumai/ces-client/node_modules/@vellumai/service-contracts/src/plan-credit.ts +66 -0
  12. package/node_modules/@vellumai/ces-client/node_modules/@vellumai/service-contracts/src/secret-detection.ts +7 -0
  13. package/node_modules/@vellumai/gateway-client/node_modules/@vellumai/service-contracts/package.json +3 -1
  14. package/node_modules/@vellumai/gateway-client/node_modules/@vellumai/service-contracts/src/__tests__/plan-credit.test.ts +51 -0
  15. package/node_modules/@vellumai/gateway-client/node_modules/@vellumai/service-contracts/src/__tests__/secret-detection.test.ts +2 -0
  16. package/node_modules/@vellumai/gateway-client/node_modules/@vellumai/service-contracts/src/desktop-presence.ts +11 -0
  17. package/node_modules/@vellumai/gateway-client/node_modules/@vellumai/service-contracts/src/index.ts +1 -0
  18. package/node_modules/@vellumai/gateway-client/node_modules/@vellumai/service-contracts/src/plan-credit.ts +66 -0
  19. package/node_modules/@vellumai/gateway-client/node_modules/@vellumai/service-contracts/src/secret-detection.ts +7 -0
  20. package/node_modules/@vellumai/gateway-client/src/gateway-ipc-contracts.ts +72 -0
  21. package/node_modules/@vellumai/service-contracts/package.json +3 -1
  22. package/node_modules/@vellumai/service-contracts/src/__tests__/plan-credit.test.ts +51 -0
  23. package/node_modules/@vellumai/service-contracts/src/__tests__/secret-detection.test.ts +2 -0
  24. package/node_modules/@vellumai/service-contracts/src/desktop-presence.ts +11 -0
  25. package/node_modules/@vellumai/service-contracts/src/index.ts +1 -0
  26. package/node_modules/@vellumai/service-contracts/src/plan-credit.ts +66 -0
  27. package/node_modules/@vellumai/service-contracts/src/secret-detection.ts +7 -0
  28. package/openapi.yaml +729 -63
  29. package/package.json +1 -1
  30. package/src/__tests__/agent-loop-mutable-latest-user-message.test.ts +19 -21
  31. package/src/__tests__/assistant-event-hub-machine-name.test.ts +40 -0
  32. package/src/__tests__/assistant-event-hub.test.ts +45 -0
  33. package/src/__tests__/cli-memory-v2-reembed-skills.test.ts +0 -1
  34. package/src/__tests__/compactor-assistant-tail-preview.test.ts +111 -0
  35. package/src/__tests__/compactor-tail-resolution.test.ts +116 -0
  36. package/src/__tests__/computer-use-native-history.test.ts +30 -0
  37. package/src/__tests__/computer-use-window-schema.test.ts +24 -0
  38. package/src/__tests__/config-get-vision-flag.test.ts +36 -0
  39. package/src/__tests__/config-loader-validation-reset-notice.test.ts +47 -15
  40. package/src/__tests__/context-search-conversations-source.test.ts +27 -5
  41. package/src/__tests__/conversation-agent-loop-overflow.test.ts +189 -195
  42. package/src/__tests__/conversation-agent-loop.test.ts +690 -50
  43. package/src/__tests__/conversation-fork-crud.test.ts +132 -45
  44. package/src/__tests__/conversation-fork-retrospective.test.ts +9 -7
  45. package/src/__tests__/conversation-lifecycle.test.ts +684 -10
  46. package/src/__tests__/conversation-pairing.test.ts +10 -9
  47. package/src/__tests__/conversation-runtime-assembly.test.ts +288 -1
  48. package/src/__tests__/conversation-surfaces-history-restored-completion.test.ts +21 -4
  49. package/src/__tests__/conversation-surfaces-point-at-budget.test.ts +150 -0
  50. package/src/__tests__/conversation-surfaces-point-at-capability.test.ts +161 -0
  51. package/src/__tests__/copy-composer-tc-templates.test.ts +2 -2
  52. package/src/__tests__/credential-security-invariants.test.ts +1 -0
  53. package/src/__tests__/delivered-post-record.test.ts +107 -0
  54. package/src/__tests__/guardian-action-service-scope.test.ts +53 -0
  55. package/src/__tests__/guardian-question-mode.test.ts +88 -138
  56. package/src/__tests__/headless-browser-mode.test.ts +63 -13
  57. package/src/__tests__/heartbeat-disk-pressure.test.ts +2 -0
  58. package/src/__tests__/heartbeat-service.test.ts +118 -27
  59. package/src/__tests__/host-cu-proxy.test.ts +159 -1
  60. package/src/__tests__/host-proxy-interface.test.ts +15 -0
  61. package/src/__tests__/host-proxy-preactivation.test.ts +61 -0
  62. package/src/__tests__/injector-chain.test.ts +3 -3
  63. package/src/__tests__/injector-registry-order-guard.test.ts +1 -1
  64. package/src/__tests__/injector-v3-suppression.test.ts +587 -45
  65. package/src/__tests__/llm-schema.test.ts +70 -2
  66. package/src/__tests__/logger.test.ts +33 -32
  67. package/src/__tests__/mcp-config-secret-boundary.test.ts +2 -0
  68. package/src/__tests__/memory-config-file-parity.test.ts +18 -0
  69. package/src/__tests__/memory-retrieval-hook.test.ts +53 -3
  70. package/src/__tests__/messages-read-boundary-guard.test.ts +0 -1
  71. package/src/__tests__/messaging-send-tool.test.ts +251 -128
  72. package/src/__tests__/messaging-shared.test.ts +19 -0
  73. package/src/__tests__/notification-decision-fallback.test.ts +98 -76
  74. package/src/__tests__/notification-decision-strategy.test.ts +10 -38
  75. package/src/__tests__/notification-events-source-context-probe.test.ts +211 -0
  76. package/src/__tests__/openai-responses-prompt-cache.test.ts +7 -2
  77. package/src/__tests__/openai-responses-provider.test.ts +42 -0
  78. package/src/__tests__/outlook-messaging-provider.test.ts +9 -0
  79. package/src/__tests__/platform-callback-registration.test.ts +162 -3
  80. package/src/__tests__/plugin-api-webhook-url.test.ts +66 -4
  81. package/src/__tests__/plugin-import-boundary-guard.test.ts +1 -0
  82. package/src/__tests__/pricing.test.ts +29 -0
  83. package/src/__tests__/prompt-cache-cross-turn-stability.test.ts +63 -3
  84. package/src/__tests__/scheduler-result-notification.test.ts +209 -0
  85. package/src/__tests__/strip-memory-injections.test.ts +75 -27
  86. package/src/__tests__/tool-approval-seed-content-blocks.test.ts +4 -13
  87. package/src/acp/auto-install.test.ts +35 -1
  88. package/src/acp/resolve-agent.test.ts +3 -3
  89. package/src/agent/loop.ts +116 -45
  90. package/src/api/constants/personality-sliders.test.ts +21 -0
  91. package/src/api/constants/personality-sliders.ts +64 -0
  92. package/src/api/events/contact-record-request.ts +16 -4
  93. package/src/api/events/contact-request.ts +10 -1
  94. package/src/api/index.ts +12 -0
  95. package/src/api/responses/memory-v3-selection-log.ts +64 -13
  96. package/src/api/surfaces.ts +6 -5
  97. package/src/background-wake/next-wake.test.ts +13 -0
  98. package/src/background-wake/next-wake.ts +4 -2
  99. package/src/calls/__tests__/voice-session-bridge.test.ts +166 -0
  100. package/src/calls/__tests__/voice-turn-sight-hold.test.ts +301 -0
  101. package/src/calls/voice-session-bridge.ts +162 -1
  102. package/src/calls/voice-triage-escalate.ts +1 -1
  103. package/src/channels/types.ts +14 -0
  104. package/src/cli/__tests__/catalog-search-help.test.ts +1 -0
  105. package/src/cli/__tests__/contacts-address-prompt-cli.test.ts +701 -0
  106. package/src/cli/__tests__/contacts-record-prompt-cli.test.ts +276 -15
  107. package/src/cli/__tests__/roadmap-cli.test.ts +313 -0
  108. package/src/cli/__tests__/run-assistant-command.ts +59 -20
  109. package/src/cli/commands/__tests__/conversations-slack.test.ts +12 -0
  110. package/src/cli/commands/__tests__/plugins-search.test.ts +81 -0
  111. package/src/cli/commands/config.help.ts +3 -1
  112. package/src/cli/commands/contacts.help.ts +179 -12
  113. package/src/cli/commands/contacts.ts +442 -47
  114. package/src/cli/commands/memory/worker.ts +1 -1
  115. package/src/cli/commands/platform/__tests__/credits-format.test.ts +152 -0
  116. package/src/cli/commands/platform/__tests__/credits.test.ts +20 -0
  117. package/src/cli/commands/platform/credits-format.ts +108 -0
  118. package/src/cli/commands/platform/index.help.ts +33 -11
  119. package/src/cli/commands/platform/index.ts +7 -18
  120. package/src/cli/commands/plugins.help.ts +4 -1
  121. package/src/cli/commands/plugins.ts +2 -1
  122. package/src/cli/commands/roadmap.help.ts +171 -0
  123. package/src/cli/commands/roadmap.ts +358 -0
  124. package/src/cli/index.help.ts +2 -0
  125. package/src/cli/lib/__tests__/cli-output.test.ts +5 -0
  126. package/src/cli/lib/cli-output.ts +6 -6
  127. package/src/cli/program.ts +2 -0
  128. package/src/config/__tests__/webhook-routing.test.ts +42 -0
  129. package/src/config/acp-defaults.test.ts +3 -3
  130. package/src/config/acp-defaults.ts +5 -5
  131. package/src/config/bundled-skills/acp/SKILL.md +8 -11
  132. package/src/config/bundled-skills/computer-use/SKILL.md +21 -0
  133. package/src/config/bundled-skills/computer-use/TOOLS.json +6 -0
  134. package/src/config/bundled-skills/contacts/SKILL.md +61 -11
  135. package/src/config/bundled-skills/messaging/SKILL.md +2 -0
  136. package/src/config/bundled-skills/messaging/TOOLS.json +4 -4
  137. package/src/config/bundled-skills/messaging/tools/messaging-send.ts +160 -36
  138. package/src/config/bundled-skills/messaging/tools/shared.ts +6 -0
  139. package/src/config/bundled-skills/schedule/SKILL.md +10 -2
  140. package/src/config/bundled-skills/screen-annotation/SKILL.md +80 -0
  141. package/src/config/bundled-skills/screen-annotation/TOOLS.json +73 -0
  142. package/src/config/bundled-skills/screen-annotation/tools/screen-annotation.test.ts +74 -0
  143. package/src/config/bundled-skills/screen-annotation/tools/screen-clear-marks.ts +33 -0
  144. package/src/config/bundled-skills/screen-annotation/tools/screen-point-at.ts +25 -0
  145. package/src/config/env-registry.ts +2 -0
  146. package/src/config/feature-flag-registry.json +39 -7
  147. package/src/config/input-modalities.test.ts +71 -0
  148. package/src/config/input-modalities.ts +95 -0
  149. package/src/config/loader.ts +2 -0
  150. package/src/config/schemas/__tests__/memory-v3.test.ts +58 -15
  151. package/src/config/schemas/heartbeat.ts +3 -3
  152. package/src/config/schemas/llm.ts +47 -10
  153. package/src/config/schemas/memory-storage.test.ts +39 -0
  154. package/src/config/schemas/memory-storage.ts +21 -0
  155. package/src/config/schemas/memory-v3.ts +73 -46
  156. package/src/config/schemas/services.ts +18 -0
  157. package/src/config/webhook-routing.ts +12 -2
  158. package/src/context/compactor.ts +12 -13
  159. package/src/context/strip-injections.ts +29 -25
  160. package/src/context/token-estimator.ts +2 -2
  161. package/src/daemon/__tests__/embedding-reconcile.test.ts +77 -0
  162. package/src/daemon/__tests__/lifecycle-embedding-reconcile.test.ts +3 -0
  163. package/src/daemon/__tests__/turn-actor.test.ts +68 -0
  164. package/src/daemon/conversation-agent-loop-handlers.ts +152 -22
  165. package/src/daemon/conversation-agent-loop.ts +19 -3
  166. package/src/daemon/conversation-messaging.ts +3 -2
  167. package/src/daemon/conversation-runtime-assembly.ts +191 -69
  168. package/src/daemon/conversation-surfaces.ts +32 -62
  169. package/src/daemon/conversation.ts +153 -46
  170. package/src/daemon/embedding-reconcile.ts +64 -1
  171. package/src/daemon/handlers/config-embeddings.ts +31 -0
  172. package/src/daemon/host-cu-proxy.ts +66 -50
  173. package/src/daemon/host-cu-target.ts +139 -0
  174. package/src/daemon/host-proxy-preactivation.ts +29 -1
  175. package/src/daemon/mcp-reload-service.ts +6 -0
  176. package/src/daemon/providers-setup.ts +5 -26
  177. package/src/daemon/trust-context.ts +1 -1
  178. package/src/daemon/turn-actor.ts +46 -0
  179. package/src/heartbeat/heartbeat-service.ts +72 -13
  180. package/src/inbound/platform-callback-registration.ts +77 -11
  181. package/src/inbound/pod-webhook-claim.ts +35 -0
  182. package/src/inbound/velay-webhooks-gate.ts +20 -0
  183. package/src/ipc/gateway-client.ts +91 -0
  184. package/src/live-voice/__tests__/live-voice-photo.test.ts +174 -0
  185. package/src/live-voice/__tests__/live-voice-session-guardian.test.ts +127 -0
  186. package/src/live-voice/__tests__/live-voice-session-telemetry.test.ts +42 -2
  187. package/src/live-voice/__tests__/live-voice-sight-frame.test.ts +81 -0
  188. package/src/live-voice/__tests__/protocol.test.ts +67 -0
  189. package/src/live-voice/live-voice-connection.ts +14 -1
  190. package/src/live-voice/live-voice-photo.ts +109 -4
  191. package/src/live-voice/live-voice-session-manager.ts +10 -1
  192. package/src/live-voice/live-voice-session.ts +196 -31
  193. package/src/live-voice/protocol.ts +134 -1
  194. package/src/mcp/__tests__/reload-signal-emission.test.ts +54 -0
  195. package/src/mcp/__tests__/reload-signal.test.ts +57 -0
  196. package/src/mcp/__tests__/startup.test.ts +150 -0
  197. package/src/mcp/reload-signal.ts +50 -0
  198. package/src/mcp/startup.ts +101 -0
  199. package/src/messaging/providers/outlook/adapter.ts +2 -13
  200. package/src/messaging/providers/outlook/client.ts +13 -1
  201. package/src/messaging/providers/outlook/types.ts +3 -0
  202. package/src/messaging/providers/telegram-bot/adapter.ts +9 -2
  203. package/src/messaging/providers/telegram-bot/client.ts +8 -2
  204. package/src/messaging/providers/whatsapp/adapter.ts +9 -2
  205. package/src/messaging/providers/whatsapp/client.ts +8 -2
  206. package/src/notifications/AGENTS.md +5 -0
  207. package/src/notifications/README.md +21 -7
  208. package/src/notifications/__tests__/assistant-reply-producer.test.ts +3 -10
  209. package/src/notifications/__tests__/background-failure-signal.test.ts +96 -0
  210. package/src/notifications/__tests__/broadcaster.test.ts +171 -7
  211. package/src/notifications/__tests__/decision-engine.test.ts +79 -6
  212. package/src/notifications/__tests__/edit-notification.test.ts +59 -0
  213. package/src/notifications/__tests__/resolve-visible-in-source.test.ts +96 -0
  214. package/src/notifications/__tests__/schedule-result-producer.test.ts +397 -0
  215. package/src/notifications/access-request-copy.ts +5 -5
  216. package/src/notifications/approval-card-data.ts +29 -13
  217. package/src/notifications/assistant-reply-producer.ts +0 -4
  218. package/src/notifications/background-failure-signal.ts +13 -1
  219. package/src/notifications/broadcaster.ts +65 -2
  220. package/src/notifications/conversation-pairing.ts +263 -155
  221. package/src/notifications/copy-composer.ts +38 -22
  222. package/src/notifications/decision-engine.ts +89 -61
  223. package/src/notifications/delivered-post-record.ts +81 -0
  224. package/src/notifications/deliveries-store.ts +8 -1
  225. package/src/notifications/edit-notification.ts +16 -0
  226. package/src/notifications/events-store.ts +68 -2
  227. package/src/notifications/guardian-question-mode.ts +24 -232
  228. package/src/notifications/home-feed-side-effect.ts +1 -0
  229. package/src/notifications/notification-utils.ts +13 -5
  230. package/src/notifications/resolve-visible-in-source.ts +56 -0
  231. package/src/notifications/schedule-result-producer.ts +275 -0
  232. package/src/notifications/signal.ts +5 -0
  233. package/src/oauth/__tests__/seed-providers-managed.test.ts +82 -0
  234. package/src/oauth/seed-providers.ts +201 -3
  235. package/src/onboarding/onboarding-events-store.ts +14 -8
  236. package/src/persistence/conversation-crud.ts +68 -19
  237. package/src/persistence/embeddings/embedding-backend.test.ts +162 -0
  238. package/src/persistence/embeddings/embedding-backend.ts +148 -11
  239. package/src/persistence/embeddings/embedding-gemini.test.ts +328 -9
  240. package/src/persistence/embeddings/embedding-gemini.ts +211 -27
  241. package/src/persistence/embeddings/embedding-openai.test.ts +113 -0
  242. package/src/persistence/embeddings/embedding-openai.ts +55 -4
  243. package/src/persistence/embeddings/embedding-types.test.ts +24 -0
  244. package/src/persistence/embeddings/embedding-types.ts +25 -1
  245. package/src/persistence/job-utils.ts +6 -2
  246. package/src/persistence/message-metadata.ts +20 -0
  247. package/src/persistence/migrations/283-memory-v3-selections-message-id-and-sections.ts +2 -1
  248. package/src/persistence/migrations/376-notification-deliveries-canonical-message-id.ts +37 -0
  249. package/src/persistence/schema/memory-injection.ts +31 -9
  250. package/src/persistence/schema/notifications.ts +8 -0
  251. package/src/persistence/steps.ts +2 -0
  252. package/src/plugin-api/index.ts +2 -1
  253. package/src/plugin-api/vision-support.test.ts +81 -0
  254. package/src/plugin-api/vision-support.ts +57 -10
  255. package/src/plugin-api/webhook-url.ts +18 -4
  256. package/src/plugins/AGENTS.md +1 -1
  257. package/src/plugins/defaults/channel/injectors.ts +3 -1
  258. package/src/plugins/defaults/injector-order.ts +2 -2
  259. package/src/plugins/defaults/memory/AGENTS.md +263 -30
  260. package/src/plugins/defaults/memory/__tests__/conversation-memory-orphan-sweep.test.ts +4 -0
  261. package/src/plugins/defaults/memory/__tests__/conversation-memory-purge.test.ts +6 -0
  262. package/src/plugins/defaults/memory/__tests__/db-memory-attach.test.ts +9 -3
  263. package/src/plugins/defaults/memory/__tests__/memory-log-stores-degraded.test.ts +3 -7
  264. package/src/plugins/defaults/memory/__tests__/relocated-memory-test-rows.ts +18 -0
  265. package/src/plugins/defaults/memory/context-search/sources/conversations.ts +16 -2
  266. package/src/plugins/defaults/memory/conversation-memory-purge.ts +2 -0
  267. package/src/plugins/defaults/memory/fork-conversation-memory.ts +13 -13
  268. package/src/plugins/defaults/memory/graph/__tests__/conversation-graph-memory-v2-routing.test.ts +19 -12
  269. package/src/plugins/defaults/memory/graph/conversation-graph-memory.ts +17 -15
  270. package/src/plugins/defaults/memory/graph-topology/build-memory-graph.ts +1 -1
  271. package/src/plugins/defaults/memory/hooks/__tests__/post-compact.test.ts +121 -0
  272. package/src/plugins/defaults/memory/hooks/init.ts +10 -0
  273. package/src/plugins/defaults/memory/hooks/injection-metadata.ts +100 -0
  274. package/src/plugins/defaults/memory/hooks/post-compact.ts +19 -7
  275. package/src/plugins/defaults/memory/hooks/user-prompt-submit.ts +11 -83
  276. package/src/plugins/defaults/memory/injectors.ts +4 -4
  277. package/src/plugins/defaults/memory/job-handlers.ts +4 -1
  278. package/src/plugins/defaults/memory/jobs/__tests__/embed-concept-page.test.ts +1 -0
  279. package/src/plugins/defaults/memory/jobs/embed-concept-page.ts +11 -3
  280. package/src/plugins/defaults/memory/memory-db.ts +4 -0
  281. package/src/plugins/defaults/memory/memory-marker.ts +28 -17
  282. package/src/plugins/defaults/memory/src/__tests__/memory-v2-simulate-route.test.ts +0 -1
  283. package/src/plugins/defaults/memory/src/__tests__/memory-worker-routes.test.ts +20 -0
  284. package/src/plugins/defaults/memory/src/memory-item-routes.test.ts +0 -1
  285. package/src/plugins/defaults/memory/src/memory-worker-routes.ts +3 -1
  286. package/src/plugins/defaults/memory/substrate/__tests__/cli-command-store.test.ts +1 -1
  287. package/src/plugins/defaults/memory/substrate/__tests__/consolidation-job.test.ts +66 -0
  288. package/src/plugins/defaults/memory/substrate/__tests__/injected-block-slugs.test.ts +345 -0
  289. package/src/plugins/defaults/memory/substrate/__tests__/page-index.test.ts +0 -1
  290. package/src/plugins/defaults/memory/substrate/__tests__/prompts-consolidation.test.ts +170 -1
  291. package/src/plugins/defaults/memory/substrate/__tests__/reembed-job.test.ts +1 -0
  292. package/src/plugins/defaults/memory/substrate/capability-slugs.ts +53 -0
  293. package/src/plugins/defaults/memory/substrate/cli-command-store.ts +4 -18
  294. package/src/plugins/defaults/memory/substrate/consolidation-job.ts +40 -1
  295. package/src/plugins/defaults/memory/substrate/ingest.ts +11 -9
  296. package/src/plugins/defaults/memory/substrate/injected-block-slugs.ts +426 -42
  297. package/src/plugins/defaults/memory/substrate/page-index.ts +5 -4
  298. package/src/plugins/defaults/memory/substrate/prompts/consolidation.ts +127 -14
  299. package/src/plugins/defaults/memory/substrate/skill-store.ts +1 -18
  300. package/src/plugins/defaults/memory/v2/__tests__/backfill-jobs.test.ts +1 -0
  301. package/src/plugins/defaults/memory/v2/__tests__/injection.test.ts +2 -8
  302. package/src/plugins/defaults/memory/v2/__tests__/router.test.ts +0 -1
  303. package/src/plugins/defaults/memory/v2/injection.ts +4 -4
  304. package/src/plugins/defaults/memory/v3/__tests__/capabilities.test.ts +16 -0
  305. package/src/plugins/defaults/memory/v3/__tests__/carry-integration.test.ts +1004 -319
  306. package/src/plugins/defaults/memory/v3/__tests__/dense.test.ts +227 -4
  307. package/src/plugins/defaults/memory/v3/__tests__/injection.test.ts +836 -263
  308. package/src/plugins/defaults/memory/v3/__tests__/live-integration.test.ts +65 -38
  309. package/src/plugins/defaults/memory/v3/__tests__/maintain-job.test.ts +354 -3
  310. package/src/plugins/defaults/memory/v3/__tests__/orchestrate.test.ts +688 -104
  311. package/src/plugins/defaults/memory/v3/__tests__/overlong-sections.test.ts +109 -0
  312. package/src/plugins/defaults/memory/v3/__tests__/page-content.test.ts +144 -0
  313. package/src/plugins/defaults/memory/v3/__tests__/plugin-schema.test.ts +534 -0
  314. package/src/plugins/defaults/memory/v3/__tests__/pool-log-store.test.ts +449 -0
  315. package/src/plugins/defaults/memory/v3/__tests__/pool-select.test.ts +265 -27
  316. package/src/plugins/defaults/memory/v3/__tests__/render-injection.test.ts +34 -117
  317. package/src/plugins/defaults/memory/v3/__tests__/section-dense-store.test.ts +491 -4
  318. package/src/plugins/defaults/memory/v3/__tests__/section-needle.test.ts +124 -1
  319. package/src/plugins/defaults/memory/v3/__tests__/sections.test.ts +264 -4
  320. package/src/plugins/defaults/memory/v3/__tests__/selection-log-store.test.ts +560 -22
  321. package/src/plugins/defaults/memory/v3/__tests__/shadow-integration.test.ts +40 -33
  322. package/src/plugins/defaults/memory/v3/__tests__/shadow-plugin.test.ts +718 -63
  323. package/src/plugins/defaults/memory/v3/__tests__/types.test.ts +83 -2
  324. package/src/plugins/defaults/memory/v3/candidate-match.ts +1 -1
  325. package/src/plugins/defaults/memory/v3/capabilities.ts +90 -14
  326. package/src/plugins/defaults/memory/v3/card.test.ts +15 -16
  327. package/src/plugins/defaults/memory/v3/card.ts +16 -15
  328. package/src/plugins/defaults/memory/v3/dense.ts +10 -0
  329. package/src/plugins/defaults/memory/v3/ever-injected-store.test.ts +643 -140
  330. package/src/plugins/defaults/memory/v3/ever-injected-store.ts +462 -212
  331. package/src/plugins/defaults/memory/v3/hot-set.test.ts +2 -2
  332. package/src/plugins/defaults/memory/v3/injector.ts +366 -278
  333. package/src/plugins/defaults/memory/v3/learned-edges.test.ts +2 -2
  334. package/src/plugins/defaults/memory/v3/maintain-job.ts +299 -73
  335. package/src/plugins/defaults/memory/v3/orchestrate.ts +327 -214
  336. package/src/plugins/defaults/memory/v3/overlong-sections.ts +83 -0
  337. package/src/plugins/defaults/memory/v3/page-content.ts +72 -92
  338. package/src/plugins/defaults/memory/v3/plugin-schema.ts +346 -0
  339. package/src/plugins/defaults/memory/v3/pool-log-store.ts +291 -0
  340. package/src/plugins/defaults/memory/v3/pool-select.test.ts +2 -2
  341. package/src/plugins/defaults/memory/v3/pool-select.ts +160 -60
  342. package/src/plugins/defaults/memory/v3/prune.test.ts +1042 -329
  343. package/src/plugins/defaults/memory/v3/prune.ts +433 -270
  344. package/src/plugins/defaults/memory/v3/rare-term-lane.test.ts +269 -0
  345. package/src/plugins/defaults/memory/v3/rare-term-lane.ts +141 -0
  346. package/src/plugins/defaults/memory/v3/render-injection.ts +43 -82
  347. package/src/plugins/defaults/memory/v3/section-dense-store.ts +316 -28
  348. package/src/plugins/defaults/memory/v3/section-needle.ts +145 -11
  349. package/src/plugins/defaults/memory/v3/sections.ts +103 -16
  350. package/src/plugins/defaults/memory/v3/selection-log-store.ts +243 -78
  351. package/src/plugins/defaults/memory/v3/shadow-plugin.ts +189 -68
  352. package/src/plugins/defaults/memory/v3/tuning-profile.ts +6 -0
  353. package/src/plugins/defaults/memory/v3/types.ts +169 -23
  354. package/src/plugins/defaults/memory/v3-eval/__tests__/eval-packets.test.ts +21 -4
  355. package/src/plugins/defaults/memory/v3-eval/eval-packets.ts +77 -26
  356. package/src/plugins/types.ts +14 -0
  357. package/src/providers/__tests__/connection-model-compat.test.ts +1 -0
  358. package/src/providers/__tests__/provider-secret-catalog.test.ts +4 -0
  359. package/src/providers/__tests__/xml-tool-call-salvage.test.ts +172 -0
  360. package/src/providers/inline-audio-support.test.ts +34 -0
  361. package/src/providers/inline-audio-support.ts +27 -0
  362. package/src/providers/model-catalog.ts +102 -0
  363. package/src/providers/openai/__tests__/chat-completions-extra-body.test.ts +51 -0
  364. package/src/providers/openai/__tests__/chat-completions-provider-xml-salvage.test.ts +291 -0
  365. package/src/providers/openai/chat-completions-provider.ts +114 -14
  366. package/src/providers/openai/codex-models.ts +1 -0
  367. package/src/providers/openai/responses-provider.ts +65 -15
  368. package/src/providers/opencode/client.test.ts +24 -0
  369. package/src/providers/opencode/client.ts +6 -1
  370. package/src/providers/provider-secret-catalog.ts +11 -1
  371. package/src/providers/retry.ts +6 -0
  372. package/src/providers/vellum/client.ts +14 -1
  373. package/src/providers/vellum/personality-directions.test.ts +163 -0
  374. package/src/providers/vellum/personality-directions.ts +120 -0
  375. package/src/providers/xml-tool-call-salvage.ts +212 -0
  376. package/src/runtime/AGENTS.md +7 -2
  377. package/src/runtime/__tests__/background-job-runner.test.ts +115 -0
  378. package/src/runtime/__tests__/guardian-form-registry.test.ts +0 -32
  379. package/src/runtime/__tests__/host-observe.test.ts +44 -0
  380. package/src/runtime/assistant-event-hub.ts +14 -9
  381. package/src/runtime/auth/__tests__/guard-tests.test.ts +1 -4
  382. package/src/runtime/auth/__tests__/route-policy.test.ts +65 -0
  383. package/src/runtime/auth/same-actor.ts +4 -3
  384. package/src/runtime/background-job-runner.ts +10 -0
  385. package/src/runtime/channel-reply-delivery.ts +1 -162
  386. package/src/runtime/guardian-action-service.ts +20 -1
  387. package/src/runtime/host-observe.ts +56 -6
  388. package/src/runtime/http-server.ts +35 -0
  389. package/src/runtime/outbound-post-reconciliation.ts +183 -0
  390. package/src/runtime/routes/__tests__/contact-address-prompt-route.test.ts +231 -0
  391. package/src/runtime/routes/__tests__/contact-record-prompt-route.test.ts +59 -3
  392. package/src/runtime/routes/__tests__/guardian-form-routes.test.ts +85 -0
  393. package/src/runtime/routes/__tests__/heartbeat-routes.test.ts +24 -0
  394. package/src/runtime/routes/__tests__/platform-credits-routes.test.ts +239 -0
  395. package/src/runtime/routes/__tests__/roadmap-routes.test.ts +469 -0
  396. package/src/runtime/routes/__tests__/watch-routes.test.ts +70 -1
  397. package/src/runtime/routes/__tests__/webhook-routes.test.ts +83 -0
  398. package/src/runtime/routes/contact-prompt-routes.ts +177 -28
  399. package/src/runtime/routes/conversation-query-routes.ts +53 -11
  400. package/src/runtime/routes/events-routes.ts +13 -3
  401. package/src/runtime/routes/guardian-action-routes.ts +7 -0
  402. package/src/runtime/routes/guardian-form-routes.ts +6 -4
  403. package/src/runtime/routes/heartbeat-routes.ts +41 -53
  404. package/src/runtime/routes/index.ts +2 -2
  405. package/src/runtime/routes/integrations/a2a.ts +12 -3
  406. package/src/runtime/routes/integrations/vercel.ts +13 -3
  407. package/src/runtime/routes/platform-routes.ts +175 -23
  408. package/src/runtime/routes/roadmap-routes.ts +744 -0
  409. package/src/runtime/routes/watch-routes.ts +50 -0
  410. package/src/runtime/routes/webhook-routes.ts +24 -2
  411. package/src/runtime/web-presence.ts +13 -9
  412. package/src/schedule/__tests__/schedule-timezone.test.ts +21 -3
  413. package/src/schedule/__tests__/worker-mcp-tools.test.ts +88 -0
  414. package/src/schedule/schedule-timezone.ts +25 -0
  415. package/src/schedule/scheduler.ts +19 -0
  416. package/src/schedule/worker.ts +119 -2
  417. package/src/telemetry/__tests__/live-voice-funnel.test.ts +32 -0
  418. package/src/telemetry/live-voice-funnel.ts +33 -0
  419. package/src/tools/acp/list-agents.test.ts +1 -1
  420. package/src/tools/browser/__tests__/browser-status.test.ts +3 -0
  421. package/src/tools/browser/browser-execution.ts +117 -53
  422. package/src/tools/browser/browser-status-constants.ts +6 -6
  423. package/src/tools/capability-offer.test.ts +87 -0
  424. package/src/tools/capability-offer.ts +93 -0
  425. package/src/tools/computer-use/definitions.ts +6 -0
  426. package/src/tools/computer-use/skill-proxy-bridge.ts +10 -0
  427. package/src/tools/terminal/safe-env.ts +2 -0
  428. package/src/watch/__tests__/watch-retro.test.ts +11 -10
  429. package/src/watch/__tests__/watch-session-manager.test.ts +75 -1
  430. package/src/watch/watch-retro.ts +10 -9
  431. package/src/watch/watch-session-manager.ts +17 -0
  432. package/src/runtime/routes/__tests__/sight-frame-routes.test.ts +0 -487
  433. package/src/runtime/routes/sight-frame-routes.ts +0 -136
@@ -13,7 +13,13 @@
13
13
  * - the span-query pass — the dense lane re-run over the current
14
14
  * message's clause chunks as separate queries at a small per-chunk
15
15
  * budget (`spanQueryK`), rescuing motifs a long multi-topic message's
16
- * single query vector averages away — and
16
+ * single query vector averages away,
17
+ * - the entity lane (`entityLane`) and the rare-term lane
18
+ * (`rareTermLane`), which key on one strong token each (a
19
+ * distinctive `## ` heading token the message names; a query word
20
+ * that occurs in at most a handful of sections) so the section a
21
+ * name or a rare word points at surfaces regardless of the
22
+ * message's bulk theme, and
17
23
  * - link-graph edge expansion (`edgeExpand`) over the top
18
24
  * user-message needle+dense article seeds, and
19
25
  * - learned-edge expansion (`edgeExpand` over the co-selection NPMI
@@ -31,9 +37,14 @@
31
37
  * throw inside it logs a warning and falls through to normal selection.
32
38
  * 2. Build the candidate pool in CACHE ORDER: the stable prefix —
33
39
  * `[...core (file order), ...hot (score order), ...fresh (recency order),
34
- * ...always-candidate (skills pinned every turn)]`, all computed at lane
35
- * init — followed by the finder candidates (needle → dense → edge
36
- * surfacing order). The stable prefix
40
+ * ...always-candidate (skills listed every turn)]`, all computed at lane
41
+ * init, followed by the finder candidates (needle → dense → reply →
42
+ * span → entity → rare → edge → learned surfacing order), one line per
43
+ * distinct (page, matched section) and at most `finderSectionsPerPage`
44
+ * lines per page from the lanes other than entity and rare (an entity
45
+ * line and a rare-term line never count against the cap or yield to it;
46
+ * see `poolLine`), so a page whose sections match different parts of
47
+ * the message is shown section by section. The stable prefix
37
48
  * is identical across consecutive turns while the lanes are unchanged
38
49
  * (lane invalidation at consolidation is the recompute cadence), so the
39
50
  * selector input's leading segment rides the provider KV cache (the
@@ -42,16 +53,17 @@
42
53
  * Stable-prefix candidates render as FULL CARDS (`renderCard` — head
43
54
  * section + TOC), pre-rendered at lane init (`prefixCards`) so the
44
55
  * rendered prefix is byte-identical across turns. Finder candidates
45
- * render as compact snippet lines: the matched section's text (or the
46
- * curated `links` description for an edge hit), falling back to the
47
- * page's lead-section text when no match text exists.
56
+ * render as compact snippet lines: the matched section's
57
+ * keyword-in-context window around the query terms that scored it (or
58
+ * the curated `links` description for an edge hit), falling back to
59
+ * the page's lead-section text when no match text exists.
48
60
  *
49
61
  * The finder tail is NOT deduped against the stable prefix: a finder hit
50
62
  * on a core/hot page keeps its matched-section line (and its
51
- * `matchedSections` ref + `lanes.finder` entry), so the selector and the
52
- * section spotlight see that page's CURRENT relevance even though the
53
- * page itself sits in the stable prefix. The selector dedupes selections
54
- * by slug.
63
+ * `lanes.finder` entry), so the selector and the
64
+ * section injection see that page's CURRENT relevance even though the
65
+ * page itself sits in the stable prefix. The selector merges selections
66
+ * per slug, carrying every selected section.
55
67
  * 3. A SINGLE forced-tool select (`selectPool`) over the whole pool. The
56
68
  * result is this turn's selections — current turn only. Cross-turn
57
69
  * persistence is the injector's job (net-new blocks frozen into history),
@@ -65,7 +77,7 @@ import {
65
77
  } from "../../../../daemon/turn-latency-sub-spans.js";
66
78
  import { recordWatchdogEvent } from "../../../../telemetry/watchdog-events-store.js";
67
79
  import { getLogger } from "../logging.js";
68
- import type { DenseHitScored } from "./dense.js";
80
+ import { injectionUnits } from "./capabilities.js";
69
81
  import { denseLaneScored } from "./dense.js";
70
82
  import type { EdgeGraph } from "./edge.js";
71
83
  import { edgeExpand } from "./edge.js";
@@ -78,15 +90,21 @@ import type {
78
90
  StableCandidate,
79
91
  } from "./pool-select.js";
80
92
  import { selectAllPoolCandidates, selectPool } from "./pool-select.js";
93
+ import {
94
+ type RareTermHit,
95
+ rareTermLane,
96
+ type RareTermLaneOptions,
97
+ } from "./rare-term-lane.js";
81
98
  import type { SectionNeedle } from "./section-needle.js";
82
99
  import { spanChunksOf } from "./span-query.js";
83
- import type {
84
- FinderLane,
85
- MemoryRoutingTurn,
86
- Section,
87
- SectionIndex,
88
- SelectedPage,
89
- Slug,
100
+ import {
101
+ type FinderLane,
102
+ type MemoryRoutingTurn,
103
+ type Section,
104
+ type SectionIndex,
105
+ sectionKey,
106
+ type SelectedPage,
107
+ type Slug,
90
108
  } from "./types.js";
91
109
 
92
110
  // Named to disambiguate from the unrelated `src/config/memory-v3-gate.ts`: this
@@ -159,6 +177,10 @@ export const DEFAULT_NEEDLE_K = 12;
159
177
  export const DEFAULT_DENSE_K = 0;
160
178
  /** Default hard cap on entity-lane articles folded into the pool per turn. */
161
179
  export const DEFAULT_ENTITY_CAP = 8;
180
+ /** Contributing query terms carried per finder candidate for its
181
+ * keyword-in-context snippet (the renderer uses the first one that occurs
182
+ * in the section body). */
183
+ const SNIPPET_TERMS = 3;
162
184
 
163
185
  export interface OrchestrateDeps {
164
186
  sectionIndex: SectionIndex;
@@ -180,7 +202,7 @@ export interface OrchestrateDeps {
180
202
  /** The modification-recency fresh set in recency order (computed at lane
181
203
  * init with core and hot excluded). Follows hot in the stable prefix. */
182
204
  freshSlugs: Slug[];
183
- /** Skills pinned into the candidate pool every turn regardless of retrieval
205
+ /** Skills placed in the candidate pool every turn regardless of retrieval
184
206
  * (existence-filtered and core/hot/fresh-excluded at lane init). Follow fresh
185
207
  * in the stable prefix so the selector always sees them. */
186
208
  alwaysCandidateSlugs?: Slug[];
@@ -197,6 +219,21 @@ export interface OrchestrateDeps {
197
219
  /** Hard cap on entity-lane articles. Defaults to {@link DEFAULT_ENTITY_CAP}.
198
220
  * Ignored when `entityIndex` is omitted (the lane is off). */
199
221
  entityCap?: number;
222
+ /** Rare-term lane tuning (canonical value: `memory.v3.rareTerm`): the df
223
+ * ceiling for a query word to count as rare (`maxDf`, lowered on a smaller
224
+ * corpus by `maxDfFraction`), the sections surfaced per rare word, and the
225
+ * per-turn cap. Omitted disables the lane, which the caller does whenever
226
+ * the selector is off: rare lines are candidates for a judge, not evidence
227
+ * strong enough to inject unjudged. */
228
+ rareTerm?: RareTermLaneOptions;
229
+ /** Cap on finder lines one page may carry per turn, applied in surfacing
230
+ * order (needle, dense, reply, span); a section-less edge or learned line
231
+ * counts as one. An entity line and a rare-term line are outside the cap,
232
+ * neither counted against it nor displaced by it (the lanes' own
233
+ * `entityCap` and `rareTerm.cap` bound those per turn), so a page carries
234
+ * at most this many lines plus its entity and rare lines (canonical
235
+ * value, default included: `memory.v3.finderSectionsPerPage`). */
236
+ finderSectionsPerPage: number;
200
237
  /** Per-lane article budget for the reply-query pass (needle + dense re-run
201
238
  * over `turn.previousAssistantMessage` as separate queries). `0` or
202
239
  * omitted disables the pass (canonical value: `memory.v3.replyQueryK`). */
@@ -242,26 +279,36 @@ export interface OrchestrateDeps {
242
279
  * `MEMORY_V3_FULL_PROFILE_MIN_PAGES`; omitted drops the field from the
243
280
  * telemetry detail (the gate itself never reads it). */
244
281
  realConceptPageCount?: number;
245
- /** Slugs already live in this conversation (prior turns' injected cards). Used
246
- * ONLY to compute the `net_new_count` telemetry field — selections minus this
247
- * set are what the injector actually renders. Read-only and side-effect-free:
248
- * selection never consults it, and omitting it just drops the field. The
249
- * injector reads the same store, so the two agree for a turn that has not yet
250
- * committed. */
251
- activeSlugs?: ReadonlySet<Slug>;
282
+ /** Whether one of this turn's injection units (`injectionUnits` in
283
+ * `capabilities.ts`: a selected section, or the lead of a page selected
284
+ * with none, by page slug and section-store key) is already resident in
285
+ * the conversation. Used ONLY to compute the `net_new_count` telemetry
286
+ * field, selections it rejects are what the injector actually renders.
287
+ * Read-only and side-effect-free: selection never consults it, and
288
+ * omitting it just drops the field. The injector reads the same store, so
289
+ * the two agree for a turn that has not yet committed. */
290
+ isResident?: (slug: Slug, key: string) => boolean;
252
291
  }
253
292
 
254
- /** A finder-lane candidate: the slug, the descriptor that justified it, and
255
- * the finder lane that FIRST surfaced it (needle → dense → edge precedence). */
293
+ /** A finder-lane candidate, one pool line: the slug, the matched section
294
+ * when the lane scored one (absent for an edge or learned hit), the query
295
+ * terms that contributed most to that match (best first; they drive the
296
+ * selector's keyword-in-context snippet, and a rare-term line carries the
297
+ * one word it was keyed on as its only term), the descriptor that
298
+ * justified the line, and the lane that surfaced it. One page can carry
299
+ * several candidates, one per distinct matched section, in surfacing
300
+ * order. */
256
301
  export interface FinderCandidate {
257
302
  slug: Slug;
303
+ section?: Section;
304
+ terms?: string[];
258
305
  descriptor: string;
259
306
  lane: FinderLane;
260
307
  }
261
308
 
262
309
  /**
263
- * The candidate lanes in cache order. `core`, `hot`, and `fresh` are the
264
- * stable prefix (byte-identical across turns while lanes are unchanged);
310
+ * The candidate lanes in cache order. `core`, `hot`, `fresh`, and `always` are
311
+ * the stable prefix (byte-identical across turns while lanes are unchanged);
265
312
  * `finder` is the dynamic tail and MAY repeat a stable-prefix slug (a finder
266
313
  * hit on a stable-prefix page is kept so its current relevance stays visible
267
314
  * downstream).
@@ -273,24 +320,31 @@ export interface OrchestrateLanes {
273
320
  hot: Slug[];
274
321
  /** Modification-recency fresh set, recency order (never overlaps core/hot). */
275
322
  fresh: Slug[];
276
- /** Finder candidates in surfacing order, deduped among themselves only. */
323
+ /** Always-candidate skills, install order (never overlaps core/hot/fresh). */
324
+ always: Slug[];
325
+ /** Finder candidates in surfacing order: one per distinct (page, matched
326
+ * section), capped per page, deduped among themselves only. */
277
327
  finder: FinderCandidate[];
278
328
  }
279
329
 
280
330
  export interface OrchestrateResult {
281
- /** This turn's selections, deduped by slug (pinned flags ORed; the dedup is
282
- * `selectPool`'s contract). Current turn only — there is no
331
+ /** This turn's selections, one per slug with the selected finder lines'
332
+ * sections merged in pool order (the merge is `selectPool`'s contract);
333
+ * the injector renders each of them. Current turn only: there is no
283
334
  * carried-forward set unioned in. */
284
335
  selections: SelectedPage[];
285
- /** The matched `Section` for each candidate slug that had one, keyed by slug.
286
- * Populated from the finder-lane hits — including hits on core/hot pages —
287
- * and consumed by the injector to render each selected slug's matched
288
- * section (progressive disclosure). */
289
- matchedSections: Map<Slug, Section>;
290
336
  /** The candidate lanes in cache order; see {@link OrchestrateLanes}. Consumed
291
- * by the selection telemetry (lane attribution) and the downstream selector
292
- * rendering/spotlight. */
337
+ * by the selection telemetry (lane attribution), the per-turn pool record
338
+ * (`pool-log-store.ts`), and the downstream selector rendering. */
293
339
  lanes: OrchestrateLanes;
340
+ /** Whether the selector LLM judged a non-empty pool this turn (the
341
+ * `selector_ran` telemetry field). False when the pool was empty, when the
342
+ * disabled-selector passthrough kept every candidate, and when a closed
343
+ * injection gate hard-skipped selection. On that last path `lanes` still
344
+ * carries the stable prefix as computed, but no pool was ever assembled,
345
+ * so a false value with empty `selections` means the selector was given
346
+ * nothing. */
347
+ selectorRan: boolean;
294
348
  }
295
349
 
296
350
  /** Stable-order de-duplication preserving first occurrence. */
@@ -408,11 +462,12 @@ export async function orchestrate(
408
462
  ),
409
463
  ]),
410
464
  );
411
- // Everything from here to the step-3 selection — finder assembly, the
412
- // entity lane, the injection gate, edge + learned-edge expansion, pool
413
- // assembly — is synchronous in-memory work, measured as one `v3_expand`
414
- // region rather than wrapped calls. Gate-closed early returns skip the
415
- // record on purpose: the expansion work didn't happen on those turns.
465
+ // Everything from here to the step-3 selection (finder assembly, the
466
+ // entity and rare-term lanes, the injection gate, edge + learned-edge
467
+ // expansion, pool assembly) is synchronous in-memory work, measured as one
468
+ // `v3_expand` region rather than wrapped calls. Gate-closed early returns
469
+ // skip the record on purpose: the expansion work didn't happen on those
470
+ // turns.
416
471
  const expandStartedAt = Date.now();
417
472
 
418
473
  // Dense hits restricted to pages still in the live section index. A deleted
@@ -424,152 +479,176 @@ export async function orchestrate(
424
479
  deps.sectionIndex.byArticle.has(hit.article),
425
480
  );
426
481
 
427
- // `matchedSections` records the matched `Section` (when one is known) for
428
- // every finder hit — INCLUDING hits on stable-prefix slugs — for downstream
429
- // injection/spotlight. `finder` accumulates one entry per distinct
430
- // finder-surfaced article; the first lane to surface a slug wins the entry,
431
- // so the needle → dense → edge call order encodes lane precedence.
432
- const matchedSections = new Map<Slug, Section>();
482
+ // `finder` accumulates the pool's dynamic tail: one entry per distinct
483
+ // (article, matched section), in the needle → dense → reply → span →
484
+ // entity → rare call order, so a page whose sections match different parts of
485
+ // the message carries one line per section and the selector sees each
486
+ // section's own text. A hit that resolves to no section (an edge or
487
+ // learned neighbour, a dense ordinal the index no longer holds) is one
488
+ // section-less line per page, added only when nothing has surfaced the
489
+ // page yet. Each page's lines are capped at `finderSectionsPerPage` in
490
+ // surfacing order, its entity and rare lines aside (`poolLine`). Hits on
491
+ // stable-prefix slugs are kept like any other, so the selector and the
492
+ // injection see those pages' CURRENT relevance.
493
+ const finderCap = deps.finderSectionsPerPage;
433
494
  const finder: FinderCandidate[] = [];
434
- const finderSeen = new Set<Slug>();
495
+ const finderByArticle = new Map<Slug, FinderCandidate[]>();
496
+
497
+ // Whether a line counts against its page's cap. An entity line and a
498
+ // rare-term line do not: both lanes key on one strong token the message
499
+ // names and run after every lane that fills the cap, so holding them to
500
+ // the cap would displace exactly the line each lane exists to surface.
501
+ // The lanes' own caps (`entityCap`, `rareTerm.cap`) bound the lines they
502
+ // add per turn instead.
503
+ const countsAgainstCap = (line: FinderCandidate): boolean =>
504
+ line.lane !== "entity" && line.lane !== "rare";
435
505
 
436
- // `descriptor` overrides the section text when supplied (the edge lane
437
- // prefers a curated `links` description).
438
- const addFinder = (
506
+ // Pool a line for its page unless the page already carries it or is at
507
+ // the cap: a line with a section duplicates a line for the same section
508
+ // key; a section-less line duplicates any line. The cap holds the page's
509
+ // counted lines at `finderCap`; a line outside the cap joins past it, so a
510
+ // page carries at most `finderCap` counted lines plus its entity and rare
511
+ // lines, `finderCap + entityCap + rareTerm.cap` in all.
512
+ const poolLine = (candidate: FinderCandidate): void => {
513
+ const lines = finderByArticle.get(candidate.slug) ?? [];
514
+ const key = candidate.section ? sectionKey(candidate.section) : undefined;
515
+ const duplicate =
516
+ key === undefined
517
+ ? lines.length > 0
518
+ : lines.some((c) => c.section && sectionKey(c.section) === key);
519
+ const atCap =
520
+ countsAgainstCap(candidate) &&
521
+ lines.filter(countsAgainstCap).length >= finderCap;
522
+ if (duplicate || atCap) {
523
+ return;
524
+ }
525
+ lines.push(candidate);
526
+ finderByArticle.set(candidate.slug, lines);
527
+ finder.push(candidate);
528
+ };
529
+
530
+ // A lane hit on section `doc` (an index into `sections`) scored against
531
+ // `query`, whose best-contributing terms ride the line for the selector's
532
+ // keyword-in-context snippet. A `doc` the index does not hold pools as a
533
+ // section-less line with a blank descriptor.
534
+ const addSectionHit = (
439
535
  slug: Slug,
440
- section: Section | undefined,
441
- descriptor: string | undefined,
536
+ doc: number | undefined,
442
537
  lane: FinderLane,
538
+ query: string,
443
539
  ): void => {
444
- if (section && !matchedSections.has(slug)) {
445
- matchedSections.set(slug, section);
446
- }
447
- if (finderSeen.has(slug)) {
448
- return;
449
- }
450
- finderSeen.add(slug);
451
- finder.push({
452
- slug,
453
- descriptor: descriptor ?? section?.text ?? "",
454
- lane,
540
+ const section = doc === undefined ? undefined : sections[doc];
541
+ poolLine(
542
+ doc !== undefined && section
543
+ ? {
544
+ slug,
545
+ section,
546
+ terms: deps.needle.topTerms(doc, query, SNIPPET_TERMS),
547
+ descriptor: section.text,
548
+ lane,
549
+ }
550
+ : { slug, descriptor: "", lane },
551
+ );
552
+ };
553
+
554
+ // A rare-term hit is keyed on one query word, which is the line's only
555
+ // snippet term and, through the lane, its tag.
556
+ const addRareHit = (hit: RareTermHit): void => {
557
+ const section = sections[hit.section]!;
558
+ poolLine({
559
+ slug: hit.article,
560
+ section,
561
+ terms: [hit.term],
562
+ descriptor: section.text,
563
+ lane: "rare",
455
564
  });
456
565
  };
457
566
 
458
- // Step 1a: needle hits — descriptor is the matched section's text. `section`
459
- // is an index into `sections`.
567
+ // A page surfaced by association (an edge or learned neighbour): no
568
+ // section, described by its curated `links` text or a fallback.
569
+ const addNeighbour = (
570
+ slug: Slug,
571
+ descriptor: string | undefined,
572
+ lane: FinderLane,
573
+ ): void => {
574
+ poolLine({ slug, descriptor: descriptor ?? "", lane });
575
+ };
576
+
577
+ // Step 1a: needle hits, `section` is an index into `sections`.
460
578
  for (const hit of needled) {
461
- addFinder(hit.article, sections[hit.section], undefined, "needle");
579
+ addSectionHit(hit.article, hit.section, "needle", turn.currentMessage);
462
580
  }
463
581
 
464
- // Step 1b: dense hits — `section` is the matched ORDINAL; resolve it to the
465
- // concrete `Section` via the section index. Falls back to undefined (blank
466
- // descriptor) if the ordinal is not in the in-memory index.
467
- //
468
- // `denseOwnedSection` tracks the articles whose recorded matched section
469
- // came from THIS loop (needle records first and wins ties), along with the
470
- // hit's cosine score — the span pass upgrades those sections when a clause
471
- // query finds a strictly stronger match under the same metric.
472
- const denseOwnedSection = new Map<Slug, number>();
582
+ // Step 1b: dense hits, `section` is the matched ORDINAL; resolve it to the
583
+ // section's index via the section index. An ordinal the in-memory index
584
+ // does not hold yields a section-less candidate (blank descriptor).
473
585
  for (const hit of densed) {
474
586
  // A deleted page's points can linger in Qdrant; keep only live-index
475
587
  // articles. The section index is rebuilt from `getPageIndex` at `initLanes`,
476
588
  // so `byArticle` holds exactly the live pages (synthetic capability slugs
477
- // included) — only truly-deleted pages are dropped here.
589
+ // included), only truly-deleted pages are dropped here.
478
590
  if (!deps.sectionIndex.byArticle.has(hit.article)) {
479
591
  continue;
480
592
  }
481
- const section = sectionByOrdinal(
482
- deps.sectionIndex,
593
+ addSectionHit(
483
594
  hit.article,
484
- hit.section,
595
+ sectionDocByOrdinal(deps.sectionIndex, hit.article, hit.section),
596
+ "dense",
597
+ turn.currentMessage,
485
598
  );
486
- if (section && !matchedSections.has(hit.article)) {
487
- denseOwnedSection.set(hit.article, hit.score);
488
- }
489
- addFinder(hit.article, section, undefined, "dense");
490
599
  }
491
600
 
492
- // Step 1b': reply-query hits — candidates the user-message lanes already
493
- // surfaced keep their primary attribution (`addFinder`'s first-lane-wins
494
- // dedup); only genuinely reply-surfaced articles tag `"reply"`. Matched
495
- // sections are recorded the same way as the primary lanes', so injection
496
- // and the spotlight render the reply-matched section.
601
+ // Step 1b': reply-query hits. A section the user-message lanes already
602
+ // pooled is a no-op (`poolLine`'s pair dedup), so only a genuinely
603
+ // reply-surfaced section tags `"reply"`; its snippet terms come from the
604
+ // reply text it was scored against.
497
605
  for (const hit of replyNeedled) {
498
- addFinder(hit.article, sections[hit.section], undefined, "reply");
606
+ addSectionHit(hit.article, hit.section, "reply", replyQuery);
499
607
  }
500
608
  for (const hit of replyDensed) {
501
609
  if (!deps.sectionIndex.byArticle.has(hit.article)) {
502
610
  continue;
503
611
  }
504
- addFinder(
612
+ addSectionHit(
505
613
  hit.article,
506
- sectionByOrdinal(deps.sectionIndex, hit.article, hit.section),
507
- undefined,
614
+ sectionDocByOrdinal(deps.sectionIndex, hit.article, hit.section),
508
615
  "reply",
616
+ replyQuery,
509
617
  );
510
618
  }
511
619
 
512
- // Step 1b'': span-query hits — union-additive at the pass's own small
513
- // budget. Candidates the primary or reply lanes already surfaced keep their
514
- // attribution (`addFinder`'s first-lane-wins dedupe); only genuinely
515
- // span-surfaced articles tag `"span"`. Like the reply pass, span hits are
516
- // excluded from the injection gate (which scores current-message needle +
517
- // dense only) and from the edge-expansion seeds.
620
+ // Step 1b'': span-query hits, union-additive at the pass's own small
621
+ // budget. A section a primary or reply lane already pooled is a no-op; a
622
+ // different section of an already-surfaced page joins as its own line,
623
+ // which is the buried-clause match the pass exists to recover. Like the
624
+ // reply pass, span hits are excluded from the injection gate (which scores
625
+ // current-message needle + dense only) and from the edge-expansion seeds.
518
626
  //
519
- // An article can be surfaced by SEVERAL chunks; dedupe by best cosine score
520
- // before `addFinder`, since chunk order would otherwise decide which section
521
- // gets recorded — letting an earlier chunk's weak match mask the strong
522
- // buried-clause match the pass exists to recover.
523
- const bestSpanHits = new Map<Slug, DenseHitScored>();
524
- for (const hit of spanDensed.flat()) {
525
- const prev = bestSpanHits.get(hit.article);
526
- if (!prev || hit.score > prev.score) {
527
- bestSpanHits.set(hit.article, hit);
528
- }
529
- }
530
- // For an article a primary lane already surfaced, upgrade its matched
531
- // section/descriptor ONLY when the existing section was recorded by the
532
- // full-message dense hit and the span's cosine is strictly higher — same
533
- // encoder, same collection, so the comparison is evidence, not judgment.
534
- // Needle- and reply-recorded sections stay (BM25 and cosine scores are not
535
- // comparable, and the reply pass's own convention is first-wins); lane
536
- // attribution never changes here.
537
- for (const hit of bestSpanHits.values()) {
627
+ // Several chunks can hit one article on different sections; they are
628
+ // pooled strongest cosine first, so chunk order never decides which
629
+ // sections fill the page's cap.
630
+ const spanHits = spanDensed.flat().sort((a, c) => c.score - a.score);
631
+ for (const hit of spanHits) {
538
632
  if (!deps.sectionIndex.byArticle.has(hit.article)) {
539
633
  continue;
540
634
  }
541
- const section = sectionByOrdinal(
542
- deps.sectionIndex,
635
+ addSectionHit(
543
636
  hit.article,
544
- hit.section,
637
+ sectionDocByOrdinal(deps.sectionIndex, hit.article, hit.section),
638
+ "span",
639
+ turn.currentMessage,
545
640
  );
546
- const denseScore = denseOwnedSection.get(hit.article);
547
- if (section && denseScore !== undefined && hit.score > denseScore) {
548
- matchedSections.set(hit.article, section);
549
- const existing = finder.find((c) => c.slug === hit.article);
550
- if (existing) {
551
- existing.descriptor = section.text;
552
- }
553
- continue;
554
- }
555
- addFinder(hit.article, section, undefined, "span");
556
641
  }
557
642
 
558
- // Step 1b''': entity lane — sections whose `## ` heading NAMES a distinctive
643
+ // Step 1b''': entity lane, sections whose `## ` heading NAMES a distinctive
559
644
  // entity the message mentions. Additive BM25 buries a single named entity
560
645
  // under a long, multi-topic message's bulk theme; this keys on the heading
561
- // vocabulary so the page the user named surfaces regardless of the bulk
562
- // theme. Runs before edge expansion so an entity hit joins `finderSeen` (edge
563
- // won't re-surface it section-less); it is NOT added to the edge seeds, so it
564
- // only contributes its own page.
565
- //
566
- // The heading section IS the identity this lane exists to surface, so it
567
- // takes precedence over any bulk-theme section a prior lane (needle / dense /
568
- // reply) already recorded for the SAME page: `addFinder` keeps the first
569
- // matched section and skips duplicate slugs, so override the matched section
570
- // and the existing finder descriptor here before delegating, ensuring
571
- // injection, the spotlight, and the selector snippet all render the heading
572
- // rather than the earlier non-entity match.
646
+ // vocabulary so the section the user named surfaces regardless of the bulk
647
+ // theme, as its own line beside any bulk-theme section a prior lane pooled
648
+ // for the same page (a no-op when that lane already pooled the heading).
649
+ // Runs before edge expansion so an entity hit counts as surfaced (edge
650
+ // won't re-surface its page section-less); it is NOT added to the edge
651
+ // seeds, so it only contributes its own section.
573
652
  if (deps.entityIndex) {
574
653
  for (const hit of entityLane(
575
654
  deps.entityIndex,
@@ -577,25 +656,39 @@ export async function orchestrate(
577
656
  turn.currentMessage,
578
657
  deps.entityCap ?? DEFAULT_ENTITY_CAP,
579
658
  )) {
580
- const section = sections[hit.section];
581
- if (section) {
582
- matchedSections.set(hit.article, section);
583
- const existing = finder.find((c) => c.slug === hit.article);
584
- if (existing) {
585
- existing.descriptor = section.text;
586
- }
587
- }
588
- addFinder(hit.article, section, undefined, "entity");
659
+ addSectionHit(hit.article, hit.section, "entity", turn.currentMessage);
660
+ }
661
+ }
662
+
663
+ // Step 1b'''': rare-term lane, the sections a rare query word occurs in. A
664
+ // word found in at most `maxDf` sections is a near-certain signal on its
665
+ // own: additive BM25 lets the message's bulk theme pick a page's section,
666
+ // and a query on the clause alone cannot rank a page whose only
667
+ // distinctive token is that word. Each rare word's top sections by
668
+ // single-term score join as their own lines, tagged with the word, which
669
+ // also centers the selector's snippet; a section a prior lane pooled is a
670
+ // no-op, and a page the prior lanes filled to the per-page cap still
671
+ // takes its rare lines (`poolLine`). Like the entity lane, rare hits feed
672
+ // neither the gate nor the edge seeds.
673
+ if (deps.rareTerm) {
674
+ for (const hit of rareTermLane(
675
+ deps.needle,
676
+ deps.sectionIndex,
677
+ turn.currentMessage,
678
+ deps.rareTerm,
679
+ )) {
680
+ addRareHit(hit);
589
681
  }
590
682
  }
591
683
 
592
- // Step 1b'''': opt-in injection gate. With the CURRENT-message finder lanes in
593
- // hand (needle + dense — NOT reply/span/entity/edge, which only add recall), decide
594
- // whether retrieval is confident enough to spend the selectPool LLM call this
595
- // turn. Default-off via `?.enabled`; pass-open on any throw (a gate bug must
596
- // never drop a turn's memory). A closed gate either hard-skips selection
597
- // (empty selections) or, when `bypassForCore` is set, runs selectPool over the
598
- // stable prefix only — never the finder tail.
684
+ // Step 1b''''': opt-in injection gate. With the CURRENT-message finder lanes
685
+ // in hand (needle + dense, NOT reply/span/entity/rare/edge, which only add
686
+ // recall), decide whether retrieval is confident enough to spend the
687
+ // selectPool LLM call this turn. Default-off via `?.enabled`; pass-open on
688
+ // any throw (a gate bug must never drop a turn's memory). A closed gate
689
+ // either hard-skips selection (empty selections) or, when `bypassForCore`
690
+ // is set, runs selectPool over the stable prefix only, never the finder
691
+ // tail.
599
692
  //
600
693
  // The gate is dense-gated: it only runs when the live dense lane produced hits
601
694
  // (`liveDensed.length > 0`). In healthy operation dense returns top-k hits for
@@ -650,18 +743,25 @@ export async function orchestrate(
650
743
  // the provider (also a 0%).
651
744
  // The last is why `poolSize` decides this rather than each call site: an empty
652
745
  // pool is not a judgment that nothing was relevant, and no caller has to
653
- // remember that.
746
+ // remember that. `selectorRanOver` is that rule; the selection event and the
747
+ // result's `selectorRan` both read it.
654
748
  // `selector_kept_all` and `net_new_count` separate what the selector JUDGED
655
749
  // from what actually reaches the turn, which `selected_count` alone conflates:
656
750
  // - kept_all: the recall-safe fallback fired (model omitted `ids`), so every
657
751
  // candidate was kept without a real judgment. Distinguishes "kept the whole
658
752
  // pool because it gave up" from "explicitly selected a large set", which
659
753
  // otherwise look identical and inflate the same way.
660
- // - net_new: selections not already live in the conversation — the injector
661
- // renders only these (prior turns' cards ride history), so it is the real
662
- // incremental injection, where `selected_count` re-counts the whole
663
- // standing set every turn. Omitted when the caller did not supply
664
- // `activeSlugs` (tests, shadow-less paths).
754
+ // - net_new: the injection units among the selections (`injectionUnits`:
755
+ // each selected section, or the lead of a page selected with none, a
756
+ // capability page as one unit) not already live in the conversation,
757
+ // the injector renders only these (prior turns' sections ride
758
+ // history), so it is the real incremental injection, where
759
+ // `selected_count` re-counts the whole standing set every turn.
760
+ // Omitted when the caller did not supply `isResident` (tests,
761
+ // shadow-less paths). The count reads the same units the injector will
762
+ // (a closed gate's selections carry no sections, so it counts leads).
763
+ const selectorRanOver = (poolSize: number): boolean =>
764
+ deps.selectorEnabled !== false && poolSize > 0;
665
765
  const recordSelection = (
666
766
  selections: SelectedPage[],
667
767
  poolSize: number,
@@ -670,14 +770,15 @@ export async function orchestrate(
670
770
  const detail: Record<string, unknown> = {
671
771
  gate_reason: gateOutcome?.reason ?? null,
672
772
  gate_pass: gateOutcome?.pass ?? null,
673
- selector_ran: deps.selectorEnabled !== false && poolSize > 0,
773
+ selector_ran: selectorRanOver(poolSize),
674
774
  selector_kept_all: keptAll,
675
775
  selected_count: selections.length,
676
776
  pool_size: poolSize,
677
777
  };
678
- if (deps.activeSlugs !== undefined) {
679
- detail.net_new_count = selections.filter(
680
- (s) => !deps.activeSlugs!.has(s.slug),
778
+ const isResident = deps.isResident;
779
+ if (isResident !== undefined) {
780
+ detail.net_new_count = injectionUnits(selections).filter(
781
+ ({ slug, key }) => !isResident(slug, key),
681
782
  ).length;
682
783
  }
683
784
  if (deps.realConceptPageCount !== undefined) {
@@ -739,12 +840,15 @@ export async function orchestrate(
739
840
  checked_articles: gate.checkedArticles,
740
841
  });
741
842
  if (!gate.pass) {
742
- // A closed gate produces no finder lane and no matched sections; only
743
- // the `selections` differ between bypass (stable prefix) and hard-skip.
744
- const closed = (selections: SelectedPage[]): OrchestrateResult => ({
843
+ // A closed gate produces no finder lane; only `selections` and
844
+ // `selectorRan` differ between bypass (stable prefix) and hard-skip.
845
+ const closed = (
846
+ selections: SelectedPage[],
847
+ selectorRan: boolean,
848
+ ): OrchestrateResult => ({
745
849
  selections,
746
- matchedSections: new Map(),
747
- lanes: { core, hot, fresh, finder: [] },
850
+ lanes: { core, hot, fresh, always, finder: [] },
851
+ selectorRan,
748
852
  });
749
853
  if (deps.gateConfig.bypassForCore) {
750
854
  // Select over the stable prefix only. `runSelection` mirrors the
@@ -762,13 +866,14 @@ export async function orchestrate(
762
866
  finder: [],
763
867
  });
764
868
  recordSelection(bypassed, stableOnly.length, keptAll);
765
- return closed(bypassed);
869
+ return closed(bypassed, selectorRanOver(stableOnly.length));
766
870
  }
767
871
  // Hard skip: the selector is never consulted, so this is a zero
768
872
  // selection BY CONSTRUCTION, not a judgment that nothing was relevant.
769
- // `selector_ran: false` keeps it out of any relevance rate.
873
+ // `selector_ran: false` keeps it out of any relevance rate, and the
874
+ // result's `selectorRan` keeps it out of the persisted pool record.
770
875
  recordSelection([], 0, false);
771
- return closed([]);
876
+ return closed([], false);
772
877
  }
773
878
  }
774
879
  }
@@ -783,8 +888,8 @@ export async function orchestrate(
783
888
  // its first/lead section on a zero-score match. That lead is often empty for
784
889
  // heading-structured pages, and it is the curated `links` description (not
785
890
  // the lead) that made the candidate relevant. So we record NO matched
786
- // section for edge-only pages (pass `undefined`), which makes injection fall
787
- // back to the FULL page — where the link-relevant content lives.
891
+ // section for edge-only pages (pass `undefined`): the candidate is a
892
+ // section-less line and a selection of it injects the page's lead.
788
893
  // `bestSection`'s text is kept only as the select-pool DESCRIPTOR fallback
789
894
  // for when the traversed edge carried no curated `links` description.
790
895
  const seeds = unique<Slug>([
@@ -795,14 +900,13 @@ export async function orchestrate(
795
900
  seedCount: deps.edgeSeeds,
796
901
  perSeed: deps.edgePerSeed,
797
902
  cap: deps.edgeCap,
798
- alive: (slug) => !finderSeen.has(slug) && !stablePrefix.has(slug),
903
+ alive: (slug) => !finderByArticle.has(slug) && !stablePrefix.has(slug),
799
904
  });
800
905
  for (const neighbor of surfaced) {
801
906
  const best = deps.needle.bestSection(neighbor.article, turn.currentMessage);
802
907
  const fallbackDescriptor = best >= 0 ? sections[best]?.text : undefined;
803
- addFinder(
908
+ addNeighbour(
804
909
  neighbor.article,
805
- undefined,
806
910
  neighbor.description ?? fallbackDescriptor,
807
911
  "edge",
808
912
  );
@@ -820,16 +924,15 @@ export async function orchestrate(
820
924
  seedCount: deps.edgeSeeds,
821
925
  perSeed: deps.learnedPerSeed,
822
926
  cap: deps.learnedCap,
823
- alive: (slug) => !finderSeen.has(slug) && !stablePrefix.has(slug),
927
+ alive: (slug) => !finderByArticle.has(slug) && !stablePrefix.has(slug),
824
928
  });
825
929
  for (const neighbor of learned) {
826
930
  const best = deps.needle.bestSection(
827
931
  neighbor.article,
828
932
  turn.currentMessage,
829
933
  );
830
- addFinder(
934
+ addNeighbour(
831
935
  neighbor.article,
832
- undefined,
833
936
  best >= 0 ? sections[best]?.text : undefined,
834
937
  "learned",
835
938
  );
@@ -843,12 +946,15 @@ export async function orchestrate(
843
946
  // byte-identical across turns while the lanes are unchanged. The tail is
844
947
  // NOT deduped against the prefix — a finder hit on a core/hot page renders
845
948
  // its own snippet line so its CURRENT relevance stays visible; `selectPool`
846
- // dedupes selections by slug. Finder candidates with no match text fall
847
- // back to the page's lead-section snippet.
949
+ // merges selections per slug. Each line carries its matched section and
950
+ // snippet terms; a candidate with no match text falls back to the page's
951
+ // lead-section snippet.
848
952
  const stable = buildStable();
849
953
  const finderTail: PoolCandidate[] = finder.map((c) => ({
850
954
  slug: c.slug,
851
955
  lane: c.lane,
956
+ section: c.section,
957
+ terms: c.terms,
852
958
  descriptor:
853
959
  c.descriptor.trim().length > 0
854
960
  ? c.descriptor
@@ -856,50 +962,57 @@ export async function orchestrate(
856
962
  }));
857
963
 
858
964
  // Step 3: a SINGLE forced-tool select over the cache-ordered pool. The
859
- // selections come back slug-deduped (pinned flags ORed) — `selectPool`'s
860
- // contract. `selectorPrompt` is the (optionally overridden) instruction
861
- // scaffold; `undefined` falls through to the bundled default.
965
+ // selections come back slug-deduped (`selectPool`'s contract).
966
+ // `selectorPrompt` is the (optionally overridden) instruction scaffold;
967
+ // `undefined` falls through to the bundled default.
862
968
  const pool = { stable, finder: finderTail };
863
969
  recordLatencySubSpan(
864
970
  "v3_expand",
865
971
  "Gate & edge expansion",
866
972
  Date.now() - expandStartedAt,
867
973
  );
974
+ const poolSize = stable.length + finderTail.length;
868
975
  const { selections, keptAll } = await runSelection(pool);
869
- recordSelection(selections, stable.length + finderTail.length, keptAll);
976
+ recordSelection(selections, poolSize, keptAll);
870
977
 
871
978
  return {
872
979
  selections,
873
- matchedSections,
874
- lanes: { core, hot, fresh, finder },
980
+ lanes: { core, hot, fresh, always, finder },
981
+ selectorRan: selectorRanOver(poolSize),
875
982
  };
876
983
  }
877
984
 
878
985
  /**
879
- * Resolve a dense-lane hit's matched ordinal to the concrete `Section` in the
880
- * in-memory index. The dense store keys sections by `(article, ordinal)`, so we
881
- * scan the article's sections for the matching ordinal. Returns `undefined`
882
- * when the article or ordinal is not in the index (e.g. the dense store is
883
- * ahead of the in-memory rebuild).
986
+ * Resolve a dense-lane hit's matched ordinal to its index into
987
+ * `index.sections`. The dense store keys sections by `(article, ordinal)`, so
988
+ * we scan the article's sections for the matching ordinal. Returns
989
+ * `undefined` when the article or ordinal is not in the index (e.g. the dense
990
+ * store is ahead of the in-memory rebuild).
884
991
  */
885
- export function sectionByOrdinal(
992
+ function sectionDocByOrdinal(
886
993
  index: SectionIndex,
887
994
  article: Slug,
888
995
  ordinal: number,
889
- ): Section | undefined {
890
- const indices = index.byArticle.get(article);
891
- if (!indices) {
892
- return undefined;
893
- }
894
- for (const i of indices) {
895
- const section = index.sections[i];
896
- if (section && section.ordinal === ordinal) {
897
- return section;
996
+ ): number | undefined {
997
+ for (const doc of index.byArticle.get(article) ?? []) {
998
+ if (index.sections[doc]?.ordinal === ordinal) {
999
+ return doc;
898
1000
  }
899
1001
  }
900
1002
  return undefined;
901
1003
  }
902
1004
 
1005
+ /** The concrete `Section` a dense-lane hit's ordinal resolves to; see
1006
+ * {@link sectionDocByOrdinal}. */
1007
+ export function sectionByOrdinal(
1008
+ index: SectionIndex,
1009
+ article: Slug,
1010
+ ordinal: number,
1011
+ ): Section | undefined {
1012
+ const doc = sectionDocByOrdinal(index, article, ordinal);
1013
+ return doc === undefined ? undefined : index.sections[doc];
1014
+ }
1015
+
903
1016
  /**
904
1017
  * The text of an article's LEAD (first) section, or `""` when the article has
905
1018
  * no indexed sections. Used as the finder-line snippet fallback when a