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,3 +1,5 @@
1
+ import { getObservedWaitHost, registerObservedWaitClient } from "./observed-wait-client.js";
2
+ export { getObservedWaitHost, registerObservedWaitClient } from "./observed-wait-client.js";
1
3
  /**
2
4
  * Parent-side observed waits: the integration between background tasks, the
3
5
  * detached local supervisor and the durable operation coordinator.
@@ -21,18 +23,21 @@
21
23
  */
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, type FSWatcher } from "node:fs";
25
27
  import { homedir } from "node:os";
26
28
  import { dirname, isAbsolute, join, relative, resolve } from "node:path";
27
29
 
28
30
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
29
31
 
32
+ import { describeSupervisedProgress, supervisedProgress, type SupervisedProgress } from "./supervised-progress.js";
33
+ import { formatProgressDuration } from "./stall.js";
30
34
  import { validateCondition } from "./conditions.js";
31
35
  import {
32
36
  STEP_GATE_COMMAND_ENV,
33
37
  commandExecution,
34
38
  parseStepGateFailure,
35
39
  processExists,
40
+ resolveWindowsLaunchShell,
36
41
  stepGateScript,
37
42
  validateCommandSpec,
38
43
  } from "./process.js";
@@ -71,6 +76,8 @@ import {
71
76
  type SupervisorStartOptions,
72
77
  type SupervisorTaskStatus,
73
78
  } from "./supervisor/index.js";
79
+ import { processGroupAlive } from "./supervisor/identity.js";
80
+ import { readStopRequest, writeTextAtomic } from "./supervisor/store.js";
74
81
  import type { BackgroundTaskCallbackOrigin, CommandSpec, Condition, TaskSandboxProvenance } from "./types.js";
75
82
  import type { SpawnTaskParams, WatchTaskParams } from "./runtime.js";
76
83
 
@@ -148,6 +155,7 @@ export interface DurableProjectionMetrics {
148
155
  export interface DurableTaskChange {
149
156
  readonly sessionId: string;
150
157
  readonly workspace: string;
158
+ readonly branchId?: string | null;
151
159
  }
152
160
 
153
161
  /** A parent launch is always local; remote launches stay on the legacy task route. */
@@ -215,6 +223,7 @@ export interface WaitEvidenceView {
215
223
  export interface WaitDispatchEvent {
216
224
  readonly waitId: string;
217
225
  readonly generation: number;
226
+ readonly parkedAttemptId?: string;
218
227
  readonly owner: OwnerIdentity;
219
228
  /** Parent session origin captured when the supervised task launched. */
220
229
  readonly parentOrigin?: BackgroundTaskCallbackOrigin;
@@ -265,6 +274,7 @@ export type ParentNotifier = (notification: ParentNotification, delivery: Parent
265
274
 
266
275
  export interface WorkerRunScope {
267
276
  readonly runId: string;
277
+ readonly assignmentAttemptId?: string;
268
278
  readonly conversationId: string;
269
279
  readonly workspace: string;
270
280
  readonly authorityReference: string;
@@ -274,6 +284,7 @@ export interface WorkerRunScope {
274
284
 
275
285
  interface RpcRunBinding {
276
286
  readonly runId: string;
287
+ readonly assignmentTaskOwnership: boolean;
277
288
  readonly conversationId: string;
278
289
  readonly attemptId: string;
279
290
  readonly workspace: string;
@@ -392,6 +403,7 @@ export interface AcknowledgeView {
392
403
  }
393
404
 
394
405
  export interface StatusView {
406
+ readonly progress?: SupervisedProgress;
395
407
  readonly taskId: string;
396
408
  readonly operationId: string;
397
409
  readonly kind: DurableTaskKind;
@@ -414,6 +426,10 @@ export interface StatusView {
414
426
 
415
427
  /** Read-only projection of one supervised durable task for list/navigator/Goal. */
416
428
  export interface DurableTaskProjection {
429
+ readonly progress?: SupervisedProgress;
430
+ readonly parentAgentId?: string;
431
+ readonly parentRecipient?: { sessionId: string; workspace: string; branchId?: string | null };
432
+ readonly readOnly?: boolean;
417
433
  readonly id: string;
418
434
  readonly operationId: string;
419
435
  readonly kind: DurableTaskKind;
@@ -443,7 +459,7 @@ export interface DurableTaskProjection {
443
459
  readonly logPaths: { stdout: string; stderr: string; events: string };
444
460
  readonly waits: readonly WaitView[];
445
461
  readonly sandbox?: TaskSandboxProvenance;
446
- readonly owner: { sessionId: string; workspace: string };
462
+ readonly owner: { sessionId: string; workspace: string; branchId?: string | null };
447
463
  }
448
464
 
449
465
  export interface DurableTaskLogView {
@@ -566,6 +582,8 @@ export interface ObservedWaitHostOptions {
566
582
  beforeParentOperation?: (operation: { operationId: string; taskId: string; token: string }) => void;
567
583
  /** Runtime-owned coordinator handle. The caller retains its lifetime lease. */
568
584
  sharedStore?: Store;
585
+ enterControl?: () => (() => void) | undefined;
586
+ verificationMs?: number;
569
587
  /** Production adapters leave global discovery and terminal import to the server. */
570
588
  serverOwnedResults?: boolean;
571
589
  /** SQLite path. Defaults under the Pi agent directory. */
@@ -645,23 +663,16 @@ export function observedWaitServiceUnavailableReason(pi: unknown): string | unde
645
663
  return events ? serviceErrors.get(events) : undefined;
646
664
  }
647
665
 
648
- const hosts = new WeakMap<object, ObservedWaitHost>();
649
-
650
666
  export function createObservedWaitHost(pi: ExtensionAPI, options: ObservedWaitHostOptions = {}): ObservedWaitHost {
651
- const existing = hosts.get(pi as unknown as object);
667
+ const existing = getObservedWaitHost(pi);
652
668
  if (existing && existing !== undefined) existing.close();
653
669
  const host = new ObservedWaitHost(pi, options);
654
- hosts.set(pi as unknown as object, host);
670
+ registerObservedWaitClient(pi, host);
655
671
  return host;
656
672
  }
657
673
 
658
- export function registerObservedWaitClient(pi: ExtensionAPI, host: ObservedWaitHost): void { hosts.set(pi as object, host); }
659
-
660
- export function getObservedWaitHost(pi: unknown): ObservedWaitHost | undefined {
661
- return pi && typeof pi === "object" ? hosts.get(pi as object) : undefined;
662
- }
663
-
664
674
  interface LaunchContext {
675
+ readonly workerAttemptId?: string;
665
676
  readonly kind: DurableTaskKind;
666
677
  readonly parentOrigin?: BackgroundTaskCallbackOrigin;
667
678
  readonly gated: boolean;
@@ -875,6 +886,43 @@ export class ObservedWaitHost {
875
886
  private readonly pollMs: number;
876
887
  private readonly options: ObservedWaitHostOptions;
877
888
  private timer?: NodeJS.Timeout;
889
+ private changeWatcher?: FSWatcher;
890
+ private changeRepair?: NodeJS.Timeout;
891
+ private changePosition?: { generation: string; seq: number };
892
+ private changeScheduled = false;
893
+ private managedDirty = false;
894
+ private managedAfter = 0;
895
+ private observeManagedChanges() {
896
+ const schedule = () => {
897
+ if (this.closed || this.changeScheduled) return;
898
+ this.changeScheduled = true;
899
+ setImmediate(() => {
900
+ this.changeScheduled = false;
901
+ if (this.closed || !this.store) return;
902
+ try {
903
+ const page = this.store.resultSupervisionChanges(this.changePosition);
904
+ const changed = page.reset || page.seq !== this.changePosition?.seq;
905
+ this.changePosition = { generation: page.generation, seq: page.seq };
906
+ this.managedDirty ||= changed;
907
+ if (this.managedDirty && Date.now() >= this.managedAfter) {
908
+ this.managedDirty = false; this.managedAfter = Date.now() + 1000;
909
+ void this.reconcileNow();
910
+ }
911
+ if (page.more) schedule();
912
+ } catch { /* Existing authority remains unchanged; the bounded feed repair retries. */ }
913
+ });
914
+ };
915
+ this.changeWatcher = watch(dirname(this.storePath), (_event, file) => {
916
+ if (!file || String(file).startsWith("operation-coordinator.sqlite")) schedule();
917
+ });
918
+ this.changeWatcher.on("error", () => { this.changeWatcher?.close(); this.changeWatcher = undefined; });
919
+ const repair = () => {
920
+ if (this.closed) return;
921
+ schedule();
922
+ this.changeRepair = setTimeout(repair, 1000); this.changeRepair.unref();
923
+ };
924
+ repair();
925
+ }
878
926
  private closed = false;
879
927
  private activationAttempted = false;
880
928
  private unavailableReason?: string;
@@ -912,6 +960,7 @@ export class ObservedWaitHost {
912
960
  private continuationError?: string;
913
961
  private readonly launches = new Map<string, LaunchContext>();
914
962
  private readonly localCancels = new Set<string>();
963
+ private assignmentCleanupCursor?: string;
915
964
  private readonly resultHandoffs = new Set<string>();
916
965
  private readonly rpcRuns = new Map<string, RpcRunBinding>();
917
966
  private readonly waitOwners = new Map<string, OwnerIdentity>();
@@ -926,6 +975,7 @@ export class ObservedWaitHost {
926
975
  private discoveryToken?: string;
927
976
  private discoveryRole?: "holder" | "follower";
928
977
  private reconcileInFlight?: Promise<void>;
978
+ private reconcileScope?: object;
929
979
  private authorityPassCache?: Map<string, "live" | "dead" | "unknown">;
930
980
  /** Running operations this follower is currently assigned to supervise. */
931
981
  private readonly followerRunningTasks = new Set<string>();
@@ -933,7 +983,8 @@ export class ObservedWaitHost {
933
983
  private readonly callbackRecoveryScopes = new Map<string, { revision: number; delivery?: string; claims?: string; branch: string }>();
934
984
  private recoveryScopeState() {
935
985
  if (!this.activeOrigin) return this.unscopedCallbackRecovery;
936
- const key = JSON.stringify([this.activeOrigin?.cwd, this.activeOrigin?.sessionId]);
986
+ // Concurrent foregrounds can retain different branch snapshots of one session.
987
+ const key = JSON.stringify([this.activeOrigin.cwd, this.activeOrigin.sessionId, branchIdsOf(this.activeContext!)]);
937
988
  let state = this.callbackRecoveryScopes.get(key);
938
989
  if (!state) {
939
990
  if (this.callbackRecoveryScopes.size >= 128) this.callbackRecoveryScopes.delete(this.callbackRecoveryScopes.keys().next().value!);
@@ -1011,6 +1062,16 @@ export class ObservedWaitHost {
1011
1062
  get usesServerResults(): boolean { return this.options.serverOwnedResults === true; }
1012
1063
  get hasActivated(): boolean { return this.activationAttempted; }
1013
1064
 
1065
+ /** Ready worker continuations can advance; held decisions and unread results cannot. */
1066
+ advancingWaits() {
1067
+ if (!this.store || !this.continuation) return [];
1068
+ return this.store.listWaits({ phase: ["ready", "resuming"], pendingOnly: true })
1069
+ .filter(wait => wait.owner.kind === "worker-conversation")
1070
+ .map(wait => ({ kind: "advancing-wait", id: wait.waitId, generation: wait.generation, owner: wait.owner,
1071
+ lastProgressAt: wait.updatedAt, nextDeadline: wait.updatedAt + (this.options.verificationMs ?? 30000), recovery: "captured-worker-continuation" }))
1072
+ .filter(wait => wait.nextDeadline > Date.now());
1073
+ }
1074
+
1014
1075
  get reason(): string | undefined {
1015
1076
  return this.unavailableReason;
1016
1077
  }
@@ -1053,7 +1114,9 @@ export class ObservedWaitHost {
1053
1114
  void this.reconcileNow();
1054
1115
  this.recoverTerminalNotifications();
1055
1116
  this.terminalRecoveryNeeded = false;
1056
- if (this.pollMs > 0) {
1117
+ if (this.options.serverOwnedResults && this.options.sharedStore) {
1118
+ this.observeManagedChanges();
1119
+ } else if (this.pollMs > 0) {
1057
1120
  this.timer = setInterval(() => { void this.reconcileNow(); }, this.pollMs);
1058
1121
  this.timer.unref?.();
1059
1122
  }
@@ -1064,6 +1127,9 @@ export class ObservedWaitHost {
1064
1127
  this.closed = true;
1065
1128
  HOST_INSTANCE_STATE.closed.add(this.hostId);
1066
1129
  if (this.timer) clearInterval(this.timer);
1130
+ this.changeWatcher?.close(); this.changeWatcher = undefined;
1131
+ if (this.changeRepair) clearTimeout(this.changeRepair);
1132
+ this.changeRepair = undefined; this.changePosition = undefined;
1067
1133
  this.timer = undefined;
1068
1134
  this.releaseDiscoveryAuthority();
1069
1135
  this.releaseSupervisionAuthority();
@@ -1200,13 +1266,26 @@ export class ObservedWaitHost {
1200
1266
 
1201
1267
  /** A deterministic, awaitable reconciliation pass for tests and session activation. */
1202
1268
  async reconcileNow(): Promise<void> {
1203
- if (this.reconcileInFlight) return this.reconcileInFlight;
1204
- const pass = this.reconcilePass();
1269
+ const scope = this.recoveryScopeState();
1270
+ if (this.reconcileInFlight) {
1271
+ const sameScope = this.reconcileScope === scope;
1272
+ await this.reconcileInFlight;
1273
+ // Startup or another foreground's pass cannot verify this scope's recovery.
1274
+ if (!sameScope) return this.reconcileNow();
1275
+ return;
1276
+ }
1277
+ const release = this.options.enterControl?.();
1278
+ if (this.options.enterControl && !release) { this.managedDirty = true; return; }
1279
+ this.reconcileScope = scope;
1280
+ const pass = this.reconcilePass().finally(() => release?.());
1205
1281
  this.reconcileInFlight = pass;
1206
1282
  try {
1207
1283
  await pass;
1208
1284
  } finally {
1209
- if (this.reconcileInFlight === pass) this.reconcileInFlight = undefined;
1285
+ if (this.reconcileInFlight === pass) {
1286
+ this.reconcileInFlight = undefined;
1287
+ this.reconcileScope = undefined;
1288
+ }
1210
1289
  }
1211
1290
  }
1212
1291
 
@@ -1228,6 +1307,7 @@ export class ObservedWaitHost {
1228
1307
  if (role === "holder") {
1229
1308
  this.discoverObservedTasks();
1230
1309
  this.reconcileGlobalRunning();
1310
+ if (discovery!.hasAssignmentTasks) await this.reconcileAssignmentCleanup();
1231
1311
  } else {
1232
1312
  this.reconcileFollowerRunning();
1233
1313
  this.reconcileOwnerChanges();
@@ -1239,6 +1319,35 @@ export class ObservedWaitHost {
1239
1319
  }
1240
1320
  }
1241
1321
 
1322
+ private async reconcileAssignmentCleanup(): Promise<void> {
1323
+ const store = this.requireStore();
1324
+ const [candidate] = store.listAssignmentCleanupOperations(1, this.assignmentCleanupCursor);
1325
+ this.assignmentCleanupCursor = candidate?.operationId;
1326
+ if (!candidate || candidate.resultManaged || this.supervisionAuthority(candidate) !== "self") return;
1327
+ const { taskId, launchToken } = candidate;
1328
+ try {
1329
+ const inspection = this.supervisor.snapshot(taskId);
1330
+ const stop = readStopRequest(this.directory, taskId);
1331
+ if (inspection?.token !== launchToken || (stop && stop.token !== launchToken)) return;
1332
+ if (inspection.terminal) {
1333
+ if (inspection.status !== "lost" && inspection.result?.groupCleanup !== "unproven") return;
1334
+ const pgid = inspection.command?.pgid ?? inspection.command?.pid;
1335
+ if (inspection.cleanup?.groupEmpty === true || (pgid && !processGroupAlive(pgid))) {
1336
+ store.verifyAssignmentCleanup(candidate.operationId, launchToken, candidate.terminalRevision);
1337
+ return;
1338
+ }
1339
+ if (!pgid) return;
1340
+ }
1341
+ if (!this.localCancels.has(taskId)) {
1342
+ this.localCancels.add(taskId);
1343
+ try { await this.supervisor.stop(taskId, { token: launchToken, reason: "owning assignment ended" }); }
1344
+ finally { this.localCancels.delete(taskId); }
1345
+ }
1346
+ } catch (error) {
1347
+ this.options.logger?.(`Assignment cleanup for ${taskId}: ${String(error)}`);
1348
+ }
1349
+ }
1350
+
1242
1351
  private reconcileGlobalRunning(): void {
1243
1352
  const store = this.store;
1244
1353
  if (!store) return;
@@ -1403,7 +1512,7 @@ export class ObservedWaitHost {
1403
1512
  const owner = this.ownerFor(input.ctx);
1404
1513
  const prepared = this.prepareLaunch(input.kind, input.params, "bg_task_spawn", owner, undefined);
1405
1514
  if (this.options.serverOwnedResults) {
1406
- this.assertResultAdmission(prepared.provenance);
1515
+ this.assertManagedResultAdmission(prepared.provenance);
1407
1516
  const client = await this.resultSupervisionClient();
1408
1517
  client.close();
1409
1518
  }
@@ -1440,7 +1549,7 @@ export class ObservedWaitHost {
1440
1549
  // worker-owned operation to the parent's callback.
1441
1550
  this.writeLaunchContext(taskId, launchContext);
1442
1551
  this.launches.set(taskId, launchContext);
1443
- if (this.options.serverOwnedResults) await this.handoffResults([store.getOperation(operationId)!]);
1552
+ if (this.options.serverOwnedResults) await this.handoffResults([store.getOperation(operationId)!], true);
1444
1553
  const started = await this.startSupervisor({
1445
1554
  token, taskId, kind: input.kind, params: input.params, prepared, operationId,
1446
1555
  });
@@ -1687,6 +1796,102 @@ export class ObservedWaitHost {
1687
1796
  return this.projectDurable(operation, now);
1688
1797
  }
1689
1798
 
1799
+ /** Rebuild a live incident from the runner checkpoint. Only the native handoff writes its receipt. */
1800
+ pendingStallAlert(origin: BackgroundTaskCallbackOrigin, taskId: string, waits: readonly { waitId: string; generation: number }[]) {
1801
+ const operation = this.operationForTask(taskId);
1802
+ if (!operation || operation.terminalRevision || !this.belongsToParentOrigin(operation, origin)) return;
1803
+ const branchId = operation.owner.branchId;
1804
+ if (!this.isParentOriginActive(origin, branchId)) return;
1805
+ const directory = this.observationDirectory(operation);
1806
+ if (!directory) return;
1807
+ const context = this.readLaunchContext(taskId, directory);
1808
+ if (!context?.callback) return;
1809
+ const inspection = this.passiveSnapshot(taskId, directory);
1810
+ if (!inspection || inspection.token !== operation.launchToken || inspection.stopRequestedAt !== undefined) return;
1811
+ const now = this.options.now?.() ?? Date.now();
1812
+ const progress = supervisedProgress(inspection, now);
1813
+ if (!progress?.alertDue) return;
1814
+ const receiptId = `background-stall:${operation.operationId}:${progress.observedAt}`;
1815
+ const receiptPath = join(inspection.taskDir, "stall-receipt");
1816
+ try {
1817
+ if (readFileSync(receiptPath, "utf8") === receiptId) return;
1818
+ } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
1819
+ const lines = [describeSupervisedProgress(progress, now)!,
1820
+ `Task has run for ${formatProgressDuration(now - inspection.launch.createdAt)}.`];
1821
+ for (const ref of waits) {
1822
+ const wait = this.requireStore().getWait(ref);
1823
+ if (!wait || wait.phase === "cancelled" || wait.phase === "consumed" || !sameOwner(wait.owner, operation.owner)) continue;
1824
+ if (!wait.dependencies.some(dep => dep.operationId === operation.operationId)) continue;
1825
+ const others = wait.dependencies.filter(dep => dep.operationId !== operation.operationId);
1826
+ const siblings = others.slice(0, 8).map(dep => {
1827
+ const sibling = this.requireStore().getOperation(dep.operationId);
1828
+ return `${sibling?.taskId ?? dep.operationId} ${sibling?.terminalOutcome ?? sibling?.phase ?? "unknown"}`;
1829
+ });
1830
+ if (others.length > siblings.length) siblings.push(`+${others.length - siblings.length} more`);
1831
+ lines.push(`Wait ${ref.waitId} ${wait.phase}${siblings.length ? ". Other tasks: " + siblings.join(", ") : ""}`);
1832
+ }
1833
+ const output = [inspection.logs.stdout, inspection.logs.stderr].map(path => lastLines(tail(path).text, 1).slice(-300)).filter(Boolean);
1834
+ lines.push(...output, `Evidence: bg_task_log id=${taskId}`);
1835
+ const notification = { taskId, operationId: operation.operationId, origin, branchId, urgent: true,
1836
+ event: { source: "background-task", id: receiptId, inspectId: taskId, label: context.name ?? taskId,
1837
+ status: "suspected stall", customType: "background-task-stall", content: lines.join("\n"), detailTool: "bg_task_status" } };
1838
+ return { notification, delivery: { receiptId, delivered: () => writeTextAtomic(receiptPath, receiptId), defer: () => {} } };
1839
+ }
1840
+
1841
+ /** Review an ongoing parent wait using durable launch, progress and handoff evidence. */
1842
+ backgroundWaitReview(origin: BackgroundTaskCallbackOrigin, taskId: string, waits: readonly { waitId: string; generation: number }[], intervalMs: number) {
1843
+ const operation = this.operationForTask(taskId);
1844
+ if (!operation || operation.terminalRevision || !this.belongsToParentOrigin(operation, origin)) return;
1845
+ const branchId = operation.owner.branchId;
1846
+ if (!this.isParentOriginActive(origin, branchId)) return;
1847
+ const wait = waits.map(ref => this.requireStore().getWait(ref)).find(record => record?.phase === "waiting"
1848
+ && sameOwner(record.owner, operation.owner)
1849
+ && record.dependencies.some(dep => dep.operationId === operation.operationId));
1850
+ if (!wait) return;
1851
+ const directory = this.observationDirectory(operation);
1852
+ if (!directory) return;
1853
+ const context = this.readLaunchContext(taskId, directory);
1854
+ if (!context?.callback) return;
1855
+ const inspection = this.passiveSnapshot(taskId, directory);
1856
+ if (!inspection || inspection.token !== operation.launchToken || inspection.stopRequestedAt !== undefined) return;
1857
+ const clock = this.options.now ?? Date.now;
1858
+ const now = clock();
1859
+ const progress = supervisedProgress(inspection, now);
1860
+ if (!progress) return;
1861
+ const receiptPath = join(inspection.taskDir, "wait-review-receipt.json");
1862
+ const incident = [wait.waitId, wait.generation, progress.observedAt].join(":");
1863
+ const firstReviewAnchor = Math.max(wait.createdAt, progress.observedAt);
1864
+ let anchor = firstReviewAnchor;
1865
+ try {
1866
+ const receipt = JSON.parse(readFileSync(receiptPath, "utf8"));
1867
+ if (receipt?.incident === incident && Number.isFinite(receipt.deliveredAt)) {
1868
+ anchor = Math.max(anchor, receipt.deliveredAt);
1869
+ }
1870
+ } catch (error) {
1871
+ if (!(error instanceof SyntaxError) && (error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
1872
+ }
1873
+ const dueAt = anchor + intervalMs;
1874
+ if (now < dueAt) return { dueAt };
1875
+
1876
+ const receiptId = `background-wait-review:${operation.operationId}:${incident}:${anchor}`;
1877
+ const lines = [
1878
+ `Task has run for ${formatProgressDuration(now - inspection.launch.createdAt)}. No observed progress for ${formatProgressDuration(now - progress.observedAt)}.`,
1879
+ `Wait ${wait.waitId} is still waiting. Reassess the blocker and report the next step.`,
1880
+ `Continuation note: ${oneLine(wait.continuationNote, 250)}`,
1881
+ ];
1882
+ if (inspection.kind === "watch") {
1883
+ const lastCheck = lastLines(tail(inspection.logs.events).text, 12).split("\n").reverse().find(line => / check #\d+ exit=/.test(line));
1884
+ if (lastCheck) lines.push(`Latest check: ${oneLine(lastCheck, 200)}`);
1885
+ }
1886
+ const output = [inspection.logs.stdout, inspection.logs.stderr].map(path => lastLines(tail(path).text, 1).slice(-300)).filter(Boolean);
1887
+ lines.push(...output, `Evidence: bg_task_log id=${taskId}`);
1888
+ const notification = { taskId, operationId: operation.operationId, origin, branchId, urgent: true,
1889
+ event: { source: "background-task", id: receiptId, inspectId: taskId, label: context.name ?? taskId,
1890
+ status: "wait review due", customType: "background-wait-review", content: lines.join("\n"), detailTool: "bg_task_status" } };
1891
+ return { dueAt, alert: { notification, delivery: { receiptId,
1892
+ delivered: () => writeTextAtomic(receiptPath, JSON.stringify({ incident, deliveredAt: clock() })), defer: () => {} } } };
1893
+ }
1894
+
1690
1895
  /** Accumulated projection work, for performance regression proof. */
1691
1896
  getDurableProjectionMetrics(): DurableProjectionMetrics {
1692
1897
  return { ...this.projectionMetrics };
@@ -1781,7 +1986,7 @@ export class ObservedWaitHost {
1781
1986
  // request a repaint.
1782
1987
  if (owner.kind !== "parent-session" || this.activeOwnerRelation(owner) !== "match") return;
1783
1988
  this.invalidateDurableProjection(owner);
1784
- const change = { sessionId: owner.sessionId, workspace: owner.workspace };
1989
+ const change = { sessionId: owner.sessionId, workspace: owner.workspace, branchId: owner.branchId ?? null };
1785
1990
  for (const listener of [...this.durableChangeListeners]) {
1786
1991
  try { listener(change); } catch { /* a projection listener cannot break supervision */ }
1787
1992
  }
@@ -1799,13 +2004,24 @@ export class ObservedWaitHost {
1799
2004
  return true;
1800
2005
  }
1801
2006
 
2007
+ private observationDirectory(operation: OperationRecord): string | undefined {
2008
+ if (!operation.supervision?.hostId?.startsWith("server:")) return this.directory;
2009
+ const grant = this.store?.resultSupervision(operation.operationId);
2010
+ if (!grant || grant.launchToken !== operation.launchToken || !sameOwner(grant.owner, operation.owner)) return;
2011
+ return grant.directory;
2012
+ }
2013
+
2014
+ private passiveSnapshot(taskId: string, directory: string | undefined): SupervisorInspection | undefined {
2015
+ if (!directory || !LOCAL_DURABLE_ID.test(taskId)) return;
2016
+ const supervisor = directory === this.directory ? this.supervisor : createLocalSupervisor({ directory });
2017
+ try { return supervisor.snapshot(taskId); } catch { return; }
2018
+ }
2019
+
1802
2020
  private projectDurable(operation: OperationRecord, now: number): DurableTaskProjection | undefined {
1803
- const context = this.launchContext(operation.taskId);
1804
- // Projection is the rendering path: a snapshot reads the durable records
1805
- // without taking the cross-process fence or spawning `ps`.
1806
- const inspection = LOCAL_DURABLE_ID.test(operation.taskId)
1807
- ? (() => { try { return this.supervisor.snapshot(operation.taskId); } catch { return undefined; } })()
1808
- : undefined;
2021
+ const directory = this.observationDirectory(operation);
2022
+ const context = directory === this.directory ? this.launchContext(operation.taskId)
2023
+ : directory ? this.readLaunchContext(operation.taskId, directory) : undefined;
2024
+ const inspection = this.passiveSnapshot(operation.taskId, directory);
1809
2025
  const storeStatus = operation.terminalRevision > 0 ? this.statusOf(operation.operationId) : undefined;
1810
2026
  const status: SupervisorTaskStatus = inspection?.terminal ? inspection.status : storeStatus ?? inspection?.status ?? "running";
1811
2027
  const terminal = inspection?.terminal === true || operation.terminalRevision > 0;
@@ -1829,6 +2045,7 @@ export class ObservedWaitHost {
1829
2045
  status,
1830
2046
  active,
1831
2047
  terminal,
2048
+ progress: active ? supervisedProgress(inspection, now) : undefined,
1832
2049
  attention: terminal && status !== "succeeded",
1833
2050
  ...(context?.name ?? inspection?.launch.name ? { name: context?.name ?? inspection?.launch.name } : {}),
1834
2051
  cwd: inspection?.launch.cwd ?? context?.cwd ?? operation.owner.workspace,
@@ -1852,7 +2069,7 @@ export class ObservedWaitHost {
1852
2069
  logPaths: { stdout: pathSet.stdout, stderr: pathSet.stderr, events: pathSet.events },
1853
2070
  waits,
1854
2071
  ...(context?.sandbox ? { sandbox: context.sandbox } : {}),
1855
- owner: { sessionId: operation.owner.sessionId, workspace: operation.owner.workspace },
2072
+ owner: { sessionId: operation.owner.sessionId, workspace: operation.owner.workspace, branchId: operation.owner.branchId ?? null },
1856
2073
  };
1857
2074
  }
1858
2075
 
@@ -1862,7 +2079,8 @@ export class ObservedWaitHost {
1862
2079
 
1863
2080
  private statusForOperation(operation: OperationRecord, owner: OwnerIdentity): StatusView {
1864
2081
  const store = this.requireStore(), taskId = operation.taskId;
1865
- const inspection = this.inspect(taskId);
2082
+ const directory = this.observationDirectory(operation);
2083
+ const inspection = directory === this.directory ? this.inspect(taskId) : this.passiveSnapshot(taskId, directory);
1866
2084
  this.reconcileInspection(operation, inspection);
1867
2085
  const current = store.getOperation(operation.operationId) ?? operation;
1868
2086
  if (this.watchedRunningTasks.delete(taskId) && current.terminalRevision > 0) {
@@ -1886,14 +2104,14 @@ export class ObservedWaitHost {
1886
2104
  );
1887
2105
  }
1888
2106
  this.recordReadsForTask(owner, current);
1889
- const paths = supervisorPaths(this.directory, taskId);
2107
+ const paths = inspection?.logs ?? supervisorPaths(this.directory, taskId);
1890
2108
  const gateText = inspection ? `${tail(paths.stderr).text}` : "";
1891
2109
  const waits = store.listWaits({ pendingOnly: true })
1892
2110
  .filter((wait) => sameOwner(wait.owner, owner))
1893
2111
  .filter((wait) => wait.dependencies.some((dep) => dep.operationId === current.operationId))
1894
2112
  .map((wait) => this.waitView(wait));
1895
2113
  const result = inspection?.result;
1896
- const launched = this.launchContext(taskId);
2114
+ const launched = directory === this.directory ? this.launchContext(taskId) : directory ? this.readLaunchContext(taskId, directory) : undefined;
1897
2115
  const stepGate = result && launched?.gated ? parseStepGateFailure(gateText, taskId) : undefined;
1898
2116
  const kind = inspection?.kind ?? launched?.kind ?? "process";
1899
2117
  return {
@@ -1902,6 +2120,7 @@ export class ObservedWaitHost {
1902
2120
  kind: kind === "watch" ? "watch" : "process",
1903
2121
  status: inspection?.status ?? this.statusOf(current.operationId),
1904
2122
  phase: current.phase,
2123
+ progress: current.terminalRevision === 0 ? supervisedProgress(inspection, this.options.now?.() ?? Date.now()) : undefined,
1905
2124
  exitCode: result?.exitCode ?? null,
1906
2125
  signal: result?.signal ?? null,
1907
2126
  ...supervisionReasonFields(inspection),
@@ -1920,10 +2139,12 @@ export class ObservedWaitHost {
1920
2139
  private log(taskId: string, owner: OwnerIdentity, options: { lines?: number } = {}): LogView {
1921
2140
  const store = this.requireStore();
1922
2141
  const operation = this.ownedOperation(taskId, owner);
1923
- const inspection = this.inspect(taskId);
2142
+ const directory = this.observationDirectory(operation);
2143
+ const inspection = directory === this.directory ? this.inspect(taskId) : this.passiveSnapshot(taskId, directory);
1924
2144
  this.reconcileInspection(operation, inspection);
1925
2145
  this.recordReadsForTask(owner, store.getOperation(operation.operationId) ?? operation);
1926
- const paths = supervisorPaths(this.directory, taskId);
2146
+ if (!directory) throw new Error("Captured Background log directory unavailable");
2147
+ const paths = inspection?.logs ?? supervisorPaths(directory, taskId);
1927
2148
  const lines = Math.max(1, Math.floor(options.lines ?? 40));
1928
2149
  const stdout = tail(paths.stdout);
1929
2150
  const stderr = tail(paths.stderr);
@@ -1960,6 +2181,8 @@ export class ObservedWaitHost {
1960
2181
  `${view.taskId} ${view.kind}: ${view.status} (${view.phase})`,
1961
2182
  `operation: ${view.operationId}; terminal revision: ${view.terminalRevision}${view.terminalOutcome ? ` (${view.terminalOutcome})` : ""}`,
1962
2183
  ];
2184
+ const progress = view.progress && describeSupervisedProgress(view.progress, this.options.now?.() ?? Date.now());
2185
+ if (progress) lines.push(progress);
1963
2186
  if (view.sandbox) {
1964
2187
  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.`);
1965
2188
  }
@@ -2053,6 +2276,12 @@ export class ObservedWaitHost {
2053
2276
  return imported;
2054
2277
  }
2055
2278
 
2279
+ private assertManagedResultAdmission(captured: TaskSandboxProvenance): void {
2280
+ if (captured.policySource !== "no-publisher" && !currentForegroundSandboxPolicy(this.pi)) {
2281
+ throw new Error("permission-unavailable: expected current Background permission source is unavailable");
2282
+ }
2283
+ }
2284
+
2056
2285
  private assertResultAdmission(captured: TaskSandboxProvenance, transferring: ReadonlySet<string> = new Set()): void {
2057
2286
  const discovery = this.requireStore().readDiscoveryClaim(this.discoveryScope);
2058
2287
  if (discovery && discovery.hostId !== this.hostId && this.discoveryHolderState(discovery.hostId) !== "dead") {
@@ -2077,12 +2306,15 @@ export class ObservedWaitHost {
2077
2306
  }
2078
2307
  }
2079
2308
 
2080
- private async handoffResults(operations: readonly OperationRecord[]): Promise<void> {
2309
+ private async handoffResults(operations: readonly OperationRecord[], newManaged = false): Promise<void> {
2081
2310
  const client = await this.resultSupervisionClient();
2082
2311
  try {
2083
2312
  const manager = await client.request("runtime_result_supervision");
2313
+ // Already granted dependencies need no discovery scope transfer. Legacy
2314
+ // holders may keep supervising unrelated work beside server-owned tasks.
2315
+ if (operations.every(operation => this.requireStore().resultSupervision(operation.operationId))) return;
2084
2316
  const discovery = this.requireStore().readDiscoveryClaim(this.discoveryScope);
2085
- if (discovery && discovery.hostId !== this.hostId && this.discoveryHolderState(discovery.hostId) !== "dead") {
2317
+ if (!newManaged && discovery && discovery.hostId !== this.hostId && this.discoveryHolderState(discovery.hostId) !== "dead") {
2086
2318
  throw new Error("permission-unavailable: live or unknown original discovery holder prevents scope handoff");
2087
2319
  }
2088
2320
  const transfers = [];
@@ -2094,7 +2326,8 @@ export class ObservedWaitHost {
2094
2326
  }
2095
2327
  const context = this.launchContext(operation.taskId);
2096
2328
  if (!context?.sandbox || !context.supervisionPolicy || !operation.authorityRef) throw new Error("permission-unavailable: captured Background authority is unavailable");
2097
- this.assertResultAdmission(context.sandbox, transferring);
2329
+ if (newManaged) this.assertManagedResultAdmission(context.sandbox);
2330
+ else this.assertResultAdmission(context.sandbox, transferring);
2098
2331
  const current = currentForegroundSandboxPolicy(this.pi);
2099
2332
  if (context.sandbox.policySource !== "no-publisher" && !current) throw new Error("permission-unavailable: expected current Background permission source is unavailable");
2100
2333
  transfers.push({ operationId: operation.operationId,
@@ -2104,10 +2337,15 @@ export class ObservedWaitHost {
2104
2337
  // Validate the whole batch, then stop admission before the durable CAS.
2105
2338
  for (const transfer of transfers) this.resultHandoffs.add(transfer.operationId);
2106
2339
  try {
2107
- this.requireStore().handoffResultScope({ scope: this.discoveryScope,
2108
- expectedDiscovery: discovery ? { hostId: discovery.hostId, token: discovery.token } : null, grants: transfers });
2109
- this.discoveryToken = undefined;
2110
- this.discoveryRole = "follower";
2340
+ if (newManaged) {
2341
+ // New work grants only its own results; legacy discovery remains live.
2342
+ this.requireStore().handoffResultSupervisions(transfers);
2343
+ } else {
2344
+ this.requireStore().handoffResultScope({ scope: this.discoveryScope,
2345
+ expectedDiscovery: discovery ? { hostId: discovery.hostId, token: discovery.token } : null, grants: transfers });
2346
+ this.discoveryToken = undefined;
2347
+ this.discoveryRole = "follower";
2348
+ }
2111
2349
  } catch (error) {
2112
2350
  // The transaction rolled back; only these uncommitted local fences may reopen.
2113
2351
  for (const transfer of transfers) this.resultHandoffs.delete(transfer.operationId);
@@ -2177,7 +2415,7 @@ export class ObservedWaitHost {
2177
2415
  input.policy,
2178
2416
  run.workspace,
2179
2417
  );
2180
- if (this.options.serverOwnedResults) this.assertResultAdmission(prepared.provenance);
2418
+ if (this.options.serverOwnedResults) this.assertManagedResultAdmission(prepared.provenance);
2181
2419
  const operationId = `op_${randomUUID()}`;
2182
2420
  const token = `launch_${randomUUID()}`;
2183
2421
  const taskId = supervisorTaskIdForToken(token);
@@ -2190,8 +2428,10 @@ export class ObservedWaitHost {
2190
2428
  supervision: this.supervision(),
2191
2429
  authorityRef: authorityReference(`worker:${run.authorityReference}`),
2192
2430
  intentRef: typeof input.params.operation_id === "string" ? input.params.operation_id : null,
2431
+ ...(run.assignmentAttemptId ? { assignmentAttemptId: run.assignmentAttemptId } : {}),
2193
2432
  });
2194
2433
  const launchContext: LaunchContext = {
2434
+ workerAttemptId: run.runId,
2195
2435
  kind: input.kind,
2196
2436
  parentOrigin: this.parentOrigin,
2197
2437
  gated: prepared.gated,
@@ -2206,7 +2446,7 @@ export class ObservedWaitHost {
2206
2446
  };
2207
2447
  this.writeLaunchContext(taskId, launchContext);
2208
2448
  this.launches.set(taskId, launchContext);
2209
- if (this.options.serverOwnedResults) await this.handoffResults([store.getOperation(operationId)!]);
2449
+ if (this.options.serverOwnedResults) await this.handoffResults([store.getOperation(operationId)!], true);
2210
2450
  const started = await this.startSupervisor({
2211
2451
  token, taskId, kind: input.kind, params: input.params, prepared, operationId, assertDispatch: assertWorkerPolicy,
2212
2452
  });
@@ -2562,6 +2802,7 @@ export class ObservedWaitHost {
2562
2802
  : {};
2563
2803
  this.rpcRuns.set(runId, Object.freeze({
2564
2804
  runId,
2805
+ assignmentTaskOwnership: params.assignmentTaskOwnership === true,
2565
2806
  conversationId,
2566
2807
  attemptId,
2567
2808
  workspace,
@@ -2918,6 +3159,7 @@ export class ObservedWaitHost {
2918
3159
  private rpcScope(binding: RpcRunBinding): WorkerRunScope {
2919
3160
  return {
2920
3161
  runId: binding.runId,
3162
+ ...(binding.assignmentTaskOwnership ? { assignmentAttemptId: binding.attemptId } : {}),
2921
3163
  conversationId: binding.conversationId,
2922
3164
  workspace: binding.workspace,
2923
3165
  authorityReference: binding.authorityReference,
@@ -3010,6 +3252,7 @@ export class ObservedWaitHost {
3010
3252
  ? resolveWorkerSandboxPlan(this.pi, workerPolicy, params, tool)
3011
3253
  : resolveForegroundSandboxPlan(this.pi, false, params, tool);
3012
3254
  assertBackgroundExecutionAllowed(spec, plan, { remote: false, cwd });
3255
+ if (spec.shell !== false) spec.resolvedWindowsShell = resolveWindowsLaunchShell(this.pi);
3013
3256
  const limits = backgroundExecutionLimits(plan);
3014
3257
  const gated = kind === "process" && params.require_successful_steps === true;
3015
3258
  if (gated) {
@@ -3146,10 +3389,16 @@ export class ObservedWaitHost {
3146
3389
  throw error;
3147
3390
  }
3148
3391
  }
3149
- const inspection = this.inspect(operation.taskId);
3392
+ let inspection: SupervisorInspection | undefined;
3393
+ let unavailable = false;
3394
+ try {
3395
+ if (LOCAL_DURABLE_ID.test(operation.taskId)) inspection = this.supervisor.inspect(operation.taskId, { recordLost: true });
3396
+ } catch {
3397
+ unavailable = true;
3398
+ }
3150
3399
  if (!inspection) {
3151
3400
  const now = this.options.now?.() ?? Date.now();
3152
- if (now - operation.createdAt >= 30_000) {
3401
+ if (!unavailable && now - operation.createdAt >= 30_000) {
3153
3402
  // The supervisor writes its launch record before spawning. No record
3154
3403
  // after the claim grace means no execution can be witnessed; this is
3155
3404
  // `lost`, never a success and never a silent retry.
@@ -3172,14 +3421,15 @@ export class ObservedWaitHost {
3172
3421
  void this.dispatchOutbox();
3173
3422
  return;
3174
3423
  }
3424
+ const reason = unavailable ? "durable supervisor records could not be read" : "no durable supervisor record exists for this operation";
3175
3425
  try {
3176
- if (claimed || operation.health !== "unmonitored" || operation.healthReason !== "no durable supervisor record exists for this operation") {
3426
+ if (claimed || operation.health !== "unmonitored" || operation.healthReason !== reason) {
3177
3427
  this.store?.recordSupervision({
3178
3428
  operationId: operation.operationId,
3179
3429
  owner: operation.owner,
3180
3430
  expectedHostId: this.hostId,
3181
3431
  health: "unmonitored",
3182
- reason: "no durable supervisor record exists for this operation",
3432
+ reason,
3183
3433
  });
3184
3434
  }
3185
3435
  } catch { /* the owner may have been superseded; health is observational */ }
@@ -3336,7 +3586,7 @@ export class ObservedWaitHost {
3336
3586
  return;
3337
3587
  }
3338
3588
  this.options.logger?.(`observed waits: ${operation.taskId} ${status} (revision ${recorded.operation.terminalRevision})`);
3339
- this.attemptTerminalCallback(operation, status, outcome, refs, { pendingWithoutContext: true });
3589
+ this.attemptTerminalCallback(recorded.operation, status, outcome, refs, { pendingWithoutContext: true });
3340
3590
  this.emitDurableTaskChange(operation.owner);
3341
3591
  // The parent callback is independent from the worker's wait: a worker may be
3342
3592
  // parked, while the parent session still learns that the supervised task ended.
@@ -3381,6 +3631,11 @@ export class ObservedWaitHost {
3381
3631
  skip("already delivered");
3382
3632
  return;
3383
3633
  }
3634
+ if (this.waitDeliveredTerminalRevision(operation, context)) {
3635
+ this.pendingTerminalCallbacks.delete(operation.taskId);
3636
+ this.store?.setParentCallbackPending(operation.taskId, false);
3637
+ return;
3638
+ }
3384
3639
  const waitPending = this.store?.listWaits({ owner: operation.owner, pendingOnly: true })
3385
3640
  .some((wait) => wait.dependencies.some((dep) => dep.operationId === operation.operationId)) ?? false;
3386
3641
  if (waitPending) {
@@ -3556,6 +3811,12 @@ export class ObservedWaitHost {
3556
3811
  && proof.terminalRevision === event.terminalRevision;
3557
3812
  }
3558
3813
 
3814
+ private waitDeliveredTerminalRevision(operation: OperationRecord, context: LaunchContext): boolean {
3815
+ if (operation.terminalRevision === 0) return false;
3816
+ return Object.values(context.outboxDelivered ?? {}).some(proof => proof.terminalRevision === operation.terminalRevision)
3817
+ || (this.store?.hasDeliveredWaitDependency(operation.operationId, operation.terminalRevision, operation.owner) ?? false);
3818
+ }
3819
+
3559
3820
  private recordOutboxHandoffProof(taskId: string, event: OutboxEventRecord): void {
3560
3821
  const context = this.currentLaunchContext(taskId);
3561
3822
  if (!context) return;
@@ -3704,6 +3965,7 @@ export class ObservedWaitHost {
3704
3965
  const outcome = await adapter.onWaitReady({
3705
3966
  waitId: event.waitId,
3706
3967
  generation: event.generation,
3968
+ ...(wait?.park?.attemptId ? { parkedAttemptId: wait.park.attemptId } : {}),
3707
3969
  owner,
3708
3970
  ...(taskId && this.launches.get(taskId)?.parentOrigin
3709
3971
  ? { parentOrigin: this.launches.get(taskId)!.parentOrigin }
@@ -3766,7 +4028,13 @@ export class ObservedWaitHost {
3766
4028
  } catch { /* the store closed between handoff and receipt */ }
3767
4029
  // Key the recovered receipt to this exact event. Never use the
3768
4030
  // standalone task callback's receipt as proof for a wait.
3769
- if (!receipted && taskId) this.recordOutboxHandoffProof(taskId, event);
4031
+ if (taskId) {
4032
+ this.pendingTerminalCallbacks.delete(taskId);
4033
+ if (!receipted) this.recordOutboxHandoffProof(taskId, event);
4034
+ else {
4035
+ try { store.setParentCallbackPending(taskId, false); } catch { /* the wait receipt survives for recovery */ }
4036
+ }
4037
+ }
3770
4038
  },
3771
4039
  defer: (reason: string) => {
3772
4040
  if (settled) return;
@@ -4169,16 +4437,16 @@ export class ObservedWaitHost {
4169
4437
  }
4170
4438
  }
4171
4439
 
4172
- private sidecarPath(taskId: string): string {
4173
- return join(this.directory, "observed", `${taskId}.json`);
4440
+ private sidecarPath(taskId: string, directory = this.directory): string {
4441
+ return join(directory, "observed", `${taskId}.json`);
4174
4442
  }
4175
4443
 
4176
4444
  private writeLaunchContext(taskId: string, context: LaunchContext): void {
4177
4445
  try {
4178
4446
  const operation = this.operationForTask(taskId);
4179
4447
  const parent = operation?.owner.kind === "parent-session";
4180
- const outboxDelivered = operation && Object.values(context.outboxDelivered ?? {}).some(proof => proof.terminalRevision === operation.terminalRevision);
4181
- const pending = context.callback !== false && context.callbackDeliveredAt === undefined && !outboxDelivered;
4448
+ const pending = context.callback !== false && context.callbackDeliveredAt === undefined
4449
+ && (!parent || !this.waitDeliveredTerminalRevision(operation, context));
4182
4450
  // Publish the obligation before the sidecar: a crash may leave a pending
4183
4451
  // candidate, but cannot hide an accepted callback. Retire only after the
4184
4452
  // delivered/disabled sidecar is durable, so replay can prove suppression.
@@ -4192,9 +4460,9 @@ export class ObservedWaitHost {
4192
4460
  } catch { /* retain an obligation if the exact sidecar cannot be persisted */ }
4193
4461
  }
4194
4462
 
4195
- private readLaunchContext(taskId: string): LaunchContext | undefined {
4463
+ private readLaunchContext(taskId: string, directory = this.directory): LaunchContext | undefined {
4196
4464
  try {
4197
- const value = JSON.parse(readFileSync(this.sidecarPath(taskId), "utf8")) as Partial<LaunchContext>;
4465
+ const value = JSON.parse(readFileSync(this.sidecarPath(taskId, directory), "utf8")) as Partial<LaunchContext>;
4198
4466
  if (value.kind !== "process" && value.kind !== "watch") return undefined;
4199
4467
  return {
4200
4468
  kind: value.kind,