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,21 +1,26 @@
1
+ import { affectedAttempts } from "./attempt-invalidation.ts";
1
2
  import { processMatchesStart } from "../daemon-owner.ts";
2
3
  import { createHash } from "node:crypto";
3
- import { readdir, readFile, stat } from "node:fs/promises";
4
- import { watch, type FSWatcher } from "node:fs";
5
- import { join, resolve, sep } from "node:path";
6
- import { realpathSync, statSync } from "node:fs";
4
+ import { opendir, readFile, stat, writeFile, mkdir, rename } from "node:fs/promises";
5
+ import { watchSource, type SourceWatch, type SourceWatcher as FSWatcher } from "./source-watch.ts";
6
+ import { basename, dirname, relative, join, resolve, sep } from "node:path";
7
+ import { realpathSync, statSync, mkdirSync } from "node:fs";
7
8
  import { tmpdir } from "node:os";
8
9
  import { createRequire } from "node:module";
9
10
  import { setImmediate as yieldTurn } from "node:timers/promises";
11
+ import type { InventoryPhase } from "./read-watchdog-probe.ts";
10
12
  import { performance } from "node:perf_hooks";
11
13
  import { createAssignmentProjector } from "./domain/assignment-projection.mjs";
12
14
  import { createAssignmentReader } from "./domain/assignment-observation.mjs";
13
15
  import { parseArchivedAttempt, parseArchivedSessionState } from "./domain/session-store.mjs";
14
- import { parseRun, readRunTranscript } from "./domain/parse.mjs";
16
+ import { parseRun, parseRunDisplay, readRunTranscript, encodeParseLogState, decodeParseLogState } from "./domain/parse.mjs";
17
+ import { withLogReadBatch, logReadMetrics } from "./domain/log-cursor.mjs";
15
18
  import { fmtSpend } from "./domain/widget.mjs";
16
19
  import { effectiveStatus } from "./domain/process-status.mjs";
17
- import { extractChildEventFactsFromLog, healthThresholdsForConfig } from "./domain/health-observation.mjs";
20
+ import { extractChildEventFactsFromLog, healthThresholdsForConfig, encodeHealthLogState, decodeHealthLogState } from "./domain/health-observation.mjs";
21
+ import { LogCheckpoints, isSqliteLockContention } from "./log-checkpoints.ts";
18
22
  import { BackgroundObservation } from "./background.ts";
23
+ import { workPage, createWorkBudget } from "./work-budget.ts";
19
24
  // @ts-expect-error Generated canonical read-only failure projection.
20
25
  import { readFailureStateReadOnly, pendingFailureAttention } from "./domain/subagents/shared-failure-observations.domain.mjs";
21
26
  import { readHealthConfig } from "./health-config.ts";
@@ -25,7 +30,7 @@ export interface WorkSnapshot {
25
30
  instanceId: string; runtimeEpoch: string; scopeRevision: string; seq: number;
26
31
  observedRevisionVector: { inventory: number; coordinator: string; healthConfig: string };
27
32
  status: "ready" | "rebuilding" | "degraded"; reason?: string;
28
- rows: Array<{ meta: any; assignment: any; sourceRevision: string }>;
33
+ rows: Array<{ meta: any; assignment: any; sourceRevision: string; recipientPending?: boolean }>;
29
34
  nextCursor?: string; activity: { active: number }; nextDeadline: number | null;
30
35
  totalMatching: number;
31
36
  backgroundIndex?: any;
@@ -34,55 +39,126 @@ export interface WorkSnapshot {
34
39
  const hash = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
35
40
  const safeId = /^[A-Za-z0-9_-]+$/;
36
41
 
42
+ function healthWithThresholds(health: any, config: any, meta: any) {
43
+ if (!health) return undefined;
44
+ const value = { ...health, thresholds: healthThresholdsForConfig(config) };
45
+ return { ...value, nextDeadline: nextHealthDeadline(value, meta) };
46
+ }
47
+
48
+ function nextHealthDeadline(health: any, meta: any, now = Date.now()): number | null {
49
+ if (!health) return null;
50
+ const { thresholds } = health;
51
+ const facts = health.facts;
52
+ const tool = facts.activeTools.at(-1);
53
+ const toolStart = tool?.startedAt ?? facts.lastToolAt ?? facts.lastMeaningfulAt;
54
+ const compactionStart = facts.compactionStartedAt ?? facts.lastMeaningfulAt;
55
+ const anchor = facts.lastMeaningfulAt ?? meta.startedAt;
56
+ const deadlines: number[] = [];
57
+ if (["running", "orphaned"].includes(meta.status)) {
58
+ if (tool && Number.isFinite(toolStart)) deadlines.push(toolStart + thresholds.longToolMs);
59
+ if (facts.compacting && Number.isFinite(compactionStart)) deadlines.push(compactionStart + thresholds.longCompactionMs);
60
+ if (!tool && !facts.compacting && !["retrying", "error"].includes(facts.model.state) && Number.isFinite(anchor)) {
61
+ deadlines.push(anchor + thresholds.quietMs, anchor + thresholds.staleMs);
62
+ }
63
+ }
64
+ const future = deadlines.filter(deadline => deadline > now);
65
+ return future.length ? Math.min(...future) : null;
66
+ }
67
+
68
+ const healthDeadlineExpired = (row: { health?: any }, now: number) => typeof row.health?.nextDeadline === "number" && row.health.nextDeadline <= now;
69
+
37
70
  /** Reconstructable query state. It never authorizes execution or writes source records. */
38
71
  export class WorkReadModel {
72
+ private budget: ReturnType<typeof createWorkBudget>;
39
73
  onTerminalLogsChanged?: () => void;
40
74
  private background: BackgroundObservation;
41
75
  private db: any;
42
- private reader: ReturnType<typeof createAssignmentReader>;
76
+ private reader!: ReturnType<typeof createAssignmentReader>;
43
77
  private files = new Map<string, { signature: string; meta: any }>();
44
- private projected = new Map<string, { meta: any; assignment: any; sourceRevision: string; display?: { spend: string; tool: string }; health?: any; recipientPending?: boolean; failurePending?: boolean }>();
78
+ private projected = new Map<string, { meta: any; assignment: any; sourceRevision: string; display?: { spend: string; tool: string; diagnostics?: string[]; coverage?: any }; health?: any; recipientPending?: boolean; failurePending?: boolean }>();
45
79
  private logs = new Map<string, string>();
80
+ private parseStates = new Map();
81
+ private healthStates = new Map();
82
+ private checkpoints: LogCheckpoints;
83
+ private checkpointAttemptAllowed = true;
84
+ private checkpointFailure = false;
85
+ private initialization = { attempts: 0, contentions: 0 };
86
+ private get observationInitialized() { return this.checkpoints.ready && Boolean(this.reader) && this.background.ready; }
46
87
  private failureJournals = new Map<string, string>();
47
88
  private processes = new Map<string, string>();
48
89
  private staged?: {
49
90
  files: WorkReadModel["files"]; projected: WorkReadModel["projected"];
50
91
  logs: Map<string, string>; failureJournals: Map<string, string>; processes: Map<string, string>; healthRevision: string;
51
- coordinator: string; coordinatorConversations?: Map<string, string>;
92
+ coordinator: string;
93
+ assignmentChanges?: Map<string, string>; assignmentGeneration: string;
52
94
  };
53
95
  private healthRevision = "";
54
96
  private details = new Map<string, { revision: string; value: any }>();
55
97
  private watchers = new Map<string, FSWatcher>();
98
+ private rootParents = new Map<string, { path: string; identity: string; watcher: FSWatcher }>();
56
99
  private rootWatchIdentities = new Map<string, string>();
57
100
  private listeners = new Set<() => void>();
58
101
  private timer?: ReturnType<typeof setInterval>;
59
102
  private pending?: Promise<void>;
60
103
  private dirty = false;
104
+ private sourceConflicts = 0;
105
+ private conflictRetry?: ReturnType<typeof setTimeout>;
106
+ private conflictDelay = 100;
107
+ private hints = new Map<string, number>();
108
+ private repair?: AsyncGenerator<string[]>;
109
+ private repairOwed = false;
110
+ private imported = false;
111
+ private repairWrite: Promise<void> = Promise.resolve();
112
+ private repairPersistencePending = false;
113
+ private sourceErrors = new Map<string, string>();
114
+ private sourceRace?: { reason: string; paths: Set<string>; rows: any[] };
115
+ private sourceStats = 0;
116
+ private sourceWork = { entity: { batches: 0, paths: 0, stats: 0, metadataReads: 0, logBytes: 0, logReads: 0 }, repair: { batches: 0, paths: 0, stats: 0, metadataReads: 0, logBytes: 0, logReads: 0 } };
117
+ private scheduling = { entityBatches: 0, repairBatches: 0, repairEntries: 0, overflows: 0, maxQueueAgeMs: 0, maxPublicationMs: 0 };
61
118
  private closed = false;
62
119
  private inventory = 0;
63
120
  private coordinator = "unknown";
64
- private coordinatorConversations?: Map<string, string>;
121
+ private assignmentBaseline?: { key: string; seq: string };
122
+ private assignmentFault?: { state: WorkSnapshot["status"]; reason?: string };
123
+ private unsupportedAssignmentRevision?: string;
65
124
  private revision = 0;
125
+ private scopeSequence = 0;
126
+ private scopes = new Map<string, { scope: WorkScope; token: number; revision: number; used: number; status: string }>();
127
+ private changedRows: Array<{ before?: any; after?: any }> = [];
66
128
  private foldQueueSequence = 0;
67
129
  private state: WorkSnapshot["status"] = "rebuilding";
68
130
  private reason: string | undefined = "Initial source inventory is rebuilding.";
69
- private counters = { inventories: 0, metadataReads: 0, projections: 0 };
131
+ private counters = { inventories: 0, metadataReads: 0, projections: 0, assignmentProjections: 0, logProjections: 0, healthProjections: 0, failureProjections: 0, healthRecomputations: 0, healthConfigInvalidations: 0 };
132
+ private invalidations = { assignmentInput: 0, process: 0, log: 0, failureAttention: 0, healthConfig: 0, healthDeadline: 0, unverified: 0, initial: 0 };
133
+ private get assignmentMetrics() {
134
+ if (this.observationInitialized) {
135
+ try { return this.reader.changeMetrics; }
136
+ catch (error) { if (!isSqliteLockContention(error)) throw error; }
137
+ }
138
+ return { available: false, received: null, applied: null, pending: null };
139
+ }
70
140
  get metrics() {
71
- return { ...this.counters, coordinatorConnections: Number(Boolean(this.reader.connection(false))) + this.background.connectionCount,
72
- indexConnections: this.closed ? 0 : 1, sourceWatchers: this.watchers.size };
141
+ return { ...this.counters, assignments: this.assignmentMetrics, initialization: { ...this.initialization }, checkpoints: { ...this.checkpoints.metrics, hotDisplay: this.parseStates.size, hotHealth: this.healthStates.size }, sourceWork: structuredClone(this.sourceWork), scheduling: { ...this.scheduling, queued: this.hints.size }, invalidations: { ...this.invalidations }, logReads: { ...logReadMetrics }, coordinatorConnections: Number(Boolean(this.reader?.connection(false))) + this.background.connectionCount,
142
+ indexConnections: this.closed ? 0 : 1, sourceWatchers: this.watchers.size, sourceParentWatchers: this.rootParents.size, rootParentWatchers: this.rootParents.size };
73
143
  }
74
144
  readonly runs: string;
75
145
  readonly archives: string;
76
146
  readonly markers: string;
77
147
  readonly agentDir: string;
78
148
  readonly instanceId: string;
149
+ private readonly inventoryPhase?: (phase: InventoryPhase) => void;
79
150
 
80
- constructor(agentDir: string, instanceId: string, options: { supervisorDirectory?: string; baseDir?: string; durableDir?: string; intervalMs?: number } = {}) {
151
+ private watch: SourceWatch;
152
+ constructor(agentDir: string, instanceId: string, options: { supervisorDirectory?: string; baseDir?: string; durableDir?: string; intervalMs?: number; watch?: SourceWatch; budgetBuffer?: SharedArrayBuffer; inventoryPhase?: (phase: InventoryPhase) => void } = {}) {
153
+ this.budget = createWorkBudget(options.budgetBuffer);
154
+ this.watch = options.watch ?? watchSource;
81
155
  this.agentDir = agentDir; this.instanceId = instanceId;
156
+ this.inventoryPhase = options.inventoryPhase;
82
157
  const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
83
158
  this.db = new DatabaseSync(":memory:");
84
- this.reader = createAssignmentReader(join(agentDir, "operation-coordinator.sqlite"));
85
- this.background = new BackgroundObservation(agentDir, options.supervisorDirectory, this.db, () => this.publish(), refresh => this.reader.connection(refresh));
159
+ this.checkpoints = new LogCheckpoints(join(agentDir, "runtime-log-checkpoints.sqlite"), this.db, { defer: true });
160
+ mkdirSync(join(agentDir, "runtime-read-repair"), { recursive: true });
161
+ this.background = new BackgroundObservation(agentDir, options.supervisorDirectory, this.db, () => this.publish(true), refresh => this.reader?.connection(refresh), { defer: true });
86
162
  this.db.exec(`CREATE TABLE rows (id TEXT PRIMARY KEY, cwd TEXT, origin_cwd TEXT, origin_session TEXT,
87
163
  started REAL, state TEXT, active INTEGER, ended REAL, recipient_pending INTEGER, payload TEXT);
88
164
  CREATE INDEX work_folder ON rows(cwd, started DESC, id DESC);
@@ -91,6 +167,8 @@ export class WorkReadModel {
91
167
  CREATE INDEX work_terminal ON rows(active, ended, started DESC, id DESC);
92
168
  CREATE INDEX work_recipient_pending ON rows(origin_cwd, origin_session, recipient_pending, started DESC, id DESC);
93
169
  CREATE INDEX work_state ON rows(state, started DESC, id DESC);
170
+ CREATE TABLE assignment_members (scope TEXT NOT NULL, id TEXT NOT NULL, PRIMARY KEY(scope,id));
171
+ CREATE INDEX assignment_member_id ON assignment_members(id);
94
172
  CREATE TABLE terminal_log_folds (id TEXT PRIMARY KEY, revision TEXT NOT NULL, pending INTEGER NOT NULL, queue_position INTEGER NOT NULL);
95
173
  CREATE INDEX pending_terminal_log_folds ON terminal_log_folds(pending, queue_position, id);`);
96
174
  this.runs = join(options.baseDir ?? join(realpathSync(tmpdir()), "pi-better-subagents"), "runs");
@@ -99,50 +177,189 @@ export class WorkReadModel {
99
177
  // Watch directory entries, not file inodes. Node's Linux recursive watcher
100
178
  // can retain a replaced file's old inode after atomic rename and miss later
101
179
  // commits. Flat archives need one watcher; raw runs use one per directory.
102
- for (const path of [this.runs, this.archives, this.markers]) this.watchDirectory(path);
103
- this.timer = setInterval(() => { if (!this.pending) void this.reconcile(); }, options.intervalMs ?? 1000);
180
+ for (const path of [this.runs, this.archives, this.markers]) { this.watchRootParent(path); this.watchDirectory(path); }
181
+ this.timer = setInterval(() => { this.checkpointAttemptAllowed = true; this.repairOwed = true; if (!this.pending) void this.reconcile(false); }, options.intervalMs ?? 1000);
104
182
  this.timer.unref();
105
183
  }
106
184
 
107
185
  private unwatchDirectory(path: string) {
108
186
  this.watchers.get(path)?.close(); this.watchers.delete(path);
109
187
  }
188
+ private watchRootParent(root: string) {
189
+ if (this.closed) return;
190
+ // A watch follows an inode, not the source pathname. Keep an independent
191
+ // parent entry watch so recreation after an observed ENOENT remains visible.
192
+ for (let parent = dirname(root); ; parent = dirname(parent)) {
193
+ const previous = this.rootParents.get(root);
194
+ try {
195
+ const info = statSync(parent, { bigint: true });
196
+ const identity = `${info.dev}:${info.ino}`;
197
+ if (previous?.path === parent && previous.identity === identity) return;
198
+ const entry = relative(parent, root).split(sep)[0];
199
+ const watcher = this.watch(parent, (_event, filename) => {
200
+ if (this.closed || this.rootParents.get(root)?.watcher !== watcher) return;
201
+ if (!filename || String(filename) === entry || String(filename) === relative(dirname(parent), parent)) void this.reconcile();
202
+ });
203
+ watcher.on("error", () => {
204
+ if (this.rootParents.get(root)?.watcher !== watcher) return;
205
+ watcher.close(); this.rootParents.delete(root);
206
+ this.invalidate("Source parent watcher failed; reconciling source inventory.");
207
+ });
208
+ previous?.watcher.close();
209
+ this.rootParents.set(root, { path: parent, identity, watcher });
210
+ return;
211
+ } catch { /* Missing source ancestors are watched from their nearest existing parent. */ }
212
+ if (dirname(parent) === parent) return;
213
+ }
214
+ }
110
215
  private watchDirectory(path: string) {
111
- if (this.closed || this.watchers.has(path)) return;
216
+ if (this.closed) return;
217
+ let identity: string | undefined;
218
+ if ([this.runs, this.archives, this.markers].includes(path)) {
219
+ try {
220
+ const info = statSync(path, { bigint: true });
221
+ identity = `${info.dev}:${info.ino}`;
222
+ } catch (error) {
223
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") return;
224
+ }
225
+ if (!identity || this.rootWatchIdentities.get(path) !== identity) {
226
+ this.unwatchDirectory(path); this.rootWatchIdentities.delete(path);
227
+ if (path === this.runs) for (const child of this.watchers.keys()) if (child.startsWith(this.runs + sep)) this.unwatchDirectory(child);
228
+ }
229
+ if (!identity) return;
230
+ }
231
+ if (this.watchers.has(path)) return;
112
232
  try {
113
- const watcher = watch(path, (_event, filename) => {
233
+ const watcher = this.watch(path, (_event, filename) => {
234
+ if (this.closed || this.watchers.get(path) !== watcher) return;
114
235
  if (path === this.runs) {
115
236
  // A raw directory may itself have been removed/replaced. Reattach
116
237
  // from the shared inventory, never retain its preceding inode.
117
238
  if (filename && safeId.test(String(filename))) this.unwatchDirectory(join(this.runs, String(filename)));
118
239
  else for (const watched of this.watchers.keys()) if (watched.startsWith(this.runs + sep)) this.unwatchDirectory(watched);
119
240
  }
120
- void this.reconcile();
121
- });
241
+ this.fileHint(path, filename ? String(filename) : undefined);
242
+ }, dirname(path) === this.runs);
122
243
  watcher.on("error", () => {
123
244
  if (this.watchers.get(path) !== watcher) return;
124
245
  this.unwatchDirectory(path);
125
246
  this.invalidate("Watcher overflow or failure; reconciling source inventory.");
126
247
  });
127
248
  this.watchers.set(path, watcher);
249
+ if (identity) this.rootWatchIdentities.set(path, identity);
128
250
  } catch { /* Missing roots are discovered by the existing compatibility inventory. */ }
129
251
  }
130
252
 
253
+ /** File notifications are hints, never authority. Unknown names owe scoped repair. */
254
+ fileHint(directory: string, name?: string) {
255
+ // Some fs.watch backends report the watched directory's own name for a
256
+ // contained write. It identifies a source to verify, not a child entry.
257
+ if (name === basename(directory)) {
258
+ name = directory.startsWith(this.runs + sep) ? "meta.json" : undefined;
259
+ }
260
+ let path: string | undefined;
261
+ if (directory === this.runs && name && safeId.test(name)) path = join(directory, name, "meta.json");
262
+ else if ([this.archives, this.markers].includes(directory) && name && /^[A-Za-z0-9_-]+\.json$/.test(name)) path = join(directory, name);
263
+ else if (directory.startsWith(this.runs + sep) && name && ["meta.json", "output.log", "failures.jsonl", "failures.jsonl.observed"].includes(name)) path = join(directory, "meta.json");
264
+ else if (name) return; // Locks, temporary files and coordinator controls are not task inputs.
265
+ if (!path) { this.repairOwed = true; void this.reconcile(false); return; }
266
+ if (!this.hints.has(path)) {
267
+ if (this.hints.size >= 256) {
268
+ this.scheduling.overflows++; this.repairOwed = true;
269
+ // Persist the bounded source scope before discarding the individual hint.
270
+ if (!this.repairPersistencePending) {
271
+ this.repairPersistencePending = true;
272
+ this.repairWrite = this.persistRepair().finally(() => { this.repairPersistencePending = false; });
273
+ void this.repairWrite.then(() => this.reconcile(false)).catch(error => this.invalidate(String(error)));
274
+ }
275
+ return;
276
+ }
277
+ this.hints.set(path, Date.now());
278
+ }
279
+ void this.reconcile(false);
280
+ }
281
+
282
+ private async persistRepair() {
283
+ const directory = join(this.agentDir, "runtime-read-repair");
284
+ await mkdir(directory, { recursive: true });
285
+ const path = join(directory, "subagents.json");
286
+ await writeFile(path + ".tmp", JSON.stringify({ version: 1, roots: [this.runs, this.archives, this.markers] }));
287
+ await rename(path + ".tmp", path);
288
+ }
289
+
290
+ private async *repairPaths(): AsyncGenerator<string[]> {
291
+ // Check known paths too: an incomplete walk never deletes unseen records.
292
+ // Discovery and failed-source repair can overlap these paths. Retry each
293
+ // source once per pass, not once per inventory route.
294
+ const seen = new Set<string>();
295
+ let batch: string[] = [];
296
+ for (const path of this.files.keys()) {
297
+ seen.add(path);
298
+ batch.push(path);
299
+ if (batch.length === 128) { yield batch; batch = []; }
300
+ }
301
+ // Failed first reads have no verified file entry, but still owe repair.
302
+ for (const path of this.sourceErrors.keys()) {
303
+ if (seen.has(path)) continue;
304
+ seen.add(path);
305
+ batch.push(path);
306
+ if (batch.length === 128) { yield batch; batch = []; }
307
+ }
308
+ for (const directory of [this.markers, this.archives, this.runs]) {
309
+ this.watchRootParent(directory);
310
+ let handle;
311
+ try {
312
+ const info = await stat(directory, { bigint: true });
313
+ const identity = `${info.dev}:${info.ino}`;
314
+ if (this.rootWatchIdentities.get(directory) !== identity) {
315
+ this.unwatchDirectory(directory);
316
+ if (directory === this.runs) for (const path of this.watchers.keys()) if (path.startsWith(this.runs + sep)) this.unwatchDirectory(path);
317
+ }
318
+ this.watchDirectory(directory);
319
+ handle = await opendir(directory);
320
+ } catch (error) {
321
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
322
+ this.unwatchDirectory(directory);
323
+ this.rootWatchIdentities.delete(directory);
324
+ if (directory === this.runs) for (const path of this.watchers.keys()) if (path.startsWith(this.runs + sep)) this.unwatchDirectory(path);
325
+ continue;
326
+ }
327
+ for await (const entry of handle) {
328
+ if (directory === this.runs ? safeId.test(entry.name) : /^[A-Za-z0-9_-]+\.json$/.test(entry.name)) {
329
+ const path = directory === this.runs ? join(directory, entry.name, "meta.json") : join(directory, entry.name);
330
+ if (seen.has(path)) continue;
331
+ seen.add(path);
332
+ batch.push(path);
333
+ if (batch.length === 128) { yield batch; batch = []; }
334
+ }
335
+ }
336
+ }
337
+ if (batch.length) yield batch;
338
+ }
339
+
131
340
  onChange(listener: () => void, scope?: WorkScope) {
341
+ if (scope) scope = { ...scope, cursor: undefined };
132
342
  const release = scope?.background ? this.background.retain(scope) : undefined;
133
- this.listeners.add(listener);
134
- return () => { this.listeners.delete(listener); release?.(); };
343
+ let revision = scope ? this.contentRevision(scope) : undefined;
344
+ const notify = () => {
345
+ const next = scope ? this.contentRevision(scope) : undefined;
346
+ if (scope && next === revision) return;
347
+ revision = next; listener();
348
+ };
349
+ this.listeners.add(notify);
350
+ return () => { this.listeners.delete(notify); release?.(); };
135
351
  }
136
- get backgroundMetrics() { return { ...this.background.metrics, scopes: this.background.scopeCount, history: this.background.historyMetrics }; }
137
- observation(reasons = this.livenessReasons({ refresh: false })) {
352
+ get backgroundMetrics() { return { ...this.background.metrics, registry: this.background.registryMetrics, changes: this.background.changeMetrics, scopes: this.background.scopeCount, history: this.background.historyMetrics }; }
353
+ observation(reasons = this.observationInitialized ? this.livenessReasons({ refresh: false }) : []) {
138
354
  return { status: this.state, reason: this.reason, observedAt: Date.now(), reasons };
139
355
  }
140
356
  livenessReasons(options: { refresh?: boolean } = {}) {
357
+ if (!this.observationInitialized) throw new Error(`Runtime observation ${this.state}: checkpoint coverage is unverified (including assignment and Background inboxes)`);
141
358
  return [
142
359
  ...[...this.projected.values()].filter(row => row.meta.status === "running"
143
360
  && processMatchesStart(row.meta.pid, row.meta.pidStartTime))
144
361
  .map(row => ({ kind: "worker", id: row.meta.id, owner: row.meta.callbackOrigin,
145
- lastProgressAt: row.meta.startedAt, nextDeadline: null, recovery: "observe-existing-worker" })),
362
+ lastProgressAt: row.meta.startedAt, nextDeadline: nextHealthDeadline(row.health, row.meta), recovery: "observe-existing-worker" })),
146
363
  ...this.background.livenessReasons(options),
147
364
  ];
148
365
  }
@@ -164,7 +381,7 @@ export class WorkReadModel {
164
381
  let timeout: ReturnType<typeof setTimeout> | undefined;
165
382
  try {
166
383
  return await Promise.race([
167
- this.reconcile().then(() => !!this.db.prepare("SELECT id FROM rows WHERE id = ?").get(id)),
384
+ (this.fileHint(this.runs, id), this.pending ?? Promise.resolve()).then(() => !!this.db.prepare("SELECT id FROM rows WHERE id = ?").get(id)),
168
385
  new Promise<false>(resolve => { timeout = setTimeout(() => resolve(false), 100); }),
169
386
  ]);
170
387
  } finally {
@@ -172,62 +389,324 @@ export class WorkReadModel {
172
389
  }
173
390
  }
174
391
  invalidate(reason: string) {
392
+ const changed = this.state !== "degraded" || this.reason !== reason;
175
393
  this.state = "degraded"; this.reason = reason;
176
- this.publish();
394
+ if (changed) this.publish();
177
395
  void this.reconcile();
178
396
  }
179
- private publish() { this.revision++; for (const listener of this.listeners) listener(); }
397
+ private scopeKey(scope: WorkScope) { return hash({ ...scope, cursor: undefined }); }
398
+ private scopeEntry(scope: WorkScope) {
399
+ const key = this.scopeKey(scope), now = Date.now();
400
+ for (const [id, entry] of this.scopes) if (now - entry.used >= 300000) this.scopes.delete(id);
401
+ let entry = this.scopes.get(key);
402
+ if (!entry) {
403
+ if (scope.cursor) throw new Error("resync_required: cursor retention expired");
404
+ if (this.scopes.size >= 128) this.scopes.delete(this.scopes.keys().next().value!);
405
+ entry = { scope: { ...scope, cursor: undefined }, token: ++this.scopeSequence, revision: 0, used: now, status: hash(this.scopeStatus(scope)) };
406
+ this.scopes.set(key, entry);
407
+ }
408
+ entry.used = now;
409
+ return entry;
410
+ }
411
+ contentRevision(scope: WorkScope = {}) {
412
+ if (scope.background) {
413
+ if (scope.backgroundHistory) return String(this.revision);
414
+ this.background.prepareQuery();
415
+ return hash([this.revision, this.background.sourceRevision(scope)]);
416
+ }
417
+ const entry = this.scopeEntry(scope);
418
+ return `${entry.token}:${entry.revision}`;
419
+ }
420
+ private matchesScope(scope: WorkScope, row: any, activity = false) {
421
+ if (!row) return false;
422
+ const m = row.meta;
423
+ if (scope.id && scope.id !== m.id) return false;
424
+ if (scope.sessionId) {
425
+ if (scope.sessionId !== m.callbackOrigin?.sessionId || scope.cwd !== (m.callbackOrigin?.cwd ?? m.cwd)) return false;
426
+ } else if (scope.cwd) {
427
+ const cwd = resolve(scope.cwd), prefix = cwd.endsWith(sep) ? cwd : cwd + sep;
428
+ if (m.cwd !== cwd && !m.cwd.startsWith(prefix)) return false;
429
+ }
430
+ const active = ["running", "waiting"].includes(row.assignment.state);
431
+ if (activity) return active;
432
+ return (scope.active === undefined || scope.active === active)
433
+ && (scope.pendingRecipient === undefined || scope.pendingRecipient === !!row.recipientPending)
434
+ && (scope.endedAfter === undefined || (m.endedAt ?? m.lostAt ?? Infinity) >= scope.endedAfter)
435
+ && (!scope.statuses?.length || scope.statuses.includes(row.assignment.state));
436
+ }
437
+ private publish(backgroundOnly = false) {
438
+ this.revision++;
439
+ for (const entry of this.scopes.values()) {
440
+ if (backgroundOnly) continue;
441
+ const status = hash(this.scopeStatus(entry.scope));
442
+ if (entry.status !== status || this.changedRows.some(({ before, after }) =>
443
+ this.matchesScope(entry.scope, before) || this.matchesScope(entry.scope, after)
444
+ || this.matchesScope(entry.scope, before, true) !== this.matchesScope(entry.scope, after, true))) entry.revision++;
445
+ entry.status = status;
446
+ }
447
+ this.changedRows = [];
448
+ for (const listener of this.listeners) listener();
449
+ }
450
+
451
+ /** Ordinary coordinator commits use the reverse scope index, not the source inventory. */
452
+ private refreshAssignments(baselineOnly = false) {
453
+ if ((!this.imported && !baselineOnly) || this.staged || this.reader.snapshotActive) return;
454
+ let release: (() => void) | undefined;
455
+ let revision: string | undefined;
456
+ try {
457
+ if (this.unsupportedAssignmentRevision && this.unsupportedAssignmentRevision === this.reader.revision()) return;
458
+ this.unsupportedAssignmentRevision = undefined;
459
+ const changes = this.reader.changes();
460
+ const snapshot = this.reader.beginSnapshot(); release = snapshot.release;
461
+ revision = snapshot.revision;
462
+ if (changes.has("*")) {
463
+ const key = `${this.reader.changeMetrics.generation}:${changes.get("*")}`;
464
+ if (baselineOnly) {
465
+ this.assignmentBaseline = { key, seq: changes.get("*")! };
466
+ this.coordinator = snapshot.revision;
467
+ return;
468
+ }
469
+ if (this.assignmentBaseline?.key === key) return;
470
+ this.imported = false; this.repairOwed = true;
471
+ if (!this.sourceErrors.size) { this.state = "rebuilding"; this.reason = "Assignment source baseline is rebuilding."; }
472
+ this.publish(); return;
473
+ }
474
+ const selected = new Map<string, any>();
475
+ const select = this.db.prepare("SELECT r.payload FROM assignment_members m JOIN rows r ON r.id=m.id WHERE m.scope=?");
476
+ for (const scope of changes.keys()) for (const record of select.all(scope)) {
477
+ const row = JSON.parse(record.payload); selected.set(row.meta.id, row);
478
+ }
479
+ const project = createAssignmentProjector({ attempts: [...selected.values()].map(row => row.meta), observe: (owner: any) => this.reader.read(owner) });
480
+ const updated: any[] = [];
481
+ for (const row of selected.values()) {
482
+ const meta = row.meta;
483
+ const assignment = project(meta, this.processes.get(meta.id) ?? meta.status);
484
+ if (!assignment.verified) throw new Error(`Assignment observation is unverified: ${meta.id}`);
485
+ const outcome = meta.assignment ? this.reader.read({ ...meta.assignment.owner, assignmentId: meta.assignment.assignmentId }).outcome : undefined;
486
+ const recipientPending = Boolean(row.failurePending || meta.timing?.pendingWakes?.length
487
+ || (meta.status === "orphaned" && meta.orphanedCallbackSentAt === undefined && meta.orphanedCallbackSuppressedAt === undefined)
488
+ || (meta.status === "lost" && meta.lostCallbackSentAt === undefined && meta.lostCallbackSuppressedAt === undefined)
489
+ || (meta.callback !== false && (meta.assignment ? outcome && !outcome.deliveryReceipt && !outcome.disposition
490
+ : meta.completionCallbackPendingAt !== undefined && meta.completionCallbackSentAt === undefined && meta.completionCallbackSuppressedAt === undefined)));
491
+ updated.push({ ...row, assignment, recipientPending, sourceRevision: hash([meta, assignment.revision, row.display, row.health, recipientPending, row.failurePending, this.failureJournals.get(meta.id)]) });
492
+ }
493
+ let changed = false;
494
+ const changedRows: WorkReadModel["changedRows"] = [];
495
+ this.db.exec("SAVEPOINT assignment_refresh");
496
+ try {
497
+ const update = this.db.prepare("UPDATE rows SET state=?, active=?, recipient_pending=?, payload=? WHERE id=?");
498
+ for (const row of updated) {
499
+ if (row.sourceRevision === this.projected.get(row.meta.id)?.sourceRevision) continue;
500
+ update.run(row.assignment.state, ["running", "waiting"].includes(row.assignment.state) ? 1 : 0, row.recipientPending ? 1 : 0, JSON.stringify(row), row.meta.id);
501
+ changedRows.push({ before: this.projected.get(row.meta.id), after: row });
502
+ changed = true;
503
+ }
504
+ this.db.exec("RELEASE assignment_refresh");
505
+ } catch (error) { this.db.exec("ROLLBACK TO assignment_refresh; RELEASE assignment_refresh"); throw error; }
506
+ // A crash after application but before acknowledgement safely repeats this batch.
507
+ this.reader.acknowledgeChanges(changes, false);
508
+ snapshot.commit();
509
+ for (const row of updated) this.projected.set(row.meta.id, row);
510
+ if (this.reader.changeMetrics.more || this.reader.changeMetrics.pending) this.dirty = true;
511
+ this.coordinator = snapshot.revision;
512
+ this.counters.assignmentProjections += updated.length; this.counters.projections += updated.length;
513
+ this.invalidations.assignmentInput += updated.length;
514
+ this.changedRows = changedRows;
515
+ if (this.assignmentFault) {
516
+ this.state = this.assignmentFault.state; this.reason = this.assignmentFault.reason;
517
+ this.assignmentFault = undefined; this.changedRows = []; changed = true;
518
+ }
519
+ if (changed) this.publish();
520
+ } catch (error) {
521
+ release?.(); release = undefined;
522
+ if (!this.projected.size) return;
523
+ // A coordinator has never been required for plain archived/log-only runs.
524
+ // Losing an already observed database still degrades the existing coverage.
525
+ if ((error as NodeJS.ErrnoException).code === "ENOENT" && this.coordinator === "unknown") return;
526
+ if (error instanceof Error && error.message === "Unsupported assignment source schema") this.unsupportedAssignmentRevision = revision;
527
+ this.assignmentFault ??= { state: this.state, reason: this.reason };
528
+ if (/no such table: (?:coordinator_source\.)?assignment_change_source$/.test(String(error))) {
529
+ // Old sources have no feed. Finish one budgeted compatibility pass;
530
+ // continuous legacy writes do not restart a pass already in progress.
531
+ this.imported = false; this.repairOwed = true; this.state = "rebuilding";
532
+ } else this.state = "degraded";
533
+ this.reason = String(error).slice(0, 512); this.publish();
534
+ } finally { release?.(); }
535
+ }
180
536
 
181
- reconcile(): Promise<void> {
182
- if (this.closed) return Promise.resolve();
183
- if (this.pending) { this.dirty = true; return this.pending; }
537
+ private scopeStatus(scope: WorkScope): { status: WorkSnapshot["status"]; reason?: string } {
538
+ const race = this.sourceRace;
539
+ // Only a validated, entity-attributed retry can leave another scope ready.
540
+ // Root, coordinator, unattributed and initial-import failures stay global.
541
+ if (this.imported && this.state === "degraded" && race && this.reason === race.reason
542
+ && [...this.sourceErrors.keys()].every(path => race.paths.has(path))
543
+ && !race.rows.some(row => this.matchesScope({ id: scope.id, cwd: scope.cwd, sessionId: scope.sessionId }, row))) {
544
+ return { status: "ready" };
545
+ }
546
+ return { status: this.state, reason: this.reason };
547
+ }
548
+
549
+ private rejectUnsupportedAssignmentRevision(): boolean {
550
+ let release: (() => void) | undefined;
551
+ try {
552
+ if (this.unsupportedAssignmentRevision) {
553
+ if (this.unsupportedAssignmentRevision === this.reader.revision()) return true;
554
+ this.unsupportedAssignmentRevision = undefined;
555
+ }
556
+ const connection = this.reader.connection(false);
557
+ const supported = (version: unknown) => version === undefined || (typeof version === "string" && ["1", "2", "3", "4"].includes(version));
558
+ if (!connection || supported(connection.prepare("SELECT value FROM schema_meta WHERE key='schema_version'").get()?.value)) return false;
559
+ const snapshot = this.reader.beginSnapshot(); release = snapshot.release;
560
+ const version = this.reader.connection(false).prepare("SELECT value FROM schema_meta WHERE key='schema_version'").get()?.value;
561
+ if (!supported(version)) {
562
+ this.unsupportedAssignmentRevision = snapshot.revision;
563
+ const reason = "Unsupported assignment source schema";
564
+ const changed = this.state !== "degraded" || this.reason !== reason;
565
+ this.state = "degraded"; this.reason = reason;
566
+ if (changed) this.publish();
567
+ return true;
568
+ }
569
+ } catch {
570
+ // Missing/initializing sources still follow the ordinary verification path.
571
+ this.unsupportedAssignmentRevision = undefined;
572
+ } finally { release?.(); }
573
+ return false;
574
+ }
575
+
576
+ reconcile(drain = true): Promise<void> {
577
+ if (this.closed || this.conflictRetry) return Promise.resolve();
578
+ if (this.pending) {
579
+ return drain && this.observationInitialized ? this.pending.then(() => this.reconcile()) : this.pending;
580
+ }
581
+ const release = this.budget.enter("repair");
582
+ if (!release) return Promise.resolve();
184
583
  this.pending = (async () => {
185
- for (let pass = 0; pass < 2; pass++) {
186
- this.dirty = false;
187
- await this.scan();
188
- if (!this.dirty || this.closed) break;
584
+ await this.watchRegistrations();
585
+ if (this.closed) return;
586
+ if (!this.observationInitialized) {
587
+ if (!this.checkpointAttemptAllowed || this.checkpointFailure) return;
588
+ this.checkpointAttemptAllowed = false;
589
+ this.initialization.attempts++;
590
+ let initialized: boolean;
591
+ try {
592
+ if (this.db.isTransaction) throw new Error("Derived observation initialization requires an unpinned owner");
593
+ initialized = this.checkpoints.initialize();
594
+ if (initialized) this.reader ??= createAssignmentReader(join(this.agentDir, "operation-coordinator.sqlite"),
595
+ join(this.agentDir, "runtime-read-repair", "assignments.sqlite"), this.db, { composed: true });
596
+ if (initialized) this.background.initialize();
597
+ } catch (error) {
598
+ if (isSqliteLockContention(error)) initialized = false;
599
+ else { this.checkpointFailure = true; throw error; }
600
+ }
601
+ if (!initialized) {
602
+ this.initialization.contentions++;
603
+ const reason = "Derived checkpoint, assignment or Background inbox acquisition is contended; source coverage remains unverified.";
604
+ if (this.reason !== reason) { this.state = "rebuilding"; this.reason = reason; this.publish(); }
605
+ return;
606
+ }
189
607
  }
190
- })().finally(() => {
608
+ let resetRepair = drain;
609
+ do {
610
+ this.dirty = false;
611
+ // Background progress is independent of whether Subagent repair finds files.
612
+ this.inventoryPhase?.("background");
613
+ if (this.background.refresh()) this.publish(true);
614
+ if (this.rejectUnsupportedAssignmentRevision()) break;
615
+ this.refreshAssignments();
616
+ // Metadata repair cannot verify an incompatible coordinator. Keep its
617
+ // obligations and last verified rows until a different source revision.
618
+ if (this.unsupportedAssignmentRevision) break;
619
+ if (resetRepair && this.repair) { await this.repair.return(undefined); this.repair = undefined; }
620
+ resetRepair = false;
621
+ if (this.hints.size) {
622
+ const entries = workPage(this.hints);
623
+ for (const [path, queued] of entries) { this.hints.delete(path); this.scheduling.maxQueueAgeMs = Math.max(this.scheduling.maxQueueAgeMs, Date.now() - queued); }
624
+ this.scheduling.entityBatches++;
625
+ const started = performance.now();
626
+ await this.measuredScan("entity", entries.map(([path]) => path));
627
+ this.scheduling.maxPublicationMs = Math.max(this.scheduling.maxPublicationMs, performance.now() - started);
628
+ if (this.sourceConflicts > 1) break;
629
+ }
630
+ if (!this.repair && this.imported && !drain && !this.repairOwed) {
631
+ if (this.hints.size) { await yieldTurn(); continue; }
632
+ break;
633
+ }
634
+ this.repair ??= this.repairPaths();
635
+ const next = await this.repair.next();
636
+ if (next.done) {
637
+ await this.watchRegistrations();
638
+ this.repair = undefined; this.repairOwed = false;
639
+ // An empty metadata inventory still needs a journal baseline before
640
+ // later exact hints can be treated as incremental updates.
641
+ if (!this.imported && !this.assignmentBaseline && !this.files.size && !this.sourceErrors.size) this.refreshAssignments(true);
642
+ if (this.assignmentBaseline && !this.sourceErrors.size && ![...this.projected.values()].some(row => !row.assignment.verified)) this.reader.acknowledgeChanges(new Map([["*", this.assignmentBaseline.seq]]), true);
643
+ if (!this.imported) {
644
+ this.imported = true;
645
+ const degraded = this.state === "degraded" || this.sourceErrors.size || [...this.projected.values()].some(row => !row.assignment.verified);
646
+ this.state = degraded ? "degraded" : "ready";
647
+ this.reason = this.state === "ready" ? undefined : this.sourceErrors.values().next().value ?? this.reason ?? "Some assignment sources could not be verified.";
648
+ this.publish();
649
+ }
650
+ }
651
+ else { this.scheduling.repairBatches++; this.scheduling.repairEntries += next.value.length; await this.measuredScan("repair", next.value); }
652
+ await yieldTurn();
653
+ if (this.closed || this.sourceConflicts > 1 || (!drain && !this.hints.size)) break;
654
+ } while (this.repair || this.hints.size);
655
+ })().catch(error => {
656
+ this.repair = undefined; this.state = "degraded"; this.reason = String(error).slice(0, 512); this.publish();
657
+ }).finally(() => {
658
+ this.inventoryPhase?.("idle");
659
+ release();
191
660
  this.pending = undefined;
192
- if (this.dirty && !this.closed) { this.dirty = false; void this.reconcile(); }
661
+ if (this.observationInitialized && (this.hints.size || this.dirty) && !this.closed && !this.unsupportedAssignmentRevision) {
662
+ this.dirty = false;
663
+ if (this.sourceConflicts > 1) {
664
+ this.conflictRetry = setTimeout(() => {
665
+ this.conflictRetry = undefined;
666
+ void this.reconcile(false);
667
+ }, this.conflictDelay);
668
+ this.conflictRetry.unref();
669
+ this.conflictDelay = Math.min(1000, this.conflictDelay * 2);
670
+ } else void this.reconcile(false);
671
+ }
193
672
  });
194
673
  return this.pending;
195
674
  }
196
675
 
197
- private async scan() {
676
+ private async measuredScan(kind: "entity" | "repair", paths: string[]) {
677
+ const before = { stats: this.sourceStats, metadataReads: this.counters.metadataReads, logBytes: logReadMetrics.bytes, logReads: logReadMetrics.reads };
678
+ await this.scan(paths);
679
+ const counter = this.sourceWork[kind]; counter.batches++; counter.paths += paths.length;
680
+ counter.stats += this.sourceStats - before.stats; counter.metadataReads += this.counters.metadataReads - before.metadataReads;
681
+ counter.logBytes += logReadMetrics.bytes - before.logBytes; counter.logReads += logReadMetrics.reads - before.logReads;
682
+ }
683
+
684
+ private async watchRegistrations() {
685
+ await Promise.all([...this.watchers.values(), ...[...this.rootParents.values()].map(value => value.watcher)].map(watcher => watcher.ready));
686
+ }
687
+
688
+ private async scan(paths: string[]) {
689
+ let sourceConflict = false;
690
+ this.assignmentFault = undefined;
691
+ const sourceStat: typeof stat = ((...args: any[]) => { this.sourceStats++; return (stat as any)(...args); }) as typeof stat;
198
692
  this.counters.inventories++;
199
- if (this.background.refresh()) this.publish();
200
693
  let releaseCoordinator: (() => void) | undefined;
694
+ let commitCoordinator: (() => void) | undefined;
695
+ const checkpointWrites: Array<[string, unknown]> = [];
696
+ const parseBefore = new Map(this.parseStates), healthBefore = new Map(this.healthStates);
697
+ let sourceRace: WorkReadModel["sourceRace"];
201
698
  const baseline = this.staged ?? { files: this.files, projected: this.projected, logs: this.logs, failureJournals: this.failureJournals, processes: this.processes,
202
- healthRevision: this.healthRevision, coordinator: this.coordinator, coordinatorConversations: this.coordinatorConversations };
699
+ healthRevision: this.healthRevision, coordinator: this.coordinator };
203
700
  try {
204
- const next = new Map<string, { signature: string; meta: any }>();
701
+ this.inventoryPhase?.("metadata");
702
+ const next = new Map(baseline.files);
703
+ const failedPaths = new Map<string, string>();
704
+ const malformedPaths = new Set<string>();
205
705
  let batch = 0;
206
706
  let sliceStarted = performance.now();
207
707
  for (const [directory, archived] of [[this.markers, true], [this.archives, true], [this.runs, false]] as const) {
208
- let names: string[];
209
- try { names = await readdir(directory); }
210
- catch (error) {
211
- if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
212
- this.unwatchDirectory(directory); this.rootWatchIdentities.delete(directory);
213
- if (!archived) for (const watched of this.watchers.keys()) if (watched.startsWith(this.runs + sep)) this.unwatchDirectory(watched);
214
- continue;
215
- }
216
- // Three root identities per inventory, independent of archive/client
217
- // cardinality. A root can be replaced without an observed ENOENT gap.
218
- const rootInfo = await stat(directory, { bigint: true });
219
- const rootIdentity = `${rootInfo.dev}:${rootInfo.ino}`;
220
- const previousRootIdentity = this.rootWatchIdentities.get(directory);
221
- if (previousRootIdentity !== undefined && previousRootIdentity !== rootIdentity) {
222
- this.unwatchDirectory(directory);
223
- if (!archived) for (const watched of this.watchers.keys()) if (watched.startsWith(this.runs + sep)) this.unwatchDirectory(watched);
224
- }
225
- this.rootWatchIdentities.set(directory, rootIdentity);
226
- this.watchDirectory(directory);
227
- if (!archived) {
228
- const present = new Set(names.filter(name => safeId.test(name)).map(name => join(directory, name)));
229
- for (const watched of this.watchers.keys()) if (watched.startsWith(this.runs + sep) && !present.has(watched)) this.unwatchDirectory(watched);
230
- }
708
+ const names = paths.filter(path => archived ? path.startsWith(directory + sep) && !path.slice(directory.length + 1).includes(sep)
709
+ : path.startsWith(directory + sep)).map(path => archived ? path.slice(directory.length + 1) : path.slice(directory.length + 1).split(sep)[0]!);
231
710
  // Bound filesystem concurrency without serializing every archive round trip.
232
711
  const candidates = names.filter(name => safeId.test(archived ? name.replace(/\.json$/, "") : name)
233
712
  && (!archived || name.endsWith(".json")));
@@ -236,7 +715,7 @@ export class WorkReadModel {
236
715
  const observations = await Promise.all(group.map(async name => {
237
716
  if (!archived) this.watchDirectory(join(directory, name));
238
717
  const path = archived ? join(directory, name) : join(directory, name, "meta.json");
239
- try { return { info: await stat(path, { bigint: true }) }; }
718
+ try { return { info: await sourceStat(path, { bigint: true }) }; }
240
719
  catch (error) { return { error }; }
241
720
  }));
242
721
  for (const [index, name] of group.entries()) {
@@ -247,8 +726,9 @@ export class WorkReadModel {
247
726
  if (!observation.info) throw observation.error;
248
727
  const info = observation.info;
249
728
  const signature = `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
250
- let entry = baseline.files.get(path);
729
+ let entry = next.get(path);
251
730
  if (entry?.signature !== signature) {
731
+ if (info.size > 1024n * 1024n) throw new Error(`Run metadata exceeds the 1 MiB observation budget: ${id}`);
252
732
  this.counters.metadataReads++;
253
733
  const raw = await readFile(path, "utf8");
254
734
  if (directory === this.markers) {
@@ -264,7 +744,29 @@ export class WorkReadModel {
264
744
  }
265
745
  next.set(path, entry!);
266
746
  } catch (error) {
267
- if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
747
+ if (!archived && error instanceof SyntaxError && this.files.has(path)) malformedPaths.add(path);
748
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {
749
+ try {
750
+ await sourceStat(directory);
751
+ next.delete(path);
752
+ if (!archived) {
753
+ // A mkdir notification can arrive before its metadata commit.
754
+ // Retire the inode watcher only when the directory is gone.
755
+ try { await sourceStat(join(directory, name)); }
756
+ catch (error) {
757
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
758
+ this.unwatchDirectory(join(directory, name));
759
+ }
760
+ }
761
+ } catch {
762
+ failedPaths.set(path, `Source directory unavailable; retaining verified records: ${directory}`);
763
+ }
764
+ } else failedPaths.set(path, String(error).slice(0, 512));
765
+ if (failedPaths.has(path)) {
766
+ const verified = this.files.get(path);
767
+ if (verified) next.set(path, verified);
768
+ else next.delete(path);
769
+ }
268
770
  }
269
771
  if (++batch % 256 === 0 || performance.now() - sliceStarted >= 8) {
270
772
  await yieldTurn(); sliceStarted = performance.now();
@@ -273,12 +775,26 @@ export class WorkReadModel {
273
775
  }
274
776
  }
275
777
  }
778
+ this.inventoryPhase?.("coordinator");
779
+ let assignmentChanges: Map<string, string> | undefined;
780
+ try { assignmentChanges = this.reader.changes(); } catch { /* Legacy sources retain bounded repair. */ }
276
781
  let coordinator: string;
277
782
  try {
278
783
  const snapshot = this.reader.beginSnapshot();
279
- coordinator = snapshot.revision; releaseCoordinator = snapshot.release;
784
+ coordinator = snapshot.revision; releaseCoordinator = snapshot.release; commitCoordinator = snapshot.commit;
280
785
  } catch { coordinator = "unknown"; }
281
- const coordinatorConversations = coordinator === baseline.coordinator ? baseline.coordinatorConversations : this.reader.conversationRevisions();
786
+ if (assignmentChanges?.has("*")) {
787
+ const seq = assignmentChanges.get("*")!;
788
+ const key = `${this.reader.changeMetrics.generation}:${seq}`;
789
+ if (this.assignmentBaseline?.key !== key) {
790
+ this.assignmentBaseline = { key, seq };
791
+ if (this.imported) {
792
+ this.imported = false; this.repairOwed = true;
793
+ await this.repair?.return(undefined); this.repair = undefined;
794
+ }
795
+ }
796
+ }
797
+ this.inventoryPhase?.("log-stats");
282
798
  const logs = new Map<string, string>();
283
799
  const failureJournals = new Map<string, string>();
284
800
  const processes = new Map<string, string>();
@@ -286,63 +802,169 @@ export class WorkReadModel {
286
802
  const terminalLogChanges: string[] = [];
287
803
  for (const [path, entry] of next) {
288
804
  if (!path.startsWith(this.runs + sep)) continue;
805
+ if (failedPaths.has(path)) {
806
+ const id = entry.meta.id;
807
+ if (this.logs.has(id)) logs.set(id, this.logs.get(id)!);
808
+ if (this.failureJournals.has(id)) failureJournals.set(id, this.failureJournals.get(id)!);
809
+ if (this.processes.has(id)) processes.set(id, this.processes.get(id)!);
810
+ continue;
811
+ }
812
+ if (!paths.includes(path)) {
813
+ const id = entry.meta.id;
814
+ if (baseline.logs.has(id)) logs.set(id, baseline.logs.get(id)!);
815
+ if (baseline.failureJournals.has(id)) failureJournals.set(id, baseline.failureJournals.get(id)!);
816
+ if (baseline.processes.has(id)) processes.set(id, baseline.processes.get(id)!);
817
+ continue;
818
+ }
289
819
  let signature = baseline.logs.get(entry.meta.id);
290
820
  {
291
821
  try {
292
- const info = await stat(join(this.runs, entry.meta.id, "output.log"), { bigint: true });
822
+ const info = await sourceStat(join(this.runs, entry.meta.id, "output.log"), { bigint: true });
293
823
  signature = `${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
294
824
  } catch (error) { signature = (error as NodeJS.ErrnoException).code === "ENOENT" ? "missing" : "unverified"; }
295
825
  }
296
826
  logs.set(entry.meta.id, signature);
297
827
  if ((signature !== this.logs.get(entry.meta.id) || this.files.get(path)?.meta.status !== entry.meta.status) && entry.meta.status !== "running"
298
828
  && entry.meta.management?.root === this.agentDir) terminalLogChanges.push(entry.meta.id);
299
- if (signature !== baseline.logs.get(entry.meta.id)) logFamilies.add(JSON.stringify([entry.meta.sessionId, entry.meta.cwd]));
829
+ if (signature !== baseline.logs.get(entry.meta.id)) logFamilies.add(entry.meta.id);
300
830
  const failureSignature = (await Promise.all(["failures.jsonl", "failures.jsonl.observed"].map(async name => {
301
- try { const info = await stat(join(this.runs, entry.meta.id, name), { bigint: true }); return `${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`; }
831
+ try { const info = await sourceStat(join(this.runs, entry.meta.id, name), { bigint: true }); return `${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`; }
302
832
  catch (error) { return (error as NodeJS.ErrnoException).code === "ENOENT" ? "missing" : "unverified"; }
303
833
  }))).join(":");
304
834
  failureJournals.set(entry.meta.id, failureSignature);
305
- if (failureSignature !== baseline.failureJournals.get(entry.meta.id)) logFamilies.add(JSON.stringify([entry.meta.sessionId, entry.meta.cwd]));
835
+ if (failureSignature !== baseline.failureJournals.get(entry.meta.id)) logFamilies.add(entry.meta.id);
306
836
 
307
837
  const status = effectiveStatus(entry.meta); processes.set(entry.meta.id, status);
308
- if (status !== baseline.processes.get(entry.meta.id)) logFamilies.add(JSON.stringify([entry.meta.sessionId, entry.meta.cwd]));
838
+ if (status !== baseline.processes.get(entry.meta.id)) logFamilies.add(entry.meta.id);
309
839
  if (performance.now() - sliceStarted >= 8) { await yieldTurn(); sliceStarted = performance.now(); }
310
840
  }
311
841
  const healthConfig = await readHealthConfig(this.agentDir, next.size > 0);
842
+ if (healthConfig.revision !== baseline.healthRevision) this.counters.healthConfigInvalidations++;
312
843
  const changed = next.size !== baseline.files.size || [...next].some(([path, entry]) => baseline.files.get(path)?.signature !== entry.signature);
313
- if (!this.staged && !changed && !logFamilies.size && coordinator === this.coordinator && healthConfig.revision === this.healthRevision && this.state === "ready") return;
844
+ const now = Date.now();
845
+ const deadlineExpired = [...baseline.projected.values()].some(row => healthDeadlineExpired(row, now));
846
+ const rawDirectories = [...new Set(paths.filter(path => path.startsWith(this.runs + sep) && next.has(path)).map(path => dirname(path)))];
847
+ const rearmRawDirectories = () => {
848
+ if (!rawDirectories.length) return;
849
+ this.watchDirectory(this.runs);
850
+ for (const directory of rawDirectories) this.watchDirectory(directory);
851
+ };
852
+ // A delayed mkdir notification may retire a watch during the awaited reads.
853
+ rearmRawDirectories();
854
+ await this.watchRegistrations();
855
+ if (!this.staged && !changed && !failedPaths.size && !this.sourceErrors.size && !logFamilies.size && !assignmentChanges?.size && !deadlineExpired && coordinator === this.coordinator && healthConfig.revision === this.healthRevision && !healthConfig.reason && this.state === "ready") return;
314
856
  const metas = new Map<string, any>();
315
857
  const markers = new Map([...next].filter(([path]) => path.startsWith(this.markers + sep)).map(([, entry]) => [entry.meta.sessionId, entry.meta]));
316
858
  for (const [path, entry] of next) {
317
859
  if (path.startsWith(this.markers + sep)) continue;
860
+ // Compact archives omit volatile delivery markers. A verified live
861
+ // record wins independently of which source was discovered last.
862
+ if (path.startsWith(this.archives + sep) && next.has(join(this.runs, entry.meta.id, "meta.json"))) continue;
318
863
  const marker = markers.get(entry.meta.sessionId);
319
864
  if (path.startsWith(this.archives + sep) && marker && marker.attemptId !== entry.meta.id && marker.startedAt >= entry.meta.startedAt) continue;
320
865
  metas.set(entry.meta.id, entry.meta);
321
866
  }
867
+ this.inventoryPhase?.("projection");
322
868
  const attempts = [...metas.values()];
323
- const affected = new Set<string>(logFamilies);
324
- const family = (meta: any) => JSON.stringify([meta.sessionId, meta.cwd]);
869
+ const changedAttempts = new Set<any>();
325
870
  for (const [path, entry] of [...baseline.files, ...next]) {
326
- if (baseline.files.get(path)?.signature !== next.get(path)?.signature) affected.add(family(entry.meta));
871
+ if (baseline.files.get(path)?.signature !== next.get(path)?.signature) {
872
+ if (path.startsWith(this.markers + sep)) {
873
+ for (const meta of attempts) if (meta.sessionId === entry.meta.sessionId) changedAttempts.add(meta);
874
+ } else changedAttempts.add(entry.meta);
875
+ }
327
876
  }
328
- if (coordinator !== baseline.coordinator) for (const meta of attempts) {
877
+ const assignmentGeneration = this.reader.changeMetrics.generation;
878
+ // An unpublished retry may reuse a verified projection only at the same
879
+ // durable source generation and per-scope position. Receipt stays pending.
880
+ const changedScope = (scope: string) => assignmentChanges?.has(scope)
881
+ && (!this.staged || this.staged.assignmentGeneration !== assignmentGeneration
882
+ || this.staged.assignmentChanges?.get(scope) !== assignmentChanges.get(scope));
883
+ for (const meta of attempts) {
329
884
  if (!(meta.assignment || meta.operations || meta.park)) continue;
330
- const owner = JSON.stringify([meta.operations?.conversationId ?? meta.sessionId, meta.operations?.workspace ?? meta.cwd]);
331
- if (!coordinatorConversations || !baseline.coordinatorConversations ||
332
- coordinatorConversations.get(owner) !== baseline.coordinatorConversations.get(owner)) affected.add(family(meta));
885
+ const session = meta.assignment?.owner?.sessionId ?? meta.operations?.conversationId ?? meta.sessionId;
886
+ const workspace = meta.assignment?.owner?.workspace ?? meta.operations?.workspace ?? meta.cwd;
887
+ if ((changedScope("*") && paths.some(path => next.get(path)?.meta.id === meta.id))
888
+ || changedScope(JSON.stringify([session, workspace, meta.assignment?.assignmentId ?? null]))
889
+ || changedScope(JSON.stringify([session, workspace, null]))
890
+ || (!assignmentChanges && paths.some(path => next.get(path)?.meta.id === meta.id))) changedAttempts.add(meta);
333
891
  }
892
+ const affected = await affectedAttempts(
893
+ [...baseline.projected.values()].map(row => row.meta).concat(attempts), changedAttempts);
894
+ if (this.closed) return;
334
895
  const project = createAssignmentProjector({ attempts, observe: (owner: any) => this.reader.read(owner) });
896
+ const touched = new Set(paths.map(path => next.get(path)?.meta.id));
335
897
  const rows = [];
336
898
  for (const meta of attempts) {
337
899
  let row = baseline.projected.get(meta.id);
338
- if (!row || !row.assignment.verified || healthConfig.revision !== baseline.healthRevision || affected.has(family(meta))) {
900
+ const assignmentChanged = !row || (!row.assignment.verified && touched.has(meta.id)) || affected.has(meta.id) || processes.get(meta.id) !== baseline.processes.get(meta.id);
901
+ const logChanged = !row || logs.get(meta.id) !== baseline.logs.get(meta.id);
902
+ const failureChanged = !row || failureJournals.get(meta.id) !== baseline.failureJournals.get(meta.id);
903
+ const deadlineChanged = row && healthDeadlineExpired(row, now);
904
+ if (row && !assignmentChanged && !logChanged && !failureChanged && (healthConfig.revision !== baseline.healthRevision || deadlineChanged)) {
905
+ if (healthConfig.revision !== baseline.healthRevision) this.invalidations.healthConfig++;
906
+ if (deadlineChanged) this.invalidations.healthDeadline++;
907
+ this.counters.healthRecomputations++;
908
+ const health = healthWithThresholds(row.health, healthConfig.config, meta);
909
+ row = { ...row, health, sourceRevision: hash([meta, row.assignment.revision, row.display, health, row.recipientPending, row.failurePending, failureJournals.get(meta.id)]) };
910
+ } else if (assignmentChanged || logChanged || failureChanged) {
911
+ if (!row) this.invalidations.initial++;
912
+ else {
913
+ if (affected.has(meta.id)) this.invalidations.assignmentInput++;
914
+ if (!row.assignment.verified) this.invalidations.unverified++;
915
+ if (processes.get(meta.id) !== baseline.processes.get(meta.id)) this.invalidations.process++;
916
+ if (logChanged) this.invalidations.log++;
917
+ if (failureChanged) this.invalidations.failureAttention++;
918
+ if (healthConfig.revision !== baseline.healthRevision) this.invalidations.healthConfig++;
919
+ if (deadlineChanged) this.invalidations.healthDeadline++;
920
+ }
339
921
  this.counters.projections++;
340
- const assignment = project(meta, processes.get(meta.id) ?? meta.status);
341
- const parsed = logs.get(meta.id) && logs.get(meta.id) !== "missing" ? parseRun(meta.id, { logPath: join(this.runs, meta.id, "output.log") }) : undefined;
342
- const display = { spend: parsed ? fmtSpend(parsed.usage) : "", tool: parsed?.toolCalls.at(-1) ?? "" };
343
- const health = logs.has(meta.id) ? { ...extractChildEventFactsFromLog(meta.id, { logPath: join(this.runs, meta.id, "output.log") }), thresholds: healthThresholdsForConfig(healthConfig.config) } : undefined;
922
+ if (assignmentChanged) this.counters.assignmentProjections++;
923
+ const assignment = assignmentChanged ? project(meta, processes.get(meta.id) ?? meta.status) : row!.assignment;
924
+ let display = row?.display, health = row?.health;
925
+ if (logChanged) withLogReadBatch(() => {
926
+ this.counters.logProjections++; this.counters.healthProjections++;
927
+ const logPath = join(this.runs, meta.id, "output.log");
928
+ const priorDisplay = parseBefore.get(logPath), priorHealth = healthBefore.get(logPath);
929
+ if (priorDisplay && this.parseStates.get(logPath) === priorDisplay)
930
+ this.parseStates.set(logPath, decodeParseLogState(structuredClone(encodeParseLogState(priorDisplay))));
931
+ if (priorHealth && this.healthStates.get(logPath) === priorHealth)
932
+ this.healthStates.set(logPath, decodeHealthLogState(structuredClone(encodeHealthLogState(priorHealth))));
933
+ if (!this.parseStates.has(logPath) || !this.healthStates.has(logPath)) {
934
+ const saved = this.checkpoints.load(logPath);
935
+ if (saved) {
936
+ try {
937
+ if (!Number.isSafeInteger(saved.display.cursor.offset) || !Number.isSafeInteger(saved.health.cursor.offset)) throw new Error("Invalid checkpoint offset");
938
+ this.parseStates.set(logPath, decodeParseLogState(saved.display));
939
+ this.healthStates.set(logPath, decodeHealthLogState(saved.health));
940
+ } catch { this.parseStates.delete(logPath); this.healthStates.delete(logPath); }
941
+ }
942
+ }
943
+ const parsed = logs.get(meta.id) && logs.get(meta.id) !== "missing" ? parseRunDisplay(meta.id, { logPath, states: this.parseStates, summaryOnly: true }) : undefined;
944
+ display = { spend: parsed ? fmtSpend(parsed.usage) : "", tool: parsed?.tool ?? "" };
945
+ health = logs.has(meta.id) ? extractChildEventFactsFromLog(meta.id, { logPath, states: this.healthStates }) : undefined;
946
+ const displayState = this.parseStates.get(logPath), healthState = this.healthStates.get(logPath);
947
+ display = { ...display!, diagnostics: parsed?.diagnostics, coverage: displayState ? {
948
+ start: displayState.cursor.coverageStart ?? 0, offset: displayState.cursor.offset,
949
+ totalBytes: displayState.totalBytes, missing: displayState.cursor.missing,
950
+ complete: !displayState.catchingUp && !displayState.windowTruncated && displayState.cursor.offset === displayState.totalBytes,
951
+ } : undefined };
952
+ if (health && healthState) health = { ...health, coverage: { start: healthState.cursor.coverageStart ?? 0,
953
+ offset: healthState.cursor.offset, missing: healthState.cursor.missing } };
954
+ if (displayState?.catchingUp) logs.set(meta.id, `${logs.get(meta.id)}:catching-up`);
955
+ if (displayState && healthState) checkpointWrites.push([logPath, {
956
+ display: encodeParseLogState(displayState), health: encodeHealthLogState(healthState),
957
+ }]);
958
+ while (this.parseStates.size > 64) this.parseStates.delete(this.parseStates.keys().next().value);
959
+ while (this.healthStates.size > 64) this.healthStates.delete(this.healthStates.keys().next().value);
960
+ });
961
+ if (logChanged || assignmentChanged || deadlineChanged || healthConfig.revision !== baseline.healthRevision) {
962
+ this.counters.healthRecomputations++;
963
+ health = healthWithThresholds(health, healthConfig.config, meta);
964
+ }
344
965
  const outcome = meta.assignment ? this.reader.read({ ...meta.assignment.owner, assignmentId: meta.assignment.assignmentId }).outcome : undefined;
345
- const failurePending = meta.callback !== false && failureJournals.has(meta.id) && Boolean(pendingFailureAttention(
966
+ if (failureChanged || assignmentChanged) this.counters.failureProjections++;
967
+ const failurePending = !failureChanged && !assignmentChanged ? row!.failurePending : meta.callback !== false && failureJournals.has(meta.id) && Boolean(pendingFailureAttention(
346
968
  readFailureStateReadOnly(join(this.runs, meta.id, "failures.jsonl")), Date.now(),
347
969
  { terminal: !["running", "orphaned"].includes(meta.status), deferObservationGaps: meta.status === "running" }));
348
970
  const recipientPending = Boolean(failurePending || meta.timing?.pendingWakes?.length
@@ -352,35 +974,64 @@ export class WorkReadModel {
352
974
  : meta.completionCallbackPendingAt !== undefined && meta.completionCallbackSentAt === undefined && meta.completionCallbackSuppressedAt === undefined)));
353
975
  row = { meta, assignment, display, health, recipientPending, failurePending, sourceRevision: hash([meta, assignment.revision, display, health, recipientPending, failurePending, failureJournals.get(meta.id)]) };
354
976
  }
355
- rows.push(row);
977
+ rows.push(row!);
356
978
  if (++batch % 256 === 0 || performance.now() - sliceStarted >= 8) {
357
979
  await yieldTurn(); sliceStarted = performance.now();
358
980
  }
359
981
  }
982
+ this.inventoryPhase?.("verify");
983
+ // The pinned source snapshot is a valid baseline even while writers advance.
984
+ // Subsequent commits remain beyond the durable received position.
985
+ const globallyUnverified = !!healthConfig.reason || rows.some(row => !row.assignment.verified);
360
986
  let after: string;
361
987
  try { after = this.reader.revision(); } catch { after = "unknown"; }
362
- if (after !== coordinator) { this.state = "degraded"; this.reason = "Coordinator changed during observation; retrying."; this.dirty = true; this.publish(); return; }
988
+ if (after !== coordinator) {
989
+ sourceConflict = true;
990
+ this.dirty = true;
991
+ throw new Error("Coordinator changed during observation; retrying.");
992
+ }
363
993
  // Retry caches are never queryable. Validate all unpublished families again before committing them.
364
994
  this.staged = { files: next, projected: new Map(rows.map(row => [row.meta.id, row])), logs, failureJournals, processes,
365
- healthRevision: healthConfig.revision, coordinator, coordinatorConversations };
995
+ healthRevision: healthConfig.revision, coordinator, assignmentChanges: assignmentChanges && new Map(assignmentChanges),
996
+ assignmentGeneration };
366
997
  const uncommitted = new Set(affected);
367
998
  for (const [path, entry] of [...this.files, ...next]) {
368
- if (this.files.get(path)?.signature !== next.get(path)?.signature) uncommitted.add(family(entry.meta));
999
+ if (this.files.get(path)?.signature !== next.get(path)?.signature) uncommitted.add(entry.meta.id);
369
1000
  }
370
- const verify = [...next].filter(([, entry]) => uncommitted.has(family(entry.meta)));
1001
+ const verify = [...next].filter(([path, entry]) => !failedPaths.has(path) && uncommitted.has(entry.meta.id));
371
1002
  for (let offset = 0; offset < verify.length; offset += 32) {
372
1003
  const group = verify.slice(offset, offset + 32);
373
1004
  const observations = await Promise.all(group.map(async ([path]) => {
374
- try { return { info: await stat(path, { bigint: true }) }; }
1005
+ try { return { info: await sourceStat(path, { bigint: true }) }; }
375
1006
  catch (error) { return { error }; }
376
1007
  }));
377
- for (const [index, [, entry]] of group.entries()) {
1008
+ for (const [index, [path, entry]] of group.entries()) {
378
1009
  const observation = observations[index]!;
379
1010
  if (!observation.info) throw observation.error;
380
1011
  const info = observation.info;
381
1012
  if (`${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}` !== entry.signature) {
1013
+ sourceConflict = true;
382
1014
  this.dirty = true;
383
- throw new Error("Source changed during observation; retaining the previous snapshot while reconciling.");
1015
+ const error = new Error("Source changed during observation; retaining the previous snapshot while reconciling.");
1016
+ if (!globallyUnverified && (this.state === "ready" || this.sourceRace && this.reason === this.sourceRace.reason)
1017
+ && path.startsWith(this.runs + sep) && info.size <= 1024n * 1024n && !failedPaths.size && [...this.sourceErrors].every(([path, reason]) =>
1018
+ this.sourceRace?.paths.has(path) && reason === this.sourceRace.reason)) {
1019
+ // Recheck only for error routing: a concurrent move can affect a
1020
+ // new workspace/recipient. Never publish this uncommitted row.
1021
+ try {
1022
+ this.counters.metadataReads++;
1023
+ const current = JSON.parse(await readFile(path, "utf8"));
1024
+ const checked = await sourceStat(path, { bigint: true });
1025
+ if (current?.id === entry.meta.id && typeof current.cwd === "string" && Number.isFinite(current.startedAt)
1026
+ && typeof current.status === "string" && checked.size <= 1024n * 1024n
1027
+ && `${checked.dev}:${checked.ino}:${checked.size}:${checked.mtimeNs}:${checked.ctimeNs}` === `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`) {
1028
+ sourceRace = { reason: String(error), paths: new Set(paths), rows: [
1029
+ ...[...uncommitted].flatMap(id => [this.projected.get(id), this.staged?.projected.get(id)].filter(Boolean)),
1030
+ { meta: current, assignment: { state: current.status } }] };
1031
+ }
1032
+ } catch { /* Unreadable/unstable routing evidence keeps degradation global. */ }
1033
+ }
1034
+ throw error;
384
1035
  }
385
1036
  if (++batch % 256 === 0 || performance.now() - sliceStarted >= 8) {
386
1037
  await yieldTurn(); sliceStarted = performance.now();
@@ -388,36 +1039,83 @@ export class WorkReadModel {
388
1039
  }
389
1040
  }
390
1041
  if (this.closed) return;
391
- this.db.exec("BEGIN");
1042
+ rearmRawDirectories();
1043
+ await this.watchRegistrations();
1044
+ this.inventoryPhase?.("commit");
1045
+ if (!commitCoordinator) this.db.exec("BEGIN");
392
1046
  const insert = this.db.prepare("INSERT OR REPLACE INTO rows VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
393
1047
  const remove = this.db.prepare("DELETE FROM rows WHERE id = ?");
394
1048
  let semanticChange = false;
1049
+ const changedRows: WorkReadModel["changedRows"] = [];
1050
+ const publishCheckpoints: Array<() => void> = [];
395
1051
  try {
396
- for (const id of this.projected.keys()) if (!metas.has(id)) { remove.run(id); this.db.prepare("DELETE FROM terminal_log_folds WHERE id=?").run(id); semanticChange = true; }
1052
+ for (const id of this.projected.keys()) if (!metas.has(id)) { changedRows.push({ before: this.projected.get(id) }); remove.run(id); this.db.prepare("DELETE FROM assignment_members WHERE id=?").run(id); this.db.prepare("DELETE FROM terminal_log_folds WHERE id=?").run(id); semanticChange = true; }
397
1053
  for (const id of terminalLogChanges) this.db.prepare("INSERT INTO terminal_log_folds VALUES (?, ?, 1, ?) ON CONFLICT(id) DO UPDATE SET revision=excluded.revision, pending=1, queue_position=CASE WHEN terminal_log_folds.pending=0 THEN excluded.queue_position ELSE terminal_log_folds.queue_position END").run(id, hash([logs.get(id), metas.get(id)?.status]), ++this.foldQueueSequence);
398
1054
  for (const row of rows) {
399
1055
  if (this.projected.get(row.meta.id)?.sourceRevision === row.sourceRevision) continue;
400
1056
  semanticChange = true;
1057
+ changedRows.push({ before: this.projected.get(row.meta.id), after: row });
401
1058
  const m = row.meta;
402
1059
  if (m.management?.root !== this.agentDir || m.status === "running") this.db.prepare("DELETE FROM terminal_log_folds WHERE id=?").run(m.id);
403
1060
  insert.run(m.id, m.cwd, m.callbackOrigin?.cwd ?? m.cwd, m.callbackOrigin?.sessionId ?? null,
404
1061
  m.startedAt, row.assignment.state, ["running", "waiting"].includes(row.assignment.state) ? 1 : 0, m.endedAt ?? m.lostAt ?? null, row.recipientPending ? 1 : 0, JSON.stringify(row));
1062
+ this.db.prepare("DELETE FROM assignment_members WHERE id=?").run(m.id);
1063
+ const session = m.assignment?.owner?.sessionId ?? m.operations?.conversationId ?? m.sessionId;
1064
+ const workspace = m.assignment?.owner?.workspace ?? m.operations?.workspace ?? m.cwd;
1065
+ for (const assignmentId of new Set([m.assignment?.assignmentId ?? null, null])) this.db.prepare("INSERT INTO assignment_members VALUES(?,?)").run(JSON.stringify([session, workspace, assignmentId]), m.id);
405
1066
  }
406
- this.db.exec("COMMIT");
407
- } catch (error) { this.db.exec("ROLLBACK"); throw error; }
1067
+ for (const [path, checkpoint] of checkpointWrites) publishCheckpoints.push(this.checkpoints.save(path, checkpoint, true));
1068
+ // Application and its exact acknowledgement share the owner commit.
1069
+ if (assignmentChanges && rows.every(row => row.assignment.verified)) this.reader.acknowledgeChanges(assignmentChanges, false);
1070
+ if (commitCoordinator) commitCoordinator(); else this.db.exec("COMMIT");
1071
+ } catch (error) {
1072
+ if (releaseCoordinator) releaseCoordinator(); else this.db.exec("ROLLBACK");
1073
+ throw error;
1074
+ }
1075
+ for (const publish of publishCheckpoints) publish();
408
1076
  this.files = next; this.logs = logs; this.failureJournals = failureJournals; this.processes = processes; this.healthRevision = healthConfig.revision; this.coordinator = coordinator; this.inventory++;
409
- this.coordinatorConversations = coordinatorConversations;
410
1077
  this.projected = new Map(rows.map(row => [row.meta.id, row]));
1078
+ for (const states of [this.parseStates, this.healthStates]) for (const path of states.keys()) {
1079
+ if (!metas.has(path.slice(this.runs.length + 1).split(sep)[0])) states.delete(path);
1080
+ }
411
1081
  this.staged = undefined;
1082
+ this.sourceConflicts = 0; this.conflictDelay = 100;
412
1083
  if (terminalLogChanges.length) this.onTerminalLogsChanged?.();
413
1084
  const previousState = this.state;
414
1085
  const previousReason = this.reason;
415
- this.state = rows.some(row => !row.assignment.verified) ? "degraded" : "ready";
416
- this.reason = this.state === "degraded" ? "Some assignment sources could not be verified." : undefined;
417
- if (semanticChange || previousState !== this.state || previousReason !== this.reason) this.publish();
1086
+ for (const path of paths) {
1087
+ const error = failedPaths.get(path);
1088
+ if (error) this.sourceErrors.set(path, error);
1089
+ else this.sourceErrors.delete(path);
1090
+ }
1091
+ // Incomplete raw writes retain their verified namespace, not partial JSON.
1092
+ // New/unknown records and mixed failures cannot be narrowed this way.
1093
+ if (globallyUnverified) this.sourceRace = undefined;
1094
+ if (!globallyUnverified && failedPaths.size && failedPaths.size === malformedPaths.size
1095
+ && (previousState === "ready" || this.sourceRace && previousReason === this.sourceRace.reason)
1096
+ && [...this.sourceErrors.keys()].every(path => malformedPaths.has(path))) {
1097
+ this.sourceRace = { reason: failedPaths.values().next().value!, paths: malformedPaths,
1098
+ rows: [...malformedPaths].map(path => this.projected.get(this.files.get(path)!.meta.id)) };
1099
+ }
1100
+ if (!this.sourceErrors.size) this.sourceRace = undefined;
1101
+ this.state = this.sourceErrors.size || healthConfig.reason ? "degraded" : !this.imported ? "rebuilding" : rows.some(row => !row.assignment.verified) ? "degraded" : "ready";
1102
+ this.reason = this.sourceErrors.values().next().value ?? healthConfig.reason ?? (this.state === "rebuilding" ? "Initial source inventory is rebuilding." : this.state === "degraded" ? "Some assignment sources could not be verified." : undefined);
1103
+ if ((this.imported || paths.length === 128) && (semanticChange || previousState !== this.state || previousReason !== this.reason)) {
1104
+ this.changedRows = changedRows;
1105
+ this.publish();
1106
+ }
418
1107
  } catch (error) {
1108
+ releaseCoordinator?.(); releaseCoordinator = undefined;
1109
+ this.parseStates = parseBefore; this.healthStates = healthBefore;
419
1110
  if (this.closed) return;
420
- this.state = "degraded"; this.reason = String(error).slice(0, 512); this.publish();
1111
+ if (sourceConflict) this.sourceConflicts++;
1112
+ const reason = String(error).slice(0, 512);
1113
+ this.sourceRace = sourceRace;
1114
+ if (this.dirty) for (const path of paths) if (!this.hints.has(path)) this.hints.set(path, Date.now());
1115
+ for (const path of paths) this.sourceErrors.set(path, reason);
1116
+ const changed = this.state !== "degraded" || this.reason !== reason;
1117
+ this.state = "degraded"; this.reason = reason;
1118
+ if (changed) this.publish();
421
1119
  } finally { releaseCoordinator?.(); }
422
1120
  }
423
1121
 
@@ -426,6 +1124,11 @@ export class WorkReadModel {
426
1124
  return this.db.prepare("SELECT id, revision FROM terminal_log_folds WHERE pending=1 ORDER BY queue_position, id LIMIT 128").all();
427
1125
  }
428
1126
  acknowledgeTerminalLogs(batch: Array<{id: string; revision: string}>) {
1127
+ if (this.closed) return;
1128
+ if (this.reader?.snapshotActive && this.pending) {
1129
+ void this.pending.then(() => this.acknowledgeTerminalLogs(batch));
1130
+ return;
1131
+ }
429
1132
  const acknowledge = this.db.prepare("UPDATE terminal_log_folds SET pending=CASE WHEN revision=? THEN 0 ELSE 1 END, queue_position=? WHERE id=?");
430
1133
  // A newer revision remains owed, but rejoins behind existing obligations.
431
1134
  // Continuously changing low IDs cannot monopolize every subsequent batch.
@@ -433,8 +1136,18 @@ export class WorkReadModel {
433
1136
  }
434
1137
 
435
1138
  snapshot(scope: WorkScope = {}): WorkSnapshot {
1139
+ if (!this.observationInitialized && !this.closed) return { instanceId: this.instanceId, runtimeEpoch: this.instanceId, scopeRevision: hash([scope, this.state, this.reason]), seq: this.revision,
1140
+ observedRevisionVector: { inventory: this.inventory, coordinator: this.coordinator, healthConfig: this.healthRevision }, status: this.state, reason: this.reason,
1141
+ rows: [], totalMatching: 0, activity: { active: 0 }, nextDeadline: null };
436
1142
  if (scope.background) {
437
- if (scope.backgroundHistory && this.background.refresh()) this.publish();
1143
+ if (!this.observationInitialized) {
1144
+ const status = this.state === "ready" ? "degraded" : this.state;
1145
+ const reason = this.reason ?? "Derived observation inputs are unavailable.";
1146
+ return { instanceId: this.instanceId, runtimeEpoch: this.instanceId, scopeRevision: hash([scope, status, reason]), seq: this.revision,
1147
+ observedRevisionVector: { inventory: this.inventory, coordinator: this.coordinator, healthConfig: this.healthRevision },
1148
+ status, reason, rows: [], totalMatching: 0, activity: { active: 0 }, nextDeadline: null };
1149
+ }
1150
+ if (scope.backgroundHistory && this.background.refresh()) this.publish(true);
438
1151
  const index = scope.backgroundHistory ? this.background.historyIndex(scope) : undefined;
439
1152
  const tasks = this.background.read(scope, index);
440
1153
  const status = this.background.status === "degraded" ? "degraded" : index ? this.background.historyStatus : this.background.status;
@@ -445,7 +1158,7 @@ export class WorkReadModel {
445
1158
  rows: tasks.map(meta => ({ meta, assignment: null, sourceRevision: hash(meta) })), totalMatching: index?.page.total ?? tasks.length,
446
1159
  ...(index?.page.nextCursor ? { nextCursor: index.page.nextCursor } : {}),
447
1160
  ...(index ? { backgroundIndex: index } : {}),
448
- activity: { active }, nextDeadline: null };
1161
+ activity: { active }, nextDeadline: scope.backgroundHistory ? null : this.background.nextDeadline(scope) };
449
1162
  }
450
1163
  const clauses: string[] = [], args: any[] = [];
451
1164
  if (scope.id) { clauses.push("id = ?"); args.push(scope.id); }
@@ -460,22 +1173,31 @@ export class WorkReadModel {
460
1173
  if (scope.active !== undefined) { clauses.push("active = ?"); args.push(scope.active ? 1 : 0); }
461
1174
  if (scope.endedAfter !== undefined) { clauses.push("(ended IS NULL OR ended >= ?)"); args.push(scope.endedAfter); }
462
1175
  if (scope.statuses?.length) { clauses.push(`state IN (${scope.statuses.map(() => "?").join(",")})`); args.push(...scope.statuses); }
463
- const key = hash({ ...scope, cursor: undefined });
1176
+ const key = this.scopeKey(scope);
1177
+ const entry = this.scopeEntry(scope);
464
1178
  const totalMatching = Number(this.db.prepare(`SELECT count(*) AS n FROM rows ${clauses.length ? "WHERE " + clauses.join(" AND ") : ""}`).get(...args).n);
465
1179
  if (scope.cursor) {
466
1180
  let cursor;
467
1181
  try { cursor = JSON.parse(Buffer.from(scope.cursor, "base64url").toString()); } catch { throw new Error("Invalid runtime cursor"); }
468
- if (!Array.isArray(cursor) || cursor[0] !== key || cursor[1] !== this.instanceId || cursor[2] !== this.revision) throw new Error("resync_required: cursor snapshot changed");
1182
+ if (!Array.isArray(cursor) || cursor[0] !== key || cursor[1] !== this.instanceId || cursor[2] !== `${entry.token}:${entry.revision}`) throw new Error("resync_required: cursor snapshot changed");
469
1183
  clauses.push("(started < ? OR (started = ? AND id < ?))"); args.push(cursor[3], cursor[3], cursor[4]);
470
1184
  }
471
1185
  const limit = Math.max(1, Math.min(200, Number.isSafeInteger(scope.limit) ? scope.limit! : 50));
472
1186
  const records = this.db.prepare(`SELECT payload, started, id FROM rows ${clauses.length ? "WHERE " + clauses.join(" AND ") : ""} ORDER BY started DESC, id DESC LIMIT ?`).all(...args, limit + 1);
473
1187
  const page = records.slice(0, limit), last = page.at(-1);
474
- return { instanceId: this.instanceId, runtimeEpoch: this.instanceId, scopeRevision: hash([key, this.revision]), seq: this.revision,
475
- observedRevisionVector: { inventory: this.inventory, coordinator: this.coordinator, healthConfig: this.healthRevision }, status: this.state, reason: this.reason,
1188
+ const now = Date.now();
1189
+ const rows = page.map((record: any) => {
1190
+ const row = JSON.parse(record.payload);
1191
+ if (this.unsupportedAssignmentRevision) row.assignment = { ...row.assignment, verified: false, reason: this.reason };
1192
+ if (row.health) row.health.nextDeadline = nextHealthDeadline(row.health, row.meta, now);
1193
+ return row;
1194
+ });
1195
+ const deadlines = rows.map((row: any) => row.health?.nextDeadline).filter((deadline: any) => typeof deadline === "number");
1196
+ return { instanceId: this.instanceId, runtimeEpoch: this.instanceId, scopeRevision: hash([key, entry.token, entry.revision]), seq: this.revision,
1197
+ observedRevisionVector: { inventory: this.inventory, coordinator: this.coordinator, healthConfig: this.healthRevision }, ...this.scopeStatus(scope),
476
1198
  totalMatching,
477
- rows: page.map((record: any) => {
478
- const row = JSON.parse(record.payload);
1199
+ rows: page.map((record: any, index: number) => {
1200
+ const row = rows[index];
479
1201
  if (scope.detail && scope.id) {
480
1202
  let cached = this.details.get(row.meta.id);
481
1203
  if (!cached || cached.revision !== row.sourceRevision) {
@@ -494,16 +1216,20 @@ export class WorkReadModel {
494
1216
  }
495
1217
  row.detail = cached.value;
496
1218
  }
497
- return { ...row, cursor: Buffer.from(JSON.stringify([key, this.instanceId, this.revision, record.started, record.id])).toString("base64url") };
1219
+ return { ...row, cursor: Buffer.from(JSON.stringify([key, this.instanceId, `${entry.token}:${entry.revision}`, record.started, record.id])).toString("base64url") };
498
1220
  }),
499
- ...(records.length > limit ? { nextCursor: Buffer.from(JSON.stringify([key, this.instanceId, this.revision, last.started, last.id])).toString("base64url") } : {}),
500
- activity: { active }, nextDeadline: null };
1221
+ ...(records.length > limit ? { nextCursor: Buffer.from(JSON.stringify([key, this.instanceId, `${entry.token}:${entry.revision}`, last.started, last.id])).toString("base64url") } : {}),
1222
+ activity: { active }, nextDeadline: deadlines.length ? Math.min(...deadlines) : null };
501
1223
  }
502
1224
 
503
1225
  async close() {
504
1226
  this.closed = true; if (this.timer) clearInterval(this.timer);
1227
+ if (this.conflictRetry) clearTimeout(this.conflictRetry);
505
1228
  for (const watcher of this.watchers.values()) watcher.close();
1229
+ for (const { watcher } of this.rootParents.values()) watcher.close();
1230
+ this.rootParents.clear();
506
1231
  this.watchers.clear(); this.rootWatchIdentities.clear();
507
- await this.pending; this.listeners.clear(); await this.background.close(); this.reader.close(); this.db.close();
1232
+ await this.pending; await this.repairWrite; this.listeners.clear(); await this.background.close(); this.reader?.close(); this.checkpoints.close(); this.db.close();
1233
+ await this.repair?.return(undefined);
508
1234
  }
509
1235
  }