experimental-a2 0.20.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (309) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +1 -1
  3. package/dist/{actor-C7b-1arn.d.ts → actor-CqibLgjQ.d.ts} +15 -7
  4. package/dist/actor-CqibLgjQ.d.ts.map +1 -0
  5. package/dist/actor-client.d.ts +1 -1
  6. package/dist/actor-client.js +2 -2
  7. package/dist/actor-react.d.ts +3 -3
  8. package/dist/actor-react.js +5 -5
  9. package/dist/{actor-shared-t7w8xIKP.js → actor-shared-DFET5q16.js} +3 -3
  10. package/dist/actor-shared-DFET5q16.js.map +1 -0
  11. package/dist/actor.d.ts +1 -1
  12. package/dist/actor.js +54 -43
  13. package/dist/actor.js.map +1 -1
  14. package/dist/{ai-Cz3hqVhk.d.ts → ai-DAu77CDr.d.ts} +8 -8
  15. package/dist/{ai-Cz3hqVhk.d.ts.map → ai-DAu77CDr.d.ts.map} +1 -1
  16. package/dist/{ai-mMiWul1T.js → ai-EEfKyc-z.js} +9 -9
  17. package/dist/ai-EEfKyc-z.js.map +1 -0
  18. package/dist/ai-client.d.ts +2 -2
  19. package/dist/ai-client.js +2 -2
  20. package/dist/ai-fx.d.ts +4 -2
  21. package/dist/ai-fx.d.ts.map +1 -1
  22. package/dist/ai-fx.js +214 -67
  23. package/dist/ai-fx.js.map +1 -1
  24. package/dist/{ai-harness-CV6rXbB3.d.ts → ai-harness-DTjkAr2T.d.ts} +2 -2
  25. package/dist/{ai-harness-CV6rXbB3.d.ts.map → ai-harness-DTjkAr2T.d.ts.map} +1 -1
  26. package/dist/{ai-harness-Clbg5ei7.js → ai-harness-dQeJaR1t.js} +7 -3
  27. package/dist/ai-harness-dQeJaR1t.js.map +1 -0
  28. package/dist/ai-pi.d.ts +1 -1
  29. package/dist/ai-pi.js +3 -3
  30. package/dist/ai-pi.js.map +1 -1
  31. package/dist/ai-react.d.ts +5 -5
  32. package/dist/ai-react.js +2 -2
  33. package/dist/ai-server.d.ts +14 -17
  34. package/dist/ai-server.d.ts.map +1 -1
  35. package/dist/ai-server.js +86 -73
  36. package/dist/ai-server.js.map +1 -1
  37. package/dist/ai.d.ts +2 -2
  38. package/dist/ai.js +2 -2
  39. package/dist/{client-BhHLoNKF.js → client-BQS4i_V9.js} +29 -6
  40. package/dist/client-BQS4i_V9.js.map +1 -0
  41. package/dist/{client-h_DKFAjj.d.ts → client-CUMbS_38.d.ts} +3 -3
  42. package/dist/{client-h_DKFAjj.d.ts.map → client-CUMbS_38.d.ts.map} +1 -1
  43. package/dist/client.d.ts +3 -3
  44. package/dist/client.js +1 -1
  45. package/dist/{contract-BYKASlCV.js → contract-CWukt01d.js} +2 -2
  46. package/dist/contract-CWukt01d.js.map +1 -0
  47. package/dist/index.d.ts +5 -5
  48. package/dist/index.js +3 -3
  49. package/dist/{initial-snapshot-Bx-c0pDP.d.ts → initial-snapshot-D3Lve43o.d.ts} +4 -4
  50. package/dist/initial-snapshot-D3Lve43o.d.ts.map +1 -0
  51. package/dist/{internal-CscSY7K_.js → internal-CvsrprnU.js} +40 -16
  52. package/dist/internal-CvsrprnU.js.map +1 -0
  53. package/dist/otel.d.ts +1 -1
  54. package/dist/otel.js +1 -1
  55. package/dist/otel.js.map +1 -1
  56. package/dist/{react-BBXgHWFc.d.ts → react-BoHvC3v9.d.ts} +4 -4
  57. package/dist/{react-BBXgHWFc.d.ts.map → react-BoHvC3v9.d.ts.map} +1 -1
  58. package/dist/react.d.ts +1 -1
  59. package/dist/react.js +1 -1
  60. package/dist/{reducer-CqA59Q6U.d.ts → reducer-CYPHsSmd.d.ts} +2 -2
  61. package/dist/{reducer-CqA59Q6U.d.ts.map → reducer-CYPHsSmd.d.ts.map} +1 -1
  62. package/dist/{reducer-BAXc8JyF.js → reducer-CjmvZSAb.js} +2 -2
  63. package/dist/{reducer-BAXc8JyF.js.map → reducer-CjmvZSAb.js.map} +1 -1
  64. package/dist/runtime-consumer-CIeL33wj.js +12 -0
  65. package/dist/runtime-consumer-CIeL33wj.js.map +1 -0
  66. package/dist/scheduler-qstash.d.ts +2 -2
  67. package/dist/scheduler-qstash.js +3 -3
  68. package/dist/scheduler-task-X1SToDjP.js.map +1 -1
  69. package/dist/scheduler-vercel.d.ts +2 -2
  70. package/dist/scheduler-vercel.js +3 -3
  71. package/dist/scheduler-vercel.js.map +1 -1
  72. package/dist/{server-qyb5aJJG.js → server-DtFrWxi3.js} +412 -116
  73. package/dist/server-DtFrWxi3.js.map +1 -0
  74. package/dist/{server-DYAATFuT.d.ts → server-qgez0Xny.d.ts} +108 -41
  75. package/dist/server-qgez0Xny.d.ts.map +1 -0
  76. package/dist/server.browser.js +1 -1
  77. package/dist/server.browser.js.map +1 -1
  78. package/dist/server.d.ts +4 -4
  79. package/dist/server.js +2 -2
  80. package/dist/{session-clear-C-QwTXV1.d.ts → session-clear-D1PFe7xl.d.ts} +2 -2
  81. package/dist/session-clear-D1PFe7xl.d.ts.map +1 -0
  82. package/dist/{session-clear-DGI4jTQ5.js → session-clear-wHd5GCpZ.js} +5 -4
  83. package/dist/session-clear-wHd5GCpZ.js.map +1 -0
  84. package/dist/store-D0MhBvg6.d.ts +532 -0
  85. package/dist/store-D0MhBvg6.d.ts.map +1 -0
  86. package/dist/store-N8PXxDAS.js.map +1 -1
  87. package/dist/store-codec-DwrWlgQx.js +65 -0
  88. package/dist/store-codec-DwrWlgQx.js.map +1 -0
  89. package/dist/store-memory.d.ts +1 -1
  90. package/dist/store-memory.d.ts.map +1 -1
  91. package/dist/store-memory.js +406 -225
  92. package/dist/store-memory.js.map +1 -1
  93. package/dist/{store-polling-7WJV0YWP.js → store-polling-BZt2Rf3D.js} +2 -2
  94. package/dist/{store-polling-7WJV0YWP.js.map → store-polling-BZt2Rf3D.js.map} +1 -1
  95. package/dist/store-postgres.d.ts +1 -1
  96. package/dist/store-postgres.d.ts.map +1 -1
  97. package/dist/store-postgres.js +1598 -587
  98. package/dist/store-postgres.js.map +1 -1
  99. package/dist/store-presence-polling-JuAy2Ck2.js +111 -0
  100. package/dist/store-presence-polling-JuAy2Ck2.js.map +1 -0
  101. package/dist/store-redis-http.d.ts +1 -1
  102. package/dist/store-redis-http.js +4 -4
  103. package/dist/store-redis-notify-CsJw_hfD.js +3060 -0
  104. package/dist/store-redis-notify-CsJw_hfD.js.map +1 -0
  105. package/dist/store-redis.d.ts +1 -1
  106. package/dist/store-redis.d.ts.map +1 -1
  107. package/dist/store-redis.js +4 -5
  108. package/dist/store-redis.js.map +1 -1
  109. package/dist/store-sqlite.d.ts +1 -1
  110. package/dist/store-sqlite.d.ts.map +1 -1
  111. package/dist/store-sqlite.js +527 -299
  112. package/dist/store-sqlite.js.map +1 -1
  113. package/dist/stream-buffer-DrTyiIuo.js +57 -0
  114. package/dist/stream-buffer-DrTyiIuo.js.map +1 -0
  115. package/dist/{telemetry-Cyfqo6Qt.d.ts → telemetry-CWwsh-Gx.d.ts} +3 -3
  116. package/dist/telemetry-CWwsh-Gx.d.ts.map +1 -0
  117. package/dist/{wire-BKxH1vbP.js → wire-CV-Z7wz-.js} +6 -5
  118. package/dist/wire-CV-Z7wz-.js.map +1 -0
  119. package/docs/01-quickstart.mdx +21 -15
  120. package/docs/02-examples.mdx +1 -1
  121. package/docs/actors/01-introduction.mdx +13 -2
  122. package/docs/actors/02-concurrency.mdx +1 -1
  123. package/docs/agents/01-introduction.mdx +1 -1
  124. package/docs/agents/02-tools.mdx +12 -11
  125. package/docs/agents/03-conversations.mdx +36 -25
  126. package/docs/agents/04-harnesses.mdx +14 -7
  127. package/docs/client/03-presence.mdx +18 -14
  128. package/docs/contract/01-events.mdx +2 -2
  129. package/docs/contract/02-state.mdx +18 -14
  130. package/docs/contract/03-sessions.mdx +32 -25
  131. package/docs/index.mdx +29 -24
  132. package/docs/reference/01-core.mdx +7 -6
  133. package/docs/reference/02-server.mdx +250 -191
  134. package/docs/reference/04-ai.mdx +33 -23
  135. package/docs/reference/05-telemetry.mdx +27 -13
  136. package/docs/reference/06-errors.mdx +25 -19
  137. package/docs/reference/meta.ts +1 -1
  138. package/docs/schedulers/01-overview.mdx +8 -8
  139. package/docs/schedulers/02-vercel-queues.mdx +2 -2
  140. package/docs/schedulers/03-qstash.mdx +4 -4
  141. package/docs/server/01-consumers.mdx +418 -0
  142. package/docs/server/02-timers.mdx +31 -21
  143. package/docs/server/03-cancellation.mdx +52 -44
  144. package/docs/server/04-routes.mdx +4 -1
  145. package/docs/server/05-sql-projections.mdx +391 -0
  146. package/docs/server/06-guarantees.mdx +61 -51
  147. package/docs/stores/01-overview.mdx +3 -3
  148. package/docs/stores/02-redis.mdx +24 -10
  149. package/docs/stores/03-redis-http.mdx +8 -6
  150. package/docs/stores/04-postgres.mdx +65 -14
  151. package/docs/stores/05-sqlite.mdx +5 -3
  152. package/docs/upgrades/01-overview.mdx +31 -0
  153. package/docs/upgrades/78-0-22.mdx +115 -0
  154. package/docs/upgrades/79-0-21.mdx +165 -0
  155. package/docs/upgrades/80-0-20.mdx +43 -0
  156. package/docs/upgrades/81-0-19.mdx +33 -0
  157. package/docs/upgrades/82-0-18.mdx +33 -0
  158. package/docs/upgrades/83-0-17.mdx +69 -0
  159. package/docs/upgrades/meta.ts +3 -0
  160. package/examples/playground/DEPLOY.md +39 -7
  161. package/examples/playground/app/a0/chat.test.tsx +2 -2
  162. package/examples/playground/app/a0/sandbox-log.ts +17 -15
  163. package/examples/playground/app/a0/sandbox.ts +58 -13
  164. package/examples/playground/app/a0/server.ts +4 -4
  165. package/examples/playground/app/a2slack/a2slack.css +1067 -0
  166. package/examples/playground/app/a2slack/c/[channel]/page.tsx +20 -0
  167. package/examples/playground/app/a2slack/consumers/agent.ts +63 -0
  168. package/examples/playground/app/a2slack/consumers/feed.ts +164 -0
  169. package/examples/playground/app/a2slack/consumers/notify.ts +116 -0
  170. package/examples/playground/app/a2slack/consumers/search.ts +37 -0
  171. package/examples/playground/app/a2slack/consumers/triage.ts +31 -0
  172. package/examples/playground/app/a2slack/consumers/welcome.ts +25 -0
  173. package/examples/playground/app/a2slack/db/a2.ts +209 -0
  174. package/examples/playground/app/a2slack/db/index.ts +73 -0
  175. package/examples/playground/app/a2slack/db/migrations/0000_extensions.sql +4 -0
  176. package/examples/playground/app/a2slack/db/migrations/0001_workspace.sql +74 -0
  177. package/examples/playground/app/a2slack/db/migrations/0002_a2.sql +215 -0
  178. package/examples/playground/app/a2slack/db/migrations/0003_a2_batch.sql +67 -0
  179. package/examples/playground/app/a2slack/db/migrations/0004_a2_session_event_ids.sql +2 -0
  180. package/examples/playground/app/a2slack/db/migrations/meta/0000_snapshot.json +18 -0
  181. package/examples/playground/app/a2slack/db/migrations/meta/0001_snapshot.json +500 -0
  182. package/examples/playground/app/a2slack/db/migrations/meta/0002_snapshot.json +1159 -0
  183. package/examples/playground/app/a2slack/db/migrations/meta/0003_snapshot.json +1159 -0
  184. package/examples/playground/app/a2slack/db/migrations/meta/0004_snapshot.json +1165 -0
  185. package/examples/playground/app/a2slack/db/migrations/meta/_journal.json +41 -0
  186. package/examples/playground/app/a2slack/db/queries.ts +263 -0
  187. package/examples/playground/app/a2slack/db/schema.ts +145 -0
  188. package/examples/playground/app/a2slack/drills/a2slack.drill.ts +708 -0
  189. package/examples/playground/app/a2slack/drills/harness.ts +244 -0
  190. package/examples/playground/app/a2slack/events/route.ts +36 -0
  191. package/examples/playground/app/a2slack/identity.ts +44 -0
  192. package/examples/playground/app/a2slack/inbox/route.ts +8 -0
  193. package/examples/playground/app/a2slack/lag/data/route.ts +8 -0
  194. package/examples/playground/app/a2slack/lag/page.tsx +101 -0
  195. package/examples/playground/app/a2slack/lag.ts +73 -0
  196. package/examples/playground/app/a2slack/layout.tsx +43 -0
  197. package/examples/playground/app/a2slack/messages/route.ts +17 -0
  198. package/examples/playground/app/a2slack/model.test.ts +208 -0
  199. package/examples/playground/app/a2slack/model.ts +369 -0
  200. package/examples/playground/app/a2slack/models.test.ts +72 -0
  201. package/examples/playground/app/a2slack/page.tsx +10 -0
  202. package/examples/playground/app/a2slack/scheduler/route.ts +5 -0
  203. package/examples/playground/app/a2slack/search/route.ts +40 -0
  204. package/examples/playground/app/a2slack/search-index.ts +108 -0
  205. package/examples/playground/app/a2slack/server.test.ts +315 -0
  206. package/examples/playground/app/a2slack/server.ts +55 -0
  207. package/examples/playground/app/a2slack/sessions.ts +50 -0
  208. package/examples/playground/app/a2slack/thread/route.ts +8 -0
  209. package/examples/playground/app/a2slack/ui/ChannelView.tsx +87 -0
  210. package/examples/playground/app/a2slack/ui/Composer.tsx +117 -0
  211. package/examples/playground/app/a2slack/ui/DotsShadow.tsx +42 -0
  212. package/examples/playground/app/a2slack/ui/Feed.tsx +157 -0
  213. package/examples/playground/app/a2slack/ui/InboxContext.tsx +63 -0
  214. package/examples/playground/app/a2slack/ui/InboxView.tsx +82 -0
  215. package/examples/playground/app/a2slack/ui/Menu.tsx +128 -0
  216. package/examples/playground/app/a2slack/ui/MessageRow.tsx +314 -0
  217. package/examples/playground/app/a2slack/ui/NameGate.tsx +35 -0
  218. package/examples/playground/app/a2slack/ui/SearchContext.tsx +146 -0
  219. package/examples/playground/app/a2slack/ui/SearchResults.tsx +97 -0
  220. package/examples/playground/app/a2slack/ui/Shell.tsx +34 -0
  221. package/examples/playground/app/a2slack/ui/Sidebar.tsx +199 -0
  222. package/examples/playground/app/a2slack/ui/ThreadPanel.tsx +134 -0
  223. package/examples/playground/app/a2slack/ui/useInbox.ts +71 -0
  224. package/examples/playground/app/agent/server.ts +3 -3
  225. package/examples/playground/app/chat/[chatId]/chat-client.tsx +1 -1
  226. package/examples/playground/app/chat/server.ts +45 -35
  227. package/examples/playground/app/components/demo-icons.tsx +7 -0
  228. package/examples/playground/app/components/demos.tsx +7 -0
  229. package/examples/playground/app/orders/[orderId]/order-client.tsx +2 -2
  230. package/examples/playground/app/orders/page.tsx +1 -1
  231. package/examples/playground/app/orders/server.ts +49 -30
  232. package/examples/playground/app/recovery/[recoveryId]/recovery-client.tsx +14 -15
  233. package/examples/playground/app/recovery/page.tsx +4 -4
  234. package/examples/playground/app/recovery/server.ts +23 -32
  235. package/examples/playground/drizzle.config.ts +14 -0
  236. package/examples/playground/lib/store.ts +1 -1
  237. package/examples/playground/next.config.ts +6 -1
  238. package/examples/playground/package.json +12 -1
  239. package/examples/playground/scripts/migrate.mjs +31 -0
  240. package/examples/playground/vercel.json +9 -0
  241. package/examples/playground/vitest.drills.config.ts +32 -0
  242. package/package.json +5 -2
  243. package/sql/postgres/drizzle-schema.ts +209 -0
  244. package/sql/postgres/schema.sql +227 -67
  245. package/src/actor-shared.ts +10 -2
  246. package/src/actor.ts +101 -71
  247. package/src/ai-agent.ts +162 -111
  248. package/src/ai-control-server.ts +8 -8
  249. package/src/ai-fx.ts +324 -82
  250. package/src/ai-harness.ts +17 -2
  251. package/src/ai-pi.ts +2 -2
  252. package/src/ai-server.ts +2 -2
  253. package/src/ai.ts +7 -7
  254. package/src/client.ts +19 -2
  255. package/src/contract.ts +1 -1
  256. package/src/deterministic-id.ts +27 -4
  257. package/src/errors.ts +8 -5
  258. package/src/idempotent-replay.ts +0 -1
  259. package/src/index.ts +1 -1
  260. package/src/internal.ts +57 -16
  261. package/src/otel.ts +1 -1
  262. package/src/postgres-schema.ts +98 -57
  263. package/src/presence-recovery.ts +18 -11
  264. package/src/presence-tombstones.ts +52 -0
  265. package/src/push-envelope.ts +20 -0
  266. package/src/runtime-consumer.ts +10 -0
  267. package/src/scheduler-task.ts +2 -2
  268. package/src/scheduler-vercel.ts +1 -1
  269. package/src/server.browser.ts +1 -1
  270. package/src/server.ts +819 -218
  271. package/src/session-socket.ts +1 -1
  272. package/src/store-codec.ts +66 -0
  273. package/src/store-memory.ts +604 -286
  274. package/src/store-postgres.ts +2006 -857
  275. package/src/store-presence-polling.ts +59 -34
  276. package/src/store-redis-core.ts +1961 -1333
  277. package/src/store-redis-notify.ts +76 -26
  278. package/src/store-redis.ts +2 -3
  279. package/src/store-sqlite.ts +915 -516
  280. package/src/store.ts +241 -102
  281. package/src/telemetry.ts +2 -1
  282. package/src/wire.ts +1 -0
  283. package/dist/actor-C7b-1arn.d.ts.map +0 -1
  284. package/dist/actor-shared-t7w8xIKP.js.map +0 -1
  285. package/dist/ai-harness-Clbg5ei7.js.map +0 -1
  286. package/dist/ai-mMiWul1T.js.map +0 -1
  287. package/dist/client-BhHLoNKF.js.map +0 -1
  288. package/dist/contract-BYKASlCV.js.map +0 -1
  289. package/dist/idempotent-replay-JdgMQRRm.js +0 -21
  290. package/dist/idempotent-replay-JdgMQRRm.js.map +0 -1
  291. package/dist/initial-snapshot-Bx-c0pDP.d.ts.map +0 -1
  292. package/dist/internal-CscSY7K_.js.map +0 -1
  293. package/dist/server-DYAATFuT.d.ts.map +0 -1
  294. package/dist/server-qyb5aJJG.js.map +0 -1
  295. package/dist/session-clear-C-QwTXV1.d.ts.map +0 -1
  296. package/dist/session-clear-DGI4jTQ5.js.map +0 -1
  297. package/dist/store-CyLUy86v.d.ts +0 -404
  298. package/dist/store-CyLUy86v.d.ts.map +0 -1
  299. package/dist/store-codec-DTG0Ftek.js +0 -10
  300. package/dist/store-codec-DTG0Ftek.js.map +0 -1
  301. package/dist/store-presence-polling-B1ixeqIS.js +0 -94
  302. package/dist/store-presence-polling-B1ixeqIS.js.map +0 -1
  303. package/dist/store-redis-notify-CM0AfLY0.js +0 -2544
  304. package/dist/store-redis-notify-CM0AfLY0.js.map +0 -1
  305. package/dist/stream-buffer-Cx7AAPGq.js +0 -23
  306. package/dist/stream-buffer-Cx7AAPGq.js.map +0 -1
  307. package/dist/telemetry-Cyfqo6Qt.d.ts.map +0 -1
  308. package/dist/wire-BKxH1vbP.js.map +0 -1
  309. package/docs/server/01-handlers.mdx +0 -227
@@ -0,0 +1,532 @@
1
+ import { p as PresencePatch } from "./reducer-CYPHsSmd.js";
2
+ //#region src/store.d.ts
3
+ /** A stored event, as the public API exposes it. */
4
+ type Event = {
5
+ id: string;
6
+ type: string;
7
+ payload: unknown;
8
+ /** Position in the session's event log, from 1. */
9
+ index: number;
10
+ sessionId: string;
11
+ createdAt: Date;
12
+ };
13
+ /** The consumer attempt whose append first persisted a child event. */
14
+ type EventCause = {
15
+ consumer: string;
16
+ /** The cursor's lane; null for a concurrent consumer's cursor of one event. */
17
+ lane: string | null;
18
+ index: number;
19
+ attempt: number;
20
+ /** Size of one named consumer append, used to reject truncated retries. */
21
+ batchSize?: number;
22
+ };
23
+ /** What the store persists: immutable event history and its causal edge. */
24
+ type StoredEvent = Event & {
25
+ /** Same-session consumer attempt that appended this event; null means root. */
26
+ cause: EventCause | null;
27
+ };
28
+ /**
29
+ * Where a consumer's cursor stands on its head event. A cursor is one record
30
+ * per (session, consumer, lane): a log cursor for a consumer with one string
31
+ * lane, a lane cursor per lane for a lane function, and a cursor per event
32
+ * (lane null) for a concurrent consumer. Its attempt and failure fields
33
+ * describe the current head and reset when the cursor moves past it.
34
+ */
35
+ type HeadDispatch = {
36
+ consumer: string;
37
+ lane: string | null;
38
+ /** Adapter clock time recorded by the first durable claim of this head. */
39
+ firstClaimedAt: Date | null;
40
+ /** Adapter clock time recorded by the most recent durable claim of this head. */
41
+ lastClaimedAt: Date | null;
42
+ /** Durable claims of this head, including claims abandoned by hard kills. */
43
+ attemptCount: number;
44
+ /** Current holder; null when the head is not claimed. */
45
+ claimHolder: string | null;
46
+ /**
47
+ * Adapter clock expiry for the current claim, or, with no holder, the end
48
+ * of a failed attempt's retry hold.
49
+ */
50
+ claimExpiresAt: Date | null;
51
+ /**
52
+ * Failed attempts on this head: caught failures, and lapsed claims a later
53
+ * claim took over. This alone drives dead-lettering.
54
+ */
55
+ failureCount: number;
56
+ /** Adapter clock time recorded by the most recent caught failure. */
57
+ lastFailedAt: Date | null;
58
+ /** Attempt that produced the most recent caught failure. */
59
+ lastFailedAttempt: number | null;
60
+ /** The last failure, stringified. */
61
+ lastError: string | null;
62
+ /** Adapter clock time recorded when dead-lettered; null otherwise. */
63
+ failedAt: Date | null;
64
+ };
65
+ /** Where one cursor stands: its position, its head, and the head's dispatch state. */
66
+ type StoredCursor = HeadDispatch & {
67
+ /** The last index this cursor finished; a log cursor counts from the latest clear marker. */
68
+ position: number;
69
+ /** The event it runs next; null when it has nothing to run. */
70
+ head: number | null;
71
+ };
72
+ /** A cursor's head event together with its dispatch state. */
73
+ type HeadEvent = StoredEvent & HeadDispatch & {
74
+ /** Latest clear marker, on claimed heads of a cleared session. */
75
+ clearIndex?: number;
76
+ };
77
+ /** Names one cursor head: the consumer, its lane, and the head's index. */
78
+ type HeadRef = {
79
+ consumer: string;
80
+ lane: string | null;
81
+ index: number;
82
+ };
83
+ /**
84
+ * A consumer the caller serves. Work for consumers it does not name is
85
+ * neither pending nor claimed, so a removed consumer's cursors wait for its
86
+ * name to return.
87
+ */
88
+ type StoreConsumer = {
89
+ name: string;
90
+ /**
91
+ * Set for a consumer with one string lane. Its cursor keeps one position
92
+ * over the log and runs the next event whose type is in `types` (null:
93
+ * every type). A missing cursor is created by the first append that
94
+ * carries one of those types: at the start of the log with `backfill`,
95
+ * otherwise just before that append.
96
+ */
97
+ log?: {
98
+ lane: string;
99
+ types: readonly string[] | null;
100
+ backfill: boolean;
101
+ };
102
+ };
103
+ /**
104
+ * One live presence value, as `A2Store.presence.read` returns it. The
105
+ * row is the LWW unit — one participant's one field. `at` is the
106
+ * sender's stamp, the LWW comparator. `expiresAt` is the storage's
107
+ * own clock at the applied set plus its `ttlMs` — never derived from
108
+ * the sender stamp; a row is live strictly before it.
109
+ */
110
+ type PresenceRow = {
111
+ participant: string;
112
+ field: string;
113
+ value: unknown;
114
+ seen: number;
115
+ at: Date;
116
+ expiresAt: Date;
117
+ };
118
+ /** One consistent cache-plus-tail read for a reducer fold. */
119
+ type StoreStateRead = {
120
+ /** The current head checkpoint, even when an older historical snapshot is selected. */
121
+ headIndex: number | null;
122
+ /** The greatest cached fold at or before the requested snapshot frontier. */
123
+ snapshot: {
124
+ index: number;
125
+ state: unknown;
126
+ } | null;
127
+ /** Immutable events strictly after `snapshot.index`, or the full log on a miss. */
128
+ events: Event[];
129
+ /** Latest clear marker; omitted when the session was never cleared. */
130
+ clearIndex?: number;
131
+ };
132
+ type StoreSnapshotWrite = {
133
+ index: number;
134
+ state: unknown;
135
+ /** Unfinished cursor heads that durably retain this exact checkpoint. */
136
+ pins?: readonly HeadRef[];
137
+ };
138
+ type StoreStateReadRequest = {
139
+ sessionId: string;
140
+ throughIndex?: number;
141
+ snapshotThroughIndex?: number;
142
+ };
143
+ /** The result of atomically claiming every currently eligible head. */
144
+ type StoreClaimAvailableResult = {
145
+ outcome: "claimed";
146
+ events: HeadEvent[];
147
+ /** The session's head when the claim was made: how far behind each event is. */
148
+ head?: number;
149
+ } | {
150
+ outcome: "busy";
151
+ retryAt: Date;
152
+ } | {
153
+ outcome: "settled";
154
+ };
155
+ /** A completion may lose to a newer claim or an earlier completion. */
156
+ type CompleteAttemptResult = {
157
+ outcome: "completed";
158
+ events: StoredEvent[];
159
+ } | {
160
+ outcome: "superseded";
161
+ };
162
+ /** The result of one claim-renewal heartbeat, both lists in head order. */
163
+ type RenewClaimsResult = {
164
+ /** Listed claims that remain owned by the holder. */
165
+ renewed: HeadRef[];
166
+ /** Listed claims a newer attempt has durably taken, or whose cursor moved on. */
167
+ superseded: HeadRef[];
168
+ };
169
+ /** The result of atomically recording a caught failure. */
170
+ type FailAttemptResult = {
171
+ outcome: "failed" | "dead_lettered" | "superseded";
172
+ failureCount: number;
173
+ };
174
+ /** A consumer an appended event starts work for, with its resolved lane. */
175
+ type EventTarget = {
176
+ consumer: string;
177
+ /** The lane a lane function resolved; null runs the event concurrently. */
178
+ lane: string | null;
179
+ };
180
+ /** Input to `A2Store.append` — already validated by the machine. */
181
+ type AppendEvent = {
182
+ type: string;
183
+ payload: unknown;
184
+ /** Caller-supplied idempotency key; generated when absent. */
185
+ id?: string;
186
+ /** Internal causal edge supplied atomically by consumer `session.append`. */
187
+ cause?: EventCause;
188
+ /**
189
+ * Lane-function and concurrent consumers this event starts work for,
190
+ * resolved before persistence. Log-cursor consumers are matched by type
191
+ * from `StoreConsumer.log` instead.
192
+ */
193
+ targets?: readonly EventTarget[];
194
+ };
195
+ /** A consumer-returned event with the deterministic id retries require. */
196
+ type ReturnedEvent = AppendEvent & {
197
+ id: string;
198
+ };
199
+ /** The rows written by an append and the session's pending state. */
200
+ type StoreAppendResult = {
201
+ events: StoredEvent[];
202
+ /**
203
+ * Whether a served consumer has a live head in this session: one that is
204
+ * not dead-lettered. An append whose own batch starts work for a served
205
+ * consumer may report true without checking that work is runnable.
206
+ */
207
+ hasPending: boolean;
208
+ };
209
+ type StoreClearOptions = {
210
+ sessionId: string;
211
+ ifLastIndex?: number;
212
+ /** The clearing consumer's attempt, fenced like a consumer append. */
213
+ cause?: EventCause;
214
+ };
215
+ type StoreClearResult = {
216
+ cleared: boolean;
217
+ /** The head after the operation. */
218
+ index: number;
219
+ /** The latest clear marker after the operation, or 0. */
220
+ clearIndex: number;
221
+ };
222
+ type StoreReclaimResult = {
223
+ deleted: number;
224
+ done: boolean;
225
+ };
226
+ type StoreRedriveOptions = {
227
+ sessionId: string;
228
+ consumer: string;
229
+ index: number;
230
+ /** `retry` clears the dead letter; `skip` moves the cursor past it. */
231
+ action: "retry" | "skip";
232
+ consumers?: readonly StoreConsumer[];
233
+ };
234
+ type StoreRedriveResult = {
235
+ /** Whether the head was dead-lettered and this operation resolved it. */
236
+ redriven: boolean;
237
+ /** Whether a served consumer has a live head in this session: one that is not dead-lettered. */
238
+ hasPending: boolean;
239
+ };
240
+ /**
241
+ * An injectable clock. Adapters take one so tests can drive claim
242
+ * expiry, failure timestamps, and (later) stuck-session detection
243
+ * deterministically — against real storage, no mocking.
244
+ */
245
+ type Clock = {
246
+ now(): Date;
247
+ };
248
+ /** An injectable id source for generated event ids. */
249
+ type IdSource = () => string;
250
+ /**
251
+ * Cursor rules every operation shares:
252
+ *
253
+ * - `consumers` names the consumers the caller serves. Omitted, every cursor
254
+ * counts and no log cursor is created or advanced by type.
255
+ * - A cursor's head is the next event it runs: the lowest unfinished event of
256
+ * its lane, the event itself for a concurrent cursor, or for a log cursor
257
+ * the next event after its position whose type it takes. The clear marker
258
+ * is never a head.
259
+ * - A head is eligible when no live claim or retry hold owns it, it is not
260
+ * dead-lettered, and it lies above the latest clear marker.
261
+ * - Moving a cursor past its head resets the head's attempt and failure
262
+ * fields and releases snapshot pins on it.
263
+ */
264
+ interface A2Store {
265
+ /**
266
+ * Accepts a batch; the batch is atomic — one transaction, consecutive
267
+ * `index`es, all-or-nothing. The idempotency key covers the whole
268
+ * operation, not each item: if *every* event's `id` already exists in
269
+ * this session, this is a retry of a committed batch whose ack was
270
+ * lost — return the existing rows as success. If only *some* ids
271
+ * exist, the caller mixed an already-sent batch with fresh events —
272
+ * always a caller bug — so throw `A2Error('PARTIAL_DUPLICATE_BATCH')`.
273
+ * Ids are unique per session: the same id in another session names a
274
+ * different event and plays no part in these checks.
275
+ *
276
+ * In the same atomic operation, each event's `targets` start cursor work:
277
+ * a lane target queues the event in that consumer's lane, a null lane
278
+ * creates a cursor for that event alone. Each log consumer in `consumers`
279
+ * whose types the batch carries gets its cursor created or, when idle, a
280
+ * head: the next event after its position that it takes, which may
281
+ * precede the batch when an appender that doesn't serve it wrote in
282
+ * between. `hasPending` reflects the whole session for the served consumers,
283
+ * including older work and idempotent retries.
284
+ *
285
+ * An event carrying `cause` is a consumer append, fenced by attempt
286
+ * currency: accept it only while the cause's cursor still has
287
+ * `cause.index` as its head, `cause.attempt` is that head's latest
288
+ * attempt, and the head is not dead-lettered; otherwise throw
289
+ * `A2Error('SUPERSEDED_ATTEMPT')` and write nothing. The check is part of
290
+ * this atomic operation and must serialize against a concurrent
291
+ * `claimAvailable` — an unlocked read of the cursor admits write skew. The
292
+ * idempotent-replay path runs first, so a batch whose ids all exist
293
+ * replays regardless of the current attempt.
294
+ *
295
+ * Clearing stores (a2-implementation.md §17.2) fence one level earlier:
296
+ * a `cause` at or below the latest clear marker throws
297
+ * `SUPERSEDED_ATTEMPT`, an `originIndex` there throws `SESSION_CLEARED`,
298
+ * and ids whose rows lie below the marker are free to reuse.
299
+ */
300
+ append(sessionId: string, events: AppendEvent[], options?: {
301
+ originIndex?: number;
302
+ consumers?: readonly StoreConsumer[];
303
+ }): Promise<StoreAppendResult>;
304
+ /**
305
+ * Optional with `reclaim`. Serialized with `append`: checks
306
+ * `ifLastIndex` against the head and the latest marker, then appends a
307
+ * clear marker at the next index without touching existing rows.
308
+ * Afterwards every event at or below the marker is superseded: no head
309
+ * lies there, and every log cursor's position counts from the marker.
310
+ */
311
+ clear?(options: StoreClearOptions): Promise<StoreClearResult>;
312
+ /**
313
+ * Deletes one bounded batch of rows below the latest clear marker, with
314
+ * their cursor records, id records, and cached folds. `done` once nothing
315
+ * remains below it. Never waits on a lock that other operations hold.
316
+ */
317
+ reclaim?(sessionId: string): Promise<StoreReclaimResult>;
318
+ /**
319
+ * Optional with `redrive`. The session's dead-lettered heads above the
320
+ * latest clear marker, in event order, then by consumer name.
321
+ */
322
+ deadLetters?(sessionId: string): Promise<HeadEvent[]>;
323
+ /**
324
+ * Optional with `deadLetters`. Atomically resolves the consumer's
325
+ * dead-lettered head at `index` above the latest clear marker; anything
326
+ * else is untouched and reports `redriven: false`. `retry` clears
327
+ * `failedAt` and `failureCount`, so the head is claimable again with a
328
+ * fresh failure budget, keeping its claim history and last failure. `skip`
329
+ * moves the cursor past the head with no completion. Both serialize with
330
+ * `claimAvailable` and the consumer-append fence. `hasPending` is read in
331
+ * the same step.
332
+ */
333
+ redrive?(options: StoreRedriveOptions): Promise<StoreRedriveResult>;
334
+ /**
335
+ * Brings one log consumer's cursor up to date without an append, for
336
+ * `session.consume()`. A missing cursor is created: with `backfill`, at
337
+ * the latest clear marker, taking the first event of its types after it;
338
+ * otherwise at the head, with nothing to run. When the session has nothing
339
+ * after its latest clear (or was never written), a missing cursor stays
340
+ * missing: nothing is written, and the cursor comes back idle at the
341
+ * marker, so a consume of an unknown session leaves no trace. That is
342
+ * exact with `backfill`; without it, the consumer starts at the first
343
+ * consume or serving append that finds events. An
344
+ * idle cursor takes the next event of its types after its position, so it
345
+ * finds events appended by deployments that don't serve it. A cursor with
346
+ * a head, claimed or not, is left as it is. Records the consumer's types,
347
+ * as an append would, and returns the cursor and the session's head.
348
+ */
349
+ wakeLog(options: {
350
+ sessionId: string;
351
+ consumer: StoreConsumer & {
352
+ log: NonNullable<StoreConsumer["log"]>;
353
+ };
354
+ }): Promise<{
355
+ cursor: StoredCursor;
356
+ head: number;
357
+ }>;
358
+ /**
359
+ * The session's cursors: every log and lane cursor, and every concurrent
360
+ * cursor that still has a head, by consumer, then lane (concurrent cursors
361
+ * last, by head). Lane and concurrent cursors whose work lies at or below
362
+ * the latest clear marker are not listed.
363
+ */
364
+ cursors(sessionId: string): Promise<StoredCursor[]>;
365
+ /** Events for one session, oldest first. Bounds form `(afterIndex, throughIndex]`. */
366
+ read(sessionId: string, opts?: {
367
+ afterIndex?: number;
368
+ throughIndex?: number;
369
+ }): Promise<StoredEvent[]>;
370
+ /** Public history without causal edges; core falls back to read when absent. */
371
+ readHistory?(sessionId: string, opts?: {
372
+ afterIndex?: number;
373
+ throughIndex?: number;
374
+ }): Promise<Event[]>;
375
+ /**
376
+ * Atomically claims every eligible head of the served consumers. A live
377
+ * claim or retry hold produces `busy` only when it is the sole remaining
378
+ * obstacle to actionable work. Claimed heads are returned in event order,
379
+ * then by consumer name. Excluded heads stay unclaimed and keep blocking
380
+ * their lane.
381
+ */
382
+ claimAvailable(options: {
383
+ sessionId: string;
384
+ holder: string;
385
+ ttlMs: number;
386
+ expiresAtMs?: number;
387
+ exclude?: readonly HeadRef[];
388
+ consumers?: readonly StoreConsumer[];
389
+ /**
390
+ * Taking over a lapsed claim (one whose holder is still recorded, never
391
+ * completed or failed) adds one to `failureCount`. When that reaches
392
+ * `maxFailures`, the head dead-letters instead of being claimed: it
393
+ * comes back in `events` with `failedAt` set and no claim. Its
394
+ * `attemptCount` still advances, fencing the lapsed attempt, and its
395
+ * `lastFailedAttempt` is unchanged.
396
+ */
397
+ maxFailures?: number;
398
+ /**
399
+ * Claims only heads at or below this index: a head past it is neither
400
+ * claimed nor reported `busy`, and stays claimable without it.
401
+ */
402
+ through?: number;
403
+ }): Promise<StoreClaimAvailableResult>;
404
+ /**
405
+ * Renews the listed live claims still owned by `holder`. Each listed claim
406
+ * carries the attempt the holder owns. `renewed` lists the claims that
407
+ * remain owned after the operation; `superseded` lists the claims whose
408
+ * head a newer attempt has durably taken, or whose cursor has moved past
409
+ * it. An expired claim no successor has taken appears in neither list — its
410
+ * attempt may still complete (`completeAttempt` is the fence), so it is
411
+ * not reported as lost. Renewal never revives an expired claim.
412
+ */
413
+ renewClaims(options: {
414
+ sessionId: string;
415
+ holder: string;
416
+ claims: readonly (HeadRef & {
417
+ attempt: number;
418
+ })[];
419
+ ttlMs: number;
420
+ expiresAtMs?: number;
421
+ }): Promise<RenewClaimsResult>;
422
+ /**
423
+ * Atomically completes one current attempt: appends its returned events
424
+ * (with their own targets, waking the served log consumers) and moves the
425
+ * cursor past its head. Retrying a committed completion with the same
426
+ * attempt and deterministic child ids returns the existing children. A
427
+ * stale attempt never appends.
428
+ */
429
+ completeAttempt(options: {
430
+ sessionId: string;
431
+ consumer: string;
432
+ lane: string | null;
433
+ index: number;
434
+ attempt: number;
435
+ events: ReturnedEvent[];
436
+ consumers?: readonly StoreConsumer[];
437
+ }): Promise<CompleteAttemptResult>;
438
+ /**
439
+ * Atomically records a caught failure for one claimed attempt. A stale
440
+ * attempt cannot poison a finished head or a newer attempt. Accepted
441
+ * failures record the operation's clock time. A failure that does not
442
+ * dead-letter releases the claim and, with `retryAfterMs`, keeps the head
443
+ * unclaimable for that long: its claim expiry is set with no holder, so
444
+ * `claimAvailable` reports it `busy` until then.
445
+ */
446
+ failAttempt(options: {
447
+ sessionId: string;
448
+ consumer: string;
449
+ lane: string | null;
450
+ index: number;
451
+ attempt: number;
452
+ error: string;
453
+ maxFailures: number;
454
+ retryAfterMs?: number;
455
+ }): Promise<FailAttemptResult>;
456
+ /**
457
+ * Reads a reducer snapshot and its event tail as one consistent adapter
458
+ * operation. On a cache miss, `snapshot` is null and `events` is the full
459
+ * log. The snapshot is untrusted; core may reject it and issue a full
460
+ * `read()` when its state schema no longer accepts the cached value.
461
+ * Operational failures propagate without falling back to a full-log read.
462
+ */
463
+ readState(sessionId: string, reducerName: string, options?: {
464
+ throughIndex?: number;
465
+ snapshotThroughIndex?: number;
466
+ }): Promise<StoreStateRead>;
467
+ /**
468
+ * Optional batched `readState` — one consistent snapshot-plus-tail read
469
+ * per session id, aligned positionally with the input (duplicates
470
+ * allowed). Each element has its own frontier; the batch makes no
471
+ * cross-session consistency claim. Core falls back to parallel
472
+ * `readState` calls when absent.
473
+ */
474
+ readStates?(requests: readonly StoreStateReadRequest[], reducerName: string): Promise<StoreStateRead[]>;
475
+ /**
476
+ * Atomically writes disposable reducer checkpoints. The greatest index
477
+ * advances the head cache. Older checkpoints survive only while at least
478
+ * one listed cursor head is still unfinished; moving that cursor past it
479
+ * or dead-lettering it releases the pin and collects unreferenced
480
+ * historical checkpoints.
481
+ */
482
+ putSnapshots(sessionId: string, reducerName: string, snapshots: readonly StoreSnapshotWrite[]): Promise<void>;
483
+ /**
484
+ * Optional ephemeral-plane capability (specs/a2-implementation.md
485
+ * §15.1) — optional like snapshots are. Values arrive already
486
+ * validated by core; adapters store them opaquely. Presence never
487
+ * touches the event log: no index, no history row, no recovery arm.
488
+ */
489
+ presence?: {
490
+ /**
491
+ * Field-wise last-writer-wins merge of one participant's values:
492
+ * a field whose unexpired entry has a strictly newer `at` (the
493
+ * sender's stamp) is left untouched. `null` deletes the value but
494
+ * keeps a tombstone with its `at`, which takes part in the merge
495
+ * like a value until it expires, so a set older than the delete
496
+ * still loses when it arrives later. Every applied write, value or
497
+ * tombstone, refreshes that field's expiry to the storage's own
498
+ * clock plus `ttlMs` — the sender stamp orders writes but never
499
+ * anchors their lifetime. `subscribe` delivers applied writes only,
500
+ * a delete as `null`.
501
+ */
502
+ set(ns: string, participant: string, values: Record<string, unknown | null>, meta: {
503
+ seen: number;
504
+ at: Date;
505
+ ttlMs: number;
506
+ }): Promise<void>;
507
+ /**
508
+ * The current map, pruned of rows at or past their `expiresAt`.
509
+ * Tombstones never appear.
510
+ */
511
+ read(ns: string): Promise<PresenceRow[]>;
512
+ /**
513
+ * Adapter-managed patch delivery. Without it, live feeds re-read
514
+ * presence on their poll cadence. HTTP Redis uses adaptive polling
515
+ * here when its endpoint does not support subscriptions.
516
+ */
517
+ subscribe?(ns: string, onPatch: (patch: PresencePatch) => void): () => void;
518
+ };
519
+ /**
520
+ * A live feed of one session's events, starting after `startAfter`
521
+ * (exclusive). Transport is the backend's choice — in-process pub/sub,
522
+ * polling, LISTEN/NOTIFY — callers never branch on which. The iterable
523
+ * ends when the consumer calls `return()` (e.g. a disconnecting SSE
524
+ * client) and must deliver events appended after subscription.
525
+ */
526
+ stream(sessionId: string, opts?: {
527
+ startAfter?: number;
528
+ }): AsyncIterable<Event>;
529
+ }
530
+ //#endregion
531
+ export { EventCause as a, PresenceRow as c, StoreStateRead as d, StoredEvent as f, Event as i, StoreAppendResult as l, AppendEvent as n, FailAttemptResult as o, Clock as r, IdSource as s, A2Store as t, StoreClaimAvailableResult as u };
532
+ //# sourceMappingURL=store-D0MhBvg6.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store-D0MhBvg6.d.ts","names":[],"sources":["../src/store.ts"],"mappings":";;;KAaY;EACV;EACA;EACA;;EAEA;EACA;EACA,WAAW;;;KAID;EACV;;EAEA;EACA;EACA;;EAEA;;;KAIU,cAAc;;EAExB,OAAO;;;;;;;;;KAUG;EACV;EACA;;EAEA,gBAAgB;;EAEhB,eAAe;;EAEf;;EAEA;;;;;EAKA,gBAAgB;;;;;EAKhB;;EAEA,cAAc;;EAEd;;EAEA;;EAEA,UAAU;;;KAIA,eAAe;;EAEzB;;EAEA;;;KAIU,YAAY,cACtB;;EAEE;;;KAIQ;EACV;EACA;EACA;;;;;;;KAQU;EACV;;;;;;;;EAQA;IACE;IACA;IACA;;;;;;;;;;KAWQ;EACV;EACA;EACA;EACA;EACA,IAAI;EACJ,WAAW;;;KAID;;EAEV;;EAEA;IAAY;IAAe;;;EAE3B,QAAQ;;EAER;;KAGU;EACV;EACA;;EAEA,gBAAgB;;KAGN;EACV;EACA;EACA;;;KAIU;EAEN;EACA,QAAQ;;EAER;;EAEA;EAAiB,SAAS;;EAC1B;;;KAGM;EACR;EAAsB,QAAQ;;EAAoB;;;KAG1C;;EAEV,SAAS;;EAET,YAAY;;;KAIF;EACV;EACA;;;KAIU;EACV;;EAEA;;;KAIU;EACV;EACA;;EAEA;;EAEA,QAAQ;;;;;;EAMR,mBAAmB;;;KAIT,gBAAgB;EAAgB;;;KAGhC;EACV,QAAQ;;;;;;EAMR;;KAGU;EACV;EACA;;EAEA,QAAQ;;KAGE;EACV;;EAEA;;EAEA;;KAGU;EAAuB;EAAiB;;KAExC;EACV;EACA;EACA;;EAEA;EACA,qBAAqB;;KAGX;;EAEV;;EAEA;;;;;;;KAQU;EACV,OAAO;;;KAIG;;;;;;;;;;;;;;;UAsBK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAoCf,OACE,mBACA,QAAQ,eACR;IACE;IACA,qBAAqB;MAEtB,QAAQ;;;;;;;;EASX,OAAO,SAAS,oBAAoB,QAAQ;;;;;;EAO5C,SAAS,oBAAoB,QAAQ;;;;;EAMrC,aAAa,oBAAoB,QAAQ;;;;;;;;;;;EAYzC,SAAS,SAAS,sBAAsB,QAAQ;;;;;;;;;;;;;;;;EAiBhD,QAAQ;IACN;IACA,UAAU;MAAkB,KAAK,YAAY;;MAC3C;IAAU,QAAQ;IAAc;;;;;;;;EAQpC,QAAQ,oBAAoB,QAAQ;;EAGpC,KACE,mBACA;IAAS;IAAqB;MAC7B,QAAQ;;EAGX,aACE,mBACA;IAAS;IAAqB;MAC7B,QAAQ;;;;;;;;EASX,eAAe;IACb;IACA;IACA;IACA;IACA,mBAAmB;IACnB,qBAAqB;;;;;;;;;IASrB;;;;;IAKA;MACE,QAAQ;;;;;;;;;;EAWZ,YAAY;IACV;IACA;IACA,kBAAkB;MAAY;;IAC9B;IACA;MACE,QAAQ;;;;;;;;EASZ,gBAAgB;IACd;IACA;IACA;IACA;IACA;IACA,QAAQ;IACR,qBAAqB;MACnB,QAAQ;;;;;;;;;EAUZ,YAAY;IACV;IACA;IACA;IACA;IACA;IACA;IACA;IACA;MACE,QAAQ;;;;;;;;EASZ,UACE,mBACA,qBACA;IAAY;IAAuB;MAClC,QAAQ;;;;;;;;EASX,YACE,mBAAmB,yBACnB,sBACC,QAAQ;;;;;;;;EASX,aACE,mBACA,qBACA,oBAAoB,uBACnB;;;;;;;EAQH;;;;;;;;;;;;;IAaE,IACE,YACA,qBACA,QAAQ,gCACR;MAAQ;MAAc,IAAI;MAAM;QAC/B;;;;;IAMH,KAAK,aAAa,QAAQ;;;;;;IAO1B,WAAW,YAAY,UAAU,OAAO;;;;;;;;;EAU1C,OACE,mBACA;IAAS;MACR,cAAc"}
@@ -1 +1 @@
1
- {"version":3,"file":"store-N8PXxDAS.js","names":[],"sources":["../src/store.ts"],"sourcesContent":["/**\n * The A2Store interface — the storage contract every store backend\n * implements. See specs/a2-implementation.md §2–3.\n *\n * This is the whole storage contract: append, read, dispatch claims,\n * failure markers, snapshots, and the live stream. The scheduler\n * needs nothing extra — the armed queue message is its own state, and\n * the store is the only thing it consults.\n */\n\nimport type { PresencePatch } from './contract.ts'\n\n/** A stored event, as the public API exposes it. */\nexport type Event = {\n id: string\n type: string\n payload: unknown\n /** Position in the session's event log, from 1. */\n index: number\n sessionId: string\n createdAt: Date\n}\n\n/** The handler dispatch whose append first persisted a child event. */\nexport type EventCause = {\n index: number\n attempt: number\n /** Size of one named handler append, used to reject truncated retries. */\n batchSize?: number\n}\n\n/**\n * What the store persists: immutable event history, including its causal edge,\n * plus derived dispatch and failure bookkeeping. The bookkeeping is disposable;\n * the event and its cause are not.\n */\nexport type StoredEvent = Event & {\n /** Same-session handler dispatch that appended this event; null means root. */\n cause: EventCause | null\n /** Session-scoped serial execution key resolved when the event is appended. */\n lane: string | null\n /** Adapter clock time recorded by append settlement, completion, or manual skip; null while pending. */\n processedAt: Date | null\n /** Dispatch attempt that completed this event; null without dispatch or while pending. */\n processedByAttempt: number | null\n /** Exact ordered child ids atomically returned by the completing attempt. */\n returnedEventIds: string[] | null\n /** Adapter clock time recorded by the first durable dispatch claim. */\n firstClaimedAt: Date | null\n /** Adapter clock time recorded by the most recent durable dispatch claim. */\n lastClaimedAt: Date | null\n /** Durable dispatch claims, including claims abandoned by hard kills. */\n attemptCount: number\n /** Current dispatch holder; null when the event is not claimed. */\n claimHolder: string | null\n /**\n * Adapter clock expiry for the current dispatch claim, or, with no holder,\n * the end of a failed attempt's retry hold.\n */\n claimExpiresAt: Date | null\n /**\n * Failed attempts: caught handler failures, and lapsed claims a later claim\n * took over. This alone drives dead-lettering.\n */\n failureCount: number\n /** Adapter clock time recorded by the most recent caught handler failure. */\n lastFailedAt: Date | null\n /** Dispatch attempt that produced the most recent caught handler failure. */\n lastFailedAttempt: number | null\n /** The last handler failure, stringified. */\n lastError: string | null\n /** Adapter clock time recorded when dead-lettered; null otherwise. */\n failedAt: Date | null\n /** Latest clear marker, on claimed events of a cleared session. */\n clearIndex?: number\n}\n\n/**\n * One live presence value, as `A2Store.presence.read` returns it. The\n * row is the LWW unit — one participant's one field. `at` is the\n * sender's stamp, the LWW comparator. `expiresAt` is the storage's\n * own clock at the applied set plus its `ttlMs` — never derived from\n * the sender stamp; a row is live strictly before it.\n */\nexport type PresenceRow = {\n participant: string\n field: string\n value: unknown\n seen: number\n at: Date\n expiresAt: Date\n}\n\n/** One consistent cache-plus-tail read for a reducer fold. */\nexport type StoreStateRead = {\n /** The current head checkpoint, even when an older historical snapshot is selected. */\n headIndex: number | null\n /** The greatest cached fold at or before the requested snapshot frontier. */\n snapshot: { index: number; state: unknown } | null\n /** Immutable events strictly after `snapshot.index`, or the full log on a miss. */\n events: Event[]\n /** Latest clear marker; omitted when the session was never cleared. */\n clearIndex?: number\n}\n\nexport type StoreSnapshotWrite = {\n index: number\n state: unknown\n /** Unfinished trigger events that durably retain this exact checkpoint. */\n pinEventIndexes?: readonly number[]\n}\n\nexport type StoreStateReadRequest = {\n sessionId: string\n throughIndex?: number\n snapshotThroughIndex?: number\n}\n/** The result of atomically claiming every currently eligible event. */\nexport type StoreClaimAvailableResult =\n | { outcome: 'claimed'; events: StoredEvent[] }\n | { outcome: 'busy'; retryAt: Date }\n | { outcome: 'settled' }\n\n/** A completion may lose to a newer claim or an earlier completion. */\nexport type CompleteAttemptResult =\n { outcome: 'completed'; events: StoredEvent[] } | { outcome: 'superseded' }\n\n/** The result of one claim-renewal heartbeat, both lists in append order. */\nexport type RenewClaimsResult = {\n /** Listed claims that remain owned by the holder. */\n renewed: number[]\n /** Listed claims whose event a newer attempt has durably taken. */\n superseded: number[]\n}\n\n/** The result of atomically recording a caught handler failure. */\nexport type FailAttemptResult = {\n outcome: 'failed' | 'dead_lettered' | 'superseded'\n failureCount: number\n}\n\n/** Input to `A2Store.append` — already validated by the machine. */\nexport type AppendEvent = {\n type: string\n payload: unknown\n /** Caller-supplied idempotency key; generated when absent. */\n id?: string\n /** Internal causal edge supplied atomically by handler `session.append`. */\n cause?: EventCause\n /** Session-scoped serial execution key resolved before persistence. */\n lane?: string\n /** Internal hint: settle this event in the append transaction; no handler is registered. */\n settled?: true\n}\n\n/** A handler-returned event with the deterministic id retries require. */\nexport type ReturnedEvent = AppendEvent & { id: string }\n\n/** The rows written by an append and the session's pending state. */\nexport type StoreAppendResult = {\n events: StoredEvent[]\n /** Whether the session contains an event without a completion marker. */\n hasPending: boolean\n}\n\nexport type StoreClearOptions = {\n sessionId: string\n ifLastIndex?: number\n /** The clearing handler's dispatch, fenced like a handler append. */\n cause?: EventCause\n}\n\nexport type StoreClearResult = {\n cleared: boolean\n /** The head after the operation. */\n index: number\n /** The latest clear marker after the operation, or 0. */\n clearIndex: number\n}\n\nexport type StoreReclaimResult = { deleted: number; done: boolean }\n\nexport type StoreRedriveOptions = {\n sessionId: string\n index: number\n /** `retry` clears the dead letter; `skip` settles it without a handler. */\n action: 'retry' | 'skip'\n}\n\nexport type StoreRedriveResult = {\n /** Whether the event was dead-lettered and this operation resolved it. */\n redriven: boolean\n /** Whether the session contains an event without a completion marker. */\n hasPending: boolean\n}\n\n/**\n * An injectable clock. Adapters take one so tests can drive claim\n * expiry, failure timestamps, and (later) stuck-session detection\n * deterministically — against real storage, no mocking.\n */\nexport type Clock = {\n now(): Date\n}\n\n/** An injectable id source for generated event ids. */\nexport type IdSource = () => string\n\nexport const SYSTEM_CLOCK: Clock = {\n now: () => new Date(),\n}\n\nexport const RANDOM_IDS: IdSource = () => crypto.randomUUID()\n\nexport interface A2Store {\n /**\n * Accepts a batch; the batch is atomic — one transaction, consecutive\n * `index`es, all-or-nothing. The idempotency key covers the whole\n * operation, not each item: if *every* event's `id` already exists in\n * this session, this is a retry of a committed batch whose ack was\n * lost — return the existing rows as success. If only *some* ids\n * exist, the caller mixed an already-sent batch with fresh events —\n * always a caller bug — so throw `A2Error('PARTIAL_DUPLICATE_BATCH')`.\n * Events carrying `settled: true` get `processedAt` in this same atomic\n * operation, with no dispatch claim or `processedByAttempt`. The result's\n * `hasPending` reflects the whole session in the same atomic operation,\n * including older events and idempotent retries.\n *\n * An event carrying `cause` is a handler append, fenced by attempt\n * currency: accept it only while `cause.attempt` is still the parent\n * event's latest attempt and the parent is not dead-lettered; otherwise\n * throw `A2Error('SUPERSEDED_ATTEMPT')` and write nothing. The check is\n * part of this atomic operation and must serialize against a concurrent\n * `claimAvailable` — an unlocked read of the parent admits write skew.\n * The idempotent-replay path runs first, so a batch whose ids all exist\n * replays regardless of the current attempt.\n *\n * Clearing stores (a2-implementation.md §17.2) fence one level earlier:\n * a `cause` at or below the latest clear marker throws\n * `SUPERSEDED_ATTEMPT`, an `originIndex` there throws `SESSION_CLEARED`,\n * and ids whose rows lie below the marker are free to reuse.\n */\n append(\n sessionId: string,\n events: AppendEvent[],\n options?: { originIndex?: number },\n ): Promise<StoreAppendResult>\n\n /**\n * Optional with `reclaim`. Serialized with `append`: checks\n * `ifLastIndex` against the head and the latest marker, then appends a\n * settled clear marker at the next index without touching existing\n * rows. Afterwards every event at or below the marker is superseded.\n */\n clear?(options: StoreClearOptions): Promise<StoreClearResult>\n\n /**\n * Deletes one bounded batch of rows below the latest clear marker, with\n * their bookkeeping, id records, and cached folds. `done` once nothing\n * remains below it. Never waits on a lock that other operations hold.\n */\n reclaim?(sessionId: string): Promise<StoreReclaimResult>\n\n /**\n * Optional with `redrive`. The session's dead-lettered events above the\n * latest clear marker, oldest first.\n */\n deadLetters?(sessionId: string): Promise<StoredEvent[]>\n\n /**\n * Optional with `deadLetters`. Atomically resolves one dead-lettered event\n * above the latest clear marker; any other event is untouched and reports\n * `redriven: false`. `retry` clears `failedAt` and `failureCount`, so the\n * event is claimable again with a fresh failure budget, keeping its claim\n * history and last failure. `skip` records `processedAt` with no\n * `processedByAttempt` or `returnedEventIds` and exposes the next event in\n * its lane. Both serialize with `claimAvailable` and the handler-append\n * parent fence; `skip` also serializes with lane promotion in `append` and\n * `completeAttempt`. `hasPending` is read in the same step.\n */\n redrive?(options: StoreRedriveOptions): Promise<StoreRedriveResult>\n\n /** Events for one session, oldest first. Bounds form `(afterIndex, throughIndex]`. */\n read(\n sessionId: string,\n opts?: { afterIndex?: number; throughIndex?: number },\n ): Promise<StoredEvent[]>\n\n /** Public history without dispatch metadata; core falls back to read when absent. */\n readHistory?(\n sessionId: string,\n opts?: { afterIndex?: number; throughIndex?: number },\n ): Promise<Event[]>\n\n /**\n * Atomically claims every eligible pending event. Unlaned events are all\n * independently eligible. Within a lane, only the lowest-index unfinished\n * event is eligible. A live claim produces `busy` only when it is the sole\n * remaining obstacle to actionable work. Claimed events are returned in event-log\n * order. Excluded rows remain lane barriers.\n */\n claimAvailable(options: {\n sessionId: string\n holder: string\n ttlMs: number\n expiresAtMs?: number\n excludeIndexes?: readonly number[]\n /**\n * Taking over a lapsed claim (one whose holder is still recorded, never\n * completed or failed) adds one to `failureCount`. When that reaches\n * `maxFailures`, the event dead-letters instead of being claimed: it\n * comes back in `events` with `failedAt` set and no claim. Its\n * `attemptCount` still advances, fencing the lapsed attempt, and its\n * `lastFailedAttempt` is unchanged.\n */\n maxFailures?: number\n }): Promise<StoreClaimAvailableResult>\n\n /**\n * Renews the listed live claims still owned by `holder`. Each listed claim\n * carries the attempt ordinal the holder owns. `renewed` lists the claims\n * that remain owned after the operation; `superseded` lists the claims\n * whose event's `attemptCount` has durably passed the listed attempt. An\n * expired claim no successor has taken appears in neither list — its\n * attempt may still complete (`completeAttempt` is the fence), so it is\n * not reported as lost. Renewal never revives an expired claim.\n */\n renewClaims(options: {\n sessionId: string\n holder: string\n claims: readonly { index: number; attempt: number }[]\n ttlMs: number\n expiresAtMs?: number\n }): Promise<RenewClaimsResult>\n\n /**\n * Atomically completes one current attempt and appends its returned events.\n * Retrying a committed completion with the same attempt and deterministic\n * child ids returns the existing children. A stale attempt never appends.\n */\n completeAttempt(options: {\n sessionId: string\n index: number\n attempt: number\n events: ReturnedEvent[]\n }): Promise<CompleteAttemptResult>\n\n /**\n * Atomically records a caught failure for one claimed attempt. A stale\n * attempt cannot poison a processed event or a newer dispatch. Accepted\n * failures record the operation's clock time. A failure that does not\n * dead-letter releases the claim and, with `retryAfterMs`, keeps the event\n * unclaimable for that long: its claim expiry is set with no holder, so\n * `claimAvailable` reports it `busy` until then.\n */\n failAttempt(options: {\n sessionId: string\n index: number\n attempt: number\n error: string\n maxFailures: number\n retryAfterMs?: number\n }): Promise<FailAttemptResult>\n\n /**\n * Reads a reducer snapshot and its event tail as one consistent adapter\n * operation. On a cache miss, `snapshot` is null and `events` is the full\n * log. The snapshot is untrusted; core may reject it and issue a full\n * `read()` when its state schema no longer accepts the cached value.\n * Operational failures propagate without falling back to a full-log read.\n */\n readState(\n sessionId: string,\n reducerName: string,\n options?: { throughIndex?: number; snapshotThroughIndex?: number },\n ): Promise<StoreStateRead>\n\n /**\n * Optional batched `readState` — one consistent snapshot-plus-tail read\n * per session id, aligned positionally with the input (duplicates\n * allowed). Each element has its own frontier; the batch makes no\n * cross-session consistency claim. Core falls back to parallel\n * `readState` calls when absent.\n */\n readStates?(\n requests: readonly StoreStateReadRequest[],\n reducerName: string,\n ): Promise<StoreStateRead[]>\n\n /**\n * Atomically writes disposable reducer checkpoints. The greatest index\n * advances the head cache. Older checkpoints survive only when at least one\n * listed trigger event is still unfinished; completion and dead-lettering\n * release that event's pins and collect unreferenced historical checkpoints.\n */\n putSnapshots(\n sessionId: string,\n reducerName: string,\n snapshots: readonly StoreSnapshotWrite[],\n ): Promise<void>\n\n /**\n * Optional ephemeral-plane capability (specs/a2-implementation.md\n * §15.1) — optional like snapshots are. Values arrive already\n * validated by core; adapters store them opaquely. Presence never\n * touches the event log: no index, no history row, no recovery arm.\n */\n presence?: {\n /**\n * Field-wise last-writer-wins merge of one participant's values:\n * a field whose existing row has a strictly newer `at` (the\n * sender's stamp) is left untouched; `null` deletes the row. Every\n * applied write refreshes that field's expiry to the storage's own\n * clock plus `ttlMs` — the sender stamp orders writes but never\n * anchors their lifetime.\n */\n set(\n ns: string,\n participant: string,\n values: Record<string, unknown | null>,\n meta: { seen: number; at: Date; ttlMs: number },\n ): Promise<void>\n\n /** The current map, pruned of rows at or past their `expiresAt`. */\n read(ns: string): Promise<PresenceRow[]>\n\n /**\n * Adapter-managed patch delivery. Without it, live feeds re-read\n * presence on their poll cadence. HTTP Redis uses adaptive polling\n * here when its endpoint does not support subscriptions.\n */\n subscribe?(ns: string, onPatch: (patch: PresencePatch) => void): () => void\n }\n\n /**\n * A live feed of one session's events, starting after `startAfter`\n * (exclusive). Transport is the backend's choice — in-process pub/sub,\n * polling, LISTEN/NOTIFY — callers never branch on which. The iterable\n * ends when the consumer calls `return()` (e.g. a disconnecting SSE\n * client) and must deliver events appended after subscription.\n */\n stream(\n sessionId: string,\n opts?: { startAfter?: number },\n ): AsyncIterable<Event>\n}\n"],"mappings":";AAgNA,MAAa,eAAsB,EACjC,2BAAW,IAAI,KAAK,EACtB;AAEA,MAAa,mBAA6B,OAAO,WAAW"}
1
+ {"version":3,"file":"store-N8PXxDAS.js","names":[],"sources":["../src/store.ts"],"sourcesContent":["/**\n * The A2Store interface — the storage contract every store backend\n * implements. See specs/a2-implementation.md §2–3.\n *\n * This is the whole storage contract: append, read, consumer cursors,\n * failure markers, snapshots, and the live stream. The scheduler\n * needs nothing extra — the armed queue message is its own state, and\n * the store is the only thing it consults.\n */\n\nimport type { PresencePatch } from './contract.ts'\n\n/** A stored event, as the public API exposes it. */\nexport type Event = {\n id: string\n type: string\n payload: unknown\n /** Position in the session's event log, from 1. */\n index: number\n sessionId: string\n createdAt: Date\n}\n\n/** The consumer attempt whose append first persisted a child event. */\nexport type EventCause = {\n consumer: string\n /** The cursor's lane; null for a concurrent consumer's cursor of one event. */\n lane: string | null\n index: number\n attempt: number\n /** Size of one named consumer append, used to reject truncated retries. */\n batchSize?: number\n}\n\n/** What the store persists: immutable event history and its causal edge. */\nexport type StoredEvent = Event & {\n /** Same-session consumer attempt that appended this event; null means root. */\n cause: EventCause | null\n}\n\n/**\n * Where a consumer's cursor stands on its head event. A cursor is one record\n * per (session, consumer, lane): a log cursor for a consumer with one string\n * lane, a lane cursor per lane for a lane function, and a cursor per event\n * (lane null) for a concurrent consumer. Its attempt and failure fields\n * describe the current head and reset when the cursor moves past it.\n */\nexport type HeadDispatch = {\n consumer: string\n lane: string | null\n /** Adapter clock time recorded by the first durable claim of this head. */\n firstClaimedAt: Date | null\n /** Adapter clock time recorded by the most recent durable claim of this head. */\n lastClaimedAt: Date | null\n /** Durable claims of this head, including claims abandoned by hard kills. */\n attemptCount: number\n /** Current holder; null when the head is not claimed. */\n claimHolder: string | null\n /**\n * Adapter clock expiry for the current claim, or, with no holder, the end\n * of a failed attempt's retry hold.\n */\n claimExpiresAt: Date | null\n /**\n * Failed attempts on this head: caught failures, and lapsed claims a later\n * claim took over. This alone drives dead-lettering.\n */\n failureCount: number\n /** Adapter clock time recorded by the most recent caught failure. */\n lastFailedAt: Date | null\n /** Attempt that produced the most recent caught failure. */\n lastFailedAttempt: number | null\n /** The last failure, stringified. */\n lastError: string | null\n /** Adapter clock time recorded when dead-lettered; null otherwise. */\n failedAt: Date | null\n}\n\n/** Where one cursor stands: its position, its head, and the head's dispatch state. */\nexport type StoredCursor = HeadDispatch & {\n /** The last index this cursor finished; a log cursor counts from the latest clear marker. */\n position: number\n /** The event it runs next; null when it has nothing to run. */\n head: number | null\n}\n\n/** A cursor's head event together with its dispatch state. */\nexport type HeadEvent = StoredEvent &\n HeadDispatch & {\n /** Latest clear marker, on claimed heads of a cleared session. */\n clearIndex?: number\n }\n\n/** Names one cursor head: the consumer, its lane, and the head's index. */\nexport type HeadRef = {\n consumer: string\n lane: string | null\n index: number\n}\n\n/**\n * A consumer the caller serves. Work for consumers it does not name is\n * neither pending nor claimed, so a removed consumer's cursors wait for its\n * name to return.\n */\nexport type StoreConsumer = {\n name: string\n /**\n * Set for a consumer with one string lane. Its cursor keeps one position\n * over the log and runs the next event whose type is in `types` (null:\n * every type). A missing cursor is created by the first append that\n * carries one of those types: at the start of the log with `backfill`,\n * otherwise just before that append.\n */\n log?: {\n lane: string\n types: readonly string[] | null\n backfill: boolean\n }\n}\n\n/**\n * One live presence value, as `A2Store.presence.read` returns it. The\n * row is the LWW unit — one participant's one field. `at` is the\n * sender's stamp, the LWW comparator. `expiresAt` is the storage's\n * own clock at the applied set plus its `ttlMs` — never derived from\n * the sender stamp; a row is live strictly before it.\n */\nexport type PresenceRow = {\n participant: string\n field: string\n value: unknown\n seen: number\n at: Date\n expiresAt: Date\n}\n\n/** One consistent cache-plus-tail read for a reducer fold. */\nexport type StoreStateRead = {\n /** The current head checkpoint, even when an older historical snapshot is selected. */\n headIndex: number | null\n /** The greatest cached fold at or before the requested snapshot frontier. */\n snapshot: { index: number; state: unknown } | null\n /** Immutable events strictly after `snapshot.index`, or the full log on a miss. */\n events: Event[]\n /** Latest clear marker; omitted when the session was never cleared. */\n clearIndex?: number\n}\n\nexport type StoreSnapshotWrite = {\n index: number\n state: unknown\n /** Unfinished cursor heads that durably retain this exact checkpoint. */\n pins?: readonly HeadRef[]\n}\n\nexport type StoreStateReadRequest = {\n sessionId: string\n throughIndex?: number\n snapshotThroughIndex?: number\n}\n\n/** The result of atomically claiming every currently eligible head. */\nexport type StoreClaimAvailableResult =\n | {\n outcome: 'claimed'\n events: HeadEvent[]\n /** The session's head when the claim was made: how far behind each event is. */\n head?: number\n }\n | { outcome: 'busy'; retryAt: Date }\n | { outcome: 'settled' }\n\n/** A completion may lose to a newer claim or an earlier completion. */\nexport type CompleteAttemptResult =\n { outcome: 'completed'; events: StoredEvent[] } | { outcome: 'superseded' }\n\n/** The result of one claim-renewal heartbeat, both lists in head order. */\nexport type RenewClaimsResult = {\n /** Listed claims that remain owned by the holder. */\n renewed: HeadRef[]\n /** Listed claims a newer attempt has durably taken, or whose cursor moved on. */\n superseded: HeadRef[]\n}\n\n/** The result of atomically recording a caught failure. */\nexport type FailAttemptResult = {\n outcome: 'failed' | 'dead_lettered' | 'superseded'\n failureCount: number\n}\n\n/** A consumer an appended event starts work for, with its resolved lane. */\nexport type EventTarget = {\n consumer: string\n /** The lane a lane function resolved; null runs the event concurrently. */\n lane: string | null\n}\n\n/** Input to `A2Store.append` — already validated by the machine. */\nexport type AppendEvent = {\n type: string\n payload: unknown\n /** Caller-supplied idempotency key; generated when absent. */\n id?: string\n /** Internal causal edge supplied atomically by consumer `session.append`. */\n cause?: EventCause\n /**\n * Lane-function and concurrent consumers this event starts work for,\n * resolved before persistence. Log-cursor consumers are matched by type\n * from `StoreConsumer.log` instead.\n */\n targets?: readonly EventTarget[]\n}\n\n/** A consumer-returned event with the deterministic id retries require. */\nexport type ReturnedEvent = AppendEvent & { id: string }\n\n/** The rows written by an append and the session's pending state. */\nexport type StoreAppendResult = {\n events: StoredEvent[]\n /**\n * Whether a served consumer has a live head in this session: one that is\n * not dead-lettered. An append whose own batch starts work for a served\n * consumer may report true without checking that work is runnable.\n */\n hasPending: boolean\n}\n\nexport type StoreClearOptions = {\n sessionId: string\n ifLastIndex?: number\n /** The clearing consumer's attempt, fenced like a consumer append. */\n cause?: EventCause\n}\n\nexport type StoreClearResult = {\n cleared: boolean\n /** The head after the operation. */\n index: number\n /** The latest clear marker after the operation, or 0. */\n clearIndex: number\n}\n\nexport type StoreReclaimResult = { deleted: number; done: boolean }\n\nexport type StoreRedriveOptions = {\n sessionId: string\n consumer: string\n index: number\n /** `retry` clears the dead letter; `skip` moves the cursor past it. */\n action: 'retry' | 'skip'\n consumers?: readonly StoreConsumer[]\n}\n\nexport type StoreRedriveResult = {\n /** Whether the head was dead-lettered and this operation resolved it. */\n redriven: boolean\n /** Whether a served consumer has a live head in this session: one that is not dead-lettered. */\n hasPending: boolean\n}\n\n/**\n * An injectable clock. Adapters take one so tests can drive claim\n * expiry, failure timestamps, and (later) stuck-session detection\n * deterministically — against real storage, no mocking.\n */\nexport type Clock = {\n now(): Date\n}\n\n/** An injectable id source for generated event ids. */\nexport type IdSource = () => string\n\nexport const SYSTEM_CLOCK: Clock = {\n now: () => new Date(),\n}\n\nexport const RANDOM_IDS: IdSource = () => crypto.randomUUID()\n\n/**\n * Cursor rules every operation shares:\n *\n * - `consumers` names the consumers the caller serves. Omitted, every cursor\n * counts and no log cursor is created or advanced by type.\n * - A cursor's head is the next event it runs: the lowest unfinished event of\n * its lane, the event itself for a concurrent cursor, or for a log cursor\n * the next event after its position whose type it takes. The clear marker\n * is never a head.\n * - A head is eligible when no live claim or retry hold owns it, it is not\n * dead-lettered, and it lies above the latest clear marker.\n * - Moving a cursor past its head resets the head's attempt and failure\n * fields and releases snapshot pins on it.\n */\nexport interface A2Store {\n /**\n * Accepts a batch; the batch is atomic — one transaction, consecutive\n * `index`es, all-or-nothing. The idempotency key covers the whole\n * operation, not each item: if *every* event's `id` already exists in\n * this session, this is a retry of a committed batch whose ack was\n * lost — return the existing rows as success. If only *some* ids\n * exist, the caller mixed an already-sent batch with fresh events —\n * always a caller bug — so throw `A2Error('PARTIAL_DUPLICATE_BATCH')`.\n * Ids are unique per session: the same id in another session names a\n * different event and plays no part in these checks.\n *\n * In the same atomic operation, each event's `targets` start cursor work:\n * a lane target queues the event in that consumer's lane, a null lane\n * creates a cursor for that event alone. Each log consumer in `consumers`\n * whose types the batch carries gets its cursor created or, when idle, a\n * head: the next event after its position that it takes, which may\n * precede the batch when an appender that doesn't serve it wrote in\n * between. `hasPending` reflects the whole session for the served consumers,\n * including older work and idempotent retries.\n *\n * An event carrying `cause` is a consumer append, fenced by attempt\n * currency: accept it only while the cause's cursor still has\n * `cause.index` as its head, `cause.attempt` is that head's latest\n * attempt, and the head is not dead-lettered; otherwise throw\n * `A2Error('SUPERSEDED_ATTEMPT')` and write nothing. The check is part of\n * this atomic operation and must serialize against a concurrent\n * `claimAvailable` — an unlocked read of the cursor admits write skew. The\n * idempotent-replay path runs first, so a batch whose ids all exist\n * replays regardless of the current attempt.\n *\n * Clearing stores (a2-implementation.md §17.2) fence one level earlier:\n * a `cause` at or below the latest clear marker throws\n * `SUPERSEDED_ATTEMPT`, an `originIndex` there throws `SESSION_CLEARED`,\n * and ids whose rows lie below the marker are free to reuse.\n */\n append(\n sessionId: string,\n events: AppendEvent[],\n options?: {\n originIndex?: number\n consumers?: readonly StoreConsumer[]\n },\n ): Promise<StoreAppendResult>\n\n /**\n * Optional with `reclaim`. Serialized with `append`: checks\n * `ifLastIndex` against the head and the latest marker, then appends a\n * clear marker at the next index without touching existing rows.\n * Afterwards every event at or below the marker is superseded: no head\n * lies there, and every log cursor's position counts from the marker.\n */\n clear?(options: StoreClearOptions): Promise<StoreClearResult>\n\n /**\n * Deletes one bounded batch of rows below the latest clear marker, with\n * their cursor records, id records, and cached folds. `done` once nothing\n * remains below it. Never waits on a lock that other operations hold.\n */\n reclaim?(sessionId: string): Promise<StoreReclaimResult>\n\n /**\n * Optional with `redrive`. The session's dead-lettered heads above the\n * latest clear marker, in event order, then by consumer name.\n */\n deadLetters?(sessionId: string): Promise<HeadEvent[]>\n\n /**\n * Optional with `deadLetters`. Atomically resolves the consumer's\n * dead-lettered head at `index` above the latest clear marker; anything\n * else is untouched and reports `redriven: false`. `retry` clears\n * `failedAt` and `failureCount`, so the head is claimable again with a\n * fresh failure budget, keeping its claim history and last failure. `skip`\n * moves the cursor past the head with no completion. Both serialize with\n * `claimAvailable` and the consumer-append fence. `hasPending` is read in\n * the same step.\n */\n redrive?(options: StoreRedriveOptions): Promise<StoreRedriveResult>\n\n /**\n * Brings one log consumer's cursor up to date without an append, for\n * `session.consume()`. A missing cursor is created: with `backfill`, at\n * the latest clear marker, taking the first event of its types after it;\n * otherwise at the head, with nothing to run. When the session has nothing\n * after its latest clear (or was never written), a missing cursor stays\n * missing: nothing is written, and the cursor comes back idle at the\n * marker, so a consume of an unknown session leaves no trace. That is\n * exact with `backfill`; without it, the consumer starts at the first\n * consume or serving append that finds events. An\n * idle cursor takes the next event of its types after its position, so it\n * finds events appended by deployments that don't serve it. A cursor with\n * a head, claimed or not, is left as it is. Records the consumer's types,\n * as an append would, and returns the cursor and the session's head.\n */\n wakeLog(options: {\n sessionId: string\n consumer: StoreConsumer & { log: NonNullable<StoreConsumer['log']> }\n }): Promise<{ cursor: StoredCursor; head: number }>\n\n /**\n * The session's cursors: every log and lane cursor, and every concurrent\n * cursor that still has a head, by consumer, then lane (concurrent cursors\n * last, by head). Lane and concurrent cursors whose work lies at or below\n * the latest clear marker are not listed.\n */\n cursors(sessionId: string): Promise<StoredCursor[]>\n\n /** Events for one session, oldest first. Bounds form `(afterIndex, throughIndex]`. */\n read(\n sessionId: string,\n opts?: { afterIndex?: number; throughIndex?: number },\n ): Promise<StoredEvent[]>\n\n /** Public history without causal edges; core falls back to read when absent. */\n readHistory?(\n sessionId: string,\n opts?: { afterIndex?: number; throughIndex?: number },\n ): Promise<Event[]>\n\n /**\n * Atomically claims every eligible head of the served consumers. A live\n * claim or retry hold produces `busy` only when it is the sole remaining\n * obstacle to actionable work. Claimed heads are returned in event order,\n * then by consumer name. Excluded heads stay unclaimed and keep blocking\n * their lane.\n */\n claimAvailable(options: {\n sessionId: string\n holder: string\n ttlMs: number\n expiresAtMs?: number\n exclude?: readonly HeadRef[]\n consumers?: readonly StoreConsumer[]\n /**\n * Taking over a lapsed claim (one whose holder is still recorded, never\n * completed or failed) adds one to `failureCount`. When that reaches\n * `maxFailures`, the head dead-letters instead of being claimed: it\n * comes back in `events` with `failedAt` set and no claim. Its\n * `attemptCount` still advances, fencing the lapsed attempt, and its\n * `lastFailedAttempt` is unchanged.\n */\n maxFailures?: number\n /**\n * Claims only heads at or below this index: a head past it is neither\n * claimed nor reported `busy`, and stays claimable without it.\n */\n through?: number\n }): Promise<StoreClaimAvailableResult>\n\n /**\n * Renews the listed live claims still owned by `holder`. Each listed claim\n * carries the attempt the holder owns. `renewed` lists the claims that\n * remain owned after the operation; `superseded` lists the claims whose\n * head a newer attempt has durably taken, or whose cursor has moved past\n * it. An expired claim no successor has taken appears in neither list — its\n * attempt may still complete (`completeAttempt` is the fence), so it is\n * not reported as lost. Renewal never revives an expired claim.\n */\n renewClaims(options: {\n sessionId: string\n holder: string\n claims: readonly (HeadRef & { attempt: number })[]\n ttlMs: number\n expiresAtMs?: number\n }): Promise<RenewClaimsResult>\n\n /**\n * Atomically completes one current attempt: appends its returned events\n * (with their own targets, waking the served log consumers) and moves the\n * cursor past its head. Retrying a committed completion with the same\n * attempt and deterministic child ids returns the existing children. A\n * stale attempt never appends.\n */\n completeAttempt(options: {\n sessionId: string\n consumer: string\n lane: string | null\n index: number\n attempt: number\n events: ReturnedEvent[]\n consumers?: readonly StoreConsumer[]\n }): Promise<CompleteAttemptResult>\n\n /**\n * Atomically records a caught failure for one claimed attempt. A stale\n * attempt cannot poison a finished head or a newer attempt. Accepted\n * failures record the operation's clock time. A failure that does not\n * dead-letter releases the claim and, with `retryAfterMs`, keeps the head\n * unclaimable for that long: its claim expiry is set with no holder, so\n * `claimAvailable` reports it `busy` until then.\n */\n failAttempt(options: {\n sessionId: string\n consumer: string\n lane: string | null\n index: number\n attempt: number\n error: string\n maxFailures: number\n retryAfterMs?: number\n }): Promise<FailAttemptResult>\n\n /**\n * Reads a reducer snapshot and its event tail as one consistent adapter\n * operation. On a cache miss, `snapshot` is null and `events` is the full\n * log. The snapshot is untrusted; core may reject it and issue a full\n * `read()` when its state schema no longer accepts the cached value.\n * Operational failures propagate without falling back to a full-log read.\n */\n readState(\n sessionId: string,\n reducerName: string,\n options?: { throughIndex?: number; snapshotThroughIndex?: number },\n ): Promise<StoreStateRead>\n\n /**\n * Optional batched `readState` — one consistent snapshot-plus-tail read\n * per session id, aligned positionally with the input (duplicates\n * allowed). Each element has its own frontier; the batch makes no\n * cross-session consistency claim. Core falls back to parallel\n * `readState` calls when absent.\n */\n readStates?(\n requests: readonly StoreStateReadRequest[],\n reducerName: string,\n ): Promise<StoreStateRead[]>\n\n /**\n * Atomically writes disposable reducer checkpoints. The greatest index\n * advances the head cache. Older checkpoints survive only while at least\n * one listed cursor head is still unfinished; moving that cursor past it\n * or dead-lettering it releases the pin and collects unreferenced\n * historical checkpoints.\n */\n putSnapshots(\n sessionId: string,\n reducerName: string,\n snapshots: readonly StoreSnapshotWrite[],\n ): Promise<void>\n\n /**\n * Optional ephemeral-plane capability (specs/a2-implementation.md\n * §15.1) — optional like snapshots are. Values arrive already\n * validated by core; adapters store them opaquely. Presence never\n * touches the event log: no index, no history row, no recovery arm.\n */\n presence?: {\n /**\n * Field-wise last-writer-wins merge of one participant's values:\n * a field whose unexpired entry has a strictly newer `at` (the\n * sender's stamp) is left untouched. `null` deletes the value but\n * keeps a tombstone with its `at`, which takes part in the merge\n * like a value until it expires, so a set older than the delete\n * still loses when it arrives later. Every applied write, value or\n * tombstone, refreshes that field's expiry to the storage's own\n * clock plus `ttlMs` — the sender stamp orders writes but never\n * anchors their lifetime. `subscribe` delivers applied writes only,\n * a delete as `null`.\n */\n set(\n ns: string,\n participant: string,\n values: Record<string, unknown | null>,\n meta: { seen: number; at: Date; ttlMs: number },\n ): Promise<void>\n\n /**\n * The current map, pruned of rows at or past their `expiresAt`.\n * Tombstones never appear.\n */\n read(ns: string): Promise<PresenceRow[]>\n\n /**\n * Adapter-managed patch delivery. Without it, live feeds re-read\n * presence on their poll cadence. HTTP Redis uses adaptive polling\n * here when its endpoint does not support subscriptions.\n */\n subscribe?(ns: string, onPatch: (patch: PresencePatch) => void): () => void\n }\n\n /**\n * A live feed of one session's events, starting after `startAfter`\n * (exclusive). Transport is the backend's choice — in-process pub/sub,\n * polling, LISTEN/NOTIFY — callers never branch on which. The iterable\n * ends when the consumer calls `return()` (e.g. a disconnecting SSE\n * client) and must deliver events appended after subscription.\n */\n stream(\n sessionId: string,\n opts?: { startAfter?: number },\n ): AsyncIterable<Event>\n}\n"],"mappings":";AAiRA,MAAa,eAAsB,EACjC,2BAAW,IAAI,KAAK,EACtB;AAEA,MAAa,mBAA6B,OAAO,WAAW"}