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
@@ -0,0 +1,43 @@
1
+ import { readFileSync, statSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { backgroundTaskStallThresholds, formatBackgroundTaskStall } from "./stall.js";
4
+ import { observeStall } from "./shared-stall-detector.js";
5
+
6
+ interface ProgressSource {
7
+ status: string;
8
+ kind: string;
9
+ claim?: { claimedAt: number };
10
+ logs: { stdout: string; stderr?: string };
11
+ }
12
+
13
+ export function supervisedProgress(source: ProgressSource | undefined, now = Date.now()) {
14
+ if (source?.status !== "running" || !source.claim) return;
15
+ let observedAt: number;
16
+ try {
17
+ observedAt = JSON.parse(readFileSync(join(dirname(source.logs.stdout), "progress.json"), "utf8")).observedAt;
18
+ if (!Number.isFinite(observedAt) || observedAt < source.claim.claimedAt) return;
19
+ } catch (error) {
20
+ // Older process runners still have separate append-only streams. Older watches
21
+ // appended every poll, so their logs cannot establish a meaningful progress time.
22
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT" || source.kind !== "process") return;
23
+ observedAt = source.claim.claimedAt;
24
+ for (const path of [source.logs.stdout, source.logs.stderr]) {
25
+ if (!path) continue;
26
+ try {
27
+ const stat = statSync(path, { throwIfNoEntry: false });
28
+ if (stat?.size) observedAt = Math.max(observedAt, Math.trunc(stat.mtimeMs));
29
+ } catch { return; }
30
+ }
31
+ }
32
+ const { state, thresholds } = observeStall({ now, lastProgressAt: observedAt, thresholds: backgroundTaskStallThresholds() });
33
+ const quietAt = observedAt + thresholds.quietMs;
34
+ const stalledAt = observedAt + thresholds.stallMs;
35
+ const alertAt = stalledAt + 60_000;
36
+ return { observedAt, state, alertDue: now >= alertAt, nextDeadline: [quietAt, stalledAt, alertAt].find(time => time > now) };
37
+ }
38
+
39
+ export type SupervisedProgress = NonNullable<ReturnType<typeof supervisedProgress>>;
40
+
41
+ export function describeSupervisedProgress(progress: SupervisedProgress, now = Date.now()) {
42
+ return formatBackgroundTaskStall({ ...progress, ageMs: now - progress.observedAt });
43
+ }
@@ -1,9 +1,6 @@
1
1
  # Detached local supervisor
2
2
 
3
- Slice 2 of [ADR 0020](../../../../docs/adr/0020-observed-waits-retain-an-owner.md) and the
4
- [observed-waits design](../../../../docs/plans/observed-waits-design.md): local process and command-watch
5
- supervision that survives the process that launched it. Nothing in this directory is wired into the
6
- Background Tasks tools yet; the parent owns that integration.
3
+ The detached supervisor runs local processes and command watches after the launching frontend exits. The coordinator retains the wait and its owner. [Observed waits](https://github.com/1aboveio/pi-better-harness/blob/main/docs/adr/0020-observed-waits-retain-an-owner.md) · [Supervisor design](https://github.com/1aboveio/pi-better-harness/blob/main/docs/plans/observed-waits-design.md)
7
4
 
8
5
  ## Contract
9
6
 
@@ -36,6 +36,7 @@ const CLOSURE = [
36
36
  { source: join(here, "store.ts"), out: "store.mjs" },
37
37
  { source: join(here, "types.ts"), out: "types.mjs" },
38
38
  { source: join(here, "identity.ts"), out: "identity.mjs" },
39
+ { source: join(here, "..", "watch-fingerprint.ts"), out: "watch-fingerprint.mjs" },
39
40
  { source: join(here, "..", "conditions.ts"), out: "conditions.mjs" },
40
41
  { source: join(here, "..", "process.ts"), out: "process.mjs" },
41
42
  { source: join(here, "..", "process-identity.ts"), out: "process-identity.mjs" },
@@ -1,6 +1,7 @@
1
1
  // Generated fixed launch domain from packages/pi-better-background-tasks/src/supervisor/generated/process-identity.mjs. Do not edit directly.
2
2
  // Generated by src/supervisor/emit-runner.mjs from the TypeScript source.
3
3
  // Do not edit: change the source and re-run the emitter (a drift test enforces this).
4
+ import { readFileSync } from "node:fs";
4
5
  import { execFileSync } from "node:child_process";
5
6
  /**
6
7
  * Process start-token reads.
@@ -23,11 +24,12 @@ const TOKEN_MEMO_TTL_MS = 1_000;
23
24
  /** Bound on memo entries; the panel is small, but a long session is not. */
24
25
  const TOKEN_MEMO_MAX_ENTRIES = 512;
25
26
  const tokenMemo = new Map();
26
- function readTokenUncached(pid) {
27
+ function readTokenUncached(pid, admission = false) {
27
28
  if (!Number.isInteger(pid) || pid <= 0 || process.platform === "win32")
28
29
  return undefined;
29
30
  try {
30
- const output = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], {
31
+ const output = execFileSync(admission ? "/bin/ps" : "ps", ["-o", "lstart=", "-p", String(pid)], {
32
+ env: admission ? { LC_ALL: "C", TZ: "UTC0", PATH: "/usr/bin:/bin" } : process.env,
31
33
  encoding: "utf8",
32
34
  stdio: ["ignore", "pipe", "ignore"],
33
35
  timeout: 2_000,
@@ -38,6 +40,22 @@ function readTokenUncached(pid) {
38
40
  return undefined;
39
41
  }
40
42
  }
43
+ // Admission crosses process environments; stored task tokens retain their original format.
44
+ export function readAdmissionStartToken(pid) {
45
+ if (process.platform !== "linux")
46
+ return readTokenUncached(pid, true);
47
+ if (!Number.isInteger(pid) || pid <= 0)
48
+ return undefined;
49
+ try {
50
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
51
+ // Fields after the parenthesized command start at field 3. Start time is field 22.
52
+ const start = stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
53
+ return start && /^\d+$/.test(start) ? start : undefined;
54
+ }
55
+ catch {
56
+ return undefined;
57
+ }
58
+ }
41
59
  function remember(pid, token, now) {
42
60
  if (tokenMemo.size >= TOKEN_MEMO_MAX_ENTRIES) {
43
61
  // Drop expired entries first; only evict live ones if that was not enough.
@@ -2,8 +2,9 @@
2
2
  // Generated by src/supervisor/emit-runner.mjs from the TypeScript source.
3
3
  // Do not edit: change the source and re-run the emitter (a drift test enforces this).
4
4
  import { spawn, spawnSync } from "node:child_process";
5
- import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, writeSync } from "node:fs";
6
- import { dirname, join } from "node:path";
5
+ import { accessSync, appendFileSync, closeSync, constants, existsSync, mkdirSync, openSync, readFileSync, writeSync } from "node:fs";
6
+ import { homedir } from "node:os";
7
+ import { dirname, join, win32 } from "node:path";
7
8
  /** Known Git for Windows locations; `bash -lc` needs a real bash, not the WSL shim. */
8
9
  const WINDOWS_BASH_CANDIDATES = [
9
10
  "C:\\Program Files\\Git\\bin\\bash.exe",
@@ -16,7 +17,8 @@ const WINDOWS_BASH_CANDIDATES = [
16
17
  * POSIX keeps `/bin/bash`. Windows has no `/bin/bash`, and the `bash.exe` found
17
18
  * on PATH is usually the WSL launcher in System32 or the WindowsApps alias,
18
19
  * either of which would run the command inside WSL instead of Windows. Prefer
19
- * an explicit override, then Git for Windows, then a non-WSL `bash.exe` on PATH.
20
+ * an explicit override, then Pi's shellPath, Git for Windows, and a non-WSL
21
+ * `bash.exe` on PATH.
20
22
  *
21
23
  * Resolved lazily at spawn time, not module load: env-injection extensions
22
24
  * (e.g. pi-env) may apply settings.json `env` values after this module is
@@ -24,27 +26,62 @@ const WINDOWS_BASH_CANDIDATES = [
24
26
  *
25
27
  * Exposed for tests and reuse.
26
28
  */
27
- export function resolveDefaultShell() {
29
+ export function resolveDefaultShell(shellPath) {
28
30
  const fromEnv = process.env.PI_BETTER_BACKGROUND_TASKS_SHELL;
29
31
  if (fromEnv)
30
32
  return fromEnv;
31
33
  if (process.platform !== "win32")
32
34
  return "/bin/bash";
33
- for (const candidate of WINDOWS_BASH_CANDIDATES) {
35
+ const configured = shellPath ?? readWindowsShellSetting();
36
+ const tried = [];
37
+ if (configured?.trim()) {
38
+ const candidate = /^~[\\/]/.test(configured) ? win32.join(homedir(), configured.slice(2)) : configured;
39
+ tried.push(candidate);
40
+ try {
41
+ accessSync(candidate, constants.F_OK);
42
+ return candidate;
43
+ }
44
+ catch { /* An unavailable setting leaves standard Windows discovery enabled. */ }
45
+ }
46
+ const gitCandidates = [process.env.ProgramFiles, process.env["ProgramFiles(x86)"]]
47
+ .filter((directory) => Boolean(directory))
48
+ .map(directory => win32.join(directory, "Git", "bin", "bash.exe"));
49
+ for (const candidate of new Set([...gitCandidates, ...WINDOWS_BASH_CANDIDATES])) {
50
+ tried.push(candidate);
34
51
  if (existsSync(candidate))
35
52
  return candidate;
36
53
  }
37
- for (const dir of (process.env.PATH ?? "").split(";")) {
54
+ for (const dir of (process.env.PATH ?? process.env.Path ?? "").split(";")) {
38
55
  const trimmed = dir.trim();
39
56
  if (!trimmed || /(^|[\\/])(system32|windowsapps)([\\/]|$)/i.test(trimmed))
40
57
  continue;
41
- const candidate = join(trimmed, "bash.exe");
58
+ const candidate = win32.join(trimmed, "bash.exe");
59
+ tried.push(candidate);
42
60
  if (existsSync(candidate))
43
61
  return candidate;
44
62
  }
45
- // Nothing usable found: keep the POSIX default so the failure surfaces as a
46
- // logged spawn error for the task instead of crashing the whole host process.
47
- return "/bin/bash";
63
+ throw new Error("No Bash executable found for Windows Background tasks. Set Pi's shellPath in settings.json or "
64
+ + "PI_BETTER_BACKGROUND_TASKS_SHELL to a working bash.exe. Searched:\n " + [...new Set(tried)].join("\n "));
65
+ }
66
+ function readWindowsShellSetting() {
67
+ const agentDir = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
68
+ try {
69
+ const settings = JSON.parse(readFileSync(join(agentDir, "settings.json"), "utf8"));
70
+ return typeof settings?.shellPath === "string" ? settings.shellPath : undefined;
71
+ }
72
+ catch {
73
+ return undefined;
74
+ }
75
+ }
76
+ /** Capture effective session settings before dispatching a Windows launch. */
77
+ export function resolveWindowsLaunchShell(pi) {
78
+ if (process.platform !== "win32")
79
+ return undefined;
80
+ const override = process.env.PI_BETTER_BACKGROUND_TASKS_SHELL;
81
+ if (override)
82
+ return override;
83
+ const settings = pi.getSettings?.();
84
+ return resolveDefaultShell(typeof settings?.shellPath === "string" ? settings.shellPath : undefined);
48
85
  }
49
86
  /** How long a timed-out process group has to exit on SIGTERM before SIGKILL. */
50
87
  const TERMINATION_GRACE_MS = 2_000;
@@ -62,8 +99,8 @@ export function validateCommandSpec(spec) {
62
99
  /** Convert a Windows path to the `/c/...` form MSYS bash resolves in redirections. Exposed for tests and reuse. */
63
100
  export function toMsysPath(path) {
64
101
  const forward = path.replace(/\\/g, "/");
65
- const drive = /^([A-Za-z]):(\/.+)$/.exec(forward);
66
- return drive ? `/${drive[1].toLowerCase()}${drive[2]}` : forward;
102
+ const [, drive, rest] = /^([A-Za-z]):(\/.+)$/.exec(forward) ?? [];
103
+ return drive && rest ? `/${drive.toLowerCase()}${rest}` : forward;
67
104
  }
68
105
  /** Single-quote a value for safe literal use in a bash script line. Exposed for tests and reuse. */
69
106
  export function bashSingleQuote(value) {
@@ -147,7 +184,7 @@ export function parseStepGateFailure(logText, id) {
147
184
  if (!line.startsWith(marker) || !line.endsWith(" ---"))
148
185
  continue;
149
186
  const match = /^--- step gate \[[^\]]+\]: first failing step exit=(-?\d+); shell exit=(-?\d+): (.*) ---$/.exec(line);
150
- if (!match)
187
+ if (!match || match[3] === undefined)
151
188
  continue;
152
189
  const stepExitCode = Number(match[1]);
153
190
  const shellExitCode = Number(match[2]);
@@ -497,7 +534,8 @@ export function commandExecution(spec) {
497
534
  const [command, ...args] = spec.argv;
498
535
  return { execPath: command, execArgs: args };
499
536
  }
500
- return { execPath: resolveDefaultShell(), execArgs: [spec.loginShell === false ? "-c" : "-lc", spec.command] };
537
+ const resolved = process.platform === "win32" ? spec.resolvedWindowsShell : undefined;
538
+ return { execPath: resolved ?? resolveDefaultShell(), execArgs: [spec.loginShell === false ? "-c" : "-lc", spec.command] };
501
539
  }
502
540
  function spawnArgs(spec, detached, stdio) {
503
541
  const env = { ...process.env, ...spec.env };
@@ -32,14 +32,15 @@
32
32
  */
33
33
  import { spawn } from "node:child_process";
34
34
  import { closeSync, openSync, realpathSync } from "node:fs";
35
- import { resolve } from "node:path";
35
+ import { join, resolve } from "node:path";
36
36
  import { setTimeout as delay } from "node:timers/promises";
37
37
  import { fileURLToPath } from "node:url";
38
+ import { watchOutcomeFingerprint } from "./watch-fingerprint.mjs";
38
39
  import { evaluateCondition, validateCondition } from "./conditions.mjs";
39
40
  import { completeUtf8Length, stopProcessGroup, utf8PrefixLength } from "./process.mjs";
40
41
  import { readProcessStartToken } from "./process-identity.mjs";
41
42
  import { processGroupAlive } from "./identity.mjs";
42
- import { appendEvent, appendStreamBytes, claimLaunch, ensureSupervisorTaskDir, readLaunchRecord, readStopRequest, writeCommandRecord, writeTerminalRecord, } from "./store.mjs";
43
+ import { appendEvent, appendStreamBytes, claimLaunch, ensureSupervisorTaskDir, readLaunchRecord, readStopRequest, writeCommandRecord, writeTerminalRecord, writeTextAtomic, } from "./store.mjs";
43
44
  import { DEFAULT_TERMINAL_TAIL_BYTES, DEFAULT_WATCH_INTERVAL_MS, SUPERVISOR_GROUP_CLEANUP_DEADLINE_MS, SUPERVISOR_POLL_MS, SUPERVISOR_RECORD_VERSION, SUPERVISOR_RUNNER_VERSION, SUPERVISOR_TERMINATION_GRACE_MS, } from "./types.mjs";
44
45
  /** How long the runner waits for `close` after the child reported `exit`. */
45
46
  const PIPE_CLOSE_GRACE_MS = 1_000;
@@ -117,6 +118,39 @@ function streamChunk(sink, chunk, maxBytes) {
117
118
  sink.tailBytes = keep.length;
118
119
  }
119
120
  }
121
+ /** Coalesce stream bursts while retaining the timestamp of the last byte, including discarded output. */
122
+ function progressRecorder(directory) {
123
+ const path = join(directory, "progress.json");
124
+ let pending;
125
+ let timer;
126
+ let lastWrite = 0;
127
+ const flush = () => {
128
+ timer = undefined;
129
+ if (!pending)
130
+ return;
131
+ try {
132
+ writeTextAtomic(path, JSON.stringify(pending));
133
+ }
134
+ catch (error) {
135
+ process.stderr.write(`Could not record Background progress: ${String(error)}\n`);
136
+ }
137
+ lastWrite = Date.now();
138
+ };
139
+ return (observedAt, fingerprint) => {
140
+ if (fingerprint !== undefined && pending?.fingerprint === fingerprint)
141
+ return;
142
+ pending = { observedAt, fingerprint };
143
+ if (timer)
144
+ return;
145
+ const remaining = lastWrite + 1000 - Date.now();
146
+ if (remaining <= 0)
147
+ flush();
148
+ else {
149
+ timer = setTimeout(flush, remaining);
150
+ timer.unref();
151
+ }
152
+ };
153
+ }
120
154
  function startToken(pid) {
121
155
  return pid === undefined ? undefined : readProcessStartToken(pid);
122
156
  }
@@ -389,15 +423,21 @@ function runChild(ctx, plan) {
389
423
  };
390
424
  child.stdout?.on("data", (chunk) => {
391
425
  const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
392
- if (plan.mode === "stream")
426
+ if (plan.mode === "stream") {
393
427
  streamChunk(ctx.stdout, buffer, plan.maxBytes);
428
+ if (buffer.length)
429
+ ctx.progress(Date.now());
430
+ }
394
431
  else
395
432
  captureChunk(stdoutCapture, buffer, plan.maxBytes);
396
433
  });
397
434
  child.stderr?.on("data", (chunk) => {
398
435
  const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
399
- if (plan.mode === "stream")
436
+ if (plan.mode === "stream") {
400
437
  streamChunk(ctx.stderr, buffer, plan.maxBytes);
438
+ if (buffer.length)
439
+ ctx.progress(Date.now());
440
+ }
401
441
  else
402
442
  captureChunk(stderrCapture, buffer, plan.maxBytes);
403
443
  });
@@ -596,6 +636,7 @@ async function runWatch(ctx) {
596
636
  if (ctx.finalized)
597
637
  return;
598
638
  ctx.checks += 1;
639
+ ctx.progress(outcome.endedAt, watchOutcomeFingerprint({ ...asCommandResult(outcome), ...(outcome.spawnError ? { error: outcome.spawnError } : {}) }));
599
640
  // Per-check output keeps the streams apart: stdout bytes in stdout.log, stderr in stderr.log.
600
641
  streamChunk(ctx.stdout, Buffer.from(outcome.stdout), ctx.launch.maxLogBytes);
601
642
  streamChunk(ctx.stderr, Buffer.from(outcome.stderr), ctx.launch.maxLogBytes);
@@ -823,9 +864,11 @@ function main() {
823
864
  checks: 0,
824
865
  stdout,
825
866
  stderr,
867
+ progress: progressRecorder(paths.dir),
826
868
  stopRequested: false,
827
869
  finalized: false,
828
870
  };
871
+ ctx.progress(ctx.startedAt);
829
872
  appendEvent(paths.events, `claimed runner_pid=${process.pid} runner_version=${SUPERVISOR_RUNNER_VERSION} kind=${launch.kind} cwd=${launch.command.cwd}`);
830
873
  const onSignal = (signal) => {
831
874
  appendEvent(paths.events, `runner received ${signal}`);
@@ -330,13 +330,13 @@ function readText(path) {
330
330
  catch (error) {
331
331
  if (error.code === "ENOENT")
332
332
  return { missing: true };
333
- return { missing: true, error: error instanceof Error ? error.message : String(error) };
333
+ return { missing: false, error: error instanceof Error ? error.message : String(error) };
334
334
  }
335
335
  }
336
336
  function readJsonRecord(path, problem) {
337
337
  const read = readText(path);
338
- if (read.missing)
339
- return { missing: true, error: read.error };
338
+ if (read.value === undefined)
339
+ return { missing: read.missing, error: read.error };
340
340
  let parsed;
341
341
  try {
342
342
  parsed = JSON.parse(read.value);
@@ -0,0 +1,69 @@
1
+ // Generated fixed launch domain from packages/pi-better-background-tasks/src/supervisor/generated/watch-fingerprint.mjs. Do not edit directly.
2
+ // Generated by src/supervisor/emit-runner.mjs from the TypeScript source.
3
+ // Do not edit: change the source and re-run the emitter (a drift test enforces this).
4
+ import { createHash } from "node:crypto";
5
+ /** Version tag of the watch outcome fingerprint. A value from another version is adopted, never compared. */
6
+ export const WATCH_FINGERPRINT_VERSION = "v1";
7
+ /** OSC and CSI control sequences are display markup, not content. */
8
+ const TERMINAL_ESCAPE = /\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)|\u001b\[[0-?]*[ -/]*[@-~]/g;
9
+ /**
10
+ * Text as the terminal would settle it. Redraw frames and control sequences are
11
+ * display churn: repainting the same visible line is not a new observation.
12
+ */
13
+ function settledTerminalText(text) {
14
+ return text
15
+ .replace(TERMINAL_ESCAPE, "")
16
+ .split("\n")
17
+ .map((line) => {
18
+ // A CR immediately before LF ends the line; any other CR overwrites it in place.
19
+ const body = line.endsWith("\r") ? line.slice(0, -1) : line;
20
+ return (body.split("\r").at(-1) ?? "").replace(/[ \t]+$/, "");
21
+ })
22
+ .join("\n")
23
+ .replace(/\n+$/, "");
24
+ }
25
+ /** Objects compare by content regardless of key order, so reordered keys are not progress. */
26
+ function canonicalJsonText(value) {
27
+ if (Array.isArray(value))
28
+ return `[${value.map(canonicalJsonText).join(",")}]`;
29
+ if (value && typeof value === "object") {
30
+ const record = value;
31
+ const entries = Object.keys(record).sort()
32
+ .map((key) => `${JSON.stringify(key)}:${canonicalJsonText(record[key])}`);
33
+ return `{${entries.join(",")}}`;
34
+ }
35
+ return JSON.stringify(value) ?? "null";
36
+ }
37
+ /** stdout compares as JSON content when it parses, and as settled text otherwise. */
38
+ function canonicalWatchStdout(stdout) {
39
+ const settled = settledTerminalText(stdout);
40
+ try {
41
+ return `json:${canonicalJsonText(JSON.parse(settled))}`;
42
+ }
43
+ catch {
44
+ return `text:${settled}`;
45
+ }
46
+ }
47
+ /**
48
+ * What a poll observed, independent of when it ran. Exit status, signal, error,
49
+ * stdout content, and stderr content are included; poll metadata (start time,
50
+ * end time, duration, check count) is deliberately not, so it can never hide a
51
+ * watch that reports the same outcome forever. Watch stdout may carry its own
52
+ * timestamps: projecting meaningful fields is the caller's job, not this
53
+ * fingerprint's guess.
54
+ */
55
+ export function watchOutcomeFingerprint(result) {
56
+ // A runner may report why the check itself could not run; that is part of the
57
+ // observed outcome, not poll metadata.
58
+ const reported = result.error;
59
+ const error = typeof reported === "string" ? settledTerminalText(reported) : null;
60
+ const payload = JSON.stringify([
61
+ result.exitCode,
62
+ result.signal ?? null,
63
+ result.timedOut === true,
64
+ error,
65
+ canonicalWatchStdout(result.stdout),
66
+ settledTerminalText(result.stderr),
67
+ ]);
68
+ return `${WATCH_FINGERPRINT_VERSION}:${createHash("sha256").update(payload).digest("hex")}`;
69
+ }
@@ -30,14 +30,15 @@
30
30
  */
31
31
  import { spawn } from "node:child_process";
32
32
  import { closeSync, openSync, realpathSync } from "node:fs";
33
- import { resolve } from "node:path";
33
+ import { join, resolve } from "node:path";
34
34
  import { setTimeout as delay } from "node:timers/promises";
35
35
  import { fileURLToPath } from "node:url";
36
+ import { watchOutcomeFingerprint } from "../watch-fingerprint.domain.mjs";
36
37
  import { evaluateCondition, validateCondition } from "../conditions.domain.mjs";
37
38
  import { completeUtf8Length, stopProcessGroup, utf8PrefixLength } from "../process.domain.mjs";
38
39
  import { readProcessStartToken } from "../process-identity.domain.mjs";
39
40
  import { processGroupAlive } from "./identity.domain.mjs";
40
- import { appendEvent, appendStreamBytes, claimLaunch, ensureSupervisorTaskDir, readLaunchRecord, readStopRequest, writeCommandRecord, writeTerminalRecord, } from "./store.domain.mjs";
41
+ import { appendEvent, appendStreamBytes, claimLaunch, ensureSupervisorTaskDir, readLaunchRecord, readStopRequest, writeCommandRecord, writeTerminalRecord, writeTextAtomic, } from "./store.domain.mjs";
41
42
  import { DEFAULT_TERMINAL_TAIL_BYTES, DEFAULT_WATCH_INTERVAL_MS, SUPERVISOR_GROUP_CLEANUP_DEADLINE_MS, SUPERVISOR_POLL_MS, SUPERVISOR_RECORD_VERSION, SUPERVISOR_RUNNER_VERSION, SUPERVISOR_TERMINATION_GRACE_MS, } from "./types.domain.mjs";
42
43
  /** How long the runner waits for `close` after the child reported `exit`. */
43
44
  const PIPE_CLOSE_GRACE_MS = 1_000;
@@ -115,6 +116,39 @@ function streamChunk(sink, chunk, maxBytes) {
115
116
  sink.tailBytes = keep.length;
116
117
  }
117
118
  }
119
+ /** Coalesce stream bursts while retaining the timestamp of the last byte, including discarded output. */
120
+ function progressRecorder(directory) {
121
+ const path = join(directory, "progress.json");
122
+ let pending;
123
+ let timer;
124
+ let lastWrite = 0;
125
+ const flush = () => {
126
+ timer = undefined;
127
+ if (!pending)
128
+ return;
129
+ try {
130
+ writeTextAtomic(path, JSON.stringify(pending));
131
+ }
132
+ catch (error) {
133
+ process.stderr.write(`Could not record Background progress: ${String(error)}\n`);
134
+ }
135
+ lastWrite = Date.now();
136
+ };
137
+ return (observedAt, fingerprint) => {
138
+ if (fingerprint !== undefined && pending?.fingerprint === fingerprint)
139
+ return;
140
+ pending = { observedAt, fingerprint };
141
+ if (timer)
142
+ return;
143
+ const remaining = lastWrite + 1000 - Date.now();
144
+ if (remaining <= 0)
145
+ flush();
146
+ else {
147
+ timer = setTimeout(flush, remaining);
148
+ timer.unref();
149
+ }
150
+ };
151
+ }
118
152
  function startToken(pid) {
119
153
  return pid === undefined ? undefined : readProcessStartToken(pid);
120
154
  }
@@ -387,15 +421,21 @@ function runChild(ctx, plan) {
387
421
  };
388
422
  child.stdout?.on("data", (chunk) => {
389
423
  const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
390
- if (plan.mode === "stream")
424
+ if (plan.mode === "stream") {
391
425
  streamChunk(ctx.stdout, buffer, plan.maxBytes);
426
+ if (buffer.length)
427
+ ctx.progress(Date.now());
428
+ }
392
429
  else
393
430
  captureChunk(stdoutCapture, buffer, plan.maxBytes);
394
431
  });
395
432
  child.stderr?.on("data", (chunk) => {
396
433
  const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
397
- if (plan.mode === "stream")
434
+ if (plan.mode === "stream") {
398
435
  streamChunk(ctx.stderr, buffer, plan.maxBytes);
436
+ if (buffer.length)
437
+ ctx.progress(Date.now());
438
+ }
399
439
  else
400
440
  captureChunk(stderrCapture, buffer, plan.maxBytes);
401
441
  });
@@ -594,6 +634,7 @@ async function runWatch(ctx) {
594
634
  if (ctx.finalized)
595
635
  return;
596
636
  ctx.checks += 1;
637
+ ctx.progress(outcome.endedAt, watchOutcomeFingerprint({ ...asCommandResult(outcome), ...(outcome.spawnError ? { error: outcome.spawnError } : {}) }));
597
638
  // Per-check output keeps the streams apart: stdout bytes in stdout.log, stderr in stderr.log.
598
639
  streamChunk(ctx.stdout, Buffer.from(outcome.stdout), ctx.launch.maxLogBytes);
599
640
  streamChunk(ctx.stderr, Buffer.from(outcome.stderr), ctx.launch.maxLogBytes);
@@ -821,9 +862,11 @@ function main() {
821
862
  checks: 0,
822
863
  stdout,
823
864
  stderr,
865
+ progress: progressRecorder(paths.dir),
824
866
  stopRequested: false,
825
867
  finalized: false,
826
868
  };
869
+ ctx.progress(ctx.startedAt);
827
870
  appendEvent(paths.events, `claimed runner_pid=${process.pid} runner_version=${SUPERVISOR_RUNNER_VERSION} kind=${launch.kind} cwd=${launch.command.cwd}`);
828
871
  const onSignal = (signal) => {
829
872
  appendEvent(paths.events, `runner received ${signal}`);
@@ -30,9 +30,10 @@
30
30
 
31
31
  import { spawn } from "node:child_process";
32
32
  import { closeSync, openSync, realpathSync } from "node:fs";
33
- import { resolve } from "node:path";
33
+ import { join, resolve } from "node:path";
34
34
  import { setTimeout as delay } from "node:timers/promises";
35
35
  import { fileURLToPath } from "node:url";
36
+ import { watchOutcomeFingerprint } from "../watch-fingerprint.ts";
36
37
  import { evaluateCondition, validateCondition } from "../conditions.ts";
37
38
  import { completeUtf8Length, stopProcessGroup, utf8PrefixLength } from "../process.ts";
38
39
  import { readProcessStartToken } from "../process-identity.ts";
@@ -47,6 +48,7 @@ import {
47
48
  supervisorPaths,
48
49
  writeCommandRecord,
49
50
  writeTerminalRecord,
51
+ writeTextAtomic,
50
52
  } from "./store.ts";
51
53
  import {
52
54
  DEFAULT_TERMINAL_TAIL_BYTES,
@@ -88,6 +90,7 @@ interface RunnerContext {
88
90
  checks: number;
89
91
  stdout: StreamSink;
90
92
  stderr: StreamSink;
93
+ progress: (observedAt: number, fingerprint?: string) => void;
91
94
  stopRequested: boolean;
92
95
  finalized: boolean;
93
96
  command?: { pid: number; pgid?: number; pidStartTime?: string; startedAt: number; attempt: number };
@@ -212,6 +215,29 @@ function streamChunk(sink: StreamSink, chunk: Buffer, maxBytes: number): void {
212
215
  }
213
216
  }
214
217
 
218
+ /** Coalesce stream bursts while retaining the timestamp of the last byte, including discarded output. */
219
+ function progressRecorder(directory: string) {
220
+ const path = join(directory, "progress.json");
221
+ let pending: { observedAt: number; fingerprint?: string } | undefined;
222
+ let timer: NodeJS.Timeout | undefined;
223
+ let lastWrite = 0;
224
+ const flush = () => {
225
+ timer = undefined;
226
+ if (!pending) return;
227
+ try { writeTextAtomic(path, JSON.stringify(pending)); }
228
+ catch (error) { process.stderr.write(`Could not record Background progress: ${String(error)}\n`); }
229
+ lastWrite = Date.now();
230
+ };
231
+ return (observedAt: number, fingerprint?: string) => {
232
+ if (fingerprint !== undefined && pending?.fingerprint === fingerprint) return;
233
+ pending = { observedAt, fingerprint };
234
+ if (timer) return;
235
+ const remaining = lastWrite + 1000 - Date.now();
236
+ if (remaining <= 0) flush();
237
+ else { timer = setTimeout(flush, remaining); timer.unref(); }
238
+ };
239
+ }
240
+
215
241
  function startToken(pid: number | undefined): string | undefined {
216
242
  return pid === undefined ? undefined : readProcessStartToken(pid);
217
243
  }
@@ -482,12 +508,18 @@ function runChild(ctx: RunnerContext, plan: ChildPlan): Promise<ChildOutcome> {
482
508
 
483
509
  child.stdout?.on("data", (chunk: Buffer | string) => {
484
510
  const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
485
- if (plan.mode === "stream") streamChunk(ctx.stdout, buffer, plan.maxBytes);
511
+ if (plan.mode === "stream") {
512
+ streamChunk(ctx.stdout, buffer, plan.maxBytes);
513
+ if (buffer.length) ctx.progress(Date.now());
514
+ }
486
515
  else captureChunk(stdoutCapture, buffer, plan.maxBytes);
487
516
  });
488
517
  child.stderr?.on("data", (chunk: Buffer | string) => {
489
518
  const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
490
- if (plan.mode === "stream") streamChunk(ctx.stderr, buffer, plan.maxBytes);
519
+ if (plan.mode === "stream") {
520
+ streamChunk(ctx.stderr, buffer, plan.maxBytes);
521
+ if (buffer.length) ctx.progress(Date.now());
522
+ }
491
523
  else captureChunk(stderrCapture, buffer, plan.maxBytes);
492
524
  });
493
525
  child.on("error", (error) => {
@@ -704,6 +736,7 @@ async function runWatch(ctx: RunnerContext): Promise<void> {
704
736
  });
705
737
  if (ctx.finalized) return;
706
738
  ctx.checks += 1;
739
+ ctx.progress(outcome.endedAt, watchOutcomeFingerprint({ ...asCommandResult(outcome), ...(outcome.spawnError ? { error: outcome.spawnError } : {}) }));
707
740
  // Per-check output keeps the streams apart: stdout bytes in stdout.log, stderr in stderr.log.
708
741
  streamChunk(ctx.stdout, Buffer.from(outcome.stdout), ctx.launch.maxLogBytes);
709
742
  streamChunk(ctx.stderr, Buffer.from(outcome.stderr), ctx.launch.maxLogBytes);
@@ -936,9 +969,11 @@ function main(): number {
936
969
  checks: 0,
937
970
  stdout,
938
971
  stderr,
972
+ progress: progressRecorder(paths.dir),
939
973
  stopRequested: false,
940
974
  finalized: false,
941
975
  };
976
+ ctx.progress(ctx.startedAt);
942
977
  appendEvent(paths.events, `claimed runner_pid=${process.pid} runner_version=${SUPERVISOR_RUNNER_VERSION} kind=${launch.kind} cwd=${launch.command.cwd}`);
943
978
 
944
979
  const onSignal = (signal: NodeJS.Signals): void => {
@@ -326,13 +326,13 @@ function readText(path) {
326
326
  catch (error) {
327
327
  if (error.code === "ENOENT")
328
328
  return { missing: true };
329
- return { missing: true, error: error instanceof Error ? error.message : String(error) };
329
+ return { missing: false, error: error instanceof Error ? error.message : String(error) };
330
330
  }
331
331
  }
332
332
  function readJsonRecord(path, problem) {
333
333
  const read = readText(path);
334
- if (read.missing)
335
- return { missing: true, error: read.error };
334
+ if (read.value === undefined)
335
+ return { missing: read.missing, error: read.error };
336
336
  let parsed;
337
337
  try {
338
338
  parsed = JSON.parse(read.value);
@@ -397,16 +397,16 @@ function readText(path: string): RecordRead<string> {
397
397
  return { value: readFileSync(path, "utf8"), missing: false };
398
398
  } catch (error) {
399
399
  if ((error as NodeJS.ErrnoException).code === "ENOENT") return { missing: true };
400
- return { missing: true, error: error instanceof Error ? error.message : String(error) };
400
+ return { missing: false, error: error instanceof Error ? error.message : String(error) };
401
401
  }
402
402
  }
403
403
 
404
404
  function readJsonRecord<T>(path: string, problem: (value: unknown) => string | undefined): RecordRead<T> {
405
405
  const read = readText(path);
406
- if (read.missing) return { missing: true, error: read.error };
406
+ if (read.value === undefined) return { missing: read.missing, error: read.error };
407
407
  let parsed: unknown;
408
408
  try {
409
- parsed = JSON.parse(read.value!);
409
+ parsed = JSON.parse(read.value);
410
410
  } catch (error) {
411
411
  return { missing: false, error: `invalid JSON: ${error instanceof Error ? error.message : String(error)}` };
412
412
  }