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
@@ -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.domain.mjs";
14
+ import { DEFAULT_MAX_READ_BYTES, readAppendedLines, parseLogEvent, logReadMetrics } from "./log-cursor.domain.mjs";
15
15
  import { logPathFor } from "./registry.domain.mjs";
16
16
  import { loadConfig } from "./config.domain.mjs";
17
17
  import { observeStall } from "./shared-stall-detector.domain.mjs";
@@ -147,188 +147,206 @@ export function mayAffectChildEventFacts(line) {
147
147
  * that already parsed NDJSON). Skips non-objects; ignores raw non-JSON noise.
148
148
  */
149
149
  export function extractChildEventFacts(events) {
150
- const openTools = new Map();
151
- let anonymous = 0;
152
- const meaningful = {};
153
- let lastToolAt;
154
- let compacting = false;
155
- let compactionStartedAt;
156
- let lastCompaction;
157
- let sawAgentSettled = false;
158
- let retry;
159
- const recovery = {
150
+ return createChildEventFactFold()(events);
151
+ }
152
+ function createChildEventFactFold(saved) {
153
+ const openTools = new Map(saved?.openTools);
154
+ let anonymous = saved?.anonymous ?? 0;
155
+ const meaningful = saved?.meaningful ?? {};
156
+ let lastToolAt = saved?.lastToolAt;
157
+ let compacting = saved?.compacting ?? false;
158
+ let compactionStartedAt = saved?.compactionStartedAt;
159
+ let lastCompaction = saved?.lastCompaction;
160
+ let sawAgentSettled = saved?.sawAgentSettled ?? false;
161
+ let retry = saved?.retry;
162
+ const recovery = saved?.recovery ?? {
160
163
  recoveredAfterError: false,
161
164
  retrying: false,
162
165
  willRetry: undefined,
163
166
  lastError: undefined,
164
167
  errorHistory: [],
165
168
  };
166
- for (const raw of events) {
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;
183
- }
184
- if (type === "tool_execution_update") {
185
- lastToolAt = at ?? lastToolAt;
186
- bumpMeaningful(meaningful, at);
187
- continue;
188
- }
189
- if (type === "tool_execution_end") {
190
- const toolCallId = typeof e.toolCallId === "string" ? e.toolCallId : undefined;
191
- if (toolCallId) {
192
- openTools.delete(toolCallId);
169
+ const fold = (events) => {
170
+ for (const raw of events) {
171
+ logReadMetrics.healthFolded++;
172
+ if (!raw || typeof raw !== "object")
173
+ continue;
174
+ const e = raw;
175
+ const type = typeof e.type === "string" ? e.type : undefined;
176
+ if (!type)
177
+ continue;
178
+ // Only parsed-event write provenance counts as wall-clock activity.
179
+ const at = eventTime(e);
180
+ if (type === "tool_execution_start") {
181
+ const toolName = typeof e.toolName === "string" ? e.toolName : "unknown";
182
+ const toolCallId = typeof e.toolCallId === "string" ? e.toolCallId : undefined;
183
+ const key = toolCallId ?? `anonymous:${anonymous++}`;
184
+ openTools.set(key, { toolCallId, toolName, startedAt: at });
185
+ lastToolAt = at ?? lastToolAt;
186
+ bumpMeaningful(meaningful, at);
187
+ continue;
193
188
  }
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]);
189
+ if (type === "tool_execution_update") {
190
+ lastToolAt = at ?? lastToolAt;
191
+ bumpMeaningful(meaningful, at);
192
+ continue;
198
193
  }
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;
224
- }
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";
235
- recovery.lastError = { message: msg, at };
236
- pushError(recovery.errorHistory, recovery.lastError);
237
- bumpMeaningful(meaningful, at);
238
- continue;
239
- }
240
- if (type === "auto_retry_end") {
241
- recovery.retrying = false;
242
- const success = e.success === true;
243
- if (success) {
244
- markRecovered(recovery);
194
+ if (type === "tool_execution_end") {
195
+ const toolCallId = typeof e.toolCallId === "string" ? e.toolCallId : undefined;
196
+ if (toolCallId) {
197
+ openTools.delete(toolCallId);
198
+ }
199
+ else if (typeof e.toolName === "string") {
200
+ const match = [...openTools].find(([, t]) => t.toolName === e.toolName);
201
+ if (match)
202
+ openTools.delete(match[0]);
203
+ }
204
+ lastToolAt = at ?? lastToolAt;
205
+ bumpMeaningful(meaningful, at);
206
+ // Successful tool completion supersedes prior retry intent (AC9).
207
+ if (e.isError !== true)
208
+ markRecovered(recovery);
209
+ continue;
210
+ }
211
+ if (type === "compaction_start") {
212
+ compacting = true;
213
+ compactionStartedAt = at;
214
+ bumpMeaningful(meaningful, at);
215
+ continue;
216
+ }
217
+ if (type === "compaction_end") {
218
+ compacting = false;
219
+ lastCompaction = {
220
+ reason: typeof e.reason === "string" ? e.reason : undefined,
221
+ aborted: typeof e.aborted === "boolean" ? e.aborted : undefined,
222
+ willRetry: typeof e.willRetry === "boolean" ? e.willRetry : undefined,
223
+ errorMessage: typeof e.errorMessage === "string" ? e.errorMessage : undefined,
224
+ at,
225
+ };
226
+ compactionStartedAt = undefined;
227
+ bumpMeaningful(meaningful, at);
228
+ continue;
245
229
  }
246
- else {
247
- const msg = typeof e.finalError === "string"
248
- ? e.finalError
249
- : (recovery.lastError?.message ?? "model retry exhausted");
230
+ if (type === "auto_retry_start") {
231
+ recovery.retrying = true;
232
+ recovery.recoveredAfterError = false;
233
+ recovery.willRetry = true;
234
+ retry = {
235
+ attempt: typeof e.attempt === "number" ? e.attempt : undefined,
236
+ maxAttempts: typeof e.maxAttempts === "number" ? e.maxAttempts : undefined,
237
+ startedAt: at,
238
+ };
239
+ const msg = typeof e.errorMessage === "string" ? e.errorMessage : "model retry";
250
240
  recovery.lastError = { message: msg, at };
251
241
  pushError(recovery.errorHistory, recovery.lastError);
252
- recovery.recoveredAfterError = false;
242
+ bumpMeaningful(meaningful, at);
243
+ continue;
253
244
  }
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 };
245
+ if (type === "auto_retry_end") {
246
+ recovery.retrying = false;
247
+ const success = e.success === true;
248
+ if (success) {
249
+ markRecovered(recovery);
250
+ }
251
+ else {
252
+ const msg = typeof e.finalError === "string"
253
+ ? e.finalError
254
+ : (recovery.lastError?.message ?? "model retry exhausted");
255
+ recovery.lastError = { message: msg, at };
265
256
  pushError(recovery.errorHistory, recovery.lastError);
266
257
  recovery.recoveredAfterError = false;
267
- // Model-error evidence is meaningful for timing, not healthy progress.
268
- bumpMeaningful(meaningful, at);
269
258
  }
270
- else {
259
+ bumpMeaningful(meaningful, at);
260
+ continue;
261
+ }
262
+ if (type === "message_end") {
263
+ const msg = e.message;
264
+ if (isAssistantMessage(msg)) {
265
+ if (assistantIsError(msg)) {
266
+ const message = typeof msg.errorMessage === "string"
267
+ ? msg.errorMessage
268
+ : "assistant stopReason=error";
269
+ recovery.lastError = { message, at };
270
+ pushError(recovery.errorHistory, recovery.lastError);
271
+ recovery.recoveredAfterError = false;
272
+ // Model-error evidence is meaningful for timing, not healthy progress.
273
+ bumpMeaningful(meaningful, at);
274
+ }
275
+ else {
276
+ bumpMeaningful(meaningful, at);
277
+ // Later successful assistant evidence clears retry/warning (AC9).
278
+ markRecovered(recovery);
279
+ }
280
+ }
281
+ // user message_end is not child progress
282
+ continue;
283
+ }
284
+ if (type === "turn_end") {
285
+ const msg = e.message;
286
+ if (isAssistantMessage(msg) && !assistantIsError(msg)) {
271
287
  bumpMeaningful(meaningful, at);
272
- // Later successful assistant evidence clears retry/warning (AC9).
273
288
  markRecovered(recovery);
274
289
  }
290
+ continue;
275
291
  }
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)) {
282
- bumpMeaningful(meaningful, at);
283
- markRecovered(recovery);
292
+ if (type === "agent_end") {
293
+ if (typeof e.willRetry === "boolean")
294
+ recovery.willRetry = e.willRetry;
295
+ if (recovery.willRetry === true) {
296
+ recovery.retrying = true;
297
+ recovery.recoveredAfterError = false;
298
+ bumpMeaningful(meaningful, at);
299
+ }
300
+ continue;
284
301
  }
285
- continue;
286
- }
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;
302
+ if (type === "agent_settled") {
303
+ sawAgentSettled = true;
304
+ // Settled ends the active retry phase; retain error history for detail.
305
+ recovery.retrying = false;
306
+ if (recovery.willRetry === true)
307
+ recovery.willRetry = false;
293
308
  bumpMeaningful(meaningful, at);
309
+ continue;
294
310
  }
295
- continue;
296
- }
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;
303
- bumpMeaningful(meaningful, at);
304
- continue;
311
+ // message_update is noisy; intentionally NOT meaningful for stale detection.
305
312
  }
306
- // message_update is noisy; intentionally NOT meaningful for stale detection.
307
- }
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,
313
+ let modelState = "ok";
314
+ if (recovery.retrying || recovery.willRetry === true)
315
+ modelState = "retrying";
316
+ else if (recovery.lastError && !recovery.recoveredAfterError)
317
+ modelState = "error";
318
+ else
319
+ modelState = "ok";
320
+ return {
321
+ lastMeaningfulAt: meaningful.last,
322
+ activeTools: [...openTools.values()],
323
+ lastToolAt,
324
+ compacting,
325
+ compactionStartedAt,
326
+ lastCompaction,
327
+ model: {
328
+ state: modelState,
329
+ lastError: recovery.lastError,
330
+ errorHistory: [...recovery.errorHistory],
331
+ retry,
332
+ },
333
+ sawAgentSettled,
334
+ willRetry: recovery.willRetry,
335
+ longModelCallSupported: false,
336
+ };
331
337
  };
338
+ return Object.assign(fold, { snapshot: () => ({ openTools: [...openTools], anonymous,
339
+ meaningful, lastToolAt, compacting, compactionStartedAt, lastCompaction,
340
+ sawAgentSettled, retry, recovery }) });
341
+ }
342
+ export function encodeHealthLogState(state) {
343
+ return { cursor: state.cursor, truncated: state.truncated, fold: state.fold.snapshot() };
344
+ }
345
+ export function decodeHealthLogState(saved) {
346
+ if (!saved?.fold?.recovery || !Array.isArray(saved.fold.openTools)
347
+ || !Number.isSafeInteger(saved.cursor?.offset) || saved.cursor.offset < 0)
348
+ throw new Error("Invalid health checkpoint");
349
+ return { cursor: saved.cursor, truncated: saved.truncated, fold: createChildEventFactFold(saved.fold) };
332
350
  }
333
351
  /** Parse the fact-relevant events out of raw NDJSON lines. */
334
352
  function parseFactEvents(lines) {
@@ -341,7 +359,7 @@ function parseFactEvents(lines) {
341
359
  if (!mayAffectChildEventFacts(s))
342
360
  continue;
343
361
  try {
344
- events.push(JSON.parse(s));
362
+ events.push(parseLogEvent(s));
345
363
  sizes.push(s.length);
346
364
  }
347
365
  catch {
@@ -352,14 +370,8 @@ function parseFactEvents(lines) {
352
370
  }
353
371
  // ---- incremental log reading ----------------------------------------------
354
372
  //
355
- // Logs are append-only and reach gigabytes, so facts are folded from an
356
- // accumulated event list that grows by the bytes appended since the last read
357
- // (see log-cursor.ts). Only the types the fold consumes are retained, which is
358
- // ~2% of a log's lines; `message_update` alone is 98% of the volume and cannot
359
- // move a fact. The retained list is capped, oldest-first, and a drop is
360
- // reported as a diagnostic rather than silently changing an observation.
361
- /** Memory budget for one run's retained fact-relevant events. */
362
- const MAX_RETAINED_EVENT_BYTES = 8 * 1024 * 1024; // 8 MiB
373
+ // Retain structural facts, not source events. Only newly completed lines enter
374
+ // the fold; a skipped byte window remains explicitly reported in rawLog.
363
375
  function maxHealthReadBytes() {
364
376
  const raw = process.env.PI_SUBAGENT_MAX_HEALTH_READ_BYTES;
365
377
  if (!raw)
@@ -394,15 +406,6 @@ function rememberState(id, state) {
394
406
  factLogStates.delete(oldest.value);
395
407
  }
396
408
  }
397
- function trimToBudget(state) {
398
- while (state.bytes > MAX_RETAINED_EVENT_BYTES && state.events.length > 1) {
399
- state.events.shift();
400
- state.bytes -= state.sizes.shift() ?? 0;
401
- state.dropped = true;
402
- }
403
- if (state.bytes < 0)
404
- state.bytes = 0;
405
- }
406
409
  /**
407
410
  * Read a run log for event facts + raw mtime/size diagnostics.
408
411
  * Raw log write time never promotes activity health by itself.
@@ -433,7 +436,8 @@ export function extractChildEventFactsFromLog(id, opts = {}) {
433
436
  return { facts: extractChildEventFacts(events), rawLog };
434
437
  }
435
438
  const key = opts.logPath ?? id;
436
- const previous = factLogStates.get(key);
439
+ const states = opts.states ?? factLogStates;
440
+ const previous = states.get(key);
437
441
  const read = readAppendedLines(path, previous?.cursor, maxHealthReadBytes());
438
442
  if (read.error !== undefined) {
439
443
  rawLog.error = rawLog.error ?? read.error;
@@ -441,24 +445,19 @@ export function extractChildEventFactsFromLog(id, opts = {}) {
441
445
  return { facts: emptyFacts(), rawLog };
442
446
  }
443
447
  const state = read.restarted || !previous
444
- ? { cursor: read.cursor, events: [], sizes: [], bytes: 0, truncated: false, dropped: false }
448
+ ? { cursor: read.cursor, fold: createChildEventFactFold(), truncated: false }
445
449
  : previous;
446
450
  state.cursor = read.cursor;
447
451
  state.truncated = state.truncated || read.truncated;
448
452
  const parsed = parseFactEvents(read.lines);
449
- if (parsed.events.length > 0) {
450
- state.events.push(...parsed.events);
451
- state.sizes.push(...parsed.sizes);
452
- for (const size of parsed.sizes)
453
- state.bytes += size;
454
- trimToBudget(state);
455
- }
456
- rememberState(key, state);
453
+ const facts = state.fold(parsed.events);
454
+ if (opts.states)
455
+ states.set(key, state);
456
+ else
457
+ rememberState(key, state);
457
458
  if (state.truncated)
458
459
  rawLog.windowTruncated = true;
459
- if (state.dropped)
460
- rawLog.eventsDropped = true;
461
- return { facts: extractChildEventFacts(state.events), rawLog };
460
+ return { facts, rawLog };
462
461
  }
463
462
  function processLiveness(status, supervised) {
464
463
  if (status === "orphaned")
@@ -11,7 +11,7 @@
11
11
  */
12
12
 
13
13
  import { statSync } from "node:fs";
14
- import { DEFAULT_MAX_READ_BYTES, readAppendedLines, type LogCursor } from "./log-cursor.ts";
14
+ import { DEFAULT_MAX_READ_BYTES, readAppendedLines, parseLogEvent, logReadMetrics, type LogCursor } from "./log-cursor.ts";
15
15
  import { logPathFor } from "./registry.ts";
16
16
  import type { RunStatus } from "./registry.ts";
17
17
  import { loadConfig, type SubagentConfig } from "./config.ts";
@@ -251,16 +251,20 @@ export function mayAffectChildEventFacts(line: string): boolean {
251
251
  * that already parsed NDJSON). Skips non-objects; ignores raw non-JSON noise.
252
252
  */
253
253
  export function extractChildEventFacts(events: ReadonlyArray<unknown>): ChildEventFacts {
254
- const openTools = new Map<string, ActiveToolFact>();
255
- let anonymous = 0;
256
- const meaningful: { last?: number } = {};
257
- let lastToolAt: number | undefined;
258
- let compacting = false;
259
- let compactionStartedAt: number | undefined;
260
- let lastCompaction: CompactionEndFact | undefined;
261
- let sawAgentSettled = false;
262
- let retry: ModelFacts["retry"];
263
- const recovery: RetryRecoveryState = {
254
+ return createChildEventFactFold()(events);
255
+ }
256
+
257
+ function createChildEventFactFold(saved?: any) {
258
+ const openTools = new Map<string, ActiveToolFact>(saved?.openTools);
259
+ let anonymous = saved?.anonymous ?? 0;
260
+ const meaningful: { last?: number } = saved?.meaningful ?? {};
261
+ let lastToolAt: number | undefined = saved?.lastToolAt;
262
+ let compacting = saved?.compacting ?? false;
263
+ let compactionStartedAt: number | undefined = saved?.compactionStartedAt;
264
+ let lastCompaction: CompactionEndFact | undefined = saved?.lastCompaction;
265
+ let sawAgentSettled = saved?.sawAgentSettled ?? false;
266
+ let retry: ModelFacts["retry"] = saved?.retry;
267
+ const recovery: RetryRecoveryState = saved?.recovery ?? {
264
268
  recoveredAfterError: false,
265
269
  retrying: false,
266
270
  willRetry: undefined,
@@ -268,7 +272,9 @@ export function extractChildEventFacts(events: ReadonlyArray<unknown>): ChildEve
268
272
  errorHistory: [],
269
273
  };
270
274
 
275
+ const fold = (events: ReadonlyArray<unknown>): ChildEventFacts => {
271
276
  for (const raw of events) {
277
+ logReadMetrics.healthFolded++;
272
278
  if (!raw || typeof raw !== "object") continue;
273
279
  const e = raw as LooseEvent;
274
280
  const type = typeof e.type === "string" ? e.type : undefined;
@@ -431,6 +437,20 @@ export function extractChildEventFacts(events: ReadonlyArray<unknown>): ChildEve
431
437
  willRetry: recovery.willRetry,
432
438
  longModelCallSupported: false,
433
439
  };
440
+ };
441
+ return Object.assign(fold, { snapshot: () => ({ openTools: [...openTools], anonymous,
442
+ meaningful, lastToolAt, compacting, compactionStartedAt, lastCompaction,
443
+ sawAgentSettled, retry, recovery }) });
444
+ }
445
+
446
+ export function encodeHealthLogState(state: FactLogState): unknown {
447
+ return { cursor: state.cursor, truncated: state.truncated, fold: state.fold.snapshot() };
448
+ }
449
+
450
+ export function decodeHealthLogState(saved: any): FactLogState {
451
+ if (!saved?.fold?.recovery || !Array.isArray(saved.fold.openTools)
452
+ || !Number.isSafeInteger(saved.cursor?.offset) || saved.cursor.offset < 0) throw new Error("Invalid health checkpoint");
453
+ return { cursor: saved.cursor, truncated: saved.truncated, fold: createChildEventFactFold(saved.fold) };
434
454
  }
435
455
 
436
456
  /** Parse the fact-relevant events out of raw NDJSON lines. */
@@ -442,7 +462,7 @@ function parseFactEvents(lines: Iterable<string>): { events: unknown[]; sizes: n
442
462
  if (!s || s[0] !== "{") continue;
443
463
  if (!mayAffectChildEventFacts(s)) continue;
444
464
  try {
445
- events.push(JSON.parse(s));
465
+ events.push(parseLogEvent(s));
446
466
  sizes.push(s.length);
447
467
  } catch {
448
468
  // bad JSON — ignore (noise / partial line)
@@ -453,15 +473,8 @@ function parseFactEvents(lines: Iterable<string>): { events: unknown[]; sizes: n
453
473
 
454
474
  // ---- incremental log reading ----------------------------------------------
455
475
  //
456
- // Logs are append-only and reach gigabytes, so facts are folded from an
457
- // accumulated event list that grows by the bytes appended since the last read
458
- // (see log-cursor.ts). Only the types the fold consumes are retained, which is
459
- // ~2% of a log's lines; `message_update` alone is 98% of the volume and cannot
460
- // move a fact. The retained list is capped, oldest-first, and a drop is
461
- // reported as a diagnostic rather than silently changing an observation.
462
-
463
- /** Memory budget for one run's retained fact-relevant events. */
464
- const MAX_RETAINED_EVENT_BYTES = 8 * 1024 * 1024; // 8 MiB
476
+ // Retain structural facts, not source events. Only newly completed lines enter
477
+ // the fold; a skipped byte window remains explicitly reported in rawLog.
465
478
 
466
479
  function maxHealthReadBytes(): number {
467
480
  const raw = process.env.PI_SUBAGENT_MAX_HEALTH_READ_BYTES;
@@ -478,13 +491,8 @@ const MAX_TRACKED_RUNS = 64;
478
491
 
479
492
  interface FactLogState {
480
493
  cursor: LogCursor;
481
- events: unknown[];
482
- /** Retained source bytes per event, index-aligned with `events`. */
483
- sizes: number[];
484
- /** Sum of `sizes`, for the drop-oldest budget. */
485
- bytes: number;
494
+ fold: ReturnType<typeof createChildEventFactFold>;
486
495
  truncated: boolean;
487
- dropped: boolean;
488
496
  }
489
497
 
490
498
  const factLogStates = new Map<string, FactLogState>();
@@ -509,15 +517,6 @@ function rememberState(id: string, state: FactLogState): void {
509
517
  }
510
518
  }
511
519
 
512
- function trimToBudget(state: FactLogState): void {
513
- while (state.bytes > MAX_RETAINED_EVENT_BYTES && state.events.length > 1) {
514
- state.events.shift();
515
- state.bytes -= state.sizes.shift() ?? 0;
516
- state.dropped = true;
517
- }
518
- if (state.bytes < 0) state.bytes = 0;
519
- }
520
-
521
520
  /**
522
521
  * Read a run log for event facts + raw mtime/size diagnostics.
523
522
  * Raw log write time never promotes activity health by itself.
@@ -529,7 +528,7 @@ function trimToBudget(state: FactLogState): void {
529
528
  */
530
529
  export function extractChildEventFactsFromLog(
531
530
  id: string,
532
- opts: { now?: number; logText?: string; logPath?: string } = {},
531
+ opts: { now?: number; logText?: string; logPath?: string; states?: Map<string, FactLogState> } = {},
533
532
  ): { facts: ChildEventFacts; rawLog: RawLogDiagnostic } {
534
533
  const path = opts.logPath ?? logPathFor(id);
535
534
  const rawLog: RawLogDiagnostic = {};
@@ -553,7 +552,8 @@ export function extractChildEventFactsFromLog(
553
552
  }
554
553
 
555
554
  const key = opts.logPath ?? id;
556
- const previous = factLogStates.get(key);
555
+ const states = opts.states ?? factLogStates;
556
+ const previous = states.get(key);
557
557
  const read = readAppendedLines(path, previous?.cursor, maxHealthReadBytes());
558
558
  if (read.error !== undefined) {
559
559
  rawLog.error = rawLog.error ?? read.error;
@@ -561,23 +561,18 @@ export function extractChildEventFactsFromLog(
561
561
  }
562
562
 
563
563
  const state: FactLogState = read.restarted || !previous
564
- ? { cursor: read.cursor, events: [], sizes: [], bytes: 0, truncated: false, dropped: false }
564
+ ? { cursor: read.cursor, fold: createChildEventFactFold(), truncated: false }
565
565
  : previous;
566
566
  state.cursor = read.cursor;
567
567
  state.truncated = state.truncated || read.truncated;
568
568
 
569
569
  const parsed = parseFactEvents(read.lines);
570
- if (parsed.events.length > 0) {
571
- state.events.push(...parsed.events);
572
- state.sizes.push(...parsed.sizes);
573
- for (const size of parsed.sizes) state.bytes += size;
574
- trimToBudget(state);
575
- }
576
- rememberState(key, state);
570
+ const facts = state.fold(parsed.events);
571
+ if (opts.states) states.set(key, state);
572
+ else rememberState(key, state);
577
573
 
578
574
  if (state.truncated) rawLog.windowTruncated = true;
579
- if (state.dropped) rawLog.eventsDropped = true;
580
- return { facts: extractChildEventFacts(state.events), rawLog };
575
+ return { facts, rawLog };
581
576
  }
582
577
 
583
578
  // ---- observation ----------------------------------------------------------