@cleocode/core 2026.9.24 → 2026.9.26

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 (481) hide show
  1. package/dist/admin/import-tasks.d.ts.map +1 -1
  2. package/dist/admin/import-tasks.js +5 -2
  3. package/dist/admin/import-tasks.js.map +1 -1
  4. package/dist/admin/import.d.ts.map +1 -1
  5. package/dist/admin/import.js +7 -2
  6. package/dist/admin/import.js.map +1 -1
  7. package/dist/audit-prune.d.ts +32 -0
  8. package/dist/audit-prune.d.ts.map +1 -1
  9. package/dist/audit-prune.js +37 -3
  10. package/dist/audit-prune.js.map +1 -1
  11. package/dist/build-provenance.json +2 -2
  12. package/dist/cloud/crypto.d.ts +1 -2
  13. package/dist/cloud/crypto.d.ts.map +1 -1
  14. package/dist/cloud/crypto.js +1 -11
  15. package/dist/cloud/crypto.js.map +1 -1
  16. package/dist/cloud/index.d.ts +1 -0
  17. package/dist/cloud/index.d.ts.map +1 -1
  18. package/dist/cloud/index.js +1 -0
  19. package/dist/cloud/index.js.map +1 -1
  20. package/dist/cloud/nexus-auth.d.ts +26 -1
  21. package/dist/cloud/nexus-auth.d.ts.map +1 -1
  22. package/dist/cloud/nexus-auth.js +61 -32
  23. package/dist/cloud/nexus-auth.js.map +1 -1
  24. package/dist/cloud/nexus-credentials.js +2 -2
  25. package/dist/cloud/nexus-credentials.js.map +1 -1
  26. package/dist/cloud/nexus-device.d.ts +809 -0
  27. package/dist/cloud/nexus-device.d.ts.map +1 -0
  28. package/dist/cloud/nexus-device.js +1680 -0
  29. package/dist/cloud/nexus-device.js.map +1 -0
  30. package/dist/cloud/nexus-enrol.d.ts +210 -0
  31. package/dist/cloud/nexus-enrol.d.ts.map +1 -0
  32. package/dist/cloud/nexus-enrol.js +1023 -0
  33. package/dist/cloud/nexus-enrol.js.map +1 -0
  34. package/dist/cloud/nexus-link.d.ts +3 -0
  35. package/dist/cloud/nexus-link.d.ts.map +1 -1
  36. package/dist/cloud/nexus-link.js +38 -4
  37. package/dist/cloud/nexus-link.js.map +1 -1
  38. package/dist/cloud/signing.d.ts +20 -0
  39. package/dist/cloud/signing.d.ts.map +1 -1
  40. package/dist/cloud/signing.js +14 -0
  41. package/dist/cloud/signing.js.map +1 -1
  42. package/dist/cloud/uuidv7.d.ts +9 -0
  43. package/dist/cloud/uuidv7.d.ts.map +1 -0
  44. package/dist/cloud/uuidv7.js +19 -0
  45. package/dist/cloud/uuidv7.js.map +1 -0
  46. package/dist/crypto/credentials.d.ts +61 -0
  47. package/dist/crypto/credentials.d.ts.map +1 -1
  48. package/dist/crypto/credentials.js +154 -58
  49. package/dist/crypto/credentials.js.map +1 -1
  50. package/dist/decide/bench/index.d.ts +1 -1
  51. package/dist/decide/bench/index.d.ts.map +1 -1
  52. package/dist/decide/bench/index.js +1 -1
  53. package/dist/decide/bench/index.js.map +1 -1
  54. package/dist/decide/bench/operation.d.ts +1 -1
  55. package/dist/decide/bench/operation.d.ts.map +1 -1
  56. package/dist/decide/bench/operation.js +1 -1
  57. package/dist/decide/bench/operation.js.map +1 -1
  58. package/dist/decide/bench/profiles.d.ts +50 -22
  59. package/dist/decide/bench/profiles.d.ts.map +1 -1
  60. package/dist/decide/bench/profiles.js +103 -59
  61. package/dist/decide/bench/profiles.js.map +1 -1
  62. package/dist/decide/bench/report.d.ts.map +1 -1
  63. package/dist/decide/bench/report.js +6 -1
  64. package/dist/decide/bench/report.js.map +1 -1
  65. package/dist/decide/bench/runner.d.ts +6 -1
  66. package/dist/decide/bench/runner.d.ts.map +1 -1
  67. package/dist/decide/bench/runner.js +1 -0
  68. package/dist/decide/bench/runner.js.map +1 -1
  69. package/dist/decide/client.d.ts.map +1 -1
  70. package/dist/decide/client.js +11 -5
  71. package/dist/decide/client.js.map +1 -1
  72. package/dist/decide/jev-wire.d.ts +31 -1
  73. package/dist/decide/jev-wire.d.ts.map +1 -1
  74. package/dist/decide/jev-wire.js +61 -7
  75. package/dist/decide/jev-wire.js.map +1 -1
  76. package/dist/docs/export-document.js +12907 -10622
  77. package/dist/docs/export-document.js.map +3 -3
  78. package/dist/doctor/dependency-cycles.d.ts +41 -0
  79. package/dist/doctor/dependency-cycles.d.ts.map +1 -0
  80. package/dist/doctor/dependency-cycles.js +39 -0
  81. package/dist/doctor/dependency-cycles.js.map +1 -0
  82. package/dist/doctor/index.d.ts +2 -0
  83. package/dist/doctor/index.d.ts.map +1 -1
  84. package/dist/doctor/index.js +1 -0
  85. package/dist/doctor/index.js.map +1 -1
  86. package/dist/doctor/orphan-ac-bindings.d.ts +64 -0
  87. package/dist/doctor/orphan-ac-bindings.d.ts.map +1 -0
  88. package/dist/doctor/orphan-ac-bindings.js +59 -0
  89. package/dist/doctor/orphan-ac-bindings.js.map +1 -0
  90. package/dist/doctor/projects.d.ts.map +1 -1
  91. package/dist/doctor/projects.js +43 -29
  92. package/dist/doctor/projects.js.map +1 -1
  93. package/dist/doctor/row-identity.d.ts +42 -0
  94. package/dist/doctor/row-identity.d.ts.map +1 -0
  95. package/dist/doctor/row-identity.js +151 -0
  96. package/dist/doctor/row-identity.js.map +1 -0
  97. package/dist/doctor/twin-collapse.d.ts +58 -2
  98. package/dist/doctor/twin-collapse.d.ts.map +1 -1
  99. package/dist/doctor/twin-collapse.js +212 -14
  100. package/dist/doctor/twin-collapse.js.map +1 -1
  101. package/dist/error-catalog.d.ts.map +1 -1
  102. package/dist/error-catalog.js +4 -0
  103. package/dist/error-catalog.js.map +1 -1
  104. package/dist/error-registry.d.ts.map +1 -1
  105. package/dist/error-registry.js +8 -0
  106. package/dist/error-registry.js.map +1 -1
  107. package/dist/lifecycle/verification/satisfies-validator.d.ts.map +1 -1
  108. package/dist/lifecycle/verification/satisfies-validator.js +10 -0
  109. package/dist/lifecycle/verification/satisfies-validator.js.map +1 -1
  110. package/dist/llm/plugin-facade.js +17767 -15482
  111. package/dist/llm/plugin-facade.js.map +3 -3
  112. package/dist/memory/index.d.ts.map +1 -1
  113. package/dist/memory/index.js +19 -10
  114. package/dist/memory/index.js.map +1 -1
  115. package/dist/memory/manifest-identity.d.ts +171 -0
  116. package/dist/memory/manifest-identity.d.ts.map +1 -0
  117. package/dist/memory/manifest-identity.js +345 -0
  118. package/dist/memory/manifest-identity.js.map +1 -0
  119. package/dist/memory/mental-model-queue.d.ts +14 -4
  120. package/dist/memory/mental-model-queue.d.ts.map +1 -1
  121. package/dist/memory/mental-model-queue.js +64 -35
  122. package/dist/memory/mental-model-queue.js.map +1 -1
  123. package/dist/memory/pipeline-manifest-sqlite.d.ts +47 -5
  124. package/dist/memory/pipeline-manifest-sqlite.d.ts.map +1 -1
  125. package/dist/memory/pipeline-manifest-sqlite.js +130 -14
  126. package/dist/memory/pipeline-manifest-sqlite.js.map +1 -1
  127. package/dist/memory/retrieval/observe.d.ts.map +1 -1
  128. package/dist/memory/retrieval/observe.js +2 -0
  129. package/dist/memory/retrieval/observe.js.map +1 -1
  130. package/dist/memory/transcript-scanner.js +1 -1
  131. package/dist/nexus/deps.d.ts.map +1 -1
  132. package/dist/nexus/deps.js +7 -14
  133. package/dist/nexus/deps.js.map +1 -1
  134. package/dist/nexus/discover.d.ts.map +1 -1
  135. package/dist/nexus/discover.js +6 -9
  136. package/dist/nexus/discover.js.map +1 -1
  137. package/dist/nexus/git-state.d.ts.map +1 -1
  138. package/dist/nexus/git-state.js +10 -1
  139. package/dist/nexus/git-state.js.map +1 -1
  140. package/dist/nexus/projects-clean.d.ts.map +1 -1
  141. package/dist/nexus/projects-clean.js +22 -11
  142. package/dist/nexus/projects-clean.js.map +1 -1
  143. package/dist/nexus/projects-scan.d.ts.map +1 -1
  144. package/dist/nexus/projects-scan.js +8 -13
  145. package/dist/nexus/projects-scan.js.map +1 -1
  146. package/dist/nexus/query.d.ts.map +1 -1
  147. package/dist/nexus/query.js +4 -12
  148. package/dist/nexus/query.js.map +1 -1
  149. package/dist/nexus/registry-roots.d.ts +5 -2
  150. package/dist/nexus/registry-roots.d.ts.map +1 -1
  151. package/dist/nexus/registry-roots.js +8 -10
  152. package/dist/nexus/registry-roots.js.map +1 -1
  153. package/dist/nexus/registry.d.ts +18 -0
  154. package/dist/nexus/registry.d.ts.map +1 -1
  155. package/dist/nexus/registry.js +37 -16
  156. package/dist/nexus/registry.js.map +1 -1
  157. package/dist/nexus/workspace.d.ts.map +1 -1
  158. package/dist/nexus/workspace.js +54 -4
  159. package/dist/nexus/workspace.js.map +1 -1
  160. package/dist/orchestrate/lifecycle-ops.js +1 -1
  161. package/dist/orchestrate/lifecycle-ops.js.map +1 -1
  162. package/dist/orchestrate/pivot.d.ts.map +1 -1
  163. package/dist/orchestrate/pivot.js +4 -2
  164. package/dist/orchestrate/pivot.js.map +1 -1
  165. package/dist/orchestrate/query-ops.d.ts.map +1 -1
  166. package/dist/orchestrate/query-ops.js +3 -3
  167. package/dist/orchestrate/query-ops.js.map +1 -1
  168. package/dist/orchestrate/spawn-ops.js +1 -1
  169. package/dist/orchestrate/spawn-ops.js.map +1 -1
  170. package/dist/orchestrate/worktree-complete.d.ts.map +1 -1
  171. package/dist/orchestrate/worktree-complete.js +40 -2
  172. package/dist/orchestrate/worktree-complete.js.map +1 -1
  173. package/dist/orchestration/index.js +1 -1
  174. package/dist/orchestration/index.js.map +1 -1
  175. package/dist/orchestration/lead-rollup.d.ts.map +1 -1
  176. package/dist/orchestration/lead-rollup.js +3 -3
  177. package/dist/orchestration/lead-rollup.js.map +1 -1
  178. package/dist/orchestration/parallel.js +1 -1
  179. package/dist/orchestration/parallel.js.map +1 -1
  180. package/dist/orchestration/spawn-prompt.d.ts +26 -0
  181. package/dist/orchestration/spawn-prompt.d.ts.map +1 -1
  182. package/dist/orchestration/spawn-prompt.js +62 -91
  183. package/dist/orchestration/spawn-prompt.js.map +1 -1
  184. package/dist/orchestration/wave-topic.d.ts +4 -2
  185. package/dist/orchestration/wave-topic.d.ts.map +1 -1
  186. package/dist/orchestration/wave-topic.js +6 -4
  187. package/dist/orchestration/wave-topic.js.map +1 -1
  188. package/dist/orchestration/waves.d.ts +2 -1
  189. package/dist/orchestration/waves.d.ts.map +1 -1
  190. package/dist/orchestration/waves.js +4 -3
  191. package/dist/orchestration/waves.js.map +1 -1
  192. package/dist/phases/index.d.ts.map +1 -1
  193. package/dist/phases/index.js +4 -2
  194. package/dist/phases/index.js.map +1 -1
  195. package/dist/release/ci-evidence.d.ts +190 -0
  196. package/dist/release/ci-evidence.d.ts.map +1 -1
  197. package/dist/release/ci-evidence.js +436 -4
  198. package/dist/release/ci-evidence.js.map +1 -1
  199. package/dist/sdk/validator-ac-pull.d.ts.map +1 -1
  200. package/dist/sdk/validator-ac-pull.js +2 -1
  201. package/dist/sdk/validator-ac-pull.js.map +1 -1
  202. package/dist/selfimprove/fix-gen.js +12807 -10522
  203. package/dist/selfimprove/fix-gen.js.map +3 -3
  204. package/dist/sentient/cross-project-hygiene.d.ts +5 -0
  205. package/dist/sentient/cross-project-hygiene.d.ts.map +1 -1
  206. package/dist/sentient/cross-project-hygiene.js +7 -1
  207. package/dist/sentient/cross-project-hygiene.js.map +1 -1
  208. package/dist/sentient/propose-tick.d.ts.map +1 -1
  209. package/dist/sentient/propose-tick.js +2 -3
  210. package/dist/sentient/propose-tick.js.map +1 -1
  211. package/dist/sentient/stage-drift-tick.d.ts.map +1 -1
  212. package/dist/sentient/stage-drift-tick.js +2 -3
  213. package/dist/sentient/stage-drift-tick.js.map +1 -1
  214. package/dist/session/engine-ops.d.ts.map +1 -1
  215. package/dist/session/engine-ops.js +77 -49
  216. package/dist/session/engine-ops.js.map +1 -1
  217. package/dist/sessions/focus-state-store.d.ts +69 -23
  218. package/dist/sessions/focus-state-store.d.ts.map +1 -1
  219. package/dist/sessions/focus-state-store.js +113 -27
  220. package/dist/sessions/focus-state-store.js.map +1 -1
  221. package/dist/sessions/handoff.js +1 -1
  222. package/dist/sessions/handoff.js.map +1 -1
  223. package/dist/sessions/index.d.ts.map +1 -1
  224. package/dist/sessions/index.js +24 -13
  225. package/dist/sessions/index.js.map +1 -1
  226. package/dist/sessions/terminal-identity.d.ts +165 -17
  227. package/dist/sessions/terminal-identity.d.ts.map +1 -1
  228. package/dist/sessions/terminal-identity.js +341 -32
  229. package/dist/sessions/terminal-identity.js.map +1 -1
  230. package/dist/skills/manifests/research.js +2 -0
  231. package/dist/skills/manifests/research.js.map +1 -1
  232. package/dist/skills/orchestrator/startup.js +2 -2
  233. package/dist/skills/orchestrator/startup.js.map +1 -1
  234. package/dist/skills/orchestrator/validator.d.ts.map +1 -1
  235. package/dist/skills/orchestrator/validator.js +9 -2
  236. package/dist/skills/orchestrator/validator.js.map +1 -1
  237. package/dist/skills/validation.d.ts +4 -1
  238. package/dist/skills/validation.d.ts.map +1 -1
  239. package/dist/skills/validation.js +11 -3
  240. package/dist/skills/validation.js.map +1 -1
  241. package/dist/snapshot/index.d.ts +4 -0
  242. package/dist/snapshot/index.d.ts.map +1 -1
  243. package/dist/snapshot/index.js +50 -3
  244. package/dist/snapshot/index.js.map +1 -1
  245. package/dist/spawn/branch-lock.d.ts +111 -7
  246. package/dist/spawn/branch-lock.d.ts.map +1 -1
  247. package/dist/spawn/branch-lock.js +296 -8
  248. package/dist/spawn/branch-lock.js.map +1 -1
  249. package/dist/store/ac-binding-prune.d.ts +144 -0
  250. package/dist/store/ac-binding-prune.d.ts.map +1 -0
  251. package/dist/store/ac-binding-prune.js +293 -0
  252. package/dist/store/ac-binding-prune.js.map +1 -0
  253. package/dist/store/agent-registry-store.d.ts.map +1 -1
  254. package/dist/store/agent-registry-store.js +3 -2
  255. package/dist/store/agent-registry-store.js.map +1 -1
  256. package/dist/store/backup-sidecar.d.ts +85 -2
  257. package/dist/store/backup-sidecar.d.ts.map +1 -1
  258. package/dist/store/backup-sidecar.js +173 -1
  259. package/dist/store/backup-sidecar.js.map +1 -1
  260. package/dist/store/conduit-sqlite.d.ts.map +1 -1
  261. package/dist/store/conduit-sqlite.js +3 -2
  262. package/dist/store/conduit-sqlite.js.map +1 -1
  263. package/dist/store/credential-transfer.d.ts.map +1 -1
  264. package/dist/store/credential-transfer.js +3 -0
  265. package/dist/store/credential-transfer.js.map +1 -1
  266. package/dist/store/db-helpers.d.ts +32 -13
  267. package/dist/store/db-helpers.d.ts.map +1 -1
  268. package/dist/store/db-helpers.js +144 -40
  269. package/dist/store/db-helpers.js.map +1 -1
  270. package/dist/store/dependency-cycles.d.ts +164 -0
  271. package/dist/store/dependency-cycles.d.ts.map +1 -0
  272. package/dist/store/dependency-cycles.js +360 -0
  273. package/dist/store/dependency-cycles.js.map +1 -0
  274. package/dist/store/display-id-alias.d.ts +585 -0
  275. package/dist/store/display-id-alias.d.ts.map +1 -0
  276. package/dist/store/display-id-alias.js +1538 -0
  277. package/dist/store/display-id-alias.js.map +1 -0
  278. package/dist/store/dual-scope-db.d.ts.map +1 -1
  279. package/dist/store/dual-scope-db.js +48 -0
  280. package/dist/store/dual-scope-db.js.map +1 -1
  281. package/dist/store/exodus/migrate.d.ts.map +1 -1
  282. package/dist/store/exodus/migrate.js +8 -1
  283. package/dist/store/exodus/migrate.js.map +1 -1
  284. package/dist/store/exodus/reconcile.d.ts.map +1 -1
  285. package/dist/store/exodus/reconcile.js +7 -2
  286. package/dist/store/exodus/reconcile.js.map +1 -1
  287. package/dist/store/exodus/recovery.d.ts.map +1 -1
  288. package/dist/store/exodus/recovery.js +20 -1
  289. package/dist/store/exodus/recovery.js.map +1 -1
  290. package/dist/store/global-salt.d.ts +35 -0
  291. package/dist/store/global-salt.d.ts.map +1 -1
  292. package/dist/store/global-salt.js +136 -16
  293. package/dist/store/global-salt.js.map +1 -1
  294. package/dist/store/legacy-tasks-lineage.d.ts.map +1 -1
  295. package/dist/store/legacy-tasks-lineage.js +19 -2
  296. package/dist/store/legacy-tasks-lineage.js.map +1 -1
  297. package/dist/store/migration-sqlite.d.ts.map +1 -1
  298. package/dist/store/migration-sqlite.js +19 -11
  299. package/dist/store/migration-sqlite.js.map +1 -1
  300. package/dist/store/portable-bundle-scan.d.ts.map +1 -1
  301. package/dist/store/portable-bundle-scan.js +6 -0
  302. package/dist/store/portable-bundle-scan.js.map +1 -1
  303. package/dist/store/row-identity-flag.d.ts +26 -0
  304. package/dist/store/row-identity-flag.d.ts.map +1 -0
  305. package/dist/store/row-identity-flag.js +31 -0
  306. package/dist/store/row-identity-flag.js.map +1 -0
  307. package/dist/store/row-identity-registry.d.ts +61 -0
  308. package/dist/store/row-identity-registry.d.ts.map +1 -0
  309. package/dist/store/row-identity-registry.js +206 -0
  310. package/dist/store/row-identity-registry.js.map +1 -0
  311. package/dist/store/row-identity.d.ts +480 -0
  312. package/dist/store/row-identity.d.ts.map +1 -0
  313. package/dist/store/row-identity.js +1509 -0
  314. package/dist/store/row-identity.js.map +1 -0
  315. package/dist/store/safety-data-accessor.d.ts +5 -2
  316. package/dist/store/safety-data-accessor.d.ts.map +1 -1
  317. package/dist/store/safety-data-accessor.js +9 -2
  318. package/dist/store/safety-data-accessor.js.map +1 -1
  319. package/dist/store/schema/attachments.d.ts +1 -1
  320. package/dist/store/schema/audit.d.ts +4 -4
  321. package/dist/store/schema/background-jobs.d.ts +1 -1
  322. package/dist/store/schema/cleo-global/nexus.d.ts +1 -1
  323. package/dist/store/schema/cleo-global/skills.d.ts +2 -2
  324. package/dist/store/schema/cleo-project/audit.d.ts +4 -4
  325. package/dist/store/schema/cleo-project/docs.d.ts +1 -1
  326. package/dist/store/schema/cleo-project/lifecycle.d.ts +4 -4
  327. package/dist/store/schema/cleo-project/nexus-graph.d.ts +3 -3
  328. package/dist/store/schema/cleo-project/provenance-commits.d.ts +2 -2
  329. package/dist/store/schema/cleo-project/provenance-rest.d.ts +3 -3
  330. package/dist/store/schema/cleo-project/runtime.d.ts +3 -3
  331. package/dist/store/schema/cleo-project/tasks-core-batch2.d.ts +87 -1
  332. package/dist/store/schema/cleo-project/tasks-core-batch2.d.ts.map +1 -1
  333. package/dist/store/schema/cleo-project/tasks-core-batch2.js +35 -0
  334. package/dist/store/schema/cleo-project/tasks-core-batch2.js.map +1 -1
  335. package/dist/store/schema/cleo-project/tasks-core.d.ts +183 -7
  336. package/dist/store/schema/cleo-project/tasks-core.d.ts.map +1 -1
  337. package/dist/store/schema/cleo-project/tasks-core.js +52 -1
  338. package/dist/store/schema/cleo-project/tasks-core.js.map +1 -1
  339. package/dist/store/schema/cleo-shared/brain.d.ts +6 -6
  340. package/dist/store/schema/lifecycle.d.ts +4 -4
  341. package/dist/store/schema/manifest.d.ts +1 -1
  342. package/dist/store/schema/memory-schema.d.ts +5 -5
  343. package/dist/store/schema/nexus-schema.d.ts +3 -3
  344. package/dist/store/schema/provenance/releases.d.ts +1 -1
  345. package/dist/store/schema/skills-schema.d.ts +2 -2
  346. package/dist/store/schema/tasks.d.ts +6 -6
  347. package/dist/store/session-store.d.ts +63 -3
  348. package/dist/store/session-store.d.ts.map +1 -1
  349. package/dist/store/session-store.js +121 -8
  350. package/dist/store/session-store.js.map +1 -1
  351. package/dist/store/split-brain-import.d.ts +2 -14
  352. package/dist/store/split-brain-import.d.ts.map +1 -1
  353. package/dist/store/split-brain-import.js +40 -19
  354. package/dist/store/split-brain-import.js.map +1 -1
  355. package/dist/store/sqlite-data-accessor.d.ts +326 -2
  356. package/dist/store/sqlite-data-accessor.d.ts.map +1 -1
  357. package/dist/store/sqlite-data-accessor.js +782 -49
  358. package/dist/store/sqlite-data-accessor.js.map +1 -1
  359. package/dist/store/sync/clock-store.d.ts +67 -0
  360. package/dist/store/sync/clock-store.d.ts.map +1 -0
  361. package/dist/store/sync/clock-store.js +117 -0
  362. package/dist/store/sync/clock-store.js.map +1 -0
  363. package/dist/store/sync/flags.d.ts +51 -0
  364. package/dist/store/sync/flags.d.ts.map +1 -0
  365. package/dist/store/sync/flags.js +81 -0
  366. package/dist/store/sync/flags.js.map +1 -0
  367. package/dist/store/sync/hlc.d.ts +115 -0
  368. package/dist/store/sync/hlc.d.ts.map +1 -0
  369. package/dist/store/sync/hlc.js +172 -0
  370. package/dist/store/sync/hlc.js.map +1 -0
  371. package/dist/store/sync/index.d.ts +20 -0
  372. package/dist/store/sync/index.d.ts.map +1 -0
  373. package/dist/store/sync/index.js +20 -0
  374. package/dist/store/sync/index.js.map +1 -0
  375. package/dist/store/sync/replica-registry.d.ts +85 -0
  376. package/dist/store/sync/replica-registry.d.ts.map +1 -0
  377. package/dist/store/sync/replica-registry.js +147 -0
  378. package/dist/store/sync/replica-registry.js.map +1 -0
  379. package/dist/store/sync/replica.d.ts +181 -0
  380. package/dist/store/sync/replica.d.ts.map +1 -0
  381. package/dist/store/sync/replica.js +305 -0
  382. package/dist/store/sync/replica.js.map +1 -0
  383. package/dist/store/sync/schema.d.ts +68 -0
  384. package/dist/store/sync/schema.d.ts.map +1 -0
  385. package/dist/store/sync/schema.js +130 -0
  386. package/dist/store/sync/schema.js.map +1 -0
  387. package/dist/store/sync/skew-hold.d.ts +71 -0
  388. package/dist/store/sync/skew-hold.d.ts.map +1 -0
  389. package/dist/store/sync/skew-hold.js +89 -0
  390. package/dist/store/sync/skew-hold.js.map +1 -0
  391. package/dist/store/table-classification.d.ts +10 -8
  392. package/dist/store/table-classification.d.ts.map +1 -1
  393. package/dist/store/table-classification.js +93 -25
  394. package/dist/store/table-classification.js.map +1 -1
  395. package/dist/store/tasks-sqlite.d.ts.map +1 -1
  396. package/dist/store/tasks-sqlite.js +23 -3
  397. package/dist/store/tasks-sqlite.js.map +1 -1
  398. package/dist/store/twin-collapse.d.ts +113 -2
  399. package/dist/store/twin-collapse.d.ts.map +1 -1
  400. package/dist/store/twin-collapse.js +247 -19
  401. package/dist/store/twin-collapse.js.map +1 -1
  402. package/dist/store/umbrella-data-accessor.d.ts +5 -2
  403. package/dist/store/umbrella-data-accessor.d.ts.map +1 -1
  404. package/dist/store/umbrella-data-accessor.js +9 -2
  405. package/dist/store/umbrella-data-accessor.js.map +1 -1
  406. package/dist/store/validation-schemas.d.ts +241 -49
  407. package/dist/store/validation-schemas.d.ts.map +1 -1
  408. package/dist/system/health.d.ts +2 -0
  409. package/dist/system/health.d.ts.map +1 -1
  410. package/dist/system/health.js +57 -0
  411. package/dist/system/health.js.map +1 -1
  412. package/dist/system/project-health.d.ts +9 -2
  413. package/dist/system/project-health.d.ts.map +1 -1
  414. package/dist/system/project-health.js +8 -3
  415. package/dist/system/project-health.js.map +1 -1
  416. package/dist/task-work/index.d.ts.map +1 -1
  417. package/dist/task-work/index.js +9 -6
  418. package/dist/task-work/index.js.map +1 -1
  419. package/dist/tasks/ac-coverage-gate.d.ts.map +1 -1
  420. package/dist/tasks/ac-coverage-gate.js +3 -0
  421. package/dist/tasks/ac-coverage-gate.js.map +1 -1
  422. package/dist/tasks/ac-table.d.ts +35 -7
  423. package/dist/tasks/ac-table.d.ts.map +1 -1
  424. package/dist/tasks/ac-table.js +119 -14
  425. package/dist/tasks/ac-table.js.map +1 -1
  426. package/dist/tasks/add.d.ts.map +1 -1
  427. package/dist/tasks/add.js +48 -2
  428. package/dist/tasks/add.js.map +1 -1
  429. package/dist/tasks/analyze.d.ts.map +1 -1
  430. package/dist/tasks/analyze.js +3 -2
  431. package/dist/tasks/analyze.js.map +1 -1
  432. package/dist/tasks/backfill-child-projections.js +47 -6
  433. package/dist/tasks/backfill-child-projections.js.map +1 -1
  434. package/dist/tasks/complete.d.ts.map +1 -1
  435. package/dist/tasks/complete.js +6 -1
  436. package/dist/tasks/complete.js.map +1 -1
  437. package/dist/tasks/completion-evaluation.d.ts.map +1 -1
  438. package/dist/tasks/completion-evaluation.js +3 -0
  439. package/dist/tasks/completion-evaluation.js.map +1 -1
  440. package/dist/tasks/evidence.d.ts +19 -1
  441. package/dist/tasks/evidence.d.ts.map +1 -1
  442. package/dist/tasks/evidence.js +93 -21
  443. package/dist/tasks/evidence.js.map +1 -1
  444. package/dist/tasks/infer-add-params.js +1 -1
  445. package/dist/tasks/infer-add-params.js.map +1 -1
  446. package/dist/tasks/task-context.d.ts.map +1 -1
  447. package/dist/tasks/task-context.js +3 -1
  448. package/dist/tasks/task-context.js.map +1 -1
  449. package/dist/tasks/task-import.d.ts.map +1 -1
  450. package/dist/tasks/task-import.js +11 -3
  451. package/dist/tasks/task-import.js.map +1 -1
  452. package/dist/tasks/task-next.d.ts +5 -1
  453. package/dist/tasks/task-next.d.ts.map +1 -1
  454. package/dist/tasks/task-next.js +7 -2
  455. package/dist/tasks/task-next.js.map +1 -1
  456. package/dist/validation/compliance.d.ts +5 -1
  457. package/dist/validation/compliance.d.ts.map +1 -1
  458. package/dist/validation/compliance.js +24 -3
  459. package/dist/validation/compliance.js.map +1 -1
  460. package/dist/validation/engine-ops.d.ts.map +1 -1
  461. package/dist/validation/engine-ops.js +3 -2
  462. package/dist/validation/engine-ops.js.map +1 -1
  463. package/dist/validation/index.d.ts +1 -1
  464. package/dist/validation/index.d.ts.map +1 -1
  465. package/dist/validation/index.js +1 -1
  466. package/dist/validation/index.js.map +1 -1
  467. package/dist/validation/protocol-common.d.ts +47 -2
  468. package/dist/validation/protocol-common.d.ts.map +1 -1
  469. package/dist/validation/protocol-common.js +86 -21
  470. package/dist/validation/protocol-common.js.map +1 -1
  471. package/dist/workgraph/scaffold-apply.d.ts.map +1 -1
  472. package/dist/workgraph/scaffold-apply.js +14 -5
  473. package/dist/workgraph/scaffold-apply.js.map +1 -1
  474. package/migrations/README.md +12 -0
  475. package/migrations/drizzle-cleo-project/20260928120000_t12341-row-uids/migration.sql +169 -0
  476. package/migrations/drizzle-cleo-project/20260930160000_t12886-dependency-cycle-guard/migration.sql +76 -0
  477. package/migrations/drizzle-cleo-project/20260930160000_t12886-dependency-cycle-guard/revert.sql +7 -0
  478. package/migrations/sync-journal/20260929140000_t12342-sync-clock/migration.sql +42 -0
  479. package/package.json +13 -13
  480. package/templates/CLEO-INJECTION.md +2 -2
  481. package/templates/CLEO-REFERENCE.md +5 -1
@@ -0,0 +1,1509 @@
1
+ /**
2
+ * Row uids (T12341): the merge key every syncing row carries.
3
+ *
4
+ * A table whose Gate A class syncs gets a `uid TEXT` column. The local primary
5
+ * key (`T####`, an AC id, a session id, a composite edge key) stays the local
6
+ * key, and local foreign keys keep pointing at it; the uid is what a merge
7
+ * compares, as (project, uid). Spec: `cleo docs fetch t12341-uid-scheme`.
8
+ *
9
+ * ## How a uid is made
10
+ *
11
+ * - **Minted, new row** (this build writes it): a random UUIDv7
12
+ * ({@link mintRowUid}), set by the Drizzle `$defaultFn` or by the writer.
13
+ * - **Minted, no uid yet** (an existing row, or one an older build or a raw-SQL
14
+ * writer inserted): a DETERMINISTIC v7-layout uid. Its timestamp is the
15
+ * row's birth; its other 74 bits are SHA-256 over (scope, table, key, birth,
16
+ * the uids of its owning rows, and, for append-only tables, a frozen content
17
+ * list) ({@link mintedRowUid}). A `randomOnly` table (portable-secret) gets a
18
+ * random uid instead.
19
+ * - **Natural** (edges, labels): a UUIDv8 over the key with every reference
20
+ * replaced by the referenced row's uid ({@link naturalRowUid}); a pure
21
+ * function of the row. Symmetric relation types hash their endpoints in
22
+ * sorted order; the reversed twin of a symmetric edge stored both ways takes
23
+ * the `natural-mirror` recipe. A reference whose row does not exist hashes
24
+ * `dangling:<raw key>` and is reported.
25
+ *
26
+ * Deterministic identity can coincide for different rows (the same `T100`
27
+ * with the same `created_at` in two stores). Every minted row therefore also
28
+ * carries a birth fingerprint ({@link birthFingerprint}, `birth_fp`), hashed
29
+ * once from creation facts no edit changes. Same uid and same `birth_fp` is
30
+ * the same row; same uid and a different `birth_fp` is a COLLISION
31
+ * ({@link classifyUidMatch}), which the merge never merges.
32
+ *
33
+ * ## When uids are filled
34
+ *
35
+ * {@link prepareRowIdentity} runs on every open of a `cleo.db`, inside the
36
+ * cold-open lease right after the migrations:
37
+ *
38
+ * 1. re-asserts the identity columns and indexes (idempotent; heals a
39
+ * migration the journal probe stamped without running its index DDL);
40
+ * 2. registers the deterministic SQL functions on the connection, re-links
41
+ * acceptance criteria an older build recreated without their uid (the AC
42
+ * uid graveyard, spec §6.5), then fills every NULL uid (minted tables,
43
+ * owners first; then natural tables), the stored reference facts (`ac_uid`,
44
+ * `ac_text_hash`) and the birth fingerprints, in one savepoint;
45
+ * 3. installs one TEMP `AFTER INSERT` trigger per declared table on this
46
+ * connection, so a row inserted here without them gets the same values the
47
+ * open pass would give it, in the same statement. A trigger never fails the
48
+ * insert: a value that would clash is left NULL and reported at the next
49
+ * open.
50
+ *
51
+ * A row an older build inserts keeps NULL values until the next open by this
52
+ * build: there is no persistent trigger that computes them (see the
53
+ * migration's header). Row uids are OPT-IN: nothing here runs unless
54
+ * `CLEO_ROW_UID_FILL=1` ({@link rowUidFillEnabled}).
55
+ *
56
+ * A failure never fails the open: it is logged, and the rows keep NULL values
57
+ * until a later open succeeds. A uid's timestamp is ordering sugar only: HLC
58
+ * (T12342) never reads time from a uid.
59
+ *
60
+ * @module
61
+ * @task T12341
62
+ * @epic T12323
63
+ */
64
+ import { createHash } from 'node:crypto';
65
+ import { uuidv7 } from '../cloud/uuidv7.js';
66
+ import { getLogger } from '../logger.js';
67
+ import { acTextHash } from '../tasks/ac-table.js';
68
+ import { rowUidFillEnabled } from './row-identity-flag.js';
69
+ import { BIRTH_FP_COLUMN, ROW_IDENTITY, rowIdentityColumns, rowIdentitySpec, UID_COLUMN, } from './row-identity-registry.js';
70
+ import { schemaWritesAllowed } from './worktree-build-guard.js';
71
+ export { BIRTH_FP_COLUMN, ROW_IDENTITY, rowIdentityColumns, rowIdentitySpec, UID_COLUMN };
72
+ /** Domain separator hashed into every deterministic uid. Changing it re-keys every row. */
73
+ export const ROW_UID_DOMAIN = 'cleo/row-uid/v1';
74
+ /** Domain separator hashed into every birth fingerprint. */
75
+ export const ROW_BIRTH_DOMAIN = 'cleo/row-birth/v1';
76
+ /** Per-connection SQL function computing a deterministic uid. */
77
+ export const ROW_UID_SQL_FUNCTION = 'cleo_row_uid';
78
+ /** Per-connection SQL function computing a birth fingerprint. */
79
+ export const ROW_BIRTH_FP_SQL_FUNCTION = 'cleo_row_birth_fp';
80
+ /** Per-connection SQL function returning a fresh random UUIDv7 (`randomOnly` tables). */
81
+ export const ROW_RANDOM_UID_SQL_FUNCTION = 'cleo_row_random_uid';
82
+ /** Per-connection SQL function hashing AC text like `acTextHash`. */
83
+ export const AC_TEXT_HASH_SQL_FUNCTION = 'cleo_ac_text_hash';
84
+ /** Physical name of the AC uid graveyard (spec §6.5). */
85
+ export const AC_UID_GRAVEYARD = 'tasks_ac_uid_graveyard';
86
+ let registeredWriters;
87
+ /**
88
+ * Register the chokepoint's row-identity writers (called once by
89
+ * `store/sqlite-data-accessor.ts` at load).
90
+ *
91
+ * @param writers - The writers.
92
+ */
93
+ export function registerRowIdentityWriters(writers) {
94
+ registeredWriters = writers;
95
+ }
96
+ /** The registered writers, or an error naming the module that registers them. */
97
+ function requireWriters() {
98
+ if (!registeredWriters) {
99
+ throw new Error('row identity writers are not registered: load store/sqlite-data-accessor.js');
100
+ }
101
+ return registeredWriters;
102
+ }
103
+ /**
104
+ * Unambiguous encoding of uid inputs: per value a type tag (0 null, 1 text,
105
+ * 2 integer, 3 real, 4 blob), a big-endian u32 byte length, and the bytes. An
106
+ * integer-valued number is tag 2 (SQLite `3` and `3.0` encode alike); any other
107
+ * number is tag 3 with its ECMAScript shortest round-trip text. Frozen for
108
+ * recipe v1.
109
+ *
110
+ * @param values - Inputs in hash order.
111
+ * @returns The encoded bytes.
112
+ */
113
+ export function encodeUidInputs(values) {
114
+ const parts = [];
115
+ for (const value of values) {
116
+ let tag;
117
+ let bytes;
118
+ if (value === null) {
119
+ tag = 0;
120
+ bytes = Buffer.alloc(0);
121
+ }
122
+ else if (typeof value === 'string') {
123
+ tag = 1;
124
+ bytes = Buffer.from(value, 'utf8');
125
+ }
126
+ else if (typeof value === 'bigint' || Number.isInteger(value)) {
127
+ tag = 2;
128
+ bytes = Buffer.from(String(value), 'utf8');
129
+ }
130
+ else if (typeof value === 'number') {
131
+ tag = 3;
132
+ bytes = Buffer.from(value.toString(), 'utf8');
133
+ }
134
+ else {
135
+ tag = 4;
136
+ bytes = Buffer.from(value);
137
+ }
138
+ const head = Buffer.alloc(5);
139
+ head.writeUInt8(tag, 0);
140
+ head.writeUInt32BE(bytes.length, 1);
141
+ parts.push(head, bytes);
142
+ }
143
+ return Buffer.concat(parts);
144
+ }
145
+ /** Strict ISO-8601 / SQLite timestamp: date, optional time, optional zone. */
146
+ const STORE_TIMESTAMP = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,9}))?)?)?(Z|[+-]\d{2}:?\d{2})?$/;
147
+ /**
148
+ * Epoch milliseconds of a stored timestamp, or `null` when absent or not a
149
+ * strict ISO-8601 / SQLite timestamp. A value WITHOUT a zone is UTC:
150
+ * `datetime('now')` writes `YYYY-MM-DD HH:MM:SS` meaning UTC, and a zoneless
151
+ * `YYYY-MM-DDTHH:MM:SS` is read the same way, never as the device's local
152
+ * time (`Date.parse` would, and a uid would then depend on the device's
153
+ * timezone). Anything else (`Date.parse` extensions such as `Sep 24 2026`,
154
+ * out-of-range fields) is `null`, i.e. an unparseable birth. Comparing that
155
+ * text against ISO text is wrong within a day (`' '` sorts before `'T'`), so
156
+ * every comparison and every uid birth goes through this function (T12329).
157
+ *
158
+ * @param value - Stored timestamp.
159
+ * @returns Epoch milliseconds, or `null`.
160
+ */
161
+ export function parseStoreTimestamp(value) {
162
+ if (typeof value !== 'string')
163
+ return null;
164
+ const m = STORE_TIMESTAMP.exec(value);
165
+ if (!m)
166
+ return null;
167
+ const [, y, mo, d, h = '0', mi = '0', sec = '0', frac = '', zone] = m;
168
+ const year = Number(y);
169
+ const month = Number(mo);
170
+ const day = Number(d);
171
+ const hour = Number(h);
172
+ const minute = Number(mi);
173
+ const second = Number(sec);
174
+ if (month < 1 || month > 12 || day < 1 || hour > 23 || minute > 59 || second > 59)
175
+ return null;
176
+ const ms = Number(frac.padEnd(3, '0').slice(0, 3) || '0');
177
+ const utc = Date.UTC(year, month - 1, day, hour, minute, second, ms);
178
+ const check = new Date(utc);
179
+ if (check.getUTCMonth() !== month - 1 || check.getUTCDate() !== day)
180
+ return null;
181
+ if (!zone || zone === 'Z')
182
+ return utc;
183
+ const sign = zone.startsWith('-') ? -1 : 1;
184
+ const digits = zone.slice(1).replace(':', '');
185
+ const offset = (Number(digits.slice(0, 2)) * 60 + Number(digits.slice(2, 4))) * 60_000;
186
+ if (Number(digits.slice(0, 2)) > 23 || Number(digits.slice(2, 4)) > 59)
187
+ return null;
188
+ return utc - sign * offset;
189
+ }
190
+ /** Largest value a UUIDv7 timestamp field holds. */
191
+ const MAX_UUID_MS = 2 ** 48 - 1;
192
+ /** Format 16 bytes as a lowercase canonical UUID string. */
193
+ function formatUuid(bytes) {
194
+ const h = bytes.toString('hex');
195
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20, 32)}`;
196
+ }
197
+ /**
198
+ * A new uid for a row this build creates: a random UUIDv7.
199
+ *
200
+ * @param birthMs - The row's own birth, for a row imported with one (an
201
+ * importer must never stamp import time into an old row's uid).
202
+ * @returns Canonical lowercase UUID string.
203
+ */
204
+ export function mintRowUid(birthMs) {
205
+ return birthMs === undefined ? uuidv7() : uuidv7(birthMs);
206
+ }
207
+ /**
208
+ * The deterministic uid of a minted row that has none: a v7 layout whose
209
+ * timestamp is the row's birth and whose other 74 bits come from SHA-256 over
210
+ * the row's identity. An unknown birth gives timestamp 0; the row's birth
211
+ * fingerprint flags it (`birth:unknown`), and {@link rowIdentityFindings}
212
+ * lists it.
213
+ *
214
+ * @param scope - Store scope.
215
+ * @param table - Physical table name.
216
+ * @param key - Local key values.
217
+ * @param birth - Stored birth value (any format, or null).
218
+ * @param ownerUids - Uids of the owning rows.
219
+ * @param content - Frozen content values of an append-only row.
220
+ * @returns Canonical lowercase UUID string.
221
+ */
222
+ export function mintedRowUid(scope, table, key, birth, ownerUids = [], content = []) {
223
+ const birthMs = parseStoreTimestamp(birth);
224
+ const canonicalBirth = birthMs ?? birth;
225
+ const h = createHash('sha256')
226
+ .update(encodeUidInputs([
227
+ ROW_UID_DOMAIN,
228
+ 'minted',
229
+ scope,
230
+ table,
231
+ ...key,
232
+ canonicalBirth,
233
+ ...ownerUids,
234
+ ...content,
235
+ ]))
236
+ .digest();
237
+ const ms = birthMs !== null && birthMs >= 0 && birthMs <= MAX_UUID_MS ? birthMs : 0;
238
+ const b = Buffer.alloc(16);
239
+ b.writeUIntBE(ms, 0, 6);
240
+ b[6] = 0x70 | ((h[0] ?? 0) & 0x0f);
241
+ b[7] = h[1] ?? 0;
242
+ b[8] = 0x80 | ((h[2] ?? 0) & 0x3f);
243
+ h.copy(b, 9, 3, 10);
244
+ return formatUuid(b);
245
+ }
246
+ /**
247
+ * The new uid of a minted child row when its owner is re-keyed (spec §6.4):
248
+ * derived from STORED identity only (the child's old uid and the owner's new
249
+ * uid), never from a local key or content, so every replica that computes it
250
+ * gets the same value whatever display ids it holds. The child's timestamp
251
+ * bits are kept; the other 74 bits come from SHA-256.
252
+ *
253
+ * @param scope - Store scope.
254
+ * @param table - Physical table of the child.
255
+ * @param oldChildUid - The child's uid before the re-key.
256
+ * @param newOwnerUid - The owner's new uid.
257
+ * @returns Canonical lowercase UUID string.
258
+ */
259
+ export function rekeyedChildUid(scope, table, oldChildUid, newOwnerUid) {
260
+ const h = createHash('sha256')
261
+ .update(encodeUidInputs([ROW_UID_DOMAIN, 'rekey-child', scope, table, oldChildUid, newOwnerUid]))
262
+ .digest();
263
+ const b = Buffer.alloc(16);
264
+ Buffer.from(oldChildUid.replaceAll('-', '').slice(0, 12), 'hex').copy(b, 0);
265
+ b[6] = 0x70 | ((h[0] ?? 0) & 0x0f);
266
+ b[7] = h[1] ?? 0;
267
+ b[8] = 0x80 | ((h[2] ?? 0) & 0x3f);
268
+ h.copy(b, 9, 3, 10);
269
+ return formatUuid(b);
270
+ }
271
+ /**
272
+ * The uid of a natural row: a UUIDv8 over (scope, table, key), with every
273
+ * reference in the key already replaced by the referenced row's uid.
274
+ *
275
+ * @param scope - Store scope.
276
+ * @param table - Physical table name.
277
+ * @param parts - Key values, references as uids.
278
+ * @param recipe - `natural-mirror` for the reversed twin of a symmetric edge.
279
+ * @returns Canonical lowercase UUID string.
280
+ */
281
+ export function naturalRowUid(scope, table, parts, recipe = 'natural') {
282
+ const h = createHash('sha256')
283
+ .update(encodeUidInputs([ROW_UID_DOMAIN, recipe, scope, table, ...parts]))
284
+ .digest();
285
+ const b = Buffer.from(h.subarray(0, 16));
286
+ b[6] = 0x80 | ((b[6] ?? 0) & 0x0f);
287
+ b[8] = 0x80 | ((b[8] ?? 0) & 0x3f);
288
+ return formatUuid(b);
289
+ }
290
+ /**
291
+ * The birth-token part of a birth fingerprint: the stored birth at full
292
+ * precision, or a flag when it is missing or unparseable.
293
+ */
294
+ function birthToken(birth) {
295
+ if (birth === null)
296
+ return 'birth:unknown';
297
+ const ms = parseStoreTimestamp(birth);
298
+ if (ms !== null)
299
+ return `ms:${ms}`;
300
+ return `birth:unparseable:${canonicalText(String(birth))}`;
301
+ }
302
+ /**
303
+ * Canonical form of a text input to a birth fingerprint: Unicode NFC, line
304
+ * endings as LF, surrounding whitespace trimmed. Two stores that hold the same
305
+ * text in different normal forms fingerprint it identically.
306
+ *
307
+ * @param text - Stored text.
308
+ * @returns The canonical text.
309
+ */
310
+ export function canonicalText(text) {
311
+ return text.normalize('NFC').replace(/\r\n?/g, '\n').trim();
312
+ }
313
+ /** Canonicalise one birth-fact value (text as {@link canonicalText}; others as stored). */
314
+ function canonicalFact(value) {
315
+ return typeof value === 'string' ? canonicalText(value) : value;
316
+ }
317
+ /**
318
+ * A minted row's birth fingerprint: 128 bits of SHA-256 over the canonical
319
+ * birth (epoch ms when it parses, so a format-only difference fingerprints
320
+ * alike; a flagged token otherwise) and the table's frozen birth facts, each
321
+ * canonicalised ({@link canonicalText}). Computed ONCE, when the row first
322
+ * gets its identity, from the row as it is then; never recomputed. It is
323
+ * write-once and syncs with the row: a receiver stores the value it receives.
324
+ *
325
+ * @param table - Physical table name.
326
+ * @param birth - Stored birth value.
327
+ * @param facts - Birth fact values, in declared order.
328
+ * @returns 32 lowercase hex characters.
329
+ */
330
+ export function birthFingerprint(table, birth, facts) {
331
+ return createHash('sha256')
332
+ .update(encodeUidInputs([ROW_BIRTH_DOMAIN, table, birthToken(birth), ...facts.map(canonicalFact)]))
333
+ .digest('hex')
334
+ .slice(0, 32);
335
+ }
336
+ /**
337
+ * Classify two rows of one table that carry the same uid (merge contract,
338
+ * spec §6.4): equal birth fingerprints are one row; different ones are a
339
+ * COLLISION that must never be merged; a missing fingerprint must be filled
340
+ * before the row is emitted.
341
+ *
342
+ * @param a - Birth fingerprint of one row.
343
+ * @param b - Birth fingerprint of the other.
344
+ * @returns The relation.
345
+ */
346
+ export function classifyUidMatch(a, b) {
347
+ if (a === null || b === null)
348
+ return 'unknown';
349
+ return a === b ? 'same-row' : 'collision';
350
+ }
351
+ /** Quote an identifier for SQL. */
352
+ function q(name) {
353
+ return `"${name.replaceAll('"', '""')}"`;
354
+ }
355
+ /** The local key column of a referenced table (its declared single-column key). */
356
+ function targetKey(scope, table) {
357
+ const target = rowIdentitySpec(scope, table);
358
+ if (!target || target.key.length !== 1) {
359
+ throw new Error(`row identity: ${table} is not a declared single-key table`);
360
+ }
361
+ return target.key[0];
362
+ }
363
+ /** SQL for the uid of the row `ref` points at, read from `row`. */
364
+ function refUidSql(scope, ref, row) {
365
+ return (`(SELECT _r.${q(UID_COLUMN)} FROM main.${q(ref.table)} AS _r ` +
366
+ `WHERE _r.${q(targetKey(scope, ref.table))} = ${row}.${q(ref.column)})`);
367
+ }
368
+ /** SQL for "the row `ref` points at exists". */
369
+ function refExistsSql(scope, ref, row) {
370
+ return (`EXISTS(SELECT 1 FROM main.${q(ref.table)} AS _e ` +
371
+ `WHERE _e.${q(targetKey(scope, ref.table))} = ${row}.${q(ref.column)})`);
372
+ }
373
+ /** A reference passed to the uid function as (uid, raw key, target exists). */
374
+ function refArgs(scope, ref, row) {
375
+ return [refUidSql(scope, ref, row), `${row}.${q(ref.column)}`, refExistsSql(scope, ref, row)];
376
+ }
377
+ /**
378
+ * Resolve one reference argument triple: the target's uid; `dangling:<key>`
379
+ * when the target does not exist; `undefined` when it exists but has no uid
380
+ * yet (fill later).
381
+ */
382
+ function resolveRef(uid, raw, exists) {
383
+ if (uid !== null)
384
+ return uid;
385
+ if (raw === null)
386
+ return null;
387
+ if (Number(exists) === 1)
388
+ return undefined;
389
+ return `dangling:${String(raw)}`;
390
+ }
391
+ /** Whether a table's symmetric-type twin check applies (two key refs). */
392
+ function symmetricTwinSql(spec, row) {
393
+ const [a, b] = spec.keyRefs ?? [];
394
+ const sym = spec.symmetric;
395
+ if (!a || !b || !sym)
396
+ throw new Error(`row identity: ${spec.table} symmetric needs two key refs`);
397
+ return (`EXISTS(SELECT 1 FROM main.${q(spec.table)} AS _t WHERE _t.${q(a.column)} = ${row}.${q(b.column)} ` +
398
+ `AND _t.${q(b.column)} = ${row}.${q(a.column)} AND _t.${q(sym.column)} = ${row}.${q(sym.column)})`);
399
+ }
400
+ /**
401
+ * The uid-function arguments of one table, as SQL over `row` (`NEW` inside a
402
+ * trigger, the qualified table name inside an UPDATE).
403
+ */
404
+ function uidArgSql(scope, spec, row) {
405
+ const col = (name) => `${row}.${q(name)}`;
406
+ if (spec.kind === 'minted') {
407
+ return [
408
+ ...spec.key.map(col),
409
+ spec.birth ? col(spec.birth) : 'NULL',
410
+ ...(spec.owners ?? []).flatMap((ref) => refArgs(scope, ref, row)),
411
+ ...(spec.content ?? []).map(col),
412
+ ];
413
+ }
414
+ return [
415
+ ...spec.key.flatMap((column) => {
416
+ const ref = spec.keyRefs?.find((r) => r.column === column);
417
+ return ref ? refArgs(scope, ref, row) : [col(column)];
418
+ }),
419
+ ...(spec.symmetric ? [symmetricTwinSql(spec, row)] : []),
420
+ ];
421
+ }
422
+ /** SQL call of the uid function for one table; `variant` 1 forces the mirror recipe. */
423
+ function uidCallSql(scope, spec, row, variant = 0) {
424
+ if (spec.randomOnly)
425
+ return `${ROW_RANDOM_UID_SQL_FUNCTION}()`;
426
+ const args = uidArgSql(scope, spec, row);
427
+ return `${ROW_UID_SQL_FUNCTION}(${[`'${spec.table}'`, String(variant), ...args].join(', ')})`;
428
+ }
429
+ /**
430
+ * Compute a deterministic uid from the arguments the SQL function receives,
431
+ * in {@link uidArgSql} order. Returns `null` while a referenced row exists but
432
+ * has no uid yet.
433
+ */
434
+ function uidFromArgs(scope, table, variant, args) {
435
+ const spec = rowIdentitySpec(scope, table);
436
+ if (!spec)
437
+ throw new Error(`row identity: ${table} is not declared in scope ${scope}`);
438
+ let i = 0;
439
+ const take = () => {
440
+ if (i >= args.length)
441
+ throw new Error(`row identity: ${table} got too few arguments`);
442
+ return args[i++] ?? null;
443
+ };
444
+ const takeRef = () => resolveRef(take(), take(), take());
445
+ if (spec.kind === 'minted') {
446
+ const key = spec.key.map(() => take());
447
+ const birth = take();
448
+ const owners = [];
449
+ for (const _ of spec.owners ?? []) {
450
+ const owner = takeRef();
451
+ if (owner === undefined)
452
+ return null;
453
+ owners.push(owner);
454
+ }
455
+ const content = (spec.content ?? []).map(() => take());
456
+ return mintedRowUid(scope, table, key, birth, owners, content);
457
+ }
458
+ const parts = [];
459
+ for (const column of spec.key) {
460
+ if (spec.keyRefs?.some((r) => r.column === column)) {
461
+ const value = takeRef();
462
+ if (value === undefined)
463
+ return null;
464
+ parts.push(value);
465
+ }
466
+ else
467
+ parts.push(take());
468
+ }
469
+ if (!spec.symmetric)
470
+ return naturalRowUid(scope, table, parts);
471
+ const twinExists = Number(take()) === 1;
472
+ const typeIndex = spec.key.indexOf(spec.symmetric.column);
473
+ const type = parts[typeIndex];
474
+ if (typeof type !== 'string' || !spec.symmetric.values.includes(type)) {
475
+ return naturalRowUid(scope, table, parts);
476
+ }
477
+ const [a, b] = [parts[0], parts[1]].map((p) => String(p));
478
+ const sorted = a <= b ? [a, b] : [b, a];
479
+ const rest = parts.filter((_, k) => k > 1);
480
+ const mirror = variant === 1 || (a > b && twinExists);
481
+ return naturalRowUid(scope, table, [...sorted, ...rest], mirror ? 'natural-mirror' : 'natural');
482
+ }
483
+ /** SQL for one birth fact of a minted table. */
484
+ function birthFactSql(scope, spec, fact, row) {
485
+ const target = fingerprintRef(scope, spec, fact);
486
+ if (target) {
487
+ // The referenced row's fingerprint; a flag when there is no reference or
488
+ // the row is gone; NULL (wait) while it exists without a fingerprint.
489
+ const match = `_r.${q(target.key)} = ${row}.${q(target.column)}`;
490
+ return (`(CASE WHEN ${row}.${q(target.column)} IS NULL THEN 'ref:none' ` +
491
+ `WHEN NOT EXISTS (SELECT 1 FROM main.${q(target.table)} AS _r WHERE ${match}) THEN 'ref:missing' ` +
492
+ `ELSE (SELECT _r.${q(BIRTH_FP_COLUMN)} FROM main.${q(target.table)} AS _r WHERE ${match}) END)`);
493
+ }
494
+ return `${row}.${q(fact)}`;
495
+ }
496
+ /**
497
+ * The row a fingerprint fact reads the fingerprint of: `@ownerFp:<column>` is
498
+ * the owner that column references (matched on the owner's key);
499
+ * `@refFp:<column>` is a stored reference uid column (matched on the uid).
500
+ */
501
+ function fingerprintRef(scope, spec, fact) {
502
+ if (fact.startsWith('@ownerFp:')) {
503
+ const column = fact.slice('@ownerFp:'.length);
504
+ const ref = spec.owners?.find((r) => r.column === column);
505
+ if (!ref)
506
+ throw new Error(`row identity: ${spec.table} birth fact ${fact} names no owner`);
507
+ return { table: ref.table, column, key: targetKey(scope, ref.table) };
508
+ }
509
+ if (fact.startsWith('@refFp:')) {
510
+ const column = fact.slice('@refFp:'.length);
511
+ const ref = spec.storedRefUids?.find((r) => r.column === column && (r.source ?? 'uid') === 'uid');
512
+ if (!ref)
513
+ throw new Error(`row identity: ${spec.table} birth fact ${fact} names no stored uid`);
514
+ return { table: ref.table, column, key: UID_COLUMN };
515
+ }
516
+ return null;
517
+ }
518
+ /** Minted tables ordered so a table comes after every table its fingerprint facts read. */
519
+ function fingerprintOrder(scope, specs) {
520
+ const minted = specs.filter((s) => s.kind === 'minted');
521
+ const deps = (spec) => (spec.birthFacts ?? [])
522
+ .map((f) => fingerprintRef(scope, spec, f)?.table)
523
+ .filter((t) => t !== undefined && t !== spec.table);
524
+ const done = new Set();
525
+ const out = [];
526
+ let pending = [...minted];
527
+ while (pending.length > 0) {
528
+ const ready = pending.filter((s) => deps(s).every((t) => done.has(t) || !minted.some((m) => m.table === t)));
529
+ if (ready.length === 0)
530
+ throw new Error('row identity: cyclic fingerprint facts');
531
+ for (const s of ready) {
532
+ out.push(s);
533
+ done.add(s.table);
534
+ }
535
+ pending = pending.filter((s) => !ready.includes(s));
536
+ }
537
+ return out;
538
+ }
539
+ /** SQL call of the birth-fingerprint function for one minted table. */
540
+ function birthFpCallSql(scope, spec, row) {
541
+ const birth = spec.birth ? `${row}.${q(spec.birth)}` : 'NULL';
542
+ const facts = (spec.birthFacts ?? []).map((f) => birthFactSql(scope, spec, f, row));
543
+ return `${ROW_BIRTH_FP_SQL_FUNCTION}(${[`'${spec.table}'`, birth, ...facts].join(', ')})`;
544
+ }
545
+ /** SQL for a stored reference fact (`ac_uid`, `ac_text_hash`) read from `row`. */
546
+ function storedRefSql(scope, ref, row) {
547
+ if (ref.source === 'text_hash') {
548
+ return (`${AC_TEXT_HASH_SQL_FUNCTION}((SELECT _r.${q('text')} FROM main.${q(ref.table)} AS _r ` +
549
+ `WHERE _r.${q(targetKey(scope, ref.table))} = ${row}.${q(ref.from)}))`);
550
+ }
551
+ return refUidSql(scope, { column: ref.from, table: ref.table }, row);
552
+ }
553
+ /**
554
+ * Register the identity SQL functions on a connection: the deterministic uid
555
+ * and birth fingerprint, the AC text hash, and a random v7 for `randomOnly`
556
+ * tables.
557
+ *
558
+ * @param db - Connection on a `cleo.db`.
559
+ * @param scope - The store's scope.
560
+ */
561
+ export function registerRowUidFunction(db, scope) {
562
+ db.function(ROW_UID_SQL_FUNCTION, { varargs: true, deterministic: true }, (table, variant, ...args) => {
563
+ if (typeof table !== 'string')
564
+ throw new Error('row identity: table name must be text');
565
+ return uidFromArgs(scope, table, Number(variant), args);
566
+ });
567
+ db.function(ROW_BIRTH_FP_SQL_FUNCTION, { varargs: true, deterministic: true }, (table, birth, ...facts) => {
568
+ if (typeof table !== 'string')
569
+ throw new Error('row identity: table name must be text');
570
+ const spec = rowIdentitySpec(scope, table);
571
+ const ownerFacts = (spec?.birthFacts ?? []).map((f) => f.startsWith('@ownerFp:') || f.startsWith('@refFp:'));
572
+ if (facts.some((v, k) => ownerFacts[k] && v === null))
573
+ return null;
574
+ return birthFingerprint(table, birth, facts);
575
+ });
576
+ db.function(AC_TEXT_HASH_SQL_FUNCTION, { deterministic: true }, (text) => typeof text === 'string' ? acTextHash(text) : null);
577
+ db.function(ROW_RANDOM_UID_SQL_FUNCTION, { deterministic: false }, () => mintRowUid());
578
+ }
579
+ /** Whether a table exists in `main`. */
580
+ function hasTable(db, table) {
581
+ return (db.prepare("SELECT 1 FROM main.sqlite_master WHERE type = 'table' AND name = ?").get(table) !==
582
+ undefined);
583
+ }
584
+ /** Column names of a `main` table. */
585
+ function columnsOf(db, table) {
586
+ const rows = db.prepare('SELECT name FROM pragma_table_info(?)').all(table);
587
+ return new Set(rows.map((r) => r.name));
588
+ }
589
+ /** Declared tables present in this store, minted before natural, owners before children. */
590
+ function fillOrder(db, scope) {
591
+ const present = ROW_IDENTITY[scope].filter((spec) => hasTable(db, spec.table));
592
+ const done = new Set();
593
+ const ordered = [];
594
+ const deps = (spec) => [...(spec.owners ?? []), ...(spec.keyRefs ?? [])]
595
+ .map((ref) => ref.table)
596
+ .filter((t) => t !== spec.table);
597
+ for (const kind of ['minted', 'natural']) {
598
+ let pending = present.filter((spec) => spec.kind === kind);
599
+ while (pending.length > 0) {
600
+ const ready = pending.filter((spec) => deps(spec).every((t) => done.has(t) || !present.some((p) => p.table === t)));
601
+ if (ready.length === 0) {
602
+ throw new Error(`row identity: cyclic owners among ${pending.map((s) => s.table).join(', ')}`);
603
+ }
604
+ for (const spec of ready) {
605
+ ordered.push(spec);
606
+ done.add(spec.table);
607
+ }
608
+ pending = pending.filter((spec) => !ready.includes(spec));
609
+ }
610
+ }
611
+ return ordered;
612
+ }
613
+ /** Whether the uid column is the table's primary key (no separate index needed). */
614
+ function uidIsPrimaryKey(db, table) {
615
+ const rows = db.prepare('SELECT name, pk FROM pragma_table_info(?)').all(table);
616
+ return rows.some((r) => r.name === UID_COLUMN && r.pk > 0);
617
+ }
618
+ /**
619
+ * Re-assert the identity columns and indexes of every declared table present
620
+ * in the store. Idempotent; the migration normally created them already.
621
+ *
622
+ * @param db - Connection on a `cleo.db`.
623
+ * @param scope - The store's scope.
624
+ * @returns Statements that had to be run (empty on a healthy store).
625
+ */
626
+ export function ensureRowIdentitySchema(db, scope) {
627
+ const healed = [];
628
+ for (const spec of ROW_IDENTITY[scope]) {
629
+ if (!hasTable(db, spec.table))
630
+ continue;
631
+ const cols = columnsOf(db, spec.table);
632
+ for (const column of rowIdentityColumns(scope, spec.table)) {
633
+ if (cols.has(column))
634
+ continue;
635
+ const stmt = `ALTER TABLE main.${q(spec.table)} ADD COLUMN ${q(column)} TEXT`;
636
+ db.exec(stmt);
637
+ healed.push(stmt);
638
+ }
639
+ const indexes = [];
640
+ if (!uidIsPrimaryKey(db, spec.table)) {
641
+ indexes.push(`CREATE UNIQUE INDEX IF NOT EXISTS main.${q(`uq_${spec.table}_uid`)} ON ${q(spec.table)} (${q(UID_COLUMN)})`);
642
+ }
643
+ for (const ref of spec.storedRefUids ?? []) {
644
+ indexes.push(`CREATE INDEX IF NOT EXISTS main.${q(`idx_${spec.table}_${ref.column}`)} ON ${q(spec.table)} (${q(ref.column)})`);
645
+ }
646
+ for (const stmt of indexes) {
647
+ const name = /INDEX IF NOT EXISTS main\."([^"]+)"/.exec(stmt)?.[1];
648
+ const exists = db
649
+ .prepare("SELECT 1 FROM main.sqlite_master WHERE type = 'index' AND name = ?")
650
+ .get(name ?? '') !== undefined;
651
+ if (exists)
652
+ continue;
653
+ db.exec(stmt);
654
+ healed.push(stmt);
655
+ }
656
+ }
657
+ return healed;
658
+ }
659
+ /** Count of rows with a NULL value in `column`. */
660
+ function nullCount(db, table, column) {
661
+ const row = db
662
+ .prepare(`SELECT count(*) AS n FROM main.${q(table)} WHERE ${q(column)} IS NULL`)
663
+ .get();
664
+ return row.n;
665
+ }
666
+ /** Whether an error is a SQLite UNIQUE constraint failure. */
667
+ function isUniqueViolation(error) {
668
+ return error instanceof Error && /UNIQUE constraint failed/i.test(error.message);
669
+ }
670
+ /**
671
+ * Fill the NULL uids of one table. A bulk UPDATE normally does it; if a
672
+ * computed uid clashes with an existing one, the rows are filled one by one
673
+ * (a symmetric edge then tries its mirror recipe) and a row that still clashes
674
+ * keeps its NULL (reported, never fatal).
675
+ */
676
+ function fillTable(db, scope, spec, writers) {
677
+ const before = nullCount(db, spec.table, UID_COLUMN);
678
+ if (before === 0)
679
+ return 0;
680
+ const table = `main.${q(spec.table)}`;
681
+ const fill = (variant, rowid) => writers.fillIdentityColumnNative(db, spec.table, UID_COLUMN, uidCallSql(scope, spec, table, variant), rowid);
682
+ db.exec('SAVEPOINT row_uid_fill_table');
683
+ try {
684
+ fill(0);
685
+ db.exec('RELEASE SAVEPOINT row_uid_fill_table');
686
+ }
687
+ catch (error) {
688
+ db.exec('ROLLBACK TO SAVEPOINT row_uid_fill_table');
689
+ db.exec('RELEASE SAVEPOINT row_uid_fill_table');
690
+ if (!isUniqueViolation(error))
691
+ throw error;
692
+ const rowids = db
693
+ .prepare(`SELECT rowid AS r FROM ${table} WHERE ${q(UID_COLUMN)} IS NULL ORDER BY rowid`)
694
+ .all();
695
+ const variants = spec.symmetric ? [0, 1] : [0];
696
+ for (const { r } of rowids) {
697
+ for (const variant of variants) {
698
+ try {
699
+ if (fill(variant, r) > 0)
700
+ break;
701
+ }
702
+ catch (rowError) {
703
+ if (!isUniqueViolation(rowError))
704
+ throw rowError;
705
+ }
706
+ }
707
+ }
708
+ }
709
+ return before - nullCount(db, spec.table, UID_COLUMN);
710
+ }
711
+ /**
712
+ * Fill the NULL uids of one declared table (the open pass's recipe). Requires
713
+ * {@link registerRowUidFunction} on the connection. Used after a uid re-key,
714
+ * which clears the uids of the natural rows keyed by the re-keyed row.
715
+ *
716
+ * @param db - Connection on a `cleo.db`.
717
+ * @param scope - The store's scope.
718
+ * @param table - Declared table.
719
+ * @returns Uids written.
720
+ */
721
+ export function fillTableUids(db, scope, table, writers = requireWriters()) {
722
+ const spec = rowIdentitySpec(scope, table);
723
+ if (!spec)
724
+ throw new Error(`row identity: ${table} is not declared in scope ${scope}`);
725
+ return fillTable(db, scope, spec, writers);
726
+ }
727
+ /** Fill the stored reference facts (`ac_uid`, `ac_text_hash`) that resolve. */
728
+ function fillStoredRefs(db, scope, spec, out, writers) {
729
+ const table = `main.${q(spec.table)}`;
730
+ for (const ref of spec.storedRefUids ?? []) {
731
+ const before = nullCount(db, spec.table, ref.column);
732
+ if (before === 0)
733
+ continue;
734
+ writers.fillIdentityColumnNative(db, spec.table, ref.column, storedRefSql(scope, ref, table));
735
+ const written = before - nullCount(db, spec.table, ref.column);
736
+ if (written > 0)
737
+ out[`${spec.table}.${ref.column}`] = written;
738
+ }
739
+ }
740
+ /** Fill the NULL birth fingerprints of one minted table. */
741
+ function fillBirthFp(db, scope, spec, writers) {
742
+ if (spec.kind !== 'minted')
743
+ return 0;
744
+ const before = nullCount(db, spec.table, BIRTH_FP_COLUMN);
745
+ if (before === 0)
746
+ return 0;
747
+ const table = `main.${q(spec.table)}`;
748
+ writers.fillIdentityColumnNative(db, spec.table, BIRTH_FP_COLUMN, birthFpCallSql(scope, spec, table));
749
+ return before - nullCount(db, spec.table, BIRTH_FP_COLUMN);
750
+ }
751
+ /**
752
+ * Re-link acceptance criteria an older build deleted and recreated without
753
+ * their uid (spec §6.5). For each task with criteria lacking a uid, the uids
754
+ * its deleted criteria carried (recorded by the graveyard trigger) are handed
755
+ * back by the carry rule of `planAcUpdate`: same text first, then same
756
+ * ordinal. Returns how many criteria got their uid back. The graveyard is
757
+ * emptied afterwards: an entry whose criterion was not recreated is a real
758
+ * deletion.
759
+ */
760
+ function relinkAcUids(db, writers) {
761
+ if (!hasTable(db, AC_UID_GRAVEYARD) || !hasTable(db, 'tasks_task_acceptance_criteria'))
762
+ return 0;
763
+ let relinked = 0;
764
+ const orphans = db
765
+ .prepare(`SELECT id, task_id AS taskId, ordinal, text FROM main.tasks_task_acceptance_criteria
766
+ WHERE uid IS NULL AND task_id IN (SELECT task_id FROM main.${AC_UID_GRAVEYARD})
767
+ ORDER BY task_id, ordinal`)
768
+ .all();
769
+ const dead = db.prepare(`SELECT uid, ordinal, text, birth_fp AS birthFp FROM main.${AC_UID_GRAVEYARD} g
770
+ WHERE task_id = ? AND NOT EXISTS (SELECT 1 FROM main.tasks_task_acceptance_criteria a WHERE a.uid = g.uid)
771
+ ORDER BY seq DESC`);
772
+ const assign = (dead, acId) => writers.relinkAcUidNative(db, acId, dead.uid, dead.birthFp);
773
+ const byTask = new Map();
774
+ for (const row of orphans)
775
+ byTask.set(row.taskId, [...(byTask.get(row.taskId) ?? []), row]);
776
+ for (const [taskId, rows] of byTask) {
777
+ const seen = new Set();
778
+ const pool = dead.all(taskId).filter((d) => !seen.has(d.uid) && seen.add(d.uid));
779
+ const claimed = new Set();
780
+ const pick = (match) => pool.find((d) => !claimed.has(d.uid) && match(d));
781
+ const pending = rows.filter((row) => {
782
+ const same = pick((d) => d.text === row.text);
783
+ if (!same)
784
+ return true;
785
+ claimed.add(same.uid);
786
+ relinked += assign(same, row.id);
787
+ return false;
788
+ });
789
+ for (const row of pending) {
790
+ const same = pick((d) => d.ordinal === row.ordinal);
791
+ if (!same)
792
+ continue;
793
+ claimed.add(same.uid);
794
+ relinked += assign(same, row.id);
795
+ }
796
+ }
797
+ writers.clearAcUidGraveyardNative(db);
798
+ return relinked;
799
+ }
800
+ /** Count rows per table matching `where`, keeping non-zero counts. */
801
+ function countWhere(db, table, where, out) {
802
+ const n = db.prepare(`SELECT count(*) AS n FROM main.${q(table)} AS x WHERE ${where}`).get().n;
803
+ if (n > 0)
804
+ out[table] = n;
805
+ }
806
+ /**
807
+ * Rows the recipes flag: minted rows with an unknown birth (uid timestamp 0),
808
+ * natural rows with a dangling key reference, and reversed twins of symmetric
809
+ * edges stored both ways.
810
+ *
811
+ * @param db - Connection on a `cleo.db`.
812
+ * @param scope - The store's scope.
813
+ * @returns Counts per table (tables without findings are absent).
814
+ */
815
+ export function rowIdentityFindings(db, scope) {
816
+ const unknownBirth = {};
817
+ const danglingRefs = {};
818
+ const mirrorEdges = {};
819
+ for (const spec of ROW_IDENTITY[scope]) {
820
+ if (!hasTable(db, spec.table))
821
+ continue;
822
+ if (spec.kind === 'minted' && spec.birth) {
823
+ const b = `x.${q(spec.birth)}`;
824
+ countWhere(db, spec.table, `${b} IS NULL OR (julianday(replace(${b}, 'T', ' ')) IS NULL AND julianday(${b}) IS NULL)`, unknownBirth);
825
+ }
826
+ const refs = spec.kind === 'natural' ? (spec.keyRefs ?? []) : (spec.owners ?? []);
827
+ if (refs.length > 0) {
828
+ countWhere(db, spec.table, refs
829
+ .map((ref) => `(x.${q(ref.column)} IS NOT NULL AND NOT ${refExistsSql(scope, ref, 'x')})`)
830
+ .join(' OR '), danglingRefs);
831
+ }
832
+ if (spec.symmetric) {
833
+ const [a, b] = spec.keyRefs ?? [];
834
+ if (a && b) {
835
+ const values = spec.symmetric.values.map((v) => `'${v.replaceAll("'", "''")}'`).join(', ');
836
+ countWhere(db, spec.table, `x.${q(spec.symmetric.column)} IN (${values}) AND ${symmetricTwinSql(spec, 'x')} ` +
837
+ `AND ${refUidSql(scope, a, 'x')} > ${refUidSql(scope, b, 'x')}`, mirrorEdges);
838
+ }
839
+ }
840
+ }
841
+ return { unknownBirth, danglingRefs, mirrorEdges };
842
+ }
843
+ /**
844
+ * Fill every NULL uid, stored reference fact and birth fingerprint of the
845
+ * declared tables, in one savepoint, after re-linking graveyard AC uids.
846
+ * Requires {@link registerRowUidFunction} on the connection. Idempotent: a
847
+ * filled store writes nothing.
848
+ *
849
+ * @param db - Connection on a `cleo.db`.
850
+ * @param scope - The store's scope.
851
+ * @returns What was written and what could not be.
852
+ */
853
+ export function fillRowUids(db, scope, writers = requireWriters()) {
854
+ const filled = {};
855
+ const refsFilled = {};
856
+ const fingerprinted = {};
857
+ const unfilled = {};
858
+ const order = fillOrder(db, scope);
859
+ db.exec('SAVEPOINT row_uid_fill');
860
+ try {
861
+ const relinked = scope === 'project' ? relinkAcUids(db, writers) : 0;
862
+ for (const spec of order) {
863
+ const n = fillTable(db, scope, spec, writers);
864
+ if (n > 0)
865
+ filled[spec.table] = n;
866
+ }
867
+ for (const spec of order)
868
+ fillStoredRefs(db, scope, spec, refsFilled, writers);
869
+ for (const spec of fingerprintOrder(scope, order)) {
870
+ const n = fillBirthFp(db, scope, spec, writers);
871
+ if (n > 0)
872
+ fingerprinted[spec.table] = n;
873
+ }
874
+ for (const spec of order) {
875
+ const left = nullCount(db, spec.table, UID_COLUMN) +
876
+ (spec.kind === 'minted' ? nullCount(db, spec.table, BIRTH_FP_COLUMN) : 0);
877
+ if (left > 0)
878
+ unfilled[spec.table] = left;
879
+ }
880
+ db.exec('RELEASE SAVEPOINT row_uid_fill');
881
+ return { filled, refsFilled, fingerprinted, relinked, unfilled };
882
+ }
883
+ catch (error) {
884
+ db.exec('ROLLBACK TO SAVEPOINT row_uid_fill');
885
+ db.exec('RELEASE SAVEPOINT row_uid_fill');
886
+ throw error;
887
+ }
888
+ }
889
+ /**
890
+ * Install the per-connection TEMP triggers that fill a uid, the stored
891
+ * reference facts and the birth fingerprint on insert, in that order. Each
892
+ * step is guarded so the trigger never fails the insert: a uid that would
893
+ * clash is left NULL (a symmetric edge first tries its mirror recipe).
894
+ * Requires {@link registerRowUidFunction}.
895
+ *
896
+ * @param db - Connection on a `cleo.db`.
897
+ * @param scope - The store's scope.
898
+ */
899
+ export function installRowUidTriggers(db, scope) {
900
+ for (const spec of ROW_IDENTITY[scope]) {
901
+ if (!hasTable(db, spec.table) || uidIsPrimaryKey(db, spec.table))
902
+ continue;
903
+ const table = `main.${q(spec.table)}`;
904
+ const uid = q(UID_COLUMN);
905
+ const steps = [];
906
+ for (const variant of spec.symmetric ? [0, 1] : [0]) {
907
+ const value = uidCallSql(scope, spec, 'NEW', variant);
908
+ steps.push(`UPDATE ${table} SET ${uid} = ${value} WHERE rowid = NEW.rowid AND ${uid} IS NULL ` +
909
+ `AND NOT EXISTS (SELECT 1 FROM ${table} AS _u WHERE _u.${uid} = ${value});`);
910
+ }
911
+ for (const ref of spec.storedRefUids ?? []) {
912
+ steps.push(`UPDATE ${table} SET ${q(ref.column)} = ${storedRefSql(scope, ref, 'NEW')} ` +
913
+ `WHERE rowid = NEW.rowid AND ${q(ref.column)} IS NULL;`);
914
+ }
915
+ if (spec.kind === 'minted') {
916
+ // Reads the row as stored, so the facts filled above (ac_text_hash) count.
917
+ steps.push(`UPDATE ${table} SET ${q(BIRTH_FP_COLUMN)} = ${birthFpCallSql(scope, spec, table)} ` +
918
+ `WHERE rowid = NEW.rowid AND ${q(BIRTH_FP_COLUMN)} IS NULL;`);
919
+ }
920
+ db.exec(`CREATE TEMP TRIGGER IF NOT EXISTS ${q(`trg_row_uid_${spec.table}`)} ` +
921
+ `AFTER INSERT ON ${table} BEGIN ${steps.join(' ')} END`);
922
+ }
923
+ }
924
+ /**
925
+ * Bring a freshly opened `cleo.db` connection's row identity up to date:
926
+ * schema, graveyard re-link, fill, per-connection triggers. Never throws: a
927
+ * failure is logged and the store opens with the values it has.
928
+ *
929
+ * @param db - Connection on a `cleo.db`, after its migrations ran.
930
+ * @param scope - The store's scope.
931
+ * @param options - `triggers: false` skips the per-connection triggers (a
932
+ * dedicated migration connection: exodus refuses copies whose triggers call
933
+ * an opaque function, so its rows are filled at the next open instead).
934
+ * @returns The fill report, or `null` when skipped or failed.
935
+ */
936
+ /**
937
+ * Version of every identity recipe this build derives (uid, natural uid,
938
+ * birth fingerprint, encoding). Written to {@link ROW_IDENTITY_META_TABLE} under
939
+ * {@link ROW_IDENTITY_RECIPE_KEY} by the first fill; bumped by any change to a
940
+ * recipe, a frozen content or birth-fact list, or the encoding.
941
+ */
942
+ export const ROW_IDENTITY_RECIPE = 'cleo/row-identity/v2';
943
+ /**
944
+ * The recipe 9.25 shipped (v1). v2 changed only the birth facts of AC history
945
+ * and evidence bindings (@refFp:ac_uid and ac_text_hash → none / ac_id,
946
+ * T12802); a store filled
947
+ * with v1 has those two tables' fingerprints re-derived (see
948
+ * {@link v1ReleaseBirthFp}).
949
+ */
950
+ export const ROW_IDENTITY_RECIPE_V1 = 'cleo/row-identity/v1';
951
+ /**
952
+ * The v1 fingerprint of an AC-history or binding row, to recognise a value
953
+ * the 9.25 recipe derived: v1 hashed the criterion's fingerprint
954
+ * (`@refFp:ac_uid`), or `ref:none` / `ref:missing`. Other tables: `null`
955
+ * (their v1 and v2 recipes are the same).
956
+ *
957
+ * @param db - Connection on the project `cleo.db`.
958
+ * @param table - Declared minted table.
959
+ * @param row - The stored row.
960
+ * @returns The v1 value, or `null`.
961
+ * @task T12802
962
+ */
963
+ export function v1ReleaseBirthFp(db, table, row) {
964
+ const col = (c) => row[c] ?? null;
965
+ const facts = table === 'tasks_task_acceptance_criteria_history'
966
+ ? [col('ac_id'), col('previous_text'), col('reason')]
967
+ : table === 'tasks_evidence_ac_bindings'
968
+ ? [col('evidence_atom_id'), col('binding_type'), col('ac_text_hash')]
969
+ : [];
970
+ if (facts.length === 0)
971
+ return null;
972
+ const acUid = col('ac_uid');
973
+ let ref = 'ref:none';
974
+ if (acUid !== null) {
975
+ const ac = db
976
+ .prepare('SELECT birth_fp AS fp FROM main.tasks_task_acceptance_criteria WHERE uid = ?')
977
+ .get(acUid);
978
+ ref = ac === undefined ? 'ref:missing' : ac.fp;
979
+ if (ref === null)
980
+ return null;
981
+ }
982
+ const spec = rowIdentitySpec('project', table);
983
+ return birthFingerprint(table, spec?.birth ? col(spec.birth) : null, [...facts, ref]);
984
+ }
985
+ /**
986
+ * Local-only key/value table of the row-identity layer. Not
987
+ * `tasks_schema_meta`: the twin collapse drops twin-only keys of that table on
988
+ * its first run (T12535), which would lose the marker.
989
+ */
990
+ export const ROW_IDENTITY_META_TABLE = 'tasks_row_identity_meta';
991
+ /** Key holding the recipe version the store's identity values were derived with. */
992
+ export const ROW_IDENTITY_RECIPE_KEY = 'row_identity_recipe';
993
+ /**
994
+ * Key the sync layer (T12342/T12343) writes BEFORE the
995
+ * first uid leaves the device. Once present, identity values are shared and
996
+ * are never cleared locally.
997
+ */
998
+ export const ROW_IDENTITY_SYNCED_KEY = 'row_identity_synced';
999
+ /** Tables the uid migration creates, as `CREATE … IF NOT EXISTS` (kept equal to its SQL). */
1000
+ const IDENTITY_TABLE_DDL = {
1001
+ [ROW_IDENTITY_META_TABLE]: [
1002
+ `CREATE TABLE IF NOT EXISTS main.${ROW_IDENTITY_META_TABLE} (
1003
+ key TEXT PRIMARY KEY NOT NULL, value TEXT NOT NULL)`,
1004
+ ],
1005
+ tasks_display_id_aliases: [
1006
+ `CREATE TABLE IF NOT EXISTS main.tasks_display_id_aliases (
1007
+ uid TEXT PRIMARY KEY NOT NULL, entity_table TEXT NOT NULL, display_id TEXT NOT NULL,
1008
+ entity_uid TEXT NOT NULL, reason TEXT NOT NULL, origin TEXT, displaced_hlc TEXT,
1009
+ created_at TEXT NOT NULL, entity_birth_fp TEXT)`,
1010
+ 'CREATE INDEX IF NOT EXISTS main.idx_tasks_display_id_aliases_lookup ON tasks_display_id_aliases (entity_table, display_id)',
1011
+ 'CREATE INDEX IF NOT EXISTS main.idx_tasks_display_id_aliases_entity ON tasks_display_id_aliases (entity_uid)',
1012
+ ],
1013
+ tasks_uid_aliases: [
1014
+ `CREATE TABLE IF NOT EXISTS main.tasks_uid_aliases (
1015
+ uid TEXT PRIMARY KEY NOT NULL, entity_table TEXT NOT NULL, old_uid TEXT NOT NULL,
1016
+ old_birth_fp TEXT NOT NULL, new_uid TEXT NOT NULL, origin TEXT, displaced_hlc TEXT,
1017
+ created_at TEXT NOT NULL)`,
1018
+ 'CREATE INDEX IF NOT EXISTS main.idx_tasks_uid_aliases_old ON tasks_uid_aliases (entity_table, old_uid)',
1019
+ ],
1020
+ tasks_identity_quarantine: [
1021
+ `CREATE TABLE IF NOT EXISTS main.tasks_identity_quarantine (
1022
+ entity_table TEXT NOT NULL, uid TEXT NOT NULL, birth_fp TEXT NOT NULL, reason TEXT NOT NULL,
1023
+ contested_id TEXT, row_json TEXT NOT NULL, received_hlc TEXT, created_at TEXT NOT NULL,
1024
+ PRIMARY KEY (entity_table, uid, birth_fp))`,
1025
+ ],
1026
+ [AC_UID_GRAVEYARD]: [
1027
+ `CREATE TABLE IF NOT EXISTS main.${AC_UID_GRAVEYARD} (
1028
+ seq INTEGER PRIMARY KEY AUTOINCREMENT, ac_id TEXT NOT NULL, uid TEXT NOT NULL,
1029
+ task_id TEXT NOT NULL, ordinal INTEGER NOT NULL, text TEXT NOT NULL, birth_fp TEXT,
1030
+ deleted_at TEXT NOT NULL)`,
1031
+ `CREATE INDEX IF NOT EXISTS main.idx_${AC_UID_GRAVEYARD}_task ON ${AC_UID_GRAVEYARD} (task_id)`,
1032
+ ],
1033
+ };
1034
+ /** The graveyard's pure-SQL delete trigger (kept equal to the migration's). */
1035
+ const AC_UID_GRAVEYARD_TRIGGER = `CREATE TRIGGER IF NOT EXISTS main.trg_tasks_ac_uid_graveyard
1036
+ AFTER DELETE ON tasks_task_acceptance_criteria
1037
+ WHEN OLD.uid IS NOT NULL
1038
+ BEGIN
1039
+ INSERT INTO ${AC_UID_GRAVEYARD} (ac_id, uid, task_id, ordinal, text, birth_fp, deleted_at)
1040
+ VALUES (OLD.id, OLD.uid, OLD.task_id, OLD.ordinal, OLD.text, OLD.birth_fp, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
1041
+ END`;
1042
+ /** Whether a schema object of `type` named `name` exists in `main`. */
1043
+ function hasObject(db, type, name) {
1044
+ return (db.prepare('SELECT 1 FROM main.sqlite_master WHERE type = ? AND name = ?').get(type, name) !==
1045
+ undefined);
1046
+ }
1047
+ /**
1048
+ * Re-create the tables, trigger and columns the uid migration adds when they
1049
+ * are missing: a store the journal probe stamped as migrated after only its
1050
+ * ADD COLUMNs had run (Scenario 3, Case A) otherwise never gets them.
1051
+ * Idempotent.
1052
+ *
1053
+ * @param db - Connection on the project `cleo.db`.
1054
+ * @returns Statements that had to be run.
1055
+ */
1056
+ export function ensureIdentityTables(db) {
1057
+ if (!hasTable(db, 'tasks_task_acceptance_criteria'))
1058
+ return [];
1059
+ const healed = [];
1060
+ for (const [table, ddl] of Object.entries(IDENTITY_TABLE_DDL)) {
1061
+ const tableExisted = hasTable(db, table);
1062
+ for (const stmt of ddl) {
1063
+ const index = /INDEX IF NOT EXISTS main\.(\w+)/.exec(stmt)?.[1];
1064
+ if (index ? hasObject(db, 'index', index) : tableExisted)
1065
+ continue;
1066
+ db.exec(stmt);
1067
+ healed.push(stmt);
1068
+ }
1069
+ }
1070
+ // Columns an early pre-release table lacks (the live-cleocode state, §12.1).
1071
+ for (const [table, column] of [
1072
+ ['tasks_display_id_aliases', 'displaced_hlc'],
1073
+ ['tasks_display_id_aliases', 'entity_birth_fp'],
1074
+ [AC_UID_GRAVEYARD, 'birth_fp'],
1075
+ ]) {
1076
+ if (columnsOf(db, table).has(column))
1077
+ continue;
1078
+ const stmt = `ALTER TABLE main.${table} ADD COLUMN ${column} TEXT`;
1079
+ db.exec(stmt);
1080
+ healed.push(stmt);
1081
+ }
1082
+ if (!hasObject(db, 'trigger', 'trg_tasks_ac_uid_graveyard')) {
1083
+ db.exec(AC_UID_GRAVEYARD_TRIGGER);
1084
+ healed.push(AC_UID_GRAVEYARD_TRIGGER);
1085
+ }
1086
+ return healed;
1087
+ }
1088
+ /** A row-identity meta value, or `undefined` (also when the table is absent). */
1089
+ function readMeta(db, key) {
1090
+ if (!hasTable(db, ROW_IDENTITY_META_TABLE))
1091
+ return undefined;
1092
+ const row = db
1093
+ .prepare(`SELECT value FROM main.${ROW_IDENTITY_META_TABLE} WHERE key = ?`)
1094
+ .get(key);
1095
+ return row?.value;
1096
+ }
1097
+ /** The pre-release (v4/v5 build) parse of a birth: a zoneless SQLite value as UTC, else `Date.parse`. */
1098
+ function preReleaseParses(value) {
1099
+ if (typeof value !== 'string' || value.length === 0)
1100
+ return false;
1101
+ const iso = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}(:\d{2}(\.\d+)?)?$/.test(value)
1102
+ ? `${value.replace(' ', 'T')}Z`
1103
+ : value;
1104
+ return !Number.isNaN(Date.parse(iso));
1105
+ }
1106
+ /**
1107
+ * The birth fingerprint the pre-release v4/v5 build derived (the recipe that
1108
+ * reached live cleocode on 2026-09-28): raw birth text, raw facts, the task
1109
+ * title from the earliest `task_created` audit event, and an AC's OWNER UID
1110
+ * instead of its owner's fingerprint. Used only to recognise those values.
1111
+ *
1112
+ * @param db - Connection on the project `cleo.db`.
1113
+ * @param table - Minted table.
1114
+ * @param row - The stored row.
1115
+ * @returns The pre-release fingerprint, or `null` when the table had none.
1116
+ */
1117
+ export function preReleaseBirthFp(db, table, row) {
1118
+ const facts = [];
1119
+ const col = (c) => row[c] ?? null;
1120
+ switch (table) {
1121
+ case 'tasks_tasks': {
1122
+ let title = col('title');
1123
+ if (hasTable(db, 'tasks_audit_log')) {
1124
+ const ev = db
1125
+ .prepare(`SELECT json_extract(details_json, '$.title') AS t FROM main.tasks_audit_log
1126
+ WHERE task_id = ? AND +action = 'task_created' AND json_valid(details_json)
1127
+ ORDER BY +timestamp, +id LIMIT 1`)
1128
+ .get(col('id'));
1129
+ if (ev && ev.t !== null && ev.t !== undefined)
1130
+ title = ev.t;
1131
+ }
1132
+ facts.push(title, col('type'));
1133
+ break;
1134
+ }
1135
+ case 'tasks_sessions':
1136
+ facts.push(col('name'));
1137
+ break;
1138
+ case 'tasks_task_acceptance_criteria': {
1139
+ const owner = db
1140
+ .prepare('SELECT uid FROM main.tasks_tasks WHERE id = ?')
1141
+ .get(col('task_id'));
1142
+ facts.push(col('text'), owner?.uid ?? null);
1143
+ break;
1144
+ }
1145
+ case 'tasks_task_acceptance_criteria_history':
1146
+ facts.push(col('ac_id'), col('previous_text'), col('reason'));
1147
+ break;
1148
+ case 'tasks_evidence_ac_bindings':
1149
+ facts.push(col('evidence_atom_id'), col('binding_type'), col('ac_text_hash'));
1150
+ break;
1151
+ default:
1152
+ return null;
1153
+ }
1154
+ const spec = rowIdentitySpec('project', table);
1155
+ const birth = spec?.birth ? col(spec.birth) : null;
1156
+ const token = birth === null
1157
+ ? 'birth:unknown'
1158
+ : preReleaseParses(birth)
1159
+ ? String(birth)
1160
+ : `birth:unparseable:${String(birth)}`;
1161
+ return createHash('sha256')
1162
+ .update(encodeUidInputs([ROW_BIRTH_DOMAIN, table, token, ...facts]))
1163
+ .digest('hex')
1164
+ .slice(0, 32);
1165
+ }
1166
+ /**
1167
+ * Birth fingerprints a pre-release build derived (e.g. a worktree CLI that
1168
+ * opened live cleocode, 2026-09-28) are cleared, so the fill re-derives them
1169
+ * with the release recipe. Targeted: a value is cleared ONLY when it equals
1170
+ * {@link preReleaseBirthFp} of its row, or hashes a fingerprint cleared here
1171
+ * (@ownerFp / @refFp; T12801); values from any other source (a
1172
+ * device that received them by sync, a store whose meta table was lost) are
1173
+ * kept, and alias rows are never touched. The uid recipe did not change, so
1174
+ * uids are kept. Runs only while the recipe marker is missing or stale, and
1175
+ * never once uids have synced ({@link ROW_IDENTITY_SYNCED_KEY}): `refused`.
1176
+ */
1177
+ function resetStaleIdentity(db, scope, writers) {
1178
+ if (scope !== 'project' || !hasTable(db, ROW_IDENTITY_META_TABLE))
1179
+ return 'none';
1180
+ if (readMeta(db, ROW_IDENTITY_RECIPE_KEY) === ROW_IDENTITY_RECIPE)
1181
+ return 'none';
1182
+ const minted = fingerprintOrder('project', ROW_IDENTITY.project).filter((spec) => hasTable(db, spec.table) && columnsOf(db, spec.table).has(BIRTH_FP_COLUMN));
1183
+ // A value is stale when it equals the pre-release recipe of its row, OR when
1184
+ // it was derived from a stale value: a fingerprint that hashes its owner's
1185
+ // or its criterion's fingerprint (@ownerFp / @refFp) whose source is being
1186
+ // cleared. That covers a criterion whose uid and fingerprint an edit carried
1187
+ // onto a new row (the pre-release recipe cannot be recomputed from the new
1188
+ // row, T12801). Tables are visited owners first.
1189
+ const stale = [];
1190
+ const cleared = new Map(); // `${table}.${column}` → cleared values
1191
+ const mark = (table, column, value) => {
1192
+ if (value === null || value === undefined)
1193
+ return;
1194
+ const key = `${table}.${column}`;
1195
+ const set = cleared.get(key) ?? new Set();
1196
+ set.add(String(value));
1197
+ cleared.set(key, set);
1198
+ };
1199
+ for (const spec of minted) {
1200
+ const deps = (spec.birthFacts ?? [])
1201
+ .map((fact) => fingerprintRef('project', spec, fact))
1202
+ .filter((d) => d !== null);
1203
+ const keyColumn = targetKey('project', spec.table);
1204
+ const rows = db
1205
+ .prepare(`SELECT rowid AS _rowid, * FROM main.${q(spec.table)} WHERE ${q(BIRTH_FP_COLUMN)} IS NOT NULL`)
1206
+ .all();
1207
+ for (const row of rows) {
1208
+ const derivedFromStale = deps.some((d) => cleared.get(`${d.table}.${d.key}`)?.has(String(row[d.column] ?? '')));
1209
+ // Three sources of a stale value, all kept (T12801 x T12802): derived
1210
+ // from a value cleared in this pass, the pre-release recipe, or the
1211
+ // 9.25 (v1) recipe.
1212
+ if (derivedFromStale ||
1213
+ row[BIRTH_FP_COLUMN] === preReleaseBirthFp(db, spec.table, row) ||
1214
+ row[BIRTH_FP_COLUMN] === v1ReleaseBirthFp(db, spec.table, row)) {
1215
+ stale.push({ table: spec.table, rowid: row._rowid });
1216
+ mark(spec.table, keyColumn, row[keyColumn]);
1217
+ mark(spec.table, UID_COLUMN, row[UID_COLUMN]);
1218
+ }
1219
+ }
1220
+ }
1221
+ // The AC uid graveyard records deletions made while the recipe marker was
1222
+ // missing or stale: with the fill off, the schema heal (T12878) restores
1223
+ // its trigger, which then records the stale pre-release uid and birth_fp of
1224
+ // every criterion deleted since. Relinking those would carry a stale
1225
+ // fingerprint into the release recipe and, through the ordinal fallback,
1226
+ // hand a deleted criterion's uid to an unrelated new one. They are not an
1227
+ // older build's delete-and-recreate of one edit, so they are dropped in
1228
+ // this same step, before the fill relinks anything (T12878 review F1).
1229
+ const graveyardRows = scope === 'project' && hasTable(db, AC_UID_GRAVEYARD)
1230
+ ? db.prepare(`SELECT count(*) AS n FROM main.${AC_UID_GRAVEYARD}`).get().n
1231
+ : 0;
1232
+ if (stale.length === 0 && graveyardRows === 0)
1233
+ return 'none';
1234
+ if (readMeta(db, ROW_IDENTITY_SYNCED_KEY) !== undefined)
1235
+ return 'refused';
1236
+ db.exec('SAVEPOINT row_identity_reset');
1237
+ try {
1238
+ if (graveyardRows > 0)
1239
+ writers.clearAcUidGraveyardNative(db);
1240
+ for (const { table, rowid } of stale) {
1241
+ writers.clearBirthFpNative(db, table, rowid);
1242
+ }
1243
+ db.exec('RELEASE SAVEPOINT row_identity_reset');
1244
+ }
1245
+ catch (error) {
1246
+ db.exec('ROLLBACK TO SAVEPOINT row_identity_reset');
1247
+ db.exec('RELEASE SAVEPOINT row_identity_reset');
1248
+ throw error;
1249
+ }
1250
+ return 'cleared';
1251
+ }
1252
+ /**
1253
+ * Record that the store's identity values follow {@link ROW_IDENTITY_RECIPE}.
1254
+ * The fill writes it; {@link markRowIdentityShared} writes it too on the
1255
+ * first receive (a device that pulls before it ever fills).
1256
+ *
1257
+ * @param db - Connection on the project `cleo.db`.
1258
+ */
1259
+ export function writeRecipeMarker(db, writers = requireWriters()) {
1260
+ if (!hasTable(db, ROW_IDENTITY_META_TABLE))
1261
+ return;
1262
+ writers.writeRowIdentityMetaNative(db, ROW_IDENTITY_RECIPE_KEY, ROW_IDENTITY_RECIPE);
1263
+ }
1264
+ /**
1265
+ * Whether the store's identity values are shared with other devices
1266
+ * ({@link ROW_IDENTITY_SYNCED_KEY} present): from then on no local write may
1267
+ * clear or re-point a uid.
1268
+ *
1269
+ * @param db - Connection on the project `cleo.db`.
1270
+ * @returns True once identity has been sent or received.
1271
+ * @task T12806
1272
+ */
1273
+ export function rowIdentityShared(db) {
1274
+ return readMeta(db, ROW_IDENTITY_SYNCED_KEY) !== undefined;
1275
+ }
1276
+ /**
1277
+ * Record that identity values are now SHARED with other devices: the recipe
1278
+ * marker, and {@link ROW_IDENTITY_SYNCED_KEY} (first write wins, with the
1279
+ * direction). Called on the first receive (a pull-first clone that never
1280
+ * filled) as well as before the first send; once present, the open pass
1281
+ * never clears an identity value (spec §12.1).
1282
+ *
1283
+ * @param db - Connection on the project `cleo.db`.
1284
+ * @param direction - `receive` (the merge applied a row or op) or `send`.
1285
+ * @param writers - The chokepoint writers.
1286
+ * @task T12746
1287
+ */
1288
+ export function markRowIdentityShared(db, direction, writers = requireWriters()) {
1289
+ if (!hasTable(db, ROW_IDENTITY_META_TABLE))
1290
+ return;
1291
+ if (readMeta(db, ROW_IDENTITY_RECIPE_KEY) === undefined)
1292
+ writeRecipeMarker(db, writers);
1293
+ if (readMeta(db, ROW_IDENTITY_SYNCED_KEY) !== undefined)
1294
+ return;
1295
+ writers.writeRowIdentityMetaNative(db, ROW_IDENTITY_SYNCED_KEY, JSON.stringify({ first: direction, at: new Date().toISOString() }));
1296
+ }
1297
+ /**
1298
+ * Re-create the row-identity SCHEMA a store should have, on every open,
1299
+ * whatever the fill flag (T12878). DDL only: the identity tables, the
1300
+ * graveyard trigger, the columns an early table lacks, the uid columns and
1301
+ * their indexes. No row value is read or written. A store whose uid migration
1302
+ * was journaled without running its statements (journal Scenario 3 Case A:
1303
+ * live cleocode under 9.25, spec §12.2) gets the full schema here; the fill,
1304
+ * refill and TEMP triggers stay opt-in ({@link prepareRowIdentity}).
1305
+ *
1306
+ * Never throws: a failure is logged and the open continues.
1307
+ *
1308
+ * @param db - Connection on a `cleo.db`, inside the cold-open lease.
1309
+ * @param scope - The store's scope.
1310
+ * @returns The DDL statements it ran (empty when the schema was complete).
1311
+ * @task T12878
1312
+ */
1313
+ export function healRowIdentitySchema(db, scope, writers = registeredWriters) {
1314
+ const log = getLogger('row-identity');
1315
+ if (ROW_IDENTITY[scope].length === 0) {
1316
+ // Nothing is declared in this scope yet (the global store today): there is
1317
+ // no identity schema to heal, so nothing to record either.
1318
+ return [];
1319
+ }
1320
+ // A build that may not change this store's schema (a worktree-built CLI on a
1321
+ // live store, T12687) never heals it: the released build will.
1322
+ if (!schemaWritesAllowed(db)) {
1323
+ log.debug({ scope }, 'row identity schema heal skipped: schema writes refused for this build');
1324
+ return [];
1325
+ }
1326
+ try {
1327
+ db.exec('SAVEPOINT row_identity_heal');
1328
+ try {
1329
+ const healed = [
1330
+ ...(scope === 'project' ? ensureIdentityTables(db) : []),
1331
+ ...ensureRowIdentitySchema(db, scope),
1332
+ ];
1333
+ if (healed.length > 0)
1334
+ recordHealReceipt(db, scope, healed, writers);
1335
+ db.exec('RELEASE SAVEPOINT row_identity_heal');
1336
+ if (healed.length > 0)
1337
+ log.info({ scope, healed: healed.length }, 'row identity schema healed');
1338
+ return healed;
1339
+ }
1340
+ catch (error) {
1341
+ db.exec('ROLLBACK TO SAVEPOINT row_identity_heal');
1342
+ db.exec('RELEASE SAVEPOINT row_identity_heal');
1343
+ throw error;
1344
+ }
1345
+ }
1346
+ catch (error) {
1347
+ log.error({ scope, error }, 'row identity schema heal failed');
1348
+ return [];
1349
+ }
1350
+ }
1351
+ /**
1352
+ * Meta key of the heal receipt: when the open last re-created missing
1353
+ * identity schema, and what (T12878). Local-only bookkeeping of the heal
1354
+ * itself, in `tasks_row_identity_meta`; no row value of any other table is
1355
+ * written. `cleo doctor` (the `row_identity` check) shows it.
1356
+ */
1357
+ export const ROW_IDENTITY_HEAL_KEY = 'row_identity_schema_healed';
1358
+ /** The table holding each scope's heal receipts (`null`: the scope has none yet). */
1359
+ const HEAL_RECEIPT_TABLE = {
1360
+ project: ROW_IDENTITY_META_TABLE,
1361
+ // The global store declares no identity table yet (ROW_IDENTITY.global is
1362
+ // empty, so its heal never runs); the change that declares one adds its
1363
+ // meta table here.
1364
+ global: null,
1365
+ };
1366
+ /** How many heal receipts a store keeps (newest last). */
1367
+ const HEAL_RECEIPTS_KEPT = 20;
1368
+ function recordHealReceipt(db, scope, healed, writers) {
1369
+ const table = HEAL_RECEIPT_TABLE[scope];
1370
+ const log = getLogger('row-identity');
1371
+ if (table === null || !hasTable(db, table) || !writers) {
1372
+ log.warn({ scope, healed: healed.length }, 'row identity schema healed; no receipt table');
1373
+ return;
1374
+ }
1375
+ const objects = healed.map((stmt) => {
1376
+ const col = /ALTER TABLE main\.("?)(\w+)\1 ADD COLUMN ("?)(\w+)\3/.exec(stmt);
1377
+ if (col)
1378
+ return `${col[2]}.${col[4]}`;
1379
+ const obj = /(TABLE|INDEX|TRIGGER) IF NOT EXISTS main\.("?)(\w+)\2/.exec(stmt);
1380
+ return obj ? `${obj[1].toLowerCase()} ${obj[3]}` : stmt.slice(0, 60);
1381
+ });
1382
+ const receipt = {
1383
+ at: new Date().toISOString(),
1384
+ scope,
1385
+ statements: healed.length,
1386
+ objects,
1387
+ };
1388
+ // Appended, never overwritten: a later partial heal keeps the earlier ones.
1389
+ const history = [...readRowIdentityHealHistory(db), receipt].slice(-HEAL_RECEIPTS_KEPT);
1390
+ writers.writeRowIdentityMetaNative(db, ROW_IDENTITY_HEAL_KEY, JSON.stringify(history));
1391
+ }
1392
+ /**
1393
+ * The last heal receipt of a store, read-only (`undefined` when the schema
1394
+ * never needed healing).
1395
+ *
1396
+ * @param db - Connection on a project `cleo.db` (read-only is fine).
1397
+ * @returns The receipt.
1398
+ * @task T12878
1399
+ */
1400
+ export function readRowIdentityHealReceipt(db) {
1401
+ const history = readRowIdentityHealHistory(db);
1402
+ return history[history.length - 1];
1403
+ }
1404
+ /**
1405
+ * Every heal receipt a store kept, oldest first (read-only).
1406
+ *
1407
+ * @param db - Connection on a project `cleo.db` (read-only is fine).
1408
+ * @returns The receipts (empty when the schema never needed healing).
1409
+ * @task T12878
1410
+ */
1411
+ export function readRowIdentityHealHistory(db) {
1412
+ const raw = readMeta(db, ROW_IDENTITY_HEAL_KEY);
1413
+ if (raw === undefined)
1414
+ return [];
1415
+ try {
1416
+ const parsed = JSON.parse(raw);
1417
+ return Array.isArray(parsed) ? parsed : [parsed];
1418
+ }
1419
+ catch {
1420
+ return [];
1421
+ }
1422
+ }
1423
+ /**
1424
+ * Identity schema a project store lacks, read-only: missing identity tables,
1425
+ * the graveyard trigger, and the alias / graveyard columns an early table
1426
+ * lacks (T12878; the open heals them).
1427
+ *
1428
+ * @param db - Connection on a project `cleo.db` (read-only is fine).
1429
+ * @returns What is missing (empty when complete).
1430
+ * @task T12878
1431
+ */
1432
+ export function missingRowIdentitySchema(db) {
1433
+ if (!hasTable(db, 'tasks_task_acceptance_criteria'))
1434
+ return [];
1435
+ const missing = [];
1436
+ for (const table of Object.keys(IDENTITY_TABLE_DDL)) {
1437
+ if (!hasTable(db, table))
1438
+ missing.push(`table ${table}`);
1439
+ }
1440
+ for (const [table, column] of [
1441
+ ['tasks_display_id_aliases', 'displaced_hlc'],
1442
+ ['tasks_display_id_aliases', 'entity_birth_fp'],
1443
+ [AC_UID_GRAVEYARD, 'birth_fp'],
1444
+ ]) {
1445
+ if (hasTable(db, table) && !columnsOf(db, table).has(column)) {
1446
+ missing.push(`column ${table}.${column}`);
1447
+ }
1448
+ }
1449
+ if (!hasObject(db, 'trigger', 'trg_tasks_ac_uid_graveyard')) {
1450
+ missing.push('trigger trg_tasks_ac_uid_graveyard');
1451
+ }
1452
+ // The uid columns and indexes ensureRowIdentitySchema heals.
1453
+ for (const spec of ROW_IDENTITY.project) {
1454
+ if (!hasTable(db, spec.table))
1455
+ continue;
1456
+ const cols = columnsOf(db, spec.table);
1457
+ for (const column of rowIdentityColumns('project', spec.table)) {
1458
+ if (!cols.has(column))
1459
+ missing.push(`column ${spec.table}.${column}`);
1460
+ }
1461
+ if (!uidIsPrimaryKey(db, spec.table) && !hasObject(db, 'index', `uq_${spec.table}_uid`)) {
1462
+ missing.push(`index uq_${spec.table}_uid`);
1463
+ }
1464
+ for (const ref of spec.storedRefUids ?? []) {
1465
+ const index = `idx_${spec.table}_${ref.column}`;
1466
+ if (!hasObject(db, 'index', index))
1467
+ missing.push(`index ${index}`);
1468
+ }
1469
+ }
1470
+ return missing;
1471
+ }
1472
+ export function prepareRowIdentity(db, scope, options = {}) {
1473
+ if (ROW_IDENTITY[scope].length === 0)
1474
+ return null;
1475
+ if (!rowUidFillEnabled())
1476
+ return null;
1477
+ const log = getLogger('row-identity');
1478
+ try {
1479
+ const healed = [
1480
+ ...(scope === 'project' ? ensureIdentityTables(db) : []),
1481
+ ...ensureRowIdentitySchema(db, scope),
1482
+ ];
1483
+ registerRowUidFunction(db, scope);
1484
+ const writers = options.writers ?? requireWriters();
1485
+ const refill = resetStaleIdentity(db, scope, writers);
1486
+ if (refill === 'refused') {
1487
+ log.error({ scope, marker: readMeta(db, ROW_IDENTITY_RECIPE_KEY) }, 'identity values predate the current recipe but uids have synced; kept as they are');
1488
+ }
1489
+ const filled = fillRowUids(db, scope, writers);
1490
+ if (refill !== 'refused')
1491
+ writeRecipeMarker(db, writers);
1492
+ const findings = rowIdentityFindings(db, scope);
1493
+ const report = { ...filled, findings, healed, refill };
1494
+ if (options.triggers !== false)
1495
+ installRowUidTriggers(db, scope);
1496
+ if (Object.keys(report.unfilled).length > 0) {
1497
+ log.warn({ scope, unfilled: report.unfilled }, 'rows left without a uid (filled on a later open)');
1498
+ }
1499
+ if (healed.length > 0 || Object.keys(report.filled).length > 0 || report.relinked > 0) {
1500
+ log.debug({ scope, ...report }, 'row uids filled');
1501
+ }
1502
+ return report;
1503
+ }
1504
+ catch (error) {
1505
+ log.error({ scope, error }, 'row uid fill failed; rows keep a NULL uid until a later open');
1506
+ return null;
1507
+ }
1508
+ }
1509
+ //# sourceMappingURL=row-identity.js.map