pi-better-server 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (340) hide show
  1. package/package.json +7 -3
  2. package/scripts/copy-pi-test-providers.mjs +10 -0
  3. package/scripts/event-publication/README.md +26 -0
  4. package/scripts/event-publication/commit.mjs +21 -0
  5. package/scripts/event-publication/measure.mjs +37 -5
  6. package/scripts/event-publication/writer.mjs +3 -8
  7. package/scripts/measure-full-runtime/frontend.ts +10 -2
  8. package/scripts/measure-full-runtime/probe.mjs +4 -2
  9. package/scripts/measure-full-runtime/recovery-trace-loader.mjs +51 -0
  10. package/scripts/measure-full-runtime/recovery-trace.mjs +16 -0
  11. package/scripts/measure-full-runtime.mjs +2 -0
  12. package/scripts/measure-shared-reads.mjs +2 -1
  13. package/scripts/private-runtime/package-lock.json +18 -0
  14. package/scripts/private-runtime/package.json +4 -1
  15. package/scripts/source-provenance.mjs +2 -2
  16. package/scripts/test-on-pi.sh +2 -9
  17. package/src/handshake.ts +1 -1
  18. package/src/hosted-session.ts +32 -4
  19. package/src/maintenance.ts +35 -7
  20. package/src/registry.ts +28 -4
  21. package/src/runtime/attempt-invalidation.ts +54 -0
  22. package/src/runtime/background-history.ts +151 -45
  23. package/src/runtime/background-policy.ts +9 -4
  24. package/src/runtime/background-tools.ts +181 -27
  25. package/src/runtime/background.ts +365 -70
  26. package/src/runtime/cancellation.ts +28 -7
  27. package/src/runtime/catalog-sources.ts +199 -0
  28. package/src/runtime/catalog.ts +53 -21
  29. package/src/runtime/client.ts +22 -2
  30. package/src/runtime/domain/assignment-inbox.mjs +119 -0
  31. package/src/runtime/domain/assignment-observation.d.mts +1 -1
  32. package/src/runtime/domain/assignment-observation.mjs +43 -35
  33. package/src/runtime/domain/background/process-identity.mjs +20 -2
  34. package/src/runtime/domain/background/process.mjs +52 -14
  35. package/src/runtime/domain/background/registry.mjs +61 -3
  36. package/src/runtime/domain/background/supervisor/store.mjs +3 -3
  37. package/src/runtime/domain/background/supervisor/supervisor.mjs +9 -3
  38. package/src/runtime/domain/background/types.mjs +1 -0
  39. package/src/runtime/domain/background-service/adapter-contract.domain.mjs +1 -1
  40. package/src/runtime/domain/background-service/adapter-contract.ts +1 -1
  41. package/src/runtime/domain/background-service/goal-provider.domain.mjs +35 -16
  42. package/src/runtime/domain/background-service/goal-provider.ts +31 -16
  43. package/src/runtime/domain/background-service/index.domain.mjs +25 -9
  44. package/src/runtime/domain/background-service/index.ts +25 -9
  45. package/src/runtime/domain/background-service/managed-authority.domain.mjs +6 -3
  46. package/src/runtime/domain/background-service/managed-authority.ts +5 -3
  47. package/src/runtime/domain/background-service/managed-client.domain.mjs +21 -7
  48. package/src/runtime/domain/background-service/managed-client.ts +20 -7
  49. package/src/runtime/domain/background-service/managed-frontend.domain.mjs +159 -19
  50. package/src/runtime/domain/background-service/managed-frontend.ts +135 -19
  51. package/src/runtime/domain/background-service/navigator-provider.domain.mjs +21 -5
  52. package/src/runtime/domain/background-service/navigator-provider.ts +19 -5
  53. package/src/runtime/domain/background-service/observed-wait-client.domain.mjs +6 -0
  54. package/src/runtime/domain/background-service/observed-wait-client.ts +10 -0
  55. package/src/runtime/domain/background-service/observed-waits.domain.mjs +372 -57
  56. package/src/runtime/domain/background-service/observed-waits.ts +321 -53
  57. package/src/runtime/domain/background-service/process-identity.domain.mjs +20 -2
  58. package/src/runtime/domain/background-service/process-identity.ts +18 -2
  59. package/src/runtime/domain/background-service/process.domain.mjs +52 -14
  60. package/src/runtime/domain/background-service/process.ts +48 -14
  61. package/src/runtime/domain/background-service/registry.domain.mjs +61 -3
  62. package/src/runtime/domain/background-service/registry.ts +53 -5
  63. package/src/runtime/domain/background-service/review-settings.domain.mjs +16 -0
  64. package/src/runtime/domain/background-service/review-settings.ts +18 -0
  65. package/src/runtime/domain/background-service/runtime.domain.mjs +40 -86
  66. package/src/runtime/domain/background-service/runtime.ts +27 -82
  67. package/src/runtime/domain/background-service/sandbox.domain.mjs +14 -15
  68. package/src/runtime/domain/background-service/sandbox.ts +14 -11
  69. package/src/runtime/domain/background-service/shared-callback-batcher.domain.mjs +8 -1
  70. package/src/runtime/domain/background-service/shared-callback-batcher.ts +11 -2
  71. package/src/runtime/domain/background-service/shared-navigator-panels.domain.mjs +24 -2
  72. package/src/runtime/domain/background-service/shared-navigator-panels.ts +26 -4
  73. package/src/runtime/domain/background-service/shared-navigator.domain.mjs +273 -41
  74. package/src/runtime/domain/background-service/shared-navigator.ts +244 -40
  75. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-inbox.mjs +144 -0
  76. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-observation.mjs +53 -41
  77. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
  78. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  79. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
  80. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  81. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
  82. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.ts +14 -3
  83. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
  84. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.ts +5 -3
  85. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.domain.mjs +44 -4
  86. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.ts +50 -2
  87. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  88. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.ts +9 -0
  89. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
  90. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.ts +12 -0
  91. package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.domain.mjs +2 -0
  92. package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.ts +2 -0
  93. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +42 -21
  94. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +40 -24
  95. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +26 -4
  96. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +40 -8
  97. package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
  98. package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.ts +24 -1
  99. package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.domain.mjs +1 -1
  100. package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.ts +5 -1
  101. package/src/runtime/domain/background-service/shared-sandbox-core.ts +1 -1
  102. package/src/runtime/domain/background-service/shared-work-client.mjs +174 -7
  103. package/src/runtime/domain/background-service/stall.domain.mjs +5 -3
  104. package/src/runtime/domain/background-service/stall.ts +7 -4
  105. package/src/runtime/domain/background-service/supervised-progress.domain.mjs +42 -0
  106. package/src/runtime/domain/background-service/supervised-progress.ts +43 -0
  107. package/src/runtime/domain/background-service/supervisor/README.md +1 -4
  108. package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +1 -0
  109. package/src/runtime/domain/background-service/supervisor/generated/process-identity.mjs +20 -2
  110. package/src/runtime/domain/background-service/supervisor/generated/process.mjs +52 -14
  111. package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +47 -4
  112. package/src/runtime/domain/background-service/supervisor/generated/store.mjs +3 -3
  113. package/src/runtime/domain/background-service/supervisor/generated/watch-fingerprint.mjs +69 -0
  114. package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +47 -4
  115. package/src/runtime/domain/background-service/supervisor/runner.ts +38 -3
  116. package/src/runtime/domain/background-service/supervisor/store.domain.mjs +3 -3
  117. package/src/runtime/domain/background-service/supervisor/store.ts +3 -3
  118. package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +9 -3
  119. package/src/runtime/domain/background-service/supervisor/supervisor.ts +6 -3
  120. package/src/runtime/domain/background-service/task-diagnostics.domain.mjs +1 -1
  121. package/src/runtime/domain/background-service/task-diagnostics.ts +1 -1
  122. package/src/runtime/domain/background-service/tools.domain.mjs +53 -40
  123. package/src/runtime/domain/background-service/tools.ts +67 -54
  124. package/src/runtime/domain/background-service/types.domain.mjs +1 -0
  125. package/src/runtime/domain/background-service/types.ts +7 -3
  126. package/src/runtime/domain/background-service/watch-fingerprint.domain.mjs +67 -0
  127. package/src/runtime/domain/background-service/watch-fingerprint.ts +70 -0
  128. package/src/runtime/domain/background-service/work-observation.domain.mjs +46 -20
  129. package/src/runtime/domain/background-service/work-observation.ts +46 -19
  130. package/src/runtime/domain/catalog/catalog-store.d.mts +9 -1
  131. package/src/runtime/domain/catalog/catalog-store.mjs +20 -22
  132. package/src/runtime/domain/coordinator/src/assignment-changes.mjs +75 -0
  133. package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +2 -0
  134. package/src/runtime/domain/coordinator/src/background-requests.mjs +11 -2
  135. package/src/runtime/domain/coordinator/src/discovery.mjs +4 -2
  136. package/src/runtime/domain/coordinator/src/operations.mjs +44 -4
  137. package/src/runtime/domain/coordinator/src/outbox.mjs +7 -0
  138. package/src/runtime/domain/coordinator/src/result-supervision.mjs +12 -0
  139. package/src/runtime/domain/coordinator/src/rows.mjs +2 -0
  140. package/src/runtime/domain/coordinator/src/schema.mjs +42 -21
  141. package/src/runtime/domain/coordinator/src/store.mjs +26 -4
  142. package/src/runtime/domain/coordinator/src/subagent-launch.mjs +23 -1
  143. package/src/runtime/domain/coordinator/src/types.mjs +1 -1
  144. package/src/runtime/domain/health-observation.d.mts +3 -1
  145. package/src/runtime/domain/health-observation.mjs +189 -190
  146. package/src/runtime/domain/log-cursor.d.mts +2 -0
  147. package/src/runtime/domain/log-cursor.mjs +85 -16
  148. package/src/runtime/domain/log-paths.mjs +8 -1
  149. package/src/runtime/domain/parse.d.mts +4 -1
  150. package/src/runtime/domain/parse.mjs +58 -9
  151. package/src/runtime/domain/sandbox-policy/README.md +63 -65
  152. package/src/runtime/domain/sandbox-policy/commands.domain.mjs +11 -8
  153. package/src/runtime/domain/sandbox-policy/commands.ts +12 -7
  154. package/src/runtime/domain/sandbox-policy/index.domain.mjs +53 -9
  155. package/src/runtime/domain/sandbox-policy/index.ts +52 -9
  156. package/src/runtime/domain/sandbox-policy/package.json +1 -1
  157. package/src/runtime/domain/sandbox-policy/permission-settings.domain.mjs +5 -2
  158. package/src/runtime/domain/sandbox-policy/permission-settings.ts +9 -2
  159. package/src/runtime/domain/sandbox-policy/permissions-page.domain.mjs +56 -137
  160. package/src/runtime/domain/sandbox-policy/permissions-page.ts +52 -130
  161. package/src/runtime/domain/sandbox-policy/permissions.domain.mjs +1 -6
  162. package/src/runtime/domain/sandbox-policy/permissions.ts +1 -6
  163. package/src/runtime/domain/sandbox-policy/shared-sandbox-core.ts +1 -1
  164. package/src/runtime/domain/sandbox-policy/shared-task-exec.domain.mjs +14 -1
  165. package/src/runtime/domain/sandbox-policy/shared-task-exec.ts +12 -1
  166. package/src/runtime/domain/sandbox-policy/shared-task-process-identity.domain.mjs +140 -0
  167. package/src/runtime/domain/sandbox-policy/shared-task-process-identity.ts +126 -0
  168. package/src/runtime/domain/sandbox-policy/shared-task-process-list.domain.mjs +3 -2
  169. package/src/runtime/domain/sandbox-policy/shared-task-process-list.ts +8 -2
  170. package/src/runtime/domain/sandbox-policy/shared-task-sandbox.domain.mjs +4 -3
  171. package/src/runtime/domain/sandbox-policy/shared-task-sandbox.ts +5 -3
  172. package/src/runtime/domain/sandbox-policy/shared-task-tools.domain.mjs +8 -5
  173. package/src/runtime/domain/sandbox-policy/shared-task-tools.ts +8 -5
  174. package/src/runtime/domain/session-store.mjs +7 -0
  175. package/src/runtime/domain/subagents/README.md +13 -11
  176. package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +10 -7
  177. package/src/runtime/domain/subagents/assignment-outcomes.ts +9 -6
  178. package/src/runtime/domain/subagents/assignment-report.domain.mjs +109 -24
  179. package/src/runtime/domain/subagents/assignment-report.ts +103 -19
  180. package/src/runtime/domain/subagents/batch.mjs +13 -5
  181. package/src/runtime/domain/subagents/catalog-host-admission.domain.mjs +21 -3
  182. package/src/runtime/domain/subagents/catalog-host-admission.ts +19 -3
  183. package/src/runtime/domain/subagents/catalog-preferences.ts +1 -1
  184. package/src/runtime/domain/subagents/catalog-resolver.domain.mjs +35 -1
  185. package/src/runtime/domain/subagents/catalog-resolver.ts +35 -1
  186. package/src/runtime/domain/subagents/catalog-store.domain.mjs +20 -22
  187. package/src/runtime/domain/subagents/catalog-store.ts +27 -20
  188. package/src/runtime/domain/subagents/child-apply-patch.domain.mjs +13 -0
  189. package/src/runtime/domain/subagents/child-apply-patch.ts +13 -0
  190. package/src/runtime/domain/subagents/child-dependencies.mjs +27 -15
  191. package/src/runtime/domain/subagents/child-operations.domain.mjs +80 -2
  192. package/src/runtime/domain/subagents/child-operations.ts +80 -1
  193. package/src/runtime/domain/subagents/child-preflight.mjs +9 -2
  194. package/src/runtime/domain/subagents/child-process-list.domain.mjs +7 -0
  195. package/src/runtime/domain/subagents/child-process-list.ts +8 -0
  196. package/src/runtime/domain/subagents/cleanup.domain.mjs +11 -2
  197. package/src/runtime/domain/subagents/cleanup.ts +10 -2
  198. package/src/runtime/domain/subagents/config.domain.mjs +54 -2
  199. package/src/runtime/domain/subagents/config.ts +53 -3
  200. package/src/runtime/domain/subagents/continuation-authority.domain.mjs +5 -1
  201. package/src/runtime/domain/subagents/continuation-authority.ts +3 -1
  202. package/src/runtime/domain/subagents/continuation-runtime.domain.mjs +89 -0
  203. package/src/runtime/domain/subagents/continuation-runtime.ts +88 -0
  204. package/src/runtime/domain/subagents/continuation.domain.mjs +4 -2
  205. package/src/runtime/domain/subagents/continuation.ts +4 -2
  206. package/src/runtime/domain/subagents/extensions.mjs +11 -13
  207. package/src/runtime/domain/subagents/failures.domain.mjs +11 -2
  208. package/src/runtime/domain/subagents/failures.ts +10 -2
  209. package/src/runtime/domain/subagents/finalization.domain.mjs +16 -1
  210. package/src/runtime/domain/subagents/finalization.ts +21 -1
  211. package/src/runtime/domain/subagents/goal-provider.domain.mjs +44 -2
  212. package/src/runtime/domain/subagents/goal-provider.ts +44 -2
  213. package/src/runtime/domain/subagents/health-observation.domain.mjs +189 -190
  214. package/src/runtime/domain/subagents/health-observation.ts +43 -48
  215. package/src/runtime/domain/subagents/index.domain.mjs +457 -182
  216. package/src/runtime/domain/subagents/index.ts +417 -155
  217. package/src/runtime/domain/subagents/isolated-workspace.domain.mjs +515 -0
  218. package/src/runtime/domain/subagents/isolated-workspace.ts +557 -0
  219. package/src/runtime/domain/subagents/launch-context.domain.mjs +24 -0
  220. package/src/runtime/domain/subagents/launch-context.ts +23 -0
  221. package/src/runtime/domain/subagents/launch-digest.mjs +6 -0
  222. package/src/runtime/domain/subagents/list.mjs +2 -2
  223. package/src/runtime/domain/subagents/log-cursor.domain.mjs +85 -16
  224. package/src/runtime/domain/subagents/log-cursor.ts +91 -15
  225. package/src/runtime/domain/subagents/managed-launch-bootstrap.mjs +2 -2
  226. package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +27 -7
  227. package/src/runtime/domain/subagents/managed-launch-client.ts +28 -8
  228. package/src/runtime/domain/subagents/managed-launch-host.domain.mjs +222 -14
  229. package/src/runtime/domain/subagents/managed-launch-host.ts +168 -15
  230. package/src/runtime/domain/subagents/managed-launch-journal.mjs +1 -5
  231. package/src/runtime/domain/subagents/managed-launch-port.ts +4 -0
  232. package/src/runtime/domain/subagents/operation-bridge-types.domain.mjs +27 -2
  233. package/src/runtime/domain/subagents/operation-bridge-types.ts +27 -2
  234. package/src/runtime/domain/subagents/output-payload.domain.mjs +24 -9
  235. package/src/runtime/domain/subagents/output-payload.ts +26 -12
  236. package/src/runtime/domain/subagents/owned-exit.domain.mjs +12 -0
  237. package/src/runtime/domain/subagents/owned-exit.ts +12 -0
  238. package/src/runtime/domain/subagents/package.json +4 -2
  239. package/src/runtime/domain/subagents/parse.domain.mjs +58 -9
  240. package/src/runtime/domain/subagents/parse.ts +57 -10
  241. package/src/runtime/domain/subagents/permission-policy.domain.mjs +32 -8
  242. package/src/runtime/domain/subagents/permission-policy.ts +41 -8
  243. package/src/runtime/domain/subagents/process-identity.mjs +33 -0
  244. package/src/runtime/domain/subagents/registry.domain.mjs +71 -51
  245. package/src/runtime/domain/subagents/registry.ts +77 -38
  246. package/src/runtime/domain/subagents/retained-result.domain.mjs +56 -0
  247. package/src/runtime/domain/subagents/retained-result.ts +65 -0
  248. package/src/runtime/domain/subagents/session-selection.domain.mjs +3 -1
  249. package/src/runtime/domain/subagents/session-selection.ts +2 -1
  250. package/src/runtime/domain/subagents/session-store.domain.mjs +7 -0
  251. package/src/runtime/domain/subagents/session-store.ts +9 -0
  252. package/src/runtime/domain/subagents/settings-page.domain.mjs +151 -107
  253. package/src/runtime/domain/subagents/settings-page.ts +147 -108
  254. package/src/runtime/domain/subagents/shared-callback-batcher.domain.mjs +8 -1
  255. package/src/runtime/domain/subagents/shared-callback-batcher.ts +11 -2
  256. package/src/runtime/domain/subagents/shared-catalog.domain.mjs +28 -29
  257. package/src/runtime/domain/subagents/shared-catalog.ts +29 -21
  258. package/src/runtime/domain/subagents/shared-navigator-panels.domain.mjs +24 -2
  259. package/src/runtime/domain/subagents/shared-navigator-panels.ts +26 -4
  260. package/src/runtime/domain/subagents/shared-navigator.domain.mjs +273 -41
  261. package/src/runtime/domain/subagents/shared-navigator.ts +244 -40
  262. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-inbox.mjs +144 -0
  263. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-observation.mjs +53 -41
  264. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
  265. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  266. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
  267. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  268. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
  269. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.ts +14 -3
  270. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
  271. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.ts +5 -3
  272. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.domain.mjs +44 -4
  273. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.ts +50 -2
  274. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  275. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.ts +9 -0
  276. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
  277. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.ts +12 -0
  278. package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.domain.mjs +2 -0
  279. package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.ts +2 -0
  280. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +42 -21
  281. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +40 -24
  282. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +26 -4
  283. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +40 -8
  284. package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
  285. package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.ts +24 -1
  286. package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.domain.mjs +1 -1
  287. package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.ts +5 -1
  288. package/src/runtime/domain/subagents/shared-sandbox-core.ts +1 -1
  289. package/src/runtime/domain/subagents/shared-task-exec.domain.mjs +14 -1
  290. package/src/runtime/domain/subagents/shared-task-exec.ts +12 -1
  291. package/src/runtime/domain/subagents/shared-task-process-identity.domain.mjs +140 -0
  292. package/src/runtime/domain/subagents/shared-task-process-identity.ts +126 -0
  293. package/src/runtime/domain/subagents/shared-task-process-list.domain.mjs +3 -2
  294. package/src/runtime/domain/subagents/shared-task-process-list.ts +8 -2
  295. package/src/runtime/domain/subagents/shared-task-sandbox.domain.mjs +4 -3
  296. package/src/runtime/domain/subagents/shared-task-sandbox.ts +5 -3
  297. package/src/runtime/domain/subagents/shared-task-tools.domain.mjs +8 -5
  298. package/src/runtime/domain/subagents/shared-task-tools.ts +8 -5
  299. package/src/runtime/domain/subagents/shared-work-client.mjs +174 -7
  300. package/src/runtime/domain/subagents/subagent-tools.domain.mjs +22 -38
  301. package/src/runtime/domain/subagents/subagent-tools.ts +28 -34
  302. package/src/runtime/domain/subagents/task-guard.domain.mjs +14 -1
  303. package/src/runtime/domain/subagents/task-guard.ts +13 -1
  304. package/src/runtime/domain/subagents/task-policy.domain.mjs +3 -2
  305. package/src/runtime/domain/subagents/task-policy.ts +8 -2
  306. package/src/runtime/domain/subagents/timing.domain.mjs +10 -1
  307. package/src/runtime/domain/subagents/timing.ts +10 -1
  308. package/src/runtime/domain/subagents/tools.domain.mjs +4 -8
  309. package/src/runtime/domain/subagents/tools.ts +4 -7
  310. package/src/runtime/domain/subagents/work-observation.domain.mjs +102 -17
  311. package/src/runtime/domain/subagents/work-observation.ts +91 -17
  312. package/src/runtime/domain/subagents/worker-operations-host.domain.mjs +9 -4
  313. package/src/runtime/domain/subagents/worker-operations-host.ts +12 -4
  314. package/src/runtime/domain/subagents/worker-waits.domain.mjs +89 -35
  315. package/src/runtime/domain/subagents/worker-waits.ts +93 -34
  316. package/src/runtime/domain/subagents/workspace-files.domain.mjs +103 -0
  317. package/src/runtime/domain/subagents/workspace-files.ts +114 -0
  318. package/src/runtime/domain/subagents/workspace-scope.domain.d.mts +38 -0
  319. package/src/runtime/domain/subagents/workspace-scope.domain.mjs +5 -0
  320. package/src/runtime/domain/subagents/workspace-scope.ts +6 -0
  321. package/src/runtime/domain/subagents/worktree-feedback.domain.mjs +55 -0
  322. package/src/runtime/domain/subagents/worktree-feedback.ts +77 -0
  323. package/src/runtime/health-config.ts +27 -11
  324. package/src/runtime/log-checkpoints.ts +117 -0
  325. package/src/runtime/mutation-store.ts +5 -4
  326. package/src/runtime/queries.ts +25 -2
  327. package/src/runtime/query-executor.ts +149 -28
  328. package/src/runtime/query-worker.mjs +106 -21
  329. package/src/runtime/read-model.ts +849 -121
  330. package/src/runtime/read-watchdog-probe.ts +4 -0
  331. package/src/runtime/result-supervision.ts +188 -16
  332. package/src/runtime/root.ts +5 -2
  333. package/src/runtime/source-watch.ts +175 -0
  334. package/src/runtime/subagent-launch.ts +11 -4
  335. package/src/runtime/work-budget.ts +130 -0
  336. package/src/runtime/work-client.d.mts +8 -0
  337. package/src/runtime/work-client.mjs +150 -7
  338. package/src/server.ts +104 -23
  339. package/src/session-activity.ts +26 -4
  340. package/src/version.ts +1 -1
@@ -0,0 +1,33 @@
1
+ // Generated fixed launch domain from packages/pi-better-subagents/process-identity.mjs. Do not edit directly.
2
+ import { execFileSync } from "node:child_process";
3
+ import { readFileSync } from "node:fs";
4
+ /** Best-effort process start identity. Unavailable does not prove the pid is dead. */
5
+ export function processStartToken(pid) {
6
+ if (process.platform === "linux") {
7
+ try {
8
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf-8");
9
+ const close = stat.lastIndexOf(") ");
10
+ if (close >= 0) {
11
+ const starttime = stat.slice(close + 2).split(" ")[19];
12
+ if (starttime && /^\d+$/.test(starttime))
13
+ return starttime;
14
+ }
15
+ }
16
+ catch (error) {
17
+ if (error.code !== "ENOENT" && error.code !== "EACCES")
18
+ return undefined;
19
+ }
20
+ }
21
+ try {
22
+ const out = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], {
23
+ encoding: "utf-8",
24
+ timeout: 1_000,
25
+ env: { ...process.env, LC_ALL: "C" },
26
+ stdio: ["ignore", "pipe", "ignore"],
27
+ }).trim().replace(/\s+/g, " ");
28
+ return out === "" ? undefined : out;
29
+ }
30
+ catch {
31
+ return undefined;
32
+ }
33
+ }
@@ -1,26 +1,17 @@
1
1
  // Generated fixed launch domain from packages/pi-better-subagents/registry.ts. Do not edit directly.
2
- /**
3
- * Run registry — durable metadata for each spawned subagent.
4
- *
5
- * The authoritative record for every run is a `meta.json` sidecar on disk, so
6
- * `list` / `output` / `result` keep working across foreground turns, `/reload`,
7
- * and even a full pi restart. In-memory state holds only the live exit handlers
8
- * for runs this process spawned.
9
- *
10
- * Catalog launches may attach an optional immutable `catalog` snapshot to that
11
- * same record. Display-label reservations live under `{baseDir()}/labels`
12
- * (see catalog-identity.ts). They are not a second registry, and removing a
13
- * run directory does not delete them.
14
- */
2
+ import { reclaimWorkspace } from "./isolated-workspace.domain.mjs";
3
+ import { retainResult } from "./retained-result.domain.mjs";
15
4
  import { assignmentRetainsEvidence } from "./assignment-outcomes.domain.mjs";
16
- import { execFileSync } from "node:child_process";
5
+ import { processStartToken } from "./process-identity.mjs";
6
+ export { processStartToken } from "./process-identity.mjs";
17
7
  import { createHash, randomBytes } from "node:crypto";
18
8
  import { closeSync, existsSync, fsyncSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
19
9
  import { createRequire } from "node:module";
10
+ import { readFile, readdir } from "node:fs/promises";
20
11
  import { tmpdir } from "node:os";
21
12
  import { basename, dirname, join } from "node:path";
22
13
  import { processExists } from "./spawn.domain.mjs";
23
- import { archiveCompletedAttempt, durableSessionsDir, listArchivedAttempts, readArchivedAttempt, recordArchiveStatusTombstone, } from "./session-store.domain.mjs";
14
+ import { archiveCompletedAttempt, durableSessionsDir, listArchivedAttempts, readArchivedAttempt, recordArchiveStatusTombstone, retainedLogPath, } from "./session-store.domain.mjs";
24
15
  import { failureIdentity, observeFailures, readFailureState } from "./shared-failure-observations.domain.mjs";
25
16
  /**
26
17
  * True when coherent child-exit evidence may finalize a run in this status.
@@ -59,6 +50,12 @@ export function runDir(id) {
59
50
  export function logPathFor(id) {
60
51
  return join(runDir(id), "output.log");
61
52
  }
53
+ export function evidenceLogPath(id) {
54
+ const live = logPathFor(id);
55
+ if (existsSync(live) || existsSync(runDir(id)))
56
+ return live;
57
+ return retainedLogPath(id) ?? live;
58
+ }
62
59
  export function promptPathFor(id) {
63
60
  return join(runDir(id), "prompt.md");
64
61
  }
@@ -172,6 +169,33 @@ export function listParkRecordCandidates(metas = listMetas()) {
172
169
  return metas.filter((meta) => meta.park !== undefined
173
170
  || (volatileIds.has(meta.id) && existsSync(parkRecordPath(meta.id))));
174
171
  }
172
+ /** Read recovery sidecars in batches so a large registry does not block socket replies. */
173
+ export async function* scanParkRecords(metas = listMetas()) {
174
+ const runs = join(baseDir(), "runs");
175
+ const volatileIds = new Set(await readdir(runs).catch(() => []));
176
+ const batchSize = 32;
177
+ for (let offset = 0; offset < metas.length; offset += batchSize) {
178
+ const batch = await Promise.all(metas.slice(offset, offset + batchSize).map(async (meta) => {
179
+ if (!meta.park && !volatileIds.has(meta.id))
180
+ return;
181
+ try {
182
+ const record = parseParkRecord(JSON.parse(await readFile(join(runs, meta.id, "park.json"), "utf-8")));
183
+ if (record)
184
+ return { meta, record };
185
+ }
186
+ catch (error) {
187
+ if (error.code === "ENOENT" && meta.park) {
188
+ const record = readMeta(meta.id)?.park;
189
+ if (record)
190
+ return { meta, record };
191
+ }
192
+ }
193
+ }));
194
+ for (const entry of batch)
195
+ if (entry)
196
+ yield entry;
197
+ }
198
+ }
175
199
  /**
176
200
  * How long a launch attempt that never produced a child is kept before a sweep
177
201
  * reclaims it. Launch preparation takes seconds; the grace only exists so a
@@ -473,36 +497,6 @@ function lockTimeout(id) {
473
497
  let ownStartKnown = false;
474
498
  let ownStartCache;
475
499
  const foreignStartCache = new Map();
476
- /** Best-effort process start identity. Unavailable does not prove the pid is dead. */
477
- export function processStartToken(pid) {
478
- if (process.platform === "linux") {
479
- try {
480
- const stat = readFileSync(`/proc/${pid}/stat`, "utf-8");
481
- const close = stat.lastIndexOf(") ");
482
- if (close >= 0) {
483
- const starttime = stat.slice(close + 2).split(" ")[19];
484
- if (starttime && /^\d+$/.test(starttime))
485
- return starttime;
486
- }
487
- }
488
- catch (error) {
489
- if (errnoOf(error) !== "ENOENT" && errnoOf(error) !== "EACCES")
490
- return undefined;
491
- }
492
- }
493
- try {
494
- const out = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], {
495
- encoding: "utf-8",
496
- timeout: 1_000,
497
- env: { ...process.env, LC_ALL: "C" },
498
- stdio: ["ignore", "pipe", "ignore"],
499
- }).trim().replace(/\s+/g, " ");
500
- return out === "" ? undefined : out;
501
- }
502
- catch {
503
- return undefined;
504
- }
505
- }
506
500
  function ownStartToken() {
507
501
  if (ownStartKnown)
508
502
  return ownStartCache;
@@ -974,10 +968,22 @@ export function observeArchivePublication(id, error) {
974
968
  catch { /* the journal is best-effort; retaining the run is the safety net */ }
975
969
  }
976
970
  export function writeMeta(meta, options = {}) {
971
+ if (options.patch && !readMeta(meta.id))
972
+ return;
977
973
  mkdirSync(runDir(meta.id), { recursive: true });
974
+ let written = false;
978
975
  withRunMetaLock(meta.id, (owns) => {
979
976
  if (options.ifAbsent && existsSync(metaPathFor(meta.id)))
980
977
  return;
978
+ if (options.patch) {
979
+ const current = readMeta(meta.id);
980
+ if (!current)
981
+ return;
982
+ const patch = options.patch(current);
983
+ if (!patch)
984
+ return;
985
+ meta = { ...current, ...patch, id: meta.id };
986
+ }
981
987
  metaWriteBarrier?.();
982
988
  if (!owns())
983
989
  throw new MetadataLockLost();
@@ -999,10 +1005,13 @@ export function writeMeta(meta, options = {}) {
999
1005
  }
1000
1006
  }
1001
1007
  owns();
1008
+ written = true;
1002
1009
  });
1010
+ if (options.patch && !written)
1011
+ return;
1003
1012
  for (const listener of metaChangedListeners) {
1004
1013
  try {
1005
- listener();
1014
+ listener(meta);
1006
1015
  }
1007
1016
  catch { /* best effort */ }
1008
1017
  }
@@ -1039,14 +1048,24 @@ export function removeMetaArtifacts(meta, options = {}) {
1039
1048
  // conversation's visible last word and could be continued as if this
1040
1049
  // attempt had never happened. A marker that cannot be published retains
1041
1050
  // the run (the throw below): the unsafe direction is deleting both.
1051
+ // Called under the conversation mutation lock by both retention sweeps.
1052
+ if (assignmentRetainsEvidence(meta))
1053
+ throw new Error("Assignment outcome or uncertain writer still retains this run's evidence.");
1054
+ const scratch = meta.taskRuntime && meta.taskScratch && dirname(meta.taskScratch) === realpathSync(tmpdir()) &&
1055
+ /^pi-task-scratch-[a-z0-9]{6}$/i.test(basename(meta.taskScratch)) ? meta.taskScratch : undefined;
1056
+ if (meta.timing?.stopReason || meta.recipe?.workspace || scratch)
1057
+ retainResult(meta, logPathFor(meta.id), scratch);
1058
+ const workspace = meta.recipe?.workspace;
1059
+ if (workspace)
1060
+ reclaimWorkspace(workspace, meta.id);
1042
1061
  recordArchiveStatusTombstone(meta);
1043
1062
  removeRunDirectory(meta.id);
1044
- if (!options.keepWorkspace
1063
+ if (!workspace && !meta.timing?.stopReason && !options.keepWorkspace
1045
1064
  && meta.taskRuntime && /^sa_[a-z0-9]+_[a-z0-9]+$/i.test(meta.id) && meta.cwd === taskWorkspaceDir(meta.id)) {
1046
1065
  rmSync(taskWorkspaceDir(meta.id), { recursive: true, force: true });
1047
1066
  }
1048
- if (meta.taskRuntime && meta.taskScratch && dirname(meta.taskScratch) === realpathSync(tmpdir()) && /^pi-task-scratch-[a-z0-9]{6}$/i.test(basename(meta.taskScratch))) {
1049
- rmSync(meta.taskScratch, { recursive: true, force: true });
1067
+ if (scratch) {
1068
+ rmSync(scratch, { recursive: true, force: true });
1050
1069
  }
1051
1070
  metaCache.delete(meta.id);
1052
1071
  removeIndexEntry(join(baseDir(), "by-parent", String(meta.spawnPid)), meta.id);
@@ -1054,13 +1073,14 @@ export function removeMetaArtifacts(meta, options = {}) {
1054
1073
  removeIndexEntry(join(baseDir(), "by-origin", originKey(originOf(meta))), meta.id);
1055
1074
  for (const listener of metaChangedListeners) {
1056
1075
  try {
1057
- listener();
1076
+ listener(meta);
1058
1077
  }
1059
1078
  catch { /* best effort */ }
1060
1079
  }
1061
1080
  return true;
1062
1081
  }
1063
- catch {
1082
+ catch (error) {
1083
+ options.errors?.push(meta.cwd + ": " + String(error));
1064
1084
  return false;
1065
1085
  }
1066
1086
  }
@@ -1,3 +1,5 @@
1
+ import { reclaimWorkspace } from "./isolated-workspace.ts";
2
+ import { retainResult } from "./retained-result.ts";
1
3
  /**
2
4
  * Run registry — durable metadata for each spawned subagent.
3
5
  *
@@ -15,10 +17,12 @@
15
17
  import type { RunTiming } from "./timing.ts";
16
18
  import { assignmentRetainsEvidence } from "./assignment-outcomes.ts";
17
19
  import type { SkillExposureSource } from "./skills.ts";
18
- import { execFileSync } from "node:child_process";
20
+ import { processStartToken } from "./process-identity.mjs";
21
+ export { processStartToken } from "./process-identity.mjs";
19
22
  import { createHash, randomBytes } from "node:crypto";
20
23
  import { closeSync, existsSync, fsyncSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
21
24
  import { createRequire } from "node:module";
25
+ import { readFile, readdir } from "node:fs/promises";
22
26
  import { tmpdir } from "node:os";
23
27
  import { basename, dirname, join } from "node:path";
24
28
  import { processExists } from "./spawn.ts";
@@ -28,7 +32,7 @@ import {
28
32
  durableSessionsDir,
29
33
  listArchivedAttempts,
30
34
  readArchivedAttempt,
31
- recordArchiveStatusTombstone,
35
+ recordArchiveStatusTombstone, retainedLogPath,
32
36
  } from "./session-store.ts";
33
37
  import { failureIdentity, observeFailures, readFailureState } from "./shared-failure-observations.ts";
34
38
 
@@ -42,6 +46,7 @@ export type RunStatus = "running" | "completed" | "failed" | "killed" | "orphane
42
46
  export interface RunCallbackOrigin {
43
47
  cwd: string;
44
48
  sessionId?: string;
49
+ branchId?: string | null;
45
50
  }
46
51
 
47
52
  /**
@@ -110,6 +115,8 @@ export interface LaunchRecipe {
110
115
  effort?: string;
111
116
  /** Effective tool allowlist (already adjusted for confinement). */
112
117
  tools: string;
118
+ /** Inherited trusted tools may be registered but inactive in the child. Older recipes are strict. */
119
+ optionalTrustedTools?: string[];
113
120
  excludeTools?: string;
114
121
  /**
115
122
  * Effective skill exposure: absent means discovery of the user catalog,
@@ -124,16 +131,22 @@ export interface LaunchRecipe {
124
131
  /** Confinement root when the attempt was sandboxed. */
125
132
  sandboxDir?: string;
126
133
  gitCloneWorkspace: boolean;
134
+ workspace?: import("./isolated-workspace.ts").IsolatedWorkspace;
135
+ workspaceAuthority?: Pick<import("./worker-waits.ts").WorkerRunPolicy, "sandbox" | "mandatoryPermissions">;
127
136
  callback: boolean;
128
137
  name?: string;
129
138
  agent?: string;
130
139
  role?: string | readonly string[];
131
140
  alias?: string;
132
141
  catalog?: CatalogLaunchSnapshot;
142
+ /** Absent on recipes that predate explicit ordinary worker providers. */
143
+ toolLoadingVersion?: 1;
133
144
  /** Resolved extension arguments; a changed implementation requires explicit replacement. */
134
145
  extensionArgs?: string[];
135
146
  /** Provider/tool runtime arguments, excluding permission-dependent trusted tools. */
136
147
  baseExtensionArgs?: string[];
148
+ /** Published worker closure retained for this conversation across server upgrades. */
149
+ runtimeRoot?: string;
137
150
  /** Initial trusted implementations survive revocation so re-grants cannot replace them. */
138
151
  trustedExtensions?: { name: string; package: string; loadPath: string }[];
139
152
  }
@@ -244,6 +257,8 @@ export interface RunMeta {
244
257
  completionCallbackSuppressedReason?: string;
245
258
  outcomeDeliveryDeferredReason?: string;
246
259
  assignmentReport?: { version: 1; assignmentId: string; attemptId: string; digest: string; path: string };
260
+ /** Latest authenticated refusal, cleared when a corrected report is retained. */
261
+ assignmentReportRejection?: { reason: string; rejectedAt: number };
247
262
  orphanedCallbackSuppressedAt?: number;
248
263
  orphanedCallbackSuppressedReason?: string;
249
264
  lostCallbackSuppressedAt?: number;
@@ -316,6 +331,11 @@ export function runDir(id: string): string {
316
331
  export function logPathFor(id: string): string {
317
332
  return join(runDir(id), "output.log");
318
333
  }
334
+ export function evidenceLogPath(id: string): string {
335
+ const live = logPathFor(id);
336
+ if (existsSync(live) || existsSync(runDir(id))) return live;
337
+ return retainedLogPath(id) ?? live;
338
+ }
319
339
  export function promptPathFor(id: string): string {
320
340
  return join(runDir(id), "prompt.md");
321
341
  }
@@ -522,6 +542,28 @@ export function listParkRecordCandidates(metas: readonly RunMeta[] = listMetas()
522
542
  || (volatileIds.has(meta.id) && existsSync(parkRecordPath(meta.id))));
523
543
  }
524
544
 
545
+ /** Read recovery sidecars in batches so a large registry does not block socket replies. */
546
+ export async function* scanParkRecords(metas: readonly RunMeta[] = listMetas()): AsyncGenerator<{ meta: RunMeta; record: ParkRecord }> {
547
+ const runs = join(baseDir(), "runs");
548
+ const volatileIds = new Set(await readdir(runs).catch(() => [] as string[]));
549
+ const batchSize = 32;
550
+ for (let offset = 0; offset < metas.length; offset += batchSize) {
551
+ const batch = await Promise.all(metas.slice(offset, offset + batchSize).map(async (meta) => {
552
+ if (!meta.park && !volatileIds.has(meta.id)) return;
553
+ try {
554
+ const record = parseParkRecord(JSON.parse(await readFile(join(runs, meta.id, "park.json"), "utf-8")));
555
+ if (record) return { meta, record };
556
+ } catch (error) {
557
+ if ((error as NodeJS.ErrnoException).code === "ENOENT" && meta.park) {
558
+ const record = readMeta(meta.id)?.park;
559
+ if (record) return { meta, record };
560
+ }
561
+ }
562
+ }));
563
+ for (const entry of batch) if (entry) yield entry;
564
+ }
565
+ }
566
+
525
567
  /**
526
568
  * How long a launch attempt that never produced a child is kept before a sweep
527
569
  * reclaims it. Launch preparation takes seconds; the grace only exists so a
@@ -797,33 +839,6 @@ let ownStartKnown = false;
797
839
  let ownStartCache: string | undefined;
798
840
  const foreignStartCache = new Map<number, { token: string | undefined; at: number }>();
799
841
 
800
- /** Best-effort process start identity. Unavailable does not prove the pid is dead. */
801
- export function processStartToken(pid: number): string | undefined {
802
- if (process.platform === "linux") {
803
- try {
804
- const stat = readFileSync(`/proc/${pid}/stat`, "utf-8");
805
- const close = stat.lastIndexOf(") ");
806
- if (close >= 0) {
807
- const starttime = stat.slice(close + 2).split(" ")[19];
808
- if (starttime && /^\d+$/.test(starttime)) return starttime;
809
- }
810
- } catch (error) {
811
- if (errnoOf(error) !== "ENOENT" && errnoOf(error) !== "EACCES") return undefined;
812
- }
813
- }
814
- try {
815
- const out = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], {
816
- encoding: "utf-8",
817
- timeout: 1_000,
818
- env: { ...process.env, LC_ALL: "C" },
819
- stdio: ["ignore", "pipe", "ignore"],
820
- }).trim().replace(/\s+/g, " ");
821
- return out === "" ? undefined : out;
822
- } catch {
823
- return undefined;
824
- }
825
- }
826
-
827
842
  function ownStartToken(): string | undefined {
828
843
  if (ownStartKnown) return ownStartCache;
829
844
  ownStartCache = processStartToken(process.pid);
@@ -1177,7 +1192,7 @@ export function setMetaWriteBarrierForTests(barrier: (() => void) | undefined):
1177
1192
  // cross-process index changes before any cached IDs are reused.
1178
1193
  const indexIdsCache = new Map<string, { ids: Set<string>; signature: string }>();
1179
1194
  const initializedIndexes = new Set<string>();
1180
- const metaChangedListeners = new Set<() => void>();
1195
+ const metaChangedListeners = new Set<(meta?: RunMeta) => void>();
1181
1196
  const registryIo = { fullDirectoryReads: 0, indexDirectoryReads: 0, metadataFileReads: 0, indexRevisionChecks: 0 };
1182
1197
 
1183
1198
  export interface RegistryIoMetrics {
@@ -1251,10 +1266,23 @@ export function observeArchivePublication(id: string, error?: unknown): void {
1251
1266
  } catch { /* the journal is best-effort; retaining the run is the safety net */ }
1252
1267
  }
1253
1268
 
1254
- export function writeMeta(meta: RunMeta, options: { ifAbsent?: boolean } = {}): void {
1269
+ export function writeMeta(meta: RunMeta, options: {
1270
+ ifAbsent?: boolean;
1271
+ /** Build a field update from current metadata under the existing run lock. */
1272
+ patch?: (current: Readonly<RunMeta>) => Partial<RunMeta> | undefined;
1273
+ } = {}): void {
1274
+ if (options.patch && !readMeta(meta.id)) return;
1255
1275
  mkdirSync(runDir(meta.id), { recursive: true });
1276
+ let written = false;
1256
1277
  withRunMetaLock(meta.id, (owns) => {
1257
1278
  if (options.ifAbsent && existsSync(metaPathFor(meta.id))) return;
1279
+ if (options.patch) {
1280
+ const current = readMeta(meta.id);
1281
+ if (!current) return;
1282
+ const patch = options.patch(current);
1283
+ if (!patch) return;
1284
+ meta = { ...current, ...patch, id: meta.id };
1285
+ }
1258
1286
  metaWriteBarrier?.();
1259
1287
  if (!owns()) throw new MetadataLockLost();
1260
1288
  writeMetaFile(meta);
@@ -1273,13 +1301,15 @@ export function writeMeta(meta: RunMeta, options: { ifAbsent?: boolean } = {}):
1273
1301
  }
1274
1302
  }
1275
1303
  owns();
1304
+ written = true;
1276
1305
  });
1306
+ if (options.patch && !written) return;
1277
1307
  for (const listener of metaChangedListeners) {
1278
- try { listener(); } catch { /* best effort */ }
1308
+ try { listener(meta); } catch { /* best effort */ }
1279
1309
  }
1280
1310
  }
1281
1311
 
1282
- export function onMetaChanged(listener: () => void): () => void {
1312
+ export function onMetaChanged(listener: (meta?: RunMeta) => void): () => void {
1283
1313
  metaChangedListeners.add(listener);
1284
1314
  return () => metaChangedListeners.delete(listener);
1285
1315
  }
@@ -1317,6 +1347,7 @@ export interface RemoveMetaArtifactsOptions {
1317
1347
  * only its volatile log, metadata, and task scratch are reclaimed.
1318
1348
  */
1319
1349
  keepWorkspace?: boolean;
1350
+ errors?: string[];
1320
1351
  }
1321
1352
 
1322
1353
  export function removeMetaArtifacts(meta: RunMeta, options: RemoveMetaArtifactsOptions = {}): boolean {
@@ -1327,24 +1358,32 @@ export function removeMetaArtifacts(meta: RunMeta, options: RemoveMetaArtifactsO
1327
1358
  // conversation's visible last word and could be continued as if this
1328
1359
  // attempt had never happened. A marker that cannot be published retains
1329
1360
  // the run (the throw below): the unsafe direction is deleting both.
1361
+ // Called under the conversation mutation lock by both retention sweeps.
1362
+ if (assignmentRetainsEvidence(meta)) throw new Error("Assignment outcome or uncertain writer still retains this run's evidence.");
1363
+ const scratch = meta.taskRuntime && meta.taskScratch && dirname(meta.taskScratch) === realpathSync(tmpdir()) &&
1364
+ /^pi-task-scratch-[a-z0-9]{6}$/i.test(basename(meta.taskScratch)) ? meta.taskScratch : undefined;
1365
+ if (meta.timing?.stopReason || meta.recipe?.workspace || scratch) retainResult(meta, logPathFor(meta.id), scratch);
1366
+ const workspace = meta.recipe?.workspace;
1367
+ if (workspace) reclaimWorkspace(workspace, meta.id);
1330
1368
  recordArchiveStatusTombstone(meta);
1331
1369
  removeRunDirectory(meta.id);
1332
- if (!options.keepWorkspace
1370
+ if (!workspace && !meta.timing?.stopReason && !options.keepWorkspace
1333
1371
  && meta.taskRuntime && /^sa_[a-z0-9]+_[a-z0-9]+$/i.test(meta.id) && meta.cwd === taskWorkspaceDir(meta.id)) {
1334
1372
  rmSync(taskWorkspaceDir(meta.id), { recursive: true, force: true });
1335
1373
  }
1336
- if (meta.taskRuntime && meta.taskScratch && dirname(meta.taskScratch) === realpathSync(tmpdir()) && /^pi-task-scratch-[a-z0-9]{6}$/i.test(basename(meta.taskScratch))) {
1337
- rmSync(meta.taskScratch, { recursive: true, force: true });
1374
+ if (scratch) {
1375
+ rmSync(scratch, { recursive: true, force: true });
1338
1376
  }
1339
1377
  metaCache.delete(meta.id);
1340
1378
  removeIndexEntry(join(baseDir(), "by-parent", String(meta.spawnPid)), meta.id);
1341
1379
  removeIndexEntry(join(baseDir(), "by-parent-active", String(meta.spawnPid)), meta.id);
1342
1380
  removeIndexEntry(join(baseDir(), "by-origin", originKey(originOf(meta))), meta.id);
1343
1381
  for (const listener of metaChangedListeners) {
1344
- try { listener(); } catch { /* best effort */ }
1382
+ try { listener(meta); } catch { /* best effort */ }
1345
1383
  }
1346
1384
  return true;
1347
- } catch {
1385
+ } catch (error) {
1386
+ options.errors?.push(meta.cwd + ": " + String(error));
1348
1387
  return false;
1349
1388
  }
1350
1389
  }
@@ -0,0 +1,56 @@
1
+ // Generated fixed launch domain from packages/pi-better-subagents/retained-result.ts. Do not edit directly.
2
+ import { copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync, } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { snapshotTree, verifyTree } from "./workspace-files.domain.mjs";
5
+ import { resultDir } from "./session-store.domain.mjs";
6
+ // Published only while retiring a quiescent attempt. A result record can answer reads,
7
+ // but cannot authorize admission, revive a writer or make a failed attempt resumable.
8
+ export function retainResult(meta, logPath, scratch) {
9
+ const dir = resultDir(meta.id);
10
+ if (!dir)
11
+ throw new Error("Invalid result identity");
12
+ if (existsSync(dir)) {
13
+ if (readRetainedResult(meta.id)?.sessionId !== meta.sessionId)
14
+ throw new Error("Retained result identity changed");
15
+ return;
16
+ }
17
+ mkdirSync(dirname(dir), { recursive: true, mode: 0o700 });
18
+ const temp = mkdtempSync(dir + "-");
19
+ try {
20
+ for (const name of ["output.log", "failures.jsonl"]) {
21
+ const source = join(dirname(logPath), name);
22
+ if (existsSync(source))
23
+ copyFileSync(source, join(temp, name));
24
+ }
25
+ let savedScratch;
26
+ if (scratch && existsSync(scratch)) {
27
+ const files = snapshotTree(scratch);
28
+ if (files.some((entry) => entry.name !== ".sandbox-anchor")) {
29
+ cpSync(scratch, join(temp, "scratch"), { recursive: true, verbatimSymlinks: true });
30
+ verifyTree(join(temp, "scratch"), files);
31
+ verifyTree(scratch, files);
32
+ savedScratch = join(dir, "scratch");
33
+ }
34
+ }
35
+ writeFileSync(join(temp, "result.json"), JSON.stringify({ ...meta, taskScratch: savedScratch, logPath: join(dir, "output.log") }), { mode: 0o600 });
36
+ renameSync(temp, dir);
37
+ }
38
+ finally {
39
+ rmSync(temp, { recursive: true, force: true });
40
+ }
41
+ }
42
+ export function readRetainedResult(id) {
43
+ const dir = resultDir(id);
44
+ if (!dir)
45
+ return;
46
+ try {
47
+ const meta = JSON.parse(readFileSync(join(dir, "result.json"), "utf8"));
48
+ if (meta.id === id && ["completed", "killed", "failed", "lost"].includes(meta.status))
49
+ return meta;
50
+ }
51
+ catch (error) {
52
+ if (error.code !== "ENOENT")
53
+ throw error;
54
+ }
55
+ return undefined;
56
+ }
@@ -0,0 +1,65 @@
1
+ import {
2
+ copyFileSync,
3
+ cpSync,
4
+ existsSync,
5
+ mkdirSync,
6
+ mkdtempSync,
7
+ readFileSync,
8
+ renameSync,
9
+ rmSync,
10
+ writeFileSync,
11
+ } from "node:fs";
12
+ import { dirname, join } from "node:path";
13
+ import { snapshotTree, verifyTree } from "./workspace-files.ts";
14
+ import type { RunMeta } from "./registry.ts";
15
+ import { resultDir } from "./session-store.ts";
16
+
17
+ // Published only while retiring a quiescent attempt. A result record can answer reads,
18
+ // but cannot authorize admission, revive a writer or make a failed attempt resumable.
19
+ export function retainResult(meta: RunMeta, logPath: string, scratch?: string): void {
20
+ const dir = resultDir(meta.id);
21
+ if (!dir) throw new Error("Invalid result identity");
22
+ if (existsSync(dir)) {
23
+ if (readRetainedResult(meta.id)?.sessionId !== meta.sessionId)
24
+ throw new Error("Retained result identity changed");
25
+ return;
26
+ }
27
+ mkdirSync(dirname(dir), { recursive: true, mode: 0o700 });
28
+ const temp = mkdtempSync(dir + "-");
29
+ try {
30
+ for (const name of ["output.log", "failures.jsonl"]) {
31
+ const source = join(dirname(logPath), name);
32
+ if (existsSync(source)) copyFileSync(source, join(temp, name));
33
+ }
34
+ let savedScratch: string | undefined;
35
+ if (scratch && existsSync(scratch)) {
36
+ const files = snapshotTree(scratch);
37
+ if (files.some((entry) => entry.name !== ".sandbox-anchor")) {
38
+ cpSync(scratch, join(temp, "scratch"), { recursive: true, verbatimSymlinks: true });
39
+ verifyTree(join(temp, "scratch"), files);
40
+ verifyTree(scratch, files);
41
+ savedScratch = join(dir, "scratch");
42
+ }
43
+ }
44
+ writeFileSync(
45
+ join(temp, "result.json"),
46
+ JSON.stringify({ ...meta, taskScratch: savedScratch, logPath: join(dir, "output.log") }),
47
+ { mode: 0o600 },
48
+ );
49
+ renameSync(temp, dir);
50
+ } finally {
51
+ rmSync(temp, { recursive: true, force: true });
52
+ }
53
+ }
54
+
55
+ export function readRetainedResult(id: string): RunMeta | undefined {
56
+ const dir = resultDir(id);
57
+ if (!dir) return;
58
+ try {
59
+ const meta = JSON.parse(readFileSync(join(dir, "result.json"), "utf8")) as RunMeta;
60
+ if (meta.id === id && ["completed", "killed", "failed", "lost"].includes(meta.status)) return meta;
61
+ } catch (error) {
62
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
63
+ }
64
+ return undefined;
65
+ }
@@ -1,4 +1,6 @@
1
1
  // Generated fixed launch domain from packages/pi-better-subagents/session-selection.ts. Do not edit directly.
2
+ /** Exact-name selection of saved conversations; attempt IDs never become session IDs. */
3
+ import { discoveryWorkspace } from "./workspace-scope.domain.mjs";
2
4
  /**
3
5
  * Select a single conversation in the caller's workspace scope. Several attempts
4
6
  * of one conversation count once; distinct conversations with the same display
@@ -18,7 +20,7 @@ export function selectSessionByName(metas, name, inWorkspace) {
18
20
  latest.set(meta.sessionId, meta);
19
21
  }
20
22
  const matches = [...latest.values()]
21
- .filter((meta) => meta.name === requested && inWorkspace(meta.cwd))
23
+ .filter((meta) => meta.name === requested && inWorkspace(discoveryWorkspace(meta)))
22
24
  .sort((a, b) => a.sessionId.localeCompare(b.sessionId));
23
25
  if (matches.length === 0) {
24
26
  throw new Error(`No saved subagent conversation named ${JSON.stringify(requested)} in the current folder. Use subagent_list({all:true}) to find its session_id.`);
@@ -1,4 +1,5 @@
1
1
  /** Exact-name selection of saved conversations; attempt IDs never become session IDs. */
2
+ import { discoveryWorkspace } from "./workspace-scope.ts";
2
3
  import type { RunMeta } from "./registry.ts";
3
4
 
4
5
  /**
@@ -21,7 +22,7 @@ export function selectSessionByName(
21
22
  if (!previous || meta.startedAt > previous.startedAt) latest.set(meta.sessionId, meta);
22
23
  }
23
24
  const matches = [...latest.values()]
24
- .filter((meta) => meta.name === requested && inWorkspace(meta.cwd))
25
+ .filter((meta) => meta.name === requested && inWorkspace(discoveryWorkspace(meta)))
25
26
  .sort((a, b) => a.sessionId.localeCompare(b.sessionId));
26
27
  if (matches.length === 0) {
27
28
  throw new Error(`No saved subagent conversation named ${JSON.stringify(requested)} in the current folder. Use subagent_list({all:true}) to find its session_id.`);
@@ -72,6 +72,13 @@ export function durableSubagentRoot(env = process.env, home = homedir()) {
72
72
  const agentDir = env.PI_CODING_AGENT_DIR?.trim();
73
73
  return join(agentDir || join(home, ".pi", "agent"), "subagents");
74
74
  }
75
+ export function resultDir(id) {
76
+ return /^sa_[a-z0-9]+_[a-z0-9]+$/i.test(id) ? join(durableSubagentRoot(), "results", id) : undefined;
77
+ }
78
+ export function retainedLogPath(id) {
79
+ const dir = resultDir(id);
80
+ return dir && join(dir, "output.log");
81
+ }
75
82
  /** Durable `--session-dir` for new child launches. */
76
83
  export function durableSessionsDir() {
77
84
  return join(durableSubagentRoot(), "sessions");
@@ -83,6 +83,15 @@ export function durableSubagentRoot(env: NodeJS.ProcessEnv = process.env, home:
83
83
  return join(agentDir || join(home, ".pi", "agent"), "subagents");
84
84
  }
85
85
 
86
+ export function resultDir(id: string): string | undefined {
87
+ return /^sa_[a-z0-9]+_[a-z0-9]+$/i.test(id) ? join(durableSubagentRoot(), "results", id) : undefined;
88
+ }
89
+
90
+ export function retainedLogPath(id: string): string | undefined {
91
+ const dir = resultDir(id);
92
+ return dir && join(dir, "output.log");
93
+ }
94
+
86
95
  /** Durable `--session-dir` for new child launches. */
87
96
  export function durableSessionsDir(): string {
88
97
  return join(durableSubagentRoot(), "sessions");