@agimon-ai/doompi-task 0.0.1-alpha.2 → 0.0.1-alpha.21

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 (330) hide show
  1. package/README.md +39 -12
  2. package/dist/adapters/pi/extension.cjs +3 -0
  3. package/dist/adapters/pi/extension.cjs.map +1 -0
  4. package/dist/adapters/pi/extension.d.cts +12 -0
  5. package/dist/adapters/pi/extension.d.cts.map +1 -0
  6. package/dist/adapters/pi/extension.d.mts +12 -0
  7. package/dist/adapters/pi/extension.d.mts.map +1 -0
  8. package/dist/adapters/pi/extension.mjs +3 -0
  9. package/dist/adapters/pi/extension.mjs.map +1 -0
  10. package/dist/adapters/store/paths.cjs +2 -0
  11. package/dist/adapters/store/paths.cjs.map +1 -0
  12. package/dist/adapters/store/paths.d.cts +26 -0
  13. package/dist/adapters/store/paths.d.cts.map +1 -0
  14. package/dist/adapters/store/paths.d.mts +26 -0
  15. package/dist/adapters/store/paths.d.mts.map +1 -0
  16. package/dist/adapters/store/paths.mjs +2 -0
  17. package/dist/adapters/store/paths.mjs.map +1 -0
  18. package/dist/adapters/store/taskStore.cjs +2 -0
  19. package/dist/adapters/store/taskStore.cjs.map +1 -0
  20. package/dist/adapters/store/taskStore.d.cts +87 -0
  21. package/dist/adapters/store/taskStore.d.cts.map +1 -0
  22. package/dist/adapters/store/taskStore.d.mts +87 -0
  23. package/dist/adapters/store/taskStore.d.mts.map +1 -0
  24. package/dist/adapters/store/taskStore.mjs +2 -0
  25. package/dist/adapters/store/taskStore.mjs.map +1 -0
  26. package/dist/adapters/telemetry/logSinkTelemetry.cjs +2 -0
  27. package/dist/adapters/telemetry/logSinkTelemetry.cjs.map +1 -0
  28. package/dist/adapters/telemetry/logSinkTelemetry.d.cts +52 -0
  29. package/dist/adapters/telemetry/logSinkTelemetry.d.cts.map +1 -0
  30. package/dist/adapters/telemetry/logSinkTelemetry.d.mts +52 -0
  31. package/dist/adapters/telemetry/logSinkTelemetry.d.mts.map +1 -0
  32. package/dist/adapters/telemetry/logSinkTelemetry.mjs +2 -0
  33. package/dist/adapters/telemetry/logSinkTelemetry.mjs.map +1 -0
  34. package/dist/commands/index.cjs +2 -0
  35. package/dist/commands/index.cjs.map +1 -0
  36. package/dist/commands/index.d.cts +15 -0
  37. package/dist/commands/index.d.cts.map +1 -0
  38. package/dist/commands/index.d.mts +15 -0
  39. package/dist/commands/index.d.mts.map +1 -0
  40. package/dist/commands/index.mjs +2 -0
  41. package/dist/commands/index.mjs.map +1 -0
  42. package/dist/commands/task/promptGuidelines.cjs +2 -0
  43. package/dist/commands/task/promptGuidelines.cjs.map +1 -0
  44. package/dist/commands/task/promptGuidelines.d.cts +5 -0
  45. package/dist/commands/task/promptGuidelines.d.cts.map +1 -0
  46. package/dist/commands/task/promptGuidelines.d.mts +5 -0
  47. package/dist/commands/task/promptGuidelines.d.mts.map +1 -0
  48. package/dist/commands/task/promptGuidelines.mjs +2 -0
  49. package/dist/commands/task/promptGuidelines.mjs.map +1 -0
  50. package/dist/commands/task/responseEnvelope.cjs +7 -0
  51. package/dist/commands/task/responseEnvelope.cjs.map +1 -0
  52. package/dist/commands/task/responseEnvelope.d.cts +51 -0
  53. package/dist/commands/task/responseEnvelope.d.cts.map +1 -0
  54. package/dist/commands/task/responseEnvelope.d.mts +51 -0
  55. package/dist/commands/task/responseEnvelope.d.mts.map +1 -0
  56. package/dist/commands/task/responseEnvelope.mjs +7 -0
  57. package/dist/commands/task/responseEnvelope.mjs.map +1 -0
  58. package/dist/commands/task/taskTool.cjs +3 -0
  59. package/dist/commands/task/taskTool.cjs.map +1 -0
  60. package/dist/commands/task/taskTool.d.cts +19 -0
  61. package/dist/commands/task/taskTool.d.cts.map +1 -0
  62. package/dist/commands/task/taskTool.d.mts +19 -0
  63. package/dist/commands/task/taskTool.d.mts.map +1 -0
  64. package/dist/commands/task/taskTool.mjs +3 -0
  65. package/dist/commands/task/taskTool.mjs.map +1 -0
  66. package/dist/commands.cjs +1 -2
  67. package/dist/commands.d.cts +2 -14
  68. package/dist/commands.d.mts +2 -14
  69. package/dist/commands.mjs +1 -2
  70. package/dist/config.cjs +1 -2
  71. package/dist/config.d.cts +2 -38
  72. package/dist/config.d.mts +2 -38
  73. package/dist/config.mjs +1 -2
  74. package/dist/delegation/manager.cjs +1 -6
  75. package/dist/delegation/manager.d.cts +2 -189
  76. package/dist/delegation/manager.d.mts +2 -189
  77. package/dist/delegation/manager.mjs +1 -6
  78. package/dist/extension.cjs +1 -3
  79. package/dist/extension.d.cts +2 -12
  80. package/dist/extension.d.mts +2 -12
  81. package/dist/extension.mjs +1 -3
  82. package/dist/extensions/doom.cjs +1 -1
  83. package/dist/extensions/doom.cjs.map +1 -1
  84. package/dist/extensions/doom.mjs +1 -1
  85. package/dist/extensions/doom.mjs.map +1 -1
  86. package/dist/extensions/pi.cjs +1 -1
  87. package/dist/extensions/pi.cjs.map +1 -1
  88. package/dist/extensions/pi.d.cts +1 -1
  89. package/dist/extensions/pi.d.mts +1 -1
  90. package/dist/extensions/pi.mjs +1 -1
  91. package/dist/extensions/pi.mjs.map +1 -1
  92. package/dist/index.cjs +1 -1
  93. package/dist/index.d.cts +15 -14
  94. package/dist/index.d.mts +15 -14
  95. package/dist/index.mjs +1 -1
  96. package/dist/logSinkTelemetry.cjs +1 -2
  97. package/dist/logSinkTelemetry.d.cts +2 -51
  98. package/dist/logSinkTelemetry.d.mts +2 -51
  99. package/dist/logSinkTelemetry.mjs +1 -2
  100. package/dist/schemas/task.cjs +2 -0
  101. package/dist/schemas/task.cjs.map +1 -0
  102. package/dist/schemas/task.d.cts +103 -0
  103. package/dist/schemas/task.d.cts.map +1 -0
  104. package/dist/schemas/task.d.mts +103 -0
  105. package/dist/schemas/task.d.mts.map +1 -0
  106. package/dist/schemas/task.mjs +2 -0
  107. package/dist/schemas/task.mjs.map +1 -0
  108. package/dist/services/delegation/manager.cjs +6 -0
  109. package/dist/services/delegation/manager.cjs.map +1 -0
  110. package/dist/services/delegation/manager.d.cts +188 -0
  111. package/dist/services/delegation/manager.d.cts.map +1 -0
  112. package/dist/services/delegation/manager.d.mts +188 -0
  113. package/dist/services/delegation/manager.d.mts.map +1 -0
  114. package/dist/services/delegation/manager.mjs +6 -0
  115. package/dist/services/delegation/manager.mjs.map +1 -0
  116. package/dist/services/narration/taskNarration.cjs +2 -0
  117. package/dist/services/narration/taskNarration.cjs.map +1 -0
  118. package/dist/services/narration/taskNarration.mjs +2 -0
  119. package/dist/services/narration/taskNarration.mjs.map +1 -0
  120. package/dist/services/store/invariants.cjs +2 -0
  121. package/dist/services/store/invariants.cjs.map +1 -0
  122. package/dist/services/store/invariants.d.cts +14 -0
  123. package/dist/services/store/invariants.d.cts.map +1 -0
  124. package/dist/services/store/invariants.d.mts +14 -0
  125. package/dist/services/store/invariants.d.mts.map +1 -0
  126. package/dist/services/store/invariants.mjs +2 -0
  127. package/dist/services/store/invariants.mjs.map +1 -0
  128. package/dist/services/store/paths.cjs +1 -0
  129. package/dist/services/store/paths.mjs +1 -0
  130. package/dist/services/store/processLiveness.cjs +2 -0
  131. package/dist/services/store/processLiveness.cjs.map +1 -0
  132. package/dist/services/store/processLiveness.d.cts +12 -0
  133. package/dist/services/store/processLiveness.d.cts.map +1 -0
  134. package/dist/services/store/processLiveness.d.mts +12 -0
  135. package/dist/services/store/processLiveness.d.mts.map +1 -0
  136. package/dist/services/store/processLiveness.mjs +2 -0
  137. package/dist/services/store/processLiveness.mjs.map +1 -0
  138. package/dist/services/store/reconcile.cjs +2 -0
  139. package/dist/services/store/reconcile.cjs.map +1 -0
  140. package/dist/services/store/reconcile.d.cts +34 -0
  141. package/dist/services/store/reconcile.d.cts.map +1 -0
  142. package/dist/services/store/reconcile.d.mts +34 -0
  143. package/dist/services/store/reconcile.d.mts.map +1 -0
  144. package/dist/services/store/reconcile.mjs +2 -0
  145. package/dist/services/store/reconcile.mjs.map +1 -0
  146. package/dist/services/store/reducer.cjs +3 -0
  147. package/dist/services/store/reducer.cjs.map +1 -0
  148. package/dist/services/store/reducer.d.cts +72 -0
  149. package/dist/services/store/reducer.d.cts.map +1 -0
  150. package/dist/services/store/reducer.d.mts +72 -0
  151. package/dist/services/store/reducer.d.mts.map +1 -0
  152. package/dist/services/store/reducer.mjs +3 -0
  153. package/dist/services/store/reducer.mjs.map +1 -0
  154. package/dist/services/store/taskGraph.cjs +2 -0
  155. package/dist/services/store/taskGraph.cjs.map +1 -0
  156. package/dist/services/store/taskGraph.d.cts +25 -0
  157. package/dist/services/store/taskGraph.d.cts.map +1 -0
  158. package/dist/services/store/taskGraph.d.mts +25 -0
  159. package/dist/services/store/taskGraph.d.mts.map +1 -0
  160. package/dist/services/store/taskGraph.mjs +2 -0
  161. package/dist/services/store/taskGraph.mjs.map +1 -0
  162. package/dist/services/store/taskStore.cjs +1 -0
  163. package/dist/services/store/taskStore.d.cts +2 -0
  164. package/dist/services/store/taskStore.d.mts +2 -0
  165. package/dist/services/store/taskStore.mjs +1 -0
  166. package/dist/services/store/types.cjs +2 -0
  167. package/dist/services/store/types.cjs.map +1 -0
  168. package/dist/services/store/types.d.cts +177 -0
  169. package/dist/services/store/types.d.cts.map +1 -0
  170. package/dist/services/store/types.d.mts +177 -0
  171. package/dist/services/store/types.d.mts.map +1 -0
  172. package/dist/services/store/types.mjs +2 -0
  173. package/dist/services/store/types.mjs.map +1 -0
  174. package/dist/store/invariants.cjs +1 -2
  175. package/dist/store/invariants.d.cts +2 -14
  176. package/dist/store/invariants.d.mts +2 -14
  177. package/dist/store/invariants.mjs +1 -2
  178. package/dist/store/paths.cjs +1 -2
  179. package/dist/store/paths.d.cts +2 -23
  180. package/dist/store/paths.d.mts +2 -23
  181. package/dist/store/paths.mjs +1 -2
  182. package/dist/store/processLiveness.cjs +1 -2
  183. package/dist/store/processLiveness.d.cts +2 -12
  184. package/dist/store/processLiveness.d.mts +2 -12
  185. package/dist/store/processLiveness.mjs +1 -2
  186. package/dist/store/reconcile.cjs +1 -2
  187. package/dist/store/reconcile.d.cts +2 -34
  188. package/dist/store/reconcile.d.mts +2 -34
  189. package/dist/store/reconcile.mjs +1 -2
  190. package/dist/store/reducer.cjs +1 -3
  191. package/dist/store/reducer.d.cts +2 -72
  192. package/dist/store/reducer.d.mts +2 -72
  193. package/dist/store/reducer.mjs +1 -3
  194. package/dist/store/taskGraph.cjs +1 -2
  195. package/dist/store/taskGraph.d.cts +2 -25
  196. package/dist/store/taskGraph.d.mts +2 -25
  197. package/dist/store/taskGraph.mjs +1 -2
  198. package/dist/store/taskStore.cjs +1 -2
  199. package/dist/store/taskStore.d.cts +3 -77
  200. package/dist/store/taskStore.d.mts +3 -77
  201. package/dist/store/taskStore.mjs +1 -2
  202. package/dist/store/types.cjs +1 -2
  203. package/dist/store/types.d.cts +2 -165
  204. package/dist/store/types.d.mts +2 -165
  205. package/dist/store/types.mjs +1 -2
  206. package/dist/tool/promptGuidelines.cjs +1 -2
  207. package/dist/tool/promptGuidelines.d.cts +2 -5
  208. package/dist/tool/promptGuidelines.d.mts +2 -5
  209. package/dist/tool/promptGuidelines.mjs +1 -2
  210. package/dist/tool/responseEnvelope.cjs +1 -6
  211. package/dist/tool/responseEnvelope.d.cts +2 -39
  212. package/dist/tool/responseEnvelope.d.mts +2 -39
  213. package/dist/tool/responseEnvelope.mjs +1 -6
  214. package/dist/tool/schema.cjs +1 -2
  215. package/dist/tool/schema.d.cts +2 -86
  216. package/dist/tool/schema.d.mts +2 -86
  217. package/dist/tool/schema.mjs +1 -2
  218. package/dist/tool/taskTool.cjs +1 -3
  219. package/dist/tool/taskTool.d.cts +3 -17
  220. package/dist/tool/taskTool.d.mts +3 -17
  221. package/dist/tool/taskTool.mjs +1 -3
  222. package/dist/tui/format.cjs +3 -3
  223. package/dist/tui/format.cjs.map +1 -1
  224. package/dist/tui/format.d.cts +5 -5
  225. package/dist/tui/format.d.cts.map +1 -1
  226. package/dist/tui/format.d.mts +5 -5
  227. package/dist/tui/format.d.mts.map +1 -1
  228. package/dist/tui/format.mjs +3 -3
  229. package/dist/tui/format.mjs.map +1 -1
  230. package/dist/tui/selectors.cjs +1 -1
  231. package/dist/tui/selectors.cjs.map +1 -1
  232. package/dist/tui/selectors.d.cts +8 -1
  233. package/dist/tui/selectors.d.cts.map +1 -1
  234. package/dist/tui/selectors.d.mts +8 -1
  235. package/dist/tui/selectors.d.mts.map +1 -1
  236. package/dist/tui/selectors.mjs +1 -1
  237. package/dist/tui/selectors.mjs.map +1 -1
  238. package/dist/tui/taskOverlay.cjs +1 -1
  239. package/dist/tui/taskOverlay.cjs.map +1 -1
  240. package/dist/tui/taskOverlay.d.cts +2 -2
  241. package/dist/tui/taskOverlay.d.cts.map +1 -1
  242. package/dist/tui/taskOverlay.d.mts +2 -2
  243. package/dist/tui/taskOverlay.d.mts.map +1 -1
  244. package/dist/tui/taskOverlay.mjs +1 -1
  245. package/dist/tui/taskOverlay.mjs.map +1 -1
  246. package/dist/tui/taskSpace.cjs +3 -3
  247. package/dist/tui/taskSpace.cjs.map +1 -1
  248. package/dist/tui/taskSpace.d.cts +2 -1
  249. package/dist/tui/taskSpace.d.cts.map +1 -1
  250. package/dist/tui/taskSpace.d.mts +2 -1
  251. package/dist/tui/taskSpace.d.mts.map +1 -1
  252. package/dist/tui/taskSpace.mjs +3 -3
  253. package/dist/tui/taskSpace.mjs.map +1 -1
  254. package/dist/types/config.cjs +2 -0
  255. package/dist/types/config.cjs.map +1 -0
  256. package/dist/types/config.d.cts +43 -0
  257. package/dist/types/config.d.cts.map +1 -0
  258. package/dist/types/config.d.mts +43 -0
  259. package/dist/types/config.d.mts.map +1 -0
  260. package/dist/types/config.mjs +2 -0
  261. package/dist/types/config.mjs.map +1 -0
  262. package/package.json +16 -9
  263. package/dist/commands.cjs.map +0 -1
  264. package/dist/commands.d.cts.map +0 -1
  265. package/dist/commands.d.mts.map +0 -1
  266. package/dist/commands.mjs.map +0 -1
  267. package/dist/config.cjs.map +0 -1
  268. package/dist/config.d.cts.map +0 -1
  269. package/dist/config.d.mts.map +0 -1
  270. package/dist/config.mjs.map +0 -1
  271. package/dist/delegation/manager.cjs.map +0 -1
  272. package/dist/delegation/manager.d.cts.map +0 -1
  273. package/dist/delegation/manager.d.mts.map +0 -1
  274. package/dist/delegation/manager.mjs.map +0 -1
  275. package/dist/extension.cjs.map +0 -1
  276. package/dist/extension.d.cts.map +0 -1
  277. package/dist/extension.d.mts.map +0 -1
  278. package/dist/extension.mjs.map +0 -1
  279. package/dist/logSinkTelemetry.cjs.map +0 -1
  280. package/dist/logSinkTelemetry.d.cts.map +0 -1
  281. package/dist/logSinkTelemetry.d.mts.map +0 -1
  282. package/dist/logSinkTelemetry.mjs.map +0 -1
  283. package/dist/store/invariants.cjs.map +0 -1
  284. package/dist/store/invariants.d.cts.map +0 -1
  285. package/dist/store/invariants.d.mts.map +0 -1
  286. package/dist/store/invariants.mjs.map +0 -1
  287. package/dist/store/paths.cjs.map +0 -1
  288. package/dist/store/paths.d.cts.map +0 -1
  289. package/dist/store/paths.d.mts.map +0 -1
  290. package/dist/store/paths.mjs.map +0 -1
  291. package/dist/store/processLiveness.cjs.map +0 -1
  292. package/dist/store/processLiveness.d.cts.map +0 -1
  293. package/dist/store/processLiveness.d.mts.map +0 -1
  294. package/dist/store/processLiveness.mjs.map +0 -1
  295. package/dist/store/reconcile.cjs.map +0 -1
  296. package/dist/store/reconcile.d.cts.map +0 -1
  297. package/dist/store/reconcile.d.mts.map +0 -1
  298. package/dist/store/reconcile.mjs.map +0 -1
  299. package/dist/store/reducer.cjs.map +0 -1
  300. package/dist/store/reducer.d.cts.map +0 -1
  301. package/dist/store/reducer.d.mts.map +0 -1
  302. package/dist/store/reducer.mjs.map +0 -1
  303. package/dist/store/taskGraph.cjs.map +0 -1
  304. package/dist/store/taskGraph.d.cts.map +0 -1
  305. package/dist/store/taskGraph.d.mts.map +0 -1
  306. package/dist/store/taskGraph.mjs.map +0 -1
  307. package/dist/store/taskStore.cjs.map +0 -1
  308. package/dist/store/taskStore.d.cts.map +0 -1
  309. package/dist/store/taskStore.d.mts.map +0 -1
  310. package/dist/store/taskStore.mjs.map +0 -1
  311. package/dist/store/types.cjs.map +0 -1
  312. package/dist/store/types.d.cts.map +0 -1
  313. package/dist/store/types.d.mts.map +0 -1
  314. package/dist/store/types.mjs.map +0 -1
  315. package/dist/tool/promptGuidelines.cjs.map +0 -1
  316. package/dist/tool/promptGuidelines.d.cts.map +0 -1
  317. package/dist/tool/promptGuidelines.d.mts.map +0 -1
  318. package/dist/tool/promptGuidelines.mjs.map +0 -1
  319. package/dist/tool/responseEnvelope.cjs.map +0 -1
  320. package/dist/tool/responseEnvelope.d.cts.map +0 -1
  321. package/dist/tool/responseEnvelope.d.mts.map +0 -1
  322. package/dist/tool/responseEnvelope.mjs.map +0 -1
  323. package/dist/tool/schema.cjs.map +0 -1
  324. package/dist/tool/schema.d.cts.map +0 -1
  325. package/dist/tool/schema.d.mts.map +0 -1
  326. package/dist/tool/schema.mjs.map +0 -1
  327. package/dist/tool/taskTool.cjs.map +0 -1
  328. package/dist/tool/taskTool.d.cts.map +0 -1
  329. package/dist/tool/taskTool.d.mts.map +0 -1
  330. package/dist/tool/taskTool.mjs.map +0 -1
@@ -0,0 +1,12 @@
1
+ //#region src/services/store/processLiveness.d.ts
2
+ /**
3
+ * Is a process still running?
4
+ *
5
+ * Signal 0 performs the permission and existence check without delivering a
6
+ * signal. EPERM means the process exists but belongs to another user, which
7
+ * still counts as alive.
8
+ */
9
+ declare function isProcessAlive(pid: number): boolean;
10
+ //#endregion
11
+ export { isProcessAlive };
12
+ //# sourceMappingURL=processLiveness.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"processLiveness.d.cts","names":[],"sources":["../../../src/services/store/processLiveness.ts"],"mappings":";;;;;;;;iBAOgB,eAAe"}
@@ -0,0 +1,12 @@
1
+ //#region src/services/store/processLiveness.d.ts
2
+ /**
3
+ * Is a process still running?
4
+ *
5
+ * Signal 0 performs the permission and existence check without delivering a
6
+ * signal. EPERM means the process exists but belongs to another user, which
7
+ * still counts as alive.
8
+ */
9
+ declare function isProcessAlive(pid: number): boolean;
10
+ //#endregion
11
+ export { isProcessAlive };
12
+ //# sourceMappingURL=processLiveness.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"processLiveness.d.mts","names":[],"sources":["../../../src/services/store/processLiveness.ts"],"mappings":";;;;;;;;iBAOgB,eAAe"}
@@ -0,0 +1,2 @@
1
+ function e(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}export{e as isProcessAlive};
2
+ //# sourceMappingURL=processLiveness.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"processLiveness.mjs","names":[],"sources":["../../../src/services/store/processLiveness.ts"],"sourcesContent":["/**\n * Is a process still running?\n *\n * Signal 0 performs the permission and existence check without delivering a\n * signal. EPERM means the process exists but belongs to another user, which\n * still counts as alive.\n */\nexport function isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === 'EPERM';\n }\n}\n"],"mappings":"AAOA,SAAgB,EAAe,EAAsB,CACnD,GAAI,CAEF,OADA,QAAQ,KAAK,EAAK,CAAC,EACZ,EACT,OAAS,EAAO,CACd,OAAQ,EAAgC,OAAS,OACnD,CACF"}
@@ -0,0 +1,2 @@
1
+ const e=require("./processLiveness.cjs"),t=require("./types.cjs"),n=`Delegation orphaned by harness restart`,r=`Delegation orphaned by session restart`;function i(i,a=new Date().toISOString(),o=e.isProcessAlive,s){let c=[],l=i.tasks.map(e=>{if(!t.isDelegationActive(e))return e;let i=e.delegation?.pid;if(i===void 0)return e;let l=s!==void 0&&i===s.pid&&!s.liveRequestIds.has(e.delegation.requestId);if(!l&&o(i))return e;let u={...e,status:`pending`,updatedAt:a,delegation:{...e.delegation,state:`failed`,endedAt:a,result:{status:`failed`,error:l?r:n}}};return c.push(u),u});return c.length===0?{document:i,orphaned:c}:{document:{...i,tasks:l},orphaned:c}}exports.ERR_ORPHANED_BY_RESTART=n,exports.ERR_ORPHANED_BY_SESSION=r,exports.reconcileOrphanedDelegations=i;
2
+ //# sourceMappingURL=reconcile.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reconcile.cjs","names":["isProcessAlive","isDelegationActive"],"sources":["../../../src/services/store/reconcile.ts"],"sourcesContent":["import { isProcessAlive } from './processLiveness.ts';\nimport { isDelegationActive, type Task, type TaskDocument } from './types.ts';\n\nexport const ERR_ORPHANED_BY_RESTART = 'Delegation orphaned by harness restart';\nexport const ERR_ORPHANED_BY_SESSION = 'Delegation orphaned by session restart';\n\nexport interface ReconcileResult {\n document: TaskDocument;\n orphaned: Task[];\n}\n\n/** The delegations this process can still settle, used to spot its own leftovers. */\nexport interface ReconcileSelf {\n pid: number;\n liveRequestIds: ReadonlySet<string>;\n}\n\n/**\n * Recover tasks that no longer have anyone able to finish them.\n *\n * A subagent run dies with the harness that spawned it, but the store file\n * outlives both, so a crash leaves tasks stuck in `in_progress` forever. Two\n * kinds of delegation qualify as dead:\n *\n * - the owning pid is gone, so nothing is left to report a result;\n * - the owning pid is *this* process, yet the request is absent from the live\n * set. Settling requires an in-memory record, so an in-process session\n * restart (which clears that map without writing to the store) leaves rows\n * nothing can ever resolve. Checking pid liveness alone misses these, because\n * the pid is our own and very much alive.\n *\n * Delegations owned by a different, still-running pid belong to a parallel\n * session and are left untouched.\n */\nexport function reconcileOrphanedDelegations(\n document: TaskDocument,\n now: string = new Date().toISOString(),\n isAlive: (pid: number) => boolean = isProcessAlive,\n self?: ReconcileSelf,\n): ReconcileResult {\n const orphaned: Task[] = [];\n\n const tasks = document.tasks.map((task) => {\n if (!isDelegationActive(task)) return task;\n const pid = task.delegation?.pid;\n if (pid === undefined) return task;\n\n const ownedByThisSession = self !== undefined && pid === self.pid;\n const abandonedHere = ownedByThisSession && !self.liveRequestIds.has(task.delegation!.requestId);\n if (!abandonedHere && isAlive(pid)) return task;\n\n const recovered: Task = {\n ...task,\n status: 'pending',\n updatedAt: now,\n delegation: {\n ...task.delegation!,\n state: 'failed',\n endedAt: now,\n result: {\n status: 'failed',\n error: abandonedHere ? ERR_ORPHANED_BY_SESSION : ERR_ORPHANED_BY_RESTART,\n },\n },\n };\n orphaned.push(recovered);\n return recovered;\n });\n\n if (orphaned.length === 0) return { document, orphaned };\n return { document: { ...document, tasks }, orphaned };\n}\n"],"mappings":"kEAGa,EAA0B,yCAC1B,EAA0B,yCA8BvC,SAAgB,EACd,EACA,EAAc,IAAI,KAAK,CAAA,CAAE,YAAY,EACrC,EAAoCA,EAAAA,eACpC,EACiB,CACjB,IAAM,EAAmB,CAAC,EAEpB,EAAQ,EAAS,MAAM,IAAK,GAAS,CACzC,GAAI,CAACC,EAAAA,mBAAmB,CAAI,EAAG,OAAO,EACtC,IAAM,EAAM,EAAK,YAAY,IAC7B,GAAI,IAAQ,IAAA,GAAW,OAAO,EAG9B,IAAM,EADqB,IAAS,IAAA,IAAa,IAAQ,EAAK,KAClB,CAAC,EAAK,eAAe,IAAI,EAAK,WAAY,SAAS,EAC/F,GAAI,CAAC,GAAiB,EAAQ,CAAG,EAAG,OAAO,EAE3C,IAAM,EAAkB,CACtB,GAAG,EACH,OAAQ,UACR,UAAW,EACX,WAAY,CACV,GAAG,EAAK,WACR,MAAO,SACP,QAAS,EACT,OAAQ,CACN,OAAQ,SACR,MAAO,EAAgB,EAA0B,CACnD,CACF,CACF,EAEA,OADA,EAAS,KAAK,CAAS,EAChB,CACT,CAAC,EAGD,OADI,EAAS,SAAW,EAAU,CAAE,WAAU,UAAS,EAChD,CAAE,SAAU,CAAE,GAAG,EAAU,OAAM,EAAG,UAAS,CACtD"}
@@ -0,0 +1,34 @@
1
+ import { Task, TaskDocument } from "./types.cjs";
2
+ //#region src/services/store/reconcile.d.ts
3
+ declare const ERR_ORPHANED_BY_RESTART = "Delegation orphaned by harness restart";
4
+ declare const ERR_ORPHANED_BY_SESSION = "Delegation orphaned by session restart";
5
+ interface ReconcileResult {
6
+ document: TaskDocument;
7
+ orphaned: Task[];
8
+ }
9
+ /** The delegations this process can still settle, used to spot its own leftovers. */
10
+ interface ReconcileSelf {
11
+ pid: number;
12
+ liveRequestIds: ReadonlySet<string>;
13
+ }
14
+ /**
15
+ * Recover tasks that no longer have anyone able to finish them.
16
+ *
17
+ * A subagent run dies with the harness that spawned it, but the store file
18
+ * outlives both, so a crash leaves tasks stuck in `in_progress` forever. Two
19
+ * kinds of delegation qualify as dead:
20
+ *
21
+ * - the owning pid is gone, so nothing is left to report a result;
22
+ * - the owning pid is *this* process, yet the request is absent from the live
23
+ * set. Settling requires an in-memory record, so an in-process session
24
+ * restart (which clears that map without writing to the store) leaves rows
25
+ * nothing can ever resolve. Checking pid liveness alone misses these, because
26
+ * the pid is our own and very much alive.
27
+ *
28
+ * Delegations owned by a different, still-running pid belong to a parallel
29
+ * session and are left untouched.
30
+ */
31
+ declare function reconcileOrphanedDelegations(document: TaskDocument, now?: string, isAlive?: (pid: number) => boolean, self?: ReconcileSelf): ReconcileResult;
32
+ //#endregion
33
+ export { ERR_ORPHANED_BY_RESTART, ERR_ORPHANED_BY_SESSION, ReconcileResult, ReconcileSelf, reconcileOrphanedDelegations };
34
+ //# sourceMappingURL=reconcile.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reconcile.d.cts","names":[],"sources":["../../../src/services/store/reconcile.ts"],"mappings":";;cAGa;cACA;UAEI;EACf,UAAU;EACV,UAAU;;;UAIK;EACf;EACA,gBAAgB;;;;;;;;;;;;;;;;;;;iBAoBF,6BACd,UAAU,cACV,cACA,WAAU,yBACV,OAAO,gBACN"}
@@ -0,0 +1,34 @@
1
+ import { Task, TaskDocument } from "./types.mjs";
2
+ //#region src/services/store/reconcile.d.ts
3
+ declare const ERR_ORPHANED_BY_RESTART = "Delegation orphaned by harness restart";
4
+ declare const ERR_ORPHANED_BY_SESSION = "Delegation orphaned by session restart";
5
+ interface ReconcileResult {
6
+ document: TaskDocument;
7
+ orphaned: Task[];
8
+ }
9
+ /** The delegations this process can still settle, used to spot its own leftovers. */
10
+ interface ReconcileSelf {
11
+ pid: number;
12
+ liveRequestIds: ReadonlySet<string>;
13
+ }
14
+ /**
15
+ * Recover tasks that no longer have anyone able to finish them.
16
+ *
17
+ * A subagent run dies with the harness that spawned it, but the store file
18
+ * outlives both, so a crash leaves tasks stuck in `in_progress` forever. Two
19
+ * kinds of delegation qualify as dead:
20
+ *
21
+ * - the owning pid is gone, so nothing is left to report a result;
22
+ * - the owning pid is *this* process, yet the request is absent from the live
23
+ * set. Settling requires an in-memory record, so an in-process session
24
+ * restart (which clears that map without writing to the store) leaves rows
25
+ * nothing can ever resolve. Checking pid liveness alone misses these, because
26
+ * the pid is our own and very much alive.
27
+ *
28
+ * Delegations owned by a different, still-running pid belong to a parallel
29
+ * session and are left untouched.
30
+ */
31
+ declare function reconcileOrphanedDelegations(document: TaskDocument, now?: string, isAlive?: (pid: number) => boolean, self?: ReconcileSelf): ReconcileResult;
32
+ //#endregion
33
+ export { ERR_ORPHANED_BY_RESTART, ERR_ORPHANED_BY_SESSION, ReconcileResult, ReconcileSelf, reconcileOrphanedDelegations };
34
+ //# sourceMappingURL=reconcile.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reconcile.d.mts","names":[],"sources":["../../../src/services/store/reconcile.ts"],"mappings":";;cAGa;cACA;UAEI;EACf,UAAU;EACV,UAAU;;;UAIK;EACf;EACA,gBAAgB;;;;;;;;;;;;;;;;;;;iBAoBF,6BACd,UAAU,cACV,cACA,WAAU,yBACV,OAAO,gBACN"}
@@ -0,0 +1,2 @@
1
+ import{isProcessAlive as e}from"./processLiveness.mjs";import{isDelegationActive as t}from"./types.mjs";const n=`Delegation orphaned by harness restart`,r=`Delegation orphaned by session restart`;function i(i,a=new Date().toISOString(),o=e,s){let c=[],l=i.tasks.map(e=>{if(!t(e))return e;let i=e.delegation?.pid;if(i===void 0)return e;let l=s!==void 0&&i===s.pid&&!s.liveRequestIds.has(e.delegation.requestId);if(!l&&o(i))return e;let u={...e,status:`pending`,updatedAt:a,delegation:{...e.delegation,state:`failed`,endedAt:a,result:{status:`failed`,error:l?r:n}}};return c.push(u),u});return c.length===0?{document:i,orphaned:c}:{document:{...i,tasks:l},orphaned:c}}export{n as ERR_ORPHANED_BY_RESTART,r as ERR_ORPHANED_BY_SESSION,i as reconcileOrphanedDelegations};
2
+ //# sourceMappingURL=reconcile.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reconcile.mjs","names":[],"sources":["../../../src/services/store/reconcile.ts"],"sourcesContent":["import { isProcessAlive } from './processLiveness.ts';\nimport { isDelegationActive, type Task, type TaskDocument } from './types.ts';\n\nexport const ERR_ORPHANED_BY_RESTART = 'Delegation orphaned by harness restart';\nexport const ERR_ORPHANED_BY_SESSION = 'Delegation orphaned by session restart';\n\nexport interface ReconcileResult {\n document: TaskDocument;\n orphaned: Task[];\n}\n\n/** The delegations this process can still settle, used to spot its own leftovers. */\nexport interface ReconcileSelf {\n pid: number;\n liveRequestIds: ReadonlySet<string>;\n}\n\n/**\n * Recover tasks that no longer have anyone able to finish them.\n *\n * A subagent run dies with the harness that spawned it, but the store file\n * outlives both, so a crash leaves tasks stuck in `in_progress` forever. Two\n * kinds of delegation qualify as dead:\n *\n * - the owning pid is gone, so nothing is left to report a result;\n * - the owning pid is *this* process, yet the request is absent from the live\n * set. Settling requires an in-memory record, so an in-process session\n * restart (which clears that map without writing to the store) leaves rows\n * nothing can ever resolve. Checking pid liveness alone misses these, because\n * the pid is our own and very much alive.\n *\n * Delegations owned by a different, still-running pid belong to a parallel\n * session and are left untouched.\n */\nexport function reconcileOrphanedDelegations(\n document: TaskDocument,\n now: string = new Date().toISOString(),\n isAlive: (pid: number) => boolean = isProcessAlive,\n self?: ReconcileSelf,\n): ReconcileResult {\n const orphaned: Task[] = [];\n\n const tasks = document.tasks.map((task) => {\n if (!isDelegationActive(task)) return task;\n const pid = task.delegation?.pid;\n if (pid === undefined) return task;\n\n const ownedByThisSession = self !== undefined && pid === self.pid;\n const abandonedHere = ownedByThisSession && !self.liveRequestIds.has(task.delegation!.requestId);\n if (!abandonedHere && isAlive(pid)) return task;\n\n const recovered: Task = {\n ...task,\n status: 'pending',\n updatedAt: now,\n delegation: {\n ...task.delegation!,\n state: 'failed',\n endedAt: now,\n result: {\n status: 'failed',\n error: abandonedHere ? ERR_ORPHANED_BY_SESSION : ERR_ORPHANED_BY_RESTART,\n },\n },\n };\n orphaned.push(recovered);\n return recovered;\n });\n\n if (orphaned.length === 0) return { document, orphaned };\n return { document: { ...document, tasks }, orphaned };\n}\n"],"mappings":"wGAGA,MAAa,EAA0B,yCAC1B,EAA0B,yCA8BvC,SAAgB,EACd,EACA,EAAc,IAAI,KAAK,CAAA,CAAE,YAAY,EACrC,EAAoC,EACpC,EACiB,CACjB,IAAM,EAAmB,CAAC,EAEpB,EAAQ,EAAS,MAAM,IAAK,GAAS,CACzC,GAAI,CAAC,EAAmB,CAAI,EAAG,OAAO,EACtC,IAAM,EAAM,EAAK,YAAY,IAC7B,GAAI,IAAQ,IAAA,GAAW,OAAO,EAG9B,IAAM,EADqB,IAAS,IAAA,IAAa,IAAQ,EAAK,KAClB,CAAC,EAAK,eAAe,IAAI,EAAK,WAAY,SAAS,EAC/F,GAAI,CAAC,GAAiB,EAAQ,CAAG,EAAG,OAAO,EAE3C,IAAM,EAAkB,CACtB,GAAG,EACH,OAAQ,UACR,UAAW,EACX,WAAY,CACV,GAAG,EAAK,WACR,MAAO,SACP,QAAS,EACT,OAAQ,CACN,OAAQ,SACR,MAAO,EAAgB,EAA0B,CACnD,CACF,CACF,EAEA,OADA,EAAS,KAAK,CAAS,EAChB,CACT,CAAC,EAGD,OADI,EAAS,SAAW,EAAU,CAAE,WAAU,UAAS,EAChD,CAAE,SAAU,CAAE,GAAG,EAAU,OAAM,EAAG,UAAS,CACtD"}
@@ -0,0 +1,3 @@
1
+ const e=require("./types.cjs"),t=require("./taskGraph.cjs"),n=require("./invariants.cjs"),r=/^[A-Za-z][A-Za-z0-9_-]{0,31}$/;function i(e){switch(e.kind){case`error`:case`list`:case`get`:return!1;case`upsert`:return e.items.some(e=>e.kind===`created`||e.kind===`updated`);case`delete`:case`clear`:return!0}}function a(e){return e.items.filter(e=>e.kind===`failed`).map(e=>`item[${e.index}]: ${e.message}`).join(`
2
+ `)}function o(e){return e.kind===`upsert`?e.items[0]:void 0}function s(e,t){return{document:e,op:{kind:`error`,message:t}}}function c(e,t){let n=e??[],r=t??[];return n.length===r.length&&n.every((e,t)=>e===r[t])}function l(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function u(e,t){return e.subject!==t.subject||e.status!==t.status||e.description!==t.description||e.activeForm!==t.activeForm||e.owner!==t.owner||!c(e.blockedBy,t.blockedBy)||!l(e.metadata,t.metadata)}function d(e,t,n=e.nextId){return{...e,tasks:t,nextId:n}}function f(e,t){let n={...e};for(let[e,r]of Object.entries(t))r===null?delete n[e]:n[e]=r;return Object.keys(n).length?n:void 0}function p(e,t){if(t.subject!==void 0&&(e.subject=t.subject),t.description!==void 0&&(e.description=t.description),t.activeForm!==void 0&&(e.activeForm=t.activeForm),t.owner!==void 0&&(e.owner=t.owner),t.metadata!==void 0){let n=f(e.metadata,t.metadata);n===void 0?delete e.metadata:e.metadata=n}}function m(e,t,n){if(typeof n==`number`)return{ok:!0,id:n};if(!r.test(n))return{ok:!1,message:`${t}: "${n}" is not a valid ref; pass an existing task id as a number`};let i=e.refIds.get(n);if(i!==void 0)return{ok:!0,id:i};let a=e.failedRefs.get(n);return a===void 0?{ok:!1,message:`${t}: unknown ref "${n}" — a ref must be declared by an earlier entry in the same call`}:{ok:!1,message:`${t}: ref "${n}" refers to item[${a}], which failed`}}function h(e){return{ok:!1,message:e}}function g(e,t){if(t.ref!==void 0){if(t.id!==void 0)return`ref is only valid when creating a task; drop the id, or drop the ref`;if(!r.test(t.ref))return`ref "${t.ref}" is invalid: a ref must start with a letter and contain only letters, digits, - or _`;if(e.refIds.get(t.ref)!==void 0||e.failedRefs.has(t.ref))return`duplicate ref "${t.ref}": it was already declared by an earlier entry`}}function _(e,t,n,r){if(t.subject===void 0)return h(`subject is required when the entry has no id`);if(!t.subject.trim())return h(`subject must not be blank`);if(t.addBlockedBy!==void 0||t.removeBlockedBy!==void 0)return h(`addBlockedBy / removeBlockedBy are only for an entry with an id; a new task uses blockedBy`);if(t.status===`deleted`)return h(`cannot create a task with status deleted; create it, then use action delete`);if(e.tasks.filter(e=>e.status!==`deleted`).length>=e.maxTasks)return h(`task limit of ${e.maxTasks} reached; delete completed tasks first before creating new tasks`);let i=[];for(let n of t.blockedBy??[]){let t=m(e,`blockedBy`,n);if(!t.ok)return h(t.message);let r=e.tasks.find(e=>e.id===t.id);if(!r)return h(`blockedBy: #${t.id} not found`);if(r.status===`deleted`)return h(`blockedBy: #${t.id} is deleted`);i.includes(t.id)||i.push(t.id)}let a={id:e.nextId,subject:t.subject,status:t.status??`pending`,createdAt:r,updatedAt:r};return p(a,t),i.length&&(a.blockedBy=i),e.nextId+=1,e.tasks.push(a),t.ref&&e.refIds.set(t.ref,a.id),{ok:!0,outcome:{index:n,kind:`created`,id:a.id,subject:a.subject,status:a.status,...t.ref?{ref:t.ref}:{},...i.length?{blockedBy:i}:{}}}}function v(e,r,i,a){let o=r.id,s=e.tasks.findIndex(e=>e.id===o);if(s===-1)return h(`#${o} not found`);if(r.blockedBy!==void 0)return h(`blockedBy is only for a new entry; use addBlockedBy / removeBlockedBy on an entry that has an id`);if(!(r.subject!==void 0||r.description!==void 0||r.activeForm!==void 0||r.status!==void 0||r.owner!==void 0||r.metadata!==void 0||r.addBlockedBy?.length||r.removeBlockedBy?.length))return h(`nothing to change: provide at least one of subject, description, activeForm, status, owner, metadata, addBlockedBy, or removeBlockedBy`);let c=e.tasks[s];if(r.subject!==void 0&&!r.subject.trim())return h(`subject must not be blank`);let l=c.status;if(r.status!==void 0){if(!n.isTransitionValid(c.status,r.status))return h(`illegal transition ${c.status} -> ${r.status}`);l=r.status}let d=c.blockedBy?[...c.blockedBy]:[];for(let t of r.removeBlockedBy??[]){let n=m(e,`removeBlockedBy`,t);if(!n.ok)return h(n.message);d=d.filter(e=>e!==n.id)}for(let t of r.addBlockedBy??[]){let n=m(e,`addBlockedBy`,t);if(!n.ok)return h(n.message);if(n.id===o)return h(`cannot block #${o} on itself`);let r=e.tasks.find(e=>e.id===n.id);if(!r)return h(`addBlockedBy: #${n.id} not found`);if(r.status===`deleted`)return h(`addBlockedBy: #${n.id} is deleted`);d.includes(n.id)||d.push(n.id)}let f={...c,status:l};p(f,r),d.length?f.blockedBy=d:delete f.blockedBy;let g=[...e.tasks];if(g[s]=f,r.addBlockedBy?.length&&t.detectCycle(g,o,d))return h(`addBlockedBy would create a cycle in the blockedBy graph`);let _=u(c,f);return _&&(f.updatedAt=a),e.tasks=g,{ok:!0,outcome:_?{index:i,kind:`updated`,id:o,fromStatus:c.status,toStatus:l}:{index:i,kind:`unchanged`,id:o,status:l}}}function y(e,t,n,i){let a={tasks:[...e.tasks],nextId:e.nextId,maxTasks:i,refIds:new Map,failedRefs:new Map},o=[],s=0;for(let[e,i]of t.entries()){let t=g(a,i),c=t?h(t):i.id===void 0?_(a,i,e,n):v(a,i,e,n);if(c.ok){o.push(c.outcome),s+=1;continue}i.ref&&r.test(i.ref)&&!a.refIds.has(i.ref)&&a.failedRefs.set(i.ref,e),o.push({index:e,kind:`failed`,message:c.message,...i.id===void 0?{}:{id:i.id},...i.ref?{ref:i.ref}:{}})}return{document:s>0?d(e,a.tasks,a.nextId):e,op:{kind:`upsert`,items:o,applied:s,failed:o.length-s}}}function b(t,n,r,i=new Date().toISOString(),a=15){switch(n){case`upsert`:{let e=r.tasks;return!Array.isArray(e)||e.length===0?s(t,`upsert requires a non-empty tasks array, e.g. {"action":"upsert","tasks":[{"subject":"Write tests"}]}`):e.length>100?s(t,`upsert accepts at most 100 entries per call (received ${e.length})`):y(t,e,i,a)}case`list`:return{document:t,op:{kind:`list`,includeDeleted:r.includeDeleted===!0,...r.status===void 0?{}:{statusFilter:r.status}}};case`get`:{if(r.id===void 0)return s(t,`id required for get`);let e=t.tasks.find(e=>e.id===r.id);return e?{document:t,op:{kind:`get`,task:e}}:s(t,`#${r.id} not found`)}case`delete`:{if(r.id===void 0)return s(t,`id required for delete`);let n=t.tasks.findIndex(e=>e.id===r.id);if(n===-1)return s(t,`#${r.id} not found`);let a=t.tasks[n];if(a.status===`deleted`)return s(t,`#${a.id} is already deleted`);if(e.isDelegationActive(a))return s(t,`#${a.id} has a running delegation — cancel it before deleting`);let o=[...t.tasks];return o[n]={...a,status:e.DELETED_STATUS,updatedAt:i},{document:d(t,o),op:{kind:`delete`,id:a.id,subject:a.subject}}}case`clear`:{let n=t.tasks.filter(e.isDelegationActive);if(n.length>0)return s(t,`cannot clear while delegations are running (${n.map(e=>`#${e.id}`).join(`, `)}) — cancel them first`);let r=t.tasks.length;return{document:d(t,[],1),op:{kind:`clear`,count:r}}}}}exports.MAX_UPSERT_ITEMS=100,exports.REF_PATTERN=r,exports.applyTaskMutation=b,exports.formatUpsertFailure=a,exports.isCommittingOp=i,exports.singleItemOutcome=o;
3
+ //# sourceMappingURL=reducer.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reducer.cjs","names":["isTransitionValid","detectCycle","isDelegationActive","DELETED_STATUS"],"sources":["../../../src/services/store/reducer.ts"],"sourcesContent":["import { isTransitionValid } from './invariants.ts';\nimport { detectCycle } from './taskGraph.ts';\nimport {\n DELETED_STATUS,\n type DepToken,\n isDelegationActive,\n type Task,\n type TaskAction,\n type TaskDocument,\n type TaskItemMutation,\n type TaskMutationParams,\n type TaskStatus,\n type UpsertItemOutcome,\n} from './types.ts';\n\n/** Default board capacity when a caller does not provide a configured limit. */\nconst DEFAULT_REDUCER_MAX_TASKS = 15;\n\n/** Bounds the work one call can do, and with it the size of one committed write. */\nexport const MAX_UPSERT_ITEMS = 100;\n\n/**\n * A ref must start with a letter, which makes it structurally unconfusable with\n * a stringified id. That is why resolving a dependency token is just a `typeof`\n * check with no coercion heuristics.\n */\nexport const REF_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,31}$/;\n\n/**\n * Reducer outcome. Closed tagged union: adding an action requires extending\n * this union and the response formatter, which the compiler enforces.\n *\n * `upsert` carries one outcome per request item. It is returned even when every\n * item failed — `error` is reserved for whole-call faults — so the tool layer\n * still has the per-item messages to report.\n */\nexport type Op =\n | { kind: 'upsert'; items: UpsertItemOutcome[]; applied: number; failed: number }\n | { kind: 'delete'; id: number; subject: string }\n | { kind: 'list'; statusFilter?: TaskStatus; includeDeleted: boolean }\n | { kind: 'get'; task: Task }\n | { kind: 'clear'; count: number }\n | { kind: 'error'; message: string };\n\nexport interface ApplyResult {\n document: TaskDocument;\n op: Op;\n}\n\n/** Actions the reducer owns. `assign`/`cancel` are handled by the delegation manager. */\nexport type ReducerAction = Exclude<TaskAction, 'assign' | 'cancel'>;\n\n/**\n * Does this op represent state that must reach disk?\n *\n * The exhaustive switch is the point: a future `Op` variant cannot be added\n * without declaring its persistence intent, so nothing silently starts or stops\n * bumping `rev`.\n */\nexport function isCommittingOp(op: Op): boolean {\n switch (op.kind) {\n case 'error':\n case 'list':\n case 'get':\n return false;\n case 'upsert':\n return op.items.some((item) => item.kind === 'created' || item.kind === 'updated');\n case 'delete':\n case 'clear':\n return true;\n }\n}\n\n/** Joined per-item failures, for the thrown error when an upsert applied nothing. */\nexport function formatUpsertFailure(op: Extract<Op, { kind: 'upsert' }>): string {\n return op.items\n .filter((item) => item.kind === 'failed')\n .map((item) => `item[${item.index}]: ${item.message}`)\n .join('\\n');\n}\n\n/** The single item's outcome, for callers that only ever send a batch of one. */\nexport function singleItemOutcome(op: Op): UpsertItemOutcome | undefined {\n return op.kind === 'upsert' ? op.items[0] : undefined;\n}\n\nfunction errorResult(document: TaskDocument, message: string): ApplyResult {\n return { document, op: { kind: 'error', message } };\n}\n\nfunction sameNumberList(a: number[] | undefined, b: number[] | undefined): boolean {\n const x = a ?? [];\n const y = b ?? [];\n return x.length === y.length && x.every((value, index) => value === y[index]);\n}\n\nfunction sameRecord(a: Record<string, unknown> | undefined, b: Record<string, unknown> | undefined): boolean {\n return JSON.stringify(a ?? null) === JSON.stringify(b ?? null);\n}\n\n/**\n * Did this update change anything? A no-effect update (status re-set to its\n * current value, fields re-sent unchanged) reports \"No change\" rather than\n * \"Updated #N\" — without the distinction a model can loop re-issuing the same\n * call believing it never landed.\n */\nfunction taskChanged(before: Task, after: Task): boolean {\n return (\n before.subject !== after.subject ||\n before.status !== after.status ||\n before.description !== after.description ||\n before.activeForm !== after.activeForm ||\n before.owner !== after.owner ||\n !sameNumberList(before.blockedBy, after.blockedBy) ||\n !sameRecord(before.metadata, after.metadata)\n );\n}\n\nfunction withTasks(document: TaskDocument, tasks: Task[], nextId = document.nextId): TaskDocument {\n return { ...document, tasks, nextId };\n}\n\n/** Merge incoming metadata over a base; a `null` value deletes its key. */\nfunction mergeMetadata(\n base: Record<string, unknown> | undefined,\n incoming: Record<string, unknown>,\n): Record<string, unknown> | undefined {\n const merged: Record<string, unknown> = { ...base };\n for (const [key, value] of Object.entries(incoming)) {\n if (value === null) delete merged[key];\n else merged[key] = value;\n }\n return Object.keys(merged).length ? merged : undefined;\n}\n\n/** Copy the optional scalar fields an item may set onto a task, in place. */\nfunction assignScalars(target: Task, item: TaskItemMutation): void {\n if (item.subject !== undefined) target.subject = item.subject;\n if (item.description !== undefined) target.description = item.description;\n if (item.activeForm !== undefined) target.activeForm = item.activeForm;\n if (item.owner !== undefined) target.owner = item.owner;\n if (item.metadata !== undefined) {\n const merged = mergeMetadata(target.metadata, item.metadata);\n if (merged === undefined) delete target.metadata;\n else target.metadata = merged;\n }\n}\n\n/**\n * Working state threaded item to item, so entry N observes every effect of\n * entries 1..N-1. `refIds` and `failedRefs` are what make the cascade work:\n * refs resolve backward only, so an entry that names a failed sibling is always\n * processed after the failure that killed it.\n */\ninterface UpsertContext {\n tasks: Task[];\n nextId: number;\n maxTasks: number;\n refIds: Map<string, number>;\n failedRefs: Map<string, number>;\n}\n\ntype Resolved = { ok: true; id: number } | { ok: false; message: string };\n\nfunction resolveDep(context: UpsertContext, field: string, token: DepToken): Resolved {\n if (typeof token === 'number') return { ok: true, id: token };\n if (!REF_PATTERN.test(token)) {\n return { ok: false, message: `${field}: \"${token}\" is not a valid ref; pass an existing task id as a number` };\n }\n const id = context.refIds.get(token);\n if (id !== undefined) return { ok: true, id };\n const failedAt = context.failedRefs.get(token);\n if (failedAt !== undefined) {\n return { ok: false, message: `${field}: ref \"${token}\" refers to item[${failedAt}], which failed` };\n }\n return {\n ok: false,\n message: `${field}: unknown ref \"${token}\" — a ref must be declared by an earlier entry in the same call`,\n };\n}\n\ntype ItemResult = { ok: true; outcome: UpsertItemOutcome } | { ok: false; message: string };\n\nfunction fail(message: string): ItemResult {\n return { ok: false, message };\n}\n\n/** Structural checks that apply to every entry, whichever kind it is. */\nfunction checkShape(context: UpsertContext, item: TaskItemMutation): string | undefined {\n if (item.ref !== undefined) {\n if (item.id !== undefined) return 'ref is only valid when creating a task; drop the id, or drop the ref';\n if (!REF_PATTERN.test(item.ref)) {\n return `ref \"${item.ref}\" is invalid: a ref must start with a letter and contain only letters, digits, - or _`;\n }\n const owner = context.refIds.get(item.ref) !== undefined || context.failedRefs.has(item.ref);\n if (owner) return `duplicate ref \"${item.ref}\": it was already declared by an earlier entry`;\n }\n return undefined;\n}\n\nfunction applyCreateItem(context: UpsertContext, item: TaskItemMutation, index: number, now: string): ItemResult {\n if (item.subject === undefined) return fail('subject is required when the entry has no id');\n if (!item.subject.trim()) return fail('subject must not be blank');\n if (item.addBlockedBy !== undefined || item.removeBlockedBy !== undefined) {\n return fail('addBlockedBy / removeBlockedBy are only for an entry with an id; a new task uses blockedBy');\n }\n // A task created as a tombstone is invisible to every view and can never\n // leave `deleted`, so it would be a write-only black hole.\n if (item.status === DELETED_STATUS) {\n return fail('cannot create a task with status deleted; create it, then use action delete');\n }\n\n const taskCount = context.tasks.filter((task) => task.status !== DELETED_STATUS).length;\n if (taskCount >= context.maxTasks) {\n return fail(`task limit of ${context.maxTasks} reached; delete completed tasks first before creating new tasks`);\n }\n\n const blockedBy: number[] = [];\n for (const token of item.blockedBy ?? []) {\n const resolved = resolveDep(context, 'blockedBy', token);\n if (!resolved.ok) return fail(resolved.message);\n const dep = context.tasks.find((task) => task.id === resolved.id);\n if (!dep) return fail(`blockedBy: #${resolved.id} not found`);\n if (dep.status === DELETED_STATUS) return fail(`blockedBy: #${resolved.id} is deleted`);\n if (!blockedBy.includes(resolved.id)) blockedBy.push(resolved.id);\n }\n\n // No cycle check is needed: the id is freshly allocated, so nothing already\n // in the document can point at it yet.\n const created: Task = {\n id: context.nextId,\n subject: item.subject,\n status: item.status ?? 'pending',\n createdAt: now,\n updatedAt: now,\n };\n assignScalars(created, item);\n if (blockedBy.length) created.blockedBy = blockedBy;\n\n context.nextId += 1;\n context.tasks.push(created);\n if (item.ref) context.refIds.set(item.ref, created.id);\n\n return {\n ok: true,\n outcome: {\n index,\n kind: 'created',\n id: created.id,\n subject: created.subject,\n status: created.status,\n ...(item.ref ? { ref: item.ref } : {}),\n ...(blockedBy.length ? { blockedBy } : {}),\n },\n };\n}\n\nfunction applyUpdateItem(context: UpsertContext, item: TaskItemMutation, index: number, now: string): ItemResult {\n const id = item.id as number;\n const at = context.tasks.findIndex((task) => task.id === id);\n if (at === -1) return fail(`#${id} not found`);\n if (item.blockedBy !== undefined) {\n return fail('blockedBy is only for a new entry; use addBlockedBy / removeBlockedBy on an entry that has an id');\n }\n\n const hasMutation =\n item.subject !== undefined ||\n item.description !== undefined ||\n item.activeForm !== undefined ||\n item.status !== undefined ||\n item.owner !== undefined ||\n item.metadata !== undefined ||\n Boolean(item.addBlockedBy?.length) ||\n Boolean(item.removeBlockedBy?.length);\n if (!hasMutation) {\n return fail(\n 'nothing to change: provide at least one of subject, description, activeForm, status, owner, metadata, addBlockedBy, or removeBlockedBy',\n );\n }\n\n const current = context.tasks[at];\n\n // The Task Space overlay commits free text from an inline editor, so a blank\n // subject reaches the reducer as a real update rather than as a missing\n // field. Persisting it would leave an unidentifiable row.\n if (item.subject !== undefined && !item.subject.trim()) return fail('subject must not be blank');\n\n let newStatus = current.status;\n if (item.status !== undefined) {\n if (!isTransitionValid(current.status, item.status)) {\n return fail(`illegal transition ${current.status} -> ${item.status}`);\n }\n newStatus = item.status;\n }\n\n let newBlockedBy = current.blockedBy ? [...current.blockedBy] : [];\n for (const token of item.removeBlockedBy ?? []) {\n const resolved = resolveDep(context, 'removeBlockedBy', token);\n if (!resolved.ok) return fail(resolved.message);\n // Removing an id that is not there is a well-defined no-op, so unlike the\n // add path this deliberately skips the existence check.\n newBlockedBy = newBlockedBy.filter((dep) => dep !== resolved.id);\n }\n for (const token of item.addBlockedBy ?? []) {\n const resolved = resolveDep(context, 'addBlockedBy', token);\n if (!resolved.ok) return fail(resolved.message);\n if (resolved.id === id) return fail(`cannot block #${id} on itself`);\n const dep = context.tasks.find((task) => task.id === resolved.id);\n if (!dep) return fail(`addBlockedBy: #${resolved.id} not found`);\n if (dep.status === DELETED_STATUS) return fail(`addBlockedBy: #${resolved.id} is deleted`);\n if (!newBlockedBy.includes(resolved.id)) newBlockedBy.push(resolved.id);\n }\n\n const updated: Task = { ...current, status: newStatus };\n assignScalars(updated, item);\n if (newBlockedBy.length) updated.blockedBy = newBlockedBy;\n else delete updated.blockedBy;\n\n // The candidate is written before the check because `detectCycle` unions the\n // node's stored edges with the ones passed in: checking against the old array\n // would resurrect an edge `removeBlockedBy` just stripped and reject a\n // remove+add that legitimately breaks a cycle.\n const candidate = [...context.tasks];\n candidate[at] = updated;\n if (item.addBlockedBy?.length && detectCycle(candidate, id, newBlockedBy)) {\n return fail('addBlockedBy would create a cycle in the blockedBy graph');\n }\n\n const changed = taskChanged(current, updated);\n if (changed) updated.updatedAt = now;\n context.tasks = candidate;\n\n return {\n ok: true,\n outcome: changed\n ? { index, kind: 'updated', id, fromStatus: current.status, toStatus: newStatus }\n : { index, kind: 'unchanged', id, status: newStatus },\n };\n}\n\n/**\n * Apply every entry in request order, threading the document.\n *\n * Each entry lands completely or not at all: a create whose dependencies fail\n * is not kept dependency-free, because handing back an unblocked task the\n * caller asked to be blocked is a lie it may immediately act on.\n */\nfunction applyUpsert(document: TaskDocument, items: TaskItemMutation[], now: string, maxTasks: number): ApplyResult {\n const context: UpsertContext = {\n tasks: [...document.tasks],\n nextId: document.nextId,\n maxTasks,\n refIds: new Map(),\n failedRefs: new Map(),\n };\n const outcomes: UpsertItemOutcome[] = [];\n let applied = 0;\n\n for (const [index, item] of items.entries()) {\n const shapeError = checkShape(context, item);\n const result = shapeError\n ? fail(shapeError)\n : item.id === undefined\n ? applyCreateItem(context, item, index, now)\n : applyUpdateItem(context, item, index, now);\n\n if (result.ok) {\n outcomes.push(result.outcome);\n applied += 1;\n continue;\n }\n // A ref whose owner failed must not read as a typo to the entries that\n // depend on it, so the dead ref is recorded rather than left unknown.\n if (item.ref && REF_PATTERN.test(item.ref) && !context.refIds.has(item.ref)) {\n context.failedRefs.set(item.ref, index);\n }\n outcomes.push({\n index,\n kind: 'failed',\n message: result.message,\n ...(item.id === undefined ? {} : { id: item.id }),\n ...(item.ref ? { ref: item.ref } : {}),\n });\n }\n\n return {\n // Nothing applied means nothing to write: returning the original object by\n // reference keeps the caller's write-skip path identical to a hard error.\n document: applied > 0 ? withTasks(document, context.tasks, context.nextId) : document,\n op: { kind: 'upsert', items: outcomes, applied, failed: outcomes.length - applied },\n };\n}\n\n/**\n * Pure reducer: (document, action, params) -> (document, op).\n *\n * All validation is in-line: structural guards plus state-aware checks\n * (transition legality, dangling or deleted blockedBy, self-block, cycles,\n * in-flight delegations). The caller owns persistence and formatting.\n */\nexport function applyTaskMutation(\n document: TaskDocument,\n action: ReducerAction,\n params: TaskMutationParams,\n now: string = new Date().toISOString(),\n maxTasks = DEFAULT_REDUCER_MAX_TASKS,\n): ApplyResult {\n switch (action) {\n case 'upsert': {\n const items = params.tasks;\n if (!Array.isArray(items) || items.length === 0) {\n return errorResult(\n document,\n 'upsert requires a non-empty tasks array, e.g. {\"action\":\"upsert\",\"tasks\":[{\"subject\":\"Write tests\"}]}',\n );\n }\n if (items.length > MAX_UPSERT_ITEMS) {\n return errorResult(\n document,\n `upsert accepts at most ${MAX_UPSERT_ITEMS} entries per call (received ${items.length})`,\n );\n }\n return applyUpsert(document, items, now, maxTasks);\n }\n\n case 'list': {\n return {\n document,\n op: {\n kind: 'list',\n includeDeleted: params.includeDeleted === true,\n ...(params.status !== undefined ? { statusFilter: params.status } : {}),\n },\n };\n }\n\n case 'get': {\n if (params.id === undefined) return errorResult(document, 'id required for get');\n const task = document.tasks.find((candidate) => candidate.id === params.id);\n if (!task) return errorResult(document, `#${params.id} not found`);\n return { document, op: { kind: 'get', task } };\n }\n\n case 'delete': {\n if (params.id === undefined) return errorResult(document, 'id required for delete');\n const index = document.tasks.findIndex((task) => task.id === params.id);\n if (index === -1) return errorResult(document, `#${params.id} not found`);\n const current = document.tasks[index];\n if (current.status === DELETED_STATUS) return errorResult(document, `#${current.id} is already deleted`);\n if (isDelegationActive(current)) {\n return errorResult(document, `#${current.id} has a running delegation — cancel it before deleting`);\n }\n\n const tasks = [...document.tasks];\n tasks[index] = { ...current, status: DELETED_STATUS, updatedAt: now };\n return {\n document: withTasks(document, tasks),\n op: { kind: 'delete', id: current.id, subject: current.subject },\n };\n }\n\n case 'clear': {\n const active = document.tasks.filter(isDelegationActive);\n if (active.length > 0) {\n const ids = active.map((task) => `#${task.id}`).join(', ');\n return errorResult(document, `cannot clear while delegations are running (${ids}) — cancel them first`);\n }\n const count = document.tasks.length;\n return {\n document: withTasks(document, [], 1),\n op: { kind: 'clear', count },\n };\n }\n }\n}\n"],"mappings":"0FA0Ba,EAAc,gCAiC3B,SAAgB,EAAe,EAAiB,CAC9C,OAAQ,EAAG,KAAX,CACE,IAAK,QACL,IAAK,OACL,IAAK,MACH,MAAO,GACT,IAAK,SACH,OAAO,EAAG,MAAM,KAAM,GAAS,EAAK,OAAS,WAAa,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AAK,IACyB,EAAE,sBAAsB,EAExG,IAAM,EAAQ,EAAS,MAAM,OAC7B,MAAO,CACL,SAAU,EAAU,EAAU,CAAC,EAAG,CAAC,EACnC,GAAI,CAAE,KAAM,QAAS,OAAM,CAC7B,CACF,CACF,CACF"}
@@ -0,0 +1,72 @@
1
+ import { Task, TaskAction, TaskDocument, TaskMutationParams, TaskStatus, UpsertItemOutcome } from "./types.cjs";
2
+ //#region src/services/store/reducer.d.ts
3
+ /** Bounds the work one call can do, and with it the size of one committed write. */
4
+ declare const MAX_UPSERT_ITEMS = 100;
5
+ /**
6
+ * A ref must start with a letter, which makes it structurally unconfusable with
7
+ * a stringified id. That is why resolving a dependency token is just a `typeof`
8
+ * check with no coercion heuristics.
9
+ */
10
+ declare const REF_PATTERN: RegExp;
11
+ /**
12
+ * Reducer outcome. Closed tagged union: adding an action requires extending
13
+ * this union and the response formatter, which the compiler enforces.
14
+ *
15
+ * `upsert` carries one outcome per request item. It is returned even when every
16
+ * item failed — `error` is reserved for whole-call faults — so the tool layer
17
+ * still has the per-item messages to report.
18
+ */
19
+ type Op = {
20
+ kind: 'upsert';
21
+ items: UpsertItemOutcome[];
22
+ applied: number;
23
+ failed: number;
24
+ } | {
25
+ kind: 'delete';
26
+ id: number;
27
+ subject: string;
28
+ } | {
29
+ kind: 'list';
30
+ statusFilter?: TaskStatus;
31
+ includeDeleted: boolean;
32
+ } | {
33
+ kind: 'get';
34
+ task: Task;
35
+ } | {
36
+ kind: 'clear';
37
+ count: number;
38
+ } | {
39
+ kind: 'error';
40
+ message: string;
41
+ };
42
+ interface ApplyResult {
43
+ document: TaskDocument;
44
+ op: Op;
45
+ }
46
+ /** Actions the reducer owns. `assign`/`cancel` are handled by the delegation manager. */
47
+ type ReducerAction = Exclude<TaskAction, 'assign' | 'cancel'>;
48
+ /**
49
+ * Does this op represent state that must reach disk?
50
+ *
51
+ * The exhaustive switch is the point: a future `Op` variant cannot be added
52
+ * without declaring its persistence intent, so nothing silently starts or stops
53
+ * bumping `rev`.
54
+ */
55
+ declare function isCommittingOp(op: Op): boolean;
56
+ /** Joined per-item failures, for the thrown error when an upsert applied nothing. */
57
+ declare function formatUpsertFailure(op: Extract<Op, {
58
+ kind: 'upsert';
59
+ }>): string;
60
+ /** The single item's outcome, for callers that only ever send a batch of one. */
61
+ declare function singleItemOutcome(op: Op): UpsertItemOutcome | undefined;
62
+ /**
63
+ * Pure reducer: (document, action, params) -> (document, op).
64
+ *
65
+ * All validation is in-line: structural guards plus state-aware checks
66
+ * (transition legality, dangling or deleted blockedBy, self-block, cycles,
67
+ * in-flight delegations). The caller owns persistence and formatting.
68
+ */
69
+ declare function applyTaskMutation(document: TaskDocument, action: ReducerAction, params: TaskMutationParams, now?: string, maxTasks?: number): ApplyResult;
70
+ //#endregion
71
+ export { ApplyResult, MAX_UPSERT_ITEMS, Op, REF_PATTERN, ReducerAction, applyTaskMutation, formatUpsertFailure, isCommittingOp, singleItemOutcome };
72
+ //# sourceMappingURL=reducer.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reducer.d.cts","names":[],"sources":["../../../src/services/store/reducer.ts"],"mappings":";;;cAmBa;;;;;;cAOA,aAAW;;;;;;;;;KAUZ;EACN;EAAgB,OAAO;EAAqB;EAAiB;;EAC7D;EAAgB;EAAY;;EAC5B;EAAc,eAAe;EAAY;;EACzC;EAAa,MAAM;;EACnB;EAAe;;EACf;EAAe;;UAEJ;EACf,UAAU;EACV,IAAI;;;KAIM,gBAAgB,QAAQ;;;;;;;;iBASpB,eAAe,IAAI;;iBAenB,oBAAoB,IAAI,QAAQ;EAAM;;;iBAQtC,kBAAkB,IAAI,KAAK;;;;;;;;iBA8T3B,kBACd,UAAU,cACV,QAAQ,eACR,QAAQ,oBACR,cACA,oBACC"}
@@ -0,0 +1,72 @@
1
+ import { Task, TaskAction, TaskDocument, TaskMutationParams, TaskStatus, UpsertItemOutcome } from "./types.mjs";
2
+ //#region src/services/store/reducer.d.ts
3
+ /** Bounds the work one call can do, and with it the size of one committed write. */
4
+ declare const MAX_UPSERT_ITEMS = 100;
5
+ /**
6
+ * A ref must start with a letter, which makes it structurally unconfusable with
7
+ * a stringified id. That is why resolving a dependency token is just a `typeof`
8
+ * check with no coercion heuristics.
9
+ */
10
+ declare const REF_PATTERN: RegExp;
11
+ /**
12
+ * Reducer outcome. Closed tagged union: adding an action requires extending
13
+ * this union and the response formatter, which the compiler enforces.
14
+ *
15
+ * `upsert` carries one outcome per request item. It is returned even when every
16
+ * item failed — `error` is reserved for whole-call faults — so the tool layer
17
+ * still has the per-item messages to report.
18
+ */
19
+ type Op = {
20
+ kind: 'upsert';
21
+ items: UpsertItemOutcome[];
22
+ applied: number;
23
+ failed: number;
24
+ } | {
25
+ kind: 'delete';
26
+ id: number;
27
+ subject: string;
28
+ } | {
29
+ kind: 'list';
30
+ statusFilter?: TaskStatus;
31
+ includeDeleted: boolean;
32
+ } | {
33
+ kind: 'get';
34
+ task: Task;
35
+ } | {
36
+ kind: 'clear';
37
+ count: number;
38
+ } | {
39
+ kind: 'error';
40
+ message: string;
41
+ };
42
+ interface ApplyResult {
43
+ document: TaskDocument;
44
+ op: Op;
45
+ }
46
+ /** Actions the reducer owns. `assign`/`cancel` are handled by the delegation manager. */
47
+ type ReducerAction = Exclude<TaskAction, 'assign' | 'cancel'>;
48
+ /**
49
+ * Does this op represent state that must reach disk?
50
+ *
51
+ * The exhaustive switch is the point: a future `Op` variant cannot be added
52
+ * without declaring its persistence intent, so nothing silently starts or stops
53
+ * bumping `rev`.
54
+ */
55
+ declare function isCommittingOp(op: Op): boolean;
56
+ /** Joined per-item failures, for the thrown error when an upsert applied nothing. */
57
+ declare function formatUpsertFailure(op: Extract<Op, {
58
+ kind: 'upsert';
59
+ }>): string;
60
+ /** The single item's outcome, for callers that only ever send a batch of one. */
61
+ declare function singleItemOutcome(op: Op): UpsertItemOutcome | undefined;
62
+ /**
63
+ * Pure reducer: (document, action, params) -> (document, op).
64
+ *
65
+ * All validation is in-line: structural guards plus state-aware checks
66
+ * (transition legality, dangling or deleted blockedBy, self-block, cycles,
67
+ * in-flight delegations). The caller owns persistence and formatting.
68
+ */
69
+ declare function applyTaskMutation(document: TaskDocument, action: ReducerAction, params: TaskMutationParams, now?: string, maxTasks?: number): ApplyResult;
70
+ //#endregion
71
+ export { ApplyResult, MAX_UPSERT_ITEMS, Op, REF_PATTERN, ReducerAction, applyTaskMutation, formatUpsertFailure, isCommittingOp, singleItemOutcome };
72
+ //# sourceMappingURL=reducer.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reducer.d.mts","names":[],"sources":["../../../src/services/store/reducer.ts"],"mappings":";;;cAmBa;;;;;;cAOA,aAAW;;;;;;;;;KAUZ;EACN;EAAgB,OAAO;EAAqB;EAAiB;;EAC7D;EAAgB;EAAY;;EAC5B;EAAc,eAAe;EAAY;;EACzC;EAAa,MAAM;;EACnB;EAAe;;EACf;EAAe;;UAEJ;EACf,UAAU;EACV,IAAI;;;KAIM,gBAAgB,QAAQ;;;;;;;;iBASpB,eAAe,IAAI;;iBAenB,oBAAoB,IAAI,QAAQ;EAAM;;;iBAQtC,kBAAkB,IAAI,KAAK;;;;;;;;iBA8T3B,kBACd,UAAU,cACV,QAAQ,eACR,QAAQ,oBACR,cACA,oBACC"}
@@ -0,0 +1,3 @@
1
+ import{DELETED_STATUS as e,isDelegationActive as t}from"./types.mjs";import{detectCycle as n}from"./taskGraph.mjs";import{isTransitionValid as r}from"./invariants.mjs";const i=100,a=/^[A-Za-z][A-Za-z0-9_-]{0,31}$/;function o(e){switch(e.kind){case`error`:case`list`:case`get`:return!1;case`upsert`:return e.items.some(e=>e.kind===`created`||e.kind===`updated`);case`delete`:case`clear`:return!0}}function s(e){return e.items.filter(e=>e.kind===`failed`).map(e=>`item[${e.index}]: ${e.message}`).join(`
2
+ `)}function c(e){return e.kind===`upsert`?e.items[0]:void 0}function l(e,t){return{document:e,op:{kind:`error`,message:t}}}function u(e,t){let n=e??[],r=t??[];return n.length===r.length&&n.every((e,t)=>e===r[t])}function d(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function f(e,t){return e.subject!==t.subject||e.status!==t.status||e.description!==t.description||e.activeForm!==t.activeForm||e.owner!==t.owner||!u(e.blockedBy,t.blockedBy)||!d(e.metadata,t.metadata)}function p(e,t,n=e.nextId){return{...e,tasks:t,nextId:n}}function m(e,t){let n={...e};for(let[e,r]of Object.entries(t))r===null?delete n[e]:n[e]=r;return Object.keys(n).length?n:void 0}function h(e,t){if(t.subject!==void 0&&(e.subject=t.subject),t.description!==void 0&&(e.description=t.description),t.activeForm!==void 0&&(e.activeForm=t.activeForm),t.owner!==void 0&&(e.owner=t.owner),t.metadata!==void 0){let n=m(e.metadata,t.metadata);n===void 0?delete e.metadata:e.metadata=n}}function g(e,t,n){if(typeof n==`number`)return{ok:!0,id:n};if(!a.test(n))return{ok:!1,message:`${t}: "${n}" is not a valid ref; pass an existing task id as a number`};let r=e.refIds.get(n);if(r!==void 0)return{ok:!0,id:r};let i=e.failedRefs.get(n);return i===void 0?{ok:!1,message:`${t}: unknown ref "${n}" — a ref must be declared by an earlier entry in the same call`}:{ok:!1,message:`${t}: ref "${n}" refers to item[${i}], which failed`}}function _(e){return{ok:!1,message:e}}function v(e,t){if(t.ref!==void 0){if(t.id!==void 0)return`ref is only valid when creating a task; drop the id, or drop the ref`;if(!a.test(t.ref))return`ref "${t.ref}" is invalid: a ref must start with a letter and contain only letters, digits, - or _`;if(e.refIds.get(t.ref)!==void 0||e.failedRefs.has(t.ref))return`duplicate ref "${t.ref}": it was already declared by an earlier entry`}}function y(e,t,n,r){if(t.subject===void 0)return _(`subject is required when the entry has no id`);if(!t.subject.trim())return _(`subject must not be blank`);if(t.addBlockedBy!==void 0||t.removeBlockedBy!==void 0)return _(`addBlockedBy / removeBlockedBy are only for an entry with an id; a new task uses blockedBy`);if(t.status===`deleted`)return _(`cannot create a task with status deleted; create it, then use action delete`);if(e.tasks.filter(e=>e.status!==`deleted`).length>=e.maxTasks)return _(`task limit of ${e.maxTasks} reached; delete completed tasks first before creating new tasks`);let i=[];for(let n of t.blockedBy??[]){let t=g(e,`blockedBy`,n);if(!t.ok)return _(t.message);let r=e.tasks.find(e=>e.id===t.id);if(!r)return _(`blockedBy: #${t.id} not found`);if(r.status===`deleted`)return _(`blockedBy: #${t.id} is deleted`);i.includes(t.id)||i.push(t.id)}let a={id:e.nextId,subject:t.subject,status:t.status??`pending`,createdAt:r,updatedAt:r};return h(a,t),i.length&&(a.blockedBy=i),e.nextId+=1,e.tasks.push(a),t.ref&&e.refIds.set(t.ref,a.id),{ok:!0,outcome:{index:n,kind:`created`,id:a.id,subject:a.subject,status:a.status,...t.ref?{ref:t.ref}:{},...i.length?{blockedBy:i}:{}}}}function b(e,t,i,a){let o=t.id,s=e.tasks.findIndex(e=>e.id===o);if(s===-1)return _(`#${o} not found`);if(t.blockedBy!==void 0)return _(`blockedBy is only for a new entry; use addBlockedBy / removeBlockedBy on an entry that has an id`);if(!(t.subject!==void 0||t.description!==void 0||t.activeForm!==void 0||t.status!==void 0||t.owner!==void 0||t.metadata!==void 0||t.addBlockedBy?.length||t.removeBlockedBy?.length))return _(`nothing to change: provide at least one of subject, description, activeForm, status, owner, metadata, addBlockedBy, or removeBlockedBy`);let c=e.tasks[s];if(t.subject!==void 0&&!t.subject.trim())return _(`subject must not be blank`);let l=c.status;if(t.status!==void 0){if(!r(c.status,t.status))return _(`illegal transition ${c.status} -> ${t.status}`);l=t.status}let u=c.blockedBy?[...c.blockedBy]:[];for(let n of t.removeBlockedBy??[]){let t=g(e,`removeBlockedBy`,n);if(!t.ok)return _(t.message);u=u.filter(e=>e!==t.id)}for(let n of t.addBlockedBy??[]){let t=g(e,`addBlockedBy`,n);if(!t.ok)return _(t.message);if(t.id===o)return _(`cannot block #${o} on itself`);let r=e.tasks.find(e=>e.id===t.id);if(!r)return _(`addBlockedBy: #${t.id} not found`);if(r.status===`deleted`)return _(`addBlockedBy: #${t.id} is deleted`);u.includes(t.id)||u.push(t.id)}let d={...c,status:l};h(d,t),u.length?d.blockedBy=u:delete d.blockedBy;let p=[...e.tasks];if(p[s]=d,t.addBlockedBy?.length&&n(p,o,u))return _(`addBlockedBy would create a cycle in the blockedBy graph`);let m=f(c,d);return m&&(d.updatedAt=a),e.tasks=p,{ok:!0,outcome:m?{index:i,kind:`updated`,id:o,fromStatus:c.status,toStatus:l}:{index:i,kind:`unchanged`,id:o,status:l}}}function x(e,t,n,r){let i={tasks:[...e.tasks],nextId:e.nextId,maxTasks:r,refIds:new Map,failedRefs:new Map},o=[],s=0;for(let[e,r]of t.entries()){let t=v(i,r),c=t?_(t):r.id===void 0?y(i,r,e,n):b(i,r,e,n);if(c.ok){o.push(c.outcome),s+=1;continue}r.ref&&a.test(r.ref)&&!i.refIds.has(r.ref)&&i.failedRefs.set(r.ref,e),o.push({index:e,kind:`failed`,message:c.message,...r.id===void 0?{}:{id:r.id},...r.ref?{ref:r.ref}:{}})}return{document:s>0?p(e,i.tasks,i.nextId):e,op:{kind:`upsert`,items:o,applied:s,failed:o.length-s}}}function S(n,r,i,a=new Date().toISOString(),o=15){switch(r){case`upsert`:{let e=i.tasks;return!Array.isArray(e)||e.length===0?l(n,`upsert requires a non-empty tasks array, e.g. {"action":"upsert","tasks":[{"subject":"Write tests"}]}`):e.length>100?l(n,`upsert accepts at most 100 entries per call (received ${e.length})`):x(n,e,a,o)}case`list`:return{document:n,op:{kind:`list`,includeDeleted:i.includeDeleted===!0,...i.status===void 0?{}:{statusFilter:i.status}}};case`get`:{if(i.id===void 0)return l(n,`id required for get`);let e=n.tasks.find(e=>e.id===i.id);return e?{document:n,op:{kind:`get`,task:e}}:l(n,`#${i.id} not found`)}case`delete`:{if(i.id===void 0)return l(n,`id required for delete`);let r=n.tasks.findIndex(e=>e.id===i.id);if(r===-1)return l(n,`#${i.id} not found`);let o=n.tasks[r];if(o.status===`deleted`)return l(n,`#${o.id} is already deleted`);if(t(o))return l(n,`#${o.id} has a running delegation — cancel it before deleting`);let s=[...n.tasks];return s[r]={...o,status:e,updatedAt:a},{document:p(n,s),op:{kind:`delete`,id:o.id,subject:o.subject}}}case`clear`:{let e=n.tasks.filter(t);if(e.length>0)return l(n,`cannot clear while delegations are running (${e.map(e=>`#${e.id}`).join(`, `)}) — cancel them first`);let r=n.tasks.length;return{document:p(n,[],1),op:{kind:`clear`,count:r}}}}}export{i as MAX_UPSERT_ITEMS,a as REF_PATTERN,S as applyTaskMutation,s as formatUpsertFailure,o as isCommittingOp,c as singleItemOutcome};
3
+ //# sourceMappingURL=reducer.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reducer.mjs","names":[],"sources":["../../../src/services/store/reducer.ts"],"sourcesContent":["import { isTransitionValid } from './invariants.ts';\nimport { detectCycle } from './taskGraph.ts';\nimport {\n DELETED_STATUS,\n type DepToken,\n isDelegationActive,\n type Task,\n type TaskAction,\n type TaskDocument,\n type TaskItemMutation,\n type TaskMutationParams,\n type TaskStatus,\n type UpsertItemOutcome,\n} from './types.ts';\n\n/** Default board capacity when a caller does not provide a configured limit. */\nconst DEFAULT_REDUCER_MAX_TASKS = 15;\n\n/** Bounds the work one call can do, and with it the size of one committed write. */\nexport const MAX_UPSERT_ITEMS = 100;\n\n/**\n * A ref must start with a letter, which makes it structurally unconfusable with\n * a stringified id. That is why resolving a dependency token is just a `typeof`\n * check with no coercion heuristics.\n */\nexport const REF_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,31}$/;\n\n/**\n * Reducer outcome. Closed tagged union: adding an action requires extending\n * this union and the response formatter, which the compiler enforces.\n *\n * `upsert` carries one outcome per request item. It is returned even when every\n * item failed — `error` is reserved for whole-call faults — so the tool layer\n * still has the per-item messages to report.\n */\nexport type Op =\n | { kind: 'upsert'; items: UpsertItemOutcome[]; applied: number; failed: number }\n | { kind: 'delete'; id: number; subject: string }\n | { kind: 'list'; statusFilter?: TaskStatus; includeDeleted: boolean }\n | { kind: 'get'; task: Task }\n | { kind: 'clear'; count: number }\n | { kind: 'error'; message: string };\n\nexport interface ApplyResult {\n document: TaskDocument;\n op: Op;\n}\n\n/** Actions the reducer owns. `assign`/`cancel` are handled by the delegation manager. */\nexport type ReducerAction = Exclude<TaskAction, 'assign' | 'cancel'>;\n\n/**\n * Does this op represent state that must reach disk?\n *\n * The exhaustive switch is the point: a future `Op` variant cannot be added\n * without declaring its persistence intent, so nothing silently starts or stops\n * bumping `rev`.\n */\nexport function isCommittingOp(op: Op): boolean {\n switch (op.kind) {\n case 'error':\n case 'list':\n case 'get':\n return false;\n case 'upsert':\n return op.items.some((item) => item.kind === 'created' || item.kind === 'updated');\n case 'delete':\n case 'clear':\n return true;\n }\n}\n\n/** Joined per-item failures, for the thrown error when an upsert applied nothing. */\nexport function formatUpsertFailure(op: Extract<Op, { kind: 'upsert' }>): string {\n return op.items\n .filter((item) => item.kind === 'failed')\n .map((item) => `item[${item.index}]: ${item.message}`)\n .join('\\n');\n}\n\n/** The single item's outcome, for callers that only ever send a batch of one. */\nexport function singleItemOutcome(op: Op): UpsertItemOutcome | undefined {\n return op.kind === 'upsert' ? op.items[0] : undefined;\n}\n\nfunction errorResult(document: TaskDocument, message: string): ApplyResult {\n return { document, op: { kind: 'error', message } };\n}\n\nfunction sameNumberList(a: number[] | undefined, b: number[] | undefined): boolean {\n const x = a ?? [];\n const y = b ?? [];\n return x.length === y.length && x.every((value, index) => value === y[index]);\n}\n\nfunction sameRecord(a: Record<string, unknown> | undefined, b: Record<string, unknown> | undefined): boolean {\n return JSON.stringify(a ?? null) === JSON.stringify(b ?? null);\n}\n\n/**\n * Did this update change anything? A no-effect update (status re-set to its\n * current value, fields re-sent unchanged) reports \"No change\" rather than\n * \"Updated #N\" — without the distinction a model can loop re-issuing the same\n * call believing it never landed.\n */\nfunction taskChanged(before: Task, after: Task): boolean {\n return (\n before.subject !== after.subject ||\n before.status !== after.status ||\n before.description !== after.description ||\n before.activeForm !== after.activeForm ||\n before.owner !== after.owner ||\n !sameNumberList(before.blockedBy, after.blockedBy) ||\n !sameRecord(before.metadata, after.metadata)\n );\n}\n\nfunction withTasks(document: TaskDocument, tasks: Task[], nextId = document.nextId): TaskDocument {\n return { ...document, tasks, nextId };\n}\n\n/** Merge incoming metadata over a base; a `null` value deletes its key. */\nfunction mergeMetadata(\n base: Record<string, unknown> | undefined,\n incoming: Record<string, unknown>,\n): Record<string, unknown> | undefined {\n const merged: Record<string, unknown> = { ...base };\n for (const [key, value] of Object.entries(incoming)) {\n if (value === null) delete merged[key];\n else merged[key] = value;\n }\n return Object.keys(merged).length ? merged : undefined;\n}\n\n/** Copy the optional scalar fields an item may set onto a task, in place. */\nfunction assignScalars(target: Task, item: TaskItemMutation): void {\n if (item.subject !== undefined) target.subject = item.subject;\n if (item.description !== undefined) target.description = item.description;\n if (item.activeForm !== undefined) target.activeForm = item.activeForm;\n if (item.owner !== undefined) target.owner = item.owner;\n if (item.metadata !== undefined) {\n const merged = mergeMetadata(target.metadata, item.metadata);\n if (merged === undefined) delete target.metadata;\n else target.metadata = merged;\n }\n}\n\n/**\n * Working state threaded item to item, so entry N observes every effect of\n * entries 1..N-1. `refIds` and `failedRefs` are what make the cascade work:\n * refs resolve backward only, so an entry that names a failed sibling is always\n * processed after the failure that killed it.\n */\ninterface UpsertContext {\n tasks: Task[];\n nextId: number;\n maxTasks: number;\n refIds: Map<string, number>;\n failedRefs: Map<string, number>;\n}\n\ntype Resolved = { ok: true; id: number } | { ok: false; message: string };\n\nfunction resolveDep(context: UpsertContext, field: string, token: DepToken): Resolved {\n if (typeof token === 'number') return { ok: true, id: token };\n if (!REF_PATTERN.test(token)) {\n return { ok: false, message: `${field}: \"${token}\" is not a valid ref; pass an existing task id as a number` };\n }\n const id = context.refIds.get(token);\n if (id !== undefined) return { ok: true, id };\n const failedAt = context.failedRefs.get(token);\n if (failedAt !== undefined) {\n return { ok: false, message: `${field}: ref \"${token}\" refers to item[${failedAt}], which failed` };\n }\n return {\n ok: false,\n message: `${field}: unknown ref \"${token}\" — a ref must be declared by an earlier entry in the same call`,\n };\n}\n\ntype ItemResult = { ok: true; outcome: UpsertItemOutcome } | { ok: false; message: string };\n\nfunction fail(message: string): ItemResult {\n return { ok: false, message };\n}\n\n/** Structural checks that apply to every entry, whichever kind it is. */\nfunction checkShape(context: UpsertContext, item: TaskItemMutation): string | undefined {\n if (item.ref !== undefined) {\n if (item.id !== undefined) return 'ref is only valid when creating a task; drop the id, or drop the ref';\n if (!REF_PATTERN.test(item.ref)) {\n return `ref \"${item.ref}\" is invalid: a ref must start with a letter and contain only letters, digits, - or _`;\n }\n const owner = context.refIds.get(item.ref) !== undefined || context.failedRefs.has(item.ref);\n if (owner) return `duplicate ref \"${item.ref}\": it was already declared by an earlier entry`;\n }\n return undefined;\n}\n\nfunction applyCreateItem(context: UpsertContext, item: TaskItemMutation, index: number, now: string): ItemResult {\n if (item.subject === undefined) return fail('subject is required when the entry has no id');\n if (!item.subject.trim()) return fail('subject must not be blank');\n if (item.addBlockedBy !== undefined || item.removeBlockedBy !== undefined) {\n return fail('addBlockedBy / removeBlockedBy are only for an entry with an id; a new task uses blockedBy');\n }\n // A task created as a tombstone is invisible to every view and can never\n // leave `deleted`, so it would be a write-only black hole.\n if (item.status === DELETED_STATUS) {\n return fail('cannot create a task with status deleted; create it, then use action delete');\n }\n\n const taskCount = context.tasks.filter((task) => task.status !== DELETED_STATUS).length;\n if (taskCount >= context.maxTasks) {\n return fail(`task limit of ${context.maxTasks} reached; delete completed tasks first before creating new tasks`);\n }\n\n const blockedBy: number[] = [];\n for (const token of item.blockedBy ?? []) {\n const resolved = resolveDep(context, 'blockedBy', token);\n if (!resolved.ok) return fail(resolved.message);\n const dep = context.tasks.find((task) => task.id === resolved.id);\n if (!dep) return fail(`blockedBy: #${resolved.id} not found`);\n if (dep.status === DELETED_STATUS) return fail(`blockedBy: #${resolved.id} is deleted`);\n if (!blockedBy.includes(resolved.id)) blockedBy.push(resolved.id);\n }\n\n // No cycle check is needed: the id is freshly allocated, so nothing already\n // in the document can point at it yet.\n const created: Task = {\n id: context.nextId,\n subject: item.subject,\n status: item.status ?? 'pending',\n createdAt: now,\n updatedAt: now,\n };\n assignScalars(created, item);\n if (blockedBy.length) created.blockedBy = blockedBy;\n\n context.nextId += 1;\n context.tasks.push(created);\n if (item.ref) context.refIds.set(item.ref, created.id);\n\n return {\n ok: true,\n outcome: {\n index,\n kind: 'created',\n id: created.id,\n subject: created.subject,\n status: created.status,\n ...(item.ref ? { ref: item.ref } : {}),\n ...(blockedBy.length ? { blockedBy } : {}),\n },\n };\n}\n\nfunction applyUpdateItem(context: UpsertContext, item: TaskItemMutation, index: number, now: string): ItemResult {\n const id = item.id as number;\n const at = context.tasks.findIndex((task) => task.id === id);\n if (at === -1) return fail(`#${id} not found`);\n if (item.blockedBy !== undefined) {\n return fail('blockedBy is only for a new entry; use addBlockedBy / removeBlockedBy on an entry that has an id');\n }\n\n const hasMutation =\n item.subject !== undefined ||\n item.description !== undefined ||\n item.activeForm !== undefined ||\n item.status !== undefined ||\n item.owner !== undefined ||\n item.metadata !== undefined ||\n Boolean(item.addBlockedBy?.length) ||\n Boolean(item.removeBlockedBy?.length);\n if (!hasMutation) {\n return fail(\n 'nothing to change: provide at least one of subject, description, activeForm, status, owner, metadata, addBlockedBy, or removeBlockedBy',\n );\n }\n\n const current = context.tasks[at];\n\n // The Task Space overlay commits free text from an inline editor, so a blank\n // subject reaches the reducer as a real update rather than as a missing\n // field. Persisting it would leave an unidentifiable row.\n if (item.subject !== undefined && !item.subject.trim()) return fail('subject must not be blank');\n\n let newStatus = current.status;\n if (item.status !== undefined) {\n if (!isTransitionValid(current.status, item.status)) {\n return fail(`illegal transition ${current.status} -> ${item.status}`);\n }\n newStatus = item.status;\n }\n\n let newBlockedBy = current.blockedBy ? [...current.blockedBy] : [];\n for (const token of item.removeBlockedBy ?? []) {\n const resolved = resolveDep(context, 'removeBlockedBy', token);\n if (!resolved.ok) return fail(resolved.message);\n // Removing an id that is not there is a well-defined no-op, so unlike the\n // add path this deliberately skips the existence check.\n newBlockedBy = newBlockedBy.filter((dep) => dep !== resolved.id);\n }\n for (const token of item.addBlockedBy ?? []) {\n const resolved = resolveDep(context, 'addBlockedBy', token);\n if (!resolved.ok) return fail(resolved.message);\n if (resolved.id === id) return fail(`cannot block #${id} on itself`);\n const dep = context.tasks.find((task) => task.id === resolved.id);\n if (!dep) return fail(`addBlockedBy: #${resolved.id} not found`);\n if (dep.status === DELETED_STATUS) return fail(`addBlockedBy: #${resolved.id} is deleted`);\n if (!newBlockedBy.includes(resolved.id)) newBlockedBy.push(resolved.id);\n }\n\n const updated: Task = { ...current, status: newStatus };\n assignScalars(updated, item);\n if (newBlockedBy.length) updated.blockedBy = newBlockedBy;\n else delete updated.blockedBy;\n\n // The candidate is written before the check because `detectCycle` unions the\n // node's stored edges with the ones passed in: checking against the old array\n // would resurrect an edge `removeBlockedBy` just stripped and reject a\n // remove+add that legitimately breaks a cycle.\n const candidate = [...context.tasks];\n candidate[at] = updated;\n if (item.addBlockedBy?.length && detectCycle(candidate, id, newBlockedBy)) {\n return fail('addBlockedBy would create a cycle in the blockedBy graph');\n }\n\n const changed = taskChanged(current, updated);\n if (changed) updated.updatedAt = now;\n context.tasks = candidate;\n\n return {\n ok: true,\n outcome: changed\n ? { index, kind: 'updated', id, fromStatus: current.status, toStatus: newStatus }\n : { index, kind: 'unchanged', id, status: newStatus },\n };\n}\n\n/**\n * Apply every entry in request order, threading the document.\n *\n * Each entry lands completely or not at all: a create whose dependencies fail\n * is not kept dependency-free, because handing back an unblocked task the\n * caller asked to be blocked is a lie it may immediately act on.\n */\nfunction applyUpsert(document: TaskDocument, items: TaskItemMutation[], now: string, maxTasks: number): ApplyResult {\n const context: UpsertContext = {\n tasks: [...document.tasks],\n nextId: document.nextId,\n maxTasks,\n refIds: new Map(),\n failedRefs: new Map(),\n };\n const outcomes: UpsertItemOutcome[] = [];\n let applied = 0;\n\n for (const [index, item] of items.entries()) {\n const shapeError = checkShape(context, item);\n const result = shapeError\n ? fail(shapeError)\n : item.id === undefined\n ? applyCreateItem(context, item, index, now)\n : applyUpdateItem(context, item, index, now);\n\n if (result.ok) {\n outcomes.push(result.outcome);\n applied += 1;\n continue;\n }\n // A ref whose owner failed must not read as a typo to the entries that\n // depend on it, so the dead ref is recorded rather than left unknown.\n if (item.ref && REF_PATTERN.test(item.ref) && !context.refIds.has(item.ref)) {\n context.failedRefs.set(item.ref, index);\n }\n outcomes.push({\n index,\n kind: 'failed',\n message: result.message,\n ...(item.id === undefined ? {} : { id: item.id }),\n ...(item.ref ? { ref: item.ref } : {}),\n });\n }\n\n return {\n // Nothing applied means nothing to write: returning the original object by\n // reference keeps the caller's write-skip path identical to a hard error.\n document: applied > 0 ? withTasks(document, context.tasks, context.nextId) : document,\n op: { kind: 'upsert', items: outcomes, applied, failed: outcomes.length - applied },\n };\n}\n\n/**\n * Pure reducer: (document, action, params) -> (document, op).\n *\n * All validation is in-line: structural guards plus state-aware checks\n * (transition legality, dangling or deleted blockedBy, self-block, cycles,\n * in-flight delegations). The caller owns persistence and formatting.\n */\nexport function applyTaskMutation(\n document: TaskDocument,\n action: ReducerAction,\n params: TaskMutationParams,\n now: string = new Date().toISOString(),\n maxTasks = DEFAULT_REDUCER_MAX_TASKS,\n): ApplyResult {\n switch (action) {\n case 'upsert': {\n const items = params.tasks;\n if (!Array.isArray(items) || items.length === 0) {\n return errorResult(\n document,\n 'upsert requires a non-empty tasks array, e.g. {\"action\":\"upsert\",\"tasks\":[{\"subject\":\"Write tests\"}]}',\n );\n }\n if (items.length > MAX_UPSERT_ITEMS) {\n return errorResult(\n document,\n `upsert accepts at most ${MAX_UPSERT_ITEMS} entries per call (received ${items.length})`,\n );\n }\n return applyUpsert(document, items, now, maxTasks);\n }\n\n case 'list': {\n return {\n document,\n op: {\n kind: 'list',\n includeDeleted: params.includeDeleted === true,\n ...(params.status !== undefined ? { statusFilter: params.status } : {}),\n },\n };\n }\n\n case 'get': {\n if (params.id === undefined) return errorResult(document, 'id required for get');\n const task = document.tasks.find((candidate) => candidate.id === params.id);\n if (!task) return errorResult(document, `#${params.id} not found`);\n return { document, op: { kind: 'get', task } };\n }\n\n case 'delete': {\n if (params.id === undefined) return errorResult(document, 'id required for delete');\n const index = document.tasks.findIndex((task) => task.id === params.id);\n if (index === -1) return errorResult(document, `#${params.id} not found`);\n const current = document.tasks[index];\n if (current.status === DELETED_STATUS) return errorResult(document, `#${current.id} is already deleted`);\n if (isDelegationActive(current)) {\n return errorResult(document, `#${current.id} has a running delegation — cancel it before deleting`);\n }\n\n const tasks = [...document.tasks];\n tasks[index] = { ...current, status: DELETED_STATUS, updatedAt: now };\n return {\n document: withTasks(document, tasks),\n op: { kind: 'delete', id: current.id, subject: current.subject },\n };\n }\n\n case 'clear': {\n const active = document.tasks.filter(isDelegationActive);\n if (active.length > 0) {\n const ids = active.map((task) => `#${task.id}`).join(', ');\n return errorResult(document, `cannot clear while delegations are running (${ids}) — cancel them first`);\n }\n const count = document.tasks.length;\n return {\n document: withTasks(document, [], 1),\n op: { kind: 'clear', count },\n };\n }\n }\n}\n"],"mappings":"wKAgBA,MAGa,EAAmB,IAOnB,EAAc,gCAiC3B,SAAgB,EAAe,EAAiB,CAC9C,OAAQ,EAAG,KAAX,CACE,IAAK,QACL,IAAK,OACL,IAAK,MACH,MAAO,GACT,IAAK,SACH,OAAO,EAAG,MAAM,KAAM,GAAS,EAAK,OAAS,WAAa,EAAK,OAAS,SAAS,EACnF,IAAK,SACL,IAAK,QACH,MAAO,EACX,CACF,CAGA,SAAgB,EAAoB,EAA6C,CAC/E,OAAO,EAAG,MACP,OAAQ,GAAS,EAAK,OAAS,QAAQ,CAAC,CACxC,IAAK,GAAS,QAAQ,EAAK,MAAM,KAAK,EAAK,SAAS,CAAC,CACrD,KAAK;CAAI,CACd,CAGA,SAAgB,EAAkB,EAAuC,CACvE,OAAO,EAAG,OAAS,SAAW,EAAG,MAAM,GAAK,IAAA,EAC9C,CAEA,SAAS,EAAY,EAAwB,EAA8B,CACzE,MAAO,CAAE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AAG,WAAW,CAEnE,CAEA,IAAK,SAAU,CACb,GAAI,EAAO,KAAO,IAAA,GAAW,OAAO,EAAY,EAAU,wBAAwB,EAClF,IAAM,EAAQ,EAAS,MAAM,UAAW,GAAS,EAAK,KAAO,EAAO,EAAE,EACtE,GAAI,IAAU,GAAI,OAAO,EAAY,EAAU,IAAI,EAAO,GAAG,WAAW,EACxE,IAAM,EAAU,EAAS,MAAM,GAC/B,GAAI,EAAQ,SAAA,UAA2B,OAAO,EAAY,EAAU,IAAI,EAAQ,GAAG,oBAAoB,EACvG,GAAI,EAAmB,CAAO,EAC5B,OAAO,EAAY,EAAU,IAAI,EAAQ,GAAG,sDAAsD,EAGpG,IAAM,EAAQ,CAAC,GAAG,EAAS,KAAK,EAEhC,MADA,GAAM,GAAS,CAAE,GAAG,EAAS,OAAQ,EAAgB,UAAW,CAAI,EAC7D,CACL,SAAU,EAAU,EAAU,CAAK,EACnC,GAAI,CAAE,KAAM,SAAU,GAAI,EAAQ,GAAI,QAAS,EAAQ,OAAQ,CACjE,CACF,CAEA,IAAK,QAAS,CACZ,IAAM,EAAS,EAAS,MAAM,OAAO,CAAkB,EACvD,GAAI,EAAO,OAAS,EAElB,OAAO,EAAY,EAAU,+CADjB,EAAO,IAAK,GAAS,IAAI,EAAK,IAAI,CAAC,CAAC,KAAK,IACyB,EAAE,sBAAsB,EAExG,IAAM,EAAQ,EAAS,MAAM,OAC7B,MAAO,CACL,SAAU,EAAU,EAAU,CAAC,EAAG,CAAC,EACnC,GAAI,CAAE,KAAM,QAAS,OAAM,CAC7B,CACF,CACF,CACF"}
@@ -0,0 +1,2 @@
1
+ const e=`completed`,t=`deleted`;function n(n){let r=n.filter(e=>e.status!==t);return r.length>0&&r.every(t=>t.status===e)}function r(e,t,n){let r=new Map;for(let i of e)i.id===t?r.set(i.id,[...new Set([...i.blockedBy??[],...n])]):r.set(i.id,i.blockedBy?[...i.blockedBy]:[]);let i=new Set,a=new Set,o=e=>{if(i.has(e))return!0;if(a.has(e))return!1;i.add(e);for(let t of r.get(e)??[])if(o(t))return!0;return i.delete(e),a.add(e),!1};for(let e of r.keys())if(o(e))return!0;return!1}function i(e){let t=new Map;for(let n of e)for(let e of n.blockedBy??[]){let r=t.get(e)??[];r.push(n.id),t.set(e,r)}return t}function a(n,r){return(r.blockedBy??[]).filter(r=>{let i=n.find(e=>e.id===r);return i?i.status!==e&&i.status!==t:!1})}function o(e,t){return a(e,t).length>0}exports.deriveBlocks=i,exports.detectCycle=r,exports.isBlocked=o,exports.isTaskListComplete=n,exports.unresolvedBlockers=a;
2
+ //# sourceMappingURL=taskGraph.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"taskGraph.cjs","names":[],"sources":["../../../src/services/store/taskGraph.ts"],"sourcesContent":["import type { Task } from './types.ts';\n\nconst COMPLETED_STATUS: Task['status'] = 'completed';\nconst DELETED_STATUS: Task['status'] = 'deleted';\n\n/** True when a non-empty list has no visible work left to finish. */\nexport function isTaskListComplete(taskList: readonly Task[]): boolean {\n const visible = taskList.filter((task) => task.status !== DELETED_STATUS);\n return visible.length > 0 && visible.every((task) => task.status === COMPLETED_STATUS);\n}\n\n/**\n * Would merging `newBlockedBy` into `taskId`'s dependencies introduce a cycle?\n *\n * Takes the proposed additions explicitly so the reducer can ask the question\n * before mutating anything.\n */\nexport function detectCycle(taskList: readonly Task[], taskId: number, newBlockedBy: readonly number[]): boolean {\n const edges = new Map<number, number[]>();\n for (const task of taskList) {\n if (task.id === taskId) {\n edges.set(task.id, [...new Set([...(task.blockedBy ?? []), ...newBlockedBy])]);\n } else {\n edges.set(task.id, task.blockedBy ? [...task.blockedBy] : []);\n }\n }\n\n const visiting = new Set<number>();\n const visited = new Set<number>();\n const hasCycleFrom = (node: number): boolean => {\n if (visiting.has(node)) return true;\n if (visited.has(node)) return false;\n visiting.add(node);\n for (const next of edges.get(node) ?? []) {\n if (hasCycleFrom(next)) return true;\n }\n visiting.delete(node);\n visited.add(node);\n return false;\n };\n\n for (const node of edges.keys()) {\n if (hasCycleFrom(node)) return true;\n }\n return false;\n}\n\n/** Inverse adjacency: for each task, which tasks list it in their blockedBy. */\nexport function deriveBlocks(taskList: readonly Task[]): Map<number, number[]> {\n const blocks = new Map<number, number[]>();\n for (const task of taskList) {\n for (const dep of task.blockedBy ?? []) {\n const dependents = blocks.get(dep) ?? [];\n dependents.push(task.id);\n blocks.set(dep, dependents);\n }\n }\n return blocks;\n}\n\n/**\n * Blocking dependencies of a task that are not yet resolved.\n *\n * `completed` clears a dependency; `failed` deliberately does not, so a failed\n * delegation keeps its dependents blocked instead of silently releasing work\n * that was never actually finished.\n */\nexport function unresolvedBlockers(taskList: readonly Task[], task: Task): number[] {\n return (task.blockedBy ?? []).filter((dep) => {\n const blocker = taskList.find((candidate) => candidate.id === dep);\n if (!blocker) return false;\n return blocker.status !== COMPLETED_STATUS && blocker.status !== DELETED_STATUS;\n });\n}\n\nexport function isBlocked(taskList: readonly Task[], task: Task): boolean {\n return unresolvedBlockers(taskList, task).length > 0;\n}\n"],"mappings":"AAEA,MAAM,EAAmC,YACnC,EAAiC,UAGvC,SAAgB,EAAmB,EAAoC,CACrE,IAAM,EAAU,EAAS,OAAQ,GAAS,EAAK,SAAW,CAAc,EACxE,OAAO,EAAQ,OAAS,GAAK,EAAQ,MAAO,GAAS,EAAK,SAAW,CAAgB,CACvF,CAQA,SAAgB,EAAY,EAA2B,EAAgB,EAA0C,CAC/G,IAAM,EAAQ,IAAI,IAClB,IAAK,IAAM,KAAQ,EACb,EAAK,KAAO,EACd,EAAM,IAAI,EAAK,GAAI,CAAC,GAAG,IAAI,IAAI,CAAC,GAAI,EAAK,WAAa,CAAC,EAAI,GAAG,CAAY,CAAC,CAAC,CAAC,EAE7E,EAAM,IAAI,EAAK,GAAI,EAAK,UAAY,CAAC,GAAG,EAAK,SAAS,EAAI,CAAC,CAAC,EAIhE,IAAM,EAAW,IAAI,IACf,EAAU,IAAI,IACd,EAAgB,GAA0B,CAC9C,GAAI,EAAS,IAAI,CAAI,EAAG,MAAO,GAC/B,GAAI,EAAQ,IAAI,CAAI,EAAG,MAAO,GAC9B,EAAS,IAAI,CAAI,EACjB,IAAK,IAAM,KAAQ,EAAM,IAAI,CAAI,GAAK,CAAC,EACrC,GAAI,EAAa,CAAI,EAAG,MAAO,GAIjC,OAFA,EAAS,OAAO,CAAI,EACpB,EAAQ,IAAI,CAAI,EACT,EACT,EAEA,IAAK,IAAM,KAAQ,EAAM,KAAK,EAC5B,GAAI,EAAa,CAAI,EAAG,MAAO,GAEjC,MAAO,EACT,CAGA,SAAgB,EAAa,EAAkD,CAC7E,IAAM,EAAS,IAAI,IACnB,IAAK,IAAM,KAAQ,EACjB,IAAK,IAAM,KAAO,EAAK,WAAa,CAAC,EAAG,CACtC,IAAM,EAAa,EAAO,IAAI,CAAG,GAAK,CAAC,EACvC,EAAW,KAAK,EAAK,EAAE,EACvB,EAAO,IAAI,EAAK,CAAU,CAC5B,CAEF,OAAO,CACT,CASA,SAAgB,EAAmB,EAA2B,EAAsB,CAClF,OAAQ,EAAK,WAAa,CAAC,EAAA,CAAG,OAAQ,GAAQ,CAC5C,IAAM,EAAU,EAAS,KAAM,GAAc,EAAU,KAAO,CAAG,EAEjE,OADK,EACE,EAAQ,SAAW,GAAoB,EAAQ,SAAW,EAD5C,EAEvB,CAAC,CACH,CAEA,SAAgB,EAAU,EAA2B,EAAqB,CACxE,OAAO,EAAmB,EAAU,CAAI,CAAC,CAAC,OAAS,CACrD"}
@@ -0,0 +1,25 @@
1
+ import { Task } from "./types.cjs";
2
+ //#region src/services/store/taskGraph.d.ts
3
+ /** True when a non-empty list has no visible work left to finish. */
4
+ declare function isTaskListComplete(taskList: readonly Task[]): boolean;
5
+ /**
6
+ * Would merging `newBlockedBy` into `taskId`'s dependencies introduce a cycle?
7
+ *
8
+ * Takes the proposed additions explicitly so the reducer can ask the question
9
+ * before mutating anything.
10
+ */
11
+ declare function detectCycle(taskList: readonly Task[], taskId: number, newBlockedBy: readonly number[]): boolean;
12
+ /** Inverse adjacency: for each task, which tasks list it in their blockedBy. */
13
+ declare function deriveBlocks(taskList: readonly Task[]): Map<number, number[]>;
14
+ /**
15
+ * Blocking dependencies of a task that are not yet resolved.
16
+ *
17
+ * `completed` clears a dependency; `failed` deliberately does not, so a failed
18
+ * delegation keeps its dependents blocked instead of silently releasing work
19
+ * that was never actually finished.
20
+ */
21
+ declare function unresolvedBlockers(taskList: readonly Task[], task: Task): number[];
22
+ declare function isBlocked(taskList: readonly Task[], task: Task): boolean;
23
+ //#endregion
24
+ export { deriveBlocks, detectCycle, isBlocked, isTaskListComplete, unresolvedBlockers };
25
+ //# sourceMappingURL=taskGraph.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"taskGraph.d.cts","names":[],"sources":["../../../src/services/store/taskGraph.ts"],"mappings":";;;iBAMgB,mBAAmB,mBAAmB;;;;;;;iBAWtC,YAAY,mBAAmB,QAAQ,gBAAgB;;iBA+BvD,aAAa,mBAAmB,SAAS;;;;;;;;iBAmBzC,mBAAmB,mBAAmB,QAAQ,MAAM;iBAQpD,UAAU,mBAAmB,QAAQ,MAAM"}
@@ -0,0 +1,25 @@
1
+ import { Task } from "./types.mjs";
2
+ //#region src/services/store/taskGraph.d.ts
3
+ /** True when a non-empty list has no visible work left to finish. */
4
+ declare function isTaskListComplete(taskList: readonly Task[]): boolean;
5
+ /**
6
+ * Would merging `newBlockedBy` into `taskId`'s dependencies introduce a cycle?
7
+ *
8
+ * Takes the proposed additions explicitly so the reducer can ask the question
9
+ * before mutating anything.
10
+ */
11
+ declare function detectCycle(taskList: readonly Task[], taskId: number, newBlockedBy: readonly number[]): boolean;
12
+ /** Inverse adjacency: for each task, which tasks list it in their blockedBy. */
13
+ declare function deriveBlocks(taskList: readonly Task[]): Map<number, number[]>;
14
+ /**
15
+ * Blocking dependencies of a task that are not yet resolved.
16
+ *
17
+ * `completed` clears a dependency; `failed` deliberately does not, so a failed
18
+ * delegation keeps its dependents blocked instead of silently releasing work
19
+ * that was never actually finished.
20
+ */
21
+ declare function unresolvedBlockers(taskList: readonly Task[], task: Task): number[];
22
+ declare function isBlocked(taskList: readonly Task[], task: Task): boolean;
23
+ //#endregion
24
+ export { deriveBlocks, detectCycle, isBlocked, isTaskListComplete, unresolvedBlockers };
25
+ //# sourceMappingURL=taskGraph.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"taskGraph.d.mts","names":[],"sources":["../../../src/services/store/taskGraph.ts"],"mappings":";;;iBAMgB,mBAAmB,mBAAmB;;;;;;;iBAWtC,YAAY,mBAAmB,QAAQ,gBAAgB;;iBA+BvD,aAAa,mBAAmB,SAAS;;;;;;;;iBAmBzC,mBAAmB,mBAAmB,QAAQ,MAAM;iBAQpD,UAAU,mBAAmB,QAAQ,MAAM"}
@@ -0,0 +1,2 @@
1
+ const e=`completed`,t=`deleted`;function n(n){let r=n.filter(e=>e.status!==t);return r.length>0&&r.every(t=>t.status===e)}function r(e,t,n){let r=new Map;for(let i of e)i.id===t?r.set(i.id,[...new Set([...i.blockedBy??[],...n])]):r.set(i.id,i.blockedBy?[...i.blockedBy]:[]);let i=new Set,a=new Set,o=e=>{if(i.has(e))return!0;if(a.has(e))return!1;i.add(e);for(let t of r.get(e)??[])if(o(t))return!0;return i.delete(e),a.add(e),!1};for(let e of r.keys())if(o(e))return!0;return!1}function i(e){let t=new Map;for(let n of e)for(let e of n.blockedBy??[]){let r=t.get(e)??[];r.push(n.id),t.set(e,r)}return t}function a(n,r){return(r.blockedBy??[]).filter(r=>{let i=n.find(e=>e.id===r);return i?i.status!==e&&i.status!==t:!1})}function o(e,t){return a(e,t).length>0}export{i as deriveBlocks,r as detectCycle,o as isBlocked,n as isTaskListComplete,a as unresolvedBlockers};
2
+ //# sourceMappingURL=taskGraph.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"taskGraph.mjs","names":[],"sources":["../../../src/services/store/taskGraph.ts"],"sourcesContent":["import type { Task } from './types.ts';\n\nconst COMPLETED_STATUS: Task['status'] = 'completed';\nconst DELETED_STATUS: Task['status'] = 'deleted';\n\n/** True when a non-empty list has no visible work left to finish. */\nexport function isTaskListComplete(taskList: readonly Task[]): boolean {\n const visible = taskList.filter((task) => task.status !== DELETED_STATUS);\n return visible.length > 0 && visible.every((task) => task.status === COMPLETED_STATUS);\n}\n\n/**\n * Would merging `newBlockedBy` into `taskId`'s dependencies introduce a cycle?\n *\n * Takes the proposed additions explicitly so the reducer can ask the question\n * before mutating anything.\n */\nexport function detectCycle(taskList: readonly Task[], taskId: number, newBlockedBy: readonly number[]): boolean {\n const edges = new Map<number, number[]>();\n for (const task of taskList) {\n if (task.id === taskId) {\n edges.set(task.id, [...new Set([...(task.blockedBy ?? []), ...newBlockedBy])]);\n } else {\n edges.set(task.id, task.blockedBy ? [...task.blockedBy] : []);\n }\n }\n\n const visiting = new Set<number>();\n const visited = new Set<number>();\n const hasCycleFrom = (node: number): boolean => {\n if (visiting.has(node)) return true;\n if (visited.has(node)) return false;\n visiting.add(node);\n for (const next of edges.get(node) ?? []) {\n if (hasCycleFrom(next)) return true;\n }\n visiting.delete(node);\n visited.add(node);\n return false;\n };\n\n for (const node of edges.keys()) {\n if (hasCycleFrom(node)) return true;\n }\n return false;\n}\n\n/** Inverse adjacency: for each task, which tasks list it in their blockedBy. */\nexport function deriveBlocks(taskList: readonly Task[]): Map<number, number[]> {\n const blocks = new Map<number, number[]>();\n for (const task of taskList) {\n for (const dep of task.blockedBy ?? []) {\n const dependents = blocks.get(dep) ?? [];\n dependents.push(task.id);\n blocks.set(dep, dependents);\n }\n }\n return blocks;\n}\n\n/**\n * Blocking dependencies of a task that are not yet resolved.\n *\n * `completed` clears a dependency; `failed` deliberately does not, so a failed\n * delegation keeps its dependents blocked instead of silently releasing work\n * that was never actually finished.\n */\nexport function unresolvedBlockers(taskList: readonly Task[], task: Task): number[] {\n return (task.blockedBy ?? []).filter((dep) => {\n const blocker = taskList.find((candidate) => candidate.id === dep);\n if (!blocker) return false;\n return blocker.status !== COMPLETED_STATUS && blocker.status !== DELETED_STATUS;\n });\n}\n\nexport function isBlocked(taskList: readonly Task[], task: Task): boolean {\n return unresolvedBlockers(taskList, task).length > 0;\n}\n"],"mappings":"AAEA,MAAM,EAAmC,YACnC,EAAiC,UAGvC,SAAgB,EAAmB,EAAoC,CACrE,IAAM,EAAU,EAAS,OAAQ,GAAS,EAAK,SAAW,CAAc,EACxE,OAAO,EAAQ,OAAS,GAAK,EAAQ,MAAO,GAAS,EAAK,SAAW,CAAgB,CACvF,CAQA,SAAgB,EAAY,EAA2B,EAAgB,EAA0C,CAC/G,IAAM,EAAQ,IAAI,IAClB,IAAK,IAAM,KAAQ,EACb,EAAK,KAAO,EACd,EAAM,IAAI,EAAK,GAAI,CAAC,GAAG,IAAI,IAAI,CAAC,GAAI,EAAK,WAAa,CAAC,EAAI,GAAG,CAAY,CAAC,CAAC,CAAC,EAE7E,EAAM,IAAI,EAAK,GAAI,EAAK,UAAY,CAAC,GAAG,EAAK,SAAS,EAAI,CAAC,CAAC,EAIhE,IAAM,EAAW,IAAI,IACf,EAAU,IAAI,IACd,EAAgB,GAA0B,CAC9C,GAAI,EAAS,IAAI,CAAI,EAAG,MAAO,GAC/B,GAAI,EAAQ,IAAI,CAAI,EAAG,MAAO,GAC9B,EAAS,IAAI,CAAI,EACjB,IAAK,IAAM,KAAQ,EAAM,IAAI,CAAI,GAAK,CAAC,EACrC,GAAI,EAAa,CAAI,EAAG,MAAO,GAIjC,OAFA,EAAS,OAAO,CAAI,EACpB,EAAQ,IAAI,CAAI,EACT,EACT,EAEA,IAAK,IAAM,KAAQ,EAAM,KAAK,EAC5B,GAAI,EAAa,CAAI,EAAG,MAAO,GAEjC,MAAO,EACT,CAGA,SAAgB,EAAa,EAAkD,CAC7E,IAAM,EAAS,IAAI,IACnB,IAAK,IAAM,KAAQ,EACjB,IAAK,IAAM,KAAO,EAAK,WAAa,CAAC,EAAG,CACtC,IAAM,EAAa,EAAO,IAAI,CAAG,GAAK,CAAC,EACvC,EAAW,KAAK,EAAK,EAAE,EACvB,EAAO,IAAI,EAAK,CAAU,CAC5B,CAEF,OAAO,CACT,CASA,SAAgB,EAAmB,EAA2B,EAAsB,CAClF,OAAQ,EAAK,WAAa,CAAC,EAAA,CAAG,OAAQ,GAAQ,CAC5C,IAAM,EAAU,EAAS,KAAM,GAAc,EAAU,KAAO,CAAG,EAEjE,OADK,EACE,EAAQ,SAAW,GAAoB,EAAQ,SAAW,EAD5C,EAEvB,CAAC,CACH,CAEA,SAAgB,EAAU,EAA2B,EAAqB,CACxE,OAAO,EAAmB,EAAU,CAAI,CAAC,CAAC,OAAS,CACrD"}
@@ -0,0 +1 @@
1
+ const e=require("../../adapters/store/taskStore.cjs");exports.TaskStore=e.TaskStore;
@@ -0,0 +1,2 @@
1
+ import { TaskStore, TaskStoreCommitListener, TaskStoreOptions } from "../../adapters/store/taskStore.cjs";
2
+ export { TaskStore, type TaskStoreCommitListener, type TaskStoreOptions };
@@ -0,0 +1,2 @@
1
+ import { TaskStore, TaskStoreCommitListener, TaskStoreOptions } from "../../adapters/store/taskStore.mjs";
2
+ export { TaskStore, type TaskStoreCommitListener, type TaskStoreOptions };
@@ -0,0 +1 @@
1
+ import{TaskStore as e}from"../../adapters/store/taskStore.mjs";export{e as TaskStore};
@@ -0,0 +1,2 @@
1
+ function e(){return{version:1,rev:0,nextId:1,tasks:[]}}function t(e){let t=e.delegation?.state;return t===`requested`||t===`running`}exports.DELETED_STATUS=`deleted`,exports.STORE_SCHEMA_VERSION=1,exports.emptyDocument=e,exports.isDelegationActive=t;
2
+ //# sourceMappingURL=types.cjs.map