@opencorelabs/lucidity 0.3.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (527) hide show
  1. package/README.md +18 -3
  2. package/dist/assets/speech/licenses/FluidAudio/LICENSE +201 -0
  3. package/dist/assets/speech/licenses/FluidAudio/ThirdPartyLicenses/fastcluster-LICENSE.md +11 -0
  4. package/dist/assets/speech/licenses/FluidAudio/ThirdPartyLicenses/vbx-LICENSE.md +201 -0
  5. package/dist/assets/speech/lucidity-speech +0 -0
  6. package/dist/automations/agent.d.ts +16 -0
  7. package/dist/automations/agent.d.ts.map +1 -0
  8. package/dist/automations/agent.js +196 -0
  9. package/dist/automations/cli.d.ts +4 -0
  10. package/dist/automations/cli.d.ts.map +1 -0
  11. package/dist/automations/cli.js +44 -0
  12. package/dist/automations/connections.d.ts +11 -0
  13. package/dist/automations/connections.d.ts.map +1 -0
  14. package/dist/automations/connections.js +74 -0
  15. package/dist/automations/designer.d.ts +39 -0
  16. package/dist/automations/designer.d.ts.map +1 -0
  17. package/dist/automations/designer.js +450 -0
  18. package/dist/automations/history.d.ts +4 -0
  19. package/dist/automations/history.d.ts.map +1 -0
  20. package/dist/automations/history.js +57 -0
  21. package/dist/automations/learning.d.ts +19 -0
  22. package/dist/automations/learning.d.ts.map +1 -0
  23. package/dist/automations/learning.js +121 -0
  24. package/dist/automations/pinterest.d.ts +21 -0
  25. package/dist/automations/pinterest.d.ts.map +1 -0
  26. package/dist/automations/pinterest.js +113 -0
  27. package/dist/automations/service.d.ts +42 -0
  28. package/dist/automations/service.d.ts.map +1 -0
  29. package/dist/automations/service.js +406 -0
  30. package/dist/automations/setup.d.ts +3 -0
  31. package/dist/automations/setup.d.ts.map +1 -0
  32. package/dist/automations/setup.js +48 -0
  33. package/dist/automations/skill.d.ts +3 -0
  34. package/dist/automations/skill.d.ts.map +1 -0
  35. package/dist/automations/skill.js +29 -0
  36. package/dist/automations/store.d.ts +13 -0
  37. package/dist/automations/store.d.ts.map +1 -0
  38. package/dist/automations/store.js +46 -0
  39. package/dist/chat/server.d.ts +2 -0
  40. package/dist/chat/server.d.ts.map +1 -1
  41. package/dist/chat/server.js +46 -2
  42. package/dist/coding/commandContext.d.ts +6 -0
  43. package/dist/coding/commandContext.d.ts.map +1 -0
  44. package/dist/coding/commandContext.js +20 -0
  45. package/dist/coding/runCodeTurn.d.ts +12 -2
  46. package/dist/coding/runCodeTurn.d.ts.map +1 -1
  47. package/dist/coding/runCodeTurn.js +49 -19
  48. package/dist/coding/worktree.d.ts +3 -4
  49. package/dist/coding/worktree.d.ts.map +1 -1
  50. package/dist/coding/worktree.js +3 -4
  51. package/dist/config.d.ts +4 -0
  52. package/dist/config.d.ts.map +1 -1
  53. package/dist/config.js +20 -3
  54. package/dist/decisions/cli.d.ts +2 -0
  55. package/dist/decisions/cli.d.ts.map +1 -0
  56. package/dist/decisions/cli.js +106 -0
  57. package/dist/decisions/client.d.ts +20 -0
  58. package/dist/decisions/client.d.ts.map +1 -0
  59. package/dist/decisions/client.js +41 -0
  60. package/dist/handoff.d.ts +11 -0
  61. package/dist/handoff.d.ts.map +1 -0
  62. package/dist/handoff.js +21 -0
  63. package/dist/index.js +185 -40
  64. package/dist/jobs/briefing.js +1 -1
  65. package/dist/jobs/extraction.d.ts.map +1 -1
  66. package/dist/jobs/extraction.js +112 -22
  67. package/dist/jobs/fastModeReview.d.ts +39 -0
  68. package/dist/jobs/fastModeReview.d.ts.map +1 -0
  69. package/dist/jobs/fastModeReview.js +192 -0
  70. package/dist/jobs/voiceReview.d.ts +24 -0
  71. package/dist/jobs/voiceReview.d.ts.map +1 -0
  72. package/dist/jobs/voiceReview.js +128 -0
  73. package/dist/mcp/clients.d.ts +5 -0
  74. package/dist/mcp/clients.d.ts.map +1 -1
  75. package/dist/mcp/clients.js +1 -1
  76. package/dist/mcp/config.d.ts +3 -1
  77. package/dist/mcp/config.d.ts.map +1 -1
  78. package/dist/mcp/config.js +48 -6
  79. package/dist/mcp/paired.js +1 -0
  80. package/dist/notesContext.d.ts.map +1 -1
  81. package/dist/notesContext.js +3 -2
  82. package/dist/room/client.d.ts +20 -7
  83. package/dist/room/client.d.ts.map +1 -1
  84. package/dist/room/client.js +266 -47
  85. package/dist/room/computer.d.ts.map +1 -1
  86. package/dist/room/computer.js +9 -0
  87. package/dist/room/context.d.ts +3 -2
  88. package/dist/room/context.d.ts.map +1 -1
  89. package/dist/room/context.js +10 -3
  90. package/dist/room/turnQueue.d.ts +40 -0
  91. package/dist/room/turnQueue.d.ts.map +1 -0
  92. package/dist/room/turnQueue.js +301 -0
  93. package/dist/skills/lucidity-automations/SKILL.md +54 -0
  94. package/dist/speech/captures.d.ts +30 -0
  95. package/dist/speech/captures.d.ts.map +1 -0
  96. package/dist/speech/captures.js +209 -0
  97. package/dist/speech/fluidAudio.d.ts +28 -0
  98. package/dist/speech/fluidAudio.d.ts.map +1 -0
  99. package/dist/speech/fluidAudio.js +182 -0
  100. package/dist/speech/service.d.ts +14 -0
  101. package/dist/speech/service.d.ts.map +1 -0
  102. package/dist/speech/service.js +88 -0
  103. package/dist/speech/types.d.ts +19 -0
  104. package/dist/speech/types.d.ts.map +1 -0
  105. package/dist/speech/types.js +1 -0
  106. package/dist/turnLog.d.ts +1 -0
  107. package/dist/turnLog.d.ts.map +1 -1
  108. package/dist/turnLog.js +3 -0
  109. package/native/speech/Package.resolved +15 -0
  110. package/native/speech/Package.swift +16 -0
  111. package/native/speech/Sources/lucidity-speech/Speech.swift +81 -0
  112. package/package.json +6 -2
  113. package/src/automations/agent.ts +239 -0
  114. package/src/automations/cli.ts +52 -0
  115. package/src/automations/connections.ts +83 -0
  116. package/src/automations/designer.ts +594 -0
  117. package/src/automations/history.ts +59 -0
  118. package/src/automations/learning.ts +180 -0
  119. package/src/automations/pinterest.ts +146 -0
  120. package/src/automations/service.ts +505 -0
  121. package/src/automations/setup.ts +71 -0
  122. package/src/automations/skill.ts +40 -0
  123. package/src/automations/store.ts +63 -0
  124. package/src/chat/server.ts +62 -3
  125. package/src/coding/commandContext.ts +29 -0
  126. package/src/coding/runCodeTurn.ts +65 -21
  127. package/src/coding/worktree.ts +3 -4
  128. package/src/config.ts +29 -2
  129. package/src/decisions/cli.ts +136 -0
  130. package/src/decisions/client.ts +62 -0
  131. package/src/handoff.ts +28 -0
  132. package/src/index.ts +202 -67
  133. package/src/jobs/briefing.ts +1 -1
  134. package/src/jobs/extraction.ts +157 -32
  135. package/src/jobs/fastModeReview.ts +221 -0
  136. package/src/jobs/voiceReview.ts +156 -0
  137. package/src/mcp/clients.ts +1 -1
  138. package/src/mcp/config.ts +56 -6
  139. package/src/mcp/paired.ts +1 -0
  140. package/src/notesContext.ts +3 -2
  141. package/src/room/client.ts +320 -54
  142. package/src/room/computer.ts +9 -0
  143. package/src/room/context.ts +12 -3
  144. package/src/room/turnQueue.ts +358 -0
  145. package/src/speech/captures.ts +265 -0
  146. package/src/speech/fluidAudio.ts +242 -0
  147. package/src/speech/service.ts +108 -0
  148. package/src/speech/types.ts +13 -0
  149. package/src/turnLog.ts +4 -0
  150. package/vendor/decisions/LICENSE +662 -0
  151. package/vendor/decisions/dist/capture.d.ts +79 -0
  152. package/vendor/decisions/dist/capture.js +183 -0
  153. package/vendor/decisions/dist/command.d.ts +202 -0
  154. package/vendor/decisions/dist/command.js +750 -0
  155. package/vendor/decisions/dist/dayPlan.d.ts +9 -0
  156. package/vendor/decisions/dist/dayPlan.js +82 -0
  157. package/vendor/decisions/dist/gate.d.ts +12 -0
  158. package/vendor/decisions/dist/gate.js +18 -0
  159. package/vendor/decisions/dist/index.d.ts +6 -0
  160. package/vendor/decisions/dist/index.js +6 -0
  161. package/vendor/decisions/dist/jev.d.ts +15 -0
  162. package/vendor/decisions/dist/jev.js +244 -0
  163. package/vendor/decisions/dist/types.d.ts +67 -0
  164. package/vendor/decisions/dist/types.js +1 -0
  165. package/vendor/decisions/package.json +22 -0
  166. package/vendor/decisions/src/capture.ts +199 -0
  167. package/vendor/decisions/src/command.ts +836 -0
  168. package/vendor/decisions/src/dayPlan.ts +80 -0
  169. package/vendor/decisions/src/gate.ts +32 -0
  170. package/vendor/decisions/src/index.ts +6 -0
  171. package/vendor/decisions/src/jev.ts +295 -0
  172. package/vendor/decisions/src/types.ts +79 -0
  173. package/vendor/mcp-server/README.md +6 -1
  174. package/vendor/mcp-server/dist/client.d.ts +1 -0
  175. package/vendor/mcp-server/dist/client.d.ts.map +1 -1
  176. package/vendor/mcp-server/dist/client.js +8 -0
  177. package/vendor/mcp-server/dist/commentProvider.d.ts +3 -0
  178. package/vendor/mcp-server/dist/commentProvider.d.ts.map +1 -0
  179. package/vendor/mcp-server/dist/commentProvider.js +10 -0
  180. package/vendor/mcp-server/dist/index.js +21 -6
  181. package/vendor/mcp-server/dist/tools/automations.d.ts +6 -0
  182. package/vendor/mcp-server/dist/tools/automations.d.ts.map +1 -0
  183. package/vendor/mcp-server/dist/tools/automations.js +163 -0
  184. package/vendor/mcp-server/dist/tools/commandEventFormat.d.ts +52 -0
  185. package/vendor/mcp-server/dist/tools/commandEventFormat.d.ts.map +1 -0
  186. package/vendor/mcp-server/dist/tools/commandEventFormat.js +83 -0
  187. package/vendor/mcp-server/dist/tools/commandEvents.d.ts +3 -0
  188. package/vendor/mcp-server/dist/tools/commandEvents.d.ts.map +1 -0
  189. package/vendor/mcp-server/dist/tools/commandEvents.js +21 -0
  190. package/vendor/mcp-server/dist/tools/comments.d.ts.map +1 -1
  191. package/vendor/mcp-server/dist/tools/comments.js +25 -4
  192. package/vendor/mcp-server/dist/tools/index.d.ts +2 -0
  193. package/vendor/mcp-server/dist/tools/index.d.ts.map +1 -1
  194. package/vendor/mcp-server/dist/tools/index.js +2 -0
  195. package/vendor/mcp-server/dist/tools/journal.d.ts +3 -0
  196. package/vendor/mcp-server/dist/tools/journal.d.ts.map +1 -0
  197. package/vendor/mcp-server/dist/tools/journal.js +131 -0
  198. package/vendor/mcp-server/dist/tools/taskActivity.d.ts +3 -0
  199. package/vendor/mcp-server/dist/tools/taskActivity.d.ts.map +1 -0
  200. package/vendor/mcp-server/dist/tools/taskActivity.js +32 -0
  201. package/vendor/mcp-server/dist/tools/taskOccurrences.d.ts +3 -0
  202. package/vendor/mcp-server/dist/tools/taskOccurrences.d.ts.map +1 -0
  203. package/vendor/mcp-server/dist/tools/taskOccurrences.js +12 -0
  204. package/vendor/mcp-server/dist/tools/taskTrash.d.ts +3 -0
  205. package/vendor/mcp-server/dist/tools/taskTrash.d.ts.map +1 -0
  206. package/vendor/mcp-server/dist/tools/taskTrash.js +21 -0
  207. package/vendor/mcp-server/dist/tools/tasks.d.ts.map +1 -1
  208. package/vendor/mcp-server/dist/tools/tasks.js +67 -27
  209. package/vendor/mcp-server/package.json +5 -1
  210. package/vendor/mcp-server/src/client.ts +10 -0
  211. package/vendor/mcp-server/src/commentProvider.ts +9 -0
  212. package/vendor/mcp-server/src/index.ts +20 -6
  213. package/vendor/mcp-server/src/tools/automations.ts +199 -0
  214. package/vendor/mcp-server/src/tools/commandEventFormat.ts +108 -0
  215. package/vendor/mcp-server/src/tools/commandEvents.ts +27 -0
  216. package/vendor/mcp-server/src/tools/comments.ts +24 -3
  217. package/vendor/mcp-server/src/tools/index.ts +2 -0
  218. package/vendor/mcp-server/src/tools/journal.ts +168 -0
  219. package/vendor/mcp-server/src/tools/taskActivity.ts +55 -0
  220. package/vendor/mcp-server/src/tools/taskOccurrences.ts +26 -0
  221. package/vendor/mcp-server/src/tools/taskTrash.ts +23 -0
  222. package/vendor/mcp-server/src/tools/tasks.ts +66 -30
  223. package/vendor/notes/dist/index.d.ts +2 -0
  224. package/vendor/notes/dist/index.d.ts.map +1 -1
  225. package/vendor/notes/dist/index.js +2 -0
  226. package/vendor/notes/dist/journal-backend.d.ts +4 -0
  227. package/vendor/notes/dist/journal-backend.d.ts.map +1 -0
  228. package/vendor/notes/dist/journal-backend.js +33 -0
  229. package/vendor/notes/dist/journal.d.ts +7 -0
  230. package/vendor/notes/dist/journal.d.ts.map +1 -0
  231. package/vendor/notes/dist/journal.js +173 -0
  232. package/vendor/notes/dist/vault.d.ts.map +1 -1
  233. package/vendor/notes/dist/vault.js +6 -1
  234. package/vendor/notes/src/index.ts +2 -0
  235. package/vendor/notes/src/journal-backend.ts +53 -0
  236. package/vendor/notes/src/journal.ts +194 -0
  237. package/vendor/notes/src/vault.ts +9 -1
  238. package/vendor/runtime/README.md +4 -0
  239. package/vendor/runtime/dist/executor/claudeAgent.d.ts +2 -0
  240. package/vendor/runtime/dist/executor/claudeAgent.d.ts.map +1 -1
  241. package/vendor/runtime/dist/executor/claudeAgent.js +117 -8
  242. package/vendor/runtime/dist/executor/claudeCode.d.ts.map +1 -1
  243. package/vendor/runtime/dist/executor/claudeCode.js +8 -4
  244. package/vendor/runtime/dist/executor/codex.d.ts +2 -0
  245. package/vendor/runtime/dist/executor/codex.d.ts.map +1 -1
  246. package/vendor/runtime/dist/executor/codex.js +214 -11
  247. package/vendor/runtime/dist/executor/codexProtocol/PlanType.d.ts +2 -0
  248. package/vendor/runtime/dist/executor/codexProtocol/PlanType.d.ts.map +1 -0
  249. package/vendor/runtime/dist/executor/codexProtocol/PlanType.js +2 -0
  250. package/vendor/runtime/dist/executor/codexProtocol/v2/CreditsSnapshot.d.ts +6 -0
  251. package/vendor/runtime/dist/executor/codexProtocol/v2/CreditsSnapshot.d.ts.map +1 -0
  252. package/vendor/runtime/dist/executor/codexProtocol/v2/CreditsSnapshot.js +2 -0
  253. package/vendor/runtime/dist/executor/codexProtocol/v2/GetAccountRateLimitsResponse.d.ts +26 -0
  254. package/vendor/runtime/dist/executor/codexProtocol/v2/GetAccountRateLimitsResponse.d.ts.map +1 -0
  255. package/vendor/runtime/dist/executor/codexProtocol/v2/GetAccountRateLimitsResponse.js +2 -0
  256. package/vendor/runtime/dist/executor/codexProtocol/v2/RateLimitReachedType.d.ts +2 -0
  257. package/vendor/runtime/dist/executor/codexProtocol/v2/RateLimitReachedType.d.ts.map +1 -0
  258. package/vendor/runtime/dist/executor/codexProtocol/v2/RateLimitReachedType.js +2 -0
  259. package/vendor/runtime/dist/executor/codexProtocol/v2/RateLimitResetCredit.d.ts +27 -0
  260. package/vendor/runtime/dist/executor/codexProtocol/v2/RateLimitResetCredit.d.ts.map +1 -0
  261. package/vendor/runtime/dist/executor/codexProtocol/v2/RateLimitResetCredit.js +2 -0
  262. package/vendor/runtime/dist/executor/codexProtocol/v2/RateLimitResetCreditStatus.d.ts +2 -0
  263. package/vendor/runtime/dist/executor/codexProtocol/v2/RateLimitResetCreditStatus.d.ts.map +1 -0
  264. package/vendor/runtime/dist/executor/codexProtocol/v2/RateLimitResetCreditStatus.js +2 -0
  265. package/vendor/runtime/dist/executor/codexProtocol/v2/RateLimitResetCreditsSummary.d.ts +13 -0
  266. package/vendor/runtime/dist/executor/codexProtocol/v2/RateLimitResetCreditsSummary.d.ts.map +1 -0
  267. package/vendor/runtime/dist/executor/codexProtocol/v2/RateLimitResetCreditsSummary.js +2 -0
  268. package/vendor/runtime/dist/executor/codexProtocol/v2/RateLimitResetType.d.ts +2 -0
  269. package/vendor/runtime/dist/executor/codexProtocol/v2/RateLimitResetType.d.ts.map +1 -0
  270. package/vendor/runtime/dist/executor/codexProtocol/v2/RateLimitResetType.js +2 -0
  271. package/vendor/runtime/dist/executor/codexProtocol/v2/RateLimitSnapshot.d.ts +20 -0
  272. package/vendor/runtime/dist/executor/codexProtocol/v2/RateLimitSnapshot.d.ts.map +1 -0
  273. package/vendor/runtime/dist/executor/codexProtocol/v2/RateLimitSnapshot.js +2 -0
  274. package/vendor/runtime/dist/executor/codexProtocol/v2/RateLimitWindow.d.ts +6 -0
  275. package/vendor/runtime/dist/executor/codexProtocol/v2/RateLimitWindow.d.ts.map +1 -0
  276. package/vendor/runtime/dist/executor/codexProtocol/v2/RateLimitWindow.js +2 -0
  277. package/vendor/runtime/dist/executor/codexProtocol/v2/ReviewDelivery.d.ts +2 -0
  278. package/vendor/runtime/dist/executor/codexProtocol/v2/ReviewDelivery.d.ts.map +1 -0
  279. package/vendor/runtime/dist/executor/codexProtocol/v2/ReviewDelivery.js +2 -0
  280. package/vendor/runtime/dist/executor/codexProtocol/v2/ReviewStartParams.d.ts +12 -0
  281. package/vendor/runtime/dist/executor/codexProtocol/v2/ReviewStartParams.d.ts.map +1 -0
  282. package/vendor/runtime/dist/executor/codexProtocol/v2/ReviewStartParams.js +2 -0
  283. package/vendor/runtime/dist/executor/codexProtocol/v2/ReviewTarget.d.ts +17 -0
  284. package/vendor/runtime/dist/executor/codexProtocol/v2/ReviewTarget.d.ts.map +1 -0
  285. package/vendor/runtime/dist/executor/codexProtocol/v2/ReviewTarget.js +2 -0
  286. package/vendor/runtime/dist/executor/codexProtocol/v2/SkillDependencies.d.ts +5 -0
  287. package/vendor/runtime/dist/executor/codexProtocol/v2/SkillDependencies.d.ts.map +1 -0
  288. package/vendor/runtime/dist/executor/codexProtocol/v2/SkillDependencies.js +2 -0
  289. package/vendor/runtime/dist/executor/codexProtocol/v2/SkillErrorInfo.d.ts +5 -0
  290. package/vendor/runtime/dist/executor/codexProtocol/v2/SkillErrorInfo.d.ts.map +1 -0
  291. package/vendor/runtime/dist/executor/codexProtocol/v2/SkillErrorInfo.js +2 -0
  292. package/vendor/runtime/dist/executor/codexProtocol/v2/SkillInterface.d.ts +18 -0
  293. package/vendor/runtime/dist/executor/codexProtocol/v2/SkillInterface.d.ts.map +1 -0
  294. package/vendor/runtime/dist/executor/codexProtocol/v2/SkillInterface.js +2 -0
  295. package/vendor/runtime/dist/executor/codexProtocol/v2/SkillMetadata.d.ts +22 -0
  296. package/vendor/runtime/dist/executor/codexProtocol/v2/SkillMetadata.d.ts.map +1 -0
  297. package/vendor/runtime/dist/executor/codexProtocol/v2/SkillMetadata.js +2 -0
  298. package/vendor/runtime/dist/executor/codexProtocol/v2/SkillScope.d.ts +2 -0
  299. package/vendor/runtime/dist/executor/codexProtocol/v2/SkillScope.d.ts.map +1 -0
  300. package/vendor/runtime/dist/executor/codexProtocol/v2/SkillScope.js +2 -0
  301. package/vendor/runtime/dist/executor/codexProtocol/v2/SkillToolDependency.d.ts +9 -0
  302. package/vendor/runtime/dist/executor/codexProtocol/v2/SkillToolDependency.d.ts.map +1 -0
  303. package/vendor/runtime/dist/executor/codexProtocol/v2/SkillToolDependency.js +2 -0
  304. package/vendor/runtime/dist/executor/codexProtocol/v2/SkillsListEntry.d.ts +8 -0
  305. package/vendor/runtime/dist/executor/codexProtocol/v2/SkillsListEntry.d.ts.map +1 -0
  306. package/vendor/runtime/dist/executor/codexProtocol/v2/SkillsListEntry.js +2 -0
  307. package/vendor/runtime/dist/executor/codexProtocol/v2/SkillsListResponse.d.ts +5 -0
  308. package/vendor/runtime/dist/executor/codexProtocol/v2/SkillsListResponse.d.ts.map +1 -0
  309. package/vendor/runtime/dist/executor/codexProtocol/v2/SkillsListResponse.js +2 -0
  310. package/vendor/runtime/dist/executor/codexProtocol/v2/SpendControlLimitSnapshot.d.ts +7 -0
  311. package/vendor/runtime/dist/executor/codexProtocol/v2/SpendControlLimitSnapshot.d.ts.map +1 -0
  312. package/vendor/runtime/dist/executor/codexProtocol/v2/SpendControlLimitSnapshot.js +2 -0
  313. package/vendor/runtime/dist/executor/codexProtocol/v2/ThreadSetNameParams.d.ts +5 -0
  314. package/vendor/runtime/dist/executor/codexProtocol/v2/ThreadSetNameParams.d.ts.map +1 -0
  315. package/vendor/runtime/dist/executor/codexProtocol/v2/ThreadSetNameParams.js +2 -0
  316. package/vendor/runtime/dist/executor/health.d.ts +1 -0
  317. package/vendor/runtime/dist/executor/health.d.ts.map +1 -1
  318. package/vendor/runtime/dist/executor/health.js +3 -0
  319. package/vendor/runtime/dist/executor/liveTurns.d.ts.map +1 -1
  320. package/vendor/runtime/dist/executor/liveTurns.js +3 -0
  321. package/vendor/runtime/dist/executor/providerRouter.d.ts.map +1 -1
  322. package/vendor/runtime/dist/executor/providerRouter.js +2 -1
  323. package/vendor/runtime/dist/executor/types.d.ts +10 -0
  324. package/vendor/runtime/dist/executor/types.d.ts.map +1 -1
  325. package/vendor/runtime/dist/harness/index.d.ts +2 -0
  326. package/vendor/runtime/dist/harness/index.d.ts.map +1 -1
  327. package/vendor/runtime/dist/harness/index.js +46 -1
  328. package/vendor/runtime/dist/harness/types.d.ts +5 -1
  329. package/vendor/runtime/dist/harness/types.d.ts.map +1 -1
  330. package/vendor/runtime/dist/index.d.ts +2 -1
  331. package/vendor/runtime/dist/index.d.ts.map +1 -1
  332. package/vendor/runtime/dist/index.js +2 -0
  333. package/vendor/runtime/dist/journal/context.d.ts +18 -0
  334. package/vendor/runtime/dist/journal/context.d.ts.map +1 -1
  335. package/vendor/runtime/dist/journal/context.js +19 -5
  336. package/vendor/runtime/dist/prompts/briefing.d.ts +4 -7
  337. package/vendor/runtime/dist/prompts/briefing.d.ts.map +1 -1
  338. package/vendor/runtime/dist/prompts/briefing.js +61 -12
  339. package/vendor/runtime/dist/prompts/cardStatement.d.ts +7 -0
  340. package/vendor/runtime/dist/prompts/cardStatement.d.ts.map +1 -0
  341. package/vendor/runtime/dist/prompts/cardStatement.js +52 -0
  342. package/vendor/runtime/dist/prompts/chat.d.ts +1 -0
  343. package/vendor/runtime/dist/prompts/chat.d.ts.map +1 -1
  344. package/vendor/runtime/dist/prompts/chat.js +15 -1
  345. package/vendor/runtime/dist/prompts/dayPlanning.d.ts +44 -0
  346. package/vendor/runtime/dist/prompts/dayPlanning.d.ts.map +1 -0
  347. package/vendor/runtime/dist/prompts/dayPlanning.js +42 -0
  348. package/vendor/runtime/dist/prompts/projectCapture.d.ts +7 -0
  349. package/vendor/runtime/dist/prompts/projectCapture.d.ts.map +1 -0
  350. package/vendor/runtime/dist/prompts/projectCapture.js +31 -0
  351. package/vendor/runtime/src/executor/claudeAgent.ts +137 -7
  352. package/vendor/runtime/src/executor/claudeCode.ts +6 -4
  353. package/vendor/runtime/src/executor/codex.ts +281 -20
  354. package/vendor/runtime/src/executor/codexProtocol/PlanType.ts +5 -0
  355. package/vendor/runtime/src/executor/codexProtocol/v2/CreditsSnapshot.ts +5 -0
  356. package/vendor/runtime/src/executor/codexProtocol/v2/GetAccountRateLimitsResponse.ts +25 -0
  357. package/vendor/runtime/src/executor/codexProtocol/v2/RateLimitReachedType.ts +5 -0
  358. package/vendor/runtime/src/executor/codexProtocol/v2/RateLimitResetCredit.ts +27 -0
  359. package/vendor/runtime/src/executor/codexProtocol/v2/RateLimitResetCreditStatus.ts +5 -0
  360. package/vendor/runtime/src/executor/codexProtocol/v2/RateLimitResetCreditsSummary.ts +14 -0
  361. package/vendor/runtime/src/executor/codexProtocol/v2/RateLimitResetType.ts +5 -0
  362. package/vendor/runtime/src/executor/codexProtocol/v2/RateLimitSnapshot.ts +14 -0
  363. package/vendor/runtime/src/executor/codexProtocol/v2/RateLimitWindow.ts +5 -0
  364. package/vendor/runtime/src/executor/codexProtocol/v2/ReviewDelivery.ts +5 -0
  365. package/vendor/runtime/src/executor/codexProtocol/v2/ReviewStartParams.ts +12 -0
  366. package/vendor/runtime/src/executor/codexProtocol/v2/ReviewTarget.ts +9 -0
  367. package/vendor/runtime/src/executor/codexProtocol/v2/SkillDependencies.ts +6 -0
  368. package/vendor/runtime/src/executor/codexProtocol/v2/SkillErrorInfo.ts +5 -0
  369. package/vendor/runtime/src/executor/codexProtocol/v2/SkillInterface.ts +14 -0
  370. package/vendor/runtime/src/executor/codexProtocol/v2/SkillMetadata.ts +17 -0
  371. package/vendor/runtime/src/executor/codexProtocol/v2/SkillScope.ts +5 -0
  372. package/vendor/runtime/src/executor/codexProtocol/v2/SkillToolDependency.ts +5 -0
  373. package/vendor/runtime/src/executor/codexProtocol/v2/SkillsListEntry.ts +7 -0
  374. package/vendor/runtime/src/executor/codexProtocol/v2/SkillsListResponse.ts +6 -0
  375. package/vendor/runtime/src/executor/codexProtocol/v2/SpendControlLimitSnapshot.ts +5 -0
  376. package/vendor/runtime/src/executor/codexProtocol/v2/ThreadSetNameParams.ts +5 -0
  377. package/vendor/runtime/src/executor/health.ts +3 -0
  378. package/vendor/runtime/src/executor/liveTurns.ts +3 -0
  379. package/vendor/runtime/src/executor/providerRouter.ts +2 -1
  380. package/vendor/runtime/src/executor/types.ts +10 -0
  381. package/vendor/runtime/src/harness/index.ts +51 -6
  382. package/vendor/runtime/src/harness/types.ts +5 -1
  383. package/vendor/runtime/src/index.ts +4 -1
  384. package/vendor/runtime/src/journal/context.ts +40 -7
  385. package/vendor/runtime/src/prompts/briefing.ts +62 -17
  386. package/vendor/runtime/src/prompts/cardStatement.ts +64 -0
  387. package/vendor/runtime/src/prompts/chat.ts +25 -3
  388. package/vendor/runtime/src/prompts/dayPlanning.ts +46 -0
  389. package/vendor/runtime/src/prompts/projectCapture.ts +51 -0
  390. package/vendor/shared/dist/agentCommands.d.ts +22 -0
  391. package/vendor/shared/dist/agentCommands.d.ts.map +1 -0
  392. package/vendor/shared/dist/agentCommands.js +11 -0
  393. package/vendor/shared/dist/automationTemplates.d.ts +37 -0
  394. package/vendor/shared/dist/automationTemplates.d.ts.map +1 -0
  395. package/vendor/shared/dist/automationTemplates.js +48 -0
  396. package/vendor/shared/dist/automations.d.ts +1052 -0
  397. package/vendor/shared/dist/automations.d.ts.map +1 -0
  398. package/vendor/shared/dist/automations.js +300 -0
  399. package/vendor/shared/dist/cardStatement.d.ts +28 -0
  400. package/vendor/shared/dist/cardStatement.d.ts.map +1 -0
  401. package/vendor/shared/dist/cardStatement.js +37 -0
  402. package/vendor/shared/dist/cardStudio.d.ts +756 -0
  403. package/vendor/shared/dist/cardStudio.d.ts.map +1 -0
  404. package/vendor/shared/dist/cardStudio.js +297 -0
  405. package/vendor/shared/dist/commandLocal.d.ts +218 -0
  406. package/vendor/shared/dist/commandLocal.d.ts.map +1 -0
  407. package/vendor/shared/dist/commandLocal.js +664 -0
  408. package/vendor/shared/dist/commandText.d.ts +12 -0
  409. package/vendor/shared/dist/commandText.d.ts.map +1 -0
  410. package/vendor/shared/dist/commandText.js +21 -0
  411. package/vendor/shared/dist/commands.d.ts +1534 -0
  412. package/vendor/shared/dist/commands.d.ts.map +1 -0
  413. package/vendor/shared/dist/commands.js +233 -0
  414. package/vendor/shared/dist/computer.d.ts +9 -9
  415. package/vendor/shared/dist/computer.d.ts.map +1 -1
  416. package/vendor/shared/dist/computer.js +12 -2
  417. package/vendor/shared/dist/constants.d.ts +3 -3
  418. package/vendor/shared/dist/constants.d.ts.map +1 -1
  419. package/vendor/shared/dist/constants.js +9 -2
  420. package/vendor/shared/dist/dayPlan.d.ts +86 -0
  421. package/vendor/shared/dist/dayPlan.d.ts.map +1 -0
  422. package/vendor/shared/dist/dayPlan.js +46 -0
  423. package/vendor/shared/dist/dayPlanning.d.ts +139 -0
  424. package/vendor/shared/dist/dayPlanning.d.ts.map +1 -0
  425. package/vendor/shared/dist/dayPlanning.js +67 -0
  426. package/vendor/shared/dist/githubContributions.d.ts +93 -0
  427. package/vendor/shared/dist/githubContributions.d.ts.map +1 -0
  428. package/vendor/shared/dist/githubContributions.js +54 -0
  429. package/vendor/shared/dist/habitContributions.d.ts +26 -0
  430. package/vendor/shared/dist/habitContributions.d.ts.map +1 -0
  431. package/vendor/shared/dist/habitContributions.js +119 -0
  432. package/vendor/shared/dist/index.d.ts +28 -2
  433. package/vendor/shared/dist/index.d.ts.map +1 -1
  434. package/vendor/shared/dist/index.js +25 -2
  435. package/vendor/shared/dist/journal-migration.d.ts +29 -0
  436. package/vendor/shared/dist/journal-migration.d.ts.map +1 -0
  437. package/vendor/shared/dist/journal-migration.js +73 -0
  438. package/vendor/shared/dist/journal-vault.d.ts +414 -0
  439. package/vendor/shared/dist/journal-vault.d.ts.map +1 -0
  440. package/vendor/shared/dist/journal-vault.js +972 -0
  441. package/vendor/shared/dist/projectCapture.d.ts +73 -0
  442. package/vendor/shared/dist/projectCapture.d.ts.map +1 -0
  443. package/vendor/shared/dist/projectCapture.js +66 -0
  444. package/vendor/shared/dist/quickAdd.d.ts +90 -0
  445. package/vendor/shared/dist/quickAdd.d.ts.map +1 -0
  446. package/vendor/shared/dist/quickAdd.js +260 -0
  447. package/vendor/shared/dist/recurrence.d.ts +44 -0
  448. package/vendor/shared/dist/recurrence.d.ts.map +1 -0
  449. package/vendor/shared/dist/recurrence.js +37 -0
  450. package/vendor/shared/dist/reminderWords.d.ts +11 -0
  451. package/vendor/shared/dist/reminderWords.d.ts.map +1 -0
  452. package/vendor/shared/dist/reminderWords.js +63 -0
  453. package/vendor/shared/dist/schemas/comment.d.ts +13 -1
  454. package/vendor/shared/dist/schemas/comment.d.ts.map +1 -1
  455. package/vendor/shared/dist/schemas/comment.js +5 -0
  456. package/vendor/shared/dist/schemas/conversation.d.ts +3 -3
  457. package/vendor/shared/dist/schemas/harness.d.ts +976 -59
  458. package/vendor/shared/dist/schemas/harness.d.ts.map +1 -1
  459. package/vendor/shared/dist/schemas/harness.js +124 -3
  460. package/vendor/shared/dist/schemas/journal.d.ts +10 -0
  461. package/vendor/shared/dist/schemas/journal.d.ts.map +1 -1
  462. package/vendor/shared/dist/schemas/journal.js +10 -2
  463. package/vendor/shared/dist/schemas/notification.d.ts +1 -1
  464. package/vendor/shared/dist/schemas/organization.d.ts +3 -2
  465. package/vendor/shared/dist/schemas/organization.d.ts.map +1 -1
  466. package/vendor/shared/dist/schemas/organization.js +3 -2
  467. package/vendor/shared/dist/schemas/proposal.d.ts +7 -3
  468. package/vendor/shared/dist/schemas/proposal.d.ts.map +1 -1
  469. package/vendor/shared/dist/schemas/proposal.js +2 -1
  470. package/vendor/shared/dist/schemas/request.d.ts +44 -4
  471. package/vendor/shared/dist/schemas/request.d.ts.map +1 -1
  472. package/vendor/shared/dist/schemas/task.d.ts +83 -8
  473. package/vendor/shared/dist/schemas/task.d.ts.map +1 -1
  474. package/vendor/shared/dist/schemas/task.js +20 -2
  475. package/vendor/shared/dist/schemas/timeSession.d.ts +2 -2
  476. package/vendor/shared/dist/smartCapture.d.ts +60 -0
  477. package/vendor/shared/dist/smartCapture.d.ts.map +1 -0
  478. package/vendor/shared/dist/smartCapture.js +56 -0
  479. package/vendor/shared/dist/speech.d.ts +39 -0
  480. package/vendor/shared/dist/speech.d.ts.map +1 -0
  481. package/vendor/shared/dist/speech.js +36 -0
  482. package/vendor/shared/dist/spokenNames.d.ts +25 -0
  483. package/vendor/shared/dist/spokenNames.d.ts.map +1 -0
  484. package/vendor/shared/dist/spokenNames.js +120 -0
  485. package/vendor/shared/dist/taskActivity.d.ts +76 -0
  486. package/vendor/shared/dist/taskActivity.d.ts.map +1 -0
  487. package/vendor/shared/dist/taskActivity.js +27 -0
  488. package/vendor/shared/dist/vault-search.d.ts +50 -0
  489. package/vendor/shared/dist/vault-search.d.ts.map +1 -0
  490. package/vendor/shared/dist/vault-search.js +177 -0
  491. package/vendor/shared/dist/voiceCapture.d.ts +32 -0
  492. package/vendor/shared/dist/voiceCapture.d.ts.map +1 -0
  493. package/vendor/shared/dist/voiceCapture.js +29 -0
  494. package/vendor/shared/package.json +4 -0
  495. package/vendor/shared/src/agentCommands.ts +35 -0
  496. package/vendor/shared/src/automationTemplates.ts +54 -0
  497. package/vendor/shared/src/automations.ts +329 -0
  498. package/vendor/shared/src/cardStatement.ts +49 -0
  499. package/vendor/shared/src/cardStudio.ts +340 -0
  500. package/vendor/shared/src/commandLocal.ts +740 -0
  501. package/vendor/shared/src/commandText.ts +25 -0
  502. package/vendor/shared/src/commands.ts +255 -0
  503. package/vendor/shared/src/computer.ts +25 -6
  504. package/vendor/shared/src/constants.ts +9 -2
  505. package/vendor/shared/src/dayPlan.ts +81 -0
  506. package/vendor/shared/src/dayPlanning.ts +77 -0
  507. package/vendor/shared/src/githubContributions.ts +70 -0
  508. package/vendor/shared/src/habitContributions.ts +144 -0
  509. package/vendor/shared/src/index.ts +44 -1
  510. package/vendor/shared/src/journal-migration.ts +130 -0
  511. package/vendor/shared/src/journal-vault.ts +1240 -0
  512. package/vendor/shared/src/projectCapture.ts +86 -0
  513. package/vendor/shared/src/quickAdd.ts +310 -0
  514. package/vendor/shared/src/recurrence.ts +37 -0
  515. package/vendor/shared/src/reminderWords.ts +54 -0
  516. package/vendor/shared/src/schemas/comment.ts +5 -0
  517. package/vendor/shared/src/schemas/harness.ts +146 -7
  518. package/vendor/shared/src/schemas/journal.ts +15 -6
  519. package/vendor/shared/src/schemas/organization.ts +3 -2
  520. package/vendor/shared/src/schemas/proposal.ts +6 -1
  521. package/vendor/shared/src/schemas/task.ts +20 -2
  522. package/vendor/shared/src/smartCapture.ts +67 -0
  523. package/vendor/shared/src/speech.ts +44 -0
  524. package/vendor/shared/src/spokenNames.ts +128 -0
  525. package/vendor/shared/src/taskActivity.ts +34 -0
  526. package/vendor/shared/src/vault-search.ts +243 -0
  527. package/vendor/shared/src/voiceCapture.ts +34 -0
@@ -0,0 +1,1240 @@
1
+ import { z } from 'zod';
2
+ import {
3
+ CreateJournalSegmentSchema,
4
+ JournalDaySchema,
5
+ JournalSegmentSchema,
6
+ JournalObservationSchema,
7
+ CorrectJournalSegmentSchema,
8
+ } from './schemas/journal.js';
9
+ import {
10
+ ProposalWithEvidenceSchema,
11
+ ProposalSchema,
12
+ TaskProposalPayloadSchema,
13
+ LinkProposalPayloadSchema,
14
+ } from './schemas/proposal.js';
15
+ import { LocalSearchIndex, type IndexedDocument } from './vault-search.js';
16
+
17
+ /** Reserved application records. Portable exports belong outside this directory. */
18
+ export const JOURNAL_RECORDS = 'Journal/Records/';
19
+ export function isJournalRecordPath(path: string) {
20
+ const parts: string[] = [];
21
+ for (const part of path.replaceAll('\\', '/').split('/')) {
22
+ if (!part || part === '.') continue;
23
+ if (part === '..') parts.pop();
24
+ else parts.push(part);
25
+ }
26
+ const normalized = parts.join('/').toLowerCase();
27
+ return (
28
+ normalized === 'journal/records' ||
29
+ normalized.startsWith('journal/records/')
30
+ );
31
+ }
32
+ const sha = z.string().regex(/^[a-f0-9]{64}$/);
33
+ const common = { version: z.literal(1), owner: z.uuidv7(), id: z.uuidv7() };
34
+ const recordSchema = z.discriminatedUnion('kind', [
35
+ z.object({
36
+ ...common,
37
+ kind: z.literal('capture'),
38
+ segment: JournalSegmentSchema.omit({
39
+ transcript: true,
40
+ correctedTranscript: true,
41
+ }),
42
+ day: JournalDaySchema,
43
+ bodyHash: sha,
44
+ }),
45
+ z.object({
46
+ ...common,
47
+ kind: z.literal('correction'),
48
+ segmentId: z.uuidv7(),
49
+ parents: z.array(sha).min(1),
50
+ at: z.coerce.date(),
51
+ revert: z.boolean(),
52
+ bodyHash: sha,
53
+ }),
54
+ z.object({
55
+ ...common,
56
+ kind: z.literal('deletion'),
57
+ segmentId: z.uuidv7(),
58
+ at: z.coerce.date(),
59
+ }),
60
+ z.object({
61
+ ...common,
62
+ kind: z.literal('extraction'),
63
+ segmentId: z.uuidv7(),
64
+ revision: sha,
65
+ extractorVersion: z.string(),
66
+ at: z.coerce.date(),
67
+ model: z.string().optional(),
68
+ error: z.string().optional(),
69
+ observations: z.array(JournalObservationSchema),
70
+ proposals: z.array(ProposalWithEvidenceSchema),
71
+ legacyStamp: z.unknown().optional(),
72
+ }),
73
+ z.object({
74
+ ...common,
75
+ kind: z.literal('decision'),
76
+ proposalId: z.uuidv7(),
77
+ segmentId: z.uuidv7().nullable(),
78
+ status: z.enum(['accepting', 'accepted', 'rejected']),
79
+ at: z.coerce.date(),
80
+ payload: z.unknown(),
81
+ resultId: z.uuidv7().nullable(),
82
+ reason: z.string().nullable(),
83
+ }),
84
+ z.object({
85
+ ...common,
86
+ kind: z.literal('legacy-proposal'),
87
+ proposal: ProposalWithEvidenceSchema,
88
+ segmentId: z.uuidv7().nullable(),
89
+ }),
90
+ z.object({ ...common, kind: z.literal('legacy-day'), day: JournalDaySchema }),
91
+ z.object({
92
+ ...common,
93
+ kind: z.literal('activation'),
94
+ sourceDigest: sha,
95
+ vaultDigest: sha,
96
+ files: z
97
+ .array(
98
+ z.object({
99
+ path: z.string(),
100
+ hash: sha,
101
+ segmentId: z.uuidv7().optional(),
102
+ }),
103
+ )
104
+ .default([]),
105
+ }),
106
+ ]);
107
+ export type JournalVaultRecord = z.infer<typeof recordSchema>;
108
+ type StoredRecord = {
109
+ record: JournalVaultRecord;
110
+ body: string;
111
+ revision: string;
112
+ path: string;
113
+ };
114
+ export type PrivateJournalSegment = z.infer<typeof JournalSegmentSchema> & {
115
+ observations: z.infer<typeof JournalObservationSchema>[];
116
+ revisions: string[];
117
+ conflicts: { revision: string; text: string }[];
118
+ localDate: string;
119
+ timeZone: string | null;
120
+ };
121
+ export interface JournalFiles {
122
+ scope(): Promise<string>;
123
+ list(): Promise<
124
+ {
125
+ path: string;
126
+ fingerprint: string;
127
+ downloaded?: boolean;
128
+ uploaded?: boolean;
129
+ conflicted?: boolean;
130
+ }[]
131
+ >;
132
+ read(path: string): Promise<string>;
133
+ /** Atomic create; must never overwrite an existing file. */
134
+ create(path: string, content: string): Promise<void>;
135
+ /** Remove only if the current contents equal expectedContent. */
136
+ remove(path: string, expectedContent: string): Promise<void>;
137
+ requestDownloads?(paths: string[]): Promise<void>;
138
+ hash(content: string): Promise<string>;
139
+ uuid(): string;
140
+ }
141
+ export class JournalVaultError extends Error {
142
+ constructor(
143
+ public code: 'unavailable' | 'changed' | 'conflict' | 'invalid' | 'deleted',
144
+ message: string,
145
+ ) {
146
+ super(message);
147
+ }
148
+ }
149
+ const invalid = () =>
150
+ new JournalVaultError(
151
+ 'invalid',
152
+ 'A Journal record needs attention. Its original file has been preserved.',
153
+ );
154
+ const prefix = '<!-- lucidity-journal-v1 ';
155
+
156
+ /** Immutable files plus a disposable index; no HTTP client or hosted fallback. */
157
+ export class JournalVault {
158
+ private records = new Map<
159
+ string,
160
+ StoredRecord & { fingerprint: string; content: string }
161
+ >();
162
+ private scope = '';
163
+ private revoked = false;
164
+ private unresolved = 0;
165
+ private serial: Promise<unknown> = Promise.resolve();
166
+ private listeners = new Set<() => void>();
167
+ private state = { version: 0, pending: 0, ready: false, error: '' };
168
+ constructor(
169
+ readonly owner: string,
170
+ private files: JournalFiles,
171
+ private index?: () => Promise<LocalSearchIndex>,
172
+ ) {
173
+ z.uuidv7().parse(owner);
174
+ }
175
+ get root() {
176
+ return `${JOURNAL_RECORDS}${this.owner}/`;
177
+ }
178
+ get storageScope() {
179
+ return this.scope;
180
+ }
181
+ getSnapshot = () => this.state;
182
+ subscribe = (fn: () => void) => {
183
+ this.listeners.add(fn);
184
+ return () => {
185
+ this.listeners.delete(fn);
186
+ };
187
+ };
188
+ private publish(next: Partial<typeof this.state>) {
189
+ this.state = { ...this.state, ...next, version: this.state.version + 1 };
190
+ this.listeners.forEach((fn) => fn());
191
+ }
192
+ private run<T>(fn: () => Promise<T>): Promise<T> {
193
+ const work = this.serial.then(fn, fn);
194
+ this.serial = work.catch(() => {});
195
+ return work;
196
+ }
197
+ private async session() {
198
+ if (this.revoked)
199
+ throw new JournalVaultError(
200
+ 'changed',
201
+ 'Reopen Journal to connect the current vault account.',
202
+ );
203
+ let scope: string;
204
+ try {
205
+ scope = await this.files.scope();
206
+ } catch (error) {
207
+ this.records.clear();
208
+ if (error instanceof JournalVaultError && error.code === 'changed')
209
+ this.revoked = true;
210
+ if (this.scope)
211
+ await (
212
+ await this.index?.()
213
+ )?.clear(`${this.scope}:journal:${this.owner}`);
214
+ this.publish({
215
+ ready: false,
216
+ error:
217
+ 'Your Journal vault is unavailable. Reconnect the original account.',
218
+ });
219
+ throw error;
220
+ }
221
+ if (!scope)
222
+ throw new JournalVaultError(
223
+ 'unavailable',
224
+ 'Connect your personal vault to use Journal.',
225
+ );
226
+ if (this.scope && this.scope !== scope) {
227
+ const previous = this.scope;
228
+ this.records.clear();
229
+ this.revoked = true;
230
+ await (await this.index?.())?.clear(`${previous}:journal:${this.owner}`);
231
+ this.publish({
232
+ ready: false,
233
+ error:
234
+ 'The vault account changed. Reopen Journal to connect this account.',
235
+ });
236
+ throw new JournalVaultError('changed', this.state.error);
237
+ }
238
+ this.scope = scope;
239
+ return scope;
240
+ }
241
+ private async check(scope: string) {
242
+ if (scope !== (await this.session())) {
243
+ this.records.clear();
244
+ this.revoked = true;
245
+ this.publish({ ready: false });
246
+ throw new JournalVaultError(
247
+ 'changed',
248
+ 'The vault account changed. Your capture has not been saved to the new account.',
249
+ );
250
+ }
251
+ }
252
+ private async encode(record: JournalVaultRecord, body = '') {
253
+ const metadata = JSON.stringify(recordSchema.parse(record))
254
+ .replaceAll('<', '\\u003c')
255
+ .replaceAll('>', '\\u003e');
256
+ return `${prefix}${metadata} -->\n\n${body}`;
257
+ }
258
+ private async decode(path: string, content: string): Promise<StoredRecord> {
259
+ const end = content.indexOf(' -->\n\n');
260
+ if (!content.startsWith(prefix) || end < 0) throw invalid();
261
+ let record: JournalVaultRecord;
262
+ try {
263
+ record = recordSchema.parse(
264
+ JSON.parse(content.slice(prefix.length, end)),
265
+ );
266
+ } catch {
267
+ throw invalid();
268
+ }
269
+ const body = content.slice(end + ' -->\n\n'.length);
270
+ if (record.owner !== this.owner) throw invalid();
271
+ if (
272
+ 'bodyHash' in record &&
273
+ (await this.files.hash(body)) !== record.bodyHash
274
+ )
275
+ throw invalid();
276
+ if (
277
+ record.kind === 'capture' &&
278
+ (record.segment.userId !== this.owner ||
279
+ record.day.userId !== this.owner ||
280
+ record.segment.dayId !== record.day.id ||
281
+ record.segment.id !== record.id)
282
+ )
283
+ throw invalid();
284
+ if (path !== this.path(record)) throw invalid();
285
+ return { path, record, body, revision: await this.files.hash(content) };
286
+ }
287
+ private path(record: JournalVaultRecord) {
288
+ switch (record.kind) {
289
+ case 'capture':
290
+ return `${this.root}captures/${record.day.localDate.replaceAll('-', '/')}/${record.id}.md`;
291
+ case 'correction':
292
+ return `${this.root}corrections/${record.segmentId}/${record.id}.md`;
293
+ case 'deletion':
294
+ return `${this.root}deletions/${record.segmentId}.md`;
295
+ case 'extraction':
296
+ return `${this.root}extractions/${record.segmentId}/${record.id}.md`;
297
+ case 'decision':
298
+ return `${this.root}decisions/${record.proposalId}/${record.id}.md`;
299
+ case 'legacy-proposal':
300
+ return `${this.root}imports/proposals/${record.id}.md`;
301
+ case 'legacy-day':
302
+ return `${this.root}imports/days/${record.id}.md`;
303
+ case 'activation':
304
+ return `${this.root}activation/${record.id}.md`;
305
+ }
306
+ }
307
+ private async commit(record: JournalVaultRecord, body = '') {
308
+ const scope = await this.session();
309
+ const path = this.path(record),
310
+ content = await this.encode(record, body);
311
+ await this.check(scope);
312
+ try {
313
+ await this.files.create(path, content);
314
+ } catch (error) {
315
+ // A response may be lost after a successful create. Only identical bytes are a retry.
316
+ let existing: string;
317
+ try {
318
+ existing = await this.files.read(path);
319
+ } catch {
320
+ throw error;
321
+ }
322
+ if (existing !== content)
323
+ throw new JournalVaultError(
324
+ 'conflict',
325
+ 'A different Journal record already exists. Both copies have been preserved.',
326
+ );
327
+ }
328
+ await this.check(scope);
329
+ if ((await this.files.read(path)) !== content) throw invalid();
330
+ this.records.set(path, {
331
+ ...(await this.decode(path, content)),
332
+ content,
333
+ fingerprint: '',
334
+ });
335
+ return path;
336
+ }
337
+ refresh = () => this.run(() => this.reconcile());
338
+ private async reconcile() {
339
+ const scope = await this.session();
340
+ try {
341
+ const files = (await this.files.list()).filter((file) =>
342
+ file.path.startsWith(this.root),
343
+ );
344
+ await this.check(scope);
345
+ const paths = new Set(files.map((file) => file.path));
346
+ for (const path of this.records.keys())
347
+ if (!paths.has(path)) this.records.delete(path);
348
+ let pending = 0;
349
+ for (const file of files) {
350
+ if (file.conflicted) {
351
+ this.records.delete(file.path);
352
+ throw new JournalVaultError(
353
+ 'conflict',
354
+ 'iCloud has conflicting Journal files. Both copies are preserved; resolve them before continuing.',
355
+ );
356
+ }
357
+ if (file.downloaded === false) {
358
+ this.records.delete(file.path);
359
+ pending++;
360
+ continue;
361
+ }
362
+ if (this.records.get(file.path)?.fingerprint === file.fingerprint)
363
+ continue;
364
+ this.records.delete(file.path);
365
+ let content: string;
366
+ try {
367
+ content = await this.files.read(file.path);
368
+ } catch (error) {
369
+ if (
370
+ error instanceof JournalVaultError &&
371
+ error.code === 'unavailable'
372
+ ) {
373
+ pending++;
374
+ continue;
375
+ }
376
+ throw error;
377
+ }
378
+ const decoded = await this.decode(file.path, content);
379
+ await this.check(scope);
380
+ this.records.set(file.path, {
381
+ ...decoded,
382
+ content,
383
+ fingerprint: file.fingerprint,
384
+ });
385
+ }
386
+ if (pending)
387
+ await this.files.requestDownloads?.(
388
+ files
389
+ .filter((f) => f.downloaded === false)
390
+ .slice(0, 8)
391
+ .map((f) => f.path),
392
+ );
393
+ await this.cleanup();
394
+ await this.reindex();
395
+ await this.check(scope);
396
+ this.publish({
397
+ pending: pending + this.unresolved,
398
+ ready: true,
399
+ error: '',
400
+ });
401
+ } catch (error) {
402
+ // Never let an invalid/deleted record leave searchable stale words behind.
403
+ await (await this.index?.())?.clear(`${scope}:journal:${this.owner}`);
404
+ this.publish({
405
+ ready: false,
406
+ error:
407
+ error instanceof JournalVaultError
408
+ ? error.message
409
+ : 'Journal could not read your vault. Your files are unchanged.',
410
+ });
411
+ throw error;
412
+ }
413
+ }
414
+ private tombstones() {
415
+ return new Set(
416
+ [...this.records.values()].flatMap(({ record }) =>
417
+ record.kind === 'deletion' ? [record.segmentId] : [],
418
+ ),
419
+ );
420
+ }
421
+ private async cleanup() {
422
+ const deleted = this.tombstones();
423
+ for (const [path, stored] of this.records) {
424
+ const r = stored.record;
425
+ const id =
426
+ r.kind === 'capture' ? r.id : 'segmentId' in r ? r.segmentId : null;
427
+ if (id && deleted.has(id) && r.kind !== 'deletion') {
428
+ await this.check(this.scope);
429
+ await this.files.remove(path, stored.content);
430
+ this.records.delete(path);
431
+ }
432
+ }
433
+ }
434
+ segments(): PrivateJournalSegment[] {
435
+ const deleted = this.tombstones();
436
+ const all = [...this.records.values()];
437
+ const correctionsBySegment = new Map<string, StoredRecord[]>();
438
+ const extractionsByRevision = new Map<string, StoredRecord[]>();
439
+ const proposals = new Map<
440
+ string,
441
+ z.infer<typeof ProposalWithEvidenceSchema>
442
+ >();
443
+ for (const stored of all) {
444
+ const r = stored.record;
445
+ if (r.kind === 'correction') {
446
+ const list = correctionsBySegment.get(r.segmentId) ?? [];
447
+ list.push(stored);
448
+ correctionsBySegment.set(r.segmentId, list);
449
+ } else if (r.kind === 'extraction') {
450
+ const key = r.segmentId + r.revision;
451
+ const list = extractionsByRevision.get(key) ?? [];
452
+ list.push(stored);
453
+ extractionsByRevision.set(key, list);
454
+ r.proposals.forEach((p) => proposals.set(p.id, p));
455
+ } else if (r.kind === 'legacy-proposal')
456
+ proposals.set(r.proposal.id, r.proposal);
457
+ }
458
+ const links = new Map<
459
+ string,
460
+ Extract<JournalVaultRecord, { kind: 'decision' }>
461
+ >();
462
+ for (const { record: r } of all)
463
+ if (r.kind === 'decision' && r.status === 'accepted') {
464
+ const proposal = proposals.get(r.proposalId);
465
+ if (
466
+ proposal?.kind === 'link' &&
467
+ proposal.observationId &&
468
+ (!links.has(proposal.observationId) ||
469
+ links.get(proposal.observationId)!.id < r.id)
470
+ )
471
+ links.set(proposal.observationId, r);
472
+ }
473
+ const captureIds = new Set(
474
+ all.flatMap((r) => (r.record.kind === 'capture' ? [r.record.id] : [])),
475
+ );
476
+ this.unresolved = new Set(
477
+ all.flatMap(({ record: r }) =>
478
+ 'segmentId' in r &&
479
+ r.segmentId &&
480
+ r.kind !== 'deletion' &&
481
+ !deleted.has(r.segmentId) &&
482
+ !captureIds.has(r.segmentId)
483
+ ? [r.segmentId]
484
+ : [],
485
+ ),
486
+ ).size;
487
+ return all
488
+ .flatMap((capture) => {
489
+ const c = capture.record;
490
+ if (c.kind !== 'capture' || deleted.has(c.id)) return [];
491
+ const candidates = correctionsBySegment.get(c.id) ?? [];
492
+ // Parents must exist. Missing parents are an incomplete download, not a new winner.
493
+ const connected = new Set([capture.revision]);
494
+ for (let pass = 0; pass < candidates.length; pass++)
495
+ for (const candidate of candidates) {
496
+ if (
497
+ candidate.record.kind === 'correction' &&
498
+ candidate.record.parents.every((p) => connected.has(p))
499
+ )
500
+ connected.add(candidate.revision);
501
+ }
502
+ if (candidates.some((r) => !connected.has(r.revision))) {
503
+ this.unresolved++;
504
+ return [];
505
+ }
506
+ const superseded = new Set(
507
+ candidates.flatMap((r) =>
508
+ r.record.kind === 'correction' ? r.record.parents : [],
509
+ ),
510
+ );
511
+ const leaves = [capture, ...candidates]
512
+ .filter((r) => !superseded.has(r.revision))
513
+ .sort((a, b) => a.revision.localeCompare(b.revision));
514
+ const text = (r: StoredRecord) =>
515
+ r.record.kind === 'correction' && !r.record.revert
516
+ ? r.body
517
+ : capture.body;
518
+ const current = leaves.length === 1 ? leaves[0]! : capture;
519
+ const corrections = leaves.filter(
520
+ (r) => r.record.kind === 'correction',
521
+ );
522
+ const extraction = (
523
+ extractionsByRevision.get(c.id + current.revision) ?? []
524
+ ).sort((a, b) => b.record.id.localeCompare(a.record.id))[0];
525
+ const observations = (
526
+ leaves.length === 1 && extraction?.record.kind === 'extraction'
527
+ ? extraction.record.observations
528
+ : []
529
+ ).map((observation) => {
530
+ const decision = links.get(observation.id);
531
+ if (!decision) return observation;
532
+ const link = LinkProposalPayloadSchema.safeParse(decision.payload);
533
+ return link.success
534
+ ? {
535
+ ...observation,
536
+ [link.data.target === 'project' ? 'projectId' : 'taskId']:
537
+ link.data.targetId,
538
+ updatedAt: decision.at,
539
+ }
540
+ : observation;
541
+ });
542
+ return [
543
+ {
544
+ ...c.segment,
545
+ transcript: capture.body,
546
+ correctedTranscript:
547
+ current.record.kind === 'correction' && !current.record.revert
548
+ ? current.body
549
+ : null,
550
+ localDate: c.day.localDate,
551
+ timeZone: c.day.timeZone,
552
+ updatedAt: corrections.reduce(
553
+ (at, r) =>
554
+ r.record.kind === 'correction' && r.record.at > at
555
+ ? r.record.at
556
+ : at,
557
+ c.segment.updatedAt,
558
+ ),
559
+ revisions: leaves.map((r) => r.revision),
560
+ conflicts:
561
+ leaves.length > 1
562
+ ? leaves.map((r) => ({ revision: r.revision, text: text(r) }))
563
+ : [],
564
+ observations,
565
+ },
566
+ ];
567
+ })
568
+ .sort(
569
+ (a, b) =>
570
+ a.capturedAt.getTime() - b.capturedAt.getTime() ||
571
+ a.id.localeCompare(b.id),
572
+ );
573
+ }
574
+ async days(opts: { before?: string; limit?: number } = {}) {
575
+ await this.refresh();
576
+ const groups = new Map<string, PrivateJournalSegment[]>();
577
+ for (const segment of this.segments()) {
578
+ const list = groups.get(segment.localDate) ?? [];
579
+ list.push(segment);
580
+ groups.set(segment.localDate, list);
581
+ }
582
+ return [...groups]
583
+ .filter(([date]) => !opts.before || date < opts.before)
584
+ .sort(([a], [b]) => b.localeCompare(a))
585
+ .slice(0, opts.limit ?? 30)
586
+ .map(([localDate, segments]) => {
587
+ const first = segments[0]!;
588
+ return {
589
+ id: first.dayId,
590
+ userId: this.owner,
591
+ localDate,
592
+ timeZone: first.timeZone,
593
+ createdAt: first.createdAt,
594
+ updatedAt: new Date(
595
+ Math.max(...segments.map((s) => s.updatedAt.getTime())),
596
+ ),
597
+ segmentCount: segments.length,
598
+ totalDurationMs: segments.reduce(
599
+ (n, s) => n + (s.durationMs ?? 0),
600
+ 0,
601
+ ),
602
+ firstCapturedAt: first.capturedAt,
603
+ lastCapturedAt: segments.at(-1)!.capturedAt,
604
+ preview: (first.correctedTranscript ?? first.transcript)
605
+ .replace(/\s+/g, ' ')
606
+ .slice(0, 180),
607
+ };
608
+ });
609
+ }
610
+ async day(localDate: string) {
611
+ const days = await this.days({ limit: Number.MAX_SAFE_INTEGER });
612
+ const day = days.find((d) => d.localDate === localDate);
613
+ return day
614
+ ? {
615
+ ...day,
616
+ segments: this.segments().filter((s) => s.localDate === localDate),
617
+ }
618
+ : null;
619
+ }
620
+ capture(input: z.input<typeof CreateJournalSegmentSchema>) {
621
+ return this.run(async () => {
622
+ await this.reconcile();
623
+ const parsed = CreateJournalSegmentSchema.parse(input);
624
+ if (this.tombstones().has(parsed.id))
625
+ throw new JournalVaultError(
626
+ 'deleted',
627
+ 'This capture was deleted on another device.',
628
+ );
629
+ const existing = this.segments().find((s) => s.id === parsed.id);
630
+ if (existing) {
631
+ if (
632
+ existing.transcript !== parsed.transcript ||
633
+ existing.localDate !== parsed.localDate
634
+ )
635
+ throw invalid();
636
+ return existing;
637
+ }
638
+ const at = parsed.capturedAt;
639
+ const dayId =
640
+ this.segments().find((s) => s.localDate === parsed.localDate)?.dayId ??
641
+ parsed.id;
642
+ await this.commit(
643
+ {
644
+ version: 1,
645
+ owner: this.owner,
646
+ id: parsed.id,
647
+ kind: 'capture',
648
+ bodyHash: await this.files.hash(parsed.transcript),
649
+ day: {
650
+ id: dayId,
651
+ userId: this.owner,
652
+ localDate: parsed.localDate,
653
+ timeZone: parsed.timeZone ?? null,
654
+ createdAt: at,
655
+ updatedAt: at,
656
+ },
657
+ segment: {
658
+ id: parsed.id,
659
+ dayId,
660
+ userId: this.owner,
661
+ capturedAt: at,
662
+ durationMs: parsed.durationMs ?? null,
663
+ source: parsed.source,
664
+ engine: parsed.engine ?? null,
665
+ createdAt: at,
666
+ updatedAt: at,
667
+ },
668
+ },
669
+ parsed.transcript,
670
+ );
671
+ await this.reindex();
672
+ this.publish({});
673
+ return this.segments().find((s) => s.id === parsed.id)!;
674
+ });
675
+ }
676
+ correct(segmentId: string, text: string | null, expectedRevisions: string[]) {
677
+ return this.run(async () => {
678
+ await this.reconcile();
679
+ const segment = this.segments().find((s) => s.id === segmentId);
680
+ if (!segment)
681
+ throw new JournalVaultError(
682
+ 'deleted',
683
+ 'The capture is unavailable or has been deleted.',
684
+ );
685
+ if (
686
+ [...expectedRevisions].sort().join() !==
687
+ [...segment.revisions].sort().join()
688
+ )
689
+ throw new JournalVaultError(
690
+ 'changed',
691
+ 'This capture changed on another device. Reload it before saving your correction.',
692
+ );
693
+ const { correctedTranscript } = CorrectJournalSegmentSchema.parse({
694
+ correctedTranscript: text,
695
+ });
696
+ await this.commit(
697
+ {
698
+ version: 1,
699
+ owner: this.owner,
700
+ id: this.files.uuid(),
701
+ kind: 'correction',
702
+ segmentId,
703
+ parents: expectedRevisions,
704
+ at: new Date(),
705
+ revert: correctedTranscript === null,
706
+ bodyHash: await this.files.hash(correctedTranscript ?? ''),
707
+ },
708
+ correctedTranscript ?? '',
709
+ );
710
+ await this.reindex();
711
+ this.publish({});
712
+ return this.segments().find((s) => s.id === segmentId)!;
713
+ });
714
+ }
715
+ delete(segmentId: string) {
716
+ return this.run(async () => {
717
+ await this.reconcile();
718
+ if (!this.tombstones().has(segmentId))
719
+ await this.commit({
720
+ version: 1,
721
+ owner: this.owner,
722
+ id: segmentId,
723
+ kind: 'deletion',
724
+ segmentId,
725
+ at: new Date(),
726
+ });
727
+ await this.cleanup();
728
+ await this.reindex();
729
+ this.publish({});
730
+ return { ok: true as const };
731
+ });
732
+ }
733
+ private async reindex() {
734
+ const index = await this.index?.();
735
+ if (!index) return;
736
+ const scope = `${this.scope}:journal:${this.owner}`;
737
+ const segments = this.segments().filter((s) => !s.conflicts.length);
738
+ const ids = new Set(segments.map((s) => s.id));
739
+ const inventory = new Map(
740
+ (await index.inventory(scope, 'journal')).map((row) => [
741
+ row.id,
742
+ row.fingerprint,
743
+ ]),
744
+ );
745
+ for (const id of inventory.keys())
746
+ if (!ids.has(id)) await index.remove(scope, 'journal', id);
747
+ for (const segment of segments) {
748
+ const revision = segment.revisions[0]!;
749
+ if (inventory.get(segment.id) === revision) continue;
750
+ const document: IndexedDocument = {
751
+ id: segment.id,
752
+ kind: 'journal',
753
+ path: segment.localDate,
754
+ title: segment.localDate,
755
+ body: segment.correctedTranscript ?? segment.transcript,
756
+ revision,
757
+ fingerprint: revision,
758
+ modifiedAt: segment.capturedAt.getTime(),
759
+ };
760
+ await this.check(this.scope);
761
+ await index.put(scope, document);
762
+ }
763
+ }
764
+ /** Imports are replayable, preserve server timestamps/IDs, and verify each written file. */
765
+ importLegacy(snapshot: JournalLegacySnapshot) {
766
+ return this.run(async () => {
767
+ await this.reconcile();
768
+ const paths = new Set<string>();
769
+ const commit = async (record: JournalVaultRecord, body = '') => {
770
+ paths.add(await this.commit(record, body));
771
+ };
772
+ const days = snapshot.days.map((row) => JournalDaySchema.parse(row));
773
+ const segments = snapshot.segments.map((row) =>
774
+ JournalSegmentSchema.parse(row),
775
+ );
776
+ const observations = snapshot.observations.map((row) =>
777
+ JournalObservationSchema.parse(row),
778
+ );
779
+ for (const day of days) {
780
+ if (day.userId !== this.owner) throw invalid();
781
+ await commit({
782
+ version: 1,
783
+ owner: this.owner,
784
+ id: day.id,
785
+ kind: 'legacy-day',
786
+ day,
787
+ });
788
+ }
789
+ for (const source of segments) {
790
+ const day = days.find((d) => d.id === source.dayId);
791
+ if (!day || source.userId !== this.owner) throw invalid();
792
+ if (this.tombstones().has(source.id))
793
+ throw new JournalVaultError(
794
+ 'deleted',
795
+ 'A migrated capture has since been deleted. Resume from the completed migration receipt.',
796
+ );
797
+ const { transcript, correctedTranscript, ...segment } = source;
798
+ const base: JournalVaultRecord = {
799
+ version: 1,
800
+ owner: this.owner,
801
+ id: source.id,
802
+ kind: 'capture',
803
+ day,
804
+ segment,
805
+ bodyHash: await this.files.hash(transcript),
806
+ };
807
+ await commit(base, transcript);
808
+ let revision = await this.files.hash(
809
+ await this.encode(base, transcript),
810
+ );
811
+ if (correctedTranscript !== null) {
812
+ const correction: JournalVaultRecord = {
813
+ version: 1,
814
+ owner: this.owner,
815
+ id: source.id,
816
+ kind: 'correction',
817
+ segmentId: source.id,
818
+ parents: [revision],
819
+ at: source.updatedAt,
820
+ revert: false,
821
+ bodyHash: await this.files.hash(correctedTranscript),
822
+ };
823
+ await commit(correction, correctedTranscript);
824
+ revision = await this.files.hash(
825
+ await this.encode(correction, correctedTranscript),
826
+ );
827
+ }
828
+ const stamp = snapshot.extractions.find(
829
+ (row) => row.segmentId === source.id,
830
+ );
831
+ const derived = observations.filter((o) => o.segmentId === source.id);
832
+ if (derived.some((o) => o.userId !== this.owner)) throw invalid();
833
+ if (stamp || derived.length) {
834
+ const at = new Date(
835
+ String(stamp?.extractedAt ?? source.updatedAt.toISOString()),
836
+ );
837
+ // Preserve stale evidence for the migration audit, but never quote it as current.
838
+ await commit({
839
+ version: 1,
840
+ owner: this.owner,
841
+ id: source.id,
842
+ kind: 'extraction',
843
+ segmentId: source.id,
844
+ revision: at < source.updatedAt ? '0'.repeat(64) : revision,
845
+ extractorVersion: String(stamp?.extractorVersion ?? 'legacy'),
846
+ at,
847
+ ...(stamp?.model ? { model: String(stamp.model) } : {}),
848
+ ...(stamp?.error ? { error: String(stamp.error) } : {}),
849
+ observations: derived,
850
+ proposals: [],
851
+ ...(stamp ? { legacyStamp: stamp } : {}),
852
+ });
853
+ }
854
+ }
855
+ for (const row of snapshot.proposals) {
856
+ const proposal = ProposalSchema.parse(row);
857
+ if (proposal.userId !== this.owner) throw invalid();
858
+ const observation = observations.find(
859
+ (o) => o.id === proposal.observationId,
860
+ );
861
+ const segment = segments.find((s) => s.id === observation?.segmentId);
862
+ const day = days.find((d) => d.id === segment?.dayId);
863
+ const evidence =
864
+ observation && segment && day
865
+ ? {
866
+ segmentId: segment.id,
867
+ localDate: day.localDate,
868
+ capturedAt: segment.capturedAt,
869
+ quote: (
870
+ segment.correctedTranscript ?? segment.transcript
871
+ ).slice(observation.startOffset, observation.endOffset),
872
+ }
873
+ : null;
874
+ await commit({
875
+ version: 1,
876
+ owner: this.owner,
877
+ id: proposal.id,
878
+ kind: 'legacy-proposal',
879
+ segmentId: segment?.id ?? null,
880
+ proposal: { ...proposal, evidence },
881
+ });
882
+ }
883
+ const receipts: { path: string; hash: string; segmentId?: string }[] = [];
884
+ for (const path of [...paths].sort()) {
885
+ const record = this.records.get(path)!.record;
886
+ const segmentId =
887
+ record.kind === 'capture'
888
+ ? record.id
889
+ : 'segmentId' in record
890
+ ? record.segmentId
891
+ : null;
892
+ receipts.push({
893
+ path,
894
+ hash: await this.files.hash(await this.files.read(path)),
895
+ ...(segmentId ? { segmentId } : {}),
896
+ });
897
+ }
898
+ await this.reindex();
899
+ this.publish({});
900
+ return {
901
+ files: receipts,
902
+ vaultDigest: await this.files.hash(JSON.stringify(receipts)),
903
+ };
904
+ });
905
+ }
906
+ activate(
907
+ migrationId: string,
908
+ sourceDigest: string,
909
+ vaultDigest: string,
910
+ files: { path: string; hash: string; segmentId?: string }[] = [],
911
+ ) {
912
+ return this.run(async () => {
913
+ await this.commit({
914
+ version: 1,
915
+ owner: this.owner,
916
+ id: migrationId,
917
+ kind: 'activation',
918
+ sourceDigest,
919
+ vaultDigest,
920
+ files,
921
+ });
922
+ this.publish({});
923
+ });
924
+ }
925
+ activation() {
926
+ return [...this.records.values()]
927
+ .map((r) => r.record)
928
+ .find((r) => r.kind === 'activation');
929
+ }
930
+ async verifyMigration(requireUploaded = false) {
931
+ await this.refresh();
932
+ const activation = this.activation();
933
+ if (
934
+ activation?.kind !== 'activation' ||
935
+ (await this.files.hash(JSON.stringify(activation.files))) !==
936
+ activation.vaultDigest
937
+ )
938
+ throw new JournalVaultError(
939
+ 'invalid',
940
+ 'The migration receipt could not be verified. Server originals have been preserved.',
941
+ );
942
+ const inventory = new Map(
943
+ (await this.files.list()).map((file) => [file.path, file]),
944
+ );
945
+ const deleted = this.tombstones();
946
+ const requireUpload = (path: string) => {
947
+ if (requireUploaded && inventory.get(path)?.uploaded !== true)
948
+ throw new JournalVaultError(
949
+ 'unavailable',
950
+ 'Wait until iCloud has uploaded all migrated Journal files before removing the server copy.',
951
+ );
952
+ };
953
+ for (const file of activation.files) {
954
+ if (!file.path.startsWith(this.root)) throw invalid();
955
+ if (file.segmentId && deleted.has(file.segmentId)) {
956
+ requireUpload(`${this.root}deletions/${file.segmentId}.md`);
957
+ continue;
958
+ }
959
+ if (
960
+ (await this.files.hash(await this.files.read(file.path))) !== file.hash
961
+ )
962
+ throw new JournalVaultError(
963
+ 'changed',
964
+ 'A migrated file changed outside Journal. Server originals have been preserved.',
965
+ );
966
+ requireUpload(file.path);
967
+ }
968
+ requireUpload(this.path(activation));
969
+ return {
970
+ migrationId: activation.id,
971
+ vaultDigest: activation.vaultDigest,
972
+ files: activation.files.length,
973
+ };
974
+ }
975
+ async unextracted(version: string, limit = 25) {
976
+ await this.refresh();
977
+ const extracted = new Set(
978
+ [...this.records.values()].flatMap(({ record: r }) =>
979
+ r.kind === 'extraction' && r.extractorVersion === version
980
+ ? [r.segmentId + r.revision]
981
+ : [],
982
+ ),
983
+ );
984
+ return this.segments()
985
+ .filter(
986
+ (s) => !s.conflicts.length && !extracted.has(s.id + s.revisions[0]),
987
+ )
988
+ .slice(0, limit);
989
+ }
990
+ writeExtraction(input: {
991
+ segmentId: string;
992
+ revision: string;
993
+ extractorVersion: string;
994
+ model?: string;
995
+ error?: string;
996
+ observations: z.infer<typeof JournalObservationSchema>[];
997
+ proposals: z.infer<typeof ProposalWithEvidenceSchema>[];
998
+ }) {
999
+ return this.run(async () => {
1000
+ await this.reconcile();
1001
+ const segment = this.segments().find((s) => s.id === input.segmentId);
1002
+ if (
1003
+ !segment ||
1004
+ segment.conflicts.length ||
1005
+ segment.revisions[0] !== input.revision
1006
+ )
1007
+ throw new JournalVaultError(
1008
+ 'changed',
1009
+ 'The capture changed during extraction. Results were not applied.',
1010
+ );
1011
+ const words = segment.correctedTranscript ?? segment.transcript;
1012
+ if (
1013
+ input.observations.some(
1014
+ (o) =>
1015
+ o.userId !== this.owner ||
1016
+ o.segmentId !== segment.id ||
1017
+ o.startOffset < 0 ||
1018
+ o.endOffset > words.length ||
1019
+ o.endOffset <= o.startOffset,
1020
+ )
1021
+ )
1022
+ throw invalid();
1023
+ if (
1024
+ input.proposals.some(
1025
+ (p) =>
1026
+ p.userId !== this.owner ||
1027
+ p.evidence?.segmentId !== segment.id ||
1028
+ !input.observations.some((o) => o.id === p.observationId),
1029
+ )
1030
+ )
1031
+ throw invalid();
1032
+ // One completed result per revision/version, including empty/error results.
1033
+ if (
1034
+ [...this.records.values()].some(
1035
+ ({ record: r }) =>
1036
+ r.kind === 'extraction' &&
1037
+ r.segmentId === segment.id &&
1038
+ r.revision === input.revision &&
1039
+ r.extractorVersion === input.extractorVersion,
1040
+ )
1041
+ )
1042
+ return;
1043
+ await this.commit({
1044
+ ...input,
1045
+ version: 1,
1046
+ owner: this.owner,
1047
+ id: this.files.uuid(),
1048
+ kind: 'extraction',
1049
+ at: new Date(),
1050
+ });
1051
+ this.publish({});
1052
+ });
1053
+ }
1054
+ private proposalSnapshot() {
1055
+ const all = [...this.records.values()].map((r) => r.record);
1056
+ const segments = this.segments();
1057
+ const candidates = all.flatMap((r) =>
1058
+ r.kind === 'legacy-proposal'
1059
+ ? [r.proposal]
1060
+ : r.kind === 'extraction' &&
1061
+ segments.some(
1062
+ (s) =>
1063
+ s.id === r.segmentId &&
1064
+ s.revisions.length === 1 &&
1065
+ s.revisions[0] === r.revision,
1066
+ )
1067
+ ? r.proposals
1068
+ : [],
1069
+ );
1070
+ return candidates
1071
+ .filter(
1072
+ (p) =>
1073
+ !p.evidence ||
1074
+ (!this.tombstones().has(p.evidence.segmentId) &&
1075
+ (p.status !== 'pending' ||
1076
+ segments.some(
1077
+ (s) =>
1078
+ s.id === p.evidence!.segmentId &&
1079
+ s.observations.some((o) => o.id === p.observationId),
1080
+ ))),
1081
+ )
1082
+ .map((p) => {
1083
+ const decisions = all
1084
+ .filter((r) => r.kind === 'decision' && r.proposalId === p.id)
1085
+ .sort((a, b) => b.id.localeCompare(a.id));
1086
+ const decision =
1087
+ decisions.find(
1088
+ (r) => r.kind === 'decision' && r.status === 'accepted',
1089
+ ) ?? decisions[0];
1090
+ if (decision?.kind !== 'decision') return p;
1091
+ return {
1092
+ ...p,
1093
+ status:
1094
+ decision.status === 'accepting'
1095
+ ? ('pending' as const)
1096
+ : decision.status,
1097
+ payload: decision.payload,
1098
+ resultId: decision.resultId,
1099
+ rejectionReason: decision.reason,
1100
+ decidedAt: decision.at,
1101
+ };
1102
+ })
1103
+ .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
1104
+ }
1105
+ async proposals(status: 'pending' | 'all' = 'pending') {
1106
+ await this.refresh();
1107
+ return this.proposalSnapshot().filter(
1108
+ (p) => status === 'all' || p.status === 'pending',
1109
+ );
1110
+ }
1111
+ decide(
1112
+ input: {
1113
+ id: string;
1114
+ decision: 'accept' | 'reject';
1115
+ payload?: unknown;
1116
+ reason?: string;
1117
+ },
1118
+ publish: (
1119
+ proposalId: string,
1120
+ task: z.infer<typeof TaskProposalPayloadSchema>,
1121
+ ) => Promise<{ id: string }>,
1122
+ validateLink: (target: 'project' | 'task', id: string) => Promise<void>,
1123
+ ) {
1124
+ return this.run(async () => {
1125
+ await this.reconcile();
1126
+ const proposal = this.proposalSnapshot().find((p) => p.id === input.id);
1127
+ if (!proposal)
1128
+ throw new JournalVaultError(
1129
+ 'unavailable',
1130
+ 'The suggestion is no longer available.',
1131
+ );
1132
+ if (proposal.status !== 'pending') return proposal;
1133
+ if (proposal.evidence) {
1134
+ const segment = this.segments().find(
1135
+ (s) => s.id === proposal.evidence!.segmentId,
1136
+ );
1137
+ if (
1138
+ !segment ||
1139
+ segment.conflicts.length ||
1140
+ !segment.observations.some((o) => o.id === proposal.observationId)
1141
+ )
1142
+ throw new JournalVaultError(
1143
+ 'changed',
1144
+ 'The source words changed. Wait for the refreshed suggestion.',
1145
+ );
1146
+ }
1147
+ const payload = input.payload ?? proposal.payload;
1148
+ const accepting = [...this.records.values()]
1149
+ .map((r) => r.record)
1150
+ .find(
1151
+ (r) =>
1152
+ r.kind === 'decision' &&
1153
+ r.proposalId === proposal.id &&
1154
+ r.status === 'accepting',
1155
+ );
1156
+ if (accepting?.kind === 'decision') {
1157
+ if (input.decision === 'reject')
1158
+ throw new JournalVaultError(
1159
+ 'changed',
1160
+ 'This task may already have been added. Finish the pending Add to Tasks action before deciding again.',
1161
+ );
1162
+ if (JSON.stringify(accepting.payload) !== JSON.stringify(payload))
1163
+ throw new JournalVaultError(
1164
+ 'changed',
1165
+ 'Finish publishing the original task fields first. You can edit the resulting task afterward.',
1166
+ );
1167
+ }
1168
+ const base = {
1169
+ version: 1 as const,
1170
+ owner: this.owner,
1171
+ kind: 'decision' as const,
1172
+ proposalId: proposal.id,
1173
+ segmentId: proposal.evidence?.segmentId ?? null,
1174
+ at: new Date(),
1175
+ payload,
1176
+ reason: input.reason ?? null,
1177
+ };
1178
+ if (input.decision === 'reject') {
1179
+ await this.commit({
1180
+ ...base,
1181
+ id: this.files.uuid(),
1182
+ status: 'rejected',
1183
+ resultId: null,
1184
+ });
1185
+ } else {
1186
+ let resultId: string;
1187
+ if (proposal.kind === 'task') {
1188
+ const task = TaskProposalPayloadSchema.parse(payload);
1189
+ // Durable intent before the only content publication: selected task fields.
1190
+ await this.commit({
1191
+ ...base,
1192
+ id: this.files.uuid(),
1193
+ status: 'accepting',
1194
+ resultId: proposal.id,
1195
+ });
1196
+ resultId = (await publish(proposal.id, task)).id;
1197
+ } else if (proposal.kind === 'link') {
1198
+ const link = LinkProposalPayloadSchema.parse(payload);
1199
+ await validateLink(link.target, link.targetId);
1200
+ resultId = link.targetId;
1201
+ } else throw invalid();
1202
+ await this.commit({
1203
+ ...base,
1204
+ id: this.files.uuid(),
1205
+ status: 'accepted',
1206
+ resultId,
1207
+ });
1208
+ }
1209
+ this.publish({});
1210
+ return this.proposalSnapshot().find((p) => p.id === input.id)!;
1211
+ });
1212
+ }
1213
+ async search(query: string, limit = 30, offset = 0) {
1214
+ await this.refresh();
1215
+ const index = await this.index?.();
1216
+ if (!index)
1217
+ throw new JournalVaultError(
1218
+ 'unavailable',
1219
+ 'This device has no Journal search index.',
1220
+ );
1221
+ const scope = this.scope;
1222
+ const hits = await index.search(
1223
+ `${scope}:journal:${this.owner}`,
1224
+ 'journal',
1225
+ query,
1226
+ limit,
1227
+ offset,
1228
+ );
1229
+ await this.check(scope);
1230
+ return hits;
1231
+ }
1232
+ }
1233
+
1234
+ export interface JournalLegacySnapshot {
1235
+ days: unknown[];
1236
+ segments: unknown[];
1237
+ observations: unknown[];
1238
+ extractions: Record<string, unknown>[];
1239
+ proposals: unknown[];
1240
+ }