pi-better-server 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (278) hide show
  1. package/package.json +4 -1
  2. package/scripts/copy-pi-test-providers.mjs +10 -0
  3. package/scripts/event-publication/README.md +26 -0
  4. package/scripts/event-publication/commit.mjs +21 -0
  5. package/scripts/event-publication/measure.mjs +37 -5
  6. package/scripts/event-publication/writer.mjs +3 -8
  7. package/scripts/measure-full-runtime/probe.mjs +4 -2
  8. package/scripts/measure-full-runtime/recovery-trace-loader.mjs +51 -0
  9. package/scripts/measure-full-runtime/recovery-trace.mjs +16 -0
  10. package/scripts/measure-shared-reads.mjs +2 -1
  11. package/scripts/private-runtime/package-lock.json +18 -0
  12. package/scripts/private-runtime/package.json +4 -1
  13. package/scripts/source-provenance.mjs +2 -2
  14. package/scripts/test-on-pi.sh +2 -9
  15. package/src/handshake.ts +1 -1
  16. package/src/hosted-session.ts +32 -4
  17. package/src/maintenance.ts +35 -7
  18. package/src/registry.ts +28 -4
  19. package/src/runtime/attempt-invalidation.ts +54 -0
  20. package/src/runtime/background-history.ts +151 -45
  21. package/src/runtime/background-policy.ts +9 -4
  22. package/src/runtime/background-tools.ts +131 -23
  23. package/src/runtime/background.ts +351 -68
  24. package/src/runtime/cancellation.ts +28 -7
  25. package/src/runtime/catalog-sources.ts +199 -0
  26. package/src/runtime/catalog.ts +53 -21
  27. package/src/runtime/client.ts +22 -2
  28. package/src/runtime/domain/assignment-inbox.mjs +119 -0
  29. package/src/runtime/domain/assignment-observation.d.mts +1 -1
  30. package/src/runtime/domain/assignment-observation.mjs +43 -35
  31. package/src/runtime/domain/background/process-identity.mjs +20 -2
  32. package/src/runtime/domain/background/process.mjs +3 -3
  33. package/src/runtime/domain/background/registry.mjs +61 -3
  34. package/src/runtime/domain/background/types.mjs +1 -0
  35. package/src/runtime/domain/background-service/adapter-contract.domain.mjs +1 -1
  36. package/src/runtime/domain/background-service/adapter-contract.ts +1 -1
  37. package/src/runtime/domain/background-service/goal-provider.domain.mjs +35 -16
  38. package/src/runtime/domain/background-service/goal-provider.ts +31 -16
  39. package/src/runtime/domain/background-service/index.domain.mjs +6 -9
  40. package/src/runtime/domain/background-service/index.ts +6 -9
  41. package/src/runtime/domain/background-service/managed-authority.domain.mjs +6 -3
  42. package/src/runtime/domain/background-service/managed-authority.ts +5 -3
  43. package/src/runtime/domain/background-service/managed-client.domain.mjs +21 -7
  44. package/src/runtime/domain/background-service/managed-client.ts +20 -7
  45. package/src/runtime/domain/background-service/managed-frontend.domain.mjs +75 -17
  46. package/src/runtime/domain/background-service/managed-frontend.ts +62 -17
  47. package/src/runtime/domain/background-service/navigator-provider.domain.mjs +16 -5
  48. package/src/runtime/domain/background-service/navigator-provider.ts +15 -5
  49. package/src/runtime/domain/background-service/observed-wait-client.domain.mjs +6 -0
  50. package/src/runtime/domain/background-service/observed-wait-client.ts +10 -0
  51. package/src/runtime/domain/background-service/observed-waits.domain.mjs +170 -27
  52. package/src/runtime/domain/background-service/observed-waits.ts +154 -30
  53. package/src/runtime/domain/background-service/process-identity.domain.mjs +20 -2
  54. package/src/runtime/domain/background-service/process-identity.ts +18 -2
  55. package/src/runtime/domain/background-service/process.domain.mjs +3 -3
  56. package/src/runtime/domain/background-service/process.ts +3 -3
  57. package/src/runtime/domain/background-service/registry.domain.mjs +61 -3
  58. package/src/runtime/domain/background-service/registry.ts +53 -5
  59. package/src/runtime/domain/background-service/runtime.domain.mjs +32 -16
  60. package/src/runtime/domain/background-service/runtime.ts +19 -9
  61. package/src/runtime/domain/background-service/sandbox.domain.mjs +14 -15
  62. package/src/runtime/domain/background-service/sandbox.ts +14 -11
  63. package/src/runtime/domain/background-service/shared-callback-batcher.domain.mjs +8 -1
  64. package/src/runtime/domain/background-service/shared-callback-batcher.ts +11 -2
  65. package/src/runtime/domain/background-service/shared-navigator-panels.domain.mjs +24 -2
  66. package/src/runtime/domain/background-service/shared-navigator-panels.ts +26 -4
  67. package/src/runtime/domain/background-service/shared-navigator.domain.mjs +218 -13
  68. package/src/runtime/domain/background-service/shared-navigator.ts +197 -14
  69. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-inbox.mjs +144 -0
  70. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-observation.mjs +53 -41
  71. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
  72. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  73. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
  74. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  75. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
  76. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.ts +14 -3
  77. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
  78. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.ts +5 -3
  79. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.domain.mjs +44 -4
  80. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.ts +50 -2
  81. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
  82. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.ts +12 -0
  83. package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.domain.mjs +2 -0
  84. package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.ts +2 -0
  85. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +42 -21
  86. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +40 -24
  87. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +21 -3
  88. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +34 -8
  89. package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
  90. package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.ts +24 -1
  91. package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.domain.mjs +1 -1
  92. package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.ts +5 -1
  93. package/src/runtime/domain/background-service/shared-sandbox-core.ts +1 -1
  94. package/src/runtime/domain/background-service/shared-work-client.mjs +174 -7
  95. package/src/runtime/domain/background-service/supervisor/generated/process-identity.mjs +20 -2
  96. package/src/runtime/domain/background-service/supervisor/generated/process.mjs +3 -3
  97. package/src/runtime/domain/background-service/task-diagnostics.domain.mjs +1 -1
  98. package/src/runtime/domain/background-service/task-diagnostics.ts +1 -1
  99. package/src/runtime/domain/background-service/tools.domain.mjs +31 -24
  100. package/src/runtime/domain/background-service/tools.ts +41 -38
  101. package/src/runtime/domain/background-service/types.domain.mjs +1 -0
  102. package/src/runtime/domain/background-service/types.ts +3 -1
  103. package/src/runtime/domain/background-service/work-observation.domain.mjs +46 -20
  104. package/src/runtime/domain/background-service/work-observation.ts +46 -19
  105. package/src/runtime/domain/catalog/catalog-store.d.mts +9 -1
  106. package/src/runtime/domain/catalog/catalog-store.mjs +20 -22
  107. package/src/runtime/domain/coordinator/src/assignment-changes.mjs +75 -0
  108. package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +2 -0
  109. package/src/runtime/domain/coordinator/src/background-requests.mjs +11 -2
  110. package/src/runtime/domain/coordinator/src/discovery.mjs +4 -2
  111. package/src/runtime/domain/coordinator/src/operations.mjs +44 -4
  112. package/src/runtime/domain/coordinator/src/result-supervision.mjs +12 -0
  113. package/src/runtime/domain/coordinator/src/rows.mjs +2 -0
  114. package/src/runtime/domain/coordinator/src/schema.mjs +42 -21
  115. package/src/runtime/domain/coordinator/src/store.mjs +21 -3
  116. package/src/runtime/domain/coordinator/src/subagent-launch.mjs +23 -1
  117. package/src/runtime/domain/coordinator/src/types.mjs +1 -1
  118. package/src/runtime/domain/health-observation.d.mts +3 -1
  119. package/src/runtime/domain/health-observation.mjs +189 -190
  120. package/src/runtime/domain/log-cursor.d.mts +2 -0
  121. package/src/runtime/domain/log-cursor.mjs +85 -16
  122. package/src/runtime/domain/parse.d.mts +4 -1
  123. package/src/runtime/domain/parse.mjs +50 -5
  124. package/src/runtime/domain/sandbox-policy/README.md +61 -63
  125. package/src/runtime/domain/sandbox-policy/commands.domain.mjs +11 -8
  126. package/src/runtime/domain/sandbox-policy/commands.ts +12 -7
  127. package/src/runtime/domain/sandbox-policy/index.domain.mjs +53 -9
  128. package/src/runtime/domain/sandbox-policy/index.ts +52 -9
  129. package/src/runtime/domain/sandbox-policy/package.json +1 -1
  130. package/src/runtime/domain/sandbox-policy/permission-settings.domain.mjs +5 -2
  131. package/src/runtime/domain/sandbox-policy/permission-settings.ts +9 -2
  132. package/src/runtime/domain/sandbox-policy/permissions-page.domain.mjs +56 -137
  133. package/src/runtime/domain/sandbox-policy/permissions-page.ts +52 -130
  134. package/src/runtime/domain/sandbox-policy/permissions.domain.mjs +1 -6
  135. package/src/runtime/domain/sandbox-policy/permissions.ts +1 -6
  136. package/src/runtime/domain/sandbox-policy/shared-sandbox-core.ts +1 -1
  137. package/src/runtime/domain/sandbox-policy/shared-task-exec.domain.mjs +14 -1
  138. package/src/runtime/domain/sandbox-policy/shared-task-exec.ts +12 -1
  139. package/src/runtime/domain/sandbox-policy/shared-task-process-identity.domain.mjs +140 -0
  140. package/src/runtime/domain/sandbox-policy/shared-task-process-identity.ts +126 -0
  141. package/src/runtime/domain/sandbox-policy/shared-task-process-list.domain.mjs +3 -2
  142. package/src/runtime/domain/sandbox-policy/shared-task-process-list.ts +8 -2
  143. package/src/runtime/domain/sandbox-policy/shared-task-sandbox.domain.mjs +4 -3
  144. package/src/runtime/domain/sandbox-policy/shared-task-sandbox.ts +5 -3
  145. package/src/runtime/domain/sandbox-policy/shared-task-tools.domain.mjs +8 -5
  146. package/src/runtime/domain/sandbox-policy/shared-task-tools.ts +8 -5
  147. package/src/runtime/domain/subagents/README.md +1 -1
  148. package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +12 -6
  149. package/src/runtime/domain/subagents/assignment-outcomes.ts +11 -5
  150. package/src/runtime/domain/subagents/assignment-report.domain.mjs +87 -24
  151. package/src/runtime/domain/subagents/assignment-report.ts +83 -19
  152. package/src/runtime/domain/subagents/catalog-host-admission.domain.mjs +21 -3
  153. package/src/runtime/domain/subagents/catalog-host-admission.ts +19 -3
  154. package/src/runtime/domain/subagents/catalog-preferences.ts +1 -1
  155. package/src/runtime/domain/subagents/catalog-resolver.domain.mjs +35 -1
  156. package/src/runtime/domain/subagents/catalog-resolver.ts +35 -1
  157. package/src/runtime/domain/subagents/catalog-store.domain.mjs +20 -22
  158. package/src/runtime/domain/subagents/catalog-store.ts +27 -20
  159. package/src/runtime/domain/subagents/child-apply-patch.domain.mjs +13 -0
  160. package/src/runtime/domain/subagents/child-apply-patch.ts +13 -0
  161. package/src/runtime/domain/subagents/child-dependencies.mjs +27 -15
  162. package/src/runtime/domain/subagents/child-operations.domain.mjs +80 -2
  163. package/src/runtime/domain/subagents/child-operations.ts +80 -1
  164. package/src/runtime/domain/subagents/child-preflight.mjs +9 -2
  165. package/src/runtime/domain/subagents/child-process-list.domain.mjs +7 -0
  166. package/src/runtime/domain/subagents/child-process-list.ts +8 -0
  167. package/src/runtime/domain/subagents/config.domain.mjs +49 -2
  168. package/src/runtime/domain/subagents/config.ts +46 -2
  169. package/src/runtime/domain/subagents/continuation-authority.domain.mjs +5 -1
  170. package/src/runtime/domain/subagents/continuation-authority.ts +3 -1
  171. package/src/runtime/domain/subagents/continuation-runtime.domain.mjs +89 -0
  172. package/src/runtime/domain/subagents/continuation-runtime.ts +88 -0
  173. package/src/runtime/domain/subagents/extensions.mjs +11 -13
  174. package/src/runtime/domain/subagents/finalization.domain.mjs +12 -0
  175. package/src/runtime/domain/subagents/finalization.ts +15 -0
  176. package/src/runtime/domain/subagents/goal-provider.domain.mjs +44 -2
  177. package/src/runtime/domain/subagents/goal-provider.ts +44 -2
  178. package/src/runtime/domain/subagents/health-observation.domain.mjs +189 -190
  179. package/src/runtime/domain/subagents/health-observation.ts +43 -48
  180. package/src/runtime/domain/subagents/index.domain.mjs +296 -123
  181. package/src/runtime/domain/subagents/index.ts +257 -98
  182. package/src/runtime/domain/subagents/launch-context.domain.mjs +24 -0
  183. package/src/runtime/domain/subagents/launch-context.ts +23 -0
  184. package/src/runtime/domain/subagents/launch-digest.mjs +6 -0
  185. package/src/runtime/domain/subagents/log-cursor.domain.mjs +85 -16
  186. package/src/runtime/domain/subagents/log-cursor.ts +91 -15
  187. package/src/runtime/domain/subagents/managed-launch-bootstrap.mjs +2 -2
  188. package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +6 -3
  189. package/src/runtime/domain/subagents/managed-launch-client.ts +6 -3
  190. package/src/runtime/domain/subagents/managed-launch-host.domain.mjs +222 -14
  191. package/src/runtime/domain/subagents/managed-launch-host.ts +168 -15
  192. package/src/runtime/domain/subagents/managed-launch-journal.mjs +1 -5
  193. package/src/runtime/domain/subagents/managed-launch-port.ts +4 -0
  194. package/src/runtime/domain/subagents/operation-bridge-types.domain.mjs +27 -2
  195. package/src/runtime/domain/subagents/operation-bridge-types.ts +27 -2
  196. package/src/runtime/domain/subagents/owned-exit.domain.mjs +12 -0
  197. package/src/runtime/domain/subagents/owned-exit.ts +12 -0
  198. package/src/runtime/domain/subagents/package.json +1 -1
  199. package/src/runtime/domain/subagents/parse.domain.mjs +50 -5
  200. package/src/runtime/domain/subagents/parse.ts +48 -6
  201. package/src/runtime/domain/subagents/permission-policy.domain.mjs +32 -8
  202. package/src/runtime/domain/subagents/permission-policy.ts +41 -8
  203. package/src/runtime/domain/subagents/process-identity.mjs +33 -0
  204. package/src/runtime/domain/subagents/registry.domain.mjs +47 -33
  205. package/src/runtime/domain/subagents/registry.ts +54 -33
  206. package/src/runtime/domain/subagents/shared-callback-batcher.domain.mjs +8 -1
  207. package/src/runtime/domain/subagents/shared-callback-batcher.ts +11 -2
  208. package/src/runtime/domain/subagents/shared-catalog.domain.mjs +6 -23
  209. package/src/runtime/domain/subagents/shared-catalog.ts +6 -14
  210. package/src/runtime/domain/subagents/shared-navigator-panels.domain.mjs +24 -2
  211. package/src/runtime/domain/subagents/shared-navigator-panels.ts +26 -4
  212. package/src/runtime/domain/subagents/shared-navigator.domain.mjs +218 -13
  213. package/src/runtime/domain/subagents/shared-navigator.ts +197 -14
  214. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-inbox.mjs +144 -0
  215. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-observation.mjs +53 -41
  216. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
  217. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  218. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
  219. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  220. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
  221. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.ts +14 -3
  222. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
  223. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.ts +5 -3
  224. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.domain.mjs +44 -4
  225. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.ts +50 -2
  226. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
  227. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.ts +12 -0
  228. package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.domain.mjs +2 -0
  229. package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.ts +2 -0
  230. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +42 -21
  231. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +40 -24
  232. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +21 -3
  233. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +34 -8
  234. package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
  235. package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.ts +24 -1
  236. package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.domain.mjs +1 -1
  237. package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.ts +5 -1
  238. package/src/runtime/domain/subagents/shared-sandbox-core.ts +1 -1
  239. package/src/runtime/domain/subagents/shared-task-exec.domain.mjs +14 -1
  240. package/src/runtime/domain/subagents/shared-task-exec.ts +12 -1
  241. package/src/runtime/domain/subagents/shared-task-process-identity.domain.mjs +140 -0
  242. package/src/runtime/domain/subagents/shared-task-process-identity.ts +126 -0
  243. package/src/runtime/domain/subagents/shared-task-process-list.domain.mjs +3 -2
  244. package/src/runtime/domain/subagents/shared-task-process-list.ts +8 -2
  245. package/src/runtime/domain/subagents/shared-task-sandbox.domain.mjs +4 -3
  246. package/src/runtime/domain/subagents/shared-task-sandbox.ts +5 -3
  247. package/src/runtime/domain/subagents/shared-task-tools.domain.mjs +8 -5
  248. package/src/runtime/domain/subagents/shared-task-tools.ts +8 -5
  249. package/src/runtime/domain/subagents/shared-work-client.mjs +174 -7
  250. package/src/runtime/domain/subagents/subagent-tools.domain.mjs +22 -38
  251. package/src/runtime/domain/subagents/subagent-tools.ts +28 -34
  252. package/src/runtime/domain/subagents/task-policy.domain.mjs +1 -1
  253. package/src/runtime/domain/subagents/task-policy.ts +3 -1
  254. package/src/runtime/domain/subagents/timing.domain.mjs +10 -1
  255. package/src/runtime/domain/subagents/timing.ts +10 -1
  256. package/src/runtime/domain/subagents/work-observation.domain.mjs +77 -16
  257. package/src/runtime/domain/subagents/work-observation.ts +71 -16
  258. package/src/runtime/domain/subagents/worker-operations-host.domain.mjs +9 -4
  259. package/src/runtime/domain/subagents/worker-operations-host.ts +12 -4
  260. package/src/runtime/domain/subagents/worker-waits.domain.mjs +89 -35
  261. package/src/runtime/domain/subagents/worker-waits.ts +93 -34
  262. package/src/runtime/health-config.ts +27 -11
  263. package/src/runtime/log-checkpoints.ts +117 -0
  264. package/src/runtime/mutation-store.ts +5 -4
  265. package/src/runtime/queries.ts +25 -2
  266. package/src/runtime/query-executor.ts +149 -28
  267. package/src/runtime/query-worker.mjs +106 -21
  268. package/src/runtime/read-model.ts +846 -120
  269. package/src/runtime/read-watchdog-probe.ts +4 -0
  270. package/src/runtime/result-supervision.ts +188 -16
  271. package/src/runtime/source-watch.ts +175 -0
  272. package/src/runtime/subagent-launch.ts +11 -4
  273. package/src/runtime/work-budget.ts +130 -0
  274. package/src/runtime/work-client.d.mts +8 -0
  275. package/src/runtime/work-client.mjs +150 -7
  276. package/src/server.ts +104 -23
  277. package/src/session-activity.ts +26 -4
  278. package/src/version.ts +1 -1
@@ -1,5 +1,5 @@
1
1
  // Generated canonical coordinator. Do not edit directly.
2
- import { randomBytes } from "node:crypto";
2
+ import { createHash, randomBytes } from "node:crypto";
3
3
  /** Fixed launch journal on the coordinator's existing connection and transaction. */
4
4
  export class SubagentLaunchJournal {
5
5
  context;
@@ -40,6 +40,25 @@ export class SubagentLaunchJournal {
40
40
  pendingIntents() {
41
41
  return this.db.prepare("SELECT * FROM subagent_launch_intents WHERE state='accepted'").all();
42
42
  }
43
+ progressKey(owner, key) { return `launch-progress:${createHash('sha256').update(JSON.stringify([owner, key])).digest('hex')}`; }
44
+ progress(owner, key) {
45
+ const row = this.db.prepare('SELECT value FROM coordinator_state WHERE key=?').get(this.progressKey(owner, key));
46
+ return row ? JSON.parse(String(row.value)) : undefined;
47
+ }
48
+ noteProgress(owner, key) {
49
+ const previous = this.progress(owner, key), now = Date.now();
50
+ this.db.prepare('INSERT OR REPLACE INTO coordinator_state (key,value) VALUES (?,?)').run(this.progressKey(owner, key), JSON.stringify({ acceptedAt: previous?.acceptedAt ?? now, lastProgressAt: now }));
51
+ }
52
+ lifecycleReasons(owner, key) {
53
+ const exact = owner !== undefined && key !== undefined ? this.read(owner, key) : undefined;
54
+ const intents = owner !== undefined ? exact?.state === 'accepted' ? [exact] : [] : this.pendingIntents();
55
+ return intents.map(intent => ({ kind: 'task', id: this.progressKey(intent.owner, intent.request_key),
56
+ owner: intent.owner, management: { epoch: intent.epoch }, acceptedAt: this.progress(intent.owner, intent.request_key)?.acceptedAt ?? null,
57
+ lastProgressAt: this.progress(intent.owner, intent.request_key)?.lastProgressAt ?? null, executionDeadline: null, nextDeadline: null,
58
+ attempts: JSON.parse(intent.attempts).map(attempt => ({ id: attempt.id, sessionId: attempt.sessionId,
59
+ state: attempt.state, writer: { pid: attempt.writerPid ?? attempt.pid, start: attempt.writerStartTime ?? attempt.pidStartTime } })),
60
+ recovery: 'drain-accepted-launch-until-journal-return-or-authoritative-handoff' }));
61
+ }
43
62
  finishRecovery(owner, key, epoch, result) {
44
63
  this.transaction(() => {
45
64
  this.current(epoch);
@@ -57,6 +76,7 @@ export class SubagentLaunchJournal {
57
76
  return { prior: true, ...prior };
58
77
  }
59
78
  this.db.prepare("INSERT INTO subagent_launch_intents VALUES (?, ?, ?, ?, 'accepted', '[]', NULL)").run(owner, key, digest, epoch);
79
+ this.noteProgress(owner, key);
60
80
  return this.read(owner, key);
61
81
  });
62
82
  }
@@ -72,6 +92,7 @@ export class SubagentLaunchJournal {
72
92
  const attempt = { ...input, token: randomBytes(32).toString("hex"), state: "prepared" };
73
93
  attempts.push(attempt);
74
94
  this.db.prepare("UPDATE subagent_launch_intents SET attempts=? WHERE owner=? AND request_key=?").run(JSON.stringify(attempts), owner, key);
95
+ this.noteProgress(owner, key);
75
96
  return attempt;
76
97
  });
77
98
  }
@@ -86,6 +107,7 @@ export class SubagentLaunchJournal {
86
107
  throw new Error("Launch writer does not match spawned process");
87
108
  Object.assign(attempt, { state: "spawned", pid, pidStartTime });
88
109
  this.db.prepare("UPDATE subagent_launch_intents SET attempts=? WHERE owner=? AND request_key=?").run(JSON.stringify(attempts), owner, key);
110
+ this.noteProgress(owner, key);
89
111
  });
90
112
  }
91
113
  finish(owner, key, epoch, result) {
@@ -18,7 +18,7 @@
18
18
  * - a resume attempt id and launch token are persisted before the attempt is
19
19
  * spawned, so a crash is reconciled instead of relaunched.
20
20
  */
21
- /** Schema version this build writes and accepts. Any other version is refused. */
21
+ /** Schema version this build writes after creating or migrating a store. */
22
22
  export const SCHEMA_VERSION = 4;
23
23
  /** Phases that no longer accept automatic continuation. */
24
24
  export const TERMINAL_WAIT_PHASES = ["consumed", "cancelled"];
@@ -1,3 +1,5 @@
1
1
  export function resolveHealthThresholds(config?: any): any;
2
+ export function encodeHealthLogState(state: any): any;
3
+ export function decodeHealthLogState(state: any): any;
2
4
  export function healthThresholdsForConfig(config: any): any;
3
- export function extractChildEventFactsFromLog(id: string, options?: { logPath?: string }): { facts: any; rawLog: any };
5
+ export function extractChildEventFactsFromLog(id: string, options?: { logPath?: string; states?: Map<any, any> }): { facts: any; rawLog: any };
@@ -11,7 +11,7 @@
11
11
  * and must not collapse into stale. Raw log mtime/size is diagnostic only.
12
12
  */
13
13
  import { statSync } from "node:fs";
14
- import { DEFAULT_MAX_READ_BYTES, readAppendedLines } from "./log-cursor.mjs";
14
+ import { DEFAULT_MAX_READ_BYTES, readAppendedLines, parseLogEvent, logReadMetrics } from "./log-cursor.mjs";
15
15
  import { logPathFor } from "./log-paths.mjs";
16
16
  import { observeStall } from "./shared-stall-detector.mjs";
17
17
  /** Defaults tuned for coordinator workloads; override per call or via config. */
@@ -142,188 +142,206 @@ export function mayAffectChildEventFacts(line) {
142
142
  * that already parsed NDJSON). Skips non-objects; ignores raw non-JSON noise.
143
143
  */
144
144
  export function extractChildEventFacts(events) {
145
- const openTools = new Map();
146
- let anonymous = 0;
147
- const meaningful = {};
148
- let lastToolAt;
149
- let compacting = false;
150
- let compactionStartedAt;
151
- let lastCompaction;
152
- let sawAgentSettled = false;
153
- let retry;
154
- const recovery = {
145
+ return createChildEventFactFold()(events);
146
+ }
147
+ function createChildEventFactFold(saved) {
148
+ const openTools = new Map(saved?.openTools);
149
+ let anonymous = saved?.anonymous ?? 0;
150
+ const meaningful = saved?.meaningful ?? {};
151
+ let lastToolAt = saved?.lastToolAt;
152
+ let compacting = saved?.compacting ?? false;
153
+ let compactionStartedAt = saved?.compactionStartedAt;
154
+ let lastCompaction = saved?.lastCompaction;
155
+ let sawAgentSettled = saved?.sawAgentSettled ?? false;
156
+ let retry = saved?.retry;
157
+ const recovery = saved?.recovery ?? {
155
158
  recoveredAfterError: false,
156
159
  retrying: false,
157
160
  willRetry: undefined,
158
161
  lastError: undefined,
159
162
  errorHistory: [],
160
163
  };
161
- for (const raw of events) {
162
- if (!raw || typeof raw !== "object")
163
- continue;
164
- const e = raw;
165
- const type = typeof e.type === "string" ? e.type : undefined;
166
- if (!type)
167
- continue;
168
- // Only parsed-event write provenance counts as wall-clock activity.
169
- const at = eventTime(e);
170
- if (type === "tool_execution_start") {
171
- const toolName = typeof e.toolName === "string" ? e.toolName : "unknown";
172
- const toolCallId = typeof e.toolCallId === "string" ? e.toolCallId : undefined;
173
- const key = toolCallId ?? `anonymous:${anonymous++}`;
174
- openTools.set(key, { toolCallId, toolName, startedAt: at });
175
- lastToolAt = at ?? lastToolAt;
176
- bumpMeaningful(meaningful, at);
177
- continue;
178
- }
179
- if (type === "tool_execution_update") {
180
- lastToolAt = at ?? lastToolAt;
181
- bumpMeaningful(meaningful, at);
182
- continue;
183
- }
184
- if (type === "tool_execution_end") {
185
- const toolCallId = typeof e.toolCallId === "string" ? e.toolCallId : undefined;
186
- if (toolCallId) {
187
- openTools.delete(toolCallId);
164
+ const fold = (events) => {
165
+ for (const raw of events) {
166
+ logReadMetrics.healthFolded++;
167
+ if (!raw || typeof raw !== "object")
168
+ continue;
169
+ const e = raw;
170
+ const type = typeof e.type === "string" ? e.type : undefined;
171
+ if (!type)
172
+ continue;
173
+ // Only parsed-event write provenance counts as wall-clock activity.
174
+ const at = eventTime(e);
175
+ if (type === "tool_execution_start") {
176
+ const toolName = typeof e.toolName === "string" ? e.toolName : "unknown";
177
+ const toolCallId = typeof e.toolCallId === "string" ? e.toolCallId : undefined;
178
+ const key = toolCallId ?? `anonymous:${anonymous++}`;
179
+ openTools.set(key, { toolCallId, toolName, startedAt: at });
180
+ lastToolAt = at ?? lastToolAt;
181
+ bumpMeaningful(meaningful, at);
182
+ continue;
188
183
  }
189
- else if (typeof e.toolName === "string") {
190
- const match = [...openTools].find(([, t]) => t.toolName === e.toolName);
191
- if (match)
192
- openTools.delete(match[0]);
184
+ if (type === "tool_execution_update") {
185
+ lastToolAt = at ?? lastToolAt;
186
+ bumpMeaningful(meaningful, at);
187
+ continue;
193
188
  }
194
- lastToolAt = at ?? lastToolAt;
195
- bumpMeaningful(meaningful, at);
196
- // Successful tool completion supersedes prior retry intent (AC9).
197
- if (e.isError !== true)
198
- markRecovered(recovery);
199
- continue;
200
- }
201
- if (type === "compaction_start") {
202
- compacting = true;
203
- compactionStartedAt = at;
204
- bumpMeaningful(meaningful, at);
205
- continue;
206
- }
207
- if (type === "compaction_end") {
208
- compacting = false;
209
- lastCompaction = {
210
- reason: typeof e.reason === "string" ? e.reason : undefined,
211
- aborted: typeof e.aborted === "boolean" ? e.aborted : undefined,
212
- willRetry: typeof e.willRetry === "boolean" ? e.willRetry : undefined,
213
- errorMessage: typeof e.errorMessage === "string" ? e.errorMessage : undefined,
214
- at,
215
- };
216
- compactionStartedAt = undefined;
217
- bumpMeaningful(meaningful, at);
218
- continue;
219
- }
220
- if (type === "auto_retry_start") {
221
- recovery.retrying = true;
222
- recovery.recoveredAfterError = false;
223
- recovery.willRetry = true;
224
- retry = {
225
- attempt: typeof e.attempt === "number" ? e.attempt : undefined,
226
- maxAttempts: typeof e.maxAttempts === "number" ? e.maxAttempts : undefined,
227
- startedAt: at,
228
- };
229
- const msg = typeof e.errorMessage === "string" ? e.errorMessage : "model retry";
230
- recovery.lastError = { message: msg, at };
231
- pushError(recovery.errorHistory, recovery.lastError);
232
- bumpMeaningful(meaningful, at);
233
- continue;
234
- }
235
- if (type === "auto_retry_end") {
236
- recovery.retrying = false;
237
- const success = e.success === true;
238
- if (success) {
239
- markRecovered(recovery);
189
+ if (type === "tool_execution_end") {
190
+ const toolCallId = typeof e.toolCallId === "string" ? e.toolCallId : undefined;
191
+ if (toolCallId) {
192
+ openTools.delete(toolCallId);
193
+ }
194
+ else if (typeof e.toolName === "string") {
195
+ const match = [...openTools].find(([, t]) => t.toolName === e.toolName);
196
+ if (match)
197
+ openTools.delete(match[0]);
198
+ }
199
+ lastToolAt = at ?? lastToolAt;
200
+ bumpMeaningful(meaningful, at);
201
+ // Successful tool completion supersedes prior retry intent (AC9).
202
+ if (e.isError !== true)
203
+ markRecovered(recovery);
204
+ continue;
205
+ }
206
+ if (type === "compaction_start") {
207
+ compacting = true;
208
+ compactionStartedAt = at;
209
+ bumpMeaningful(meaningful, at);
210
+ continue;
211
+ }
212
+ if (type === "compaction_end") {
213
+ compacting = false;
214
+ lastCompaction = {
215
+ reason: typeof e.reason === "string" ? e.reason : undefined,
216
+ aborted: typeof e.aborted === "boolean" ? e.aborted : undefined,
217
+ willRetry: typeof e.willRetry === "boolean" ? e.willRetry : undefined,
218
+ errorMessage: typeof e.errorMessage === "string" ? e.errorMessage : undefined,
219
+ at,
220
+ };
221
+ compactionStartedAt = undefined;
222
+ bumpMeaningful(meaningful, at);
223
+ continue;
240
224
  }
241
- else {
242
- const msg = typeof e.finalError === "string"
243
- ? e.finalError
244
- : (recovery.lastError?.message ?? "model retry exhausted");
225
+ if (type === "auto_retry_start") {
226
+ recovery.retrying = true;
227
+ recovery.recoveredAfterError = false;
228
+ recovery.willRetry = true;
229
+ retry = {
230
+ attempt: typeof e.attempt === "number" ? e.attempt : undefined,
231
+ maxAttempts: typeof e.maxAttempts === "number" ? e.maxAttempts : undefined,
232
+ startedAt: at,
233
+ };
234
+ const msg = typeof e.errorMessage === "string" ? e.errorMessage : "model retry";
245
235
  recovery.lastError = { message: msg, at };
246
236
  pushError(recovery.errorHistory, recovery.lastError);
247
- recovery.recoveredAfterError = false;
237
+ bumpMeaningful(meaningful, at);
238
+ continue;
248
239
  }
249
- bumpMeaningful(meaningful, at);
250
- continue;
251
- }
252
- if (type === "message_end") {
253
- const msg = e.message;
254
- if (isAssistantMessage(msg)) {
255
- if (assistantIsError(msg)) {
256
- const message = typeof msg.errorMessage === "string"
257
- ? msg.errorMessage
258
- : "assistant stopReason=error";
259
- recovery.lastError = { message, at };
240
+ if (type === "auto_retry_end") {
241
+ recovery.retrying = false;
242
+ const success = e.success === true;
243
+ if (success) {
244
+ markRecovered(recovery);
245
+ }
246
+ else {
247
+ const msg = typeof e.finalError === "string"
248
+ ? e.finalError
249
+ : (recovery.lastError?.message ?? "model retry exhausted");
250
+ recovery.lastError = { message: msg, at };
260
251
  pushError(recovery.errorHistory, recovery.lastError);
261
252
  recovery.recoveredAfterError = false;
262
- // Model-error evidence is meaningful for timing, not healthy progress.
263
- bumpMeaningful(meaningful, at);
264
253
  }
265
- else {
254
+ bumpMeaningful(meaningful, at);
255
+ continue;
256
+ }
257
+ if (type === "message_end") {
258
+ const msg = e.message;
259
+ if (isAssistantMessage(msg)) {
260
+ if (assistantIsError(msg)) {
261
+ const message = typeof msg.errorMessage === "string"
262
+ ? msg.errorMessage
263
+ : "assistant stopReason=error";
264
+ recovery.lastError = { message, at };
265
+ pushError(recovery.errorHistory, recovery.lastError);
266
+ recovery.recoveredAfterError = false;
267
+ // Model-error evidence is meaningful for timing, not healthy progress.
268
+ bumpMeaningful(meaningful, at);
269
+ }
270
+ else {
271
+ bumpMeaningful(meaningful, at);
272
+ // Later successful assistant evidence clears retry/warning (AC9).
273
+ markRecovered(recovery);
274
+ }
275
+ }
276
+ // user message_end is not child progress
277
+ continue;
278
+ }
279
+ if (type === "turn_end") {
280
+ const msg = e.message;
281
+ if (isAssistantMessage(msg) && !assistantIsError(msg)) {
266
282
  bumpMeaningful(meaningful, at);
267
- // Later successful assistant evidence clears retry/warning (AC9).
268
283
  markRecovered(recovery);
269
284
  }
285
+ continue;
270
286
  }
271
- // user message_end is not child progress
272
- continue;
273
- }
274
- if (type === "turn_end") {
275
- const msg = e.message;
276
- if (isAssistantMessage(msg) && !assistantIsError(msg)) {
277
- bumpMeaningful(meaningful, at);
278
- markRecovered(recovery);
287
+ if (type === "agent_end") {
288
+ if (typeof e.willRetry === "boolean")
289
+ recovery.willRetry = e.willRetry;
290
+ if (recovery.willRetry === true) {
291
+ recovery.retrying = true;
292
+ recovery.recoveredAfterError = false;
293
+ bumpMeaningful(meaningful, at);
294
+ }
295
+ continue;
279
296
  }
280
- continue;
281
- }
282
- if (type === "agent_end") {
283
- if (typeof e.willRetry === "boolean")
284
- recovery.willRetry = e.willRetry;
285
- if (recovery.willRetry === true) {
286
- recovery.retrying = true;
287
- recovery.recoveredAfterError = false;
297
+ if (type === "agent_settled") {
298
+ sawAgentSettled = true;
299
+ // Settled ends the active retry phase; retain error history for detail.
300
+ recovery.retrying = false;
301
+ if (recovery.willRetry === true)
302
+ recovery.willRetry = false;
288
303
  bumpMeaningful(meaningful, at);
304
+ continue;
289
305
  }
290
- continue;
291
- }
292
- if (type === "agent_settled") {
293
- sawAgentSettled = true;
294
- // Settled ends the active retry phase; retain error history for detail.
295
- recovery.retrying = false;
296
- if (recovery.willRetry === true)
297
- recovery.willRetry = false;
298
- bumpMeaningful(meaningful, at);
299
- continue;
306
+ // message_update is noisy; intentionally NOT meaningful for stale detection.
300
307
  }
301
- // message_update is noisy; intentionally NOT meaningful for stale detection.
302
- }
303
- let modelState = "ok";
304
- if (recovery.retrying || recovery.willRetry === true)
305
- modelState = "retrying";
306
- else if (recovery.lastError && !recovery.recoveredAfterError)
307
- modelState = "error";
308
- else
309
- modelState = "ok";
310
- return {
311
- lastMeaningfulAt: meaningful.last,
312
- activeTools: [...openTools.values()],
313
- lastToolAt,
314
- compacting,
315
- compactionStartedAt,
316
- lastCompaction,
317
- model: {
318
- state: modelState,
319
- lastError: recovery.lastError,
320
- errorHistory: [...recovery.errorHistory],
321
- retry,
322
- },
323
- sawAgentSettled,
324
- willRetry: recovery.willRetry,
325
- longModelCallSupported: false,
308
+ let modelState = "ok";
309
+ if (recovery.retrying || recovery.willRetry === true)
310
+ modelState = "retrying";
311
+ else if (recovery.lastError && !recovery.recoveredAfterError)
312
+ modelState = "error";
313
+ else
314
+ modelState = "ok";
315
+ return {
316
+ lastMeaningfulAt: meaningful.last,
317
+ activeTools: [...openTools.values()],
318
+ lastToolAt,
319
+ compacting,
320
+ compactionStartedAt,
321
+ lastCompaction,
322
+ model: {
323
+ state: modelState,
324
+ lastError: recovery.lastError,
325
+ errorHistory: [...recovery.errorHistory],
326
+ retry,
327
+ },
328
+ sawAgentSettled,
329
+ willRetry: recovery.willRetry,
330
+ longModelCallSupported: false,
331
+ };
326
332
  };
333
+ return Object.assign(fold, { snapshot: () => ({ openTools: [...openTools], anonymous,
334
+ meaningful, lastToolAt, compacting, compactionStartedAt, lastCompaction,
335
+ sawAgentSettled, retry, recovery }) });
336
+ }
337
+ export function encodeHealthLogState(state) {
338
+ return { cursor: state.cursor, truncated: state.truncated, fold: state.fold.snapshot() };
339
+ }
340
+ export function decodeHealthLogState(saved) {
341
+ if (!saved?.fold?.recovery || !Array.isArray(saved.fold.openTools)
342
+ || !Number.isSafeInteger(saved.cursor?.offset) || saved.cursor.offset < 0)
343
+ throw new Error("Invalid health checkpoint");
344
+ return { cursor: saved.cursor, truncated: saved.truncated, fold: createChildEventFactFold(saved.fold) };
327
345
  }
328
346
  /** Parse the fact-relevant events out of raw NDJSON lines. */
329
347
  function parseFactEvents(lines) {
@@ -336,7 +354,7 @@ function parseFactEvents(lines) {
336
354
  if (!mayAffectChildEventFacts(s))
337
355
  continue;
338
356
  try {
339
- events.push(JSON.parse(s));
357
+ events.push(parseLogEvent(s));
340
358
  sizes.push(s.length);
341
359
  }
342
360
  catch {
@@ -347,14 +365,8 @@ function parseFactEvents(lines) {
347
365
  }
348
366
  // ---- incremental log reading ----------------------------------------------
349
367
  //
350
- // Logs are append-only and reach gigabytes, so facts are folded from an
351
- // accumulated event list that grows by the bytes appended since the last read
352
- // (see log-cursor.ts). Only the types the fold consumes are retained, which is
353
- // ~2% of a log's lines; `message_update` alone is 98% of the volume and cannot
354
- // move a fact. The retained list is capped, oldest-first, and a drop is
355
- // reported as a diagnostic rather than silently changing an observation.
356
- /** Memory budget for one run's retained fact-relevant events. */
357
- const MAX_RETAINED_EVENT_BYTES = 8 * 1024 * 1024; // 8 MiB
368
+ // Retain structural facts, not source events. Only newly completed lines enter
369
+ // the fold; a skipped byte window remains explicitly reported in rawLog.
358
370
  function maxHealthReadBytes() {
359
371
  const raw = process.env.PI_SUBAGENT_MAX_HEALTH_READ_BYTES;
360
372
  if (!raw)
@@ -389,15 +401,6 @@ function rememberState(id, state) {
389
401
  factLogStates.delete(oldest.value);
390
402
  }
391
403
  }
392
- function trimToBudget(state) {
393
- while (state.bytes > MAX_RETAINED_EVENT_BYTES && state.events.length > 1) {
394
- state.events.shift();
395
- state.bytes -= state.sizes.shift() ?? 0;
396
- state.dropped = true;
397
- }
398
- if (state.bytes < 0)
399
- state.bytes = 0;
400
- }
401
404
  /**
402
405
  * Read a run log for event facts + raw mtime/size diagnostics.
403
406
  * Raw log write time never promotes activity health by itself.
@@ -428,7 +431,8 @@ export function extractChildEventFactsFromLog(id, opts = {}) {
428
431
  return { facts: extractChildEventFacts(events), rawLog };
429
432
  }
430
433
  const key = opts.logPath ?? id;
431
- const previous = factLogStates.get(key);
434
+ const states = opts.states ?? factLogStates;
435
+ const previous = states.get(key);
432
436
  const read = readAppendedLines(path, previous?.cursor, maxHealthReadBytes());
433
437
  if (read.error !== undefined) {
434
438
  rawLog.error = rawLog.error ?? read.error;
@@ -436,24 +440,19 @@ export function extractChildEventFactsFromLog(id, opts = {}) {
436
440
  return { facts: emptyFacts(), rawLog };
437
441
  }
438
442
  const state = read.restarted || !previous
439
- ? { cursor: read.cursor, events: [], sizes: [], bytes: 0, truncated: false, dropped: false }
443
+ ? { cursor: read.cursor, fold: createChildEventFactFold(), truncated: false }
440
444
  : previous;
441
445
  state.cursor = read.cursor;
442
446
  state.truncated = state.truncated || read.truncated;
443
447
  const parsed = parseFactEvents(read.lines);
444
- if (parsed.events.length > 0) {
445
- state.events.push(...parsed.events);
446
- state.sizes.push(...parsed.sizes);
447
- for (const size of parsed.sizes)
448
- state.bytes += size;
449
- trimToBudget(state);
450
- }
451
- rememberState(key, state);
448
+ const facts = state.fold(parsed.events);
449
+ if (opts.states)
450
+ states.set(key, state);
451
+ else
452
+ rememberState(key, state);
452
453
  if (state.truncated)
453
454
  rawLog.windowTruncated = true;
454
- if (state.dropped)
455
- rawLog.eventsDropped = true;
456
- return { facts: extractChildEventFacts(state.events), rawLog };
455
+ return { facts, rawLog };
457
456
  }
458
457
  function processLiveness(status, supervised) {
459
458
  if (status === "orphaned")
@@ -0,0 +1,2 @@
1
+ export function withLogReadBatch<T>(observe: () => T): T;
2
+ export const logReadMetrics: { bytes: number; reads: number; parsedEvents: number; displayFolded: number; healthFolded: number };