@yaks/session 0.0.0-stage → 0.2.36

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 (393) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +1392 -2
  3. package/_dist/admission.d.ts +15 -0
  4. package/_dist/admission.d.ts.map +1 -0
  5. package/_dist/announce.d.ts +17 -0
  6. package/_dist/announce.d.ts.map +1 -0
  7. package/_dist/answer.d.ts +200 -0
  8. package/_dist/answer.d.ts.map +1 -0
  9. package/_dist/append.d.ts +10 -0
  10. package/_dist/append.d.ts.map +1 -0
  11. package/_dist/archive.d.ts +6 -0
  12. package/_dist/archive.d.ts.map +1 -0
  13. package/_dist/asks.d.ts +11 -0
  14. package/_dist/asks.d.ts.map +1 -0
  15. package/_dist/audit.d.ts +15 -0
  16. package/_dist/audit.d.ts.map +1 -0
  17. package/_dist/bounce.d.ts +19 -0
  18. package/_dist/bounce.d.ts.map +1 -0
  19. package/_dist/bus.d.ts +8 -0
  20. package/_dist/bus.d.ts.map +1 -0
  21. package/_dist/cache.d.ts +45 -0
  22. package/_dist/cache.d.ts.map +1 -0
  23. package/_dist/child-notice.d.ts +6 -0
  24. package/_dist/child-notice.d.ts.map +1 -0
  25. package/_dist/children.d.ts +59 -0
  26. package/_dist/children.d.ts.map +1 -0
  27. package/_dist/cli.d.ts +8 -0
  28. package/_dist/cli.d.ts.map +1 -0
  29. package/_dist/comp.d.ts +9 -0
  30. package/_dist/comp.d.ts.map +1 -0
  31. package/_dist/compact.d.ts +19 -0
  32. package/_dist/compact.d.ts.map +1 -0
  33. package/_dist/conversation.d.ts +158 -0
  34. package/_dist/conversation.d.ts.map +1 -0
  35. package/_dist/cost.d.ts +13 -0
  36. package/_dist/cost.d.ts.map +1 -0
  37. package/_dist/deferred.d.ts +79 -0
  38. package/_dist/deferred.d.ts.map +1 -0
  39. package/_dist/ended.d.ts +27 -0
  40. package/_dist/ended.d.ts.map +1 -0
  41. package/_dist/files.d.ts +73 -0
  42. package/_dist/files.d.ts.map +1 -0
  43. package/_dist/fork.d.ts +23 -0
  44. package/_dist/fork.d.ts.map +1 -0
  45. package/_dist/graft.d.ts +33 -0
  46. package/_dist/graft.d.ts.map +1 -0
  47. package/_dist/graph.d.ts +14 -0
  48. package/_dist/graph.d.ts.map +1 -0
  49. package/_dist/handoff.d.ts +29 -0
  50. package/_dist/handoff.d.ts.map +1 -0
  51. package/_dist/imported.d.ts +63 -0
  52. package/_dist/imported.d.ts.map +1 -0
  53. package/_dist/intake.d.ts +43 -0
  54. package/_dist/intake.d.ts.map +1 -0
  55. package/_dist/joined.d.ts +35 -0
  56. package/_dist/joined.d.ts.map +1 -0
  57. package/_dist/lease.d.ts +21 -0
  58. package/_dist/lease.d.ts.map +1 -0
  59. package/_dist/lines.d.ts +13 -0
  60. package/_dist/lines.d.ts.map +1 -0
  61. package/_dist/mod.d.ts +107 -0
  62. package/_dist/mod.d.ts.map +1 -0
  63. package/_dist/naming.d.ts +10 -0
  64. package/_dist/naming.d.ts.map +1 -0
  65. package/_dist/native.d.ts +13 -0
  66. package/_dist/native.d.ts.map +1 -0
  67. package/_dist/parts.d.ts +145 -0
  68. package/_dist/parts.d.ts.map +1 -0
  69. package/_dist/plugin.d.ts +33 -0
  70. package/_dist/plugin.d.ts.map +1 -0
  71. package/_dist/project.d.ts +67 -0
  72. package/_dist/project.d.ts.map +1 -0
  73. package/_dist/prose.d.ts +7 -0
  74. package/_dist/prose.d.ts.map +1 -0
  75. package/_dist/providers.d.ts +36 -0
  76. package/_dist/providers.d.ts.map +1 -0
  77. package/_dist/reach.d.ts +39 -0
  78. package/_dist/reach.d.ts.map +1 -0
  79. package/_dist/react.d.ts +236 -0
  80. package/_dist/react.d.ts.map +1 -0
  81. package/_dist/readers.d.ts +221 -0
  82. package/_dist/readers.d.ts.map +1 -0
  83. package/_dist/reap.d.ts +21 -0
  84. package/_dist/reap.d.ts.map +1 -0
  85. package/_dist/recall.d.ts +32 -0
  86. package/_dist/recall.d.ts.map +1 -0
  87. package/_dist/routes.d.ts +15 -0
  88. package/_dist/routes.d.ts.map +1 -0
  89. package/_dist/run.d.ts +81 -0
  90. package/_dist/run.d.ts.map +1 -0
  91. package/_dist/service.d.ts +131 -0
  92. package/_dist/service.d.ts.map +1 -0
  93. package/_dist/source.d.ts +9 -0
  94. package/_dist/source.d.ts.map +1 -0
  95. package/_dist/start.d.ts +29 -0
  96. package/_dist/start.d.ts.map +1 -0
  97. package/_dist/state.d.ts +75 -0
  98. package/_dist/state.d.ts.map +1 -0
  99. package/_dist/status.d.ts +38 -0
  100. package/_dist/status.d.ts.map +1 -0
  101. package/_dist/tail.d.ts +121 -0
  102. package/_dist/tail.d.ts.map +1 -0
  103. package/_dist/timing.d.ts +9 -0
  104. package/_dist/timing.d.ts.map +1 -0
  105. package/_dist/told.d.ts +17 -0
  106. package/_dist/told.d.ts.map +1 -0
  107. package/_dist/tools.d.ts +41 -0
  108. package/_dist/tools.d.ts.map +1 -0
  109. package/_dist/transcript.d.ts +5 -0
  110. package/_dist/transcript.d.ts.map +1 -0
  111. package/_dist/turn.d.ts +49 -0
  112. package/_dist/turn.d.ts.map +1 -0
  113. package/_dist/unknown.d.ts +6 -0
  114. package/_dist/unknown.d.ts.map +1 -0
  115. package/_dist/views.d.ts +9 -0
  116. package/_dist/views.d.ts.map +1 -0
  117. package/_dist/vocab.d.ts +9 -0
  118. package/_dist/vocab.d.ts.map +1 -0
  119. package/_dist/wait.d.ts +15 -0
  120. package/_dist/wait.d.ts.map +1 -0
  121. package/_dist/wake.d.ts +116 -0
  122. package/_dist/wake.d.ts.map +1 -0
  123. package/_dist/watch.d.ts +52 -0
  124. package/_dist/watch.d.ts.map +1 -0
  125. package/_dist/who.d.ts +84 -0
  126. package/_dist/who.d.ts.map +1 -0
  127. package/_dist/window.d.ts +43 -0
  128. package/_dist/window.d.ts.map +1 -0
  129. package/admission.js +137 -0
  130. package/admission.js.map +1 -0
  131. package/admission.ts +164 -0
  132. package/announce.js +123 -0
  133. package/announce.js.map +1 -0
  134. package/announce.ts +126 -0
  135. package/answer.js +372 -0
  136. package/answer.js.map +1 -0
  137. package/answer.ts +426 -0
  138. package/append.js +125 -0
  139. package/append.js.map +1 -0
  140. package/append.ts +205 -0
  141. package/archive.js +62 -0
  142. package/archive.js.map +1 -0
  143. package/archive.ts +62 -0
  144. package/asks.js +80 -0
  145. package/asks.js.map +1 -0
  146. package/asks.ts +106 -0
  147. package/attempt.js +46 -0
  148. package/attempt.js.map +1 -0
  149. package/attempt.ts +60 -0
  150. package/audit.js +57 -0
  151. package/audit.js.map +1 -0
  152. package/audit.ts +65 -0
  153. package/bounce.js +29 -0
  154. package/bounce.js.map +1 -0
  155. package/bounce.ts +34 -0
  156. package/bus.js +568 -0
  157. package/bus.js.map +1 -0
  158. package/bus.ts +683 -0
  159. package/cache.js +169 -0
  160. package/cache.js.map +1 -0
  161. package/cache.ts +230 -0
  162. package/child-notice.js +128 -0
  163. package/child-notice.js.map +1 -0
  164. package/child-notice.ts +136 -0
  165. package/children.js +937 -0
  166. package/children.js.map +1 -0
  167. package/children.ts +925 -0
  168. package/claude-control.js +8 -0
  169. package/claude-control.js.map +1 -0
  170. package/claude-control.ts +12 -0
  171. package/cli.js +23 -0
  172. package/cli.js.map +1 -0
  173. package/cli.ts +28 -0
  174. package/comp.js +76 -0
  175. package/comp.js.map +1 -0
  176. package/comp.ts +78 -0
  177. package/compact.js +157 -0
  178. package/compact.js.map +1 -0
  179. package/compact.ts +209 -0
  180. package/compact_ask.js +280 -0
  181. package/compact_ask.js.map +1 -0
  182. package/compact_ask.ts +199 -0
  183. package/continue.js +131 -0
  184. package/continue.js.map +1 -0
  185. package/continue.ts +143 -0
  186. package/conversation.js +337 -0
  187. package/conversation.js.map +1 -0
  188. package/conversation.ts +593 -0
  189. package/cost.js +111 -0
  190. package/cost.js.map +1 -0
  191. package/cost.ts +93 -0
  192. package/deferred.js +207 -0
  193. package/deferred.js.map +1 -0
  194. package/deferred.ts +219 -0
  195. package/deno.json +1 -0
  196. package/dependencies.js +114 -0
  197. package/dependencies.js.map +1 -0
  198. package/dependencies.ts +110 -0
  199. package/draining.js +20 -0
  200. package/draining.js.map +1 -0
  201. package/draining.ts +26 -0
  202. package/ended.js +210 -0
  203. package/ended.js.map +1 -0
  204. package/ended.ts +225 -0
  205. package/files.js +285 -0
  206. package/files.js.map +1 -0
  207. package/files.ts +318 -0
  208. package/fork.js +96 -0
  209. package/fork.js.map +1 -0
  210. package/fork.ts +124 -0
  211. package/graft.js +97 -0
  212. package/graft.js.map +1 -0
  213. package/graft.ts +88 -0
  214. package/graph.js +49 -0
  215. package/graph.js.map +1 -0
  216. package/graph.ts +61 -0
  217. package/handoff.js +111 -0
  218. package/handoff.js.map +1 -0
  219. package/handoff.ts +147 -0
  220. package/help.js +432 -0
  221. package/help.js.map +1 -0
  222. package/help.ts +431 -0
  223. package/hooks.js +253 -0
  224. package/hooks.js.map +1 -0
  225. package/hooks.ts +333 -0
  226. package/imported.js +259 -0
  227. package/imported.js.map +1 -0
  228. package/imported.ts +201 -0
  229. package/inspect.js +353 -0
  230. package/inspect.js.map +1 -0
  231. package/inspect.ts +378 -0
  232. package/intake.js +115 -0
  233. package/intake.js.map +1 -0
  234. package/intake.ts +124 -0
  235. package/joined.js +67 -0
  236. package/joined.js.map +1 -0
  237. package/joined.ts +69 -0
  238. package/lease.js +146 -0
  239. package/lease.js.map +1 -0
  240. package/lease.ts +151 -0
  241. package/lifecycle.js +49 -0
  242. package/lifecycle.js.map +1 -0
  243. package/lifecycle.ts +46 -0
  244. package/lines.js +171 -0
  245. package/lines.js.map +1 -0
  246. package/lines.ts +177 -0
  247. package/listen.js +604 -0
  248. package/listen.js.map +1 -0
  249. package/listen.ts +976 -0
  250. package/log.js +78 -0
  251. package/log.js.map +1 -0
  252. package/log.ts +88 -0
  253. package/mod.js +107 -0
  254. package/mod.js.map +1 -0
  255. package/mod.ts +113 -0
  256. package/name.js +51 -0
  257. package/name.js.map +1 -0
  258. package/name.ts +84 -0
  259. package/naming.js +96 -0
  260. package/naming.js.map +1 -0
  261. package/naming.ts +102 -0
  262. package/native.js +17 -0
  263. package/native.js.map +1 -0
  264. package/native.ts +17 -0
  265. package/package.json +133 -4
  266. package/parts.js +334 -0
  267. package/parts.js.map +1 -0
  268. package/parts.ts +383 -0
  269. package/plugin.js +77 -0
  270. package/plugin.js.map +1 -0
  271. package/plugin.ts +98 -0
  272. package/project.js +354 -0
  273. package/project.js.map +1 -0
  274. package/project.ts +407 -0
  275. package/prompt.js +57 -0
  276. package/prompt.js.map +1 -0
  277. package/prompt.ts +92 -0
  278. package/prose.js +43 -0
  279. package/prose.js.map +1 -0
  280. package/prose.ts +63 -0
  281. package/providers.js +279 -0
  282. package/providers.js.map +1 -0
  283. package/providers.ts +306 -0
  284. package/pruning.js +80 -0
  285. package/pruning.js.map +1 -0
  286. package/pruning.ts +147 -0
  287. package/reach.js +923 -0
  288. package/reach.js.map +1 -0
  289. package/reach.ts +1107 -0
  290. package/react.js +2259 -0
  291. package/react.js.map +1 -0
  292. package/react.ts +2864 -0
  293. package/readers.js +956 -0
  294. package/readers.js.map +1 -0
  295. package/readers.ts +1017 -0
  296. package/reap.js +60 -0
  297. package/reap.js.map +1 -0
  298. package/reap.ts +65 -0
  299. package/recall.js +67 -0
  300. package/recall.js.map +1 -0
  301. package/recall.ts +114 -0
  302. package/reopen.js +45 -0
  303. package/reopen.js.map +1 -0
  304. package/reopen.ts +44 -0
  305. package/result-entry.js +32 -0
  306. package/result-entry.js.map +1 -0
  307. package/result-entry.ts +34 -0
  308. package/resume.js +266 -0
  309. package/resume.js.map +1 -0
  310. package/resume.ts +283 -0
  311. package/routes.js +129 -0
  312. package/routes.js.map +1 -0
  313. package/routes.ts +147 -0
  314. package/routine.js +179 -0
  315. package/routine.js.map +1 -0
  316. package/routine.ts +191 -0
  317. package/run.js +932 -0
  318. package/run.js.map +1 -0
  319. package/run.ts +999 -0
  320. package/service.js +806 -0
  321. package/service.js.map +1 -0
  322. package/service.ts +911 -0
  323. package/source.js +26 -0
  324. package/source.js.map +1 -0
  325. package/source.ts +40 -0
  326. package/start.js +197 -0
  327. package/start.js.map +1 -0
  328. package/start.ts +214 -0
  329. package/state.js +247 -0
  330. package/state.js.map +1 -0
  331. package/state.ts +404 -0
  332. package/status.js +1222 -0
  333. package/status.js.map +1 -0
  334. package/status.ts +1555 -0
  335. package/status_bench.ts +50 -0
  336. package/statusline.js +187 -0
  337. package/statusline.js.map +1 -0
  338. package/statusline.ts +232 -0
  339. package/tail.js +748 -0
  340. package/tail.js.map +1 -0
  341. package/tail.ts +815 -0
  342. package/talk.js +58 -0
  343. package/talk.js.map +1 -0
  344. package/talk.ts +51 -0
  345. package/task-context.js +41 -0
  346. package/task-context.js.map +1 -0
  347. package/task-context.ts +53 -0
  348. package/texted.js +65 -0
  349. package/texted.js.map +1 -0
  350. package/texted.ts +65 -0
  351. package/timing.js +37 -0
  352. package/timing.js.map +1 -0
  353. package/timing.ts +52 -0
  354. package/told.js +56 -0
  355. package/told.js.map +1 -0
  356. package/told.ts +54 -0
  357. package/tools.js +595 -0
  358. package/tools.js.map +1 -0
  359. package/tools.ts +633 -0
  360. package/transcript.js +34 -0
  361. package/transcript.js.map +1 -0
  362. package/transcript.ts +41 -0
  363. package/turn.js +47 -0
  364. package/turn.js.map +1 -0
  365. package/turn.ts +68 -0
  366. package/unknown.js +8 -0
  367. package/unknown.js.map +1 -0
  368. package/unknown.ts +9 -0
  369. package/views.js +15 -0
  370. package/views.js.map +1 -0
  371. package/views.ts +21 -0
  372. package/vocab.js +24 -0
  373. package/vocab.js.map +1 -0
  374. package/vocab.json +1573 -0
  375. package/vocab.ts +30 -0
  376. package/wait.js +30 -0
  377. package/wait.js.map +1 -0
  378. package/wait.ts +45 -0
  379. package/wake.js +552 -0
  380. package/wake.js.map +1 -0
  381. package/wake.ts +597 -0
  382. package/watch.js +520 -0
  383. package/watch.js.map +1 -0
  384. package/watch.ts +596 -0
  385. package/who.js +309 -0
  386. package/who.js.map +1 -0
  387. package/who.ts +347 -0
  388. package/window.js +179 -0
  389. package/window.js.map +1 -0
  390. package/window.ts +268 -0
  391. package/woken.js +129 -0
  392. package/woken.js.map +1 -0
  393. package/woken.ts +127 -0
package/status.ts ADDED
@@ -0,0 +1,1555 @@
1
+ // What a transcript is doing, computed from its entries — never stored. The
2
+ // rule is written twice on purpose, once over bundles (for the runner,
3
+ // @yaks/ram, and any code holding entries) and once as SQL (the
4
+ // `session.status` derived property @yaks/sqlite reads and filters through),
5
+ // and a test holds the two together. There is no third copy: a stored `status`
6
+ // property that had to be kept in sync is exactly what the old session
7
+ // component was, and why its views disagreed.
8
+ //
9
+ // Settled means nothing is outstanding. The newest entry covers most of it, but
10
+ // not all: a model that returns prose before it calls a tool leaves an `output`
11
+ // as the newest entry in the middle of its turn, and reading that alone ended a
12
+ // run 14 minutes early (T-35230). So an open call — one the newest ask made
13
+ // that no result answers — outranks the newest entry, and it is the same set
14
+ // `react` runs next, so the status and the step cannot disagree.
15
+ // an open call → running a tool owes an answer, whatever landed after
16
+ // input, result → pending the model owes a turn
17
+ // ask, call → running a model or a tool owes an answer
18
+ // output → settled the turn returned prose and asked for nothing
19
+ // stop → stopped nothing may be done
20
+ // exception → failed the runner could not continue past it
21
+ // refusal → failed a deliberate no, until new input
22
+ // `pending` is the runner's to answer (./run.ts), and it answers only a
23
+ // transcript that asked it: one carrying a `using` (its request) or an `ask`
24
+ // (a turn it took, not one read from a harness's file). One with neither is run
25
+ // outside the graph — a harness's session its hooks record, a Claude Code
26
+ // subagent, a run from before the runner — so its newest input
27
+ // is owed by whatever runs it: running, never pending, which the runner would
28
+ // answer with no model to ask.
29
+ //
30
+ // A turn lands as one batch — the ask, the prose, and the calls together — so
31
+ // no reader ever sees the prose without the calls that came with it.
32
+ //
33
+ // Prose is `content{body}`; alone it is an input, and an `output{source}`
34
+ // beside it records what produced it — the ask, for what a model returned. A
35
+ // result, refusal or exception carries its prose the same way and is its own
36
+ // kind.
37
+
38
+ import {
39
+ among,
40
+ and,
41
+ as,
42
+ at,
43
+ col,
44
+ cross,
45
+ desc,
46
+ descriptorHolds,
47
+ eq,
48
+ exists,
49
+ type Expr,
50
+ fn,
51
+ from,
52
+ gate,
53
+ ge,
54
+ gt,
55
+ iff,
56
+ isNull,
57
+ type Join,
58
+ join,
59
+ le,
60
+ left,
61
+ lit,
62
+ not,
63
+ notNull,
64
+ op,
65
+ or,
66
+ type Select,
67
+ select,
68
+ type Source,
69
+ star,
70
+ sub,
71
+ table,
72
+ unionAll,
73
+ when,
74
+ } from '@yaks/sql/core'
75
+ import { ASK, RESULT } from './native.js'
76
+ import { attemptDerived } from './attempt.js'
77
+ import { derived as executionDerived } from '@yaks/tools/vocab'
78
+ import { sessionCost } from './cost.js'
79
+ import { COST } from '@yaks/model/vocab'
80
+ import type { Derived, DerivedScope } from '@yaks/sql/core'
81
+ import type { Vocab } from 'jsr:@yaks/vocab@0.2.36'
82
+
83
+ export * from './state.js'
84
+ import { RETRIES, UNFINISHED } from './state.js'
85
+ import { claudeStops } from './claude-control.js'
86
+
87
+ // Old servers still write state during the marks expansion. A non-null state
88
+ // wins until cutover; otherwise waiting precedes admitted in the declared ladder.
89
+ export let dispatchStatus = {
90
+ stable: true,
91
+ tag: 'text' as const,
92
+ values: ['queued', 'active', 'waiting', 'settled'],
93
+ deps: ['dispatch', 'waiting', 'admitted'],
94
+ expr: (owner: Expr, marks = ['waiting', 'admitted']): Expr => {
95
+ let marked = (comp: string) =>
96
+ exists(select({
97
+ cols: [lit(1)],
98
+ from: table(comp, 'm'),
99
+ where: eq(col('entity', 'm'), owner),
100
+ }))
101
+ let rungs: [Expr, Expr][] = marks.map((comp) => [
102
+ marked(comp),
103
+ lit(comp == 'waiting' ? 'waiting' : 'active'),
104
+ ])
105
+ let status = rungs.length ? when(rungs, lit('queued')) : lit('queued')
106
+ return sub(select({
107
+ cols: [fn('coalesce', col('state', 'd'), status)],
108
+ from: table('dispatch', 'd'),
109
+ where: eq(col('entity', 'd'), owner),
110
+ }))
111
+ },
112
+ }
113
+
114
+ // How far down a transcript the status selector walks to prove a turn at rest.
115
+ let TAIL = 128
116
+ // The common table expressions the SQL rule names, apart from any component.
117
+ let LATEST = '__latest'
118
+ let ANCHOR = '__anchor'
119
+
120
+ // The session index orders entries by identity, independently of sequence.
121
+ // These bounds seek sparse marks; the join still checks their session when
122
+ // other transcripts' entries lie between the two ends.
123
+ let within = (owner: Expr, entry: Expr): Expr => {
124
+ let bound = (descending: boolean) =>
125
+ sub(select({
126
+ cols: [col('entity', 'extent')],
127
+ from: table('entry', 'extent'),
128
+ where: eq(col('session', 'extent'), owner),
129
+ order: [
130
+ descending ? desc(col('entity', 'extent')) : col('entity', 'extent'),
131
+ ],
132
+ limit: lit(1),
133
+ }))
134
+ return and(ge(entry, bound(false)), le(entry, bound(true)))
135
+ }
136
+
137
+ /** What the rule asks of a store's words: whether one is declared, and how
138
+ * an archetype's stored descriptor, `tables`, says it holds one (@yaks/sql
139
+ * `descriptorHolds`). */
140
+ export type Words = {
141
+ declared: (name: string) => boolean
142
+ holds: (tables: Expr, comp: string) => Expr
143
+ }
144
+
145
+ let anyWords: Words = {
146
+ declared: () => true,
147
+ holds: (tables, comp) => descriptorHolds(tables, undefined, comp),
148
+ }
149
+
150
+ /**
151
+ * The same rule as SQL, for @yaks/sqlite's derived-property registry
152
+ * (`storage(driver, vocab, { derived: sessionDerived(vocab) })`), so
153
+ * `.session.status=running` compiles through the index. `owner` is the SQL
154
+ * naming the session's integer id; a reference column stores the referent's
155
+ * integer id, which is what `entry.session` is compared against.
156
+ */
157
+ export let sessionStatus = {
158
+ tag: 'text' as const,
159
+ values: [
160
+ 'empty',
161
+ 'pending',
162
+ 'running',
163
+ 'queued',
164
+ 'settled',
165
+ 'stopped',
166
+ 'failed',
167
+ ],
168
+ deps: ['session'],
169
+ // Only a session not ended owes anything, and sessions end: what the cap
170
+ // counts is a few dozen of a store's tens of thousands.
171
+ few: ['pending', 'running', 'queued'],
172
+ select: (
173
+ values: Expr[],
174
+ dispatch = dispatchStatus,
175
+ words: Words = anyWords,
176
+ text: (stored: Expr) => Expr = (stored) => stored,
177
+ one?: Expr,
178
+ ): Select | undefined => {
179
+ let { declared, holds } = words
180
+ if (
181
+ !values.every((v) =>
182
+ (v.t == 'val' || v.t == 'lit') && typeof v.v == 'string'
183
+ )
184
+ ) return undefined
185
+ let wanted = values.map((v) => (v as { v: string }).v)
186
+ if (
187
+ !wanted.every((v) =>
188
+ ['pending', 'running', 'queued', 'stopped', 'empty'].includes(v)
189
+ )
190
+ ) return undefined
191
+ let owner = col('entity', 'candidate')
192
+ let wears = (name: string, entry: Expr) =>
193
+ declared(name)
194
+ ? exists(
195
+ select({
196
+ cols: [lit(1)],
197
+ from: table(name, 'mark'),
198
+ where: eq(col('entity', 'mark'), entry),
199
+ }),
200
+ )
201
+ : lit(false)
202
+ let cancelled = (entry: Expr) =>
203
+ ['notice', 'content', 'lines'].every(declared)
204
+ ? exists(select({
205
+ cols: [lit(1)],
206
+ from: table('lines', 'origin'),
207
+ joins: [
208
+ {
209
+ ...cross(table('content', 'prose')),
210
+ on: eq(col('entity', 'origin'), col('entity', 'prose')),
211
+ },
212
+ ],
213
+ where: and(
214
+ eq(col('entity', 'prose'), entry),
215
+ among(text(col('body', 'prose')), claudeStops.map(lit)),
216
+ ),
217
+ }))
218
+ : lit(false)
219
+ // Seek one latest meaningful entry per owner, not the status expression
220
+ // for every owner. A notice is passive except historical cancellation.
221
+ let latest = sub(select({
222
+ cols: [col('entity', 'recent')],
223
+ from: table('entry', 'recent'),
224
+ where: and(
225
+ eq(col('session', 'recent'), col('entity', 's')),
226
+ or(
227
+ not(wears('notice', col('entity', 'recent'))),
228
+ cancelled(col('entity', 'recent')),
229
+ ),
230
+ ),
231
+ order: [desc(col('seq', 'recent'))],
232
+ limit: lit(1),
233
+ }))
234
+ let stopped = wanted.includes('stopped')
235
+ // A transcript with no entry a passive notice leaves is empty, ended or not.
236
+ let empty = wanted.includes('empty')
237
+ // Nothing ended owes anything, so the mark answers before any entry is read.
238
+ // Given `one` owner, the screen reads that session alone.
239
+ let kept = [
240
+ ...one ? [eq(col('entity', 's'), one)] : [],
241
+ ...stopped || empty
242
+ ? []
243
+ : [not(fn('coalesce', col('ended', 's'), lit(false)))],
244
+ ]
245
+ let candidates = select({
246
+ cols: [col('entity', 's'), col('ended', 's'), as(latest, 'latest')],
247
+ from: table('session', 's'),
248
+ ...kept.length ? { where: and(...kept) } : {},
249
+ })
250
+ let actionable = wanted.some((v) => v != 'stopped' && v != 'empty')
251
+ let newest = col('latest', 'candidate')
252
+ let ended = fn('coalesce', col('ended', 'candidate'), lit(false))
253
+ // A stopped transcript must either be ended or contain a stop/control.
254
+ // Historical controls are candidates, never an alternative status rule.
255
+ let controls = ['stop', 'notice'].filter(declared).map((name) =>
256
+ select({
257
+ cols: [col('session', 'ce'), col('seq', 'ce')],
258
+ from: table(name, 'cm'),
259
+ joins: [
260
+ {
261
+ ...cross(table('entry', 'ce')),
262
+ on: eq(col('entity', 'ce'), col('entity', 'cm')),
263
+ },
264
+ ],
265
+ ...name == 'notice' ? { where: cancelled(col('entity', 'ce')) } : {},
266
+ })
267
+ )
268
+ let controlOwners = controls.length ? unionAll(...controls) : select({
269
+ cols: [as(lit(null), 'session'), as(lit(null), 'seq')],
270
+ where: lit(false),
271
+ })
272
+ // Whether a transcript's newest turn is at rest, read walking down from its
273
+ // newest entry: the first entry holding work or an ask ends the walk. An ask
274
+ // with nothing unread above it proves it, and so does reaching the start of
275
+ // a transcript that asked nothing, whose inputs no runner owes. A longer
276
+ // transcript is left to the exact rule. What ends the walk is worked out in
277
+ // FROM subqueries, which add nothing to this expression's height (workerd's
278
+ // depth limit, as below).
279
+ let inputKinds = [
280
+ 'output',
281
+ 'notice',
282
+ 'result',
283
+ 'tool_progress',
284
+ 'refusal',
285
+ 'exception',
286
+ 'ask',
287
+ 'call',
288
+ 'stop',
289
+ 'interrupted',
290
+ ].filter(declared)
291
+ let input = (entry: Expr) =>
292
+ and(
293
+ wears('content', entry),
294
+ ...inputKinds.map((name) => not(wears(name, entry))),
295
+ )
296
+ // A historical stop matters only until the next input. Find that input
297
+ // directly after the newest control, rather than working out the entire
298
+ // status of every transcript that ever stopped and later resumed.
299
+ let halted = exists(select({
300
+ cols: [lit(1)],
301
+ from: table('__status_controls', 'control'),
302
+ where: and(
303
+ eq(col('session', 'control'), owner),
304
+ or(
305
+ col('legacy', 'control'),
306
+ not(exists(select({
307
+ cols: [lit(1)],
308
+ from: table('entry', 'resumed'),
309
+ where: and(
310
+ eq(col('session', 'resumed'), owner),
311
+ gt(col('seq', 'resumed'), col('seq', 'control')),
312
+ input(col('entity', 'resumed')),
313
+ ),
314
+ }))),
315
+ ),
316
+ ),
317
+ }))
318
+ let inflight = (entry: Expr) =>
319
+ declared('attempt')
320
+ ? exists(select({
321
+ cols: [lit(1)],
322
+ from: table('attempt', 'flight'),
323
+ where: and(
324
+ eq(col('entity', 'flight'), entry),
325
+ notNull(col('by', 'flight')),
326
+ ),
327
+ }))
328
+ : lit(false)
329
+ // An input arriving above what the newest ask read. Any other reply there
330
+ // would have ended the walk, or lies between the two and is read here too.
331
+ let unread = (ask: Expr, seq: Expr) =>
332
+ exists(select({
333
+ cols: [lit(1)],
334
+ from: from(
335
+ select({
336
+ cols: [
337
+ as(
338
+ or(
339
+ wears('result', col('entity', 'gap')),
340
+ wears('tool_progress', col('entity', 'gap')),
341
+ input(col('entity', 'gap')),
342
+ ),
343
+ 'heard',
344
+ ),
345
+ ],
346
+ from: table('entry', 'gap'),
347
+ where: and(
348
+ eq(col('session', 'gap'), owner),
349
+ gt(
350
+ col('seq', 'gap'),
351
+ fn(
352
+ 'coalesce',
353
+ sub(select({
354
+ cols: [col('seq', 'read')],
355
+ from: table('ask', 'request'),
356
+ joins: [
357
+ join(
358
+ table('entry', 'read'),
359
+ eq(col('entity', 'read'), col('through', 'request')),
360
+ ),
361
+ ],
362
+ where: eq(col('entity', 'request'), ask),
363
+ })),
364
+ seq,
365
+ ),
366
+ ),
367
+ ),
368
+ }),
369
+ 'above',
370
+ ),
371
+ where: col('heard', 'above'),
372
+ }))
373
+ // In a store keeping archetypes, one joined row answers for every component
374
+ // an entry wears, the way the exact rule reads it (`archetype`), where a
375
+ // probe of each table costs a seek per component per entry.
376
+ let typed = declared('archetype')
377
+ let shapes: Join[] = typed
378
+ ? [
379
+ {
380
+ ...cross(table('entity', 'owner')),
381
+ on: eq(col('id', 'owner'), col('entity', 'e')),
382
+ },
383
+ {
384
+ ...cross(table('archetype', 'shape')),
385
+ on: eq(col('entity', 'shape'), col('archetype', 'owner')),
386
+ },
387
+ ]
388
+ : []
389
+ let walks = (name: string, entry: Expr) =>
390
+ typed
391
+ ? declared(name) ? holds(col('tables', 'shape'), name) : lit(false)
392
+ : wears(name, entry)
393
+ let resting = (inputs: boolean) => {
394
+ let e = col('entity', 'e')
395
+ let work = [
396
+ 'stop',
397
+ 'call',
398
+ 'result',
399
+ 'tool_progress',
400
+ 'tool_async',
401
+ 'exception',
402
+ 'interrupted',
403
+ ]
404
+ return fn(
405
+ 'coalesce',
406
+ sub(select({
407
+ cols: [col('clean', 'tail')],
408
+ from: from(
409
+ select({
410
+ cols: [
411
+ col('seq', 'e'),
412
+ as(
413
+ or(
414
+ walks('ask', e),
415
+ isNull(col('seq', 'e')),
416
+ ...work.map((name) => walks(name, e)),
417
+ and(walks('attempt', e), inflight(e)),
418
+ and(walks('notice', e), cancelled(e)),
419
+ ),
420
+ 'ends',
421
+ ),
422
+ as(
423
+ and(
424
+ walks('ask', e),
425
+ notNull(col('seq', 'e')),
426
+ ...work.map((name) => not(walks(name, e))),
427
+ not(and(walks('attempt', e), inflight(e))),
428
+ ...inputs ? [not(unread(e, col('seq', 'e')))] : [],
429
+ ),
430
+ 'clean',
431
+ ),
432
+ ],
433
+ from: table('entry', 'e'),
434
+ joins: shapes,
435
+ where: eq(col('session', 'e'), owner),
436
+ order: [desc(col('seq', 'e'))],
437
+ limit: lit(TAIL),
438
+ }),
439
+ 'tail',
440
+ ),
441
+ where: col('ends', 'tail'),
442
+ order: [desc(col('seq', 'tail'))],
443
+ limit: lit(1),
444
+ })),
445
+ not(exists(select({
446
+ cols: [lit(1)],
447
+ from: table('entry', 'beyond'),
448
+ where: eq(col('session', 'beyond'), owner),
449
+ order: [desc(col('seq', 'beyond'))],
450
+ limit: lit(1),
451
+ offset: lit(TAIL - 1),
452
+ }))),
453
+ )
454
+ }
455
+ let notQueued = not(
456
+ eq(fn('coalesce', dispatch.expr(owner), lit('')), lit('queued')),
457
+ )
458
+ let marked = (entry: Expr, names: string[]) =>
459
+ names.map((name) => not(wears(name, entry)))
460
+ // Three last turns the rule can only read as finished: prose that asks for
461
+ // nothing, a refusal naming no request, and a turn given up on. Nothing
462
+ // about them needs the exact rule, and they are nearly every transcript.
463
+ // A background call still unanswered: probed in each candidate's own
464
+ // entries where the candidates are the few not ended, and read once for
465
+ // the store where every ended session is one too.
466
+ let unanswered = (p: string) =>
467
+ not(exists(select({
468
+ cols: [lit(1)],
469
+ from: table('result', 'answer'),
470
+ where: eq(col('call', 'answer'), col('entity', p)),
471
+ })))
472
+ let few = !stopped && !empty
473
+ let background = declared('tool_async') && declared('result')
474
+ let waiting = !background ? lit(false) : few
475
+ ? exists(select({
476
+ cols: [lit(1)],
477
+ from: table('tool_async', 'p'),
478
+ joins: [{
479
+ ...cross(table('entry', 'pe')),
480
+ on: eq(col('entity', 'p'), col('entity', 'pe')),
481
+ }],
482
+ where: and(
483
+ within(owner, col('entity', 'p')),
484
+ eq(col('session', 'pe'), owner),
485
+ unanswered('p'),
486
+ ),
487
+ }))
488
+ : among(
489
+ owner,
490
+ select({ cols: [col('session')], from: table('__status_waiting') }),
491
+ )
492
+ let atRest = or(
493
+ and(
494
+ wears('output', newest),
495
+ ...marked(newest, ['ask', 'refusal']),
496
+ resting(true),
497
+ not(waiting),
498
+ notQueued,
499
+ ),
500
+ and(
501
+ wears('refusal', newest),
502
+ ...marked(newest, ['output', 'ask', 'result']),
503
+ resting(false),
504
+ notQueued,
505
+ ),
506
+ and(
507
+ wears('ask', newest),
508
+ wears('interrupted', newest),
509
+ wears('failed', newest),
510
+ ...marked(newest, ['call', 'result', 'refusal', 'exception']),
511
+ notQueued,
512
+ ),
513
+ )
514
+ let eligible = or(
515
+ empty ? isNull(newest) : lit(false),
516
+ stopped
517
+ ? or(
518
+ wears('stop', newest),
519
+ halted,
520
+ and(ended, notNull(newest), not(atRest)),
521
+ )
522
+ : lit(false),
523
+ actionable
524
+ ? and(
525
+ not(ended),
526
+ notNull(newest),
527
+ not(wears('stop', newest)),
528
+ not(atRest),
529
+ )
530
+ : lit(false),
531
+ )
532
+ // Materialization is essential: SQLite must apply the cheap candidate
533
+ // filter before it evaluates the exact turn expression.
534
+ return select({
535
+ with: [
536
+ { name: '__status_latest', materialized: true, q: candidates },
537
+ ...stopped
538
+ ? [{
539
+ name: '__status_controls',
540
+ materialized: true,
541
+ q: select({
542
+ cols: [
543
+ col('session', 'controls'),
544
+ as(fn('max', col('seq', 'controls')), 'seq'),
545
+ as(fn('max', isNull(col('seq', 'controls'))), 'legacy'),
546
+ ],
547
+ from: from(controlOwners, 'controls'),
548
+ group: [col('session', 'controls')],
549
+ }),
550
+ }]
551
+ : [],
552
+ ...background && !few
553
+ ? [{
554
+ name: '__status_waiting',
555
+ materialized: true,
556
+ q: select({
557
+ cols: [col('session', 'pe')],
558
+ from: table('tool_async', 'p'),
559
+ joins: [{
560
+ ...cross(table('entry', 'pe')),
561
+ on: eq(col('entity', 'pe'), col('entity', 'p')),
562
+ }],
563
+ where: unanswered('p'),
564
+ }),
565
+ }]
566
+ : [],
567
+ {
568
+ name: '__status_candidates',
569
+ materialized: true,
570
+ q: select({
571
+ cols: [owner, col('ended', 'candidate'), newest],
572
+ from: table('__status_latest', 'candidate'),
573
+ where: eligible,
574
+ }),
575
+ },
576
+ ],
577
+ cols: [col('entity', 'chosen')],
578
+ from: table('__status_candidates', 'chosen'),
579
+ where: among(
580
+ when(
581
+ [
582
+ [isNull(col('latest', 'chosen')), lit('empty')],
583
+ [wears('stop', col('latest', 'chosen')), lit('stopped')],
584
+ ],
585
+ sessionStatus.expr(col('entity', 'chosen'), dispatch, words, text),
586
+ ),
587
+ values,
588
+ ),
589
+ })
590
+ },
591
+ expr: (
592
+ owner: Expr,
593
+ dispatch = dispatchStatus,
594
+ words: Words = anyWords,
595
+ text: (stored: Expr) => Expr = (stored) => stored,
596
+ terminal = false,
597
+ ): Expr => {
598
+ let { declared, holds } = words
599
+ // Each fact about an entry is said once (`marks`), and each fact about
600
+ // the transcript is said once, as a common table expression the next
601
+ // reads: its newest entry (LATEST) and the anchors of its turn (ANCHOR).
602
+ // Both name the owner, so SQLite runs them again at every reference,
603
+ // whatever the hint: they are left for the planner to flatten rather than
604
+ // materialized, and each is referenced as few times as the rule allows.
605
+ // The turn's rows are read once, and every fact in the decision is
606
+ // reduced from them in one pass. Each read seeks its own rows through the
607
+ // entry index, so the cost is bounded by the turn, whatever the
608
+ // transcript's length.
609
+ let typed = declared('archetype')
610
+ let mine = (alias: string) => eq(col('session', alias), owner)
611
+ let inputKinds = [
612
+ 'output',
613
+ 'notice',
614
+ 'result',
615
+ 'tool_progress',
616
+ 'refusal',
617
+ 'exception',
618
+ 'ask',
619
+ 'call',
620
+ 'stop',
621
+ 'interrupted',
622
+ ].filter(declared)
623
+ // Older consumed imports classified a cancellation as a passive notice.
624
+ // Interpret that format here without rewriting the owner's transcripts:
625
+ // whether the entry with the id `entry` holds the prose such an import
626
+ // recorded.
627
+ let cancellation = (entry: Expr) =>
628
+ ['notice', 'content', 'lines'].every(declared)
629
+ ? exists(select({
630
+ cols: [lit(1)],
631
+ from: table('lines', 'origin'),
632
+ joins: [
633
+ {
634
+ ...cross(table('content', 'text')),
635
+ on: eq(col('entity', 'origin'), col('entity', 'text')),
636
+ },
637
+ ],
638
+ where: and(
639
+ eq(col('entity', 'text'), entry),
640
+ among(text(col('body', 'text')), claudeStops.map(lit)),
641
+ ),
642
+ }))
643
+ : lit(false)
644
+ // What an entry is to the rule, from whether it `wears` each declared
645
+ // component and whether its prose is `cancelled`.
646
+ let marks = (wears: (comp: string) => Expr, cancelled: Expr) => {
647
+ let worn = (comp: string) => declared(comp) ? wears(comp) : lit(false)
648
+ let notice = worn('notice')
649
+ let cancel = iff(notice, cancelled, lit(false))
650
+ return {
651
+ worn,
652
+ cancel,
653
+ halted: or(worn('stop'), cancel),
654
+ passive: and(notice, not(cancelled)),
655
+ // A cancellation is a notice, so an input is neither.
656
+ input: and(worn('content'), ...inputKinds.map((c) => not(wears(c)))),
657
+ }
658
+ }
659
+ // Whether an entry wears a component: in a store that keeps archetypes,
660
+ // read off the archetype one joined row names, which answers for every
661
+ // component; else by seeking the component's own table.
662
+ // Each joined in the order written: the entry leads, so it is the one
663
+ // sought through its index.
664
+ let archetype = (alias: string): Join[] => [
665
+ {
666
+ ...cross(table('entity', 'owner')),
667
+ on: eq(col('id', 'owner'), col('entity', alias)),
668
+ },
669
+ {
670
+ ...cross(table('archetype', 'shape')),
671
+ on: eq(col('entity', 'shape'), col('archetype', 'owner')),
672
+ },
673
+ ]
674
+ let shaped = (comp: string) => holds(col('tables', 'shape'), comp)
675
+ let probed = (alias: string) => (comp: string) =>
676
+ exists(select({
677
+ cols: [lit(1)],
678
+ from: table(comp, 'm'),
679
+ where: eq(col('entity', 'm'), col('entity', alias)),
680
+ }))
681
+ let shapes = typed ? archetype('e') : []
682
+ let e = marks(
683
+ typed ? shaped : probed('e'),
684
+ cancellation(col('entity', 'e')),
685
+ )
686
+ // The newest entry a passive notice does not hide, whether it is a stop,
687
+ // and, when it is a refusal, the request it refused.
688
+ let latest = select({
689
+ cols: [
690
+ col('entity', 'e'),
691
+ col('seq', 'e'),
692
+ as(e.worn('stop'), 'stop'),
693
+ as(
694
+ and(
695
+ e.worn('ask'),
696
+ not(e.worn('attempt')),
697
+ ...['exception', 'refusal', 'interrupted'].map((c) =>
698
+ not(e.worn(c))
699
+ ),
700
+ ),
701
+ 'unfinished',
702
+ ),
703
+ as(
704
+ iff(
705
+ e.worn('refusal'),
706
+ sub(select({
707
+ cols: [col('source', 'o')],
708
+ from: table('output', 'o'),
709
+ where: eq(col('entity', 'o'), col('entity', 'e')),
710
+ })),
711
+ lit(null),
712
+ ),
713
+ 'refused_source',
714
+ ),
715
+ ...typed ? [col('tables', 'shape')] : [],
716
+ ],
717
+ from: table('entry', 'e'),
718
+ joins: shapes,
719
+ where: and(mine('e'), not(e.passive)),
720
+ order: [desc(col('seq', 'e'))],
721
+ limit: lit(1),
722
+ })
723
+ // Imported asks may have no input boundary. Seek the last input/stop in
724
+ // this transcript so a late ask cannot hide the stop it followed.
725
+ let control = select({
726
+ cols: [col('seq', 'e')],
727
+ from: table('entry', 'e'),
728
+ joins: shapes,
729
+ where: and(
730
+ mine('e'),
731
+ notNull(col('seq', 'e')),
732
+ // a stop no passive notice hides: a plain stop, or a cancellation
733
+ or(and(e.worn('stop'), not(e.worn('notice'))), e.cancel, e.input),
734
+ ),
735
+ order: [desc(col('seq', 'e'))],
736
+ limit: lit(1),
737
+ })
738
+ // The newest ask: the newest sequenced one, else the newest one written
739
+ // before entries were sequenced. The first arm with a row ends the read,
740
+ // so a sequenced ask never pays for the search.
741
+ let onAsk = eq(col('entity', 'a'), col('entity', 'e'))
742
+ // A correlated scalar cannot flatten into the join whose tiny ANALYZE
743
+ // estimate makes SQLite scan all asks instead of seeking their primary key.
744
+ let askField = (alias: string, name: string): Expr =>
745
+ sub(select({
746
+ cols: [col(name, 'point_ask')],
747
+ from: table(ASK, 'point_ask'),
748
+ where: eq(col('entity', 'point_ask'), col('entity', alias)),
749
+ }))
750
+ let askAt = (where: Expr): Select =>
751
+ select({
752
+ cols: [star()],
753
+ from: from(select({
754
+ cols: [
755
+ col('entity', 'candidate'),
756
+ col('seq', 'candidate'),
757
+ as(
758
+ fn('json_extract', col('request', 'candidate'), lit('$[1]')),
759
+ 'through',
760
+ ),
761
+ ],
762
+ from: from(
763
+ select({
764
+ cols: [
765
+ col('entity', 'e'),
766
+ col('seq', 'e'),
767
+ as(
768
+ sub(select({
769
+ cols: [
770
+ fn(
771
+ 'json_array',
772
+ col('entity', 'point_ask'),
773
+ col('through', 'point_ask'),
774
+ ),
775
+ ],
776
+ from: table(ASK, 'point_ask'),
777
+ where: eq(col('entity', 'point_ask'), col('entity', 'e')),
778
+ })),
779
+ 'request',
780
+ ),
781
+ ],
782
+ from: table('entry', 'e'),
783
+ where,
784
+ order: [desc(col('seq', 'e'))],
785
+ // Keep the scalar row together: flattening would evaluate it once
786
+ // for presence and again for through, billing the ask twice.
787
+ limit: lit(-1),
788
+ }),
789
+ 'candidate',
790
+ ),
791
+ where: notNull(col('request', 'candidate')),
792
+ limit: lit(1),
793
+ })),
794
+ })
795
+ let unsequenced = (source: Source, joins: Join[], point = false) =>
796
+ sub(select({
797
+ cols: [col('entity', 'e')],
798
+ from: source,
799
+ joins,
800
+ where: and(
801
+ mine('e'),
802
+ isNull(col('seq', 'e')),
803
+ ...(point ? [notNull(askField('e', 'entity'))] : []),
804
+ ),
805
+ order: [desc(col('seq', 'e'))],
806
+ limit: lit(1),
807
+ }))
808
+ // Only a transcript holding an entry written before entries were
809
+ // sequenced is searched for one: one seek of its own entries answers for
810
+ // the rest, where the search reads the store's asks while they are few.
811
+ let legacy = exists(select({
812
+ cols: [lit(1)],
813
+ from: gate('entry', 'old'),
814
+ where: and(mine('old'), isNull(col('seq', 'old'))),
815
+ limit: lit(1),
816
+ }))
817
+ let ask = {
818
+ ...unionAll(
819
+ askAt(and(mine('e'), notNull(col('seq', 'e')))),
820
+ askAt(and(
821
+ mine('e'),
822
+ eq(
823
+ col('entity', 'e'),
824
+ iff(
825
+ legacy,
826
+ iff(
827
+ exists(select({
828
+ cols: [lit(1)],
829
+ from: gate(ASK),
830
+ limit: lit(1),
831
+ offset: lit(64),
832
+ })),
833
+ unsequenced(table('entry', 'e'), [], true),
834
+ unsequenced(table(ASK, 'a'), [{
835
+ ...cross(table('entry', 'e')),
836
+ on: onAsk,
837
+ }]),
838
+ ),
839
+ lit(null),
840
+ ),
841
+ ),
842
+ )),
843
+ ),
844
+ limit: lit(1),
845
+ }
846
+ let anchors = select({
847
+ cols: [
848
+ as(col('entity', 'l'), 'newest'),
849
+ as(col('seq', 'l'), 'newest_seq'),
850
+ as(col('entity', 'a'), 'asked'),
851
+ as(col('seq', 'a'), 'asked_seq'),
852
+ as(col('seq', 'boundary'), 'boundary_seq'),
853
+ // The ask's boundary also acknowledges input admitted while that
854
+ // request was in flight; a stop there is part of the turn.
855
+ as(
856
+ fn(
857
+ 'coalesce',
858
+ op(
859
+ '+',
860
+ col('seq', 'boundary'),
861
+ iff(
862
+ or(
863
+ probed('boundary')('stop'),
864
+ iff(
865
+ probed('boundary')('notice'),
866
+ cancellation(col('entity', 'boundary')),
867
+ lit(false),
868
+ ),
869
+ ),
870
+ lit(0),
871
+ lit(1),
872
+ ),
873
+ ),
874
+ sub(control),
875
+ ),
876
+ 'control_seq',
877
+ ),
878
+ as(
879
+ sub(select({
880
+ cols: [col('seq', 'r')],
881
+ from: table('entry', 'r'),
882
+ where: eq(col('entity', 'r'), col('refused_source', 'l')),
883
+ })),
884
+ 'refused_seq',
885
+ ),
886
+ as(col('refused_source', 'l'), 'refused_source'),
887
+ ...typed ? [as(col('tables', 'l'), 'newest_tables')] : [],
888
+ ],
889
+ from: table(LATEST, 'l'),
890
+ joins: [
891
+ left(from(ask, 'a'), lit(true)),
892
+ left(
893
+ table('entry', 'boundary'),
894
+ eq(col('entity', 'boundary'), col('through', 'a')),
895
+ ),
896
+ ],
897
+ })
898
+ let anchor = at('anchor')
899
+ let start = fn(
900
+ 'min',
901
+ fn('coalesce', anchor('asked_seq'), lit(0)),
902
+ fn(
903
+ 'coalesce',
904
+ anchor('control_seq'),
905
+ anchor('asked_seq'),
906
+ anchor('newest_seq'),
907
+ ),
908
+ fn(
909
+ 'coalesce',
910
+ op('+', anchor('refused_seq'), lit(1)),
911
+ anchor('newest_seq'),
912
+ ),
913
+ )
914
+ // The turn: its entries from its start through the newest, or the newest
915
+ // alone in a transcript written before entries were sequenced. The
916
+ // anchors are read once, so the turn's rows hang off them as a left join
917
+ // rather than a union of two reads. Each row reads every component it
918
+ // wears in one pass: through the archetype, else a join per component.
919
+ // The shape is joined on the entry itself, where a reader's scope admits
920
+ // it with the entry (@yaks/sql bind.ts `ownerReads`); the newest alone
921
+ // brings its own. Naming the anchor columns keeps the admitted `entity`
922
+ // unambiguous through this projection.
923
+ let span = select({
924
+ cols: [
925
+ as(fn('coalesce', col('entity', 'i'), anchor('newest')), 'entity'),
926
+ col('seq', 'i'),
927
+ anchor('asked'),
928
+ anchor('asked_seq'),
929
+ anchor('boundary_seq'),
930
+ anchor('newest'),
931
+ anchor('refused_source'),
932
+ ...typed
933
+ ? [as(
934
+ fn(
935
+ 'coalesce',
936
+ col('tables', 'shape'),
937
+ iff(
938
+ isNull(col('entity', 'i')),
939
+ anchor('newest_tables'),
940
+ lit(null),
941
+ ),
942
+ ),
943
+ 'tables',
944
+ )]
945
+ : [],
946
+ ],
947
+ from: table(ANCHOR, 'anchor'),
948
+ joins: [
949
+ left(
950
+ table('entry', 'i'),
951
+ and(
952
+ mine('i'),
953
+ notNull(anchor('newest_seq')),
954
+ ge(col('seq', 'i'), start),
955
+ ),
956
+ ),
957
+ ...typed
958
+ ? [
959
+ left(
960
+ table('entity', 'owner'),
961
+ eq(col('id', 'owner'), col('entity', 'i')),
962
+ ),
963
+ left(
964
+ table('archetype', 'shape'),
965
+ eq(col('entity', 'shape'), col('archetype', 'owner')),
966
+ ),
967
+ ]
968
+ : [],
969
+ ],
970
+ where: or(isNull(anchor('newest_seq')), notNull(col('entity', 'i'))),
971
+ })
972
+ let wears = typed
973
+ ? (comp: string) => holds(col('tables', 'span'), comp)
974
+ : (comp: string) => notNull(col('entity', comp))
975
+ // Each component the rule reads, where the entry wears it: its id.
976
+ let comps = [
977
+ 'stop',
978
+ 'notice',
979
+ 'content',
980
+ 'exception',
981
+ 'refusal',
982
+ 'interrupted',
983
+ 'failed',
984
+ 'provisional',
985
+ 'using',
986
+ 'sending',
987
+ 'ask',
988
+ 'call',
989
+ 'result',
990
+ 'tool_progress',
991
+ 'tool_async',
992
+ 'output',
993
+ 'attempt',
994
+ 'execution',
995
+ ]
996
+ let joins: Join[] = []
997
+ if (!typed) {
998
+ joins.push(
999
+ ...comps.filter(declared).map((comp) =>
1000
+ left(
1001
+ table(comp, comp),
1002
+ eq(col('entity', comp), col('entity', 'span')),
1003
+ )
1004
+ ),
1005
+ )
1006
+ }
1007
+ let prop = (comp: string, p: string) =>
1008
+ as(
1009
+ !declared(comp) ? lit(null) : typed
1010
+ ? iff(
1011
+ wears(comp),
1012
+ sub(select({
1013
+ cols: [col(p, 'v')],
1014
+ from: table(comp, 'v'),
1015
+ where: eq(col('entity', 'v'), col('entity', 'span')),
1016
+ })),
1017
+ lit(null),
1018
+ )
1019
+ : col(p, comp),
1020
+ `${comp}_${p}`,
1021
+ )
1022
+ let turn = select({
1023
+ cols: [
1024
+ col('entity', 'span'),
1025
+ col('seq', 'span'),
1026
+ ...comps.map((comp) =>
1027
+ as(
1028
+ !declared(comp)
1029
+ ? lit(null)
1030
+ : typed
1031
+ ? iff(wears(comp), col('entity', 'span'), lit(null))
1032
+ : col('entity', comp),
1033
+ comp,
1034
+ )
1035
+ ),
1036
+ as(
1037
+ declared('notice')
1038
+ ? iff(
1039
+ wears('notice'),
1040
+ cancellation(col('entity', 'span')),
1041
+ lit(false),
1042
+ )
1043
+ : lit(false),
1044
+ 'cancelled',
1045
+ ),
1046
+ prop('attempt', 'by'),
1047
+ prop('execution', 'by'),
1048
+ // Final results close work; a Pending entry of the newest reply's
1049
+ // background call permits the model to continue.
1050
+ as(
1051
+ declared('call')
1052
+ ? iff(
1053
+ wears('call'),
1054
+ sub(select({
1055
+ cols: [col('entity', 'r')],
1056
+ from: table(RESULT, 'r'),
1057
+ where: eq(col('call', 'r'), col('entity', 'span')),
1058
+ limit: lit(1),
1059
+ })),
1060
+ lit(null),
1061
+ )
1062
+ : lit(null),
1063
+ 'answered',
1064
+ ),
1065
+ prop('call', 'source'),
1066
+ as(
1067
+ declared('tool_progress')
1068
+ ? iff(
1069
+ wears('call'),
1070
+ exists(select({
1071
+ cols: [lit(1)],
1072
+ from: table('tool_progress', 'p'),
1073
+ where: eq(col('call', 'p'), col('entity', 'span')),
1074
+ })),
1075
+ lit(false),
1076
+ )
1077
+ : lit(false),
1078
+ 'progressed',
1079
+ ),
1080
+ col('boundary_seq', 'span'),
1081
+ as(col('asked', 'span'), 'ask_id'),
1082
+ col('refused_source', 'span'),
1083
+ as(eq(col('entity', 'span'), col('newest', 'span')), 'newest'),
1084
+ as(eq(col('entity', 'span'), col('asked', 'span')), 'asked'),
1085
+ as(
1086
+ ge(
1087
+ col('seq', 'span'),
1088
+ fn('coalesce', col('asked_seq', 'span'), lit(0)),
1089
+ ),
1090
+ 'current',
1091
+ ),
1092
+ ],
1093
+ from: from(span, 'span'),
1094
+ joins,
1095
+ })
1096
+ let has = (comp: string, alias = 't') => notNull(col(comp, alias))
1097
+ // Whether the entry `alias` was read from a harness's file: looked up only
1098
+ // for an ask, the one entry it changes.
1099
+ let read = (alias: string) =>
1100
+ declared('lines')
1101
+ ? exists(select({
1102
+ cols: [lit(1)],
1103
+ from: table('lines', 'line'),
1104
+ where: eq(col('entity', 'line'), col('entity', alias)),
1105
+ }))
1106
+ : lit(false)
1107
+ let lacks = (comp: string, alias = 't') => isNull(col(comp, alias))
1108
+ let current = col('current', 't')
1109
+ let open = and(
1110
+ current,
1111
+ has('call'),
1112
+ lacks('answered'),
1113
+ lacks('tool_async'),
1114
+ )
1115
+ let inflight = and(
1116
+ current,
1117
+ has('attempt'),
1118
+ notNull(col('attempt_by', 't')),
1119
+ lacks('interrupted'),
1120
+ )
1121
+ let flag = (name: string, condition: Expr) =>
1122
+ as(fn('max', iff(condition, lit(1), lit(0))), name)
1123
+ let newest = col('newest', 't')
1124
+ let asked = col('asked', 't')
1125
+ let row = marks((comp) => has(comp), col('cancelled', 't'))
1126
+ // A result carrying its call's refusal is a result, as `kindOf` reads it.
1127
+ let value = (name: string) =>
1128
+ name == 'stop'
1129
+ ? iff(row.halted, col('entity', 't'), lit(null))
1130
+ : name == 'exception' || name == 'refusal'
1131
+ ? iff(has('result'), lit(null), col(name, 't'))
1132
+ : col(name, 't')
1133
+ let names = [
1134
+ 'stop',
1135
+ 'exception',
1136
+ 'refusal',
1137
+ 'interrupted',
1138
+ 'failed',
1139
+ 'ask',
1140
+ 'call',
1141
+ 'result',
1142
+ 'tool_progress',
1143
+ 'output',
1144
+ 'attempt',
1145
+ 'attempt_by',
1146
+ 'refused_source',
1147
+ 'boundary_seq',
1148
+ ]
1149
+ let askNames = [
1150
+ 'interrupted',
1151
+ 'failed',
1152
+ 'provisional',
1153
+ 'seq',
1154
+ ]
1155
+ // Keep these historical predicates out of the turn aggregate: earlier
1156
+ // verdicts need neither. Presence includes answered background calls;
1157
+ // only the running branch needs an unanswered one.
1158
+ let background = (unanswered: boolean): Expr =>
1159
+ declared('tool_async')
1160
+ ? iff(
1161
+ exists(select({ cols: [lit(1)], from: gate('tool_async') })),
1162
+ sub(select({
1163
+ cols: [lit(1)],
1164
+ from: table('entry', 'pe'),
1165
+ joins: [{
1166
+ ...cross(table('tool_async', 'p')),
1167
+ on: eq(col('entity', 'pe'), col('entity', 'p')),
1168
+ }],
1169
+ where: and(
1170
+ mine('pe'),
1171
+ ...unanswered
1172
+ ? [not(exists(select({
1173
+ cols: [lit(1)],
1174
+ from: table(RESULT, 'r'),
1175
+ where: eq(col('call', 'r'), col('entity', 'p')),
1176
+ })))]
1177
+ : [],
1178
+ ),
1179
+ // EXISTS discards ordering. A scalar LIMIT keeps newest-first seeks.
1180
+ order: [desc(col('seq', 'pe'))],
1181
+ limit: lit(1),
1182
+ })),
1183
+ lit(null),
1184
+ )
1185
+ : lit(null)
1186
+ let facts = select({
1187
+ cols: [
1188
+ flag('open', open),
1189
+ flag(
1190
+ 'abandoned',
1191
+ and(
1192
+ open,
1193
+ has('execution'),
1194
+ isNull(col('execution_by', 't')),
1195
+ lacks('interrupted'),
1196
+ ),
1197
+ ),
1198
+ flag('inflight', inflight),
1199
+ // A call of the newest reply still running within its patience: the
1200
+ // reply's other answers wait for it.
1201
+ flag(
1202
+ 'unheard',
1203
+ and(
1204
+ current,
1205
+ has('tool_async'),
1206
+ eq(col('call_source', 't'), col('ask_id', 't')),
1207
+ lacks('answered'),
1208
+ not(col('progressed', 't')),
1209
+ ),
1210
+ ),
1211
+ as(
1212
+ fn(
1213
+ 'max',
1214
+ iff(
1215
+ or(
1216
+ has('result'),
1217
+ declared('tool_progress') && declared('call')
1218
+ ? and(
1219
+ has('tool_progress'),
1220
+ exists(select({
1221
+ cols: [lit(1)],
1222
+ from: table('tool_progress', 'rp'),
1223
+ joins: [join(
1224
+ table('call', 'rc'),
1225
+ eq(col('entity', 'rc'), col('call', 'rp')),
1226
+ )],
1227
+ where: and(
1228
+ eq(col('entity', 'rp'), col('entity', 't')),
1229
+ eq(col('source', 'rc'), col('ask_id', 't')),
1230
+ ),
1231
+ })),
1232
+ )
1233
+ : lit(false),
1234
+ ),
1235
+ col('seq', 't'),
1236
+ lit(null),
1237
+ ),
1238
+ ),
1239
+ 'ready_seq',
1240
+ ),
1241
+ as(fn('max', iff(row.input, col('seq', 't'), lit(null))), 'input_seq'),
1242
+ as(fn('max', iff(row.halted, col('seq', 't'), lit(null))), 'stop_seq'),
1243
+ flag('served', or(has('using'), and(has('ask'), not(read('t'))))),
1244
+ ...names.map((name) =>
1245
+ as(fn('max', iff(newest, value(name), lit(null))), 'n_' + name)
1246
+ ),
1247
+ ...askNames.map((name) =>
1248
+ as(fn('max', iff(asked, col(name, 't'), lit(null))), 'a_' + name)
1249
+ ),
1250
+ as(fn('max', col('entity', 't')), 'any'),
1251
+ ],
1252
+ from: from(turn, 't'),
1253
+ // Past plain outputs contribute no historical fact. Keep both anchors
1254
+ // and every other mark: an output can also carry outstanding work.
1255
+ where: and(
1256
+ not(row.passive),
1257
+ or(
1258
+ newest,
1259
+ asked,
1260
+ lacks('output'),
1261
+ ...comps.filter((c) => c != 'content' && c != 'output').map((c) =>
1262
+ has(c)
1263
+ ),
1264
+ ),
1265
+ ),
1266
+ })
1267
+ let n = (name: string) => notNull(col('n_' + name, 'f'))
1268
+ let f = (name: string) => col(name, 'f')
1269
+ let a = (name: string) => notNull(col('a_' + name, 'f'))
1270
+ let after = (seq: Expr) =>
1271
+ fn('coalesce', gt(f('input_seq'), seq), lit(false))
1272
+ let boundary = fn('coalesce', f('n_boundary_seq'), f('a_seq'), lit(0))
1273
+ // Two bounded historical facts remain: a refusal can explicitly name an
1274
+ // older ask, and the retry limit covers at most RETRIES consecutive asks.
1275
+ // Neither is an open-work scan.
1276
+ let refused = sub(select({
1277
+ cols: [col('seq', 'b')],
1278
+ from: table('entry', 'b'),
1279
+ where: and(
1280
+ mine('b'),
1281
+ notNull(askField('b', 'entity')),
1282
+ eq(col('entity', 'b'), col('n_refused_source', 'f')),
1283
+ ),
1284
+ }))
1285
+ let probe = marks(probed('e'), cancellation(col('entity', 'e')))
1286
+ let retries = sub(select({
1287
+ cols: [fn('sum', col('interrupted', 'r'))],
1288
+ from: from(
1289
+ select({
1290
+ cols: [col('seq', 'e'), as(probe.worn('interrupted'), 'interrupted')],
1291
+ from: table('entry', 'e'),
1292
+ where: and(
1293
+ mine('e'),
1294
+ notNull(askField('e', 'entity')),
1295
+ not(probe.passive),
1296
+ ),
1297
+ order: [desc(col('seq', 'e'))],
1298
+ limit: lit(RETRIES),
1299
+ }),
1300
+ 'r',
1301
+ ),
1302
+ where: or(isNull(f('input_seq')), gt(col('seq', 'r'), f('input_seq'))),
1303
+ }))
1304
+ // Before the first ask, a model selection on the original request still
1305
+ // makes a later input owed by this runner. Once asked, the turn itself is
1306
+ // the proof of service and no historical request is read, unless it was
1307
+ // read from a harness's file: that harness answers its own transcript.
1308
+ let owed = iff(f('served'), lit('pending'), lit('running'))
1309
+ // Once these branches decline, only nonterminal answers remain. A test
1310
+ // for stopped/failed needs none of the historical progress census below.
1311
+ let verdict = (rest: Expr) =>
1312
+ when(
1313
+ [
1314
+ [
1315
+ or(
1316
+ n('stop'),
1317
+ and(notNull(f('stop_seq')), not(after(f('stop_seq')))),
1318
+ ),
1319
+ lit('stopped'),
1320
+ ],
1321
+ [f('abandoned'), lit('running')],
1322
+ [n('exception'), lit('failed')],
1323
+ [
1324
+ and(n('interrupted'), n('failed'), not(n('ask')), not(n('call'))),
1325
+ lit('failed'),
1326
+ ],
1327
+ [f('inflight'), lit('running')],
1328
+ [eq(dispatch.expr(owner), lit('queued')), lit('queued')],
1329
+ [n('refusal'), iff(after(refused), lit('pending'), lit('failed'))],
1330
+ [
1331
+ and(a('interrupted'), a('failed'), not(after(col('a_seq', 'f')))),
1332
+ lit('failed'),
1333
+ ],
1334
+ [and(a('interrupted'), after(col('a_seq', 'f'))), lit('pending')],
1335
+ [and(a('interrupted'), a('provisional')), lit('pending')],
1336
+ [
1337
+ a('interrupted'),
1338
+ iff(ge(retries, lit(RETRIES)), lit('failed'), lit('pending')),
1339
+ ],
1340
+ ],
1341
+ rest,
1342
+ )
1343
+ let nonterminal = when([
1344
+ [f('open'), lit('running')],
1345
+ [
1346
+ and(
1347
+ or(
1348
+ after(boundary),
1349
+ and(eq(f('unheard'), lit(0)), gt(f('ready_seq'), boundary)),
1350
+ ),
1351
+ notNull(background(false)),
1352
+ ),
1353
+ lit('pending'),
1354
+ ],
1355
+ [notNull(background(true)), lit('running')],
1356
+ [
1357
+ and(
1358
+ n('ask'),
1359
+ n('attempt'),
1360
+ isNull(col('n_attempt_by', 'f')),
1361
+ not(n('interrupted')),
1362
+ ),
1363
+ lit('settled'),
1364
+ ],
1365
+ [or(n('ask'), n('call')), lit('running')],
1366
+ [
1367
+ and(
1368
+ n('output'),
1369
+ not(n('result')),
1370
+ not(n('tool_progress')),
1371
+ not(n('interrupted')),
1372
+ ),
1373
+ iff(
1374
+ after(col('n_boundary_seq', 'f')),
1375
+ lit('pending'),
1376
+ lit('settled'),
1377
+ ),
1378
+ ],
1379
+ ], owed)
1380
+ // Keep the expression below workerd's depth limit, including the runner's
1381
+ // enclosing union. FROM subqueries and common table expressions don't add
1382
+ // to expression height.
1383
+ let decision = (rest: Expr) =>
1384
+ select({
1385
+ cols: [as(verdict(rest), 'v')],
1386
+ from: from(facts, 'f'),
1387
+ where: notNull(col('any', 'f')),
1388
+ })
1389
+ let ended = sub(
1390
+ select({
1391
+ cols: [col('ended', 's')],
1392
+ from: table('session', 's'),
1393
+ where: eq(col('entity', 's'), owner),
1394
+ }),
1395
+ )
1396
+ // A newest stop, or an ended ask with no attempt or failure, is stopped
1397
+ // whatever the earlier turn owes. Neither needs its history read.
1398
+ let said = (verdict: Select) =>
1399
+ fn(
1400
+ 'coalesce',
1401
+ sub(select({
1402
+ with: [
1403
+ { name: LATEST, q: latest, materialized: false },
1404
+ // The anchor is consumed once by the sequenced branch (or its
1405
+ // legacy fallback). Inlining avoids a billed temporary-row read;
1406
+ // its newest-entry and ask seeks remain bounded.
1407
+ { name: ANCHOR, q: anchors, materialized: false },
1408
+ ],
1409
+ cols: [
1410
+ iff(
1411
+ exists(select({
1412
+ from: table(LATEST, 'l'),
1413
+ where: or(col('stop', 'l'), and(ended, col('unfinished', 'l'))),
1414
+ })),
1415
+ lit('stopped'),
1416
+ sub(select({ cols: [col('v', 'x')], from: from(verdict, 'x') })),
1417
+ ),
1418
+ ],
1419
+ })),
1420
+ lit('empty'),
1421
+ )
1422
+ // A process of its own runs it while its row wears a `process` with no
1423
+ // `exit` (./state.ts `Marks`): what the entries leave owing is that
1424
+ // process's to answer, never the runner's.
1425
+ let wearing = (name: string) =>
1426
+ exists(select({
1427
+ cols: [lit(1)],
1428
+ from: table(name, 'm'),
1429
+ where: eq(col('entity', 'm'), owner),
1430
+ }))
1431
+ let process = declared('process') && declared('exit')
1432
+ ? and(wearing('process'), not(wearing('exit')))
1433
+ : lit(false)
1434
+ // The mark ends only what its entries leave unfinished. The limit keeps the
1435
+ // status one column here, or flattening would work it out once per mention.
1436
+ let whole = sub(select({
1437
+ cols: [
1438
+ when([
1439
+ [
1440
+ and(
1441
+ fn('coalesce', col('ended', 'r'), lit(false)),
1442
+ among(col('v', 'r'), UNFINISHED.map(lit)),
1443
+ ),
1444
+ lit('stopped'),
1445
+ ],
1446
+ [and(process, eq(col('v', 'r'), lit('pending'))), lit('running')],
1447
+ ], col('v', 'r')),
1448
+ ],
1449
+ from: from(
1450
+ select({
1451
+ cols: [as(said(decision(nonterminal)), 'v'), as(ended, 'ended')],
1452
+ limit: lit(-1),
1453
+ }),
1454
+ 'r',
1455
+ ),
1456
+ }))
1457
+ if (!terminal) return whole
1458
+ return iff(ended, whole, said(decision(lit(''))))
1459
+ },
1460
+ }
1461
+
1462
+ /** The derived-property registry a SQLite store loads to read
1463
+ * `session.status`, compatible `dispatch.status`, and `session.cost` (./cost.ts)
1464
+ * where the vocabulary declares the `cost.dollars` it sums: a store may hold an app's own `cost`
1465
+ * in place of @yaks/model's. The configured `reading` registry resolves content
1466
+ * before interpreting historical controls; without an override, content is
1467
+ * text in its component. */
1468
+ export let sessionDerived = (vocab: Vocab, reading: Derived = {}): Derived => {
1469
+ // Small compositions can declare dispatch without loading kernel's marks.
1470
+ // Missing marks are absent, not tables to read (nor an empty CASE ladder).
1471
+ let marks = ['waiting', 'admitted'].filter((comp) => vocab.comp(comp))
1472
+ let dispatch = {
1473
+ ...dispatchStatus,
1474
+ deps: ['dispatch', ...marks],
1475
+ expr: (owner: Expr) => dispatchStatus.expr(owner, marks),
1476
+ }
1477
+ let states = { ...attemptDerived(vocab), ...executionDerived(vocab) }
1478
+ let text = reading['content.body']?.text
1479
+ let declared = (scope?: DerivedScope): Words => ({
1480
+ declared: (name) =>
1481
+ !!vocab.comp(name) && (name != 'archetype' || !scope?.masked.length),
1482
+ holds: (tables, comp) => descriptorHolds(tables, vocab, comp),
1483
+ })
1484
+ return {
1485
+ ...states,
1486
+ 'session.status': {
1487
+ ...sessionStatus,
1488
+ stable: !reading['content.body'] ||
1489
+ reading['content.body'].stable == true,
1490
+ test: (owner, values, scope) => {
1491
+ // Unfinished words screen the one session as the select screens
1492
+ // every session: most rest, and the exact rule reads only the rest.
1493
+ if (
1494
+ !values.every((v) =>
1495
+ (v.t == 'val' || v.t == 'lit') &&
1496
+ ['stopped', 'failed'].includes(String(v.v))
1497
+ )
1498
+ ) {
1499
+ let one = sessionStatus.select(
1500
+ values,
1501
+ dispatch,
1502
+ declared(scope),
1503
+ text,
1504
+ owner,
1505
+ )
1506
+ if (
1507
+ one &&
1508
+ values.every((v) =>
1509
+ (v.t == 'val' || v.t == 'lit') && UNFINISHED.includes(String(v.v))
1510
+ )
1511
+ ) {
1512
+ // Ended sessions cannot match. Decline before creating even empty
1513
+ // candidate CTEs for each historical owner on an ordered page.
1514
+ return iff(
1515
+ sub(select({
1516
+ cols: [col('ended', 'ended')],
1517
+ from: table('session', 'ended'),
1518
+ where: eq(col('entity', 'ended'), owner),
1519
+ })),
1520
+ lit(false),
1521
+ exists(one),
1522
+ )
1523
+ }
1524
+ return one && exists(one)
1525
+ }
1526
+ return among(
1527
+ sessionStatus.expr(
1528
+ owner,
1529
+ dispatch,
1530
+ declared(scope),
1531
+ text,
1532
+ true,
1533
+ ),
1534
+ values,
1535
+ )
1536
+ },
1537
+ select: (values, scope) =>
1538
+ sessionStatus.select(
1539
+ values,
1540
+ dispatch,
1541
+ declared(scope),
1542
+ text,
1543
+ ),
1544
+ expr: (owner, scope) =>
1545
+ sessionStatus.expr(
1546
+ owner,
1547
+ dispatch,
1548
+ declared(scope),
1549
+ text,
1550
+ ),
1551
+ },
1552
+ 'dispatch.status': dispatch,
1553
+ ...vocab.prop(COST, 'dollars') ? { 'session.cost': sessionCost } : {},
1554
+ }
1555
+ }