pi-better-server 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (340) hide show
  1. package/package.json +7 -3
  2. package/scripts/copy-pi-test-providers.mjs +10 -0
  3. package/scripts/event-publication/README.md +26 -0
  4. package/scripts/event-publication/commit.mjs +21 -0
  5. package/scripts/event-publication/measure.mjs +37 -5
  6. package/scripts/event-publication/writer.mjs +3 -8
  7. package/scripts/measure-full-runtime/frontend.ts +10 -2
  8. package/scripts/measure-full-runtime/probe.mjs +4 -2
  9. package/scripts/measure-full-runtime/recovery-trace-loader.mjs +51 -0
  10. package/scripts/measure-full-runtime/recovery-trace.mjs +16 -0
  11. package/scripts/measure-full-runtime.mjs +2 -0
  12. package/scripts/measure-shared-reads.mjs +2 -1
  13. package/scripts/private-runtime/package-lock.json +18 -0
  14. package/scripts/private-runtime/package.json +4 -1
  15. package/scripts/source-provenance.mjs +2 -2
  16. package/scripts/test-on-pi.sh +2 -9
  17. package/src/handshake.ts +1 -1
  18. package/src/hosted-session.ts +32 -4
  19. package/src/maintenance.ts +35 -7
  20. package/src/registry.ts +28 -4
  21. package/src/runtime/attempt-invalidation.ts +54 -0
  22. package/src/runtime/background-history.ts +151 -45
  23. package/src/runtime/background-policy.ts +9 -4
  24. package/src/runtime/background-tools.ts +181 -27
  25. package/src/runtime/background.ts +365 -70
  26. package/src/runtime/cancellation.ts +28 -7
  27. package/src/runtime/catalog-sources.ts +199 -0
  28. package/src/runtime/catalog.ts +53 -21
  29. package/src/runtime/client.ts +22 -2
  30. package/src/runtime/domain/assignment-inbox.mjs +119 -0
  31. package/src/runtime/domain/assignment-observation.d.mts +1 -1
  32. package/src/runtime/domain/assignment-observation.mjs +43 -35
  33. package/src/runtime/domain/background/process-identity.mjs +20 -2
  34. package/src/runtime/domain/background/process.mjs +52 -14
  35. package/src/runtime/domain/background/registry.mjs +61 -3
  36. package/src/runtime/domain/background/supervisor/store.mjs +3 -3
  37. package/src/runtime/domain/background/supervisor/supervisor.mjs +9 -3
  38. package/src/runtime/domain/background/types.mjs +1 -0
  39. package/src/runtime/domain/background-service/adapter-contract.domain.mjs +1 -1
  40. package/src/runtime/domain/background-service/adapter-contract.ts +1 -1
  41. package/src/runtime/domain/background-service/goal-provider.domain.mjs +35 -16
  42. package/src/runtime/domain/background-service/goal-provider.ts +31 -16
  43. package/src/runtime/domain/background-service/index.domain.mjs +25 -9
  44. package/src/runtime/domain/background-service/index.ts +25 -9
  45. package/src/runtime/domain/background-service/managed-authority.domain.mjs +6 -3
  46. package/src/runtime/domain/background-service/managed-authority.ts +5 -3
  47. package/src/runtime/domain/background-service/managed-client.domain.mjs +21 -7
  48. package/src/runtime/domain/background-service/managed-client.ts +20 -7
  49. package/src/runtime/domain/background-service/managed-frontend.domain.mjs +159 -19
  50. package/src/runtime/domain/background-service/managed-frontend.ts +135 -19
  51. package/src/runtime/domain/background-service/navigator-provider.domain.mjs +21 -5
  52. package/src/runtime/domain/background-service/navigator-provider.ts +19 -5
  53. package/src/runtime/domain/background-service/observed-wait-client.domain.mjs +6 -0
  54. package/src/runtime/domain/background-service/observed-wait-client.ts +10 -0
  55. package/src/runtime/domain/background-service/observed-waits.domain.mjs +372 -57
  56. package/src/runtime/domain/background-service/observed-waits.ts +321 -53
  57. package/src/runtime/domain/background-service/process-identity.domain.mjs +20 -2
  58. package/src/runtime/domain/background-service/process-identity.ts +18 -2
  59. package/src/runtime/domain/background-service/process.domain.mjs +52 -14
  60. package/src/runtime/domain/background-service/process.ts +48 -14
  61. package/src/runtime/domain/background-service/registry.domain.mjs +61 -3
  62. package/src/runtime/domain/background-service/registry.ts +53 -5
  63. package/src/runtime/domain/background-service/review-settings.domain.mjs +16 -0
  64. package/src/runtime/domain/background-service/review-settings.ts +18 -0
  65. package/src/runtime/domain/background-service/runtime.domain.mjs +40 -86
  66. package/src/runtime/domain/background-service/runtime.ts +27 -82
  67. package/src/runtime/domain/background-service/sandbox.domain.mjs +14 -15
  68. package/src/runtime/domain/background-service/sandbox.ts +14 -11
  69. package/src/runtime/domain/background-service/shared-callback-batcher.domain.mjs +8 -1
  70. package/src/runtime/domain/background-service/shared-callback-batcher.ts +11 -2
  71. package/src/runtime/domain/background-service/shared-navigator-panels.domain.mjs +24 -2
  72. package/src/runtime/domain/background-service/shared-navigator-panels.ts +26 -4
  73. package/src/runtime/domain/background-service/shared-navigator.domain.mjs +273 -41
  74. package/src/runtime/domain/background-service/shared-navigator.ts +244 -40
  75. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-inbox.mjs +144 -0
  76. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-observation.mjs +53 -41
  77. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
  78. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  79. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
  80. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  81. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
  82. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.ts +14 -3
  83. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
  84. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.ts +5 -3
  85. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.domain.mjs +44 -4
  86. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.ts +50 -2
  87. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  88. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.ts +9 -0
  89. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
  90. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.ts +12 -0
  91. package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.domain.mjs +2 -0
  92. package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.ts +2 -0
  93. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +42 -21
  94. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +40 -24
  95. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +26 -4
  96. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +40 -8
  97. package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
  98. package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.ts +24 -1
  99. package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.domain.mjs +1 -1
  100. package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.ts +5 -1
  101. package/src/runtime/domain/background-service/shared-sandbox-core.ts +1 -1
  102. package/src/runtime/domain/background-service/shared-work-client.mjs +174 -7
  103. package/src/runtime/domain/background-service/stall.domain.mjs +5 -3
  104. package/src/runtime/domain/background-service/stall.ts +7 -4
  105. package/src/runtime/domain/background-service/supervised-progress.domain.mjs +42 -0
  106. package/src/runtime/domain/background-service/supervised-progress.ts +43 -0
  107. package/src/runtime/domain/background-service/supervisor/README.md +1 -4
  108. package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +1 -0
  109. package/src/runtime/domain/background-service/supervisor/generated/process-identity.mjs +20 -2
  110. package/src/runtime/domain/background-service/supervisor/generated/process.mjs +52 -14
  111. package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +47 -4
  112. package/src/runtime/domain/background-service/supervisor/generated/store.mjs +3 -3
  113. package/src/runtime/domain/background-service/supervisor/generated/watch-fingerprint.mjs +69 -0
  114. package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +47 -4
  115. package/src/runtime/domain/background-service/supervisor/runner.ts +38 -3
  116. package/src/runtime/domain/background-service/supervisor/store.domain.mjs +3 -3
  117. package/src/runtime/domain/background-service/supervisor/store.ts +3 -3
  118. package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +9 -3
  119. package/src/runtime/domain/background-service/supervisor/supervisor.ts +6 -3
  120. package/src/runtime/domain/background-service/task-diagnostics.domain.mjs +1 -1
  121. package/src/runtime/domain/background-service/task-diagnostics.ts +1 -1
  122. package/src/runtime/domain/background-service/tools.domain.mjs +53 -40
  123. package/src/runtime/domain/background-service/tools.ts +67 -54
  124. package/src/runtime/domain/background-service/types.domain.mjs +1 -0
  125. package/src/runtime/domain/background-service/types.ts +7 -3
  126. package/src/runtime/domain/background-service/watch-fingerprint.domain.mjs +67 -0
  127. package/src/runtime/domain/background-service/watch-fingerprint.ts +70 -0
  128. package/src/runtime/domain/background-service/work-observation.domain.mjs +46 -20
  129. package/src/runtime/domain/background-service/work-observation.ts +46 -19
  130. package/src/runtime/domain/catalog/catalog-store.d.mts +9 -1
  131. package/src/runtime/domain/catalog/catalog-store.mjs +20 -22
  132. package/src/runtime/domain/coordinator/src/assignment-changes.mjs +75 -0
  133. package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +2 -0
  134. package/src/runtime/domain/coordinator/src/background-requests.mjs +11 -2
  135. package/src/runtime/domain/coordinator/src/discovery.mjs +4 -2
  136. package/src/runtime/domain/coordinator/src/operations.mjs +44 -4
  137. package/src/runtime/domain/coordinator/src/outbox.mjs +7 -0
  138. package/src/runtime/domain/coordinator/src/result-supervision.mjs +12 -0
  139. package/src/runtime/domain/coordinator/src/rows.mjs +2 -0
  140. package/src/runtime/domain/coordinator/src/schema.mjs +42 -21
  141. package/src/runtime/domain/coordinator/src/store.mjs +26 -4
  142. package/src/runtime/domain/coordinator/src/subagent-launch.mjs +23 -1
  143. package/src/runtime/domain/coordinator/src/types.mjs +1 -1
  144. package/src/runtime/domain/health-observation.d.mts +3 -1
  145. package/src/runtime/domain/health-observation.mjs +189 -190
  146. package/src/runtime/domain/log-cursor.d.mts +2 -0
  147. package/src/runtime/domain/log-cursor.mjs +85 -16
  148. package/src/runtime/domain/log-paths.mjs +8 -1
  149. package/src/runtime/domain/parse.d.mts +4 -1
  150. package/src/runtime/domain/parse.mjs +58 -9
  151. package/src/runtime/domain/sandbox-policy/README.md +63 -65
  152. package/src/runtime/domain/sandbox-policy/commands.domain.mjs +11 -8
  153. package/src/runtime/domain/sandbox-policy/commands.ts +12 -7
  154. package/src/runtime/domain/sandbox-policy/index.domain.mjs +53 -9
  155. package/src/runtime/domain/sandbox-policy/index.ts +52 -9
  156. package/src/runtime/domain/sandbox-policy/package.json +1 -1
  157. package/src/runtime/domain/sandbox-policy/permission-settings.domain.mjs +5 -2
  158. package/src/runtime/domain/sandbox-policy/permission-settings.ts +9 -2
  159. package/src/runtime/domain/sandbox-policy/permissions-page.domain.mjs +56 -137
  160. package/src/runtime/domain/sandbox-policy/permissions-page.ts +52 -130
  161. package/src/runtime/domain/sandbox-policy/permissions.domain.mjs +1 -6
  162. package/src/runtime/domain/sandbox-policy/permissions.ts +1 -6
  163. package/src/runtime/domain/sandbox-policy/shared-sandbox-core.ts +1 -1
  164. package/src/runtime/domain/sandbox-policy/shared-task-exec.domain.mjs +14 -1
  165. package/src/runtime/domain/sandbox-policy/shared-task-exec.ts +12 -1
  166. package/src/runtime/domain/sandbox-policy/shared-task-process-identity.domain.mjs +140 -0
  167. package/src/runtime/domain/sandbox-policy/shared-task-process-identity.ts +126 -0
  168. package/src/runtime/domain/sandbox-policy/shared-task-process-list.domain.mjs +3 -2
  169. package/src/runtime/domain/sandbox-policy/shared-task-process-list.ts +8 -2
  170. package/src/runtime/domain/sandbox-policy/shared-task-sandbox.domain.mjs +4 -3
  171. package/src/runtime/domain/sandbox-policy/shared-task-sandbox.ts +5 -3
  172. package/src/runtime/domain/sandbox-policy/shared-task-tools.domain.mjs +8 -5
  173. package/src/runtime/domain/sandbox-policy/shared-task-tools.ts +8 -5
  174. package/src/runtime/domain/session-store.mjs +7 -0
  175. package/src/runtime/domain/subagents/README.md +13 -11
  176. package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +10 -7
  177. package/src/runtime/domain/subagents/assignment-outcomes.ts +9 -6
  178. package/src/runtime/domain/subagents/assignment-report.domain.mjs +109 -24
  179. package/src/runtime/domain/subagents/assignment-report.ts +103 -19
  180. package/src/runtime/domain/subagents/batch.mjs +13 -5
  181. package/src/runtime/domain/subagents/catalog-host-admission.domain.mjs +21 -3
  182. package/src/runtime/domain/subagents/catalog-host-admission.ts +19 -3
  183. package/src/runtime/domain/subagents/catalog-preferences.ts +1 -1
  184. package/src/runtime/domain/subagents/catalog-resolver.domain.mjs +35 -1
  185. package/src/runtime/domain/subagents/catalog-resolver.ts +35 -1
  186. package/src/runtime/domain/subagents/catalog-store.domain.mjs +20 -22
  187. package/src/runtime/domain/subagents/catalog-store.ts +27 -20
  188. package/src/runtime/domain/subagents/child-apply-patch.domain.mjs +13 -0
  189. package/src/runtime/domain/subagents/child-apply-patch.ts +13 -0
  190. package/src/runtime/domain/subagents/child-dependencies.mjs +27 -15
  191. package/src/runtime/domain/subagents/child-operations.domain.mjs +80 -2
  192. package/src/runtime/domain/subagents/child-operations.ts +80 -1
  193. package/src/runtime/domain/subagents/child-preflight.mjs +9 -2
  194. package/src/runtime/domain/subagents/child-process-list.domain.mjs +7 -0
  195. package/src/runtime/domain/subagents/child-process-list.ts +8 -0
  196. package/src/runtime/domain/subagents/cleanup.domain.mjs +11 -2
  197. package/src/runtime/domain/subagents/cleanup.ts +10 -2
  198. package/src/runtime/domain/subagents/config.domain.mjs +54 -2
  199. package/src/runtime/domain/subagents/config.ts +53 -3
  200. package/src/runtime/domain/subagents/continuation-authority.domain.mjs +5 -1
  201. package/src/runtime/domain/subagents/continuation-authority.ts +3 -1
  202. package/src/runtime/domain/subagents/continuation-runtime.domain.mjs +89 -0
  203. package/src/runtime/domain/subagents/continuation-runtime.ts +88 -0
  204. package/src/runtime/domain/subagents/continuation.domain.mjs +4 -2
  205. package/src/runtime/domain/subagents/continuation.ts +4 -2
  206. package/src/runtime/domain/subagents/extensions.mjs +11 -13
  207. package/src/runtime/domain/subagents/failures.domain.mjs +11 -2
  208. package/src/runtime/domain/subagents/failures.ts +10 -2
  209. package/src/runtime/domain/subagents/finalization.domain.mjs +16 -1
  210. package/src/runtime/domain/subagents/finalization.ts +21 -1
  211. package/src/runtime/domain/subagents/goal-provider.domain.mjs +44 -2
  212. package/src/runtime/domain/subagents/goal-provider.ts +44 -2
  213. package/src/runtime/domain/subagents/health-observation.domain.mjs +189 -190
  214. package/src/runtime/domain/subagents/health-observation.ts +43 -48
  215. package/src/runtime/domain/subagents/index.domain.mjs +457 -182
  216. package/src/runtime/domain/subagents/index.ts +417 -155
  217. package/src/runtime/domain/subagents/isolated-workspace.domain.mjs +515 -0
  218. package/src/runtime/domain/subagents/isolated-workspace.ts +557 -0
  219. package/src/runtime/domain/subagents/launch-context.domain.mjs +24 -0
  220. package/src/runtime/domain/subagents/launch-context.ts +23 -0
  221. package/src/runtime/domain/subagents/launch-digest.mjs +6 -0
  222. package/src/runtime/domain/subagents/list.mjs +2 -2
  223. package/src/runtime/domain/subagents/log-cursor.domain.mjs +85 -16
  224. package/src/runtime/domain/subagents/log-cursor.ts +91 -15
  225. package/src/runtime/domain/subagents/managed-launch-bootstrap.mjs +2 -2
  226. package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +27 -7
  227. package/src/runtime/domain/subagents/managed-launch-client.ts +28 -8
  228. package/src/runtime/domain/subagents/managed-launch-host.domain.mjs +222 -14
  229. package/src/runtime/domain/subagents/managed-launch-host.ts +168 -15
  230. package/src/runtime/domain/subagents/managed-launch-journal.mjs +1 -5
  231. package/src/runtime/domain/subagents/managed-launch-port.ts +4 -0
  232. package/src/runtime/domain/subagents/operation-bridge-types.domain.mjs +27 -2
  233. package/src/runtime/domain/subagents/operation-bridge-types.ts +27 -2
  234. package/src/runtime/domain/subagents/output-payload.domain.mjs +24 -9
  235. package/src/runtime/domain/subagents/output-payload.ts +26 -12
  236. package/src/runtime/domain/subagents/owned-exit.domain.mjs +12 -0
  237. package/src/runtime/domain/subagents/owned-exit.ts +12 -0
  238. package/src/runtime/domain/subagents/package.json +4 -2
  239. package/src/runtime/domain/subagents/parse.domain.mjs +58 -9
  240. package/src/runtime/domain/subagents/parse.ts +57 -10
  241. package/src/runtime/domain/subagents/permission-policy.domain.mjs +32 -8
  242. package/src/runtime/domain/subagents/permission-policy.ts +41 -8
  243. package/src/runtime/domain/subagents/process-identity.mjs +33 -0
  244. package/src/runtime/domain/subagents/registry.domain.mjs +71 -51
  245. package/src/runtime/domain/subagents/registry.ts +77 -38
  246. package/src/runtime/domain/subagents/retained-result.domain.mjs +56 -0
  247. package/src/runtime/domain/subagents/retained-result.ts +65 -0
  248. package/src/runtime/domain/subagents/session-selection.domain.mjs +3 -1
  249. package/src/runtime/domain/subagents/session-selection.ts +2 -1
  250. package/src/runtime/domain/subagents/session-store.domain.mjs +7 -0
  251. package/src/runtime/domain/subagents/session-store.ts +9 -0
  252. package/src/runtime/domain/subagents/settings-page.domain.mjs +151 -107
  253. package/src/runtime/domain/subagents/settings-page.ts +147 -108
  254. package/src/runtime/domain/subagents/shared-callback-batcher.domain.mjs +8 -1
  255. package/src/runtime/domain/subagents/shared-callback-batcher.ts +11 -2
  256. package/src/runtime/domain/subagents/shared-catalog.domain.mjs +28 -29
  257. package/src/runtime/domain/subagents/shared-catalog.ts +29 -21
  258. package/src/runtime/domain/subagents/shared-navigator-panels.domain.mjs +24 -2
  259. package/src/runtime/domain/subagents/shared-navigator-panels.ts +26 -4
  260. package/src/runtime/domain/subagents/shared-navigator.domain.mjs +273 -41
  261. package/src/runtime/domain/subagents/shared-navigator.ts +244 -40
  262. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-inbox.mjs +144 -0
  263. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-observation.mjs +53 -41
  264. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
  265. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  266. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
  267. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  268. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
  269. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.ts +14 -3
  270. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
  271. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.ts +5 -3
  272. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.domain.mjs +44 -4
  273. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.ts +50 -2
  274. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  275. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.ts +9 -0
  276. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
  277. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.ts +12 -0
  278. package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.domain.mjs +2 -0
  279. package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.ts +2 -0
  280. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +42 -21
  281. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +40 -24
  282. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +26 -4
  283. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +40 -8
  284. package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
  285. package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.ts +24 -1
  286. package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.domain.mjs +1 -1
  287. package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.ts +5 -1
  288. package/src/runtime/domain/subagents/shared-sandbox-core.ts +1 -1
  289. package/src/runtime/domain/subagents/shared-task-exec.domain.mjs +14 -1
  290. package/src/runtime/domain/subagents/shared-task-exec.ts +12 -1
  291. package/src/runtime/domain/subagents/shared-task-process-identity.domain.mjs +140 -0
  292. package/src/runtime/domain/subagents/shared-task-process-identity.ts +126 -0
  293. package/src/runtime/domain/subagents/shared-task-process-list.domain.mjs +3 -2
  294. package/src/runtime/domain/subagents/shared-task-process-list.ts +8 -2
  295. package/src/runtime/domain/subagents/shared-task-sandbox.domain.mjs +4 -3
  296. package/src/runtime/domain/subagents/shared-task-sandbox.ts +5 -3
  297. package/src/runtime/domain/subagents/shared-task-tools.domain.mjs +8 -5
  298. package/src/runtime/domain/subagents/shared-task-tools.ts +8 -5
  299. package/src/runtime/domain/subagents/shared-work-client.mjs +174 -7
  300. package/src/runtime/domain/subagents/subagent-tools.domain.mjs +22 -38
  301. package/src/runtime/domain/subagents/subagent-tools.ts +28 -34
  302. package/src/runtime/domain/subagents/task-guard.domain.mjs +14 -1
  303. package/src/runtime/domain/subagents/task-guard.ts +13 -1
  304. package/src/runtime/domain/subagents/task-policy.domain.mjs +3 -2
  305. package/src/runtime/domain/subagents/task-policy.ts +8 -2
  306. package/src/runtime/domain/subagents/timing.domain.mjs +10 -1
  307. package/src/runtime/domain/subagents/timing.ts +10 -1
  308. package/src/runtime/domain/subagents/tools.domain.mjs +4 -8
  309. package/src/runtime/domain/subagents/tools.ts +4 -7
  310. package/src/runtime/domain/subagents/work-observation.domain.mjs +102 -17
  311. package/src/runtime/domain/subagents/work-observation.ts +91 -17
  312. package/src/runtime/domain/subagents/worker-operations-host.domain.mjs +9 -4
  313. package/src/runtime/domain/subagents/worker-operations-host.ts +12 -4
  314. package/src/runtime/domain/subagents/worker-waits.domain.mjs +89 -35
  315. package/src/runtime/domain/subagents/worker-waits.ts +93 -34
  316. package/src/runtime/domain/subagents/workspace-files.domain.mjs +103 -0
  317. package/src/runtime/domain/subagents/workspace-files.ts +114 -0
  318. package/src/runtime/domain/subagents/workspace-scope.domain.d.mts +38 -0
  319. package/src/runtime/domain/subagents/workspace-scope.domain.mjs +5 -0
  320. package/src/runtime/domain/subagents/workspace-scope.ts +6 -0
  321. package/src/runtime/domain/subagents/worktree-feedback.domain.mjs +55 -0
  322. package/src/runtime/domain/subagents/worktree-feedback.ts +77 -0
  323. package/src/runtime/health-config.ts +27 -11
  324. package/src/runtime/log-checkpoints.ts +117 -0
  325. package/src/runtime/mutation-store.ts +5 -4
  326. package/src/runtime/queries.ts +25 -2
  327. package/src/runtime/query-executor.ts +149 -28
  328. package/src/runtime/query-worker.mjs +106 -21
  329. package/src/runtime/read-model.ts +849 -121
  330. package/src/runtime/read-watchdog-probe.ts +4 -0
  331. package/src/runtime/result-supervision.ts +188 -16
  332. package/src/runtime/root.ts +5 -2
  333. package/src/runtime/source-watch.ts +175 -0
  334. package/src/runtime/subagent-launch.ts +11 -4
  335. package/src/runtime/work-budget.ts +130 -0
  336. package/src/runtime/work-client.d.mts +8 -0
  337. package/src/runtime/work-client.mjs +150 -7
  338. package/src/server.ts +104 -23
  339. package/src/session-activity.ts +26 -4
  340. package/src/version.ts +1 -1
@@ -1,4 +1,5 @@
1
1
  // Generated fixed launch domain from packages/pi-better-background-tasks/src/process-identity.ts. Do not edit directly.
2
+ import { readFileSync } from "node:fs";
2
3
  import { execFileSync } from "node:child_process";
3
4
  /**
4
5
  * Process start-token reads.
@@ -21,11 +22,12 @@ const TOKEN_MEMO_TTL_MS = 1_000;
21
22
  /** Bound on memo entries; the panel is small, but a long session is not. */
22
23
  const TOKEN_MEMO_MAX_ENTRIES = 512;
23
24
  const tokenMemo = new Map();
24
- function readTokenUncached(pid) {
25
+ function readTokenUncached(pid, admission = false) {
25
26
  if (!Number.isInteger(pid) || pid <= 0 || process.platform === "win32")
26
27
  return undefined;
27
28
  try {
28
- const output = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], {
29
+ const output = execFileSync(admission ? "/bin/ps" : "ps", ["-o", "lstart=", "-p", String(pid)], {
30
+ env: admission ? { LC_ALL: "C", TZ: "UTC0", PATH: "/usr/bin:/bin" } : process.env,
29
31
  encoding: "utf8",
30
32
  stdio: ["ignore", "pipe", "ignore"],
31
33
  timeout: 2_000,
@@ -36,6 +38,22 @@ function readTokenUncached(pid) {
36
38
  return undefined;
37
39
  }
38
40
  }
41
+ // Admission crosses process environments; stored task tokens retain their original format.
42
+ export function readAdmissionStartToken(pid) {
43
+ if (process.platform !== "linux")
44
+ return readTokenUncached(pid, true);
45
+ if (!Number.isInteger(pid) || pid <= 0)
46
+ return undefined;
47
+ try {
48
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
49
+ // Fields after the parenthesized command start at field 3. Start time is field 22.
50
+ const start = stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
51
+ return start && /^\d+$/.test(start) ? start : undefined;
52
+ }
53
+ catch {
54
+ return undefined;
55
+ }
56
+ }
39
57
  function remember(pid, token, now) {
40
58
  if (tokenMemo.size >= TOKEN_MEMO_MAX_ENTRIES) {
41
59
  // Drop expired entries first; only evict live ones if that was not enough.
@@ -1,3 +1,4 @@
1
+ import { readFileSync } from "node:fs";
1
2
  import { execFileSync } from "node:child_process";
2
3
 
3
4
  /**
@@ -29,10 +30,11 @@ interface TokenMemoEntry {
29
30
 
30
31
  const tokenMemo = new Map<number, TokenMemoEntry>();
31
32
 
32
- function readTokenUncached(pid: number): string | undefined {
33
+ function readTokenUncached(pid: number, admission = false): string | undefined {
33
34
  if (!Number.isInteger(pid) || pid <= 0 || process.platform === "win32") return undefined;
34
35
  try {
35
- const output = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], {
36
+ const output = execFileSync(admission ? "/bin/ps" : "ps", ["-o", "lstart=", "-p", String(pid)], {
37
+ env: admission ? { LC_ALL: "C", TZ: "UTC0", PATH: "/usr/bin:/bin" } : process.env,
36
38
  encoding: "utf8",
37
39
  stdio: ["ignore", "pipe", "ignore"],
38
40
  timeout: 2_000,
@@ -43,6 +45,20 @@ function readTokenUncached(pid: number): string | undefined {
43
45
  }
44
46
  }
45
47
 
48
+ // Admission crosses process environments; stored task tokens retain their original format.
49
+ export function readAdmissionStartToken(pid: number): string | undefined {
50
+ if (process.platform !== "linux") return readTokenUncached(pid, true);
51
+ if (!Number.isInteger(pid) || pid <= 0) return undefined;
52
+ try {
53
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
54
+ // Fields after the parenthesized command start at field 3. Start time is field 22.
55
+ const start = stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
56
+ return start && /^\d+$/.test(start) ? start : undefined;
57
+ } catch {
58
+ return undefined;
59
+ }
60
+ }
61
+
46
62
  function remember(pid: number, token: string | undefined, now: number): void {
47
63
  if (tokenMemo.size >= TOKEN_MEMO_MAX_ENTRIES) {
48
64
  // Drop expired entries first; only evict live ones if that was not enough.
@@ -1,7 +1,8 @@
1
1
  // Generated fixed launch domain from packages/pi-better-background-tasks/src/process.ts. Do not edit directly.
2
2
  import { spawn, spawnSync } from "node:child_process";
3
- import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, writeSync } from "node:fs";
4
- import { dirname, join } from "node:path";
3
+ import { accessSync, appendFileSync, closeSync, constants, existsSync, mkdirSync, openSync, readFileSync, writeSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { dirname, join, win32 } from "node:path";
5
6
  /** Known Git for Windows locations; `bash -lc` needs a real bash, not the WSL shim. */
6
7
  const WINDOWS_BASH_CANDIDATES = [
7
8
  "C:\\Program Files\\Git\\bin\\bash.exe",
@@ -14,7 +15,8 @@ const WINDOWS_BASH_CANDIDATES = [
14
15
  * POSIX keeps `/bin/bash`. Windows has no `/bin/bash`, and the `bash.exe` found
15
16
  * on PATH is usually the WSL launcher in System32 or the WindowsApps alias,
16
17
  * either of which would run the command inside WSL instead of Windows. Prefer
17
- * an explicit override, then Git for Windows, then a non-WSL `bash.exe` on PATH.
18
+ * an explicit override, then Pi's shellPath, Git for Windows, and a non-WSL
19
+ * `bash.exe` on PATH.
18
20
  *
19
21
  * Resolved lazily at spawn time, not module load: env-injection extensions
20
22
  * (e.g. pi-env) may apply settings.json `env` values after this module is
@@ -22,27 +24,62 @@ const WINDOWS_BASH_CANDIDATES = [
22
24
  *
23
25
  * Exposed for tests and reuse.
24
26
  */
25
- export function resolveDefaultShell() {
27
+ export function resolveDefaultShell(shellPath) {
26
28
  const fromEnv = process.env.PI_BETTER_BACKGROUND_TASKS_SHELL;
27
29
  if (fromEnv)
28
30
  return fromEnv;
29
31
  if (process.platform !== "win32")
30
32
  return "/bin/bash";
31
- for (const candidate of WINDOWS_BASH_CANDIDATES) {
33
+ const configured = shellPath ?? readWindowsShellSetting();
34
+ const tried = [];
35
+ if (configured?.trim()) {
36
+ const candidate = /^~[\\/]/.test(configured) ? win32.join(homedir(), configured.slice(2)) : configured;
37
+ tried.push(candidate);
38
+ try {
39
+ accessSync(candidate, constants.F_OK);
40
+ return candidate;
41
+ }
42
+ catch { /* An unavailable setting leaves standard Windows discovery enabled. */ }
43
+ }
44
+ const gitCandidates = [process.env.ProgramFiles, process.env["ProgramFiles(x86)"]]
45
+ .filter((directory) => Boolean(directory))
46
+ .map(directory => win32.join(directory, "Git", "bin", "bash.exe"));
47
+ for (const candidate of new Set([...gitCandidates, ...WINDOWS_BASH_CANDIDATES])) {
48
+ tried.push(candidate);
32
49
  if (existsSync(candidate))
33
50
  return candidate;
34
51
  }
35
- for (const dir of (process.env.PATH ?? "").split(";")) {
52
+ for (const dir of (process.env.PATH ?? process.env.Path ?? "").split(";")) {
36
53
  const trimmed = dir.trim();
37
54
  if (!trimmed || /(^|[\\/])(system32|windowsapps)([\\/]|$)/i.test(trimmed))
38
55
  continue;
39
- const candidate = join(trimmed, "bash.exe");
56
+ const candidate = win32.join(trimmed, "bash.exe");
57
+ tried.push(candidate);
40
58
  if (existsSync(candidate))
41
59
  return candidate;
42
60
  }
43
- // Nothing usable found: keep the POSIX default so the failure surfaces as a
44
- // logged spawn error for the task instead of crashing the whole host process.
45
- return "/bin/bash";
61
+ throw new Error("No Bash executable found for Windows Background tasks. Set Pi's shellPath in settings.json or "
62
+ + "PI_BETTER_BACKGROUND_TASKS_SHELL to a working bash.exe. Searched:\n " + [...new Set(tried)].join("\n "));
63
+ }
64
+ function readWindowsShellSetting() {
65
+ const agentDir = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
66
+ try {
67
+ const settings = JSON.parse(readFileSync(join(agentDir, "settings.json"), "utf8"));
68
+ return typeof settings?.shellPath === "string" ? settings.shellPath : undefined;
69
+ }
70
+ catch {
71
+ return undefined;
72
+ }
73
+ }
74
+ /** Capture effective session settings before dispatching a Windows launch. */
75
+ export function resolveWindowsLaunchShell(pi) {
76
+ if (process.platform !== "win32")
77
+ return undefined;
78
+ const override = process.env.PI_BETTER_BACKGROUND_TASKS_SHELL;
79
+ if (override)
80
+ return override;
81
+ const settings = pi.getSettings?.();
82
+ return resolveDefaultShell(typeof settings?.shellPath === "string" ? settings.shellPath : undefined);
46
83
  }
47
84
  /** How long a timed-out process group has to exit on SIGTERM before SIGKILL. */
48
85
  const TERMINATION_GRACE_MS = 2_000;
@@ -60,8 +97,8 @@ export function validateCommandSpec(spec) {
60
97
  /** Convert a Windows path to the `/c/...` form MSYS bash resolves in redirections. Exposed for tests and reuse. */
61
98
  export function toMsysPath(path) {
62
99
  const forward = path.replace(/\\/g, "/");
63
- const drive = /^([A-Za-z]):(\/.+)$/.exec(forward);
64
- return drive ? `/${drive[1].toLowerCase()}${drive[2]}` : forward;
100
+ const [, drive, rest] = /^([A-Za-z]):(\/.+)$/.exec(forward) ?? [];
101
+ return drive && rest ? `/${drive.toLowerCase()}${rest}` : forward;
65
102
  }
66
103
  /** Single-quote a value for safe literal use in a bash script line. Exposed for tests and reuse. */
67
104
  export function bashSingleQuote(value) {
@@ -145,7 +182,7 @@ export function parseStepGateFailure(logText, id) {
145
182
  if (!line.startsWith(marker) || !line.endsWith(" ---"))
146
183
  continue;
147
184
  const match = /^--- step gate \[[^\]]+\]: first failing step exit=(-?\d+); shell exit=(-?\d+): (.*) ---$/.exec(line);
148
- if (!match)
185
+ if (!match || match[3] === undefined)
149
186
  continue;
150
187
  const stepExitCode = Number(match[1]);
151
188
  const shellExitCode = Number(match[2]);
@@ -495,7 +532,8 @@ export function commandExecution(spec) {
495
532
  const [command, ...args] = spec.argv;
496
533
  return { execPath: command, execArgs: args };
497
534
  }
498
- return { execPath: resolveDefaultShell(), execArgs: [spec.loginShell === false ? "-c" : "-lc", spec.command] };
535
+ const resolved = process.platform === "win32" ? spec.resolvedWindowsShell : undefined;
536
+ return { execPath: resolved ?? resolveDefaultShell(), execArgs: [spec.loginShell === false ? "-c" : "-lc", spec.command] };
499
537
  }
500
538
  function spawnArgs(spec, detached, stdio) {
501
539
  const env = { ...process.env, ...spec.env };
@@ -1,6 +1,7 @@
1
1
  import { spawn, spawnSync } from "node:child_process";
2
- import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, writeSync } from "node:fs";
3
- import { dirname, join } from "node:path";
2
+ import { accessSync, appendFileSync, closeSync, constants, existsSync, mkdirSync, openSync, readFileSync, writeSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join, win32 } from "node:path";
4
5
  import type { ChildProcess } from "node:child_process";
5
6
  import type { CommandResult, CommandSpec, StepGateFailure } from "./types.js";
6
7
 
@@ -17,7 +18,8 @@ const WINDOWS_BASH_CANDIDATES = [
17
18
  * POSIX keeps `/bin/bash`. Windows has no `/bin/bash`, and the `bash.exe` found
18
19
  * on PATH is usually the WSL launcher in System32 or the WindowsApps alias,
19
20
  * either of which would run the command inside WSL instead of Windows. Prefer
20
- * an explicit override, then Git for Windows, then a non-WSL `bash.exe` on PATH.
21
+ * an explicit override, then Pi's shellPath, Git for Windows, and a non-WSL
22
+ * `bash.exe` on PATH.
21
23
  *
22
24
  * Resolved lazily at spawn time, not module load: env-injection extensions
23
25
  * (e.g. pi-env) may apply settings.json `env` values after this module is
@@ -25,22 +27,53 @@ const WINDOWS_BASH_CANDIDATES = [
25
27
  *
26
28
  * Exposed for tests and reuse.
27
29
  */
28
- export function resolveDefaultShell(): string {
30
+ export function resolveDefaultShell(shellPath?: string): string {
29
31
  const fromEnv = process.env.PI_BETTER_BACKGROUND_TASKS_SHELL;
30
32
  if (fromEnv) return fromEnv;
31
33
  if (process.platform !== "win32") return "/bin/bash";
32
- for (const candidate of WINDOWS_BASH_CANDIDATES) {
34
+ const configured = shellPath ?? readWindowsShellSetting();
35
+ const tried: string[] = [];
36
+ if (configured?.trim()) {
37
+ const candidate = /^~[\\/]/.test(configured) ? win32.join(homedir(), configured.slice(2)) : configured;
38
+ tried.push(candidate);
39
+ try {
40
+ accessSync(candidate, constants.F_OK);
41
+ return candidate;
42
+ } catch { /* An unavailable setting leaves standard Windows discovery enabled. */ }
43
+ }
44
+ const gitCandidates = [process.env.ProgramFiles, process.env["ProgramFiles(x86)"]]
45
+ .filter((directory): directory is string => Boolean(directory))
46
+ .map(directory => win32.join(directory, "Git", "bin", "bash.exe"));
47
+ for (const candidate of new Set([...gitCandidates, ...WINDOWS_BASH_CANDIDATES])) {
48
+ tried.push(candidate);
33
49
  if (existsSync(candidate)) return candidate;
34
50
  }
35
- for (const dir of (process.env.PATH ?? "").split(";")) {
51
+ for (const dir of (process.env.PATH ?? process.env.Path ?? "").split(";")) {
36
52
  const trimmed = dir.trim();
37
53
  if (!trimmed || /(^|[\\/])(system32|windowsapps)([\\/]|$)/i.test(trimmed)) continue;
38
- const candidate = join(trimmed, "bash.exe");
54
+ const candidate = win32.join(trimmed, "bash.exe");
55
+ tried.push(candidate);
39
56
  if (existsSync(candidate)) return candidate;
40
57
  }
41
- // Nothing usable found: keep the POSIX default so the failure surfaces as a
42
- // logged spawn error for the task instead of crashing the whole host process.
43
- return "/bin/bash";
58
+ throw new Error("No Bash executable found for Windows Background tasks. Set Pi's shellPath in settings.json or "
59
+ + "PI_BETTER_BACKGROUND_TASKS_SHELL to a working bash.exe. Searched:\n " + [...new Set(tried)].join("\n "));
60
+ }
61
+
62
+ function readWindowsShellSetting(): string | undefined {
63
+ const agentDir = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
64
+ try {
65
+ const settings = JSON.parse(readFileSync(join(agentDir, "settings.json"), "utf8"));
66
+ return typeof settings?.shellPath === "string" ? settings.shellPath : undefined;
67
+ } catch { return undefined; }
68
+ }
69
+
70
+ /** Capture effective session settings before dispatching a Windows launch. */
71
+ export function resolveWindowsLaunchShell(pi: object): string | undefined {
72
+ if (process.platform !== "win32") return undefined;
73
+ const override = process.env.PI_BETTER_BACKGROUND_TASKS_SHELL;
74
+ if (override) return override;
75
+ const settings = (pi as { getSettings?(): { shellPath?: unknown } }).getSettings?.();
76
+ return resolveDefaultShell(typeof settings?.shellPath === "string" ? settings.shellPath : undefined);
44
77
  }
45
78
 
46
79
  /** How long a timed-out process group has to exit on SIGTERM before SIGKILL. */
@@ -66,8 +99,8 @@ export function validateCommandSpec(spec: CommandSpec): void {
66
99
  /** Convert a Windows path to the `/c/...` form MSYS bash resolves in redirections. Exposed for tests and reuse. */
67
100
  export function toMsysPath(path: string): string {
68
101
  const forward = path.replace(/\\/g, "/");
69
- const drive = /^([A-Za-z]):(\/.+)$/.exec(forward);
70
- 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;
71
104
  }
72
105
 
73
106
  /** Single-quote a value for safe literal use in a bash script line. Exposed for tests and reuse. */
@@ -155,7 +188,7 @@ export function parseStepGateFailure(logText: string, id: string): StepGateFailu
155
188
  const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
156
189
  if (!line.startsWith(marker) || !line.endsWith(" ---")) continue;
157
190
  const match = /^--- step gate \[[^\]]+\]: first failing step exit=(-?\d+); shell exit=(-?\d+): (.*) ---$/.exec(line);
158
- if (!match) continue;
191
+ if (!match || match[3] === undefined) continue;
159
192
  const stepExitCode = Number(match[1]);
160
193
  const shellExitCode = Number(match[2]);
161
194
  if (!Number.isInteger(stepExitCode) || stepExitCode === 0) continue;
@@ -507,7 +540,8 @@ export function commandExecution(spec: CommandSpec): { execPath: string; execArg
507
540
  const [command, ...args] = spec.argv!;
508
541
  return { execPath: command!, execArgs: args };
509
542
  }
510
- return { execPath: resolveDefaultShell(), execArgs: [spec.loginShell === false ? "-c" : "-lc", spec.command!] };
543
+ const resolved = process.platform === "win32" ? spec.resolvedWindowsShell : undefined;
544
+ return { execPath: resolved ?? resolveDefaultShell(), execArgs: [spec.loginShell === false ? "-c" : "-lc", spec.command!] };
511
545
  }
512
546
 
513
547
  /** Stdio for a spawned task: stdin is always ignored; stdout/stderr are piped (collected) or ignored (redirected into the log by the child itself). */
@@ -1,6 +1,6 @@
1
1
  // Generated fixed launch domain from packages/pi-better-background-tasks/src/registry.ts. Do not edit directly.
2
2
  import { createHash } from "node:crypto";
3
- import { mkdirSync, readFileSync, readdirSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
4
4
  import { tmpdir } from "node:os";
5
5
  import { join } from "node:path";
6
6
  import { isTerminalStatus } from "./types.domain.mjs";
@@ -65,7 +65,7 @@ export function writeMeta(meta) {
65
65
  indexMeta(meta);
66
66
  for (const listener of metaChangedListeners) {
67
67
  try {
68
- listener();
68
+ listener(meta);
69
69
  }
70
70
  catch { /* best effort */ }
71
71
  }
@@ -163,9 +163,10 @@ export function removeMeta(meta) {
163
163
  metaCache.delete(meta.id);
164
164
  removeIndexEntry(originIndexDir(originOf(meta)), meta.id);
165
165
  removeIndexEntry(originActiveIndexDir(originOf(meta)), meta.id);
166
+ removeIndexEntry(recentPath(originOf(meta)), meta.id);
166
167
  for (const listener of metaChangedListeners) {
167
168
  try {
168
- listener();
169
+ listener(meta);
169
170
  }
170
171
  catch { /* best effort */ }
171
172
  }
@@ -233,6 +234,7 @@ export function listActiveMetasForOrigin(origin) {
233
234
  export function observeMetasForOrigin(origin, activeOnly = true) {
234
235
  const directory = activeOnly ? originActiveIndexDir(origin) : originIndexDir(origin);
235
236
  let ids;
237
+ registryIo.indexDirectoryReads++;
236
238
  try {
237
239
  ids = readdirSync(directory).filter(id => id !== ".initialized");
238
240
  }
@@ -249,6 +251,50 @@ export function observeMetasForOrigin(origin, activeOnly = true) {
249
251
  }).filter((meta) => !!meta && !!meta.callbackOrigin && belongsToOrigin(meta, origin)
250
252
  && (!activeOnly || meta.status === "running")).sort((a, b) => b.startedAt - a.startedAt);
251
253
  }
254
+ const RECENT_LIMIT = 256;
255
+ const RECENT_MS = 30000;
256
+ function recentPath(origin) {
257
+ return join(baseDir(), "by-origin-recent", originKey(origin));
258
+ }
259
+ function recentEntries(origin) {
260
+ const directory = recentPath(origin);
261
+ try {
262
+ registryIo.indexDirectoryReads++;
263
+ const entries = readdirSync(directory).filter(id => !id.startsWith(".")).flatMap(id => {
264
+ try {
265
+ registryIo.indexRevisionChecks++;
266
+ return [{ id, observedAt: statSync(join(directory, id)).mtimeMs }];
267
+ }
268
+ catch (error) {
269
+ if (error.code === "ENOENT")
270
+ return [];
271
+ throw error;
272
+ }
273
+ }).sort((a, b) => b.observedAt - a.observedAt || b.id.localeCompare(a.id));
274
+ return entries.filter(entry => Date.now() - entry.observedAt < RECENT_MS).slice(0, RECENT_LIMIT);
275
+ }
276
+ catch (error) {
277
+ if (error.code === "ENOENT")
278
+ return [];
279
+ throw error;
280
+ }
281
+ }
282
+ export function recentMetaDeadline(origin) {
283
+ return recentEntries(origin).map(entry => entry.observedAt + RECENT_MS);
284
+ }
285
+ /** Exact cooperative source identity; no metadata or historical enumeration. */
286
+ export function observationRevisionForOrigin(origin) {
287
+ return [originActiveIndexDir(origin), recentPath(origin)].map(indexDirectorySignature).join(";");
288
+ }
289
+ /** Bounded cooperative writes, including results written before the first reader. */
290
+ export function observeRecentMetasForOrigin(origin) {
291
+ return recentEntries(origin).map(entry => {
292
+ const record = inspectMeta(entry.id);
293
+ if (record.found && !record.meta)
294
+ throw new Error(`Unverified background task ${entry.id}: ${record.error}`);
295
+ return record.meta;
296
+ }).filter((meta) => !!meta && belongsToOrigin(meta, origin) && meta.dismissedAt === undefined);
297
+ }
252
298
  function readMetaForSweep(id) {
253
299
  const cached = metaCache.get(id);
254
300
  if (cached && isTerminalStatus(cached.status))
@@ -297,6 +343,18 @@ function indexMeta(meta) {
297
343
  writeIndexEntry(activeDirectory, meta.id);
298
344
  else
299
345
  removeIndexEntry(activeDirectory, meta.id);
346
+ const origin = originOf(meta), recentDirectory = recentPath(origin);
347
+ mkdirSync(recentDirectory, { recursive: true });
348
+ // Independent pointers preserve concurrent writers; prune only this bounded
349
+ // recent-write accelerator, never the authoritative metadata or history.
350
+ const candidates = readdirSync(recentDirectory).filter(id => !id.startsWith("."));
351
+ const retained = new Set(recentEntries(origin).filter(entry => entry.id !== meta.id).slice(0, RECENT_LIMIT - 1).map(entry => entry.id));
352
+ for (const id of candidates)
353
+ if (id !== meta.id && !retained.has(id))
354
+ removeIndexEntry(recentDirectory, id);
355
+ const temporary = join(recentDirectory, `.${meta.id}.${process.pid}.next`);
356
+ writeFileSync(temporary, "");
357
+ renameSync(temporary, join(recentDirectory, meta.id));
300
358
  }
301
359
  catch {
302
360
  // Indexes are accelerators; meta.json remains authoritative.
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- import { mkdirSync, readFileSync, readdirSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import type { BackgroundTaskCallbackOrigin, BackgroundTaskMeta } from "./types.js";
@@ -11,7 +11,7 @@ const metaCache = new Map<string, BackgroundTaskMeta>();
11
11
  // cross-process index changes before any cached IDs are reused.
12
12
  const indexIdsCache = new Map<string, { ids: Set<string>; signature: string }>();
13
13
  const initializedIndexes = new Set<string>();
14
- const metaChangedListeners = new Set<() => void>();
14
+ const metaChangedListeners = new Set<(meta?: BackgroundTaskMeta) => void>();
15
15
  const registryIo = { fullDirectoryReads: 0, indexDirectoryReads: 0, metadataFileReads: 0, terminalMetadataFileReads: 0, indexRevisionChecks: 0 };
16
16
 
17
17
  export interface RegistryIoMetrics {
@@ -84,11 +84,11 @@ export function writeMeta(meta: BackgroundTaskMeta): void {
84
84
  metaCache.set(meta.id, meta);
85
85
  indexMeta(meta);
86
86
  for (const listener of metaChangedListeners) {
87
- try { listener(); } catch { /* best effort */ }
87
+ try { listener(meta); } catch { /* best effort */ }
88
88
  }
89
89
  }
90
90
 
91
- export function onMetaChanged(listener: () => void): () => void {
91
+ export function onMetaChanged(listener: (meta?: BackgroundTaskMeta) => void): () => void {
92
92
  metaChangedListeners.add(listener);
93
93
  return () => metaChangedListeners.delete(listener);
94
94
  }
@@ -190,8 +190,9 @@ export function removeMeta(meta: BackgroundTaskMeta): boolean {
190
190
  metaCache.delete(meta.id);
191
191
  removeIndexEntry(originIndexDir(originOf(meta)), meta.id);
192
192
  removeIndexEntry(originActiveIndexDir(originOf(meta)), meta.id);
193
+ removeIndexEntry(recentPath(originOf(meta)), meta.id);
193
194
  for (const listener of metaChangedListeners) {
194
- try { listener(); } catch { /* best effort */ }
195
+ try { listener(meta); } catch { /* best effort */ }
195
196
  }
196
197
  return true;
197
198
  } catch {
@@ -251,6 +252,7 @@ export function listActiveMetasForOrigin(origin: BackgroundTaskCallbackOrigin):
251
252
  export function observeMetasForOrigin(origin: BackgroundTaskCallbackOrigin, activeOnly = true): BackgroundTaskMeta[] {
252
253
  const directory = activeOnly ? originActiveIndexDir(origin) : originIndexDir(origin);
253
254
  let ids: string[];
255
+ registryIo.indexDirectoryReads++;
254
256
  try { ids = readdirSync(directory).filter(id => id !== ".initialized"); }
255
257
  catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; throw error; }
256
258
  return ids.map(id => {
@@ -261,6 +263,42 @@ export function observeMetasForOrigin(origin: BackgroundTaskCallbackOrigin, acti
261
263
  && (!activeOnly || meta.status === "running")).sort((a, b) => b.startedAt - a.startedAt);
262
264
  }
263
265
 
266
+ const RECENT_LIMIT = 256;
267
+ const RECENT_MS = 30000;
268
+ function recentPath(origin: BackgroundTaskCallbackOrigin): string {
269
+ return join(baseDir(), "by-origin-recent", originKey(origin));
270
+ }
271
+ function recentEntries(origin: BackgroundTaskCallbackOrigin): Array<{ id: string; observedAt: number }> {
272
+ const directory = recentPath(origin);
273
+ try {
274
+ registryIo.indexDirectoryReads++;
275
+ const entries = readdirSync(directory).filter(id => !id.startsWith(".")).flatMap(id => {
276
+ try { registryIo.indexRevisionChecks++; return [{ id, observedAt: statSync(join(directory, id)).mtimeMs }]; }
277
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; throw error; }
278
+ }).sort((a, b) => b.observedAt - a.observedAt || b.id.localeCompare(a.id));
279
+ return entries.filter(entry => Date.now() - entry.observedAt < RECENT_MS).slice(0, RECENT_LIMIT);
280
+ } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; throw error; }
281
+ }
282
+
283
+ export function recentMetaDeadline(origin: BackgroundTaskCallbackOrigin): number[] {
284
+ return recentEntries(origin).map(entry => entry.observedAt + RECENT_MS);
285
+ }
286
+
287
+ /** Exact cooperative source identity; no metadata or historical enumeration. */
288
+ export function observationRevisionForOrigin(origin: BackgroundTaskCallbackOrigin): string {
289
+ return [originActiveIndexDir(origin), recentPath(origin)].map(indexDirectorySignature).join(";");
290
+ }
291
+
292
+ /** Bounded cooperative writes, including results written before the first reader. */
293
+ export function observeRecentMetasForOrigin(origin: BackgroundTaskCallbackOrigin): BackgroundTaskMeta[] {
294
+ return recentEntries(origin).map(entry => {
295
+ const record = inspectMeta(entry.id);
296
+ if (record.found && !record.meta) throw new Error(`Unverified background task ${entry.id}: ${record.error}`);
297
+ return record.meta;
298
+ }).filter((meta): meta is BackgroundTaskMeta =>
299
+ !!meta && belongsToOrigin(meta, origin) && meta.dismissedAt === undefined);
300
+ }
301
+
264
302
  function readMetaForSweep(id: string): BackgroundTaskMeta | undefined {
265
303
  const cached = metaCache.get(id);
266
304
  if (cached && isTerminalStatus(cached.status)) return cached;
@@ -308,6 +346,16 @@ function indexMeta(meta: BackgroundTaskMeta): void {
308
346
  const activeDirectory = originActiveIndexDir(originOf(meta));
309
347
  if (meta.status === "running") writeIndexEntry(activeDirectory, meta.id);
310
348
  else removeIndexEntry(activeDirectory, meta.id);
349
+ const origin = originOf(meta), recentDirectory = recentPath(origin);
350
+ mkdirSync(recentDirectory, { recursive: true });
351
+ // Independent pointers preserve concurrent writers; prune only this bounded
352
+ // recent-write accelerator, never the authoritative metadata or history.
353
+ const candidates = readdirSync(recentDirectory).filter(id => !id.startsWith("."));
354
+ const retained = new Set(recentEntries(origin).filter(entry => entry.id !== meta.id).slice(0, RECENT_LIMIT - 1).map(entry => entry.id));
355
+ for (const id of candidates) if (id !== meta.id && !retained.has(id)) removeIndexEntry(recentDirectory, id);
356
+ const temporary = join(recentDirectory, `.${meta.id}.${process.pid}.next`);
357
+ writeFileSync(temporary, "");
358
+ renameSync(temporary, join(recentDirectory, meta.id));
311
359
  } catch {
312
360
  // Indexes are accelerators; meta.json remains authoritative.
313
361
  }
@@ -0,0 +1,16 @@
1
+ // Generated fixed launch domain from packages/pi-better-background-tasks/src/review-settings.ts. Do not edit directly.
2
+ import { readHarnessSetting, updateHarnessSetting } from "./shared-harness-settings.domain.mjs";
3
+ export const DEFAULT_BACKGROUND_REVIEW_INTERVAL_MINUTES = 10;
4
+ const key = "backgroundReviewIntervalMinutes";
5
+ function validMinutes(value) {
6
+ return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 1440;
7
+ }
8
+ export function readBackgroundReviewInterval(seams) {
9
+ const value = readHarnessSetting(key, seams);
10
+ return validMinutes(value) ? value : DEFAULT_BACKGROUND_REVIEW_INTERVAL_MINUTES;
11
+ }
12
+ export function saveBackgroundReviewInterval(minutes, seams) {
13
+ if (!validMinutes(minutes))
14
+ throw new Error("Background review interval must be a whole number from 1 to 1440 minutes.");
15
+ updateHarnessSetting(key, () => minutes, seams);
16
+ }
@@ -0,0 +1,18 @@
1
+ import { readHarnessSetting, updateHarnessSetting, type HarnessSettingsSeams } from "./shared-harness-settings.ts";
2
+
3
+ export const DEFAULT_BACKGROUND_REVIEW_INTERVAL_MINUTES = 10;
4
+ const key = "backgroundReviewIntervalMinutes";
5
+
6
+ function validMinutes(value: unknown): value is number {
7
+ return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 1440;
8
+ }
9
+
10
+ export function readBackgroundReviewInterval(seams?: HarnessSettingsSeams): number {
11
+ const value = readHarnessSetting(key, seams);
12
+ return validMinutes(value) ? value : DEFAULT_BACKGROUND_REVIEW_INTERVAL_MINUTES;
13
+ }
14
+
15
+ export function saveBackgroundReviewInterval(minutes: number, seams?: HarnessSettingsSeams): void {
16
+ if (!validMinutes(minutes)) throw new Error("Background review interval must be a whole number from 1 to 1440 minutes.");
17
+ updateHarnessSetting(key, () => minutes, seams);
18
+ }