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,7 +1,17 @@
1
1
  // Generated fixed launch domain from packages/pi-better-subagents/shared-operation-coordinator/assignment-observation.mjs. Do not edit directly.
2
2
  // Generated from packages/operation-coordinator/assignment-observation.mjs. Do not edit directly.
3
3
  import { createRequire } from "node:module";
4
- import { createHash } from "node:crypto";
4
+ import { AssignmentInbox } from "./assignment-inbox.mjs";
5
+ import { pathToFileURL } from "node:url";
6
+ // Only first-party source SQL passes this facade; quoted values stay untouched.
7
+ const sourceTables = new Set(["schema_meta", "sqlite_master", "sqlite_schema", "assignment_change_source", "assignment_changes",
8
+ "waits", "wait_dependencies", "resume_claims", "operations", "coordinator_state", "assignment_outcomes",
9
+ "subagent_launch_intents", "background_input_versions", "background_parent_callbacks", "assignments", "assignment_bindings", "assignment_attempts"]);
10
+ function sourceSQL(sql) {
11
+ if (/^PRAGMA\s+data_version\s*$/i.test(sql))
12
+ return "PRAGMA coordinator_source.data_version";
13
+ return sql.replace(/'(?:''|[^'])*'|\b[A-Za-z_][A-Za-z_0-9]*\b/g, token => sourceTables.has(token) ? `coordinator_source.${token}` : token);
14
+ }
5
15
  /** Read-only, bounded projection input. Never creates/migrates a database. */
6
16
  export function readAssignmentWaits(path, owner, connection) {
7
17
  let db;
@@ -46,12 +56,25 @@ export function readAssignmentWaits(path, owner, connection) {
46
56
  }
47
57
  }
48
58
  /** A root read model owns this connection; ordinary observers remain one-shot. */
49
- export function createAssignmentReader(path) {
59
+ export function createAssignmentReader(path, inboxPath = ":memory:", derivedConnection, options = {}) {
60
+ const inbox = new AssignmentInbox(inboxPath, derivedConnection);
50
61
  let db;
51
62
  let identity;
52
63
  let snapshot = false;
64
+ const composed = options.composed === true;
65
+ const owner = derivedConnection;
66
+ const dropSource = () => {
67
+ if (composed) {
68
+ if (db)
69
+ owner.exec("DETACH DATABASE coordinator_source");
70
+ }
71
+ else
72
+ db?.close();
73
+ db = undefined;
74
+ statements.clear();
75
+ };
53
76
  const statements = new Map();
54
- return {
77
+ const reader = {
55
78
  revision() {
56
79
  const { statSync } = createRequire(import.meta.url)("node:fs");
57
80
  const stat = statSync(path, { bigint: true });
@@ -59,28 +82,40 @@ export function createAssignmentReader(path) {
59
82
  if (identity !== next) {
60
83
  if (snapshot)
61
84
  throw new Error("Coordinator identity changed during observation");
62
- db?.close();
63
- db = undefined;
64
- statements.clear();
85
+ dropSource();
65
86
  identity = next;
66
87
  }
67
88
  const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
68
- db ??= new DatabaseSync(path, { readOnly: true });
89
+ if (!db) {
90
+ if (composed) {
91
+ const uri = pathToFileURL(path);
92
+ uri.searchParams.set("mode", "ro");
93
+ owner.prepare("ATTACH DATABASE ? AS coordinator_source").run(uri.href);
94
+ db = { prepare: sql => owner.prepare(sourceSQL(sql)), get observationActive() { return snapshot; }, beginSnapshot: () => reader.beginSnapshot() };
95
+ }
96
+ else
97
+ db = new DatabaseSync(path, { readOnly: true });
98
+ }
69
99
  return `${identity}:${db.prepare("PRAGMA data_version").get().data_version}`;
70
100
  },
71
101
  connection(refresh = true) { if (refresh)
72
102
  this.revision(); return db; },
103
+ changes() { this.revision(); return inbox.receive(db, identity); },
104
+ acknowledgeChanges(batch, complete) { inbox.acknowledge(batch, complete); },
105
+ get changeMetrics() { return inbox.metrics; },
106
+ get snapshotActive() { return snapshot; },
73
107
  beginSnapshot() {
74
108
  this.revision();
75
109
  if (snapshot)
76
110
  throw new Error("Coordinator snapshot already open");
77
- db.exec("BEGIN");
111
+ const transaction = composed ? owner : db;
112
+ transaction.exec("BEGIN");
78
113
  snapshot = true;
79
114
  const release = () => {
80
115
  if (!snapshot)
81
116
  return;
82
117
  try {
83
- db.exec("ROLLBACK");
118
+ transaction.exec("ROLLBACK");
84
119
  }
85
120
  finally {
86
121
  snapshot = false;
@@ -89,7 +124,12 @@ export function createAssignmentReader(path) {
89
124
  try {
90
125
  // Pin the WAL read view before recording its revision; other writers keep advancing.
91
126
  db.prepare("SELECT count(*) FROM sqlite_schema").get();
92
- return { revision: this.revision(), release };
127
+ return { revision: this.revision(), release, commit: () => {
128
+ if (!snapshot)
129
+ return;
130
+ transaction.exec("COMMIT");
131
+ snapshot = false;
132
+ } };
93
133
  }
94
134
  catch (error) {
95
135
  release();
@@ -109,35 +149,6 @@ export function createAssignmentReader(path) {
109
149
  return { verified: false, waits: [], reason: "Coordinator state is unverified; compatible supervision is unavailable." };
110
150
  }
111
151
  },
112
- conversationRevisions() {
113
- try {
114
- this.revision();
115
- if (!["1", "2", "3", "4"].includes(db.prepare("SELECT value FROM schema_meta WHERE key = 'schema_version'").get()?.value))
116
- return undefined;
117
- const hashes = new Map();
118
- const add = (sessionId, workspace, value) => {
119
- const key = JSON.stringify([sessionId, workspace]);
120
- if (!hashes.has(key))
121
- hashes.set(key, createHash("sha256"));
122
- hashes.get(key).update(JSON.stringify(value));
123
- };
124
- // One source pass per changed database revision, instead of one
125
- // projection/query/log parse for every historical attempt.
126
- for (const row of db.prepare(`SELECT w.*, (SELECT json_group_array(attempt_id)
127
- FROM resume_claims c WHERE c.wait_id = w.wait_id AND c.generation = w.generation) AS claimed_attempts
128
- FROM waits w WHERE owner_kind = 'worker-conversation' ORDER BY wait_id, generation`).all()) {
129
- add(row.owner_session_id, row.owner_workspace, row);
130
- }
131
- for (const row of db.prepare("SELECT record_json FROM assignment_outcomes ORDER BY assignment_id").all()) {
132
- const record = JSON.parse(row.record_json);
133
- add(record.owner.sessionId, record.owner.workspace, record);
134
- }
135
- return new Map([...hashes].map(([key, hash]) => [key, hash.digest("hex")]));
136
- }
137
- catch {
138
- return undefined;
139
- }
140
- },
141
152
  upgradeObligations() {
142
153
  try {
143
154
  this.revision();
@@ -170,8 +181,9 @@ export function createAssignmentReader(path) {
170
181
  return [...obligations, ...reasons];
171
182
  },
172
183
  close() { if (snapshot) {
173
- db.exec("ROLLBACK");
184
+ (composed ? owner : db).exec("ROLLBACK");
174
185
  snapshot = false;
175
- } db?.close(); db = undefined; statements.clear(); identity = undefined; },
186
+ } dropSource(); identity = undefined; inbox.close(); },
176
187
  };
188
+ return reader;
177
189
  }
@@ -0,0 +1,75 @@
1
+ // Generated fixed launch domain from packages/pi-better-subagents/shared-operation-coordinator/src/assignment-changes.ts. Do not edit directly.
2
+ /** Additive observation journal. Triggers also cover already-running old writers. */
3
+ export function ensureAssignmentChanges(ctx) {
4
+ ctx.transaction(() => {
5
+ ctx.db.exec(`CREATE TABLE IF NOT EXISTS assignment_change_source (
6
+ singleton INTEGER PRIMARY KEY CHECK(singleton=1), generation TEXT NOT NULL);
7
+ INSERT OR IGNORE INTO assignment_change_source VALUES(1, lower(hex(randomblob(16))));
8
+ CREATE TABLE IF NOT EXISTS assignment_changes (
9
+ seq INTEGER PRIMARY KEY AUTOINCREMENT, entity TEXT NOT NULL, entity_id TEXT NOT NULL DEFAULT '',
10
+ assignment_id TEXT, session_id TEXT NOT NULL, workspace TEXT NOT NULL,
11
+ changed_at INTEGER NOT NULL DEFAULT (unixepoch()*1000));
12
+ CREATE INDEX IF NOT EXISTS waits_assignment_observation ON waits
13
+ (owner_kind,owner_session_id,owner_workspace,json_extract(origin_json,'$.assignmentRef'),created_at DESC,generation DESC);
14
+ CREATE INDEX IF NOT EXISTS resume_claims_wait_observation ON resume_claims(wait_id,generation,attempt_id);
15
+ CREATE TABLE IF NOT EXISTS background_input_versions (
16
+ operation_id TEXT PRIMARY KEY, revision INTEGER NOT NULL);
17
+ CREATE TRIGGER IF NOT EXISTS assignment_changes_retention AFTER INSERT ON assignment_changes
18
+ BEGIN DELETE FROM assignment_changes WHERE seq <= NEW.seq - 4096; END;`);
19
+ // Repair is an operation-ID keyset, not an observer equality lookup.
20
+ // A leading observer column competes with the ordered recent-terminal index.
21
+ if (ctx.db.prepare("PRAGMA index_info(background_operation_repair)").all().length > 1)
22
+ ctx.db.exec("DROP INDEX background_operation_repair");
23
+ ctx.db.exec("CREATE INDEX IF NOT EXISTS background_operation_repair ON operations(operation_id) WHERE observer_kind='local-supervisor'");
24
+ const sources = [
25
+ { table: "waits", select: (r) => `SELECT 'wait', ${r}.wait_id || ':' || ${r}.generation, json_extract(${r}.origin_json,'$.assignmentRef'), ${r}.owner_session_id, ${r}.owner_workspace WHERE ${r}.owner_kind='worker-conversation'` },
26
+ { table: "resume_claims", select: (r) => `SELECT 'claim', ${r}.claim_id, json_extract(w.origin_json,'$.assignmentRef'), w.owner_session_id, w.owner_workspace FROM waits w WHERE w.wait_id=${r}.wait_id AND w.generation=${r}.generation AND w.owner_kind='worker-conversation'` },
27
+ { table: "assignment_bindings", select: (r) => `SELECT 'binding', ${r}.assignment_id, ${r}.assignment_id, json_extract(${r}.owner_json,'$.sessionId'), json_extract(${r}.owner_json,'$.workspace')` },
28
+ { table: "assignment_attempts", select: (r) => `SELECT 'attempt', ${r}.attempt_id, b.assignment_id, json_extract(b.owner_json,'$.sessionId'), json_extract(b.owner_json,'$.workspace') FROM assignment_bindings b WHERE b.assignment_id=${r}.assignment_id` },
29
+ { table: "assignment_outcomes", select: (r) => `SELECT 'outcome', ${r}.assignment_id, ${r}.assignment_id, json_extract(${r}.record_json,'$.owner.sessionId'), json_extract(${r}.record_json,'$.owner.workspace')` },
30
+ { table: "outbox_events", select: (r) => `SELECT 'receipt', ${r}.event_id, b.assignment_id, json_extract(b.owner_json,'$.sessionId'), json_extract(b.owner_json,'$.workspace') FROM assignment_bindings b WHERE b.assignment_id=${r}.operation_id UNION ALL SELECT 'receipt', ${r}.event_id, json_extract(w.origin_json,'$.assignmentRef'), w.owner_session_id, w.owner_workspace FROM waits w WHERE w.wait_id=${r}.wait_id AND w.generation=${r}.generation AND w.owner_kind='worker-conversation'` },
31
+ ];
32
+ for (const { table, select } of sources)
33
+ for (const action of ["INSERT", "UPDATE", "DELETE"]) {
34
+ const records = action === "UPDATE" ? ["OLD", "NEW"] : [action === "DELETE" ? "OLD" : "NEW"];
35
+ ctx.db.exec(`CREATE TRIGGER IF NOT EXISTS assignment_change_${table}_${action.toLowerCase()} AFTER ${action} ON ${table} BEGIN ${records.map(r => `INSERT INTO assignment_changes(entity,entity_id,assignment_id,session_id,workspace) ${select(r)};`).join(" ")} END;`);
36
+ }
37
+ // These are observation inputs, not execution or delivery authority. Old
38
+ // cooperative SQL writers inherit the same atomic invalidation triggers.
39
+ const backgroundSources = [
40
+ { table: "operations", select: (r) => `SELECT ${r}.operation_id, 1 WHERE ${r}.observer_kind='local-supervisor'` },
41
+ { table: "waits", select: (r) => `SELECT d.operation_id, 1 FROM wait_dependencies d JOIN operations o ON o.operation_id=d.operation_id WHERE d.wait_id=${r}.wait_id AND d.generation=${r}.generation AND o.observer_kind='local-supervisor'` },
42
+ { table: "wait_dependencies", select: (r) => `SELECT ${r}.operation_id, 1 WHERE EXISTS(SELECT 1 FROM operations o WHERE o.operation_id=${r}.operation_id AND o.observer_kind='local-supervisor')` },
43
+ { table: "background_parent_callbacks", select: (r) => `SELECT ${r}.operation_id, 1 WHERE 1` },
44
+ { table: "coordinator_state", select: (r) => `SELECT o.operation_id, 1 FROM operations o WHERE ${r}.key LIKE 'result-supervision-v1:%' AND o.operation_id=substr(${r}.key,length('result-supervision-v1:')+1) AND o.observer_kind='local-supervisor'` },
45
+ ];
46
+ // Version 1 installed one-column SELECTs into a two-column INSERT. Replace
47
+ // only these owned triggers, atomically, without resetting source positions.
48
+ const replaceBackgroundTriggers = ctx.db.prepare("SELECT value FROM schema_meta WHERE key='background_input_triggers_version'").get()?.value !== "2";
49
+ for (const { table, select } of backgroundSources)
50
+ for (const action of ["INSERT", "UPDATE", "DELETE"]) {
51
+ if (replaceBackgroundTriggers)
52
+ ctx.db.exec(`DROP TRIGGER IF EXISTS background_input_${table}_${action.toLowerCase()}`);
53
+ const records = action === "UPDATE" ? ["OLD", "NEW"] : [action === "DELETE" ? "OLD" : "NEW"];
54
+ ctx.db.exec(`CREATE TRIGGER IF NOT EXISTS background_input_${table}_${action.toLowerCase()}
55
+ ${action === "DELETE" ? "BEFORE" : "AFTER"} ${action} ON ${table} BEGIN
56
+ ${records.map(r => `INSERT INTO background_input_versions(operation_id,revision) ${select(r)}
57
+ ON CONFLICT(operation_id) DO UPDATE SET revision=revision+1;`).join(" ")}
58
+ END;`);
59
+ }
60
+ if (replaceBackgroundTriggers)
61
+ ctx.db.prepare("INSERT OR REPLACE INTO schema_meta(key,value) VALUES('background_input_triggers_version','2')").run();
62
+ ctx.db.exec(`CREATE TRIGGER IF NOT EXISTS background_journal_insert AFTER INSERT ON background_input_versions BEGIN
63
+ INSERT INTO assignment_changes(entity,entity_id,assignment_id,session_id,workspace)
64
+ SELECT 'background:operation', NEW.operation_id, NEW.operation_id, owner_session_id, owner_workspace FROM operations WHERE operation_id=NEW.operation_id;
65
+ END;
66
+ CREATE TRIGGER IF NOT EXISTS background_journal_update AFTER UPDATE ON background_input_versions BEGIN
67
+ INSERT INTO assignment_changes(entity,entity_id,assignment_id,session_id,workspace)
68
+ SELECT 'background:operation', NEW.operation_id, NEW.operation_id, owner_session_id, owner_workspace FROM operations WHERE operation_id=NEW.operation_id;
69
+ END;
70
+ CREATE TRIGGER IF NOT EXISTS background_journal_previous_scope AFTER UPDATE ON operations
71
+ WHEN OLD.observer_kind='local-supervisor' AND (OLD.owner_session_id<>NEW.owner_session_id OR OLD.owner_workspace<>NEW.owner_workspace OR OLD.owner_kind<>NEW.owner_kind)
72
+ BEGIN INSERT INTO assignment_changes(entity,entity_id,assignment_id,session_id,workspace)
73
+ VALUES('background:operation',OLD.operation_id,OLD.operation_id,OLD.owner_session_id,OLD.owner_workspace); END;`);
74
+ });
75
+ }
@@ -0,0 +1,73 @@
1
+ // Generated from packages/operation-coordinator/src/assignment-changes.ts. Do not edit directly.
2
+ import type { StoreContext } from "./sqlite.ts";
3
+
4
+ /** Additive observation journal. Triggers also cover already-running old writers. */
5
+ export function ensureAssignmentChanges(ctx: StoreContext): void {
6
+ ctx.transaction(() => {
7
+ ctx.db.exec(`CREATE TABLE IF NOT EXISTS assignment_change_source (
8
+ singleton INTEGER PRIMARY KEY CHECK(singleton=1), generation TEXT NOT NULL);
9
+ INSERT OR IGNORE INTO assignment_change_source VALUES(1, lower(hex(randomblob(16))));
10
+ CREATE TABLE IF NOT EXISTS assignment_changes (
11
+ seq INTEGER PRIMARY KEY AUTOINCREMENT, entity TEXT NOT NULL, entity_id TEXT NOT NULL DEFAULT '',
12
+ assignment_id TEXT, session_id TEXT NOT NULL, workspace TEXT NOT NULL,
13
+ changed_at INTEGER NOT NULL DEFAULT (unixepoch()*1000));
14
+ CREATE INDEX IF NOT EXISTS waits_assignment_observation ON waits
15
+ (owner_kind,owner_session_id,owner_workspace,json_extract(origin_json,'$.assignmentRef'),created_at DESC,generation DESC);
16
+ CREATE INDEX IF NOT EXISTS resume_claims_wait_observation ON resume_claims(wait_id,generation,attempt_id);
17
+ CREATE TABLE IF NOT EXISTS background_input_versions (
18
+ operation_id TEXT PRIMARY KEY, revision INTEGER NOT NULL);
19
+ CREATE TRIGGER IF NOT EXISTS assignment_changes_retention AFTER INSERT ON assignment_changes
20
+ BEGIN DELETE FROM assignment_changes WHERE seq <= NEW.seq - 4096; END;`);
21
+ // Repair is an operation-ID keyset, not an observer equality lookup.
22
+ // A leading observer column competes with the ordered recent-terminal index.
23
+ if (ctx.db.prepare("PRAGMA index_info(background_operation_repair)").all().length > 1)
24
+ ctx.db.exec("DROP INDEX background_operation_repair");
25
+ ctx.db.exec("CREATE INDEX IF NOT EXISTS background_operation_repair ON operations(operation_id) WHERE observer_kind='local-supervisor'");
26
+ const sources = [
27
+ { table: "waits", select: (r: string) => `SELECT 'wait', ${r}.wait_id || ':' || ${r}.generation, json_extract(${r}.origin_json,'$.assignmentRef'), ${r}.owner_session_id, ${r}.owner_workspace WHERE ${r}.owner_kind='worker-conversation'` },
28
+ { table: "resume_claims", select: (r: string) => `SELECT 'claim', ${r}.claim_id, json_extract(w.origin_json,'$.assignmentRef'), w.owner_session_id, w.owner_workspace FROM waits w WHERE w.wait_id=${r}.wait_id AND w.generation=${r}.generation AND w.owner_kind='worker-conversation'` },
29
+ { table: "assignment_bindings", select: (r: string) => `SELECT 'binding', ${r}.assignment_id, ${r}.assignment_id, json_extract(${r}.owner_json,'$.sessionId'), json_extract(${r}.owner_json,'$.workspace')` },
30
+ { table: "assignment_attempts", select: (r: string) => `SELECT 'attempt', ${r}.attempt_id, b.assignment_id, json_extract(b.owner_json,'$.sessionId'), json_extract(b.owner_json,'$.workspace') FROM assignment_bindings b WHERE b.assignment_id=${r}.assignment_id` },
31
+ { table: "assignment_outcomes", select: (r: string) => `SELECT 'outcome', ${r}.assignment_id, ${r}.assignment_id, json_extract(${r}.record_json,'$.owner.sessionId'), json_extract(${r}.record_json,'$.owner.workspace')` },
32
+ { table: "outbox_events", select: (r: string) => `SELECT 'receipt', ${r}.event_id, b.assignment_id, json_extract(b.owner_json,'$.sessionId'), json_extract(b.owner_json,'$.workspace') FROM assignment_bindings b WHERE b.assignment_id=${r}.operation_id UNION ALL SELECT 'receipt', ${r}.event_id, json_extract(w.origin_json,'$.assignmentRef'), w.owner_session_id, w.owner_workspace FROM waits w WHERE w.wait_id=${r}.wait_id AND w.generation=${r}.generation AND w.owner_kind='worker-conversation'` },
33
+ ];
34
+ for (const { table, select } of sources) for (const action of ["INSERT", "UPDATE", "DELETE"]) {
35
+ const records = action === "UPDATE" ? ["OLD", "NEW"] : [action === "DELETE" ? "OLD" : "NEW"];
36
+ ctx.db.exec(`CREATE TRIGGER IF NOT EXISTS assignment_change_${table}_${action.toLowerCase()} AFTER ${action} ON ${table} BEGIN ${records.map(r => `INSERT INTO assignment_changes(entity,entity_id,assignment_id,session_id,workspace) ${select(r)};`).join(" ")} END;`);
37
+ }
38
+ // These are observation inputs, not execution or delivery authority. Old
39
+ // cooperative SQL writers inherit the same atomic invalidation triggers.
40
+ const backgroundSources = [
41
+ { table: "operations", select: (r: string) => `SELECT ${r}.operation_id, 1 WHERE ${r}.observer_kind='local-supervisor'` },
42
+ { table: "waits", select: (r: string) => `SELECT d.operation_id, 1 FROM wait_dependencies d JOIN operations o ON o.operation_id=d.operation_id WHERE d.wait_id=${r}.wait_id AND d.generation=${r}.generation AND o.observer_kind='local-supervisor'` },
43
+ { table: "wait_dependencies", select: (r: string) => `SELECT ${r}.operation_id, 1 WHERE EXISTS(SELECT 1 FROM operations o WHERE o.operation_id=${r}.operation_id AND o.observer_kind='local-supervisor')` },
44
+ { table: "background_parent_callbacks", select: (r: string) => `SELECT ${r}.operation_id, 1 WHERE 1` },
45
+ { table: "coordinator_state", select: (r: string) => `SELECT o.operation_id, 1 FROM operations o WHERE ${r}.key LIKE 'result-supervision-v1:%' AND o.operation_id=substr(${r}.key,length('result-supervision-v1:')+1) AND o.observer_kind='local-supervisor'` },
46
+ ];
47
+ // Version 1 installed one-column SELECTs into a two-column INSERT. Replace
48
+ // only these owned triggers, atomically, without resetting source positions.
49
+ const replaceBackgroundTriggers = ctx.db.prepare("SELECT value FROM schema_meta WHERE key='background_input_triggers_version'").get()?.value !== "2";
50
+ for (const { table, select } of backgroundSources) for (const action of ["INSERT", "UPDATE", "DELETE"]) {
51
+ if (replaceBackgroundTriggers) ctx.db.exec(`DROP TRIGGER IF EXISTS background_input_${table}_${action.toLowerCase()}`);
52
+ const records = action === "UPDATE" ? ["OLD", "NEW"] : [action === "DELETE" ? "OLD" : "NEW"];
53
+ ctx.db.exec(`CREATE TRIGGER IF NOT EXISTS background_input_${table}_${action.toLowerCase()}
54
+ ${action === "DELETE" ? "BEFORE" : "AFTER"} ${action} ON ${table} BEGIN
55
+ ${records.map(r => `INSERT INTO background_input_versions(operation_id,revision) ${select(r)}
56
+ ON CONFLICT(operation_id) DO UPDATE SET revision=revision+1;`).join(" ")}
57
+ END;`);
58
+ }
59
+ if (replaceBackgroundTriggers) ctx.db.prepare("INSERT OR REPLACE INTO schema_meta(key,value) VALUES('background_input_triggers_version','2')").run();
60
+ ctx.db.exec(`CREATE TRIGGER IF NOT EXISTS background_journal_insert AFTER INSERT ON background_input_versions BEGIN
61
+ INSERT INTO assignment_changes(entity,entity_id,assignment_id,session_id,workspace)
62
+ SELECT 'background:operation', NEW.operation_id, NEW.operation_id, owner_session_id, owner_workspace FROM operations WHERE operation_id=NEW.operation_id;
63
+ END;
64
+ CREATE TRIGGER IF NOT EXISTS background_journal_update AFTER UPDATE ON background_input_versions BEGIN
65
+ INSERT INTO assignment_changes(entity,entity_id,assignment_id,session_id,workspace)
66
+ SELECT 'background:operation', NEW.operation_id, NEW.operation_id, owner_session_id, owner_workspace FROM operations WHERE operation_id=NEW.operation_id;
67
+ END;
68
+ CREATE TRIGGER IF NOT EXISTS background_journal_previous_scope AFTER UPDATE ON operations
69
+ WHEN OLD.observer_kind='local-supervisor' AND (OLD.owner_session_id<>NEW.owner_session_id OR OLD.owner_workspace<>NEW.owner_workspace OR OLD.owner_kind<>NEW.owner_kind)
70
+ BEGIN INSERT INTO assignment_changes(entity,entity_id,assignment_id,session_id,workspace)
71
+ VALUES('background:operation',OLD.operation_id,OLD.operation_id,OLD.owner_session_id,OLD.owner_workspace); END;`);
72
+ });
73
+ }
@@ -1,6 +1,7 @@
1
1
  // Generated fixed launch domain from packages/pi-better-subagents/shared-operation-coordinator/src/assignment-outcomes.ts. Do not edit directly.
2
2
  // Generated from packages/operation-coordinator/src/assignment-outcomes.ts. Do not edit directly.
3
3
  import { createHash, randomUUID } from "node:crypto";
4
+ import { bumpChangeRevision } from "./discovery.domain.mjs";
4
5
  import { StoreError } from "./errors.domain.mjs";
5
6
  import { columnText, getRow, getRows, run } from "./sqlite.domain.mjs";
6
7
  import { requireWait, readPins } from "./rows.domain.mjs";
@@ -108,6 +109,7 @@ export function recordAssignmentOutcome(ctx, input) {
108
109
  for (const e of retained)
109
110
  run(ctx, `INSERT OR IGNORE INTO evidence_pins (pin_id, wait_id, generation, operation_id, terminal_revision, kind, ref, summary, detail_lost, bytes, pinned_at) VALUES (?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?)`, `pin_${randomUUID()}`, eventId, e.operationId, e.terminalRevision, e.kind, e.ref, e.summary ?? null, e.detailLost ? 1 : 0, e.bytes ?? null, at);
110
111
  run(ctx, `INSERT INTO outbox_events (event_id, event_type, operation_id, terminal_revision, wait_id, generation, recipient_kind, recipient_session_id, recipient_workspace, recipient_branch_id, recipient_goal_id, state, created_at) VALUES (?, 'assignment-outcome', ?, ?, ?, 1, ?, ?, ?, ?, ?, 'pending', ?)`, eventId, assignmentId, revision, eventId, recipient.kind, recipient.sessionId, recipient.workspace, recipient.branchId ?? null, recipient.goalId ?? null, at);
112
+ bumpChangeRevision(ctx);
111
113
  return record;
112
114
  });
113
115
  }
@@ -1,5 +1,6 @@
1
1
  // Generated from packages/operation-coordinator/src/assignment-outcomes.ts. Do not edit directly.
2
2
  import { createHash, randomUUID } from "node:crypto";
3
+ import { bumpChangeRevision } from "./discovery.ts";
3
4
  import { StoreError } from "./errors.ts";
4
5
  import { columnText, getRow, getRows, run, type StoreContext } from "./sqlite.ts";
5
6
  import { requireWait, readPins } from "./rows.ts";
@@ -120,6 +121,7 @@ export function recordAssignmentOutcome(ctx: StoreContext, input: AssignmentOutc
120
121
  }
121
122
  for (const e of retained) run(ctx, `INSERT OR IGNORE INTO evidence_pins (pin_id, wait_id, generation, operation_id, terminal_revision, kind, ref, summary, detail_lost, bytes, pinned_at) VALUES (?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?)`, `pin_${randomUUID()}`, eventId, e.operationId, e.terminalRevision, e.kind, e.ref, e.summary ?? null, e.detailLost ? 1 : 0, e.bytes ?? null, at);
122
123
  run(ctx, `INSERT INTO outbox_events (event_id, event_type, operation_id, terminal_revision, wait_id, generation, recipient_kind, recipient_session_id, recipient_workspace, recipient_branch_id, recipient_goal_id, state, created_at) VALUES (?, 'assignment-outcome', ?, ?, ?, 1, ?, ?, ?, ?, ?, 'pending', ?)`, eventId, assignmentId, revision, eventId, recipient.kind, recipient.sessionId, recipient.workspace, recipient.branchId ?? null, recipient.goalId ?? null, at);
124
+ bumpChangeRevision(ctx);
123
125
  return record;
124
126
  });
125
127
  }
@@ -24,7 +24,7 @@ export class BackgroundRequests {
24
24
  write(value) {
25
25
  this.context.db.prepare('INSERT OR REPLACE INTO coordinator_state (key,value) VALUES (?,?)').run(storageKey(value.owner, value.key), JSON.stringify(value));
26
26
  }
27
- accept(owner, key, digest) {
27
+ accept(owner, key, digest, writerFence) {
28
28
  this.alive();
29
29
  return this.context.transaction(() => {
30
30
  const prior = this.read(owner, key);
@@ -33,7 +33,7 @@ export class BackgroundRequests {
33
33
  throw new Error('request-conflict: Background request key changed content');
34
34
  return { prior: true, record: prior };
35
35
  }
36
- const record = { owner, key, digest, state: 'accepted', operations: [] };
36
+ const record = { owner, key, digest, state: 'accepted', operations: [], acceptedAt: Date.now(), lastProgressAt: Date.now(), writerFence };
37
37
  this.write(record);
38
38
  return { prior: false, record };
39
39
  });
@@ -62,9 +62,18 @@ export class BackgroundRequests {
62
62
  if (!value)
63
63
  throw new Error('Background request not admitted');
64
64
  change(value);
65
+ value.lastProgressAt = Date.now();
65
66
  this.write(value);
66
67
  });
67
68
  }
69
+ lifecycleReasons() {
70
+ return this.pending().map(record => ({ kind: 'task', id: storageKey(record.owner, record.key),
71
+ owner: record.owner, state: record.state, acceptedAt: record.acceptedAt ?? null,
72
+ writerFence: record.writerFence ?? null,
73
+ lastProgressAt: record.lastProgressAt ?? null, executionDeadline: null, nextDeadline: null,
74
+ operations: record.operations.map(({ operationId, taskId }) => ({ operationId, taskId })),
75
+ recovery: 'drain-accepted-background-request-until-journal-return-or-authoritative-handoff' }));
76
+ }
68
77
  hasPending() {
69
78
  this.alive();
70
79
  return Boolean(this.context.db.prepare(`SELECT 1 FROM coordinator_state INDEXED BY background_requests_pending WHERE ${pendingPredicate} LIMIT 1`).get());
@@ -12,6 +12,9 @@ export interface BackgroundRequest {
12
12
  token: string;
13
13
  }>;
14
14
  result?: unknown;
15
+ acceptedAt?: number;
16
+ lastProgressAt?: number;
17
+ writerFence?: { instance: string; pid: number; start: string };
15
18
  }
16
19
  const prefix = 'background-request-v1:';
17
20
  // A partial index excludes returned history. CASE protects other coordinator
@@ -36,7 +39,7 @@ export class BackgroundRequests {
36
39
  private write(value: BackgroundRequest) {
37
40
  this.context.db.prepare('INSERT OR REPLACE INTO coordinator_state (key,value) VALUES (?,?)').run(storageKey(value.owner, value.key), JSON.stringify(value));
38
41
  }
39
- accept(owner: string, key: string, digest: string) {
42
+ accept(owner: string, key: string, digest: string, writerFence?: BackgroundRequest['writerFence']) {
40
43
  this.alive();
41
44
  return this.context.transaction(() => {
42
45
  const prior = this.read(owner, key);
@@ -45,7 +48,7 @@ export class BackgroundRequests {
45
48
  throw new Error('request-conflict: Background request key changed content');
46
49
  return { prior: true, record: prior };
47
50
  }
48
- const record: BackgroundRequest = { owner, key, digest, state: 'accepted', operations: [] };
51
+ const record: BackgroundRequest = { owner, key, digest, state: 'accepted', operations: [], acceptedAt: Date.now(), lastProgressAt: Date.now(), writerFence };
49
52
  this.write(record);
50
53
  return { prior: false, record };
51
54
  });
@@ -65,7 +68,15 @@ export class BackgroundRequests {
65
68
  private update(owner: string, key: string, change: (value: BackgroundRequest) => void) {
66
69
  this.alive();
67
70
  this.context.transaction(() => { const value = this.read(owner, key); if (!value)
68
- throw new Error('Background request not admitted'); change(value); this.write(value); });
71
+ throw new Error('Background request not admitted'); change(value); value.lastProgressAt = Date.now(); this.write(value); });
72
+ }
73
+ lifecycleReasons() {
74
+ return this.pending().map(record => ({ kind: 'task', id: storageKey(record.owner, record.key),
75
+ owner: record.owner, state: record.state, acceptedAt: record.acceptedAt ?? null,
76
+ writerFence: record.writerFence ?? null,
77
+ lastProgressAt: record.lastProgressAt ?? null, executionDeadline: null, nextDeadline: null,
78
+ operations: record.operations.map(({ operationId, taskId }) => ({ operationId, taskId })),
79
+ recovery: 'drain-accepted-background-request-until-journal-return-or-authoritative-handoff' }));
69
80
  }
70
81
  hasPending(): boolean {
71
82
  this.alive();
@@ -36,9 +36,11 @@ export function readDiscoveryClaim(ctx, scope) {
36
36
  /** Read scope transfer and its discovery claim from one SQLite snapshot. */
37
37
  export function readDiscoveryState(ctx, scope) {
38
38
  scope = requireId("scope", scope);
39
- const row = getRow(ctx, `SELECT d.*, EXISTS(SELECT 1 FROM coordinator_state WHERE key = ?) AS managed
39
+ const row = getRow(ctx, `SELECT d.*, EXISTS(SELECT 1 FROM coordinator_state WHERE key = ?) AS managed,
40
+ EXISTS(SELECT 1 FROM operations INDEXED BY operations_assignment_cleanup
41
+ WHERE assignment_attempt_id IS NOT NULL) AS has_assignment_tasks
40
42
  FROM (SELECT 1) LEFT JOIN discovery_claims d ON d.scope = ?`, "result-scope-v1:" + scope, scope);
41
- return { managed: Number(row.managed) === 1, claim: row.scope == null ? null : mapClaim(row) };
43
+ return { managed: Number(row.managed) === 1, claim: row.scope == null ? null : mapClaim(row), hasAssignmentTasks: Number(row.has_assignment_tasks) === 1 };
42
44
  }
43
45
  export function tryClaimDiscovery(ctx, input) {
44
46
  const scope = requireId("scope", input.scope);
@@ -49,11 +49,13 @@ export function readDiscoveryClaim(ctx: StoreContext, scope: unknown): Discovery
49
49
  }
50
50
 
51
51
  /** Read scope transfer and its discovery claim from one SQLite snapshot. */
52
- export function readDiscoveryState(ctx: StoreContext, scope: string): { managed: boolean; claim: DiscoveryClaimRecord | null } {
52
+ export function readDiscoveryState(ctx: StoreContext, scope: string): { managed: boolean; claim: DiscoveryClaimRecord | null; hasAssignmentTasks: boolean } {
53
53
  scope = requireId("scope", scope);
54
- const row = getRow(ctx, `SELECT d.*, EXISTS(SELECT 1 FROM coordinator_state WHERE key = ?) AS managed
54
+ const row = getRow(ctx, `SELECT d.*, EXISTS(SELECT 1 FROM coordinator_state WHERE key = ?) AS managed,
55
+ EXISTS(SELECT 1 FROM operations INDEXED BY operations_assignment_cleanup
56
+ WHERE assignment_attempt_id IS NOT NULL) AS has_assignment_tasks
55
57
  FROM (SELECT 1) LEFT JOIN discovery_claims d ON d.scope = ?`, "result-scope-v1:" + scope, scope)!;
56
- return { managed: Number(row.managed) === 1, claim: row.scope == null ? null : mapClaim(row) };
58
+ return { managed: Number(row.managed) === 1, claim: row.scope == null ? null : mapClaim(row), hasAssignmentTasks: Number(row.has_assignment_tasks) === 1 };
57
59
  }
58
60
 
59
61
  export function tryClaimDiscovery(
@@ -14,13 +14,14 @@
14
14
  */
15
15
  import { StoreError } from "./errors.domain.mjs";
16
16
  import { mapOperation, ownerFromRow, readOperation, requireOperation } from "./rows.domain.mjs";
17
- import { columnText, getRows, isUniqueViolation, run, } from "./sqlite.domain.mjs";
18
- import { describeOwnerDiff, normalizeOwner, optionalText, requireBoolean, requireEnum, requireEvidenceKind, requireId, requireObserver, requireOptionalCounter, requireText, sameOwner, } from "./validate.domain.mjs";
17
+ import { columnJson, columnText, getRow, getRows, isUniqueViolation, run, } from "./sqlite.domain.mjs";
18
+ import { describeOwnerDiff, normalizeOwner, optionalText, requireBoolean, requireCounter, requireEnum, requireEvidenceKind, requireId, requireObserver, requireOptionalCounter, requireText, sameOwner, } from "./validate.domain.mjs";
19
19
  import { mapOutbox } from "./rows.domain.mjs";
20
20
  import { settleWaitsForOperation } from "./waits.domain.mjs";
21
21
  import { bumpChangeRevision } from "./discovery.domain.mjs";
22
22
  const HEALTH_VALUES = ["active", "unmonitored", "lost"];
23
23
  const OUTCOME_VALUES = ["succeeded", "failed", "cancelled", "lost"];
24
+ const ASSIGNMENT_CLEANUP_PAGE_MAX = 256;
24
25
  function normalizeSupervision(value) {
25
26
  if (value === undefined || value === null)
26
27
  return null;
@@ -70,6 +71,9 @@ export function registerOperation(ctx, input) {
70
71
  const taskId = requireId("taskId", input.taskId);
71
72
  const launchToken = requireId("launchToken", input.launchToken);
72
73
  const owner = normalizeOwner("owner", input.owner);
74
+ const assignmentAttemptId = input.assignmentAttemptId === undefined
75
+ ? undefined
76
+ : requireId("assignmentAttemptId", input.assignmentAttemptId);
73
77
  const observer = requireObserver("observer", input.observer);
74
78
  const supervision = normalizeSupervision(input.supervision);
75
79
  const authorityRef = optionalText("authorityRef", input.authorityRef, 512);
@@ -90,6 +94,8 @@ export function registerOperation(ctx, input) {
90
94
  differences.push("taskId");
91
95
  if (existing.launchToken !== launchToken)
92
96
  differences.push("launchToken");
97
+ if (existing.assignmentAttemptId !== assignmentAttemptId)
98
+ differences.push("assignmentAttemptId");
93
99
  if (!sameOwner(existing.owner, owner)) {
94
100
  differences.push(`owner (${describeOwnerDiff(existing.owner, owner)})`);
95
101
  }
@@ -107,14 +113,28 @@ export function registerOperation(ctx, input) {
107
113
  return { operation: existing, created: false };
108
114
  }
109
115
  assertTaskAvailable();
116
+ if (assignmentAttemptId !== undefined) {
117
+ const binding = getRow(ctx, `SELECT b.owner_json, o.assignment_id AS terminal_assignment_id
118
+ FROM assignment_attempts a
119
+ JOIN assignment_bindings b ON b.assignment_id = a.assignment_id
120
+ LEFT JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
121
+ WHERE a.attempt_id = ?`, assignmentAttemptId);
122
+ const capturedOwner = binding && columnJson(binding, "owner_json");
123
+ if (!binding || !capturedOwner || !sameOwner(capturedOwner, owner)) {
124
+ throw new StoreError("foreign-owner", "Operation owner must match the captured owner of a registered assignment attempt.");
125
+ }
126
+ if (binding.terminal_assignment_id !== null) {
127
+ throw new StoreError("validation", "A terminal assignment cannot register a new operation.");
128
+ }
129
+ }
110
130
  const at = ctx.now();
111
131
  try {
112
132
  run(ctx, `INSERT INTO operations (
113
133
  operation_id, task_id, launch_token,
114
- owner_kind, owner_session_id, owner_workspace, owner_branch_id, owner_goal_id,
134
+ owner_kind, owner_session_id, owner_workspace, owner_branch_id, owner_goal_id, assignment_attempt_id,
115
135
  observer_kind, observer_version, supervision_json, supervision_host_id, authority_ref, intent_ref,
116
136
  phase, health, health_reason, terminal_revision, created_at, updated_at
117
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'running', 'active', NULL, 0, ?, ?)`, operationId, taskId, launchToken, owner.kind, owner.sessionId, owner.workspace, owner.branchId ?? null, owner.goalId ?? null, observer.kind, observer.version, supervision ? JSON.stringify(supervision) : null, supervision?.hostId ?? null, authorityRef, intentRef, at, at);
137
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'running', 'active', NULL, 0, ?, ?)`, operationId, taskId, launchToken, owner.kind, owner.sessionId, owner.workspace, owner.branchId ?? null, owner.goalId ?? null, assignmentAttemptId ?? null, observer.kind, observer.version, supervision ? JSON.stringify(supervision) : null, supervision?.hostId ?? null, authorityRef, intentRef, at, at);
118
138
  }
119
139
  catch (error) {
120
140
  // Another process may have registered the same launch (or the same task)
@@ -293,6 +313,26 @@ export function listOperations(ctx, filter = {}) {
293
313
  return getRows(ctx, `SELECT *, EXISTS(SELECT 1 FROM coordinator_state s WHERE s.key = 'result-supervision-v1:' || operations.operation_id) AS result_managed FROM operations ${where} ORDER BY created_at, operation_id`, ...params)
294
314
  .map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
295
315
  }
316
+ export function listAssignmentCleanupOperations(ctx, limit, afterOperationId) {
317
+ const requested = requireCounter("limit", limit);
318
+ if (requested === 0)
319
+ throw new StoreError("validation", "Invalid limit: must be at least 1");
320
+ const cursor = afterOperationId === undefined ? "" : requireId("afterOperationId", afterOperationId);
321
+ // Seek the partial index in cursor order rather than sorting all running operations.
322
+ return getRows(ctx, `SELECT op.*, EXISTS(SELECT 1 FROM coordinator_state s
323
+ WHERE s.key = 'result-supervision-v1:' || op.operation_id) AS result_managed
324
+ FROM operations op INDEXED BY operations_assignment_cleanup
325
+ JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
326
+ JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
327
+ WHERE op.assignment_attempt_id IS NOT NULL AND op.operation_id > ?
328
+ AND (op.terminal_revision = 0 OR op.terminal_outcome = 'lost'
329
+ OR EXISTS (SELECT 1 FROM operation_evidence e WHERE e.operation_id = op.operation_id
330
+ AND e.terminal_revision = op.terminal_revision AND e.kind = 'terminal-record'
331
+ AND e.summary LIKE '%groupCleanup=unproven%'))
332
+ AND NOT EXISTS (SELECT 1 FROM coordinator_state s WHERE s.key = 'assignment-cleanup-verified:' || op.operation_id)
333
+ ORDER BY op.operation_id LIMIT ?`, cursor, Math.min(requested, ASSIGNMENT_CLEANUP_PAGE_MAX))
334
+ .map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
335
+ }
296
336
  /** Running operations assigned to one supervising host, using the phase/host index. */
297
337
  export function listRunningSupervisedBy(ctx, hostId) {
298
338
  return getRows(ctx, "SELECT *, EXISTS(SELECT 1 FROM coordinator_state s WHERE s.key = 'result-supervision-v1:' || operations.operation_id) AS result_managed FROM operations WHERE phase = 'running' AND supervision_host_id = ? ORDER BY created_at, operation_id", requireId("hostId", hostId)).map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));