pi-better-server 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (340) hide show
  1. package/package.json +7 -3
  2. package/scripts/copy-pi-test-providers.mjs +10 -0
  3. package/scripts/event-publication/README.md +26 -0
  4. package/scripts/event-publication/commit.mjs +21 -0
  5. package/scripts/event-publication/measure.mjs +37 -5
  6. package/scripts/event-publication/writer.mjs +3 -8
  7. package/scripts/measure-full-runtime/frontend.ts +10 -2
  8. package/scripts/measure-full-runtime/probe.mjs +4 -2
  9. package/scripts/measure-full-runtime/recovery-trace-loader.mjs +51 -0
  10. package/scripts/measure-full-runtime/recovery-trace.mjs +16 -0
  11. package/scripts/measure-full-runtime.mjs +2 -0
  12. package/scripts/measure-shared-reads.mjs +2 -1
  13. package/scripts/private-runtime/package-lock.json +18 -0
  14. package/scripts/private-runtime/package.json +4 -1
  15. package/scripts/source-provenance.mjs +2 -2
  16. package/scripts/test-on-pi.sh +2 -9
  17. package/src/handshake.ts +1 -1
  18. package/src/hosted-session.ts +32 -4
  19. package/src/maintenance.ts +35 -7
  20. package/src/registry.ts +28 -4
  21. package/src/runtime/attempt-invalidation.ts +54 -0
  22. package/src/runtime/background-history.ts +151 -45
  23. package/src/runtime/background-policy.ts +9 -4
  24. package/src/runtime/background-tools.ts +181 -27
  25. package/src/runtime/background.ts +365 -70
  26. package/src/runtime/cancellation.ts +28 -7
  27. package/src/runtime/catalog-sources.ts +199 -0
  28. package/src/runtime/catalog.ts +53 -21
  29. package/src/runtime/client.ts +22 -2
  30. package/src/runtime/domain/assignment-inbox.mjs +119 -0
  31. package/src/runtime/domain/assignment-observation.d.mts +1 -1
  32. package/src/runtime/domain/assignment-observation.mjs +43 -35
  33. package/src/runtime/domain/background/process-identity.mjs +20 -2
  34. package/src/runtime/domain/background/process.mjs +52 -14
  35. package/src/runtime/domain/background/registry.mjs +61 -3
  36. package/src/runtime/domain/background/supervisor/store.mjs +3 -3
  37. package/src/runtime/domain/background/supervisor/supervisor.mjs +9 -3
  38. package/src/runtime/domain/background/types.mjs +1 -0
  39. package/src/runtime/domain/background-service/adapter-contract.domain.mjs +1 -1
  40. package/src/runtime/domain/background-service/adapter-contract.ts +1 -1
  41. package/src/runtime/domain/background-service/goal-provider.domain.mjs +35 -16
  42. package/src/runtime/domain/background-service/goal-provider.ts +31 -16
  43. package/src/runtime/domain/background-service/index.domain.mjs +25 -9
  44. package/src/runtime/domain/background-service/index.ts +25 -9
  45. package/src/runtime/domain/background-service/managed-authority.domain.mjs +6 -3
  46. package/src/runtime/domain/background-service/managed-authority.ts +5 -3
  47. package/src/runtime/domain/background-service/managed-client.domain.mjs +21 -7
  48. package/src/runtime/domain/background-service/managed-client.ts +20 -7
  49. package/src/runtime/domain/background-service/managed-frontend.domain.mjs +159 -19
  50. package/src/runtime/domain/background-service/managed-frontend.ts +135 -19
  51. package/src/runtime/domain/background-service/navigator-provider.domain.mjs +21 -5
  52. package/src/runtime/domain/background-service/navigator-provider.ts +19 -5
  53. package/src/runtime/domain/background-service/observed-wait-client.domain.mjs +6 -0
  54. package/src/runtime/domain/background-service/observed-wait-client.ts +10 -0
  55. package/src/runtime/domain/background-service/observed-waits.domain.mjs +372 -57
  56. package/src/runtime/domain/background-service/observed-waits.ts +321 -53
  57. package/src/runtime/domain/background-service/process-identity.domain.mjs +20 -2
  58. package/src/runtime/domain/background-service/process-identity.ts +18 -2
  59. package/src/runtime/domain/background-service/process.domain.mjs +52 -14
  60. package/src/runtime/domain/background-service/process.ts +48 -14
  61. package/src/runtime/domain/background-service/registry.domain.mjs +61 -3
  62. package/src/runtime/domain/background-service/registry.ts +53 -5
  63. package/src/runtime/domain/background-service/review-settings.domain.mjs +16 -0
  64. package/src/runtime/domain/background-service/review-settings.ts +18 -0
  65. package/src/runtime/domain/background-service/runtime.domain.mjs +40 -86
  66. package/src/runtime/domain/background-service/runtime.ts +27 -82
  67. package/src/runtime/domain/background-service/sandbox.domain.mjs +14 -15
  68. package/src/runtime/domain/background-service/sandbox.ts +14 -11
  69. package/src/runtime/domain/background-service/shared-callback-batcher.domain.mjs +8 -1
  70. package/src/runtime/domain/background-service/shared-callback-batcher.ts +11 -2
  71. package/src/runtime/domain/background-service/shared-navigator-panels.domain.mjs +24 -2
  72. package/src/runtime/domain/background-service/shared-navigator-panels.ts +26 -4
  73. package/src/runtime/domain/background-service/shared-navigator.domain.mjs +273 -41
  74. package/src/runtime/domain/background-service/shared-navigator.ts +244 -40
  75. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-inbox.mjs +144 -0
  76. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-observation.mjs +53 -41
  77. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
  78. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  79. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
  80. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  81. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
  82. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.ts +14 -3
  83. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
  84. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.ts +5 -3
  85. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.domain.mjs +44 -4
  86. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.ts +50 -2
  87. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  88. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.ts +9 -0
  89. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
  90. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.ts +12 -0
  91. package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.domain.mjs +2 -0
  92. package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.ts +2 -0
  93. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +42 -21
  94. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +40 -24
  95. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +26 -4
  96. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +40 -8
  97. package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
  98. package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.ts +24 -1
  99. package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.domain.mjs +1 -1
  100. package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.ts +5 -1
  101. package/src/runtime/domain/background-service/shared-sandbox-core.ts +1 -1
  102. package/src/runtime/domain/background-service/shared-work-client.mjs +174 -7
  103. package/src/runtime/domain/background-service/stall.domain.mjs +5 -3
  104. package/src/runtime/domain/background-service/stall.ts +7 -4
  105. package/src/runtime/domain/background-service/supervised-progress.domain.mjs +42 -0
  106. package/src/runtime/domain/background-service/supervised-progress.ts +43 -0
  107. package/src/runtime/domain/background-service/supervisor/README.md +1 -4
  108. package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +1 -0
  109. package/src/runtime/domain/background-service/supervisor/generated/process-identity.mjs +20 -2
  110. package/src/runtime/domain/background-service/supervisor/generated/process.mjs +52 -14
  111. package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +47 -4
  112. package/src/runtime/domain/background-service/supervisor/generated/store.mjs +3 -3
  113. package/src/runtime/domain/background-service/supervisor/generated/watch-fingerprint.mjs +69 -0
  114. package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +47 -4
  115. package/src/runtime/domain/background-service/supervisor/runner.ts +38 -3
  116. package/src/runtime/domain/background-service/supervisor/store.domain.mjs +3 -3
  117. package/src/runtime/domain/background-service/supervisor/store.ts +3 -3
  118. package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +9 -3
  119. package/src/runtime/domain/background-service/supervisor/supervisor.ts +6 -3
  120. package/src/runtime/domain/background-service/task-diagnostics.domain.mjs +1 -1
  121. package/src/runtime/domain/background-service/task-diagnostics.ts +1 -1
  122. package/src/runtime/domain/background-service/tools.domain.mjs +53 -40
  123. package/src/runtime/domain/background-service/tools.ts +67 -54
  124. package/src/runtime/domain/background-service/types.domain.mjs +1 -0
  125. package/src/runtime/domain/background-service/types.ts +7 -3
  126. package/src/runtime/domain/background-service/watch-fingerprint.domain.mjs +67 -0
  127. package/src/runtime/domain/background-service/watch-fingerprint.ts +70 -0
  128. package/src/runtime/domain/background-service/work-observation.domain.mjs +46 -20
  129. package/src/runtime/domain/background-service/work-observation.ts +46 -19
  130. package/src/runtime/domain/catalog/catalog-store.d.mts +9 -1
  131. package/src/runtime/domain/catalog/catalog-store.mjs +20 -22
  132. package/src/runtime/domain/coordinator/src/assignment-changes.mjs +75 -0
  133. package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +2 -0
  134. package/src/runtime/domain/coordinator/src/background-requests.mjs +11 -2
  135. package/src/runtime/domain/coordinator/src/discovery.mjs +4 -2
  136. package/src/runtime/domain/coordinator/src/operations.mjs +44 -4
  137. package/src/runtime/domain/coordinator/src/outbox.mjs +7 -0
  138. package/src/runtime/domain/coordinator/src/result-supervision.mjs +12 -0
  139. package/src/runtime/domain/coordinator/src/rows.mjs +2 -0
  140. package/src/runtime/domain/coordinator/src/schema.mjs +42 -21
  141. package/src/runtime/domain/coordinator/src/store.mjs +26 -4
  142. package/src/runtime/domain/coordinator/src/subagent-launch.mjs +23 -1
  143. package/src/runtime/domain/coordinator/src/types.mjs +1 -1
  144. package/src/runtime/domain/health-observation.d.mts +3 -1
  145. package/src/runtime/domain/health-observation.mjs +189 -190
  146. package/src/runtime/domain/log-cursor.d.mts +2 -0
  147. package/src/runtime/domain/log-cursor.mjs +85 -16
  148. package/src/runtime/domain/log-paths.mjs +8 -1
  149. package/src/runtime/domain/parse.d.mts +4 -1
  150. package/src/runtime/domain/parse.mjs +58 -9
  151. package/src/runtime/domain/sandbox-policy/README.md +63 -65
  152. package/src/runtime/domain/sandbox-policy/commands.domain.mjs +11 -8
  153. package/src/runtime/domain/sandbox-policy/commands.ts +12 -7
  154. package/src/runtime/domain/sandbox-policy/index.domain.mjs +53 -9
  155. package/src/runtime/domain/sandbox-policy/index.ts +52 -9
  156. package/src/runtime/domain/sandbox-policy/package.json +1 -1
  157. package/src/runtime/domain/sandbox-policy/permission-settings.domain.mjs +5 -2
  158. package/src/runtime/domain/sandbox-policy/permission-settings.ts +9 -2
  159. package/src/runtime/domain/sandbox-policy/permissions-page.domain.mjs +56 -137
  160. package/src/runtime/domain/sandbox-policy/permissions-page.ts +52 -130
  161. package/src/runtime/domain/sandbox-policy/permissions.domain.mjs +1 -6
  162. package/src/runtime/domain/sandbox-policy/permissions.ts +1 -6
  163. package/src/runtime/domain/sandbox-policy/shared-sandbox-core.ts +1 -1
  164. package/src/runtime/domain/sandbox-policy/shared-task-exec.domain.mjs +14 -1
  165. package/src/runtime/domain/sandbox-policy/shared-task-exec.ts +12 -1
  166. package/src/runtime/domain/sandbox-policy/shared-task-process-identity.domain.mjs +140 -0
  167. package/src/runtime/domain/sandbox-policy/shared-task-process-identity.ts +126 -0
  168. package/src/runtime/domain/sandbox-policy/shared-task-process-list.domain.mjs +3 -2
  169. package/src/runtime/domain/sandbox-policy/shared-task-process-list.ts +8 -2
  170. package/src/runtime/domain/sandbox-policy/shared-task-sandbox.domain.mjs +4 -3
  171. package/src/runtime/domain/sandbox-policy/shared-task-sandbox.ts +5 -3
  172. package/src/runtime/domain/sandbox-policy/shared-task-tools.domain.mjs +8 -5
  173. package/src/runtime/domain/sandbox-policy/shared-task-tools.ts +8 -5
  174. package/src/runtime/domain/session-store.mjs +7 -0
  175. package/src/runtime/domain/subagents/README.md +13 -11
  176. package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +10 -7
  177. package/src/runtime/domain/subagents/assignment-outcomes.ts +9 -6
  178. package/src/runtime/domain/subagents/assignment-report.domain.mjs +109 -24
  179. package/src/runtime/domain/subagents/assignment-report.ts +103 -19
  180. package/src/runtime/domain/subagents/batch.mjs +13 -5
  181. package/src/runtime/domain/subagents/catalog-host-admission.domain.mjs +21 -3
  182. package/src/runtime/domain/subagents/catalog-host-admission.ts +19 -3
  183. package/src/runtime/domain/subagents/catalog-preferences.ts +1 -1
  184. package/src/runtime/domain/subagents/catalog-resolver.domain.mjs +35 -1
  185. package/src/runtime/domain/subagents/catalog-resolver.ts +35 -1
  186. package/src/runtime/domain/subagents/catalog-store.domain.mjs +20 -22
  187. package/src/runtime/domain/subagents/catalog-store.ts +27 -20
  188. package/src/runtime/domain/subagents/child-apply-patch.domain.mjs +13 -0
  189. package/src/runtime/domain/subagents/child-apply-patch.ts +13 -0
  190. package/src/runtime/domain/subagents/child-dependencies.mjs +27 -15
  191. package/src/runtime/domain/subagents/child-operations.domain.mjs +80 -2
  192. package/src/runtime/domain/subagents/child-operations.ts +80 -1
  193. package/src/runtime/domain/subagents/child-preflight.mjs +9 -2
  194. package/src/runtime/domain/subagents/child-process-list.domain.mjs +7 -0
  195. package/src/runtime/domain/subagents/child-process-list.ts +8 -0
  196. package/src/runtime/domain/subagents/cleanup.domain.mjs +11 -2
  197. package/src/runtime/domain/subagents/cleanup.ts +10 -2
  198. package/src/runtime/domain/subagents/config.domain.mjs +54 -2
  199. package/src/runtime/domain/subagents/config.ts +53 -3
  200. package/src/runtime/domain/subagents/continuation-authority.domain.mjs +5 -1
  201. package/src/runtime/domain/subagents/continuation-authority.ts +3 -1
  202. package/src/runtime/domain/subagents/continuation-runtime.domain.mjs +89 -0
  203. package/src/runtime/domain/subagents/continuation-runtime.ts +88 -0
  204. package/src/runtime/domain/subagents/continuation.domain.mjs +4 -2
  205. package/src/runtime/domain/subagents/continuation.ts +4 -2
  206. package/src/runtime/domain/subagents/extensions.mjs +11 -13
  207. package/src/runtime/domain/subagents/failures.domain.mjs +11 -2
  208. package/src/runtime/domain/subagents/failures.ts +10 -2
  209. package/src/runtime/domain/subagents/finalization.domain.mjs +16 -1
  210. package/src/runtime/domain/subagents/finalization.ts +21 -1
  211. package/src/runtime/domain/subagents/goal-provider.domain.mjs +44 -2
  212. package/src/runtime/domain/subagents/goal-provider.ts +44 -2
  213. package/src/runtime/domain/subagents/health-observation.domain.mjs +189 -190
  214. package/src/runtime/domain/subagents/health-observation.ts +43 -48
  215. package/src/runtime/domain/subagents/index.domain.mjs +457 -182
  216. package/src/runtime/domain/subagents/index.ts +417 -155
  217. package/src/runtime/domain/subagents/isolated-workspace.domain.mjs +515 -0
  218. package/src/runtime/domain/subagents/isolated-workspace.ts +557 -0
  219. package/src/runtime/domain/subagents/launch-context.domain.mjs +24 -0
  220. package/src/runtime/domain/subagents/launch-context.ts +23 -0
  221. package/src/runtime/domain/subagents/launch-digest.mjs +6 -0
  222. package/src/runtime/domain/subagents/list.mjs +2 -2
  223. package/src/runtime/domain/subagents/log-cursor.domain.mjs +85 -16
  224. package/src/runtime/domain/subagents/log-cursor.ts +91 -15
  225. package/src/runtime/domain/subagents/managed-launch-bootstrap.mjs +2 -2
  226. package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +27 -7
  227. package/src/runtime/domain/subagents/managed-launch-client.ts +28 -8
  228. package/src/runtime/domain/subagents/managed-launch-host.domain.mjs +222 -14
  229. package/src/runtime/domain/subagents/managed-launch-host.ts +168 -15
  230. package/src/runtime/domain/subagents/managed-launch-journal.mjs +1 -5
  231. package/src/runtime/domain/subagents/managed-launch-port.ts +4 -0
  232. package/src/runtime/domain/subagents/operation-bridge-types.domain.mjs +27 -2
  233. package/src/runtime/domain/subagents/operation-bridge-types.ts +27 -2
  234. package/src/runtime/domain/subagents/output-payload.domain.mjs +24 -9
  235. package/src/runtime/domain/subagents/output-payload.ts +26 -12
  236. package/src/runtime/domain/subagents/owned-exit.domain.mjs +12 -0
  237. package/src/runtime/domain/subagents/owned-exit.ts +12 -0
  238. package/src/runtime/domain/subagents/package.json +4 -2
  239. package/src/runtime/domain/subagents/parse.domain.mjs +58 -9
  240. package/src/runtime/domain/subagents/parse.ts +57 -10
  241. package/src/runtime/domain/subagents/permission-policy.domain.mjs +32 -8
  242. package/src/runtime/domain/subagents/permission-policy.ts +41 -8
  243. package/src/runtime/domain/subagents/process-identity.mjs +33 -0
  244. package/src/runtime/domain/subagents/registry.domain.mjs +71 -51
  245. package/src/runtime/domain/subagents/registry.ts +77 -38
  246. package/src/runtime/domain/subagents/retained-result.domain.mjs +56 -0
  247. package/src/runtime/domain/subagents/retained-result.ts +65 -0
  248. package/src/runtime/domain/subagents/session-selection.domain.mjs +3 -1
  249. package/src/runtime/domain/subagents/session-selection.ts +2 -1
  250. package/src/runtime/domain/subagents/session-store.domain.mjs +7 -0
  251. package/src/runtime/domain/subagents/session-store.ts +9 -0
  252. package/src/runtime/domain/subagents/settings-page.domain.mjs +151 -107
  253. package/src/runtime/domain/subagents/settings-page.ts +147 -108
  254. package/src/runtime/domain/subagents/shared-callback-batcher.domain.mjs +8 -1
  255. package/src/runtime/domain/subagents/shared-callback-batcher.ts +11 -2
  256. package/src/runtime/domain/subagents/shared-catalog.domain.mjs +28 -29
  257. package/src/runtime/domain/subagents/shared-catalog.ts +29 -21
  258. package/src/runtime/domain/subagents/shared-navigator-panels.domain.mjs +24 -2
  259. package/src/runtime/domain/subagents/shared-navigator-panels.ts +26 -4
  260. package/src/runtime/domain/subagents/shared-navigator.domain.mjs +273 -41
  261. package/src/runtime/domain/subagents/shared-navigator.ts +244 -40
  262. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-inbox.mjs +144 -0
  263. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-observation.mjs +53 -41
  264. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
  265. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  266. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
  267. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  268. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
  269. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.ts +14 -3
  270. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
  271. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.ts +5 -3
  272. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.domain.mjs +44 -4
  273. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.ts +50 -2
  274. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  275. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.ts +9 -0
  276. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
  277. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.ts +12 -0
  278. package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.domain.mjs +2 -0
  279. package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.ts +2 -0
  280. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +42 -21
  281. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +40 -24
  282. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +26 -4
  283. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +40 -8
  284. package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
  285. package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.ts +24 -1
  286. package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.domain.mjs +1 -1
  287. package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.ts +5 -1
  288. package/src/runtime/domain/subagents/shared-sandbox-core.ts +1 -1
  289. package/src/runtime/domain/subagents/shared-task-exec.domain.mjs +14 -1
  290. package/src/runtime/domain/subagents/shared-task-exec.ts +12 -1
  291. package/src/runtime/domain/subagents/shared-task-process-identity.domain.mjs +140 -0
  292. package/src/runtime/domain/subagents/shared-task-process-identity.ts +126 -0
  293. package/src/runtime/domain/subagents/shared-task-process-list.domain.mjs +3 -2
  294. package/src/runtime/domain/subagents/shared-task-process-list.ts +8 -2
  295. package/src/runtime/domain/subagents/shared-task-sandbox.domain.mjs +4 -3
  296. package/src/runtime/domain/subagents/shared-task-sandbox.ts +5 -3
  297. package/src/runtime/domain/subagents/shared-task-tools.domain.mjs +8 -5
  298. package/src/runtime/domain/subagents/shared-task-tools.ts +8 -5
  299. package/src/runtime/domain/subagents/shared-work-client.mjs +174 -7
  300. package/src/runtime/domain/subagents/subagent-tools.domain.mjs +22 -38
  301. package/src/runtime/domain/subagents/subagent-tools.ts +28 -34
  302. package/src/runtime/domain/subagents/task-guard.domain.mjs +14 -1
  303. package/src/runtime/domain/subagents/task-guard.ts +13 -1
  304. package/src/runtime/domain/subagents/task-policy.domain.mjs +3 -2
  305. package/src/runtime/domain/subagents/task-policy.ts +8 -2
  306. package/src/runtime/domain/subagents/timing.domain.mjs +10 -1
  307. package/src/runtime/domain/subagents/timing.ts +10 -1
  308. package/src/runtime/domain/subagents/tools.domain.mjs +4 -8
  309. package/src/runtime/domain/subagents/tools.ts +4 -7
  310. package/src/runtime/domain/subagents/work-observation.domain.mjs +102 -17
  311. package/src/runtime/domain/subagents/work-observation.ts +91 -17
  312. package/src/runtime/domain/subagents/worker-operations-host.domain.mjs +9 -4
  313. package/src/runtime/domain/subagents/worker-operations-host.ts +12 -4
  314. package/src/runtime/domain/subagents/worker-waits.domain.mjs +89 -35
  315. package/src/runtime/domain/subagents/worker-waits.ts +93 -34
  316. package/src/runtime/domain/subagents/workspace-files.domain.mjs +103 -0
  317. package/src/runtime/domain/subagents/workspace-files.ts +114 -0
  318. package/src/runtime/domain/subagents/workspace-scope.domain.d.mts +38 -0
  319. package/src/runtime/domain/subagents/workspace-scope.domain.mjs +5 -0
  320. package/src/runtime/domain/subagents/workspace-scope.ts +6 -0
  321. package/src/runtime/domain/subagents/worktree-feedback.domain.mjs +55 -0
  322. package/src/runtime/domain/subagents/worktree-feedback.ts +77 -0
  323. package/src/runtime/health-config.ts +27 -11
  324. package/src/runtime/log-checkpoints.ts +117 -0
  325. package/src/runtime/mutation-store.ts +5 -4
  326. package/src/runtime/queries.ts +25 -2
  327. package/src/runtime/query-executor.ts +149 -28
  328. package/src/runtime/query-worker.mjs +106 -21
  329. package/src/runtime/read-model.ts +849 -121
  330. package/src/runtime/read-watchdog-probe.ts +4 -0
  331. package/src/runtime/result-supervision.ts +188 -16
  332. package/src/runtime/root.ts +5 -2
  333. package/src/runtime/source-watch.ts +175 -0
  334. package/src/runtime/subagent-launch.ts +11 -4
  335. package/src/runtime/work-budget.ts +130 -0
  336. package/src/runtime/work-client.d.mts +8 -0
  337. package/src/runtime/work-client.mjs +150 -7
  338. package/src/server.ts +104 -23
  339. package/src/session-activity.ts +26 -4
  340. package/src/version.ts +1 -1
@@ -4,19 +4,25 @@ import { resolve } from "node:path";
4
4
  import type { Duplex } from "node:stream";
5
5
  import type { WorkReadModel } from "./read-model.ts";
6
6
  import { workScope } from "./queries.ts";
7
+ import { executionPhases, inventoryPhases } from "./read-watchdog-probe.ts";
8
+ import { notifyWorkBudget } from "./work-budget.ts";
9
+ import { HostSourceWatches } from "./source-watch.ts";
7
10
 
8
11
  export interface EncodedRead { json: string }
9
- interface Waiter { connection: number; resolve(value: EncodedRead): void; reject(error: Error): void }
12
+ interface Waiter { connection: number; expiresAt: number; deadline: ReturnType<typeof setTimeout>; resolve(value: EncodedRead): void; reject(error: Error): void }
10
13
  interface Query {
11
14
  id: number; key?: string; command: Record<string, unknown>; connection: number;
12
- enqueued: number; deadline: ReturnType<typeof setTimeout>; waiters: Set<Waiter>;
15
+ enqueued: number; started?: number; progressAt: number; waiters: Set<Waiter>;
13
16
  }
14
17
  export type ReadStream = Pick<Duplex, "destroyed" | "writableLength" | "write" | "on" | "once" | "off">;
15
18
  interface Stream { socket: ReadStream; paused: boolean; generation: number; drain: () => void; close: () => void }
16
19
  interface WorkerMetrics { sourceWatchers?: number; inventories?: number; coordinatorConnections?: number; indexConnections?: number; sqlite?: { opens: number; active: number; maximum: number }; [key: string]: unknown }
17
20
  export interface QueryExecutorOptions {
18
- capacity?: number; timeoutMs?: number; maxConnections?: number;
21
+ queryCacheDiagnostics?: boolean;
22
+ capacity?: number; timeoutMs?: number; maxConnections?: number; watchdogMs?: number;
19
23
  workerUrl?: URL;
24
+ logWatchdog?: (line: string) => void;
25
+ budgetBuffer?: SharedArrayBuffer;
20
26
  onTerminalLogsChanged?: (ids: string[]) => Promise<void>;
21
27
  modelOptions?: { supervisorDirectory?: string; baseDir?: string; durableDir?: string; intervalMs?: number };
22
28
  }
@@ -24,6 +30,7 @@ export interface QueryExecutorOptions {
24
30
  /** One root, one read worker, one admitted operation at a time. No mutation RPC. */
25
31
  export class WorkQueryExecutor {
26
32
  private worker: Worker;
33
+ private sourceWatches = new HostSourceWatches();
27
34
  private streams = new Map<number, Stream>();
28
35
  private workerConnections = new Set<number>();
29
36
  private queue: Query[] = [];
@@ -40,6 +47,11 @@ export class WorkQueryExecutor {
40
47
  private recoveryAttempts: number[] = [];
41
48
  private internalRecoveryDemand = false;
42
49
  private recoveryTimer?: ReturnType<typeof setTimeout>;
50
+ private watchdog?: ReturnType<typeof setInterval>;
51
+ private watchdogCheck?: ReturnType<typeof setImmediate>;
52
+ private lastResponse = performance.now();
53
+ private heartbeat!: BigInt64Array;
54
+ private probe?: Int32Array;
43
55
  private workerMetrics: WorkerMetrics = {};
44
56
  private lastObservation: Omit<ReturnType<WorkReadModel["observation"]>, "observedAt"> & { observedAt: number | null } = {
45
57
  status: "rebuilding", reason: "Initial source inventory is rebuilding.", observedAt: null, reasons: [],
@@ -51,27 +63,97 @@ export class WorkQueryExecutor {
51
63
  private rejected = 0;
52
64
  private cancelled = 0;
53
65
  private timeouts = 0;
66
+ private queueTimeouts = 0;
67
+ private callerTimeouts = 0;
54
68
  private durations: number[] = [];
55
69
  private options: QueryExecutorOptions;
56
70
  private agentDir: string;
57
71
  readonly instanceId: string;
72
+ requestReasons() {
73
+ return [...this.queue, ...(this.active ? [this.active] : [])].flatMap(query => [...query.waiters].map(waiter => ({
74
+ kind: 'read-request', id: query.id, connection: waiter.connection, generation: this.workerGeneration,
75
+ phase: query.started === undefined ? 'queued' : 'dispatched',
76
+ lastProgressAt: query.progressAt,
77
+ nextDeadline: waiter.expiresAt, executionDeadline: null,
78
+ recovery: 'caller-timeout-or-disconnect-removes-waiter-without-cancelling-physical-worker-work',
79
+ })));
80
+ }
58
81
 
59
82
  constructor(agentDir: string, instanceId: string, options: QueryExecutorOptions = {}) {
60
83
  this.options = options; this.instanceId = instanceId; this.agentDir = agentDir;
61
84
  this.lag.enable();
62
85
  this.worker = this.startWorker();
86
+ const watchdogMs = this.options.watchdogMs ?? 4000;
87
+ let previousCheck = performance.now();
88
+ let resumedAt = previousCheck;
89
+ this.watchdog = setInterval(() => {
90
+ const now = performance.now();
91
+ // After system sleep both threads can resume with an expired heartbeat.
92
+ if (now - previousCheck > watchdogMs) resumedAt = now;
93
+ previousCheck = now;
94
+ if (this.closed || this.failure || now - Math.max(this.lastResponse, resumedAt) <= watchdogMs) return;
95
+ // Drain queued worker responses before treating a delayed timer as worker silence.
96
+ this.watchdogCheck ??= setImmediate(() => {
97
+ this.watchdogCheck = undefined;
98
+ this.checkWatchdog();
99
+ });
100
+ this.watchdogCheck.unref();
101
+ }, Math.min(250, watchdogMs / 4));
102
+ this.watchdog.unref();
103
+ }
104
+
105
+ private checkWatchdog() {
106
+ const silenceMs = performance.now() - this.lastResponse;
107
+ if (!this.closed && !this.failure && silenceMs > (this.options.watchdogMs ?? 4000)) {
108
+ const tick = Atomics.load(this.heartbeat, 0);
109
+ const heartbeatAgeMs = tick === 0n ? null : Number(process.hrtime.bigint() - tick) / 1e6;
110
+ // A busy parent can run the overdue watchdog before draining queued messages.
111
+ if (heartbeatAgeMs !== null && heartbeatAgeMs <= (this.options.watchdogMs ?? 4000)) return;
112
+ if (this.probe) {
113
+ const evidence = { generation: this.workerGeneration, silenceMs: Math.round(silenceMs),
114
+ heartbeatAgeMs: heartbeatAgeMs === null ? null : Math.round(heartbeatAgeMs),
115
+ mainLoopMaxDelayMs: Math.round(this.lag.max / 1e6), active: !!this.active, queued: this.queue.length,
116
+ execution: executionPhases[Atomics.load(this.probe, 0)], inventory: inventoryPhases[Atomics.load(this.probe, 1)] };
117
+ try { this.options.logWatchdog?.(`Read worker watchdog: ${JSON.stringify(evidence)}`); } catch { /* preserve watchdog behavior */ }
118
+ }
119
+ this.fail(new Error("runtime-unhealthy: read worker unresponsive; watchdog deadline exceeded"));
120
+ }
63
121
  }
64
122
 
65
123
  private startWorker() {
124
+ if (this.options.budgetBuffer) {
125
+ // startWorker runs only initially or after the preceding thread exited.
126
+ // A dead generation cannot retain source credits in the shared budget.
127
+ const counts = new Int32Array(this.options.budgetBuffer);
128
+ Atomics.store(counts, 1, 0); Atomics.store(counts, 2, 0);
129
+ notifyWorkBudget(this.options.budgetBuffer);
130
+ }
131
+ const generation = this.workerGeneration;
66
132
  const instanceId = this.workerGeneration ? `${this.instanceId}:reads:${this.workerGeneration}` : this.instanceId;
133
+ this.heartbeat = new BigInt64Array(new SharedArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT));
134
+ this.probe = this.options.logWatchdog ? new Int32Array(new SharedArrayBuffer(8)) : undefined;
67
135
  const worker = new Worker(this.options.workerUrl ?? new URL("./query-worker.mjs", import.meta.url), {
68
- execArgv: [], workerData: { agentDir: this.agentDir, instanceId, modelOptions: this.options.modelOptions },
136
+ execArgv: [], workerData: { agentDir: this.agentDir, instanceId, modelOptions: { ...this.options.modelOptions, budgetBuffer: this.options.budgetBuffer },
137
+ queryCacheDiagnostics: this.options.queryCacheDiagnostics === true, probe: this.probe, heartbeat: this.heartbeat },
138
+ });
139
+ worker.on("message", message => {
140
+ if (this.sourceWatches.handle(generation, message, value => {
141
+ if (worker === this.worker && !this.exited) worker.postMessage(value);
142
+ })) return;
143
+ if (worker === this.worker) this.receive(message);
144
+ });
145
+ worker.on("error", error => {
146
+ if (worker !== this.worker) return;
147
+ const original = String(error);
148
+ // Preserve the SQLite producer that the forwarded Error message omits.
149
+ const producer = /database (?:is locked|table is locked)/.test(original)
150
+ ? `\n${String(error instanceof Error ? error.stack ?? error : error).split("\n").slice(0, 12).join("\n").slice(0, 4096)}` : "";
151
+ this.fail(new Error(`runtime-unhealthy: read worker failed: ${original}${producer}`, { cause: error }));
69
152
  });
70
- worker.on("message", message => { if (worker === this.worker) this.receive(message); });
71
- worker.on("error", error => { if (worker === this.worker) this.fail(new Error(`runtime-unhealthy: read worker failed: ${String(error)}`)); });
72
153
  worker.on("exit", code => {
73
154
  if (worker !== this.worker) return;
74
155
  this.exited = true;
156
+ void this.sourceWatches.revoke(generation).catch(() => {});
75
157
  const sqlite = this.workerMetrics.sqlite;
76
158
  this.workerMetrics = { ...this.workerMetrics, sourceWatchers: 0, coordinatorConnections: 0, indexConnections: 0,
77
159
  ...(sqlite ? { sqlite: { ...sqlite, active: 0 } } : {}) };
@@ -99,6 +181,7 @@ export class WorkQueryExecutor {
99
181
  this.internalRecoveryDemand = false;
100
182
  this.exited = false; this.failure = undefined; this.termination = undefined;
101
183
  this.workerMetrics = {}; this.workerConnections.clear(); this.revision++;
184
+ this.lastResponse = performance.now();
102
185
  this.lastObservation = { status: "rebuilding", reason: "Read worker is recovering its source inventory.", observedAt: null, reasons: [] };
103
186
  this.lag.reset(); this.lag.enable();
104
187
  try { this.worker = this.startWorker(); }
@@ -145,9 +228,9 @@ export class WorkQueryExecutor {
145
228
  }
146
229
 
147
230
  metrics() {
148
- return { ...this.workerMetrics, executor: { active: this.active ? 1 : 0, queued: this.queue.length,
231
+ return { ...this.workerMetrics, sourceSubscriptions: this.sourceWatches.metrics(), executor: { active: this.active ? 1 : 0, queued: this.queue.length,
149
232
  clients: this.streams.size, completed: this.completed, singleflightHits: this.coalesced, rejected: this.rejected,
150
- cancelled: this.cancelled, timeouts: this.timeouts,
233
+ cancelled: this.cancelled, timeouts: this.timeouts, queueTimeouts: this.queueTimeouts, callerTimeouts: this.callerTimeouts,
151
234
  capacity: this.options.capacity ?? 64, waitMs: [...this.waits], readMs: [...this.durations],
152
235
  eventLoopLagMs: { p50: this.lag.percentile(50) / 1e6, p95: this.lag.percentile(95) / 1e6, p99: this.lag.percentile(99) / 1e6 },
153
236
  worker: this.exited ? "stopped" : this.failure ? "stopping" : "running",
@@ -162,9 +245,21 @@ export class WorkQueryExecutor {
162
245
  if (connection === 0) this.internalRecoveryDemand = true;
163
246
  this.scheduleRecovery(); return Promise.reject(this.failure);
164
247
  }
165
- if (!["runtime_get_snapshot", "runtime_subscribe", "runtime_unsubscribe", "runtime_get_liveness", "runtime_get_upgrade_obligations"].includes(String(input.type))) return Promise.reject(new Error("Unsupported read operation"));
166
248
  if (input.sinceSeq !== undefined && !Number.isSafeInteger(input.sinceSeq)) return Promise.reject(new Error("Invalid replay sequence"));
167
249
  if (input.instanceId !== undefined && (typeof input.instanceId !== "string" || input.instanceId.length > 256)) return Promise.reject(new Error("Invalid runtime instance"));
250
+ if (input.type === "runtime_unsubscribe") {
251
+ for (const query of [...this.queue, ...(this.active ? [this.active] : [])]) {
252
+ if (query.command.type !== "runtime_subscribe" || query.connection !== connection) continue;
253
+ this.finish(query, new Error("runtime-unavailable: subscription cancelled"));
254
+ this.release(query);
255
+ }
256
+ const stream = this.streams.get(connection);
257
+ if (stream) stream.generation++;
258
+ this.worker.postMessage({ type: "detach", connection });
259
+ this.workerConnections.delete(connection);
260
+ return Promise.resolve({ json: '{"unsubscribed":true}' });
261
+ }
262
+ if (!["runtime_get_snapshot", "runtime_subscribe", "runtime_unsubscribe", "runtime_get_liveness", "runtime_get_upgrade_obligations"].includes(String(input.type))) return Promise.reject(new Error("Unsupported read operation"));
168
263
  const command: Record<string, unknown> = { type: input.type, sinceSeq: input.sinceSeq, instanceId: input.instanceId };
169
264
  if (command.type !== "runtime_unsubscribe" && command.type !== "runtime_get_liveness" && command.type !== "runtime_get_upgrade_obligations") {
170
265
  const scope = workScope(input.scope);
@@ -183,13 +278,17 @@ export class WorkQueryExecutor {
183
278
  return Promise.reject(new Error("runtime-overloaded: read queue is full; retry later"));
184
279
  }
185
280
  const id = ++this.counter;
186
- query = { id, key, command, connection: key ? 0 : connection, enqueued: performance.now(),
187
- deadline: setTimeout(() => this.expire(id), this.options.timeoutMs ?? 4000), waiters: new Set() };
281
+ query = { id, key, command, connection: key ? 0 : connection, enqueued: performance.now(), progressAt: Date.now(), waiters: new Set() };
188
282
  this.queue.push(query);
189
283
  if (key) this.flights.set(key, query);
190
284
  }
191
285
  const admitted = query;
192
- const result = new Promise<EncodedRead>((resolve, reject) => admitted.waiters.add({ connection, resolve, reject }));
286
+ const result = new Promise<EncodedRead>((resolve, reject) => {
287
+ const waiter: Waiter = { connection, resolve, reject,
288
+ expiresAt: Date.now() + (this.options.timeoutMs ?? 4000),
289
+ deadline: setTimeout(() => this.expire(admitted, waiter), this.options.timeoutMs ?? 4000) };
290
+ admitted.waiters.add(waiter);
291
+ });
193
292
  this.pump();
194
293
  return result;
195
294
  }
@@ -197,6 +296,8 @@ export class WorkQueryExecutor {
197
296
  private pump() {
198
297
  if (this.failure || this.active || !this.queue.length) return;
199
298
  const query = this.active = this.queue.shift()!;
299
+ query.started = performance.now();
300
+ query.progressAt = Date.now();
200
301
  this.waits.push(performance.now() - query.enqueued);
201
302
  if (this.waits.length > 128) this.waits.shift();
202
303
  const stream = this.streams.get(query.connection);
@@ -207,6 +308,13 @@ export class WorkQueryExecutor {
207
308
 
208
309
  private receive(message: any) {
209
310
  if (this.failure) return;
311
+ this.lastResponse = performance.now();
312
+ if (message.type === "heartbeat") { this.worker.postMessage({ type: "heartbeat-consumed" }); return; }
313
+ // Replies to cancelled reads carry no fresh observation or metrics authority.
314
+ if (message.type === "reply" && (!this.active || message.id !== this.active.id || !this.active.waiters.size)) {
315
+ if (message.id === this.active?.id) { this.active = undefined; this.pump(); }
316
+ return;
317
+ }
210
318
  if (message.metrics) this.workerMetrics = message.metrics;
211
319
  if (message.observation) this.lastObservation = message.observation;
212
320
  if (message.type === "terminal-logs") {
@@ -227,27 +335,40 @@ export class WorkQueryExecutor {
227
335
  if (message.type !== "reply" || message.id !== this.active?.id) return;
228
336
  const query = this.active!;
229
337
  this.active = undefined; this.completed++;
230
- this.durations.push(performance.now() - query.enqueued);
338
+ this.durations.push(performance.now() - query.started!);
231
339
  if (this.durations.length > 128) this.durations.shift();
232
340
  this.finish(query, message.error ? new Error(message.error) : undefined, { json: message.json });
233
341
  this.pump();
234
342
  }
235
343
 
236
344
  private finish(query: Query, error?: Error, value: EncodedRead = { json: "null" }) {
237
- clearTimeout(query.deadline);
238
345
  if (query.key && this.flights.get(query.key) === query) this.flights.delete(query.key);
239
- for (const waiter of query.waiters) { if (error) waiter.reject(error); else waiter.resolve(value); }
346
+ for (const waiter of query.waiters) { clearTimeout(waiter.deadline); if (error) waiter.reject(error); else waiter.resolve(value); }
240
347
  query.waiters.clear();
241
348
  }
242
349
 
243
- private expire(id: number) {
350
+ private expire(query: Query, waiter: Waiter) {
351
+ if (!query.waiters.delete(waiter)) return;
244
352
  this.timeouts++;
245
- const error = new Error("runtime-unhealthy: read deadline exceeded; retry after recovery");
246
- if (this.active?.id === id) { this.fail(error); return; }
247
- const index = this.queue.findIndex(query => query.id === id);
248
- if (index < 0) return;
249
- const [query] = this.queue.splice(index, 1);
250
- this.finish(query!, error);
353
+ if (query === this.active) this.callerTimeouts++;
354
+ else this.queueTimeouts++;
355
+ waiter.reject(new Error(query === this.active
356
+ ? "runtime-timeout: caller read deadline exceeded; source was not verified"
357
+ : "runtime-overloaded: queued read deadline exceeded; retry later"));
358
+ this.release(query);
359
+ }
360
+
361
+ private release(query: Query) {
362
+ if (query.waiters.size) return;
363
+ this.finish(query);
364
+ if (query === this.active) {
365
+ // Keep the execution slot until cancellation is acknowledged. This bounds
366
+ // the worker mailbox even when native work cannot be interrupted.
367
+ this.worker.postMessage({ type: "cancel", id: query.id });
368
+ } else {
369
+ const index = this.queue.indexOf(query);
370
+ if (index >= 0) this.queue.splice(index, 1);
371
+ }
251
372
  }
252
373
 
253
374
  private event(connection: number, line: string) {
@@ -265,12 +386,9 @@ export class WorkQueryExecutor {
265
386
  if (this.workerConnections.delete(connection) && !this.failure) this.worker.postMessage({ type: "detach", connection });
266
387
  for (const query of [...this.queue, ...(this.active ? [this.active] : [])]) {
267
388
  for (const waiter of query.waiters) if (waiter.connection === connection) {
268
- query.waiters.delete(waiter); this.cancelled++; waiter.reject(new Error("runtime-unavailable: client disconnected"));
269
- }
270
- if (!query.waiters.size && query !== this.active) {
271
- this.queue.splice(this.queue.indexOf(query), 1);
272
- this.finish(query);
389
+ query.waiters.delete(waiter); clearTimeout(waiter.deadline); this.cancelled++; waiter.reject(new Error("runtime-unavailable: client disconnected"));
273
390
  }
391
+ this.release(query);
274
392
  }
275
393
  }
276
394
 
@@ -283,18 +401,21 @@ export class WorkQueryExecutor {
283
401
  this.queue = []; this.active = undefined;
284
402
  for (const connection of this.streams.keys()) this.event(connection, JSON.stringify({ type: "event",
285
403
  event: { type: "resync_required", reason: error.message, instanceId: this.instanceId } }) + "\n");
404
+ void this.sourceWatches.revoke(this.workerGeneration).catch(() => {});
286
405
  this.termination = this.worker.terminate();
287
406
  this.worker.unref();
288
407
  }
289
408
 
290
409
  async close() {
291
410
  this.closed = true;
411
+ if (this.watchdog) clearInterval(this.watchdog);
412
+ if (this.watchdogCheck) clearImmediate(this.watchdogCheck);
292
413
  if (this.recoveryTimer) { clearTimeout(this.recoveryTimer); this.recoveryTimer = undefined; }
293
414
  this.fail(new Error("runtime-unavailable: query executor closed"));
294
415
  for (const connection of this.streams.keys()) this.detach(connection);
295
416
  let timeout: ReturnType<typeof setTimeout> | undefined;
296
417
  // Bound graceful close even while native SQLite is still finishing a call.
297
- await Promise.race([this.termination, new Promise<void>(resolve => { timeout = setTimeout(resolve, 1000); })]);
418
+ await Promise.race([Promise.all([this.termination, this.sourceWatches.close().catch(() => {})]), new Promise<void>(resolve => { timeout = setTimeout(resolve, 1000); })]);
298
419
  if (timeout) clearTimeout(timeout);
299
420
  }
300
421
  }
@@ -3,6 +3,20 @@ import { createRequire } from "node:module";
3
3
  import { EventEmitter } from "node:events";
4
4
  import { performance } from "node:perf_hooks";
5
5
 
6
+ // Publish liveness during async imports too. This clock measures the worker's
7
+ // own event loop, independently of parent delivery and source readiness.
8
+ let heartbeatPending = false;
9
+ let rpcInstalled = false;
10
+ const heartbeat = workerData.heartbeat;
11
+ const markHeartbeat = () => { if (heartbeat) Atomics.store(heartbeat, 0, process.hrtime.bigint()); };
12
+ markHeartbeat();
13
+ setInterval(() => {
14
+ markHeartbeat();
15
+ if (!rpcInstalled || heartbeatPending) return;
16
+ heartbeatPending = true;
17
+ parentPort.postMessage({ type: "heartbeat" });
18
+ }, 250).unref();
19
+
6
20
  // The fixed Node 24 artifact strips types natively and does not depend on tsx.
7
21
  // Development on Node 22 uses the workspace loader without inheriting test preloads.
8
22
  if (Number(process.versions.node.split(".")[0]) < 24) {
@@ -25,8 +39,33 @@ sqlite.DatabaseSync = class extends OriginalDatabase {
25
39
  }
26
40
  };
27
41
  const { WorkReadModel } = await import("./read-model.ts");
28
- const { WorkQueries } = await import("./queries.ts");
29
- const model = new WorkReadModel(workerData.agentDir, workerData.instanceId, workerData.modelOptions);
42
+ const { createWorkBudget } = await import("./work-budget.ts");
43
+ const budget = createWorkBudget(workerData.modelOptions?.budgetBuffer);
44
+ const { workerSourceWatch } = await import("./source-watch.ts");
45
+ const { WorkQueries, workScope, queryEncodingMetrics, snapshotJSON } = await import("./queries.ts");
46
+ const { executionPhases, inventoryPhases } = await import("./read-watchdog-probe.ts");
47
+ const probe = workerData.probe;
48
+ const markExecution = phase => { if (probe) Atomics.store(probe, 0, executionPhases.indexOf(phase)); };
49
+ function observeExecution(phase, run) {
50
+ if (!probe) return run();
51
+ const previous = Atomics.exchange(probe, 0, executionPhases.indexOf(phase));
52
+ try { return run(); } finally { Atomics.store(probe, 0, previous); }
53
+ }
54
+ let model;
55
+ try {
56
+ model = new WorkReadModel(workerData.agentDir, workerData.instanceId, {
57
+ ...workerData.modelOptions, watch: workerSourceWatch(parentPort),
58
+ inventoryPhase: probe ? phase => Atomics.store(probe, 1, inventoryPhases.indexOf(phase)) : undefined,
59
+ });
60
+ } catch (error) {
61
+ // Worker error forwarding retains only String(error). Keep the original
62
+ // statement's stack for this specific bootstrap failure, without source data.
63
+ if (/database is locked/.test(String(error))) {
64
+ console.error(`[runtime-read-bootstrap] WorkReadModel constructor\n${String(error?.stack ?? error).split("\n").slice(0, 12).join("\n").slice(0, 4096)}`);
65
+ }
66
+ throw error;
67
+ }
68
+ markExecution("idle");
30
69
  // One bounded in-flight batch. Remaining obligations stay in the reconstructable
31
70
  // inventory index; an acknowledgement cannot erase a newer revision of an ID.
32
71
  let terminalLogsPending;
@@ -39,22 +78,44 @@ const sendTerminalLogs = () => {
39
78
  };
40
79
  model.onTerminalLogsChanged = sendTerminalLogs;
41
80
  const sessions = new Map();
81
+ const requests = new Map();
42
82
  const cache = new Map();
43
83
  const encoded = new WeakMap();
44
- let cacheBytes = 0, cacheHits = 0, queryCount = 0;
84
+ let cacheBytes = 0, cacheHits = 0, queryCount = 0, serializationCount = 0;
45
85
  let revisionPending = false, revisionDirty = false;
46
86
  const durations = [];
47
- const metrics = () => ({ ...model.metrics, background: model.backgroundMetrics, sqlite: { ...connections }, cacheHits, queryCount, cacheBytes,
48
- cacheEntries: cache.size, queryDurationMs: [...durations] });
87
+ const cacheComparisons = workerData.queryCacheDiagnostics ? [] : undefined;
88
+ const metrics = () => ({ ...model.metrics, background: model.backgroundMetrics, sqlite: { ...connections }, cacheHits, queryCount, serializationCount, eventEncoding: { ...queryEncodingMetrics }, cacheBytes,
89
+ cacheEntries: cache.size, queryDurationMs: [...durations], ...(cacheComparisons ? { cacheComparisons: [...cacheComparisons] } : {}) });
49
90
  const snapshot = model.snapshot.bind(model);
50
- model.snapshot = scope => {
91
+ model.snapshot = scope => observeExecution("snapshot", () => {
92
+ scope = workScope(scope ?? {});
51
93
  const key = JSON.stringify(scope ?? {});
94
+ const revision = model.contentRevision(scope);
52
95
  const cacheable = !scope?.backgroundHistory;
53
96
  const previous = cacheable ? cache.get(key) : undefined;
54
- if (previous) { cacheHits++; cache.delete(key); cache.set(key, previous); return previous.value; }
97
+ const comparedAt = Date.now();
98
+ const hit = previous?.revision === revision && (previous.value.nextDeadline === null || previous.value.nextDeadline > comparedAt);
99
+ // Only the original regression fixture opts in; no extra source reads.
100
+ let comparison;
101
+ if (cacheComparisons) {
102
+ comparison = { queryCount, scope, revision, priorRevision: previous?.revision ?? null,
103
+ priorScopeRevision: previous?.value.scopeRevision ?? null, priorSeq: previous?.value.seq ?? null,
104
+ priorObservedRevisionVector: previous?.value.observedRevisionVector ?? null, priorDeadline: previous?.value.nextDeadline ?? null,
105
+ comparedAt, hit: Boolean(hit) };
106
+ cacheComparisons.push(comparison);
107
+ if (cacheComparisons.length > 16) cacheComparisons.shift();
108
+ }
109
+ if (hit) {
110
+ cacheHits++; cache.delete(key); cache.set(key, previous); return previous.value;
111
+ }
112
+ if (previous) { cacheBytes -= previous.bytes; cache.delete(key); }
55
113
  const started = performance.now();
56
114
  const value = snapshot(scope);
57
- const json = JSON.stringify(value);
115
+ if (comparison) Object.assign(comparison, { scopeRevision: value.scopeRevision,
116
+ nextDeadline: value.nextDeadline, seq: value.seq, observedRevisionVector: value.observedRevisionVector });
117
+ const json = snapshotJSON(value);
118
+ serializationCount++;
58
119
  const bytes = Buffer.byteLength(json);
59
120
  encoded.set(value, json);
60
121
  queryCount++; durations.push(performance.now() - started);
@@ -64,16 +125,15 @@ model.snapshot = scope => {
64
125
  const oldest = cache.keys().next().value;
65
126
  cacheBytes -= cache.get(oldest).bytes; cache.delete(oldest);
66
127
  }
67
- cache.set(key, { value, bytes }); cacheBytes += bytes;
128
+ cache.set(key, { value, bytes, revision }); cacheBytes += bytes;
68
129
  }
69
130
  return value;
70
- };
131
+ });
71
132
  function revision() {
72
133
  revisionPending = true;
73
- parentPort.postMessage({ type: "revision", metrics: metrics(), observation: model.observation() });
134
+ observeExecution("publish", () => parentPort.postMessage({ type: "revision", metrics: metrics(), observation: model.observation() }));
74
135
  }
75
136
  model.onChange(() => {
76
- cache.clear(); cacheBytes = 0;
77
137
  if (revisionPending) revisionDirty = true;
78
138
  else revision();
79
139
  });
@@ -96,36 +156,61 @@ function session(id) {
96
156
  }
97
157
 
98
158
  parentPort.on("message", async message => {
159
+ if (message.type === "heartbeat-consumed") { heartbeatPending = false; return; }
160
+ if (message.type === "cancel") {
161
+ const request = requests.get(message.id);
162
+ if (request) {
163
+ request.cancelled = true;
164
+ requests.delete(message.id);
165
+ parentPort.postMessage({ type: "reply", id: message.id, error: "runtime-timeout: read cancelled" });
166
+ }
167
+ return;
168
+ }
99
169
  if (message.type === "terminal-logs-consumed") { if (terminalLogsPending) model.acknowledgeTerminalLogs(terminalLogsPending); terminalLogsPending = undefined; sendTerminalLogs(); return; }
100
170
  if (message.type === "revision-consumed") {
101
171
  revisionPending = false;
102
172
  if (revisionDirty) { revisionDirty = false; revision(); }
103
173
  return;
104
174
  }
105
- if (message.type === "detach") { sessions.get(message.connection)?.queries.close(); sessions.delete(message.connection); return; }
175
+ if (message.type === "detach") {
176
+ for (const request of requests.values()) if (request.connection === message.connection) request.cancelled = true;
177
+ sessions.get(message.connection)?.queries.close(); sessions.delete(message.connection); return;
178
+ }
106
179
  if (message.type === "event-consumed") {
107
180
  const state = sessions.get(message.connection);
108
181
  if (state?.awaiting && state.serial === message.serial) { state.awaiting = false; state.flush(); }
109
182
  return;
110
183
  }
111
184
  if (message.type !== "query") return;
185
+ const request = { connection: message.connection, cancelled: false };
186
+ requests.set(message.id, request);
187
+ const release = budget.enter("query");
112
188
  try {
189
+ if (!release) throw new Error("runtime-overloaded: shared source query budget exhausted");
113
190
  const command = message.command;
114
191
  if (["runtime_get_liveness", "runtime_get_upgrade_obligations"].includes(command.type)) {
115
192
  await model.reconcile();
116
- const observation = model.observation(command.type === "runtime_get_upgrade_obligations" ? model.upgradeObligations() : model.livenessReasons());
117
- parentPort.postMessage({ type: "reply", id: message.id, json: JSON.stringify(observation.reasons), metrics: metrics(), observation });
193
+ if (request.cancelled) return;
194
+ observeExecution("request", () => {
195
+ const observation = model.observation(command.type === "runtime_get_upgrade_obligations" ? model.upgradeObligations() : model.livenessReasons());
196
+ parentPort.postMessage({ type: "reply", id: message.id, json: JSON.stringify(observation.reasons), metrics: metrics(), observation });
197
+ });
118
198
  return;
119
199
  }
120
200
  if (!["runtime_get_snapshot", "runtime_subscribe", "runtime_unsubscribe"].includes(command.type)) throw new Error("Unsupported read operation");
121
201
  const indexed = command.type !== "runtime_get_snapshot" || !command.scope?.id || await model.ensureId(command.scope.id);
122
- const state = session(message.connection);
123
- state.generation = message.generation; state.pending = undefined;
124
- let value = state.queries.handle(command);
125
- if (!indexed && !value.rows.length) value = { ...value, status: "rebuilding", reason: "The requested run is being indexed; retry after reconciliation." };
126
- parentPort.postMessage({ type: "reply", id: message.id, json: encoded.get(value) ?? JSON.stringify(value), metrics: metrics() });
202
+ if (request.cancelled) return;
203
+ observeExecution("request", () => {
204
+ const state = session(message.connection);
205
+ state.generation = message.generation; state.pending = undefined;
206
+ let value = state.queries.handle(command);
207
+ if (!indexed && !value.rows.length) value = { ...value, status: "rebuilding", reason: "The requested run is being indexed; retry after reconciliation." };
208
+ parentPort.postMessage({ type: "reply", id: message.id, json: encoded.get(value) ?? JSON.stringify(value), metrics: metrics() });
209
+ });
127
210
  } catch (error) {
211
+ if (request.cancelled) return;
128
212
  parentPort.postMessage({ type: "reply", id: message.id, error: String(error).slice(0, 512), metrics: metrics() });
129
- }
213
+ } finally { release?.(); requests.delete(message.id); }
130
214
  });
215
+ rpcInstalled = true;
131
216
  void model.reconcile();