pi-better-server 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (597) hide show
  1. package/package.json +8 -1
  2. package/scripts/copy-pi-test-providers.mjs +10 -0
  3. package/scripts/event-publication/README.md +26 -0
  4. package/scripts/event-publication/commit.mjs +21 -0
  5. package/scripts/event-publication/measure.mjs +87 -0
  6. package/scripts/event-publication/writer.mjs +6 -0
  7. package/scripts/measure-full-runtime/frontend.ts +24 -0
  8. package/scripts/measure-full-runtime/hosted-extension.ts +28 -0
  9. package/scripts/measure-full-runtime/probe.mjs +29 -0
  10. package/scripts/measure-full-runtime/recovery-trace-loader.mjs +51 -0
  11. package/scripts/measure-full-runtime/recovery-trace.mjs +16 -0
  12. package/scripts/measure-full-runtime.mjs +146 -0
  13. package/scripts/measure-shared-reads/probe.mjs +26 -2
  14. package/scripts/measure-shared-reads.mjs +44 -9
  15. package/scripts/private-runtime/package-lock.json +66 -4
  16. package/scripts/private-runtime/package.json +10 -2
  17. package/scripts/source-provenance.mjs +31 -0
  18. package/scripts/test-on-pi.sh +3 -9
  19. package/src/handshake.ts +1 -1
  20. package/src/hosted-session.ts +32 -4
  21. package/src/maintenance.ts +35 -7
  22. package/src/registry.ts +28 -4
  23. package/src/runtime/attempt-invalidation.ts +54 -0
  24. package/src/runtime/background-history.ts +151 -45
  25. package/src/runtime/background-policy.ts +27 -0
  26. package/src/runtime/background-tools.ts +389 -0
  27. package/src/runtime/background.ts +410 -48
  28. package/src/runtime/cancellation.ts +28 -7
  29. package/src/runtime/catalog-sources.ts +199 -0
  30. package/src/runtime/catalog.ts +53 -21
  31. package/src/runtime/client.ts +22 -2
  32. package/src/runtime/domain/assignment-inbox.mjs +119 -0
  33. package/src/runtime/domain/assignment-observation.d.mts +1 -1
  34. package/src/runtime/domain/assignment-observation.mjs +71 -33
  35. package/src/runtime/domain/background/process-identity.mjs +20 -2
  36. package/src/runtime/domain/background/process.mjs +3 -3
  37. package/src/runtime/domain/background/registry.mjs +89 -4
  38. package/src/runtime/domain/background/types.mjs +1 -0
  39. package/src/runtime/domain/background-service/adapter-contract.domain.mjs +83 -0
  40. package/src/runtime/domain/background-service/adapter-contract.ts +70 -0
  41. package/src/runtime/domain/background-service/batch.domain.mjs +91 -0
  42. package/src/runtime/domain/background-service/batch.ts +111 -0
  43. package/src/runtime/domain/background-service/conditions.domain.mjs +94 -0
  44. package/src/runtime/domain/background-service/conditions.ts +99 -0
  45. package/src/runtime/domain/background-service/delivery-observer.domain.mjs +37 -0
  46. package/src/runtime/domain/background-service/delivery-observer.ts +42 -0
  47. package/src/runtime/domain/background-service/failures.domain.mjs +209 -0
  48. package/src/runtime/domain/background-service/failures.ts +212 -0
  49. package/src/runtime/domain/background-service/goal-provider.domain.mjs +193 -0
  50. package/src/runtime/domain/background-service/goal-provider.ts +209 -0
  51. package/src/runtime/domain/background-service/index.domain.mjs +54 -0
  52. package/src/runtime/domain/background-service/index.ts +55 -0
  53. package/src/runtime/domain/background-service/logs.domain.mjs +129 -0
  54. package/src/runtime/domain/background-service/logs.ts +134 -0
  55. package/src/runtime/domain/background-service/maintenance.domain.mjs +95 -0
  56. package/src/runtime/domain/background-service/maintenance.ts +98 -0
  57. package/src/runtime/domain/background-service/managed-authority.domain.mjs +32 -0
  58. package/src/runtime/domain/background-service/managed-authority.ts +30 -0
  59. package/src/runtime/domain/background-service/managed-client.domain.mjs +79 -0
  60. package/src/runtime/domain/background-service/managed-client.ts +73 -0
  61. package/src/runtime/domain/background-service/managed-frontend.domain.mjs +225 -0
  62. package/src/runtime/domain/background-service/managed-frontend.ts +176 -0
  63. package/src/runtime/domain/background-service/navigator-provider.domain.mjs +492 -0
  64. package/src/runtime/domain/background-service/navigator-provider.ts +485 -0
  65. package/src/runtime/domain/background-service/observed-wait-client.domain.mjs +6 -0
  66. package/src/runtime/domain/background-service/observed-wait-client.ts +10 -0
  67. package/src/runtime/domain/background-service/observed-waits.domain.mjs +4080 -0
  68. package/src/runtime/domain/background-service/observed-waits.ts +4513 -0
  69. package/src/runtime/domain/background-service/output.domain.mjs +867 -0
  70. package/src/runtime/domain/background-service/output.ts +952 -0
  71. package/src/runtime/domain/background-service/process-identity.domain.mjs +129 -0
  72. package/src/runtime/domain/background-service/process-identity.ts +134 -0
  73. package/src/runtime/domain/background-service/process.domain.mjs +512 -0
  74. package/src/runtime/domain/background-service/process.ts +532 -0
  75. package/src/runtime/domain/background-service/prompt.domain.mjs +58 -0
  76. package/src/runtime/domain/background-service/prompt.ts +72 -0
  77. package/src/runtime/domain/background-service/registry.domain.mjs +460 -0
  78. package/src/runtime/domain/background-service/registry.ts +450 -0
  79. package/src/runtime/domain/background-service/remote-task-preset.domain.mjs +67 -0
  80. package/src/runtime/domain/background-service/remote-task-preset.ts +127 -0
  81. package/src/runtime/domain/background-service/runtime.domain.mjs +1511 -0
  82. package/src/runtime/domain/background-service/runtime.ts +1636 -0
  83. package/src/runtime/domain/background-service/sandbox.domain.mjs +735 -0
  84. package/src/runtime/domain/background-service/sandbox.ts +913 -0
  85. package/src/runtime/domain/background-service/shared-callback-batcher.domain.mjs +777 -0
  86. package/src/runtime/domain/background-service/shared-callback-batcher.ts +956 -0
  87. package/src/runtime/domain/background-service/shared-execution-policy.domain.mjs +50 -0
  88. package/src/runtime/domain/background-service/shared-execution-policy.ts +61 -0
  89. package/src/runtime/domain/background-service/shared-failure-observations.domain.mjs +1078 -0
  90. package/src/runtime/domain/background-service/shared-failure-observations.ts +1166 -0
  91. package/src/runtime/domain/background-service/shared-harness-settings.domain.mjs +126 -0
  92. package/src/runtime/domain/background-service/shared-harness-settings.ts +116 -0
  93. package/src/runtime/domain/background-service/shared-log-utils.domain.mjs +1223 -0
  94. package/src/runtime/domain/background-service/shared-log-utils.ts +1492 -0
  95. package/src/runtime/domain/background-service/shared-navigator-panels.domain.mjs +289 -0
  96. package/src/runtime/domain/background-service/shared-navigator-panels.ts +272 -0
  97. package/src/runtime/domain/background-service/shared-navigator.domain.mjs +1930 -0
  98. package/src/runtime/domain/background-service/shared-navigator.ts +1962 -0
  99. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-inbox.mjs +144 -0
  100. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-observation.mjs +189 -0
  101. package/src/runtime/domain/background-service/shared-operation-coordinator/index.domain.mjs +51 -0
  102. package/src/runtime/domain/background-service/shared-operation-coordinator/index.ts +122 -0
  103. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
  104. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  105. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +163 -0
  106. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.ts +174 -0
  107. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-parent-callbacks.domain.mjs +66 -0
  108. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-parent-callbacks.ts +68 -0
  109. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.domain.mjs +87 -0
  110. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.ts +90 -0
  111. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.domain.mjs +97 -0
  112. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.ts +139 -0
  113. package/src/runtime/domain/background-service/shared-operation-coordinator/src/errors.domain.mjs +12 -0
  114. package/src/runtime/domain/background-service/shared-operation-coordinator/src/errors.ts +79 -0
  115. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.domain.mjs +342 -0
  116. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.ts +513 -0
  117. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.domain.mjs +283 -0
  118. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.ts +458 -0
  119. package/src/runtime/domain/background-service/shared-operation-coordinator/src/recovery.domain.mjs +52 -0
  120. package/src/runtime/domain/background-service/shared-operation-coordinator/src/recovery.ts +55 -0
  121. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.domain.mjs +114 -0
  122. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.ts +140 -0
  123. package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.domain.mjs +280 -0
  124. package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.ts +442 -0
  125. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +420 -0
  126. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +441 -0
  127. package/src/runtime/domain/background-service/shared-operation-coordinator/src/sqlite.domain.mjs +194 -0
  128. package/src/runtime/domain/background-service/shared-operation-coordinator/src/sqlite.ts +239 -0
  129. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +275 -0
  130. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +585 -0
  131. package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.domain.mjs +120 -0
  132. package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.ts +142 -0
  133. package/src/runtime/domain/background-service/shared-operation-coordinator/src/task-cancellation.domain.mjs +188 -0
  134. package/src/runtime/domain/background-service/shared-operation-coordinator/src/task-cancellation.ts +224 -0
  135. package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.domain.mjs +25 -0
  136. package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.ts +707 -0
  137. package/src/runtime/domain/background-service/shared-operation-coordinator/src/upgrade.domain.mjs +22 -0
  138. package/src/runtime/domain/background-service/shared-operation-coordinator/src/upgrade.ts +22 -0
  139. package/src/runtime/domain/background-service/shared-operation-coordinator/src/validate.domain.mjs +234 -0
  140. package/src/runtime/domain/background-service/shared-operation-coordinator/src/validate.ts +241 -0
  141. package/src/runtime/domain/background-service/shared-operation-coordinator/src/waits.domain.mjs +851 -0
  142. package/src/runtime/domain/background-service/shared-operation-coordinator/src/waits.ts +1424 -0
  143. package/src/runtime/domain/background-service/shared-permission-blocker.domain.mjs +40 -0
  144. package/src/runtime/domain/background-service/shared-permission-blocker.ts +48 -0
  145. package/src/runtime/domain/background-service/shared-render-scheduler.domain.mjs +41 -0
  146. package/src/runtime/domain/background-service/shared-render-scheduler.ts +47 -0
  147. package/src/runtime/domain/background-service/shared-sandbox-core.domain.mjs +1531 -0
  148. package/src/runtime/domain/background-service/shared-sandbox-core.ts +1757 -0
  149. package/src/runtime/domain/background-service/shared-sandbox-diagnostics.domain.mjs +591 -0
  150. package/src/runtime/domain/background-service/shared-sandbox-diagnostics.ts +491 -0
  151. package/src/runtime/domain/background-service/shared-ssh-core/index.domain.mjs +698 -0
  152. package/src/runtime/domain/background-service/shared-ssh-core/index.ts +979 -0
  153. package/src/runtime/domain/background-service/shared-stall-detector.domain.mjs +37 -0
  154. package/src/runtime/domain/background-service/shared-stall-detector.ts +69 -0
  155. package/src/runtime/domain/background-service/shared-work-client.mjs +303 -0
  156. package/src/runtime/domain/background-service/stall-attention.domain.mjs +29 -0
  157. package/src/runtime/domain/background-service/stall-attention.ts +31 -0
  158. package/src/runtime/domain/background-service/stall.domain.mjs +57 -0
  159. package/src/runtime/domain/background-service/stall.ts +57 -0
  160. package/src/runtime/domain/background-service/supervisor/README.md +111 -0
  161. package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +90 -0
  162. package/src/runtime/domain/background-service/supervisor/generated/conditions.mjs +96 -0
  163. package/src/runtime/domain/background-service/supervisor/generated/identity.mjs +95 -0
  164. package/src/runtime/domain/background-service/supervisor/generated/process-identity.mjs +131 -0
  165. package/src/runtime/domain/background-service/supervisor/generated/process.mjs +514 -0
  166. package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +872 -0
  167. package/src/runtime/domain/background-service/supervisor/generated/store.mjs +609 -0
  168. package/src/runtime/domain/background-service/supervisor/generated/types.mjs +50 -0
  169. package/src/runtime/domain/background-service/supervisor/identity.domain.mjs +93 -0
  170. package/src/runtime/domain/background-service/supervisor/identity.ts +99 -0
  171. package/src/runtime/domain/background-service/supervisor/index.domain.mjs +22 -0
  172. package/src/runtime/domain/background-service/supervisor/index.ts +37 -0
  173. package/src/runtime/domain/background-service/supervisor/invocation.domain.mjs +30 -0
  174. package/src/runtime/domain/background-service/supervisor/invocation.ts +44 -0
  175. package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +870 -0
  176. package/src/runtime/domain/background-service/supervisor/runner.ts +982 -0
  177. package/src/runtime/domain/background-service/supervisor/store.domain.mjs +605 -0
  178. package/src/runtime/domain/background-service/supervisor/store.ts +651 -0
  179. package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +721 -0
  180. package/src/runtime/domain/background-service/supervisor/supervisor.ts +804 -0
  181. package/src/runtime/domain/background-service/supervisor/types.domain.mjs +48 -0
  182. package/src/runtime/domain/background-service/supervisor/types.ts +394 -0
  183. package/src/runtime/domain/background-service/task-diagnostics.domain.mjs +60 -0
  184. package/src/runtime/domain/background-service/task-diagnostics.ts +71 -0
  185. package/src/runtime/domain/background-service/tools.domain.mjs +1050 -0
  186. package/src/runtime/domain/background-service/tools.ts +1142 -0
  187. package/src/runtime/domain/background-service/types.domain.mjs +5 -0
  188. package/src/runtime/domain/background-service/types.ts +236 -0
  189. package/src/runtime/domain/background-service/work-observation.domain.mjs +176 -0
  190. package/src/runtime/domain/background-service/work-observation.ts +144 -0
  191. package/src/runtime/domain/catalog/catalog-store.d.mts +9 -1
  192. package/src/runtime/domain/catalog/catalog-store.mjs +20 -22
  193. package/src/runtime/domain/coordinator/src/assignment-changes.mjs +75 -0
  194. package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +2 -0
  195. package/src/runtime/domain/coordinator/src/background-parent-callbacks.mjs +65 -0
  196. package/src/runtime/domain/coordinator/src/background-requests.mjs +86 -0
  197. package/src/runtime/domain/coordinator/src/discovery.mjs +4 -2
  198. package/src/runtime/domain/coordinator/src/operations.mjs +44 -4
  199. package/src/runtime/domain/coordinator/src/result-supervision.mjs +12 -0
  200. package/src/runtime/domain/coordinator/src/rows.mjs +2 -0
  201. package/src/runtime/domain/coordinator/src/schema.mjs +73 -21
  202. package/src/runtime/domain/coordinator/src/store.mjs +32 -3
  203. package/src/runtime/domain/coordinator/src/subagent-launch.mjs +119 -0
  204. package/src/runtime/domain/coordinator/src/types.mjs +1 -1
  205. package/src/runtime/domain/coordinator/src/upgrade.mjs +22 -0
  206. package/src/runtime/domain/health-observation.d.mts +3 -1
  207. package/src/runtime/domain/health-observation.mjs +189 -190
  208. package/src/runtime/domain/log-cursor.d.mts +2 -0
  209. package/src/runtime/domain/log-cursor.mjs +85 -16
  210. package/src/runtime/domain/parse.d.mts +4 -1
  211. package/src/runtime/domain/parse.mjs +50 -5
  212. package/src/runtime/domain/sandbox-policy/README.md +633 -0
  213. package/src/runtime/domain/sandbox-policy/background-admission.domain.mjs +83 -0
  214. package/src/runtime/domain/sandbox-policy/background-admission.ts +75 -0
  215. package/src/runtime/domain/sandbox-policy/commands.domain.mjs +245 -0
  216. package/src/runtime/domain/sandbox-policy/commands.ts +336 -0
  217. package/src/runtime/domain/sandbox-policy/deny-rules.domain.mjs +440 -0
  218. package/src/runtime/domain/sandbox-policy/deny-rules.ts +620 -0
  219. package/src/runtime/domain/sandbox-policy/diagnostics-command.domain.mjs +30 -0
  220. package/src/runtime/domain/sandbox-policy/diagnostics-command.ts +27 -0
  221. package/src/runtime/domain/sandbox-policy/events.domain.mjs +49 -0
  222. package/src/runtime/domain/sandbox-policy/events.ts +85 -0
  223. package/src/runtime/domain/sandbox-policy/files.domain.mjs +153 -0
  224. package/src/runtime/domain/sandbox-policy/files.ts +224 -0
  225. package/src/runtime/domain/sandbox-policy/index.domain.mjs +289 -0
  226. package/src/runtime/domain/sandbox-policy/index.ts +386 -0
  227. package/src/runtime/domain/sandbox-policy/package.json +66 -0
  228. package/src/runtime/domain/sandbox-policy/permission-settings.domain.mjs +36 -0
  229. package/src/runtime/domain/sandbox-policy/permission-settings.ts +46 -0
  230. package/src/runtime/domain/sandbox-policy/permissions-page.domain.mjs +309 -0
  231. package/src/runtime/domain/sandbox-policy/permissions-page.ts +295 -0
  232. package/src/runtime/domain/sandbox-policy/permissions.domain.mjs +98 -0
  233. package/src/runtime/domain/sandbox-policy/permissions.ts +125 -0
  234. package/src/runtime/domain/sandbox-policy/policy.domain.mjs +80 -0
  235. package/src/runtime/domain/sandbox-policy/policy.ts +102 -0
  236. package/src/runtime/domain/sandbox-policy/preferences.domain.mjs +55 -0
  237. package/src/runtime/domain/sandbox-policy/preferences.ts +82 -0
  238. package/src/runtime/domain/sandbox-policy/rules-page.domain.mjs +138 -0
  239. package/src/runtime/domain/sandbox-policy/rules-page.ts +176 -0
  240. package/src/runtime/domain/sandbox-policy/session-permissions.domain.mjs +22 -0
  241. package/src/runtime/domain/sandbox-policy/session-permissions.ts +24 -0
  242. package/src/runtime/domain/sandbox-policy/shared-harness-settings.domain.mjs +126 -0
  243. package/src/runtime/domain/sandbox-policy/shared-harness-settings.ts +116 -0
  244. package/src/runtime/domain/sandbox-policy/shared-permission-blocker.domain.mjs +40 -0
  245. package/src/runtime/domain/sandbox-policy/shared-permission-blocker.ts +48 -0
  246. package/src/runtime/domain/sandbox-policy/shared-sandbox-core.domain.mjs +1531 -0
  247. package/src/runtime/domain/sandbox-policy/shared-sandbox-core.ts +1757 -0
  248. package/src/runtime/domain/sandbox-policy/shared-sandbox-diagnostics.domain.mjs +591 -0
  249. package/src/runtime/domain/sandbox-policy/shared-sandbox-diagnostics.ts +491 -0
  250. package/src/runtime/domain/sandbox-policy/shared-task-application.domain.mjs +185 -0
  251. package/src/runtime/domain/sandbox-policy/shared-task-application.ts +185 -0
  252. package/src/runtime/domain/sandbox-policy/shared-task-apply-patch.domain.mjs +416 -0
  253. package/src/runtime/domain/sandbox-policy/shared-task-apply-patch.ts +409 -0
  254. package/src/runtime/domain/sandbox-policy/shared-task-exec.domain.mjs +325 -0
  255. package/src/runtime/domain/sandbox-policy/shared-task-exec.ts +335 -0
  256. package/src/runtime/domain/sandbox-policy/shared-task-files.domain.mjs +346 -0
  257. package/src/runtime/domain/sandbox-policy/shared-task-files.ts +342 -0
  258. package/src/runtime/domain/sandbox-policy/shared-task-process-identity.domain.mjs +140 -0
  259. package/src/runtime/domain/sandbox-policy/shared-task-process-identity.ts +126 -0
  260. package/src/runtime/domain/sandbox-policy/shared-task-process-list.domain.mjs +220 -0
  261. package/src/runtime/domain/sandbox-policy/shared-task-process-list.ts +209 -0
  262. package/src/runtime/domain/sandbox-policy/shared-task-sandbox.domain.mjs +227 -0
  263. package/src/runtime/domain/sandbox-policy/shared-task-sandbox.ts +224 -0
  264. package/src/runtime/domain/sandbox-policy/shared-task-tools.domain.mjs +92 -0
  265. package/src/runtime/domain/sandbox-policy/shared-task-tools.ts +123 -0
  266. package/src/runtime/domain/sandbox-policy/shell.domain.mjs +93 -0
  267. package/src/runtime/domain/sandbox-policy/shell.ts +129 -0
  268. package/src/runtime/domain/sandbox-policy/state.domain.mjs +307 -0
  269. package/src/runtime/domain/sandbox-policy/state.ts +408 -0
  270. package/src/runtime/domain/sandbox-policy/status.domain.mjs +64 -0
  271. package/src/runtime/domain/sandbox-policy/status.ts +76 -0
  272. package/src/runtime/domain/sandbox-policy/subagent-admission.domain.mjs +69 -0
  273. package/src/runtime/domain/sandbox-policy/subagent-admission.ts +60 -0
  274. package/src/runtime/domain/subagents/CONTEXT.md +202 -0
  275. package/src/runtime/domain/subagents/PRODUCT.md +49 -0
  276. package/src/runtime/domain/subagents/README.md +201 -0
  277. package/src/runtime/domain/subagents/agent-catalog.mjs +64 -0
  278. package/src/runtime/domain/subagents/agent-commands.domain.mjs +822 -0
  279. package/src/runtime/domain/subagents/agent-commands.ts +905 -0
  280. package/src/runtime/domain/subagents/agent-inspection.domain.mjs +398 -0
  281. package/src/runtime/domain/subagents/agent-inspection.ts +574 -0
  282. package/src/runtime/domain/subagents/agent-operations.domain.mjs +40 -0
  283. package/src/runtime/domain/subagents/agent-operations.ts +61 -0
  284. package/src/runtime/domain/subagents/agent-session-settings.domain.mjs +112 -0
  285. package/src/runtime/domain/subagents/agent-session-settings.ts +118 -0
  286. package/src/runtime/domain/subagents/agents-catalog-tool.domain.mjs +84 -0
  287. package/src/runtime/domain/subagents/agents-catalog-tool.ts +118 -0
  288. package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +276 -0
  289. package/src/runtime/domain/subagents/assignment-outcomes.ts +212 -0
  290. package/src/runtime/domain/subagents/assignment-projection.mjs +261 -0
  291. package/src/runtime/domain/subagents/assignment-report.domain.mjs +174 -0
  292. package/src/runtime/domain/subagents/assignment-report.ts +156 -0
  293. package/src/runtime/domain/subagents/batch.mjs +275 -0
  294. package/src/runtime/domain/subagents/callback-fields.domain.mjs +72 -0
  295. package/src/runtime/domain/subagents/callback-fields.ts +95 -0
  296. package/src/runtime/domain/subagents/capacity.mjs +108 -0
  297. package/src/runtime/domain/subagents/catalog-editor.domain.mjs +98 -0
  298. package/src/runtime/domain/subagents/catalog-editor.ts +125 -0
  299. package/src/runtime/domain/subagents/catalog-host-admission.domain.mjs +104 -0
  300. package/src/runtime/domain/subagents/catalog-host-admission.ts +85 -0
  301. package/src/runtime/domain/subagents/catalog-identity.domain.mjs +222 -0
  302. package/src/runtime/domain/subagents/catalog-identity.ts +258 -0
  303. package/src/runtime/domain/subagents/catalog-overlay.domain.mjs +9 -0
  304. package/src/runtime/domain/subagents/catalog-overlay.ts +10 -0
  305. package/src/runtime/domain/subagents/catalog-preferences.domain.mjs +164 -0
  306. package/src/runtime/domain/subagents/catalog-preferences.ts +139 -0
  307. package/src/runtime/domain/subagents/catalog-resolver.domain.mjs +366 -0
  308. package/src/runtime/domain/subagents/catalog-resolver.ts +540 -0
  309. package/src/runtime/domain/subagents/catalog-runtime.domain.mjs +570 -0
  310. package/src/runtime/domain/subagents/catalog-runtime.ts +680 -0
  311. package/src/runtime/domain/subagents/catalog-schema.domain.mjs +1331 -0
  312. package/src/runtime/domain/subagents/catalog-schema.ts +1563 -0
  313. package/src/runtime/domain/subagents/catalog-skill-edits.domain.mjs +95 -0
  314. package/src/runtime/domain/subagents/catalog-skill-edits.ts +116 -0
  315. package/src/runtime/domain/subagents/catalog-store.domain.mjs +808 -0
  316. package/src/runtime/domain/subagents/catalog-store.ts +1006 -0
  317. package/src/runtime/domain/subagents/catalog-ui.domain.mjs +651 -0
  318. package/src/runtime/domain/subagents/catalog-ui.ts +611 -0
  319. package/src/runtime/domain/subagents/child-apply-patch.domain.mjs +13 -0
  320. package/src/runtime/domain/subagents/child-apply-patch.ts +13 -0
  321. package/src/runtime/domain/subagents/child-codemode.domain.mjs +16 -0
  322. package/src/runtime/domain/subagents/child-codemode.ts +17 -0
  323. package/src/runtime/domain/subagents/child-dependencies.mjs +193 -0
  324. package/src/runtime/domain/subagents/child-incidents.domain.mjs +170 -0
  325. package/src/runtime/domain/subagents/child-incidents.ts +169 -0
  326. package/src/runtime/domain/subagents/child-operations.domain.mjs +986 -0
  327. package/src/runtime/domain/subagents/child-operations.ts +1191 -0
  328. package/src/runtime/domain/subagents/child-ownership.domain.mjs +205 -0
  329. package/src/runtime/domain/subagents/child-ownership.ts +160 -0
  330. package/src/runtime/domain/subagents/child-preflight.mjs +38 -0
  331. package/src/runtime/domain/subagents/child-process-list.domain.mjs +7 -0
  332. package/src/runtime/domain/subagents/child-process-list.ts +8 -0
  333. package/src/runtime/domain/subagents/child-runtime.mjs +67 -0
  334. package/src/runtime/domain/subagents/child-steer.domain.mjs +109 -0
  335. package/src/runtime/domain/subagents/child-steer.ts +102 -0
  336. package/src/runtime/domain/subagents/cleanup.domain.mjs +818 -0
  337. package/src/runtime/domain/subagents/cleanup.ts +1017 -0
  338. package/src/runtime/domain/subagents/codex-import.domain.mjs +575 -0
  339. package/src/runtime/domain/subagents/codex-import.ts +717 -0
  340. package/src/runtime/domain/subagents/completion.domain.mjs +6 -0
  341. package/src/runtime/domain/subagents/completion.mjs +152 -0
  342. package/src/runtime/domain/subagents/completion.ts +11 -0
  343. package/src/runtime/domain/subagents/config.domain.mjs +248 -0
  344. package/src/runtime/domain/subagents/config.json +15 -0
  345. package/src/runtime/domain/subagents/config.ts +328 -0
  346. package/src/runtime/domain/subagents/continuation-authority.domain.mjs +38 -0
  347. package/src/runtime/domain/subagents/continuation-authority.ts +31 -0
  348. package/src/runtime/domain/subagents/continuation-runtime.domain.mjs +89 -0
  349. package/src/runtime/domain/subagents/continuation-runtime.ts +88 -0
  350. package/src/runtime/domain/subagents/continuation.domain.mjs +942 -0
  351. package/src/runtime/domain/subagents/continuation.ts +1051 -0
  352. package/src/runtime/domain/subagents/delegation.domain.mjs +19 -0
  353. package/src/runtime/domain/subagents/delegation.ts +24 -0
  354. package/src/runtime/domain/subagents/effective-settings.domain.mjs +130 -0
  355. package/src/runtime/domain/subagents/effective-settings.ts +184 -0
  356. package/src/runtime/domain/subagents/extensions.domain.mjs +6 -0
  357. package/src/runtime/domain/subagents/extensions.mjs +164 -0
  358. package/src/runtime/domain/subagents/extensions.ts +19 -0
  359. package/src/runtime/domain/subagents/failures.domain.mjs +362 -0
  360. package/src/runtime/domain/subagents/failures.ts +319 -0
  361. package/src/runtime/domain/subagents/finalization.domain.mjs +168 -0
  362. package/src/runtime/domain/subagents/finalization.ts +218 -0
  363. package/src/runtime/domain/subagents/git-remotes.domain.mjs +351 -0
  364. package/src/runtime/domain/subagents/git-remotes.ts +413 -0
  365. package/src/runtime/domain/subagents/git-workspace.domain.mjs +337 -0
  366. package/src/runtime/domain/subagents/git-workspace.ts +430 -0
  367. package/src/runtime/domain/subagents/goal-provider.domain.mjs +125 -0
  368. package/src/runtime/domain/subagents/goal-provider.ts +132 -0
  369. package/src/runtime/domain/subagents/health-observation.domain.mjs +617 -0
  370. package/src/runtime/domain/subagents/health-observation.ts +818 -0
  371. package/src/runtime/domain/subagents/health-surface.mjs +284 -0
  372. package/src/runtime/domain/subagents/health.domain.mjs +261 -0
  373. package/src/runtime/domain/subagents/health.ts +343 -0
  374. package/src/runtime/domain/subagents/historical-attention.domain.mjs +37 -0
  375. package/src/runtime/domain/subagents/historical-attention.ts +35 -0
  376. package/src/runtime/domain/subagents/incident-model.domain.mjs +322 -0
  377. package/src/runtime/domain/subagents/incident-model.ts +358 -0
  378. package/src/runtime/domain/subagents/index.domain.mjs +4731 -0
  379. package/src/runtime/domain/subagents/index.ts +4781 -0
  380. package/src/runtime/domain/subagents/launch-abort.domain.mjs +13 -0
  381. package/src/runtime/domain/subagents/launch-abort.ts +21 -0
  382. package/src/runtime/domain/subagents/launch-context.domain.mjs +24 -0
  383. package/src/runtime/domain/subagents/launch-context.ts +23 -0
  384. package/src/runtime/domain/subagents/launch-digest.mjs +6 -0
  385. package/src/runtime/domain/subagents/lifecycle.domain.mjs +265 -0
  386. package/src/runtime/domain/subagents/lifecycle.ts +360 -0
  387. package/src/runtime/domain/subagents/list.domain.mjs +2 -0
  388. package/src/runtime/domain/subagents/list.mjs +152 -0
  389. package/src/runtime/domain/subagents/list.ts +19 -0
  390. package/src/runtime/domain/subagents/log-cursor.domain.mjs +217 -0
  391. package/src/runtime/domain/subagents/log-cursor.ts +268 -0
  392. package/src/runtime/domain/subagents/managed-background-capability.domain.mjs +10 -0
  393. package/src/runtime/domain/subagents/managed-background-capability.ts +9 -0
  394. package/src/runtime/domain/subagents/managed-failure-worker.mjs +36 -0
  395. package/src/runtime/domain/subagents/managed-launch-bootstrap.mjs +48 -0
  396. package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +75 -0
  397. package/src/runtime/domain/subagents/managed-launch-client.ts +59 -0
  398. package/src/runtime/domain/subagents/managed-launch-host.domain.mjs +627 -0
  399. package/src/runtime/domain/subagents/managed-launch-host.ts +504 -0
  400. package/src/runtime/domain/subagents/managed-launch-journal.mjs +17 -0
  401. package/src/runtime/domain/subagents/managed-launch-ownership.domain.mjs +29 -0
  402. package/src/runtime/domain/subagents/managed-launch-ownership.ts +22 -0
  403. package/src/runtime/domain/subagents/managed-launch-port.domain.mjs +2 -0
  404. package/src/runtime/domain/subagents/managed-launch-port.ts +25 -0
  405. package/src/runtime/domain/subagents/managed-launch-recovery.domain.mjs +29 -0
  406. package/src/runtime/domain/subagents/managed-launch-recovery.ts +45 -0
  407. package/src/runtime/domain/subagents/managed-worker-bridge.domain.mjs +63 -0
  408. package/src/runtime/domain/subagents/managed-worker-bridge.ts +48 -0
  409. package/src/runtime/domain/subagents/managed-worker.mjs +13 -0
  410. package/src/runtime/domain/subagents/model-resolution-core.domain.mjs +822 -0
  411. package/src/runtime/domain/subagents/model-resolution-core.ts +1074 -0
  412. package/src/runtime/domain/subagents/model-resolution.domain.mjs +22 -0
  413. package/src/runtime/domain/subagents/model-resolution.ts +32 -0
  414. package/src/runtime/domain/subagents/navigator.domain.mjs +6 -0
  415. package/src/runtime/domain/subagents/navigator.mjs +1233 -0
  416. package/src/runtime/domain/subagents/navigator.ts +39 -0
  417. package/src/runtime/domain/subagents/operation-bridge-types.domain.mjs +1012 -0
  418. package/src/runtime/domain/subagents/operation-bridge-types.ts +1156 -0
  419. package/src/runtime/domain/subagents/outage-observations.domain.mjs +84 -0
  420. package/src/runtime/domain/subagents/outage-observations.ts +73 -0
  421. package/src/runtime/domain/subagents/output-payload.domain.mjs +767 -0
  422. package/src/runtime/domain/subagents/output-payload.ts +987 -0
  423. package/src/runtime/domain/subagents/owned-exit.domain.mjs +12 -0
  424. package/src/runtime/domain/subagents/owned-exit.ts +12 -0
  425. package/src/runtime/domain/subagents/package.json +86 -0
  426. package/src/runtime/domain/subagents/park-checkpoint.domain.mjs +55 -0
  427. package/src/runtime/domain/subagents/park-checkpoint.ts +61 -0
  428. package/src/runtime/domain/subagents/parse.domain.mjs +1218 -0
  429. package/src/runtime/domain/subagents/parse.ts +1451 -0
  430. package/src/runtime/domain/subagents/permission-policy.domain.mjs +232 -0
  431. package/src/runtime/domain/subagents/permission-policy.ts +291 -0
  432. package/src/runtime/domain/subagents/process-identity.mjs +33 -0
  433. package/src/runtime/domain/subagents/registry.domain.mjs +1584 -0
  434. package/src/runtime/domain/subagents/registry.ts +1904 -0
  435. package/src/runtime/domain/subagents/role-assignment.domain.mjs +104 -0
  436. package/src/runtime/domain/subagents/role-assignment.ts +141 -0
  437. package/src/runtime/domain/subagents/roles/role.architect.md +13 -0
  438. package/src/runtime/domain/subagents/roles/role.developer.md +16 -0
  439. package/src/runtime/domain/subagents/roles/role.explorer.md +13 -0
  440. package/src/runtime/domain/subagents/roles/role.product-manager.md +13 -0
  441. package/src/runtime/domain/subagents/roles/role.researcher.md +13 -0
  442. package/src/runtime/domain/subagents/roles/role.reviewer.md +13 -0
  443. package/src/runtime/domain/subagents/roles/role.writer.md +12 -0
  444. package/src/runtime/domain/subagents/sandbox.domain.mjs +64 -0
  445. package/src/runtime/domain/subagents/sandbox.ts +92 -0
  446. package/src/runtime/domain/subagents/session-selection.domain.mjs +32 -0
  447. package/src/runtime/domain/subagents/session-selection.ts +35 -0
  448. package/src/runtime/domain/subagents/session-store.domain.mjs +489 -0
  449. package/src/runtime/domain/subagents/session-store.ts +468 -0
  450. package/src/runtime/domain/subagents/settings-page.domain.mjs +313 -0
  451. package/src/runtime/domain/subagents/settings-page.ts +363 -0
  452. package/src/runtime/domain/subagents/shared-callback-batcher.domain.mjs +777 -0
  453. package/src/runtime/domain/subagents/shared-callback-batcher.ts +956 -0
  454. package/src/runtime/domain/subagents/shared-catalog.domain.mjs +70 -0
  455. package/src/runtime/domain/subagents/shared-catalog.ts +61 -0
  456. package/src/runtime/domain/subagents/shared-execution-policy.domain.mjs +50 -0
  457. package/src/runtime/domain/subagents/shared-execution-policy.ts +61 -0
  458. package/src/runtime/domain/subagents/shared-failure-observations.domain.mjs +1078 -0
  459. package/src/runtime/domain/subagents/shared-failure-observations.ts +1166 -0
  460. package/src/runtime/domain/subagents/shared-harness-settings.domain.mjs +126 -0
  461. package/src/runtime/domain/subagents/shared-harness-settings.ts +116 -0
  462. package/src/runtime/domain/subagents/shared-log-utils.domain.mjs +1223 -0
  463. package/src/runtime/domain/subagents/shared-log-utils.ts +1492 -0
  464. package/src/runtime/domain/subagents/shared-navigator-panels.domain.mjs +289 -0
  465. package/src/runtime/domain/subagents/shared-navigator-panels.ts +272 -0
  466. package/src/runtime/domain/subagents/shared-navigator.domain.mjs +1930 -0
  467. package/src/runtime/domain/subagents/shared-navigator.ts +1962 -0
  468. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-inbox.mjs +144 -0
  469. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-observation.mjs +189 -0
  470. package/src/runtime/domain/subagents/shared-operation-coordinator/index.domain.mjs +51 -0
  471. package/src/runtime/domain/subagents/shared-operation-coordinator/index.ts +122 -0
  472. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
  473. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  474. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +163 -0
  475. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.ts +174 -0
  476. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-parent-callbacks.domain.mjs +66 -0
  477. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-parent-callbacks.ts +68 -0
  478. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.domain.mjs +87 -0
  479. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.ts +90 -0
  480. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.domain.mjs +97 -0
  481. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.ts +139 -0
  482. package/src/runtime/domain/subagents/shared-operation-coordinator/src/errors.domain.mjs +12 -0
  483. package/src/runtime/domain/subagents/shared-operation-coordinator/src/errors.ts +79 -0
  484. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.domain.mjs +342 -0
  485. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.ts +513 -0
  486. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.domain.mjs +283 -0
  487. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.ts +458 -0
  488. package/src/runtime/domain/subagents/shared-operation-coordinator/src/recovery.domain.mjs +52 -0
  489. package/src/runtime/domain/subagents/shared-operation-coordinator/src/recovery.ts +55 -0
  490. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.domain.mjs +114 -0
  491. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.ts +140 -0
  492. package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.domain.mjs +280 -0
  493. package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.ts +442 -0
  494. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +420 -0
  495. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +441 -0
  496. package/src/runtime/domain/subagents/shared-operation-coordinator/src/sqlite.domain.mjs +194 -0
  497. package/src/runtime/domain/subagents/shared-operation-coordinator/src/sqlite.ts +239 -0
  498. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +275 -0
  499. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +585 -0
  500. package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.domain.mjs +120 -0
  501. package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.ts +142 -0
  502. package/src/runtime/domain/subagents/shared-operation-coordinator/src/task-cancellation.domain.mjs +188 -0
  503. package/src/runtime/domain/subagents/shared-operation-coordinator/src/task-cancellation.ts +224 -0
  504. package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.domain.mjs +25 -0
  505. package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.ts +707 -0
  506. package/src/runtime/domain/subagents/shared-operation-coordinator/src/upgrade.domain.mjs +22 -0
  507. package/src/runtime/domain/subagents/shared-operation-coordinator/src/upgrade.ts +22 -0
  508. package/src/runtime/domain/subagents/shared-operation-coordinator/src/validate.domain.mjs +234 -0
  509. package/src/runtime/domain/subagents/shared-operation-coordinator/src/validate.ts +241 -0
  510. package/src/runtime/domain/subagents/shared-operation-coordinator/src/waits.domain.mjs +851 -0
  511. package/src/runtime/domain/subagents/shared-operation-coordinator/src/waits.ts +1424 -0
  512. package/src/runtime/domain/subagents/shared-permission-blocker.domain.mjs +40 -0
  513. package/src/runtime/domain/subagents/shared-permission-blocker.ts +48 -0
  514. package/src/runtime/domain/subagents/shared-render-scheduler.domain.mjs +41 -0
  515. package/src/runtime/domain/subagents/shared-render-scheduler.ts +47 -0
  516. package/src/runtime/domain/subagents/shared-sandbox-core.domain.mjs +1531 -0
  517. package/src/runtime/domain/subagents/shared-sandbox-core.ts +1757 -0
  518. package/src/runtime/domain/subagents/shared-sandbox-diagnostics.domain.mjs +591 -0
  519. package/src/runtime/domain/subagents/shared-sandbox-diagnostics.ts +491 -0
  520. package/src/runtime/domain/subagents/shared-stall-detector.domain.mjs +37 -0
  521. package/src/runtime/domain/subagents/shared-stall-detector.ts +69 -0
  522. package/src/runtime/domain/subagents/shared-task-application.domain.mjs +185 -0
  523. package/src/runtime/domain/subagents/shared-task-application.ts +185 -0
  524. package/src/runtime/domain/subagents/shared-task-apply-patch.domain.mjs +416 -0
  525. package/src/runtime/domain/subagents/shared-task-apply-patch.ts +409 -0
  526. package/src/runtime/domain/subagents/shared-task-exec.domain.mjs +325 -0
  527. package/src/runtime/domain/subagents/shared-task-exec.ts +335 -0
  528. package/src/runtime/domain/subagents/shared-task-files.domain.mjs +346 -0
  529. package/src/runtime/domain/subagents/shared-task-files.ts +342 -0
  530. package/src/runtime/domain/subagents/shared-task-process-identity.domain.mjs +140 -0
  531. package/src/runtime/domain/subagents/shared-task-process-identity.ts +126 -0
  532. package/src/runtime/domain/subagents/shared-task-process-list.domain.mjs +220 -0
  533. package/src/runtime/domain/subagents/shared-task-process-list.ts +209 -0
  534. package/src/runtime/domain/subagents/shared-task-sandbox.domain.mjs +227 -0
  535. package/src/runtime/domain/subagents/shared-task-sandbox.ts +224 -0
  536. package/src/runtime/domain/subagents/shared-task-tools.domain.mjs +92 -0
  537. package/src/runtime/domain/subagents/shared-task-tools.ts +123 -0
  538. package/src/runtime/domain/subagents/shared-work-client.mjs +303 -0
  539. package/src/runtime/domain/subagents/shared-worktree-context.domain.mjs +142 -0
  540. package/src/runtime/domain/subagents/shared-worktree-context.ts +158 -0
  541. package/src/runtime/domain/subagents/skill-picker.domain.mjs +316 -0
  542. package/src/runtime/domain/subagents/skill-picker.ts +353 -0
  543. package/src/runtime/domain/subagents/skills.domain.mjs +138 -0
  544. package/src/runtime/domain/subagents/skills.ts +183 -0
  545. package/src/runtime/domain/subagents/spawn.domain.mjs +72 -0
  546. package/src/runtime/domain/subagents/spawn.ts +80 -0
  547. package/src/runtime/domain/subagents/stop.domain.mjs +184 -0
  548. package/src/runtime/domain/subagents/stop.ts +217 -0
  549. package/src/runtime/domain/subagents/subagent-tools.domain.mjs +101 -0
  550. package/src/runtime/domain/subagents/subagent-tools.ts +137 -0
  551. package/src/runtime/domain/subagents/task-guard.domain.mjs +163 -0
  552. package/src/runtime/domain/subagents/task-guard.ts +144 -0
  553. package/src/runtime/domain/subagents/task-policy.domain.mjs +201 -0
  554. package/src/runtime/domain/subagents/task-policy.ts +236 -0
  555. package/src/runtime/domain/subagents/task-runtime.mjs +53 -0
  556. package/src/runtime/domain/subagents/task-tool-owner.domain.mjs +18 -0
  557. package/src/runtime/domain/subagents/task-tool-owner.ts +21 -0
  558. package/src/runtime/domain/subagents/thinking.domain.mjs +22 -0
  559. package/src/runtime/domain/subagents/thinking.ts +28 -0
  560. package/src/runtime/domain/subagents/tier-policy.domain.mjs +75 -0
  561. package/src/runtime/domain/subagents/tier-policy.ts +126 -0
  562. package/src/runtime/domain/subagents/timing-notifications.domain.mjs +51 -0
  563. package/src/runtime/domain/subagents/timing-notifications.ts +37 -0
  564. package/src/runtime/domain/subagents/timing.domain.mjs +487 -0
  565. package/src/runtime/domain/subagents/timing.ts +634 -0
  566. package/src/runtime/domain/subagents/tools.domain.mjs +558 -0
  567. package/src/runtime/domain/subagents/tools.ts +629 -0
  568. package/src/runtime/domain/subagents/widget.domain.mjs +6 -0
  569. package/src/runtime/domain/subagents/widget.mjs +246 -0
  570. package/src/runtime/domain/subagents/widget.ts +30 -0
  571. package/src/runtime/domain/subagents/work-observation.domain.mjs +316 -0
  572. package/src/runtime/domain/subagents/work-observation.ts +248 -0
  573. package/src/runtime/domain/subagents/worker-catalog.domain.mjs +120 -0
  574. package/src/runtime/domain/subagents/worker-catalog.ts +162 -0
  575. package/src/runtime/domain/subagents/worker-operations-host.domain.mjs +1009 -0
  576. package/src/runtime/domain/subagents/worker-operations-host.ts +1238 -0
  577. package/src/runtime/domain/subagents/worker-waits.domain.mjs +2336 -0
  578. package/src/runtime/domain/subagents/worker-waits.ts +2878 -0
  579. package/src/runtime/domain/subagents/workspace-scope.domain.mjs +52 -0
  580. package/src/runtime/domain/subagents/workspace-scope.ts +50 -0
  581. package/src/runtime/health-config.ts +27 -11
  582. package/src/runtime/log-checkpoints.ts +117 -0
  583. package/src/runtime/mutation-store.ts +5 -4
  584. package/src/runtime/queries.ts +27 -3
  585. package/src/runtime/query-executor.ts +178 -34
  586. package/src/runtime/query-worker.mjs +119 -22
  587. package/src/runtime/read-model.ts +939 -113
  588. package/src/runtime/read-watchdog-probe.ts +4 -0
  589. package/src/runtime/result-supervision.ts +188 -16
  590. package/src/runtime/source-watch.ts +175 -0
  591. package/src/runtime/subagent-launch.ts +73 -0
  592. package/src/runtime/work-budget.ts +130 -0
  593. package/src/runtime/work-client.d.mts +8 -0
  594. package/src/runtime/work-client.mjs +150 -7
  595. package/src/server.ts +185 -22
  596. package/src/session-activity.ts +26 -4
  597. package/src/version.ts +1 -1
@@ -1,29 +1,36 @@
1
+ import { affectedAttempts } from "./attempt-invalidation.ts";
1
2
  import { processMatchesStart } from "../daemon-owner.ts";
2
3
  import { createHash } from "node:crypto";
3
- import { readdir, readFile, stat } from "node:fs/promises";
4
- import { watch, type FSWatcher } from "node:fs";
5
- import { join, resolve, sep } from "node:path";
6
- import { realpathSync, statSync } from "node:fs";
4
+ import { opendir, readFile, stat, writeFile, mkdir, rename } from "node:fs/promises";
5
+ import { watchSource, type SourceWatch, type SourceWatcher as FSWatcher } from "./source-watch.ts";
6
+ import { basename, dirname, relative, join, resolve, sep } from "node:path";
7
+ import { realpathSync, statSync, mkdirSync } from "node:fs";
7
8
  import { tmpdir } from "node:os";
8
9
  import { createRequire } from "node:module";
9
10
  import { setImmediate as yieldTurn } from "node:timers/promises";
11
+ import type { InventoryPhase } from "./read-watchdog-probe.ts";
10
12
  import { performance } from "node:perf_hooks";
11
13
  import { createAssignmentProjector } from "./domain/assignment-projection.mjs";
12
14
  import { createAssignmentReader } from "./domain/assignment-observation.mjs";
13
15
  import { parseArchivedAttempt, parseArchivedSessionState } from "./domain/session-store.mjs";
14
- import { parseRun, readRunTranscript } from "./domain/parse.mjs";
16
+ import { parseRun, parseRunDisplay, readRunTranscript, encodeParseLogState, decodeParseLogState } from "./domain/parse.mjs";
17
+ import { withLogReadBatch, logReadMetrics } from "./domain/log-cursor.mjs";
15
18
  import { fmtSpend } from "./domain/widget.mjs";
16
19
  import { effectiveStatus } from "./domain/process-status.mjs";
17
- import { extractChildEventFactsFromLog, healthThresholdsForConfig } from "./domain/health-observation.mjs";
20
+ import { extractChildEventFactsFromLog, healthThresholdsForConfig, encodeHealthLogState, decodeHealthLogState } from "./domain/health-observation.mjs";
21
+ import { LogCheckpoints, isSqliteLockContention } from "./log-checkpoints.ts";
18
22
  import { BackgroundObservation } from "./background.ts";
23
+ import { workPage, createWorkBudget } from "./work-budget.ts";
24
+ // @ts-expect-error Generated canonical read-only failure projection.
25
+ import { readFailureStateReadOnly, pendingFailureAttention } from "./domain/subagents/shared-failure-observations.domain.mjs";
19
26
  import { readHealthConfig } from "./health-config.ts";
20
27
 
21
- export interface WorkScope { processId?: number; backgroundAll?: boolean; background?: boolean; backgroundHistory?: boolean; cwd?: string; sessionId?: string; id?: string; statuses?: string[]; active?: boolean; endedAfter?: number; detail?: boolean; limit?: number; cursor?: string }
28
+ export interface WorkScope { processId?: number; backgroundAll?: boolean; background?: boolean; backgroundHistory?: boolean; cwd?: string; sessionId?: string; id?: string; statuses?: string[]; active?: boolean; pendingRecipient?: boolean; endedAfter?: number; detail?: boolean; limit?: number; cursor?: string }
22
29
  export interface WorkSnapshot {
23
30
  instanceId: string; runtimeEpoch: string; scopeRevision: string; seq: number;
24
31
  observedRevisionVector: { inventory: number; coordinator: string; healthConfig: string };
25
32
  status: "ready" | "rebuilding" | "degraded"; reason?: string;
26
- rows: Array<{ meta: any; assignment: any; sourceRevision: string }>;
33
+ rows: Array<{ meta: any; assignment: any; sourceRevision: string; recipientPending?: boolean }>;
27
34
  nextCursor?: string; activity: { active: number }; nextDeadline: number | null;
28
35
  totalMatching: number;
29
36
  backgroundIndex?: any;
@@ -32,88 +39,339 @@ export interface WorkSnapshot {
32
39
  const hash = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
33
40
  const safeId = /^[A-Za-z0-9_-]+$/;
34
41
 
42
+ function healthWithThresholds(health: any, config: any, meta: any) {
43
+ if (!health) return undefined;
44
+ const value = { ...health, thresholds: healthThresholdsForConfig(config) };
45
+ return { ...value, nextDeadline: nextHealthDeadline(value, meta) };
46
+ }
47
+
48
+ function nextHealthDeadline(health: any, meta: any, now = Date.now()): number | null {
49
+ if (!health) return null;
50
+ const { thresholds } = health;
51
+ const facts = health.facts;
52
+ const tool = facts.activeTools.at(-1);
53
+ const toolStart = tool?.startedAt ?? facts.lastToolAt ?? facts.lastMeaningfulAt;
54
+ const compactionStart = facts.compactionStartedAt ?? facts.lastMeaningfulAt;
55
+ const anchor = facts.lastMeaningfulAt ?? meta.startedAt;
56
+ const deadlines: number[] = [];
57
+ if (["running", "orphaned"].includes(meta.status)) {
58
+ if (tool && Number.isFinite(toolStart)) deadlines.push(toolStart + thresholds.longToolMs);
59
+ if (facts.compacting && Number.isFinite(compactionStart)) deadlines.push(compactionStart + thresholds.longCompactionMs);
60
+ if (!tool && !facts.compacting && !["retrying", "error"].includes(facts.model.state) && Number.isFinite(anchor)) {
61
+ deadlines.push(anchor + thresholds.quietMs, anchor + thresholds.staleMs);
62
+ }
63
+ }
64
+ const future = deadlines.filter(deadline => deadline > now);
65
+ return future.length ? Math.min(...future) : null;
66
+ }
67
+
68
+ const healthDeadlineExpired = (row: { health?: any }, now: number) => typeof row.health?.nextDeadline === "number" && row.health.nextDeadline <= now;
69
+
35
70
  /** Reconstructable query state. It never authorizes execution or writes source records. */
36
71
  export class WorkReadModel {
72
+ private budget: ReturnType<typeof createWorkBudget>;
73
+ onTerminalLogsChanged?: () => void;
37
74
  private background: BackgroundObservation;
38
75
  private db: any;
39
- private reader: ReturnType<typeof createAssignmentReader>;
76
+ private reader!: ReturnType<typeof createAssignmentReader>;
40
77
  private files = new Map<string, { signature: string; meta: any }>();
41
- private projected = new Map<string, { meta: any; assignment: any; sourceRevision: string; display?: { spend: string; tool: string }; health?: any }>();
78
+ private projected = new Map<string, { meta: any; assignment: any; sourceRevision: string; display?: { spend: string; tool: string; diagnostics?: string[]; coverage?: any }; health?: any; recipientPending?: boolean; failurePending?: boolean }>();
42
79
  private logs = new Map<string, string>();
80
+ private parseStates = new Map();
81
+ private healthStates = new Map();
82
+ private checkpoints: LogCheckpoints;
83
+ private checkpointAttemptAllowed = true;
84
+ private checkpointFailure = false;
85
+ private initialization = { attempts: 0, contentions: 0 };
86
+ private get observationInitialized() { return this.checkpoints.ready && Boolean(this.reader) && this.background.ready; }
87
+ private failureJournals = new Map<string, string>();
43
88
  private processes = new Map<string, string>();
44
89
  private staged?: {
45
90
  files: WorkReadModel["files"]; projected: WorkReadModel["projected"];
46
- logs: Map<string, string>; processes: Map<string, string>; healthRevision: string;
47
- coordinator: string; coordinatorConversations?: Map<string, string>;
91
+ logs: Map<string, string>; failureJournals: Map<string, string>; processes: Map<string, string>; healthRevision: string;
92
+ coordinator: string;
93
+ assignmentChanges?: Map<string, string>; assignmentGeneration: string;
48
94
  };
49
95
  private healthRevision = "";
50
96
  private details = new Map<string, { revision: string; value: any }>();
51
- private watchers: FSWatcher[] = [];
97
+ private watchers = new Map<string, FSWatcher>();
98
+ private rootParents = new Map<string, { path: string; identity: string; watcher: FSWatcher }>();
99
+ private rootWatchIdentities = new Map<string, string>();
52
100
  private listeners = new Set<() => void>();
53
101
  private timer?: ReturnType<typeof setInterval>;
54
102
  private pending?: Promise<void>;
55
103
  private dirty = false;
104
+ private sourceConflicts = 0;
105
+ private conflictRetry?: ReturnType<typeof setTimeout>;
106
+ private conflictDelay = 100;
107
+ private hints = new Map<string, number>();
108
+ private repair?: AsyncGenerator<string[]>;
109
+ private repairOwed = false;
110
+ private imported = false;
111
+ private repairWrite: Promise<void> = Promise.resolve();
112
+ private repairPersistencePending = false;
113
+ private sourceErrors = new Map<string, string>();
114
+ private sourceRace?: { reason: string; paths: Set<string>; rows: any[] };
115
+ private sourceStats = 0;
116
+ private sourceWork = { entity: { batches: 0, paths: 0, stats: 0, metadataReads: 0, logBytes: 0, logReads: 0 }, repair: { batches: 0, paths: 0, stats: 0, metadataReads: 0, logBytes: 0, logReads: 0 } };
117
+ private scheduling = { entityBatches: 0, repairBatches: 0, repairEntries: 0, overflows: 0, maxQueueAgeMs: 0, maxPublicationMs: 0 };
56
118
  private closed = false;
57
119
  private inventory = 0;
58
120
  private coordinator = "unknown";
59
- private coordinatorConversations?: Map<string, string>;
121
+ private assignmentBaseline?: { key: string; seq: string };
122
+ private assignmentFault?: { state: WorkSnapshot["status"]; reason?: string };
123
+ private unsupportedAssignmentRevision?: string;
60
124
  private revision = 0;
125
+ private scopeSequence = 0;
126
+ private scopes = new Map<string, { scope: WorkScope; token: number; revision: number; used: number; status: string }>();
127
+ private changedRows: Array<{ before?: any; after?: any }> = [];
128
+ private foldQueueSequence = 0;
61
129
  private state: WorkSnapshot["status"] = "rebuilding";
62
130
  private reason: string | undefined = "Initial source inventory is rebuilding.";
63
- readonly metrics = { inventories: 0, metadataReads: 0, projections: 0, coordinatorConnections: 1, indexConnections: 1 };
131
+ private counters = { inventories: 0, metadataReads: 0, projections: 0, assignmentProjections: 0, logProjections: 0, healthProjections: 0, failureProjections: 0, healthRecomputations: 0, healthConfigInvalidations: 0 };
132
+ private invalidations = { assignmentInput: 0, process: 0, log: 0, failureAttention: 0, healthConfig: 0, healthDeadline: 0, unverified: 0, initial: 0 };
133
+ private get assignmentMetrics() {
134
+ if (this.observationInitialized) {
135
+ try { return this.reader.changeMetrics; }
136
+ catch (error) { if (!isSqliteLockContention(error)) throw error; }
137
+ }
138
+ return { available: false, received: null, applied: null, pending: null };
139
+ }
140
+ get metrics() {
141
+ return { ...this.counters, assignments: this.assignmentMetrics, initialization: { ...this.initialization }, checkpoints: { ...this.checkpoints.metrics, hotDisplay: this.parseStates.size, hotHealth: this.healthStates.size }, sourceWork: structuredClone(this.sourceWork), scheduling: { ...this.scheduling, queued: this.hints.size }, invalidations: { ...this.invalidations }, logReads: { ...logReadMetrics }, coordinatorConnections: Number(Boolean(this.reader?.connection(false))) + this.background.connectionCount,
142
+ indexConnections: this.closed ? 0 : 1, sourceWatchers: this.watchers.size, sourceParentWatchers: this.rootParents.size, rootParentWatchers: this.rootParents.size };
143
+ }
64
144
  readonly runs: string;
65
145
  readonly archives: string;
66
146
  readonly markers: string;
67
147
  readonly agentDir: string;
68
148
  readonly instanceId: string;
149
+ private readonly inventoryPhase?: (phase: InventoryPhase) => void;
69
150
 
70
- constructor(agentDir: string, instanceId: string, options: { supervisorDirectory?: string; baseDir?: string; durableDir?: string; intervalMs?: number } = {}) {
151
+ private watch: SourceWatch;
152
+ constructor(agentDir: string, instanceId: string, options: { supervisorDirectory?: string; baseDir?: string; durableDir?: string; intervalMs?: number; watch?: SourceWatch; budgetBuffer?: SharedArrayBuffer; inventoryPhase?: (phase: InventoryPhase) => void } = {}) {
153
+ this.budget = createWorkBudget(options.budgetBuffer);
154
+ this.watch = options.watch ?? watchSource;
71
155
  this.agentDir = agentDir; this.instanceId = instanceId;
156
+ this.inventoryPhase = options.inventoryPhase;
72
157
  const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
73
158
  this.db = new DatabaseSync(":memory:");
74
- this.background = new BackgroundObservation(agentDir, options.supervisorDirectory, this.db, () => this.publish());
159
+ this.checkpoints = new LogCheckpoints(join(agentDir, "runtime-log-checkpoints.sqlite"), this.db, { defer: true });
160
+ mkdirSync(join(agentDir, "runtime-read-repair"), { recursive: true });
161
+ this.background = new BackgroundObservation(agentDir, options.supervisorDirectory, this.db, () => this.publish(true), refresh => this.reader?.connection(refresh), { defer: true });
75
162
  this.db.exec(`CREATE TABLE rows (id TEXT PRIMARY KEY, cwd TEXT, origin_cwd TEXT, origin_session TEXT,
76
- started REAL, state TEXT, active INTEGER, ended REAL, payload TEXT);
163
+ started REAL, state TEXT, active INTEGER, ended REAL, recipient_pending INTEGER, payload TEXT);
77
164
  CREATE INDEX work_folder ON rows(cwd, started DESC, id DESC);
78
165
  CREATE INDEX work_origin ON rows(origin_cwd, origin_session, started DESC, id DESC);
79
166
  CREATE INDEX work_active ON rows(active, started DESC, id DESC);
80
167
  CREATE INDEX work_terminal ON rows(active, ended, started DESC, id DESC);
81
- CREATE INDEX work_state ON rows(state, started DESC, id DESC);`);
82
- this.reader = createAssignmentReader(join(agentDir, "operation-coordinator.sqlite"));
168
+ CREATE INDEX work_recipient_pending ON rows(origin_cwd, origin_session, recipient_pending, started DESC, id DESC);
169
+ CREATE INDEX work_state ON rows(state, started DESC, id DESC);
170
+ CREATE TABLE assignment_members (scope TEXT NOT NULL, id TEXT NOT NULL, PRIMARY KEY(scope,id));
171
+ CREATE INDEX assignment_member_id ON assignment_members(id);
172
+ CREATE TABLE terminal_log_folds (id TEXT PRIMARY KEY, revision TEXT NOT NULL, pending INTEGER NOT NULL, queue_position INTEGER NOT NULL);
173
+ CREATE INDEX pending_terminal_log_folds ON terminal_log_folds(pending, queue_position, id);`);
83
174
  this.runs = join(options.baseDir ?? join(realpathSync(tmpdir()), "pi-better-subagents"), "runs");
84
175
  this.archives = join(options.durableDir ?? process.env.PI_SUBAGENT_DURABLE_DIR ?? join(agentDir, "subagents"), "attempts");
85
176
  this.markers = join(this.archives, "../session-state");
86
- // Notifications accelerate discovery; a shared bounded inventory repairs lost hints.
87
- for (const path of [this.runs, this.archives, this.markers]) {
177
+ // Watch directory entries, not file inodes. Node's Linux recursive watcher
178
+ // can retain a replaced file's old inode after atomic rename and miss later
179
+ // commits. Flat archives need one watcher; raw runs use one per directory.
180
+ for (const path of [this.runs, this.archives, this.markers]) { this.watchRootParent(path); this.watchDirectory(path); }
181
+ this.timer = setInterval(() => { this.checkpointAttemptAllowed = true; this.repairOwed = true; if (!this.pending) void this.reconcile(false); }, options.intervalMs ?? 1000);
182
+ this.timer.unref();
183
+ }
184
+
185
+ private unwatchDirectory(path: string) {
186
+ this.watchers.get(path)?.close(); this.watchers.delete(path);
187
+ }
188
+ private watchRootParent(root: string) {
189
+ if (this.closed) return;
190
+ // A watch follows an inode, not the source pathname. Keep an independent
191
+ // parent entry watch so recreation after an observed ENOENT remains visible.
192
+ for (let parent = dirname(root); ; parent = dirname(parent)) {
193
+ const previous = this.rootParents.get(root);
88
194
  try {
89
- const watcher = watch(path, { recursive: true }, () => { void this.reconcile(); });
90
- watcher.on("error", () => this.invalidate("Watcher overflow or failure; reconciling source inventory."));
91
- this.watchers.push(watcher);
92
- } catch { /* Missing roots are discovered by the compatibility inventory. */ }
195
+ const info = statSync(parent, { bigint: true });
196
+ const identity = `${info.dev}:${info.ino}`;
197
+ if (previous?.path === parent && previous.identity === identity) return;
198
+ const entry = relative(parent, root).split(sep)[0];
199
+ const watcher = this.watch(parent, (_event, filename) => {
200
+ if (this.closed || this.rootParents.get(root)?.watcher !== watcher) return;
201
+ if (!filename || String(filename) === entry || String(filename) === relative(dirname(parent), parent)) void this.reconcile();
202
+ });
203
+ watcher.on("error", () => {
204
+ if (this.rootParents.get(root)?.watcher !== watcher) return;
205
+ watcher.close(); this.rootParents.delete(root);
206
+ this.invalidate("Source parent watcher failed; reconciling source inventory.");
207
+ });
208
+ previous?.watcher.close();
209
+ this.rootParents.set(root, { path: parent, identity, watcher });
210
+ return;
211
+ } catch { /* Missing source ancestors are watched from their nearest existing parent. */ }
212
+ if (dirname(parent) === parent) return;
93
213
  }
94
- this.timer = setInterval(() => { if (!this.pending) void this.reconcile(); }, options.intervalMs ?? 1000);
95
- this.timer.unref();
214
+ }
215
+ private watchDirectory(path: string) {
216
+ if (this.closed) return;
217
+ let identity: string | undefined;
218
+ if ([this.runs, this.archives, this.markers].includes(path)) {
219
+ try {
220
+ const info = statSync(path, { bigint: true });
221
+ identity = `${info.dev}:${info.ino}`;
222
+ } catch (error) {
223
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") return;
224
+ }
225
+ if (!identity || this.rootWatchIdentities.get(path) !== identity) {
226
+ this.unwatchDirectory(path); this.rootWatchIdentities.delete(path);
227
+ if (path === this.runs) for (const child of this.watchers.keys()) if (child.startsWith(this.runs + sep)) this.unwatchDirectory(child);
228
+ }
229
+ if (!identity) return;
230
+ }
231
+ if (this.watchers.has(path)) return;
232
+ try {
233
+ const watcher = this.watch(path, (_event, filename) => {
234
+ if (this.closed || this.watchers.get(path) !== watcher) return;
235
+ if (path === this.runs) {
236
+ // A raw directory may itself have been removed/replaced. Reattach
237
+ // from the shared inventory, never retain its preceding inode.
238
+ if (filename && safeId.test(String(filename))) this.unwatchDirectory(join(this.runs, String(filename)));
239
+ else for (const watched of this.watchers.keys()) if (watched.startsWith(this.runs + sep)) this.unwatchDirectory(watched);
240
+ }
241
+ this.fileHint(path, filename ? String(filename) : undefined);
242
+ }, dirname(path) === this.runs);
243
+ watcher.on("error", () => {
244
+ if (this.watchers.get(path) !== watcher) return;
245
+ this.unwatchDirectory(path);
246
+ this.invalidate("Watcher overflow or failure; reconciling source inventory.");
247
+ });
248
+ this.watchers.set(path, watcher);
249
+ if (identity) this.rootWatchIdentities.set(path, identity);
250
+ } catch { /* Missing roots are discovered by the existing compatibility inventory. */ }
251
+ }
252
+
253
+ /** File notifications are hints, never authority. Unknown names owe scoped repair. */
254
+ fileHint(directory: string, name?: string) {
255
+ // Some fs.watch backends report the watched directory's own name for a
256
+ // contained write. It identifies a source to verify, not a child entry.
257
+ if (name === basename(directory)) {
258
+ name = directory.startsWith(this.runs + sep) ? "meta.json" : undefined;
259
+ }
260
+ let path: string | undefined;
261
+ if (directory === this.runs && name && safeId.test(name)) path = join(directory, name, "meta.json");
262
+ else if ([this.archives, this.markers].includes(directory) && name && /^[A-Za-z0-9_-]+\.json$/.test(name)) path = join(directory, name);
263
+ else if (directory.startsWith(this.runs + sep) && name && ["meta.json", "output.log", "failures.jsonl", "failures.jsonl.observed"].includes(name)) path = join(directory, "meta.json");
264
+ else if (name) return; // Locks, temporary files and coordinator controls are not task inputs.
265
+ if (!path) { this.repairOwed = true; void this.reconcile(false); return; }
266
+ if (!this.hints.has(path)) {
267
+ if (this.hints.size >= 256) {
268
+ this.scheduling.overflows++; this.repairOwed = true;
269
+ // Persist the bounded source scope before discarding the individual hint.
270
+ if (!this.repairPersistencePending) {
271
+ this.repairPersistencePending = true;
272
+ this.repairWrite = this.persistRepair().finally(() => { this.repairPersistencePending = false; });
273
+ void this.repairWrite.then(() => this.reconcile(false)).catch(error => this.invalidate(String(error)));
274
+ }
275
+ return;
276
+ }
277
+ this.hints.set(path, Date.now());
278
+ }
279
+ void this.reconcile(false);
280
+ }
281
+
282
+ private async persistRepair() {
283
+ const directory = join(this.agentDir, "runtime-read-repair");
284
+ await mkdir(directory, { recursive: true });
285
+ const path = join(directory, "subagents.json");
286
+ await writeFile(path + ".tmp", JSON.stringify({ version: 1, roots: [this.runs, this.archives, this.markers] }));
287
+ await rename(path + ".tmp", path);
288
+ }
289
+
290
+ private async *repairPaths(): AsyncGenerator<string[]> {
291
+ // Check known paths too: an incomplete walk never deletes unseen records.
292
+ // Discovery and failed-source repair can overlap these paths. Retry each
293
+ // source once per pass, not once per inventory route.
294
+ const seen = new Set<string>();
295
+ let batch: string[] = [];
296
+ for (const path of this.files.keys()) {
297
+ seen.add(path);
298
+ batch.push(path);
299
+ if (batch.length === 128) { yield batch; batch = []; }
300
+ }
301
+ // Failed first reads have no verified file entry, but still owe repair.
302
+ for (const path of this.sourceErrors.keys()) {
303
+ if (seen.has(path)) continue;
304
+ seen.add(path);
305
+ batch.push(path);
306
+ if (batch.length === 128) { yield batch; batch = []; }
307
+ }
308
+ for (const directory of [this.markers, this.archives, this.runs]) {
309
+ this.watchRootParent(directory);
310
+ let handle;
311
+ try {
312
+ const info = await stat(directory, { bigint: true });
313
+ const identity = `${info.dev}:${info.ino}`;
314
+ if (this.rootWatchIdentities.get(directory) !== identity) {
315
+ this.unwatchDirectory(directory);
316
+ if (directory === this.runs) for (const path of this.watchers.keys()) if (path.startsWith(this.runs + sep)) this.unwatchDirectory(path);
317
+ }
318
+ this.watchDirectory(directory);
319
+ handle = await opendir(directory);
320
+ } catch (error) {
321
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
322
+ this.unwatchDirectory(directory);
323
+ this.rootWatchIdentities.delete(directory);
324
+ if (directory === this.runs) for (const path of this.watchers.keys()) if (path.startsWith(this.runs + sep)) this.unwatchDirectory(path);
325
+ continue;
326
+ }
327
+ for await (const entry of handle) {
328
+ if (directory === this.runs ? safeId.test(entry.name) : /^[A-Za-z0-9_-]+\.json$/.test(entry.name)) {
329
+ const path = directory === this.runs ? join(directory, entry.name, "meta.json") : join(directory, entry.name);
330
+ if (seen.has(path)) continue;
331
+ seen.add(path);
332
+ batch.push(path);
333
+ if (batch.length === 128) { yield batch; batch = []; }
334
+ }
335
+ }
336
+ }
337
+ if (batch.length) yield batch;
96
338
  }
97
339
 
98
340
  onChange(listener: () => void, scope?: WorkScope) {
341
+ if (scope) scope = { ...scope, cursor: undefined };
99
342
  const release = scope?.background ? this.background.retain(scope) : undefined;
100
- this.listeners.add(listener);
101
- return () => { this.listeners.delete(listener); release?.(); };
343
+ let revision = scope ? this.contentRevision(scope) : undefined;
344
+ const notify = () => {
345
+ const next = scope ? this.contentRevision(scope) : undefined;
346
+ if (scope && next === revision) return;
347
+ revision = next; listener();
348
+ };
349
+ this.listeners.add(notify);
350
+ return () => { this.listeners.delete(notify); release?.(); };
102
351
  }
103
- get backgroundMetrics() { return { ...this.background.metrics, scopes: this.background.scopeCount, history: this.background.historyMetrics }; }
104
- observation(reasons = this.livenessReasons({ refresh: false })) {
352
+ get backgroundMetrics() { return { ...this.background.metrics, registry: this.background.registryMetrics, changes: this.background.changeMetrics, scopes: this.background.scopeCount, history: this.background.historyMetrics }; }
353
+ observation(reasons = this.observationInitialized ? this.livenessReasons({ refresh: false }) : []) {
105
354
  return { status: this.state, reason: this.reason, observedAt: Date.now(), reasons };
106
355
  }
107
356
  livenessReasons(options: { refresh?: boolean } = {}) {
357
+ if (!this.observationInitialized) throw new Error(`Runtime observation ${this.state}: checkpoint coverage is unverified (including assignment and Background inboxes)`);
108
358
  return [
109
359
  ...[...this.projected.values()].filter(row => row.meta.status === "running"
110
360
  && processMatchesStart(row.meta.pid, row.meta.pidStartTime))
111
361
  .map(row => ({ kind: "worker", id: row.meta.id, owner: row.meta.callbackOrigin,
112
- lastProgressAt: row.meta.startedAt, nextDeadline: null, recovery: "observe-existing-worker" })),
362
+ lastProgressAt: row.meta.startedAt, nextDeadline: nextHealthDeadline(row.health, row.meta), recovery: "observe-existing-worker" })),
113
363
  ...this.background.livenessReasons(options),
114
364
  ];
115
365
  }
366
+ upgradeObligations() {
367
+ if (this.state !== "ready") throw new Error(`Runtime observation ${this.state}: ${this.reason}`);
368
+ return [...this.livenessReasons(), ...this.reader.upgradeObligations(),
369
+ ...[...this.projected.values()].filter(row => ["running", "orphaned"].includes(row.meta.status)
370
+ && !processMatchesStart(row.meta.pid, row.meta.pidStartTime))
371
+ .map(row => ({ kind: "unresolved-writer", id: row.meta.id }))];
372
+ }
116
373
  async ensureId(id: string): Promise<boolean> {
374
+
117
375
  if (!safeId.test(id)) throw new Error("Invalid run ID");
118
376
  if (this.state === "rebuilding") return false;
119
377
  if (this.db.prepare("SELECT id FROM rows WHERE id = ?").get(id)) return true;
@@ -123,7 +381,7 @@ export class WorkReadModel {
123
381
  let timeout: ReturnType<typeof setTimeout> | undefined;
124
382
  try {
125
383
  return await Promise.race([
126
- this.reconcile().then(() => !!this.db.prepare("SELECT id FROM rows WHERE id = ?").get(id)),
384
+ (this.fileHint(this.runs, id), this.pending ?? Promise.resolve()).then(() => !!this.db.prepare("SELECT id FROM rows WHERE id = ?").get(id)),
127
385
  new Promise<false>(resolve => { timeout = setTimeout(() => resolve(false), 100); }),
128
386
  ]);
129
387
  } finally {
@@ -131,50 +389,333 @@ export class WorkReadModel {
131
389
  }
132
390
  }
133
391
  invalidate(reason: string) {
392
+ const changed = this.state !== "degraded" || this.reason !== reason;
134
393
  this.state = "degraded"; this.reason = reason;
135
- this.publish();
394
+ if (changed) this.publish();
136
395
  void this.reconcile();
137
396
  }
138
- private publish() { this.revision++; for (const listener of this.listeners) listener(); }
397
+ private scopeKey(scope: WorkScope) { return hash({ ...scope, cursor: undefined }); }
398
+ private scopeEntry(scope: WorkScope) {
399
+ const key = this.scopeKey(scope), now = Date.now();
400
+ for (const [id, entry] of this.scopes) if (now - entry.used >= 300000) this.scopes.delete(id);
401
+ let entry = this.scopes.get(key);
402
+ if (!entry) {
403
+ if (scope.cursor) throw new Error("resync_required: cursor retention expired");
404
+ if (this.scopes.size >= 128) this.scopes.delete(this.scopes.keys().next().value!);
405
+ entry = { scope: { ...scope, cursor: undefined }, token: ++this.scopeSequence, revision: 0, used: now, status: hash(this.scopeStatus(scope)) };
406
+ this.scopes.set(key, entry);
407
+ }
408
+ entry.used = now;
409
+ return entry;
410
+ }
411
+ contentRevision(scope: WorkScope = {}) {
412
+ if (scope.background) {
413
+ if (scope.backgroundHistory) return String(this.revision);
414
+ this.background.prepareQuery();
415
+ return hash([this.revision, this.background.sourceRevision(scope)]);
416
+ }
417
+ const entry = this.scopeEntry(scope);
418
+ return `${entry.token}:${entry.revision}`;
419
+ }
420
+ private matchesScope(scope: WorkScope, row: any, activity = false) {
421
+ if (!row) return false;
422
+ const m = row.meta;
423
+ if (scope.id && scope.id !== m.id) return false;
424
+ if (scope.sessionId) {
425
+ if (scope.sessionId !== m.callbackOrigin?.sessionId || scope.cwd !== (m.callbackOrigin?.cwd ?? m.cwd)) return false;
426
+ } else if (scope.cwd) {
427
+ const cwd = resolve(scope.cwd), prefix = cwd.endsWith(sep) ? cwd : cwd + sep;
428
+ if (m.cwd !== cwd && !m.cwd.startsWith(prefix)) return false;
429
+ }
430
+ const active = ["running", "waiting"].includes(row.assignment.state);
431
+ if (activity) return active;
432
+ return (scope.active === undefined || scope.active === active)
433
+ && (scope.pendingRecipient === undefined || scope.pendingRecipient === !!row.recipientPending)
434
+ && (scope.endedAfter === undefined || (m.endedAt ?? m.lostAt ?? Infinity) >= scope.endedAfter)
435
+ && (!scope.statuses?.length || scope.statuses.includes(row.assignment.state));
436
+ }
437
+ private publish(backgroundOnly = false) {
438
+ this.revision++;
439
+ for (const entry of this.scopes.values()) {
440
+ if (backgroundOnly) continue;
441
+ const status = hash(this.scopeStatus(entry.scope));
442
+ if (entry.status !== status || this.changedRows.some(({ before, after }) =>
443
+ this.matchesScope(entry.scope, before) || this.matchesScope(entry.scope, after)
444
+ || this.matchesScope(entry.scope, before, true) !== this.matchesScope(entry.scope, after, true))) entry.revision++;
445
+ entry.status = status;
446
+ }
447
+ this.changedRows = [];
448
+ for (const listener of this.listeners) listener();
449
+ }
450
+
451
+ /** Ordinary coordinator commits use the reverse scope index, not the source inventory. */
452
+ private refreshAssignments(baselineOnly = false) {
453
+ if ((!this.imported && !baselineOnly) || this.staged || this.reader.snapshotActive) return;
454
+ let release: (() => void) | undefined;
455
+ let revision: string | undefined;
456
+ try {
457
+ if (this.unsupportedAssignmentRevision && this.unsupportedAssignmentRevision === this.reader.revision()) return;
458
+ this.unsupportedAssignmentRevision = undefined;
459
+ const changes = this.reader.changes();
460
+ const snapshot = this.reader.beginSnapshot(); release = snapshot.release;
461
+ revision = snapshot.revision;
462
+ if (changes.has("*")) {
463
+ const key = `${this.reader.changeMetrics.generation}:${changes.get("*")}`;
464
+ if (baselineOnly) {
465
+ this.assignmentBaseline = { key, seq: changes.get("*")! };
466
+ this.coordinator = snapshot.revision;
467
+ return;
468
+ }
469
+ if (this.assignmentBaseline?.key === key) return;
470
+ this.imported = false; this.repairOwed = true;
471
+ if (!this.sourceErrors.size) { this.state = "rebuilding"; this.reason = "Assignment source baseline is rebuilding."; }
472
+ this.publish(); return;
473
+ }
474
+ const selected = new Map<string, any>();
475
+ const select = this.db.prepare("SELECT r.payload FROM assignment_members m JOIN rows r ON r.id=m.id WHERE m.scope=?");
476
+ for (const scope of changes.keys()) for (const record of select.all(scope)) {
477
+ const row = JSON.parse(record.payload); selected.set(row.meta.id, row);
478
+ }
479
+ const project = createAssignmentProjector({ attempts: [...selected.values()].map(row => row.meta), observe: (owner: any) => this.reader.read(owner) });
480
+ const updated: any[] = [];
481
+ for (const row of selected.values()) {
482
+ const meta = row.meta;
483
+ const assignment = project(meta, this.processes.get(meta.id) ?? meta.status);
484
+ if (!assignment.verified) throw new Error(`Assignment observation is unverified: ${meta.id}`);
485
+ const outcome = meta.assignment ? this.reader.read({ ...meta.assignment.owner, assignmentId: meta.assignment.assignmentId }).outcome : undefined;
486
+ const recipientPending = Boolean(row.failurePending || meta.timing?.pendingWakes?.length
487
+ || (meta.status === "orphaned" && meta.orphanedCallbackSentAt === undefined && meta.orphanedCallbackSuppressedAt === undefined)
488
+ || (meta.status === "lost" && meta.lostCallbackSentAt === undefined && meta.lostCallbackSuppressedAt === undefined)
489
+ || (meta.callback !== false && (meta.assignment ? outcome && !outcome.deliveryReceipt && !outcome.disposition
490
+ : meta.completionCallbackPendingAt !== undefined && meta.completionCallbackSentAt === undefined && meta.completionCallbackSuppressedAt === undefined)));
491
+ updated.push({ ...row, assignment, recipientPending, sourceRevision: hash([meta, assignment.revision, row.display, row.health, recipientPending, row.failurePending, this.failureJournals.get(meta.id)]) });
492
+ }
493
+ let changed = false;
494
+ const changedRows: WorkReadModel["changedRows"] = [];
495
+ this.db.exec("SAVEPOINT assignment_refresh");
496
+ try {
497
+ const update = this.db.prepare("UPDATE rows SET state=?, active=?, recipient_pending=?, payload=? WHERE id=?");
498
+ for (const row of updated) {
499
+ if (row.sourceRevision === this.projected.get(row.meta.id)?.sourceRevision) continue;
500
+ update.run(row.assignment.state, ["running", "waiting"].includes(row.assignment.state) ? 1 : 0, row.recipientPending ? 1 : 0, JSON.stringify(row), row.meta.id);
501
+ changedRows.push({ before: this.projected.get(row.meta.id), after: row });
502
+ changed = true;
503
+ }
504
+ this.db.exec("RELEASE assignment_refresh");
505
+ } catch (error) { this.db.exec("ROLLBACK TO assignment_refresh; RELEASE assignment_refresh"); throw error; }
506
+ // A crash after application but before acknowledgement safely repeats this batch.
507
+ this.reader.acknowledgeChanges(changes, false);
508
+ snapshot.commit();
509
+ for (const row of updated) this.projected.set(row.meta.id, row);
510
+ if (this.reader.changeMetrics.more || this.reader.changeMetrics.pending) this.dirty = true;
511
+ this.coordinator = snapshot.revision;
512
+ this.counters.assignmentProjections += updated.length; this.counters.projections += updated.length;
513
+ this.invalidations.assignmentInput += updated.length;
514
+ this.changedRows = changedRows;
515
+ if (this.assignmentFault) {
516
+ this.state = this.assignmentFault.state; this.reason = this.assignmentFault.reason;
517
+ this.assignmentFault = undefined; this.changedRows = []; changed = true;
518
+ }
519
+ if (changed) this.publish();
520
+ } catch (error) {
521
+ release?.(); release = undefined;
522
+ if (!this.projected.size) return;
523
+ // A coordinator has never been required for plain archived/log-only runs.
524
+ // Losing an already observed database still degrades the existing coverage.
525
+ if ((error as NodeJS.ErrnoException).code === "ENOENT" && this.coordinator === "unknown") return;
526
+ if (error instanceof Error && error.message === "Unsupported assignment source schema") this.unsupportedAssignmentRevision = revision;
527
+ this.assignmentFault ??= { state: this.state, reason: this.reason };
528
+ if (/no such table: (?:coordinator_source\.)?assignment_change_source$/.test(String(error))) {
529
+ // Old sources have no feed. Finish one budgeted compatibility pass;
530
+ // continuous legacy writes do not restart a pass already in progress.
531
+ this.imported = false; this.repairOwed = true; this.state = "rebuilding";
532
+ } else this.state = "degraded";
533
+ this.reason = String(error).slice(0, 512); this.publish();
534
+ } finally { release?.(); }
535
+ }
536
+
537
+ private scopeStatus(scope: WorkScope): { status: WorkSnapshot["status"]; reason?: string } {
538
+ const race = this.sourceRace;
539
+ // Only a validated, entity-attributed retry can leave another scope ready.
540
+ // Root, coordinator, unattributed and initial-import failures stay global.
541
+ if (this.imported && this.state === "degraded" && race && this.reason === race.reason
542
+ && [...this.sourceErrors.keys()].every(path => race.paths.has(path))
543
+ && !race.rows.some(row => this.matchesScope({ id: scope.id, cwd: scope.cwd, sessionId: scope.sessionId }, row))) {
544
+ return { status: "ready" };
545
+ }
546
+ return { status: this.state, reason: this.reason };
547
+ }
139
548
 
140
- reconcile(): Promise<void> {
141
- if (this.closed) return Promise.resolve();
142
- if (this.pending) { this.dirty = true; return this.pending; }
549
+ private rejectUnsupportedAssignmentRevision(): boolean {
550
+ let release: (() => void) | undefined;
551
+ try {
552
+ if (this.unsupportedAssignmentRevision) {
553
+ if (this.unsupportedAssignmentRevision === this.reader.revision()) return true;
554
+ this.unsupportedAssignmentRevision = undefined;
555
+ }
556
+ const connection = this.reader.connection(false);
557
+ const supported = (version: unknown) => version === undefined || (typeof version === "string" && ["1", "2", "3", "4"].includes(version));
558
+ if (!connection || supported(connection.prepare("SELECT value FROM schema_meta WHERE key='schema_version'").get()?.value)) return false;
559
+ const snapshot = this.reader.beginSnapshot(); release = snapshot.release;
560
+ const version = this.reader.connection(false).prepare("SELECT value FROM schema_meta WHERE key='schema_version'").get()?.value;
561
+ if (!supported(version)) {
562
+ this.unsupportedAssignmentRevision = snapshot.revision;
563
+ const reason = "Unsupported assignment source schema";
564
+ const changed = this.state !== "degraded" || this.reason !== reason;
565
+ this.state = "degraded"; this.reason = reason;
566
+ if (changed) this.publish();
567
+ return true;
568
+ }
569
+ } catch {
570
+ // Missing/initializing sources still follow the ordinary verification path.
571
+ this.unsupportedAssignmentRevision = undefined;
572
+ } finally { release?.(); }
573
+ return false;
574
+ }
575
+
576
+ reconcile(drain = true): Promise<void> {
577
+ if (this.closed || this.conflictRetry) return Promise.resolve();
578
+ if (this.pending) {
579
+ return drain && this.observationInitialized ? this.pending.then(() => this.reconcile()) : this.pending;
580
+ }
581
+ const release = this.budget.enter("repair");
582
+ if (!release) return Promise.resolve();
143
583
  this.pending = (async () => {
144
- for (let pass = 0; pass < 2; pass++) {
145
- this.dirty = false;
146
- await this.scan();
147
- if (!this.dirty || this.closed) break;
584
+ await this.watchRegistrations();
585
+ if (this.closed) return;
586
+ if (!this.observationInitialized) {
587
+ if (!this.checkpointAttemptAllowed || this.checkpointFailure) return;
588
+ this.checkpointAttemptAllowed = false;
589
+ this.initialization.attempts++;
590
+ let initialized: boolean;
591
+ try {
592
+ if (this.db.isTransaction) throw new Error("Derived observation initialization requires an unpinned owner");
593
+ initialized = this.checkpoints.initialize();
594
+ if (initialized) this.reader ??= createAssignmentReader(join(this.agentDir, "operation-coordinator.sqlite"),
595
+ join(this.agentDir, "runtime-read-repair", "assignments.sqlite"), this.db, { composed: true });
596
+ if (initialized) this.background.initialize();
597
+ } catch (error) {
598
+ if (isSqliteLockContention(error)) initialized = false;
599
+ else { this.checkpointFailure = true; throw error; }
600
+ }
601
+ if (!initialized) {
602
+ this.initialization.contentions++;
603
+ const reason = "Derived checkpoint, assignment or Background inbox acquisition is contended; source coverage remains unverified.";
604
+ if (this.reason !== reason) { this.state = "rebuilding"; this.reason = reason; this.publish(); }
605
+ return;
606
+ }
148
607
  }
149
- })().finally(() => {
608
+ let resetRepair = drain;
609
+ do {
610
+ this.dirty = false;
611
+ // Background progress is independent of whether Subagent repair finds files.
612
+ this.inventoryPhase?.("background");
613
+ if (this.background.refresh()) this.publish(true);
614
+ if (this.rejectUnsupportedAssignmentRevision()) break;
615
+ this.refreshAssignments();
616
+ // Metadata repair cannot verify an incompatible coordinator. Keep its
617
+ // obligations and last verified rows until a different source revision.
618
+ if (this.unsupportedAssignmentRevision) break;
619
+ if (resetRepair && this.repair) { await this.repair.return(undefined); this.repair = undefined; }
620
+ resetRepair = false;
621
+ if (this.hints.size) {
622
+ const entries = workPage(this.hints);
623
+ for (const [path, queued] of entries) { this.hints.delete(path); this.scheduling.maxQueueAgeMs = Math.max(this.scheduling.maxQueueAgeMs, Date.now() - queued); }
624
+ this.scheduling.entityBatches++;
625
+ const started = performance.now();
626
+ await this.measuredScan("entity", entries.map(([path]) => path));
627
+ this.scheduling.maxPublicationMs = Math.max(this.scheduling.maxPublicationMs, performance.now() - started);
628
+ if (this.sourceConflicts > 1) break;
629
+ }
630
+ if (!this.repair && this.imported && !drain && !this.repairOwed) {
631
+ if (this.hints.size) { await yieldTurn(); continue; }
632
+ break;
633
+ }
634
+ this.repair ??= this.repairPaths();
635
+ const next = await this.repair.next();
636
+ if (next.done) {
637
+ await this.watchRegistrations();
638
+ this.repair = undefined; this.repairOwed = false;
639
+ // An empty metadata inventory still needs a journal baseline before
640
+ // later exact hints can be treated as incremental updates.
641
+ if (!this.imported && !this.assignmentBaseline && !this.files.size && !this.sourceErrors.size) this.refreshAssignments(true);
642
+ if (this.assignmentBaseline && !this.sourceErrors.size && ![...this.projected.values()].some(row => !row.assignment.verified)) this.reader.acknowledgeChanges(new Map([["*", this.assignmentBaseline.seq]]), true);
643
+ if (!this.imported) {
644
+ this.imported = true;
645
+ const degraded = this.state === "degraded" || this.sourceErrors.size || [...this.projected.values()].some(row => !row.assignment.verified);
646
+ this.state = degraded ? "degraded" : "ready";
647
+ this.reason = this.state === "ready" ? undefined : this.sourceErrors.values().next().value ?? this.reason ?? "Some assignment sources could not be verified.";
648
+ this.publish();
649
+ }
650
+ }
651
+ else { this.scheduling.repairBatches++; this.scheduling.repairEntries += next.value.length; await this.measuredScan("repair", next.value); }
652
+ await yieldTurn();
653
+ if (this.closed || this.sourceConflicts > 1 || (!drain && !this.hints.size)) break;
654
+ } while (this.repair || this.hints.size);
655
+ })().catch(error => {
656
+ this.repair = undefined; this.state = "degraded"; this.reason = String(error).slice(0, 512); this.publish();
657
+ }).finally(() => {
658
+ this.inventoryPhase?.("idle");
659
+ release();
150
660
  this.pending = undefined;
151
- if (this.dirty && !this.closed) { this.dirty = false; void this.reconcile(); }
661
+ if (this.observationInitialized && (this.hints.size || this.dirty) && !this.closed && !this.unsupportedAssignmentRevision) {
662
+ this.dirty = false;
663
+ if (this.sourceConflicts > 1) {
664
+ this.conflictRetry = setTimeout(() => {
665
+ this.conflictRetry = undefined;
666
+ void this.reconcile(false);
667
+ }, this.conflictDelay);
668
+ this.conflictRetry.unref();
669
+ this.conflictDelay = Math.min(1000, this.conflictDelay * 2);
670
+ } else void this.reconcile(false);
671
+ }
152
672
  });
153
673
  return this.pending;
154
674
  }
155
675
 
156
- private async scan() {
157
- this.metrics.inventories++;
158
- if (this.background.refresh()) this.publish();
676
+ private async measuredScan(kind: "entity" | "repair", paths: string[]) {
677
+ const before = { stats: this.sourceStats, metadataReads: this.counters.metadataReads, logBytes: logReadMetrics.bytes, logReads: logReadMetrics.reads };
678
+ await this.scan(paths);
679
+ const counter = this.sourceWork[kind]; counter.batches++; counter.paths += paths.length;
680
+ counter.stats += this.sourceStats - before.stats; counter.metadataReads += this.counters.metadataReads - before.metadataReads;
681
+ counter.logBytes += logReadMetrics.bytes - before.logBytes; counter.logReads += logReadMetrics.reads - before.logReads;
682
+ }
683
+
684
+ private async watchRegistrations() {
685
+ await Promise.all([...this.watchers.values(), ...[...this.rootParents.values()].map(value => value.watcher)].map(watcher => watcher.ready));
686
+ }
687
+
688
+ private async scan(paths: string[]) {
689
+ let sourceConflict = false;
690
+ this.assignmentFault = undefined;
691
+ const sourceStat: typeof stat = ((...args: any[]) => { this.sourceStats++; return (stat as any)(...args); }) as typeof stat;
692
+ this.counters.inventories++;
159
693
  let releaseCoordinator: (() => void) | undefined;
160
- const baseline = this.staged ?? { files: this.files, projected: this.projected, logs: this.logs, processes: this.processes,
161
- healthRevision: this.healthRevision, coordinator: this.coordinator, coordinatorConversations: this.coordinatorConversations };
694
+ let commitCoordinator: (() => void) | undefined;
695
+ const checkpointWrites: Array<[string, unknown]> = [];
696
+ const parseBefore = new Map(this.parseStates), healthBefore = new Map(this.healthStates);
697
+ let sourceRace: WorkReadModel["sourceRace"];
698
+ const baseline = this.staged ?? { files: this.files, projected: this.projected, logs: this.logs, failureJournals: this.failureJournals, processes: this.processes,
699
+ healthRevision: this.healthRevision, coordinator: this.coordinator };
162
700
  try {
163
- const next = new Map<string, { signature: string; meta: any }>();
701
+ this.inventoryPhase?.("metadata");
702
+ const next = new Map(baseline.files);
703
+ const failedPaths = new Map<string, string>();
704
+ const malformedPaths = new Set<string>();
164
705
  let batch = 0;
165
706
  let sliceStarted = performance.now();
166
707
  for (const [directory, archived] of [[this.markers, true], [this.archives, true], [this.runs, false]] as const) {
167
- let names: string[];
168
- try { names = await readdir(directory); }
169
- catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; throw error; }
708
+ const names = paths.filter(path => archived ? path.startsWith(directory + sep) && !path.slice(directory.length + 1).includes(sep)
709
+ : path.startsWith(directory + sep)).map(path => archived ? path.slice(directory.length + 1) : path.slice(directory.length + 1).split(sep)[0]!);
170
710
  // Bound filesystem concurrency without serializing every archive round trip.
171
711
  const candidates = names.filter(name => safeId.test(archived ? name.replace(/\.json$/, "") : name)
172
712
  && (!archived || name.endsWith(".json")));
173
713
  for (let offset = 0; offset < candidates.length; offset += 32) {
174
714
  const group = candidates.slice(offset, offset + 32);
175
715
  const observations = await Promise.all(group.map(async name => {
716
+ if (!archived) this.watchDirectory(join(directory, name));
176
717
  const path = archived ? join(directory, name) : join(directory, name, "meta.json");
177
- try { return { info: await stat(path, { bigint: true }) }; }
718
+ try { return { info: await sourceStat(path, { bigint: true }) }; }
178
719
  catch (error) { return { error }; }
179
720
  }));
180
721
  for (const [index, name] of group.entries()) {
@@ -185,9 +726,10 @@ export class WorkReadModel {
185
726
  if (!observation.info) throw observation.error;
186
727
  const info = observation.info;
187
728
  const signature = `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
188
- let entry = baseline.files.get(path);
729
+ let entry = next.get(path);
189
730
  if (entry?.signature !== signature) {
190
- this.metrics.metadataReads++;
731
+ if (info.size > 1024n * 1024n) throw new Error(`Run metadata exceeds the 1 MiB observation budget: ${id}`);
732
+ this.counters.metadataReads++;
191
733
  const raw = await readFile(path, "utf8");
192
734
  if (directory === this.markers) {
193
735
  const marker = parseArchivedSessionState(raw, id);
@@ -202,7 +744,29 @@ export class WorkReadModel {
202
744
  }
203
745
  next.set(path, entry!);
204
746
  } catch (error) {
205
- if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
747
+ if (!archived && error instanceof SyntaxError && this.files.has(path)) malformedPaths.add(path);
748
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {
749
+ try {
750
+ await sourceStat(directory);
751
+ next.delete(path);
752
+ if (!archived) {
753
+ // A mkdir notification can arrive before its metadata commit.
754
+ // Retire the inode watcher only when the directory is gone.
755
+ try { await sourceStat(join(directory, name)); }
756
+ catch (error) {
757
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
758
+ this.unwatchDirectory(join(directory, name));
759
+ }
760
+ }
761
+ } catch {
762
+ failedPaths.set(path, `Source directory unavailable; retaining verified records: ${directory}`);
763
+ }
764
+ } else failedPaths.set(path, String(error).slice(0, 512));
765
+ if (failedPaths.has(path)) {
766
+ const verified = this.files.get(path);
767
+ if (verified) next.set(path, verified);
768
+ else next.delete(path);
769
+ }
206
770
  }
207
771
  if (++batch % 256 === 0 || performance.now() - sliceStarted >= 8) {
208
772
  await yieldTurn(); sliceStarted = performance.now();
@@ -211,94 +775,263 @@ export class WorkReadModel {
211
775
  }
212
776
  }
213
777
  }
778
+ this.inventoryPhase?.("coordinator");
779
+ let assignmentChanges: Map<string, string> | undefined;
780
+ try { assignmentChanges = this.reader.changes(); } catch { /* Legacy sources retain bounded repair. */ }
214
781
  let coordinator: string;
215
782
  try {
216
783
  const snapshot = this.reader.beginSnapshot();
217
- coordinator = snapshot.revision; releaseCoordinator = snapshot.release;
784
+ coordinator = snapshot.revision; releaseCoordinator = snapshot.release; commitCoordinator = snapshot.commit;
218
785
  } catch { coordinator = "unknown"; }
219
- const coordinatorConversations = coordinator === baseline.coordinator ? baseline.coordinatorConversations : this.reader.conversationRevisions();
786
+ if (assignmentChanges?.has("*")) {
787
+ const seq = assignmentChanges.get("*")!;
788
+ const key = `${this.reader.changeMetrics.generation}:${seq}`;
789
+ if (this.assignmentBaseline?.key !== key) {
790
+ this.assignmentBaseline = { key, seq };
791
+ if (this.imported) {
792
+ this.imported = false; this.repairOwed = true;
793
+ await this.repair?.return(undefined); this.repair = undefined;
794
+ }
795
+ }
796
+ }
797
+ this.inventoryPhase?.("log-stats");
220
798
  const logs = new Map<string, string>();
799
+ const failureJournals = new Map<string, string>();
221
800
  const processes = new Map<string, string>();
222
801
  const logFamilies = new Set<string>();
802
+ const terminalLogChanges: string[] = [];
223
803
  for (const [path, entry] of next) {
224
804
  if (!path.startsWith(this.runs + sep)) continue;
805
+ if (failedPaths.has(path)) {
806
+ const id = entry.meta.id;
807
+ if (this.logs.has(id)) logs.set(id, this.logs.get(id)!);
808
+ if (this.failureJournals.has(id)) failureJournals.set(id, this.failureJournals.get(id)!);
809
+ if (this.processes.has(id)) processes.set(id, this.processes.get(id)!);
810
+ continue;
811
+ }
812
+ if (!paths.includes(path)) {
813
+ const id = entry.meta.id;
814
+ if (baseline.logs.has(id)) logs.set(id, baseline.logs.get(id)!);
815
+ if (baseline.failureJournals.has(id)) failureJournals.set(id, baseline.failureJournals.get(id)!);
816
+ if (baseline.processes.has(id)) processes.set(id, baseline.processes.get(id)!);
817
+ continue;
818
+ }
225
819
  let signature = baseline.logs.get(entry.meta.id);
226
820
  {
227
821
  try {
228
- const info = await stat(join(this.runs, entry.meta.id, "output.log"), { bigint: true });
822
+ const info = await sourceStat(join(this.runs, entry.meta.id, "output.log"), { bigint: true });
229
823
  signature = `${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
230
824
  } catch (error) { signature = (error as NodeJS.ErrnoException).code === "ENOENT" ? "missing" : "unverified"; }
231
825
  }
232
826
  logs.set(entry.meta.id, signature);
233
- if (signature !== baseline.logs.get(entry.meta.id)) logFamilies.add(JSON.stringify([entry.meta.sessionId, entry.meta.cwd]));
827
+ if ((signature !== this.logs.get(entry.meta.id) || this.files.get(path)?.meta.status !== entry.meta.status) && entry.meta.status !== "running"
828
+ && entry.meta.management?.root === this.agentDir) terminalLogChanges.push(entry.meta.id);
829
+ if (signature !== baseline.logs.get(entry.meta.id)) logFamilies.add(entry.meta.id);
830
+ const failureSignature = (await Promise.all(["failures.jsonl", "failures.jsonl.observed"].map(async name => {
831
+ try { const info = await sourceStat(join(this.runs, entry.meta.id, name), { bigint: true }); return `${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`; }
832
+ catch (error) { return (error as NodeJS.ErrnoException).code === "ENOENT" ? "missing" : "unverified"; }
833
+ }))).join(":");
834
+ failureJournals.set(entry.meta.id, failureSignature);
835
+ if (failureSignature !== baseline.failureJournals.get(entry.meta.id)) logFamilies.add(entry.meta.id);
836
+
234
837
  const status = effectiveStatus(entry.meta); processes.set(entry.meta.id, status);
235
- if (status !== baseline.processes.get(entry.meta.id)) logFamilies.add(JSON.stringify([entry.meta.sessionId, entry.meta.cwd]));
838
+ if (status !== baseline.processes.get(entry.meta.id)) logFamilies.add(entry.meta.id);
236
839
  if (performance.now() - sliceStarted >= 8) { await yieldTurn(); sliceStarted = performance.now(); }
237
840
  }
238
841
  const healthConfig = await readHealthConfig(this.agentDir, next.size > 0);
842
+ if (healthConfig.revision !== baseline.healthRevision) this.counters.healthConfigInvalidations++;
239
843
  const changed = next.size !== baseline.files.size || [...next].some(([path, entry]) => baseline.files.get(path)?.signature !== entry.signature);
240
- if (!this.staged && !changed && !logFamilies.size && coordinator === this.coordinator && healthConfig.revision === this.healthRevision && this.state === "ready") return;
844
+ const now = Date.now();
845
+ const deadlineExpired = [...baseline.projected.values()].some(row => healthDeadlineExpired(row, now));
846
+ const rawDirectories = [...new Set(paths.filter(path => path.startsWith(this.runs + sep) && next.has(path)).map(path => dirname(path)))];
847
+ const rearmRawDirectories = () => {
848
+ if (!rawDirectories.length) return;
849
+ this.watchDirectory(this.runs);
850
+ for (const directory of rawDirectories) this.watchDirectory(directory);
851
+ };
852
+ // A delayed mkdir notification may retire a watch during the awaited reads.
853
+ rearmRawDirectories();
854
+ await this.watchRegistrations();
855
+ if (!this.staged && !changed && !failedPaths.size && !this.sourceErrors.size && !logFamilies.size && !assignmentChanges?.size && !deadlineExpired && coordinator === this.coordinator && healthConfig.revision === this.healthRevision && !healthConfig.reason && this.state === "ready") return;
241
856
  const metas = new Map<string, any>();
242
857
  const markers = new Map([...next].filter(([path]) => path.startsWith(this.markers + sep)).map(([, entry]) => [entry.meta.sessionId, entry.meta]));
243
858
  for (const [path, entry] of next) {
244
859
  if (path.startsWith(this.markers + sep)) continue;
860
+ // Compact archives omit volatile delivery markers. A verified live
861
+ // record wins independently of which source was discovered last.
862
+ if (path.startsWith(this.archives + sep) && next.has(join(this.runs, entry.meta.id, "meta.json"))) continue;
245
863
  const marker = markers.get(entry.meta.sessionId);
246
864
  if (path.startsWith(this.archives + sep) && marker && marker.attemptId !== entry.meta.id && marker.startedAt >= entry.meta.startedAt) continue;
247
865
  metas.set(entry.meta.id, entry.meta);
248
866
  }
867
+ this.inventoryPhase?.("projection");
249
868
  const attempts = [...metas.values()];
250
- const affected = new Set<string>(logFamilies);
251
- const family = (meta: any) => JSON.stringify([meta.sessionId, meta.cwd]);
869
+ const changedAttempts = new Set<any>();
252
870
  for (const [path, entry] of [...baseline.files, ...next]) {
253
- if (baseline.files.get(path)?.signature !== next.get(path)?.signature) affected.add(family(entry.meta));
871
+ if (baseline.files.get(path)?.signature !== next.get(path)?.signature) {
872
+ if (path.startsWith(this.markers + sep)) {
873
+ for (const meta of attempts) if (meta.sessionId === entry.meta.sessionId) changedAttempts.add(meta);
874
+ } else changedAttempts.add(entry.meta);
875
+ }
254
876
  }
255
- if (coordinator !== baseline.coordinator) for (const meta of attempts) {
877
+ const assignmentGeneration = this.reader.changeMetrics.generation;
878
+ // An unpublished retry may reuse a verified projection only at the same
879
+ // durable source generation and per-scope position. Receipt stays pending.
880
+ const changedScope = (scope: string) => assignmentChanges?.has(scope)
881
+ && (!this.staged || this.staged.assignmentGeneration !== assignmentGeneration
882
+ || this.staged.assignmentChanges?.get(scope) !== assignmentChanges.get(scope));
883
+ for (const meta of attempts) {
256
884
  if (!(meta.assignment || meta.operations || meta.park)) continue;
257
- const owner = JSON.stringify([meta.operations?.conversationId ?? meta.sessionId, meta.operations?.workspace ?? meta.cwd]);
258
- if (!coordinatorConversations || !baseline.coordinatorConversations ||
259
- coordinatorConversations.get(owner) !== baseline.coordinatorConversations.get(owner)) affected.add(family(meta));
885
+ const session = meta.assignment?.owner?.sessionId ?? meta.operations?.conversationId ?? meta.sessionId;
886
+ const workspace = meta.assignment?.owner?.workspace ?? meta.operations?.workspace ?? meta.cwd;
887
+ if ((changedScope("*") && paths.some(path => next.get(path)?.meta.id === meta.id))
888
+ || changedScope(JSON.stringify([session, workspace, meta.assignment?.assignmentId ?? null]))
889
+ || changedScope(JSON.stringify([session, workspace, null]))
890
+ || (!assignmentChanges && paths.some(path => next.get(path)?.meta.id === meta.id))) changedAttempts.add(meta);
260
891
  }
892
+ const affected = await affectedAttempts(
893
+ [...baseline.projected.values()].map(row => row.meta).concat(attempts), changedAttempts);
894
+ if (this.closed) return;
261
895
  const project = createAssignmentProjector({ attempts, observe: (owner: any) => this.reader.read(owner) });
896
+ const touched = new Set(paths.map(path => next.get(path)?.meta.id));
262
897
  const rows = [];
263
898
  for (const meta of attempts) {
264
899
  let row = baseline.projected.get(meta.id);
265
- if (!row || !row.assignment.verified || healthConfig.revision !== baseline.healthRevision || affected.has(family(meta))) {
266
- this.metrics.projections++;
267
- const assignment = project(meta, processes.get(meta.id) ?? meta.status);
268
- const parsed = logs.get(meta.id) && logs.get(meta.id) !== "missing" ? parseRun(meta.id, { logPath: join(this.runs, meta.id, "output.log") }) : undefined;
269
- const display = { spend: parsed ? fmtSpend(parsed.usage) : "", tool: parsed?.toolCalls.at(-1) ?? "" };
270
- const health = logs.has(meta.id) ? { ...extractChildEventFactsFromLog(meta.id, { logPath: join(this.runs, meta.id, "output.log") }), thresholds: healthThresholdsForConfig(healthConfig.config) } : undefined;
271
- row = { meta, assignment, display, health, sourceRevision: hash([meta, assignment.revision, display, health]) };
900
+ const assignmentChanged = !row || (!row.assignment.verified && touched.has(meta.id)) || affected.has(meta.id) || processes.get(meta.id) !== baseline.processes.get(meta.id);
901
+ const logChanged = !row || logs.get(meta.id) !== baseline.logs.get(meta.id);
902
+ const failureChanged = !row || failureJournals.get(meta.id) !== baseline.failureJournals.get(meta.id);
903
+ const deadlineChanged = row && healthDeadlineExpired(row, now);
904
+ if (row && !assignmentChanged && !logChanged && !failureChanged && (healthConfig.revision !== baseline.healthRevision || deadlineChanged)) {
905
+ if (healthConfig.revision !== baseline.healthRevision) this.invalidations.healthConfig++;
906
+ if (deadlineChanged) this.invalidations.healthDeadline++;
907
+ this.counters.healthRecomputations++;
908
+ const health = healthWithThresholds(row.health, healthConfig.config, meta);
909
+ row = { ...row, health, sourceRevision: hash([meta, row.assignment.revision, row.display, health, row.recipientPending, row.failurePending, failureJournals.get(meta.id)]) };
910
+ } else if (assignmentChanged || logChanged || failureChanged) {
911
+ if (!row) this.invalidations.initial++;
912
+ else {
913
+ if (affected.has(meta.id)) this.invalidations.assignmentInput++;
914
+ if (!row.assignment.verified) this.invalidations.unverified++;
915
+ if (processes.get(meta.id) !== baseline.processes.get(meta.id)) this.invalidations.process++;
916
+ if (logChanged) this.invalidations.log++;
917
+ if (failureChanged) this.invalidations.failureAttention++;
918
+ if (healthConfig.revision !== baseline.healthRevision) this.invalidations.healthConfig++;
919
+ if (deadlineChanged) this.invalidations.healthDeadline++;
920
+ }
921
+ this.counters.projections++;
922
+ if (assignmentChanged) this.counters.assignmentProjections++;
923
+ const assignment = assignmentChanged ? project(meta, processes.get(meta.id) ?? meta.status) : row!.assignment;
924
+ let display = row?.display, health = row?.health;
925
+ if (logChanged) withLogReadBatch(() => {
926
+ this.counters.logProjections++; this.counters.healthProjections++;
927
+ const logPath = join(this.runs, meta.id, "output.log");
928
+ const priorDisplay = parseBefore.get(logPath), priorHealth = healthBefore.get(logPath);
929
+ if (priorDisplay && this.parseStates.get(logPath) === priorDisplay)
930
+ this.parseStates.set(logPath, decodeParseLogState(structuredClone(encodeParseLogState(priorDisplay))));
931
+ if (priorHealth && this.healthStates.get(logPath) === priorHealth)
932
+ this.healthStates.set(logPath, decodeHealthLogState(structuredClone(encodeHealthLogState(priorHealth))));
933
+ if (!this.parseStates.has(logPath) || !this.healthStates.has(logPath)) {
934
+ const saved = this.checkpoints.load(logPath);
935
+ if (saved) {
936
+ try {
937
+ if (!Number.isSafeInteger(saved.display.cursor.offset) || !Number.isSafeInteger(saved.health.cursor.offset)) throw new Error("Invalid checkpoint offset");
938
+ this.parseStates.set(logPath, decodeParseLogState(saved.display));
939
+ this.healthStates.set(logPath, decodeHealthLogState(saved.health));
940
+ } catch { this.parseStates.delete(logPath); this.healthStates.delete(logPath); }
941
+ }
942
+ }
943
+ const parsed = logs.get(meta.id) && logs.get(meta.id) !== "missing" ? parseRunDisplay(meta.id, { logPath, states: this.parseStates, summaryOnly: true }) : undefined;
944
+ display = { spend: parsed ? fmtSpend(parsed.usage) : "", tool: parsed?.tool ?? "" };
945
+ health = logs.has(meta.id) ? extractChildEventFactsFromLog(meta.id, { logPath, states: this.healthStates }) : undefined;
946
+ const displayState = this.parseStates.get(logPath), healthState = this.healthStates.get(logPath);
947
+ display = { ...display!, diagnostics: parsed?.diagnostics, coverage: displayState ? {
948
+ start: displayState.cursor.coverageStart ?? 0, offset: displayState.cursor.offset,
949
+ totalBytes: displayState.totalBytes, missing: displayState.cursor.missing,
950
+ complete: !displayState.catchingUp && !displayState.windowTruncated && displayState.cursor.offset === displayState.totalBytes,
951
+ } : undefined };
952
+ if (health && healthState) health = { ...health, coverage: { start: healthState.cursor.coverageStart ?? 0,
953
+ offset: healthState.cursor.offset, missing: healthState.cursor.missing } };
954
+ if (displayState?.catchingUp) logs.set(meta.id, `${logs.get(meta.id)}:catching-up`);
955
+ if (displayState && healthState) checkpointWrites.push([logPath, {
956
+ display: encodeParseLogState(displayState), health: encodeHealthLogState(healthState),
957
+ }]);
958
+ while (this.parseStates.size > 64) this.parseStates.delete(this.parseStates.keys().next().value);
959
+ while (this.healthStates.size > 64) this.healthStates.delete(this.healthStates.keys().next().value);
960
+ });
961
+ if (logChanged || assignmentChanged || deadlineChanged || healthConfig.revision !== baseline.healthRevision) {
962
+ this.counters.healthRecomputations++;
963
+ health = healthWithThresholds(health, healthConfig.config, meta);
964
+ }
965
+ const outcome = meta.assignment ? this.reader.read({ ...meta.assignment.owner, assignmentId: meta.assignment.assignmentId }).outcome : undefined;
966
+ if (failureChanged || assignmentChanged) this.counters.failureProjections++;
967
+ const failurePending = !failureChanged && !assignmentChanged ? row!.failurePending : meta.callback !== false && failureJournals.has(meta.id) && Boolean(pendingFailureAttention(
968
+ readFailureStateReadOnly(join(this.runs, meta.id, "failures.jsonl")), Date.now(),
969
+ { terminal: !["running", "orphaned"].includes(meta.status), deferObservationGaps: meta.status === "running" }));
970
+ const recipientPending = Boolean(failurePending || meta.timing?.pendingWakes?.length
971
+ || (meta.status === "orphaned" && meta.orphanedCallbackSentAt === undefined && meta.orphanedCallbackSuppressedAt === undefined)
972
+ || (meta.status === "lost" && meta.lostCallbackSentAt === undefined && meta.lostCallbackSuppressedAt === undefined)
973
+ || (meta.callback !== false && (meta.assignment ? outcome && !outcome.deliveryReceipt && !outcome.disposition
974
+ : meta.completionCallbackPendingAt !== undefined && meta.completionCallbackSentAt === undefined && meta.completionCallbackSuppressedAt === undefined)));
975
+ row = { meta, assignment, display, health, recipientPending, failurePending, sourceRevision: hash([meta, assignment.revision, display, health, recipientPending, failurePending, failureJournals.get(meta.id)]) };
272
976
  }
273
- rows.push(row);
977
+ rows.push(row!);
274
978
  if (++batch % 256 === 0 || performance.now() - sliceStarted >= 8) {
275
979
  await yieldTurn(); sliceStarted = performance.now();
276
980
  }
277
981
  }
982
+ this.inventoryPhase?.("verify");
983
+ // The pinned source snapshot is a valid baseline even while writers advance.
984
+ // Subsequent commits remain beyond the durable received position.
985
+ const globallyUnverified = !!healthConfig.reason || rows.some(row => !row.assignment.verified);
278
986
  let after: string;
279
987
  try { after = this.reader.revision(); } catch { after = "unknown"; }
280
- if (after !== coordinator) { this.state = "degraded"; this.reason = "Coordinator changed during observation; retrying."; this.dirty = true; this.publish(); return; }
988
+ if (after !== coordinator) {
989
+ sourceConflict = true;
990
+ this.dirty = true;
991
+ throw new Error("Coordinator changed during observation; retrying.");
992
+ }
281
993
  // Retry caches are never queryable. Validate all unpublished families again before committing them.
282
- this.staged = { files: next, projected: new Map(rows.map(row => [row.meta.id, row])), logs, processes,
283
- healthRevision: healthConfig.revision, coordinator, coordinatorConversations };
994
+ this.staged = { files: next, projected: new Map(rows.map(row => [row.meta.id, row])), logs, failureJournals, processes,
995
+ healthRevision: healthConfig.revision, coordinator, assignmentChanges: assignmentChanges && new Map(assignmentChanges),
996
+ assignmentGeneration };
284
997
  const uncommitted = new Set(affected);
285
998
  for (const [path, entry] of [...this.files, ...next]) {
286
- if (this.files.get(path)?.signature !== next.get(path)?.signature) uncommitted.add(family(entry.meta));
999
+ if (this.files.get(path)?.signature !== next.get(path)?.signature) uncommitted.add(entry.meta.id);
287
1000
  }
288
- const verify = [...next].filter(([, entry]) => uncommitted.has(family(entry.meta)));
1001
+ const verify = [...next].filter(([path, entry]) => !failedPaths.has(path) && uncommitted.has(entry.meta.id));
289
1002
  for (let offset = 0; offset < verify.length; offset += 32) {
290
1003
  const group = verify.slice(offset, offset + 32);
291
1004
  const observations = await Promise.all(group.map(async ([path]) => {
292
- try { return { info: await stat(path, { bigint: true }) }; }
1005
+ try { return { info: await sourceStat(path, { bigint: true }) }; }
293
1006
  catch (error) { return { error }; }
294
1007
  }));
295
- for (const [index, [, entry]] of group.entries()) {
1008
+ for (const [index, [path, entry]] of group.entries()) {
296
1009
  const observation = observations[index]!;
297
1010
  if (!observation.info) throw observation.error;
298
1011
  const info = observation.info;
299
1012
  if (`${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}` !== entry.signature) {
1013
+ sourceConflict = true;
300
1014
  this.dirty = true;
301
- throw new Error("Source changed during observation; retaining the previous snapshot while reconciling.");
1015
+ const error = new Error("Source changed during observation; retaining the previous snapshot while reconciling.");
1016
+ if (!globallyUnverified && (this.state === "ready" || this.sourceRace && this.reason === this.sourceRace.reason)
1017
+ && path.startsWith(this.runs + sep) && info.size <= 1024n * 1024n && !failedPaths.size && [...this.sourceErrors].every(([path, reason]) =>
1018
+ this.sourceRace?.paths.has(path) && reason === this.sourceRace.reason)) {
1019
+ // Recheck only for error routing: a concurrent move can affect a
1020
+ // new workspace/recipient. Never publish this uncommitted row.
1021
+ try {
1022
+ this.counters.metadataReads++;
1023
+ const current = JSON.parse(await readFile(path, "utf8"));
1024
+ const checked = await sourceStat(path, { bigint: true });
1025
+ if (current?.id === entry.meta.id && typeof current.cwd === "string" && Number.isFinite(current.startedAt)
1026
+ && typeof current.status === "string" && checked.size <= 1024n * 1024n
1027
+ && `${checked.dev}:${checked.ino}:${checked.size}:${checked.mtimeNs}:${checked.ctimeNs}` === `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`) {
1028
+ sourceRace = { reason: String(error), paths: new Set(paths), rows: [
1029
+ ...[...uncommitted].flatMap(id => [this.projected.get(id), this.staged?.projected.get(id)].filter(Boolean)),
1030
+ { meta: current, assignment: { state: current.status } }] };
1031
+ }
1032
+ } catch { /* Unreadable/unstable routing evidence keeps degradation global. */ }
1033
+ }
1034
+ throw error;
302
1035
  }
303
1036
  if (++batch % 256 === 0 || performance.now() - sliceStarted >= 8) {
304
1037
  await yieldTurn(); sliceStarted = performance.now();
@@ -306,51 +1039,126 @@ export class WorkReadModel {
306
1039
  }
307
1040
  }
308
1041
  if (this.closed) return;
309
- this.db.exec("BEGIN");
310
- const insert = this.db.prepare("INSERT OR REPLACE INTO rows VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
1042
+ rearmRawDirectories();
1043
+ await this.watchRegistrations();
1044
+ this.inventoryPhase?.("commit");
1045
+ if (!commitCoordinator) this.db.exec("BEGIN");
1046
+ const insert = this.db.prepare("INSERT OR REPLACE INTO rows VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
311
1047
  const remove = this.db.prepare("DELETE FROM rows WHERE id = ?");
312
1048
  let semanticChange = false;
1049
+ const changedRows: WorkReadModel["changedRows"] = [];
1050
+ const publishCheckpoints: Array<() => void> = [];
313
1051
  try {
314
- for (const id of this.projected.keys()) if (!metas.has(id)) { remove.run(id); semanticChange = true; }
1052
+ for (const id of this.projected.keys()) if (!metas.has(id)) { changedRows.push({ before: this.projected.get(id) }); remove.run(id); this.db.prepare("DELETE FROM assignment_members WHERE id=?").run(id); this.db.prepare("DELETE FROM terminal_log_folds WHERE id=?").run(id); semanticChange = true; }
1053
+ for (const id of terminalLogChanges) this.db.prepare("INSERT INTO terminal_log_folds VALUES (?, ?, 1, ?) ON CONFLICT(id) DO UPDATE SET revision=excluded.revision, pending=1, queue_position=CASE WHEN terminal_log_folds.pending=0 THEN excluded.queue_position ELSE terminal_log_folds.queue_position END").run(id, hash([logs.get(id), metas.get(id)?.status]), ++this.foldQueueSequence);
315
1054
  for (const row of rows) {
316
1055
  if (this.projected.get(row.meta.id)?.sourceRevision === row.sourceRevision) continue;
317
1056
  semanticChange = true;
1057
+ changedRows.push({ before: this.projected.get(row.meta.id), after: row });
318
1058
  const m = row.meta;
1059
+ if (m.management?.root !== this.agentDir || m.status === "running") this.db.prepare("DELETE FROM terminal_log_folds WHERE id=?").run(m.id);
319
1060
  insert.run(m.id, m.cwd, m.callbackOrigin?.cwd ?? m.cwd, m.callbackOrigin?.sessionId ?? null,
320
- m.startedAt, row.assignment.state, ["running", "waiting"].includes(row.assignment.state) ? 1 : 0, m.endedAt ?? m.lostAt ?? null, JSON.stringify(row));
1061
+ m.startedAt, row.assignment.state, ["running", "waiting"].includes(row.assignment.state) ? 1 : 0, m.endedAt ?? m.lostAt ?? null, row.recipientPending ? 1 : 0, JSON.stringify(row));
1062
+ this.db.prepare("DELETE FROM assignment_members WHERE id=?").run(m.id);
1063
+ const session = m.assignment?.owner?.sessionId ?? m.operations?.conversationId ?? m.sessionId;
1064
+ const workspace = m.assignment?.owner?.workspace ?? m.operations?.workspace ?? m.cwd;
1065
+ for (const assignmentId of new Set([m.assignment?.assignmentId ?? null, null])) this.db.prepare("INSERT INTO assignment_members VALUES(?,?)").run(JSON.stringify([session, workspace, assignmentId]), m.id);
321
1066
  }
322
- this.db.exec("COMMIT");
323
- } catch (error) { this.db.exec("ROLLBACK"); throw error; }
324
- this.files = next; this.logs = logs; this.processes = processes; this.healthRevision = healthConfig.revision; this.coordinator = coordinator; this.inventory++;
325
- this.coordinatorConversations = coordinatorConversations;
1067
+ for (const [path, checkpoint] of checkpointWrites) publishCheckpoints.push(this.checkpoints.save(path, checkpoint, true));
1068
+ // Application and its exact acknowledgement share the owner commit.
1069
+ if (assignmentChanges && rows.every(row => row.assignment.verified)) this.reader.acknowledgeChanges(assignmentChanges, false);
1070
+ if (commitCoordinator) commitCoordinator(); else this.db.exec("COMMIT");
1071
+ } catch (error) {
1072
+ if (releaseCoordinator) releaseCoordinator(); else this.db.exec("ROLLBACK");
1073
+ throw error;
1074
+ }
1075
+ for (const publish of publishCheckpoints) publish();
1076
+ this.files = next; this.logs = logs; this.failureJournals = failureJournals; this.processes = processes; this.healthRevision = healthConfig.revision; this.coordinator = coordinator; this.inventory++;
326
1077
  this.projected = new Map(rows.map(row => [row.meta.id, row]));
1078
+ for (const states of [this.parseStates, this.healthStates]) for (const path of states.keys()) {
1079
+ if (!metas.has(path.slice(this.runs.length + 1).split(sep)[0])) states.delete(path);
1080
+ }
327
1081
  this.staged = undefined;
1082
+ this.sourceConflicts = 0; this.conflictDelay = 100;
1083
+ if (terminalLogChanges.length) this.onTerminalLogsChanged?.();
328
1084
  const previousState = this.state;
329
1085
  const previousReason = this.reason;
330
- this.state = rows.some(row => !row.assignment.verified) ? "degraded" : "ready";
331
- this.reason = this.state === "degraded" ? "Some assignment sources could not be verified." : undefined;
332
- if (semanticChange || previousState !== this.state || previousReason !== this.reason) this.publish();
1086
+ for (const path of paths) {
1087
+ const error = failedPaths.get(path);
1088
+ if (error) this.sourceErrors.set(path, error);
1089
+ else this.sourceErrors.delete(path);
1090
+ }
1091
+ // Incomplete raw writes retain their verified namespace, not partial JSON.
1092
+ // New/unknown records and mixed failures cannot be narrowed this way.
1093
+ if (globallyUnverified) this.sourceRace = undefined;
1094
+ if (!globallyUnverified && failedPaths.size && failedPaths.size === malformedPaths.size
1095
+ && (previousState === "ready" || this.sourceRace && previousReason === this.sourceRace.reason)
1096
+ && [...this.sourceErrors.keys()].every(path => malformedPaths.has(path))) {
1097
+ this.sourceRace = { reason: failedPaths.values().next().value!, paths: malformedPaths,
1098
+ rows: [...malformedPaths].map(path => this.projected.get(this.files.get(path)!.meta.id)) };
1099
+ }
1100
+ if (!this.sourceErrors.size) this.sourceRace = undefined;
1101
+ this.state = this.sourceErrors.size || healthConfig.reason ? "degraded" : !this.imported ? "rebuilding" : rows.some(row => !row.assignment.verified) ? "degraded" : "ready";
1102
+ this.reason = this.sourceErrors.values().next().value ?? healthConfig.reason ?? (this.state === "rebuilding" ? "Initial source inventory is rebuilding." : this.state === "degraded" ? "Some assignment sources could not be verified." : undefined);
1103
+ if ((this.imported || paths.length === 128) && (semanticChange || previousState !== this.state || previousReason !== this.reason)) {
1104
+ this.changedRows = changedRows;
1105
+ this.publish();
1106
+ }
333
1107
  } catch (error) {
1108
+ releaseCoordinator?.(); releaseCoordinator = undefined;
1109
+ this.parseStates = parseBefore; this.healthStates = healthBefore;
334
1110
  if (this.closed) return;
335
- this.state = "degraded"; this.reason = String(error).slice(0, 512); this.publish();
1111
+ if (sourceConflict) this.sourceConflicts++;
1112
+ const reason = String(error).slice(0, 512);
1113
+ this.sourceRace = sourceRace;
1114
+ if (this.dirty) for (const path of paths) if (!this.hints.has(path)) this.hints.set(path, Date.now());
1115
+ for (const path of paths) this.sourceErrors.set(path, reason);
1116
+ const changed = this.state !== "degraded" || this.reason !== reason;
1117
+ this.state = "degraded"; this.reason = reason;
1118
+ if (changed) this.publish();
336
1119
  } finally { releaseCoordinator?.(); }
337
1120
  }
338
1121
 
1122
+ /** Derived pending index: no unbounded JavaScript backlog and no dropped IDs. */
1123
+ terminalLogChanges(): Array<{id: string; revision: string}> {
1124
+ return this.db.prepare("SELECT id, revision FROM terminal_log_folds WHERE pending=1 ORDER BY queue_position, id LIMIT 128").all();
1125
+ }
1126
+ acknowledgeTerminalLogs(batch: Array<{id: string; revision: string}>) {
1127
+ if (this.closed) return;
1128
+ if (this.reader?.snapshotActive && this.pending) {
1129
+ void this.pending.then(() => this.acknowledgeTerminalLogs(batch));
1130
+ return;
1131
+ }
1132
+ const acknowledge = this.db.prepare("UPDATE terminal_log_folds SET pending=CASE WHEN revision=? THEN 0 ELSE 1 END, queue_position=? WHERE id=?");
1133
+ // A newer revision remains owed, but rejoins behind existing obligations.
1134
+ // Continuously changing low IDs cannot monopolize every subsequent batch.
1135
+ for (const entry of batch) acknowledge.run(entry.revision, ++this.foldQueueSequence, entry.id);
1136
+ }
1137
+
339
1138
  snapshot(scope: WorkScope = {}): WorkSnapshot {
1139
+ if (!this.observationInitialized && !this.closed) return { instanceId: this.instanceId, runtimeEpoch: this.instanceId, scopeRevision: hash([scope, this.state, this.reason]), seq: this.revision,
1140
+ observedRevisionVector: { inventory: this.inventory, coordinator: this.coordinator, healthConfig: this.healthRevision }, status: this.state, reason: this.reason,
1141
+ rows: [], totalMatching: 0, activity: { active: 0 }, nextDeadline: null };
340
1142
  if (scope.background) {
341
- if (scope.backgroundHistory && this.background.refresh()) this.publish();
1143
+ if (!this.observationInitialized) {
1144
+ const status = this.state === "ready" ? "degraded" : this.state;
1145
+ const reason = this.reason ?? "Derived observation inputs are unavailable.";
1146
+ return { instanceId: this.instanceId, runtimeEpoch: this.instanceId, scopeRevision: hash([scope, status, reason]), seq: this.revision,
1147
+ observedRevisionVector: { inventory: this.inventory, coordinator: this.coordinator, healthConfig: this.healthRevision },
1148
+ status, reason, rows: [], totalMatching: 0, activity: { active: 0 }, nextDeadline: null };
1149
+ }
1150
+ if (scope.backgroundHistory && this.background.refresh()) this.publish(true);
342
1151
  const index = scope.backgroundHistory ? this.background.historyIndex(scope) : undefined;
343
1152
  const tasks = this.background.read(scope, index);
344
1153
  const status = this.background.status === "degraded" ? "degraded" : index ? this.background.historyStatus : this.background.status;
345
1154
  const active = (index ? this.background.read({ ...scope, backgroundHistory: false, active: true }) : tasks).filter(task => task.durable ? task.active : task.status === "running").length;
346
- this.metrics.coordinatorConnections = 1 + this.background.connectionCount;
347
1155
  return { instanceId: this.instanceId, runtimeEpoch: this.instanceId, scopeRevision: hash([scope, tasks, status, index?.page, active]), seq: this.revision,
348
1156
  observedRevisionVector: { inventory: this.inventory, coordinator: this.coordinator, healthConfig: this.healthRevision },
349
1157
  status, reason: this.background.reason ?? (index ? this.background.historyReason : undefined),
350
1158
  rows: tasks.map(meta => ({ meta, assignment: null, sourceRevision: hash(meta) })), totalMatching: index?.page.total ?? tasks.length,
351
1159
  ...(index?.page.nextCursor ? { nextCursor: index.page.nextCursor } : {}),
352
1160
  ...(index ? { backgroundIndex: index } : {}),
353
- activity: { active }, nextDeadline: null };
1161
+ activity: { active }, nextDeadline: scope.backgroundHistory ? null : this.background.nextDeadline(scope) };
354
1162
  }
355
1163
  const clauses: string[] = [], args: any[] = [];
356
1164
  if (scope.id) { clauses.push("id = ?"); args.push(scope.id); }
@@ -358,25 +1166,38 @@ export class WorkReadModel {
358
1166
  else if (scope.cwd) { const cwd = resolve(scope.cwd); clauses.push("(cwd = ? OR substr(cwd, 1, ?) = ?)"); args.push(cwd, (cwd.endsWith(sep) ? cwd : cwd + sep).length, cwd.endsWith(sep) ? cwd : cwd + sep); }
359
1167
  // Activity describes the scope, independently of history filters and pagination.
360
1168
  const active = Number(this.db.prepare(`SELECT count(*) AS n FROM rows WHERE ${[...clauses, "active = 1"].join(" AND ")}`).get(...args).n);
1169
+ if (scope.pendingRecipient !== undefined) {
1170
+ if (!scope.sessionId || !scope.cwd) throw new Error("Pending recipient query requires an exact conversation");
1171
+ clauses.push("recipient_pending = ?"); args.push(scope.pendingRecipient ? 1 : 0);
1172
+ }
361
1173
  if (scope.active !== undefined) { clauses.push("active = ?"); args.push(scope.active ? 1 : 0); }
362
1174
  if (scope.endedAfter !== undefined) { clauses.push("(ended IS NULL OR ended >= ?)"); args.push(scope.endedAfter); }
363
1175
  if (scope.statuses?.length) { clauses.push(`state IN (${scope.statuses.map(() => "?").join(",")})`); args.push(...scope.statuses); }
364
- const key = hash({ ...scope, cursor: undefined });
1176
+ const key = this.scopeKey(scope);
1177
+ const entry = this.scopeEntry(scope);
365
1178
  const totalMatching = Number(this.db.prepare(`SELECT count(*) AS n FROM rows ${clauses.length ? "WHERE " + clauses.join(" AND ") : ""}`).get(...args).n);
366
1179
  if (scope.cursor) {
367
1180
  let cursor;
368
1181
  try { cursor = JSON.parse(Buffer.from(scope.cursor, "base64url").toString()); } catch { throw new Error("Invalid runtime cursor"); }
369
- if (!Array.isArray(cursor) || cursor[0] !== key || cursor[1] !== this.instanceId || cursor[2] !== this.revision) throw new Error("resync_required: cursor snapshot changed");
1182
+ if (!Array.isArray(cursor) || cursor[0] !== key || cursor[1] !== this.instanceId || cursor[2] !== `${entry.token}:${entry.revision}`) throw new Error("resync_required: cursor snapshot changed");
370
1183
  clauses.push("(started < ? OR (started = ? AND id < ?))"); args.push(cursor[3], cursor[3], cursor[4]);
371
1184
  }
372
1185
  const limit = Math.max(1, Math.min(200, Number.isSafeInteger(scope.limit) ? scope.limit! : 50));
373
1186
  const records = this.db.prepare(`SELECT payload, started, id FROM rows ${clauses.length ? "WHERE " + clauses.join(" AND ") : ""} ORDER BY started DESC, id DESC LIMIT ?`).all(...args, limit + 1);
374
1187
  const page = records.slice(0, limit), last = page.at(-1);
375
- return { instanceId: this.instanceId, runtimeEpoch: this.instanceId, scopeRevision: hash([key, this.revision]), seq: this.revision,
376
- observedRevisionVector: { inventory: this.inventory, coordinator: this.coordinator, healthConfig: this.healthRevision }, status: this.state, reason: this.reason,
1188
+ const now = Date.now();
1189
+ const rows = page.map((record: any) => {
1190
+ const row = JSON.parse(record.payload);
1191
+ if (this.unsupportedAssignmentRevision) row.assignment = { ...row.assignment, verified: false, reason: this.reason };
1192
+ if (row.health) row.health.nextDeadline = nextHealthDeadline(row.health, row.meta, now);
1193
+ return row;
1194
+ });
1195
+ const deadlines = rows.map((row: any) => row.health?.nextDeadline).filter((deadline: any) => typeof deadline === "number");
1196
+ return { instanceId: this.instanceId, runtimeEpoch: this.instanceId, scopeRevision: hash([key, entry.token, entry.revision]), seq: this.revision,
1197
+ observedRevisionVector: { inventory: this.inventory, coordinator: this.coordinator, healthConfig: this.healthRevision }, ...this.scopeStatus(scope),
377
1198
  totalMatching,
378
- rows: page.map((record: any) => {
379
- const row = JSON.parse(record.payload);
1199
+ rows: page.map((record: any, index: number) => {
1200
+ const row = rows[index];
380
1201
  if (scope.detail && scope.id) {
381
1202
  let cached = this.details.get(row.meta.id);
382
1203
  if (!cached || cached.revision !== row.sourceRevision) {
@@ -395,15 +1216,20 @@ export class WorkReadModel {
395
1216
  }
396
1217
  row.detail = cached.value;
397
1218
  }
398
- return { ...row, cursor: Buffer.from(JSON.stringify([key, this.instanceId, this.revision, record.started, record.id])).toString("base64url") };
1219
+ return { ...row, cursor: Buffer.from(JSON.stringify([key, this.instanceId, `${entry.token}:${entry.revision}`, record.started, record.id])).toString("base64url") };
399
1220
  }),
400
- ...(records.length > limit ? { nextCursor: Buffer.from(JSON.stringify([key, this.instanceId, this.revision, last.started, last.id])).toString("base64url") } : {}),
401
- activity: { active }, nextDeadline: null };
1221
+ ...(records.length > limit ? { nextCursor: Buffer.from(JSON.stringify([key, this.instanceId, `${entry.token}:${entry.revision}`, last.started, last.id])).toString("base64url") } : {}),
1222
+ activity: { active }, nextDeadline: deadlines.length ? Math.min(...deadlines) : null };
402
1223
  }
403
1224
 
404
1225
  async close() {
405
1226
  this.closed = true; if (this.timer) clearInterval(this.timer);
406
- for (const watcher of this.watchers) watcher.close();
407
- await this.pending; this.listeners.clear(); await this.background.close(); this.reader.close(); this.db.close();
1227
+ if (this.conflictRetry) clearTimeout(this.conflictRetry);
1228
+ for (const watcher of this.watchers.values()) watcher.close();
1229
+ for (const { watcher } of this.rootParents.values()) watcher.close();
1230
+ this.rootParents.clear();
1231
+ this.watchers.clear(); this.rootWatchIdentities.clear();
1232
+ await this.pending; await this.repairWrite; this.listeners.clear(); await this.background.close(); this.reader?.close(); this.checkpoints.close(); this.db.close();
1233
+ await this.repair?.return(undefined);
408
1234
  }
409
1235
  }