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
@@ -14,7 +14,9 @@
14
14
  import { StoreError } from "./errors.ts";
15
15
  import { mapOperation, ownerFromRow, readOperation, requireOperation } from "./rows.ts";
16
16
  import {
17
+ columnJson,
17
18
  columnText,
19
+ getRow,
18
20
  getRows,
19
21
  isUniqueViolation,
20
22
  run,
@@ -25,6 +27,7 @@ import type {
25
27
  ObserverHealth,
26
28
  OperationFilter,
27
29
  OperationRecord,
30
+ OwnerIdentity,
28
31
  ReleaseSupervisionInput,
29
32
  RecordSupervisionInput,
30
33
  RecordTerminalOutcomeInput,
@@ -40,6 +43,7 @@ import {
40
43
  normalizeOwner,
41
44
  optionalText,
42
45
  requireBoolean,
46
+ requireCounter,
43
47
  requireEnum,
44
48
  requireEvidenceKind,
45
49
  requireId,
@@ -54,6 +58,7 @@ import { bumpChangeRevision } from "./discovery.ts";
54
58
 
55
59
  const HEALTH_VALUES: readonly ObserverHealth[] = ["active", "unmonitored", "lost"];
56
60
  const OUTCOME_VALUES: readonly TerminalOutcome[] = ["succeeded", "failed", "cancelled", "lost"];
61
+ const ASSIGNMENT_CLEANUP_PAGE_MAX = 256;
57
62
 
58
63
  function normalizeSupervision(value: unknown): SupervisionIdentity | null {
59
64
  if (value === undefined || value === null) return null;
@@ -108,6 +113,9 @@ export function registerOperation(
108
113
  const taskId = requireId("taskId", input.taskId);
109
114
  const launchToken = requireId("launchToken", input.launchToken);
110
115
  const owner = normalizeOwner("owner", input.owner);
116
+ const assignmentAttemptId = input.assignmentAttemptId === undefined
117
+ ? undefined
118
+ : requireId("assignmentAttemptId", input.assignmentAttemptId);
111
119
  const observer = requireObserver("observer", input.observer);
112
120
  const supervision = normalizeSupervision(input.supervision);
113
121
  const authorityRef = optionalText("authorityRef", input.authorityRef, 512);
@@ -133,6 +141,7 @@ export function registerOperation(
133
141
  const differences: string[] = [];
134
142
  if (existing.taskId !== taskId) differences.push("taskId");
135
143
  if (existing.launchToken !== launchToken) differences.push("launchToken");
144
+ if (existing.assignmentAttemptId !== assignmentAttemptId) differences.push("assignmentAttemptId");
136
145
  if (!sameOwner(existing.owner, owner)) {
137
146
  differences.push(`owner (${describeOwnerDiff(existing.owner, owner)})`);
138
147
  }
@@ -154,6 +163,20 @@ export function registerOperation(
154
163
  return { operation: existing, created: false };
155
164
  }
156
165
  assertTaskAvailable();
166
+ if (assignmentAttemptId !== undefined) {
167
+ const binding = getRow(ctx, `SELECT b.owner_json, o.assignment_id AS terminal_assignment_id
168
+ FROM assignment_attempts a
169
+ JOIN assignment_bindings b ON b.assignment_id = a.assignment_id
170
+ LEFT JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
171
+ WHERE a.attempt_id = ?`, assignmentAttemptId);
172
+ const capturedOwner = binding && columnJson<OwnerIdentity>(binding, "owner_json");
173
+ if (!binding || !capturedOwner || !sameOwner(capturedOwner, owner)) {
174
+ throw new StoreError("foreign-owner", "Operation owner must match the captured owner of a registered assignment attempt.");
175
+ }
176
+ if (binding.terminal_assignment_id !== null) {
177
+ throw new StoreError("validation", "A terminal assignment cannot register a new operation.");
178
+ }
179
+ }
157
180
 
158
181
  const at = ctx.now();
159
182
  try {
@@ -161,10 +184,10 @@ export function registerOperation(
161
184
  ctx,
162
185
  `INSERT INTO operations (
163
186
  operation_id, task_id, launch_token,
164
- owner_kind, owner_session_id, owner_workspace, owner_branch_id, owner_goal_id,
187
+ owner_kind, owner_session_id, owner_workspace, owner_branch_id, owner_goal_id, assignment_attempt_id,
165
188
  observer_kind, observer_version, supervision_json, supervision_host_id, authority_ref, intent_ref,
166
189
  phase, health, health_reason, terminal_revision, created_at, updated_at
167
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'running', 'active', NULL, 0, ?, ?)`,
190
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'running', 'active', NULL, 0, ?, ?)`,
168
191
  operationId,
169
192
  taskId,
170
193
  launchToken,
@@ -173,6 +196,7 @@ export function registerOperation(
173
196
  owner.workspace,
174
197
  owner.branchId ?? null,
175
198
  owner.goalId ?? null,
199
+ assignmentAttemptId ?? null,
176
200
  observer.kind,
177
201
  observer.version,
178
202
  supervision ? JSON.stringify(supervision) : null,
@@ -439,6 +463,30 @@ export function listOperations(
439
463
  .map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
440
464
  }
441
465
 
466
+ export function listAssignmentCleanupOperations(
467
+ ctx: StoreContext,
468
+ limit: number,
469
+ afterOperationId?: string,
470
+ ): OperationRecord[] {
471
+ const requested = requireCounter("limit", limit);
472
+ if (requested === 0) throw new StoreError("validation", "Invalid limit: must be at least 1");
473
+ const cursor = afterOperationId === undefined ? "" : requireId("afterOperationId", afterOperationId);
474
+ // Seek the partial index in cursor order rather than sorting all running operations.
475
+ return getRows(ctx, `SELECT op.*, EXISTS(SELECT 1 FROM coordinator_state s
476
+ WHERE s.key = 'result-supervision-v1:' || op.operation_id) AS result_managed
477
+ FROM operations op INDEXED BY operations_assignment_cleanup
478
+ JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
479
+ JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
480
+ WHERE op.assignment_attempt_id IS NOT NULL AND op.operation_id > ?
481
+ AND (op.terminal_revision = 0 OR op.terminal_outcome = 'lost'
482
+ OR EXISTS (SELECT 1 FROM operation_evidence e WHERE e.operation_id = op.operation_id
483
+ AND e.terminal_revision = op.terminal_revision AND e.kind = 'terminal-record'
484
+ AND e.summary LIKE '%groupCleanup=unproven%'))
485
+ AND NOT EXISTS (SELECT 1 FROM coordinator_state s WHERE s.key = 'assignment-cleanup-verified:' || op.operation_id)
486
+ ORDER BY op.operation_id LIMIT ?`, cursor, Math.min(requested, ASSIGNMENT_CLEANUP_PAGE_MAX))
487
+ .map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
488
+ }
489
+
442
490
  /** Running operations assigned to one supervising host, using the phase/host index. */
443
491
  export function listRunningSupervisedBy(
444
492
  ctx: StoreContext,
@@ -5,6 +5,18 @@ import { getRow, run } from "./sqlite.domain.mjs";
5
5
  import { getOperation, recordSupervision, recordTerminalOutcome } from "./operations.domain.mjs";
6
6
  import { requireId, requirePath } from "./validate.domain.mjs";
7
7
  const PREFIX = "result-supervision-v1:";
8
+ /** A bounded observation page. A gap requires restoring active authority, not history. */
9
+ export function resultSupervisionChanges(ctx, after) {
10
+ const generation = String(ctx.db.prepare("SELECT generation FROM assignment_change_source WHERE singleton=1").get().generation);
11
+ const bounds = ctx.db.prepare("SELECT min(seq) AS first, max(seq) AS last FROM assignment_changes").get();
12
+ const last = Number(bounds.last ?? 0);
13
+ const reset = !after || after.generation !== generation || after.seq > last
14
+ || (bounds.first !== null && after.seq < Number(bounds.first) - 1);
15
+ const rows = reset ? [] : ctx.db.prepare("SELECT seq, entity, entity_id FROM assignment_changes WHERE seq>? ORDER BY seq LIMIT 128").all(after.seq);
16
+ const seq = reset ? last : Number(rows.at(-1)?.seq ?? after.seq);
17
+ return { generation, seq, reset, more: seq < last,
18
+ operationIds: [...new Set(rows.filter(row => row.entity === "background:operation").map(row => String(row.entity_id)))] };
19
+ }
8
20
  export function resultSupervisions(ctx, activeOnly = false) {
9
21
  const rows = activeOnly
10
22
  ? ctx.db.prepare("SELECT s.value FROM operations o JOIN coordinator_state s ON s.key = ? || o.operation_id WHERE o.phase = 'running'").all(PREFIX)
@@ -7,6 +7,18 @@ import type { RecordTerminalOutcomeInput } from "./types.ts";
7
7
  import type { OwnerIdentity } from "./types.ts";
8
8
 
9
9
  const PREFIX = "result-supervision-v1:";
10
+ /** A bounded observation page. A gap requires restoring active authority, not history. */
11
+ export function resultSupervisionChanges(ctx: StoreContext, after?: { generation: string; seq: number }) {
12
+ const generation = String(ctx.db.prepare("SELECT generation FROM assignment_change_source WHERE singleton=1").get()!.generation);
13
+ const bounds = ctx.db.prepare("SELECT min(seq) AS first, max(seq) AS last FROM assignment_changes").get()!;
14
+ const last = Number(bounds.last ?? 0);
15
+ const reset = !after || after.generation !== generation || after.seq > last
16
+ || (bounds.first !== null && after.seq < Number(bounds.first) - 1);
17
+ const rows = reset ? [] : ctx.db.prepare("SELECT seq, entity, entity_id FROM assignment_changes WHERE seq>? ORDER BY seq LIMIT 128").all(after!.seq);
18
+ const seq = reset ? last : Number(rows.at(-1)?.seq ?? after!.seq);
19
+ return { generation, seq, reset, more: seq < last,
20
+ operationIds: [...new Set(rows.filter(row => row.entity === "background:operation").map(row => String(row.entity_id)))] };
21
+ }
10
22
  export interface ResultSupervision {
11
23
  operationId: string;
12
24
  directory: string;
@@ -28,11 +28,13 @@ export function getOperationRowByTask(ctx, taskId) {
28
28
  return getRow(ctx, "SELECT * FROM operations WHERE task_id = ?", taskId);
29
29
  }
30
30
  export function mapOperation(row) {
31
+ const assignmentAttemptId = columnNullableText(row, "assignment_attempt_id");
31
32
  return {
32
33
  operationId: columnText(row, "operation_id"),
33
34
  taskId: columnText(row, "task_id"),
34
35
  launchToken: columnText(row, "launch_token"),
35
36
  owner: ownerFromRow(row),
37
+ ...(assignmentAttemptId === null ? {} : { assignmentAttemptId }),
36
38
  observer: {
37
39
  kind: columnText(row, "observer_kind"),
38
40
  version: columnText(row, "observer_version"),
@@ -74,11 +74,13 @@ export function getOperationRowByTask(
74
74
  }
75
75
 
76
76
  export function mapOperation(row: Record<string, unknown>): OperationRecord {
77
+ const assignmentAttemptId = columnNullableText(row, "assignment_attempt_id");
77
78
  return {
78
79
  operationId: columnText(row, "operation_id"),
79
80
  taskId: columnText(row, "task_id"),
80
81
  launchToken: columnText(row, "launch_token"),
81
82
  owner: ownerFromRow(row),
83
+ ...(assignmentAttemptId === null ? {} : { assignmentAttemptId }),
82
84
  observer: {
83
85
  kind: columnText(row, "observer_kind"),
84
86
  version: columnText(row, "observer_version"),
@@ -1,7 +1,7 @@
1
1
  // Generated fixed launch domain from packages/pi-better-subagents/shared-operation-coordinator/src/schema.ts. Do not edit directly.
2
2
  // Generated from packages/operation-coordinator/src/schema.ts. Do not edit directly.
3
3
  /**
4
- * Schema v4 for the durable operation coordinator.
4
+ * Schema v5 for the durable operation coordinator.
5
5
  *
6
6
  * The store refuses to open a database whose recorded version it does not
7
7
  * understand, and leaves the file untouched. An unreadable or newer database
@@ -55,6 +55,14 @@ const BACKGROUND_CALLBACK_DDL = [
55
55
  SELECT 1,'',COALESCE(MAX(operation_id),''),CASE WHEN MAX(operation_id) IS NULL THEN 1 ELSE 0 END
56
56
  FROM operations WHERE owner_kind='parent-session' AND observer_kind='local-supervisor'`,
57
57
  ];
58
+ const ASSIGNMENT_ATTEMPTS_DDL = `CREATE TABLE IF NOT EXISTS assignment_attempts (
59
+ attempt_id TEXT PRIMARY KEY,
60
+ assignment_id TEXT NOT NULL REFERENCES assignment_bindings (assignment_id)
61
+ )`;
62
+ const ASSIGNMENT_ATTEMPT_COLUMN = `assignment_attempt_id TEXT REFERENCES assignment_attempts (attempt_id)`;
63
+ const ASSIGNMENT_CLEANUP_INDEX = `CREATE INDEX IF NOT EXISTS operations_assignment_cleanup
64
+ ON operations (operation_id, assignment_attempt_id)
65
+ WHERE assignment_attempt_id IS NOT NULL`;
58
66
  const DDL = [
59
67
  `CREATE TABLE task_cancellation_authorities (
60
68
  credential_hash TEXT PRIMARY KEY,
@@ -91,6 +99,7 @@ const DDL = [
91
99
  owner_workspace TEXT NOT NULL,
92
100
  owner_branch_id TEXT,
93
101
  owner_goal_id TEXT,
102
+ ${ASSIGNMENT_ATTEMPT_COLUMN},
94
103
  observer_kind TEXT NOT NULL,
95
104
  observer_version TEXT NOT NULL,
96
105
  supervision_json TEXT,
@@ -113,6 +122,7 @@ const DDL = [
113
122
  `CREATE INDEX operations_owner ON operations (owner_kind, owner_session_id)`,
114
123
  `CREATE INDEX operations_phase ON operations (phase)`,
115
124
  `CREATE INDEX operations_running_supervisor ON operations (phase, supervision_host_id)`,
125
+ ASSIGNMENT_CLEANUP_INDEX,
116
126
  // Discovery leadership is separate from per-operation supervision. The token
117
127
  // fences stale acquisition and release; the host id is checked with process
118
128
  // identity before a replacement.
@@ -266,10 +276,7 @@ const DDL = [
266
276
  owner_json TEXT NOT NULL,
267
277
  recipient_json TEXT NOT NULL
268
278
  )`,
269
- `CREATE TABLE assignment_attempts (
270
- attempt_id TEXT PRIMARY KEY,
271
- assignment_id TEXT NOT NULL REFERENCES assignment_bindings (assignment_id)
272
- )`,
279
+ ASSIGNMENT_ATTEMPTS_DDL,
273
280
  `CREATE TABLE assignment_outcome_waits (
274
281
  assignment_id TEXT NOT NULL REFERENCES assignment_outcomes (assignment_id),
275
282
  wait_id TEXT NOT NULL,
@@ -313,17 +320,16 @@ export function ensureSchema(ctx) {
313
320
  throw new StoreError("schema-version", `The database was written by schema version ${recorded}; this build understands version ${SCHEMA_VERSION}. Upgrade the harness instead of downgrading the records.`);
314
321
  }
315
322
  if (recorded < SCHEMA_VERSION) {
316
- if (recorded === 3) {
317
- ctx.transaction(() => {
318
- ensureAdditiveSchema(ctx);
319
- ctx.db.exec(DDL.find((sql) => sql.startsWith("CREATE TABLE assignment_repairs")));
320
- run(ctx, "UPDATE schema_meta SET value = ? WHERE key = ?", String(SCHEMA_VERSION), SCHEMA_VERSION_KEY);
321
- });
322
- return;
323
- }
324
- if (recorded === 1 || recorded === 2) {
323
+ ctx.transaction(() => {
324
+ // Another opener may have finished the upgrade before we acquired the write lock.
325
+ const current = readSchemaVersion(ctx);
326
+ if (current === SCHEMA_VERSION)
327
+ return;
328
+ if (current !== recorded) {
329
+ throw new StoreError("schema-version", "The coordinator schema changed during opening. Reopen the store to verify it.");
330
+ }
325
331
  ensureAdditiveSchema(ctx);
326
- ctx.transaction(() => {
332
+ if (recorded <= 2) {
327
333
  if (recorded === 1)
328
334
  ctx.db.exec("ALTER TABLE outbox_events ADD COLUMN event_type TEXT NOT NULL DEFAULT 'dependency-ready'");
329
335
  for (const statement of DDL.filter((sql) => sql.startsWith("CREATE TABLE assignment_")))
@@ -332,14 +338,29 @@ export function ensureSchema(ctx) {
332
338
  ctx.db.exec("UPDATE waits SET dispatch_disarmed = 1 WHERE EXISTS (SELECT 1 FROM assignment_outcome_waits aw WHERE aw.wait_id = waits.wait_id AND aw.generation = waits.generation)");
333
339
  ctx.db.exec("DROP INDEX waits_one_pending_per_owner");
334
340
  ctx.db.exec(DDL.find((sql) => sql.startsWith("CREATE UNIQUE INDEX waits_one_pending_per_owner")));
335
- run(ctx, "UPDATE schema_meta SET value = ? WHERE key = ?", String(SCHEMA_VERSION), SCHEMA_VERSION_KEY);
336
- });
337
- return;
338
- }
339
- throw new StoreError("schema-version", `The database is at schema version ${recorded}; this build needs version ${SCHEMA_VERSION}. No migration is provided for this pair; records are left in place.`);
341
+ }
342
+ else if (recorded === 3) {
343
+ ctx.db.exec(DDL.find((sql) => sql.startsWith("CREATE TABLE assignment_repairs")));
344
+ }
345
+ ensureAssignmentCleanupSchema(ctx);
346
+ run(ctx, "UPDATE schema_meta SET value = ? WHERE key = ?", String(SCHEMA_VERSION), SCHEMA_VERSION_KEY);
347
+ });
348
+ return;
340
349
  }
341
350
  ensureAdditiveSchema(ctx);
342
- ctx.db.exec(DDL.find((sql) => sql.startsWith("CREATE TABLE assignment_attempts")).replace("CREATE TABLE", "CREATE TABLE IF NOT EXISTS"));
351
+ ensureAssignmentCleanupSchema(ctx);
352
+ }
353
+ function ensureAssignmentCleanupSchema(ctx) {
354
+ const hasColumn = () => getRows(ctx, "PRAGMA table_info(operations)").some(row => row.name === "assignment_attempt_id");
355
+ if (hasColumn() && getRow(ctx, "SELECT 1 FROM sqlite_master WHERE name = 'operations_assignment_cleanup'"))
356
+ return;
357
+ ctx.transaction(() => {
358
+ ctx.db.exec(ASSIGNMENT_ATTEMPTS_DDL);
359
+ // Legacy writers leave the nullable provenance unset.
360
+ if (!hasColumn())
361
+ ctx.db.exec(`ALTER TABLE operations ADD COLUMN ${ASSIGNMENT_ATTEMPT_COLUMN}`);
362
+ ctx.db.exec(ASSIGNMENT_CLEANUP_INDEX);
363
+ });
343
364
  }
344
365
  /**
345
366
  * Schema version 1 is extended additively: older readers ignore the new column,
@@ -1,6 +1,6 @@
1
1
  // Generated from packages/operation-coordinator/src/schema.ts. Do not edit directly.
2
2
  /**
3
- * Schema v4 for the durable operation coordinator.
3
+ * Schema v5 for the durable operation coordinator.
4
4
  *
5
5
  * The store refuses to open a database whose recorded version it does not
6
6
  * understand, and leaves the file untouched. An unreadable or newer database
@@ -57,6 +57,15 @@ const BACKGROUND_CALLBACK_DDL = [
57
57
  FROM operations WHERE owner_kind='parent-session' AND observer_kind='local-supervisor'`,
58
58
  ];
59
59
 
60
+ const ASSIGNMENT_ATTEMPTS_DDL = `CREATE TABLE IF NOT EXISTS assignment_attempts (
61
+ attempt_id TEXT PRIMARY KEY,
62
+ assignment_id TEXT NOT NULL REFERENCES assignment_bindings (assignment_id)
63
+ )`;
64
+ const ASSIGNMENT_ATTEMPT_COLUMN = `assignment_attempt_id TEXT REFERENCES assignment_attempts (attempt_id)`;
65
+ const ASSIGNMENT_CLEANUP_INDEX = `CREATE INDEX IF NOT EXISTS operations_assignment_cleanup
66
+ ON operations (operation_id, assignment_attempt_id)
67
+ WHERE assignment_attempt_id IS NOT NULL`;
68
+
60
69
  const DDL: readonly string[] = [
61
70
  `CREATE TABLE task_cancellation_authorities (
62
71
  credential_hash TEXT PRIMARY KEY,
@@ -93,6 +102,7 @@ const DDL: readonly string[] = [
93
102
  owner_workspace TEXT NOT NULL,
94
103
  owner_branch_id TEXT,
95
104
  owner_goal_id TEXT,
105
+ ${ASSIGNMENT_ATTEMPT_COLUMN},
96
106
  observer_kind TEXT NOT NULL,
97
107
  observer_version TEXT NOT NULL,
98
108
  supervision_json TEXT,
@@ -115,6 +125,7 @@ const DDL: readonly string[] = [
115
125
  `CREATE INDEX operations_owner ON operations (owner_kind, owner_session_id)`,
116
126
  `CREATE INDEX operations_phase ON operations (phase)`,
117
127
  `CREATE INDEX operations_running_supervisor ON operations (phase, supervision_host_id)`,
128
+ ASSIGNMENT_CLEANUP_INDEX,
118
129
  // Discovery leadership is separate from per-operation supervision. The token
119
130
  // fences stale acquisition and release; the host id is checked with process
120
131
  // identity before a replacement.
@@ -268,10 +279,7 @@ const DDL: readonly string[] = [
268
279
  owner_json TEXT NOT NULL,
269
280
  recipient_json TEXT NOT NULL
270
281
  )`,
271
- `CREATE TABLE assignment_attempts (
272
- attempt_id TEXT PRIMARY KEY,
273
- assignment_id TEXT NOT NULL REFERENCES assignment_bindings (assignment_id)
274
- )`,
282
+ ASSIGNMENT_ATTEMPTS_DDL,
275
283
  `CREATE TABLE assignment_outcome_waits (
276
284
  assignment_id TEXT NOT NULL REFERENCES assignment_outcomes (assignment_id),
277
285
  wait_id TEXT NOT NULL,
@@ -333,34 +341,42 @@ export function ensureSchema(ctx: StoreContext): void {
333
341
  );
334
342
  }
335
343
  if (recorded < SCHEMA_VERSION) {
336
- if (recorded === 3) {
337
- ctx.transaction(() => {
338
- ensureAdditiveSchema(ctx);
339
- ctx.db.exec(DDL.find((sql) => sql.startsWith("CREATE TABLE assignment_repairs"))!);
340
- run(ctx, "UPDATE schema_meta SET value = ? WHERE key = ?", String(SCHEMA_VERSION), SCHEMA_VERSION_KEY);
341
- });
342
- return;
343
- }
344
- if (recorded === 1 || recorded === 2) {
344
+ ctx.transaction(() => {
345
+ // Another opener may have finished the upgrade before we acquired the write lock.
346
+ const current = readSchemaVersion(ctx);
347
+ if (current === SCHEMA_VERSION) return;
348
+ if (current !== recorded) {
349
+ throw new StoreError("schema-version", "The coordinator schema changed during opening. Reopen the store to verify it.");
350
+ }
345
351
  ensureAdditiveSchema(ctx);
346
- ctx.transaction(() => {
352
+ if (recorded <= 2) {
347
353
  if (recorded === 1) ctx.db.exec("ALTER TABLE outbox_events ADD COLUMN event_type TEXT NOT NULL DEFAULT 'dependency-ready'");
348
354
  for (const statement of DDL.filter((sql) => sql.startsWith("CREATE TABLE assignment_"))) ctx.db.exec(statement.replace("CREATE TABLE", "CREATE TABLE IF NOT EXISTS"));
349
355
  ctx.db.exec("ALTER TABLE waits ADD COLUMN dispatch_disarmed INTEGER NOT NULL DEFAULT 0");
350
356
  ctx.db.exec("UPDATE waits SET dispatch_disarmed = 1 WHERE EXISTS (SELECT 1 FROM assignment_outcome_waits aw WHERE aw.wait_id = waits.wait_id AND aw.generation = waits.generation)");
351
357
  ctx.db.exec("DROP INDEX waits_one_pending_per_owner");
352
358
  ctx.db.exec(DDL.find((sql) => sql.startsWith("CREATE UNIQUE INDEX waits_one_pending_per_owner"))!);
353
- run(ctx, "UPDATE schema_meta SET value = ? WHERE key = ?", String(SCHEMA_VERSION), SCHEMA_VERSION_KEY);
354
- });
355
- return;
356
- }
357
- throw new StoreError(
358
- "schema-version",
359
- `The database is at schema version ${recorded}; this build needs version ${SCHEMA_VERSION}. No migration is provided for this pair; records are left in place.`,
360
- );
359
+ } else if (recorded === 3) {
360
+ ctx.db.exec(DDL.find((sql) => sql.startsWith("CREATE TABLE assignment_repairs"))!);
361
+ }
362
+ ensureAssignmentCleanupSchema(ctx);
363
+ run(ctx, "UPDATE schema_meta SET value = ? WHERE key = ?", String(SCHEMA_VERSION), SCHEMA_VERSION_KEY);
364
+ });
365
+ return;
361
366
  }
362
367
  ensureAdditiveSchema(ctx);
363
- ctx.db.exec(DDL.find((sql) => sql.startsWith("CREATE TABLE assignment_attempts"))!.replace("CREATE TABLE", "CREATE TABLE IF NOT EXISTS"));
368
+ ensureAssignmentCleanupSchema(ctx);
369
+ }
370
+
371
+ function ensureAssignmentCleanupSchema(ctx: StoreContext): void {
372
+ const hasColumn = () => getRows(ctx, "PRAGMA table_info(operations)").some(row => row.name === "assignment_attempt_id");
373
+ if (hasColumn() && getRow(ctx, "SELECT 1 FROM sqlite_master WHERE name = 'operations_assignment_cleanup'")) return;
374
+ ctx.transaction(() => {
375
+ ctx.db.exec(ASSIGNMENT_ATTEMPTS_DDL);
376
+ // Legacy writers leave the nullable provenance unset.
377
+ if (!hasColumn()) ctx.db.exec(`ALTER TABLE operations ADD COLUMN ${ASSIGNMENT_ATTEMPT_COLUMN}`);
378
+ ctx.db.exec(ASSIGNMENT_CLEANUP_INDEX);
379
+ });
364
380
  }
365
381
 
366
382
  /**
@@ -13,14 +13,15 @@ import { setParentCallbackPending, listPendingParentCallbacks, listRecentBackgro
13
13
  import { BackgroundRequests } from "./background-requests.domain.mjs";
14
14
  import { StoreError } from "./errors.domain.mjs";
15
15
  import { SubagentLaunchJournal } from "./subagent-launch.domain.mjs";
16
- import { resultSupervision, resultSupervisions, resultScopeManaged, handoffResultScope, handoffResultSupervision, handoffResultSupervisions, recoverResultSupervision, publishSupervisedResult } from "./result-supervision.domain.mjs";
16
+ import { resultSupervisionChanges, resultSupervision, resultSupervisions, resultScopeManaged, handoffResultScope, handoffResultSupervision, handoffResultSupervisions, recoverResultSupervision, publishSupervisedResult } from "./result-supervision.domain.mjs";
17
17
  import { acceptTaskCancellation, getTaskCancellation, recordTaskStopRequested, admitTaskCancellation, authorizedTaskCancellation, finishTaskCancellation, cancellationRuntimeEpoch, acceptAuthorizedTaskCancellation, taskCancellationManaged, pendingTaskCancellations, finishTaskCancellationIntent, unknownTaskCancellation } from "./task-cancellation.domain.mjs";
18
18
  import { repairFailedResume } from "./recovery.domain.mjs";
19
19
  import { recordAssignmentOutcome, getAssignmentOutcome, inspectAssignmentOutcome, consumeAssignmentOutcome, registerAssignment, receiptAssignmentOutcome } from "./assignment-outcomes.domain.mjs";
20
20
  import { describeOwnerDiff, normalizeOwner, requireCounter, requireId, requirePath, } from "./validate.domain.mjs";
21
21
  import { ensureSchema } from "./schema.domain.mjs";
22
- import { createContext, openDatabase } from "./sqlite.domain.mjs";
23
- import { getOperation as readOperationRecord, listOperations as readOperationRecords, listRunningSupervisedBy as readRunningSupervisedBy, releaseSupervision as writeSupervisionRelease, recordSupervision as writeSupervision, recordTerminalOutcome as writeTerminalOutcome, registerOperation as writeOperation, } from "./operations.domain.mjs";
22
+ import { ensureAssignmentChanges } from "./assignment-changes.domain.mjs";
23
+ import { createContext, openDatabase, run } from "./sqlite.domain.mjs";
24
+ import { getOperation as readOperationRecord, listAssignmentCleanupOperations as readAssignmentCleanupOperations, listOperations as readOperationRecords, listRunningSupervisedBy as readRunningSupervisedBy, releaseSupervision as writeSupervisionRelease, recordSupervision as writeSupervision, recordTerminalOutcome as writeTerminalOutcome, registerOperation as writeOperation, } from "./operations.domain.mjs";
24
25
  import { getChangeRevision as readChangeRevision, readDiscoveryClaim as readClaim, readDiscoveryState, releaseDiscoveryClaim as deleteDiscoveryClaim, tryClaimDiscovery as writeDiscoveryClaim, } from "./discovery.domain.mjs";
25
26
  import { acknowledgeResult as writeAcknowledgement, cancelWait as writeCancellation, claimResume as writeClaim, findPendingWaitForOwner, getWait as readWait, listDependencies as readDependencies, listEvidencePins as readPins, listEvidenceReads as readReads, listResumeClaims as readClaims, listUnreconciledClaims, listWaits as readWaits, publishResumeAttempt as writeAttemptPublication, recordEvidencePin as writePin, recordEvidenceRead as writeRead, registerWait as writeWait, releaseEvidencePins as writePinRelease, holdFailedResume as writeHoldFailedResume, releaseResumeClaim as writeClaimRelease, transitionWaitPhase as writePhase, } from "./waits.domain.mjs";
26
27
  import { claimOutbox as writeOutboxClaim, listDispatchableOutboxRecipients as readDispatchableOutboxRecipients, listOutbox as readOutbox, markOutboxDelivered as writeOutboxDelivery, releaseOutbox as writeOutboxRelease, } from "./outbox.domain.mjs";
@@ -32,6 +33,7 @@ export function openStore(options) {
32
33
  const ctx = createContext(db, options.now ? { now: options.now } : {});
33
34
  try {
34
35
  ensureSchema(ctx);
36
+ ensureAssignmentChanges(ctx);
35
37
  }
36
38
  catch (error) {
37
39
  try {
@@ -53,6 +55,8 @@ export function openStore(options) {
53
55
  resultScopeManaged(scope) { alive(); return resultScopeManaged(ctx, scope); },
54
56
  handoffResultScope(input) { alive(); return handoffResultScope(ctx, input); },
55
57
  resultSupervision(id) { alive(); return resultSupervision(ctx, id); },
58
+ hasSubagentManagement() { alive(); return Boolean(ctx.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='subagent_management'").get()); },
59
+ resultSupervisionChanges(after) { alive(); return resultSupervisionChanges(ctx, after); },
56
60
  resultSupervisions(activeOnly) { alive(); return resultSupervisions(ctx, activeOnly); },
57
61
  handoffResultSupervision(input) { alive(); return handoffResultSupervision(ctx, input); },
58
62
  handoffResultSupervisions(input) { alive(); return handoffResultSupervisions(ctx, input); },
@@ -111,6 +115,20 @@ export function openStore(options) {
111
115
  alive();
112
116
  return readOperationRecords(ctx, filter);
113
117
  },
118
+ listAssignmentCleanupOperations(limit, afterOperationId) {
119
+ alive();
120
+ return readAssignmentCleanupOperations(ctx, limit, afterOperationId);
121
+ },
122
+ verifyAssignmentCleanup(operationId, launchToken, terminalRevision) {
123
+ alive();
124
+ if (!Number.isSafeInteger(terminalRevision) || terminalRevision < 1)
125
+ return false;
126
+ return run(ctx, `INSERT OR IGNORE INTO coordinator_state (key, value)
127
+ SELECT 'assignment-cleanup-verified:' || op.operation_id, op.launch_token
128
+ FROM operations op JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
129
+ JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
130
+ WHERE op.operation_id = ? AND op.launch_token = ? AND op.terminal_revision = ?`, operationId, launchToken, terminalRevision) > 0;
131
+ },
114
132
  listRunningSupervisedBy(hostId) {
115
133
  alive();
116
134
  return readRunningSupervisedBy(ctx, hostId);
@@ -12,7 +12,7 @@ import { setParentCallbackPending, listPendingParentCallbacks, listRecentBackgro
12
12
  import { BackgroundRequests } from "./background-requests.ts";
13
13
  import { StoreError } from "./errors.ts";
14
14
  import { SubagentLaunchJournal } from "./subagent-launch.ts";
15
- import { resultSupervision, resultSupervisions, resultScopeManaged, handoffResultScope, handoffResultSupervision, handoffResultSupervisions, recoverResultSupervision, publishSupervisedResult } from "./result-supervision.ts";
15
+ import { resultSupervisionChanges, resultSupervision, resultSupervisions, resultScopeManaged, handoffResultScope, handoffResultSupervision, handoffResultSupervisions, recoverResultSupervision, publishSupervisedResult } from "./result-supervision.ts";
16
16
  import { acceptTaskCancellation, getTaskCancellation, recordTaskStopRequested, admitTaskCancellation, authorizedTaskCancellation, finishTaskCancellation, cancellationRuntimeEpoch, acceptAuthorizedTaskCancellation, taskCancellationManaged, pendingTaskCancellations, finishTaskCancellationIntent, unknownTaskCancellation } from "./task-cancellation.ts";
17
17
  import type { TaskCancellationIntent, TaskCancellationRequest } from "./task-cancellation.ts";
18
18
  import { repairFailedResume, type RepairResumeInput } from "./recovery.ts";
@@ -26,9 +26,11 @@ import {
26
26
  requirePath,
27
27
  } from "./validate.ts";
28
28
  import { ensureSchema } from "./schema.ts";
29
- import { createContext, openDatabase, type StoreContext } from "./sqlite.ts";
29
+ import { ensureAssignmentChanges } from "./assignment-changes.ts";
30
+ import { createContext, openDatabase, run, type StoreContext } from "./sqlite.ts";
30
31
  import {
31
32
  getOperation as readOperationRecord,
33
+ listAssignmentCleanupOperations as readAssignmentCleanupOperations,
32
34
  listOperations as readOperationRecords,
33
35
  listRunningSupervisedBy as readRunningSupervisedBy,
34
36
  releaseSupervision as writeSupervisionRelease,
@@ -124,6 +126,8 @@ import {
124
126
  } from "./types.ts";
125
127
 
126
128
  export interface Store {
129
+ hasSubagentManagement(): boolean;
130
+ resultSupervisionChanges(after?: Parameters<typeof resultSupervisionChanges>[1]): ReturnType<typeof resultSupervisionChanges>;
127
131
  subagentLaunchJournal(): SubagentLaunchJournal;
128
132
  resultScopeManaged(scope: string): boolean;
129
133
  handoffResultScope(input: Parameters<typeof handoffResultScope>[1]): ReturnType<typeof handoffResultScope>;
@@ -160,18 +164,17 @@ export interface Store {
160
164
 
161
165
  // ---- operations ----
162
166
 
163
- /**
164
- * Register a durable operation for one task launch. The owner, task id,
165
- * launch token and observer are immutable: a replay of the same launch
166
- * returns `created: false`, and any difference is refused with
167
- * `operation-conflict` or `task-ownership`.
168
- */
169
167
  backgroundRequests(): BackgroundRequests;
170
168
  setParentCallbackPending(taskId: string, pending: boolean): boolean;
171
169
  listPendingParentCallbacks(scope: ParentCallbackScope, options?: ParentCallbackPage): OperationRecord[];
172
170
  listRecentBackgroundTerminals(options: RecentBackgroundTerminalPage): OperationRecord[];
173
171
  seedPendingParentCallbacks(options?: { limit?: number }): { done: boolean; seeded: number };
174
172
  setUpgradeFence(epoch: string | null): void;
173
+ /**
174
+ * Register a durable launch. Owner, task id, launch token, observer, and
175
+ * assignment attempt provenance are immutable. An exact replay returns
176
+ * `created: false`, even after assignment end, and admits no new work.
177
+ */
175
178
  registerOperation(input: RegisterOperationInput): RegisterOperationResult;
176
179
  /**
177
180
  * Replace supervision identity and/or report observer health
@@ -196,6 +199,12 @@ export interface Store {
196
199
  recordTerminalOutcome(input: RecordTerminalOutcomeInput): RecordTerminalOutcomeResult;
197
200
  getOperation(operationId: string): OperationRecord | null;
198
201
  listOperations(filter?: OperationFilter): OperationRecord[];
202
+ /**
203
+ * Read up to 256 unfinished cleanup obligations in operation id order.
204
+ * The cursor is exclusive. Start each new sweep without a cursor.
205
+ */
206
+ listAssignmentCleanupOperations(limit: number, afterOperationId?: string): OperationRecord[];
207
+ verifyAssignmentCleanup(operationId: string, launchToken: string, terminalRevision: number): boolean;
199
208
  /** Running operations currently assigned to this supervising host. */
200
209
  listRunningSupervisedBy(hostId: string): OperationRecord[];
201
210
  listOperationEvidence(operationId: string, terminalRevision?: number): OperationEvidenceRecord[];
@@ -327,6 +336,7 @@ export function openStore(options: StoreOptions): Store {
327
336
  const ctx: StoreContext = createContext(db, options.now ? { now: options.now } : {});
328
337
  try {
329
338
  ensureSchema(ctx);
339
+ ensureAssignmentChanges(ctx);
330
340
  } catch (error) {
331
341
  try {
332
342
  db.close();
@@ -351,6 +361,8 @@ export function openStore(options: StoreOptions): Store {
351
361
  resultScopeManaged(scope) { alive(); return resultScopeManaged(ctx, scope); },
352
362
  handoffResultScope(input) { alive(); return handoffResultScope(ctx, input); },
353
363
  resultSupervision(id) { alive(); return resultSupervision(ctx, id); },
364
+ hasSubagentManagement() { alive(); return Boolean(ctx.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='subagent_management'").get()); },
365
+ resultSupervisionChanges(after) { alive(); return resultSupervisionChanges(ctx, after); },
354
366
  resultSupervisions(activeOnly) { alive(); return resultSupervisions(ctx, activeOnly); },
355
367
  handoffResultSupervision(input) { alive(); return handoffResultSupervision(ctx, input); },
356
368
  handoffResultSupervisions(input) { alive(); return handoffResultSupervisions(ctx, input); },
@@ -408,6 +420,20 @@ export function openStore(options: StoreOptions): Store {
408
420
  alive();
409
421
  return readOperationRecords(ctx, filter);
410
422
  },
423
+ listAssignmentCleanupOperations(limit, afterOperationId) {
424
+ alive();
425
+ return readAssignmentCleanupOperations(ctx, limit, afterOperationId);
426
+ },
427
+ verifyAssignmentCleanup(operationId, launchToken, terminalRevision) {
428
+ alive();
429
+ if (!Number.isSafeInteger(terminalRevision) || terminalRevision < 1) return false;
430
+ return run(ctx, `INSERT OR IGNORE INTO coordinator_state (key, value)
431
+ SELECT 'assignment-cleanup-verified:' || op.operation_id, op.launch_token
432
+ FROM operations op JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
433
+ JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
434
+ WHERE op.operation_id = ? AND op.launch_token = ? AND op.terminal_revision = ?`,
435
+ operationId, launchToken, terminalRevision) > 0;
436
+ },
411
437
  listRunningSupervisedBy(hostId) {
412
438
  alive();
413
439
  return readRunningSupervisedBy(ctx, hostId);
@@ -1,6 +1,6 @@
1
1
  // Generated fixed launch domain from packages/pi-better-subagents/shared-operation-coordinator/src/subagent-launch.ts. Do not edit directly.
2
2
  // Generated from packages/operation-coordinator/src/subagent-launch.ts. Do not edit directly.
3
- import { randomBytes } from "node:crypto";
3
+ import { createHash, randomBytes } from "node:crypto";
4
4
  /** Fixed launch journal on the coordinator's existing connection and transaction. */
5
5
  export class SubagentLaunchJournal {
6
6
  context;
@@ -41,6 +41,25 @@ export class SubagentLaunchJournal {
41
41
  pendingIntents() {
42
42
  return this.db.prepare("SELECT * FROM subagent_launch_intents WHERE state='accepted'").all();
43
43
  }
44
+ progressKey(owner, key) { return `launch-progress:${createHash('sha256').update(JSON.stringify([owner, key])).digest('hex')}`; }
45
+ progress(owner, key) {
46
+ const row = this.db.prepare('SELECT value FROM coordinator_state WHERE key=?').get(this.progressKey(owner, key));
47
+ return row ? JSON.parse(String(row.value)) : undefined;
48
+ }
49
+ noteProgress(owner, key) {
50
+ const previous = this.progress(owner, key), now = Date.now();
51
+ this.db.prepare('INSERT OR REPLACE INTO coordinator_state (key,value) VALUES (?,?)').run(this.progressKey(owner, key), JSON.stringify({ acceptedAt: previous?.acceptedAt ?? now, lastProgressAt: now }));
52
+ }
53
+ lifecycleReasons(owner, key) {
54
+ const exact = owner !== undefined && key !== undefined ? this.read(owner, key) : undefined;
55
+ const intents = owner !== undefined ? exact?.state === 'accepted' ? [exact] : [] : this.pendingIntents();
56
+ return intents.map(intent => ({ kind: 'task', id: this.progressKey(intent.owner, intent.request_key),
57
+ owner: intent.owner, management: { epoch: intent.epoch }, acceptedAt: this.progress(intent.owner, intent.request_key)?.acceptedAt ?? null,
58
+ lastProgressAt: this.progress(intent.owner, intent.request_key)?.lastProgressAt ?? null, executionDeadline: null, nextDeadline: null,
59
+ attempts: JSON.parse(intent.attempts).map(attempt => ({ id: attempt.id, sessionId: attempt.sessionId,
60
+ state: attempt.state, writer: { pid: attempt.writerPid ?? attempt.pid, start: attempt.writerStartTime ?? attempt.pidStartTime } })),
61
+ recovery: 'drain-accepted-launch-until-journal-return-or-authoritative-handoff' }));
62
+ }
44
63
  finishRecovery(owner, key, epoch, result) {
45
64
  this.transaction(() => {
46
65
  this.current(epoch);
@@ -58,6 +77,7 @@ export class SubagentLaunchJournal {
58
77
  return { prior: true, ...prior };
59
78
  }
60
79
  this.db.prepare("INSERT INTO subagent_launch_intents VALUES (?, ?, ?, ?, 'accepted', '[]', NULL)").run(owner, key, digest, epoch);
80
+ this.noteProgress(owner, key);
61
81
  return this.read(owner, key);
62
82
  });
63
83
  }
@@ -73,6 +93,7 @@ export class SubagentLaunchJournal {
73
93
  const attempt = { ...input, token: randomBytes(32).toString("hex"), state: "prepared" };
74
94
  attempts.push(attempt);
75
95
  this.db.prepare("UPDATE subagent_launch_intents SET attempts=? WHERE owner=? AND request_key=?").run(JSON.stringify(attempts), owner, key);
96
+ this.noteProgress(owner, key);
76
97
  return attempt;
77
98
  });
78
99
  }
@@ -87,6 +108,7 @@ export class SubagentLaunchJournal {
87
108
  throw new Error("Launch writer does not match spawned process");
88
109
  Object.assign(attempt, { state: "spawned", pid, pidStartTime });
89
110
  this.db.prepare("UPDATE subagent_launch_intents SET attempts=? WHERE owner=? AND request_key=?").run(JSON.stringify(attempts), owner, key);
111
+ this.noteProgress(owner, key);
90
112
  });
91
113
  }
92
114
  finish(owner, key, epoch, result) {