@agimon-ai/doompi-task 0.0.1-alpha.7 → 0.0.1-alpha.71

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 (439) hide show
  1. package/README.md +114 -15
  2. package/dist/api-contracts.cjs +1 -0
  3. package/dist/api-contracts.d.cts +2 -0
  4. package/dist/api-contracts.d.mts +2 -0
  5. package/dist/api-contracts.mjs +1 -0
  6. package/dist/commands.cjs +1 -2
  7. package/dist/commands.d.cts +2 -14
  8. package/dist/commands.d.mts +2 -14
  9. package/dist/commands.mjs +1 -2
  10. package/dist/config.cjs +1 -2
  11. package/dist/config.d.cts +2 -38
  12. package/dist/config.d.mts +2 -38
  13. package/dist/config.mjs +1 -2
  14. package/dist/constants/promptGuidelines.cjs +2 -0
  15. package/dist/constants/promptGuidelines.cjs.map +1 -0
  16. package/dist/constants/promptGuidelines.d.cts +13 -0
  17. package/dist/constants/promptGuidelines.d.cts.map +1 -0
  18. package/dist/constants/promptGuidelines.d.mts +13 -0
  19. package/dist/constants/promptGuidelines.d.mts.map +1 -0
  20. package/dist/constants/promptGuidelines.mjs +2 -0
  21. package/dist/constants/promptGuidelines.mjs.map +1 -0
  22. package/dist/constants/task.cjs +2 -0
  23. package/dist/constants/task.cjs.map +1 -0
  24. package/dist/constants/task.d.cts +4 -0
  25. package/dist/constants/task.d.cts.map +1 -0
  26. package/dist/constants/task.d.mts +4 -0
  27. package/dist/constants/task.d.mts.map +1 -0
  28. package/dist/constants/task.mjs +2 -0
  29. package/dist/constants/task.mjs.map +1 -0
  30. package/dist/controllers/tasksCommand.cjs +2 -0
  31. package/dist/controllers/tasksCommand.cjs.map +1 -0
  32. package/dist/controllers/tasksCommand.d.cts +15 -0
  33. package/dist/controllers/tasksCommand.d.cts.map +1 -0
  34. package/dist/controllers/tasksCommand.d.mts +15 -0
  35. package/dist/controllers/tasksCommand.d.mts.map +1 -0
  36. package/dist/controllers/tasksCommand.mjs +2 -0
  37. package/dist/controllers/tasksCommand.mjs.map +1 -0
  38. package/dist/controllers/webTasksChannel.cjs +2 -0
  39. package/dist/controllers/webTasksChannel.cjs.map +1 -0
  40. package/dist/controllers/webTasksChannel.mjs +2 -0
  41. package/dist/controllers/webTasksChannel.mjs.map +1 -0
  42. package/dist/delegation-manager.cjs +1 -0
  43. package/dist/delegation-manager.d.cts +3 -0
  44. package/dist/delegation-manager.d.mts +3 -0
  45. package/dist/delegation-manager.mjs +1 -0
  46. package/dist/extensions/pi.cjs +2 -1
  47. package/dist/extensions/pi.cjs.map +1 -1
  48. package/dist/extensions/pi.d.cts +6 -2
  49. package/dist/extensions/pi.d.cts.map +1 -0
  50. package/dist/extensions/pi.d.mts +6 -2
  51. package/dist/extensions/pi.d.mts.map +1 -0
  52. package/dist/extensions/pi.mjs +2 -1
  53. package/dist/extensions/pi.mjs.map +1 -1
  54. package/dist/extensions/server.cjs +2 -0
  55. package/dist/extensions/server.cjs.map +1 -0
  56. package/dist/extensions/server.d.cts +5 -0
  57. package/dist/extensions/server.d.cts.map +1 -0
  58. package/dist/extensions/server.d.mts +5 -0
  59. package/dist/extensions/server.d.mts.map +1 -0
  60. package/dist/extensions/server.mjs +2 -0
  61. package/dist/extensions/server.mjs.map +1 -0
  62. package/dist/index.cjs +1 -1
  63. package/dist/index.d.cts +15 -14
  64. package/dist/index.d.mts +15 -14
  65. package/dist/index.mjs +1 -1
  66. package/dist/logSinkTelemetry.cjs +1 -2
  67. package/dist/logSinkTelemetry.d.cts +3 -51
  68. package/dist/logSinkTelemetry.d.mts +3 -51
  69. package/dist/logSinkTelemetry.mjs +1 -2
  70. package/dist/models/task.cjs +2 -0
  71. package/dist/models/task.cjs.map +1 -0
  72. package/dist/{store/types.d.cts → models/task.d.cts} +41 -30
  73. package/dist/models/task.d.cts.map +1 -0
  74. package/dist/{store/types.d.mts → models/task.d.mts} +41 -30
  75. package/dist/models/task.d.mts.map +1 -0
  76. package/dist/{store/types.mjs → models/task.mjs} +1 -1
  77. package/dist/models/task.mjs.map +1 -0
  78. package/dist/models/taskGraph.cjs +2 -0
  79. package/dist/models/taskGraph.cjs.map +1 -0
  80. package/dist/{store → models}/taskGraph.d.cts +7 -8
  81. package/dist/models/taskGraph.d.cts.map +1 -0
  82. package/dist/{store → models}/taskGraph.d.mts +7 -8
  83. package/dist/models/taskGraph.d.mts.map +1 -0
  84. package/dist/models/taskGraph.mjs.map +1 -0
  85. package/dist/schemas/apiContracts.cjs +2 -0
  86. package/dist/schemas/apiContracts.cjs.map +1 -0
  87. package/dist/schemas/apiContracts.d.cts +53 -0
  88. package/dist/schemas/apiContracts.d.cts.map +1 -0
  89. package/dist/schemas/apiContracts.d.mts +53 -0
  90. package/dist/schemas/apiContracts.d.mts.map +1 -0
  91. package/dist/schemas/apiContracts.mjs +2 -0
  92. package/dist/schemas/apiContracts.mjs.map +1 -0
  93. package/dist/schemas/task.cjs +2 -0
  94. package/dist/schemas/task.cjs.map +1 -0
  95. package/dist/{tool/schema.d.cts → schemas/task.d.cts} +46 -29
  96. package/dist/schemas/task.d.cts.map +1 -0
  97. package/dist/{tool/schema.d.mts → schemas/task.d.mts} +46 -29
  98. package/dist/schemas/task.d.mts.map +1 -0
  99. package/dist/schemas/task.mjs +2 -0
  100. package/dist/schemas/task.mjs.map +1 -0
  101. package/dist/services/config/index.cjs +2 -0
  102. package/dist/services/config/index.cjs.map +1 -0
  103. package/dist/services/config/index.d.cts +42 -0
  104. package/dist/services/config/index.d.cts.map +1 -0
  105. package/dist/services/config/index.d.mts +42 -0
  106. package/dist/services/config/index.d.mts.map +1 -0
  107. package/dist/services/config/index.mjs +2 -0
  108. package/dist/services/config/index.mjs.map +1 -0
  109. package/dist/services/contextContribution/index.cjs +3 -0
  110. package/dist/services/contextContribution/index.cjs.map +1 -0
  111. package/dist/services/contextContribution/index.mjs +3 -0
  112. package/dist/services/contextContribution/index.mjs.map +1 -0
  113. package/dist/services/delegation/index.cjs +6 -0
  114. package/dist/services/delegation/index.cjs.map +1 -0
  115. package/dist/{delegation/manager.d.cts → services/delegation/index.d.cts} +52 -49
  116. package/dist/services/delegation/index.d.cts.map +1 -0
  117. package/dist/{delegation/manager.d.mts → services/delegation/index.d.mts} +52 -49
  118. package/dist/services/delegation/index.d.mts.map +1 -0
  119. package/dist/services/delegation/index.mjs +6 -0
  120. package/dist/services/delegation/index.mjs.map +1 -0
  121. package/dist/services/delegationPlatform/index.cjs +2 -0
  122. package/dist/services/delegationPlatform/index.cjs.map +1 -0
  123. package/dist/services/delegationPlatform/index.mjs +2 -0
  124. package/dist/services/delegationPlatform/index.mjs.map +1 -0
  125. package/dist/services/invariants/index.cjs +2 -0
  126. package/dist/services/invariants/index.cjs.map +1 -0
  127. package/dist/services/invariants/index.d.cts +23 -0
  128. package/dist/services/invariants/index.d.cts.map +1 -0
  129. package/dist/services/invariants/index.d.mts +23 -0
  130. package/dist/services/invariants/index.d.mts.map +1 -0
  131. package/dist/services/invariants/index.mjs +2 -0
  132. package/dist/services/invariants/index.mjs.map +1 -0
  133. package/dist/services/logSinkTelemetry/index.cjs +2 -0
  134. package/dist/services/logSinkTelemetry/index.cjs.map +1 -0
  135. package/dist/services/logSinkTelemetry/index.d.cts +23 -0
  136. package/dist/services/logSinkTelemetry/index.d.cts.map +1 -0
  137. package/dist/services/logSinkTelemetry/index.d.mts +23 -0
  138. package/dist/services/logSinkTelemetry/index.d.mts.map +1 -0
  139. package/dist/services/logSinkTelemetry/index.mjs +2 -0
  140. package/dist/services/logSinkTelemetry/index.mjs.map +1 -0
  141. package/dist/services/paths/index.cjs +2 -0
  142. package/dist/services/paths/index.cjs.map +1 -0
  143. package/dist/services/paths/index.d.cts +25 -0
  144. package/dist/services/paths/index.d.cts.map +1 -0
  145. package/dist/services/paths/index.d.mts +25 -0
  146. package/dist/services/paths/index.d.mts.map +1 -0
  147. package/dist/services/paths/index.mjs +2 -0
  148. package/dist/services/paths/index.mjs.map +1 -0
  149. package/dist/services/processLiveness/index.cjs +2 -0
  150. package/dist/services/processLiveness/index.cjs.map +1 -0
  151. package/dist/{store/processLiveness.d.cts → services/processLiveness/index.d.cts} +3 -4
  152. package/dist/services/processLiveness/index.d.cts.map +1 -0
  153. package/dist/{store/processLiveness.d.mts → services/processLiveness/index.d.mts} +3 -4
  154. package/dist/services/processLiveness/index.d.mts.map +1 -0
  155. package/dist/{store/processLiveness.mjs → services/processLiveness/index.mjs} +1 -1
  156. package/dist/services/processLiveness/index.mjs.map +1 -0
  157. package/dist/services/reconcile/index.cjs +2 -0
  158. package/dist/services/reconcile/index.cjs.map +1 -0
  159. package/dist/{store/reconcile.d.cts → services/reconcile/index.d.cts} +8 -9
  160. package/dist/services/reconcile/index.d.cts.map +1 -0
  161. package/dist/{store/reconcile.d.mts → services/reconcile/index.d.mts} +8 -9
  162. package/dist/services/reconcile/index.d.mts.map +1 -0
  163. package/dist/services/reconcile/index.mjs +2 -0
  164. package/dist/services/reconcile/index.mjs.map +1 -0
  165. package/dist/services/reducer/index.cjs +3 -0
  166. package/dist/services/reducer/index.cjs.map +1 -0
  167. package/dist/{store/reducer.d.cts → services/reducer/index.d.cts} +12 -13
  168. package/dist/services/reducer/index.d.cts.map +1 -0
  169. package/dist/{store/reducer.d.mts → services/reducer/index.d.mts} +12 -13
  170. package/dist/services/reducer/index.d.mts.map +1 -0
  171. package/dist/services/reducer/index.mjs +3 -0
  172. package/dist/services/reducer/index.mjs.map +1 -0
  173. package/dist/services/taskNarration/index.cjs +2 -0
  174. package/dist/services/taskNarration/index.cjs.map +1 -0
  175. package/dist/services/taskNarration/index.mjs +2 -0
  176. package/dist/services/taskNarration/index.mjs.map +1 -0
  177. package/dist/services/taskResult/index.cjs +7 -0
  178. package/dist/services/taskResult/index.cjs.map +1 -0
  179. package/dist/services/taskResult/index.d.cts +50 -0
  180. package/dist/services/taskResult/index.d.cts.map +1 -0
  181. package/dist/services/taskResult/index.d.mts +50 -0
  182. package/dist/services/taskResult/index.d.mts.map +1 -0
  183. package/dist/services/taskResult/index.mjs +7 -0
  184. package/dist/services/taskResult/index.mjs.map +1 -0
  185. package/dist/services/taskStore/index.cjs +2 -0
  186. package/dist/services/taskStore/index.cjs.map +1 -0
  187. package/dist/{store/taskStore.d.cts → services/taskStore/index.d.cts} +17 -25
  188. package/dist/services/taskStore/index.d.cts.map +1 -0
  189. package/dist/{store/taskStore.d.mts → services/taskStore/index.d.mts} +17 -25
  190. package/dist/services/taskStore/index.d.mts.map +1 -0
  191. package/dist/services/taskStore/index.mjs +2 -0
  192. package/dist/services/taskStore/index.mjs.map +1 -0
  193. package/dist/store-invariants.cjs +1 -0
  194. package/dist/store-invariants.d.cts +2 -0
  195. package/dist/store-invariants.d.mts +2 -0
  196. package/dist/store-invariants.mjs +1 -0
  197. package/dist/store-paths.cjs +1 -0
  198. package/dist/store-paths.d.cts +2 -0
  199. package/dist/store-paths.d.mts +2 -0
  200. package/dist/store-paths.mjs +1 -0
  201. package/dist/store-process-liveness.cjs +1 -0
  202. package/dist/store-process-liveness.d.cts +2 -0
  203. package/dist/store-process-liveness.d.mts +2 -0
  204. package/dist/store-process-liveness.mjs +1 -0
  205. package/dist/store-reconcile.cjs +1 -0
  206. package/dist/store-reconcile.d.cts +2 -0
  207. package/dist/store-reconcile.d.mts +2 -0
  208. package/dist/store-reconcile.mjs +1 -0
  209. package/dist/store-reducer.cjs +1 -0
  210. package/dist/store-reducer.d.cts +2 -0
  211. package/dist/store-reducer.d.mts +2 -0
  212. package/dist/store-reducer.mjs +1 -0
  213. package/dist/store-task-graph.cjs +1 -0
  214. package/dist/store-task-graph.d.cts +2 -0
  215. package/dist/store-task-graph.d.mts +2 -0
  216. package/dist/store-task-graph.mjs +1 -0
  217. package/dist/store-task-store.cjs +1 -0
  218. package/dist/store-task-store.d.cts +2 -0
  219. package/dist/store-task-store.d.mts +2 -0
  220. package/dist/store-task-store.mjs +1 -0
  221. package/dist/store-types.cjs +1 -0
  222. package/dist/store-types.d.cts +2 -0
  223. package/dist/store-types.d.mts +2 -0
  224. package/dist/store-types.mjs +1 -0
  225. package/dist/tool-prompt-guidelines.cjs +1 -0
  226. package/dist/tool-prompt-guidelines.d.cts +2 -0
  227. package/dist/tool-prompt-guidelines.d.mts +2 -0
  228. package/dist/tool-prompt-guidelines.mjs +1 -0
  229. package/dist/tool-response-envelope.cjs +1 -0
  230. package/dist/tool-response-envelope.d.cts +2 -0
  231. package/dist/tool-response-envelope.d.mts +2 -0
  232. package/dist/tool-response-envelope.mjs +1 -0
  233. package/dist/tool-schema.cjs +1 -0
  234. package/dist/tool-schema.d.cts +3 -0
  235. package/dist/tool-schema.d.mts +3 -0
  236. package/dist/tool-schema.mjs +1 -0
  237. package/dist/tool-task-tool.cjs +1 -0
  238. package/dist/tool-task-tool.d.cts +3 -0
  239. package/dist/tool-task-tool.d.mts +3 -0
  240. package/dist/tool-task-tool.mjs +1 -0
  241. package/dist/tools/task.cjs +3 -0
  242. package/dist/tools/task.cjs.map +1 -0
  243. package/dist/tools/task.d.cts +22 -0
  244. package/dist/tools/task.d.cts.map +1 -0
  245. package/dist/tools/task.d.mts +22 -0
  246. package/dist/tools/task.d.mts.map +1 -0
  247. package/dist/tools/task.mjs +3 -0
  248. package/dist/tools/task.mjs.map +1 -0
  249. package/dist/tui/format.cjs +3 -3
  250. package/dist/tui/format.cjs.map +1 -1
  251. package/dist/tui/format.d.cts +19 -20
  252. package/dist/tui/format.d.cts.map +1 -1
  253. package/dist/tui/format.d.mts +19 -20
  254. package/dist/tui/format.d.mts.map +1 -1
  255. package/dist/tui/format.mjs +3 -3
  256. package/dist/tui/format.mjs.map +1 -1
  257. package/dist/tui/selectors.cjs +1 -1
  258. package/dist/tui/selectors.cjs.map +1 -1
  259. package/dist/tui/selectors.d.cts +20 -14
  260. package/dist/tui/selectors.d.cts.map +1 -1
  261. package/dist/tui/selectors.d.mts +20 -14
  262. package/dist/tui/selectors.d.mts.map +1 -1
  263. package/dist/tui/selectors.mjs +1 -1
  264. package/dist/tui/selectors.mjs.map +1 -1
  265. package/dist/tui/taskOverlay.cjs +1 -1
  266. package/dist/tui/taskOverlay.cjs.map +1 -1
  267. package/dist/tui/taskOverlay.d.cts +4 -5
  268. package/dist/tui/taskOverlay.d.cts.map +1 -1
  269. package/dist/tui/taskOverlay.d.mts +4 -5
  270. package/dist/tui/taskOverlay.d.mts.map +1 -1
  271. package/dist/tui/taskOverlay.mjs +1 -1
  272. package/dist/tui/taskOverlay.mjs.map +1 -1
  273. package/dist/tui/taskSpace.cjs +3 -3
  274. package/dist/tui/taskSpace.cjs.map +1 -1
  275. package/dist/tui/taskSpace.d.cts +9 -10
  276. package/dist/tui/taskSpace.d.cts.map +1 -1
  277. package/dist/tui/taskSpace.d.mts +9 -10
  278. package/dist/tui/taskSpace.d.mts.map +1 -1
  279. package/dist/tui/taskSpace.mjs +3 -3
  280. package/dist/tui/taskSpace.mjs.map +1 -1
  281. package/dist/tui-format.cjs +1 -0
  282. package/dist/tui-format.d.cts +2 -0
  283. package/dist/tui-format.d.mts +2 -0
  284. package/dist/tui-format.mjs +1 -0
  285. package/dist/tui-selectors.cjs +1 -0
  286. package/dist/tui-selectors.d.cts +2 -0
  287. package/dist/tui-selectors.d.mts +2 -0
  288. package/dist/tui-selectors.mjs +1 -0
  289. package/dist/tui-task-overlay.cjs +1 -0
  290. package/dist/tui-task-overlay.d.cts +2 -0
  291. package/dist/tui-task-overlay.d.mts +2 -0
  292. package/dist/tui-task-overlay.mjs +1 -0
  293. package/dist/tui-task-space.cjs +1 -0
  294. package/dist/tui-task-space.d.cts +2 -0
  295. package/dist/tui-task-space.d.mts +2 -0
  296. package/dist/tui-task-space.mjs +1 -0
  297. package/dist/types/delegation.cjs +2 -0
  298. package/dist/types/delegation.cjs.map +1 -0
  299. package/dist/types/delegation.d.cts +5 -0
  300. package/dist/types/delegation.d.cts.map +1 -0
  301. package/dist/types/delegation.d.mts +5 -0
  302. package/dist/types/delegation.d.mts.map +1 -0
  303. package/dist/types/delegation.mjs +2 -0
  304. package/dist/types/delegation.mjs.map +1 -0
  305. package/dist/types/telemetry.cjs +2 -0
  306. package/dist/types/telemetry.cjs.map +1 -0
  307. package/dist/types/telemetry.d.cts +35 -0
  308. package/dist/types/telemetry.d.cts.map +1 -0
  309. package/dist/types/telemetry.d.mts +35 -0
  310. package/dist/types/telemetry.d.mts.map +1 -0
  311. package/dist/types/telemetry.mjs +2 -0
  312. package/dist/types/telemetry.mjs.map +1 -0
  313. package/dist/types/webTasks.cjs +2 -0
  314. package/dist/types/webTasks.cjs.map +1 -0
  315. package/dist/types/webTasks.mjs +2 -0
  316. package/dist/types/webTasks.mjs.map +1 -0
  317. package/package.json +158 -109
  318. package/src/extensions/web.ts +18 -0
  319. package/src/types/webTasks.ts +24 -0
  320. package/src/web/components/TaskDetailDialog.tsx +251 -0
  321. package/src/web/components/TaskToolMessage.tsx +120 -0
  322. package/src/web/components/TasksActivitySection.tsx +200 -0
  323. package/src/web/lib/taskToolFormat.ts +330 -0
  324. package/src/web/stores/tasksStore.ts +114 -0
  325. package/src/web/tsconfig.json +23 -0
  326. package/dist/commands.cjs.map +0 -1
  327. package/dist/commands.d.cts.map +0 -1
  328. package/dist/commands.d.mts.map +0 -1
  329. package/dist/commands.mjs.map +0 -1
  330. package/dist/config.cjs.map +0 -1
  331. package/dist/config.d.cts.map +0 -1
  332. package/dist/config.d.mts.map +0 -1
  333. package/dist/config.mjs.map +0 -1
  334. package/dist/delegation/manager.cjs +0 -6
  335. package/dist/delegation/manager.cjs.map +0 -1
  336. package/dist/delegation/manager.d.cts.map +0 -1
  337. package/dist/delegation/manager.d.mts.map +0 -1
  338. package/dist/delegation/manager.mjs +0 -6
  339. package/dist/delegation/manager.mjs.map +0 -1
  340. package/dist/extension.cjs +0 -3
  341. package/dist/extension.cjs.map +0 -1
  342. package/dist/extension.d.cts +0 -12
  343. package/dist/extension.d.cts.map +0 -1
  344. package/dist/extension.d.mts +0 -12
  345. package/dist/extension.d.mts.map +0 -1
  346. package/dist/extension.mjs +0 -3
  347. package/dist/extension.mjs.map +0 -1
  348. package/dist/extensions/doom.cjs +0 -2
  349. package/dist/extensions/doom.cjs.map +0 -1
  350. package/dist/extensions/doom.d.cts +0 -6
  351. package/dist/extensions/doom.d.cts.map +0 -1
  352. package/dist/extensions/doom.d.mts +0 -7
  353. package/dist/extensions/doom.d.mts.map +0 -1
  354. package/dist/extensions/doom.mjs +0 -2
  355. package/dist/extensions/doom.mjs.map +0 -1
  356. package/dist/logSinkTelemetry.cjs.map +0 -1
  357. package/dist/logSinkTelemetry.d.cts.map +0 -1
  358. package/dist/logSinkTelemetry.d.mts.map +0 -1
  359. package/dist/logSinkTelemetry.mjs.map +0 -1
  360. package/dist/store/invariants.cjs +0 -2
  361. package/dist/store/invariants.cjs.map +0 -1
  362. package/dist/store/invariants.d.cts +0 -14
  363. package/dist/store/invariants.d.cts.map +0 -1
  364. package/dist/store/invariants.d.mts +0 -14
  365. package/dist/store/invariants.d.mts.map +0 -1
  366. package/dist/store/invariants.mjs +0 -2
  367. package/dist/store/invariants.mjs.map +0 -1
  368. package/dist/store/paths.cjs +0 -2
  369. package/dist/store/paths.cjs.map +0 -1
  370. package/dist/store/paths.d.cts +0 -23
  371. package/dist/store/paths.d.cts.map +0 -1
  372. package/dist/store/paths.d.mts +0 -23
  373. package/dist/store/paths.d.mts.map +0 -1
  374. package/dist/store/paths.mjs +0 -2
  375. package/dist/store/paths.mjs.map +0 -1
  376. package/dist/store/processLiveness.cjs +0 -2
  377. package/dist/store/processLiveness.cjs.map +0 -1
  378. package/dist/store/processLiveness.d.cts.map +0 -1
  379. package/dist/store/processLiveness.d.mts.map +0 -1
  380. package/dist/store/processLiveness.mjs.map +0 -1
  381. package/dist/store/reconcile.cjs +0 -2
  382. package/dist/store/reconcile.cjs.map +0 -1
  383. package/dist/store/reconcile.d.cts.map +0 -1
  384. package/dist/store/reconcile.d.mts.map +0 -1
  385. package/dist/store/reconcile.mjs +0 -2
  386. package/dist/store/reconcile.mjs.map +0 -1
  387. package/dist/store/reducer.cjs +0 -3
  388. package/dist/store/reducer.cjs.map +0 -1
  389. package/dist/store/reducer.d.cts.map +0 -1
  390. package/dist/store/reducer.d.mts.map +0 -1
  391. package/dist/store/reducer.mjs +0 -3
  392. package/dist/store/reducer.mjs.map +0 -1
  393. package/dist/store/taskGraph.cjs +0 -2
  394. package/dist/store/taskGraph.cjs.map +0 -1
  395. package/dist/store/taskGraph.d.cts.map +0 -1
  396. package/dist/store/taskGraph.d.mts.map +0 -1
  397. package/dist/store/taskGraph.mjs.map +0 -1
  398. package/dist/store/taskStore.cjs +0 -2
  399. package/dist/store/taskStore.cjs.map +0 -1
  400. package/dist/store/taskStore.d.cts.map +0 -1
  401. package/dist/store/taskStore.d.mts.map +0 -1
  402. package/dist/store/taskStore.mjs +0 -2
  403. package/dist/store/taskStore.mjs.map +0 -1
  404. package/dist/store/types.cjs +0 -2
  405. package/dist/store/types.cjs.map +0 -1
  406. package/dist/store/types.d.cts.map +0 -1
  407. package/dist/store/types.d.mts.map +0 -1
  408. package/dist/store/types.mjs.map +0 -1
  409. package/dist/tool/promptGuidelines.cjs +0 -2
  410. package/dist/tool/promptGuidelines.cjs.map +0 -1
  411. package/dist/tool/promptGuidelines.d.cts +0 -5
  412. package/dist/tool/promptGuidelines.d.cts.map +0 -1
  413. package/dist/tool/promptGuidelines.d.mts +0 -5
  414. package/dist/tool/promptGuidelines.d.mts.map +0 -1
  415. package/dist/tool/promptGuidelines.mjs +0 -2
  416. package/dist/tool/promptGuidelines.mjs.map +0 -1
  417. package/dist/tool/responseEnvelope.cjs +0 -6
  418. package/dist/tool/responseEnvelope.cjs.map +0 -1
  419. package/dist/tool/responseEnvelope.d.cts +0 -39
  420. package/dist/tool/responseEnvelope.d.cts.map +0 -1
  421. package/dist/tool/responseEnvelope.d.mts +0 -39
  422. package/dist/tool/responseEnvelope.d.mts.map +0 -1
  423. package/dist/tool/responseEnvelope.mjs +0 -6
  424. package/dist/tool/responseEnvelope.mjs.map +0 -1
  425. package/dist/tool/schema.cjs +0 -2
  426. package/dist/tool/schema.cjs.map +0 -1
  427. package/dist/tool/schema.d.cts.map +0 -1
  428. package/dist/tool/schema.d.mts.map +0 -1
  429. package/dist/tool/schema.mjs +0 -2
  430. package/dist/tool/schema.mjs.map +0 -1
  431. package/dist/tool/taskTool.cjs +0 -3
  432. package/dist/tool/taskTool.cjs.map +0 -1
  433. package/dist/tool/taskTool.d.cts +0 -17
  434. package/dist/tool/taskTool.d.cts.map +0 -1
  435. package/dist/tool/taskTool.d.mts +0 -17
  436. package/dist/tool/taskTool.d.mts.map +0 -1
  437. package/dist/tool/taskTool.mjs +0 -3
  438. package/dist/tool/taskTool.mjs.map +0 -1
  439. /package/dist/{store → models}/taskGraph.mjs +0 -0
@@ -1,23 +0,0 @@
1
- //#region src/store/paths.d.ts
2
- declare const STORE_PATH_ENV = "DOOM_TASK_STORE";
3
- /** Resolve the tree root without relying on extension startup order. */
4
- declare function resolveSessionKey(rootSessionId: string, env?: NodeJS.ProcessEnv): string;
5
- /** Resolve one root session tree to a task document under the Pi agent directory. */
6
- declare function resolveStorePath(_cwd?: string, env?: NodeJS.ProcessEnv, sessionKey?: string): string;
7
- /** Whether a deliberate unscoped task-store override is active. */
8
- declare function hasStorePathOverride(env?: NodeJS.ProcessEnv): boolean;
9
- /** Exact legacy Git-directory store, if the current working tree has one. */
10
- declare function resolveLegacyStoreDirectory(cwd?: string): string | undefined;
11
- interface StoreSweepResult {
12
- removed: string[];
13
- errors: string[];
14
- }
15
- /** Remove only the validated legacy Git store unless it contains the active override. */
16
- declare function removeLegacyStoreDirectory(currentStorePath: string, cwd?: string): StoreSweepResult;
17
- /** Delete expired sibling session stores while preserving active or unreadable stores. */
18
- declare function sweepStoreFiles(currentStorePath: string, ttlMs: number, now?: number): StoreSweepResult;
19
- declare function lockPathFor(storePath: string): string;
20
- declare function tempPathFor(storePath: string, pid?: number): string;
21
- //#endregion
22
- export { STORE_PATH_ENV, StoreSweepResult, hasStorePathOverride, lockPathFor, removeLegacyStoreDirectory, resolveLegacyStoreDirectory, resolveSessionKey, resolveStorePath, sweepStoreFiles, tempPathFor };
23
- //# sourceMappingURL=paths.d.mts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"paths.d.mts","names":[],"sources":["../../src/store/paths.ts"],"mappings":";cAMa;;iBAyCG,kBAAkB,uBAAuB,MAAK,OAAO;;iBAQrD,iBACd,eACA,MAAK,OAAO,YACZ;;iBAWc,qBAAqB,MAAK,OAAO;;iBAKjC,4BAA4B;UAK3B;EACf;EACA;;;iBAIc,2BAA2B,0BAA0B,eAA8B;;iBAgBnF,gBAAgB,0BAA0B,eAAe,eAA2B;iBA8BpF,YAAY;iBAIZ,YAAY,mBAAmB"}
@@ -1,2 +0,0 @@
1
- import e from"node:path";import t from"node:os";import{execFileSync as n}from"node:child_process";import r from"node:fs";import{SUBAGENT_CHILD_ENV as i,SUBAGENT_PARENT_SESSION_ENV as a}from"@agimon-ai/doompi-extension-contracts/child-process";const o=`DOOM_TASK_STORE`,s=`doom-task`,c=`tasks.json`,l=`utf8`;function u(e,t){try{let r=n(`git`,e,{cwd:t,encoding:l,stdio:[`ignore`,`pipe`,`ignore`]}).trim();return r.length>0?r:void 0}catch{return}}function d(n){let r=n.PI_CODING_AGENT_DIR?.trim();return r===`~`?t.homedir():r?.startsWith(`~/`)?e.join(t.homedir(),r.slice(2)):r?e.resolve(r):e.join(t.homedir(),`.pi`,`agent`)}function f(t,n){let r=e.relative(e.resolve(t),e.resolve(n));return r===``||!r.startsWith(`..`)&&!e.isAbsolute(r)}function p(e,t=process.env){if(!t[i])return e;let n=t[a]?.trim();if(!n)throw Error(`${a} is required in a subagent child`);return n}function m(t=process.cwd(),n=process.env,r=`standalone`){let i=n[o]?.trim();if(i)return e.resolve(i);let a=r.trim();if(!a)throw Error(`doom-task session id cannot be blank`);return e.join(d(n),s,a,c)}function h(e=process.env){return!!e[o]?.trim()}function g(t=process.cwd()){let n=u([`rev-parse`,`--path-format=absolute`,`--git-common-dir`],t);return n?e.join(n,s):void 0}function _(t,n=process.cwd()){let i={removed:[],errors:[]},a=g(n);if(!a||e.basename(a)!==s||f(a,t))return i;try{if(!r.existsSync(a))return i;r.rmSync(a,{recursive:!0,force:!0}),i.removed.push(a)}catch(e){i.errors.push(`Could not remove legacy task store ${a}: ${String(e)}`)}return i}function v(t,n,i=Date.now()){let a={removed:[],errors:[]},o=e.dirname(t),s=e.dirname(o),u;try{u=r.readdirSync(s)}catch(e){return e.code===`ENOENT`||a.errors.push(`Could not read task store directory ${s}: ${String(e)}`),a}for(let t of u){let u=e.join(s,t),d=e.join(u,c);if(!(u===o||!r.existsSync(d)))try{if(r.existsSync(y(d))||(JSON.parse(r.readFileSync(d,l)),i-r.statSync(d).mtimeMs<=n))continue;r.rmSync(u,{recursive:!0,force:!0}),a.removed.push(u)}catch(e){a.errors.push(`Could not sweep task store ${d}: ${String(e)}`)}}return a}function y(e){return`${e}.lock`}function b(e,t=process.pid){return`${e}.tmp.${t}`}export{o as STORE_PATH_ENV,h as hasStorePathOverride,y as lockPathFor,_ as removeLegacyStoreDirectory,g as resolveLegacyStoreDirectory,p as resolveSessionKey,m as resolveStorePath,v as sweepStoreFiles,b as tempPathFor};
2
- //# sourceMappingURL=paths.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"paths.mjs","names":[],"sources":["../../src/store/paths.ts"],"sourcesContent":["import { execFileSync } from 'node:child_process';\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { SUBAGENT_CHILD_ENV, SUBAGENT_PARENT_SESSION_ENV } from '@agimon-ai/doompi-extension-contracts/child-process';\n\nexport const STORE_PATH_ENV = 'DOOM_TASK_STORE';\n\nconst STORE_DIR_NAME = 'doom-task';\nconst STORE_FILE_NAME = 'tasks.json';\nconst DEFAULT_CONFIG_DIR_NAME = '.pi';\nconst AGENT_DIR_NAME = 'agent';\nconst PI_CODING_AGENT_DIR_ENV = 'PI_CODING_AGENT_DIR';\nconst HOME_ALIAS = '~';\nconst HOME_ALIAS_PREFIX = '~/';\nconst FILE_ENCODING = 'utf8';\nconst NOT_FOUND_ERROR_CODE = 'ENOENT';\n\nfunction git(args: string[], cwd: string): string | undefined {\n try {\n const output = execFileSync('git', args, {\n cwd,\n encoding: FILE_ENCODING,\n stdio: ['ignore', 'pipe', 'ignore'],\n });\n const trimmed = output.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction resolveAgentDirectory(env: NodeJS.ProcessEnv): string {\n const configured = env[PI_CODING_AGENT_DIR_ENV]?.trim();\n if (configured === HOME_ALIAS) return os.homedir();\n if (configured?.startsWith(HOME_ALIAS_PREFIX)) {\n return path.join(os.homedir(), configured.slice(HOME_ALIAS_PREFIX.length));\n }\n return configured ? path.resolve(configured) : path.join(os.homedir(), DEFAULT_CONFIG_DIR_NAME, AGENT_DIR_NAME);\n}\n\nfunction isWithin(root: string, candidate: string): boolean {\n const relative = path.relative(path.resolve(root), path.resolve(candidate));\n return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));\n}\n\n/** Resolve the tree root without relying on extension startup order. */\nexport function resolveSessionKey(rootSessionId: string, env: NodeJS.ProcessEnv = process.env): string {\n if (!env[SUBAGENT_CHILD_ENV]) return rootSessionId;\n const parentSessionId = env[SUBAGENT_PARENT_SESSION_ENV]?.trim();\n if (!parentSessionId) throw new Error(`${SUBAGENT_PARENT_SESSION_ENV} is required in a subagent child`);\n return parentSessionId;\n}\n\n/** Resolve one root session tree to a task document under the Pi agent directory. */\nexport function resolveStorePath(\n _cwd: string = process.cwd(),\n env: NodeJS.ProcessEnv = process.env,\n sessionKey: string = 'standalone',\n): string {\n const override = env[STORE_PATH_ENV]?.trim();\n if (override) return path.resolve(override);\n\n const trimmedSessionKey = sessionKey.trim();\n if (!trimmedSessionKey) throw new Error('doom-task session id cannot be blank');\n return path.join(resolveAgentDirectory(env), STORE_DIR_NAME, trimmedSessionKey, STORE_FILE_NAME);\n}\n\n/** Whether a deliberate unscoped task-store override is active. */\nexport function hasStorePathOverride(env: NodeJS.ProcessEnv = process.env): boolean {\n return Boolean(env[STORE_PATH_ENV]?.trim());\n}\n\n/** Exact legacy Git-directory store, if the current working tree has one. */\nexport function resolveLegacyStoreDirectory(cwd: string = process.cwd()): string | undefined {\n const commonDirectory = git(['rev-parse', '--path-format=absolute', '--git-common-dir'], cwd);\n return commonDirectory ? path.join(commonDirectory, STORE_DIR_NAME) : undefined;\n}\n\nexport interface StoreSweepResult {\n removed: string[];\n errors: string[];\n}\n\n/** Remove only the validated legacy Git store unless it contains the active override. */\nexport function removeLegacyStoreDirectory(currentStorePath: string, cwd: string = process.cwd()): StoreSweepResult {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const target = resolveLegacyStoreDirectory(cwd);\n if (!target || path.basename(target) !== STORE_DIR_NAME || isWithin(target, currentStorePath)) return result;\n\n try {\n if (!fs.existsSync(target)) return result;\n fs.rmSync(target, { recursive: true, force: true });\n result.removed.push(target);\n } catch (error) {\n result.errors.push(`Could not remove legacy task store ${target}: ${String(error)}`);\n }\n return result;\n}\n\n/** Delete expired sibling session stores while preserving active or unreadable stores. */\nexport function sweepStoreFiles(currentStorePath: string, ttlMs: number, now: number = Date.now()): StoreSweepResult {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const currentSessionDirectory = path.dirname(currentStorePath);\n const storeDirectory = path.dirname(currentSessionDirectory);\n let entries: string[];\n try {\n entries = fs.readdirSync(storeDirectory);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) return result;\n result.errors.push(`Could not read task store directory ${storeDirectory}: ${String(error)}`);\n return result;\n }\n\n for (const entry of entries) {\n const sessionDirectory = path.join(storeDirectory, entry);\n const candidate = path.join(sessionDirectory, STORE_FILE_NAME);\n if (sessionDirectory === currentSessionDirectory || !fs.existsSync(candidate)) continue;\n try {\n if (fs.existsSync(lockPathFor(candidate))) continue;\n JSON.parse(fs.readFileSync(candidate, FILE_ENCODING));\n if (now - fs.statSync(candidate).mtimeMs <= ttlMs) continue;\n fs.rmSync(sessionDirectory, { recursive: true, force: true });\n result.removed.push(sessionDirectory);\n } catch (error) {\n result.errors.push(`Could not sweep task store ${candidate}: ${String(error)}`);\n }\n }\n return result;\n}\n\nexport function lockPathFor(storePath: string): string {\n return `${storePath}.lock`;\n}\n\nexport function tempPathFor(storePath: string, pid: number = process.pid): string {\n return `${storePath}.tmp.${pid}`;\n}\n"],"mappings":"mPAMA,MAAa,EAAiB,kBAExB,EAAiB,YACjB,EAAkB,aAMlB,EAAgB,OAGtB,SAAS,EAAI,EAAgB,EAAiC,CAC5D,GAAI,CAMF,IAAM,EALS,EAAa,MAAO,EAAM,CACvC,MACA,SAAU,EACV,MAAO,CAAC,SAAU,OAAQ,QAAQ,CACpC,CACqB,CAAC,CAAC,KAAK,EAC5B,OAAO,EAAQ,OAAS,EAAI,EAAU,IAAA,EACxC,MAAQ,CACN,MACF,CACF,CAEA,SAAS,EAAsB,EAAgC,CAC7D,IAAM,EAAa,EAAI,qBAA0B,KAAK,EAKtD,OAJI,IAAe,IAAmB,EAAG,QAAQ,EAC7C,GAAY,WAAW,IAAiB,EACnC,EAAK,KAAK,EAAG,QAAQ,EAAG,EAAW,MAAM,CAAwB,CAAC,EAEpE,EAAa,EAAK,QAAQ,CAAU,EAAI,EAAK,KAAK,EAAG,QAAQ,EAAG,MAAyB,OAAc,CAChH,CAEA,SAAS,EAAS,EAAc,EAA4B,CAC1D,IAAM,EAAW,EAAK,SAAS,EAAK,QAAQ,CAAI,EAAG,EAAK,QAAQ,CAAS,CAAC,EAC1E,OAAO,IAAa,IAAO,CAAC,EAAS,WAAW,IAAI,GAAK,CAAC,EAAK,WAAW,CAAQ,CACpF,CAGA,SAAgB,EAAkB,EAAuB,EAAyB,QAAQ,IAAa,CACrG,GAAI,CAAC,EAAI,GAAqB,OAAO,EACrC,IAAM,EAAkB,EAAI,EAA4B,EAAE,KAAK,EAC/D,GAAI,CAAC,EAAiB,MAAU,MAAM,GAAG,EAA4B,iCAA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AAQ,CAAgB,EACvD,EAAiB,EAAK,QAAQ,CAAuB,EACvD,EACJ,GAAI,CACF,EAAU,EAAG,YAAY,CAAc,CACzC,OAAS,EAAO,CAGd,OAFK,EAAgC,OAAS,UAC9C,EAAO,OAAO,KAAK,uCAAuC,EAAe,IAAI,OAAO,CAAK,GAAG,EADjB,CAG7E,CAEA,IAAK,IAAM,KAAS,EAAS,CAC3B,IAAM,EAAmB,EAAK,KAAK,EAAgB,CAAK,EAClD,EAAY,EAAK,KAAK,EAAkB,CAAe,EACzD,SAAqB,GAA2B,CAAC,EAAG,WAAW,CAAS,GAC5E,GAAI,CAGF,GAFI,EAAG,WAAW,EAAY,CAAS,CAAC,IACxC,KAAK,MAAM,EAAG,aAAa,EAAW,CAAa,CAAC,EAChD,EAAM,EAAG,SAAS,CAAS,CAAC,CAAC,SAAW,GAAO,SACnD,EAAG,OAAO,EAAkB,CAAE,UAAW,GAAM,MAAO,EAAK,CAAC,EAC5D,EAAO,QAAQ,KAAK,CAAgB,CACtC,OAAS,EAAO,CACd,EAAO,OAAO,KAAK,8BAA8B,EAAU,IAAI,OAAO,CAAK,GAAG,CAChF,CACF,CACA,OAAO,CACT,CAEA,SAAgB,EAAY,EAA2B,CACrD,MAAO,GAAG,EAAU,MACtB,CAEA,SAAgB,EAAY,EAAmB,EAAc,QAAQ,IAAa,CAChF,MAAO,GAAG,EAAU,OAAO,GAC7B"}
@@ -1,2 +0,0 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});function e(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}exports.isProcessAlive=e;
2
- //# sourceMappingURL=processLiveness.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"processLiveness.cjs","names":[],"sources":["../../src/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":"mEAOA,SAAgB,EAAe,EAAsB,CACnD,GAAI,CAEF,OADA,QAAQ,KAAK,EAAK,CAAC,EACZ,EACT,OAAS,EAAO,CACd,OAAQ,EAAgC,OAAS,OACnD,CACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"processLiveness.d.cts","names":[],"sources":["../../src/store/processLiveness.ts"],"mappings":";;;;;;;;iBAOgB,eAAe"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"processLiveness.d.mts","names":[],"sources":["../../src/store/processLiveness.ts"],"mappings":";;;;;;;;iBAOgB,eAAe"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"processLiveness.mjs","names":[],"sources":["../../src/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"}
@@ -1,2 +0,0 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});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
@@ -1 +0,0 @@
1
- {"version":3,"file":"reconcile.cjs","names":["isProcessAlive","isDelegationActive"],"sources":["../../src/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":"qIAGa,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"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"reconcile.d.cts","names":[],"sources":["../../src/store/reconcile.ts"],"mappings":";;cAGa;cACA;UAEI;EACf,UAAU;EACV,UAAU;;;UAIK;EACf;EACA,gBAAgB;;;;;;;;;;;;;;;;;;;iBAoBF,6BACd,UAAU,cACV,cACA,WAAU,yBACV,OAAO,gBACN"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"reconcile.d.mts","names":[],"sources":["../../src/store/reconcile.ts"],"mappings":";;cAGa;cACA;UAEI;EACf,UAAU;EACV,UAAU;;;UAIK;EACf;EACA,gBAAgB;;;;;;;;;;;;;;;;;;;iBAoBF,6BACd,UAAU,cACV,cACA,WAAU,yBACV,OAAO,gBACN"}
@@ -1,2 +0,0 @@
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
@@ -1 +0,0 @@
1
- {"version":3,"file":"reconcile.mjs","names":[],"sources":["../../src/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"}
@@ -1,3 +0,0 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});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`);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){let i={tasks:[...e.tasks],nextId:e.nextId,refIds:new Map,failedRefs:new Map},a=[],o=0;for(let[e,s]of t.entries()){let t=g(i,s),c=t?h(t):s.id===void 0?_(i,s,e,n):v(i,s,e,n);if(c.ok){a.push(c.outcome),o+=1;continue}s.ref&&r.test(s.ref)&&!i.refIds.has(s.ref)&&i.failedRefs.set(s.ref,e),a.push({index:e,kind:`failed`,message:c.message,...s.id===void 0?{}:{id:s.id},...s.ref?{ref:s.ref}:{}})}return{document:o>0?d(e,i.tasks,i.nextId):e,op:{kind:`upsert`,items:a,applied:o,failed:a.length-o}}}function b(t,n,r,i=new Date().toISOString()){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)}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
@@ -1 +0,0 @@
1
- {"version":3,"file":"reducer.cjs","names":["isTransitionValid","detectCycle","isDelegationActive","DELETED_STATUS"],"sources":["../../src/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/** 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 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 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): ApplyResult {\n const context: UpsertContext = {\n tasks: [...document.tasks],\n nextId: document.nextId,\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): 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);\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":"6JAuBa,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,WAAU,GAAI,CAAE,KAAM,QAAS,SAAQ,CAAE,CACpD,CAEA,SAAS,EAAe,EAAyB,EAAkC,CACjF,IAAM,EAAI,GAAK,CAAC,EACV,EAAI,GAAK,CAAC,EAChB,OAAO,EAAE,SAAW,EAAE,QAAU,EAAE,OAAO,EAAO,IAAU,IAAU,EAAE,EAAM,CAC9E,CAEA,SAAS,EAAW,EAAwC,EAAiD,CAC3G,OAAO,KAAK,UAAU,GAAK,IAAI,IAAM,KAAK,UAAU,GAAK,IAAI,CAC/D,CAQA,SAAS,EAAY,EAAc,EAAsB,CACvD,OACE,EAAO,UAAY,EAAM,SACzB,EAAO,SAAW,EAAM,QACxB,EAAO,cAAgB,EAAM,aAC7B,EAAO,aAAe,EAAM,YAC5B,EAAO,QAAU,EAAM,OACvB,CAAC,EAAe,EAAO,UAAW,EAAM,SAAS,GACjD,CAAC,EAAW,EAAO,SAAU,EAAM,QAAQ,CAE/C,CAEA,S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kB,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"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"reducer.d.cts","names":[],"sources":["../../src/store/reducer.ts"],"mappings":";;;cAgBa;;;;;;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;;;;;;;;iBAuT3B,kBACd,UAAU,cACV,QAAQ,eACR,QAAQ,oBACR,eACC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"reducer.d.mts","names":[],"sources":["../../src/store/reducer.ts"],"mappings":";;;cAgBa;;;;;;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;;;;;;;;iBAuT3B,kBACd,UAAU,cACV,QAAQ,eACR,QAAQ,oBACR,eACC"}
@@ -1,3 +0,0 @@
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`);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){let r={tasks:[...e.tasks],nextId:e.nextId,refIds:new Map,failedRefs:new Map},i=[],o=0;for(let[e,s]of t.entries()){let t=v(r,s),c=t?_(t):s.id===void 0?y(r,s,e,n):b(r,s,e,n);if(c.ok){i.push(c.outcome),o+=1;continue}s.ref&&a.test(s.ref)&&!r.refIds.has(s.ref)&&r.failedRefs.set(s.ref,e),i.push({index:e,kind:`failed`,message:c.message,...s.id===void 0?{}:{id:s.id},...s.ref?{ref:s.ref}:{}})}return{document:o>0?p(e,r.tasks,r.nextId):e,op:{kind:`upsert`,items:i,applied:o,failed:i.length-o}}}function S(n,r,i,a=new Date().toISOString()){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)}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
@@ -1 +0,0 @@
1
- {"version":3,"file":"reducer.mjs","names":[],"sources":["../../src/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/** 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 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 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): ApplyResult {\n const context: UpsertContext = {\n tasks: [...document.tasks],\n nextId: document.nextId,\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): 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);\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,MAAa,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,EA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M,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"}
@@ -1,2 +0,0 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});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
@@ -1 +0,0 @@
1
- {"version":3,"file":"taskGraph.cjs","names":[],"sources":["../../src/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":"mEAEA,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"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"taskGraph.d.cts","names":[],"sources":["../../src/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"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"taskGraph.d.mts","names":[],"sources":["../../src/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"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"taskGraph.mjs","names":[],"sources":["../../src/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"}
@@ -1,2 +0,0 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../_virtual/_rolldown/runtime.cjs"),t=require("../logSinkTelemetry.cjs"),n=require("./processLiveness.cjs"),r=require("./types.cjs"),i=require("./paths.cjs");let a=require("node:path");a=e.__toESM(a,1);let o=require("node:fs");o=e.__toESM(o,1);const s=`utf8`,c=`ENOENT`,l=`store.path`;function u(e){return new Promise(t=>setTimeout(t,e))}function d(e){if(!e||typeof e!=`object`)return r.emptyDocument();let t=e;if(!Array.isArray(t.tasks))return r.emptyDocument();let n=t.tasks.filter(e=>!!e&&typeof e==`object`&&typeof e.id==`number`),i=n.reduce((e,t)=>Math.max(e,t.id),0);return{version:typeof t.version==`number`?t.version:1,rev:typeof t.rev==`number`?t.rev:0,nextId:typeof t.nextId==`number`&&t.nextId>i?t.nextId:i+1,tasks:n}}var f=class{storePath;cwd;env;cached=r.emptyDocument();lastKnownRev=-1;watcher;pollTimer;debounceTimer;listeners=new Set;pollIntervalMs;lockTimeoutMs;report;constructor(e={}){this.cwd=e.cwd??process.cwd(),this.env=e.env??process.env,this.storePath=e.storePath??i.resolveStorePath(this.cwd,this.env),this.pollIntervalMs=e.pollIntervalMs??2e3,this.lockTimeoutMs=e.lockTimeoutMs??2e3,this.report=e.report}configureSession(e){this.env.DOOM_TASK_STORE?.trim()||(this.stopWatching(),this.storePath=i.resolveStorePath(this.cwd,this.env,e),this.cached=r.emptyDocument(),this.lastKnownRev=-1)}get snapshot(){return this.cached}read(){try{let e=o.default.readFileSync(this.storePath,s);this.cached=d(JSON.parse(e))}catch(e){e.code!==c&&this.report?.error(t.TASK_EVENT.storeReadFailed,e,{[l]:this.storePath}),this.cached=r.emptyDocument()}return this.lastKnownRev=this.cached.rev,this.cached}async mutate(e){let t=await this.acquireLock();try{let t=this.read(),n=e(t);return n.document?{document:this.write(n.document),value:n.value}:{document:t,value:n.value}}finally{t()}}write(e){let t={...e,version:1,rev:e.rev+1};o.default.mkdirSync(a.default.dirname(this.storePath),{recursive:!0});let n=i.tempPathFor(this.storePath);return o.default.writeFileSync(n,`${JSON.stringify(t,void 0,2)}\n`,s),o.default.renameSync(n,this.storePath),this.cached=t,this.lastKnownRev=t.rev,t}async acquireLock(){let e=i.lockPathFor(this.storePath);o.default.mkdirSync(a.default.dirname(this.storePath),{recursive:!0});let n=Date.now()+this.lockTimeoutMs;for(;;)try{let t=o.default.openSync(e,`wx`);return o.default.writeSync(t,JSON.stringify({pid:process.pid,time:Date.now()})),o.default.closeSync(t),()=>o.default.rmSync(e,{force:!0})}catch(r){if(r.code!==`EEXIST`)throw r;if(Date.now()>=n)return this.report?.warn(t.TASK_EVENT.storeLockTimeout,Error(`Task store lock still held after ${this.lockTimeoutMs}ms; proceeding without it`),{[l]:this.storePath}),()=>{};this.breakStaleLock(e),await u(10+Math.random()*60)}}breakStaleLock(e){try{let t=JSON.parse(o.default.readFileSync(e,s)),r=typeof t.time==`number`&&Date.now()-t.time>1e4,i=typeof t.pid==`number`&&!n.isProcessAlive(t.pid);return!r&&!i?!1:(o.default.unlinkSync(e),!0)}catch(n){return n.code!==c&&this.report?.warn(t.TASK_EVENT.storeLockBreakFailed,n,{[l]:e}),!1}}onExternalChange(e){return this.listeners.add(e),this.startWatching(),()=>{this.listeners.delete(e),this.listeners.size===0&&this.stopWatching()}}startWatching(){if(this.watcher||this.pollTimer)return;let e=a.default.dirname(this.storePath),n=a.default.basename(this.storePath);try{o.default.mkdirSync(e,{recursive:!0}),this.watcher=o.default.watch(e,(e,t)=>{t&&t!==n||this.scheduleCheck()})}catch(e){this.report?.warn(t.TASK_EVENT.storeWatchFailed,e,{[l]:this.storePath})}this.pollTimer=setInterval(()=>this.checkForChange(),this.pollIntervalMs),this.pollTimer.unref?.()}scheduleCheck(){clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>this.checkForChange(),150),this.debounceTimer.unref?.()}checkForChange(){let e=this.lastKnownRev,n=this.read();if(n.rev!==e)for(let e of this.listeners)try{e(n)}catch(e){this.report?.error(t.TASK_EVENT.storeListenerFailed,e,{[l]:this.storePath})}}stopWatching(){this.watcher?.close(),this.watcher=void 0,this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=void 0,clearTimeout(this.debounceTimer),this.debounceTimer=void 0}dispose(){this.listeners.clear(),this.stopWatching()}};exports.TaskStore=f;
2
- //# sourceMappingURL=taskStore.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"taskStore.cjs","names":["emptyDocument","resolveStorePath","fs","TASK_EVENT","path","tempPathFor","lockPathFor","isProcessAlive"],"sources":["../../src/store/taskStore.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { TASK_EVENT, type TaskFailureReporter } from '../logSinkTelemetry.ts';\nimport { lockPathFor, resolveStorePath, STORE_PATH_ENV, tempPathFor } from './paths.ts';\nimport { isProcessAlive } from './processLiveness.ts';\nimport { emptyDocument, STORE_SCHEMA_VERSION, type Task, type TaskDocument } from './types.ts';\n\nconst LOCK_TIMEOUT_MS = 2000;\nconst LOCK_STALE_MS = 10_000;\nconst LOCK_RETRY_BASE_MS = 10;\nconst LOCK_RETRY_MAX_MS = 60;\nconst WATCH_DEBOUNCE_MS = 150;\nconst POLL_INTERVAL_MS = 2000;\nconst UTF8_ENCODING = 'utf8';\nconst MISSING_FILE_CODE = 'ENOENT';\nconst LOCK_EXISTS_CODE = 'EEXIST';\nconst STORE_PATH_ATTRIBUTE = 'store.path';\n\nexport interface TaskStoreOptions {\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n storePath?: string;\n /** Backstop poll cadence for change detection. Lowered in tests so they do\n * not depend on `fs.watch`, whose delivery timing is platform-dependent. */\n pollIntervalMs?: number;\n /** How long to wait for the advisory lock before proceeding lock-free. */\n lockTimeoutMs?: number;\n /** Where swallowed failures go, so silent degradation stays visible. */\n report?: TaskFailureReporter;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Coerce arbitrary parsed JSON into a valid document.\n *\n * A corrupt or truncated store must not take the session down: the worst\n * acceptable outcome is starting from an empty list, never a crash on startup.\n */\nfunction normalizeDocument(parsed: unknown): TaskDocument {\n if (!parsed || typeof parsed !== 'object') return emptyDocument();\n const candidate = parsed as Partial<TaskDocument>;\n if (!Array.isArray(candidate.tasks)) return emptyDocument();\n\n const tasks = candidate.tasks.filter(\n (task): task is Task => Boolean(task) && typeof task === 'object' && typeof (task as Task).id === 'number',\n );\n const maxId = tasks.reduce((max, task) => Math.max(max, task.id), 0);\n return {\n version: typeof candidate.version === 'number' ? candidate.version : STORE_SCHEMA_VERSION,\n rev: typeof candidate.rev === 'number' ? candidate.rev : 0,\n nextId: typeof candidate.nextId === 'number' && candidate.nextId > maxId ? candidate.nextId : maxId + 1,\n tasks,\n };\n}\n\n/**\n * File-backed task store shared by one root session and its delegated children.\n *\n * Durability model: the JSON file is the source of truth. Mutations are\n * read-modify-write under an advisory lock so concurrent delegated processes\n * cannot clobber each other, and writes land via temp-file rename so a\n * crash mid-write can never leave a partial document behind.\n */\nexport class TaskStore {\n storePath: string;\n\n private readonly cwd: string;\n private readonly env: NodeJS.ProcessEnv;\n private cached: TaskDocument = emptyDocument();\n private lastKnownRev = -1;\n private watcher?: fs.FSWatcher;\n private pollTimer?: NodeJS.Timeout;\n private debounceTimer?: NodeJS.Timeout;\n private readonly listeners = new Set<(document: TaskDocument) => void>();\n private readonly pollIntervalMs: number;\n private readonly lockTimeoutMs: number;\n private readonly report?: TaskFailureReporter;\n\n constructor(options: TaskStoreOptions = {}) {\n this.cwd = options.cwd ?? process.cwd();\n this.env = options.env ?? process.env;\n this.storePath = options.storePath ?? resolveStorePath(this.cwd, this.env);\n this.pollIntervalMs = options.pollIntervalMs ?? POLL_INTERVAL_MS;\n this.lockTimeoutMs = options.lockTimeoutMs ?? LOCK_TIMEOUT_MS;\n this.report = options.report;\n }\n\n /** Bind a default store to the current session tree before reading or watching it. */\n configureSession(sessionKey: string): void {\n if (this.env[STORE_PATH_ENV]?.trim()) return;\n this.stopWatching();\n this.storePath = resolveStorePath(this.cwd, this.env, sessionKey);\n this.cached = emptyDocument();\n this.lastKnownRev = -1;\n }\n\n /** Last document read from disk, without hitting the filesystem. */\n get snapshot(): TaskDocument {\n return this.cached;\n }\n\n read(): TaskDocument {\n try {\n const raw = fs.readFileSync(this.storePath, UTF8_ENCODING);\n this.cached = normalizeDocument(JSON.parse(raw));\n } catch (error) {\n // A missing file is the normal state before the first write. Anything\n // else means the task list just silently became empty, which is worth a\n // record: unreadable or corrupt JSON looks identical to \"no tasks yet\".\n if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n this.report?.error(TASK_EVENT.storeReadFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n this.cached = emptyDocument();\n }\n this.lastKnownRev = this.cached.rev;\n return this.cached;\n }\n\n /**\n * Apply a mutation under the store lock.\n *\n * `mutate` receives the freshest on-disk document and returns either the next\n * document to commit or `undefined` for a read-only action (list/get), which\n * skips the write entirely so queries never bump `rev`.\n */\n async mutate<T>(\n mutate: (document: TaskDocument) => { document?: TaskDocument; value: T },\n ): Promise<{ document: TaskDocument; value: T }> {\n const release = await this.acquireLock();\n try {\n const current = this.read();\n const outcome = mutate(current);\n if (!outcome.document) {\n return { document: current, value: outcome.value };\n }\n const committed = this.write(outcome.document);\n return { document: committed, value: outcome.value };\n } finally {\n release();\n }\n }\n\n private write(document: TaskDocument): TaskDocument {\n const next: TaskDocument = { ...document, version: STORE_SCHEMA_VERSION, rev: document.rev + 1 };\n fs.mkdirSync(path.dirname(this.storePath), { recursive: true });\n const temp = tempPathFor(this.storePath);\n fs.writeFileSync(temp, `${JSON.stringify(next, undefined, 2)}\\n`, UTF8_ENCODING);\n fs.renameSync(temp, this.storePath);\n this.cached = next;\n this.lastKnownRev = next.rev;\n return next;\n }\n\n private async acquireLock(): Promise<() => void> {\n const lockPath = lockPathFor(this.storePath);\n fs.mkdirSync(path.dirname(this.storePath), { recursive: true });\n const deadline = Date.now() + this.lockTimeoutMs;\n\n for (;;) {\n try {\n const handle = fs.openSync(lockPath, 'wx');\n fs.writeSync(handle, JSON.stringify({ pid: process.pid, time: Date.now() }));\n fs.closeSync(handle);\n return () => fs.rmSync(lockPath, { force: true });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== LOCK_EXISTS_CODE) throw error;\n // The deadline is checked before breaking a stale lock so a peer that\n // keeps recreating one cannot spin this loop without bound.\n if (Date.now() >= deadline) {\n // Proceeding lock-free beats stalling the agent: the rename is atomic,\n // so the worst case is a lost concurrent update, not a corrupt file.\n // Reported because a lost update here can strand a delegation.\n this.report?.warn(\n TASK_EVENT.storeLockTimeout,\n new Error(`Task store lock still held after ${this.lockTimeoutMs}ms; proceeding without it`),\n { [STORE_PATH_ATTRIBUTE]: this.storePath },\n );\n return () => {};\n }\n // Clearing a dead holder's lock still goes through the backoff. Yielding\n // on every iteration is what stops a peer that keeps recreating the\n // lock from turning this into a spin.\n this.breakStaleLock(lockPath);\n await sleep(LOCK_RETRY_BASE_MS + Math.random() * LOCK_RETRY_MAX_MS);\n }\n }\n }\n\n /** Remove a lock left behind by a dead process or one held implausibly long. */\n private breakStaleLock(lockPath: string): boolean {\n try {\n const holder = JSON.parse(fs.readFileSync(lockPath, UTF8_ENCODING)) as { pid?: number; time?: number };\n const expired = typeof holder.time === 'number' && Date.now() - holder.time > LOCK_STALE_MS;\n const dead = typeof holder.pid === 'number' && !isProcessAlive(holder.pid);\n if (!expired && !dead) return false;\n fs.unlinkSync(lockPath);\n return true;\n } catch (error) {\n // Losing the race to another breaker is normal; a persistent failure here\n // shows up as the lock timeout above, so this stays a warning.\n if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n this.report?.warn(TASK_EVENT.storeLockBreakFailed, error, { [STORE_PATH_ATTRIBUTE]: lockPath });\n }\n return false;\n }\n }\n\n /**\n * Notify when another process changes the store.\n *\n * `fs.watch` alone is unreliable across the rename-based write (and on some\n * network filesystems), so a slow poll backs it up. Writes made by this\n * process are filtered out by revision so the UI does not redraw twice.\n */\n onExternalChange(listener: (document: TaskDocument) => void): () => void {\n this.listeners.add(listener);\n this.startWatching();\n return () => {\n this.listeners.delete(listener);\n if (this.listeners.size === 0) this.stopWatching();\n };\n }\n\n private startWatching(): void {\n if (this.watcher || this.pollTimer) return;\n const directory = path.dirname(this.storePath);\n const fileName = path.basename(this.storePath);\n\n try {\n fs.mkdirSync(directory, { recursive: true });\n this.watcher = fs.watch(directory, (_event, changed) => {\n if (changed && changed !== fileName) return;\n this.scheduleCheck();\n });\n } catch (error) {\n // Polling still covers change detection, just more slowly.\n this.report?.warn(TASK_EVENT.storeWatchFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n\n this.pollTimer = setInterval(() => this.checkForChange(), this.pollIntervalMs);\n this.pollTimer.unref?.();\n }\n\n private scheduleCheck(): void {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = setTimeout(() => this.checkForChange(), WATCH_DEBOUNCE_MS);\n this.debounceTimer.unref?.();\n }\n\n private checkForChange(): void {\n const previousRev = this.lastKnownRev;\n const document = this.read();\n if (document.rev === previousRev) return;\n for (const listener of this.listeners) {\n try {\n listener(document);\n } catch (error) {\n // This runs from a timer and from the fs.watch callback, so an\n // unguarded listener throw is an uncaught exception that takes the\n // harness down rather than a handled render failure.\n this.report?.error(TASK_EVENT.storeListenerFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n }\n }\n\n private stopWatching(): void {\n this.watcher?.close();\n this.watcher = undefined;\n if (this.pollTimer) clearInterval(this.pollTimer);\n this.pollTimer = undefined;\n clearTimeout(this.debounceTimer);\n this.debounceTimer = undefined;\n }\n\n dispose(): void {\n this.listeners.clear();\n this.stopWatching();\n }\n}\n"],"mappings":"wUAOA,MAMM,EAAgB,OAChB,EAAoB,SAEpB,EAAuB,aAe7B,SAAS,EAAM,EAA2B,CACxC,OAAO,IAAI,QAAS,GAAY,WAAW,EAAS,CAAE,CAAC,CACzD,CAQA,SAAS,EAAkB,EAA+B,CACxD,GAAI,CAAC,GAAU,OAAO,GAAW,SAAU,OAAOA,EAAAA,cAAc,EAChE,IAAM,EAAY,EAClB,GAAI,CAAC,MAAM,QAAQ,EAAU,KAAK,EAAG,OAAOA,EAAAA,cAAc,EAE1D,IAAM,EAAQ,EAAU,MAAM,OAC3B,GAAuB,EAAQ,GAAS,OAAO,GAAS,UAAY,OAAQ,EAAc,IAAO,QACpG,EACM,EAAQ,EAAM,QAAQ,EAAK,IAAS,KAAK,IAAI,EAAK,EAAK,EAAE,EAAG,CAAC,EACnE,MAAO,CACL,QAAS,OAAO,EAAU,SAAY,SAAW,EAAU,QAAA,EAC3D,IAAK,OAAO,EAAU,KAAQ,SAAW,EAAU,IAAM,EACzD,OAAQ,OAAO,EAAU,QAAW,UAAY,EAAU,OAAS,EAAQ,EAAU,OAAS,EAAQ,EACtG,OACF,C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KAAK,eAAe,EAAG,GAAiB,EAC9E,KAAK,cAAc,QAAQ,CAC7B,CAEA,gBAA+B,CAC7B,IAAM,EAAc,KAAK,aACnB,EAAW,KAAK,KAAK,EACvB,KAAS,MAAQ,EACrB,IAAK,IAAM,KAAY,KAAK,UAC1B,GAAI,CACF,EAAS,CAAQ,CACnB,OAAS,EAAO,CAId,KAAK,QAAQ,MAAMA,EAAAA,WAAW,oBAAqB,EAAO,EAAG,GAAuB,KAAK,SAAU,CAAC,CACtG,CAEJ,CAEA,cAA6B,CAC3B,KAAK,SAAS,MAAM,EACpB,KAAK,QAAU,IAAA,GACX,KAAK,WAAW,cAAc,KAAK,SAAS,EAChD,KAAK,UAAY,IAAA,GACjB,aAAa,KAAK,aAAa,EAC/B,KAAK,cAAgB,IAAA,EACvB,CAEA,SAAgB,CACd,KAAK,UAAU,MAAM,EACrB,KAAK,aAAa,CACpB,CACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"taskStore.d.cts","names":[],"sources":["../../src/store/taskStore.ts"],"mappings":";;;UAkBiB;EACf;EACA,MAAM,OAAO;EACb;;;EAGA;;EAEA;;EAEA,SAAS;;;;;;;;;;cAsCE;EACX;mBAEiB;mBACA;UACT;UACA;UACA;UACA;UACA;mBACS;mBACA;mBACA;mBACA;EAEL,YAAA,UAAS;;EAUrB,iBAAiB;;MASb,YAAY;EAIhB,QAAQ;;;;;;;;EAwBF,OAAO,GACX,SAAS,UAAU;IAAmB,WAAW;IAAc,OAAO;MACrE;IAAU,UAAU;IAAc,OAAO;;UAepC;UAWM;;UAoCN;;;;;;;;EAyBR,iBAAiB,WAAW,UAAU;UAS9B;UAoBA;UAMA;UAgBA;EASR"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"taskStore.d.mts","names":[],"sources":["../../src/store/taskStore.ts"],"mappings":";;;UAkBiB;EACf;EACA,MAAM,OAAO;EACb;;;EAGA;;EAEA;;EAEA,SAAS;;;;;;;;;;cAsCE;EACX;mBAEiB;mBACA;UACT;UACA;UACA;UACA;UACA;mBACS;mBACA;mBACA;mBACA;EAEL,YAAA,UAAS;;EAUrB,iBAAiB;;MASb,YAAY;EAIhB,QAAQ;;;;;;;;EAwBF,OAAO,GACX,SAAS,UAAU;IAAmB,WAAW;IAAc,OAAO;MACrE;IAAU,UAAU;IAAc,OAAO;;UAepC;UAWM;;UAoCN;;;;;;;;EAyBR,iBAAiB,WAAW,UAAU;UAS9B;UAoBA;UAMA;UAgBA;EASR"}
@@ -1,2 +0,0 @@
1
- import{TASK_EVENT as e}from"../logSinkTelemetry.mjs";import{isProcessAlive as t}from"./processLiveness.mjs";import{emptyDocument as n}from"./types.mjs";import{lockPathFor as r,resolveStorePath as i,tempPathFor as a}from"./paths.mjs";import o from"node:path";import s from"node:fs";const c=`utf8`,l=`ENOENT`,u=`store.path`;function d(e){return new Promise(t=>setTimeout(t,e))}function f(e){if(!e||typeof e!=`object`)return n();let t=e;if(!Array.isArray(t.tasks))return n();let r=t.tasks.filter(e=>!!e&&typeof e==`object`&&typeof e.id==`number`),i=r.reduce((e,t)=>Math.max(e,t.id),0);return{version:typeof t.version==`number`?t.version:1,rev:typeof t.rev==`number`?t.rev:0,nextId:typeof t.nextId==`number`&&t.nextId>i?t.nextId:i+1,tasks:r}}var p=class{storePath;cwd;env;cached=n();lastKnownRev=-1;watcher;pollTimer;debounceTimer;listeners=new Set;pollIntervalMs;lockTimeoutMs;report;constructor(e={}){this.cwd=e.cwd??process.cwd(),this.env=e.env??process.env,this.storePath=e.storePath??i(this.cwd,this.env),this.pollIntervalMs=e.pollIntervalMs??2e3,this.lockTimeoutMs=e.lockTimeoutMs??2e3,this.report=e.report}configureSession(e){this.env.DOOM_TASK_STORE?.trim()||(this.stopWatching(),this.storePath=i(this.cwd,this.env,e),this.cached=n(),this.lastKnownRev=-1)}get snapshot(){return this.cached}read(){try{let e=s.readFileSync(this.storePath,c);this.cached=f(JSON.parse(e))}catch(t){t.code!==l&&this.report?.error(e.storeReadFailed,t,{[u]:this.storePath}),this.cached=n()}return this.lastKnownRev=this.cached.rev,this.cached}async mutate(e){let t=await this.acquireLock();try{let t=this.read(),n=e(t);return n.document?{document:this.write(n.document),value:n.value}:{document:t,value:n.value}}finally{t()}}write(e){let t={...e,version:1,rev:e.rev+1};s.mkdirSync(o.dirname(this.storePath),{recursive:!0});let n=a(this.storePath);return s.writeFileSync(n,`${JSON.stringify(t,void 0,2)}\n`,c),s.renameSync(n,this.storePath),this.cached=t,this.lastKnownRev=t.rev,t}async acquireLock(){let t=r(this.storePath);s.mkdirSync(o.dirname(this.storePath),{recursive:!0});let n=Date.now()+this.lockTimeoutMs;for(;;)try{let e=s.openSync(t,`wx`);return s.writeSync(e,JSON.stringify({pid:process.pid,time:Date.now()})),s.closeSync(e),()=>s.rmSync(t,{force:!0})}catch(r){if(r.code!==`EEXIST`)throw r;if(Date.now()>=n)return this.report?.warn(e.storeLockTimeout,Error(`Task store lock still held after ${this.lockTimeoutMs}ms; proceeding without it`),{[u]:this.storePath}),()=>{};this.breakStaleLock(t),await d(10+Math.random()*60)}}breakStaleLock(n){try{let e=JSON.parse(s.readFileSync(n,c)),r=typeof e.time==`number`&&Date.now()-e.time>1e4,i=typeof e.pid==`number`&&!t(e.pid);return!r&&!i?!1:(s.unlinkSync(n),!0)}catch(t){return t.code!==l&&this.report?.warn(e.storeLockBreakFailed,t,{[u]:n}),!1}}onExternalChange(e){return this.listeners.add(e),this.startWatching(),()=>{this.listeners.delete(e),this.listeners.size===0&&this.stopWatching()}}startWatching(){if(this.watcher||this.pollTimer)return;let t=o.dirname(this.storePath),n=o.basename(this.storePath);try{s.mkdirSync(t,{recursive:!0}),this.watcher=s.watch(t,(e,t)=>{t&&t!==n||this.scheduleCheck()})}catch(t){this.report?.warn(e.storeWatchFailed,t,{[u]:this.storePath})}this.pollTimer=setInterval(()=>this.checkForChange(),this.pollIntervalMs),this.pollTimer.unref?.()}scheduleCheck(){clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>this.checkForChange(),150),this.debounceTimer.unref?.()}checkForChange(){let t=this.lastKnownRev,n=this.read();if(n.rev!==t)for(let t of this.listeners)try{t(n)}catch(t){this.report?.error(e.storeListenerFailed,t,{[u]:this.storePath})}}stopWatching(){this.watcher?.close(),this.watcher=void 0,this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=void 0,clearTimeout(this.debounceTimer),this.debounceTimer=void 0}dispose(){this.listeners.clear(),this.stopWatching()}};export{p as TaskStore};
2
- //# sourceMappingURL=taskStore.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"taskStore.mjs","names":[],"sources":["../../src/store/taskStore.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { TASK_EVENT, type TaskFailureReporter } from '../logSinkTelemetry.ts';\nimport { lockPathFor, resolveStorePath, STORE_PATH_ENV, tempPathFor } from './paths.ts';\nimport { isProcessAlive } from './processLiveness.ts';\nimport { emptyDocument, STORE_SCHEMA_VERSION, type Task, type TaskDocument } from './types.ts';\n\nconst LOCK_TIMEOUT_MS = 2000;\nconst LOCK_STALE_MS = 10_000;\nconst LOCK_RETRY_BASE_MS = 10;\nconst LOCK_RETRY_MAX_MS = 60;\nconst WATCH_DEBOUNCE_MS = 150;\nconst POLL_INTERVAL_MS = 2000;\nconst UTF8_ENCODING = 'utf8';\nconst MISSING_FILE_CODE = 'ENOENT';\nconst LOCK_EXISTS_CODE = 'EEXIST';\nconst STORE_PATH_ATTRIBUTE = 'store.path';\n\nexport interface TaskStoreOptions {\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n storePath?: string;\n /** Backstop poll cadence for change detection. Lowered in tests so they do\n * not depend on `fs.watch`, whose delivery timing is platform-dependent. */\n pollIntervalMs?: number;\n /** How long to wait for the advisory lock before proceeding lock-free. */\n lockTimeoutMs?: number;\n /** Where swallowed failures go, so silent degradation stays visible. */\n report?: TaskFailureReporter;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Coerce arbitrary parsed JSON into a valid document.\n *\n * A corrupt or truncated store must not take the session down: the worst\n * acceptable outcome is starting from an empty list, never a crash on startup.\n */\nfunction normalizeDocument(parsed: unknown): TaskDocument {\n if (!parsed || typeof parsed !== 'object') return emptyDocument();\n const candidate = parsed as Partial<TaskDocument>;\n if (!Array.isArray(candidate.tasks)) return emptyDocument();\n\n const tasks = candidate.tasks.filter(\n (task): task is Task => Boolean(task) && typeof task === 'object' && typeof (task as Task).id === 'number',\n );\n const maxId = tasks.reduce((max, task) => Math.max(max, task.id), 0);\n return {\n version: typeof candidate.version === 'number' ? candidate.version : STORE_SCHEMA_VERSION,\n rev: typeof candidate.rev === 'number' ? candidate.rev : 0,\n nextId: typeof candidate.nextId === 'number' && candidate.nextId > maxId ? candidate.nextId : maxId + 1,\n tasks,\n };\n}\n\n/**\n * File-backed task store shared by one root session and its delegated children.\n *\n * Durability model: the JSON file is the source of truth. Mutations are\n * read-modify-write under an advisory lock so concurrent delegated processes\n * cannot clobber each other, and writes land via temp-file rename so a\n * crash mid-write can never leave a partial document behind.\n */\nexport class TaskStore {\n storePath: string;\n\n private readonly cwd: string;\n private readonly env: NodeJS.ProcessEnv;\n private cached: TaskDocument = emptyDocument();\n private lastKnownRev = -1;\n private watcher?: fs.FSWatcher;\n private pollTimer?: NodeJS.Timeout;\n private debounceTimer?: NodeJS.Timeout;\n private readonly listeners = new Set<(document: TaskDocument) => void>();\n private readonly pollIntervalMs: number;\n private readonly lockTimeoutMs: number;\n private readonly report?: TaskFailureReporter;\n\n constructor(options: TaskStoreOptions = {}) {\n this.cwd = options.cwd ?? process.cwd();\n this.env = options.env ?? process.env;\n this.storePath = options.storePath ?? resolveStorePath(this.cwd, this.env);\n this.pollIntervalMs = options.pollIntervalMs ?? POLL_INTERVAL_MS;\n this.lockTimeoutMs = options.lockTimeoutMs ?? LOCK_TIMEOUT_MS;\n this.report = options.report;\n }\n\n /** Bind a default store to the current session tree before reading or watching it. */\n configureSession(sessionKey: string): void {\n if (this.env[STORE_PATH_ENV]?.trim()) return;\n this.stopWatching();\n this.storePath = resolveStorePath(this.cwd, this.env, sessionKey);\n this.cached = emptyDocument();\n this.lastKnownRev = -1;\n }\n\n /** Last document read from disk, without hitting the filesystem. */\n get snapshot(): TaskDocument {\n return this.cached;\n }\n\n read(): TaskDocument {\n try {\n const raw = fs.readFileSync(this.storePath, UTF8_ENCODING);\n this.cached = normalizeDocument(JSON.parse(raw));\n } catch (error) {\n // A missing file is the normal state before the first write. Anything\n // else means the task list just silently became empty, which is worth a\n // record: unreadable or corrupt JSON looks identical to \"no tasks yet\".\n if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n this.report?.error(TASK_EVENT.storeReadFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n this.cached = emptyDocument();\n }\n this.lastKnownRev = this.cached.rev;\n return this.cached;\n }\n\n /**\n * Apply a mutation under the store lock.\n *\n * `mutate` receives the freshest on-disk document and returns either the next\n * document to commit or `undefined` for a read-only action (list/get), which\n * skips the write entirely so queries never bump `rev`.\n */\n async mutate<T>(\n mutate: (document: TaskDocument) => { document?: TaskDocument; value: T },\n ): Promise<{ document: TaskDocument; value: T }> {\n const release = await this.acquireLock();\n try {\n const current = this.read();\n const outcome = mutate(current);\n if (!outcome.document) {\n return { document: current, value: outcome.value };\n }\n const committed = this.write(outcome.document);\n return { document: committed, value: outcome.value };\n } finally {\n release();\n }\n }\n\n private write(document: TaskDocument): TaskDocument {\n const next: TaskDocument = { ...document, version: STORE_SCHEMA_VERSION, rev: document.rev + 1 };\n fs.mkdirSync(path.dirname(this.storePath), { recursive: true });\n const temp = tempPathFor(this.storePath);\n fs.writeFileSync(temp, `${JSON.stringify(next, undefined, 2)}\\n`, UTF8_ENCODING);\n fs.renameSync(temp, this.storePath);\n this.cached = next;\n this.lastKnownRev = next.rev;\n return next;\n }\n\n private async acquireLock(): Promise<() => void> {\n const lockPath = lockPathFor(this.storePath);\n fs.mkdirSync(path.dirname(this.storePath), { recursive: true });\n const deadline = Date.now() + this.lockTimeoutMs;\n\n for (;;) {\n try {\n const handle = fs.openSync(lockPath, 'wx');\n fs.writeSync(handle, JSON.stringify({ pid: process.pid, time: Date.now() }));\n fs.closeSync(handle);\n return () => fs.rmSync(lockPath, { force: true });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== LOCK_EXISTS_CODE) throw error;\n // The deadline is checked before breaking a stale lock so a peer that\n // keeps recreating one cannot spin this loop without bound.\n if (Date.now() >= deadline) {\n // Proceeding lock-free beats stalling the agent: the rename is atomic,\n // so the worst case is a lost concurrent update, not a corrupt file.\n // Reported because a lost update here can strand a delegation.\n this.report?.warn(\n TASK_EVENT.storeLockTimeout,\n new Error(`Task store lock still held after ${this.lockTimeoutMs}ms; proceeding without it`),\n { [STORE_PATH_ATTRIBUTE]: this.storePath },\n );\n return () => {};\n }\n // Clearing a dead holder's lock still goes through the backoff. Yielding\n // on every iteration is what stops a peer that keeps recreating the\n // lock from turning this into a spin.\n this.breakStaleLock(lockPath);\n await sleep(LOCK_RETRY_BASE_MS + Math.random() * LOCK_RETRY_MAX_MS);\n }\n }\n }\n\n /** Remove a lock left behind by a dead process or one held implausibly long. */\n private breakStaleLock(lockPath: string): boolean {\n try {\n const holder = JSON.parse(fs.readFileSync(lockPath, UTF8_ENCODING)) as { pid?: number; time?: number };\n const expired = typeof holder.time === 'number' && Date.now() - holder.time > LOCK_STALE_MS;\n const dead = typeof holder.pid === 'number' && !isProcessAlive(holder.pid);\n if (!expired && !dead) return false;\n fs.unlinkSync(lockPath);\n return true;\n } catch (error) {\n // Losing the race to another breaker is normal; a persistent failure here\n // shows up as the lock timeout above, so this stays a warning.\n if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n this.report?.warn(TASK_EVENT.storeLockBreakFailed, error, { [STORE_PATH_ATTRIBUTE]: lockPath });\n }\n return false;\n }\n }\n\n /**\n * Notify when another process changes the store.\n *\n * `fs.watch` alone is unreliable across the rename-based write (and on some\n * network filesystems), so a slow poll backs it up. Writes made by this\n * process are filtered out by revision so the UI does not redraw twice.\n */\n onExternalChange(listener: (document: TaskDocument) => void): () => void {\n this.listeners.add(listener);\n this.startWatching();\n return () => {\n this.listeners.delete(listener);\n if (this.listeners.size === 0) this.stopWatching();\n };\n }\n\n private startWatching(): void {\n if (this.watcher || this.pollTimer) return;\n const directory = path.dirname(this.storePath);\n const fileName = path.basename(this.storePath);\n\n try {\n fs.mkdirSync(directory, { recursive: true });\n this.watcher = fs.watch(directory, (_event, changed) => {\n if (changed && changed !== fileName) return;\n this.scheduleCheck();\n });\n } catch (error) {\n // Polling still covers change detection, just more slowly.\n this.report?.warn(TASK_EVENT.storeWatchFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n\n this.pollTimer = setInterval(() => this.checkForChange(), this.pollIntervalMs);\n this.pollTimer.unref?.();\n }\n\n private scheduleCheck(): void {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = setTimeout(() => this.checkForChange(), WATCH_DEBOUNCE_MS);\n this.debounceTimer.unref?.();\n }\n\n private checkForChange(): void {\n const previousRev = this.lastKnownRev;\n const document = this.read();\n if (document.rev === previousRev) return;\n for (const listener of this.listeners) {\n try {\n listener(document);\n } catch (error) {\n // This runs from a timer and from the fs.watch callback, so an\n // unguarded listener throw is an uncaught exception that takes the\n // harness down rather than a handled render failure.\n this.report?.error(TASK_EVENT.storeListenerFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n }\n }\n\n private stopWatching(): void {\n this.watcher?.close();\n this.watcher = undefined;\n if (this.pollTimer) clearInterval(this.pollTimer);\n this.pollTimer = undefined;\n clearTimeout(this.debounceTimer);\n this.debounceTimer = undefined;\n }\n\n dispose(): void {\n this.listeners.clear();\n this.stopWatching();\n }\n}\n"],"mappings":"yRAOA,MAMM,EAAgB,OAChB,EAAoB,SAEpB,EAAuB,aAe7B,SAAS,EAAM,EAA2B,CACxC,OAAO,IAAI,QAAS,GAAY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,KAAK,QAAU,EAAG,MAAM,GAAY,EAAQ,IAAY,CAClD,GAAW,IAAY,GAC3B,KAAK,cAAc,CACrB,CAAC,CACH,OAAS,EAAO,CAEd,KAAK,QAAQ,KAAK,EAAW,iBAAkB,EAAO,EAAG,GAAuB,KAAK,SAAU,CAAC,CAClG,CAEA,KAAK,UAAY,gBAAkB,KAAK,eAAe,EAAG,KAAK,cAAc,EAC7E,KAAK,UAAU,QAAQ,CACzB,CAEA,eAA8B,CAC5B,aAAa,KAAK,aAAa,EAC/B,KAAK,cAAgB,eAAiB,KAAK,eAAe,EAAG,GAAiB,EAC9E,KAAK,cAAc,QAAQ,CAC7B,CAEA,gBAA+B,CAC7B,IAAM,EAAc,KAAK,aACnB,EAAW,KAAK,KAAK,EACvB,KAAS,MAAQ,EACrB,IAAK,IAAM,KAAY,KAAK,UAC1B,GAAI,CACF,EAAS,CAAQ,CACnB,OAAS,EAAO,CAId,KAAK,QAAQ,MAAM,EAAW,oBAAqB,EAAO,EAAG,GAAuB,KAAK,SAAU,CAAC,CACtG,CAEJ,CAEA,cAA6B,CAC3B,KAAK,SAAS,MAAM,EACpB,KAAK,QAAU,IAAA,GACX,KAAK,WAAW,cAAc,KAAK,SAAS,EAChD,KAAK,UAAY,IAAA,GACjB,aAAa,KAAK,aAAa,EAC/B,KAAK,cAAgB,IAAA,EACvB,CAEA,SAAgB,CACd,KAAK,UAAU,MAAM,EACrB,KAAK,aAAa,CACpB,CACF"}
@@ -1,2 +0,0 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});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
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.cjs","names":[],"sources":["../../src/store/types.ts"],"sourcesContent":["/**\n * Domain types for the file-backed task store.\n *\n * The on-disk document is the durable source of truth (unlike rpiv-todo, which\n * replayed state from the transcript). Every field here round-trips through\n * JSON, so nothing may hold non-serializable values.\n */\n\nimport type { InlineAgent } from '@agimon-ai/doompi-extension-contracts/subagent-tool';\n\nexport type TaskStatus = 'pending' | 'in_progress' | 'completed' | 'failed' | 'deleted';\n\nexport const DELETED_STATUS: TaskStatus = 'deleted';\n\nexport type TaskAction = 'upsert' | 'list' | 'get' | 'delete' | 'clear' | 'assign' | 'cancel';\n\nexport type DelegationState = 'requested' | 'running' | 'completed' | 'failed' | 'cancelled';\n\n/** Terminal result of a delegated subagent run, copied off the delegation response. */\nexport interface DelegationResult {\n status: string;\n output?: string;\n outputPath?: string;\n sessionFile?: string;\n error?: string;\n durationMs?: number;\n toolCount?: number;\n}\n\n/**\n * Delegation bookkeeping attached to a task that was handed to a subagent.\n *\n * `pid` is the harness process that owns the run: it is the only way to tell an\n * genuinely-running delegation from one orphaned by a harness crash, since the\n * child dies with its parent but the file survives.\n */\nexport interface TaskDelegation {\n requestId: string;\n agent: string;\n state: DelegationState;\n sessionId?: string;\n pid?: number;\n runId?: string;\n model?: string;\n startedAt?: string;\n endedAt?: string;\n result?: DelegationResult;\n}\n\nexport interface Task {\n id: number;\n subject: string;\n description?: string;\n activeForm?: string;\n status: TaskStatus;\n blockedBy?: number[];\n owner?: string;\n metadata?: Record<string, unknown>;\n createdAt?: string;\n updatedAt?: string;\n delegation?: TaskDelegation;\n}\n\nexport const STORE_SCHEMA_VERSION = 1;\n\n/** The complete on-disk document. `rev` increments on every committed write. */\nexport interface TaskDocument {\n version: number;\n rev: number;\n nextId: number;\n tasks: Task[];\n}\n\nexport function emptyDocument(): TaskDocument {\n return { version: STORE_SCHEMA_VERSION, rev: 0, nextId: 1, tasks: [] };\n}\n\n/**\n * A dependency target inside an upsert item: an existing task id, or the `ref`\n * of a task created earlier in the same call.\n *\n * Refs must start with a letter (see `REF_PATTERN`), so a ref is structurally\n * unconfusable with a stringified id and the discrimination is just `typeof`.\n */\nexport type DepToken = number | string;\n\n/**\n * One entry of an `upsert` call. No `id` creates a task; an `id` updates one.\n *\n * `blockedBy` (absolute set) is create-only and `addBlockedBy`/`removeBlockedBy`\n * (additive merge) are update-only, matching the split the two former actions\n * had. A field used against the wrong kind fails that item rather than being\n * silently ignored.\n */\nexport interface TaskItemMutation {\n id?: number;\n ref?: string;\n subject?: string;\n description?: string;\n activeForm?: string;\n status?: TaskStatus;\n blockedBy?: DepToken[];\n addBlockedBy?: DepToken[];\n removeBlockedBy?: DepToken[];\n owner?: string;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * What one upsert item did. `index` is its position in the request array, so a\n * model reading a partial result can tell which entries still need resending.\n *\n * `message` is unprefixed: the `item[N] failed:` framing belongs to the\n * formatter, because the Task Space overlay shows this text on its own.\n */\nexport type UpsertItemOutcome =\n | {\n index: number;\n kind: 'created';\n id: number;\n subject: string;\n status: TaskStatus;\n ref?: string;\n blockedBy?: number[];\n }\n | { index: number; kind: 'updated'; id: number; fromStatus: TaskStatus; toStatus: TaskStatus }\n | { index: number; kind: 'unchanged'; id: number; status: TaskStatus }\n | { index: number; kind: 'failed'; message: string; id?: number; ref?: string };\n\n/** Which tasks an upsert touched, so renderResult names them instead of guessing. */\nexport interface UpsertSummary {\n /** Ids of applied entries, in request order. A failed entry contributes nothing. */\n applied: number[];\n failed: number;\n}\n\n/**\n * Open-shape input bag the reducer accepts. The index signature lets the\n * runtime pass a TypeBox `Static<typeof TaskParamsSchema>` through without\n * casting each field.\n *\n * Per-task fields live on `tasks[]`, not here: a top-level `subject` or\n * `status` would be ambiguous once one call can carry many tasks.\n */\nexport interface TaskMutationParams {\n [key: string]: unknown;\n tasks?: TaskItemMutation[];\n /** `list` filter only. To set a status, upsert the task by id. */\n status?: TaskStatus;\n /** `get`, `delete`, `assign` and `cancel` only. */\n id?: number;\n includeDeleted?: boolean;\n agent?: string;\n inlineAgent?: InlineAgent;\n instructions?: string;\n /** `assign` only: the context pack the parent hands to the child. */\n relevantFiles?: string[];\n priorFindings?: string;\n model?: string;\n context?: 'fresh' | 'fork';\n}\n\n/** Snapshot returned under a tool result's `details` for renderResult. */\nexport interface TaskDetails {\n action: TaskAction;\n params: Record<string, unknown>;\n tasks: Task[];\n nextId: number;\n rev: number;\n error?: string;\n upsert?: UpsertSummary;\n}\n\n/** A delegation is \"live\" while the owning run may still produce a response. */\nexport function isDelegationActive(task: Task): boolean {\n const state = task.delegation?.state;\n return state === 'requested' || state === 'running';\n}\n"],"mappings":"mEAyEA,SAAgB,GAA8B,CAC5C,MAAO,CAAE,QAAA,EAA+B,IAAK,EAAG,OAAQ,EAAG,MAAO,CAAC,CAAE,CACvE,CAmGA,SAAgB,EAAmB,EAAqB,CACtD,IAAM,EAAQ,EAAK,YAAY,MAC/B,OAAO,IAAU,aAAe,IAAU,SAC5C"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.d.cts","names":[],"sources":["../../src/store/types.ts"],"mappings":";;KAUY;cAEC,gBAAgB;KAEjB;KAEA;;UAGK;EACf;EACA;EACA;EACA;EACA;EACA;EACA;;;;;;;;;UAUe;EACf;EACA;EACA,OAAO;EACP;EACA;EACA;EACA;EACA;EACA;EACA,SAAS;;UAGM;EACf;EACA;EACA;EACA;EACA,QAAQ;EACR;EACA;EACA,WAAW;EACX;EACA;EACA,aAAa;;cAGF;;UAGI;EACf;EACA;EACA;EACA,OAAO;;iBAGO,iBAAiB;;;;;;;;KAWrB;;;;;;;;;UAUK;EACf;EACA;EACA;EACA;EACA;EACA,SAAS;EACT,YAAY;EACZ,eAAe;EACf,kBAAkB;EAClB;EACA,WAAW;;;;;;;;;KAUD;EAEN;EACA;EACA;EACA;EACA,QAAQ;EACR;EACA;;EAEA;EAAe;EAAiB;EAAY,YAAY;EAAY,UAAU;;EAC9E;EAAe;EAAmB;EAAY,QAAQ;;EACtD;EAAe;EAAgB;EAAiB;EAAa;;;UAGlD;;EAEf;EACA;;;;;;;;;;UAWe;GACd;EACD,QAAQ;;EAER,SAAS;;EAET;EACA;EACA;EACA,cAAc;EACd;;EAEA;EACA;EACA;EACA;;;UAIe;EACf,QAAQ;EACR,QAAQ;EACR,OAAO;EACP;EACA;EACA;EACA,SAAS;;;iBAIK,mBAAmB,MAAM"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.d.mts","names":[],"sources":["../../src/store/types.ts"],"mappings":";;KAUY;cAEC,gBAAgB;KAEjB;KAEA;;UAGK;EACf;EACA;EACA;EACA;EACA;EACA;EACA;;;;;;;;;UAUe;EACf;EACA;EACA,OAAO;EACP;EACA;EACA;EACA;EACA;EACA;EACA,SAAS;;UAGM;EACf;EACA;EACA;EACA;EACA,QAAQ;EACR;EACA;EACA,WAAW;EACX;EACA;EACA,aAAa;;cAGF;;UAGI;EACf;EACA;EACA;EACA,OAAO;;iBAGO,iBAAiB;;;;;;;;KAWrB;;;;;;;;;UAUK;EACf;EACA;EACA;EACA;EACA;EACA,SAAS;EACT,YAAY;EACZ,eAAe;EACf,kBAAkB;EAClB;EACA,WAAW;;;;;;;;;KAUD;EAEN;EACA;EACA;EACA;EACA,QAAQ;EACR;EACA;;EAEA;EAAe;EAAiB;EAAY,YAAY;EAAY,UAAU;;EAC9E;EAAe;EAAmB;EAAY,QAAQ;;EACtD;EAAe;EAAgB;EAAiB;EAAa;;;UAGlD;;EAEf;EACA;;;;;;;;;;UAWe;GACd;EACD,QAAQ;;EAER,SAAS;;EAET;EACA;EACA;EACA,cAAc;EACd;;EAEA;EACA;EACA;EACA;;;UAIe;EACf,QAAQ;EACR,QAAQ;EACR,OAAO;EACP;EACA;EACA;EACA,SAAS;;;iBAIK,mBAAmB,MAAM"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.mjs","names":[],"sources":["../../src/store/types.ts"],"sourcesContent":["/**\n * Domain types for the file-backed task store.\n *\n * The on-disk document is the durable source of truth (unlike rpiv-todo, which\n * replayed state from the transcript). Every field here round-trips through\n * JSON, so nothing may hold non-serializable values.\n */\n\nimport type { InlineAgent } from '@agimon-ai/doompi-extension-contracts/subagent-tool';\n\nexport type TaskStatus = 'pending' | 'in_progress' | 'completed' | 'failed' | 'deleted';\n\nexport const DELETED_STATUS: TaskStatus = 'deleted';\n\nexport type TaskAction = 'upsert' | 'list' | 'get' | 'delete' | 'clear' | 'assign' | 'cancel';\n\nexport type DelegationState = 'requested' | 'running' | 'completed' | 'failed' | 'cancelled';\n\n/** Terminal result of a delegated subagent run, copied off the delegation response. */\nexport interface DelegationResult {\n status: string;\n output?: string;\n outputPath?: string;\n sessionFile?: string;\n error?: string;\n durationMs?: number;\n toolCount?: number;\n}\n\n/**\n * Delegation bookkeeping attached to a task that was handed to a subagent.\n *\n * `pid` is the harness process that owns the run: it is the only way to tell an\n * genuinely-running delegation from one orphaned by a harness crash, since the\n * child dies with its parent but the file survives.\n */\nexport interface TaskDelegation {\n requestId: string;\n agent: string;\n state: DelegationState;\n sessionId?: string;\n pid?: number;\n runId?: string;\n model?: string;\n startedAt?: string;\n endedAt?: string;\n result?: DelegationResult;\n}\n\nexport interface Task {\n id: number;\n subject: string;\n description?: string;\n activeForm?: string;\n status: TaskStatus;\n blockedBy?: number[];\n owner?: string;\n metadata?: Record<string, unknown>;\n createdAt?: string;\n updatedAt?: string;\n delegation?: TaskDelegation;\n}\n\nexport const STORE_SCHEMA_VERSION = 1;\n\n/** The complete on-disk document. `rev` increments on every committed write. */\nexport interface TaskDocument {\n version: number;\n rev: number;\n nextId: number;\n tasks: Task[];\n}\n\nexport function emptyDocument(): TaskDocument {\n return { version: STORE_SCHEMA_VERSION, rev: 0, nextId: 1, tasks: [] };\n}\n\n/**\n * A dependency target inside an upsert item: an existing task id, or the `ref`\n * of a task created earlier in the same call.\n *\n * Refs must start with a letter (see `REF_PATTERN`), so a ref is structurally\n * unconfusable with a stringified id and the discrimination is just `typeof`.\n */\nexport type DepToken = number | string;\n\n/**\n * One entry of an `upsert` call. No `id` creates a task; an `id` updates one.\n *\n * `blockedBy` (absolute set) is create-only and `addBlockedBy`/`removeBlockedBy`\n * (additive merge) are update-only, matching the split the two former actions\n * had. A field used against the wrong kind fails that item rather than being\n * silently ignored.\n */\nexport interface TaskItemMutation {\n id?: number;\n ref?: string;\n subject?: string;\n description?: string;\n activeForm?: string;\n status?: TaskStatus;\n blockedBy?: DepToken[];\n addBlockedBy?: DepToken[];\n removeBlockedBy?: DepToken[];\n owner?: string;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * What one upsert item did. `index` is its position in the request array, so a\n * model reading a partial result can tell which entries still need resending.\n *\n * `message` is unprefixed: the `item[N] failed:` framing belongs to the\n * formatter, because the Task Space overlay shows this text on its own.\n */\nexport type UpsertItemOutcome =\n | {\n index: number;\n kind: 'created';\n id: number;\n subject: string;\n status: TaskStatus;\n ref?: string;\n blockedBy?: number[];\n }\n | { index: number; kind: 'updated'; id: number; fromStatus: TaskStatus; toStatus: TaskStatus }\n | { index: number; kind: 'unchanged'; id: number; status: TaskStatus }\n | { index: number; kind: 'failed'; message: string; id?: number; ref?: string };\n\n/** Which tasks an upsert touched, so renderResult names them instead of guessing. */\nexport interface UpsertSummary {\n /** Ids of applied entries, in request order. A failed entry contributes nothing. */\n applied: number[];\n failed: number;\n}\n\n/**\n * Open-shape input bag the reducer accepts. The index signature lets the\n * runtime pass a TypeBox `Static<typeof TaskParamsSchema>` through without\n * casting each field.\n *\n * Per-task fields live on `tasks[]`, not here: a top-level `subject` or\n * `status` would be ambiguous once one call can carry many tasks.\n */\nexport interface TaskMutationParams {\n [key: string]: unknown;\n tasks?: TaskItemMutation[];\n /** `list` filter only. To set a status, upsert the task by id. */\n status?: TaskStatus;\n /** `get`, `delete`, `assign` and `cancel` only. */\n id?: number;\n includeDeleted?: boolean;\n agent?: string;\n inlineAgent?: InlineAgent;\n instructions?: string;\n /** `assign` only: the context pack the parent hands to the child. */\n relevantFiles?: string[];\n priorFindings?: string;\n model?: string;\n context?: 'fresh' | 'fork';\n}\n\n/** Snapshot returned under a tool result's `details` for renderResult. */\nexport interface TaskDetails {\n action: TaskAction;\n params: Record<string, unknown>;\n tasks: Task[];\n nextId: number;\n rev: number;\n error?: string;\n upsert?: UpsertSummary;\n}\n\n/** A delegation is \"live\" while the owning run may still produce a response. */\nexport function isDelegationActive(task: Task): boolean {\n const state = task.delegation?.state;\n return state === 'requested' || state === 'running';\n}\n"],"mappings":"AAYA,MAAa,EAA6B,UAmD7B,EAAuB,EAUpC,SAAgB,GAA8B,CAC5C,MAAO,CAAE,QAAA,EAA+B,IAAK,EAAG,OAAQ,EAAG,MAAO,CAAC,CAAE,CACvE,CAmGA,SAAgB,EAAmB,EAAqB,CACtD,IAAM,EAAQ,EAAK,YAAY,MAC/B,OAAO,IAAU,aAAe,IAAU,SAC5C"}
@@ -1,2 +0,0 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=["Use `task` for work with 3+ steps, when the user gives you a list of tasks, or immediately after receiving new instructions to capture requirements. Skip it for single trivial tasks and purely conversational requests.",`Capture a whole plan in one call: {"action":"upsert","tasks":[{"subject":"Research existing tool"},{"subject":"Write the reducer"},{"subject":"Add tests"}]}. Batch whenever you are writing the plan down — the initial list, a revised plan, or wiring dependencies across several tasks — because one call keeps ids and blockers consistent and shows the user the whole plan at once.`,`Do not batch progress. Mark a task in_progress with its own call BEFORE beginning work, and completed with its own call IMMEDIATELY when it is done. upsert accepts many tasks, but a batch of completions sent at the end of a turn is still wrong: batching is for writing a plan down, single calls are for reporting progress, and the user watches the task list to see where you are. Exactly one task should be in_progress for your own work; delegated tasks run in parallel and do not count against that.`,`Never mark a task completed if tests are failing, the implementation is partial, or you hit unresolved errors, use status "failed" or keep it in_progress and add a new task for the blocker in the same upsert.`,`When every non-deleted task is completed, review the full task list once more and call task {"action":"clear"} to close it. Do not leave an all-completed list open.`,`Status is a state machine: pending → in_progress → completed, plus failed (recoverable, can go back to pending or in_progress) and deleted as a tombstone. Pass activeForm (present-continuous, e.g. 'writing tests') when marking in_progress.`,`One call does both: an entry with an id changes that task, an entry without an id creates one. To change status, upsert the task by id, e.g. {"action":"upsert","tasks":[{"id":3,"status":"completed"}]}. Never omit the id when you meant to change an existing task — an entry with no id creates a new one instead. An entry that carries an id and no other field is rejected.`,`Use blockedBy for dependencies (A is blocked by B). On an entry with no id pass blockedBy as the initial set; on an entry with an id use addBlockedBy / removeBlockedBy (additive merge, do not resend the full array). To depend on a task created earlier in the SAME call, give that earlier entry a "ref" and list the ref string in place of an id: [{"ref":"api","subject":"Design the API"},{"subject":"Implement the API","blockedBy":["api"]}]. A ref must be declared before it is used. Cycles are rejected.`,`upsert applies each entry independently: the entries that pass are committed and the failures are reported with their array index. A failed entry changed nothing, so resend only the corrected failures — never resend the whole call, because an already-applied entry with no id would create a duplicate task.`,`Before assigning work, call subagent with {"action":"agents"} and match each task to an exact discovered agent name. Prefer a discovered general-purpose write-capable agent such as delegate or worker when no specialist fits. Use a focused inlineAgent only for read-only work.`,`Assign every unblocked pending task with task {"action":"assign","id":3,"agent":"reviewer"}, including implementation tasks. Do not use a direct subagent run for work already represented in the shared task list. Use task assign so ownership and terminal results stay visible.`,`Hand over what you already know when you assign. Pass relevantFiles with the paths you have actually read or located for that task, and priorFindings with the facts you established: symbol names, call sites, the approach you picked, what you ruled out. A fresh-context child starts with none of your context and will otherwise spend most of its run re-reading the repo. It treats this verified pack as satisfying initial context exploration, reads known paths directly, and widens discovery only for a concrete missing dependency. Send at most a dozen files and only ones you really opened — a guessed path costs the child more than an omitted one — and keep priorFindings to a few lines of facts, not directives.`,`After assigning work, continue non-overlapping parent work or end your turn. Do not poll or duplicate delegated scope.`,`When a delegated task completes and unblocks another task, repeat agent discovery if needed and assign that newly eligible task promptly. Do not poll in a loop. Completion notifications wake the parent session.`,`If a child asks for a decision through intercom, or an assignment fails to start for another concrete issue, respond, rescope, or retry explicitly. Do not silently leave the task pending.`,`assign refuses tasks that are blocked, already delegated, or completed. Resolve blockers first. Use {"action":"cancel","id":3} to stop a running delegation; the task returns to pending.`,`Doom Task records delegated lifecycle and results on the shared task. The child does not update task status directly. Read the completion or failure result before deciding what to do next.`,`The task list is scoped to this session tree: delegated subagents share it, while unrelated sessions start empty. It persists for later inspection until retention cleanup.`,`Subject must be short and imperative (e.g. 'Research existing tool'); description is long-form detail written when you plan the task, and the delegated brief is that description plus the assign-time instructions, relevantFiles and priorFindings. Put durable scope in description and what you learned while exploring in the assign-time pack — do not repeat one in the other.`];exports.DEFAULT_PROMPT_GUIDELINES=e;
2
- //# sourceMappingURL=promptGuidelines.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"promptGuidelines.cjs","names":[],"sources":["../../src/tool/promptGuidelines.ts"],"sourcesContent":["export const DEFAULT_PROMPT_GUIDELINES: string[] = [\n 'Use `task` for work with 3+ steps, when the user gives you a list of tasks, or immediately after receiving new instructions to capture requirements. Skip it for single trivial tasks and purely conversational requests.',\n 'Capture a whole plan in one call: {\"action\":\"upsert\",\"tasks\":[{\"subject\":\"Research existing tool\"},{\"subject\":\"Write the reducer\"},{\"subject\":\"Add tests\"}]}. Batch whenever you are writing the plan down — the initial list, a revised plan, or wiring dependencies across several tasks — because one call keeps ids and blockers consistent and shows the user the whole plan at once.',\n 'Do not batch progress. Mark a task in_progress with its own call BEFORE beginning work, and completed with its own call IMMEDIATELY when it is done. upsert accepts many tasks, but a batch of completions sent at the end of a turn is still wrong: batching is for writing a plan down, single calls are for reporting progress, and the user watches the task list to see where you are. Exactly one task should be in_progress for your own work; delegated tasks run in parallel and do not count against that.',\n 'Never mark a task completed if tests are failing, the implementation is partial, or you hit unresolved errors, use status \"failed\" or keep it in_progress and add a new task for the blocker in the same upsert.',\n 'When every non-deleted task is completed, review the full task list once more and call task {\"action\":\"clear\"} to close it. Do not leave an all-completed list open.',\n \"Status is a state machine: pending → in_progress → completed, plus failed (recoverable, can go back to pending or in_progress) and deleted as a tombstone. Pass activeForm (present-continuous, e.g. 'writing tests') when marking in_progress.\",\n 'One call does both: an entry with an id changes that task, an entry without an id creates one. To change status, upsert the task by id, e.g. {\"action\":\"upsert\",\"tasks\":[{\"id\":3,\"status\":\"completed\"}]}. Never omit the id when you meant to change an existing task — an entry with no id creates a new one instead. An entry that carries an id and no other field is rejected.',\n 'Use blockedBy for dependencies (A is blocked by B). On an entry with no id pass blockedBy as the initial set; on an entry with an id use addBlockedBy / removeBlockedBy (additive merge, do not resend the full array). To depend on a task created earlier in the SAME call, give that earlier entry a \"ref\" and list the ref string in place of an id: [{\"ref\":\"api\",\"subject\":\"Design the API\"},{\"subject\":\"Implement the API\",\"blockedBy\":[\"api\"]}]. A ref must be declared before it is used. Cycles are rejected.',\n 'upsert applies each entry independently: the entries that pass are committed and the failures are reported with their array index. A failed entry changed nothing, so resend only the corrected failures — never resend the whole call, because an already-applied entry with no id would create a duplicate task.',\n 'Before assigning work, call subagent with {\"action\":\"agents\"} and match each task to an exact discovered agent name. Prefer a discovered general-purpose write-capable agent such as delegate or worker when no specialist fits. Use a focused inlineAgent only for read-only work.',\n 'Assign every unblocked pending task with task {\"action\":\"assign\",\"id\":3,\"agent\":\"reviewer\"}, including implementation tasks. Do not use a direct subagent run for work already represented in the shared task list. Use task assign so ownership and terminal results stay visible.',\n 'Hand over what you already know when you assign. Pass relevantFiles with the paths you have actually read or located for that task, and priorFindings with the facts you established: symbol names, call sites, the approach you picked, what you ruled out. A fresh-context child starts with none of your context and will otherwise spend most of its run re-reading the repo. It treats this verified pack as satisfying initial context exploration, reads known paths directly, and widens discovery only for a concrete missing dependency. Send at most a dozen files and only ones you really opened — a guessed path costs the child more than an omitted one — and keep priorFindings to a few lines of facts, not directives.',\n 'After assigning work, continue non-overlapping parent work or end your turn. Do not poll or duplicate delegated scope.',\n 'When a delegated task completes and unblocks another task, repeat agent discovery if needed and assign that newly eligible task promptly. Do not poll in a loop. Completion notifications wake the parent session.',\n 'If a child asks for a decision through intercom, or an assignment fails to start for another concrete issue, respond, rescope, or retry explicitly. Do not silently leave the task pending.',\n 'assign refuses tasks that are blocked, already delegated, or completed. Resolve blockers first. Use {\"action\":\"cancel\",\"id\":3} to stop a running delegation; the task returns to pending.',\n 'Doom Task records delegated lifecycle and results on the shared task. The child does not update task status directly. Read the completion or failure result before deciding what to do next.',\n 'The task list is scoped to this session tree: delegated subagents share it, while unrelated sessions start empty. It persists for later inspection until retention cleanup.',\n \"Subject must be short and imperative (e.g. 'Research existing tool'); description is long-form detail written when you plan the task, and the delegated brief is that description plus the assign-time instructions, relevantFiles and priorFindings. Put durable scope in description and what you learned while exploring in the assign-time pack — do not repeat one in the other.\",\n];\n"],"mappings":"mEAAA,MAAa,EAAsC,CACjD,4NACA,6XACA,ufACA,mNACA,uKACA,kPACA,qXACA,0fACA,qTACA,sRACA,sRACA,4sBACA,yHACA,qNACA,8LACA,4LACA,+LACA,8KACA,uXACF"}
@@ -1,5 +0,0 @@
1
- //#region src/tool/promptGuidelines.d.ts
2
- declare const DEFAULT_PROMPT_GUIDELINES: string[];
3
- //#endregion
4
- export { DEFAULT_PROMPT_GUIDELINES };
5
- //# sourceMappingURL=promptGuidelines.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"promptGuidelines.d.cts","names":[],"sources":["../../src/tool/promptGuidelines.ts"],"mappings":";cAAa"}
@@ -1,5 +0,0 @@
1
- //#region src/tool/promptGuidelines.d.ts
2
- declare const DEFAULT_PROMPT_GUIDELINES: string[];
3
- //#endregion
4
- export { DEFAULT_PROMPT_GUIDELINES };
5
- //# sourceMappingURL=promptGuidelines.d.mts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"promptGuidelines.d.mts","names":[],"sources":["../../src/tool/promptGuidelines.ts"],"mappings":";cAAa"}