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,19 +1,41 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { truncateToWidth as piTruncateToWidth, visibleWidth as piVisibleWidth } from "@earendil-works/pi-tui";
3
+ import { readHarnessSetting, updateHarnessSetting } from "./shared-harness-settings.ts";
3
4
  import type { Component } from "@earendil-works/pi-tui";
4
5
  import { createRenderScheduler, type RenderScheduler } from "./shared-render-scheduler.ts";
5
- import { setNavigatorPanel } from "./shared-navigator-panels.ts";
6
+ import { setNavigatorPanel, type NavigatorPanelLayout } from "./shared-navigator-panels.ts";
6
7
 
7
8
  export default function navigatorExtension(): void {
8
9
  // Internal shared package. Pi may scan its symlink in the extension directory
9
10
  // for sibling relative imports; loading it directly should be harmless.
10
11
  }
11
12
 
13
+ export type NavigatorView = "tree" | "flatten";
14
+ export function getNavigatorView(): NavigatorView { return state().view ?? "flatten"; }
15
+ export function loadNavigatorView(): void {
16
+ const value = readHarnessSetting("navigatorView");
17
+ state().view = value === "tree" ? "tree" : "flatten";
18
+ }
19
+ export function setNavigatorView(value: string): void {
20
+ if (value !== "tree" && value !== "flatten") throw new Error("View must be tree or flatten.");
21
+ updateHarnessSetting("navigatorView", () => value);
22
+ state().view = value;
23
+ refreshBackgroundWorkNavigator();
24
+ }
25
+
12
26
  export type BackgroundWorkStatusTone = "running" | "success" | "failed" | "warning" | "muted";
13
27
 
14
28
  export type BackgroundWorkRow = {
15
29
  providerId: string;
16
30
  id: string;
31
+ /** Stable worker conversation identity, independent of execution attempts. */
32
+ agentId?: string;
33
+ parentAgentId?: string;
34
+ readOnly?: boolean;
35
+ treeDepth?: number;
36
+ lastChild?: boolean;
37
+
38
+ ownerGroupLabel?: string;
17
39
  name?: string;
18
40
  model?: string;
19
41
  effort?: string;
@@ -70,9 +92,65 @@ export type BackgroundWorkProvider = {
70
92
  close(id: string): BackgroundWorkCloseOutcome;
71
93
  /** Return true when this detail handled the key. The navigator refreshes the sheet. */
72
94
  handleDetailInput?(id: string, data: string): boolean;
95
+ /** An explicit navigator interaction may attach a deferred work subscription. */
96
+ onOpen?(): void;
73
97
  onVisibleChanged?(notify: () => void): () => void;
74
98
  };
75
99
 
100
+ /** UI time is independent of worker time; repeated refreshes never renew it. */
101
+ export function createTerminalRowRetention(retentionMs = 30_000) {
102
+ const held = new Map<string, { row: BackgroundWorkRow; until: number }>();
103
+ const dismissed = new Set<string>();
104
+ return {
105
+ clear() { held.clear(); dismissed.clear(); },
106
+ dismiss(id: string) { held.delete(id); dismissed.add(id); },
107
+ merge(rows: BackgroundWorkRow[], now: number): BackgroundWorkRow[] {
108
+ const result: BackgroundWorkRow[] = [];
109
+ const present = new Set(rows.map(row => row.id));
110
+ for (const id of dismissed) if (!present.has(id)) dismissed.delete(id);
111
+ for (const row of rows) {
112
+ if (dismissed.has(row.id)) continue;
113
+ const terminal = ["completed", "succeeded", "failed", "cancelled", "killed", "lost", "timed_out"].includes(row.status);
114
+ if (!terminal) { held.delete(row.id); result.push(row); continue; }
115
+ let entry = held.get(row.id);
116
+ if (!entry) { entry = {row, until: now + retentionMs}; held.set(row.id, entry); }
117
+ entry.row = {...row, expiresAt: entry.until};
118
+ if (now < entry.until) result.push(entry.row);
119
+ }
120
+ for (const [id, entry] of held) {
121
+ if (present.has(id)) continue;
122
+ if (now < entry.until) result.push(entry.row);
123
+ else held.delete(id);
124
+ }
125
+ return result;
126
+ },
127
+ };
128
+ }
129
+
130
+ /** A frontend-only diagnostic, never an execution record or authority to retry. */
131
+ export async function observeNavigatorLaunch<T>(ctx: ExtensionContext, providerId: string, key: string, name: string, launch: () => Promise<T>): Promise<T> {
132
+ const scope = JSON.stringify([ctx.cwd, ctx.sessionManager?.getSessionId?.()]);
133
+ const report = (error: unknown) => {
134
+ const s = state();
135
+ if (!isNavigatorUiAvailable(s.uiCtx) || s.observationScope !== scope) return;
136
+ const id = `launch-error-${key}`;
137
+ const primary = error instanceof Error ? error.message : String(error);
138
+ const failures = s.launchFailures ??= new Map();
139
+ const identity = rowKey(providerId, id);
140
+ failures.set(identity, {providerId, id, name, status: "failed", statusTone: "failed", kind: "launch-error", elapsed: "", primary,
141
+ secondary: "Launch failed or was not confirmed; inspect before retrying.", sortStartedAt: Date.now()});
142
+ // Diagnostics are session-local and bounded, including expired tombstones.
143
+ if (failures.size > 128) failures.delete(failures.keys().next().value!);
144
+ refreshBackgroundWorkNavigator();
145
+ };
146
+ try {
147
+ const result = await launch();
148
+ const response = result as {isError?: boolean; content?: {type: string; text?: string}[]};
149
+ if (response?.isError) report(response.content?.filter(item => item.type === "text").map(item => item.text).join("\n") || "Launch request failed");
150
+ return result;
151
+ } catch (error) { report(error); throw error; }
152
+ }
153
+
76
154
  type HostDeps = {
77
155
  createDefaultEditor: (tui: unknown, theme: unknown, keybindings: unknown) => unknown;
78
156
  isOpenTrigger: (data: string) => boolean;
@@ -83,6 +161,10 @@ type HostDeps = {
83
161
 
84
162
  type NavigatorState = {
85
163
  providers: Map<string, BackgroundWorkProvider>;
164
+ view?: NavigatorView;
165
+ terminalRows?: Map<string, ReturnType<typeof createTerminalRowRetention>>;
166
+ launchFailures?: Map<string, BackgroundWorkRow>;
167
+ observationScope?: string;
86
168
  registrationTokens?: Map<string, symbol>;
87
169
  unsubscribers: Map<string, () => void>;
88
170
  uiCtx?: ExtensionContext;
@@ -202,6 +284,10 @@ export function applyCloseConfirmFooter(ui: { setStatus(key: string, value: stri
202
284
  export function ensureBackgroundWorkNavigator(ctx: ExtensionContext, deps: HostDeps, owner?: symbol): void {
203
285
  if (!isNavigatorUiAvailable(ctx)) return;
204
286
  const s = state();
287
+ if (s.view === undefined) { try { loadNavigatorView(); } catch { s.view = "flatten"; } }
288
+ const scope = JSON.stringify([ctx.cwd, ctx.sessionManager?.getSessionId?.()]);
289
+ if (s.observationScope !== scope) { s.terminalRows?.clear(); s.launchFailures?.clear(); }
290
+ s.observationScope = scope;
205
291
  s.uiCtx = ctx;
206
292
  s.uiOwner = owner;
207
293
  s.deps = {
@@ -239,6 +325,9 @@ export function disposeBackgroundWorkNavigator(ctx?: ExtensionContext, owner?: s
239
325
  stopMainListWidget();
240
326
  const activeCtx = ctx ?? s.uiCtx;
241
327
  s.uiCtx = undefined;
328
+ s.terminalRows?.clear();
329
+ s.launchFailures?.clear();
330
+ s.observationScope = undefined;
242
331
  s.uiOwner = undefined;
243
332
  if (activeCtx && isNavigatorUiAvailable(activeCtx)) {
244
333
  try { setNavigatorPanel(activeCtx, MAIN_LIST_WIDGET_KEY, undefined); } catch { /* ignore */ }
@@ -328,7 +417,7 @@ function refreshMainListWidget(): void {
328
417
  }
329
418
  if (!s.mainListWidgetInstalled) {
330
419
  try {
331
- setNavigatorPanel(ctx, MAIN_LIST_WIDGET_KEY, (tui: { requestRender?(): void }, theme: unknown) => createMainListWidget(tui, theme, deps), { placement: "aboveEditor" });
420
+ setNavigatorPanel(ctx, MAIN_LIST_WIDGET_KEY, (tui: { requestRender?(): void }, theme: unknown, layout) => createMainListWidget(tui, theme, deps, layout), { placement: "aboveEditor" });
332
421
  s.mainListWidgetInstalled = true;
333
422
  } catch { /* ignore */ }
334
423
  }
@@ -406,7 +495,7 @@ function createPointerNavigation(targetAt: (event: WidgetMouseEvent) => string |
406
495
  };
407
496
  }
408
497
 
409
- function createMainListWidget(tui: { requestRender?(): void }, theme: unknown, deps: HostDeps): MainListWidget {
498
+ function createMainListWidget(tui: { requestRender?(): void }, theme: unknown, deps: HostDeps, panelLayout: NavigatorPanelLayout = { availableRows: () => Infinity }): MainListWidget {
410
499
  const requestRender = () => tui.requestRender?.();
411
500
  state().mainListRequestRender = requestRender;
412
501
  // navigatorId per rendered line, so a pointer row resolves by structure, never by row text.
@@ -439,8 +528,23 @@ function createMainListWidget(tui: { requestRender?(): void }, theme: unknown, d
439
528
  if (hint) { layout.lines.push(deps.truncate(` ${hint}`, renderWidth(width))); layout.owners.push(undefined); }
440
529
  lineWidth = renderWidth(width);
441
530
  // The leading gap line belongs to the widget too, so its slot stays ownerless.
531
+ let rawLines = ["", ...layout.lines];
442
532
  lineOwners = [undefined, ...layout.owners];
443
- const lines = ["", ...layout.lines].map((line, index) =>
533
+ const budget = Math.max(0, Math.floor(panelLayout.availableRows()));
534
+ if (rawLines.length > budget) {
535
+ const selected = state().mainListFocused ? lineOwners.indexOf(state().mainListSelectedId) : -1;
536
+ const count = Math.max(0, budget - 1);
537
+ const start = selected >= 0 ? Math.max(0, Math.min(selected - Math.floor(count / 2), rawLines.length - count)) : 2;
538
+ rawLines = rawLines.slice(start, start + count);
539
+ lineOwners = lineOwners.slice(start, start + count);
540
+ const visible = new Set(lineOwners.filter(Boolean));
541
+ if (budget > 0) {
542
+ const hidden = rows.length - visible.size;
543
+ rawLines.push(deps.truncate(hidden ? ` +${hidden} tasks` : ` ${rows.length} tasks`, renderWidth(width)));
544
+ lineOwners.push(undefined);
545
+ }
546
+ }
547
+ const lines = rawLines.map((line, index) =>
444
548
  pointer.hovered && lineOwners[index] === pointer.hovered ? highlightPointerTarget(theme, line, lineWidth) : line);
445
549
  state().lastMainListLines = lines;
446
550
  return lines;
@@ -483,10 +587,14 @@ function listRows(now = Date.now()): InternalRow[] {
483
587
  for (const provider of providers()) {
484
588
  let providerRows: BackgroundWorkRow[] = [];
485
589
  try { providerRows = provider.listRows(now) ?? []; } catch { providerRows = []; }
590
+ providerRows = [...providerRows, ...[...(state().launchFailures?.values() ?? [])].filter(row => row.providerId === provider.id)];
591
+ const retention = state().terminalRows ??= new Map();
592
+ if (!retention.has(provider.id)) retention.set(provider.id, createTerminalRowRetention());
593
+ if (isNavigatorUiAvailable(state().uiCtx)) providerRows = retention.get(provider.id)!.merge(providerRows, now);
486
594
  const orderedProviderRows = [...providerRows].sort((a, b) => b.sortStartedAt - a.sortStartedAt || rowDisplayName(a).localeCompare(rowDisplayName(b)));
487
595
  let showSection = orderedProviderRows.length > 0 || provider.parentRow !== undefined;
488
596
  try { showSection = provider.showSection?.(orderedProviderRows, now) ?? showSection; } catch { showSection = false; }
489
- if (!showSection) continue;
597
+ if (!showSection && !(getNavigatorView() === "tree" && provider.parentRow)) continue;
490
598
  let parentRow: BackgroundWorkRow | null = null;
491
599
  try { parentRow = provider.parentRow?.(now) ?? null; } catch { parentRow = null; }
492
600
  if (parentRow) {
@@ -501,7 +609,48 @@ function listRows(now = Date.now()): InternalRow[] {
501
609
  rows.push({ ...row, navigatorId: rowKey(provider.id, row.id), providerLabel: provider.label });
502
610
  }
503
611
  }
504
- return rows;
612
+ const conversations = mergeAgentAttempts(rows);
613
+ return getNavigatorView() === "tree" ? treeRows(conversations) : conversations;
614
+ }
615
+
616
+ /** A resumed execution is still the same agent in either layout. */
617
+ export function mergeAgentAttempts<T extends BackgroundWorkRow>(rows: T[]): T[] {
618
+ const latest = new Map<string, T>();
619
+ for (const row of rows) {
620
+ if (row.providerId !== "subagents" || !row.agentId) continue;
621
+ const previous = latest.get(row.agentId);
622
+ if (!previous || row.sortStartedAt > previous.sortStartedAt
623
+ || (row.sortStartedAt === previous.sortStartedAt && row.id > previous.id)) latest.set(row.agentId, row);
624
+ }
625
+ return rows.filter(row => row.providerId !== "subagents" || !row.agentId || latest.get(row.agentId) === row);
626
+ }
627
+
628
+ /** Two levels only: agents are peers, tasks attach by captured conversation. */
629
+ export function treeRows<T extends BackgroundWorkRow>(rows: T[]): T[] {
630
+ const agents = new Map<string, T>();
631
+ for (const row of rows.filter(row => row.providerId === "subagents")) {
632
+ const key = row.agentId ?? row.id;
633
+ const prior = agents.get(key);
634
+ if (!prior || row.sortStartedAt > prior.sortStartedAt) agents.set(key, row);
635
+ }
636
+ const tasks = rows.filter(row => row.providerId !== "subagents");
637
+ const ordered = [...agents.entries()].sort(([a], [b]) => a === "main" ? -1 : b === "main" ? 1 : 0);
638
+ const result: T[] = [], attached = new Set<T>();
639
+ for (const [key, agent] of ordered) {
640
+ const children = tasks.filter(row => (row.parentAgentId ?? "main") === key);
641
+ result.push({...agent, treeDepth: 0});
642
+ children.forEach((row, i) => { result.push({...row, treeDepth: 1, lastChild: i === children.length - 1}); attached.add(row); });
643
+ }
644
+ // Never hide live work when its owner's observation has not arrived yet.
645
+ const missing = new Map<string, T[]>();
646
+ for (const row of tasks) if (!attached.has(row)) {
647
+ const key = row.parentAgentId ?? "main";
648
+ missing.set(key, [...(missing.get(key) ?? []), row]);
649
+ }
650
+ for (const [key, children] of missing) children.forEach((row, i) => result.push({...row,
651
+ treeDepth: 1, lastChild: i === children.length - 1,
652
+ ownerGroupLabel: i === 0 ? (key === "main" ? "Main" : `Agent ${key} · not running`) : undefined}));
653
+ return result;
505
654
  }
506
655
 
507
656
  function rowDisplayName(row: Pick<BackgroundWorkRow, "name" | "id">): string {
@@ -582,6 +731,15 @@ function buildMainListLayout(
582
731
  lines.push(line);
583
732
  owners.push(owner);
584
733
  };
734
+ if (getNavigatorView() === "tree") {
735
+ push(providerGroupLabel("work", fg));
736
+ for (const row of rows) {
737
+ if (row.ownerGroupLabel) push(` ${dim(row.ownerGroupLabel, fg)}`);
738
+ push(formatMainListRow(row, options.focused === true && row.navigatorId === options.selectedId, fg, width), row.navigatorId);
739
+ }
740
+ push(""); push(shortcutsLine(options.focused === true, fg));
741
+ return {lines: lines.map(line => safeTruncate(line, width, truncate)), owners};
742
+ }
585
743
  const grouped = new Map<string, InternalRow[]>();
586
744
  for (const row of rows) {
587
745
  const existing = grouped.get(row.providerLabel) ?? [];
@@ -606,8 +764,9 @@ function buildMainListLayout(
606
764
  }
607
765
 
608
766
  function shortcutsLine(focused: boolean, fg: (color: string, value: string) => string): string {
767
+ const selected = state().mainListRows?.find(row => row.navigatorId === state().mainListSelectedId);
609
768
  const keys = focused
610
- ? "↑↓ switch · Enter detail · x stop · Esc unfocus"
769
+ ? `↑↓ switch · Enter detail${selected?.readOnly || selected?.parentRow ? "" : " · x stop"} · Esc unfocus`
611
770
  : "← work navigator";
612
771
  return dim(keys, fg);
613
772
  }
@@ -618,7 +777,7 @@ function providerGroupLabel(label: string, fg: (color: string, value: string) =>
618
777
  }
619
778
 
620
779
  function formatMainListRow(row: InternalRow, selected: boolean, fg: (color: string, value: string) => string, width: number): string {
621
- const prefix = selected ? fg("accent", "› ") : " ";
780
+ const prefix = (selected ? fg("accent", "› ") : " ") + (row.treeDepth === 1 ? dim(` ${row.lastChild ? "└─" : "├─"} `, fg) : "");
622
781
  const name = row.name || row.id;
623
782
  const indicator = statusIndicator(row);
624
783
  const status = fg(indicator.color, indicator.glyph);
@@ -648,17 +807,21 @@ function statusGlyph(row: InternalRow): string {
648
807
  function statusIndicator(row: InternalRow, now = Date.now()): { glyph: string; color: string } {
649
808
  void now;
650
809
  if (row.statusTone !== "running") return { glyph: statusGlyph(row), color: toneColor(row.statusTone, row.status) };
651
- return { glyph: RUNNING_DOT_GLYPH, color: "accent" };
810
+ const glyph = row.treeDepth === 1 && row.providerId === "background-tasks" ? ">_" : RUNNING_DOT_GLYPH;
811
+ return { glyph, color: "accent" };
652
812
  }
653
813
 
654
814
  function mainListSignature(rows: InternalRow[], options: { selectedId?: string; focused?: boolean; closeHint?: string | null } = {}): string {
655
815
  return JSON.stringify({
816
+ view: getNavigatorView(),
656
817
  focused: options.focused === true,
657
818
  closeHint: options.closeHint ?? null,
658
819
  selectedId: options.focused === true ? options.selectedId ?? null : null,
659
820
  rows: rows.map((row) => ({
660
821
  navigatorId: row.navigatorId,
661
822
  providerLabel: row.providerLabel,
823
+ parentAgentId: row.parentAgentId,
824
+ agentId: row.agentId,
662
825
  parentRow: row.parentRow === true,
663
826
  providerId: row.providerId,
664
827
  id: row.id,
@@ -684,6 +847,9 @@ function stableFacts(facts: string[] | undefined): string[] {
684
847
  }
685
848
 
686
849
  function rowSummary(row: InternalRow): string {
850
+ if (getNavigatorView() === "tree" && row.providerId === "background-tasks") {
851
+ return [singleLine(row.status).replaceAll("_", " "), ...(row.facts ?? []).map(singleLine)].join(" · ");
852
+ }
687
853
  if (row.providerId === "subagents") {
688
854
  const attention = row.facts?.map(singleLine).filter(Boolean);
689
855
  if (attention?.length) return `${singleLine(row.status)} · ${attention.join(" · ")}`;
@@ -736,20 +902,33 @@ function prepareDetail(navigatorId: string, options?: {logTailLines?: number}):
736
902
 
737
903
  function detailFor(navigatorId: string, now = Date.now(), options?: { logTailLines?: number }): BackgroundWorkDetail | null {
738
904
  const { providerId, id } = splitRowKey(navigatorId);
905
+ const failed = state().launchFailures?.get(navigatorId);
906
+ if (failed) return {providerId, id, title: failed.name ?? "Launch failed", status: "failed", statusTone: "failed", metadata: [], evidence: {label: "Launch error", text: failed.primary}};
739
907
  const provider = state().providers.get(providerId);
740
908
  if (!provider) return null;
741
909
  try { return provider.detail(id, now, options); } catch { return null; }
742
910
  }
743
911
 
744
912
  function closeFor(row: InternalRow): BackgroundWorkCloseOutcome {
745
- if (row.parentRow) return { action: "not-closable", providerId: row.providerId, id: row.id };
913
+ if (row.parentRow || row.readOnly) return { action: "not-closable", providerId: row.providerId, id: row.id };
746
914
  const provider = state().providers.get(row.providerId);
915
+ if (state().launchFailures?.delete(row.navigatorId)) {
916
+ state().terminalRows?.get(row.providerId)?.dismiss(row.id);
917
+ return {action: "dismissed", providerId: row.providerId, id: row.id};
918
+ }
747
919
  if (!provider) return { action: "missing", providerId: row.providerId, id: row.id };
748
- try { return provider.close(row.id); } catch { return { action: "missing", providerId: row.providerId, id: row.id }; }
920
+ try {
921
+ const outcome = provider.close(row.id);
922
+ if (["dismissed", "stopped-and-dismissed"].includes(outcome.action)
923
+ || outcome.action === "requested" && ["completed", "succeeded", "failed", "cancelled", "killed", "lost", "timed_out"].includes(row.status)) {
924
+ state().terminalRows?.get(row.providerId)?.dismiss(row.id);
925
+ }
926
+ return outcome;
927
+ } catch { return { action: "missing", providerId: row.providerId, id: row.id }; }
749
928
  }
750
929
 
751
930
  function closeHintFor(row: InternalRow | undefined): string | null {
752
- if (!row || row.parentRow) return null;
931
+ if (!row || row.parentRow || row.readOnly) return null;
753
932
  const provider = state().providers.get(row.providerId);
754
933
  if (!provider) return null;
755
934
  try { return `${provider.armCloseLabel(row)} ${row.name || row.id}`; } catch { return null; }
@@ -807,6 +986,9 @@ function wrapEditor(inner: any, deps: HostDeps): unknown {
807
986
 
808
987
  function handleMainListInput(data: string, deps: HostDeps): boolean {
809
988
  const s = state();
989
+ if (!s.mainListFocused && deps.isOpenTrigger(data)) {
990
+ for (const provider of s.providers.values()) provider.onOpen?.();
991
+ }
810
992
  const rows = listRows();
811
993
  if (rows.length === 0) {
812
994
  // Every row is gone, but an overlay that lost focus may still be mounted: Esc still closes it.
@@ -876,7 +1058,7 @@ function dismissOverlay(): void {
876
1058
 
877
1059
  function handleMainListCloseKey(): void {
878
1060
  const row = selectedMainListRow();
879
- if (!row || row.parentRow) return;
1061
+ if (!row || row.parentRow || row.readOnly) return;
880
1062
  const s = state();
881
1063
  const now = Date.now();
882
1064
  const arm = s.mainListCloseArm;
@@ -917,6 +1099,7 @@ function openNavigator(): void {
917
1099
  const ctx = s.uiCtx;
918
1100
  const deps = s.deps;
919
1101
  if (!ctx || !deps || !isNavigatorUiAvailable(ctx)) return;
1102
+ for (const provider of s.providers.values()) provider.onOpen?.();
920
1103
  const rows = listRows();
921
1104
  if (rows.length === 0) return;
922
1105
  const selectedId = selectedMainListRow()?.navigatorId ?? rows[0]!.navigatorId;
@@ -1113,7 +1296,7 @@ function createOverlayComponent(
1113
1296
 
1114
1297
  function handleCloseKey(): void {
1115
1298
  const row = selectedRow();
1116
- if (!row || row.parentRow) return;
1299
+ if (!row || row.parentRow || row.readOnly) return;
1117
1300
  const now = Date.now();
1118
1301
  if (closeArm?.id === row.navigatorId && now >= closeArm.armedAt && now < closeArm.armedAt + CLOSE_ARM_MS) {
1119
1302
  clearCloseArm();
@@ -0,0 +1,144 @@
1
+ // Generated fixed launch domain from packages/pi-better-background-tasks/src/shared-operation-coordinator/assignment-inbox.mjs. Do not edit directly.
2
+ import { createRequire } from "node:module";
3
+ /** Rebuildable observation state, never an execution or delivery credential. */
4
+ export class AssignmentInbox {
5
+ constructor(path, connectionOrOptions, options = {}) {
6
+ const connection = typeof connectionOrOptions?.prepare === "function" ? connectionOrOptions : undefined;
7
+ if (!connection)
8
+ options = connectionOrOptions ?? options;
9
+ this.entityPrefix = options.entityPrefix;
10
+ const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
11
+ this.shared = Boolean(connection);
12
+ this.db = connection ?? new DatabaseSync(path);
13
+ this.alias = this.entityPrefix === "background:" ? "background_inbox" : "assignment_inbox";
14
+ this.prefix = connection ? `${this.alias}.` : "";
15
+ let attached = false;
16
+ try {
17
+ // Share the query owner's handle; only the attached derived file is durable.
18
+ if (connection) {
19
+ connection.prepare(`ATTACH DATABASE ? AS ${this.alias}`).run(path);
20
+ attached = true;
21
+ }
22
+ // A second observer may open while the first holds a derived write
23
+ // transaction. Existing schema/diagnostics require no write reservation.
24
+ const tables = this.db.prepare(`SELECT count(*) AS n FROM ${this.prefix}sqlite_master
25
+ WHERE type='table' AND name IN ('position','pending','applied_scopes','diagnostics')`).get().n;
26
+ if (tables === 4 && this.db.prepare(`SELECT 1 FROM ${this.prefix}diagnostics LIMIT 1`).get())
27
+ return;
28
+ this.db.exec(`CREATE TABLE IF NOT EXISTS ${this.prefix}position (
29
+ singleton INTEGER PRIMARY KEY CHECK(singleton=1), generation TEXT NOT NULL,
30
+ received INTEGER NOT NULL, applied INTEGER NOT NULL);
31
+ CREATE TABLE IF NOT EXISTS ${this.prefix}pending (
32
+ scope TEXT PRIMARY KEY, seq INTEGER NOT NULL, first_seq INTEGER NOT NULL, since INTEGER NOT NULL);
33
+ CREATE TABLE IF NOT EXISTS ${this.prefix}applied_scopes (scope TEXT PRIMARY KEY, seq INTEGER NOT NULL);
34
+ CREATE TABLE IF NOT EXISTS ${this.prefix}diagnostics (repairs INTEGER NOT NULL);`);
35
+ // Reopening an initialized inbox must not reserve every attached file
36
+ // merely to execute an INSERT whose SELECT would produce no rows.
37
+ if (!this.db.prepare(`SELECT 1 FROM ${this.prefix}diagnostics LIMIT 1`).get()) {
38
+ this.db.exec(`INSERT INTO ${this.prefix}diagnostics SELECT 0 WHERE NOT EXISTS (SELECT 1 FROM ${this.prefix}diagnostics)`);
39
+ }
40
+ }
41
+ catch (error) {
42
+ // A failed constructor cannot transfer its alias to a caller.
43
+ // Never detach an earlier participant or close a borrowed owner.
44
+ try {
45
+ if (attached)
46
+ this.db.exec(`DETACH DATABASE ${this.alias}`);
47
+ else if (!connection)
48
+ this.db.close();
49
+ }
50
+ catch (cleanup) {
51
+ throw new AggregateError([error, cleanup], "Assignment inbox initialization and owned cleanup failed");
52
+ }
53
+ throw error;
54
+ }
55
+ }
56
+ receive(source, identity) {
57
+ const version = source.prepare("SELECT value FROM schema_meta WHERE key='schema_version'").get()?.value;
58
+ if (!["1", "2", "3", "4"].includes(version))
59
+ throw new Error("Unsupported assignment source schema");
60
+ const token = source.prepare("SELECT generation FROM assignment_change_source WHERE singleton=1").get()?.generation;
61
+ if (!token)
62
+ throw new Error("Assignment change journal unavailable");
63
+ const generation = `${identity}:${version}:${token}`;
64
+ const bounds = source.prepare("SELECT min(seq) AS first, max(seq) AS last FROM assignment_changes").get();
65
+ const last = Number(bounds.last ?? 0);
66
+ const position = this.db.prepare(`SELECT * FROM ${this.prefix}position WHERE singleton=1`).get();
67
+ const reset = !position || position.generation !== generation || position.received > last
68
+ || (bounds.first !== null && position.received < Number(bounds.first) - 1);
69
+ const after = reset ? last : position.received;
70
+ const changes = reset ? [] : source.prepare("SELECT * FROM assignment_changes WHERE seq>? ORDER BY seq LIMIT 128").all(after);
71
+ this.more = !reset && Number(changes.at(-1)?.seq ?? after) < last;
72
+ if (!reset && !changes.length)
73
+ return this.batch(generation);
74
+ this.db.exec(this.shared ? `SAVEPOINT ${this.alias}_receive` : "BEGIN IMMEDIATE");
75
+ try {
76
+ if (reset) {
77
+ this.db.exec(`DELETE FROM ${this.prefix}pending; DELETE FROM ${this.prefix}applied_scopes; UPDATE ${this.prefix}diagnostics SET repairs=repairs+1`);
78
+ this.db.prepare(`INSERT INTO ${this.prefix}pending VALUES('*', ?, 0, ?)`).run(last, Date.now());
79
+ this.db.prepare(`INSERT OR REPLACE INTO ${this.prefix}position VALUES(1, ?, ?, 0)`).run(generation, last);
80
+ }
81
+ const insert = this.db.prepare(`INSERT INTO ${this.prefix}pending VALUES(?, ?, ?, ?)
82
+ ON CONFLICT(scope) DO UPDATE SET seq=excluded.seq`);
83
+ for (const change of changes) {
84
+ const background = change.entity.startsWith('background:');
85
+ if (this.entityPrefix ? !change.entity.startsWith(this.entityPrefix) : background)
86
+ continue;
87
+ insert.run(JSON.stringify([change.session_id, change.workspace, change.assignment_id]), change.seq, change.seq, Date.now());
88
+ }
89
+ // The obligations above and received position commit together.
90
+ if (changes.length)
91
+ this.db.prepare(`UPDATE ${this.prefix}position SET received=? WHERE singleton=1`).run(changes.at(-1).seq);
92
+ this.db.exec(this.shared ? `RELEASE ${this.alias}_receive` : "COMMIT");
93
+ }
94
+ catch (error) {
95
+ this.db.exec(this.shared ? `ROLLBACK TO ${this.alias}_receive; RELEASE ${this.alias}_receive` : "ROLLBACK");
96
+ throw error;
97
+ }
98
+ return this.batch(generation);
99
+ }
100
+ batch(generation) {
101
+ const batch = new Map(this.db.prepare(`SELECT scope, seq FROM ${this.prefix}pending ORDER BY first_seq, scope LIMIT 128`).all().map(row => [row.scope, String(row.seq)]));
102
+ Object.defineProperty(batch, "generation", { value: generation });
103
+ return batch;
104
+ }
105
+ acknowledge(batch, baselineComplete) {
106
+ const position = this.db.prepare(`SELECT * FROM ${this.prefix}position WHERE singleton=1`).get();
107
+ if (batch.generation && batch.generation !== position?.generation)
108
+ return;
109
+ if (batch.size && ![...batch.keys()].some(scope => scope !== "*" || baselineComplete))
110
+ return;
111
+ if (!batch.size && (!position || position.applied === position.received))
112
+ return;
113
+ this.db.exec(this.shared ? `SAVEPOINT ${this.alias}_ack` : "BEGIN IMMEDIATE");
114
+ try {
115
+ const remove = this.db.prepare(`DELETE FROM ${this.prefix}pending WHERE scope=? AND seq=?`);
116
+ const applied = this.db.prepare(`INSERT INTO ${this.prefix}applied_scopes VALUES(?,?) ON CONFLICT(scope) DO UPDATE SET seq=max(seq,excluded.seq)`);
117
+ for (const [scope, seq] of batch)
118
+ if (scope !== "*" || baselineComplete) {
119
+ if (remove.run(scope, Number(seq)).changes)
120
+ applied.run(scope, Number(seq));
121
+ }
122
+ // A later entity completing cannot advance past any earlier obligation.
123
+ this.db.exec(`UPDATE ${this.prefix}position SET applied=max(0,min(received,
124
+ COALESCE((SELECT min(first_seq)-1 FROM ${this.prefix}pending), received))) WHERE singleton=1`);
125
+ this.db.exec(this.shared ? `RELEASE ${this.alias}_ack` : "COMMIT");
126
+ }
127
+ catch (error) {
128
+ this.db.exec(this.shared ? `ROLLBACK TO ${this.alias}_ack; RELEASE ${this.alias}_ack` : "ROLLBACK");
129
+ throw error;
130
+ }
131
+ }
132
+ get metrics() {
133
+ const pending = this.db.prepare(`SELECT count(*) AS pending, min(since) AS oldestPendingAt FROM ${this.prefix}pending`).get();
134
+ return { ...this.db.prepare(`SELECT * FROM ${this.prefix}position`).get(),
135
+ more: Boolean(this.more),
136
+ affected: this.db.prepare(`SELECT scope, seq, first_seq, since FROM ${this.prefix}pending ORDER BY first_seq, scope LIMIT 128`).all(),
137
+ ...pending, oldestPendingAgeMs: pending.oldestPendingAt === null ? 0 : Math.max(0, Date.now() - Number(pending.oldestPendingAt)),
138
+ ...this.db.prepare(`SELECT repairs FROM ${this.prefix}diagnostics`).get() };
139
+ }
140
+ close() { if (this.shared)
141
+ this.db.exec(`DETACH DATABASE ${this.alias}`);
142
+ else
143
+ this.db.close(); }
144
+ }