pi-better-server 0.4.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 (597) hide show
  1. package/package.json +8 -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 +87 -0
  6. package/scripts/event-publication/writer.mjs +6 -0
  7. package/scripts/measure-full-runtime/frontend.ts +24 -0
  8. package/scripts/measure-full-runtime/hosted-extension.ts +28 -0
  9. package/scripts/measure-full-runtime/probe.mjs +29 -0
  10. package/scripts/measure-full-runtime/recovery-trace-loader.mjs +51 -0
  11. package/scripts/measure-full-runtime/recovery-trace.mjs +16 -0
  12. package/scripts/measure-full-runtime.mjs +146 -0
  13. package/scripts/measure-shared-reads/probe.mjs +26 -2
  14. package/scripts/measure-shared-reads.mjs +44 -9
  15. package/scripts/private-runtime/package-lock.json +66 -4
  16. package/scripts/private-runtime/package.json +10 -2
  17. package/scripts/source-provenance.mjs +31 -0
  18. package/scripts/test-on-pi.sh +3 -9
  19. package/src/handshake.ts +1 -1
  20. package/src/hosted-session.ts +32 -4
  21. package/src/maintenance.ts +35 -7
  22. package/src/registry.ts +28 -4
  23. package/src/runtime/attempt-invalidation.ts +54 -0
  24. package/src/runtime/background-history.ts +151 -45
  25. package/src/runtime/background-policy.ts +27 -0
  26. package/src/runtime/background-tools.ts +389 -0
  27. package/src/runtime/background.ts +410 -48
  28. package/src/runtime/cancellation.ts +28 -7
  29. package/src/runtime/catalog-sources.ts +199 -0
  30. package/src/runtime/catalog.ts +53 -21
  31. package/src/runtime/client.ts +22 -2
  32. package/src/runtime/domain/assignment-inbox.mjs +119 -0
  33. package/src/runtime/domain/assignment-observation.d.mts +1 -1
  34. package/src/runtime/domain/assignment-observation.mjs +71 -33
  35. package/src/runtime/domain/background/process-identity.mjs +20 -2
  36. package/src/runtime/domain/background/process.mjs +3 -3
  37. package/src/runtime/domain/background/registry.mjs +89 -4
  38. package/src/runtime/domain/background/types.mjs +1 -0
  39. package/src/runtime/domain/background-service/adapter-contract.domain.mjs +83 -0
  40. package/src/runtime/domain/background-service/adapter-contract.ts +70 -0
  41. package/src/runtime/domain/background-service/batch.domain.mjs +91 -0
  42. package/src/runtime/domain/background-service/batch.ts +111 -0
  43. package/src/runtime/domain/background-service/conditions.domain.mjs +94 -0
  44. package/src/runtime/domain/background-service/conditions.ts +99 -0
  45. package/src/runtime/domain/background-service/delivery-observer.domain.mjs +37 -0
  46. package/src/runtime/domain/background-service/delivery-observer.ts +42 -0
  47. package/src/runtime/domain/background-service/failures.domain.mjs +209 -0
  48. package/src/runtime/domain/background-service/failures.ts +212 -0
  49. package/src/runtime/domain/background-service/goal-provider.domain.mjs +193 -0
  50. package/src/runtime/domain/background-service/goal-provider.ts +209 -0
  51. package/src/runtime/domain/background-service/index.domain.mjs +54 -0
  52. package/src/runtime/domain/background-service/index.ts +55 -0
  53. package/src/runtime/domain/background-service/logs.domain.mjs +129 -0
  54. package/src/runtime/domain/background-service/logs.ts +134 -0
  55. package/src/runtime/domain/background-service/maintenance.domain.mjs +95 -0
  56. package/src/runtime/domain/background-service/maintenance.ts +98 -0
  57. package/src/runtime/domain/background-service/managed-authority.domain.mjs +32 -0
  58. package/src/runtime/domain/background-service/managed-authority.ts +30 -0
  59. package/src/runtime/domain/background-service/managed-client.domain.mjs +79 -0
  60. package/src/runtime/domain/background-service/managed-client.ts +73 -0
  61. package/src/runtime/domain/background-service/managed-frontend.domain.mjs +225 -0
  62. package/src/runtime/domain/background-service/managed-frontend.ts +176 -0
  63. package/src/runtime/domain/background-service/navigator-provider.domain.mjs +492 -0
  64. package/src/runtime/domain/background-service/navigator-provider.ts +485 -0
  65. package/src/runtime/domain/background-service/observed-wait-client.domain.mjs +6 -0
  66. package/src/runtime/domain/background-service/observed-wait-client.ts +10 -0
  67. package/src/runtime/domain/background-service/observed-waits.domain.mjs +4080 -0
  68. package/src/runtime/domain/background-service/observed-waits.ts +4513 -0
  69. package/src/runtime/domain/background-service/output.domain.mjs +867 -0
  70. package/src/runtime/domain/background-service/output.ts +952 -0
  71. package/src/runtime/domain/background-service/process-identity.domain.mjs +129 -0
  72. package/src/runtime/domain/background-service/process-identity.ts +134 -0
  73. package/src/runtime/domain/background-service/process.domain.mjs +512 -0
  74. package/src/runtime/domain/background-service/process.ts +532 -0
  75. package/src/runtime/domain/background-service/prompt.domain.mjs +58 -0
  76. package/src/runtime/domain/background-service/prompt.ts +72 -0
  77. package/src/runtime/domain/background-service/registry.domain.mjs +460 -0
  78. package/src/runtime/domain/background-service/registry.ts +450 -0
  79. package/src/runtime/domain/background-service/remote-task-preset.domain.mjs +67 -0
  80. package/src/runtime/domain/background-service/remote-task-preset.ts +127 -0
  81. package/src/runtime/domain/background-service/runtime.domain.mjs +1511 -0
  82. package/src/runtime/domain/background-service/runtime.ts +1636 -0
  83. package/src/runtime/domain/background-service/sandbox.domain.mjs +735 -0
  84. package/src/runtime/domain/background-service/sandbox.ts +913 -0
  85. package/src/runtime/domain/background-service/shared-callback-batcher.domain.mjs +777 -0
  86. package/src/runtime/domain/background-service/shared-callback-batcher.ts +956 -0
  87. package/src/runtime/domain/background-service/shared-execution-policy.domain.mjs +50 -0
  88. package/src/runtime/domain/background-service/shared-execution-policy.ts +61 -0
  89. package/src/runtime/domain/background-service/shared-failure-observations.domain.mjs +1078 -0
  90. package/src/runtime/domain/background-service/shared-failure-observations.ts +1166 -0
  91. package/src/runtime/domain/background-service/shared-harness-settings.domain.mjs +126 -0
  92. package/src/runtime/domain/background-service/shared-harness-settings.ts +116 -0
  93. package/src/runtime/domain/background-service/shared-log-utils.domain.mjs +1223 -0
  94. package/src/runtime/domain/background-service/shared-log-utils.ts +1492 -0
  95. package/src/runtime/domain/background-service/shared-navigator-panels.domain.mjs +289 -0
  96. package/src/runtime/domain/background-service/shared-navigator-panels.ts +272 -0
  97. package/src/runtime/domain/background-service/shared-navigator.domain.mjs +1930 -0
  98. package/src/runtime/domain/background-service/shared-navigator.ts +1962 -0
  99. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-inbox.mjs +144 -0
  100. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-observation.mjs +189 -0
  101. package/src/runtime/domain/background-service/shared-operation-coordinator/index.domain.mjs +51 -0
  102. package/src/runtime/domain/background-service/shared-operation-coordinator/index.ts +122 -0
  103. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
  104. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  105. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +163 -0
  106. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.ts +174 -0
  107. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-parent-callbacks.domain.mjs +66 -0
  108. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-parent-callbacks.ts +68 -0
  109. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.domain.mjs +87 -0
  110. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.ts +90 -0
  111. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.domain.mjs +97 -0
  112. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.ts +139 -0
  113. package/src/runtime/domain/background-service/shared-operation-coordinator/src/errors.domain.mjs +12 -0
  114. package/src/runtime/domain/background-service/shared-operation-coordinator/src/errors.ts +79 -0
  115. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.domain.mjs +342 -0
  116. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.ts +513 -0
  117. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.domain.mjs +283 -0
  118. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.ts +458 -0
  119. package/src/runtime/domain/background-service/shared-operation-coordinator/src/recovery.domain.mjs +52 -0
  120. package/src/runtime/domain/background-service/shared-operation-coordinator/src/recovery.ts +55 -0
  121. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.domain.mjs +114 -0
  122. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.ts +140 -0
  123. package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.domain.mjs +280 -0
  124. package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.ts +442 -0
  125. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +420 -0
  126. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +441 -0
  127. package/src/runtime/domain/background-service/shared-operation-coordinator/src/sqlite.domain.mjs +194 -0
  128. package/src/runtime/domain/background-service/shared-operation-coordinator/src/sqlite.ts +239 -0
  129. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +275 -0
  130. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +585 -0
  131. package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.domain.mjs +120 -0
  132. package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.ts +142 -0
  133. package/src/runtime/domain/background-service/shared-operation-coordinator/src/task-cancellation.domain.mjs +188 -0
  134. package/src/runtime/domain/background-service/shared-operation-coordinator/src/task-cancellation.ts +224 -0
  135. package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.domain.mjs +25 -0
  136. package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.ts +707 -0
  137. package/src/runtime/domain/background-service/shared-operation-coordinator/src/upgrade.domain.mjs +22 -0
  138. package/src/runtime/domain/background-service/shared-operation-coordinator/src/upgrade.ts +22 -0
  139. package/src/runtime/domain/background-service/shared-operation-coordinator/src/validate.domain.mjs +234 -0
  140. package/src/runtime/domain/background-service/shared-operation-coordinator/src/validate.ts +241 -0
  141. package/src/runtime/domain/background-service/shared-operation-coordinator/src/waits.domain.mjs +851 -0
  142. package/src/runtime/domain/background-service/shared-operation-coordinator/src/waits.ts +1424 -0
  143. package/src/runtime/domain/background-service/shared-permission-blocker.domain.mjs +40 -0
  144. package/src/runtime/domain/background-service/shared-permission-blocker.ts +48 -0
  145. package/src/runtime/domain/background-service/shared-render-scheduler.domain.mjs +41 -0
  146. package/src/runtime/domain/background-service/shared-render-scheduler.ts +47 -0
  147. package/src/runtime/domain/background-service/shared-sandbox-core.domain.mjs +1531 -0
  148. package/src/runtime/domain/background-service/shared-sandbox-core.ts +1757 -0
  149. package/src/runtime/domain/background-service/shared-sandbox-diagnostics.domain.mjs +591 -0
  150. package/src/runtime/domain/background-service/shared-sandbox-diagnostics.ts +491 -0
  151. package/src/runtime/domain/background-service/shared-ssh-core/index.domain.mjs +698 -0
  152. package/src/runtime/domain/background-service/shared-ssh-core/index.ts +979 -0
  153. package/src/runtime/domain/background-service/shared-stall-detector.domain.mjs +37 -0
  154. package/src/runtime/domain/background-service/shared-stall-detector.ts +69 -0
  155. package/src/runtime/domain/background-service/shared-work-client.mjs +303 -0
  156. package/src/runtime/domain/background-service/stall-attention.domain.mjs +29 -0
  157. package/src/runtime/domain/background-service/stall-attention.ts +31 -0
  158. package/src/runtime/domain/background-service/stall.domain.mjs +57 -0
  159. package/src/runtime/domain/background-service/stall.ts +57 -0
  160. package/src/runtime/domain/background-service/supervisor/README.md +111 -0
  161. package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +90 -0
  162. package/src/runtime/domain/background-service/supervisor/generated/conditions.mjs +96 -0
  163. package/src/runtime/domain/background-service/supervisor/generated/identity.mjs +95 -0
  164. package/src/runtime/domain/background-service/supervisor/generated/process-identity.mjs +131 -0
  165. package/src/runtime/domain/background-service/supervisor/generated/process.mjs +514 -0
  166. package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +872 -0
  167. package/src/runtime/domain/background-service/supervisor/generated/store.mjs +609 -0
  168. package/src/runtime/domain/background-service/supervisor/generated/types.mjs +50 -0
  169. package/src/runtime/domain/background-service/supervisor/identity.domain.mjs +93 -0
  170. package/src/runtime/domain/background-service/supervisor/identity.ts +99 -0
  171. package/src/runtime/domain/background-service/supervisor/index.domain.mjs +22 -0
  172. package/src/runtime/domain/background-service/supervisor/index.ts +37 -0
  173. package/src/runtime/domain/background-service/supervisor/invocation.domain.mjs +30 -0
  174. package/src/runtime/domain/background-service/supervisor/invocation.ts +44 -0
  175. package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +870 -0
  176. package/src/runtime/domain/background-service/supervisor/runner.ts +982 -0
  177. package/src/runtime/domain/background-service/supervisor/store.domain.mjs +605 -0
  178. package/src/runtime/domain/background-service/supervisor/store.ts +651 -0
  179. package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +721 -0
  180. package/src/runtime/domain/background-service/supervisor/supervisor.ts +804 -0
  181. package/src/runtime/domain/background-service/supervisor/types.domain.mjs +48 -0
  182. package/src/runtime/domain/background-service/supervisor/types.ts +394 -0
  183. package/src/runtime/domain/background-service/task-diagnostics.domain.mjs +60 -0
  184. package/src/runtime/domain/background-service/task-diagnostics.ts +71 -0
  185. package/src/runtime/domain/background-service/tools.domain.mjs +1050 -0
  186. package/src/runtime/domain/background-service/tools.ts +1142 -0
  187. package/src/runtime/domain/background-service/types.domain.mjs +5 -0
  188. package/src/runtime/domain/background-service/types.ts +236 -0
  189. package/src/runtime/domain/background-service/work-observation.domain.mjs +176 -0
  190. package/src/runtime/domain/background-service/work-observation.ts +144 -0
  191. package/src/runtime/domain/catalog/catalog-store.d.mts +9 -1
  192. package/src/runtime/domain/catalog/catalog-store.mjs +20 -22
  193. package/src/runtime/domain/coordinator/src/assignment-changes.mjs +75 -0
  194. package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +2 -0
  195. package/src/runtime/domain/coordinator/src/background-parent-callbacks.mjs +65 -0
  196. package/src/runtime/domain/coordinator/src/background-requests.mjs +86 -0
  197. package/src/runtime/domain/coordinator/src/discovery.mjs +4 -2
  198. package/src/runtime/domain/coordinator/src/operations.mjs +44 -4
  199. package/src/runtime/domain/coordinator/src/result-supervision.mjs +12 -0
  200. package/src/runtime/domain/coordinator/src/rows.mjs +2 -0
  201. package/src/runtime/domain/coordinator/src/schema.mjs +73 -21
  202. package/src/runtime/domain/coordinator/src/store.mjs +32 -3
  203. package/src/runtime/domain/coordinator/src/subagent-launch.mjs +119 -0
  204. package/src/runtime/domain/coordinator/src/types.mjs +1 -1
  205. package/src/runtime/domain/coordinator/src/upgrade.mjs +22 -0
  206. package/src/runtime/domain/health-observation.d.mts +3 -1
  207. package/src/runtime/domain/health-observation.mjs +189 -190
  208. package/src/runtime/domain/log-cursor.d.mts +2 -0
  209. package/src/runtime/domain/log-cursor.mjs +85 -16
  210. package/src/runtime/domain/parse.d.mts +4 -1
  211. package/src/runtime/domain/parse.mjs +50 -5
  212. package/src/runtime/domain/sandbox-policy/README.md +633 -0
  213. package/src/runtime/domain/sandbox-policy/background-admission.domain.mjs +83 -0
  214. package/src/runtime/domain/sandbox-policy/background-admission.ts +75 -0
  215. package/src/runtime/domain/sandbox-policy/commands.domain.mjs +245 -0
  216. package/src/runtime/domain/sandbox-policy/commands.ts +336 -0
  217. package/src/runtime/domain/sandbox-policy/deny-rules.domain.mjs +440 -0
  218. package/src/runtime/domain/sandbox-policy/deny-rules.ts +620 -0
  219. package/src/runtime/domain/sandbox-policy/diagnostics-command.domain.mjs +30 -0
  220. package/src/runtime/domain/sandbox-policy/diagnostics-command.ts +27 -0
  221. package/src/runtime/domain/sandbox-policy/events.domain.mjs +49 -0
  222. package/src/runtime/domain/sandbox-policy/events.ts +85 -0
  223. package/src/runtime/domain/sandbox-policy/files.domain.mjs +153 -0
  224. package/src/runtime/domain/sandbox-policy/files.ts +224 -0
  225. package/src/runtime/domain/sandbox-policy/index.domain.mjs +289 -0
  226. package/src/runtime/domain/sandbox-policy/index.ts +386 -0
  227. package/src/runtime/domain/sandbox-policy/package.json +66 -0
  228. package/src/runtime/domain/sandbox-policy/permission-settings.domain.mjs +36 -0
  229. package/src/runtime/domain/sandbox-policy/permission-settings.ts +46 -0
  230. package/src/runtime/domain/sandbox-policy/permissions-page.domain.mjs +309 -0
  231. package/src/runtime/domain/sandbox-policy/permissions-page.ts +295 -0
  232. package/src/runtime/domain/sandbox-policy/permissions.domain.mjs +98 -0
  233. package/src/runtime/domain/sandbox-policy/permissions.ts +125 -0
  234. package/src/runtime/domain/sandbox-policy/policy.domain.mjs +80 -0
  235. package/src/runtime/domain/sandbox-policy/policy.ts +102 -0
  236. package/src/runtime/domain/sandbox-policy/preferences.domain.mjs +55 -0
  237. package/src/runtime/domain/sandbox-policy/preferences.ts +82 -0
  238. package/src/runtime/domain/sandbox-policy/rules-page.domain.mjs +138 -0
  239. package/src/runtime/domain/sandbox-policy/rules-page.ts +176 -0
  240. package/src/runtime/domain/sandbox-policy/session-permissions.domain.mjs +22 -0
  241. package/src/runtime/domain/sandbox-policy/session-permissions.ts +24 -0
  242. package/src/runtime/domain/sandbox-policy/shared-harness-settings.domain.mjs +126 -0
  243. package/src/runtime/domain/sandbox-policy/shared-harness-settings.ts +116 -0
  244. package/src/runtime/domain/sandbox-policy/shared-permission-blocker.domain.mjs +40 -0
  245. package/src/runtime/domain/sandbox-policy/shared-permission-blocker.ts +48 -0
  246. package/src/runtime/domain/sandbox-policy/shared-sandbox-core.domain.mjs +1531 -0
  247. package/src/runtime/domain/sandbox-policy/shared-sandbox-core.ts +1757 -0
  248. package/src/runtime/domain/sandbox-policy/shared-sandbox-diagnostics.domain.mjs +591 -0
  249. package/src/runtime/domain/sandbox-policy/shared-sandbox-diagnostics.ts +491 -0
  250. package/src/runtime/domain/sandbox-policy/shared-task-application.domain.mjs +185 -0
  251. package/src/runtime/domain/sandbox-policy/shared-task-application.ts +185 -0
  252. package/src/runtime/domain/sandbox-policy/shared-task-apply-patch.domain.mjs +416 -0
  253. package/src/runtime/domain/sandbox-policy/shared-task-apply-patch.ts +409 -0
  254. package/src/runtime/domain/sandbox-policy/shared-task-exec.domain.mjs +325 -0
  255. package/src/runtime/domain/sandbox-policy/shared-task-exec.ts +335 -0
  256. package/src/runtime/domain/sandbox-policy/shared-task-files.domain.mjs +346 -0
  257. package/src/runtime/domain/sandbox-policy/shared-task-files.ts +342 -0
  258. package/src/runtime/domain/sandbox-policy/shared-task-process-identity.domain.mjs +140 -0
  259. package/src/runtime/domain/sandbox-policy/shared-task-process-identity.ts +126 -0
  260. package/src/runtime/domain/sandbox-policy/shared-task-process-list.domain.mjs +220 -0
  261. package/src/runtime/domain/sandbox-policy/shared-task-process-list.ts +209 -0
  262. package/src/runtime/domain/sandbox-policy/shared-task-sandbox.domain.mjs +227 -0
  263. package/src/runtime/domain/sandbox-policy/shared-task-sandbox.ts +224 -0
  264. package/src/runtime/domain/sandbox-policy/shared-task-tools.domain.mjs +92 -0
  265. package/src/runtime/domain/sandbox-policy/shared-task-tools.ts +123 -0
  266. package/src/runtime/domain/sandbox-policy/shell.domain.mjs +93 -0
  267. package/src/runtime/domain/sandbox-policy/shell.ts +129 -0
  268. package/src/runtime/domain/sandbox-policy/state.domain.mjs +307 -0
  269. package/src/runtime/domain/sandbox-policy/state.ts +408 -0
  270. package/src/runtime/domain/sandbox-policy/status.domain.mjs +64 -0
  271. package/src/runtime/domain/sandbox-policy/status.ts +76 -0
  272. package/src/runtime/domain/sandbox-policy/subagent-admission.domain.mjs +69 -0
  273. package/src/runtime/domain/sandbox-policy/subagent-admission.ts +60 -0
  274. package/src/runtime/domain/subagents/CONTEXT.md +202 -0
  275. package/src/runtime/domain/subagents/PRODUCT.md +49 -0
  276. package/src/runtime/domain/subagents/README.md +201 -0
  277. package/src/runtime/domain/subagents/agent-catalog.mjs +64 -0
  278. package/src/runtime/domain/subagents/agent-commands.domain.mjs +822 -0
  279. package/src/runtime/domain/subagents/agent-commands.ts +905 -0
  280. package/src/runtime/domain/subagents/agent-inspection.domain.mjs +398 -0
  281. package/src/runtime/domain/subagents/agent-inspection.ts +574 -0
  282. package/src/runtime/domain/subagents/agent-operations.domain.mjs +40 -0
  283. package/src/runtime/domain/subagents/agent-operations.ts +61 -0
  284. package/src/runtime/domain/subagents/agent-session-settings.domain.mjs +112 -0
  285. package/src/runtime/domain/subagents/agent-session-settings.ts +118 -0
  286. package/src/runtime/domain/subagents/agents-catalog-tool.domain.mjs +84 -0
  287. package/src/runtime/domain/subagents/agents-catalog-tool.ts +118 -0
  288. package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +276 -0
  289. package/src/runtime/domain/subagents/assignment-outcomes.ts +212 -0
  290. package/src/runtime/domain/subagents/assignment-projection.mjs +261 -0
  291. package/src/runtime/domain/subagents/assignment-report.domain.mjs +174 -0
  292. package/src/runtime/domain/subagents/assignment-report.ts +156 -0
  293. package/src/runtime/domain/subagents/batch.mjs +275 -0
  294. package/src/runtime/domain/subagents/callback-fields.domain.mjs +72 -0
  295. package/src/runtime/domain/subagents/callback-fields.ts +95 -0
  296. package/src/runtime/domain/subagents/capacity.mjs +108 -0
  297. package/src/runtime/domain/subagents/catalog-editor.domain.mjs +98 -0
  298. package/src/runtime/domain/subagents/catalog-editor.ts +125 -0
  299. package/src/runtime/domain/subagents/catalog-host-admission.domain.mjs +104 -0
  300. package/src/runtime/domain/subagents/catalog-host-admission.ts +85 -0
  301. package/src/runtime/domain/subagents/catalog-identity.domain.mjs +222 -0
  302. package/src/runtime/domain/subagents/catalog-identity.ts +258 -0
  303. package/src/runtime/domain/subagents/catalog-overlay.domain.mjs +9 -0
  304. package/src/runtime/domain/subagents/catalog-overlay.ts +10 -0
  305. package/src/runtime/domain/subagents/catalog-preferences.domain.mjs +164 -0
  306. package/src/runtime/domain/subagents/catalog-preferences.ts +139 -0
  307. package/src/runtime/domain/subagents/catalog-resolver.domain.mjs +366 -0
  308. package/src/runtime/domain/subagents/catalog-resolver.ts +540 -0
  309. package/src/runtime/domain/subagents/catalog-runtime.domain.mjs +570 -0
  310. package/src/runtime/domain/subagents/catalog-runtime.ts +680 -0
  311. package/src/runtime/domain/subagents/catalog-schema.domain.mjs +1331 -0
  312. package/src/runtime/domain/subagents/catalog-schema.ts +1563 -0
  313. package/src/runtime/domain/subagents/catalog-skill-edits.domain.mjs +95 -0
  314. package/src/runtime/domain/subagents/catalog-skill-edits.ts +116 -0
  315. package/src/runtime/domain/subagents/catalog-store.domain.mjs +808 -0
  316. package/src/runtime/domain/subagents/catalog-store.ts +1006 -0
  317. package/src/runtime/domain/subagents/catalog-ui.domain.mjs +651 -0
  318. package/src/runtime/domain/subagents/catalog-ui.ts +611 -0
  319. package/src/runtime/domain/subagents/child-apply-patch.domain.mjs +13 -0
  320. package/src/runtime/domain/subagents/child-apply-patch.ts +13 -0
  321. package/src/runtime/domain/subagents/child-codemode.domain.mjs +16 -0
  322. package/src/runtime/domain/subagents/child-codemode.ts +17 -0
  323. package/src/runtime/domain/subagents/child-dependencies.mjs +193 -0
  324. package/src/runtime/domain/subagents/child-incidents.domain.mjs +170 -0
  325. package/src/runtime/domain/subagents/child-incidents.ts +169 -0
  326. package/src/runtime/domain/subagents/child-operations.domain.mjs +986 -0
  327. package/src/runtime/domain/subagents/child-operations.ts +1191 -0
  328. package/src/runtime/domain/subagents/child-ownership.domain.mjs +205 -0
  329. package/src/runtime/domain/subagents/child-ownership.ts +160 -0
  330. package/src/runtime/domain/subagents/child-preflight.mjs +38 -0
  331. package/src/runtime/domain/subagents/child-process-list.domain.mjs +7 -0
  332. package/src/runtime/domain/subagents/child-process-list.ts +8 -0
  333. package/src/runtime/domain/subagents/child-runtime.mjs +67 -0
  334. package/src/runtime/domain/subagents/child-steer.domain.mjs +109 -0
  335. package/src/runtime/domain/subagents/child-steer.ts +102 -0
  336. package/src/runtime/domain/subagents/cleanup.domain.mjs +818 -0
  337. package/src/runtime/domain/subagents/cleanup.ts +1017 -0
  338. package/src/runtime/domain/subagents/codex-import.domain.mjs +575 -0
  339. package/src/runtime/domain/subagents/codex-import.ts +717 -0
  340. package/src/runtime/domain/subagents/completion.domain.mjs +6 -0
  341. package/src/runtime/domain/subagents/completion.mjs +152 -0
  342. package/src/runtime/domain/subagents/completion.ts +11 -0
  343. package/src/runtime/domain/subagents/config.domain.mjs +248 -0
  344. package/src/runtime/domain/subagents/config.json +15 -0
  345. package/src/runtime/domain/subagents/config.ts +328 -0
  346. package/src/runtime/domain/subagents/continuation-authority.domain.mjs +38 -0
  347. package/src/runtime/domain/subagents/continuation-authority.ts +31 -0
  348. package/src/runtime/domain/subagents/continuation-runtime.domain.mjs +89 -0
  349. package/src/runtime/domain/subagents/continuation-runtime.ts +88 -0
  350. package/src/runtime/domain/subagents/continuation.domain.mjs +942 -0
  351. package/src/runtime/domain/subagents/continuation.ts +1051 -0
  352. package/src/runtime/domain/subagents/delegation.domain.mjs +19 -0
  353. package/src/runtime/domain/subagents/delegation.ts +24 -0
  354. package/src/runtime/domain/subagents/effective-settings.domain.mjs +130 -0
  355. package/src/runtime/domain/subagents/effective-settings.ts +184 -0
  356. package/src/runtime/domain/subagents/extensions.domain.mjs +6 -0
  357. package/src/runtime/domain/subagents/extensions.mjs +164 -0
  358. package/src/runtime/domain/subagents/extensions.ts +19 -0
  359. package/src/runtime/domain/subagents/failures.domain.mjs +362 -0
  360. package/src/runtime/domain/subagents/failures.ts +319 -0
  361. package/src/runtime/domain/subagents/finalization.domain.mjs +168 -0
  362. package/src/runtime/domain/subagents/finalization.ts +218 -0
  363. package/src/runtime/domain/subagents/git-remotes.domain.mjs +351 -0
  364. package/src/runtime/domain/subagents/git-remotes.ts +413 -0
  365. package/src/runtime/domain/subagents/git-workspace.domain.mjs +337 -0
  366. package/src/runtime/domain/subagents/git-workspace.ts +430 -0
  367. package/src/runtime/domain/subagents/goal-provider.domain.mjs +125 -0
  368. package/src/runtime/domain/subagents/goal-provider.ts +132 -0
  369. package/src/runtime/domain/subagents/health-observation.domain.mjs +617 -0
  370. package/src/runtime/domain/subagents/health-observation.ts +818 -0
  371. package/src/runtime/domain/subagents/health-surface.mjs +284 -0
  372. package/src/runtime/domain/subagents/health.domain.mjs +261 -0
  373. package/src/runtime/domain/subagents/health.ts +343 -0
  374. package/src/runtime/domain/subagents/historical-attention.domain.mjs +37 -0
  375. package/src/runtime/domain/subagents/historical-attention.ts +35 -0
  376. package/src/runtime/domain/subagents/incident-model.domain.mjs +322 -0
  377. package/src/runtime/domain/subagents/incident-model.ts +358 -0
  378. package/src/runtime/domain/subagents/index.domain.mjs +4731 -0
  379. package/src/runtime/domain/subagents/index.ts +4781 -0
  380. package/src/runtime/domain/subagents/launch-abort.domain.mjs +13 -0
  381. package/src/runtime/domain/subagents/launch-abort.ts +21 -0
  382. package/src/runtime/domain/subagents/launch-context.domain.mjs +24 -0
  383. package/src/runtime/domain/subagents/launch-context.ts +23 -0
  384. package/src/runtime/domain/subagents/launch-digest.mjs +6 -0
  385. package/src/runtime/domain/subagents/lifecycle.domain.mjs +265 -0
  386. package/src/runtime/domain/subagents/lifecycle.ts +360 -0
  387. package/src/runtime/domain/subagents/list.domain.mjs +2 -0
  388. package/src/runtime/domain/subagents/list.mjs +152 -0
  389. package/src/runtime/domain/subagents/list.ts +19 -0
  390. package/src/runtime/domain/subagents/log-cursor.domain.mjs +217 -0
  391. package/src/runtime/domain/subagents/log-cursor.ts +268 -0
  392. package/src/runtime/domain/subagents/managed-background-capability.domain.mjs +10 -0
  393. package/src/runtime/domain/subagents/managed-background-capability.ts +9 -0
  394. package/src/runtime/domain/subagents/managed-failure-worker.mjs +36 -0
  395. package/src/runtime/domain/subagents/managed-launch-bootstrap.mjs +48 -0
  396. package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +75 -0
  397. package/src/runtime/domain/subagents/managed-launch-client.ts +59 -0
  398. package/src/runtime/domain/subagents/managed-launch-host.domain.mjs +627 -0
  399. package/src/runtime/domain/subagents/managed-launch-host.ts +504 -0
  400. package/src/runtime/domain/subagents/managed-launch-journal.mjs +17 -0
  401. package/src/runtime/domain/subagents/managed-launch-ownership.domain.mjs +29 -0
  402. package/src/runtime/domain/subagents/managed-launch-ownership.ts +22 -0
  403. package/src/runtime/domain/subagents/managed-launch-port.domain.mjs +2 -0
  404. package/src/runtime/domain/subagents/managed-launch-port.ts +25 -0
  405. package/src/runtime/domain/subagents/managed-launch-recovery.domain.mjs +29 -0
  406. package/src/runtime/domain/subagents/managed-launch-recovery.ts +45 -0
  407. package/src/runtime/domain/subagents/managed-worker-bridge.domain.mjs +63 -0
  408. package/src/runtime/domain/subagents/managed-worker-bridge.ts +48 -0
  409. package/src/runtime/domain/subagents/managed-worker.mjs +13 -0
  410. package/src/runtime/domain/subagents/model-resolution-core.domain.mjs +822 -0
  411. package/src/runtime/domain/subagents/model-resolution-core.ts +1074 -0
  412. package/src/runtime/domain/subagents/model-resolution.domain.mjs +22 -0
  413. package/src/runtime/domain/subagents/model-resolution.ts +32 -0
  414. package/src/runtime/domain/subagents/navigator.domain.mjs +6 -0
  415. package/src/runtime/domain/subagents/navigator.mjs +1233 -0
  416. package/src/runtime/domain/subagents/navigator.ts +39 -0
  417. package/src/runtime/domain/subagents/operation-bridge-types.domain.mjs +1012 -0
  418. package/src/runtime/domain/subagents/operation-bridge-types.ts +1156 -0
  419. package/src/runtime/domain/subagents/outage-observations.domain.mjs +84 -0
  420. package/src/runtime/domain/subagents/outage-observations.ts +73 -0
  421. package/src/runtime/domain/subagents/output-payload.domain.mjs +767 -0
  422. package/src/runtime/domain/subagents/output-payload.ts +987 -0
  423. package/src/runtime/domain/subagents/owned-exit.domain.mjs +12 -0
  424. package/src/runtime/domain/subagents/owned-exit.ts +12 -0
  425. package/src/runtime/domain/subagents/package.json +86 -0
  426. package/src/runtime/domain/subagents/park-checkpoint.domain.mjs +55 -0
  427. package/src/runtime/domain/subagents/park-checkpoint.ts +61 -0
  428. package/src/runtime/domain/subagents/parse.domain.mjs +1218 -0
  429. package/src/runtime/domain/subagents/parse.ts +1451 -0
  430. package/src/runtime/domain/subagents/permission-policy.domain.mjs +232 -0
  431. package/src/runtime/domain/subagents/permission-policy.ts +291 -0
  432. package/src/runtime/domain/subagents/process-identity.mjs +33 -0
  433. package/src/runtime/domain/subagents/registry.domain.mjs +1584 -0
  434. package/src/runtime/domain/subagents/registry.ts +1904 -0
  435. package/src/runtime/domain/subagents/role-assignment.domain.mjs +104 -0
  436. package/src/runtime/domain/subagents/role-assignment.ts +141 -0
  437. package/src/runtime/domain/subagents/roles/role.architect.md +13 -0
  438. package/src/runtime/domain/subagents/roles/role.developer.md +16 -0
  439. package/src/runtime/domain/subagents/roles/role.explorer.md +13 -0
  440. package/src/runtime/domain/subagents/roles/role.product-manager.md +13 -0
  441. package/src/runtime/domain/subagents/roles/role.researcher.md +13 -0
  442. package/src/runtime/domain/subagents/roles/role.reviewer.md +13 -0
  443. package/src/runtime/domain/subagents/roles/role.writer.md +12 -0
  444. package/src/runtime/domain/subagents/sandbox.domain.mjs +64 -0
  445. package/src/runtime/domain/subagents/sandbox.ts +92 -0
  446. package/src/runtime/domain/subagents/session-selection.domain.mjs +32 -0
  447. package/src/runtime/domain/subagents/session-selection.ts +35 -0
  448. package/src/runtime/domain/subagents/session-store.domain.mjs +489 -0
  449. package/src/runtime/domain/subagents/session-store.ts +468 -0
  450. package/src/runtime/domain/subagents/settings-page.domain.mjs +313 -0
  451. package/src/runtime/domain/subagents/settings-page.ts +363 -0
  452. package/src/runtime/domain/subagents/shared-callback-batcher.domain.mjs +777 -0
  453. package/src/runtime/domain/subagents/shared-callback-batcher.ts +956 -0
  454. package/src/runtime/domain/subagents/shared-catalog.domain.mjs +70 -0
  455. package/src/runtime/domain/subagents/shared-catalog.ts +61 -0
  456. package/src/runtime/domain/subagents/shared-execution-policy.domain.mjs +50 -0
  457. package/src/runtime/domain/subagents/shared-execution-policy.ts +61 -0
  458. package/src/runtime/domain/subagents/shared-failure-observations.domain.mjs +1078 -0
  459. package/src/runtime/domain/subagents/shared-failure-observations.ts +1166 -0
  460. package/src/runtime/domain/subagents/shared-harness-settings.domain.mjs +126 -0
  461. package/src/runtime/domain/subagents/shared-harness-settings.ts +116 -0
  462. package/src/runtime/domain/subagents/shared-log-utils.domain.mjs +1223 -0
  463. package/src/runtime/domain/subagents/shared-log-utils.ts +1492 -0
  464. package/src/runtime/domain/subagents/shared-navigator-panels.domain.mjs +289 -0
  465. package/src/runtime/domain/subagents/shared-navigator-panels.ts +272 -0
  466. package/src/runtime/domain/subagents/shared-navigator.domain.mjs +1930 -0
  467. package/src/runtime/domain/subagents/shared-navigator.ts +1962 -0
  468. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-inbox.mjs +144 -0
  469. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-observation.mjs +189 -0
  470. package/src/runtime/domain/subagents/shared-operation-coordinator/index.domain.mjs +51 -0
  471. package/src/runtime/domain/subagents/shared-operation-coordinator/index.ts +122 -0
  472. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
  473. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  474. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +163 -0
  475. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.ts +174 -0
  476. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-parent-callbacks.domain.mjs +66 -0
  477. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-parent-callbacks.ts +68 -0
  478. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.domain.mjs +87 -0
  479. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.ts +90 -0
  480. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.domain.mjs +97 -0
  481. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.ts +139 -0
  482. package/src/runtime/domain/subagents/shared-operation-coordinator/src/errors.domain.mjs +12 -0
  483. package/src/runtime/domain/subagents/shared-operation-coordinator/src/errors.ts +79 -0
  484. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.domain.mjs +342 -0
  485. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.ts +513 -0
  486. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.domain.mjs +283 -0
  487. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.ts +458 -0
  488. package/src/runtime/domain/subagents/shared-operation-coordinator/src/recovery.domain.mjs +52 -0
  489. package/src/runtime/domain/subagents/shared-operation-coordinator/src/recovery.ts +55 -0
  490. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.domain.mjs +114 -0
  491. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.ts +140 -0
  492. package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.domain.mjs +280 -0
  493. package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.ts +442 -0
  494. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +420 -0
  495. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +441 -0
  496. package/src/runtime/domain/subagents/shared-operation-coordinator/src/sqlite.domain.mjs +194 -0
  497. package/src/runtime/domain/subagents/shared-operation-coordinator/src/sqlite.ts +239 -0
  498. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +275 -0
  499. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +585 -0
  500. package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.domain.mjs +120 -0
  501. package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.ts +142 -0
  502. package/src/runtime/domain/subagents/shared-operation-coordinator/src/task-cancellation.domain.mjs +188 -0
  503. package/src/runtime/domain/subagents/shared-operation-coordinator/src/task-cancellation.ts +224 -0
  504. package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.domain.mjs +25 -0
  505. package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.ts +707 -0
  506. package/src/runtime/domain/subagents/shared-operation-coordinator/src/upgrade.domain.mjs +22 -0
  507. package/src/runtime/domain/subagents/shared-operation-coordinator/src/upgrade.ts +22 -0
  508. package/src/runtime/domain/subagents/shared-operation-coordinator/src/validate.domain.mjs +234 -0
  509. package/src/runtime/domain/subagents/shared-operation-coordinator/src/validate.ts +241 -0
  510. package/src/runtime/domain/subagents/shared-operation-coordinator/src/waits.domain.mjs +851 -0
  511. package/src/runtime/domain/subagents/shared-operation-coordinator/src/waits.ts +1424 -0
  512. package/src/runtime/domain/subagents/shared-permission-blocker.domain.mjs +40 -0
  513. package/src/runtime/domain/subagents/shared-permission-blocker.ts +48 -0
  514. package/src/runtime/domain/subagents/shared-render-scheduler.domain.mjs +41 -0
  515. package/src/runtime/domain/subagents/shared-render-scheduler.ts +47 -0
  516. package/src/runtime/domain/subagents/shared-sandbox-core.domain.mjs +1531 -0
  517. package/src/runtime/domain/subagents/shared-sandbox-core.ts +1757 -0
  518. package/src/runtime/domain/subagents/shared-sandbox-diagnostics.domain.mjs +591 -0
  519. package/src/runtime/domain/subagents/shared-sandbox-diagnostics.ts +491 -0
  520. package/src/runtime/domain/subagents/shared-stall-detector.domain.mjs +37 -0
  521. package/src/runtime/domain/subagents/shared-stall-detector.ts +69 -0
  522. package/src/runtime/domain/subagents/shared-task-application.domain.mjs +185 -0
  523. package/src/runtime/domain/subagents/shared-task-application.ts +185 -0
  524. package/src/runtime/domain/subagents/shared-task-apply-patch.domain.mjs +416 -0
  525. package/src/runtime/domain/subagents/shared-task-apply-patch.ts +409 -0
  526. package/src/runtime/domain/subagents/shared-task-exec.domain.mjs +325 -0
  527. package/src/runtime/domain/subagents/shared-task-exec.ts +335 -0
  528. package/src/runtime/domain/subagents/shared-task-files.domain.mjs +346 -0
  529. package/src/runtime/domain/subagents/shared-task-files.ts +342 -0
  530. package/src/runtime/domain/subagents/shared-task-process-identity.domain.mjs +140 -0
  531. package/src/runtime/domain/subagents/shared-task-process-identity.ts +126 -0
  532. package/src/runtime/domain/subagents/shared-task-process-list.domain.mjs +220 -0
  533. package/src/runtime/domain/subagents/shared-task-process-list.ts +209 -0
  534. package/src/runtime/domain/subagents/shared-task-sandbox.domain.mjs +227 -0
  535. package/src/runtime/domain/subagents/shared-task-sandbox.ts +224 -0
  536. package/src/runtime/domain/subagents/shared-task-tools.domain.mjs +92 -0
  537. package/src/runtime/domain/subagents/shared-task-tools.ts +123 -0
  538. package/src/runtime/domain/subagents/shared-work-client.mjs +303 -0
  539. package/src/runtime/domain/subagents/shared-worktree-context.domain.mjs +142 -0
  540. package/src/runtime/domain/subagents/shared-worktree-context.ts +158 -0
  541. package/src/runtime/domain/subagents/skill-picker.domain.mjs +316 -0
  542. package/src/runtime/domain/subagents/skill-picker.ts +353 -0
  543. package/src/runtime/domain/subagents/skills.domain.mjs +138 -0
  544. package/src/runtime/domain/subagents/skills.ts +183 -0
  545. package/src/runtime/domain/subagents/spawn.domain.mjs +72 -0
  546. package/src/runtime/domain/subagents/spawn.ts +80 -0
  547. package/src/runtime/domain/subagents/stop.domain.mjs +184 -0
  548. package/src/runtime/domain/subagents/stop.ts +217 -0
  549. package/src/runtime/domain/subagents/subagent-tools.domain.mjs +101 -0
  550. package/src/runtime/domain/subagents/subagent-tools.ts +137 -0
  551. package/src/runtime/domain/subagents/task-guard.domain.mjs +163 -0
  552. package/src/runtime/domain/subagents/task-guard.ts +144 -0
  553. package/src/runtime/domain/subagents/task-policy.domain.mjs +201 -0
  554. package/src/runtime/domain/subagents/task-policy.ts +236 -0
  555. package/src/runtime/domain/subagents/task-runtime.mjs +53 -0
  556. package/src/runtime/domain/subagents/task-tool-owner.domain.mjs +18 -0
  557. package/src/runtime/domain/subagents/task-tool-owner.ts +21 -0
  558. package/src/runtime/domain/subagents/thinking.domain.mjs +22 -0
  559. package/src/runtime/domain/subagents/thinking.ts +28 -0
  560. package/src/runtime/domain/subagents/tier-policy.domain.mjs +75 -0
  561. package/src/runtime/domain/subagents/tier-policy.ts +126 -0
  562. package/src/runtime/domain/subagents/timing-notifications.domain.mjs +51 -0
  563. package/src/runtime/domain/subagents/timing-notifications.ts +37 -0
  564. package/src/runtime/domain/subagents/timing.domain.mjs +487 -0
  565. package/src/runtime/domain/subagents/timing.ts +634 -0
  566. package/src/runtime/domain/subagents/tools.domain.mjs +558 -0
  567. package/src/runtime/domain/subagents/tools.ts +629 -0
  568. package/src/runtime/domain/subagents/widget.domain.mjs +6 -0
  569. package/src/runtime/domain/subagents/widget.mjs +246 -0
  570. package/src/runtime/domain/subagents/widget.ts +30 -0
  571. package/src/runtime/domain/subagents/work-observation.domain.mjs +316 -0
  572. package/src/runtime/domain/subagents/work-observation.ts +248 -0
  573. package/src/runtime/domain/subagents/worker-catalog.domain.mjs +120 -0
  574. package/src/runtime/domain/subagents/worker-catalog.ts +162 -0
  575. package/src/runtime/domain/subagents/worker-operations-host.domain.mjs +1009 -0
  576. package/src/runtime/domain/subagents/worker-operations-host.ts +1238 -0
  577. package/src/runtime/domain/subagents/worker-waits.domain.mjs +2336 -0
  578. package/src/runtime/domain/subagents/worker-waits.ts +2878 -0
  579. package/src/runtime/domain/subagents/workspace-scope.domain.mjs +52 -0
  580. package/src/runtime/domain/subagents/workspace-scope.ts +50 -0
  581. package/src/runtime/health-config.ts +27 -11
  582. package/src/runtime/log-checkpoints.ts +117 -0
  583. package/src/runtime/mutation-store.ts +5 -4
  584. package/src/runtime/queries.ts +27 -3
  585. package/src/runtime/query-executor.ts +178 -34
  586. package/src/runtime/query-worker.mjs +119 -22
  587. package/src/runtime/read-model.ts +939 -113
  588. package/src/runtime/read-watchdog-probe.ts +4 -0
  589. package/src/runtime/result-supervision.ts +188 -16
  590. package/src/runtime/source-watch.ts +175 -0
  591. package/src/runtime/subagent-launch.ts +73 -0
  592. package/src/runtime/work-budget.ts +130 -0
  593. package/src/runtime/work-client.d.mts +8 -0
  594. package/src/runtime/work-client.mjs +150 -7
  595. package/src/server.ts +185 -22
  596. package/src/session-activity.ts +26 -4
  597. package/src/version.ts +1 -1
@@ -0,0 +1,1904 @@
1
+ /**
2
+ * Run registry — durable metadata for each spawned subagent.
3
+ *
4
+ * The authoritative record for every run is a `meta.json` sidecar on disk, so
5
+ * `list` / `output` / `result` keep working across foreground turns, `/reload`,
6
+ * and even a full pi restart. In-memory state holds only the live exit handlers
7
+ * for runs this process spawned.
8
+ *
9
+ * Catalog launches may attach an optional immutable `catalog` snapshot to that
10
+ * same record. Display-label reservations live under `{baseDir()}/labels`
11
+ * (see catalog-identity.ts). They are not a second registry, and removing a
12
+ * run directory does not delete them.
13
+ */
14
+
15
+ import type { RunTiming } from "./timing.ts";
16
+ import { assignmentRetainsEvidence } from "./assignment-outcomes.ts";
17
+ import type { SkillExposureSource } from "./skills.ts";
18
+ import { processStartToken } from "./process-identity.mjs";
19
+ export { processStartToken } from "./process-identity.mjs";
20
+ import { createHash, randomBytes } from "node:crypto";
21
+ import { closeSync, existsSync, fsyncSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
22
+ import { createRequire } from "node:module";
23
+ import { readFile, readdir } from "node:fs/promises";
24
+ import { tmpdir } from "node:os";
25
+ import { basename, dirname, join } from "node:path";
26
+ import { processExists } from "./spawn.ts";
27
+ import type { LifecycleClassification } from "./lifecycle.ts";
28
+ import {
29
+ archiveCompletedAttempt,
30
+ durableSessionsDir,
31
+ listArchivedAttempts,
32
+ readArchivedAttempt,
33
+ recordArchiveStatusTombstone,
34
+ } from "./session-store.ts";
35
+ import { failureIdentity, observeFailures, readFailureState } from "./shared-failure-observations.ts";
36
+
37
+ /**
38
+ * Terminal + live statuses as recorded on disk. `orphaned` is durable and
39
+ * NON-terminal (supervision broke, but related processes may still be alive);
40
+ * `lost` is durable and terminal (no related process evidence remains).
41
+ */
42
+ export type RunStatus = "running" | "completed" | "failed" | "killed" | "orphaned" | "lost";
43
+
44
+ export interface RunCallbackOrigin {
45
+ cwd: string;
46
+ sessionId?: string;
47
+ branchId?: string | null;
48
+ }
49
+
50
+ /**
51
+ * JSON value inside a catalog launch snapshot. The snapshot is structurally
52
+ * flexible: known sections are identity, effective configuration, and
53
+ * provenance, and callers may add further JSON fields without a schema bump.
54
+ */
55
+ export type CatalogJson =
56
+ | null
57
+ | boolean
58
+ | number
59
+ | string
60
+ | CatalogJson[]
61
+ | { [key: string]: CatalogJson | undefined };
62
+
63
+ /**
64
+ * Launch-time catalog record stored on the run. Every section is optional so
65
+ * a partial snapshot still round-trips; legacy metadata simply omits `catalog`.
66
+ * Once `writeMeta` has persisted a snapshot, later writes keep that value.
67
+ */
68
+ export interface CatalogLaunchSnapshot {
69
+ /** Role/agent identity, display label, and alias captured at launch. */
70
+ identity?: CatalogJson;
71
+ /** Effective instructions, model, effort, and related launch configuration. */
72
+ effective?: CatalogJson;
73
+ /** Why the definition, model, and effort won. */
74
+ provenance?: CatalogJson;
75
+ [key: string]: CatalogJson | undefined;
76
+ }
77
+
78
+ /**
79
+ * True when coherent child-exit evidence may finalize a run in this status.
80
+ * `running` is the normal path; `orphaned`/`lost` are PROVISIONAL
81
+ * reconciliation verdicts (a health tick can observe the just-exited pid
82
+ * before the close handler runs) that the real exit — the stronger evidence —
83
+ * supersedes. True terminal records are never overwritten: finalization is
84
+ * idempotent (`completed`/`failed`) and a deliberate `subagent_stop` kill
85
+ * (`killed`) is not undone by the resulting exit.
86
+ */
87
+ export function canExitFinalize(status: RunStatus): boolean {
88
+ return status === "running" || status === "orphaned" || status === "lost";
89
+ }
90
+
91
+ /**
92
+ * Effective launch recipe captured at spawn, sufficient to reconstruct a
93
+ * continuation attempt. Attempt identity and conversation identity are
94
+ * separate: `attemptId` is this record's run id, `sessionId` is the native
95
+ * conversation shared by every attempt of the same owner.
96
+ *
97
+ * The recipe freezes what was actually launched (resolved tools, exclusions,
98
+ * clean/nesting/approval intent, confinement, effective model and effort), not
99
+ * the configuration that happened to be set later. A continuation re-applies
100
+ * current mandatory human permissions and never re-resolves the catalog.
101
+ */
102
+ export interface LaunchRecipe {
103
+ version: 1;
104
+ /** Attempt that first recorded this recipe. */
105
+ attemptId: string;
106
+ /** Native conversation identity shared by every continuation attempt. */
107
+ sessionId: string;
108
+ /** Directory holding the saved conversation JSONL. */
109
+ sessionDir: string;
110
+ /** Canonical workspace the attempt ran in. */
111
+ cwd: string;
112
+ model?: string;
113
+ effort?: string;
114
+ /** Effective tool allowlist (already adjusted for confinement). */
115
+ tools: string;
116
+ /** Inherited trusted tools may be registered but inactive in the child. Older recipes are strict. */
117
+ optionalTrustedTools?: string[];
118
+ excludeTools?: string;
119
+ /**
120
+ * Effective skill exposure: absent means discovery of the user catalog,
121
+ * `[]` means none, and paths mean exactly those skills. Recipes written
122
+ * before skill controls existed have no key and keep discovery.
123
+ */
124
+ skills?: string[];
125
+ clean: boolean;
126
+ allowNested: boolean;
127
+ approve: boolean;
128
+ sandbox: boolean;
129
+ /** Confinement root when the attempt was sandboxed. */
130
+ sandboxDir?: string;
131
+ gitCloneWorkspace: boolean;
132
+ callback: boolean;
133
+ name?: string;
134
+ agent?: string;
135
+ role?: string | readonly string[];
136
+ alias?: string;
137
+ catalog?: CatalogLaunchSnapshot;
138
+ /** Absent on recipes that predate explicit ordinary worker providers. */
139
+ toolLoadingVersion?: 1;
140
+ /** Resolved extension arguments; a changed implementation requires explicit replacement. */
141
+ extensionArgs?: string[];
142
+ /** Provider/tool runtime arguments, excluding permission-dependent trusted tools. */
143
+ baseExtensionArgs?: string[];
144
+ /** Published worker closure retained for this conversation across server upgrades. */
145
+ runtimeRoot?: string;
146
+ /** Initial trusted implementations survive revocation so re-grants cannot replace them. */
147
+ trustedExtensions?: { name: string; package: string; loadPath: string }[];
148
+ }
149
+
150
+ export interface RunMeta {
151
+ outcomeSupport?: { version: 1; available: boolean; reason?: string };
152
+ assignment?: import("./assignment-outcomes.ts").AssignmentBinding;
153
+ id: string;
154
+ name?: string;
155
+ status: RunStatus;
156
+ /** Child process PID. */
157
+ pid: number;
158
+ /** Child's process group id, captured at spawn where available (#63). */
159
+ pgid?: number;
160
+ /**
161
+ * Opaque process-start identity token captured at spawn where available
162
+ * (#63). Only equality is meaningful: a different token means the pid was
163
+ * recycled by an unrelated process.
164
+ */
165
+ pidStartTime?: string;
166
+ /** Consecutive pid-gone health ticks with no related evidence (old metadata). */
167
+ probeMisses?: number;
168
+ /** When supervision was observed broken (transition to `orphaned`). */
169
+ orphanedAt?: number;
170
+ /** When the last related process evidence disappeared (transition to `lost`). */
171
+ lostAt?: number;
172
+ /**
173
+ * Durable per-status health-callback handoff markers (#65).
174
+ * Written only after a successful coordinator handoff (sendMessage returned,
175
+ * or callback:false suppressed the model path intentionally). Once set,
176
+ * repeated health ticks and /reload must not re-fire that status. A missing
177
+ * marker on orphaned/lost means recovery must still attempt delivery.
178
+ * Independent of completion callbacks.
179
+ */
180
+ orphanedCallbackSentAt?: number;
181
+ lostCallbackSentAt?: number;
182
+ /** PID of the pi process that launched this run (for cross-restart ownership). */
183
+ spawnPid: number;
184
+ /**
185
+ * Start-identity token of the SPAWNING pi, captured at spawn where the OS
186
+ * exposes one. Optional and additive: older metadata parses unchanged. Only
187
+ * equality is meaningful — a different token proves the parent pid was
188
+ * recycled by an unrelated process, which is how `isAbandonedByParent` tells
189
+ * a dead session's leftovers from a live session's runs.
190
+ */
191
+ spawnPidStartTime?: string;
192
+ /**
193
+ * When another pi adopted this record because its own spawning pi was gone
194
+ * (status reconciliation only — no callback was delivered). Additive and
195
+ * diagnostic: it explains a `lost` record nobody's session reported.
196
+ */
197
+ adoptedFromLostParentAt?: number;
198
+ /**
199
+ * When a session shutdown ended this extension instance's direct supervision
200
+ * of the run while its detached child was left running (#625). The child is
201
+ * never signalled for a reload/quit: a later session of the same pi process
202
+ * re-adopts the record, and because the instance that held the in-memory
203
+ * exit observer is gone, that session finalizes the run from the child's own
204
+ * coherent log when its process later disappears. Additive and diagnostic;
205
+ * terminal records keep the marker as history.
206
+ */
207
+ supervisionInterruptedAt?: number;
208
+ /** Pi's `session_shutdown` reason that interrupted supervision (`reload`, `quit`, …). */
209
+ supervisionInterruptedReason?: string;
210
+ model?: string;
211
+ /** Reasoning effort passed to the child via Pi's --thinking option. */
212
+ effort?: string;
213
+ /** Effective skill exposure when it is not discovery; absent means discovery. */
214
+ skills?: string[];
215
+ /** Which layer chose that exposure: launch, catalog, config, default, or a replayed recipe. */
216
+ skillsSource?: SkillExposureSource;
217
+ cwd: string;
218
+ /** First ~200 chars of the task prompt, for listings. */
219
+ promptPreview: string;
220
+ startedAt: number;
221
+ endedAt?: number;
222
+ exitCode?: number | null;
223
+ /** Why an otherwise-zero exit is recorded as a non-success. */
224
+ failureReason?: "incomplete-stream";
225
+ /** Named lifecycle quality from exit/stream validation. */
226
+ lifecycleClassification?: LifecycleClassification;
227
+ logPath: string;
228
+ /**
229
+ * Native child conversation id. A fresh launch uses the attempt id; a
230
+ * continuation keeps the prior run's session id, so attempt identity
231
+ * (`id`) and conversation identity diverge. Retention and session cleanup
232
+ * protect conversations by this field, not by run id.
233
+ */
234
+ sessionId: string;
235
+ /**
236
+ * First attempt of this conversation's lineage. Every attempt records it,
237
+ * so retention, cleanup protection, and ownership resolve one owner even
238
+ * after the attempt that created the conversation is gone.
239
+ */
240
+ rootRunId?: string;
241
+ /** Attempt this run continued, when it was launched by subagent_resume. */
242
+ resumedFrom?: string;
243
+ /** Effective launch recipe, frozen at launch for continuation. */
244
+ recipe?: LaunchRecipe;
245
+ /** Mechanical manager, separate from the original spawnPid capacity domain. */
246
+ management?: { root: string; instance: string; epoch: number };
247
+ /** Foreground session that is allowed to receive unsolicited callbacks. */
248
+ callbackOrigin?: RunCallbackOrigin;
249
+ /** Durable ordinary-completion callback recovery and successful-handoff markers. */
250
+ completionCallbackPendingAt?: number;
251
+ completionCallbackSentAt?: number;
252
+ completionCallbackSuppressedAt?: number;
253
+ completionCallbackSuppressedReason?: string;
254
+ outcomeDeliveryDeferredReason?: string;
255
+ assignmentReport?: { version: 1; assignmentId: string; attemptId: string; digest: string; path: string };
256
+ /** Latest authenticated refusal, cleared when a corrected report is retained. */
257
+ assignmentReportRejection?: { reason: string; rejectedAt: number };
258
+ orphanedCallbackSuppressedAt?: number;
259
+ orphanedCallbackSuppressedReason?: string;
260
+ lostCallbackSuppressedAt?: number;
261
+ lostCallbackSuppressedReason?: string;
262
+ /** Writable dir the child is OS-sandboxed to, if any. */
263
+ sandbox?: string;
264
+ /** Pi is trusted; model task operations use an immutable kernel policy. */
265
+ taskRuntime?: boolean;
266
+ taskScratch?: string;
267
+ /** Whether completion posts the result back to the main session (default true). */
268
+ callback?: boolean;
269
+ /** Batch ID for runs launched via subagent_spawn_batch. */
270
+ batchId?: string;
271
+ /** Optional batch display name. */
272
+ batchName?: string;
273
+ /**
274
+ * Durable navigator-dismissal timestamp (ms since epoch). Optional and
275
+ * additive: pre-existing metadata without this field parses unchanged, so
276
+ * no migration is required. Dismissal is navigator-organization ONLY — it
277
+ * never deletes logs, prompt, session data, metadata, or id-based tool
278
+ * access (`subagent_output` / `subagent_result` / `subagent_stop` /
279
+ * `subagent_list` keep working for dismissed runs).
280
+ */
281
+ dismissedAt?: number;
282
+ catalog?: CatalogLaunchSnapshot;
283
+ /**
284
+ * Durable park disposition for a worker attempt that ended while waiting on
285
+ * an observed dependency. Additive: a record without it is an ordinary run.
286
+ * The attempt status stays `completed`; this field is what distinguishes
287
+ * "this attempt finished" from "the assignment finished" (ADR 0020).
288
+ */
289
+ park?: ParkRecord;
290
+ /**
291
+ * Supervised-operation binding for this attempt. Additive. Records only
292
+ * references (bridge run id, conversation id, authority reference) and the
293
+ * captured worker policy — never the per-run bridge token.
294
+ */
295
+ operations?: RunOperationsBinding;
296
+ /**
297
+ * Harness-owned timing policy and one-shot markers (soft deadline, grace,
298
+ * hard ceiling, tool-wait and stuck windows). Written at launch so /reload
299
+ * keeps it.
300
+ * Additive: runs launched before it have none and are never timed.
301
+ */
302
+ timing?: RunTiming;
303
+ }
304
+
305
+ /** Root of the VOLATILE runtime registry, deliberately OUTSIDE any repo. */
306
+ export function baseDir(): string {
307
+ return join(realpathSync(tmpdir()), "pi-better-subagents");
308
+ }
309
+ /**
310
+ * `--session-dir` for NEW child launches: the durable Pi agent directory
311
+ * (`<agent dir>/subagents/sessions`), not the volatile registry. Saved
312
+ * conversations are ordinary Pi session files, so changing TMPDIR or a restart
313
+ * must not move them. Recipes recorded before this layout keep pointing at the
314
+ * old temporary directory and are read exactly as recorded.
315
+ */
316
+ export function sessionsDir(): string {
317
+ return durableSessionsDir();
318
+ }
319
+ export function taskWorkspaceDir(id: string): string {
320
+ if (!/^sa_[a-z0-9]+_[a-z0-9]+$/i.test(id)) throw new Error("Invalid task workspace run ID.");
321
+ return join(realpathSync(tmpdir()), "pi-better-subagent-workspaces", id);
322
+ }
323
+
324
+ export function runDir(id: string): string {
325
+ return join(baseDir(), "runs", id);
326
+ }
327
+ export function logPathFor(id: string): string {
328
+ return join(runDir(id), "output.log");
329
+ }
330
+ export function promptPathFor(id: string): string {
331
+ return join(runDir(id), "prompt.md");
332
+ }
333
+ function metaPathFor(id: string): string {
334
+ return join(runDir(id), "meta.json");
335
+ }
336
+
337
+ // ---- park disposition and supervised-operations binding -------------------
338
+
339
+ /**
340
+ * Phase of a parked assignment's wait, mirrored from the coordinator record for
341
+ * display, resume decisions and cleanup protection. `consumed`/`cancelled` are
342
+ * terminal; `held` needs its owner.
343
+ */
344
+ export type ParkPhase =
345
+ | "parking"
346
+ | "waiting"
347
+ | "ready"
348
+ | "resuming"
349
+ | "held"
350
+ | "consumed"
351
+ | "cancelled";
352
+
353
+ /** Proof that the wait tool result is the persisted end of the saved conversation. */
354
+ export interface ParkCheckpointIdentity {
355
+ sessionId: string;
356
+ sessionFile: string;
357
+ toolCallId: string;
358
+ entryId: string;
359
+ prefixBytes: number;
360
+ prefixSha256: string;
361
+ }
362
+
363
+ /**
364
+ * Durable park disposition of one attempt: which wait generation it parked on,
365
+ * the verified native checkpoint, and what happened afterwards. Written only by
366
+ * the parent after the checkpoint was verified and the coordinator admitted it,
367
+ * so an attempt cannot claim a park it did not prove.
368
+ */
369
+ export interface ParkRecord {
370
+ version: 1;
371
+ waitId: string;
372
+ generation: number;
373
+ phase: ParkPhase;
374
+ /** Attempt that parked (this run id). */
375
+ attemptId: string;
376
+ /** Foreground owner binding recorded for admission, when known. */
377
+ ownerSessionId?: string;
378
+ ownerWorkspace?: string;
379
+ ownerBranchId?: string | null;
380
+ ownerGoalId?: string | null;
381
+ /** The next reasoning step the worker recorded when it parked. */
382
+ continuationNote?: string;
383
+ /** Verified saved-conversation checkpoint. */
384
+ checkpoint?: ParkCheckpointIdentity;
385
+ /** Last verified coordinator evidence; observation only, never admission authority. */
386
+ observedCoordinator?: { cancelEpoch: number; dependencies: readonly { operationId: string; terminalRevision: number }[] };
387
+ parkedAt: number;
388
+ updatedAt: number;
389
+ /** Why the wait is held instead of continuing. */
390
+ heldReason?: string;
391
+ /** Continuation attempt admitted for this wait generation. */
392
+ resumedAt?: number;
393
+ resumedBy?: string;
394
+ /** Launch token persisted with the attempt id BEFORE the child is spawned. */
395
+ resumeLaunchToken?: string;
396
+ /**
397
+ * Store-issued resume claim identity persisted with the attempt, so a proven
398
+ * failed exit can hold the generation with exact claim identity (the claim
399
+ * token is the same value the durable claim row already stores).
400
+ */
401
+ resumeClaimId?: string;
402
+ resumeClaimToken?: string;
403
+ /** Exact claim whose writer exit has been reconciled with the coordinator. */
404
+ resumeExitReconciledClaimId?: string;
405
+ cancelledAt?: number;
406
+ cancelReason?: string;
407
+ }
408
+
409
+ /** References for a run whose child may use supervised operations. */
410
+ export interface RunOperationsBinding {
411
+ version: 1;
412
+ /** Bridge run id; equals the attempt id. */
413
+ bridgeRunId: string;
414
+ conversationId: string;
415
+ authorityReference: string;
416
+ /** Foreground branch/goal binding recorded for resume admission. */
417
+ branchId?: string | null;
418
+ goalId?: string | null;
419
+ /**
420
+ * Workspace the worker conversation was registered under (the sandbox or clone
421
+ * the child ran in). Background ownership uses this, not the foreground cwd.
422
+ */
423
+ workspace?: string;
424
+ /**
425
+ * Launch token persisted with the resume attempt BEFORE spawn, so a crash
426
+ * between publication and the child's own publication is reconciled instead
427
+ * of relaunched. Never a credential.
428
+ */
429
+ resumeLaunchToken?: string;
430
+ /** Worker policy captured at launch; Background intersects it, never the child. */
431
+ policy: {
432
+ version: 1;
433
+ mandatoryPermissions?: boolean;
434
+ sandbox: unknown;
435
+ tools: readonly string[];
436
+ clean: boolean;
437
+ deadlineAt: number | null;
438
+ };
439
+ /** Tools the child bridge exposes. */
440
+ tools: readonly string[];
441
+ }
442
+
443
+ export function parkRecordPath(id: string): string {
444
+ return join(runDir(id), "park.json");
445
+ }
446
+
447
+ /** Verify the shape before trusting a record read from disk. */
448
+ function parseParkRecord(value: unknown): ParkRecord | undefined {
449
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
450
+ const record = value as Partial<ParkRecord>;
451
+ if (record.version !== 1) return undefined;
452
+ if (typeof record.waitId !== "string" || !record.waitId) return undefined;
453
+ if (!Number.isSafeInteger(record.generation) || (record.generation ?? 0) < 1) return undefined;
454
+ if (typeof record.attemptId !== "string" || !record.attemptId) return undefined;
455
+ if (typeof record.parkedAt !== "number" || !Number.isFinite(record.parkedAt)) return undefined;
456
+ const phases: readonly ParkPhase[] = ["parking", "waiting", "ready", "resuming", "held", "consumed", "cancelled"];
457
+ if (!phases.includes(record.phase as ParkPhase)) return undefined;
458
+ return record as ParkRecord;
459
+ }
460
+
461
+ /**
462
+ * Write the park disposition atomically and mirror it into the run's metadata.
463
+ * The mirror keeps listings, the Goal provider and cleanup from needing a second
464
+ * read; the file remains the authoritative copy for this attempt.
465
+ */
466
+ export function writeParkRecord(id: string, record: ParkRecord, options: { ifAbsent?: boolean } = {}): void {
467
+ if (!/^[A-Za-z0-9_-]+$/.test(id)) throw new Error("Invalid run ID.");
468
+ mkdirSync(runDir(id), { recursive: true });
469
+ const path = parkRecordPath(id);
470
+ const temp = join(dirname(path), `.park.${randomBytes(6).toString("hex")}.tmp`);
471
+ writeFileSync(temp, JSON.stringify(record), { mode: 0o600, flag: "wx" });
472
+ if (options.ifAbsent) {
473
+ try { linkSync(temp, path); }
474
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "EEXIST") return; throw error; }
475
+ finally { unlinkSync(temp); }
476
+ } else renameSync(temp, path);
477
+ const meta = readMeta(id);
478
+ if (meta && (meta.park?.phase !== record.phase
479
+ || meta.park?.heldReason !== record.heldReason
480
+ || meta.park?.resumedBy !== record.resumedBy
481
+ || meta.park?.resumeExitReconciledClaimId !== record.resumeExitReconciledClaimId)) {
482
+ meta.park = record;
483
+ writeMeta(meta);
484
+ }
485
+ }
486
+
487
+ /** Read the attempt's park disposition; absent for an ordinary run. */
488
+ export function readParkRecord(id: string): ParkRecord | undefined {
489
+ try {
490
+ return parseParkRecord(JSON.parse(readFileSync(parkRecordPath(id), "utf-8")));
491
+ } catch (error) {
492
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") return undefined;
493
+ // The volatile run directory may already be reclaimed; the durable
494
+ // completed-attempt record carries the park snapshot taken at finalization.
495
+ return readMeta(id)?.park;
496
+ }
497
+ }
498
+
499
+ /** Merge one phase/reason change into the park disposition. */
500
+ export function updateParkRecord(
501
+ id: string,
502
+ patch: Partial<Omit<ParkRecord, "version" | "waitId" | "generation" | "attemptId" | "parkedAt">>,
503
+ ): ParkRecord | undefined {
504
+ const current = readParkRecord(id);
505
+ if (!current) return undefined;
506
+ const next: ParkRecord = { ...current, ...patch, updatedAt: Date.now() };
507
+ writeParkRecord(id, next);
508
+ return next;
509
+ }
510
+
511
+ /** A park still owns a pending continuation: `parking`, `waiting`, `ready`, `resuming` or `held`. */
512
+ export function isPendingPark(record: Pick<ParkRecord, "phase">): boolean {
513
+ return record.phase !== "consumed" && record.phase !== "cancelled";
514
+ }
515
+
516
+ /**
517
+ * Runs whose park disposition can still resume. Used by cleanup protection and
518
+ * by resume reconciliation; a consumed or cancelled park is not included.
519
+ */
520
+ export function listPendingParkedRuns(metas: readonly RunMeta[] = listMetas()): RunMeta[] {
521
+ return listParkRecordCandidates(metas).filter((meta) => {
522
+ const record = meta.park ?? readParkRecord(meta.id);
523
+ return record !== undefined && isPendingPark(record);
524
+ });
525
+ }
526
+
527
+ /** Include a park file that was published just before its metadata mirror was lost. */
528
+ export function listParkRecordCandidates(metas: readonly RunMeta[] = listMetas()): RunMeta[] {
529
+ let volatileIds: Set<string>;
530
+ try { volatileIds = new Set(readdirSync(join(baseDir(), "runs"))); }
531
+ catch { volatileIds = new Set(); }
532
+ return metas.filter((meta) => meta.park !== undefined
533
+ || (volatileIds.has(meta.id) && existsSync(parkRecordPath(meta.id))));
534
+ }
535
+
536
+ /** Read recovery sidecars in batches so a large registry does not block socket replies. */
537
+ export async function* scanParkRecords(metas: readonly RunMeta[] = listMetas()): AsyncGenerator<{ meta: RunMeta; record: ParkRecord }> {
538
+ const runs = join(baseDir(), "runs");
539
+ const volatileIds = new Set(await readdir(runs).catch(() => [] as string[]));
540
+ const batchSize = 32;
541
+ for (let offset = 0; offset < metas.length; offset += batchSize) {
542
+ const batch = await Promise.all(metas.slice(offset, offset + batchSize).map(async (meta) => {
543
+ if (!meta.park && !volatileIds.has(meta.id)) return;
544
+ try {
545
+ const record = parseParkRecord(JSON.parse(await readFile(join(runs, meta.id, "park.json"), "utf-8")));
546
+ if (record) return { meta, record };
547
+ } catch (error) {
548
+ if ((error as NodeJS.ErrnoException).code === "ENOENT" && meta.park) {
549
+ const record = readMeta(meta.id)?.park;
550
+ if (record) return { meta, record };
551
+ }
552
+ }
553
+ }));
554
+ for (const entry of batch) if (entry) yield entry;
555
+ }
556
+ }
557
+
558
+ /**
559
+ * How long a launch attempt that never produced a child is kept before a sweep
560
+ * reclaims it. Launch preparation takes seconds; the grace only exists so a
561
+ * paused or unusually slow launch in another process is never reclaimed under
562
+ * it. A record this old has no metadata and no log, so it can never become a run.
563
+ */
564
+ export const ABANDONED_LAUNCH_GRACE_MS = 60 * 60 * 1000;
565
+
566
+ /**
567
+ * Parent-authored provenance for a run launched on the trusted task runtime (#325).
568
+ *
569
+ * `meta.taskRuntime` alone lives in the run directory. The parent only honours a child's
570
+ * structured intent and `failure_disposition` calls when this separate record, written by the
571
+ * parent before the child starts, also exists. It sits outside every run directory, under the
572
+ * registry root that the task runtime's policy denies to the child (`runtimeRoots`), so a future
573
+ * child-writable run directory cannot forge trust by rewriting its own metadata.
574
+ */
575
+ export function taskRuntimeProvenancePath(id: string): string {
576
+ if (!/^[A-Za-z0-9_-]+$/.test(id)) throw new Error("Invalid run ID.");
577
+ return join(baseDir(), "task-runtime", `${id}.json`);
578
+ }
579
+ export function recordTaskRuntimeProvenance(id: string): void {
580
+ const path = taskRuntimeProvenancePath(id);
581
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
582
+ writeFileSync(path, JSON.stringify({ version: 1, id }), { mode: 0o600 });
583
+ }
584
+ /**
585
+ * Remove a run directory together with its provenance record (#325). Every run-removal path
586
+ * uses this, so no provenance outlives its run. Throws when the run directory cannot be removed.
587
+ */
588
+ export function removeRunDirectory(id: string): void {
589
+ const meta = readMeta(id);
590
+ if (meta && assignmentRetainsEvidence(meta)) throw new Error("Assignment outcome or uncertain writer still retains this run's evidence.");
591
+ rmSync(runDir(id), { recursive: true, force: true });
592
+ removeTaskRuntimeProvenance(id);
593
+ }
594
+ /**
595
+ * Undo everything a launch prepared before its child failed to spawn (#325, #332). Nothing references
596
+ * the run yet (no metadata), so its run directory and provenance go, plus the per-run session
597
+ * directory and disposable clone workspace of a sandboxed launch and the task scratch. Only the
598
+ * run's own paths are removed: a shared sessions directory or a caller-chosen sandbox_dir is kept.
599
+ */
600
+ export function discardFailedLaunch(id: string, prepared: { sessionDir?: string; workspaceDir?: string; scratch?: string } = {}): void {
601
+ try { removeRunDirectory(id); } catch { /* best effort */ }
602
+ const remove = (path: string) => { try { rmSync(path, { recursive: true, force: true }); } catch { /* best effort */ } };
603
+ if (prepared.sessionDir && prepared.sessionDir === join(sessionsDir(), id)) remove(prepared.sessionDir);
604
+ if (prepared.workspaceDir && /^sa_[a-z0-9]+_[a-z0-9]+$/i.test(id) && prepared.workspaceDir === taskWorkspaceDir(id)) remove(prepared.workspaceDir);
605
+ if (prepared.scratch) remove(prepared.scratch);
606
+ }
607
+ /** Best-effort removal of a run's provenance record (e.g. after a failed launch). */
608
+ export function removeTaskRuntimeProvenance(id: string): void {
609
+ try { rmSync(taskRuntimeProvenancePath(id), { force: true }); } catch { /* invalid id or already gone */ }
610
+ }
611
+ /**
612
+ * Provenance records whose run directory no longer exists (e.g. removed by an older version). Only a
613
+ * definite ENOENT counts as gone: any other stat error (permissions, I/O) keeps the record, since
614
+ * deleting a live run's provenance would silently drop it to the exact-retry rule (#332).
615
+ */
616
+ export function orphanedTaskRuntimeProvenance(): string[] {
617
+ let names: string[];
618
+ try { names = readdirSync(join(baseDir(), "task-runtime")); } catch { return []; }
619
+ return names.filter((name) => name.endsWith(".json")).map((name) => name.slice(0, -5))
620
+ .filter((id) => { try { statSync(runDir(id)); return false; } catch (error) { return (error as NodeJS.ErrnoException).code === "ENOENT"; } });
621
+ }
622
+ /**
623
+ * Whether the parent may honour structured intent for this run. `unknown` means the answer could
624
+ * not be read right now (unreadable metadata or provenance); callers retry instead of caching it.
625
+ * A missing or mismatched provenance record is a definite `unconfined` (the exact-retry rule).
626
+ */
627
+ export function taskRuntimeTrust(id: string): "trusted" | "unconfined" | "unknown" {
628
+ let raw: string;
629
+ try { raw = readFileSync(taskRuntimeProvenancePath(id), "utf-8"); }
630
+ catch (error) { return (error as NodeJS.ErrnoException).code === "ENOENT" ? "unconfined" : "unknown"; }
631
+ let record: unknown;
632
+ try { record = JSON.parse(raw); } catch { return "unconfined"; }
633
+ if (!record || typeof record !== "object" || (record as { id?: unknown }).id !== id) return "unconfined";
634
+ const inspected = inspectRunMeta(id);
635
+ if (inspected.kind !== "ok") return "unknown";
636
+ return inspected.meta.taskRuntime === true ? "trusted" : "unconfined";
637
+ }
638
+
639
+ /**
640
+ * Name and catalog from a single launch publication.
641
+ * `catalogKnown` is false when the winning snapshot omitted `catalog`.
642
+ * Explicit null is known and must not be replaced by a later object.
643
+ */
644
+ interface LaunchRecord {
645
+ name?: string;
646
+ catalogKnown: boolean;
647
+ catalog?: CatalogLaunchSnapshot | null;
648
+ }
649
+
650
+ function launchRecordPath(id: string): string {
651
+ return join(runDir(id), ".launch.json");
652
+ }
653
+
654
+ function launchFromSource(source: { name?: unknown; catalog?: CatalogLaunchSnapshot | null }): LaunchRecord {
655
+ const name = typeof source.name === "string" && source.name.length > 0 ? source.name : undefined;
656
+ const catalogKnown = Object.prototype.hasOwnProperty.call(source, "catalog") && source.catalog !== undefined;
657
+ return { name, catalogKnown, catalog: catalogKnown ? source.catalog : undefined };
658
+ }
659
+
660
+ function serializeLaunch(record: LaunchRecord): string {
661
+ const payload: { name?: string; catalog?: CatalogLaunchSnapshot | null } = {};
662
+ if (record.name !== undefined) payload.name = record.name;
663
+ if (record.catalogKnown) payload.catalog = record.catalog ?? null;
664
+ return JSON.stringify(payload);
665
+ }
666
+
667
+ function parseLaunch(raw: string, id: string): LaunchRecord {
668
+ let parsed: unknown;
669
+ try {
670
+ parsed = JSON.parse(raw);
671
+ } catch (error) {
672
+ if (error instanceof SyntaxError) throw new Error(`Unreadable launch record for ${id}`);
673
+ throw error;
674
+ }
675
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
676
+ throw new Error(`Unreadable launch record for ${id}`);
677
+ }
678
+ return launchFromSource(parsed as { name?: unknown; catalog?: CatalogLaunchSnapshot | null });
679
+ }
680
+
681
+ /** A committed meta.json is one historical launch. A truncated file is not. */
682
+ function readCommittedMetaLaunch(id: string): LaunchRecord | undefined {
683
+ let raw: string;
684
+ try {
685
+ raw = readFileSync(metaPathFor(id), "utf-8");
686
+ } catch (error) {
687
+ if (errnoOf(error) === "ENOENT") return undefined;
688
+ throw error;
689
+ }
690
+ try {
691
+ const parsed = JSON.parse(raw) as { name?: unknown; catalog?: CatalogLaunchSnapshot | null };
692
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return undefined;
693
+ return launchFromSource(parsed);
694
+ } catch (error) {
695
+ if (error instanceof SyntaxError) return undefined;
696
+ throw error;
697
+ }
698
+ }
699
+
700
+ function applyLaunchRecord(meta: RunMeta, record: LaunchRecord): void {
701
+ if (record.name !== undefined) meta.name = record.name;
702
+ else delete meta.name;
703
+ if (record.catalogKnown) meta.catalog = record.catalog as CatalogLaunchSnapshot;
704
+ else delete meta.catalog;
705
+ }
706
+
707
+ /**
708
+ * Publish `contents` at `target` so the first complete file wins.
709
+ *
710
+ * `link` of an fsynced temp is atomic: callers either see the winner's
711
+ * bytes or no file. A later link gets EEXIST and leaves the winner in place.
712
+ * This is not another lock. Token recovery can still rename `.meta.lock`
713
+ * after a stale observation (the rename syscall moves whatever inode is at
714
+ * that path), so the lock pathname is not a safe place to remember the
715
+ * first snapshot.
716
+ */
717
+ function publishImmutable(target: string, contents: string): void {
718
+ try {
719
+ statSync(target);
720
+ return;
721
+ } catch (error) {
722
+ if (errnoOf(error) !== "ENOENT") throw error;
723
+ }
724
+ const temp = join(dirname(target), `.immutable.${randomBytes(8).toString("hex")}.tmp`);
725
+ const fd = openSync(temp, "wx");
726
+ try {
727
+ writeFileSync(fd, contents);
728
+ fsyncSync(fd);
729
+ } catch (error) {
730
+ try {
731
+ closeSync(fd);
732
+ } catch (closeError) {
733
+ if (errnoOf(closeError) !== "EBADF") throw closeError;
734
+ }
735
+ try {
736
+ unlinkSync(temp);
737
+ } catch (cleanup) {
738
+ if (errnoOf(cleanup) !== "ENOENT") throw cleanup;
739
+ }
740
+ throw error;
741
+ }
742
+ closeSync(fd);
743
+ try {
744
+ linkSync(temp, target);
745
+ } catch (error) {
746
+ try {
747
+ unlinkSync(temp);
748
+ } catch (cleanup) {
749
+ if (errnoOf(cleanup) !== "ENOENT") throw cleanup;
750
+ }
751
+ if (errnoOf(error) !== "EEXIST") throw error;
752
+ return;
753
+ }
754
+ try {
755
+ unlinkSync(temp);
756
+ } catch (error) {
757
+ if (errnoOf(error) !== "ENOENT") throw error;
758
+ }
759
+ }
760
+
761
+ function readOptionalUtf8(target: string): string | undefined {
762
+ try {
763
+ return readFileSync(target, "utf-8");
764
+ } catch (error) {
765
+ if (errnoOf(error) === "ENOENT") return undefined;
766
+ throw error;
767
+ }
768
+ }
769
+
770
+ /**
771
+ * Freeze one coherent launch snapshot before `meta.json` is replaced.
772
+ *
773
+ * The exclusive link is the publication. A pause or crash before it leaves
774
+ * no snapshot; a pause or crash after it leaves the whole snapshot. Orphan
775
+ * split anchors are not read: pairing those files is the bug this replaces.
776
+ * A legacy `meta.json` is copied in as one record first, so its name and
777
+ * catalog (including absence or null) beat this writer without being
778
+ * reconciled field by field. The caller's object is then rewritten from
779
+ * whichever record won the link.
780
+ */
781
+ function applyFrozenLaunch(meta: RunMeta): void {
782
+ const path = launchRecordPath(meta.id);
783
+ let raw = readOptionalUtf8(path);
784
+ if (raw === undefined) {
785
+ const committed = readCommittedMetaLaunch(meta.id) ?? launchFromSource(meta);
786
+ publishImmutable(path, serializeLaunch(committed));
787
+ raw = readOptionalUtf8(path);
788
+ if (raw === undefined) throw new Error(`Missing launch record for ${meta.id}`);
789
+ }
790
+ applyLaunchRecord(meta, parseLaunch(raw, meta.id));
791
+ }
792
+
793
+ const META_LOCK_WAIT_MS = 5_000;
794
+ const UNPARSABLE_LOCK_GRACE_MS = 1_000;
795
+ const nodeRequire = createRequire(import.meta.url);
796
+ const lockPause = new Int32Array(new SharedArrayBuffer(4));
797
+ const sqliteWarningFilter = Symbol.for("pi-better-subagents.sqlite-warning-filter");
798
+
799
+ class MetadataLockLost extends Error {
800
+ constructor() {
801
+ super("metadata lock lost");
802
+ this.name = "MetadataLockLost";
803
+ }
804
+ }
805
+
806
+ interface LockOwner {
807
+ pid: number;
808
+ token: string;
809
+ start?: string;
810
+ }
811
+
812
+ interface LockDb {
813
+ exec(sql: string): void;
814
+ close(): void;
815
+ }
816
+
817
+ function errnoOf(error: unknown): string | undefined {
818
+ return (error as NodeJS.ErrnoException).code;
819
+ }
820
+
821
+ function sleepMs(ms: number): void {
822
+ Atomics.wait(lockPause, 0, 0, ms);
823
+ }
824
+
825
+ function lockTimeout(id: string): Error {
826
+ return new Error(`Timed out writing metadata for ${id}`);
827
+ }
828
+
829
+ let ownStartKnown = false;
830
+ let ownStartCache: string | undefined;
831
+ const foreignStartCache = new Map<number, { token: string | undefined; at: number }>();
832
+
833
+ function ownStartToken(): string | undefined {
834
+ if (ownStartKnown) return ownStartCache;
835
+ ownStartCache = processStartToken(process.pid);
836
+ ownStartKnown = true;
837
+ return ownStartCache;
838
+ }
839
+
840
+ function cachedStartToken(pid: number): string | undefined {
841
+ const now = Date.now();
842
+ const hit = foreignStartCache.get(pid);
843
+ if (hit && now - hit.at < 200) return hit.token;
844
+ const token = processStartToken(pid);
845
+ foreignStartCache.set(pid, { token, at: now });
846
+ return token;
847
+ }
848
+
849
+ function makeOwner(): LockOwner {
850
+ return { pid: process.pid, token: randomBytes(16).toString("hex"), start: ownStartToken() };
851
+ }
852
+
853
+ function serializeOwner(owner: LockOwner): string {
854
+ return JSON.stringify({ pid: owner.pid, token: owner.token, start: owner.start ?? null });
855
+ }
856
+
857
+ function parseOwner(raw: string): LockOwner | undefined {
858
+ const trimmed = raw.trim();
859
+ if (/^[1-9]\d*$/.test(trimmed)) {
860
+ const pid = Number(trimmed);
861
+ return Number.isSafeInteger(pid) ? { pid, token: "" } : undefined;
862
+ }
863
+ try {
864
+ const parsed = JSON.parse(raw) as { pid?: unknown; token?: unknown; start?: unknown };
865
+ if (!parsed || typeof parsed !== "object") return undefined;
866
+ if (typeof parsed.pid !== "number" || !Number.isInteger(parsed.pid) || parsed.pid <= 0) return undefined;
867
+ if (typeof parsed.token !== "string") return undefined;
868
+ const start = typeof parsed.start === "string" && parsed.start.length > 0 ? parsed.start : undefined;
869
+ return { pid: parsed.pid, token: parsed.token, start };
870
+ } catch {
871
+ return undefined;
872
+ }
873
+ }
874
+
875
+ /** A live pid is never stale, including when that process is stopped or paused. */
876
+ function ownerIsLive(owner: LockOwner): boolean {
877
+ if (owner.pid === process.pid) return true;
878
+ if (!processExists(owner.pid)) return false;
879
+ if (!owner.start) return true;
880
+ const current = cachedStartToken(owner.pid);
881
+ if (!current) return true;
882
+ return current === owner.start;
883
+ }
884
+
885
+ function isStaleLock(lockPath: string, raw: string): boolean {
886
+ const owner = parseOwner(raw);
887
+ if (!owner) {
888
+ try {
889
+ return Date.now() - statSync(lockPath).mtimeMs > UNPARSABLE_LOCK_GRACE_MS;
890
+ } catch (error) {
891
+ if (errnoOf(error) === "ENOENT") return false;
892
+ throw error;
893
+ }
894
+ }
895
+ return !ownerIsLive(owner);
896
+ }
897
+
898
+ function restoreDisplacedLock(grave: string, lockPath: string): void {
899
+ try {
900
+ linkSync(grave, lockPath);
901
+ } catch (error) {
902
+ if (errnoOf(error) !== "EEXIST") throw error;
903
+ let displaced: string;
904
+ try {
905
+ displaced = readFileSync(grave, "utf-8");
906
+ } catch (readError) {
907
+ if (errnoOf(readError) === "ENOENT") return;
908
+ throw readError;
909
+ }
910
+ if (!isStaleLock(grave, displaced)) return;
911
+ try {
912
+ unlinkSync(grave);
913
+ } catch (cleanup) {
914
+ if (errnoOf(cleanup) !== "ENOENT") throw cleanup;
915
+ }
916
+ return;
917
+ }
918
+ try {
919
+ unlinkSync(grave);
920
+ } catch (error) {
921
+ if (errnoOf(error) !== "ENOENT") throw error;
922
+ }
923
+ }
924
+
925
+ /** Drop the lock file only when `predicate` still matches the inode we moved aside. */
926
+ function removeLockIf(lockPath: string, predicate: (raw: string, path: string) => boolean): void {
927
+ let observed: string;
928
+ try {
929
+ observed = readFileSync(lockPath, "utf-8");
930
+ } catch (error) {
931
+ if (errnoOf(error) === "ENOENT") return;
932
+ throw error;
933
+ }
934
+ if (!predicate(observed, lockPath)) return;
935
+ const grave = join(dirname(lockPath), `.meta.lock.${randomBytes(8).toString("hex")}.displaced`);
936
+ try {
937
+ renameSync(lockPath, grave);
938
+ } catch (error) {
939
+ if (errnoOf(error) === "ENOENT") return;
940
+ throw error;
941
+ }
942
+ let moved: string;
943
+ try {
944
+ moved = readFileSync(grave, "utf-8");
945
+ } catch (error) {
946
+ let restoreError: unknown;
947
+ try {
948
+ restoreDisplacedLock(grave, lockPath);
949
+ } catch (restore) {
950
+ restoreError = restore;
951
+ }
952
+ if (restoreError) throw restoreError;
953
+ throw error;
954
+ }
955
+ if (moved === observed && predicate(moved, grave)) {
956
+ try {
957
+ unlinkSync(grave);
958
+ } catch (error) {
959
+ if (errnoOf(error) !== "ENOENT") throw error;
960
+ }
961
+ return;
962
+ }
963
+ restoreDisplacedLock(grave, lockPath);
964
+ }
965
+
966
+ function lockPayloadMatches(lockPath: string, payload: string): boolean {
967
+ try {
968
+ return readFileSync(lockPath, "utf-8") === payload;
969
+ } catch (error) {
970
+ if (errnoOf(error) === "ENOENT") return false;
971
+ throw error;
972
+ }
973
+ }
974
+
975
+ let databaseSyncCtor: (new (path: string) => LockDb) | null | undefined;
976
+
977
+ function databaseSync(): (new (path: string) => LockDb) | null {
978
+ if (databaseSyncCtor !== undefined) return databaseSyncCtor;
979
+ installSqliteWarningFilter();
980
+ try {
981
+ const loaded = nodeRequire("node:sqlite") as { DatabaseSync?: new (path: string) => LockDb };
982
+ databaseSyncCtor = loaded.DatabaseSync ?? null;
983
+ } catch (error) {
984
+ const code = errnoOf(error);
985
+ const message = error instanceof Error ? error.message : String(error);
986
+ const missing = code === "ERR_UNKNOWN_BUILTIN_MODULE"
987
+ || message.includes("Cannot find package")
988
+ || message.includes("Cannot find module")
989
+ || message.includes("No such built-in module");
990
+ if (!missing) throw error;
991
+ databaseSyncCtor = null;
992
+ }
993
+ return databaseSyncCtor;
994
+ }
995
+
996
+ function installSqliteWarningFilter(): void {
997
+ const marked = process as typeof process & { [sqliteWarningFilter]?: boolean };
998
+ if (marked[sqliteWarningFilter]) return;
999
+ marked[sqliteWarningFilter] = true;
1000
+ const emit = process.emitWarning.bind(process);
1001
+ process.emitWarning = ((warning: unknown, ...args: unknown[]) => {
1002
+ const message = typeof warning === "string"
1003
+ ? warning
1004
+ : (warning as { message?: unknown } | undefined)?.message;
1005
+ if (typeof message === "string" && message.includes("SQLite is an experimental feature")) return;
1006
+ return (emit as (warning: unknown, ...args: unknown[]) => void)(warning, ...args);
1007
+ }) as typeof process.emitWarning;
1008
+ }
1009
+
1010
+ function isSqliteBusy(error: unknown): boolean {
1011
+ const message = error instanceof Error ? error.message : String(error);
1012
+ return /database is locked|SQLITE_BUSY/i.test(message);
1013
+ }
1014
+
1015
+ /**
1016
+ * Cross-process critical section. Node's built-in SQLite reserved lock is
1017
+ * held for the whole section, including while this process is stopped, and
1018
+ * the kernel drops it if the process dies. Waiters give up at 5s instead of
1019
+ * blocking forever or stealing a live holder.
1020
+ */
1021
+ function acquireProcessLock(directory: string): () => void {
1022
+ const Ctor = databaseSync();
1023
+ if (!Ctor) return () => {};
1024
+ const db = new Ctor(join(directory, ".meta.lock.sqlite"));
1025
+ try {
1026
+ db.exec("PRAGMA busy_timeout = 5000");
1027
+ db.exec("BEGIN IMMEDIATE");
1028
+ } catch (error) {
1029
+ try {
1030
+ db.close();
1031
+ } catch (closeError) {
1032
+ if (!isSqliteBusy(error)) throw closeError;
1033
+ }
1034
+ if (isSqliteBusy(error)) throw lockTimeout(directory);
1035
+ throw error;
1036
+ }
1037
+ return () => {
1038
+ let rollbackError: unknown;
1039
+ try {
1040
+ db.exec("ROLLBACK");
1041
+ } catch (error) {
1042
+ rollbackError = error;
1043
+ }
1044
+ try {
1045
+ db.close();
1046
+ } catch (error) {
1047
+ if (!rollbackError) throw error;
1048
+ }
1049
+ if (rollbackError) throw rollbackError;
1050
+ };
1051
+ }
1052
+
1053
+ function takeToken(lockPath: string, payload: string, deadline: number, id: string): void {
1054
+ for (;;) {
1055
+ const creating = join(dirname(lockPath), `.meta.lock.${randomBytes(8).toString("hex")}.creating`);
1056
+ writeFileSync(creating, payload, { flag: "wx" });
1057
+ try {
1058
+ linkSync(creating, lockPath);
1059
+ } catch (error) {
1060
+ const code = errnoOf(error);
1061
+ try {
1062
+ unlinkSync(creating);
1063
+ } catch (cleanup) {
1064
+ if (errnoOf(cleanup) !== "ENOENT") throw cleanup;
1065
+ }
1066
+ if (code !== "EEXIST") throw error;
1067
+ removeLockIf(lockPath, (raw, path) => isStaleLock(path, raw));
1068
+ if (Date.now() > deadline) throw lockTimeout(id);
1069
+ sleepMs(5);
1070
+ continue;
1071
+ }
1072
+ try {
1073
+ unlinkSync(creating);
1074
+ } catch (error) {
1075
+ if (errnoOf(error) !== "ENOENT") throw error;
1076
+ }
1077
+ return;
1078
+ }
1079
+ }
1080
+
1081
+ /**
1082
+ * Serialize one run's read-modify-write. The owner token, not the lock's age,
1083
+ * decides who may recover or release it. A live pid — even one paused well
1084
+ * past two seconds — is not stolen. Release renames the lock aside and deletes
1085
+ * it only when the moved bytes are still ours, so a newer owner's lock stays.
1086
+ * The lock is per run and is not a second registry.
1087
+ */
1088
+ function withRunMetaLock(id: string, body: (owns: () => boolean) => void): void {
1089
+ const directory = runDir(id);
1090
+ let releaseProcessLock: () => void;
1091
+ try {
1092
+ releaseProcessLock = acquireProcessLock(directory);
1093
+ } catch (error) {
1094
+ if (isSqliteBusy(error) || (error instanceof Error && error.message === `Timed out writing metadata for ${directory}`)) {
1095
+ throw lockTimeout(id);
1096
+ }
1097
+ throw error;
1098
+ }
1099
+ try {
1100
+ const lockPath = join(directory, ".meta.lock");
1101
+ const payload = serializeOwner(makeOwner());
1102
+ const deadline = Date.now() + META_LOCK_WAIT_MS;
1103
+ for (;;) {
1104
+ let ownsLock = false;
1105
+ try {
1106
+ takeToken(lockPath, payload, deadline, id);
1107
+ ownsLock = true;
1108
+ const owns = (): boolean => {
1109
+ if (!ownsLock) return false;
1110
+ if (!lockPayloadMatches(lockPath, payload)) {
1111
+ ownsLock = false;
1112
+ return false;
1113
+ }
1114
+ return true;
1115
+ };
1116
+ if (!owns()) continue;
1117
+ body(owns);
1118
+ return;
1119
+ } catch (error) {
1120
+ if (error instanceof MetadataLockLost) {
1121
+ ownsLock = false;
1122
+ if (Date.now() > deadline) throw lockTimeout(id);
1123
+ continue;
1124
+ }
1125
+ throw error;
1126
+ } finally {
1127
+ if (ownsLock) removeLockIf(lockPath, (raw) => raw === payload);
1128
+ }
1129
+ }
1130
+ } finally {
1131
+ releaseProcessLock();
1132
+ }
1133
+ }
1134
+
1135
+ function writeMetaFile(meta: RunMeta): void {
1136
+ applyFrozenLaunch(meta);
1137
+ const target = metaPathFor(meta.id);
1138
+ const json = JSON.stringify(meta, null, 2);
1139
+ if (process.platform === "win32") {
1140
+ writeFileSync(target, json);
1141
+ return;
1142
+ }
1143
+ const temp = join(runDir(meta.id), `.meta.${randomBytes(8).toString("hex")}.tmp`);
1144
+ const fd = openSync(temp, "wx");
1145
+ try {
1146
+ writeFileSync(fd, json);
1147
+ fsyncSync(fd);
1148
+ } catch (error) {
1149
+ try {
1150
+ closeSync(fd);
1151
+ } catch (closeError) {
1152
+ if (errnoOf(closeError) !== "EBADF") throw closeError;
1153
+ }
1154
+ try {
1155
+ unlinkSync(temp);
1156
+ } catch (cleanup) {
1157
+ if (errnoOf(cleanup) !== "ENOENT") throw cleanup;
1158
+ }
1159
+ throw error;
1160
+ }
1161
+ closeSync(fd);
1162
+ try {
1163
+ renameSync(temp, target);
1164
+ } catch (error) {
1165
+ try {
1166
+ unlinkSync(temp);
1167
+ } catch (cleanup) {
1168
+ if (errnoOf(cleanup) !== "ENOENT") throw cleanup;
1169
+ }
1170
+ throw error;
1171
+ }
1172
+ }
1173
+
1174
+ let seq = 0;
1175
+ const metaCache = new Map<string, RunMeta>();
1176
+ /** Test-only pause/check after the run lock is held and before `meta.json` is replaced. */
1177
+ let metaWriteBarrier: (() => void) | undefined;
1178
+
1179
+ export function setMetaWriteBarrierForTests(barrier: (() => void) | undefined): void {
1180
+ metaWriteBarrier = barrier;
1181
+ }
1182
+ // Owned snapshots are process-resident. A cheap directory signature catches
1183
+ // cross-process index changes before any cached IDs are reused.
1184
+ const indexIdsCache = new Map<string, { ids: Set<string>; signature: string }>();
1185
+ const initializedIndexes = new Set<string>();
1186
+ const metaChangedListeners = new Set<(meta?: RunMeta) => void>();
1187
+ const registryIo = { fullDirectoryReads: 0, indexDirectoryReads: 0, metadataFileReads: 0, indexRevisionChecks: 0 };
1188
+
1189
+ export interface RegistryIoMetrics {
1190
+ fullDirectoryReads: number;
1191
+ indexDirectoryReads: number;
1192
+ metadataFileReads: number;
1193
+ indexRevisionChecks: number;
1194
+ }
1195
+
1196
+ export function getRegistryIoMetrics(): RegistryIoMetrics {
1197
+ return { ...registryIo };
1198
+ }
1199
+
1200
+ export function resetRegistryIoMetrics(): void {
1201
+ registryIo.fullDirectoryReads = 0;
1202
+ registryIo.indexDirectoryReads = 0;
1203
+ registryIo.metadataFileReads = 0;
1204
+ registryIo.indexRevisionChecks = 0;
1205
+ }
1206
+ /** Monotonic, readable, collision-free run id: `sa_<base36-time>_<seq>`. */
1207
+ export function nextRunId(): string {
1208
+ seq += 1;
1209
+ return `sa_${Date.now().toString(36)}_${seq}`;
1210
+ }
1211
+
1212
+ /** Failure-journal operation for durable archive publication. */
1213
+ const ARCHIVE_OPERATION = "durable-archive";
1214
+
1215
+ /**
1216
+ * Journal the outcome of publishing one attempt's compact durable record in the
1217
+ * run's existing failures journal (`failures.jsonl`, read by the output and
1218
+ * result payloads). `undefined` reports a verified recovery.
1219
+ *
1220
+ * While publication keeps failing, the volatile run directory still holds the
1221
+ * only copy of the recipe, so both sweeps retain it; this incident is what makes
1222
+ * that state visible instead of silent. Best-effort: journaling never throws
1223
+ * into finalization or a sweep, and an untouched run keeps no journal.
1224
+ */
1225
+ export function observeArchivePublication(id: string, error?: unknown): void {
1226
+ try {
1227
+ if (!/^[A-Za-z0-9_-]+$/.test(id)) return;
1228
+ const path = join(runDir(id), "failures.jsonl");
1229
+ const key = failureIdentity(ARCHIVE_OPERATION);
1230
+ const open = readFailureState(path).observations[key];
1231
+ const at = Date.now();
1232
+ if (error === undefined) {
1233
+ if (!open || open.status !== "unresolved") return;
1234
+ observeFailures(path, [{
1235
+ id: `archive-published:${id}:${at}`,
1236
+ operation: ARCHIVE_OPERATION,
1237
+ kind: "recovered",
1238
+ at,
1239
+ incidents: [open.id],
1240
+ summary: "the compact durable continuation record was published",
1241
+ }]);
1242
+ return;
1243
+ }
1244
+ // One open incident per run: repeated sweeps retry the same publication and
1245
+ // must not fill the journal with the same failure.
1246
+ if (open && open.status === "unresolved") return;
1247
+ const detail = error instanceof Error ? error.message : String(error);
1248
+ observeFailures(path, [{
1249
+ id: `archive-failed:${id}:${at}`,
1250
+ operation: ARCHIVE_OPERATION,
1251
+ kind: "failure",
1252
+ at,
1253
+ category: "storage",
1254
+ summary: `durable continuation record could not be published (${detail}); this attempt's log and recipe are retained until it is`,
1255
+ evidence: `compact record for ${id}`,
1256
+ }]);
1257
+ } catch { /* the journal is best-effort; retaining the run is the safety net */ }
1258
+ }
1259
+
1260
+ export function writeMeta(meta: RunMeta, options: {
1261
+ ifAbsent?: boolean;
1262
+ /** Build a field update from current metadata under the existing run lock. */
1263
+ patch?: (current: Readonly<RunMeta>) => Partial<RunMeta> | undefined;
1264
+ } = {}): void {
1265
+ if (options.patch && !readMeta(meta.id)) return;
1266
+ mkdirSync(runDir(meta.id), { recursive: true });
1267
+ let written = false;
1268
+ withRunMetaLock(meta.id, (owns) => {
1269
+ if (options.ifAbsent && existsSync(metaPathFor(meta.id))) return;
1270
+ if (options.patch) {
1271
+ const current = readMeta(meta.id);
1272
+ if (!current) return;
1273
+ const patch = options.patch(current);
1274
+ if (!patch) return;
1275
+ meta = { ...current, ...patch, id: meta.id };
1276
+ }
1277
+ metaWriteBarrier?.();
1278
+ if (!owns()) throw new MetadataLockLost();
1279
+ writeMetaFile(meta);
1280
+ metaCache.set(meta.id, meta);
1281
+ indexMeta(meta);
1282
+ // Publish the compact durable continuation record in the same critical
1283
+ // section, so a completed attempt is never visible only in volatile
1284
+ // storage. Best-effort: a durable write failure must not break a launch
1285
+ // or finalization (the volatile record still exists). It is journaled
1286
+ // instead, and both sweeps retain the run until publication succeeds.
1287
+ if (meta.status === "completed") {
1288
+ try {
1289
+ if (archiveCompletedAttempt(meta)) observeArchivePublication(meta.id);
1290
+ } catch (error) {
1291
+ observeArchivePublication(meta.id, error);
1292
+ }
1293
+ }
1294
+ owns();
1295
+ written = true;
1296
+ });
1297
+ if (options.patch && !written) return;
1298
+ for (const listener of metaChangedListeners) {
1299
+ try { listener(meta); } catch { /* best effort */ }
1300
+ }
1301
+ }
1302
+
1303
+ export function onMetaChanged(listener: (meta?: RunMeta) => void): () => void {
1304
+ metaChangedListeners.add(listener);
1305
+ return () => metaChangedListeners.delete(listener);
1306
+ }
1307
+
1308
+ export function readMeta(id: string): RunMeta | undefined {
1309
+ try {
1310
+ registryIo.metadataFileReads += 1;
1311
+ const meta = JSON.parse(readFileSync(metaPathFor(id), "utf-8")) as RunMeta;
1312
+ metaCache.set(id, meta);
1313
+ return meta;
1314
+ } catch (error) {
1315
+ metaCache.delete(id);
1316
+ // Only a MISSING volatile record falls back to the durable copy. An
1317
+ // unreadable or corrupt `meta.json` stays authoritative and is reported
1318
+ // as absent: a possibly stale archive must never replace it.
1319
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") return undefined;
1320
+ const archived = readArchivedAttempt(id);
1321
+ if (archived) metaCache.set(id, archived);
1322
+ return archived;
1323
+ }
1324
+ }
1325
+
1326
+ /**
1327
+ * Delete one run directory and its index entries.
1328
+ *
1329
+ * Catalog label reservations under `{baseDir()}/labels` are intentionally
1330
+ * kept. Age and size sweeps call this and therefore also leave reservations
1331
+ * in place, so a purged run does not free its display label for reuse.
1332
+ * Deleting the whole registry root is what clears them.
1333
+ */
1334
+ export interface RemoveMetaArtifactsOptions {
1335
+ /**
1336
+ * Keep the run's owned clone workspace. A conversation whose saved session
1337
+ * and recipe are durable still needs the workspace later attempts run in;
1338
+ * only its volatile log, metadata, and task scratch are reclaimed.
1339
+ */
1340
+ keepWorkspace?: boolean;
1341
+ }
1342
+
1343
+ export function removeMetaArtifacts(meta: RunMeta, options: RemoveMetaArtifactsOptions = {}): boolean {
1344
+ try {
1345
+ // A newer failed/killed attempt's volatile record is about to be the only
1346
+ // evidence that the conversation's newest attempt did not complete. Leave
1347
+ // a durable marker first, or an older completed archive would become the
1348
+ // conversation's visible last word and could be continued as if this
1349
+ // attempt had never happened. A marker that cannot be published retains
1350
+ // the run (the throw below): the unsafe direction is deleting both.
1351
+ recordArchiveStatusTombstone(meta);
1352
+ removeRunDirectory(meta.id);
1353
+ if (!options.keepWorkspace
1354
+ && meta.taskRuntime && /^sa_[a-z0-9]+_[a-z0-9]+$/i.test(meta.id) && meta.cwd === taskWorkspaceDir(meta.id)) {
1355
+ rmSync(taskWorkspaceDir(meta.id), { recursive: true, force: true });
1356
+ }
1357
+ if (meta.taskRuntime && meta.taskScratch && dirname(meta.taskScratch) === realpathSync(tmpdir()) && /^pi-task-scratch-[a-z0-9]{6}$/i.test(basename(meta.taskScratch))) {
1358
+ rmSync(meta.taskScratch, { recursive: true, force: true });
1359
+ }
1360
+ metaCache.delete(meta.id);
1361
+ removeIndexEntry(join(baseDir(), "by-parent", String(meta.spawnPid)), meta.id);
1362
+ removeIndexEntry(join(baseDir(), "by-parent-active", String(meta.spawnPid)), meta.id);
1363
+ removeIndexEntry(join(baseDir(), "by-origin", originKey(originOf(meta))), meta.id);
1364
+ for (const listener of metaChangedListeners) {
1365
+ try { listener(meta); } catch { /* best effort */ }
1366
+ }
1367
+ return true;
1368
+ } catch {
1369
+ return false;
1370
+ }
1371
+ }
1372
+
1373
+ /**
1374
+ * All runs, newest first: the volatile registry plus durable archived attempts
1375
+ * whose raw log/run directory was already reclaimed. The volatile record wins
1376
+ * whenever both exist, so a reclaimed log never hides the live one.
1377
+ */
1378
+ export function listMetas(options: { includeArchived?: boolean } = {}): RunMeta[] {
1379
+ let ids: string[] = [];
1380
+ try {
1381
+ registryIo.fullDirectoryReads += 1;
1382
+ ids = readdirSync(join(baseDir(), "runs"));
1383
+ } catch {
1384
+ ids = [];
1385
+ }
1386
+ const seen = new Set<string>();
1387
+ const metas: RunMeta[] = [];
1388
+ for (const id of ids) {
1389
+ seen.add(id); // A corrupt volatile record must not be hidden by an older archive.
1390
+ const meta = readMetaForSweep(id);
1391
+ if (!meta) continue;
1392
+ metas.push(meta);
1393
+ }
1394
+ for (const meta of options.includeArchived === false ? [] : listArchivedAttempts()) {
1395
+ if (seen.has(meta.id)) continue;
1396
+ seen.add(meta.id);
1397
+ metas.push(meta);
1398
+ }
1399
+ return metas.sort((a, b) => b.startedAt - a.startedAt);
1400
+ }
1401
+
1402
+ export interface RunRecordIndex {
1403
+ metas: RunMeta[];
1404
+ /** Run directories whose metadata is missing, unreadable, or corrupt. */
1405
+ unreadable: Array<{ id: string; detail: string }>;
1406
+ /**
1407
+ * Launch attempts that never produced a supervised run (no metadata, no
1408
+ * log). They are not runs, cannot be read or finalized, and are reclaimed
1409
+ * by the launch-debris sweep or an explicit `subagent_stop`.
1410
+ */
1411
+ abandoned: string[];
1412
+ /** The runs directory itself could not be read (not "no runs"). */
1413
+ indexError?: string;
1414
+ }
1415
+
1416
+ /** Why parsed metadata is not a usable run record, or undefined when it is. */
1417
+ export function runMetaShapeProblem(meta: unknown, id: string): string | undefined {
1418
+ if (!meta || typeof meta !== "object" || Array.isArray(meta)) return "not an object";
1419
+ const value = meta as Partial<RunMeta>;
1420
+ if (value.id !== id) return `id ${JSON.stringify(value.id ?? null)} does not match ${JSON.stringify(id)}`;
1421
+ if (typeof value.status !== "string" || !value.status) return "missing status";
1422
+ if (typeof value.startedAt !== "number" || !Number.isFinite(value.startedAt)) return "missing startedAt";
1423
+ return undefined;
1424
+ }
1425
+
1426
+ /** A run directory a launch created but never turned into a supervised run. */
1427
+ export interface AbandonedLaunchRecord {
1428
+ id: string;
1429
+ /** Directory mtime (ms), used as the launch attempt's age. */
1430
+ mtimeMs: number;
1431
+ }
1432
+
1433
+ /**
1434
+ * Durable claim a launch writes into its run directory before it prepares
1435
+ * anything (#623). It states WHO owns the attempt while no metadata exists, so a
1436
+ * concurrent purge can tell a live launch from the debris of a dead one.
1437
+ *
1438
+ * It is a plain file rather than the metadata lock because the claim must cover
1439
+ * the whole preparation (workspace, sandbox control dir, session dir, spawn and
1440
+ * metadata publication), not only the metadata write. It is removed at the same
1441
+ * moment `meta.json` becomes the record of the run, and it is never a second
1442
+ * registry: nothing reads it as run evidence.
1443
+ */
1444
+ export interface LaunchAttemptClaim {
1445
+ version: 1;
1446
+ id: string;
1447
+ pid: number;
1448
+ /** Start-identity token of the claiming pi; only equality is meaningful. */
1449
+ start?: string;
1450
+ at: number;
1451
+ }
1452
+
1453
+ function launchAttemptClaimPath(id: string): string {
1454
+ return join(runDir(id), ".launch-attempt.json");
1455
+ }
1456
+
1457
+ /** Claim this run directory for a launch in progress. The directory must exist. */
1458
+ export function recordLaunchAttempt(id: string): void {
1459
+ const claim: LaunchAttemptClaim = { version: 1, id, pid: process.pid, at: Date.now() };
1460
+ const start = processStartToken(process.pid);
1461
+ if (start) claim.start = start;
1462
+ writeFileSync(launchAttemptClaimPath(id), JSON.stringify(claim), { mode: 0o600 });
1463
+ }
1464
+
1465
+ /** Drop the claim once `meta.json` is the run's record. Best effort. */
1466
+ export function clearLaunchAttempt(id: string): void {
1467
+ try {
1468
+ unlinkSync(launchAttemptClaimPath(id));
1469
+ } catch { /* no claim, or the attempt's directory is already gone */ }
1470
+ }
1471
+
1472
+ /**
1473
+ * Whether a launch claim is still owned by a live process. Conservative for one
1474
+ * direction only: an unreadable, malformed, or token-less claim counts as live,
1475
+ * so the attempt's artifacts are preserved. A dead pid, or a pid whose start
1476
+ * token no longer matches (recycled), is a dead attempt.
1477
+ */
1478
+ function launchAttemptClaimIsLive(id: string): boolean {
1479
+ let raw: string;
1480
+ try {
1481
+ raw = readFileSync(launchAttemptClaimPath(id), "utf-8");
1482
+ } catch (error) {
1483
+ return errnoOf(error) !== "ENOENT";
1484
+ }
1485
+ let parsed: Partial<LaunchAttemptClaim> | undefined;
1486
+ try {
1487
+ parsed = JSON.parse(raw) as Partial<LaunchAttemptClaim>;
1488
+ } catch {
1489
+ return true;
1490
+ }
1491
+ if (!parsed || typeof parsed !== "object") return true;
1492
+ const pid = parsed.pid;
1493
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return true;
1494
+ if (!processExists(pid)) return false;
1495
+ const start = parsed.start;
1496
+ if (typeof start !== "string" || start.length === 0) return true;
1497
+ const current = cachedStartToken(pid);
1498
+ // An unavailable token does not prove the pid is dead, so the claim stays live.
1499
+ return current === undefined || current === start;
1500
+ }
1501
+
1502
+ /**
1503
+ * True when a launch is preparing this run id right now, so its directory must
1504
+ * not be treated as debris. Unreadable state counts as in progress.
1505
+ */
1506
+ export function launchAttemptInProgress(id: string): boolean {
1507
+ if (!/^sa_[a-z0-9]+_[a-z0-9]+$/i.test(id)) return false;
1508
+ return launchAttemptClaimIsLive(id);
1509
+ }
1510
+
1511
+ /**
1512
+ * Read one run directory as an abandoned launch attempt, or `undefined`.
1513
+ *
1514
+ * A launch creates the directory, claims it, writes `prompt.md`, and prepares
1515
+ * the sandbox `control/` dir before the child starts and `meta.json` is
1516
+ * committed. When that preparation throws, or pi dies in that window, only
1517
+ * those artifacts remain: no metadata (nothing was committed) and no
1518
+ * `output.log` (the log is created at spawn and removed when the spawn itself
1519
+ * fails). Such a directory was never a run: it has no owner, no status, no log
1520
+ * and no result, and it can never gain any, so it must not be reported as
1521
+ * unreadable run evidence forever.
1522
+ *
1523
+ * The rule is deliberately narrow in the other direction too. A live launch
1524
+ * claim means the attempt is still being prepared and is never debris; a
1525
+ * directory WITH a log is not debris either, because a child may have started
1526
+ * and its output is real evidence; and a directory without the launch artifacts
1527
+ * is left to the age sweep rather than guessed at.
1528
+ */
1529
+ export function abandonedLaunchRecord(id: string): AbandonedLaunchRecord | undefined {
1530
+ if (!/^sa_[a-z0-9]+_[a-z0-9]+$/i.test(id)) return undefined;
1531
+ let mtimeMs: number;
1532
+ try {
1533
+ mtimeMs = statSync(runDir(id)).mtimeMs;
1534
+ } catch {
1535
+ return undefined;
1536
+ }
1537
+ // Metadata absence is the claim of debris, so it is re-established as late as
1538
+ // possible: the launch shape first, then every piece of run evidence.
1539
+ if (!existsSync(promptPathFor(id)) && !existsSync(join(runDir(id), "control"))) return undefined;
1540
+ if (launchAttemptClaimIsLive(id)) return undefined;
1541
+ try {
1542
+ statSync(metaPathFor(id));
1543
+ return undefined;
1544
+ } catch (error) {
1545
+ if (errnoOf(error) !== "ENOENT") return undefined;
1546
+ }
1547
+ try {
1548
+ statSync(logPathFor(id));
1549
+ return undefined;
1550
+ } catch (error) {
1551
+ if (errnoOf(error) !== "ENOENT") return undefined;
1552
+ }
1553
+ return { id, mtimeMs };
1554
+ }
1555
+
1556
+ export type AbandonedLaunchPurge =
1557
+ /** The attempt's artifacts were removed. */
1558
+ | "purged"
1559
+ /** Not launch debris (a run record, a live launch, or something else entirely). */
1560
+ | "not-debris"
1561
+ /** It looked like debris, but a writer or an unavailable lock made removal unsafe. */
1562
+ | "retained";
1563
+
1564
+ /**
1565
+ * Reclaim one abandoned launch attempt: its run directory, the per-run session
1566
+ * directory a confined launch prepared, and the clone workspace it owned. Only
1567
+ * paths named by the attempt's own id are removed (shared sessions and a
1568
+ * caller-chosen `sandbox_dir` are never touched), exactly like a failed launch.
1569
+ *
1570
+ * Classification runs again inside the same per-run lock `writeMeta` publishes
1571
+ * under, and the removal happens there, so a launch that commits metadata while
1572
+ * the purger waits is preserved instead of deleted. A held or unavailable lock
1573
+ * is a live writer, so it is preserved too. This closes the race the earlier
1574
+ * shape-only rule lost (#623 review R1): no deletion of a live attempt's
1575
+ * metadata or log, and no orphaned child left behind by a purge.
1576
+ */
1577
+ export function purgeAbandonedLaunch(id: string): AbandonedLaunchPurge {
1578
+ if (!abandonedLaunchRecord(id)) return "not-debris";
1579
+ let outcome: AbandonedLaunchPurge = "retained";
1580
+ try {
1581
+ withRunMetaLock(id, (owns) => {
1582
+ if (!owns()) throw new MetadataLockLost();
1583
+ // Re-establish the negative evidence under the publication exclusion.
1584
+ if (!abandonedLaunchRecord(id)) {
1585
+ outcome = "not-debris";
1586
+ return;
1587
+ }
1588
+ discardFailedLaunch(id, { sessionDir: join(sessionsDir(), id), workspaceDir: taskWorkspaceDir(id) });
1589
+ outcome = "purged";
1590
+ });
1591
+ } catch {
1592
+ // A live writer (or an unreadable run directory) is never safe to delete.
1593
+ // A directory that disappeared meanwhile is no longer debris.
1594
+ return abandonedLaunchRecord(id) ? "retained" : "not-debris";
1595
+ }
1596
+ if (outcome === "purged") {
1597
+ try {
1598
+ statSync(runDir(id));
1599
+ outcome = "retained";
1600
+ } catch (error) {
1601
+ if (errnoOf(error) !== "ENOENT") outcome = "retained";
1602
+ }
1603
+ }
1604
+ return outcome;
1605
+ }
1606
+
1607
+ /**
1608
+ * Inspect one run's metadata without collapsing "missing" and "corrupt":
1609
+ * `missing` only when neither metadata nor the run directory exists.
1610
+ */
1611
+ export function inspectRunMeta(id: string): { kind: "ok"; meta: RunMeta } | { kind: "missing" } | { kind: "unreadable"; detail: string } {
1612
+ let raw: string;
1613
+ try {
1614
+ registryIo.metadataFileReads += 1;
1615
+ raw = readFileSync(metaPathFor(id), "utf-8");
1616
+ } catch (error) {
1617
+ metaCache.delete(id);
1618
+ const code = (error as NodeJS.ErrnoException).code;
1619
+ if (code === "ENOENT") {
1620
+ try {
1621
+ statSync(runDir(id));
1622
+ return { kind: "unreadable", detail: "metadata file is missing; the run directory and its evidence are retained" };
1623
+ } catch {
1624
+ const archived = readArchivedAttempt(id);
1625
+ return archived ? { kind: "ok", meta: archived } : { kind: "missing" };
1626
+ }
1627
+ }
1628
+ return { kind: "unreadable", detail: error instanceof Error ? error.message : String(error) };
1629
+ }
1630
+ let meta: RunMeta;
1631
+ try {
1632
+ meta = JSON.parse(raw) as RunMeta;
1633
+ } catch (error) {
1634
+ metaCache.delete(id);
1635
+ return { kind: "unreadable", detail: `invalid JSON: ${error instanceof Error ? error.message : String(error)}` };
1636
+ }
1637
+ const invalid = runMetaShapeProblem(meta, id);
1638
+ if (invalid) {
1639
+ metaCache.delete(id);
1640
+ return { kind: "unreadable", detail: `invalid metadata: ${invalid}` };
1641
+ }
1642
+ metaCache.set(id, meta);
1643
+ return { kind: "ok", meta };
1644
+ }
1645
+
1646
+ /** Every run directory, counting unreadable records instead of dropping them. */
1647
+ export function listRunRecords(): RunRecordIndex {
1648
+ let ids: string[] = [];
1649
+ try {
1650
+ registryIo.fullDirectoryReads += 1;
1651
+ ids = readdirSync(join(baseDir(), "runs"));
1652
+ } catch (error) {
1653
+ const code = (error as NodeJS.ErrnoException).code;
1654
+ if (code !== "ENOENT") return { metas: [], unreadable: [], abandoned: [], indexError: error instanceof Error ? error.message : String(error) };
1655
+ }
1656
+ const metas: RunMeta[] = [];
1657
+ const unreadable: Array<{ id: string; detail: string }> = [];
1658
+ const abandoned: string[] = [];
1659
+ for (const id of ids) {
1660
+ const cached = metaCache.get(id);
1661
+ if (cached && cached.status !== "running" && cached.status !== "orphaned") {
1662
+ metas.push(cached);
1663
+ continue;
1664
+ }
1665
+ const inspected = inspectRunMeta(id);
1666
+ if (inspected.kind === "ok") metas.push(inspected.meta);
1667
+ else if (inspected.kind === "unreadable") {
1668
+ if (abandonedLaunchRecord(id)) abandoned.push(id);
1669
+ else unreadable.push({ id, detail: inspected.detail });
1670
+ }
1671
+ }
1672
+ const volatileIds = new Set(ids);
1673
+ for (const archived of listArchivedAttempts()) {
1674
+ if (!volatileIds.has(archived.id)) metas.push(archived);
1675
+ }
1676
+ metas.sort((a, b) => b.startedAt - a.startedAt);
1677
+ return { metas, unreadable, abandoned };
1678
+ }
1679
+
1680
+ export function listMetasForParent(parentPid: number): RunMeta[] {
1681
+ const directory = join(baseDir(), "by-parent", String(parentPid));
1682
+ ensureIndex(directory, (meta) => meta.spawnPid === parentPid);
1683
+ return readIndexedMetas(directory).filter((meta) => meta.spawnPid === parentPid);
1684
+ }
1685
+
1686
+ export function listActiveMetasForParent(parentPid: number): RunMeta[] {
1687
+ const directory = join(baseDir(), "by-parent-active", String(parentPid));
1688
+ ensureActiveParentIndex(directory, parentPid);
1689
+ return readIndexedMetas(directory)
1690
+ .filter((meta) => meta.spawnPid === parentPid && isActiveStatus(meta.status));
1691
+ }
1692
+
1693
+ export function listMetasForOrigin(origin: RunCallbackOrigin): RunMeta[] {
1694
+ const directory = join(baseDir(), "by-origin", originKey(origin));
1695
+ ensureIndex(directory, (meta) => belongsToOrigin(meta, origin));
1696
+ return readIndexedMetas(directory).filter((meta) => belongsToOrigin(meta, origin));
1697
+ }
1698
+
1699
+ function readMetaForSweep(id: string): RunMeta | undefined {
1700
+ const cached = metaCache.get(id);
1701
+ if (cached && cached.status !== "running" && cached.status !== "orphaned") return cached;
1702
+ return readMeta(id);
1703
+ }
1704
+
1705
+ function readIndexedMetas(directory: string): RunMeta[] {
1706
+ return readIndexIds(directory)
1707
+ .map((id) => metaCache.get(id) ?? readMeta(id))
1708
+ .filter((meta): meta is RunMeta => meta !== undefined)
1709
+ .sort((a, b) => b.startedAt - a.startedAt);
1710
+ }
1711
+
1712
+ function indexMeta(meta: RunMeta): void {
1713
+ try {
1714
+ writeIndexEntry(join(baseDir(), "by-parent", String(meta.spawnPid)), meta.id);
1715
+ const activeDirectory = join(baseDir(), "by-parent-active", String(meta.spawnPid));
1716
+ if (isActiveStatus(meta.status)) writeIndexEntry(activeDirectory, meta.id);
1717
+ else removeIndexEntry(activeDirectory, meta.id);
1718
+ writeIndexEntry(join(baseDir(), "by-origin", originKey(originOf(meta))), meta.id);
1719
+ } catch {
1720
+ // Indexes are accelerators; meta.json remains authoritative.
1721
+ }
1722
+ }
1723
+
1724
+ function writeIndexEntry(directory: string, id: string): void {
1725
+ mkdirSync(directory, { recursive: true });
1726
+ const cached = indexIdsCache.get(directory);
1727
+ const cacheWasCurrent = cached ? cached.signature === indexDirectorySignature(directory) : false;
1728
+ try {
1729
+ writeFileSync(join(directory, id), "", { flag: "wx" });
1730
+ } catch (error) {
1731
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
1732
+ }
1733
+ if (cached && cacheWasCurrent) {
1734
+ cached.ids.add(id);
1735
+ cached.signature = indexDirectorySignature(directory);
1736
+ } else if (cached) {
1737
+ indexIdsCache.delete(directory);
1738
+ }
1739
+ }
1740
+
1741
+ function removeIndexEntry(directory: string, id: string): void {
1742
+ const cached = indexIdsCache.get(directory);
1743
+ const cacheWasCurrent = cached ? cached.signature === indexDirectorySignature(directory) : false;
1744
+ try { unlinkSync(join(directory, id)); } catch { /* stale index entries are harmless */ }
1745
+ if (cached && cacheWasCurrent) {
1746
+ cached.ids.delete(id);
1747
+ cached.signature = indexDirectorySignature(directory);
1748
+ } else if (cached) {
1749
+ indexIdsCache.delete(directory);
1750
+ }
1751
+ }
1752
+
1753
+ function readIndexIds(directory: string): string[] {
1754
+ const signature = indexDirectorySignature(directory);
1755
+ const cached = indexIdsCache.get(directory);
1756
+ if (cached && cached.signature === signature) return [...cached.ids];
1757
+ try {
1758
+ registryIo.indexDirectoryReads += 1;
1759
+ const ids = new Set(readdirSync(directory).filter((id) => id !== ".initialized"));
1760
+ indexIdsCache.set(directory, { ids, signature: indexDirectorySignature(directory) });
1761
+ return [...ids];
1762
+ } catch {
1763
+ indexIdsCache.delete(directory);
1764
+ return [];
1765
+ }
1766
+ }
1767
+
1768
+ function isActiveStatus(status: RunStatus): boolean {
1769
+ return status === "running" || status === "orphaned";
1770
+ }
1771
+
1772
+ function indexDirectorySignature(directory: string): string {
1773
+ registryIo.indexRevisionChecks += 1;
1774
+ try {
1775
+ const stat = statSync(directory);
1776
+ return `${stat.dev}:${stat.ino}:${stat.mtimeMs}:${stat.ctimeMs}`;
1777
+ } catch {
1778
+ return "missing";
1779
+ }
1780
+ }
1781
+
1782
+ function ensureIndex(directory: string, matches: (meta: RunMeta) => boolean): void {
1783
+ if (initializedIndexes.has(directory)) return;
1784
+ try {
1785
+ readFileSync(join(directory, ".initialized"));
1786
+ initializedIndexes.add(directory);
1787
+ return;
1788
+ } catch {
1789
+ // Existing registries are backfilled once for each owner.
1790
+ }
1791
+ indexIdsCache.delete(directory);
1792
+ const owned = listMetas().filter(matches);
1793
+ mkdirSync(directory, { recursive: true });
1794
+ for (const meta of owned) writeIndexEntry(directory, meta.id);
1795
+ writeFileSync(join(directory, ".initialized"), "1");
1796
+ initializedIndexes.add(directory);
1797
+ }
1798
+
1799
+ function ensureActiveParentIndex(directory: string, parentPid: number): void {
1800
+ if (initializedIndexes.has(directory)) return;
1801
+ try {
1802
+ readFileSync(join(directory, ".initialized"));
1803
+ initializedIndexes.add(directory);
1804
+ return;
1805
+ } catch {
1806
+ // Build the active set from the already owner-scoped parent index.
1807
+ }
1808
+ indexIdsCache.delete(directory);
1809
+ const active = listMetasForParent(parentPid).filter((meta) => isActiveStatus(meta.status));
1810
+ mkdirSync(directory, { recursive: true });
1811
+ for (const meta of active) writeIndexEntry(directory, meta.id);
1812
+ writeFileSync(join(directory, ".initialized"), "1");
1813
+ initializedIndexes.add(directory);
1814
+ }
1815
+
1816
+ export function originOf(meta: RunMeta): RunCallbackOrigin {
1817
+ return meta.callbackOrigin ?? { cwd: meta.cwd };
1818
+ }
1819
+
1820
+ export function belongsToOrigin(meta: RunMeta, origin: RunCallbackOrigin): boolean {
1821
+ const candidate = originOf(meta);
1822
+ if (candidate.cwd !== origin.cwd) return false;
1823
+ if (candidate.sessionId || origin.sessionId) return candidate.sessionId === origin.sessionId;
1824
+ return true;
1825
+ }
1826
+
1827
+ export function originKey(origin: RunCallbackOrigin): string {
1828
+ return createHash("sha256")
1829
+ .update(origin.cwd)
1830
+ .update("\0")
1831
+ .update(origin.sessionId ?? "")
1832
+ .digest("hex")
1833
+ .slice(0, 24);
1834
+ }
1835
+
1836
+ /**
1837
+ * Reconcile the recorded status with reality for display. A run marked
1838
+ * "running" whose PID is no longer alive exited without our handler firing
1839
+ * (foreground pi was closed / restarted) — surface that as "exited".
1840
+ */
1841
+ export function effectiveStatus(meta: RunMeta): RunStatus | "exited" {
1842
+ if (meta.status !== "running") return meta.status;
1843
+ if (processExists(meta.pid)) return "running";
1844
+ return "exited";
1845
+ }
1846
+
1847
+ /**
1848
+ * True when a status can yield a FINAL result: everything except `running`
1849
+ * and the non-terminal `orphaned`. `lost` is terminal (best-available
1850
+ * artifacts, never a completion); `exited` keeps its historic resultable
1851
+ * treatment. Used by subagent_result's gate.
1852
+ */
1853
+ export function isFinalResultStatus(status: RunStatus | "exited"): boolean {
1854
+ return status !== "running" && status !== "orphaned";
1855
+ }
1856
+
1857
+ /** True when this meta was spawned by the given parent pi PID (default: this process). */
1858
+ export function ownedByThisParent(
1859
+ meta: Pick<RunMeta, "spawnPid">,
1860
+ parentPid: number = process.pid,
1861
+ ): boolean {
1862
+ return meta.spawnPid === parentPid;
1863
+ }
1864
+
1865
+ /** True when the run has been dismissed from the human navigator. */
1866
+ export function isDismissed(meta: Pick<RunMeta, "dismissedAt">): boolean {
1867
+ return typeof meta.dismissedAt === "number";
1868
+ }
1869
+
1870
+ /**
1871
+ * Mark a run dismissed from the navigator, durably. Idempotent: the first
1872
+ * dismissal timestamp wins. Returns the updated meta, or undefined for an
1873
+ * unknown id. Only the timestamp changes — all other metadata is preserved.
1874
+ */
1875
+ export function dismissRun(id: string, at: number = Date.now()): RunMeta | undefined {
1876
+ const meta = readMeta(id);
1877
+ if (!meta) return undefined;
1878
+ if (meta.dismissedAt === undefined) {
1879
+ meta.dismissedAt = at;
1880
+ writeMeta(meta);
1881
+ }
1882
+ return meta;
1883
+ }
1884
+
1885
+ /**
1886
+ * Visible navigator runs: current-parent runs that are not dismissed. This is
1887
+ * the single visibility calculation shared by the navigator list and the
1888
+ * footer count, so they can never drift apart. `subagent_list` does NOT use
1889
+ * this — the model-facing list keeps showing dismissed runs.
1890
+ */
1891
+ export function navigatorVisibleRuns(
1892
+ metas: RunMeta[],
1893
+ parentPid: number = process.pid,
1894
+ ): RunMeta[] {
1895
+ return metas.filter((m) => ownedByThisParent(m, parentPid) && !isDismissed(m));
1896
+ }
1897
+
1898
+ /** Footer-count seam: how many runs the navigator affordance advertises. */
1899
+ export function navigatorVisibleCount(
1900
+ metas: RunMeta[],
1901
+ parentPid: number = process.pid,
1902
+ ): number {
1903
+ return navigatorVisibleRuns(metas, parentPid).length;
1904
+ }