pi-better-server 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (340) hide show
  1. package/package.json +7 -3
  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 +37 -5
  6. package/scripts/event-publication/writer.mjs +3 -8
  7. package/scripts/measure-full-runtime/frontend.ts +10 -2
  8. package/scripts/measure-full-runtime/probe.mjs +4 -2
  9. package/scripts/measure-full-runtime/recovery-trace-loader.mjs +51 -0
  10. package/scripts/measure-full-runtime/recovery-trace.mjs +16 -0
  11. package/scripts/measure-full-runtime.mjs +2 -0
  12. package/scripts/measure-shared-reads.mjs +2 -1
  13. package/scripts/private-runtime/package-lock.json +18 -0
  14. package/scripts/private-runtime/package.json +4 -1
  15. package/scripts/source-provenance.mjs +2 -2
  16. package/scripts/test-on-pi.sh +2 -9
  17. package/src/handshake.ts +1 -1
  18. package/src/hosted-session.ts +32 -4
  19. package/src/maintenance.ts +35 -7
  20. package/src/registry.ts +28 -4
  21. package/src/runtime/attempt-invalidation.ts +54 -0
  22. package/src/runtime/background-history.ts +151 -45
  23. package/src/runtime/background-policy.ts +9 -4
  24. package/src/runtime/background-tools.ts +181 -27
  25. package/src/runtime/background.ts +365 -70
  26. package/src/runtime/cancellation.ts +28 -7
  27. package/src/runtime/catalog-sources.ts +199 -0
  28. package/src/runtime/catalog.ts +53 -21
  29. package/src/runtime/client.ts +22 -2
  30. package/src/runtime/domain/assignment-inbox.mjs +119 -0
  31. package/src/runtime/domain/assignment-observation.d.mts +1 -1
  32. package/src/runtime/domain/assignment-observation.mjs +43 -35
  33. package/src/runtime/domain/background/process-identity.mjs +20 -2
  34. package/src/runtime/domain/background/process.mjs +52 -14
  35. package/src/runtime/domain/background/registry.mjs +61 -3
  36. package/src/runtime/domain/background/supervisor/store.mjs +3 -3
  37. package/src/runtime/domain/background/supervisor/supervisor.mjs +9 -3
  38. package/src/runtime/domain/background/types.mjs +1 -0
  39. package/src/runtime/domain/background-service/adapter-contract.domain.mjs +1 -1
  40. package/src/runtime/domain/background-service/adapter-contract.ts +1 -1
  41. package/src/runtime/domain/background-service/goal-provider.domain.mjs +35 -16
  42. package/src/runtime/domain/background-service/goal-provider.ts +31 -16
  43. package/src/runtime/domain/background-service/index.domain.mjs +25 -9
  44. package/src/runtime/domain/background-service/index.ts +25 -9
  45. package/src/runtime/domain/background-service/managed-authority.domain.mjs +6 -3
  46. package/src/runtime/domain/background-service/managed-authority.ts +5 -3
  47. package/src/runtime/domain/background-service/managed-client.domain.mjs +21 -7
  48. package/src/runtime/domain/background-service/managed-client.ts +20 -7
  49. package/src/runtime/domain/background-service/managed-frontend.domain.mjs +159 -19
  50. package/src/runtime/domain/background-service/managed-frontend.ts +135 -19
  51. package/src/runtime/domain/background-service/navigator-provider.domain.mjs +21 -5
  52. package/src/runtime/domain/background-service/navigator-provider.ts +19 -5
  53. package/src/runtime/domain/background-service/observed-wait-client.domain.mjs +6 -0
  54. package/src/runtime/domain/background-service/observed-wait-client.ts +10 -0
  55. package/src/runtime/domain/background-service/observed-waits.domain.mjs +372 -57
  56. package/src/runtime/domain/background-service/observed-waits.ts +321 -53
  57. package/src/runtime/domain/background-service/process-identity.domain.mjs +20 -2
  58. package/src/runtime/domain/background-service/process-identity.ts +18 -2
  59. package/src/runtime/domain/background-service/process.domain.mjs +52 -14
  60. package/src/runtime/domain/background-service/process.ts +48 -14
  61. package/src/runtime/domain/background-service/registry.domain.mjs +61 -3
  62. package/src/runtime/domain/background-service/registry.ts +53 -5
  63. package/src/runtime/domain/background-service/review-settings.domain.mjs +16 -0
  64. package/src/runtime/domain/background-service/review-settings.ts +18 -0
  65. package/src/runtime/domain/background-service/runtime.domain.mjs +40 -86
  66. package/src/runtime/domain/background-service/runtime.ts +27 -82
  67. package/src/runtime/domain/background-service/sandbox.domain.mjs +14 -15
  68. package/src/runtime/domain/background-service/sandbox.ts +14 -11
  69. package/src/runtime/domain/background-service/shared-callback-batcher.domain.mjs +8 -1
  70. package/src/runtime/domain/background-service/shared-callback-batcher.ts +11 -2
  71. package/src/runtime/domain/background-service/shared-navigator-panels.domain.mjs +24 -2
  72. package/src/runtime/domain/background-service/shared-navigator-panels.ts +26 -4
  73. package/src/runtime/domain/background-service/shared-navigator.domain.mjs +273 -41
  74. package/src/runtime/domain/background-service/shared-navigator.ts +244 -40
  75. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-inbox.mjs +144 -0
  76. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-observation.mjs +53 -41
  77. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
  78. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  79. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
  80. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  81. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
  82. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.ts +14 -3
  83. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
  84. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.ts +5 -3
  85. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.domain.mjs +44 -4
  86. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.ts +50 -2
  87. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  88. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.ts +9 -0
  89. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
  90. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.ts +12 -0
  91. package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.domain.mjs +2 -0
  92. package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.ts +2 -0
  93. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +42 -21
  94. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +40 -24
  95. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +26 -4
  96. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +40 -8
  97. package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
  98. package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.ts +24 -1
  99. package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.domain.mjs +1 -1
  100. package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.ts +5 -1
  101. package/src/runtime/domain/background-service/shared-sandbox-core.ts +1 -1
  102. package/src/runtime/domain/background-service/shared-work-client.mjs +174 -7
  103. package/src/runtime/domain/background-service/stall.domain.mjs +5 -3
  104. package/src/runtime/domain/background-service/stall.ts +7 -4
  105. package/src/runtime/domain/background-service/supervised-progress.domain.mjs +42 -0
  106. package/src/runtime/domain/background-service/supervised-progress.ts +43 -0
  107. package/src/runtime/domain/background-service/supervisor/README.md +1 -4
  108. package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +1 -0
  109. package/src/runtime/domain/background-service/supervisor/generated/process-identity.mjs +20 -2
  110. package/src/runtime/domain/background-service/supervisor/generated/process.mjs +52 -14
  111. package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +47 -4
  112. package/src/runtime/domain/background-service/supervisor/generated/store.mjs +3 -3
  113. package/src/runtime/domain/background-service/supervisor/generated/watch-fingerprint.mjs +69 -0
  114. package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +47 -4
  115. package/src/runtime/domain/background-service/supervisor/runner.ts +38 -3
  116. package/src/runtime/domain/background-service/supervisor/store.domain.mjs +3 -3
  117. package/src/runtime/domain/background-service/supervisor/store.ts +3 -3
  118. package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +9 -3
  119. package/src/runtime/domain/background-service/supervisor/supervisor.ts +6 -3
  120. package/src/runtime/domain/background-service/task-diagnostics.domain.mjs +1 -1
  121. package/src/runtime/domain/background-service/task-diagnostics.ts +1 -1
  122. package/src/runtime/domain/background-service/tools.domain.mjs +53 -40
  123. package/src/runtime/domain/background-service/tools.ts +67 -54
  124. package/src/runtime/domain/background-service/types.domain.mjs +1 -0
  125. package/src/runtime/domain/background-service/types.ts +7 -3
  126. package/src/runtime/domain/background-service/watch-fingerprint.domain.mjs +67 -0
  127. package/src/runtime/domain/background-service/watch-fingerprint.ts +70 -0
  128. package/src/runtime/domain/background-service/work-observation.domain.mjs +46 -20
  129. package/src/runtime/domain/background-service/work-observation.ts +46 -19
  130. package/src/runtime/domain/catalog/catalog-store.d.mts +9 -1
  131. package/src/runtime/domain/catalog/catalog-store.mjs +20 -22
  132. package/src/runtime/domain/coordinator/src/assignment-changes.mjs +75 -0
  133. package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +2 -0
  134. package/src/runtime/domain/coordinator/src/background-requests.mjs +11 -2
  135. package/src/runtime/domain/coordinator/src/discovery.mjs +4 -2
  136. package/src/runtime/domain/coordinator/src/operations.mjs +44 -4
  137. package/src/runtime/domain/coordinator/src/outbox.mjs +7 -0
  138. package/src/runtime/domain/coordinator/src/result-supervision.mjs +12 -0
  139. package/src/runtime/domain/coordinator/src/rows.mjs +2 -0
  140. package/src/runtime/domain/coordinator/src/schema.mjs +42 -21
  141. package/src/runtime/domain/coordinator/src/store.mjs +26 -4
  142. package/src/runtime/domain/coordinator/src/subagent-launch.mjs +23 -1
  143. package/src/runtime/domain/coordinator/src/types.mjs +1 -1
  144. package/src/runtime/domain/health-observation.d.mts +3 -1
  145. package/src/runtime/domain/health-observation.mjs +189 -190
  146. package/src/runtime/domain/log-cursor.d.mts +2 -0
  147. package/src/runtime/domain/log-cursor.mjs +85 -16
  148. package/src/runtime/domain/log-paths.mjs +8 -1
  149. package/src/runtime/domain/parse.d.mts +4 -1
  150. package/src/runtime/domain/parse.mjs +58 -9
  151. package/src/runtime/domain/sandbox-policy/README.md +63 -65
  152. package/src/runtime/domain/sandbox-policy/commands.domain.mjs +11 -8
  153. package/src/runtime/domain/sandbox-policy/commands.ts +12 -7
  154. package/src/runtime/domain/sandbox-policy/index.domain.mjs +53 -9
  155. package/src/runtime/domain/sandbox-policy/index.ts +52 -9
  156. package/src/runtime/domain/sandbox-policy/package.json +1 -1
  157. package/src/runtime/domain/sandbox-policy/permission-settings.domain.mjs +5 -2
  158. package/src/runtime/domain/sandbox-policy/permission-settings.ts +9 -2
  159. package/src/runtime/domain/sandbox-policy/permissions-page.domain.mjs +56 -137
  160. package/src/runtime/domain/sandbox-policy/permissions-page.ts +52 -130
  161. package/src/runtime/domain/sandbox-policy/permissions.domain.mjs +1 -6
  162. package/src/runtime/domain/sandbox-policy/permissions.ts +1 -6
  163. package/src/runtime/domain/sandbox-policy/shared-sandbox-core.ts +1 -1
  164. package/src/runtime/domain/sandbox-policy/shared-task-exec.domain.mjs +14 -1
  165. package/src/runtime/domain/sandbox-policy/shared-task-exec.ts +12 -1
  166. package/src/runtime/domain/sandbox-policy/shared-task-process-identity.domain.mjs +140 -0
  167. package/src/runtime/domain/sandbox-policy/shared-task-process-identity.ts +126 -0
  168. package/src/runtime/domain/sandbox-policy/shared-task-process-list.domain.mjs +3 -2
  169. package/src/runtime/domain/sandbox-policy/shared-task-process-list.ts +8 -2
  170. package/src/runtime/domain/sandbox-policy/shared-task-sandbox.domain.mjs +4 -3
  171. package/src/runtime/domain/sandbox-policy/shared-task-sandbox.ts +5 -3
  172. package/src/runtime/domain/sandbox-policy/shared-task-tools.domain.mjs +8 -5
  173. package/src/runtime/domain/sandbox-policy/shared-task-tools.ts +8 -5
  174. package/src/runtime/domain/session-store.mjs +7 -0
  175. package/src/runtime/domain/subagents/README.md +13 -11
  176. package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +10 -7
  177. package/src/runtime/domain/subagents/assignment-outcomes.ts +9 -6
  178. package/src/runtime/domain/subagents/assignment-report.domain.mjs +109 -24
  179. package/src/runtime/domain/subagents/assignment-report.ts +103 -19
  180. package/src/runtime/domain/subagents/batch.mjs +13 -5
  181. package/src/runtime/domain/subagents/catalog-host-admission.domain.mjs +21 -3
  182. package/src/runtime/domain/subagents/catalog-host-admission.ts +19 -3
  183. package/src/runtime/domain/subagents/catalog-preferences.ts +1 -1
  184. package/src/runtime/domain/subagents/catalog-resolver.domain.mjs +35 -1
  185. package/src/runtime/domain/subagents/catalog-resolver.ts +35 -1
  186. package/src/runtime/domain/subagents/catalog-store.domain.mjs +20 -22
  187. package/src/runtime/domain/subagents/catalog-store.ts +27 -20
  188. package/src/runtime/domain/subagents/child-apply-patch.domain.mjs +13 -0
  189. package/src/runtime/domain/subagents/child-apply-patch.ts +13 -0
  190. package/src/runtime/domain/subagents/child-dependencies.mjs +27 -15
  191. package/src/runtime/domain/subagents/child-operations.domain.mjs +80 -2
  192. package/src/runtime/domain/subagents/child-operations.ts +80 -1
  193. package/src/runtime/domain/subagents/child-preflight.mjs +9 -2
  194. package/src/runtime/domain/subagents/child-process-list.domain.mjs +7 -0
  195. package/src/runtime/domain/subagents/child-process-list.ts +8 -0
  196. package/src/runtime/domain/subagents/cleanup.domain.mjs +11 -2
  197. package/src/runtime/domain/subagents/cleanup.ts +10 -2
  198. package/src/runtime/domain/subagents/config.domain.mjs +54 -2
  199. package/src/runtime/domain/subagents/config.ts +53 -3
  200. package/src/runtime/domain/subagents/continuation-authority.domain.mjs +5 -1
  201. package/src/runtime/domain/subagents/continuation-authority.ts +3 -1
  202. package/src/runtime/domain/subagents/continuation-runtime.domain.mjs +89 -0
  203. package/src/runtime/domain/subagents/continuation-runtime.ts +88 -0
  204. package/src/runtime/domain/subagents/continuation.domain.mjs +4 -2
  205. package/src/runtime/domain/subagents/continuation.ts +4 -2
  206. package/src/runtime/domain/subagents/extensions.mjs +11 -13
  207. package/src/runtime/domain/subagents/failures.domain.mjs +11 -2
  208. package/src/runtime/domain/subagents/failures.ts +10 -2
  209. package/src/runtime/domain/subagents/finalization.domain.mjs +16 -1
  210. package/src/runtime/domain/subagents/finalization.ts +21 -1
  211. package/src/runtime/domain/subagents/goal-provider.domain.mjs +44 -2
  212. package/src/runtime/domain/subagents/goal-provider.ts +44 -2
  213. package/src/runtime/domain/subagents/health-observation.domain.mjs +189 -190
  214. package/src/runtime/domain/subagents/health-observation.ts +43 -48
  215. package/src/runtime/domain/subagents/index.domain.mjs +457 -182
  216. package/src/runtime/domain/subagents/index.ts +417 -155
  217. package/src/runtime/domain/subagents/isolated-workspace.domain.mjs +515 -0
  218. package/src/runtime/domain/subagents/isolated-workspace.ts +557 -0
  219. package/src/runtime/domain/subagents/launch-context.domain.mjs +24 -0
  220. package/src/runtime/domain/subagents/launch-context.ts +23 -0
  221. package/src/runtime/domain/subagents/launch-digest.mjs +6 -0
  222. package/src/runtime/domain/subagents/list.mjs +2 -2
  223. package/src/runtime/domain/subagents/log-cursor.domain.mjs +85 -16
  224. package/src/runtime/domain/subagents/log-cursor.ts +91 -15
  225. package/src/runtime/domain/subagents/managed-launch-bootstrap.mjs +2 -2
  226. package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +27 -7
  227. package/src/runtime/domain/subagents/managed-launch-client.ts +28 -8
  228. package/src/runtime/domain/subagents/managed-launch-host.domain.mjs +222 -14
  229. package/src/runtime/domain/subagents/managed-launch-host.ts +168 -15
  230. package/src/runtime/domain/subagents/managed-launch-journal.mjs +1 -5
  231. package/src/runtime/domain/subagents/managed-launch-port.ts +4 -0
  232. package/src/runtime/domain/subagents/operation-bridge-types.domain.mjs +27 -2
  233. package/src/runtime/domain/subagents/operation-bridge-types.ts +27 -2
  234. package/src/runtime/domain/subagents/output-payload.domain.mjs +24 -9
  235. package/src/runtime/domain/subagents/output-payload.ts +26 -12
  236. package/src/runtime/domain/subagents/owned-exit.domain.mjs +12 -0
  237. package/src/runtime/domain/subagents/owned-exit.ts +12 -0
  238. package/src/runtime/domain/subagents/package.json +4 -2
  239. package/src/runtime/domain/subagents/parse.domain.mjs +58 -9
  240. package/src/runtime/domain/subagents/parse.ts +57 -10
  241. package/src/runtime/domain/subagents/permission-policy.domain.mjs +32 -8
  242. package/src/runtime/domain/subagents/permission-policy.ts +41 -8
  243. package/src/runtime/domain/subagents/process-identity.mjs +33 -0
  244. package/src/runtime/domain/subagents/registry.domain.mjs +71 -51
  245. package/src/runtime/domain/subagents/registry.ts +77 -38
  246. package/src/runtime/domain/subagents/retained-result.domain.mjs +56 -0
  247. package/src/runtime/domain/subagents/retained-result.ts +65 -0
  248. package/src/runtime/domain/subagents/session-selection.domain.mjs +3 -1
  249. package/src/runtime/domain/subagents/session-selection.ts +2 -1
  250. package/src/runtime/domain/subagents/session-store.domain.mjs +7 -0
  251. package/src/runtime/domain/subagents/session-store.ts +9 -0
  252. package/src/runtime/domain/subagents/settings-page.domain.mjs +151 -107
  253. package/src/runtime/domain/subagents/settings-page.ts +147 -108
  254. package/src/runtime/domain/subagents/shared-callback-batcher.domain.mjs +8 -1
  255. package/src/runtime/domain/subagents/shared-callback-batcher.ts +11 -2
  256. package/src/runtime/domain/subagents/shared-catalog.domain.mjs +28 -29
  257. package/src/runtime/domain/subagents/shared-catalog.ts +29 -21
  258. package/src/runtime/domain/subagents/shared-navigator-panels.domain.mjs +24 -2
  259. package/src/runtime/domain/subagents/shared-navigator-panels.ts +26 -4
  260. package/src/runtime/domain/subagents/shared-navigator.domain.mjs +273 -41
  261. package/src/runtime/domain/subagents/shared-navigator.ts +244 -40
  262. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-inbox.mjs +144 -0
  263. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-observation.mjs +53 -41
  264. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
  265. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  266. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
  267. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  268. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
  269. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.ts +14 -3
  270. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
  271. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.ts +5 -3
  272. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.domain.mjs +44 -4
  273. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.ts +50 -2
  274. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  275. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.ts +9 -0
  276. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
  277. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.ts +12 -0
  278. package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.domain.mjs +2 -0
  279. package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.ts +2 -0
  280. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +42 -21
  281. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +40 -24
  282. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +26 -4
  283. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +40 -8
  284. package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
  285. package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.ts +24 -1
  286. package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.domain.mjs +1 -1
  287. package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.ts +5 -1
  288. package/src/runtime/domain/subagents/shared-sandbox-core.ts +1 -1
  289. package/src/runtime/domain/subagents/shared-task-exec.domain.mjs +14 -1
  290. package/src/runtime/domain/subagents/shared-task-exec.ts +12 -1
  291. package/src/runtime/domain/subagents/shared-task-process-identity.domain.mjs +140 -0
  292. package/src/runtime/domain/subagents/shared-task-process-identity.ts +126 -0
  293. package/src/runtime/domain/subagents/shared-task-process-list.domain.mjs +3 -2
  294. package/src/runtime/domain/subagents/shared-task-process-list.ts +8 -2
  295. package/src/runtime/domain/subagents/shared-task-sandbox.domain.mjs +4 -3
  296. package/src/runtime/domain/subagents/shared-task-sandbox.ts +5 -3
  297. package/src/runtime/domain/subagents/shared-task-tools.domain.mjs +8 -5
  298. package/src/runtime/domain/subagents/shared-task-tools.ts +8 -5
  299. package/src/runtime/domain/subagents/shared-work-client.mjs +174 -7
  300. package/src/runtime/domain/subagents/subagent-tools.domain.mjs +22 -38
  301. package/src/runtime/domain/subagents/subagent-tools.ts +28 -34
  302. package/src/runtime/domain/subagents/task-guard.domain.mjs +14 -1
  303. package/src/runtime/domain/subagents/task-guard.ts +13 -1
  304. package/src/runtime/domain/subagents/task-policy.domain.mjs +3 -2
  305. package/src/runtime/domain/subagents/task-policy.ts +8 -2
  306. package/src/runtime/domain/subagents/timing.domain.mjs +10 -1
  307. package/src/runtime/domain/subagents/timing.ts +10 -1
  308. package/src/runtime/domain/subagents/tools.domain.mjs +4 -8
  309. package/src/runtime/domain/subagents/tools.ts +4 -7
  310. package/src/runtime/domain/subagents/work-observation.domain.mjs +102 -17
  311. package/src/runtime/domain/subagents/work-observation.ts +91 -17
  312. package/src/runtime/domain/subagents/worker-operations-host.domain.mjs +9 -4
  313. package/src/runtime/domain/subagents/worker-operations-host.ts +12 -4
  314. package/src/runtime/domain/subagents/worker-waits.domain.mjs +89 -35
  315. package/src/runtime/domain/subagents/worker-waits.ts +93 -34
  316. package/src/runtime/domain/subagents/workspace-files.domain.mjs +103 -0
  317. package/src/runtime/domain/subagents/workspace-files.ts +114 -0
  318. package/src/runtime/domain/subagents/workspace-scope.domain.d.mts +38 -0
  319. package/src/runtime/domain/subagents/workspace-scope.domain.mjs +5 -0
  320. package/src/runtime/domain/subagents/workspace-scope.ts +6 -0
  321. package/src/runtime/domain/subagents/worktree-feedback.domain.mjs +55 -0
  322. package/src/runtime/domain/subagents/worktree-feedback.ts +77 -0
  323. package/src/runtime/health-config.ts +27 -11
  324. package/src/runtime/log-checkpoints.ts +117 -0
  325. package/src/runtime/mutation-store.ts +5 -4
  326. package/src/runtime/queries.ts +25 -2
  327. package/src/runtime/query-executor.ts +149 -28
  328. package/src/runtime/query-worker.mjs +106 -21
  329. package/src/runtime/read-model.ts +849 -121
  330. package/src/runtime/read-watchdog-probe.ts +4 -0
  331. package/src/runtime/result-supervision.ts +188 -16
  332. package/src/runtime/root.ts +5 -2
  333. package/src/runtime/source-watch.ts +175 -0
  334. package/src/runtime/subagent-launch.ts +11 -4
  335. package/src/runtime/work-budget.ts +130 -0
  336. package/src/runtime/work-client.d.mts +8 -0
  337. package/src/runtime/work-client.mjs +150 -7
  338. package/src/server.ts +104 -23
  339. package/src/session-activity.ts +26 -4
  340. package/src/version.ts +1 -1
@@ -1,4 +1,6 @@
1
1
  // Generated fixed launch domain from packages/pi-better-background-tasks/src/observed-waits.ts. Do not edit directly.
2
+ import { getObservedWaitHost, registerObservedWaitClient } from "./observed-wait-client.domain.mjs";
3
+ export { getObservedWaitHost, registerObservedWaitClient } from "./observed-wait-client.domain.mjs";
2
4
  /**
3
5
  * Parent-side observed waits: the integration between background tasks, the
4
6
  * detached local supervisor and the durable operation coordinator.
@@ -21,15 +23,19 @@
21
23
  * calling the existing `resolve*SandboxPlan` helpers.
22
24
  */
23
25
  import { createHash, randomUUID } from "node:crypto";
24
- import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
26
+ import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, watch } from "node:fs";
25
27
  import { homedir } from "node:os";
26
28
  import { dirname, isAbsolute, join, relative, resolve } from "node:path";
29
+ import { describeSupervisedProgress, supervisedProgress } from "./supervised-progress.domain.mjs";
30
+ import { formatProgressDuration } from "./stall.domain.mjs";
27
31
  import { validateCondition } from "./conditions.domain.mjs";
28
- import { STEP_GATE_COMMAND_ENV, commandExecution, parseStepGateFailure, processExists, stepGateScript, validateCommandSpec, } from "./process.domain.mjs";
32
+ import { STEP_GATE_COMMAND_ENV, commandExecution, parseStepGateFailure, processExists, resolveWindowsLaunchShell, stepGateScript, validateCommandSpec, } from "./process.domain.mjs";
29
33
  import { currentProcessStartToken, readProcessStartToken } from "./process-identity.domain.mjs";
30
34
  import { assertBackgroundExecutionAllowed, backgroundExecutionLimits, confineCommandSpec, resolveForegroundSandboxPlan, currentForegroundSandboxPolicy, resolveWorkerSandboxPlan, sandboxProvenance, } from "./sandbox.domain.mjs";
31
35
  import { openStore, cancellationCredential, } from "./shared-operation-coordinator/index.domain.mjs";
32
36
  import { createLocalSupervisor, defaultSupervisorDirectory, supervisorPaths, supervisorTaskIdForToken, } from "./supervisor/index.domain.mjs";
37
+ import { processGroupAlive } from "./supervisor/identity.domain.mjs";
38
+ import { readStopRequest, writeTextAtomic } from "./supervisor/store.domain.mjs";
33
39
  export const OBSERVED_WAITS_SERVICE_VERSION = 2;
34
40
  export const OBSERVED_WAITS_SERVICE_CHANNEL = "pi-better-background-tasks:observed-waits-service";
35
41
  export const OBSERVED_WAITS_SERVICE_REQUEST_CHANNEL = "pi-better-background-tasks:observed-waits-service-request";
@@ -165,19 +171,14 @@ export function observedWaitServiceUnavailableReason(pi) {
165
171
  const events = eventBusOf(pi);
166
172
  return events ? serviceErrors.get(events) : undefined;
167
173
  }
168
- const hosts = new WeakMap();
169
174
  export function createObservedWaitHost(pi, options = {}) {
170
- const existing = hosts.get(pi);
175
+ const existing = getObservedWaitHost(pi);
171
176
  if (existing && existing !== undefined)
172
177
  existing.close();
173
178
  const host = new ObservedWaitHost(pi, options);
174
- hosts.set(pi, host);
179
+ registerObservedWaitClient(pi, host);
175
180
  return host;
176
181
  }
177
- export function registerObservedWaitClient(pi, host) { hosts.set(pi, host); }
178
- export function getObservedWaitHost(pi) {
179
- return pi && typeof pi === "object" ? hosts.get(pi) : undefined;
180
- }
181
182
  function branchIdsOf(ctx) {
182
183
  try {
183
184
  const branch = ctx.sessionManager?.getBranch?.();
@@ -361,6 +362,51 @@ export class ObservedWaitHost {
361
362
  pollMs;
362
363
  options;
363
364
  timer;
365
+ changeWatcher;
366
+ changeRepair;
367
+ changePosition;
368
+ changeScheduled = false;
369
+ managedDirty = false;
370
+ managedAfter = 0;
371
+ observeManagedChanges() {
372
+ const schedule = () => {
373
+ if (this.closed || this.changeScheduled)
374
+ return;
375
+ this.changeScheduled = true;
376
+ setImmediate(() => {
377
+ this.changeScheduled = false;
378
+ if (this.closed || !this.store)
379
+ return;
380
+ try {
381
+ const page = this.store.resultSupervisionChanges(this.changePosition);
382
+ const changed = page.reset || page.seq !== this.changePosition?.seq;
383
+ this.changePosition = { generation: page.generation, seq: page.seq };
384
+ this.managedDirty ||= changed;
385
+ if (this.managedDirty && Date.now() >= this.managedAfter) {
386
+ this.managedDirty = false;
387
+ this.managedAfter = Date.now() + 1000;
388
+ void this.reconcileNow();
389
+ }
390
+ if (page.more)
391
+ schedule();
392
+ }
393
+ catch { /* Existing authority remains unchanged; the bounded feed repair retries. */ }
394
+ });
395
+ };
396
+ this.changeWatcher = watch(dirname(this.storePath), (_event, file) => {
397
+ if (!file || String(file).startsWith("operation-coordinator.sqlite"))
398
+ schedule();
399
+ });
400
+ this.changeWatcher.on("error", () => { this.changeWatcher?.close(); this.changeWatcher = undefined; });
401
+ const repair = () => {
402
+ if (this.closed)
403
+ return;
404
+ schedule();
405
+ this.changeRepair = setTimeout(repair, 1000);
406
+ this.changeRepair.unref();
407
+ };
408
+ repair();
409
+ }
364
410
  closed = false;
365
411
  activationAttempted = false;
366
412
  unavailableReason;
@@ -392,6 +438,7 @@ export class ObservedWaitHost {
392
438
  continuationError;
393
439
  launches = new Map();
394
440
  localCancels = new Set();
441
+ assignmentCleanupCursor;
395
442
  resultHandoffs = new Set();
396
443
  rpcRuns = new Map();
397
444
  waitOwners = new Map();
@@ -406,6 +453,7 @@ export class ObservedWaitHost {
406
453
  discoveryToken;
407
454
  discoveryRole;
408
455
  reconcileInFlight;
456
+ reconcileScope;
409
457
  authorityPassCache;
410
458
  /** Running operations this follower is currently assigned to supervise. */
411
459
  followerRunningTasks = new Set();
@@ -414,7 +462,8 @@ export class ObservedWaitHost {
414
462
  recoveryScopeState() {
415
463
  if (!this.activeOrigin)
416
464
  return this.unscopedCallbackRecovery;
417
- const key = JSON.stringify([this.activeOrigin?.cwd, this.activeOrigin?.sessionId]);
465
+ // Concurrent foregrounds can retain different branch snapshots of one session.
466
+ const key = JSON.stringify([this.activeOrigin.cwd, this.activeOrigin.sessionId, branchIdsOf(this.activeContext)]);
418
467
  let state = this.callbackRecoveryScopes.get(key);
419
468
  if (!state) {
420
469
  if (this.callbackRecoveryScopes.size >= 128)
@@ -491,6 +540,16 @@ export class ObservedWaitHost {
491
540
  }
492
541
  get usesServerResults() { return this.options.serverOwnedResults === true; }
493
542
  get hasActivated() { return this.activationAttempted; }
543
+ /** Ready worker continuations can advance; held decisions and unread results cannot. */
544
+ advancingWaits() {
545
+ if (!this.store || !this.continuation)
546
+ return [];
547
+ return this.store.listWaits({ phase: ["ready", "resuming"], pendingOnly: true })
548
+ .filter(wait => wait.owner.kind === "worker-conversation")
549
+ .map(wait => ({ kind: "advancing-wait", id: wait.waitId, generation: wait.generation, owner: wait.owner,
550
+ lastProgressAt: wait.updatedAt, nextDeadline: wait.updatedAt + (this.options.verificationMs ?? 30000), recovery: "captured-worker-continuation" }))
551
+ .filter(wait => wait.nextDeadline > Date.now());
552
+ }
494
553
  get reason() {
495
554
  return this.unavailableReason;
496
555
  }
@@ -534,7 +593,10 @@ export class ObservedWaitHost {
534
593
  void this.reconcileNow();
535
594
  this.recoverTerminalNotifications();
536
595
  this.terminalRecoveryNeeded = false;
537
- if (this.pollMs > 0) {
596
+ if (this.options.serverOwnedResults && this.options.sharedStore) {
597
+ this.observeManagedChanges();
598
+ }
599
+ else if (this.pollMs > 0) {
538
600
  this.timer = setInterval(() => { void this.reconcileNow(); }, this.pollMs);
539
601
  this.timer.unref?.();
540
602
  }
@@ -546,6 +608,12 @@ export class ObservedWaitHost {
546
608
  HOST_INSTANCE_STATE.closed.add(this.hostId);
547
609
  if (this.timer)
548
610
  clearInterval(this.timer);
611
+ this.changeWatcher?.close();
612
+ this.changeWatcher = undefined;
613
+ if (this.changeRepair)
614
+ clearTimeout(this.changeRepair);
615
+ this.changeRepair = undefined;
616
+ this.changePosition = undefined;
549
617
  this.timer = undefined;
550
618
  this.releaseDiscoveryAuthority();
551
619
  this.releaseSupervisionAuthority();
@@ -684,16 +752,31 @@ export class ObservedWaitHost {
684
752
  }
685
753
  /** A deterministic, awaitable reconciliation pass for tests and session activation. */
686
754
  async reconcileNow() {
687
- if (this.reconcileInFlight)
688
- return this.reconcileInFlight;
689
- const pass = this.reconcilePass();
755
+ const scope = this.recoveryScopeState();
756
+ if (this.reconcileInFlight) {
757
+ const sameScope = this.reconcileScope === scope;
758
+ await this.reconcileInFlight;
759
+ // Startup or another foreground's pass cannot verify this scope's recovery.
760
+ if (!sameScope)
761
+ return this.reconcileNow();
762
+ return;
763
+ }
764
+ const release = this.options.enterControl?.();
765
+ if (this.options.enterControl && !release) {
766
+ this.managedDirty = true;
767
+ return;
768
+ }
769
+ this.reconcileScope = scope;
770
+ const pass = this.reconcilePass().finally(() => release?.());
690
771
  this.reconcileInFlight = pass;
691
772
  try {
692
773
  await pass;
693
774
  }
694
775
  finally {
695
- if (this.reconcileInFlight === pass)
776
+ if (this.reconcileInFlight === pass) {
696
777
  this.reconcileInFlight = undefined;
778
+ this.reconcileScope = undefined;
779
+ }
697
780
  }
698
781
  }
699
782
  async reconcilePass() {
@@ -716,6 +799,8 @@ export class ObservedWaitHost {
716
799
  if (role === "holder") {
717
800
  this.discoverObservedTasks();
718
801
  this.reconcileGlobalRunning();
802
+ if (discovery.hasAssignmentTasks)
803
+ await this.reconcileAssignmentCleanup();
719
804
  }
720
805
  else {
721
806
  this.reconcileFollowerRunning();
@@ -728,6 +813,43 @@ export class ObservedWaitHost {
728
813
  this.authorityPassCache = undefined;
729
814
  }
730
815
  }
816
+ async reconcileAssignmentCleanup() {
817
+ const store = this.requireStore();
818
+ const [candidate] = store.listAssignmentCleanupOperations(1, this.assignmentCleanupCursor);
819
+ this.assignmentCleanupCursor = candidate?.operationId;
820
+ if (!candidate || candidate.resultManaged || this.supervisionAuthority(candidate) !== "self")
821
+ return;
822
+ const { taskId, launchToken } = candidate;
823
+ try {
824
+ const inspection = this.supervisor.snapshot(taskId);
825
+ const stop = readStopRequest(this.directory, taskId);
826
+ if (inspection?.token !== launchToken || (stop && stop.token !== launchToken))
827
+ return;
828
+ if (inspection.terminal) {
829
+ if (inspection.status !== "lost" && inspection.result?.groupCleanup !== "unproven")
830
+ return;
831
+ const pgid = inspection.command?.pgid ?? inspection.command?.pid;
832
+ if (inspection.cleanup?.groupEmpty === true || (pgid && !processGroupAlive(pgid))) {
833
+ store.verifyAssignmentCleanup(candidate.operationId, launchToken, candidate.terminalRevision);
834
+ return;
835
+ }
836
+ if (!pgid)
837
+ return;
838
+ }
839
+ if (!this.localCancels.has(taskId)) {
840
+ this.localCancels.add(taskId);
841
+ try {
842
+ await this.supervisor.stop(taskId, { token: launchToken, reason: "owning assignment ended" });
843
+ }
844
+ finally {
845
+ this.localCancels.delete(taskId);
846
+ }
847
+ }
848
+ }
849
+ catch (error) {
850
+ this.options.logger?.(`Assignment cleanup for ${taskId}: ${String(error)}`);
851
+ }
852
+ }
731
853
  reconcileGlobalRunning() {
732
854
  const store = this.store;
733
855
  if (!store)
@@ -886,7 +1008,7 @@ export class ObservedWaitHost {
886
1008
  const owner = this.ownerFor(input.ctx);
887
1009
  const prepared = this.prepareLaunch(input.kind, input.params, "bg_task_spawn", owner, undefined);
888
1010
  if (this.options.serverOwnedResults) {
889
- this.assertResultAdmission(prepared.provenance);
1011
+ this.assertManagedResultAdmission(prepared.provenance);
890
1012
  const client = await this.resultSupervisionClient();
891
1013
  client.close();
892
1014
  }
@@ -924,7 +1046,7 @@ export class ObservedWaitHost {
924
1046
  this.writeLaunchContext(taskId, launchContext);
925
1047
  this.launches.set(taskId, launchContext);
926
1048
  if (this.options.serverOwnedResults)
927
- await this.handoffResults([store.getOperation(operationId)]);
1049
+ await this.handoffResults([store.getOperation(operationId)], true);
928
1050
  const started = await this.startSupervisor({
929
1051
  token, taskId, kind: input.kind, params: input.params, prepared, operationId,
930
1052
  });
@@ -1188,6 +1310,124 @@ export class ObservedWaitHost {
1188
1310
  this.projectionMetrics.projectionsBuilt += 1;
1189
1311
  return this.projectDurable(operation, now);
1190
1312
  }
1313
+ /** Rebuild a live incident from the runner checkpoint. Only the native handoff writes its receipt. */
1314
+ pendingStallAlert(origin, taskId, waits) {
1315
+ const operation = this.operationForTask(taskId);
1316
+ if (!operation || operation.terminalRevision || !this.belongsToParentOrigin(operation, origin))
1317
+ return;
1318
+ const branchId = operation.owner.branchId;
1319
+ if (!this.isParentOriginActive(origin, branchId))
1320
+ return;
1321
+ const directory = this.observationDirectory(operation);
1322
+ if (!directory)
1323
+ return;
1324
+ const context = this.readLaunchContext(taskId, directory);
1325
+ if (!context?.callback)
1326
+ return;
1327
+ const inspection = this.passiveSnapshot(taskId, directory);
1328
+ if (!inspection || inspection.token !== operation.launchToken || inspection.stopRequestedAt !== undefined)
1329
+ return;
1330
+ const now = this.options.now?.() ?? Date.now();
1331
+ const progress = supervisedProgress(inspection, now);
1332
+ if (!progress?.alertDue)
1333
+ return;
1334
+ const receiptId = `background-stall:${operation.operationId}:${progress.observedAt}`;
1335
+ const receiptPath = join(inspection.taskDir, "stall-receipt");
1336
+ try {
1337
+ if (readFileSync(receiptPath, "utf8") === receiptId)
1338
+ return;
1339
+ }
1340
+ catch (error) {
1341
+ if (error.code !== "ENOENT")
1342
+ throw error;
1343
+ }
1344
+ const lines = [describeSupervisedProgress(progress, now),
1345
+ `Task has run for ${formatProgressDuration(now - inspection.launch.createdAt)}.`];
1346
+ for (const ref of waits) {
1347
+ const wait = this.requireStore().getWait(ref);
1348
+ if (!wait || wait.phase === "cancelled" || wait.phase === "consumed" || !sameOwner(wait.owner, operation.owner))
1349
+ continue;
1350
+ if (!wait.dependencies.some(dep => dep.operationId === operation.operationId))
1351
+ continue;
1352
+ const others = wait.dependencies.filter(dep => dep.operationId !== operation.operationId);
1353
+ const siblings = others.slice(0, 8).map(dep => {
1354
+ const sibling = this.requireStore().getOperation(dep.operationId);
1355
+ return `${sibling?.taskId ?? dep.operationId} ${sibling?.terminalOutcome ?? sibling?.phase ?? "unknown"}`;
1356
+ });
1357
+ if (others.length > siblings.length)
1358
+ siblings.push(`+${others.length - siblings.length} more`);
1359
+ lines.push(`Wait ${ref.waitId} ${wait.phase}${siblings.length ? ". Other tasks: " + siblings.join(", ") : ""}`);
1360
+ }
1361
+ const output = [inspection.logs.stdout, inspection.logs.stderr].map(path => lastLines(tail(path).text, 1).slice(-300)).filter(Boolean);
1362
+ lines.push(...output, `Evidence: bg_task_log id=${taskId}`);
1363
+ const notification = { taskId, operationId: operation.operationId, origin, branchId, urgent: true,
1364
+ event: { source: "background-task", id: receiptId, inspectId: taskId, label: context.name ?? taskId,
1365
+ status: "suspected stall", customType: "background-task-stall", content: lines.join("\n"), detailTool: "bg_task_status" } };
1366
+ return { notification, delivery: { receiptId, delivered: () => writeTextAtomic(receiptPath, receiptId), defer: () => { } } };
1367
+ }
1368
+ /** Review an ongoing parent wait using durable launch, progress and handoff evidence. */
1369
+ backgroundWaitReview(origin, taskId, waits, intervalMs) {
1370
+ const operation = this.operationForTask(taskId);
1371
+ if (!operation || operation.terminalRevision || !this.belongsToParentOrigin(operation, origin))
1372
+ return;
1373
+ const branchId = operation.owner.branchId;
1374
+ if (!this.isParentOriginActive(origin, branchId))
1375
+ return;
1376
+ const wait = waits.map(ref => this.requireStore().getWait(ref)).find(record => record?.phase === "waiting"
1377
+ && sameOwner(record.owner, operation.owner)
1378
+ && record.dependencies.some(dep => dep.operationId === operation.operationId));
1379
+ if (!wait)
1380
+ return;
1381
+ const directory = this.observationDirectory(operation);
1382
+ if (!directory)
1383
+ return;
1384
+ const context = this.readLaunchContext(taskId, directory);
1385
+ if (!context?.callback)
1386
+ return;
1387
+ const inspection = this.passiveSnapshot(taskId, directory);
1388
+ if (!inspection || inspection.token !== operation.launchToken || inspection.stopRequestedAt !== undefined)
1389
+ return;
1390
+ const clock = this.options.now ?? Date.now;
1391
+ const now = clock();
1392
+ const progress = supervisedProgress(inspection, now);
1393
+ if (!progress)
1394
+ return;
1395
+ const receiptPath = join(inspection.taskDir, "wait-review-receipt.json");
1396
+ const incident = [wait.waitId, wait.generation, progress.observedAt].join(":");
1397
+ const firstReviewAnchor = Math.max(wait.createdAt, progress.observedAt);
1398
+ let anchor = firstReviewAnchor;
1399
+ try {
1400
+ const receipt = JSON.parse(readFileSync(receiptPath, "utf8"));
1401
+ if (receipt?.incident === incident && Number.isFinite(receipt.deliveredAt)) {
1402
+ anchor = Math.max(anchor, receipt.deliveredAt);
1403
+ }
1404
+ }
1405
+ catch (error) {
1406
+ if (!(error instanceof SyntaxError) && error.code !== "ENOENT")
1407
+ throw error;
1408
+ }
1409
+ const dueAt = anchor + intervalMs;
1410
+ if (now < dueAt)
1411
+ return { dueAt };
1412
+ const receiptId = `background-wait-review:${operation.operationId}:${incident}:${anchor}`;
1413
+ const lines = [
1414
+ `Task has run for ${formatProgressDuration(now - inspection.launch.createdAt)}. No observed progress for ${formatProgressDuration(now - progress.observedAt)}.`,
1415
+ `Wait ${wait.waitId} is still waiting. Reassess the blocker and report the next step.`,
1416
+ `Continuation note: ${oneLine(wait.continuationNote, 250)}`,
1417
+ ];
1418
+ if (inspection.kind === "watch") {
1419
+ const lastCheck = lastLines(tail(inspection.logs.events).text, 12).split("\n").reverse().find(line => / check #\d+ exit=/.test(line));
1420
+ if (lastCheck)
1421
+ lines.push(`Latest check: ${oneLine(lastCheck, 200)}`);
1422
+ }
1423
+ const output = [inspection.logs.stdout, inspection.logs.stderr].map(path => lastLines(tail(path).text, 1).slice(-300)).filter(Boolean);
1424
+ lines.push(...output, `Evidence: bg_task_log id=${taskId}`);
1425
+ const notification = { taskId, operationId: operation.operationId, origin, branchId, urgent: true,
1426
+ event: { source: "background-task", id: receiptId, inspectId: taskId, label: context.name ?? taskId,
1427
+ status: "wait review due", customType: "background-wait-review", content: lines.join("\n"), detailTool: "bg_task_status" } };
1428
+ return { dueAt, alert: { notification, delivery: { receiptId,
1429
+ delivered: () => writeTextAtomic(receiptPath, JSON.stringify({ incident, deliveredAt: clock() })), defer: () => { } } } };
1430
+ }
1191
1431
  /** Accumulated projection work, for performance regression proof. */
1192
1432
  getDurableProjectionMetrics() {
1193
1433
  return { ...this.projectionMetrics };
@@ -1273,7 +1513,7 @@ export class ObservedWaitHost {
1273
1513
  if (owner.kind !== "parent-session" || this.activeOwnerRelation(owner) !== "match")
1274
1514
  return;
1275
1515
  this.invalidateDurableProjection(owner);
1276
- const change = { sessionId: owner.sessionId, workspace: owner.workspace };
1516
+ const change = { sessionId: owner.sessionId, workspace: owner.workspace, branchId: owner.branchId ?? null };
1277
1517
  for (const listener of [...this.durableChangeListeners]) {
1278
1518
  try {
1279
1519
  listener(change);
@@ -1295,18 +1535,30 @@ export class ObservedWaitHost {
1295
1535
  return operation.owner.sessionId === origin.sessionId;
1296
1536
  return true;
1297
1537
  }
1538
+ observationDirectory(operation) {
1539
+ if (!operation.supervision?.hostId?.startsWith("server:"))
1540
+ return this.directory;
1541
+ const grant = this.store?.resultSupervision(operation.operationId);
1542
+ if (!grant || grant.launchToken !== operation.launchToken || !sameOwner(grant.owner, operation.owner))
1543
+ return;
1544
+ return grant.directory;
1545
+ }
1546
+ passiveSnapshot(taskId, directory) {
1547
+ if (!directory || !LOCAL_DURABLE_ID.test(taskId))
1548
+ return;
1549
+ const supervisor = directory === this.directory ? this.supervisor : createLocalSupervisor({ directory });
1550
+ try {
1551
+ return supervisor.snapshot(taskId);
1552
+ }
1553
+ catch {
1554
+ return;
1555
+ }
1556
+ }
1298
1557
  projectDurable(operation, now) {
1299
- const context = this.launchContext(operation.taskId);
1300
- // Projection is the rendering path: a snapshot reads the durable records
1301
- // without taking the cross-process fence or spawning `ps`.
1302
- const inspection = LOCAL_DURABLE_ID.test(operation.taskId)
1303
- ? (() => { try {
1304
- return this.supervisor.snapshot(operation.taskId);
1305
- }
1306
- catch {
1307
- return undefined;
1308
- } })()
1309
- : undefined;
1558
+ const directory = this.observationDirectory(operation);
1559
+ const context = directory === this.directory ? this.launchContext(operation.taskId)
1560
+ : directory ? this.readLaunchContext(operation.taskId, directory) : undefined;
1561
+ const inspection = this.passiveSnapshot(operation.taskId, directory);
1310
1562
  const storeStatus = operation.terminalRevision > 0 ? this.statusOf(operation.operationId) : undefined;
1311
1563
  const status = inspection?.terminal ? inspection.status : storeStatus ?? inspection?.status ?? "running";
1312
1564
  const terminal = inspection?.terminal === true || operation.terminalRevision > 0;
@@ -1330,6 +1582,7 @@ export class ObservedWaitHost {
1330
1582
  status,
1331
1583
  active,
1332
1584
  terminal,
1585
+ progress: active ? supervisedProgress(inspection, now) : undefined,
1333
1586
  attention: terminal && status !== "succeeded",
1334
1587
  ...(context?.name ?? inspection?.launch.name ? { name: context?.name ?? inspection?.launch.name } : {}),
1335
1588
  cwd: inspection?.launch.cwd ?? context?.cwd ?? operation.owner.workspace,
@@ -1353,7 +1606,7 @@ export class ObservedWaitHost {
1353
1606
  logPaths: { stdout: pathSet.stdout, stderr: pathSet.stderr, events: pathSet.events },
1354
1607
  waits,
1355
1608
  ...(context?.sandbox ? { sandbox: context.sandbox } : {}),
1356
- owner: { sessionId: operation.owner.sessionId, workspace: operation.owner.workspace },
1609
+ owner: { sessionId: operation.owner.sessionId, workspace: operation.owner.workspace, branchId: operation.owner.branchId ?? null },
1357
1610
  };
1358
1611
  }
1359
1612
  status(taskId, owner) {
@@ -1361,7 +1614,8 @@ export class ObservedWaitHost {
1361
1614
  }
1362
1615
  statusForOperation(operation, owner) {
1363
1616
  const store = this.requireStore(), taskId = operation.taskId;
1364
- const inspection = this.inspect(taskId);
1617
+ const directory = this.observationDirectory(operation);
1618
+ const inspection = directory === this.directory ? this.inspect(taskId) : this.passiveSnapshot(taskId, directory);
1365
1619
  this.reconcileInspection(operation, inspection);
1366
1620
  const current = store.getOperation(operation.operationId) ?? operation;
1367
1621
  if (this.watchedRunningTasks.delete(taskId) && current.terminalRevision > 0) {
@@ -1373,14 +1627,14 @@ export class ObservedWaitHost {
1373
1627
  this.attemptTerminalCallback(current, this.statusOf(current.operationId), current.terminalOutcome ?? "failed", [], { pendingWithoutContext: true });
1374
1628
  }
1375
1629
  this.recordReadsForTask(owner, current);
1376
- const paths = supervisorPaths(this.directory, taskId);
1630
+ const paths = inspection?.logs ?? supervisorPaths(this.directory, taskId);
1377
1631
  const gateText = inspection ? `${tail(paths.stderr).text}` : "";
1378
1632
  const waits = store.listWaits({ pendingOnly: true })
1379
1633
  .filter((wait) => sameOwner(wait.owner, owner))
1380
1634
  .filter((wait) => wait.dependencies.some((dep) => dep.operationId === current.operationId))
1381
1635
  .map((wait) => this.waitView(wait));
1382
1636
  const result = inspection?.result;
1383
- const launched = this.launchContext(taskId);
1637
+ const launched = directory === this.directory ? this.launchContext(taskId) : directory ? this.readLaunchContext(taskId, directory) : undefined;
1384
1638
  const stepGate = result && launched?.gated ? parseStepGateFailure(gateText, taskId) : undefined;
1385
1639
  const kind = inspection?.kind ?? launched?.kind ?? "process";
1386
1640
  return {
@@ -1389,6 +1643,7 @@ export class ObservedWaitHost {
1389
1643
  kind: kind === "watch" ? "watch" : "process",
1390
1644
  status: inspection?.status ?? this.statusOf(current.operationId),
1391
1645
  phase: current.phase,
1646
+ progress: current.terminalRevision === 0 ? supervisedProgress(inspection, this.options.now?.() ?? Date.now()) : undefined,
1392
1647
  exitCode: result?.exitCode ?? null,
1393
1648
  signal: result?.signal ?? null,
1394
1649
  ...supervisionReasonFields(inspection),
@@ -1406,10 +1661,13 @@ export class ObservedWaitHost {
1406
1661
  log(taskId, owner, options = {}) {
1407
1662
  const store = this.requireStore();
1408
1663
  const operation = this.ownedOperation(taskId, owner);
1409
- const inspection = this.inspect(taskId);
1664
+ const directory = this.observationDirectory(operation);
1665
+ const inspection = directory === this.directory ? this.inspect(taskId) : this.passiveSnapshot(taskId, directory);
1410
1666
  this.reconcileInspection(operation, inspection);
1411
1667
  this.recordReadsForTask(owner, store.getOperation(operation.operationId) ?? operation);
1412
- const paths = supervisorPaths(this.directory, taskId);
1668
+ if (!directory)
1669
+ throw new Error("Captured Background log directory unavailable");
1670
+ const paths = inspection?.logs ?? supervisorPaths(directory, taskId);
1413
1671
  const lines = Math.max(1, Math.floor(options.lines ?? 40));
1414
1672
  const stdout = tail(paths.stdout);
1415
1673
  const stderr = tail(paths.stderr);
@@ -1449,6 +1707,9 @@ export class ObservedWaitHost {
1449
1707
  `${view.taskId} ${view.kind}: ${view.status} (${view.phase})`,
1450
1708
  `operation: ${view.operationId}; terminal revision: ${view.terminalRevision}${view.terminalOutcome ? ` (${view.terminalOutcome})` : ""}`,
1451
1709
  ];
1710
+ const progress = view.progress && describeSupervisedProgress(view.progress, this.options.now?.() ?? Date.now());
1711
+ if (progress)
1712
+ lines.push(progress);
1452
1713
  if (view.sandbox) {
1453
1714
  lines.push(`sandbox: ${view.sandbox.confinement}${view.sandbox.backend ? `; ${oneLine(view.sandbox.backend, 40)}` : ""}; source: ${oneLine(view.sandbox.policySource, 80)}; later changes do not affect this task.`);
1454
1715
  }
@@ -1564,6 +1825,11 @@ export class ObservedWaitHost {
1564
1825
  throw new Error("Terminal runner evidence is awaiting authoritative server import; supervision is unavailable.");
1565
1826
  return imported;
1566
1827
  }
1828
+ assertManagedResultAdmission(captured) {
1829
+ if (captured.policySource !== "no-publisher" && !currentForegroundSandboxPolicy(this.pi)) {
1830
+ throw new Error("permission-unavailable: expected current Background permission source is unavailable");
1831
+ }
1832
+ }
1567
1833
  assertResultAdmission(captured, transferring = new Set()) {
1568
1834
  const discovery = this.requireStore().readDiscoveryClaim(this.discoveryScope);
1569
1835
  if (discovery && discovery.hostId !== this.hostId && this.discoveryHolderState(discovery.hostId) !== "dead") {
@@ -1589,12 +1855,16 @@ export class ObservedWaitHost {
1589
1855
  }
1590
1856
  }
1591
1857
  }
1592
- async handoffResults(operations) {
1858
+ async handoffResults(operations, newManaged = false) {
1593
1859
  const client = await this.resultSupervisionClient();
1594
1860
  try {
1595
1861
  const manager = await client.request("runtime_result_supervision");
1862
+ // Already granted dependencies need no discovery scope transfer. Legacy
1863
+ // holders may keep supervising unrelated work beside server-owned tasks.
1864
+ if (operations.every(operation => this.requireStore().resultSupervision(operation.operationId)))
1865
+ return;
1596
1866
  const discovery = this.requireStore().readDiscoveryClaim(this.discoveryScope);
1597
- if (discovery && discovery.hostId !== this.hostId && this.discoveryHolderState(discovery.hostId) !== "dead") {
1867
+ if (!newManaged && discovery && discovery.hostId !== this.hostId && this.discoveryHolderState(discovery.hostId) !== "dead") {
1598
1868
  throw new Error("permission-unavailable: live or unknown original discovery holder prevents scope handoff");
1599
1869
  }
1600
1870
  const transfers = [];
@@ -1608,7 +1878,10 @@ export class ObservedWaitHost {
1608
1878
  const context = this.launchContext(operation.taskId);
1609
1879
  if (!context?.sandbox || !context.supervisionPolicy || !operation.authorityRef)
1610
1880
  throw new Error("permission-unavailable: captured Background authority is unavailable");
1611
- this.assertResultAdmission(context.sandbox, transferring);
1881
+ if (newManaged)
1882
+ this.assertManagedResultAdmission(context.sandbox);
1883
+ else
1884
+ this.assertResultAdmission(context.sandbox, transferring);
1612
1885
  const current = currentForegroundSandboxPolicy(this.pi);
1613
1886
  if (context.sandbox.policySource !== "no-publisher" && !current)
1614
1887
  throw new Error("permission-unavailable: expected current Background permission source is unavailable");
@@ -1620,10 +1893,16 @@ export class ObservedWaitHost {
1620
1893
  for (const transfer of transfers)
1621
1894
  this.resultHandoffs.add(transfer.operationId);
1622
1895
  try {
1623
- this.requireStore().handoffResultScope({ scope: this.discoveryScope,
1624
- expectedDiscovery: discovery ? { hostId: discovery.hostId, token: discovery.token } : null, grants: transfers });
1625
- this.discoveryToken = undefined;
1626
- this.discoveryRole = "follower";
1896
+ if (newManaged) {
1897
+ // New work grants only its own results; legacy discovery remains live.
1898
+ this.requireStore().handoffResultSupervisions(transfers);
1899
+ }
1900
+ else {
1901
+ this.requireStore().handoffResultScope({ scope: this.discoveryScope,
1902
+ expectedDiscovery: discovery ? { hostId: discovery.hostId, token: discovery.token } : null, grants: transfers });
1903
+ this.discoveryToken = undefined;
1904
+ this.discoveryRole = "follower";
1905
+ }
1627
1906
  }
1628
1907
  catch (error) {
1629
1908
  // The transaction rolled back; only these uncommitted local fences may reopen.
@@ -1679,7 +1958,7 @@ export class ObservedWaitHost {
1679
1958
  const assertWorkerPolicy = this.options.prepareWorkerPolicy?.(run);
1680
1959
  const prepared = this.prepareLaunch(input.kind, input.params, input.kind === "watch" ? "bg_task_watch" : "bg_task_spawn", owner, input.policy, run.workspace);
1681
1960
  if (this.options.serverOwnedResults)
1682
- this.assertResultAdmission(prepared.provenance);
1961
+ this.assertManagedResultAdmission(prepared.provenance);
1683
1962
  const operationId = `op_${randomUUID()}`;
1684
1963
  const token = `launch_${randomUUID()}`;
1685
1964
  const taskId = supervisorTaskIdForToken(token);
@@ -1692,8 +1971,10 @@ export class ObservedWaitHost {
1692
1971
  supervision: this.supervision(),
1693
1972
  authorityRef: authorityReference(`worker:${run.authorityReference}`),
1694
1973
  intentRef: typeof input.params.operation_id === "string" ? input.params.operation_id : null,
1974
+ ...(run.assignmentAttemptId ? { assignmentAttemptId: run.assignmentAttemptId } : {}),
1695
1975
  });
1696
1976
  const launchContext = {
1977
+ workerAttemptId: run.runId,
1697
1978
  kind: input.kind,
1698
1979
  parentOrigin: this.parentOrigin,
1699
1980
  gated: prepared.gated,
@@ -1709,7 +1990,7 @@ export class ObservedWaitHost {
1709
1990
  this.writeLaunchContext(taskId, launchContext);
1710
1991
  this.launches.set(taskId, launchContext);
1711
1992
  if (this.options.serverOwnedResults)
1712
- await this.handoffResults([store.getOperation(operationId)]);
1993
+ await this.handoffResults([store.getOperation(operationId)], true);
1713
1994
  const started = await this.startSupervisor({
1714
1995
  token, taskId, kind: input.kind, params: input.params, prepared, operationId, assertDispatch: assertWorkerPolicy,
1715
1996
  });
@@ -2058,6 +2339,7 @@ export class ObservedWaitHost {
2058
2339
  : {};
2059
2340
  this.rpcRuns.set(runId, Object.freeze({
2060
2341
  runId,
2342
+ assignmentTaskOwnership: params.assignmentTaskOwnership === true,
2061
2343
  conversationId,
2062
2344
  attemptId,
2063
2345
  workspace,
@@ -2411,6 +2693,7 @@ export class ObservedWaitHost {
2411
2693
  rpcScope(binding) {
2412
2694
  return {
2413
2695
  runId: binding.runId,
2696
+ ...(binding.assignmentTaskOwnership ? { assignmentAttemptId: binding.attemptId } : {}),
2414
2697
  conversationId: binding.conversationId,
2415
2698
  workspace: binding.workspace,
2416
2699
  authorityReference: binding.authorityReference,
@@ -2489,6 +2772,8 @@ export class ObservedWaitHost {
2489
2772
  ? resolveWorkerSandboxPlan(this.pi, workerPolicy, params, tool)
2490
2773
  : resolveForegroundSandboxPlan(this.pi, false, params, tool);
2491
2774
  assertBackgroundExecutionAllowed(spec, plan, { remote: false, cwd });
2775
+ if (spec.shell !== false)
2776
+ spec.resolvedWindowsShell = resolveWindowsLaunchShell(this.pi);
2492
2777
  const limits = backgroundExecutionLimits(plan);
2493
2778
  const gated = kind === "process" && params.require_successful_steps === true;
2494
2779
  if (gated) {
@@ -2622,10 +2907,18 @@ export class ObservedWaitHost {
2622
2907
  throw error;
2623
2908
  }
2624
2909
  }
2625
- const inspection = this.inspect(operation.taskId);
2910
+ let inspection;
2911
+ let unavailable = false;
2912
+ try {
2913
+ if (LOCAL_DURABLE_ID.test(operation.taskId))
2914
+ inspection = this.supervisor.inspect(operation.taskId, { recordLost: true });
2915
+ }
2916
+ catch {
2917
+ unavailable = true;
2918
+ }
2626
2919
  if (!inspection) {
2627
2920
  const now = this.options.now?.() ?? Date.now();
2628
- if (now - operation.createdAt >= 30_000) {
2921
+ if (!unavailable && now - operation.createdAt >= 30_000) {
2629
2922
  // The supervisor writes its launch record before spawning. No record
2630
2923
  // after the claim grace means no execution can be witnessed; this is
2631
2924
  // `lost`, never a success and never a silent retry.
@@ -2649,14 +2942,15 @@ export class ObservedWaitHost {
2649
2942
  void this.dispatchOutbox();
2650
2943
  return;
2651
2944
  }
2945
+ const reason = unavailable ? "durable supervisor records could not be read" : "no durable supervisor record exists for this operation";
2652
2946
  try {
2653
- if (claimed || operation.health !== "unmonitored" || operation.healthReason !== "no durable supervisor record exists for this operation") {
2947
+ if (claimed || operation.health !== "unmonitored" || operation.healthReason !== reason) {
2654
2948
  this.store?.recordSupervision({
2655
2949
  operationId: operation.operationId,
2656
2950
  owner: operation.owner,
2657
2951
  expectedHostId: this.hostId,
2658
2952
  health: "unmonitored",
2659
- reason: "no durable supervisor record exists for this operation",
2953
+ reason,
2660
2954
  });
2661
2955
  }
2662
2956
  }
@@ -2823,7 +3117,7 @@ export class ObservedWaitHost {
2823
3117
  return;
2824
3118
  }
2825
3119
  this.options.logger?.(`observed waits: ${operation.taskId} ${status} (revision ${recorded.operation.terminalRevision})`);
2826
- this.attemptTerminalCallback(operation, status, outcome, refs, { pendingWithoutContext: true });
3120
+ this.attemptTerminalCallback(recorded.operation, status, outcome, refs, { pendingWithoutContext: true });
2827
3121
  this.emitDurableTaskChange(operation.owner);
2828
3122
  // The parent callback is independent from the worker's wait: a worker may be
2829
3123
  // parked, while the parent session still learns that the supervised task ended.
@@ -2870,6 +3164,11 @@ export class ObservedWaitHost {
2870
3164
  skip("already delivered");
2871
3165
  return;
2872
3166
  }
3167
+ if (this.waitDeliveredTerminalRevision(operation, context)) {
3168
+ this.pendingTerminalCallbacks.delete(operation.taskId);
3169
+ this.store?.setParentCallbackPending(operation.taskId, false);
3170
+ return;
3171
+ }
2873
3172
  const waitPending = this.store?.listWaits({ owner: operation.owner, pendingOnly: true })
2874
3173
  .some((wait) => wait.dependencies.some((dep) => dep.operationId === operation.operationId)) ?? false;
2875
3174
  if (waitPending) {
@@ -3058,6 +3357,12 @@ export class ObservedWaitHost {
3058
3357
  return !!proof && proof.waitId === event.waitId && proof.generation === event.generation
3059
3358
  && proof.terminalRevision === event.terminalRevision;
3060
3359
  }
3360
+ waitDeliveredTerminalRevision(operation, context) {
3361
+ if (operation.terminalRevision === 0)
3362
+ return false;
3363
+ return Object.values(context.outboxDelivered ?? {}).some(proof => proof.terminalRevision === operation.terminalRevision)
3364
+ || (this.store?.hasDeliveredWaitDependency(operation.operationId, operation.terminalRevision, operation.owner) ?? false);
3365
+ }
3061
3366
  recordOutboxHandoffProof(taskId, event) {
3062
3367
  const context = this.currentLaunchContext(taskId);
3063
3368
  if (!context)
@@ -3219,6 +3524,7 @@ export class ObservedWaitHost {
3219
3524
  const outcome = await adapter.onWaitReady({
3220
3525
  waitId: event.waitId,
3221
3526
  generation: event.generation,
3527
+ ...(wait?.park?.attemptId ? { parkedAttemptId: wait.park.attemptId } : {}),
3222
3528
  owner,
3223
3529
  ...(taskId && this.launches.get(taskId)?.parentOrigin
3224
3530
  ? { parentOrigin: this.launches.get(taskId).parentOrigin }
@@ -3288,8 +3594,17 @@ export class ObservedWaitHost {
3288
3594
  catch { /* the store closed between handoff and receipt */ }
3289
3595
  // Key the recovered receipt to this exact event. Never use the
3290
3596
  // standalone task callback's receipt as proof for a wait.
3291
- if (!receipted && taskId)
3292
- this.recordOutboxHandoffProof(taskId, event);
3597
+ if (taskId) {
3598
+ this.pendingTerminalCallbacks.delete(taskId);
3599
+ if (!receipted)
3600
+ this.recordOutboxHandoffProof(taskId, event);
3601
+ else {
3602
+ try {
3603
+ store.setParentCallbackPending(taskId, false);
3604
+ }
3605
+ catch { /* the wait receipt survives for recovery */ }
3606
+ }
3607
+ }
3293
3608
  },
3294
3609
  defer: (reason) => {
3295
3610
  if (settled)
@@ -3709,15 +4024,15 @@ export class ObservedWaitHost {
3709
4024
  return undefined;
3710
4025
  }
3711
4026
  }
3712
- sidecarPath(taskId) {
3713
- return join(this.directory, "observed", `${taskId}.json`);
4027
+ sidecarPath(taskId, directory = this.directory) {
4028
+ return join(directory, "observed", `${taskId}.json`);
3714
4029
  }
3715
4030
  writeLaunchContext(taskId, context) {
3716
4031
  try {
3717
4032
  const operation = this.operationForTask(taskId);
3718
4033
  const parent = operation?.owner.kind === "parent-session";
3719
- const outboxDelivered = operation && Object.values(context.outboxDelivered ?? {}).some(proof => proof.terminalRevision === operation.terminalRevision);
3720
- const pending = context.callback !== false && context.callbackDeliveredAt === undefined && !outboxDelivered;
4034
+ const pending = context.callback !== false && context.callbackDeliveredAt === undefined
4035
+ && (!parent || !this.waitDeliveredTerminalRevision(operation, context));
3721
4036
  // Publish the obligation before the sidecar: a crash may leave a pending
3722
4037
  // candidate, but cannot hide an accepted callback. Retire only after the
3723
4038
  // delivered/disabled sidecar is durable, so replay can prove suppression.
@@ -3738,9 +4053,9 @@ export class ObservedWaitHost {
3738
4053
  }
3739
4054
  catch { /* retain an obligation if the exact sidecar cannot be persisted */ }
3740
4055
  }
3741
- readLaunchContext(taskId) {
4056
+ readLaunchContext(taskId, directory = this.directory) {
3742
4057
  try {
3743
- const value = JSON.parse(readFileSync(this.sidecarPath(taskId), "utf8"));
4058
+ const value = JSON.parse(readFileSync(this.sidecarPath(taskId, directory), "utf8"));
3744
4059
  if (value.kind !== "process" && value.kind !== "watch")
3745
4060
  return undefined;
3746
4061
  return {