@proofoftech/flowsafe 0.3.0 → 0.6.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 (296) hide show
  1. package/CHANGELOG.md +336 -0
  2. package/dist/agent-runner/approval-shapes.d.ts +36 -0
  3. package/dist/agent-runner/approval-shapes.d.ts.map +1 -0
  4. package/dist/agent-runner/approval-shapes.js +101 -0
  5. package/dist/agent-runner/approval-shapes.js.map +1 -0
  6. package/dist/agent-runner/durable-agent-runner.d.ts +154 -0
  7. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -0
  8. package/dist/agent-runner/durable-agent-runner.js +291 -0
  9. package/dist/agent-runner/durable-agent-runner.js.map +1 -0
  10. package/dist/agent-runner/index.d.ts +3 -0
  11. package/dist/agent-runner/index.d.ts.map +1 -0
  12. package/dist/agent-runner/index.js +10 -0
  13. package/dist/agent-runner/index.js.map +1 -0
  14. package/dist/approval-api/contract.d.ts +29 -0
  15. package/dist/approval-api/contract.d.ts.map +1 -1
  16. package/dist/approval-api/d1-store.d.ts.map +1 -1
  17. package/dist/approval-api/d1-store.js +112 -18
  18. package/dist/approval-api/d1-store.js.map +1 -1
  19. package/dist/approval-api/grants.d.ts +1 -1
  20. package/dist/approval-api/grants.d.ts.map +1 -1
  21. package/dist/approval-api/grants.js +8 -32
  22. package/dist/approval-api/grants.js.map +1 -1
  23. package/dist/approval-api/index.d.ts +2 -2
  24. package/dist/approval-api/index.d.ts.map +1 -1
  25. package/dist/approval-api/index.js.map +1 -1
  26. package/dist/approval-api/router.d.ts +1 -1
  27. package/dist/approval-api/router.d.ts.map +1 -1
  28. package/dist/approval-api/router.js +1 -0
  29. package/dist/approval-api/router.js.map +1 -1
  30. package/dist/approval-api/service.d.ts +24 -3
  31. package/dist/approval-api/service.d.ts.map +1 -1
  32. package/dist/approval-api/service.js +116 -1
  33. package/dist/approval-api/service.js.map +1 -1
  34. package/dist/approval-api/store.d.ts +29 -6
  35. package/dist/approval-api/store.d.ts.map +1 -1
  36. package/dist/approval-api/store.js +62 -2
  37. package/dist/approval-api/store.js.map +1 -1
  38. package/dist/approval-api/tenant-context.d.ts.map +1 -1
  39. package/dist/approval-api/tenant-context.js +17 -1
  40. package/dist/approval-api/tenant-context.js.map +1 -1
  41. package/dist/approval-api/tenant-store.d.ts.map +1 -1
  42. package/dist/approval-api/tenant-store.js +8 -2
  43. package/dist/approval-api/tenant-store.js.map +1 -1
  44. package/dist/approval-api/types.d.ts +19 -0
  45. package/dist/approval-api/types.d.ts.map +1 -1
  46. package/dist/approval-api/types.js +16 -0
  47. package/dist/approval-api/types.js.map +1 -1
  48. package/dist/approval-ui/App.d.ts +9 -1
  49. package/dist/approval-ui/App.d.ts.map +1 -1
  50. package/dist/approval-ui/App.js +10 -5
  51. package/dist/approval-ui/App.js.map +1 -1
  52. package/dist/approval-ui/DetailView.d.ts +4 -1
  53. package/dist/approval-ui/DetailView.d.ts.map +1 -1
  54. package/dist/approval-ui/DetailView.js +2 -2
  55. package/dist/approval-ui/DetailView.js.map +1 -1
  56. package/dist/approval-ui/QueueView.d.ts +7 -1
  57. package/dist/approval-ui/QueueView.d.ts.map +1 -1
  58. package/dist/approval-ui/QueueView.js +8 -3
  59. package/dist/approval-ui/QueueView.js.map +1 -1
  60. package/dist/approval-ui/client.d.ts +19 -0
  61. package/dist/approval-ui/client.d.ts.map +1 -1
  62. package/dist/approval-ui/client.js +29 -1
  63. package/dist/approval-ui/client.js.map +1 -1
  64. package/dist/approval-ui/components.d.ts +20 -0
  65. package/dist/approval-ui/components.d.ts.map +1 -1
  66. package/dist/approval-ui/components.js +2 -0
  67. package/dist/approval-ui/components.js.map +1 -1
  68. package/dist/approval-ui/index.d.ts +4 -2
  69. package/dist/approval-ui/index.d.ts.map +1 -1
  70. package/dist/approval-ui/index.js +3 -0
  71. package/dist/approval-ui/index.js.map +1 -1
  72. package/dist/approval-ui/stream.d.ts +142 -0
  73. package/dist/approval-ui/stream.d.ts.map +1 -0
  74. package/dist/approval-ui/stream.js +136 -0
  75. package/dist/approval-ui/stream.js.map +1 -0
  76. package/dist/approval-ui/use-approval-dashboard.d.ts +74 -1
  77. package/dist/approval-ui/use-approval-dashboard.d.ts.map +1 -1
  78. package/dist/approval-ui/use-approval-dashboard.js +307 -7
  79. package/dist/approval-ui/use-approval-dashboard.js.map +1 -1
  80. package/dist/approval-ui/use-web-socket-transport.d.ts +10 -0
  81. package/dist/approval-ui/use-web-socket-transport.d.ts.map +1 -0
  82. package/dist/approval-ui/use-web-socket-transport.js +46 -0
  83. package/dist/approval-ui/use-web-socket-transport.js.map +1 -0
  84. package/dist/background-tasks/d1-storage.d.ts +66 -0
  85. package/dist/background-tasks/d1-storage.d.ts.map +1 -0
  86. package/dist/background-tasks/d1-storage.js +196 -0
  87. package/dist/background-tasks/d1-storage.js.map +1 -0
  88. package/dist/background-tasks/host.d.ts +82 -0
  89. package/dist/background-tasks/host.d.ts.map +1 -0
  90. package/dist/background-tasks/host.js +275 -0
  91. package/dist/background-tasks/host.js.map +1 -0
  92. package/dist/background-tasks/index.d.ts +7 -0
  93. package/dist/background-tasks/index.d.ts.map +1 -0
  94. package/dist/background-tasks/index.js +10 -0
  95. package/dist/background-tasks/index.js.map +1 -0
  96. package/dist/background-tasks/routes.d.ts +15 -0
  97. package/dist/background-tasks/routes.d.ts.map +1 -0
  98. package/dist/background-tasks/routes.js +144 -0
  99. package/dist/background-tasks/routes.js.map +1 -0
  100. package/dist/do-runner/cf-types.d.ts +70 -2
  101. package/dist/do-runner/cf-types.d.ts.map +1 -1
  102. package/dist/do-runner/cf-types.js +30 -1
  103. package/dist/do-runner/cf-types.js.map +1 -1
  104. package/dist/do-runner/d1-storage.d.ts +343 -2
  105. package/dist/do-runner/d1-storage.d.ts.map +1 -1
  106. package/dist/do-runner/d1-storage.js +566 -13
  107. package/dist/do-runner/d1-storage.js.map +1 -1
  108. package/dist/do-runner/do-error-response.d.ts +29 -0
  109. package/dist/do-runner/do-error-response.d.ts.map +1 -0
  110. package/dist/do-runner/do-error-response.js +73 -0
  111. package/dist/do-runner/do-error-response.js.map +1 -0
  112. package/dist/do-runner/durable-object.d.ts +5 -2
  113. package/dist/do-runner/durable-object.d.ts.map +1 -1
  114. package/dist/do-runner/durable-object.js +87 -20
  115. package/dist/do-runner/durable-object.js.map +1 -1
  116. package/dist/do-runner/hub-do.d.ts +55 -0
  117. package/dist/do-runner/hub-do.d.ts.map +1 -0
  118. package/dist/do-runner/hub-do.js +197 -0
  119. package/dist/do-runner/hub-do.js.map +1 -0
  120. package/dist/do-runner/index.d.ts +12 -4
  121. package/dist/do-runner/index.d.ts.map +1 -1
  122. package/dist/do-runner/index.js +9 -2
  123. package/dist/do-runner/index.js.map +1 -1
  124. package/dist/do-runner/init.d.ts +20 -0
  125. package/dist/do-runner/init.d.ts.map +1 -1
  126. package/dist/do-runner/init.js +12 -1
  127. package/dist/do-runner/init.js.map +1 -1
  128. package/dist/do-runner/path-safe-id.js +1 -1
  129. package/dist/do-runner/path-safe-id.js.map +1 -1
  130. package/dist/do-runner/pubsub.d.ts +18 -0
  131. package/dist/do-runner/pubsub.d.ts.map +1 -0
  132. package/dist/do-runner/pubsub.js +42 -0
  133. package/dist/do-runner/pubsub.js.map +1 -0
  134. package/dist/do-runner/runtime.d.ts +24 -0
  135. package/dist/do-runner/runtime.d.ts.map +1 -1
  136. package/dist/do-runner/runtime.js +29 -2
  137. package/dist/do-runner/runtime.js.map +1 -1
  138. package/dist/do-runner/thread-do.d.ts +74 -0
  139. package/dist/do-runner/thread-do.d.ts.map +1 -0
  140. package/dist/do-runner/thread-do.js +156 -0
  141. package/dist/do-runner/thread-do.js.map +1 -0
  142. package/dist/do-runner/thread-header.d.ts +16 -0
  143. package/dist/do-runner/thread-header.d.ts.map +1 -0
  144. package/dist/do-runner/thread-header.js +24 -0
  145. package/dist/do-runner/thread-header.js.map +1 -0
  146. package/dist/goals/index.d.ts +2 -0
  147. package/dist/goals/index.d.ts.map +1 -0
  148. package/dist/goals/index.js +7 -0
  149. package/dist/goals/index.js.map +1 -0
  150. package/dist/goals/objective-routes.d.ts +87 -0
  151. package/dist/goals/objective-routes.d.ts.map +1 -0
  152. package/dist/goals/objective-routes.js +375 -0
  153. package/dist/goals/objective-routes.js.map +1 -0
  154. package/dist/host-kit/approval-bridge.d.ts +24 -4
  155. package/dist/host-kit/approval-bridge.d.ts.map +1 -1
  156. package/dist/host-kit/approval-bridge.js +32 -10
  157. package/dist/host-kit/approval-bridge.js.map +1 -1
  158. package/dist/host-kit/env-vars.d.ts +20 -0
  159. package/dist/host-kit/env-vars.d.ts.map +1 -1
  160. package/dist/host-kit/env-vars.js +30 -0
  161. package/dist/host-kit/env-vars.js.map +1 -1
  162. package/dist/host-kit/flowsafe-worker.d.ts +134 -5
  163. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  164. package/dist/host-kit/flowsafe-worker.js +283 -47
  165. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  166. package/dist/host-kit/host-approval-service.d.ts +20 -1
  167. package/dist/host-kit/host-approval-service.d.ts.map +1 -1
  168. package/dist/host-kit/host-approval-service.js +15 -0
  169. package/dist/host-kit/host-approval-service.js.map +1 -1
  170. package/dist/host-kit/hub-topology.d.ts +35 -0
  171. package/dist/host-kit/hub-topology.d.ts.map +1 -0
  172. package/dist/host-kit/hub-topology.js +32 -0
  173. package/dist/host-kit/hub-topology.js.map +1 -0
  174. package/dist/host-kit/index.d.ts +8 -1
  175. package/dist/host-kit/index.d.ts.map +1 -1
  176. package/dist/host-kit/index.js +10 -0
  177. package/dist/host-kit/index.js.map +1 -1
  178. package/dist/host-kit/memory-boundary.d.ts +64 -0
  179. package/dist/host-kit/memory-boundary.d.ts.map +1 -0
  180. package/dist/host-kit/memory-boundary.js +109 -0
  181. package/dist/host-kit/memory-boundary.js.map +1 -0
  182. package/dist/host-kit/route-path.d.ts +17 -0
  183. package/dist/host-kit/route-path.d.ts.map +1 -0
  184. package/dist/host-kit/route-path.js +35 -0
  185. package/dist/host-kit/route-path.js.map +1 -0
  186. package/dist/host-kit/stream-router.d.ts +22 -0
  187. package/dist/host-kit/stream-router.d.ts.map +1 -0
  188. package/dist/host-kit/stream-router.js +191 -0
  189. package/dist/host-kit/stream-router.js.map +1 -0
  190. package/dist/host-kit/stream-ticket.d.ts +55 -0
  191. package/dist/host-kit/stream-ticket.d.ts.map +1 -0
  192. package/dist/host-kit/stream-ticket.js +156 -0
  193. package/dist/host-kit/stream-ticket.js.map +1 -0
  194. package/dist/host-kit/tenant-registry.js +1 -1
  195. package/dist/host-kit/tenant-registry.js.map +1 -1
  196. package/dist/host-kit/thread-topology.d.ts +44 -0
  197. package/dist/host-kit/thread-topology.d.ts.map +1 -0
  198. package/dist/host-kit/thread-topology.js +76 -0
  199. package/dist/host-kit/thread-topology.js.map +1 -0
  200. package/dist/index.d.ts +3 -3
  201. package/dist/index.d.ts.map +1 -1
  202. package/dist/index.js +1 -1
  203. package/dist/index.js.map +1 -1
  204. package/dist/internal-error-response.d.ts +3 -0
  205. package/dist/internal-error-response.d.ts.map +1 -0
  206. package/dist/internal-error-response.js +20 -0
  207. package/dist/internal-error-response.js.map +1 -0
  208. package/dist/numeric-config.d.ts +4 -0
  209. package/dist/numeric-config.d.ts.map +1 -0
  210. package/dist/numeric-config.js +23 -0
  211. package/dist/numeric-config.js.map +1 -0
  212. package/dist/schedules/index.d.ts +5 -0
  213. package/dist/schedules/index.d.ts.map +1 -0
  214. package/dist/schedules/index.js +13 -0
  215. package/dist/schedules/index.js.map +1 -0
  216. package/dist/schedules/router.d.ts +66 -0
  217. package/dist/schedules/router.d.ts.map +1 -0
  218. package/dist/schedules/router.js +827 -0
  219. package/dist/schedules/router.js.map +1 -0
  220. package/dist/schedules/schedules-d1.d.ts +30 -0
  221. package/dist/schedules/schedules-d1.d.ts.map +1 -0
  222. package/dist/schedules/schedules-d1.js +374 -0
  223. package/dist/schedules/schedules-d1.js.map +1 -0
  224. package/dist/schedules/storage.d.ts +11 -0
  225. package/dist/schedules/storage.d.ts.map +1 -0
  226. package/dist/schedules/storage.js +34 -0
  227. package/dist/schedules/storage.js.map +1 -0
  228. package/dist/schedules/tick.d.ts +131 -0
  229. package/dist/schedules/tick.d.ts.map +1 -0
  230. package/dist/schedules/tick.js +598 -0
  231. package/dist/schedules/tick.js.map +1 -0
  232. package/dist/signal-providers/delivery.d.ts +24 -0
  233. package/dist/signal-providers/delivery.d.ts.map +1 -0
  234. package/dist/signal-providers/delivery.js +62 -0
  235. package/dist/signal-providers/delivery.js.map +1 -0
  236. package/dist/signal-providers/github-provider.d.ts +33 -0
  237. package/dist/signal-providers/github-provider.d.ts.map +1 -0
  238. package/dist/signal-providers/github-provider.js +116 -0
  239. package/dist/signal-providers/github-provider.js.map +1 -0
  240. package/dist/signal-providers/host-do.d.ts +79 -0
  241. package/dist/signal-providers/host-do.d.ts.map +1 -0
  242. package/dist/signal-providers/host-do.js +216 -0
  243. package/dist/signal-providers/host-do.js.map +1 -0
  244. package/dist/signal-providers/index.d.ts +7 -0
  245. package/dist/signal-providers/index.d.ts.map +1 -0
  246. package/dist/signal-providers/index.js +19 -0
  247. package/dist/signal-providers/index.js.map +1 -0
  248. package/dist/signal-providers/provider.d.ts +92 -0
  249. package/dist/signal-providers/provider.d.ts.map +1 -0
  250. package/dist/signal-providers/provider.js +87 -0
  251. package/dist/signal-providers/provider.js.map +1 -0
  252. package/dist/signal-providers/subscription-d1.d.ts +88 -0
  253. package/dist/signal-providers/subscription-d1.d.ts.map +1 -0
  254. package/dist/signal-providers/subscription-d1.js +259 -0
  255. package/dist/signal-providers/subscription-d1.js.map +1 -0
  256. package/dist/signal-providers/webhook-route.d.ts +88 -0
  257. package/dist/signal-providers/webhook-route.d.ts.map +1 -0
  258. package/dist/signal-providers/webhook-route.js +391 -0
  259. package/dist/signal-providers/webhook-route.js.map +1 -0
  260. package/dist/signals/client.d.ts +72 -0
  261. package/dist/signals/client.d.ts.map +1 -0
  262. package/dist/signals/client.js +87 -0
  263. package/dist/signals/client.js.map +1 -0
  264. package/dist/signals/d1-shared.d.ts +43 -0
  265. package/dist/signals/d1-shared.d.ts.map +1 -0
  266. package/dist/signals/d1-shared.js +46 -0
  267. package/dist/signals/d1-shared.js.map +1 -0
  268. package/dist/signals/index.d.ts +9 -0
  269. package/dist/signals/index.d.ts.map +1 -0
  270. package/dist/signals/index.js +15 -0
  271. package/dist/signals/index.js.map +1 -0
  272. package/dist/signals/notification-dispatch.d.ts +52 -0
  273. package/dist/signals/notification-dispatch.d.ts.map +1 -0
  274. package/dist/signals/notification-dispatch.js +198 -0
  275. package/dist/signals/notification-dispatch.js.map +1 -0
  276. package/dist/signals/notifications-d1.d.ts +28 -0
  277. package/dist/signals/notifications-d1.d.ts.map +1 -0
  278. package/dist/signals/notifications-d1.js +704 -0
  279. package/dist/signals/notifications-d1.js.map +1 -0
  280. package/dist/signals/router.d.ts +73 -0
  281. package/dist/signals/router.d.ts.map +1 -0
  282. package/dist/signals/router.js +240 -0
  283. package/dist/signals/router.js.map +1 -0
  284. package/dist/signals/storage.d.ts +11 -0
  285. package/dist/signals/storage.d.ts.map +1 -0
  286. package/dist/signals/storage.js +27 -0
  287. package/dist/signals/storage.js.map +1 -0
  288. package/dist/signals/thread-do-routes.d.ts +82 -0
  289. package/dist/signals/thread-do-routes.d.ts.map +1 -0
  290. package/dist/signals/thread-do-routes.js +660 -0
  291. package/dist/signals/thread-do-routes.js.map +1 -0
  292. package/dist/signals/thread-state-d1.d.ts +22 -0
  293. package/dist/signals/thread-state-d1.d.ts.map +1 -0
  294. package/dist/signals/thread-state-d1.js +83 -0
  295. package/dist/signals/thread-state-d1.js.map +1 -0
  296. package/package.json +11 -2
@@ -0,0 +1,704 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Track C (M-004), CI-M-004-002 — the D1 NotificationsStorage domain over
3
+ // TABLE_NOTIFICATIONS ('mastra_notifications'), mirroring core's abstract
4
+ // NotificationsStorage + InMemoryNotificationsStorage reference (create / list /
5
+ // listDue / get({threadId,id}) / update + findCoalescable coalescing). Composed
6
+ // into createD1Storage's store so `agent.sendNotificationSignal` persists here
7
+ // (core resolves the domain via `mastra.getStorage().getStore('notifications')`).
8
+ //
9
+ // NAMING: mastra_notifications is the AGENT inbox — signals delivered TO the
10
+ // model on its next turn. Distinct from flowsafe's ApprovalNotificationSink,
11
+ // which notifies HUMANS about approvals. Different layers.
12
+ //
13
+ // TENANCY: the `thread_id` column holds the tenant-salted threadId
14
+ // (`${tenantId}_${uuid}`), so purgeTenant's `[tid_, tid\x60)` range is exact
15
+ // over it (registered in TENANT_RANGE_PURGE_TABLES) and the notification TTL
16
+ // reaps terminal rows (purgeExpiredNotifications). Timestamps are ISO-8601 TEXT
17
+ // — the encoding the retention purges and the schema guard ride on.
18
+ import { NotificationsStorage, } from '@mastra/core/notifications';
19
+ import { d1Changes, dateOrUndefined, isoOrNull, jsonOrNull, parseJsonOrUndefined, } from './d1-shared.js';
20
+ /** status → the timestamp column that status stamps (mirrors core statusTimestamp). */
21
+ function statusTimestampColumn(status) {
22
+ switch (status) {
23
+ case 'delivered':
24
+ return 'deliveredAt';
25
+ case 'seen':
26
+ return 'seenAt';
27
+ case 'dismissed':
28
+ return 'dismissedAt';
29
+ case 'archived':
30
+ return 'archivedAt';
31
+ case 'discarded':
32
+ return 'discardedAt';
33
+ default:
34
+ return undefined;
35
+ }
36
+ }
37
+ const NOTIFICATION_COLUMNS = [
38
+ 'id',
39
+ 'thread_id',
40
+ 'source',
41
+ 'kind',
42
+ 'priority',
43
+ 'status',
44
+ 'summary',
45
+ 'payload',
46
+ 'resourceId',
47
+ 'agentId',
48
+ 'sourceId',
49
+ 'dedupeKey',
50
+ 'coalesceKey',
51
+ 'coalescedCount',
52
+ 'attributes',
53
+ 'createdAt',
54
+ 'updatedAt',
55
+ 'deliverAt',
56
+ 'summaryAt',
57
+ 'deliveryReason',
58
+ 'deliveryAttempts',
59
+ 'lastDeliveryAttemptAt',
60
+ 'lastDeliveryError',
61
+ 'deliveredSignalId',
62
+ 'summarySignalId',
63
+ 'deliveredAt',
64
+ 'seenAt',
65
+ 'dismissedAt',
66
+ 'archivedAt',
67
+ 'discardedAt',
68
+ 'metadata',
69
+ ];
70
+ const NOTIFICATION_UPDATE_COLUMNS = NOTIFICATION_COLUMNS.filter((column) => column !== 'id' && column !== 'thread_id');
71
+ function validLimit(limit) {
72
+ return limit !== undefined && Number.isSafeInteger(limit) && limit >= 0;
73
+ }
74
+ function isDuplicateColumn(error) {
75
+ return error instanceof Error && /duplicate column/i.test(error.message);
76
+ }
77
+ export class D1NotificationsStorage extends NotificationsStorage {
78
+ #db;
79
+ #table;
80
+ #sequenceTable;
81
+ #ordinalIndex;
82
+ #legacyReplaceTrigger;
83
+ #legacyInsertTrigger;
84
+ #ready;
85
+ constructor(db, tablePrefix = '') {
86
+ super();
87
+ this.#db = db;
88
+ this.#table = `${tablePrefix}mastra_notifications`;
89
+ this.#sequenceTable = `${tablePrefix}flowsafe_notification_sequence`;
90
+ this.#ordinalIndex = `idx_${this.#table}_insertion_ordinal`;
91
+ this.#legacyReplaceTrigger = `trg_${this.#table}_preserve_insertion_ordinal`;
92
+ this.#legacyInsertTrigger = `trg_${this.#table}_allocate_insertion_ordinal`;
93
+ }
94
+ /**
95
+ * Lazy, memoized schema creation — the same clear-on-failure promise memo the
96
+ * approval store uses: only SUCCESS memoizes, so a transient DDL failure
97
+ * retries on the next call rather than pinning the domain to a dead promise.
98
+ * `init()` (called by the composite store) and every operation await it.
99
+ */
100
+ #ensureSchema() {
101
+ if (!this.#ready) {
102
+ this.#ready = this.#createSchema().catch((error) => {
103
+ this.#ready = undefined;
104
+ throw error;
105
+ });
106
+ }
107
+ return this.#ready;
108
+ }
109
+ async #createSchema() {
110
+ await this.#db
111
+ .prepare(`CREATE TABLE IF NOT EXISTS ${this.#table} (
112
+ id TEXT NOT NULL,
113
+ thread_id TEXT NOT NULL,
114
+ source TEXT NOT NULL,
115
+ kind TEXT NOT NULL,
116
+ priority TEXT NOT NULL,
117
+ status TEXT NOT NULL,
118
+ summary TEXT NOT NULL,
119
+ payload TEXT,
120
+ resourceId TEXT,
121
+ agentId TEXT,
122
+ sourceId TEXT,
123
+ dedupeKey TEXT,
124
+ coalesceKey TEXT,
125
+ coalescedCount INTEGER NOT NULL DEFAULT 1,
126
+ attributes TEXT,
127
+ createdAt TEXT NOT NULL,
128
+ updatedAt TEXT NOT NULL,
129
+ deliverAt TEXT,
130
+ summaryAt TEXT,
131
+ deliveryReason TEXT,
132
+ deliveryAttempts INTEGER NOT NULL DEFAULT 0,
133
+ lastDeliveryAttemptAt TEXT,
134
+ lastDeliveryError TEXT,
135
+ deliveredSignalId TEXT,
136
+ summarySignalId TEXT,
137
+ deliveredAt TEXT,
138
+ seenAt TEXT,
139
+ dismissedAt TEXT,
140
+ archivedAt TEXT,
141
+ discardedAt TEXT,
142
+ metadata TEXT,
143
+ insertionOrdinal INTEGER,
144
+ PRIMARY KEY (thread_id, id)
145
+ )`)
146
+ .run();
147
+ await this.#migrateOrdinalSchema(true);
148
+ }
149
+ async #migrateOrdinalSchema(retryDuplicateColumn) {
150
+ const batch = this.#db.batch?.bind(this.#db);
151
+ if (!batch) {
152
+ throw new Error('D1NotificationsStorage requires database.batch() for atomic schema migration');
153
+ }
154
+ const { results: columns } = await this.#db
155
+ .prepare(`PRAGMA table_info(${this.#table})`)
156
+ .all();
157
+ const needsColumn = !columns.some((column) => column.name === 'insertionOrdinal');
158
+ const statements = [
159
+ this.#db.prepare(`CREATE TABLE IF NOT EXISTS ${this.#sequenceTable} (
160
+ id INTEGER PRIMARY KEY CHECK (id = 1),
161
+ value INTEGER NOT NULL
162
+ )`),
163
+ ...(needsColumn
164
+ ? [
165
+ this.#db.prepare(`ALTER TABLE ${this.#table} ADD COLUMN insertionOrdinal INTEGER`),
166
+ ]
167
+ : []),
168
+ this.#db.prepare(`INSERT INTO ${this.#sequenceTable} (id, value)
169
+ SELECT 1, COALESCE(MAX(insertionOrdinal), 0)
170
+ FROM ${this.#table}
171
+ WHERE true
172
+ ON CONFLICT(id) DO UPDATE SET
173
+ value = MAX(value, excluded.value)`),
174
+ // Assign pre-trigger legacy rows ordinals after any values already
175
+ // written by a newer binary. rowid is their only insertion-order
176
+ // evidence.
177
+ this.#db.prepare(`WITH ranked AS (
178
+ SELECT
179
+ rowid AS targetRowid,
180
+ COALESCE(
181
+ (SELECT MAX(insertionOrdinal) FROM ${this.#table}),
182
+ 0
183
+ ) + ROW_NUMBER() OVER (ORDER BY rowid) AS ordinal
184
+ FROM ${this.#table}
185
+ WHERE insertionOrdinal IS NULL
186
+ )
187
+ UPDATE ${this.#table}
188
+ SET insertionOrdinal = (
189
+ SELECT ordinal
190
+ FROM ranked
191
+ WHERE ranked.targetRowid = ${this.#table}.rowid
192
+ )
193
+ WHERE insertionOrdinal IS NULL`),
194
+ this.#db.prepare(`INSERT INTO ${this.#sequenceTable} (id, value)
195
+ SELECT 1, COALESCE(MAX(insertionOrdinal), 0)
196
+ FROM ${this.#table}
197
+ WHERE true
198
+ ON CONFLICT(id) DO UPDATE SET
199
+ value = MAX(value, excluded.value)`),
200
+ // Keep a rollback-era writer (which omits insertionOrdinal) in the same
201
+ // ordering protocol. An existing key is updated in place, matching
202
+ // Map.set; a new key atomically claims the next sequence value.
203
+ this.#db.prepare(`CREATE TRIGGER IF NOT EXISTS ${this.#legacyReplaceTrigger}
204
+ BEFORE INSERT ON ${this.#table}
205
+ WHEN NEW.insertionOrdinal IS NULL
206
+ AND EXISTS (
207
+ SELECT 1 FROM ${this.#table}
208
+ WHERE thread_id = NEW.thread_id AND id = NEW.id
209
+ )
210
+ BEGIN
211
+ UPDATE ${this.#table}
212
+ SET ${NOTIFICATION_UPDATE_COLUMNS.map((column) => `${column} = NEW.${column}`).join(', ')}
213
+ WHERE thread_id = NEW.thread_id AND id = NEW.id;
214
+ SELECT RAISE(IGNORE);
215
+ END`),
216
+ this.#db.prepare(`CREATE TRIGGER IF NOT EXISTS ${this.#legacyInsertTrigger}
217
+ AFTER INSERT ON ${this.#table}
218
+ WHEN NEW.insertionOrdinal IS NULL
219
+ BEGIN
220
+ UPDATE ${this.#sequenceTable}
221
+ SET value = value + 1
222
+ WHERE id = 1;
223
+ UPDATE ${this.#table}
224
+ SET insertionOrdinal = (
225
+ SELECT value FROM ${this.#sequenceTable} WHERE id = 1
226
+ )
227
+ WHERE rowid = NEW.rowid;
228
+ END`),
229
+ this.#db.prepare(`CREATE UNIQUE INDEX IF NOT EXISTS ${this.#ordinalIndex}
230
+ ON ${this.#table} (insertionOrdinal)
231
+ WHERE insertionOrdinal IS NOT NULL`),
232
+ this.#db.prepare(`CREATE INDEX IF NOT EXISTS idx_${this.#table}_thread
233
+ ON ${this.#table} (thread_id)`),
234
+ this.#db.prepare(`CREATE INDEX IF NOT EXISTS idx_${this.#table}_status
235
+ ON ${this.#table} (thread_id, status)`),
236
+ ];
237
+ try {
238
+ await batch(statements);
239
+ }
240
+ catch (error) {
241
+ // Two fresh isolates can both observe the legacy shape. D1 serializes
242
+ // their batches; the loser re-reads the now-migrated schema rather than
243
+ // treating the expected duplicate-column race as corruption.
244
+ if (retryDuplicateColumn && needsColumn && isDuplicateColumn(error)) {
245
+ await this.#migrateOrdinalSchema(false);
246
+ return;
247
+ }
248
+ throw error;
249
+ }
250
+ }
251
+ async init() {
252
+ await this.#ensureSchema();
253
+ }
254
+ async createNotification(input) {
255
+ await this.#ensureSchema();
256
+ const now = input.createdAt ?? new Date();
257
+ const record = {
258
+ id: input.id ?? crypto.randomUUID(),
259
+ threadId: input.threadId,
260
+ source: input.source,
261
+ kind: input.kind,
262
+ priority: input.priority ?? 'medium',
263
+ status: 'pending',
264
+ summary: input.summary,
265
+ payload: input.payload,
266
+ resourceId: input.resourceId,
267
+ agentId: input.agentId,
268
+ sourceId: input.sourceId,
269
+ dedupeKey: input.dedupeKey,
270
+ coalesceKey: input.coalesceKey,
271
+ coalescedCount: 1,
272
+ attributes: input.attributes,
273
+ createdAt: now,
274
+ updatedAt: now,
275
+ deliverAt: input.deliverAt,
276
+ summaryAt: input.summaryAt,
277
+ deliveryReason: input.deliveryReason,
278
+ deliveryAttempts: 0,
279
+ metadata: input.metadata,
280
+ };
281
+ const insertionOrdinal = await this.#allocateInsertionOrdinal();
282
+ if (!input.dedupeKey && !input.coalesceKey) {
283
+ await this.#insert(record, insertionOrdinal);
284
+ return record;
285
+ }
286
+ for (let attempt = 0; attempt < 16; attempt += 1) {
287
+ if (await this.#insertUnlessCoalescable(record, input, insertionOrdinal)) {
288
+ return record;
289
+ }
290
+ const existing = await this.#findCoalescableRow(input);
291
+ if (!existing)
292
+ continue;
293
+ const existingRecord = rowToRecord(existing);
294
+ const mergedAttributes = input.attributes
295
+ ? { ...existingRecord.attributes, ...input.attributes }
296
+ : existingRecord.attributes;
297
+ const mergedMetadata = input.metadata
298
+ ? { ...existingRecord.metadata, ...input.metadata }
299
+ : existingRecord.metadata;
300
+ const updatedAt = new Date();
301
+ const sets = ['summary = ?', 'updatedAt = ?'];
302
+ const binds = [input.summary, updatedAt.toISOString()];
303
+ if (input.payload != null) {
304
+ sets.push('payload = ?');
305
+ binds.push(jsonOrNull(input.payload));
306
+ }
307
+ if (input.priority !== undefined) {
308
+ sets.push('priority = ?');
309
+ binds.push(input.priority);
310
+ }
311
+ if (input.attributes) {
312
+ sets.push('attributes = ?');
313
+ binds.push(jsonOrNull(mergedAttributes));
314
+ }
315
+ if (input.deliverAt !== undefined) {
316
+ sets.push('deliverAt = ?');
317
+ binds.push(isoOrNull(input.deliverAt));
318
+ }
319
+ if (input.summaryAt !== undefined) {
320
+ sets.push('summaryAt = ?');
321
+ binds.push(isoOrNull(input.summaryAt));
322
+ }
323
+ if (input.deliveryReason !== undefined) {
324
+ sets.push('deliveryReason = ?');
325
+ binds.push(input.deliveryReason);
326
+ }
327
+ if (input.metadata) {
328
+ sets.push('metadata = ?');
329
+ binds.push(jsonOrNull(mergedMetadata));
330
+ }
331
+ sets.push('coalescedCount = coalescedCount + 1');
332
+ const match = this.#coalescableMatch(input);
333
+ const guards = ['id = ?', 'coalescedCount = ?', `(${match.clause})`];
334
+ binds.push(existing.id, existing.coalescedCount, ...match.binds);
335
+ if (input.attributes) {
336
+ guards.push('attributes IS ?');
337
+ binds.push(existing.attributes);
338
+ }
339
+ if (input.metadata) {
340
+ guards.push('metadata IS ?');
341
+ binds.push(existing.metadata);
342
+ }
343
+ const updated = await this.#db
344
+ .prepare(`UPDATE ${this.#table}
345
+ SET ${sets.join(', ')}
346
+ WHERE ${guards.join(' AND ')}
347
+ RETURNING *`)
348
+ .bind(...binds)
349
+ .first();
350
+ if (updated)
351
+ return rowToRecord(updated);
352
+ }
353
+ throw new Error('Notification coalescing failed after 16 contention attempts');
354
+ }
355
+ async listNotifications(input) {
356
+ await this.#ensureSchema();
357
+ const clauses = ['thread_id = ?'];
358
+ const binds = [input.threadId];
359
+ this.#pushIn(clauses, binds, 'status', input.status);
360
+ this.#pushIn(clauses, binds, 'priority', input.priority);
361
+ if (input.source !== undefined) {
362
+ clauses.push('source = ?');
363
+ binds.push(input.source);
364
+ }
365
+ if (input.resourceId !== undefined) {
366
+ clauses.push('resourceId = ?');
367
+ binds.push(input.resourceId);
368
+ }
369
+ if (input.agentId !== undefined) {
370
+ clauses.push('agentId = ?');
371
+ binds.push(input.agentId);
372
+ }
373
+ const sqlLimit = input.search === undefined && validLimit(input.limit)
374
+ ? input.limit
375
+ : undefined;
376
+ if (sqlLimit !== undefined)
377
+ binds.push(sqlLimit);
378
+ const { results } = await this.#db
379
+ .prepare(`SELECT * FROM ${this.#table} WHERE ${clauses.join(' AND ')}
380
+ ORDER BY updatedAt DESC${sqlLimit !== undefined ? ' LIMIT ?' : ''}`)
381
+ .bind(...binds)
382
+ .all();
383
+ let records = results.map(rowToRecord);
384
+ // `search` mirrors the InMemory case-insensitive scan over summary/kind/source
385
+ // (kept in JS so the SQL stays index-friendly and the semantics match exactly).
386
+ if (input.search !== undefined) {
387
+ const needle = input.search.toLowerCase();
388
+ records = records.filter((r) => r.summary.toLowerCase().includes(needle) ||
389
+ r.kind.toLowerCase().includes(needle) ||
390
+ r.source.toLowerCase().includes(needle));
391
+ }
392
+ return input.search !== undefined ||
393
+ (input.limit !== undefined && !validLimit(input.limit))
394
+ ? records.slice(0, input.limit)
395
+ : records;
396
+ }
397
+ /**
398
+ * Due pending notifications across ALL threads/tenants, filtered only by the
399
+ * optional agentId/resourceId — GLOBALLY UNSCOPED by tenant, exactly like
400
+ * core's InMemory reference (a cron dispatcher's cross-thread sweep). It is a
401
+ * TCB-only read (no client route reaches it), so this is not a leak here — but
402
+ * it is a CLOSE-BEFORE-WIRING constraint for Track A: whatever dispatcher
403
+ * drives delivery from this list MUST scope each dispatch by the row's salted
404
+ * `resourceId` (`${tenantId}_…`) / per-thread `threadId` before it acts, or a
405
+ * cross-tenant sweep would deliver one tenant's inbox into another's loop.
406
+ * (See signals/CLAUDE.md — the F3 dispatcher-scope note.)
407
+ */
408
+ async listDueNotifications(input) {
409
+ await this.#ensureSchema();
410
+ const now = input.now.toISOString();
411
+ const clauses = [
412
+ "status = 'pending'",
413
+ '((deliverAt IS NOT NULL AND deliverAt <= ?) OR (summaryAt IS NOT NULL AND summaryAt <= ?))',
414
+ ];
415
+ const binds = [now, now];
416
+ if (input.agentId !== undefined) {
417
+ clauses.push('agentId = ?');
418
+ binds.push(input.agentId);
419
+ }
420
+ if (input.resourceId !== undefined) {
421
+ clauses.push('resourceId = ?');
422
+ binds.push(input.resourceId);
423
+ }
424
+ const sqlLimit = validLimit(input.limit) ? input.limit : undefined;
425
+ if (sqlLimit !== undefined)
426
+ binds.push(sqlLimit);
427
+ const { results } = await this.#db
428
+ .prepare(`SELECT * FROM ${this.#table}
429
+ WHERE ${clauses.join(' AND ')}
430
+ ORDER BY
431
+ CASE
432
+ WHEN deliverAt IS NULL THEN summaryAt
433
+ WHEN summaryAt IS NULL THEN deliverAt
434
+ WHEN deliverAt <= summaryAt THEN deliverAt
435
+ ELSE summaryAt
436
+ END ASC,
437
+ updatedAt ASC${sqlLimit !== undefined ? ' LIMIT ?' : ''}`)
438
+ .bind(...binds)
439
+ .all();
440
+ const records = results.map(rowToRecord);
441
+ return input.limit !== undefined && !validLimit(input.limit)
442
+ ? records.slice(0, input.limit)
443
+ : records;
444
+ }
445
+ async getNotification(input) {
446
+ await this.#ensureSchema();
447
+ const row = await this.#db
448
+ .prepare(`SELECT * FROM ${this.#table} WHERE thread_id = ? AND id = ?`)
449
+ .bind(input.threadId, input.id)
450
+ .first();
451
+ return row ? rowToRecord(row) : null;
452
+ }
453
+ async updateNotification(input) {
454
+ await this.#ensureSchema();
455
+ const now = new Date();
456
+ const sets = ['updatedAt = ?'];
457
+ const binds = [now.toISOString()];
458
+ if (input.status !== undefined) {
459
+ sets.push('status = ?');
460
+ binds.push(input.status);
461
+ const column = statusTimestampColumn(input.status);
462
+ if (column) {
463
+ sets.push(`${column} = ?`);
464
+ binds.push(now.toISOString());
465
+ }
466
+ }
467
+ if (input.summary !== undefined) {
468
+ sets.push('summary = ?');
469
+ binds.push(input.summary);
470
+ }
471
+ if (input.payload !== undefined) {
472
+ sets.push('payload = ?');
473
+ binds.push(jsonOrNull(input.payload));
474
+ }
475
+ if (input.attributes !== undefined) {
476
+ sets.push('attributes = ?');
477
+ binds.push(jsonOrNull(input.attributes));
478
+ }
479
+ if (input.metadata !== undefined) {
480
+ sets.push('metadata = ?');
481
+ binds.push(jsonOrNull(input.metadata));
482
+ }
483
+ if (input.deliverAt !== undefined) {
484
+ sets.push('deliverAt = ?');
485
+ binds.push(isoOrNull(input.deliverAt ?? undefined));
486
+ }
487
+ if (input.summaryAt !== undefined) {
488
+ sets.push('summaryAt = ?');
489
+ binds.push(isoOrNull(input.summaryAt ?? undefined));
490
+ }
491
+ if (input.deliveryReason !== undefined) {
492
+ sets.push('deliveryReason = ?');
493
+ binds.push(input.deliveryReason);
494
+ }
495
+ if (input.deliveryAttempts !== undefined) {
496
+ sets.push('deliveryAttempts = ?');
497
+ binds.push(input.deliveryAttempts);
498
+ }
499
+ if (input.lastDeliveryAttemptAt !== undefined) {
500
+ sets.push('lastDeliveryAttemptAt = ?');
501
+ binds.push(isoOrNull(input.lastDeliveryAttemptAt));
502
+ }
503
+ if (input.lastDeliveryError !== undefined) {
504
+ sets.push('lastDeliveryError = ?');
505
+ binds.push(input.lastDeliveryError);
506
+ }
507
+ if (input.deliveredSignalId !== undefined) {
508
+ sets.push('deliveredSignalId = ?');
509
+ binds.push(input.deliveredSignalId);
510
+ }
511
+ if (input.summarySignalId !== undefined) {
512
+ sets.push('summarySignalId = ?');
513
+ binds.push(input.summarySignalId);
514
+ }
515
+ binds.push(input.threadId, input.id);
516
+ const updated = await this.#db
517
+ .prepare(`UPDATE ${this.#table}
518
+ SET ${sets.join(', ')}
519
+ WHERE thread_id = ? AND id = ?
520
+ RETURNING *`)
521
+ .bind(...binds)
522
+ .first();
523
+ if (!updated) {
524
+ throw new Error(`Notification ${input.id} was not found for thread ${input.threadId}`);
525
+ }
526
+ return rowToRecord(updated);
527
+ }
528
+ async dangerouslyClearAll() {
529
+ await this.#ensureSchema();
530
+ await this.#db.prepare(`DELETE FROM ${this.#table}`).run();
531
+ }
532
+ /** Build a `column IN (?, ?)` clause for a single value or an array filter. */
533
+ #pushIn(clauses, binds, column, filter) {
534
+ if (filter === undefined)
535
+ return;
536
+ const values = Array.isArray(filter) ? filter : [filter];
537
+ if (values.length === 0) {
538
+ clauses.push('0 = 1');
539
+ return;
540
+ }
541
+ clauses.push(`${column} IN (${values.map(() => '?').join(', ')})`);
542
+ binds.push(...values);
543
+ }
544
+ /**
545
+ * The first PENDING record on the same (threadId, source, kind, agentId,
546
+ * resourceId) whose dedupeKey OR coalesceKey matches — mirrors the reference's
547
+ * `.find`. The agentId/resourceId equality (including undefined-vs-undefined)
548
+ * is done in JS because SQL `= NULL` never matches; the candidate set is tiny
549
+ * (one thread's pending rows of one source/kind).
550
+ *
551
+ * Core's InMemory `.find` walks Map insertion order. insertionOrdinal
552
+ * preserves that order independently of caller-controlled createdAt; the
553
+ * nullable rowid fallback keeps legacy writers readable during rollback.
554
+ */
555
+ async #findCoalescableRow(input) {
556
+ if (!input.dedupeKey && !input.coalesceKey)
557
+ return undefined;
558
+ const match = this.#coalescableMatch(input);
559
+ const row = await this.#db
560
+ .prepare(`SELECT * FROM ${this.#table}
561
+ WHERE ${match.clause}
562
+ ORDER BY
563
+ insertionOrdinal IS NULL ASC,
564
+ insertionOrdinal ASC,
565
+ rowid ASC
566
+ LIMIT 1`)
567
+ .bind(...match.binds)
568
+ .first();
569
+ return row ?? undefined;
570
+ }
571
+ #coalescableMatch(input) {
572
+ return {
573
+ clause: `thread_id = ?
574
+ AND source = ?
575
+ AND kind = ?
576
+ AND status = 'pending'
577
+ AND agentId IS ?
578
+ AND resourceId IS ?
579
+ AND (
580
+ (? IS NOT NULL AND dedupeKey = ?)
581
+ OR (? IS NOT NULL AND coalesceKey = ?)
582
+ )`,
583
+ binds: [
584
+ input.threadId,
585
+ input.source,
586
+ input.kind,
587
+ input.agentId ?? null,
588
+ input.resourceId ?? null,
589
+ input.dedupeKey ?? null,
590
+ input.dedupeKey ?? null,
591
+ input.coalesceKey ?? null,
592
+ input.coalesceKey ?? null,
593
+ ],
594
+ };
595
+ }
596
+ async #insertUnlessCoalescable(record, input, insertionOrdinal) {
597
+ const match = this.#coalescableMatch(input);
598
+ const result = await this.#db
599
+ .prepare(`INSERT INTO ${this.#table} (${NOTIFICATION_COLUMNS.join(', ')}, insertionOrdinal)
600
+ SELECT ${NOTIFICATION_COLUMNS.map(() => '?').join(', ')}, ?
601
+ WHERE NOT EXISTS (
602
+ SELECT 1 FROM ${this.#table} WHERE ${match.clause}
603
+ )
604
+ ON CONFLICT(thread_id, id) DO UPDATE SET
605
+ ${NOTIFICATION_UPDATE_COLUMNS.map((column) => `${column} = excluded.${column}`).join(', ')}`)
606
+ .bind(...recordValues(record), insertionOrdinal, ...match.binds)
607
+ .run();
608
+ return d1Changes(result) > 0;
609
+ }
610
+ /** Upsert the public record while preserving its original insertion ordinal. */
611
+ async #insert(record, insertionOrdinal) {
612
+ await this.#db
613
+ .prepare(`INSERT INTO ${this.#table} (${NOTIFICATION_COLUMNS.join(', ')}, insertionOrdinal)
614
+ VALUES (${NOTIFICATION_COLUMNS.map(() => '?').join(', ')}, ?)
615
+ ON CONFLICT(thread_id, id) DO UPDATE SET
616
+ ${NOTIFICATION_UPDATE_COLUMNS.map((column) => `${column} = excluded.${column}`).join(', ')}`)
617
+ .bind(...recordValues(record), insertionOrdinal)
618
+ .run();
619
+ }
620
+ async #allocateInsertionOrdinal() {
621
+ const row = await this.#db
622
+ .prepare(`UPDATE ${this.#sequenceTable}
623
+ SET value = value + 1
624
+ WHERE id = 1
625
+ RETURNING value`)
626
+ .first();
627
+ if (!row || !Number.isSafeInteger(row.value) || row.value < 1) {
628
+ throw new Error('Notification insertion ordinal allocation failed');
629
+ }
630
+ return row.value;
631
+ }
632
+ }
633
+ function recordValues(record) {
634
+ return [
635
+ record.id,
636
+ record.threadId,
637
+ record.source,
638
+ record.kind,
639
+ record.priority,
640
+ record.status,
641
+ record.summary,
642
+ jsonOrNull(record.payload),
643
+ record.resourceId ?? null,
644
+ record.agentId ?? null,
645
+ record.sourceId ?? null,
646
+ record.dedupeKey ?? null,
647
+ record.coalesceKey ?? null,
648
+ record.coalescedCount ?? 1,
649
+ jsonOrNull(record.attributes),
650
+ record.createdAt.toISOString(),
651
+ record.updatedAt.toISOString(),
652
+ isoOrNull(record.deliverAt),
653
+ isoOrNull(record.summaryAt),
654
+ record.deliveryReason ?? null,
655
+ record.deliveryAttempts ?? 0,
656
+ isoOrNull(record.lastDeliveryAttemptAt),
657
+ record.lastDeliveryError ?? null,
658
+ record.deliveredSignalId ?? null,
659
+ record.summarySignalId ?? null,
660
+ isoOrNull(record.deliveredAt),
661
+ isoOrNull(record.seenAt),
662
+ isoOrNull(record.dismissedAt),
663
+ isoOrNull(record.archivedAt),
664
+ isoOrNull(record.discardedAt),
665
+ jsonOrNull(record.metadata),
666
+ ];
667
+ }
668
+ /** Map a stored row back to the core NotificationRecord shape. */
669
+ function rowToRecord(row) {
670
+ return {
671
+ id: row.id,
672
+ threadId: row.thread_id,
673
+ source: row.source,
674
+ kind: row.kind,
675
+ priority: row.priority,
676
+ status: row.status,
677
+ summary: row.summary,
678
+ payload: parseJsonOrUndefined(row.payload),
679
+ resourceId: row.resourceId ?? undefined,
680
+ agentId: row.agentId ?? undefined,
681
+ sourceId: row.sourceId ?? undefined,
682
+ dedupeKey: row.dedupeKey ?? undefined,
683
+ coalesceKey: row.coalesceKey ?? undefined,
684
+ coalescedCount: row.coalescedCount ?? undefined,
685
+ attributes: parseJsonOrUndefined(row.attributes),
686
+ createdAt: new Date(row.createdAt),
687
+ updatedAt: new Date(row.updatedAt),
688
+ deliverAt: dateOrUndefined(row.deliverAt),
689
+ summaryAt: dateOrUndefined(row.summaryAt),
690
+ deliveryReason: row.deliveryReason ?? undefined,
691
+ deliveryAttempts: row.deliveryAttempts ?? undefined,
692
+ lastDeliveryAttemptAt: dateOrUndefined(row.lastDeliveryAttemptAt),
693
+ lastDeliveryError: row.lastDeliveryError ?? undefined,
694
+ deliveredSignalId: row.deliveredSignalId ?? undefined,
695
+ summarySignalId: row.summarySignalId ?? undefined,
696
+ deliveredAt: dateOrUndefined(row.deliveredAt),
697
+ seenAt: dateOrUndefined(row.seenAt),
698
+ dismissedAt: dateOrUndefined(row.dismissedAt),
699
+ archivedAt: dateOrUndefined(row.archivedAt),
700
+ discardedAt: dateOrUndefined(row.discardedAt),
701
+ metadata: parseJsonOrUndefined(row.metadata),
702
+ };
703
+ }
704
+ //# sourceMappingURL=notifications-d1.js.map