pi-better-server 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (278) hide show
  1. package/package.json +4 -1
  2. package/scripts/copy-pi-test-providers.mjs +10 -0
  3. package/scripts/event-publication/README.md +26 -0
  4. package/scripts/event-publication/commit.mjs +21 -0
  5. package/scripts/event-publication/measure.mjs +37 -5
  6. package/scripts/event-publication/writer.mjs +3 -8
  7. package/scripts/measure-full-runtime/probe.mjs +4 -2
  8. package/scripts/measure-full-runtime/recovery-trace-loader.mjs +51 -0
  9. package/scripts/measure-full-runtime/recovery-trace.mjs +16 -0
  10. package/scripts/measure-shared-reads.mjs +2 -1
  11. package/scripts/private-runtime/package-lock.json +18 -0
  12. package/scripts/private-runtime/package.json +4 -1
  13. package/scripts/source-provenance.mjs +2 -2
  14. package/scripts/test-on-pi.sh +2 -9
  15. package/src/handshake.ts +1 -1
  16. package/src/hosted-session.ts +32 -4
  17. package/src/maintenance.ts +35 -7
  18. package/src/registry.ts +28 -4
  19. package/src/runtime/attempt-invalidation.ts +54 -0
  20. package/src/runtime/background-history.ts +151 -45
  21. package/src/runtime/background-policy.ts +9 -4
  22. package/src/runtime/background-tools.ts +131 -23
  23. package/src/runtime/background.ts +351 -68
  24. package/src/runtime/cancellation.ts +28 -7
  25. package/src/runtime/catalog-sources.ts +199 -0
  26. package/src/runtime/catalog.ts +53 -21
  27. package/src/runtime/client.ts +22 -2
  28. package/src/runtime/domain/assignment-inbox.mjs +119 -0
  29. package/src/runtime/domain/assignment-observation.d.mts +1 -1
  30. package/src/runtime/domain/assignment-observation.mjs +43 -35
  31. package/src/runtime/domain/background/process-identity.mjs +20 -2
  32. package/src/runtime/domain/background/process.mjs +3 -3
  33. package/src/runtime/domain/background/registry.mjs +61 -3
  34. package/src/runtime/domain/background/types.mjs +1 -0
  35. package/src/runtime/domain/background-service/adapter-contract.domain.mjs +1 -1
  36. package/src/runtime/domain/background-service/adapter-contract.ts +1 -1
  37. package/src/runtime/domain/background-service/goal-provider.domain.mjs +35 -16
  38. package/src/runtime/domain/background-service/goal-provider.ts +31 -16
  39. package/src/runtime/domain/background-service/index.domain.mjs +6 -9
  40. package/src/runtime/domain/background-service/index.ts +6 -9
  41. package/src/runtime/domain/background-service/managed-authority.domain.mjs +6 -3
  42. package/src/runtime/domain/background-service/managed-authority.ts +5 -3
  43. package/src/runtime/domain/background-service/managed-client.domain.mjs +21 -7
  44. package/src/runtime/domain/background-service/managed-client.ts +20 -7
  45. package/src/runtime/domain/background-service/managed-frontend.domain.mjs +75 -17
  46. package/src/runtime/domain/background-service/managed-frontend.ts +62 -17
  47. package/src/runtime/domain/background-service/navigator-provider.domain.mjs +16 -5
  48. package/src/runtime/domain/background-service/navigator-provider.ts +15 -5
  49. package/src/runtime/domain/background-service/observed-wait-client.domain.mjs +6 -0
  50. package/src/runtime/domain/background-service/observed-wait-client.ts +10 -0
  51. package/src/runtime/domain/background-service/observed-waits.domain.mjs +170 -27
  52. package/src/runtime/domain/background-service/observed-waits.ts +154 -30
  53. package/src/runtime/domain/background-service/process-identity.domain.mjs +20 -2
  54. package/src/runtime/domain/background-service/process-identity.ts +18 -2
  55. package/src/runtime/domain/background-service/process.domain.mjs +3 -3
  56. package/src/runtime/domain/background-service/process.ts +3 -3
  57. package/src/runtime/domain/background-service/registry.domain.mjs +61 -3
  58. package/src/runtime/domain/background-service/registry.ts +53 -5
  59. package/src/runtime/domain/background-service/runtime.domain.mjs +32 -16
  60. package/src/runtime/domain/background-service/runtime.ts +19 -9
  61. package/src/runtime/domain/background-service/sandbox.domain.mjs +14 -15
  62. package/src/runtime/domain/background-service/sandbox.ts +14 -11
  63. package/src/runtime/domain/background-service/shared-callback-batcher.domain.mjs +8 -1
  64. package/src/runtime/domain/background-service/shared-callback-batcher.ts +11 -2
  65. package/src/runtime/domain/background-service/shared-navigator-panels.domain.mjs +24 -2
  66. package/src/runtime/domain/background-service/shared-navigator-panels.ts +26 -4
  67. package/src/runtime/domain/background-service/shared-navigator.domain.mjs +218 -13
  68. package/src/runtime/domain/background-service/shared-navigator.ts +197 -14
  69. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-inbox.mjs +144 -0
  70. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-observation.mjs +53 -41
  71. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
  72. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  73. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
  74. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  75. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
  76. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.ts +14 -3
  77. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
  78. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.ts +5 -3
  79. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.domain.mjs +44 -4
  80. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.ts +50 -2
  81. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
  82. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.ts +12 -0
  83. package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.domain.mjs +2 -0
  84. package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.ts +2 -0
  85. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +42 -21
  86. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +40 -24
  87. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +21 -3
  88. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +34 -8
  89. package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
  90. package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.ts +24 -1
  91. package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.domain.mjs +1 -1
  92. package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.ts +5 -1
  93. package/src/runtime/domain/background-service/shared-sandbox-core.ts +1 -1
  94. package/src/runtime/domain/background-service/shared-work-client.mjs +174 -7
  95. package/src/runtime/domain/background-service/supervisor/generated/process-identity.mjs +20 -2
  96. package/src/runtime/domain/background-service/supervisor/generated/process.mjs +3 -3
  97. package/src/runtime/domain/background-service/task-diagnostics.domain.mjs +1 -1
  98. package/src/runtime/domain/background-service/task-diagnostics.ts +1 -1
  99. package/src/runtime/domain/background-service/tools.domain.mjs +31 -24
  100. package/src/runtime/domain/background-service/tools.ts +41 -38
  101. package/src/runtime/domain/background-service/types.domain.mjs +1 -0
  102. package/src/runtime/domain/background-service/types.ts +3 -1
  103. package/src/runtime/domain/background-service/work-observation.domain.mjs +46 -20
  104. package/src/runtime/domain/background-service/work-observation.ts +46 -19
  105. package/src/runtime/domain/catalog/catalog-store.d.mts +9 -1
  106. package/src/runtime/domain/catalog/catalog-store.mjs +20 -22
  107. package/src/runtime/domain/coordinator/src/assignment-changes.mjs +75 -0
  108. package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +2 -0
  109. package/src/runtime/domain/coordinator/src/background-requests.mjs +11 -2
  110. package/src/runtime/domain/coordinator/src/discovery.mjs +4 -2
  111. package/src/runtime/domain/coordinator/src/operations.mjs +44 -4
  112. package/src/runtime/domain/coordinator/src/result-supervision.mjs +12 -0
  113. package/src/runtime/domain/coordinator/src/rows.mjs +2 -0
  114. package/src/runtime/domain/coordinator/src/schema.mjs +42 -21
  115. package/src/runtime/domain/coordinator/src/store.mjs +21 -3
  116. package/src/runtime/domain/coordinator/src/subagent-launch.mjs +23 -1
  117. package/src/runtime/domain/coordinator/src/types.mjs +1 -1
  118. package/src/runtime/domain/health-observation.d.mts +3 -1
  119. package/src/runtime/domain/health-observation.mjs +189 -190
  120. package/src/runtime/domain/log-cursor.d.mts +2 -0
  121. package/src/runtime/domain/log-cursor.mjs +85 -16
  122. package/src/runtime/domain/parse.d.mts +4 -1
  123. package/src/runtime/domain/parse.mjs +50 -5
  124. package/src/runtime/domain/sandbox-policy/README.md +61 -63
  125. package/src/runtime/domain/sandbox-policy/commands.domain.mjs +11 -8
  126. package/src/runtime/domain/sandbox-policy/commands.ts +12 -7
  127. package/src/runtime/domain/sandbox-policy/index.domain.mjs +53 -9
  128. package/src/runtime/domain/sandbox-policy/index.ts +52 -9
  129. package/src/runtime/domain/sandbox-policy/package.json +1 -1
  130. package/src/runtime/domain/sandbox-policy/permission-settings.domain.mjs +5 -2
  131. package/src/runtime/domain/sandbox-policy/permission-settings.ts +9 -2
  132. package/src/runtime/domain/sandbox-policy/permissions-page.domain.mjs +56 -137
  133. package/src/runtime/domain/sandbox-policy/permissions-page.ts +52 -130
  134. package/src/runtime/domain/sandbox-policy/permissions.domain.mjs +1 -6
  135. package/src/runtime/domain/sandbox-policy/permissions.ts +1 -6
  136. package/src/runtime/domain/sandbox-policy/shared-sandbox-core.ts +1 -1
  137. package/src/runtime/domain/sandbox-policy/shared-task-exec.domain.mjs +14 -1
  138. package/src/runtime/domain/sandbox-policy/shared-task-exec.ts +12 -1
  139. package/src/runtime/domain/sandbox-policy/shared-task-process-identity.domain.mjs +140 -0
  140. package/src/runtime/domain/sandbox-policy/shared-task-process-identity.ts +126 -0
  141. package/src/runtime/domain/sandbox-policy/shared-task-process-list.domain.mjs +3 -2
  142. package/src/runtime/domain/sandbox-policy/shared-task-process-list.ts +8 -2
  143. package/src/runtime/domain/sandbox-policy/shared-task-sandbox.domain.mjs +4 -3
  144. package/src/runtime/domain/sandbox-policy/shared-task-sandbox.ts +5 -3
  145. package/src/runtime/domain/sandbox-policy/shared-task-tools.domain.mjs +8 -5
  146. package/src/runtime/domain/sandbox-policy/shared-task-tools.ts +8 -5
  147. package/src/runtime/domain/subagents/README.md +1 -1
  148. package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +12 -6
  149. package/src/runtime/domain/subagents/assignment-outcomes.ts +11 -5
  150. package/src/runtime/domain/subagents/assignment-report.domain.mjs +87 -24
  151. package/src/runtime/domain/subagents/assignment-report.ts +83 -19
  152. package/src/runtime/domain/subagents/catalog-host-admission.domain.mjs +21 -3
  153. package/src/runtime/domain/subagents/catalog-host-admission.ts +19 -3
  154. package/src/runtime/domain/subagents/catalog-preferences.ts +1 -1
  155. package/src/runtime/domain/subagents/catalog-resolver.domain.mjs +35 -1
  156. package/src/runtime/domain/subagents/catalog-resolver.ts +35 -1
  157. package/src/runtime/domain/subagents/catalog-store.domain.mjs +20 -22
  158. package/src/runtime/domain/subagents/catalog-store.ts +27 -20
  159. package/src/runtime/domain/subagents/child-apply-patch.domain.mjs +13 -0
  160. package/src/runtime/domain/subagents/child-apply-patch.ts +13 -0
  161. package/src/runtime/domain/subagents/child-dependencies.mjs +27 -15
  162. package/src/runtime/domain/subagents/child-operations.domain.mjs +80 -2
  163. package/src/runtime/domain/subagents/child-operations.ts +80 -1
  164. package/src/runtime/domain/subagents/child-preflight.mjs +9 -2
  165. package/src/runtime/domain/subagents/child-process-list.domain.mjs +7 -0
  166. package/src/runtime/domain/subagents/child-process-list.ts +8 -0
  167. package/src/runtime/domain/subagents/config.domain.mjs +49 -2
  168. package/src/runtime/domain/subagents/config.ts +46 -2
  169. package/src/runtime/domain/subagents/continuation-authority.domain.mjs +5 -1
  170. package/src/runtime/domain/subagents/continuation-authority.ts +3 -1
  171. package/src/runtime/domain/subagents/continuation-runtime.domain.mjs +89 -0
  172. package/src/runtime/domain/subagents/continuation-runtime.ts +88 -0
  173. package/src/runtime/domain/subagents/extensions.mjs +11 -13
  174. package/src/runtime/domain/subagents/finalization.domain.mjs +12 -0
  175. package/src/runtime/domain/subagents/finalization.ts +15 -0
  176. package/src/runtime/domain/subagents/goal-provider.domain.mjs +44 -2
  177. package/src/runtime/domain/subagents/goal-provider.ts +44 -2
  178. package/src/runtime/domain/subagents/health-observation.domain.mjs +189 -190
  179. package/src/runtime/domain/subagents/health-observation.ts +43 -48
  180. package/src/runtime/domain/subagents/index.domain.mjs +296 -123
  181. package/src/runtime/domain/subagents/index.ts +257 -98
  182. package/src/runtime/domain/subagents/launch-context.domain.mjs +24 -0
  183. package/src/runtime/domain/subagents/launch-context.ts +23 -0
  184. package/src/runtime/domain/subagents/launch-digest.mjs +6 -0
  185. package/src/runtime/domain/subagents/log-cursor.domain.mjs +85 -16
  186. package/src/runtime/domain/subagents/log-cursor.ts +91 -15
  187. package/src/runtime/domain/subagents/managed-launch-bootstrap.mjs +2 -2
  188. package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +6 -3
  189. package/src/runtime/domain/subagents/managed-launch-client.ts +6 -3
  190. package/src/runtime/domain/subagents/managed-launch-host.domain.mjs +222 -14
  191. package/src/runtime/domain/subagents/managed-launch-host.ts +168 -15
  192. package/src/runtime/domain/subagents/managed-launch-journal.mjs +1 -5
  193. package/src/runtime/domain/subagents/managed-launch-port.ts +4 -0
  194. package/src/runtime/domain/subagents/operation-bridge-types.domain.mjs +27 -2
  195. package/src/runtime/domain/subagents/operation-bridge-types.ts +27 -2
  196. package/src/runtime/domain/subagents/owned-exit.domain.mjs +12 -0
  197. package/src/runtime/domain/subagents/owned-exit.ts +12 -0
  198. package/src/runtime/domain/subagents/package.json +1 -1
  199. package/src/runtime/domain/subagents/parse.domain.mjs +50 -5
  200. package/src/runtime/domain/subagents/parse.ts +48 -6
  201. package/src/runtime/domain/subagents/permission-policy.domain.mjs +32 -8
  202. package/src/runtime/domain/subagents/permission-policy.ts +41 -8
  203. package/src/runtime/domain/subagents/process-identity.mjs +33 -0
  204. package/src/runtime/domain/subagents/registry.domain.mjs +47 -33
  205. package/src/runtime/domain/subagents/registry.ts +54 -33
  206. package/src/runtime/domain/subagents/shared-callback-batcher.domain.mjs +8 -1
  207. package/src/runtime/domain/subagents/shared-callback-batcher.ts +11 -2
  208. package/src/runtime/domain/subagents/shared-catalog.domain.mjs +6 -23
  209. package/src/runtime/domain/subagents/shared-catalog.ts +6 -14
  210. package/src/runtime/domain/subagents/shared-navigator-panels.domain.mjs +24 -2
  211. package/src/runtime/domain/subagents/shared-navigator-panels.ts +26 -4
  212. package/src/runtime/domain/subagents/shared-navigator.domain.mjs +218 -13
  213. package/src/runtime/domain/subagents/shared-navigator.ts +197 -14
  214. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-inbox.mjs +144 -0
  215. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-observation.mjs +53 -41
  216. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
  217. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  218. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
  219. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  220. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
  221. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.ts +14 -3
  222. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
  223. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.ts +5 -3
  224. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.domain.mjs +44 -4
  225. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.ts +50 -2
  226. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
  227. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.ts +12 -0
  228. package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.domain.mjs +2 -0
  229. package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.ts +2 -0
  230. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +42 -21
  231. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +40 -24
  232. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +21 -3
  233. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +34 -8
  234. package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
  235. package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.ts +24 -1
  236. package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.domain.mjs +1 -1
  237. package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.ts +5 -1
  238. package/src/runtime/domain/subagents/shared-sandbox-core.ts +1 -1
  239. package/src/runtime/domain/subagents/shared-task-exec.domain.mjs +14 -1
  240. package/src/runtime/domain/subagents/shared-task-exec.ts +12 -1
  241. package/src/runtime/domain/subagents/shared-task-process-identity.domain.mjs +140 -0
  242. package/src/runtime/domain/subagents/shared-task-process-identity.ts +126 -0
  243. package/src/runtime/domain/subagents/shared-task-process-list.domain.mjs +3 -2
  244. package/src/runtime/domain/subagents/shared-task-process-list.ts +8 -2
  245. package/src/runtime/domain/subagents/shared-task-sandbox.domain.mjs +4 -3
  246. package/src/runtime/domain/subagents/shared-task-sandbox.ts +5 -3
  247. package/src/runtime/domain/subagents/shared-task-tools.domain.mjs +8 -5
  248. package/src/runtime/domain/subagents/shared-task-tools.ts +8 -5
  249. package/src/runtime/domain/subagents/shared-work-client.mjs +174 -7
  250. package/src/runtime/domain/subagents/subagent-tools.domain.mjs +22 -38
  251. package/src/runtime/domain/subagents/subagent-tools.ts +28 -34
  252. package/src/runtime/domain/subagents/task-policy.domain.mjs +1 -1
  253. package/src/runtime/domain/subagents/task-policy.ts +3 -1
  254. package/src/runtime/domain/subagents/timing.domain.mjs +10 -1
  255. package/src/runtime/domain/subagents/timing.ts +10 -1
  256. package/src/runtime/domain/subagents/work-observation.domain.mjs +77 -16
  257. package/src/runtime/domain/subagents/work-observation.ts +71 -16
  258. package/src/runtime/domain/subagents/worker-operations-host.domain.mjs +9 -4
  259. package/src/runtime/domain/subagents/worker-operations-host.ts +12 -4
  260. package/src/runtime/domain/subagents/worker-waits.domain.mjs +89 -35
  261. package/src/runtime/domain/subagents/worker-waits.ts +93 -34
  262. package/src/runtime/health-config.ts +27 -11
  263. package/src/runtime/log-checkpoints.ts +117 -0
  264. package/src/runtime/mutation-store.ts +5 -4
  265. package/src/runtime/queries.ts +25 -2
  266. package/src/runtime/query-executor.ts +149 -28
  267. package/src/runtime/query-worker.mjs +106 -21
  268. package/src/runtime/read-model.ts +846 -120
  269. package/src/runtime/read-watchdog-probe.ts +4 -0
  270. package/src/runtime/result-supervision.ts +188 -16
  271. package/src/runtime/source-watch.ts +175 -0
  272. package/src/runtime/subagent-launch.ts +11 -4
  273. package/src/runtime/work-budget.ts +130 -0
  274. package/src/runtime/work-client.d.mts +8 -0
  275. package/src/runtime/work-client.mjs +150 -7
  276. package/src/server.ts +104 -23
  277. package/src/session-activity.ts +26 -4
  278. package/src/version.ts +1 -1
@@ -1,3 +1,5 @@
1
+ import { getObservedWaitHost, registerObservedWaitClient } from "./observed-wait-client.js";
2
+ export { getObservedWaitHost, registerObservedWaitClient } from "./observed-wait-client.js";
1
3
  /**
2
4
  * Parent-side observed waits: the integration between background tasks, the
3
5
  * detached local supervisor and the durable operation coordinator.
@@ -21,7 +23,7 @@
21
23
  */
22
24
 
23
25
  import { createHash, randomUUID } from "node:crypto";
24
- import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
26
+ import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, watch, type FSWatcher } from "node:fs";
25
27
  import { homedir } from "node:os";
26
28
  import { dirname, isAbsolute, join, relative, resolve } from "node:path";
27
29
 
@@ -71,6 +73,8 @@ import {
71
73
  type SupervisorStartOptions,
72
74
  type SupervisorTaskStatus,
73
75
  } from "./supervisor/index.js";
76
+ import { processGroupAlive } from "./supervisor/identity.js";
77
+ import { readStopRequest } from "./supervisor/store.js";
74
78
  import type { BackgroundTaskCallbackOrigin, CommandSpec, Condition, TaskSandboxProvenance } from "./types.js";
75
79
  import type { SpawnTaskParams, WatchTaskParams } from "./runtime.js";
76
80
 
@@ -148,6 +152,7 @@ export interface DurableProjectionMetrics {
148
152
  export interface DurableTaskChange {
149
153
  readonly sessionId: string;
150
154
  readonly workspace: string;
155
+ readonly branchId?: string | null;
151
156
  }
152
157
 
153
158
  /** A parent launch is always local; remote launches stay on the legacy task route. */
@@ -215,6 +220,7 @@ export interface WaitEvidenceView {
215
220
  export interface WaitDispatchEvent {
216
221
  readonly waitId: string;
217
222
  readonly generation: number;
223
+ readonly parkedAttemptId?: string;
218
224
  readonly owner: OwnerIdentity;
219
225
  /** Parent session origin captured when the supervised task launched. */
220
226
  readonly parentOrigin?: BackgroundTaskCallbackOrigin;
@@ -265,6 +271,7 @@ export type ParentNotifier = (notification: ParentNotification, delivery: Parent
265
271
 
266
272
  export interface WorkerRunScope {
267
273
  readonly runId: string;
274
+ readonly assignmentAttemptId?: string;
268
275
  readonly conversationId: string;
269
276
  readonly workspace: string;
270
277
  readonly authorityReference: string;
@@ -274,6 +281,7 @@ export interface WorkerRunScope {
274
281
 
275
282
  interface RpcRunBinding {
276
283
  readonly runId: string;
284
+ readonly assignmentTaskOwnership: boolean;
277
285
  readonly conversationId: string;
278
286
  readonly attemptId: string;
279
287
  readonly workspace: string;
@@ -414,6 +422,9 @@ export interface StatusView {
414
422
 
415
423
  /** Read-only projection of one supervised durable task for list/navigator/Goal. */
416
424
  export interface DurableTaskProjection {
425
+ readonly parentAgentId?: string;
426
+ readonly parentRecipient?: { sessionId: string; workspace: string; branchId?: string | null };
427
+ readonly readOnly?: boolean;
417
428
  readonly id: string;
418
429
  readonly operationId: string;
419
430
  readonly kind: DurableTaskKind;
@@ -443,7 +454,7 @@ export interface DurableTaskProjection {
443
454
  readonly logPaths: { stdout: string; stderr: string; events: string };
444
455
  readonly waits: readonly WaitView[];
445
456
  readonly sandbox?: TaskSandboxProvenance;
446
- readonly owner: { sessionId: string; workspace: string };
457
+ readonly owner: { sessionId: string; workspace: string; branchId?: string | null };
447
458
  }
448
459
 
449
460
  export interface DurableTaskLogView {
@@ -566,6 +577,8 @@ export interface ObservedWaitHostOptions {
566
577
  beforeParentOperation?: (operation: { operationId: string; taskId: string; token: string }) => void;
567
578
  /** Runtime-owned coordinator handle. The caller retains its lifetime lease. */
568
579
  sharedStore?: Store;
580
+ enterControl?: () => (() => void) | undefined;
581
+ verificationMs?: number;
569
582
  /** Production adapters leave global discovery and terminal import to the server. */
570
583
  serverOwnedResults?: boolean;
571
584
  /** SQLite path. Defaults under the Pi agent directory. */
@@ -645,23 +658,16 @@ export function observedWaitServiceUnavailableReason(pi: unknown): string | unde
645
658
  return events ? serviceErrors.get(events) : undefined;
646
659
  }
647
660
 
648
- const hosts = new WeakMap<object, ObservedWaitHost>();
649
-
650
661
  export function createObservedWaitHost(pi: ExtensionAPI, options: ObservedWaitHostOptions = {}): ObservedWaitHost {
651
- const existing = hosts.get(pi as unknown as object);
662
+ const existing = getObservedWaitHost(pi);
652
663
  if (existing && existing !== undefined) existing.close();
653
664
  const host = new ObservedWaitHost(pi, options);
654
- hosts.set(pi as unknown as object, host);
665
+ registerObservedWaitClient(pi, host);
655
666
  return host;
656
667
  }
657
668
 
658
- export function registerObservedWaitClient(pi: ExtensionAPI, host: ObservedWaitHost): void { hosts.set(pi as object, host); }
659
-
660
- export function getObservedWaitHost(pi: unknown): ObservedWaitHost | undefined {
661
- return pi && typeof pi === "object" ? hosts.get(pi as object) : undefined;
662
- }
663
-
664
669
  interface LaunchContext {
670
+ readonly workerAttemptId?: string;
665
671
  readonly kind: DurableTaskKind;
666
672
  readonly parentOrigin?: BackgroundTaskCallbackOrigin;
667
673
  readonly gated: boolean;
@@ -875,6 +881,43 @@ export class ObservedWaitHost {
875
881
  private readonly pollMs: number;
876
882
  private readonly options: ObservedWaitHostOptions;
877
883
  private timer?: NodeJS.Timeout;
884
+ private changeWatcher?: FSWatcher;
885
+ private changeRepair?: NodeJS.Timeout;
886
+ private changePosition?: { generation: string; seq: number };
887
+ private changeScheduled = false;
888
+ private managedDirty = false;
889
+ private managedAfter = 0;
890
+ private observeManagedChanges() {
891
+ const schedule = () => {
892
+ if (this.closed || this.changeScheduled) return;
893
+ this.changeScheduled = true;
894
+ setImmediate(() => {
895
+ this.changeScheduled = false;
896
+ if (this.closed || !this.store) return;
897
+ try {
898
+ const page = this.store.resultSupervisionChanges(this.changePosition);
899
+ const changed = page.reset || page.seq !== this.changePosition?.seq;
900
+ this.changePosition = { generation: page.generation, seq: page.seq };
901
+ this.managedDirty ||= changed;
902
+ if (this.managedDirty && Date.now() >= this.managedAfter) {
903
+ this.managedDirty = false; this.managedAfter = Date.now() + 1000;
904
+ void this.reconcileNow();
905
+ }
906
+ if (page.more) schedule();
907
+ } catch { /* Existing authority remains unchanged; the bounded feed repair retries. */ }
908
+ });
909
+ };
910
+ this.changeWatcher = watch(dirname(this.storePath), (_event, file) => {
911
+ if (!file || String(file).startsWith("operation-coordinator.sqlite")) schedule();
912
+ });
913
+ this.changeWatcher.on("error", () => { this.changeWatcher?.close(); this.changeWatcher = undefined; });
914
+ const repair = () => {
915
+ if (this.closed) return;
916
+ schedule();
917
+ this.changeRepair = setTimeout(repair, 1000); this.changeRepair.unref();
918
+ };
919
+ repair();
920
+ }
878
921
  private closed = false;
879
922
  private activationAttempted = false;
880
923
  private unavailableReason?: string;
@@ -912,6 +955,7 @@ export class ObservedWaitHost {
912
955
  private continuationError?: string;
913
956
  private readonly launches = new Map<string, LaunchContext>();
914
957
  private readonly localCancels = new Set<string>();
958
+ private assignmentCleanupCursor?: string;
915
959
  private readonly resultHandoffs = new Set<string>();
916
960
  private readonly rpcRuns = new Map<string, RpcRunBinding>();
917
961
  private readonly waitOwners = new Map<string, OwnerIdentity>();
@@ -926,6 +970,7 @@ export class ObservedWaitHost {
926
970
  private discoveryToken?: string;
927
971
  private discoveryRole?: "holder" | "follower";
928
972
  private reconcileInFlight?: Promise<void>;
973
+ private reconcileScope?: object;
929
974
  private authorityPassCache?: Map<string, "live" | "dead" | "unknown">;
930
975
  /** Running operations this follower is currently assigned to supervise. */
931
976
  private readonly followerRunningTasks = new Set<string>();
@@ -933,7 +978,8 @@ export class ObservedWaitHost {
933
978
  private readonly callbackRecoveryScopes = new Map<string, { revision: number; delivery?: string; claims?: string; branch: string }>();
934
979
  private recoveryScopeState() {
935
980
  if (!this.activeOrigin) return this.unscopedCallbackRecovery;
936
- const key = JSON.stringify([this.activeOrigin?.cwd, this.activeOrigin?.sessionId]);
981
+ // Concurrent foregrounds can retain different branch snapshots of one session.
982
+ const key = JSON.stringify([this.activeOrigin.cwd, this.activeOrigin.sessionId, branchIdsOf(this.activeContext!)]);
937
983
  let state = this.callbackRecoveryScopes.get(key);
938
984
  if (!state) {
939
985
  if (this.callbackRecoveryScopes.size >= 128) this.callbackRecoveryScopes.delete(this.callbackRecoveryScopes.keys().next().value!);
@@ -1011,6 +1057,16 @@ export class ObservedWaitHost {
1011
1057
  get usesServerResults(): boolean { return this.options.serverOwnedResults === true; }
1012
1058
  get hasActivated(): boolean { return this.activationAttempted; }
1013
1059
 
1060
+ /** Ready worker continuations can advance; held decisions and unread results cannot. */
1061
+ advancingWaits() {
1062
+ if (!this.store || !this.continuation) return [];
1063
+ return this.store.listWaits({ phase: ["ready", "resuming"], pendingOnly: true })
1064
+ .filter(wait => wait.owner.kind === "worker-conversation")
1065
+ .map(wait => ({ kind: "advancing-wait", id: wait.waitId, generation: wait.generation, owner: wait.owner,
1066
+ lastProgressAt: wait.updatedAt, nextDeadline: wait.updatedAt + (this.options.verificationMs ?? 30000), recovery: "captured-worker-continuation" }))
1067
+ .filter(wait => wait.nextDeadline > Date.now());
1068
+ }
1069
+
1014
1070
  get reason(): string | undefined {
1015
1071
  return this.unavailableReason;
1016
1072
  }
@@ -1053,7 +1109,9 @@ export class ObservedWaitHost {
1053
1109
  void this.reconcileNow();
1054
1110
  this.recoverTerminalNotifications();
1055
1111
  this.terminalRecoveryNeeded = false;
1056
- if (this.pollMs > 0) {
1112
+ if (this.options.serverOwnedResults && this.options.sharedStore) {
1113
+ this.observeManagedChanges();
1114
+ } else if (this.pollMs > 0) {
1057
1115
  this.timer = setInterval(() => { void this.reconcileNow(); }, this.pollMs);
1058
1116
  this.timer.unref?.();
1059
1117
  }
@@ -1064,6 +1122,9 @@ export class ObservedWaitHost {
1064
1122
  this.closed = true;
1065
1123
  HOST_INSTANCE_STATE.closed.add(this.hostId);
1066
1124
  if (this.timer) clearInterval(this.timer);
1125
+ this.changeWatcher?.close(); this.changeWatcher = undefined;
1126
+ if (this.changeRepair) clearTimeout(this.changeRepair);
1127
+ this.changeRepair = undefined; this.changePosition = undefined;
1067
1128
  this.timer = undefined;
1068
1129
  this.releaseDiscoveryAuthority();
1069
1130
  this.releaseSupervisionAuthority();
@@ -1200,13 +1261,26 @@ export class ObservedWaitHost {
1200
1261
 
1201
1262
  /** A deterministic, awaitable reconciliation pass for tests and session activation. */
1202
1263
  async reconcileNow(): Promise<void> {
1203
- if (this.reconcileInFlight) return this.reconcileInFlight;
1204
- const pass = this.reconcilePass();
1264
+ const scope = this.recoveryScopeState();
1265
+ if (this.reconcileInFlight) {
1266
+ const sameScope = this.reconcileScope === scope;
1267
+ await this.reconcileInFlight;
1268
+ // Startup or another foreground's pass cannot verify this scope's recovery.
1269
+ if (!sameScope) return this.reconcileNow();
1270
+ return;
1271
+ }
1272
+ const release = this.options.enterControl?.();
1273
+ if (this.options.enterControl && !release) { this.managedDirty = true; return; }
1274
+ this.reconcileScope = scope;
1275
+ const pass = this.reconcilePass().finally(() => release?.());
1205
1276
  this.reconcileInFlight = pass;
1206
1277
  try {
1207
1278
  await pass;
1208
1279
  } finally {
1209
- if (this.reconcileInFlight === pass) this.reconcileInFlight = undefined;
1280
+ if (this.reconcileInFlight === pass) {
1281
+ this.reconcileInFlight = undefined;
1282
+ this.reconcileScope = undefined;
1283
+ }
1210
1284
  }
1211
1285
  }
1212
1286
 
@@ -1228,6 +1302,7 @@ export class ObservedWaitHost {
1228
1302
  if (role === "holder") {
1229
1303
  this.discoverObservedTasks();
1230
1304
  this.reconcileGlobalRunning();
1305
+ if (discovery!.hasAssignmentTasks) await this.reconcileAssignmentCleanup();
1231
1306
  } else {
1232
1307
  this.reconcileFollowerRunning();
1233
1308
  this.reconcileOwnerChanges();
@@ -1239,6 +1314,35 @@ export class ObservedWaitHost {
1239
1314
  }
1240
1315
  }
1241
1316
 
1317
+ private async reconcileAssignmentCleanup(): Promise<void> {
1318
+ const store = this.requireStore();
1319
+ const [candidate] = store.listAssignmentCleanupOperations(1, this.assignmentCleanupCursor);
1320
+ this.assignmentCleanupCursor = candidate?.operationId;
1321
+ if (!candidate || candidate.resultManaged || this.supervisionAuthority(candidate) !== "self") return;
1322
+ const { taskId, launchToken } = candidate;
1323
+ try {
1324
+ const inspection = this.supervisor.snapshot(taskId);
1325
+ const stop = readStopRequest(this.directory, taskId);
1326
+ if (inspection?.token !== launchToken || (stop && stop.token !== launchToken)) return;
1327
+ if (inspection.terminal) {
1328
+ if (inspection.status !== "lost" && inspection.result?.groupCleanup !== "unproven") return;
1329
+ const pgid = inspection.command?.pgid ?? inspection.command?.pid;
1330
+ if (inspection.cleanup?.groupEmpty === true || (pgid && !processGroupAlive(pgid))) {
1331
+ store.verifyAssignmentCleanup(candidate.operationId, launchToken, candidate.terminalRevision);
1332
+ return;
1333
+ }
1334
+ if (!pgid) return;
1335
+ }
1336
+ if (!this.localCancels.has(taskId)) {
1337
+ this.localCancels.add(taskId);
1338
+ try { await this.supervisor.stop(taskId, { token: launchToken, reason: "owning assignment ended" }); }
1339
+ finally { this.localCancels.delete(taskId); }
1340
+ }
1341
+ } catch (error) {
1342
+ this.options.logger?.(`Assignment cleanup for ${taskId}: ${String(error)}`);
1343
+ }
1344
+ }
1345
+
1242
1346
  private reconcileGlobalRunning(): void {
1243
1347
  const store = this.store;
1244
1348
  if (!store) return;
@@ -1403,7 +1507,7 @@ export class ObservedWaitHost {
1403
1507
  const owner = this.ownerFor(input.ctx);
1404
1508
  const prepared = this.prepareLaunch(input.kind, input.params, "bg_task_spawn", owner, undefined);
1405
1509
  if (this.options.serverOwnedResults) {
1406
- this.assertResultAdmission(prepared.provenance);
1510
+ this.assertManagedResultAdmission(prepared.provenance);
1407
1511
  const client = await this.resultSupervisionClient();
1408
1512
  client.close();
1409
1513
  }
@@ -1440,7 +1544,7 @@ export class ObservedWaitHost {
1440
1544
  // worker-owned operation to the parent's callback.
1441
1545
  this.writeLaunchContext(taskId, launchContext);
1442
1546
  this.launches.set(taskId, launchContext);
1443
- if (this.options.serverOwnedResults) await this.handoffResults([store.getOperation(operationId)!]);
1547
+ if (this.options.serverOwnedResults) await this.handoffResults([store.getOperation(operationId)!], true);
1444
1548
  const started = await this.startSupervisor({
1445
1549
  token, taskId, kind: input.kind, params: input.params, prepared, operationId,
1446
1550
  });
@@ -1781,7 +1885,7 @@ export class ObservedWaitHost {
1781
1885
  // request a repaint.
1782
1886
  if (owner.kind !== "parent-session" || this.activeOwnerRelation(owner) !== "match") return;
1783
1887
  this.invalidateDurableProjection(owner);
1784
- const change = { sessionId: owner.sessionId, workspace: owner.workspace };
1888
+ const change = { sessionId: owner.sessionId, workspace: owner.workspace, branchId: owner.branchId ?? null };
1785
1889
  for (const listener of [...this.durableChangeListeners]) {
1786
1890
  try { listener(change); } catch { /* a projection listener cannot break supervision */ }
1787
1891
  }
@@ -1852,7 +1956,7 @@ export class ObservedWaitHost {
1852
1956
  logPaths: { stdout: pathSet.stdout, stderr: pathSet.stderr, events: pathSet.events },
1853
1957
  waits,
1854
1958
  ...(context?.sandbox ? { sandbox: context.sandbox } : {}),
1855
- owner: { sessionId: operation.owner.sessionId, workspace: operation.owner.workspace },
1959
+ owner: { sessionId: operation.owner.sessionId, workspace: operation.owner.workspace, branchId: operation.owner.branchId ?? null },
1856
1960
  };
1857
1961
  }
1858
1962
 
@@ -2053,6 +2157,12 @@ export class ObservedWaitHost {
2053
2157
  return imported;
2054
2158
  }
2055
2159
 
2160
+ private assertManagedResultAdmission(captured: TaskSandboxProvenance): void {
2161
+ if (captured.policySource !== "no-publisher" && !currentForegroundSandboxPolicy(this.pi)) {
2162
+ throw new Error("permission-unavailable: expected current Background permission source is unavailable");
2163
+ }
2164
+ }
2165
+
2056
2166
  private assertResultAdmission(captured: TaskSandboxProvenance, transferring: ReadonlySet<string> = new Set()): void {
2057
2167
  const discovery = this.requireStore().readDiscoveryClaim(this.discoveryScope);
2058
2168
  if (discovery && discovery.hostId !== this.hostId && this.discoveryHolderState(discovery.hostId) !== "dead") {
@@ -2077,12 +2187,15 @@ export class ObservedWaitHost {
2077
2187
  }
2078
2188
  }
2079
2189
 
2080
- private async handoffResults(operations: readonly OperationRecord[]): Promise<void> {
2190
+ private async handoffResults(operations: readonly OperationRecord[], newManaged = false): Promise<void> {
2081
2191
  const client = await this.resultSupervisionClient();
2082
2192
  try {
2083
2193
  const manager = await client.request("runtime_result_supervision");
2194
+ // Already granted dependencies need no discovery scope transfer. Legacy
2195
+ // holders may keep supervising unrelated work beside server-owned tasks.
2196
+ if (operations.every(operation => this.requireStore().resultSupervision(operation.operationId))) return;
2084
2197
  const discovery = this.requireStore().readDiscoveryClaim(this.discoveryScope);
2085
- if (discovery && discovery.hostId !== this.hostId && this.discoveryHolderState(discovery.hostId) !== "dead") {
2198
+ if (!newManaged && discovery && discovery.hostId !== this.hostId && this.discoveryHolderState(discovery.hostId) !== "dead") {
2086
2199
  throw new Error("permission-unavailable: live or unknown original discovery holder prevents scope handoff");
2087
2200
  }
2088
2201
  const transfers = [];
@@ -2094,7 +2207,8 @@ export class ObservedWaitHost {
2094
2207
  }
2095
2208
  const context = this.launchContext(operation.taskId);
2096
2209
  if (!context?.sandbox || !context.supervisionPolicy || !operation.authorityRef) throw new Error("permission-unavailable: captured Background authority is unavailable");
2097
- this.assertResultAdmission(context.sandbox, transferring);
2210
+ if (newManaged) this.assertManagedResultAdmission(context.sandbox);
2211
+ else this.assertResultAdmission(context.sandbox, transferring);
2098
2212
  const current = currentForegroundSandboxPolicy(this.pi);
2099
2213
  if (context.sandbox.policySource !== "no-publisher" && !current) throw new Error("permission-unavailable: expected current Background permission source is unavailable");
2100
2214
  transfers.push({ operationId: operation.operationId,
@@ -2104,10 +2218,15 @@ export class ObservedWaitHost {
2104
2218
  // Validate the whole batch, then stop admission before the durable CAS.
2105
2219
  for (const transfer of transfers) this.resultHandoffs.add(transfer.operationId);
2106
2220
  try {
2107
- this.requireStore().handoffResultScope({ scope: this.discoveryScope,
2108
- expectedDiscovery: discovery ? { hostId: discovery.hostId, token: discovery.token } : null, grants: transfers });
2109
- this.discoveryToken = undefined;
2110
- this.discoveryRole = "follower";
2221
+ if (newManaged) {
2222
+ // New work grants only its own results; legacy discovery remains live.
2223
+ this.requireStore().handoffResultSupervisions(transfers);
2224
+ } else {
2225
+ this.requireStore().handoffResultScope({ scope: this.discoveryScope,
2226
+ expectedDiscovery: discovery ? { hostId: discovery.hostId, token: discovery.token } : null, grants: transfers });
2227
+ this.discoveryToken = undefined;
2228
+ this.discoveryRole = "follower";
2229
+ }
2111
2230
  } catch (error) {
2112
2231
  // The transaction rolled back; only these uncommitted local fences may reopen.
2113
2232
  for (const transfer of transfers) this.resultHandoffs.delete(transfer.operationId);
@@ -2177,7 +2296,7 @@ export class ObservedWaitHost {
2177
2296
  input.policy,
2178
2297
  run.workspace,
2179
2298
  );
2180
- if (this.options.serverOwnedResults) this.assertResultAdmission(prepared.provenance);
2299
+ if (this.options.serverOwnedResults) this.assertManagedResultAdmission(prepared.provenance);
2181
2300
  const operationId = `op_${randomUUID()}`;
2182
2301
  const token = `launch_${randomUUID()}`;
2183
2302
  const taskId = supervisorTaskIdForToken(token);
@@ -2190,8 +2309,10 @@ export class ObservedWaitHost {
2190
2309
  supervision: this.supervision(),
2191
2310
  authorityRef: authorityReference(`worker:${run.authorityReference}`),
2192
2311
  intentRef: typeof input.params.operation_id === "string" ? input.params.operation_id : null,
2312
+ ...(run.assignmentAttemptId ? { assignmentAttemptId: run.assignmentAttemptId } : {}),
2193
2313
  });
2194
2314
  const launchContext: LaunchContext = {
2315
+ workerAttemptId: run.runId,
2195
2316
  kind: input.kind,
2196
2317
  parentOrigin: this.parentOrigin,
2197
2318
  gated: prepared.gated,
@@ -2206,7 +2327,7 @@ export class ObservedWaitHost {
2206
2327
  };
2207
2328
  this.writeLaunchContext(taskId, launchContext);
2208
2329
  this.launches.set(taskId, launchContext);
2209
- if (this.options.serverOwnedResults) await this.handoffResults([store.getOperation(operationId)!]);
2330
+ if (this.options.serverOwnedResults) await this.handoffResults([store.getOperation(operationId)!], true);
2210
2331
  const started = await this.startSupervisor({
2211
2332
  token, taskId, kind: input.kind, params: input.params, prepared, operationId, assertDispatch: assertWorkerPolicy,
2212
2333
  });
@@ -2562,6 +2683,7 @@ export class ObservedWaitHost {
2562
2683
  : {};
2563
2684
  this.rpcRuns.set(runId, Object.freeze({
2564
2685
  runId,
2686
+ assignmentTaskOwnership: params.assignmentTaskOwnership === true,
2565
2687
  conversationId,
2566
2688
  attemptId,
2567
2689
  workspace,
@@ -2918,6 +3040,7 @@ export class ObservedWaitHost {
2918
3040
  private rpcScope(binding: RpcRunBinding): WorkerRunScope {
2919
3041
  return {
2920
3042
  runId: binding.runId,
3043
+ ...(binding.assignmentTaskOwnership ? { assignmentAttemptId: binding.attemptId } : {}),
2921
3044
  conversationId: binding.conversationId,
2922
3045
  workspace: binding.workspace,
2923
3046
  authorityReference: binding.authorityReference,
@@ -3704,6 +3827,7 @@ export class ObservedWaitHost {
3704
3827
  const outcome = await adapter.onWaitReady({
3705
3828
  waitId: event.waitId,
3706
3829
  generation: event.generation,
3830
+ ...(wait?.park?.attemptId ? { parkedAttemptId: wait.park.attemptId } : {}),
3707
3831
  owner,
3708
3832
  ...(taskId && this.launches.get(taskId)?.parentOrigin
3709
3833
  ? { parentOrigin: this.launches.get(taskId)!.parentOrigin }
@@ -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.
@@ -60,8 +60,8 @@ export function validateCommandSpec(spec) {
60
60
  /** Convert a Windows path to the `/c/...` form MSYS bash resolves in redirections. Exposed for tests and reuse. */
61
61
  export function toMsysPath(path) {
62
62
  const forward = path.replace(/\\/g, "/");
63
- const drive = /^([A-Za-z]):(\/.+)$/.exec(forward);
64
- return drive ? `/${drive[1].toLowerCase()}${drive[2]}` : forward;
63
+ const [, drive, rest] = /^([A-Za-z]):(\/.+)$/.exec(forward) ?? [];
64
+ return drive && rest ? `/${drive.toLowerCase()}${rest}` : forward;
65
65
  }
66
66
  /** Single-quote a value for safe literal use in a bash script line. Exposed for tests and reuse. */
67
67
  export function bashSingleQuote(value) {
@@ -145,7 +145,7 @@ export function parseStepGateFailure(logText, id) {
145
145
  if (!line.startsWith(marker) || !line.endsWith(" ---"))
146
146
  continue;
147
147
  const match = /^--- step gate \[[^\]]+\]: first failing step exit=(-?\d+); shell exit=(-?\d+): (.*) ---$/.exec(line);
148
- if (!match)
148
+ if (!match || match[3] === undefined)
149
149
  continue;
150
150
  const stepExitCode = Number(match[1]);
151
151
  const shellExitCode = Number(match[2]);
@@ -66,8 +66,8 @@ export function validateCommandSpec(spec: CommandSpec): void {
66
66
  /** Convert a Windows path to the `/c/...` form MSYS bash resolves in redirections. Exposed for tests and reuse. */
67
67
  export function toMsysPath(path: string): string {
68
68
  const forward = path.replace(/\\/g, "/");
69
- const drive = /^([A-Za-z]):(\/.+)$/.exec(forward);
70
- return drive ? `/${drive[1].toLowerCase()}${drive[2]}` : forward;
69
+ const [, drive, rest] = /^([A-Za-z]):(\/.+)$/.exec(forward) ?? [];
70
+ return drive && rest ? `/${drive.toLowerCase()}${rest}` : forward;
71
71
  }
72
72
 
73
73
  /** Single-quote a value for safe literal use in a bash script line. Exposed for tests and reuse. */
@@ -155,7 +155,7 @@ export function parseStepGateFailure(logText: string, id: string): StepGateFailu
155
155
  const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
156
156
  if (!line.startsWith(marker) || !line.endsWith(" ---")) continue;
157
157
  const match = /^--- step gate \[[^\]]+\]: first failing step exit=(-?\d+); shell exit=(-?\d+): (.*) ---$/.exec(line);
158
- if (!match) continue;
158
+ if (!match || match[3] === undefined) continue;
159
159
  const stepExitCode = Number(match[1]);
160
160
  const shellExitCode = Number(match[2]);
161
161
  if (!Number.isInteger(stepExitCode) || stepExitCode === 0) continue;
@@ -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.