attention-manifest-protocol 0.4.2 → 0.4.3

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 (827) hide show
  1. package/CHANGELOG.md +341 -293
  2. package/CHANGELOG.zh-CN.md +41 -8
  3. package/README.md +250 -171
  4. package/README.zh-CN.md +251 -171
  5. package/lib/assignment/assign.d.ts +102 -0
  6. package/lib/assignment/assign.js +556 -0
  7. package/lib/assignment/binding.d.ts +103 -0
  8. package/lib/assignment/binding.js +575 -0
  9. package/lib/assignment/errors.d.ts +14 -0
  10. package/lib/assignment/errors.js +16 -0
  11. package/lib/assignment/guards.d.ts +18 -0
  12. package/lib/assignment/guards.js +28 -0
  13. package/lib/assignment/index.d.ts +10 -0
  14. package/lib/assignment/index.js +10 -0
  15. package/lib/assignment/types.d.ts +169 -0
  16. package/lib/assignment/types.js +1 -0
  17. package/lib/attention/budget.d.ts +1 -1
  18. package/lib/attention/budget.js +31 -9
  19. package/lib/bayes/engine.js +2 -1
  20. package/lib/bayes/reliability.js +25 -10
  21. package/lib/boundary/frame.d.ts +10 -4
  22. package/lib/boundary/frame.js +346 -109
  23. package/lib/boundary/kinds.d.ts +11 -0
  24. package/lib/boundary/kinds.js +33 -0
  25. package/lib/boundary/refTable.d.ts +19 -9
  26. package/lib/boundary/refTable.js +128 -30
  27. package/lib/boundary/toolCall.d.ts +22 -10
  28. package/lib/boundary/toolCall.js +798 -97
  29. package/lib/concept/conceptBudget.js +10 -1
  30. package/lib/concurrency/idempotency.d.ts +4 -3
  31. package/lib/concurrency/idempotency.js +57 -13
  32. package/lib/concurrency/retry.js +18 -3
  33. package/lib/context/agentContext.d.ts +13 -0
  34. package/lib/context/agentContext.js +14 -1
  35. package/lib/context/ast.d.ts +4 -1
  36. package/lib/context/ast.js +13 -3
  37. package/lib/context/contentStore.js +22 -9
  38. package/lib/context/contextBuilder.d.ts +457 -0
  39. package/lib/context/contextBuilder.js +1395 -0
  40. package/lib/context/contextPackage.d.ts +214 -0
  41. package/lib/context/contextPackage.js +191 -0
  42. package/lib/context/index.d.ts +14 -3
  43. package/lib/context/index.js +9 -1
  44. package/lib/context/relevance.d.ts +171 -0
  45. package/lib/context/relevance.js +250 -0
  46. package/lib/context/workspaceDiff.d.ts +105 -0
  47. package/lib/context/workspaceDiff.js +238 -0
  48. package/lib/context/workspaceService.d.ts +236 -1
  49. package/lib/context/workspaceService.js +1501 -73
  50. package/lib/cooperation/collaboration.d.ts +9 -0
  51. package/lib/cooperation/session.d.ts +4 -4
  52. package/lib/cooperation/session.js +3 -3
  53. package/lib/database/adapter/filesystemStore.d.ts +145 -0
  54. package/lib/database/adapter/filesystemStore.js +321 -0
  55. package/lib/database/adapter/index.d.ts +2 -0
  56. package/lib/database/adapter/index.js +2 -0
  57. package/lib/database/adapter/workspaceSessionStore.d.ts +118 -0
  58. package/lib/database/adapter/workspaceSessionStore.js +120 -0
  59. package/lib/database/entity/fileGraph.d.ts +53 -0
  60. package/lib/database/entity/fileGraph.js +15 -0
  61. package/lib/database/entity/fileTree.d.ts +76 -0
  62. package/lib/database/entity/fileTree.js +39 -0
  63. package/lib/database/entity/hook.d.ts +29 -0
  64. package/lib/database/entity/hook.js +18 -0
  65. package/lib/database/entity/index.d.ts +4 -0
  66. package/lib/database/entity/index.js +4 -0
  67. package/lib/database/entity/workspaceSession.d.ts +53 -0
  68. package/lib/database/entity/workspaceSession.js +28 -0
  69. package/lib/database/repository/fileAnnotationRepository.d.ts +75 -0
  70. package/lib/database/repository/fileAnnotationRepository.js +109 -0
  71. package/lib/database/repository/fileGraphRepository.d.ts +188 -0
  72. package/lib/database/repository/fileGraphRepository.js +648 -0
  73. package/lib/database/repository/fileNodeRepository.d.ts +116 -0
  74. package/lib/database/repository/fileNodeRepository.js +263 -0
  75. package/lib/database/repository/fileOutlineRepository.d.ts +40 -0
  76. package/lib/database/repository/fileOutlineRepository.js +104 -0
  77. package/lib/database/repository/fileWriteRepository.d.ts +41 -0
  78. package/lib/database/repository/fileWriteRepository.js +93 -0
  79. package/lib/database/repository/hookRepository.d.ts +67 -0
  80. package/lib/database/repository/hookRepository.js +150 -0
  81. package/lib/database/repository/index.d.ts +7 -0
  82. package/lib/database/repository/index.js +7 -0
  83. package/lib/database/repository/workspaceSessionRepository.d.ts +134 -0
  84. package/lib/database/repository/workspaceSessionRepository.js +327 -0
  85. package/lib/database/service/database.d.ts +14 -0
  86. package/lib/database/service/database.js +21 -0
  87. package/lib/database/sql/schema.js +187 -0
  88. package/lib/database/store/database.js +6 -1
  89. package/lib/delegate/team.d.ts +5 -0
  90. package/lib/delegate/team.js +83 -20
  91. package/lib/discover/classify.d.ts +20 -0
  92. package/lib/discover/classify.js +85 -0
  93. package/lib/discover/host.d.ts +20 -0
  94. package/lib/discover/host.js +89 -0
  95. package/lib/discover/index.d.ts +11 -0
  96. package/lib/discover/index.js +11 -0
  97. package/lib/discover/kinds.d.ts +14 -0
  98. package/lib/discover/kinds.js +23 -0
  99. package/lib/discover/tree.d.ts +7 -0
  100. package/lib/discover/tree.js +432 -0
  101. package/lib/discover/types.d.ts +115 -0
  102. package/lib/discover/types.js +1 -0
  103. package/lib/error/boundaryRejection.d.ts +1 -1
  104. package/lib/evaluation/agreement.js +2 -2
  105. package/lib/execution/handles.js +6 -0
  106. package/lib/execution/pin.js +2 -2
  107. package/lib/file/cfb.d.ts +56 -0
  108. package/lib/file/cfb.js +396 -0
  109. package/lib/file/dependency.d.ts +151 -0
  110. package/lib/file/dependency.js +568 -0
  111. package/lib/file/directory.d.ts +34 -0
  112. package/lib/file/directory.js +141 -0
  113. package/lib/file/errors.d.ts +20 -0
  114. package/lib/file/errors.js +18 -0
  115. package/lib/file/exportGraph.d.ts +31 -0
  116. package/lib/file/exportGraph.js +554 -0
  117. package/lib/file/file.d.ts +40 -0
  118. package/lib/file/file.js +339 -0
  119. package/lib/file/importGraph.d.ts +121 -0
  120. package/lib/file/importGraph.js +1022 -0
  121. package/lib/file/index.d.ts +45 -0
  122. package/lib/file/index.js +30 -0
  123. package/lib/file/metadata.d.ts +66 -0
  124. package/lib/file/metadata.js +470 -0
  125. package/lib/file/path.d.ts +60 -0
  126. package/lib/file/path.js +259 -0
  127. package/lib/file/read.d.ts +168 -0
  128. package/lib/file/read.js +541 -0
  129. package/lib/file/runtime.d.ts +95 -0
  130. package/lib/file/runtime.js +150 -0
  131. package/lib/file/service.d.ts +227 -0
  132. package/lib/file/service.js +663 -0
  133. package/lib/file/syntaxTree.d.ts +7 -0
  134. package/lib/file/syntaxTree.js +38 -0
  135. package/lib/file/time.d.ts +38 -0
  136. package/lib/file/time.js +44 -0
  137. package/lib/file/tree.d.ts +53 -0
  138. package/lib/file/tree.js +417 -0
  139. package/lib/file/types.d.ts +371 -0
  140. package/lib/file/types.js +1 -0
  141. package/lib/file/write.d.ts +159 -0
  142. package/lib/file/write.js +1028 -0
  143. package/lib/file/zip.d.ts +35 -0
  144. package/lib/file/zip.js +349 -0
  145. package/lib/fingerprint/algorithm.d.ts +97 -0
  146. package/lib/fingerprint/algorithm.js +271 -0
  147. package/lib/fingerprint/bytes.d.ts +18 -0
  148. package/lib/fingerprint/bytes.js +31 -0
  149. package/lib/fingerprint/error.d.ts +73 -0
  150. package/lib/fingerprint/error.js +86 -0
  151. package/lib/fingerprint/file.d.ts +71 -0
  152. package/lib/fingerprint/file.js +254 -0
  153. package/lib/fingerprint/index.d.ts +37 -0
  154. package/lib/fingerprint/index.js +12 -0
  155. package/lib/fingerprint/json.d.ts +41 -0
  156. package/lib/fingerprint/json.js +94 -0
  157. package/lib/fingerprint/number.d.ts +32 -0
  158. package/lib/fingerprint/number.js +95 -0
  159. package/lib/fingerprint/policy.d.ts +54 -0
  160. package/lib/fingerprint/policy.js +50 -0
  161. package/lib/fingerprint/preimage.d.ts +84 -0
  162. package/lib/fingerprint/preimage.js +133 -0
  163. package/lib/fingerprint/raw.d.ts +26 -0
  164. package/lib/fingerprint/raw.js +45 -0
  165. package/lib/fingerprint/ref.d.ts +39 -0
  166. package/lib/fingerprint/ref.js +178 -0
  167. package/lib/fingerprint/text.d.ts +42 -0
  168. package/lib/fingerprint/text.js +155 -0
  169. package/lib/fingerprint/tree.d.ts +56 -0
  170. package/lib/fingerprint/tree.js +288 -0
  171. package/lib/fingerprint/verify.d.ts +20 -0
  172. package/lib/fingerprint/verify.js +99 -0
  173. package/lib/global/filesystem.d.ts +43 -0
  174. package/lib/global/filesystem.js +75 -0
  175. package/lib/global/index.d.ts +8 -0
  176. package/lib/global/index.js +8 -0
  177. package/lib/global/service.d.ts +51 -0
  178. package/lib/global/service.js +98 -0
  179. package/lib/governance/transport.js +18 -6
  180. package/lib/hook/ast.d.ts +29 -0
  181. package/lib/hook/ast.js +22 -0
  182. package/lib/hook/code.d.ts +55 -0
  183. package/lib/hook/code.js +47 -0
  184. package/lib/hook/dependency.d.ts +45 -0
  185. package/lib/hook/dependency.js +28 -0
  186. package/lib/hook/diff.d.ts +114 -0
  187. package/lib/hook/diff.js +327 -0
  188. package/lib/hook/exportation.d.ts +31 -0
  189. package/lib/hook/exportation.js +24 -0
  190. package/lib/hook/file.d.ts +44 -0
  191. package/lib/hook/file.js +154 -0
  192. package/lib/hook/importation.d.ts +33 -0
  193. package/lib/hook/importation.js +22 -0
  194. package/lib/hook/index.d.ts +30 -0
  195. package/lib/hook/index.js +23 -0
  196. package/lib/hook/outline.d.ts +35 -0
  197. package/lib/hook/outline.js +27 -0
  198. package/lib/hook/project.d.ts +65 -0
  199. package/lib/hook/project.js +217 -0
  200. package/lib/hook/types.d.ts +114 -0
  201. package/lib/hook/types.js +407 -0
  202. package/lib/index.d.ts +9 -0
  203. package/lib/index.js +9 -0
  204. package/lib/lock/lease.js +28 -3
  205. package/lib/manifest/cardSign.d.ts +1 -1
  206. package/lib/manifest/cardSign.js +37 -7
  207. package/lib/manifest/federation.js +13 -6
  208. package/lib/manifest/trust.d.ts +2 -0
  209. package/lib/manifest/trust.js +27 -6
  210. package/lib/module/index.d.ts +4 -0
  211. package/lib/module/index.js +4 -0
  212. package/lib/module/mcp/client.js +21 -2
  213. package/lib/module/mcp/filesystemServer.d.ts +24 -0
  214. package/lib/module/mcp/filesystemServer.js +102 -0
  215. package/lib/module/mcp/http.js +32 -19
  216. package/lib/module/mcp/workspaceServer.js +20 -3
  217. package/lib/module/tool/filesystemExecutor.d.ts +18 -0
  218. package/lib/module/tool/filesystemExecutor.js +49 -0
  219. package/lib/module/tool/globalExecutor.d.ts +17 -0
  220. package/lib/module/tool/globalExecutor.js +39 -0
  221. package/lib/module/tool/globalFilesystemExecutor.d.ts +18 -0
  222. package/lib/module/tool/globalFilesystemExecutor.js +49 -0
  223. package/lib/module/tool/workspaceExecutor.d.ts +9 -0
  224. package/lib/module/tool/workspaceExecutor.js +16 -3
  225. package/lib/naming/aliases.d.ts +48 -0
  226. package/lib/naming/aliases.js +79 -0
  227. package/lib/naming/catalog.d.ts +117 -0
  228. package/lib/naming/catalog.js +108 -0
  229. package/lib/naming/grammar.d.ts +67 -0
  230. package/lib/naming/grammar.js +212 -0
  231. package/lib/naming/ids.d.ts +157 -0
  232. package/lib/naming/ids.js +119 -0
  233. package/lib/naming/index.d.ts +13 -0
  234. package/lib/naming/index.js +13 -0
  235. package/lib/outline/index.d.ts +9 -0
  236. package/lib/outline/index.js +8 -0
  237. package/lib/outline/office.d.ts +160 -0
  238. package/lib/outline/office.js +2375 -0
  239. package/lib/outline/officeBridge.d.ts +32 -0
  240. package/lib/outline/officeBridge.js +27 -0
  241. package/lib/outline/outline.d.ts +159 -0
  242. package/lib/outline/outline.js +837 -0
  243. package/lib/outline/outlineIndex.d.ts +97 -0
  244. package/lib/outline/outlineIndex.js +325 -0
  245. package/lib/outline/outlineKeywords.d.ts +59 -0
  246. package/lib/outline/outlineKeywords.js +143 -0
  247. package/lib/outline/outlineStrategies.d.ts +414 -0
  248. package/lib/outline/outlineStrategies.js +8324 -0
  249. package/lib/outline/reactOutline.d.ts +37 -0
  250. package/lib/outline/reactOutline.js +1070 -0
  251. package/lib/outline/shellOutline.d.ts +65 -0
  252. package/lib/outline/shellOutline.js +873 -0
  253. package/lib/outline/sqlOutline.d.ts +170 -0
  254. package/lib/outline/sqlOutline.js +1536 -0
  255. package/lib/outline/strategy.d.ts +46 -0
  256. package/lib/outline/strategy.js +1 -0
  257. package/lib/outline/types.d.ts +95 -0
  258. package/lib/outline/types.js +1 -0
  259. package/lib/outline/visualBasicOutline.d.ts +27 -0
  260. package/lib/outline/visualBasicOutline.js +750 -0
  261. package/lib/protocol/filesystem.d.ts +55 -0
  262. package/lib/protocol/filesystem.js +105 -0
  263. package/lib/protocol/global.d.ts +42 -0
  264. package/lib/protocol/global.js +63 -0
  265. package/lib/protocol/globalFilesystem.d.ts +40 -0
  266. package/lib/protocol/globalFilesystem.js +59 -0
  267. package/lib/protocol/index.d.ts +4 -0
  268. package/lib/protocol/index.js +4 -0
  269. package/lib/protocol/protocol.d.ts +4 -0
  270. package/lib/protocol/wire.js +5 -2
  271. package/lib/protocol/workspace.d.ts +305 -0
  272. package/lib/protocol/workspace.js +258 -0
  273. package/lib/receipt/receipt.d.ts +8 -0
  274. package/lib/registry/content.js +9 -3
  275. package/lib/runtime/kernelRuntime.js +9 -1
  276. package/lib/scenario/scenario.js +5 -4
  277. package/lib/semantic/canonical.d.ts +61 -0
  278. package/lib/semantic/canonical.js +135 -8
  279. package/lib/semantic/jsonValue.d.ts +31 -0
  280. package/lib/semantic/jsonValue.js +122 -0
  281. package/lib/semantic/sha256.js +3 -0
  282. package/lib/semantic/time.d.ts +14 -0
  283. package/lib/semantic/time.js +56 -0
  284. package/lib/session/context.d.ts +76 -0
  285. package/lib/session/context.js +419 -0
  286. package/lib/session/errors.d.ts +24 -0
  287. package/lib/session/errors.js +22 -0
  288. package/lib/session/identity.d.ts +24 -0
  289. package/lib/session/identity.js +56 -0
  290. package/lib/session/index.d.ts +14 -0
  291. package/lib/session/index.js +12 -0
  292. package/lib/session/registry.d.ts +130 -0
  293. package/lib/session/registry.js +908 -0
  294. package/lib/session/types.d.ts +227 -0
  295. package/lib/session/types.js +14 -0
  296. package/lib/structure/index.d.ts +1 -0
  297. package/lib/structure/index.js +1 -0
  298. package/lib/structure/trie.d.ts +88 -0
  299. package/lib/structure/trie.js +183 -0
  300. package/lib/syntax/byteIndex.d.ts +44 -0
  301. package/lib/syntax/byteIndex.js +148 -0
  302. package/lib/syntax/charset.d.ts +88 -0
  303. package/lib/syntax/charset.js +276 -0
  304. package/lib/syntax/index.d.ts +6 -0
  305. package/lib/syntax/index.js +5 -0
  306. package/lib/syntax/syntaxRegistry.d.ts +150 -0
  307. package/lib/syntax/syntaxRegistry.js +314 -0
  308. package/lib/syntax/syntaxTree.d.ts +106 -0
  309. package/lib/syntax/syntaxTree.js +668 -0
  310. package/lib/syntax/types.d.ts +15 -0
  311. package/lib/syntax/types.js +1 -0
  312. package/lib/types/common.d.ts +1 -1
  313. package/package.json +72 -193
  314. package/.editorconfig +0 -12
  315. package/.prettierignore +0 -17
  316. package/MCP-Token/347/250/216/344/270/216/344/270/213/344/270/200/344/273/243/345/267/245/345/205/267/345/215/217/350/256/256.html +0 -1763
  317. package/docs/annotation-campaign-A.csv +0 -54
  318. package/docs/annotation-campaign-B.csv +0 -54
  319. package/docs/annotation-campaign.csv +0 -54
  320. package/docs/eval/annotations-A.jsonl +0 -16
  321. package/docs/eval/annotations.json +0 -122
  322. package/docs/eval/recorded-labels.json +0 -12
  323. package/docs/eval/replay-cases.json +0 -14
  324. package/docs/eval/replay-labels-b.json +0 -14
  325. package/docs/examples/attention-request.json +0 -16
  326. package/docs/examples/checkpoint.json +0 -15
  327. package/docs/examples/claim.json +0 -66
  328. package/docs/examples/collaboration.json +0 -66
  329. package/docs/examples/concept-checkpoint.json +0 -15
  330. package/docs/examples/concept-prune-plan.json +0 -45
  331. package/docs/examples/federation.json +0 -126
  332. package/docs/examples/frame-chain.json +0 -77
  333. package/docs/examples/ledger-snapshot.json +0 -108
  334. package/docs/examples/manifest.json +0 -77
  335. package/docs/examples/message.json +0 -19
  336. package/docs/examples/other-model.json +0 -45
  337. package/docs/examples/plan.json +0 -50
  338. package/docs/examples/prune-plan.json +0 -48
  339. package/docs/examples/receipt.json +0 -22
  340. package/docs/examples/runtime-run.json +0 -573
  341. package/docs/examples/team.json +0 -66
  342. package/docs/examples/verb-note.json +0 -11
  343. package/docs/probes/bayes-scores.json +0 -1452
  344. package/docs/probes/calibration-imported.json +0 -141
  345. package/docs/probes/context-ast-deepseek.json +0 -1577
  346. package/docs/probes/deepseek-probe.json +0 -917
  347. package/docs/probes/eval-recorded-replay.json +0 -597
  348. package/docs/probes/eval-replay.json +0 -124
  349. package/docs/probes/eval-summary.json +0 -42
  350. package/docs/probes/runtime-eval.json +0 -4230
  351. package/docs/schemas/collaboration.schema.json +0 -73
  352. package/docs/schemas/common.schema.json +0 -125
  353. package/docs/schemas/compaction.schema.json +0 -121
  354. package/docs/schemas/concept-compaction.schema.json +0 -73
  355. package/docs/schemas/concept.schema.json +0 -97
  356. package/docs/schemas/epistemic.schema.json +0 -178
  357. package/docs/schemas/federation.schema.json +0 -66
  358. package/docs/schemas/frame.schema.json +0 -86
  359. package/docs/schemas/ledger-snapshot.schema.json +0 -30
  360. package/docs/schemas/manifest.schema.json +0 -169
  361. package/docs/schemas/message.schema.json +0 -41
  362. package/docs/schemas/plan.schema.json +0 -189
  363. package/docs/schemas/receipt.schema.json +0 -45
  364. package/docs/schemas/social.schema.json +0 -153
  365. package/docs/schemas/team.schema.json +0 -56
  366. package/docs/schemas/verb.schema.json +0 -120
  367. package/eslint.config.mts +0 -96
  368. package/index.html +0 -13
  369. package/lib/context/workspaceProtocol.d.ts +0 -30
  370. package/lib/context/workspaceProtocol.js +0 -49
  371. package/prettier.config.mts +0 -37
  372. package/public/favicon.svg +0 -1
  373. package/public/icons.svg +0 -24
  374. package/src/attention/attention.ts +0 -347
  375. package/src/attention/budget.ts +0 -72
  376. package/src/attention/cognition.ts +0 -519
  377. package/src/attention/index.ts +0 -8
  378. package/src/attention/interrupts.ts +0 -228
  379. package/src/attention/resource.ts +0 -316
  380. package/src/attention/social.ts +0 -217
  381. package/src/attention/socialTypes.ts +0 -115
  382. package/src/authz/authz.ts +0 -305
  383. package/src/authz/index.ts +0 -1
  384. package/src/bayes/calibration.ts +0 -204
  385. package/src/bayes/calibrationRegistry.ts +0 -111
  386. package/src/bayes/calibrationSelection.ts +0 -154
  387. package/src/bayes/engine.ts +0 -532
  388. package/src/bayes/index.ts +0 -6
  389. package/src/bayes/reliability.ts +0 -62
  390. package/src/bayes/scopedPriors.ts +0 -88
  391. package/src/boundary/frame.ts +0 -322
  392. package/src/boundary/ids.ts +0 -14
  393. package/src/boundary/index.ts +0 -12
  394. package/src/boundary/refTable.ts +0 -125
  395. package/src/boundary/toolCall.ts +0 -212
  396. package/src/concept/concept.ts +0 -75
  397. package/src/concept/conceptBudget.ts +0 -346
  398. package/src/concept/conceptBudgetTypes.ts +0 -79
  399. package/src/concept/index.ts +0 -3
  400. package/src/concurrency/idempotency.ts +0 -41
  401. package/src/concurrency/index.ts +0 -5
  402. package/src/concurrency/mutex.ts +0 -26
  403. package/src/concurrency/namedLocks.ts +0 -35
  404. package/src/concurrency/retry.ts +0 -50
  405. package/src/concurrency/worker.ts +0 -128
  406. package/src/context/agentContext.ts +0 -308
  407. package/src/context/ast.ts +0 -499
  408. package/src/context/contentStore.ts +0 -75
  409. package/src/context/context.ts +0 -65
  410. package/src/context/contextIndex.ts +0 -85
  411. package/src/context/document.ts +0 -137
  412. package/src/context/fileStorePath.ts +0 -14
  413. package/src/context/index.ts +0 -43
  414. package/src/context/lifecycle.ts +0 -221
  415. package/src/context/projections.ts +0 -151
  416. package/src/context/workspace.ts +0 -422
  417. package/src/context/workspaceProtocol.ts +0 -112
  418. package/src/context/workspaceService.ts +0 -423
  419. package/src/cooperation/board.ts +0 -104
  420. package/src/cooperation/collaboration.ts +0 -60
  421. package/src/cooperation/index.ts +0 -6
  422. package/src/cooperation/merge.ts +0 -190
  423. package/src/cooperation/metrics.ts +0 -57
  424. package/src/cooperation/session.ts +0 -131
  425. package/src/cooperation/unified.ts +0 -56
  426. package/src/counter.ts +0 -9
  427. package/src/database/adapter/adapters.ts +0 -35
  428. package/src/database/adapter/index.ts +0 -4
  429. package/src/database/adapter/runtimeSink.ts +0 -74
  430. package/src/database/adapter/sessionStore.ts +0 -32
  431. package/src/database/adapter/turnStore.ts +0 -23
  432. package/src/database/entity/agent.ts +0 -199
  433. package/src/database/entity/entity.ts +0 -1046
  434. package/src/database/entity/handle.ts +0 -79
  435. package/src/database/entity/index.ts +0 -32
  436. package/src/database/entity/message.ts +0 -74
  437. package/src/database/entity/meta.ts +0 -11
  438. package/src/database/entity/object.ts +0 -42
  439. package/src/database/entity/outbox.ts +0 -15
  440. package/src/database/entity/process.ts +0 -65
  441. package/src/database/entity/registry.ts +0 -155
  442. package/src/database/entity/runtimeApproval.ts +0 -30
  443. package/src/database/entity/runtimeSession.ts +0 -13
  444. package/src/database/entity/runtimeTurn.ts +0 -15
  445. package/src/database/entity/thread.ts +0 -85
  446. package/src/database/entity/window.ts +0 -85
  447. package/src/database/entity/worker.ts +0 -90
  448. package/src/database/index.ts +0 -6
  449. package/src/database/repository/addressSpaceRepository.ts +0 -72
  450. package/src/database/repository/agentRepository.ts +0 -460
  451. package/src/database/repository/base.ts +0 -41
  452. package/src/database/repository/executionRepository.ts +0 -477
  453. package/src/database/repository/handleRepository.ts +0 -64
  454. package/src/database/repository/index.ts +0 -20
  455. package/src/database/repository/messageRepository.ts +0 -52
  456. package/src/database/repository/objectRepository.ts +0 -69
  457. package/src/database/repository/outboxRepository.ts +0 -63
  458. package/src/database/repository/processRepository.ts +0 -58
  459. package/src/database/repository/registryRepository.ts +0 -119
  460. package/src/database/repository/repository.ts +0 -491
  461. package/src/database/repository/runtimeApprovalRepository.ts +0 -44
  462. package/src/database/repository/runtimeSessionRepository.ts +0 -27
  463. package/src/database/repository/runtimeTurnRepository.ts +0 -39
  464. package/src/database/repository/socialRepository.ts +0 -185
  465. package/src/database/repository/threadRepository.ts +0 -57
  466. package/src/database/repository/windowRepository.ts +0 -88
  467. package/src/database/repository/workerRepository.ts +0 -69
  468. package/src/database/service/database.ts +0 -90
  469. package/src/database/service/handleService.ts +0 -48
  470. package/src/database/service/index.ts +0 -16
  471. package/src/database/service/messageService.ts +0 -61
  472. package/src/database/service/objectService.ts +0 -59
  473. package/src/database/service/processService.ts +0 -61
  474. package/src/database/service/registryServices.ts +0 -88
  475. package/src/database/service/service.ts +0 -183
  476. package/src/database/service/stepService.ts +0 -53
  477. package/src/database/service/threadService.ts +0 -65
  478. package/src/database/service/windowService.ts +0 -30
  479. package/src/database/service/workerService.ts +0 -57
  480. package/src/database/sql/index.ts +0 -3
  481. package/src/database/sql/schema.ts +0 -418
  482. package/src/database/sql/sql.ts +0 -543
  483. package/src/database/store/database.ts +0 -210
  484. package/src/database/store/index.ts +0 -3
  485. package/src/database/store/store.ts +0 -266
  486. package/src/delegate/index.ts +0 -2
  487. package/src/delegate/team.ts +0 -268
  488. package/src/delegate/teamTypes.ts +0 -47
  489. package/src/diagnosis/checklist.ts +0 -74
  490. package/src/diagnosis/context.ts +0 -93
  491. package/src/diagnosis/frame.ts +0 -256
  492. package/src/diagnosis/index.ts +0 -5
  493. package/src/diagnosis/router.ts +0 -72
  494. package/src/diagnosis/types.ts +0 -89
  495. package/src/error/agentError.ts +0 -16
  496. package/src/error/ampError.ts +0 -20
  497. package/src/error/authzError.ts +0 -14
  498. package/src/error/boundaryRejection.ts +0 -20
  499. package/src/error/index.ts +0 -7
  500. package/src/error/kernelError.ts +0 -27
  501. package/src/error/mailboxError.ts +0 -9
  502. package/src/error/windowError.ts +0 -12
  503. package/src/evaluation/agreement.ts +0 -96
  504. package/src/evaluation/index.ts +0 -2
  505. package/src/evaluation/labels.ts +0 -241
  506. package/src/evidence/evidenceGraph.ts +0 -205
  507. package/src/evidence/index.ts +0 -4
  508. package/src/evidence/revalidation.ts +0 -191
  509. package/src/execution/exec.ts +0 -408
  510. package/src/execution/handles.ts +0 -65
  511. package/src/execution/index.ts +0 -3
  512. package/src/execution/pin.ts +0 -154
  513. package/src/frame/frame.ts +0 -70
  514. package/src/frame/index.ts +0 -1
  515. package/src/goal/goal.ts +0 -43
  516. package/src/goal/index.ts +0 -2
  517. package/src/goal/plan.ts +0 -196
  518. package/src/governance/attentionManifest.ts +0 -802
  519. package/src/governance/audit.ts +0 -362
  520. package/src/governance/budget.ts +0 -628
  521. package/src/governance/context.ts +0 -356
  522. package/src/governance/control.ts +0 -159
  523. package/src/governance/cooperation.ts +0 -479
  524. package/src/governance/credential.ts +0 -359
  525. package/src/governance/httpServer.ts +0 -99
  526. package/src/governance/index.ts +0 -32
  527. package/src/governance/legal.ts +0 -574
  528. package/src/governance/matrix.ts +0 -460
  529. package/src/governance/perspectives.ts +0 -406
  530. package/src/governance/signing.ts +0 -407
  531. package/src/governance/store.ts +0 -125
  532. package/src/governance/switching.ts +0 -459
  533. package/src/governance/toolPolicy.ts +0 -80
  534. package/src/governance/transport.ts +0 -204
  535. package/src/governance/types.ts +0 -380
  536. package/src/governance/workflow.ts +0 -743
  537. package/src/index.ts +0 -11
  538. package/src/interaction/index.ts +0 -1
  539. package/src/interaction/interaction.ts +0 -391
  540. package/src/ipc/index.ts +0 -4
  541. package/src/ipc/mailbox.ts +0 -132
  542. package/src/ipc/memorySocialStore.ts +0 -93
  543. package/src/ipc/social.ts +0 -93
  544. package/src/kernel/index.ts +0 -14
  545. package/src/kernel/scheduler.ts +0 -498
  546. package/src/ledger/checkpoint.ts +0 -304
  547. package/src/ledger/index.ts +0 -4
  548. package/src/ledger/ledger.ts +0 -31
  549. package/src/ledger/persistence.ts +0 -159
  550. package/src/ledger/share.ts +0 -80
  551. package/src/lock/index.ts +0 -2
  552. package/src/lock/lease.ts +0 -74
  553. package/src/main.ts +0 -199
  554. package/src/manifest/agentCard.ts +0 -72
  555. package/src/manifest/cardSign.ts +0 -87
  556. package/src/manifest/federation.ts +0 -237
  557. package/src/manifest/federationTypes.ts +0 -55
  558. package/src/manifest/index.ts +0 -8
  559. package/src/manifest/keys.ts +0 -643
  560. package/src/manifest/manifest.ts +0 -114
  561. package/src/manifest/sign.ts +0 -134
  562. package/src/manifest/trust.ts +0 -146
  563. package/src/mission/index.ts +0 -2
  564. package/src/mission/missionQueue.ts +0 -75
  565. package/src/module/index.ts +0 -9
  566. package/src/module/llm/deepseek.ts +0 -214
  567. package/src/module/llm/llm.ts +0 -84
  568. package/src/module/mcp/client.ts +0 -110
  569. package/src/module/mcp/http.ts +0 -102
  570. package/src/module/mcp/protocol.ts +0 -77
  571. package/src/module/mcp/server.ts +0 -148
  572. package/src/module/mcp/transport.ts +0 -30
  573. package/src/module/mcp/workspaceServer.ts +0 -111
  574. package/src/module/sandbox/sandbox.ts +0 -29
  575. package/src/module/tool/mcpExecutor.ts +0 -54
  576. package/src/module/tool/policy.ts +0 -52
  577. package/src/module/tool/redact.ts +0 -29
  578. package/src/module/tool/tool.ts +0 -53
  579. package/src/module/tool/workspaceExecutor.ts +0 -35
  580. package/src/policy/guard.ts +0 -240
  581. package/src/policy/index.ts +0 -2
  582. package/src/policy/policy.ts +0 -561
  583. package/src/process/agent.ts +0 -341
  584. package/src/process/agentService.ts +0 -236
  585. package/src/process/agentStore.ts +0 -378
  586. package/src/process/executionStore.ts +0 -151
  587. package/src/process/index.ts +0 -5
  588. package/src/process/process.ts +0 -240
  589. package/src/process/transitions.ts +0 -19
  590. package/src/progress/index.ts +0 -2
  591. package/src/progress/progress.ts +0 -85
  592. package/src/protocol/a2a.ts +0 -120
  593. package/src/protocol/channel.ts +0 -44
  594. package/src/protocol/envelope.ts +0 -655
  595. package/src/protocol/httpChannel.ts +0 -87
  596. package/src/protocol/index.ts +0 -6
  597. package/src/protocol/protocol.ts +0 -138
  598. package/src/protocol/wire.ts +0 -60
  599. package/src/receipt/index.ts +0 -1
  600. package/src/receipt/receipt.ts +0 -47
  601. package/src/registry/content.ts +0 -69
  602. package/src/registry/index.ts +0 -23
  603. package/src/registry/registry.ts +0 -599
  604. package/src/runtime/action.ts +0 -87
  605. package/src/runtime/behavior.ts +0 -330
  606. package/src/runtime/behaviorTuning.ts +0 -163
  607. package/src/runtime/cognitiveRuntime.ts +0 -703
  608. package/src/runtime/escalation.ts +0 -35
  609. package/src/runtime/governedTask.ts +0 -233
  610. package/src/runtime/index.ts +0 -15
  611. package/src/runtime/kernelRuntime.ts +0 -144
  612. package/src/runtime/operation.ts +0 -35
  613. package/src/runtime/replay.ts +0 -71
  614. package/src/runtime/routing.ts +0 -58
  615. package/src/runtime/safety.ts +0 -48
  616. package/src/runtime/session.ts +0 -341
  617. package/src/runtime/sessionStore.ts +0 -43
  618. package/src/runtime/telemetry.ts +0 -55
  619. package/src/runtime/turnStore.ts +0 -30
  620. package/src/scenario/index.ts +0 -1
  621. package/src/scenario/scenario.ts +0 -299
  622. package/src/semantic/canonical.ts +0 -24
  623. package/src/semantic/index.ts +0 -2
  624. package/src/semantic/sha256.ts +0 -82
  625. package/src/storage/appendLog.ts +0 -372
  626. package/src/storage/fileAppendSink.ts +0 -40
  627. package/src/storage/index.ts +0 -2
  628. package/src/store/bindCache.ts +0 -22
  629. package/src/store/cache.ts +0 -191
  630. package/src/store/context.ts +0 -31
  631. package/src/store/handleStore.ts +0 -31
  632. package/src/store/index.ts +0 -9
  633. package/src/store/messageStore.ts +0 -31
  634. package/src/store/objectStore.ts +0 -31
  635. package/src/store/processStore.ts +0 -31
  636. package/src/store/threadStore.ts +0 -31
  637. package/src/store/windowStore.ts +0 -31
  638. package/src/structure/abstractSyntaxTree.ts +0 -493
  639. package/src/structure/avlTree.ts +0 -408
  640. package/src/structure/binarySearchTree.ts +0 -352
  641. package/src/structure/binaryTree.ts +0 -525
  642. package/src/structure/bloomFilter.ts +0 -231
  643. package/src/structure/compare.ts +0 -110
  644. package/src/structure/cuckooFilter.ts +0 -337
  645. package/src/structure/deque.ts +0 -223
  646. package/src/structure/filterKey.ts +0 -36
  647. package/src/structure/hash.ts +0 -279
  648. package/src/structure/heap.ts +0 -268
  649. package/src/structure/index.ts +0 -20
  650. package/src/structure/iterator.ts +0 -22
  651. package/src/structure/lru.ts +0 -619
  652. package/src/structure/ordered.ts +0 -399
  653. package/src/structure/priority.ts +0 -915
  654. package/src/structure/queue.ts +0 -168
  655. package/src/structure/redBlackTree.ts +0 -680
  656. package/src/structure/segmentTree.ts +0 -248
  657. package/src/structure/stack.ts +0 -118
  658. package/src/structure/unordered.ts +0 -407
  659. package/src/style.css +0 -278
  660. package/src/thread/index.ts +0 -2
  661. package/src/thread/thread.ts +0 -176
  662. package/src/thread/transitions.ts +0 -17
  663. package/src/types/common.ts +0 -119
  664. package/src/types/index.ts +0 -23
  665. package/src/warrant/epistemic.ts +0 -154
  666. package/src/warrant/index.ts +0 -3
  667. package/src/warrant/inquiry.ts +0 -166
  668. package/src/warrant/warrant.ts +0 -179
  669. package/src/window/compaction.ts +0 -403
  670. package/src/window/compactionTypes.ts +0 -119
  671. package/src/window/index.ts +0 -7
  672. package/src/window/page.ts +0 -18
  673. package/src/window/window.ts +0 -244
  674. package/tools/_helpers.ts +0 -34
  675. package/tools/a2a-check.ts +0 -110
  676. package/tools/a2a-flow-check.ts +0 -78
  677. package/tools/agent-card-check.ts +0 -76
  678. package/tools/agent-check.ts +0 -236
  679. package/tools/agent-store-check.ts +0 -153
  680. package/tools/agreement-check.ts +0 -27
  681. package/tools/annotation-server-check.ts +0 -48
  682. package/tools/annotation-server.ts +0 -230
  683. package/tools/annotation-status.ts +0 -65
  684. package/tools/approval-access-check.ts +0 -66
  685. package/tools/arch-check.ts +0 -72
  686. package/tools/attention-core-check.ts +0 -48
  687. package/tools/attention-resource-check.ts +0 -169
  688. package/tools/audit-check.ts +0 -207
  689. package/tools/authority-check.ts +0 -124
  690. package/tools/authz-check.ts +0 -138
  691. package/tools/bayes-check.ts +0 -162
  692. package/tools/bayes-probe.ts +0 -154
  693. package/tools/behavior-tuning-check.ts +0 -53
  694. package/tools/board-check.ts +0 -87
  695. package/tools/boundary-check.ts +0 -199
  696. package/tools/bundle-trust-check.ts +0 -96
  697. package/tools/calibrate-imported.ts +0 -108
  698. package/tools/calibration-check.ts +0 -44
  699. package/tools/calibration-registry-check.ts +0 -40
  700. package/tools/calibration-sim.ts +0 -40
  701. package/tools/card-sign-check.ts +0 -71
  702. package/tools/card-trust-check.ts +0 -78
  703. package/tools/channel-check.ts +0 -86
  704. package/tools/checkpoint-check.ts +0 -620
  705. package/tools/cleanup-style-configs.ts +0 -29
  706. package/tools/cognition-check.ts +0 -648
  707. package/tools/cognitive-runtime-check.ts +0 -609
  708. package/tools/collaboration-demo.ts +0 -78
  709. package/tools/compaction-check.ts +0 -266
  710. package/tools/concept-check.ts +0 -260
  711. package/tools/concurrency-check.ts +0 -242
  712. package/tools/conformance-runtime.ts +0 -389
  713. package/tools/conformance.ts +0 -651
  714. package/tools/context-ast-check.ts +0 -90
  715. package/tools/context-ast-deepseek.ts +0 -242
  716. package/tools/context-graph-bench.ts +0 -50
  717. package/tools/context-graph-check.ts +0 -229
  718. package/tools/context-index-check.ts +0 -48
  719. package/tools/context-lifecycle-check.ts +0 -69
  720. package/tools/context-projection-check.ts +0 -73
  721. package/tools/context-scope-check.ts +0 -134
  722. package/tools/context-storage-check.ts +0 -113
  723. package/tools/cooperation-check.ts +0 -517
  724. package/tools/cooperation-http-check.ts +0 -125
  725. package/tools/deepseek-llm-check.ts +0 -147
  726. package/tools/deepseek-probe.ts +0 -494
  727. package/tools/diagnosis-check.ts +0 -109
  728. package/tools/diagnosis-router-check.ts +0 -50
  729. package/tools/document-context-check.ts +0 -237
  730. package/tools/envelope-check.ts +0 -659
  731. package/tools/eslint-rules/index.ts +0 -26
  732. package/tools/eslint-rules/rules/jsdoc-comment-format.ts +0 -105
  733. package/tools/eslint-rules/rules/no-function-keyword.ts +0 -60
  734. package/tools/eslint-rules/rules/no-multiline-parameters.ts +0 -71
  735. package/tools/eslint-rules/rules/no-multiline-type-parameters.ts +0 -57
  736. package/tools/eslint-rules/rules/no-undefined-comparison.ts +0 -115
  737. package/tools/eslint-rules/rules/prefer-template-for-string-conversion.ts +0 -97
  738. package/tools/eslint-rules/rules/require-typeof-parentheses.ts +0 -49
  739. package/tools/eslint-rules/rules/require-variable-type.ts +0 -36
  740. package/tools/eslint-rules/rules/variable-naming.ts +0 -175
  741. package/tools/eval-recorded-replay.ts +0 -215
  742. package/tools/eval-replay.ts +0 -139
  743. package/tools/eval-summary.ts +0 -136
  744. package/tools/evidence-revalidation-check.ts +0 -235
  745. package/tools/exec-check.ts +0 -217
  746. package/tools/federation-check.ts +0 -166
  747. package/tools/federation-demo.ts +0 -45
  748. package/tools/filter-check.ts +0 -243
  749. package/tools/governance-check.ts +0 -680
  750. package/tools/governance-store-check.ts +0 -131
  751. package/tools/governed-task-check.ts +0 -227
  752. package/tools/guard-check.ts +0 -122
  753. package/tools/http-channel-check.ts +0 -125
  754. package/tools/import-campaign.ts +0 -28
  755. package/tools/inquiry-check.ts +0 -126
  756. package/tools/interaction-check.ts +0 -171
  757. package/tools/interrupts-check.ts +0 -173
  758. package/tools/ipc-check.ts +0 -170
  759. package/tools/kernel-async-check.ts +0 -136
  760. package/tools/kernel-check.ts +0 -369
  761. package/tools/kernel-runtime-check.ts +0 -276
  762. package/tools/keys-check.ts +0 -559
  763. package/tools/label-audit.ts +0 -70
  764. package/tools/labels-workflow-check.ts +0 -49
  765. package/tools/linear-structure-check.ts +0 -524
  766. package/tools/live-exec.ts +0 -62
  767. package/tools/live-governance-eval.ts +0 -813
  768. package/tools/live-legacy.ts +0 -50
  769. package/tools/lru-check.ts +0 -182
  770. package/tools/make-annotation-campaign.ts +0 -57
  771. package/tools/mcp-executor-check.ts +0 -33
  772. package/tools/merge-annotations.ts +0 -32
  773. package/tools/merge-check.ts +0 -98
  774. package/tools/metrics-check.ts +0 -84
  775. package/tools/net-probe.ts +0 -107
  776. package/tools/oauth-probe.ts +0 -117
  777. package/tools/outbox-check.ts +0 -50
  778. package/tools/persistence-check.ts +0 -144
  779. package/tools/pin-check.ts +0 -116
  780. package/tools/platform-check.ts +0 -281
  781. package/tools/policy-check.ts +0 -514
  782. package/tools/prettier-plugin/index.mts +0 -84
  783. package/tools/priority-check.ts +0 -627
  784. package/tools/probe-context7.ts +0 -63
  785. package/tools/registry-check.ts +0 -252
  786. package/tools/reliability-check.ts +0 -25
  787. package/tools/retry-check.ts +0 -85
  788. package/tools/rewrite-declaration-extensions.ts +0 -98
  789. package/tools/runtime-check.ts +0 -165
  790. package/tools/runtime-deepseek-check.ts +0 -85
  791. package/tools/runtime-eval.ts +0 -358
  792. package/tools/scenario-check.ts +0 -161
  793. package/tools/scenario-incident.ts +0 -162
  794. package/tools/scoped-priors-check.ts +0 -35
  795. package/tools/scoped-priors-pooling.ts +0 -34
  796. package/tools/segment-ast-check.ts +0 -649
  797. package/tools/session-check.ts +0 -196
  798. package/tools/session-store-check.ts +0 -73
  799. package/tools/share-check.ts +0 -88
  800. package/tools/sign-check.ts +0 -95
  801. package/tools/signing-check.ts +0 -275
  802. package/tools/snapshot-demo.ts +0 -65
  803. package/tools/social-check.ts +0 -146
  804. package/tools/structure-compare-check.ts +0 -95
  805. package/tools/support/documentScanner.ts +0 -577
  806. package/tools/support/texScanner.ts +0 -631
  807. package/tools/support/workspaceScanner.ts +0 -476
  808. package/tools/team-check.ts +0 -163
  809. package/tools/team-demo.ts +0 -36
  810. package/tools/telemetry-check.ts +0 -44
  811. package/tools/tex-context-check.ts +0 -263
  812. package/tools/tool-gate-check.ts +0 -98
  813. package/tools/tree-structure-check.ts +0 -786
  814. package/tools/trust-flow-check.ts +0 -158
  815. package/tools/turn-store-check.ts +0 -57
  816. package/tools/unified-check.ts +0 -83
  817. package/tools/validate.ts +0 -309
  818. package/tools/wire-check.ts +0 -96
  819. package/tools/workspace-agent-check.ts +0 -486
  820. package/tools/workspace-agent-demo.ts +0 -62
  821. package/tools/workspace-agent-server.ts +0 -101
  822. package/tools/workspace-context-check.ts +0 -331
  823. package/tools/workspace-context.ts +0 -131
  824. package/tsconfig.build.json +0 -14
  825. package/tsconfig.json +0 -24
  826. package/tsconfig.tools.json +0 -31
  827. package/viz/context-ast.json +0 -1577
@@ -1,915 +0,0 @@
1
- /**
2
- * Priority-ordered containers.
3
- *
4
- * Every container in this module orders values by a {@link Comparator} and then
5
- * by arrival: when two values compare equal, the one enqueued first is served
6
- * first. The queues are therefore stable, and re-inserting an equal value never
7
- * reorders them.
8
- *
9
- * `order: 'max'` is the default and serves the greatest value first, matching
10
- * the priority convention used elsewhere in this project where a larger number
11
- * is more urgent; `order: 'min'` serves the smallest first. The comparator
12
- * decides priority only — it never changes which values are stored.
13
- *
14
- * Costs, with `n` entries and `b` live integer priorities:
15
- *
16
- * | Container | enqueue | dequeue | peek | re-prioritise |
17
- * | --- | --- | --- | --- | --- |
18
- * | {@link PriorityQueue} | O(log n) | O(log n) | O(1) | — |
19
- * | {@link IndexedPriorityQueue} | O(log n) | O(log n) | O(1) | O(log n) |
20
- * | {@link BucketQueue} | O(1) | O(1) amortised | O(1) | — |
21
- * | {@link TopK} | O(log k) | — | O(1) | — |
22
- *
23
- * `toArray`, iteration and `drain` expose **dequeue order**, not internal
24
- * storage order: the contract of a priority queue is the order in which it will
25
- * be served. This is the deliberate difference from {@link BinaryHeap}, whose
26
- * snapshots expose heap order. `drain` is the destructive version of `toArray`.
27
- */
28
-
29
- import { compareNatural } from "./compare.ts";
30
- import type { Comparator } from "./compare.ts";
31
- import { BinaryHeap } from "./heap.ts";
32
- import type { HeapOrder } from "./heap.ts";
33
- import { generatorFrom } from "./iterator.ts";
34
-
35
- /**
36
- * The part of a stored entry that ordering depends on: a value and the sequence
37
- * number that decides ties.
38
- */
39
- interface Sequenced<T> {
40
- value: T;
41
- sequence: number;
42
- }
43
-
44
- /**
45
- * One FIFO bucket inside a {@link BucketQueue}.
46
- *
47
- * `head` advances through `values` as entries are served. Consumed slots are
48
- * compacted away once they outnumber the live ones, so a bucket that is drained
49
- * slowly does not pin its served entries forever.
50
- */
51
- interface Bucket<T> {
52
- values: T[];
53
- head: number;
54
- }
55
-
56
- /**
57
- * Sign multiplier that turns a comparator into the serving order of a heap:
58
- * the smallest result is served first, so `'max'` inverts the comparator.
59
- */
60
- const servingDirection: (order: HeapOrder) => number = (order: HeapOrder): number => {
61
- return order === "max" ? -1 : 1;
62
- };
63
-
64
- /**
65
- * Sign multiplier for "better than": a positive result means the left value is
66
- * better, so `'max'` keeps the comparator as it is.
67
- */
68
- const qualityDirection: (order: HeapOrder) => number = (order: HeapOrder): number => {
69
- return order === "max" ? 1 : -1;
70
- };
71
-
72
- /**
73
- * Compare two stored entries: priority first, then arrival order.
74
- *
75
- * The multiplier is applied before the tie-break, so reversing the order flips
76
- * priorities without reversing equal entries. Arrival order is always the
77
- * earlier sequence first, which is what makes every queue in this module
78
- * stable.
79
- */
80
- type EntryComparator = <T>(compare: Comparator<T>, direction: number) => Comparator<Sequenced<T>>;
81
-
82
- const entryComparator: EntryComparator = <T>(compare: Comparator<T>, direction: number): Comparator<Sequenced<T>> => {
83
- return (left: Sequenced<T>, right: Sequenced<T>): number => {
84
- const byPriority: number = direction * compare(left.value, right.value);
85
- if (byPriority !== 0) {
86
- return byPriority;
87
- }
88
- return left.sequence - right.sequence;
89
- };
90
- };
91
-
92
- /**
93
- * Reject a capacity that cannot bound a container.
94
- */
95
- const requireCapacity: (capacity: number) => void = (capacity: number): void => {
96
- if (!Number.isSafeInteger(capacity) || capacity <= 0) {
97
- throw new RangeError("capacity must be a positive safe integer");
98
- }
99
- };
100
-
101
- /**
102
- * Options for {@link PriorityQueue}.
103
- */
104
- export interface PriorityQueueOptions<T> {
105
- /**
106
- * Ordering that decides priority. Defaults to {@link compareNatural}.
107
- */
108
- compare?: Comparator<T>;
109
- /**
110
- * Which end is served first. Defaults to `'max'`.
111
- */
112
- order?: HeapOrder;
113
- /**
114
- * Initial values, enqueued in iteration order.
115
- */
116
- values?: Iterable<T>;
117
- }
118
-
119
- /**
120
- * A stable priority queue backed by a binary heap.
121
- *
122
- * The value that compares greatest under `compare` is served first by default;
123
- * `order: 'min'` serves the least. Ties are broken by arrival, so two entries
124
- * with the same priority always leave in the order they were enqueued.
125
- *
126
- * `enqueue` and `dequeue` are O(log n), and `peek` is O(1). `toArray`,
127
- * iteration and `drain` return **dequeue order**; `drain` removes everything.
128
- *
129
- * `dequeue` and `peek` return `undefined` when the queue is empty. Because
130
- * `undefined` is also a valid stored value, check {@link size} or
131
- * {@link isEmpty} when presence matters.
132
- *
133
- * @example
134
- * ```ts
135
- * const queue = new PriorityQueue<number>({ values: [3, 1, 4, 1] });
136
- * queue.enqueue(2);
137
- * queue.dequeue(); // 4
138
- * [...queue]; // [3, 2, 1, 1]
139
- * queue.drain(); // [3, 2, 1, 1]
140
- * ```
141
- */
142
- export class PriorityQueue<T> implements Iterable<T> {
143
- private readonly heap: BinaryHeap<Sequenced<T>>;
144
- private readonly compareFn: Comparator<Sequenced<T>>;
145
- private sequence = 0;
146
-
147
- /**
148
- * Create a queue, optionally seeded with values and a custom ordering.
149
- *
150
- * Seeded values are enqueued in iteration order, so among equal priorities
151
- * the first seeded value is served first.
152
- *
153
- * @param options - Comparator, order, and initial values.
154
- */
155
- constructor(options?: PriorityQueueOptions<T>) {
156
- const compare: Comparator<T> = options?.compare ?? compareNatural;
157
- const order: HeapOrder = options?.order ?? "max";
158
- this.compareFn = entryComparator<T>(compare, servingDirection(order));
159
- this.heap = new BinaryHeap<Sequenced<T>>({ compare: this.compareFn });
160
- if (options?.values !== (void 0)) {
161
- this.enqueueAll(options.values);
162
- }
163
- }
164
-
165
- /**
166
- * Build a queue from `values` without repeating the `values` option.
167
- *
168
- * @param values - Initial values to enqueue in iteration order.
169
- * @param options - Comparator and order options.
170
- * @returns A new priority queue containing every supplied value.
171
- */
172
- static from<T>(values: Iterable<T>, options?: Omit<PriorityQueueOptions<T>, "values">): PriorityQueue<T> {
173
- const queueOptions: PriorityQueueOptions<T> = { values };
174
- if (options?.compare !== (void 0)) {
175
- queueOptions.compare = options.compare;
176
- }
177
- if (options?.order !== (void 0)) {
178
- queueOptions.order = options.order;
179
- }
180
- return new PriorityQueue<T>(queueOptions);
181
- }
182
-
183
- /**
184
- * Number of values currently in the queue.
185
- */
186
- get size(): number {
187
- return this.heap.size;
188
- }
189
-
190
- /**
191
- * Whether the queue contains no values.
192
- */
193
- get isEmpty(): boolean {
194
- return this.heap.isEmpty;
195
- }
196
-
197
- /**
198
- * Add a value at its priority, behind any equal value already queued.
199
- *
200
- * @param value - Value to enqueue.
201
- * @returns This queue, for chaining.
202
- */
203
- enqueue(value: T): this {
204
- const entry: Sequenced<T> = { value, sequence: this.sequence };
205
- this.sequence += 1;
206
- this.heap.push(entry);
207
- return this;
208
- }
209
-
210
- /**
211
- * Enqueue every value in iteration order.
212
- *
213
- * @param values - Values to enqueue.
214
- * @returns This queue, for chaining.
215
- */
216
- enqueueAll(values: Iterable<T>): this {
217
- const items: T[] = [...values];
218
- for (let index: number = 0; index < items.length; index += 1) {
219
- this.enqueue(items[index]);
220
- }
221
- return this;
222
- }
223
-
224
- /**
225
- * Remove and return the value with the highest priority.
226
- *
227
- * @returns The served value, or `undefined` if the queue is empty.
228
- */
229
- dequeue(): T | undefined {
230
- const entry: Sequenced<T> | undefined = this.heap.pop();
231
- return entry === (void 0) ? undefined : entry.value;
232
- }
233
-
234
- /**
235
- * Return the value that would be served next, without removing it.
236
- *
237
- * @returns The next value, or `undefined` if the queue is empty.
238
- */
239
- peek(): T | undefined {
240
- const entry: Sequenced<T> | undefined = this.heap.peek();
241
- return entry === (void 0) ? undefined : entry.value;
242
- }
243
-
244
- /**
245
- * Remove every value and reset the arrival counter.
246
- */
247
- clear(): void {
248
- this.heap.clear();
249
- this.sequence = 0;
250
- }
251
-
252
- /**
253
- * Snapshot the values in dequeue order without changing the queue.
254
- *
255
- * The cost is O(n log n): the heap is copied, then sorted by the same
256
- * comparator the queue uses.
257
- *
258
- * @returns A new array whose first item is served first.
259
- */
260
- toArray(): T[] {
261
- const entries: Sequenced<T>[] = this.heap.toArray();
262
- entries.sort(this.compareFn);
263
- return entries.map((entry: Sequenced<T>): T => entry.value);
264
- }
265
-
266
- /**
267
- * Remove and return every value in dequeue order.
268
- *
269
- * @returns A new array in the order the values would have been served.
270
- */
271
- drain(): T[] {
272
- const values: T[] = [];
273
- while (!this.heap.isEmpty) {
274
- const entry: Sequenced<T> | undefined = this.heap.pop();
275
- if (entry !== (void 0)) {
276
- values.push(entry.value);
277
- }
278
- }
279
- return values;
280
- }
281
-
282
- /**
283
- * Iterate in dequeue order over a snapshot taken when the iterator is
284
- * created.
285
- */
286
- [Symbol.iterator](): Generator<T, void, unknown> {
287
- return generatorFrom(this.toArray());
288
- }
289
- }
290
-
291
- /**
292
- * Options for {@link IndexedPriorityQueue}.
293
- */
294
- export interface IndexedPriorityQueueOptions<K, T> {
295
- /**
296
- * Derives the key that identifies a value. It is evaluated once per
297
- * {@link IndexedPriorityQueue.set}.
298
- */
299
- keyOf: (value: T) => K;
300
- /**
301
- * Ordering that decides priority. Defaults to {@link compareNatural}.
302
- */
303
- compare?: Comparator<T>;
304
- /**
305
- * Which end is served first. Defaults to `'max'`.
306
- */
307
- order?: HeapOrder;
308
- }
309
-
310
- /**
311
- * A keyed entry stored by {@link IndexedPriorityQueue}.
312
- */
313
- interface KeyedEntry<K, T> extends Sequenced<T> {
314
- key: K;
315
- }
316
-
317
- /**
318
- * A priority queue that can be addressed by key.
319
- *
320
- * A plain {@link PriorityQueue} cannot re-prioritise or remove an entry it has
321
- * already accepted, because finding it costs a scan. This queue keeps a map
322
- * from key to heap position, so `set`, `delete`, `get` and `has` are O(log n)
323
- * or O(1) — the shape Dijkstra's algorithm and task schedulers need.
324
- *
325
- * `set` inserts a new key or replaces the value stored under an existing one.
326
- * A replaced entry keeps its original arrival sequence, so re-setting an entry
327
- * at an unchanged priority does not move it behind entries that arrived later.
328
- * Ties are still served in arrival order.
329
- *
330
- * `toArray` and `keys` are O(n log n) snapshots in dequeue order; `dequeue`,
331
- * `peek`, `get` and `delete` do not scan.
332
- *
333
- * @example
334
- * ```ts
335
- * const queue = new IndexedPriorityQueue<string, Task>({
336
- * keyOf: (task: Task): string => task.id,
337
- * compare: (left: Task, right: Task): number => left.rank - right.rank,
338
- * });
339
- * queue.set({ id: "a", rank: 2 }).set({ id: "b", rank: 5 });
340
- * queue.peek()?.id; // "b"
341
- * queue.set({ id: "a", rank: 9 });
342
- * queue.dequeue()?.id; // "a"
343
- * queue.delete("b"); // true
344
- * ```
345
- */
346
- export class IndexedPriorityQueue<K, T> implements Iterable<T> {
347
- private readonly entries: KeyedEntry<K, T>[] = [];
348
- private readonly positions = new Map<K, number>();
349
- private readonly keyOf: (value: T) => K;
350
- private readonly compareFn: Comparator<Sequenced<T>>;
351
- private sequence = 0;
352
-
353
- /**
354
- * Create an empty keyed queue.
355
- *
356
- * @param options - Key selector, comparator and order.
357
- */
358
- constructor(options: IndexedPriorityQueueOptions<K, T>) {
359
- const compare: Comparator<T> = options.compare ?? compareNatural;
360
- const order: HeapOrder = options.order ?? "max";
361
- this.keyOf = options.keyOf;
362
- this.compareFn = entryComparator<T>(compare, servingDirection(order));
363
- }
364
-
365
- /**
366
- * Number of entries currently in the queue.
367
- */
368
- get size(): number {
369
- return this.entries.length;
370
- }
371
-
372
- /**
373
- * Whether the queue contains no entries.
374
- */
375
- get isEmpty(): boolean {
376
- return this.entries.length === 0;
377
- }
378
-
379
- /**
380
- * Insert a value, or replace the value stored under its key.
381
- *
382
- * A new key is appended behind entries with equal priority. An existing key
383
- * keeps its arrival sequence and only moves if its priority changed.
384
- *
385
- * @param value - Value to insert or replace.
386
- * @returns This queue, for chaining.
387
- */
388
- set(value: T): this {
389
- const key: K = this.keyOf(value);
390
- const index: number | undefined = this.positions.get(key);
391
- if (index === (void 0)) {
392
- const entry: KeyedEntry<K, T> = { key, value, sequence: this.sequence };
393
- this.sequence += 1;
394
- this.positions.set(key, this.entries.length);
395
- this.entries.push(entry);
396
- this.siftUp(this.entries.length - 1);
397
- return this;
398
- }
399
- const entry: KeyedEntry<K, T> = this.entries[index];
400
- entry.value = value;
401
- const moved: number = this.siftUp(index);
402
- this.siftDown(moved);
403
- return this;
404
- }
405
-
406
- /**
407
- * Remove the entry stored under `key`.
408
- *
409
- * @param key - Key to remove.
410
- * @returns `true` if an entry was removed, `false` if the key was absent.
411
- */
412
- delete(key: K): boolean {
413
- const index: number | undefined = this.positions.get(key);
414
- if (index === (void 0)) {
415
- return false;
416
- }
417
- this.removeAt(index);
418
- return true;
419
- }
420
-
421
- /**
422
- * Read the value stored under `key` without changing the queue.
423
- *
424
- * @param key - Key to read.
425
- * @returns The stored value, or `undefined` if the key is absent.
426
- */
427
- get(key: K): T | undefined {
428
- const index: number | undefined = this.positions.get(key);
429
- return index === (void 0) ? undefined : this.entries[index].value;
430
- }
431
-
432
- /**
433
- * Whether an entry is stored under `key`.
434
- *
435
- * @param key - Key to test.
436
- */
437
- has(key: K): boolean {
438
- return this.positions.has(key);
439
- }
440
-
441
- /**
442
- * Remove and return the value with the highest priority.
443
- *
444
- * @returns The served value, or `undefined` if the queue is empty.
445
- */
446
- dequeue(): T | undefined {
447
- if (this.entries.length === 0) {
448
- return undefined;
449
- }
450
- return this.removeAt(0).value;
451
- }
452
-
453
- /**
454
- * Return the value that would be served next, without removing it.
455
- *
456
- * @returns The next value, or `undefined` if the queue is empty.
457
- */
458
- peek(): T | undefined {
459
- return this.entries.length === 0 ? undefined : this.entries[0].value;
460
- }
461
-
462
- /**
463
- * Return the key that would be served next, without removing it.
464
- *
465
- * @returns The next key, or `undefined` if the queue is empty.
466
- */
467
- peekKey(): K | undefined {
468
- return this.entries.length === 0 ? undefined : this.entries[0].key;
469
- }
470
-
471
- /**
472
- * Remove every entry.
473
- */
474
- clear(): void {
475
- this.entries.length = 0;
476
- this.positions.clear();
477
- this.sequence = 0;
478
- }
479
-
480
- /**
481
- * Snapshot the values in dequeue order.
482
- *
483
- * @returns A new array whose first item is served first.
484
- */
485
- toArray(): T[] {
486
- const ordered: Sequenced<T>[] = this.entries.slice();
487
- ordered.sort(this.compareFn);
488
- return ordered.map((entry: Sequenced<T>): T => entry.value);
489
- }
490
-
491
- /**
492
- * Snapshot the keys in dequeue order.
493
- *
494
- * @returns A new array whose first key is served first.
495
- */
496
- keys(): K[] {
497
- const ordered: KeyedEntry<K, T>[] = this.entries.slice();
498
- ordered.sort(this.compareFn);
499
- return ordered.map((entry: KeyedEntry<K, T>): K => entry.key);
500
- }
501
-
502
- /**
503
- * Iterate in dequeue order over a snapshot taken when the iterator is
504
- * created.
505
- */
506
- [Symbol.iterator](): Generator<T, void, unknown> {
507
- return generatorFrom(this.toArray());
508
- }
509
-
510
- /**
511
- * Remove the entry at `index` and return it.
512
- *
513
- * The last entry fills the hole, then moves either up or down to restore
514
- * the heap property; the key index follows both moves.
515
- */
516
- private removeAt(index: number): KeyedEntry<K, T> {
517
- const removed: KeyedEntry<K, T> = this.entries[index];
518
- const lastIndex: number = this.entries.length - 1;
519
- const last: KeyedEntry<K, T> = this.entries[lastIndex];
520
- this.entries.pop();
521
- this.positions.delete(removed.key);
522
- if (index !== lastIndex) {
523
- this.entries[index] = last;
524
- this.positions.set(last.key, index);
525
- const moved: number = this.siftUp(index);
526
- this.siftDown(moved);
527
- }
528
- return removed;
529
- }
530
-
531
- /**
532
- * Move an entry toward the root until its parent has priority.
533
- *
534
- * @returns The index the entry ended up at.
535
- */
536
- private siftUp(index: number): number {
537
- let child: number = index;
538
- while (child > 0) {
539
- const parent: number = Math.floor((child - 1) / 2);
540
- if (this.compareFn(this.entries[child], this.entries[parent]) >= 0) {
541
- return child;
542
- }
543
- this.swap(child, parent);
544
- child = parent;
545
- }
546
- return child;
547
- }
548
-
549
- /**
550
- * Move an entry toward the leaves until both children have lower priority.
551
- */
552
- private siftDown(index: number): void {
553
- let parent: number = index;
554
- while (true) {
555
- const left: number = parent * 2 + 1;
556
- if (left >= this.entries.length) {
557
- return;
558
- }
559
- const right: number = left + 1;
560
- let first: number = left;
561
- if (right < this.entries.length && this.compareFn(this.entries[right], this.entries[left]) < 0) {
562
- first = right;
563
- }
564
- if (this.compareFn(this.entries[first], this.entries[parent]) >= 0) {
565
- return;
566
- }
567
- this.swap(parent, first);
568
- parent = first;
569
- }
570
- }
571
-
572
- /**
573
- * Exchange two entries and keep the key index consistent.
574
- */
575
- private swap(a: number, b: number): void {
576
- const left: KeyedEntry<K, T> = this.entries[a];
577
- const right: KeyedEntry<K, T> = this.entries[b];
578
- this.entries[a] = right;
579
- this.entries[b] = left;
580
- this.positions.set(right.key, a);
581
- this.positions.set(left.key, b);
582
- }
583
- }
584
-
585
- /**
586
- * Options for {@link BucketQueue}.
587
- */
588
- export interface BucketQueueOptions {
589
- /**
590
- * Which end is served first. Defaults to `'max'`.
591
- */
592
- order?: HeapOrder;
593
- }
594
-
595
- /**
596
- * A priority queue for integer priorities, with one FIFO bucket per priority.
597
- *
598
- * Values sharing a priority wait in a single bucket, so serving the next entry
599
- * costs O(1) until the active bucket empties; switching to the next live bucket
600
- * costs O(log b) once, where `b` is the number of non-empty buckets. This is
601
- * the right shape when priorities come from a small domain — scheduler ticks,
602
- * T-shirt sizes, the 0–100 behaviour priorities used in this project — and the
603
- * per-entry generality of a comparison heap is wasted.
604
- *
605
- * Priorities must be safe integers; anything else raises a `RangeError`, since
606
- * a bucket index cannot represent it. Negative priorities are fine, and the
607
- * live priorities need not be contiguous: only buckets that hold values are
608
- * tracked.
609
- *
610
- * @example
611
- * ```ts
612
- * const queue = new BucketQueue<string>();
613
- * queue.enqueue("cold", 0).enqueue("warm", 1).enqueue("hot", 9);
614
- * queue.dequeue(); // "hot"
615
- * queue.peekPriority(); // 1
616
- * queue.toArray(); // ["warm", "cold"]
617
- * ```
618
- */
619
- export class BucketQueue<T> implements Iterable<T> {
620
- private readonly buckets = new Map<number, Bucket<T>>();
621
- private readonly active: BinaryHeap<number>;
622
- private readonly order: HeapOrder;
623
- private count = 0;
624
-
625
- /**
626
- * Create an empty bucket queue.
627
- *
628
- * @param options - Which end is served first.
629
- */
630
- constructor(options?: BucketQueueOptions) {
631
- this.order = options?.order ?? "max";
632
- this.active = new BinaryHeap<number>({ order: this.order });
633
- }
634
-
635
- /**
636
- * Number of values currently in the queue.
637
- */
638
- get size(): number {
639
- return this.count;
640
- }
641
-
642
- /**
643
- * Whether the queue contains no values.
644
- */
645
- get isEmpty(): boolean {
646
- return this.count === 0;
647
- }
648
-
649
- /**
650
- * Append a value to the bucket for `priority`.
651
- *
652
- * Values with the same priority leave in enqueue order.
653
- *
654
- * @param value - Value to enqueue.
655
- * @param priority - Integer priority; greater is served first by default.
656
- * @returns This queue, for chaining.
657
- */
658
- enqueue(value: T, priority: number): this {
659
- if (!Number.isSafeInteger(priority)) {
660
- throw new RangeError("priority must be a safe integer");
661
- }
662
- let bucket: Bucket<T> | undefined = this.buckets.get(priority);
663
- if (bucket === (void 0)) {
664
- bucket = { values: [], head: 0 };
665
- this.buckets.set(priority, bucket);
666
- this.active.push(priority);
667
- }
668
- bucket.values.push(value);
669
- this.count += 1;
670
- return this;
671
- }
672
-
673
- /**
674
- * Remove and return the value with the highest priority.
675
- *
676
- * @returns The served value, or `undefined` if the queue is empty.
677
- */
678
- dequeue(): T | undefined {
679
- const priority: number | undefined = this.peekPriority();
680
- if (priority === (void 0)) {
681
- return undefined;
682
- }
683
- const bucket: Bucket<T> | undefined = this.buckets.get(priority);
684
- if (bucket === (void 0)) {
685
- return undefined;
686
- }
687
- const value: T = bucket.values[bucket.head];
688
- bucket.head += 1;
689
- this.count -= 1;
690
- if (bucket.head === bucket.values.length) {
691
- this.buckets.delete(priority);
692
- this.active.pop();
693
- } else if (bucket.head > 32 && bucket.head * 2 >= bucket.values.length) {
694
- bucket.values = bucket.values.slice(bucket.head);
695
- bucket.head = 0;
696
- }
697
- return value;
698
- }
699
-
700
- /**
701
- * Return the value that would be served next, without removing it.
702
- *
703
- * @returns The next value, or `undefined` if the queue is empty.
704
- */
705
- peek(): T | undefined {
706
- const priority: number | undefined = this.peekPriority();
707
- if (priority === (void 0)) {
708
- return undefined;
709
- }
710
- const bucket: Bucket<T> | undefined = this.buckets.get(priority);
711
- return bucket === (void 0) ? undefined : bucket.values[bucket.head];
712
- }
713
-
714
- /**
715
- * Priority of the next entry to be served, without removing it.
716
- *
717
- * @returns The next priority, or `undefined` if the queue is empty.
718
- */
719
- peekPriority(): number | undefined {
720
- while (!this.active.isEmpty) {
721
- const priority: number | undefined = this.active.peek();
722
- if (priority !== (void 0) && this.buckets.has(priority)) {
723
- return priority;
724
- }
725
- this.active.pop();
726
- }
727
- return undefined;
728
- }
729
-
730
- /**
731
- * Remove every value.
732
- */
733
- clear(): void {
734
- this.buckets.clear();
735
- this.active.clear();
736
- this.count = 0;
737
- }
738
-
739
- /**
740
- * Snapshot the values in dequeue order without changing the queue.
741
- *
742
- * @returns A new array whose first item is served first.
743
- */
744
- toArray(): T[] {
745
- const priorities: number[] = [...this.buckets.keys()];
746
- priorities.sort((left: number, right: number): number => {
747
- return this.order === "max" ? right - left : left - right;
748
- });
749
- const values: T[] = [];
750
- for (let priorityIndex: number = 0; priorityIndex < priorities.length; priorityIndex += 1) {
751
- const priority: number = priorities[priorityIndex];
752
- const bucket: Bucket<T> | undefined = this.buckets.get(priority);
753
- if (bucket === (void 0)) {
754
- continue;
755
- }
756
- for (let index: number = bucket.head; index < bucket.values.length; index += 1) {
757
- values.push(bucket.values[index]);
758
- }
759
- }
760
- return values;
761
- }
762
-
763
- /**
764
- * Iterate in dequeue order over a snapshot taken when the iterator is
765
- * created.
766
- */
767
- [Symbol.iterator](): Generator<T, void, unknown> {
768
- return generatorFrom(this.toArray());
769
- }
770
- }
771
-
772
- /**
773
- * Options for {@link TopK}.
774
- */
775
- export interface TopKOptions<T> {
776
- /**
777
- * Ordering that decides which values are best. Defaults to
778
- * {@link compareNatural}.
779
- */
780
- compare?: Comparator<T>;
781
- /**
782
- * Which end is best. Defaults to `'max'`, so the greatest values are kept.
783
- */
784
- order?: HeapOrder;
785
- }
786
-
787
- /**
788
- * The `k` best values seen so far, in a bounded buffer.
789
- *
790
- * `offer` keeps the best `capacity` values under the comparator and discards
791
- * the rest, in O(log k): the retained values live in a heap whose root is the
792
- * current worst, so a new value only displaces that root. A value equal to the
793
- * worst is refused rather than swapping equal entries, which keeps the buffer
794
- * stable and its contents independent of later arrivals.
795
- *
796
- * The buffer is useful when a full sort is wasteful — for example keeping the
797
- * `k` most salient candidates out of a stream that never ends.
798
- *
799
- * @example
800
- * ```ts
801
- * const best = new TopK<number>(3);
802
- * for (const value of [5, 1, 9, 3, 7]) {
803
- * best.offer(value);
804
- * }
805
- * best.toArray(); // [9, 7, 5]
806
- * best.worst; // 5
807
- * ```
808
- */
809
- export class TopK<T> implements Iterable<T> {
810
- /**
811
- * Maximum number of values retained.
812
- */
813
- readonly capacity: number;
814
- private readonly retained: BinaryHeap<T>;
815
- private readonly compareFn: Comparator<T>;
816
- private readonly quality: number;
817
-
818
- /**
819
- * Create an empty buffer for the `capacity` best values.
820
- *
821
- * @param capacity - Maximum number of values retained; positive integer.
822
- * @param options - Comparator and which end is best.
823
- */
824
- constructor(capacity: number, options?: TopKOptions<T>) {
825
- requireCapacity(capacity);
826
- this.capacity = capacity;
827
- this.compareFn = options?.compare ?? compareNatural;
828
- this.quality = qualityDirection(options?.order ?? "max");
829
- this.retained = new BinaryHeap<T>({
830
- compare: (left: T, right: T): number => this.signedCompare(left, right),
831
- });
832
- }
833
-
834
- /**
835
- * Number of values currently retained.
836
- */
837
- get size(): number {
838
- return this.retained.size;
839
- }
840
-
841
- /**
842
- * Whether the buffer holds `capacity` values.
843
- */
844
- get isFull(): boolean {
845
- return this.retained.size >= this.capacity;
846
- }
847
-
848
- /**
849
- * The weakest retained value: the next one to be displaced.
850
- *
851
- * @returns The current worst value, or `undefined` if nothing is retained.
852
- */
853
- get worst(): T | undefined {
854
- return this.retained.peek();
855
- }
856
-
857
- /**
858
- * Offer a value to the buffer.
859
- *
860
- * A value is retained while there is room; once full, only a value that
861
- * strictly outranks {@link worst} is kept and the worst is displaced. A tie
862
- * keeps the value that arrived first.
863
- *
864
- * @param value - Value to offer.
865
- * @returns `true` if the value is retained afterwards, `false` otherwise.
866
- */
867
- offer(value: T): boolean {
868
- if (!this.isFull) {
869
- this.retained.push(value);
870
- return true;
871
- }
872
- const worst: T | undefined = this.retained.peek();
873
- if (worst === (void 0)) {
874
- return false;
875
- }
876
- if (this.signedCompare(value, worst) <= 0) {
877
- return false;
878
- }
879
- this.retained.replace(value);
880
- return true;
881
- }
882
-
883
- /**
884
- * Discard every retained value.
885
- */
886
- clear(): void {
887
- this.retained.clear();
888
- }
889
-
890
- /**
891
- * Snapshot the retained values, best first.
892
- *
893
- * @returns A new array in dequeue order.
894
- */
895
- toArray(): T[] {
896
- const values: T[] = this.retained.toArray();
897
- values.sort((left: T, right: T): number => this.signedCompare(right, left));
898
- return values;
899
- }
900
-
901
- /**
902
- * Iterate best first over a snapshot taken when the iterator is created.
903
- */
904
- [Symbol.iterator](): Generator<T, void, unknown> {
905
- return generatorFrom(this.toArray());
906
- }
907
-
908
- /**
909
- * Compare two values so that a positive result means the left one is
910
- * better, whichever order is in effect.
911
- */
912
- private signedCompare(left: T, right: T): number {
913
- return this.quality * this.compareFn(left, right);
914
- }
915
- }