@jam-overture/loom 0.1.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 (401) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +743 -0
  3. package/dist/catalogue.d.ts +70 -0
  4. package/dist/catalogue.js +88 -0
  5. package/dist/cli/args.d.ts +17 -0
  6. package/dist/cli/args.js +83 -0
  7. package/dist/cli/filesystem.d.ts +15 -0
  8. package/dist/cli/filesystem.js +31 -0
  9. package/dist/cli/index.d.ts +12 -0
  10. package/dist/cli/index.js +12 -0
  11. package/dist/cli/main.d.ts +3 -0
  12. package/dist/cli/main.js +30 -0
  13. package/dist/cli/namespace.d.ts +40 -0
  14. package/dist/cli/namespace.js +40 -0
  15. package/dist/cli/plan.d.ts +84 -0
  16. package/dist/cli/plan.js +113 -0
  17. package/dist/cli/run.d.ts +17 -0
  18. package/dist/cli/run.js +75 -0
  19. package/dist/cli/templates.d.ts +43 -0
  20. package/dist/cli/templates.js +134 -0
  21. package/dist/closed-set.d.ts +34 -0
  22. package/dist/closed-set.js +34 -0
  23. package/dist/data/adapter.d.ts +123 -0
  24. package/dist/data/adapter.js +91 -0
  25. package/dist/data/binding.d.ts +48 -0
  26. package/dist/data/binding.js +39 -0
  27. package/dist/data/catalogue.d.ts +26 -0
  28. package/dist/data/catalogue.js +6 -0
  29. package/dist/data/index.d.ts +14 -0
  30. package/dist/data/index.js +14 -0
  31. package/dist/data/plan.d.ts +58 -0
  32. package/dist/data/plan.js +0 -0
  33. package/dist/data/resolution.d.ts +91 -0
  34. package/dist/data/resolution.js +96 -0
  35. package/dist/data/resolve.d.ts +46 -0
  36. package/dist/data/resolve.js +37 -0
  37. package/dist/data/source.d.ts +40 -0
  38. package/dist/data/source.js +45 -0
  39. package/dist/deadline.d.ts +57 -0
  40. package/dist/deadline.js +78 -0
  41. package/dist/frame/catalogue.d.ts +24 -0
  42. package/dist/frame/catalogue.js +5 -0
  43. package/dist/frame/index.d.ts +12 -0
  44. package/dist/frame/index.js +12 -0
  45. package/dist/frame/origin.d.ts +87 -0
  46. package/dist/frame/origin.js +114 -0
  47. package/dist/frame/resolution.d.ts +85 -0
  48. package/dist/frame/resolution.js +79 -0
  49. package/dist/grammar.d.ts +26 -0
  50. package/dist/grammar.js +28 -0
  51. package/dist/ids.d.ts +57 -0
  52. package/dist/ids.js +104 -0
  53. package/dist/index.d.ts +26 -0
  54. package/dist/index.js +26 -0
  55. package/dist/interactivity.d.ts +50 -0
  56. package/dist/interactivity.js +22 -0
  57. package/dist/interpretation/anthropic.d.ts +22 -0
  58. package/dist/interpretation/anthropic.js +76 -0
  59. package/dist/interpretation/client.d.ts +83 -0
  60. package/dist/interpretation/client.js +2 -0
  61. package/dist/interpretation/draft.d.ts +234 -0
  62. package/dist/interpretation/draft.js +84 -0
  63. package/dist/interpretation/index.d.ts +15 -0
  64. package/dist/interpretation/index.js +15 -0
  65. package/dist/interpretation/interpreter.d.ts +62 -0
  66. package/dist/interpretation/interpreter.js +151 -0
  67. package/dist/interpretation/materialize.d.ts +42 -0
  68. package/dist/interpretation/materialize.js +107 -0
  69. package/dist/interpretation/prompt.d.ts +229 -0
  70. package/dist/interpretation/prompt.js +285 -0
  71. package/dist/interpretation/render.d.ts +76 -0
  72. package/dist/interpretation/render.js +272 -0
  73. package/dist/interpretation/schema.d.ts +49 -0
  74. package/dist/interpretation/schema.js +131 -0
  75. package/dist/json.d.ts +35 -0
  76. package/dist/json.js +11 -0
  77. package/dist/paging.d.ts +60 -0
  78. package/dist/paging.js +49 -0
  79. package/dist/primitive-type.d.ts +32 -0
  80. package/dist/primitive-type.js +39 -0
  81. package/dist/render/addressing.d.ts +59 -0
  82. package/dist/render/addressing.js +60 -0
  83. package/dist/render/anchor.d.ts +105 -0
  84. package/dist/render/anchor.js +84 -0
  85. package/dist/render/behaviour-adjust.d.ts +62 -0
  86. package/dist/render/behaviour-adjust.js +78 -0
  87. package/dist/render/behaviour-copy.d.ts +53 -0
  88. package/dist/render/behaviour-copy.js +75 -0
  89. package/dist/render/behaviour-disclose.d.ts +74 -0
  90. package/dist/render/behaviour-disclose.js +77 -0
  91. package/dist/render/behaviour-present.d.ts +123 -0
  92. package/dist/render/behaviour-present.js +173 -0
  93. package/dist/render/behaviour.d.ts +243 -0
  94. package/dist/render/behaviour.js +284 -0
  95. package/dist/render/control.d.ts +81 -0
  96. package/dist/render/control.js +80 -0
  97. package/dist/render/decorative.d.ts +62 -0
  98. package/dist/render/decorative.js +2 -0
  99. package/dist/render/diagnostics.d.ts +260 -0
  100. package/dist/render/diagnostics.js +61 -0
  101. package/dist/render/disclosed.d.ts +37 -0
  102. package/dist/render/disclosed.js +37 -0
  103. package/dist/render/editable.d.ts +34 -0
  104. package/dist/render/editable.js +35 -0
  105. package/dist/render/frame.d.ts +42 -0
  106. package/dist/render/frame.js +31 -0
  107. package/dist/render/index.d.ts +35 -0
  108. package/dist/render/index.js +35 -0
  109. package/dist/render/inline-variables.d.ts +77 -0
  110. package/dist/render/inline-variables.js +220 -0
  111. package/dist/render/presented.d.ts +82 -0
  112. package/dist/render/presented.js +82 -0
  113. package/dist/render/primitive.d.ts +228 -0
  114. package/dist/render/primitive.js +36 -0
  115. package/dist/render/props.d.ts +48 -0
  116. package/dist/render/props.js +2 -0
  117. package/dist/render/reads.d.ts +73 -0
  118. package/dist/render/reads.js +45 -0
  119. package/dist/render/render.d.ts +164 -0
  120. package/dist/render/render.js +571 -0
  121. package/dist/render/request.d.ts +111 -0
  122. package/dist/render/request.js +60 -0
  123. package/dist/render/text.d.ts +91 -0
  124. package/dist/render/text.js +44 -0
  125. package/dist/render/theme.d.ts +61 -0
  126. package/dist/render/theme.js +52 -0
  127. package/dist/reserved-props.d.ts +35 -0
  128. package/dist/reserved-props.js +45 -0
  129. package/dist/result.d.ts +27 -0
  130. package/dist/result.js +30 -0
  131. package/dist/role.d.ts +71 -0
  132. package/dist/role.js +22 -0
  133. package/dist/runtime/analysis.d.ts +149 -0
  134. package/dist/runtime/analysis.js +187 -0
  135. package/dist/runtime/assessment.d.ts +35 -0
  136. package/dist/runtime/assessment.js +13 -0
  137. package/dist/runtime/disposition.d.ts +102 -0
  138. package/dist/runtime/disposition.js +59 -0
  139. package/dist/runtime/events.d.ts +187 -0
  140. package/dist/runtime/events.js +7 -0
  141. package/dist/runtime/gate.d.ts +43 -0
  142. package/dist/runtime/gate.js +169 -0
  143. package/dist/runtime/index.d.ts +27 -0
  144. package/dist/runtime/index.js +27 -0
  145. package/dist/runtime/intent.d.ts +60 -0
  146. package/dist/runtime/intent.js +36 -0
  147. package/dist/runtime/interpreter.d.ts +117 -0
  148. package/dist/runtime/interpreter.js +46 -0
  149. package/dist/runtime/inverse-interpreter.d.ts +90 -0
  150. package/dist/runtime/inverse-interpreter.js +56 -0
  151. package/dist/runtime/inverse.d.ts +87 -0
  152. package/dist/runtime/inverse.js +48 -0
  153. package/dist/runtime/narration.d.ts +24 -0
  154. package/dist/runtime/narration.js +36 -0
  155. package/dist/runtime/nesting.d.ts +31 -0
  156. package/dist/runtime/nesting.js +46 -0
  157. package/dist/runtime/pipeline.d.ts +124 -0
  158. package/dist/runtime/pipeline.js +178 -0
  159. package/dist/runtime/policy-fingerprint.d.ts +29 -0
  160. package/dist/runtime/policy-fingerprint.js +119 -0
  161. package/dist/runtime/policy-source.d.ts +42 -0
  162. package/dist/runtime/policy-source.js +8 -0
  163. package/dist/runtime/policy.d.ts +156 -0
  164. package/dist/runtime/policy.js +107 -0
  165. package/dist/runtime/proposal.d.ts +423 -0
  166. package/dist/runtime/proposal.js +109 -0
  167. package/dist/runtime/redirection.d.ts +53 -0
  168. package/dist/runtime/redirection.js +38 -0
  169. package/dist/runtime/repointing.d.ts +71 -0
  170. package/dist/runtime/repointing.js +0 -0
  171. package/dist/runtime/reversibility.d.ts +36 -0
  172. package/dist/runtime/reversibility.js +39 -0
  173. package/dist/runtime/stake-level.d.ts +33 -0
  174. package/dist/runtime/stake-level.js +58 -0
  175. package/dist/runtime/stakes.d.ts +47 -0
  176. package/dist/runtime/stakes.js +305 -0
  177. package/dist/runtime/vocabulary.d.ts +122 -0
  178. package/dist/runtime/vocabulary.js +87 -0
  179. package/dist/sdk/audit.d.ts +195 -0
  180. package/dist/sdk/audit.js +128 -0
  181. package/dist/sdk/catalogue.d.ts +37 -0
  182. package/dist/sdk/catalogue.js +16 -0
  183. package/dist/sdk/conformance.d.ts +342 -0
  184. package/dist/sdk/conformance.js +494 -0
  185. package/dist/sdk/copy.d.ts +105 -0
  186. package/dist/sdk/copy.js +90 -0
  187. package/dist/sdk/definition.d.ts +242 -0
  188. package/dist/sdk/definition.js +64 -0
  189. package/dist/sdk/index.d.ts +19 -0
  190. package/dist/sdk/index.js +19 -0
  191. package/dist/sdk/interactivity.d.ts +29 -0
  192. package/dist/sdk/interactivity.js +34 -0
  193. package/dist/sdk/pairings.d.ts +124 -0
  194. package/dist/sdk/pairings.js +81 -0
  195. package/dist/sdk/registry.d.ts +162 -0
  196. package/dist/sdk/registry.js +329 -0
  197. package/dist/sdk/selection.d.ts +46 -0
  198. package/dist/sdk/selection.js +24 -0
  199. package/dist/sdk/text.d.ts +100 -0
  200. package/dist/sdk/text.js +105 -0
  201. package/dist/sdk/vocabulary.d.ts +39 -0
  202. package/dist/sdk/vocabulary.js +36 -0
  203. package/dist/signals/broadcast.d.ts +134 -0
  204. package/dist/signals/broadcast.js +451 -0
  205. package/dist/signals/collect.d.ts +184 -0
  206. package/dist/signals/collect.js +196 -0
  207. package/dist/signals/deliver.d.ts +64 -0
  208. package/dist/signals/deliver.js +85 -0
  209. package/dist/signals/fold.d.ts +112 -0
  210. package/dist/signals/fold.js +76 -0
  211. package/dist/signals/index.d.ts +31 -0
  212. package/dist/signals/index.js +31 -0
  213. package/dist/signals/ingest.d.ts +51 -0
  214. package/dist/signals/ingest.js +70 -0
  215. package/dist/signals/intake.d.ts +149 -0
  216. package/dist/signals/intake.js +154 -0
  217. package/dist/signals/journal.d.ts +94 -0
  218. package/dist/signals/journal.js +11 -0
  219. package/dist/signals/kinds.d.ts +22 -0
  220. package/dist/signals/kinds.js +22 -0
  221. package/dist/signals/ledger.d.ts +46 -0
  222. package/dist/signals/ledger.js +81 -0
  223. package/dist/signals/memory.d.ts +17 -0
  224. package/dist/signals/memory.js +99 -0
  225. package/dist/signals/migrate.d.ts +27 -0
  226. package/dist/signals/migrate.js +78 -0
  227. package/dist/signals/postgres.d.ts +7 -0
  228. package/dist/signals/postgres.js +295 -0
  229. package/dist/signals/rollup.d.ts +142 -0
  230. package/dist/signals/rollup.js +0 -0
  231. package/dist/signals/schema.d.ts +534 -0
  232. package/dist/signals/schema.js +92 -0
  233. package/dist/signals/signal.d.ts +381 -0
  234. package/dist/signals/signal.js +150 -0
  235. package/dist/signals/tally.d.ts +70 -0
  236. package/dist/signals/tally.js +2 -0
  237. package/dist/signals/view.d.ts +51 -0
  238. package/dist/signals/view.js +54 -0
  239. package/dist/store/attribution.d.ts +125 -0
  240. package/dist/store/attribution.js +116 -0
  241. package/dist/store/database.d.ts +14 -0
  242. package/dist/store/database.js +2 -0
  243. package/dist/store/driver.d.ts +29 -0
  244. package/dist/store/driver.js +39 -0
  245. package/dist/store/errors.d.ts +56 -0
  246. package/dist/store/errors.js +37 -0
  247. package/dist/store/index.d.ts +16 -0
  248. package/dist/store/index.js +16 -0
  249. package/dist/store/memory.d.ts +3 -0
  250. package/dist/store/memory.js +115 -0
  251. package/dist/store/migrate.d.ts +54 -0
  252. package/dist/store/migrate.js +122 -0
  253. package/dist/store/postgres-holds.d.ts +4 -0
  254. package/dist/store/postgres-holds.js +192 -0
  255. package/dist/store/postgres.d.ts +8 -0
  256. package/dist/store/postgres.js +262 -0
  257. package/dist/store/replay.d.ts +94 -0
  258. package/dist/store/replay.js +82 -0
  259. package/dist/store/revert.d.ts +116 -0
  260. package/dist/store/revert.js +243 -0
  261. package/dist/store/schema.d.ts +371 -0
  262. package/dist/store/schema.js +78 -0
  263. package/dist/store/source.d.ts +23 -0
  264. package/dist/store/source.js +37 -0
  265. package/dist/store/store.d.ts +231 -0
  266. package/dist/store/store.js +52 -0
  267. package/dist/store/undone.d.ts +18 -0
  268. package/dist/store/undone.js +89 -0
  269. package/dist/submit/catalogue.d.ts +20 -0
  270. package/dist/submit/catalogue.js +5 -0
  271. package/dist/submit/declaration.d.ts +39 -0
  272. package/dist/submit/declaration.js +30 -0
  273. package/dist/submit/endpoint.d.ts +131 -0
  274. package/dist/submit/endpoint.js +160 -0
  275. package/dist/submit/index.d.ts +13 -0
  276. package/dist/submit/index.js +13 -0
  277. package/dist/submit/plan.d.ts +49 -0
  278. package/dist/submit/plan.js +47 -0
  279. package/dist/submit/resolution.d.ts +61 -0
  280. package/dist/submit/resolution.js +64 -0
  281. package/dist/submit/resolve.d.ts +45 -0
  282. package/dist/submit/resolve.js +36 -0
  283. package/dist/telemetry/calibration.d.ts +132 -0
  284. package/dist/telemetry/calibration.js +151 -0
  285. package/dist/telemetry/episode.d.ts +140 -0
  286. package/dist/telemetry/episode.js +272 -0
  287. package/dist/telemetry/event.d.ts +2310 -0
  288. package/dist/telemetry/event.js +405 -0
  289. package/dist/telemetry/index.d.ts +15 -0
  290. package/dist/telemetry/index.js +15 -0
  291. package/dist/telemetry/journal.d.ts +116 -0
  292. package/dist/telemetry/journal.js +11 -0
  293. package/dist/telemetry/memory.d.ts +24 -0
  294. package/dist/telemetry/memory.js +75 -0
  295. package/dist/telemetry/migrate.d.ts +26 -0
  296. package/dist/telemetry/migrate.js +40 -0
  297. package/dist/telemetry/postgres.d.ts +6 -0
  298. package/dist/telemetry/postgres.js +139 -0
  299. package/dist/telemetry/retention.d.ts +131 -0
  300. package/dist/telemetry/retention.js +217 -0
  301. package/dist/telemetry/schema.d.ts +113 -0
  302. package/dist/telemetry/schema.js +33 -0
  303. package/dist/telemetry/sink.d.ts +42 -0
  304. package/dist/telemetry/sink.js +61 -0
  305. package/dist/testing/contracts.d.ts +34 -0
  306. package/dist/testing/contracts.js +34 -0
  307. package/dist/testing/definitions.d.ts +15 -0
  308. package/dist/testing/definitions.js +48 -0
  309. package/dist/testing/doubles.d.ts +94 -0
  310. package/dist/testing/doubles.js +141 -0
  311. package/dist/testing/episode-harness.d.ts +49 -0
  312. package/dist/testing/episode-harness.js +65 -0
  313. package/dist/testing/filesystem.d.ts +17 -0
  314. package/dist/testing/filesystem.js +17 -0
  315. package/dist/testing/fixtures.d.ts +57 -0
  316. package/dist/testing/fixtures.js +84 -0
  317. package/dist/testing/hold-contract.d.ts +19 -0
  318. package/dist/testing/hold-contract.js +374 -0
  319. package/dist/testing/index.d.ts +41 -0
  320. package/dist/testing/index.js +41 -0
  321. package/dist/testing/journal-contract.d.ts +17 -0
  322. package/dist/testing/journal-contract.js +353 -0
  323. package/dist/testing/model-replies.d.ts +34 -0
  324. package/dist/testing/model-replies.js +101 -0
  325. package/dist/testing/primitives.d.ts +7 -0
  326. package/dist/testing/primitives.js +29 -0
  327. package/dist/testing/reader-signal-contract.d.ts +38 -0
  328. package/dist/testing/reader-signal-contract.js +318 -0
  329. package/dist/testing/row-security.d.ts +17 -0
  330. package/dist/testing/row-security.js +21 -0
  331. package/dist/testing/store-contract.d.ts +25 -0
  332. package/dist/testing/store-contract.js +500 -0
  333. package/dist/theme/apply.d.ts +17 -0
  334. package/dist/theme/apply.js +60 -0
  335. package/dist/theme/contrast.d.ts +197 -0
  336. package/dist/theme/contrast.js +259 -0
  337. package/dist/theme/derive.d.ts +77 -0
  338. package/dist/theme/derive.js +167 -0
  339. package/dist/theme/faces.d.ts +73 -0
  340. package/dist/theme/faces.js +119 -0
  341. package/dist/theme/font-packs.d.ts +25 -0
  342. package/dist/theme/font-packs.js +257 -0
  343. package/dist/theme/index.d.ts +20 -0
  344. package/dist/theme/index.js +20 -0
  345. package/dist/theme/lab.d.ts +30 -0
  346. package/dist/theme/lab.js +46 -0
  347. package/dist/theme/library.d.ts +114 -0
  348. package/dist/theme/library.js +300 -0
  349. package/dist/theme/measure.d.ts +144 -0
  350. package/dist/theme/measure.js +145 -0
  351. package/dist/theme/palettes.d.ts +64 -0
  352. package/dist/theme/palettes.js +497 -0
  353. package/dist/theme/registry.d.ts +59 -0
  354. package/dist/theme/registry.js +60 -0
  355. package/dist/theme/separation.d.ts +177 -0
  356. package/dist/theme/separation.js +203 -0
  357. package/dist/theme/style-presets.d.ts +60 -0
  358. package/dist/theme/style-presets.js +124 -0
  359. package/dist/theme/theme.d.ts +253 -0
  360. package/dist/theme/theme.js +171 -0
  361. package/dist/tree/apply.d.ts +16 -0
  362. package/dist/tree/apply.js +104 -0
  363. package/dist/tree/builders.d.ts +19 -0
  364. package/dist/tree/builders.js +20 -0
  365. package/dist/tree/compare.d.ts +68 -0
  366. package/dist/tree/compare.js +75 -0
  367. package/dist/tree/configuration.d.ts +25 -0
  368. package/dist/tree/configuration.js +108 -0
  369. package/dist/tree/delta.d.ts +288 -0
  370. package/dist/tree/delta.js +88 -0
  371. package/dist/tree/errors.d.ts +69 -0
  372. package/dist/tree/errors.js +34 -0
  373. package/dist/tree/identity.d.ts +117 -0
  374. package/dist/tree/identity.js +145 -0
  375. package/dist/tree/index.d.ts +21 -0
  376. package/dist/tree/index.js +21 -0
  377. package/dist/tree/inverse.d.ts +24 -0
  378. package/dist/tree/inverse.js +112 -0
  379. package/dist/tree/mutation.d.ts +18 -0
  380. package/dist/tree/mutation.js +49 -0
  381. package/dist/tree/naming.d.ts +4 -0
  382. package/dist/tree/naming.js +35 -0
  383. package/dist/tree/navigation.d.ts +38 -0
  384. package/dist/tree/navigation.js +83 -0
  385. package/dist/tree/node.d.ts +103 -0
  386. package/dist/tree/node.js +46 -0
  387. package/dist/tree/outline.d.ts +28 -0
  388. package/dist/tree/outline.js +10 -0
  389. package/dist/tree/tree.d.ts +83 -0
  390. package/dist/tree/tree.js +62 -0
  391. package/dist/write/commit.d.ts +124 -0
  392. package/dist/write/commit.js +234 -0
  393. package/dist/write/held.d.ts +674 -0
  394. package/dist/write/held.js +185 -0
  395. package/dist/write/index.d.ts +11 -0
  396. package/dist/write/index.js +11 -0
  397. package/dist/write/liveness.d.ts +132 -0
  398. package/dist/write/liveness.js +91 -0
  399. package/dist/write/revert.d.ts +79 -0
  400. package/dist/write/revert.js +134 -0
  401. package/package.json +160 -0
@@ -0,0 +1,54 @@
1
+ import type { LoomDatabase } from "./database.js";
2
+ /**
3
+ * Creating the tables the postgres store expects.
4
+ *
5
+ * Not a migration framework: one version of the schema, stated as statements a
6
+ * host runs once, and safe to run again.
7
+ */
8
+ /**
9
+ * The schema, as statements a host can run.
10
+ *
11
+ * One statement per entry, because a driver may refuse several commands in a
12
+ * single prepared statement — PGlite does, and so does any connection in
13
+ * transaction-pooling mode, which is exactly the configuration 0022 requires on
14
+ * serverless. Splitting them is not a workaround for the test environment; it is
15
+ * the shape that works everywhere.
16
+ *
17
+ * This is deliberately not a migration framework. There is one version of this
18
+ * schema and no upgrade path yet, so a list of idempotent statements is the
19
+ * honest amount of machinery. When the schema changes in a way that needs data
20
+ * moved, that is when it earns a real migration tool.
21
+ */
22
+ export declare const TREE_STORE_DDL: readonly string[];
23
+ /**
24
+ * The hold store's schema, as statements a host can run.
25
+ *
26
+ * Its own list rather than three more entries on the one above, because the two
27
+ * stores are separately useful: a host that never lets the Gate hold anything
28
+ * has no reason to carry the table, and a host that only reviews has no reason
29
+ * to be told about the log. Each store owns its schema and a deployment says
30
+ * which it wants.
31
+ *
32
+ * Neither index is decoration, and they answer different questions. `forTree`
33
+ * reads one tree's queue, so without the first it scans every hold in the
34
+ * database including every other tree's. `waiting` reads the whole deployment's
35
+ * queue a page at a time, in `(held_at, proposal_id)` order — the second index
36
+ * is what makes that one seek rather than a sort over everything held, which is
37
+ * the entire reason the read exists.
38
+ */
39
+ export declare const HOLD_STORE_DDL: readonly string[];
40
+ /**
41
+ * Creates the tables if they are absent. Every statement is `IF NOT EXISTS`, so
42
+ * running it against a populated database is a no-op rather than a hazard.
43
+ */
44
+ export declare const ensureTreeStoreSchema: (db: LoomDatabase) => Promise<void>;
45
+ /**
46
+ * Creates the hold table if it is absent. Idempotent on the same terms.
47
+ *
48
+ * Separate from `ensureTreeStoreSchema` rather than folded into it: a deployment
49
+ * that upgrades gets the table by adding this call, which is a change it made on
50
+ * purpose, instead of by a function whose name promises trees quietly creating
51
+ * something else.
52
+ */
53
+ export declare const ensureHoldStoreSchema: (db: LoomDatabase) => Promise<void>;
54
+ //# sourceMappingURL=migrate.d.ts.map
@@ -0,0 +1,122 @@
1
+ import { sql } from "drizzle-orm";
2
+ /**
3
+ * Creating the tables the postgres store expects.
4
+ *
5
+ * Not a migration framework: one version of the schema, stated as statements a
6
+ * host runs once, and safe to run again.
7
+ */
8
+ /**
9
+ * The schema, as statements a host can run.
10
+ *
11
+ * One statement per entry, because a driver may refuse several commands in a
12
+ * single prepared statement — PGlite does, and so does any connection in
13
+ * transaction-pooling mode, which is exactly the configuration 0022 requires on
14
+ * serverless. Splitting them is not a workaround for the test environment; it is
15
+ * the shape that works everywhere.
16
+ *
17
+ * This is deliberately not a migration framework. There is one version of this
18
+ * schema and no upgrade path yet, so a list of idempotent statements is the
19
+ * honest amount of machinery. When the schema changes in a way that needs data
20
+ * moved, that is when it earns a real migration tool.
21
+ */
22
+ export const TREE_STORE_DDL = [
23
+ `CREATE TABLE IF NOT EXISTS loom_trees (
24
+ tree_id text PRIMARY KEY,
25
+ revision integer NOT NULL,
26
+ document jsonb NOT NULL,
27
+ updated_at timestamptz NOT NULL DEFAULT now()
28
+ )`,
29
+ `CREATE TABLE IF NOT EXISTS loom_revisions (
30
+ tree_id text NOT NULL,
31
+ revision integer NOT NULL,
32
+ proposal_id text NOT NULL,
33
+ delta jsonb NOT NULL,
34
+ provenance jsonb NOT NULL,
35
+ applied_at text NOT NULL,
36
+ answered_by text,
37
+ PRIMARY KEY (tree_id, revision)
38
+ )`,
39
+ /**
40
+ * For a database that already has the table: `CREATE TABLE IF NOT EXISTS`
41
+ * silently leaves an existing table alone, columns and all, so a column added
42
+ * after the first deployment needs its own statement or it only ever appears
43
+ * on new databases. `IF NOT EXISTS` keeps it a no-op everywhere else.
44
+ */
45
+ `ALTER TABLE loom_revisions ADD COLUMN IF NOT EXISTS answered_by text`,
46
+ /**
47
+ * Locking the tables is part of creating them, not a step in a document.
48
+ *
49
+ * On a managed Postgres that fronts the `public` schema with a REST API — the
50
+ * kind of host Loom targets (0022) — a new table is world-readable through a public key the
51
+ * moment it exists. That has been a manual step in `docs/deployment.md` since
52
+ * the first table, and it has been carried as an open item in every report
53
+ * since the second one, which is the evidence that a manual step is the wrong
54
+ * shape for it. A table Loom creates should not have a window in which it is
55
+ * exposed.
56
+ *
57
+ * No policies accompany this, deliberately. RLS with no policy denies every
58
+ * role except the table's owner, and the owner is who Loom connects as: the
59
+ * runtime is on plain SQL rather than on the REST layer (0022), so the effect
60
+ * is to close the door Loom never uses. A host that connects as some other role
61
+ * is outside that contract and has to grant itself a policy — stated here and
62
+ * in `docs/deployment.md`, because it fails closed and a closed door is a
63
+ * thing you want to have been told about.
64
+ */
65
+ `ALTER TABLE loom_trees ENABLE ROW LEVEL SECURITY`,
66
+ `ALTER TABLE loom_revisions ENABLE ROW LEVEL SECURITY`,
67
+ ];
68
+ /**
69
+ * The hold store's schema, as statements a host can run.
70
+ *
71
+ * Its own list rather than three more entries on the one above, because the two
72
+ * stores are separately useful: a host that never lets the Gate hold anything
73
+ * has no reason to carry the table, and a host that only reviews has no reason
74
+ * to be told about the log. Each store owns its schema and a deployment says
75
+ * which it wants.
76
+ *
77
+ * Neither index is decoration, and they answer different questions. `forTree`
78
+ * reads one tree's queue, so without the first it scans every hold in the
79
+ * database including every other tree's. `waiting` reads the whole deployment's
80
+ * queue a page at a time, in `(held_at, proposal_id)` order — the second index
81
+ * is what makes that one seek rather than a sort over everything held, which is
82
+ * the entire reason the read exists.
83
+ */
84
+ export const HOLD_STORE_DDL = [
85
+ `CREATE TABLE IF NOT EXISTS loom_holds (
86
+ proposal_id text PRIMARY KEY,
87
+ tree_id text NOT NULL,
88
+ base_revision integer NOT NULL,
89
+ intent jsonb NOT NULL,
90
+ proposal jsonb NOT NULL,
91
+ disposition jsonb NOT NULL,
92
+ held_at text NOT NULL
93
+ )`,
94
+ `CREATE INDEX IF NOT EXISTS loom_holds_tree_id_held_at_idx ON loom_holds (tree_id, held_at)`,
95
+ `CREATE INDEX IF NOT EXISTS loom_holds_held_at_proposal_id_idx ON loom_holds (held_at, proposal_id)`,
96
+ /** Locked on creation for the reason the tree store's tables are — see above. */
97
+ `ALTER TABLE loom_holds ENABLE ROW LEVEL SECURITY`,
98
+ ];
99
+ /**
100
+ * Creates the tables if they are absent. Every statement is `IF NOT EXISTS`, so
101
+ * running it against a populated database is a no-op rather than a hazard.
102
+ */
103
+ export const ensureTreeStoreSchema = async (db) => {
104
+ await runStatements(db, TREE_STORE_DDL);
105
+ };
106
+ /**
107
+ * Creates the hold table if it is absent. Idempotent on the same terms.
108
+ *
109
+ * Separate from `ensureTreeStoreSchema` rather than folded into it: a deployment
110
+ * that upgrades gets the table by adding this call, which is a change it made on
111
+ * purpose, instead of by a function whose name promises trees quietly creating
112
+ * something else.
113
+ */
114
+ export const ensureHoldStoreSchema = async (db) => {
115
+ await runStatements(db, HOLD_STORE_DDL);
116
+ };
117
+ const runStatements = async (db, statements) => {
118
+ for (const statement of statements) {
119
+ await db.execute(sql.raw(statement));
120
+ }
121
+ };
122
+ //# sourceMappingURL=migrate.js.map
@@ -0,0 +1,4 @@
1
+ import { type HoldStore } from "../write/held.js";
2
+ import type { LoomDatabase } from "./database.js";
3
+ export declare const postgresHoldStore: (db: LoomDatabase) => HoldStore;
4
+ //# sourceMappingURL=postgres-holds.d.ts.map
@@ -0,0 +1,192 @@
1
+ import { asc, eq, sql } from "drizzle-orm";
2
+ import { err, ok } from "../result.js";
3
+ import { clampHoldLimit, describeHoldError, holdCursor, holdCursorPosition, holdPosition, parseHeldProposal, } from "../write/held.js";
4
+ import { isUniqueViolation, unavailable } from "./driver.js";
5
+ import { loomHolds } from "./schema.js";
6
+ /**
7
+ * Custody of held proposals, backed by Postgres (0022).
8
+ *
9
+ * The counterpart `memoryHoldStore` was always going to need. A hold has to
10
+ * survive the request that produced it, because the human who answers it arrives
11
+ * later — and on the serverless hosts §3 targets, the process that produced it is
12
+ * usually gone before they get there. A `Map` keeps that promise on a long-lived
13
+ * server and cannot keep it anywhere else.
14
+ *
15
+ * Like the tree store, the handle is injected: choosing a driver, a pooler and a
16
+ * connection lifetime belongs to the host, and injecting it is what lets the
17
+ * tests run this exact code against an embedded Postgres.
18
+ */
19
+ /**
20
+ * A row on the way out, checked rather than cast.
21
+ *
22
+ * The three JSON columns were written by whatever version of the code was
23
+ * running at the time, and a hold is the shape most likely to outlive its
24
+ * writer: it is created by one deployment and answered by whichever one is
25
+ * serving when the reviewer returns.
26
+ */
27
+ const toHeld = (row) => parseHeldProposal({
28
+ proposalId: row.proposalId,
29
+ treeId: row.treeId,
30
+ baseRevision: row.baseRevision,
31
+ intent: row.intent,
32
+ proposal: row.proposal,
33
+ disposition: row.disposition,
34
+ heldAt: row.heldAt,
35
+ });
36
+ /**
37
+ * `compareHolds`, in the one place it has to be restated rather than called:
38
+ * ordering happens in the statement so an index can serve it, and the contract
39
+ * suite is what holds this and the in-memory comparator to the same answer.
40
+ */
41
+ const HOLD_ORDER = [asc(loomHolds.heldAt), asc(loomHolds.proposalId)];
42
+ /**
43
+ * Splits a page of rows into the holds it read and the rows it could not.
44
+ *
45
+ * The rule is 0175's and it turns on the two columns the index orders by. A row
46
+ * whose position parses can always be named and always be paged past, so it is
47
+ * skipped and reported: the change it was hiding is one row, and every other
48
+ * change against that page stays on the queue where a reviewer can answer it.
49
+ *
50
+ * A row whose *position* does not parse is a different fault and fails the
51
+ * whole listing. Skipping it would mean minting a cursor from something that is
52
+ * not a position — a value the next request cannot read, which starts it again
53
+ * at the beginning and pages forever. There is no honest way to step over a row
54
+ * the ordering cannot place, so the listing says so instead.
55
+ */
56
+ const parseAll = (rows) => {
57
+ const held = [];
58
+ const unreadable = [];
59
+ for (const row of rows) {
60
+ const position = holdPosition(row);
61
+ if (position === undefined)
62
+ return err({
63
+ code: "unreadable",
64
+ detail: `a stored hold could not be placed in the queue: ${row.proposalId} held at ${row.heldAt}`,
65
+ });
66
+ const parsed = toHeld(row);
67
+ if (parsed.ok)
68
+ held.push(parsed.value);
69
+ else
70
+ unreadable.push({ ...position, detail: describeHoldError(parsed.error) });
71
+ }
72
+ return ok({ held, unreadable });
73
+ };
74
+ /**
75
+ * The position a page resumes from: the last row the window read, readable or
76
+ * not.
77
+ *
78
+ * Taking it from the last *parsed* hold is the bug that skipping would
79
+ * otherwise introduce, and it is worse than the behaviour it replaces. A page
80
+ * whose final rows were all unreadable would resume before them and report them
81
+ * again forever; a page whose rows were *all* unreadable would have no last
82
+ * hold at all, so the cursor would come back `null` and every hold after them
83
+ * would drop off the queue — the whole fault this change exists to remove,
84
+ * moved one page along.
85
+ */
86
+ const pageEnd = (rows) => {
87
+ const last = rows.at(-1);
88
+ return last === undefined ? undefined : holdPosition(last);
89
+ };
90
+ export const postgresHoldStore = (db) => ({
91
+ hold: async (held) => {
92
+ try {
93
+ await db.insert(loomHolds).values({
94
+ proposalId: held.proposalId,
95
+ treeId: held.treeId,
96
+ baseRevision: held.baseRevision,
97
+ intent: held.intent,
98
+ proposal: held.proposal,
99
+ disposition: held.disposition,
100
+ heldAt: held.heldAt,
101
+ });
102
+ return ok(held);
103
+ }
104
+ catch (cause) {
105
+ /**
106
+ * The primary key on `proposal_id` is what makes "already held" a fact the
107
+ * database establishes rather than a check this code races against. Two
108
+ * requests holding the same proposal cannot both win, and the loser arrives
109
+ * here rather than overwriting a hold somebody may already be reading.
110
+ */
111
+ return isUniqueViolation(cause)
112
+ ? err({ code: "already-held", proposalId: held.proposalId })
113
+ : err(unavailable(cause, `could not hold ${held.proposalId}`));
114
+ }
115
+ },
116
+ get: async (proposalId) => {
117
+ try {
118
+ const rows = await db.select().from(loomHolds).where(eq(loomHolds.proposalId, proposalId)).limit(1);
119
+ const row = rows[0];
120
+ return row === undefined ? err({ code: "not-held", proposalId }) : toHeld(row);
121
+ }
122
+ catch (cause) {
123
+ return err(unavailable(cause, `could not read the hold on ${proposalId}`));
124
+ }
125
+ },
126
+ forTree: async (treeId) => {
127
+ try {
128
+ const rows = await db
129
+ .select()
130
+ .from(loomHolds)
131
+ .where(eq(loomHolds.treeId, treeId))
132
+ .orderBy(...HOLD_ORDER);
133
+ return parseAll(rows);
134
+ }
135
+ catch (cause) {
136
+ return err(unavailable(cause, `could not list what is held against ${treeId}`));
137
+ }
138
+ },
139
+ waiting: async (request) => {
140
+ const limit = clampHoldLimit(request?.limit);
141
+ const from = holdCursorPosition(request?.cursor);
142
+ try {
143
+ const rows = await db
144
+ .select()
145
+ .from(loomHolds)
146
+ /**
147
+ * A row-value comparison, which is `compareHolds` said in SQL: Postgres
148
+ * compares the tuple left to right, so this is "later than that instant,
149
+ * or the same instant under a later id" without writing that out as
150
+ * three predicates one of which will eventually be wrong.
151
+ */
152
+ .where(from === undefined
153
+ ? undefined
154
+ : sql `(${loomHolds.heldAt}, ${loomHolds.proposalId}) > (${from.heldAt}, ${from.proposalId})`)
155
+ .orderBy(...HOLD_ORDER)
156
+ /** One extra row answers "is there another page" without a count. */
157
+ .limit(limit + 1);
158
+ const inPage = rows.slice(0, limit);
159
+ const parsed = parseAll(inPage);
160
+ if (!parsed.ok)
161
+ return parsed;
162
+ const last = pageEnd(inPage);
163
+ return ok({
164
+ ...parsed.value,
165
+ cursor: rows.length > limit && last !== undefined ? holdCursor(last) : null,
166
+ });
167
+ }
168
+ catch (cause) {
169
+ return err(unavailable(cause, "could not list what is held"));
170
+ }
171
+ },
172
+ /**
173
+ * One statement, because `release` is a take rather than a read.
174
+ *
175
+ * `DELETE … RETURNING` is what makes answering happen exactly once a property
176
+ * of the database instead of a rule this code has to be trusted to follow: a
177
+ * select-then-delete would let two reviewers confirming at the same moment both
178
+ * come away holding the same change, and both apply it. The in-memory store
179
+ * gets that from being single-threaded; here it has to come from the statement.
180
+ */
181
+ release: async (proposalId) => {
182
+ try {
183
+ const rows = await db.delete(loomHolds).where(eq(loomHolds.proposalId, proposalId)).returning();
184
+ const row = rows[0];
185
+ return row === undefined ? err({ code: "not-held", proposalId }) : toHeld(row);
186
+ }
187
+ catch (cause) {
188
+ return err(unavailable(cause, `could not release ${proposalId}`));
189
+ }
190
+ },
191
+ });
192
+ //# sourceMappingURL=postgres-holds.js.map
@@ -0,0 +1,8 @@
1
+ import type { LoomDatabase } from "./database.js";
2
+ import { type TreeStore } from "./store.js";
3
+ export * from "./database.js";
4
+ export * from "./migrate.js";
5
+ export * from "./postgres-holds.js";
6
+ export * from "./schema.js";
7
+ export declare const postgresTreeStore: (db: LoomDatabase) => TreeStore;
8
+ //# sourceMappingURL=postgres.d.ts.map
@@ -0,0 +1,262 @@
1
+ import { and, asc, desc, eq, gt, lt } from "drizzle-orm";
2
+ import { z } from "zod";
3
+ import { proposalIdSchema, treeIdSchema } from "../ids.js";
4
+ import { cursorPosition, pageEnds } from "../paging.js";
5
+ import { provenanceSchema } from "../runtime/proposal.js";
6
+ import { treeDeltaSchema } from "../tree/delta.js";
7
+ import { err, ok } from "../result.js";
8
+ import { applyDelta } from "../tree/apply.js";
9
+ import { parseTree } from "../tree/tree.js";
10
+ import { isUniqueViolation, unavailable } from "./driver.js";
11
+ import { loomRevisions, loomTrees } from "./schema.js";
12
+ import { anchorBound, anchorResumes, clampListingLimit, clampRevisionLimit, } from "./store.js";
13
+ export * from "./database.js";
14
+ export * from "./migrate.js";
15
+ export * from "./postgres-holds.js";
16
+ export * from "./schema.js";
17
+ /**
18
+ * The store, backed by Postgres (0022).
19
+ *
20
+ * Nothing here is Supabase-specific — it is plain SQL through Drizzle, which is
21
+ * why it is named for the database rather than the host. Supabase is where it
22
+ * runs; it is not what it talks to.
23
+ *
24
+ * The handle is injected rather than constructed. Choosing a driver, a pooler and
25
+ * a connection lifetime belongs to the host, and injecting it is also what lets
26
+ * the tests run this exact code against an embedded Postgres.
27
+ */
28
+ /**
29
+ * Rows come back as `unknown` and are parsed, never cast. A document written by
30
+ * an older schema version must not reach the renderer unvalidated — storage is a
31
+ * boundary like any other, and it is the one boundary where the data outlives the
32
+ * code that wrote it.
33
+ */
34
+ const parseStored = (document, treeId) => {
35
+ const parsed = parseTree(document);
36
+ return parsed.ok
37
+ ? ok(parsed.value)
38
+ : err({
39
+ code: "unavailable",
40
+ detail: `stored tree ${treeId} did not parse: ${parsed.error.code}`,
41
+ });
42
+ };
43
+ /**
44
+ * A log row, validated on the way out. The delta and the provenance were stored
45
+ * as JSON by whatever version of the code was running at the time, so reading
46
+ * them back is the same boundary `parseTree` guards — and the log is the one
47
+ * place where the data is guaranteed to outlive the code that wrote it.
48
+ */
49
+ const storedRevisionSchema = z.object({
50
+ treeId: treeIdSchema,
51
+ revision: z.number().int().nonnegative(),
52
+ proposalId: proposalIdSchema,
53
+ delta: treeDeltaSchema,
54
+ provenance: provenanceSchema,
55
+ appliedAt: z.string().datetime(),
56
+ /** Null on every row written before the column existed (0029), and on every change nobody had to allow. */
57
+ answeredBy: z.string().nullable().optional(),
58
+ });
59
+ /**
60
+ * A null column and an absent key have to produce the same entry, or a revision
61
+ * nobody approved would compare unequal between this store and the in-memory
62
+ * one — and the contract suite both are checked against would be measuring the
63
+ * backing store rather than the behaviour.
64
+ */
65
+ const toStoredRevision = (row) => {
66
+ const { answeredBy, ...rest } = row;
67
+ /**
68
+ * Zod infers an optional field as `T | undefined`, and
69
+ * `exactOptionalPropertyTypes` distinguishes that from an absent key — so a
70
+ * parsed `Provenance` needs asserting even though it validated. The assertion
71
+ * is about the shape of optionality, never about whether the data is valid:
72
+ * the schema above established that.
73
+ */
74
+ const entry = rest;
75
+ return answeredBy === null || answeredBy === undefined ? entry : { ...entry, answeredBy };
76
+ };
77
+ export const postgresTreeStore = (db) => {
78
+ const readHead = async (treeId) => {
79
+ const rows = await db
80
+ .select({ document: loomTrees.document })
81
+ .from(loomTrees)
82
+ .where(eq(loomTrees.treeId, treeId))
83
+ .limit(1);
84
+ const row = rows[0];
85
+ return row === undefined
86
+ ? err({ code: "not-found", treeId })
87
+ : parseStored(row.document, treeId);
88
+ };
89
+ return {
90
+ create: async (tree) => {
91
+ try {
92
+ await db.insert(loomTrees).values({
93
+ treeId: tree.treeId,
94
+ revision: tree.revision,
95
+ document: tree,
96
+ });
97
+ return ok(tree);
98
+ }
99
+ catch (cause) {
100
+ return isUniqueViolation(cause)
101
+ ? err({ code: "already-exists", treeId: tree.treeId })
102
+ : err(unavailable(cause, `could not create ${tree.treeId}`));
103
+ }
104
+ },
105
+ head: async (treeId) => {
106
+ try {
107
+ return await readHead(treeId);
108
+ }
109
+ catch (cause) {
110
+ return err(unavailable(cause, `could not read ${treeId}`));
111
+ }
112
+ },
113
+ revisions: async (treeId, request) => {
114
+ const limit = clampRevisionLimit(request?.limit);
115
+ const direction = request?.direction ?? "newer";
116
+ const at = request?.at;
117
+ /** An anchor and a cursor reach the query below as the same bound. */
118
+ const from = at === undefined ? cursorPosition(request?.cursor) : anchorBound(at, direction);
119
+ try {
120
+ const present = await db
121
+ .select({ treeId: loomTrees.treeId, revision: loomTrees.revision })
122
+ .from(loomTrees)
123
+ .where(eq(loomTrees.treeId, treeId))
124
+ .limit(1);
125
+ /** "No tree" and "a tree with no changes" are different answers. */
126
+ const head = present[0];
127
+ if (head === undefined)
128
+ return err({ code: "not-found", treeId });
129
+ /**
130
+ * `older` scans descending so the newest page costs one seek on the
131
+ * primary key rather than a walk from the start of the log, then the rows
132
+ * are put back in applied order — the contract's promise that a page's
133
+ * order never depends on which end it came from.
134
+ */
135
+ const rows = await db
136
+ .select()
137
+ .from(loomRevisions)
138
+ .where(and(eq(loomRevisions.treeId, treeId), from === undefined
139
+ ? undefined
140
+ : direction === "older"
141
+ ? lt(loomRevisions.revision, from)
142
+ : gt(loomRevisions.revision, from)))
143
+ .orderBy(direction === "older" ? desc(loomRevisions.revision) : asc(loomRevisions.revision))
144
+ /** One extra row answers "is there another page" without a count. */
145
+ .limit(limit + 1);
146
+ const taken = rows.slice(0, limit);
147
+ const parsed = z
148
+ .array(storedRevisionSchema)
149
+ .safeParse(direction === "older" ? taken.slice().reverse() : taken);
150
+ if (!parsed.success) {
151
+ return err({
152
+ code: "unavailable",
153
+ detail: `the log of ${treeId} did not parse: ${parsed.error.issues[0]?.path.join(".") ?? "unknown"}`,
154
+ });
155
+ }
156
+ const page = parsed.data.map(toStoredRevision);
157
+ return ok({
158
+ revisions: page,
159
+ ...pageEnds(page.map((stored) => stored.revision), direction, {
160
+ beyond: rows.length > limit,
161
+ resumed: at === undefined ? from !== undefined : anchorResumes(at, direction, head.revision),
162
+ }),
163
+ });
164
+ }
165
+ catch (cause) {
166
+ return err(unavailable(cause, `could not read the history of ${treeId}`));
167
+ }
168
+ },
169
+ list: async (request) => {
170
+ const limit = clampListingLimit(request?.limit);
171
+ try {
172
+ const rows = await db
173
+ .select({ treeId: loomTrees.treeId, revision: loomTrees.revision })
174
+ .from(loomTrees)
175
+ .where(request?.cursor === undefined ? undefined : gt(loomTrees.treeId, request.cursor))
176
+ .orderBy(asc(loomTrees.treeId))
177
+ /** One extra row answers "is there another page" without a count. */
178
+ .limit(limit + 1);
179
+ const page = rows.slice(0, limit);
180
+ const last = page[page.length - 1];
181
+ const listing = {
182
+ trees: page.map((row) => ({
183
+ treeId: treeIdSchema.parse(row.treeId),
184
+ revision: row.revision,
185
+ })),
186
+ cursor: rows.length > limit && last !== undefined ? last.treeId : null,
187
+ };
188
+ return ok(listing);
189
+ }
190
+ catch (cause) {
191
+ return err(unavailable(cause, "could not list trees"));
192
+ }
193
+ },
194
+ /**
195
+ * The one operation that must be atomic (0016). The log entry and the
196
+ * snapshot advance land together or not at all, because a log entry without
197
+ * its snapshot advance is exactly the divergence `auditSnapshot` exists to
198
+ * detect — and a store must never manufacture the fault its own audit is
199
+ * designed to catch.
200
+ */
201
+ append: async (treeId, request) => {
202
+ try {
203
+ return await db.transaction(async (tx) => {
204
+ const rows = await tx
205
+ .select({ document: loomTrees.document })
206
+ .from(loomTrees)
207
+ .where(eq(loomTrees.treeId, treeId))
208
+ .for("update")
209
+ .limit(1);
210
+ const row = rows[0];
211
+ if (row === undefined)
212
+ return err({ code: "not-found", treeId });
213
+ const snapshot = parseStored(row.document, treeId);
214
+ if (!snapshot.ok)
215
+ return snapshot;
216
+ if (request.delta.baseRevision !== snapshot.value.revision) {
217
+ return err({
218
+ code: "revision-conflict",
219
+ treeId,
220
+ expected: request.delta.baseRevision,
221
+ found: snapshot.value.revision,
222
+ });
223
+ }
224
+ const applied = applyDelta(snapshot.value, request.delta);
225
+ if (!applied.ok) {
226
+ return err({ code: "delta-rejected", treeId, error: applied.error });
227
+ }
228
+ await tx.insert(loomRevisions).values({
229
+ treeId,
230
+ revision: applied.value.revision,
231
+ proposalId: request.proposalId,
232
+ delta: request.delta,
233
+ provenance: request.provenance,
234
+ appliedAt: request.appliedAt,
235
+ answeredBy: request.answeredBy ?? null,
236
+ });
237
+ await tx
238
+ .update(loomTrees)
239
+ .set({ revision: applied.value.revision, document: applied.value })
240
+ .where(and(eq(loomTrees.treeId, treeId), eq(loomTrees.revision, snapshot.value.revision)));
241
+ return ok(applied.value);
242
+ });
243
+ }
244
+ catch (cause) {
245
+ /**
246
+ * The composite primary key on the log is the last line of defence: two
247
+ * writers that both passed the base-revision check cannot both commit,
248
+ * and the loser arrives here rather than corrupting the sequence.
249
+ */
250
+ return isUniqueViolation(cause)
251
+ ? err({
252
+ code: "revision-conflict",
253
+ treeId,
254
+ expected: request.delta.baseRevision,
255
+ found: request.delta.baseRevision + 1,
256
+ })
257
+ : err(unavailable(cause, `could not append to ${treeId}`));
258
+ }
259
+ },
260
+ };
261
+ };
262
+ //# sourceMappingURL=postgres.js.map