@yaks/browse 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 (271) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +324 -2
  3. package/_dist/app.d.ts +8 -0
  4. package/_dist/app.d.ts.map +1 -0
  5. package/_dist/cli.d.ts +16 -0
  6. package/_dist/cli.d.ts.map +1 -0
  7. package/_dist/hosting.d.ts +24 -0
  8. package/_dist/hosting.d.ts.map +1 -0
  9. package/_dist/mod.d.ts +7 -0
  10. package/_dist/mod.d.ts.map +1 -0
  11. package/_dist/types.d.ts +5 -0
  12. package/_dist/types.d.ts.map +1 -0
  13. package/_dist/url.d.ts +2 -0
  14. package/_dist/url.d.ts.map +1 -0
  15. package/app.js +10 -0
  16. package/app.js.map +1 -0
  17. package/app.ts +10 -0
  18. package/browser-links.js +22 -0
  19. package/browser-links.js.map +1 -0
  20. package/browser-links.ts +28 -0
  21. package/cli.js +172 -0
  22. package/cli.js.map +1 -0
  23. package/cli.ts +168 -0
  24. package/client.js +748 -0
  25. package/client.js.map +1 -0
  26. package/client.ts +734 -0
  27. package/clipboard.js +18 -0
  28. package/clipboard.js.map +1 -0
  29. package/clipboard.ts +17 -0
  30. package/commands.js +1157 -0
  31. package/commands.js.map +1 -0
  32. package/commands.ts +1108 -0
  33. package/components/Ansi.tsx +160 -0
  34. package/components/App.tsx +446 -0
  35. package/components/Canvas.tsx +625 -0
  36. package/components/Card.tsx +276 -0
  37. package/components/Chat.tsx +205 -0
  38. package/components/Configuration.tsx +218 -0
  39. package/components/Decision.tsx +49 -0
  40. package/components/Dot.tsx +52 -0
  41. package/components/Entity.tsx +609 -0
  42. package/components/Fault.tsx +43 -0
  43. package/components/Filter.tsx +103 -0
  44. package/components/Keybindings.tsx +100 -0
  45. package/components/Keys.tsx +67 -0
  46. package/components/Markdown.tsx +90 -0
  47. package/components/Navigation.tsx +161 -0
  48. package/components/New.tsx +490 -0
  49. package/components/Peek.tsx +168 -0
  50. package/components/Prio.tsx +20 -0
  51. package/components/Run.tsx +263 -0
  52. package/components/Search.tsx +280 -0
  53. package/components/Stamp.tsx +44 -0
  54. package/components/Status.tsx +514 -0
  55. package/components/Sync.tsx +173 -0
  56. package/components/Tile.tsx +50 -0
  57. package/components/answered.js +23 -0
  58. package/components/answered.js.map +1 -0
  59. package/components/answered.ts +25 -0
  60. package/components/comp.js +11 -0
  61. package/components/comp.js.map +1 -0
  62. package/components/comp.ts +10 -0
  63. package/components/drag.js +173 -0
  64. package/components/drag.js.map +1 -0
  65. package/components/drag.ts +198 -0
  66. package/components/fields.tsx +90 -0
  67. package/components/fixtures/README.md +10 -0
  68. package/components/fixtures/archetypes.json +3646 -0
  69. package/components/hits.js +63 -0
  70. package/components/hits.js.map +1 -0
  71. package/components/hits.ts +84 -0
  72. package/components/icons.tsx +177 -0
  73. package/components/inspect.tsx +331 -0
  74. package/components/mount.ts +79 -0
  75. package/components/nav.tsx +479 -0
  76. package/components/offers.js +26 -0
  77. package/components/offers.js.map +1 -0
  78. package/components/offers.ts +54 -0
  79. package/components/page.js +21 -0
  80. package/components/page.js.map +1 -0
  81. package/components/page.ts +18 -0
  82. package/components/read.js +5 -0
  83. package/components/read.js.map +1 -0
  84. package/components/read.ts +7 -0
  85. package/components/registry.js +285 -0
  86. package/components/registry.js.map +1 -0
  87. package/components/registry.ts +317 -0
  88. package/components/session_status.tsx +115 -0
  89. package/components/subscriptions.js +149 -0
  90. package/components/subscriptions.js.map +1 -0
  91. package/components/subscriptions.ts +161 -0
  92. package/components/title.tsx +21 -0
  93. package/components/useQuery.js +166 -0
  94. package/components/useQuery.js.map +1 -0
  95. package/components/useQuery.ts +211 -0
  96. package/components/views/Board.tsx +450 -0
  97. package/components/views/BoardTile.tsx +65 -0
  98. package/components/views/Dashboard.tsx +148 -0
  99. package/components/views/Debug.tsx +445 -0
  100. package/components/views/Dependency.tsx +51 -0
  101. package/components/views/Entry.tsx +500 -0
  102. package/components/views/Gist.tsx +28 -0
  103. package/components/views/Inline.tsx +54 -0
  104. package/components/views/Json.tsx +19 -0
  105. package/components/views/Layout.tsx +211 -0
  106. package/components/views/List.tsx +238 -0
  107. package/components/views/Md.tsx +43 -0
  108. package/components/views/Media.tsx +48 -0
  109. package/components/views/Memory.tsx +32 -0
  110. package/components/views/Relate.tsx +205 -0
  111. package/components/views/Search.tsx +42 -0
  112. package/components/views/Session.tsx +850 -0
  113. package/components/views/SessionManage.tsx +127 -0
  114. package/components/views/Show.tsx +758 -0
  115. package/components/views/Shown.tsx +72 -0
  116. package/components/views/Split.tsx +58 -0
  117. package/components/views/TaskTile.tsx +37 -0
  118. package/components/views/Title.tsx +105 -0
  119. package/components/views/Wake.tsx +77 -0
  120. package/components/views/Web.tsx +49 -0
  121. package/components/wells.js +30 -0
  122. package/components/wells.js.map +1 -0
  123. package/components/wells.ts +33 -0
  124. package/configuration.js +38 -0
  125. package/configuration.js.map +1 -0
  126. package/configuration.ts +41 -0
  127. package/decision_sync.js +88 -0
  128. package/decision_sync.js.map +1 -0
  129. package/decision_sync.ts +93 -0
  130. package/deno.json +1 -0
  131. package/domain-host.tsx +108 -0
  132. package/edge.js +193 -0
  133. package/edge.js.map +1 -0
  134. package/edge.ts +196 -0
  135. package/entry_log.js +241 -0
  136. package/entry_log.js.map +1 -0
  137. package/entry_log.ts +214 -0
  138. package/failure.js +22 -0
  139. package/failure.js.map +1 -0
  140. package/failure.ts +34 -0
  141. package/front.json +61 -0
  142. package/highlight.js +143 -0
  143. package/highlight.js.map +1 -0
  144. package/highlight.ts +149 -0
  145. package/history.js +68 -0
  146. package/history.js.map +1 -0
  147. package/history.ts +72 -0
  148. package/host_commands.js +107 -0
  149. package/host_commands.js.map +1 -0
  150. package/host_commands.ts +38 -0
  151. package/hosting.js +53 -0
  152. package/hosting.js.map +1 -0
  153. package/hosting.ts +72 -0
  154. package/idb.js +14 -0
  155. package/idb.js.map +1 -0
  156. package/idb.ts +15 -0
  157. package/index.js +232 -0
  158. package/index.js.map +1 -0
  159. package/index.ts +252 -0
  160. package/keybindings.js +136 -0
  161. package/keybindings.js.map +1 -0
  162. package/keybindings.ts +37 -0
  163. package/kit.js +103 -0
  164. package/kit.js.map +1 -0
  165. package/kit.ts +119 -0
  166. package/layout.js +254 -0
  167. package/layout.js.map +1 -0
  168. package/layout.ts +210 -0
  169. package/legacy_outbox.js +53 -0
  170. package/legacy_outbox.js.map +1 -0
  171. package/legacy_outbox.ts +63 -0
  172. package/live.js +2883 -0
  173. package/live.js.map +1 -0
  174. package/live.ts +3334 -0
  175. package/live_archetypes.js +92 -0
  176. package/live_archetypes.js.map +1 -0
  177. package/live_archetypes.ts +113 -0
  178. package/live_client.js +145 -0
  179. package/live_client.js.map +1 -0
  180. package/live_client.ts +120 -0
  181. package/main.tsx +5 -0
  182. package/mod.js +7 -0
  183. package/mod.js.map +1 -0
  184. package/mod.ts +7 -0
  185. package/mount.tsx +50 -0
  186. package/navigation.js +120 -0
  187. package/navigation.js.map +1 -0
  188. package/navigation.ts +152 -0
  189. package/near.js +83 -0
  190. package/near.js.map +1 -0
  191. package/near.ts +83 -0
  192. package/new.js +295 -0
  193. package/new.js.map +1 -0
  194. package/new.ts +361 -0
  195. package/outbox.js +112 -0
  196. package/outbox.js.map +1 -0
  197. package/outbox.ts +129 -0
  198. package/owner.js +39 -0
  199. package/owner.js.map +1 -0
  200. package/owner.ts +37 -0
  201. package/package.json +81 -4
  202. package/paste.js +157 -0
  203. package/paste.js.map +1 -0
  204. package/paste.ts +122 -0
  205. package/props.js +303 -0
  206. package/props.js.map +1 -0
  207. package/props.ts +358 -0
  208. package/providers.js +136 -0
  209. package/providers.js.map +1 -0
  210. package/providers.ts +194 -0
  211. package/query.js +987 -0
  212. package/query.js.map +1 -0
  213. package/query.ts +1113 -0
  214. package/remote.js +37 -0
  215. package/remote.js.map +1 -0
  216. package/remote.ts +46 -0
  217. package/resolver.js +149 -0
  218. package/resolver.js.map +1 -0
  219. package/resolver.ts +213 -0
  220. package/rfc2047.js +37 -0
  221. package/rfc2047.js.map +1 -0
  222. package/rfc2047.ts +40 -0
  223. package/row_holds.js +107 -0
  224. package/row_holds.js.map +1 -0
  225. package/row_holds.ts +93 -0
  226. package/served.ts +42 -0
  227. package/session_worktree.js +7 -0
  228. package/session_worktree.js.map +1 -0
  229. package/session_worktree.ts +16 -0
  230. package/sessions.js +57 -0
  231. package/sessions.js.map +1 -0
  232. package/sessions.ts +53 -0
  233. package/sha.js +161 -0
  234. package/sha.js.map +1 -0
  235. package/sha.ts +164 -0
  236. package/styles.css +2823 -0
  237. package/subs.js +36 -0
  238. package/subs.js.map +1 -0
  239. package/subs.ts +40 -0
  240. package/terminal-route.js +13 -0
  241. package/terminal-route.js.map +1 -0
  242. package/terminal-route.ts +17 -0
  243. package/terminal.js +251 -0
  244. package/terminal.js.map +1 -0
  245. package/terminal.ts +186 -0
  246. package/time.js +142 -0
  247. package/time.js.map +1 -0
  248. package/time.ts +133 -0
  249. package/title.js +25 -0
  250. package/title.js.map +1 -0
  251. package/title.ts +50 -0
  252. package/tui/doc.ts +6 -0
  253. package/tui/testing.ts +19 -0
  254. package/twin.js +11 -0
  255. package/twin.js.map +1 -0
  256. package/twin.ts +13 -0
  257. package/types.js +456 -0
  258. package/types.js.map +1 -0
  259. package/types.ts +1370 -0
  260. package/url.js +77 -0
  261. package/url.js.map +1 -0
  262. package/url.ts +85 -0
  263. package/verb.js +82 -0
  264. package/verb.js.map +1 -0
  265. package/verb.ts +137 -0
  266. package/warmth.js +41 -0
  267. package/warmth.js.map +1 -0
  268. package/warmth.ts +54 -0
  269. package/wire.js +86 -0
  270. package/wire.js.map +1 -0
  271. package/wire.ts +63 -0
package/live.ts ADDED
@@ -0,0 +1,3334 @@
1
+ import { queryAt } from '@yaks/query'
2
+ import { rowHolds } from './row_holds.js'
3
+ import { writeOwner } from './owner.js'
4
+ import {
5
+ formerOutboxScope,
6
+ hosting,
7
+ legacyOutboxName,
8
+ storageKey,
9
+ } from './hosting.js'
10
+ // The browser half: one graph cache, narrow render signals, one socket,
11
+ // one identity, one camera. Boots are cold and subscription-shaped (T-21491):
12
+ // ~3.4 MB for the root canvas, formerly ~3.4 GB; patches publish only the rows
13
+ // and relationships their renderers hold. The path (T-37031..T-37035) is a
14
+ // bounded 20,000-row retention floor, ready in read doors, leak-free subs,
15
+ // a trimmed boot working set, then @yaks/client with retention, ready and dedupe
16
+ // upstream. Retention lets reopens paint; ready separates loading from absent.
17
+ // Never restore whole-db sync or an unbounded cache.
18
+ import { IdError } from './types.js'
19
+ import { answering, parse } from '@yaks/id'
20
+ /* @ts-types="npm:@types/react@19.3.0" */ import { useLayoutEffect, useRef } from 'react'
21
+ import {
22
+ batch,
23
+ computed,
24
+ effect,
25
+ type Signal,
26
+ signal,
27
+ untracked,
28
+ } from '@preact/signals-core'
29
+ import {
30
+ aliasOf,
31
+ awake,
32
+ type Change,
33
+ comps,
34
+ type Dep,
35
+ type Ent,
36
+ type EntCore,
37
+ idOf,
38
+ type Pinned,
39
+ settled,
40
+ shortHex,
41
+ type Snapshot,
42
+ statusOf,
43
+ vocab,
44
+ } from './types.js'
45
+ import { moves, natureOf, typeOf } from './edge.js'
46
+ import type { Row } from './client.ts'
47
+ import { sessionQueries } from './sessions.js'
48
+ import {
49
+ distinctValues,
50
+ EXISTS,
51
+ type Field,
52
+ fieldsOf,
53
+ matchQuery,
54
+ namesLazy,
55
+ NEAR,
56
+ NEVER,
57
+ operandOf,
58
+ ORDER,
59
+ parseQuery,
60
+ type Pred,
61
+ PROJECT,
62
+ resolveRefs,
63
+ scopedSessions,
64
+ TEXT,
65
+ WANT,
66
+ windowOf,
67
+ } from './query.js'
68
+ import { warm } from './warmth.js'
69
+ import {
70
+ anchor,
71
+ children,
72
+ emptyIndex,
73
+ indexAll,
74
+ reindex,
75
+ reindexEdge,
76
+ } from './index.js'
77
+ import { type MemoryResolver, memoryResolver } from './resolver.js'
78
+ import { type LiveClient, liveClient, quiet } from './live_client.js'
79
+ import { said } from '@yaks/client/named'
80
+ import { OUTDATED, outlived, running } from '@yaks/web/outlived'
81
+ import type { Socket } from 'jsr:@yaks/sync@0.2.36'
82
+ import { type Clock, system } from '@yaks/fp'
83
+ import type { Bundle, Entity } from 'jsr:@yaks/graph@0.2.36'
84
+ import { normalizeChanges } from './props.js'
85
+ import { forgetLegacy } from './idb.js'
86
+ import { scopedOutbox } from './outbox.js'
87
+ import { legacyOutbox } from './legacy_outbox.js'
88
+ import { bundlesOf, changesOf, yakLine } from './wire.js'
89
+ import { diff, gaps } from './subs.js'
90
+ import { dead } from '@yaks/graph/bundle'
91
+ import { Refused } from '@yaks/graph/errors'
92
+ import { IDEMPOTENCY, PERSON_OUTBOX } from '@yaks/api/headers'
93
+ import { decisionWrite, deliverAnswer } from './decision_sync.js'
94
+ import { failure } from './failure.js'
95
+
96
+ // A cache row: the spine plus whichever components the entity carries.
97
+ // Derived from EntCore so a new component (types.ts) threads through here —
98
+ // and through ent() below — with zero edits. Exported so idb.ts persists
99
+ // and hydrates the exact shape the signal holds (T-6823). Omit over the CLOSED
100
+ // core keeps every known comp precise (an index signature on Ent would collapse
101
+ // keyof and lose them); the same open index signature is intersected back on so
102
+ // a plugin's comp reaches the cache as `unknown` (D-18663 seam 2, T-12765).
103
+ export type Comps =
104
+ & { entity?: Entity }
105
+ & Omit<EntCore, 'eid' | 'num' | 'prefix' | 'kind' | 'refs' | 'kids'>
106
+ & { [comp: string]: Record<string, unknown> | undefined }
107
+
108
+ // THE client cache — and it is PARTIAL (T-21491, step 4 of D-21486): the
109
+ // working-set boot seed, plus every row a mounted subscription streams in
110
+ // (defining subs, open-card reverse subs, the per-client singleton sub), plus
111
+ // rows want() fetched on demand. Last release moves a row into the bounded
112
+ // retention floor; an authoritative drop removes it. Every reader carries:
113
+ // ABSENCE NEVER MEANS NON-EXISTENCE — a row not here may simply not be held;
114
+ // ask the query door (queryEids — server-answered) or want() it, never infer
115
+ // "doesn't exist" from a miss. It exists because a mounted view must paint
116
+ // from memory at frame rate; it is a speed layer, not the graph.
117
+ export let cache = signal<Record<string, Comps>>({})
118
+ // Compatibility render snapshot: component references from the package RAM,
119
+ // never an independently retained payload owner. onRows is its only writer.
120
+ let liveGraph = cache.peek()
121
+ let setCache = (next: Record<string, Comps>) => {
122
+ liveGraph = next
123
+ cache.value = next
124
+ }
125
+ let paint = computed(() => cache.value)
126
+ let cached = (eid: string) => {
127
+ ensureClient().box.cache.touch([eid])
128
+ return cache.peek()[eid]
129
+ }
130
+ let componentViews = new WeakMap<object, Record<string, unknown>>()
131
+ let componentView = (comp: Record<string, unknown>) => {
132
+ if (!Object.values(comp).includes(null)) return comp
133
+ let view = componentViews.get(comp)
134
+ if (!view) {
135
+ view = new Proxy(comp, {
136
+ get: (target, key) => Reflect.get(target, key) ?? undefined,
137
+ ownKeys: (target) =>
138
+ Reflect.ownKeys(target).filter((k) => Reflect.get(target, k) !== null),
139
+ })
140
+ componentViews.set(comp, view)
141
+ }
142
+ return view
143
+ }
144
+ // The tab's clock: its replica's reconnects and paces, and the checks it
145
+ // defers. A test hands it one of its own.
146
+ let time: Clock = system
147
+ export let useClock = (clock: Clock): Clock => {
148
+ let prev = time
149
+ time = clock
150
+ return prev
151
+ }
152
+ let replica: LiveClient | undefined
153
+ let replacing = false
154
+ let makeClient = () => {
155
+ let outbox = typeof location !== 'undefined' && config.host
156
+ ? scopedOutbox({
157
+ endpoint: new URL(hosting().apply, base()).href,
158
+ storage: hosting().storage,
159
+ owner: () => authenticatedOwner(),
160
+ // Hosted unscoped queues have no trustworthy account provenance. Leave
161
+ // them untouched; the box is single-owner, hosted mounts name accounts.
162
+ legacy: legacyOutboxName()
163
+ ? legacyOutbox(legacyOutboxName()!)
164
+ : undefined,
165
+ former: formerOutboxScope(base()),
166
+ reconcile: clearStoredRefusal,
167
+ })
168
+ : undefined
169
+ return liveClient({
170
+ url: config.host ? base() : 'http://replica.invalid',
171
+ fetch: async (request) => {
172
+ await outbox?.assertOwner()
173
+ let bundles = await request.clone().json() as Bundle[]
174
+ let send = async (next: Request) => {
175
+ // Recheck before reading or restoring on a second request. The
176
+ // account may have changed while the answer was in flight.
177
+ if (next !== request) await outbox?.assertOwner()
178
+ let frame = next.method == 'POST'
179
+ ? {
180
+ apply: changesOf(
181
+ next === request ? bundles : await next.clone().json(),
182
+ ),
183
+ request: next,
184
+ }
185
+ : { request: next }
186
+ try {
187
+ let response = await route(frame, uuid())
188
+ if (!(response instanceof Response)) {
189
+ throw new Error('write returned no response')
190
+ }
191
+ return response
192
+ } catch (error) {
193
+ if (
194
+ !(error instanceof TypeError &&
195
+ /fetch|network|load/i.test(error.message))
196
+ ) {
197
+ console.error(`live client — write not sent: ${error}`, error)
198
+ }
199
+ throw error
200
+ }
201
+ }
202
+ let answer = decisionWrite(bundles)
203
+ let key = request.headers.get(IDEMPOTENCY)
204
+ return answer
205
+ ? deliverAnswer(request, answer, send, !!key && !!outbox?.settled(key))
206
+ : send(request)
207
+ },
208
+ connect: (url) => socketFor(url),
209
+ timer: (fn, ms) => void time.after(ms, fn),
210
+ // A refusal on a page that outlived a deploy is its old code asking the
211
+ // new server what it no longer answers: the page reloads onto the code
212
+ // now served. A read of an id that names nothing (one in the address, or a
213
+ // link) is refused for it, and the page draws the Lost face. A line the
214
+ // person typed is refused for their input, and the page shows why. On a
215
+ // page running what is served, any other refusal is a bug. So is a frame
216
+ // the page's own graph refuses, unless the page outlived a deploy: its
217
+ // vocabulary is then the old one, which can refuse a row the new
218
+ // vocabulary names (a new identity property), and it reloads too. The
219
+ // server refuses the socket of a page whose bundle is older than the one
220
+ // it serves (@yaks/web routes.ts `filter`), so such a page reloads before
221
+ // it hears a row it would refuse. A page reloads once: one that still
222
+ // meets it moments after reloading reports it.
223
+ report: (r) => {
224
+ // Delivery refusals are reported with their durable id where the
225
+ // ledger surfaces them, including those replayed without a caller.
226
+ if (r.sent.length && r.refused) return
227
+ if (r.refused?.error == OUTDATED.name) return reload(r)
228
+ if (r.error instanceof Refused) {
229
+ void outlived().then((old) => old ? reload(r) : said(r))
230
+ return
231
+ }
232
+ if (!r.refused) return said(r)
233
+ if (r.names?.length && r.names.every((n) => typed.has(n))) return
234
+ void unnamed(r.names).then(async (lost) => {
235
+ if (lost) return
236
+ if (await outlived()) reload(r)
237
+ else said(r)
238
+ })
239
+ },
240
+ disk: typeof location !== 'undefined',
241
+ outbox,
242
+ frame: (subs, f, reset) => {
243
+ if (replacing) return
244
+ let changes = changesOf(f.bundles ?? [])
245
+ // An aggregate answers whole, every time: a count under the empty key.
246
+ let agg = f.count != null ? { '': f.count } : f.tally ??
247
+ (f.distinct && Object.fromEntries(f.distinct.map((v) => [v, 1])))
248
+ batch(() => {
249
+ for (let sub of subs) {
250
+ landSubFrame({
251
+ sub,
252
+ replace: reset || !!agg,
253
+ changes,
254
+ drop: f.gone,
255
+ error: f.refused?.message,
256
+ ...agg ? { agg } : {},
257
+ })
258
+ }
259
+ })
260
+ },
261
+ ready: (sub) => {
262
+ let client = replica
263
+ if (replacing || !client) return
264
+ let ids = client.members(sub)
265
+ let s = [...queryUses.values()].find((s) => s.sub === sub)
266
+ if (s && (config.host || client.ready(sub) || ids.length)) {
267
+ let old = s.ids.peek()
268
+ if (ids.length !== old.length || ids.some((e, i) => e !== old[i])) {
269
+ s.ids.value = ids
270
+ }
271
+ s.live = client.ready(sub)
272
+ }
273
+ let agg = aggSets.get(sub)
274
+ if (agg) agg.live.value = client.ready(sub)
275
+ // A line another name already holds answers with no frame of its own.
276
+ if (client.ready(sub)) answered(sub)
277
+ ticked(sub)
278
+ },
279
+ changed: (eids) => {
280
+ let client = replica
281
+ if (replacing || !client) return
282
+ let changes: Change[] = []
283
+ let deaths = new Set<string>()
284
+ for (let eid of eids) {
285
+ let before = cache.peek()[eid]
286
+ let after = client.box.ent(eid)
287
+ if (!after || dead(after)) {
288
+ changes.push({ eid, name: 'entity', comp: null })
289
+ if (after && dead(after)) deaths.add(eid)
290
+ // A retained body may now be genuinely unloaded (LRU/epoch), unlike
291
+ // a successful read of an absent column. Let the next paint ask again.
292
+ for (let key of asked) {
293
+ if (key.startsWith(`${eid}\0`)) asked.delete(key)
294
+ }
295
+ } else {
296
+ for (let name of Object.keys(before ?? {})) {
297
+ if (!(name in after)) {
298
+ changes.push({ eid, name, comp: null })
299
+ }
300
+ }
301
+ for (let [name, raw] of Object.entries(after)) {
302
+ let comp = raw && componentView(raw as Record<string, unknown>)
303
+ if (
304
+ comp &&
305
+ (!before?.[name] ||
306
+ !sameProps(before[name]!, comp as Record<string, unknown>))
307
+ ) {
308
+ changes.push({
309
+ eid,
310
+ name,
311
+ comp: comp as Record<string, unknown>,
312
+ })
313
+ }
314
+ }
315
+ }
316
+ }
317
+ publishLocal(changes, new Set(eids), deaths)
318
+ },
319
+ })
320
+ }
321
+ // Tests/hosts may replace cache wholesale. Import that explicitly rather than
322
+ // leaving a second writable store beside RAM. Production never takes this arm.
323
+ let ensureClient = (): LiveClient => {
324
+ if (replica && cache.peek() === liveGraph) return replica
325
+ let rows = cache.peek()
326
+ replacing = true
327
+ stopPending?.()
328
+ stopAway?.()
329
+ away.value = false
330
+ replica?.box.close()
331
+ let client = makeClient()
332
+ replica = client
333
+ stopPending = client.box.wire?.onPending(() => syncOutbox(client))
334
+ stopAway = client.box.wire?.onConnection((open) => (away.value = !open))
335
+ syncOutbox(client)
336
+ liveGraph = rows
337
+ let changes = Object.entries(rows).flatMap(([eid, row]) =>
338
+ Object.entries(row).map(([name, comp]) => ({
339
+ eid,
340
+ name,
341
+ comp: comp
342
+ ? Object.fromEntries(
343
+ Object.entries(comp).filter(([p]) =>
344
+ p === 'eid' || client.box.vocab.props(name).includes(p)
345
+ ),
346
+ )
347
+ : null,
348
+ }))
349
+ )
350
+ if (changes.length) client.patch(changes)
351
+ replacing = false
352
+ for (let s of queryUses.values()) {
353
+ s.live = false
354
+ s.ids.value = config.host ? [] : mem.resolve(s.preds)
355
+ }
356
+ return client
357
+ }
358
+ export let deps = signal<Dep[]>([])
359
+ export let problem = signal('')
360
+ let pinZs = new Map<string, Signal<number>>()
361
+ let rowSignals = new Map<string, Signal<Comps | undefined>>()
362
+ let relationSignals = new Map<string, Signal<Dep[]>>()
363
+ let childSignals = new Map<string, Signal<Dep[]>>()
364
+ export let census = signal<string[]>([])
365
+ export let revealed = signal<Set<string>>(new Set())
366
+ export let reveal = (eid: string) => {
367
+ revealed.value = new Set([...revealed.peek(), eid])
368
+ }
369
+ export let shown = (eid: string) =>
370
+ !row(eid).value?.quarantined || revealed.value.has(eid)
371
+ let noRelations: Dep[] = []
372
+
373
+ // Human ids are a hot lookup vocabulary, not a query. Keep them beside the
374
+ // cache so rendering one reference never scans or subscribes to the graph.
375
+ let idGraph = paint.peek()
376
+ let numEids = new Map<number, Set<string>>() // by number, every series
377
+ let aliasEids = new Map<string, string>()
378
+ let shortEids = new Map<string, Set<string>>()
379
+ // The cache's derived indexes (index.ts) — the reverse `{eid}` views, by-
380
+ // component-presence, and edge endpoints, all flowing from the `comps`
381
+ // vocabulary. Maintained incrementally by applyLocal/evict below; the query
382
+ // layer (queryEids) anchors on it. A wholesale cache/deps replacement (tests,
383
+ // host integrations) is healed lazily: ixGraph/ixDeps mark the last-indexed
384
+ // refs, so a mismatch rebuilds once rather than per patch.
385
+ let ix = emptyIndex()
386
+ let ixGraph = paint.peek()
387
+ let ixDeps = deps.peek()
388
+ let syncIx = () => {
389
+ if (ixGraph != paint.peek() || ixDeps != deps.peek()) {
390
+ indexAll(ix, paint.peek(), deps.peek())
391
+ ixGraph = paint.peek()
392
+ ixDeps = deps.peek()
393
+ }
394
+ }
395
+
396
+ // A reverse hop's Kids accessor over the live index: heal it, read the children
397
+ // (index.ts `children`), resolve each to a bag through `get` — `paint.value` to
398
+ // stay reactive inside a render, `paint.peek()` off it. One helper so every
399
+ // matcher call site answers `.comments…` the same way.
400
+ let kidsVia =
401
+ (get: (eid: string) => Comps | undefined) =>
402
+ (eid: string, comp: string, prop: string) => {
403
+ syncIx()
404
+ return children(ix, eid, comp, prop).map((k) => get(k))
405
+ }
406
+
407
+ // The reactive query layer — the store-agnostic door for "which entities match
408
+ // this query". The mechanics live behind the Resolver seam (resolver.ts): a
409
+ // query is a value (Pred[], the query.ts grammar boards and graph_query already
410
+ // speak), resolved to a NARROW signal of matching eids. `mem` is the in-memory
411
+ // realization: it reads the cache through the store below — its initial fill
412
+ // anchors on the derived index (index.ts — O(result), never O(graph)), and
413
+ // `refresh` re-tests ONLY the eids each patch touched, so an unrelated patch
414
+ // never wakes a subscriber. Never `Object.values(paint.value).filter` in a
415
+ // render: that scans the whole graph AND subscribes to every patch (T-17036,
416
+ // the 16ms frame budget).
417
+ let makeResolver = (): MemoryResolver =>
418
+ memoryResolver({
419
+ read: (eid) => paint.peek()[eid],
420
+ keys: () => Object.keys(paint.peek()),
421
+ // Heal the derived index before narrowing — the same guard querySet held.
422
+ anchor: (preds) => {
423
+ syncIx()
424
+ return anchor(ix, preds)
425
+ },
426
+ // A reverse hop's children, read off the same derived index the anchor uses —
427
+ // the reverse map IS the EXISTS engine (index.ts). Healed first, then each
428
+ // child eid resolved to its cache bag for the sub-filter.
429
+ kids: (eid, comp, prop) => kidsVia((k) => paint.peek()[k])(eid, comp, prop),
430
+ })
431
+ let mem = makeResolver()
432
+
433
+ let seeding = false
434
+ let refreshQueries = (eids: Set<string>) => mem.refresh(eids)
435
+ let resetQueries = () => {
436
+ resetServerSets()
437
+ mem.reset()
438
+ }
439
+
440
+ // A held query rides a genuine SERVER subscription (T-17126): the cache is
441
+ // partial (T-21491), so a local scan silently under-reports — a MEMBERSHIP
442
+ // query a mounted view holds (useHold, `q:<canonical line>`) has the server
443
+ // maintain the complete set forward-and-reverse (evalFast/matchQuery, scoped
444
+ // SQL) and stream it, and landSub keeps a per-sub signal queryEids returns.
445
+ // `mem` primes the signal synchronously (no first-paint flash) and answers
446
+ // where nothing holds the query. The subs are what stream rows in, and
447
+ // eviction on release is what keeps the cache bounded.
448
+ //
449
+ // A PROJECTED query rides a server sub like any other (D-22567 §3): the line
450
+ // carries its `.fields=`, so the server ships only those columns and only
451
+ // re-fires on them. What a projection additionally needs — a waking projected
452
+ // field's move re-firing the LIST, not just the member's own row — this set
453
+ // carries below, mirroring the resolver's own `wake`/`vals` pair, because
454
+ // membership alone cannot express "the boxes moved".
455
+ type ServerSet = {
456
+ n: number
457
+ ids: Signal<string[]>
458
+ sub: string
459
+ preds: Pred[]
460
+ // The projection's WAKING columns (`.fields=…` minus the `~`-volatile ones),
461
+ // and per member a signature of their values. Empty for a plain membership
462
+ // query, so the whole mechanism costs nothing there.
463
+ wake: Field[]
464
+ vals: Map<string, string>
465
+ // Whether the server has EVER answered this sub. Until it has, the local
466
+ // resolver owns the signal (re-primed on read, refreshed on local writes);
467
+ // from the first landSub frame on, the server's answer is authoritative.
468
+ live: boolean
469
+ line: string
470
+ }
471
+ let queryUses = new Map<string, ServerSet>() // canonical preds key -> set
472
+ let querySignals = new Map<string, Signal<string[]>>() // sub name -> its signal
473
+ // A query's identity is what it SELECTS, never how it was bound: bindClause
474
+ // stamps each pred with its column's `tag` (query.ts) to type the value test,
475
+ // and a pred built by hand in this file carries none. So the tag is dropped
476
+ // here — otherwise a hand-built shape never equals its own parsed spelling,
477
+ // the round-trip below refuses every one of them, and the same filter under
478
+ // two bindings would open two server sets.
479
+ let qkey = (preds: Pred[]) =>
480
+ JSON.stringify(preds, (k, v) => {
481
+ if (k == 'tag') return undefined
482
+ if (v && typeof v == 'object' && 'comp' in v && 'op' in v && 'value' in v) {
483
+ let { tag: _tag, operand: _operand, ...plain } = v
484
+ let operand = operandOf(v)
485
+ return operand ? { ...plain, operand } : plain
486
+ }
487
+ return v
488
+ })
489
+
490
+ // Programmatic queries must round-trip through the Tasks grammar. The browser
491
+ // transports the result opaquely; FTS, semantic ranking and graph-wide walks
492
+ // must never be re-evaluated against a partial working set.
493
+ let quoteQuery = (value: string) =>
494
+ /[\s&"'\\]/.test(value) ? JSON.stringify(value) : value
495
+ let operandLine = (value: NonNullable<Pred['operand']>): string =>
496
+ value.kind == 'list'
497
+ ? value.items.map(operandLine).join(',')
498
+ : value.kind == 'range'
499
+ ? operandLine(value.lo) + (value.exclusiveEnd ? '...' : '..') +
500
+ operandLine(value.hi)
501
+ : /[,]|\.\./.test(value.raw)
502
+ ? JSON.stringify(value.raw)
503
+ : quoteQuery(value.raw)
504
+ let predLine = (p: Pred): string | undefined => {
505
+ let operand = operandOf(p)
506
+ let value = operand ? operandLine(operand) : quoteQuery(p.value)
507
+ let op = p.op === ''
508
+ ? '='
509
+ : p.op === '~'
510
+ ? '~='
511
+ : p.op === '!'
512
+ ? '!='
513
+ : p.op === EXISTS
514
+ ? ''
515
+ : ['<', '<=', '>', '>='].includes(p.op)
516
+ ? p.op
517
+ : undefined
518
+ if (p.op === TEXT) return value
519
+ if (p.refs) {
520
+ return p.op === EXISTS
521
+ ? '.refs'
522
+ : p.op === ''
523
+ ? value ? `.refs=${value}` : '!refs'
524
+ : undefined
525
+ }
526
+ if (p.win) {
527
+ return p.win.limit != null
528
+ ? `.limit=${p.win.limit}`
529
+ : p.win.after != null
530
+ ? `.after=${p.win.after}`
531
+ : undefined
532
+ }
533
+ if (p.fields) {
534
+ return p.op !== PROJECT
535
+ ? undefined
536
+ : p.fields.length
537
+ ? `.fields=${
538
+ p.fields.map((f) =>
539
+ [f, ...f.at ?? []].map((h) => h.prop ? `${h.comp}.${h.prop}` : h.comp)
540
+ .join('.') +
541
+ (f.wake ? '' : '~')
542
+ ).join(',')
543
+ }`
544
+ : '.fields=entity.eid'
545
+ }
546
+ if (p.agg) {
547
+ return p.agg === 'count' ? '.count' : `.${p.agg}=${p.comp}.${p.prop}`
548
+ }
549
+ if (p.reach) {
550
+ let r = p.reach
551
+ return `.${r.type}${
552
+ r.depth == null ? '' : `[<=${r.depth}]`
553
+ }${r.dir}${value}`
554
+ }
555
+ if (p.rev) {
556
+ let r = p.rev
557
+ let assoc = r.name
558
+ if (r.count) return op ? `.${assoc}${op}${value}` : undefined
559
+ if (!r.preds.length) return r.not ? `!${assoc}` : `.${assoc}`
560
+ // A simple reverse path has one leaf. Compound/grouped predicates require
561
+ // their original source line rather than a guessed alternate spelling.
562
+ if (r.preds.length !== 1) return undefined
563
+ let inner = predLine(r.preds[0])
564
+ return inner?.startsWith('.')
565
+ ? `.${assoc}${r.not ? '!' : ''}${inner}`
566
+ : undefined
567
+ }
568
+ if (p.op === ORDER || p.op === NEAR) return `.${p.op}=${value}`
569
+ if (p.op === WANT) return `?${p.comp}`
570
+ if (op == undefined) return undefined
571
+ let path = [p, ...p.at ?? []].map((h) =>
572
+ [h.comp, h.prop].filter(Boolean).join('.')
573
+ ).join('.')
574
+ if (!path) return undefined
575
+ // Presence and absence are prefixes: `.path` and `!path`.
576
+ if (p.op === EXISTS) return `.${path}`
577
+ return p.op === '' && !value ? `!${path}` : `.${path}${op}${value}`
578
+ }
579
+ let spellQuery = (preds: Pred[], key?: string): string | undefined => {
580
+ if (!preds.length) return undefined
581
+ let parts = preds.map(predLine)
582
+ if (parts.some((s) => s === undefined)) return undefined
583
+ let line = parts.join('&')
584
+ try {
585
+ // Self-verify: the line must re-parse to the exact same preds, or it is not
586
+ // trusted on the wire — the server would maintain a DIFFERENT set.
587
+ if (qkey(resolveRefs(parseQuery(line), findEid)) == (key ?? qkey(preds))) {
588
+ return line
589
+ }
590
+ } catch { /* the caller must supply source or refuse this shape */ }
591
+ return undefined
592
+ }
593
+
594
+ export let predsToQuery = (preds: Pred[]): string | undefined =>
595
+ spellQuery(preds)
596
+
597
+ // The line a query rides, or nothing. Never queries are locally empty by
598
+ // definition; a shape the grammar cannot spell back has no sub to open.
599
+ let serverLine = (preds: Pred[], key: string): string | undefined =>
600
+ preds.some((p) => p.op === NEVER) ? undefined : spellQuery(preds, key)
601
+
602
+ // ...and having no line is a cache MISS, not an error. Over a partial cache the
603
+ // local resolver still answers, best-effort, but the answer is not the graph's:
604
+ // it is reported unready through the same door a loading subscription uses, so
605
+ // a view tells loading from absent and repaints when the rows land. Jeff,
606
+ // 2026-09-16, verbatim: "why would a cache be throwing if it can't resolve a
607
+ // value? isn't it typical for a cache to not resolve a value? how would the
608
+ // caller know not to seek the cache for certain queries?"
609
+ let unserved = (preds: Pred[]): boolean =>
610
+ !!config.host && preds.length > 0 && !preds.some((p) => p.op === NEVER)
611
+
612
+ // A LOCAL write must paint through a server-backed set immediately: between
613
+ // applyLocal and the sub's echo (or with the socket down — a test, an offline
614
+ // tab) the signal would hold a stale set and a just-made entity wouldn't
615
+ // appear. Re-test just the touched eids, the same row-local test mem.refresh
616
+ // runs; the sub's next frame replaces the whole set and stays authoritative.
617
+ // The wholesale half: after a seed/reset every server set re-resolves from the
618
+ // fresh cache (mem.resolve — the same priming a new set gets) and awaits the
619
+ // server's re-confirmation, the same as a newborn set.
620
+ let resetServerSets = () => {
621
+ for (let s of queryUses.values()) {
622
+ s.live = false
623
+ s.ids.value = config.host
624
+ ? replica?.members(s.sub) ?? []
625
+ : mem.resolve(s.preds)
626
+ seedWake(s, s.ids.peek())
627
+ }
628
+ }
629
+
630
+ // The value signature of one member's waking projected columns — what a re-fire
631
+ // compares against to tell a move (a pin's x/y/w/h) from a mute z-bump. The
632
+ // resolver's own `sig`, over the cache these sets read.
633
+ let wakeSig = (eid: string, fields: Field[]): string => {
634
+ let r = paint.peek()[eid]
635
+ return JSON.stringify(
636
+ fields.map((f) => f.prop ? r?.[f.comp]?.[f.prop] ?? null : !!r?.[f.comp]),
637
+ )
638
+ }
639
+ let seedWake = (s: ServerSet, ids: Iterable<string>) => {
640
+ if (!s.wake.length) return
641
+ s.vals.clear()
642
+ for (let e of ids) s.vals.set(e, wakeSig(e, s.wake))
643
+ }
644
+
645
+ let refreshServerSets = (eids: Set<string>) => {
646
+ if (!queryUses.size) return
647
+ for (let s of queryUses.values()) {
648
+ // A path's far rows need not be in this cache. Re-screening a server hit
649
+ // locally would drop it merely because its requested task is unloaded.
650
+ // Ranked/windowed sets likewise belong to the server, not a local scan.
651
+ if (!config.host && !s.live) {
652
+ let next = mem.resolve(s.preds)
653
+ let before = s.ids.peek()
654
+ if (
655
+ next.length !== before.length || next.some((e, i) => e !== before[i])
656
+ ) s.ids.value = next
657
+ continue
658
+ }
659
+ // Only server frames change membership. Sets without a waking projection
660
+ // have nothing to refresh when other rows land.
661
+ if (!s.wake.length) continue
662
+ let ids = s.ids.peek()
663
+ let members = new Set(ids)
664
+ // A waking projected field of a STANDING member moved. A volatile (`~`)
665
+ // column is absent from wake, so its value lands without waking the set.
666
+ let moved = false
667
+ for (let eid of eids) {
668
+ if (!members.has(eid)) continue
669
+ let now = wakeSig(eid, s.wake)
670
+ if (s.vals.get(eid) !== now) {
671
+ s.vals.set(eid, now)
672
+ moved = true
673
+ }
674
+ }
675
+ // Republish the same ordered members so the view re-reads their boxes.
676
+ if (moved) s.ids.value = [...ids]
677
+ }
678
+ }
679
+
680
+ // Open the server set for a query, for an owner. Every live query is owned by
681
+ // the mounted component that draws its rows (T-131877): a hook below holds it
682
+ // from mount to unmount, and nothing else in the page can open one. The signal
683
+ // is primed from mem so the first paint is populated, then landSub replaces it
684
+ // with the server's answer. Identical lines share one set, counted by owners;
685
+ // the last release closes it.
686
+ let openSet = (preds: Pred[], line: string, key: string): ServerSet => {
687
+ let client = ensureClient()
688
+ let found = queryUses.get(key)
689
+ if (!found) {
690
+ // `q:<canonical preds>` — the projection is IN the key, so the same filter
691
+ // under two projections is two subs, never one set answering both.
692
+ let sub = `q:${key}`
693
+ found = {
694
+ n: 0,
695
+ ids: signal<string[]>(config.host ? [] : mem.resolve(preds)),
696
+ sub,
697
+ preds,
698
+ line,
699
+ live: false,
700
+ wake: (fieldsOf(preds) ?? []).filter((f) => f.wake),
701
+ vals: new Map(),
702
+ }
703
+ queryUses.set(key, found)
704
+ querySignals.set(sub, found.ids)
705
+ seedWake(found, found.ids.peek())
706
+ if (
707
+ config.host || client.ready(sub) ||
708
+ client.members(sub).length
709
+ ) {
710
+ found.ids.value = client.members(sub)
711
+ }
712
+ ticked(sub)
713
+ }
714
+ // A replaced replica must own a retained query before it can answer it.
715
+ if (!client.has(found.sub)) ownBoard(found.sub, found.line)
716
+ return found
717
+ }
718
+
719
+ let lineOf = (preds: Pred[], key: string, source?: string) =>
720
+ source?.trim() || serverLine(preds, key)
721
+
722
+ // Read a query's result: the held server set when a mounted owner holds one,
723
+ // else the local resolver over the rows this tab holds. A read never opens a
724
+ // subscription; it wakes when an owner opens or closes the set.
725
+ export let queryEids = (preds: Pred[]): Signal<string[]> => {
726
+ let key = qkey(preds)
727
+ tick(`q:${key}`).value
728
+ let held = queryUses.get(key)
729
+ return held?.n ? held.ids : mem.subscribe(preds)
730
+ }
731
+ // Ref-count a query for an owner's lifetime; the last release drops the set
732
+ // so distinct queries don't accumulate.
733
+ let holdQuery = (preds: Pred[], source?: string): () => void => {
734
+ let key = qkey(preds)
735
+ let line = lineOf(preds, key, source)
736
+ if (!line) {
737
+ mem.hold(preds)
738
+ return () => mem.drop(preds)
739
+ }
740
+ let s = openSet(preds, line, key)
741
+ s.n++
742
+ ticked(s.sub)
743
+ return () => {
744
+ if (--s.n > 0) return
745
+ queryUses.delete(key)
746
+ querySignals.delete(s.sub)
747
+ dropBoard(s.sub)
748
+ }
749
+ }
750
+
751
+ // A query that is evaluated PER RENDERED ROW — a reverse-lookup keyed by the
752
+ // row's own eid (a tile's comment count on every entity in a list or tree) —
753
+ // must NEVER open a server sub: that scales with rows
754
+ // on screen, not views, and a page of them floods the socket (1363 subs / a
755
+ // stalled serial chain, measured — T-21283). These resolve LOCALLY
756
+ // over the working set the DEFINING subs (boards/projects/sessions/canvases)
757
+ // stream in — a tile badge is best-effort, and an OPEN card's own view keeps its
758
+ // bounded sub for the complete, correct list. `mem` always, never the server.
759
+ //
760
+ // mem is NOT a whole-graph resolver (T-21491): the cache it indexes is partial
761
+ // by construction, so an answer from here covers only held rows. A caller must
762
+ // either HOLD a sub that guarantees its rows are present (the client-singleton
763
+ // reads over the screen rows the app holds) or explicitly accept a best-effort
764
+ // working-set answer (a tile badge before its aggregate sub goes live).
765
+ // Anything needing the complete result is held (useHold) and read through
766
+ // queryEids — the server answers.
767
+ export let localEids = (preds: Pred[]): Signal<string[]> => mem.subscribe(preds)
768
+
769
+ // The reverse-reference reads phrased as the queries the vocabulary already
770
+ // answers: an eid EQUALITY anchors on the derived refs index (index.ts), a
771
+ // component PRESENCE on byComp, a CONTAINS over a text column's pool. Each helper
772
+ // builds the `Pred[]` the query layer caches per-shape, so a face reading one of
773
+ // the functions below (commentsOn, boardsOver, projects, …) wakes only when ITS
774
+ // result changes — never on an unrelated patch — with no bespoke per-relation set
775
+ // to maintain (T-17064, collapsing the reverse-index machinery into the one query
776
+ // door). Values are eids the caller already holds, so no ref-resolution pass is
777
+ // needed; equal shapes hit the same cached signal. This is the working-set seam
778
+ // too: when the boot serves a partial cache, queryEids resolves server-side and
779
+ // a reference outside the working set still counts (T-18094), where a cache scan
780
+ // would silently under-report.
781
+ let eq = (comp: string, prop: string, value: string): Pred => ({
782
+ comp,
783
+ prop,
784
+ op: '',
785
+ value,
786
+ })
787
+ let has = (comp: string): Pred => ({ comp, prop: '', op: EXISTS, value: '' })
788
+ let contains = (comp: string, prop: string, value: string): Pred => ({
789
+ comp,
790
+ prop,
791
+ op: '~',
792
+ value,
793
+ })
794
+ // The multi-column reverse-union (query.ts): every entity referencing `value`
795
+ // through SOME {eid} column — the backlinks of one eid, across every reference
796
+ // in the vocabulary at once. `value` is already an eid the caller holds, so no
797
+ // ref-resolution pass is needed.
798
+ let refsTo = (value: string): Pred => ({
799
+ comp: '',
800
+ prop: '',
801
+ op: '',
802
+ value,
803
+ refs: true,
804
+ })
805
+
806
+ let indexId = (eid: string, r?: Comps) => {
807
+ if (!r) return
808
+ let num = r.entity?.num
809
+ if (num) numEids.set(num, (numEids.get(num) ?? new Set()).add(eid))
810
+ let a = aliasOf(r)
811
+ if (a) aliasEids.set(a.name, a.eid)
812
+ let hex = eid.replaceAll('-', '').toLowerCase()
813
+ for (let n = 6; n <= Math.min(10, hex.length); n++) {
814
+ let key = hex.slice(0, n)
815
+ let hits = shortEids.get(key)
816
+ if (hits) hits.add(eid)
817
+ else shortEids.set(key, new Set([eid]))
818
+ }
819
+ }
820
+
821
+ let unindexId = (eid: string, r?: Comps) => {
822
+ if (!r) return
823
+ let num = r.entity?.num
824
+ let held = num ? numEids.get(num) : undefined
825
+ if (held?.delete(eid) && !held.size) numEids.delete(num!)
826
+ let a = aliasOf(r)
827
+ if (a && aliasEids.get(a.name) == a.eid) aliasEids.delete(a.name)
828
+ let hex = eid.replaceAll('-', '').toLowerCase()
829
+ for (let n = 6; n <= Math.min(10, hex.length); n++) {
830
+ let key = hex.slice(0, n)
831
+ let hits = shortEids.get(key)
832
+ if (!hits) continue
833
+ hits.delete(eid)
834
+ if (!hits.size) shortEids.delete(key)
835
+ }
836
+ }
837
+
838
+ let indexIds = (graph: Record<string, Comps>) => {
839
+ numEids.clear()
840
+ aliasEids.clear()
841
+ shortEids.clear()
842
+ for (let [eid, r] of Object.entries(graph)) indexId(eid, r)
843
+ idGraph = graph
844
+ }
845
+
846
+ // Tests and host integrations may replace the exported cache directly. The
847
+ // browser stays incremental; an outside replacement pays one rebuild.
848
+ let syncIds = () => {
849
+ let graph = paint.peek()
850
+ if (graph != idGraph) indexIds(graph)
851
+ }
852
+
853
+ // Renderers hold these narrow signals; the complete cache remains the
854
+ // persistence and query door. A signal is minted once per eid so a patch
855
+ // cannot wake an unrelated entity.
856
+ // An outside replacement of the cache (a test, a host) is the one write the
857
+ // row signals cannot see coming: the browser's own writes go through setCache
858
+ // and publish() the rows they moved. Nothing renders from the whole cache any
859
+ // more, so re-prime every held row signal when the graph object is swapped.
860
+ effect(() => {
861
+ let graph = cache.value
862
+ if (graph === liveGraph) return
863
+ // The raw graph, not cached(): the replica rebuild stays lazy, on the
864
+ // next read, so a replacement no one renders from costs no scan.
865
+ batch(() => {
866
+ for (let [eid, found] of rowSignals) found.value = graph[eid]
867
+ })
868
+ })
869
+
870
+ export let row = (eid: string) => {
871
+ let current = untracked(() => cached(eid))
872
+ let found = rowSignals.get(eid)
873
+ if (!found) {
874
+ rowSignals.set(eid, found = signal(current))
875
+ } else if (found.peek() !== current) found.value = current
876
+ return found
877
+ }
878
+
879
+ // Edges by endpoint come from the derived index (index.ts byParent/byChild),
880
+ // not a bespoke computed: the same `{eid}`-derived mechanism that indexes
881
+ // references indexes the edge triples, maintained incrementally rather than
882
+ // rebuilt per edge patch. syncIx heals a wholesale deps replacement.
883
+ export let relations = (eid: string) => {
884
+ syncIx()
885
+ let current = ix.byParent.get(eid) ?? noRelations
886
+ let found = relationSignals.get(eid)
887
+ if (!found) {
888
+ relationSignals.set(eid, found = signal(current))
889
+ } else if (found.peek() !== current) found.value = current
890
+ return found
891
+ }
892
+
893
+ let childRelations = (eid: string) => {
894
+ syncIx()
895
+ let current = ix.byChild.get(eid) ?? noRelations
896
+ let found = childSignals.get(eid)
897
+ if (!found) {
898
+ childSignals.set(eid, found = signal(current))
899
+ } else if (found.peek() !== current) found.value = current
900
+ return found
901
+ }
902
+
903
+ let publish = (
904
+ eids: Set<string>,
905
+ parentEids: Set<string>,
906
+ childEids: Set<string>,
907
+ ) =>
908
+ batch(() => {
909
+ for (let eid of eids) {
910
+ let found = rowSignals.get(eid)
911
+ if (found) found.value = paint.value[eid]
912
+ }
913
+ for (let eid of parentEids) {
914
+ let found = relationSignals.get(eid)
915
+ if (found) {
916
+ found.value = ix.byParent.get(eid) ?? noRelations
917
+ }
918
+ }
919
+ for (let eid of childEids) {
920
+ let found = childSignals.get(eid)
921
+ if (found) found.value = ix.byChild.get(eid) ?? noRelations
922
+ }
923
+ })
924
+
925
+ // Re-derive every narrow signal, id index, derived index and query set from the
926
+ // cache as it stands now — the one wholesale-replacement pass a seed runs
927
+ // (seedFrom below), and the seam a test that assigns `cache.value` directly uses
928
+ // to bring the query resolver in step with the graph it just planted.
929
+ export let resetSignals = () =>
930
+ batch(() => {
931
+ syncIds()
932
+ indexAll(ix, paint.peek(), deps.peek())
933
+ ixGraph = paint.peek()
934
+ ixDeps = deps.peek()
935
+ census.value = Object.keys(paint.value)
936
+ for (let [eid, found] of rowSignals) found.value = paint.value[eid]
937
+ for (let [eid, found] of relationSignals) {
938
+ found.value = ix.byParent.get(eid) ?? noRelations
939
+ }
940
+ for (let [eid, found] of childSignals) {
941
+ found.value = ix.byChild.get(eid) ?? noRelations
942
+ }
943
+ resetQueries()
944
+ clearResolved() // a reseed may now hold what the server-resolve sidecar named
945
+ })
946
+
947
+ // Tests start a new tab in the same runtime. Dispose the prior fixture's
948
+ // replica and forget its readers before planting another graph; a production
949
+ // seed keeps those readers and uses resetSignals instead.
950
+ export let clearForTest = () => {
951
+ replacing = true
952
+ try {
953
+ let client = replica
954
+ replica = undefined
955
+ client?.box.close()
956
+ } finally {
957
+ replacing = false
958
+ }
959
+ queryUses.clear()
960
+ querySignals.clear()
961
+ aggSets.clear()
962
+ commentTargets.clear()
963
+ pinZs.clear()
964
+ rowSignals.clear()
965
+ relationSignals.clear()
966
+ childSignals.clear()
967
+ subQueries.clear()
968
+ shadowSubs.clear()
969
+ subFailures.clear()
970
+ subFields.clear()
971
+ subWindows.clear()
972
+ subTicks.clear()
973
+ heldTicks.clear()
974
+ edgeHolders.clear()
975
+ boardUses.clear()
976
+ boardEntrySubs.clear()
977
+ entryUses.clear()
978
+ routeUses.clear()
979
+ rowsSub.clear()
980
+ oneShots.clear()
981
+ mem = makeResolver()
982
+ agreement = undefined
983
+ asked.clear()
984
+ queue.clear()
985
+ cache.value = {}
986
+ deps.value = heldDeps = []
987
+ liveGraph = cache.peek()
988
+ resetSignals()
989
+ }
990
+
991
+ /** Start a fresh test tab after disposing the preceding one. */
992
+ export let resetForTest = () => {
993
+ clearForTest()
994
+ ensureClient()
995
+ }
996
+
997
+ // A z-only pin patch binds straight to its one DOM attribute. The fallback
998
+ // seeds cards mounted after the patch without making this signal map a cache.
999
+ export let pinZ = (eid: string, fallback: number) => {
1000
+ let z = pinZs.get(eid)
1001
+ if (!z) pinZs.set(eid, z = signal(fallback))
1002
+ return z
1003
+ }
1004
+
1005
+ let sameProps = (
1006
+ a: Record<string, unknown>,
1007
+ b: Record<string, unknown>,
1008
+ ) => {
1009
+ let keys = Object.keys(a)
1010
+ return keys.length == Object.keys(b).length &&
1011
+ keys.every((k) => Object.is(a[k], b[k]))
1012
+ }
1013
+
1014
+ // Where the server lives. The browser answers from its location; other hosts
1015
+ // (the TUI) configure it before boot().
1016
+ let loc = (globalThis as { location?: { host: string; protocol?: string } })
1017
+ .location
1018
+ // The host a process starts with: a page's own, or NONE. A location-less
1019
+ // process names its server (the TUI, from TASKS_HOST) or has none. This used
1020
+ // to fall back to the dev port, which made every location-less process that
1021
+ // mounted a view — every test run — stream the owner's live graph into
1022
+ // `cache` and read it back as fixture data.
1023
+ export let hostFrom = (loc?: { host: string }) => loc?.host ?? ''
1024
+ export let config: {
1025
+ host: string
1026
+ secure: boolean
1027
+ // This tab's client eid, ridden on the /ws URL so its writes journal a
1028
+ // resolved actor (T-6669). The browser sets it (clientId); the TUI
1029
+ // leaves it unset — localStorage is a browser thing — and its writes
1030
+ // resolve to the box owner.
1031
+ client?: string
1032
+ // Stage-2 migration probes compare shadow sets to scans. Deployed clients
1033
+ // maintain the shadow without carrying agreement telemetry.
1034
+ agreement: boolean
1035
+ // Legacy probe flag, accepted for URL compatibility only. The package RAM
1036
+ // replica is always the live surface; no alternate IDB query/cache owner.
1037
+ store: boolean
1038
+ } = {
1039
+ host: hostFrom(loc),
1040
+ // Behind an https front door the page's scheme must carry through to
1041
+ // the socket and fetches — a hardcoded http:// is mixed content there.
1042
+ secure: loc?.protocol == 'https:',
1043
+ agreement: false,
1044
+ store: false,
1045
+ }
1046
+ export let agreementProbe = (search: string) =>
1047
+ queryAt(search).state.get('probe') == 'subscriptions'
1048
+ export let storeProbe = (search: string) =>
1049
+ queryAt(search).state.get('store') == 'idb'
1050
+ // THE server address — every socket and fetch in this module goes through it,
1051
+ // and there is no host to guess. Refuse, so a process that never named a
1052
+ // server says so instead of reaching one it was never pointed at.
1053
+ export let serverHost = () => {
1054
+ if (config.host) return config.host
1055
+ throw new Error('live: no server host — set config.host (TASKS_HOST)')
1056
+ }
1057
+ export let base = () =>
1058
+ `http${config.secure ? 's' : ''}://${serverHost()}${hosting().api}`
1059
+
1060
+ // The column sort, and the order `.order=filed.priority` asks the server
1061
+ // for, so a column's next page lands below the rows it already shows:
1062
+ // unprioritized first (a missing value sorts before every number in
1063
+ // @yaks/sql), then lower priority higher, and the newer num breaks a tie.
1064
+ export { settled, statuses, statusOf, uuid } from './types.js'
1065
+ import { kindOf, uuid } from './types.js'
1066
+ let priority = (e: Ent) => e.filed?.priority ?? -Infinity
1067
+ export let byPriority = (a: Ent, b: Ent) =>
1068
+ (priority(a) - priority(b)) || (b.num - a.num)
1069
+
1070
+ // An Ent's warmth — the cache-side face of query.ts warm(), for boards
1071
+ // that say .order=hot. The Ent flattens the spine, so re-nest what the
1072
+ // scorer reads (project/task ride along so retirement can sink it);
1073
+ // ties break to the newer num, like byPriority.
1074
+ export let warmth = (e: Ent, now: number) =>
1075
+ warm(
1076
+ {
1077
+ recall: e.recall as Record<string, unknown> | undefined,
1078
+ updated: e.updated as Record<string, unknown> | undefined,
1079
+ created: e.created as Record<string, unknown> | undefined,
1080
+ project: e.project as Record<string, unknown> | undefined,
1081
+ task: e.task as unknown as Record<string, unknown> | undefined,
1082
+ },
1083
+ now,
1084
+ (eid) => row(eid).value,
1085
+ )
1086
+ export let byWarmth = (now: number) => (a: Ent, b: Ent) =>
1087
+ (warmth(b, now) - warmth(a, now)) || (b.num - a.num)
1088
+
1089
+ // Gated = the red alarm on the Dot: this task is BLOCKED on something
1090
+ // external (D-17094), the `blocked` facet present. That is the only thing
1091
+ // that burns red now. Open `requires`/`contains` edges are NORMAL work —
1092
+ // decomposition and queuing — so they render as the calm deps tally (the
1093
+ // Meta line's "requires N"), never the alarm. A block is a fact stamped by
1094
+ // `task block`, orthogonal to status: a task is blocked AND open/wip.
1095
+ export let gated = (e: Ent) => e.blocked != null
1096
+
1097
+ // The calm deps affordance: how many `requires`/`contains` children are
1098
+ // still unsettled — the "N open deps" count that used to (wrongly) burn red.
1099
+ // A non-task child can't settle, so it counts as open. Zero renders nothing.
1100
+ export let openDeps = (e: Ent) => {
1101
+ let requires = e.refs.filter((r) => r.type == 'requires').map((r) =>
1102
+ ent(r.child)
1103
+ )
1104
+ return [...requires, ...e.kids].filter((c) =>
1105
+ !settled(statusOf(c as Record<string, unknown>))
1106
+ ).length
1107
+ }
1108
+
1109
+ // Who this viewer IS, for the verbs that are per-actor. A browser has no
1110
+ // session — its identity is the actor its client entity names — and a
1111
+ // viewer that names none holds no standing instructions, so the verbs
1112
+ // that need one simply aren't offered.
1113
+ export let myActor = () => {
1114
+ if (!capable('canvas')) return owner.value
1115
+ let c = config.client ? row(config.client).value : undefined
1116
+ return String(c?.client?.actor ?? '') || undefined
1117
+ }
1118
+
1119
+ // What this viewer has said about an entity: 'watch', 'mute', or nothing.
1120
+ // One subscription per (actor, target), so this is a reverse-ref lookup on
1121
+ // target (index.ts `children`), not a whole-cache scan. rows() screened out
1122
+ // quarantined rows — keep that screen so the answer is unchanged.
1123
+ export let myMode = (target: string) => {
1124
+ let me = myActor()
1125
+ if (!me) return undefined
1126
+ syncIx()
1127
+ let g = (eid: string) => row(eid).value
1128
+ let hit = children(ix, target, 'subscription', 'target').find((eid) =>
1129
+ !g(eid)?.quarantined && String(g(eid)?.subscription?.actor) == me
1130
+ )
1131
+ return hit
1132
+ ? (g(hit)?.subscription?.mode as 'watch' | 'mute' | undefined)
1133
+ : undefined
1134
+ }
1135
+
1136
+ // The sentence a cached edge entity says. An edge wears `edge{from, to}` and
1137
+ // exactly one nature tag, so the row IS the triple — this is how a client that
1138
+ // holds the entity answers for a sentence its unlink no longer names.
1139
+ let depOf = (row?: Comps): Dep | undefined => {
1140
+ let ends = row?.edge as { from?: string; to?: string } | undefined
1141
+ if (!ends?.from || !ends.to) return
1142
+ for (let name of Object.keys(row!)) {
1143
+ let type = typeOf(name)
1144
+ if (type) {
1145
+ return { parent: ends.from, type: type as Dep['type'], child: ends.to }
1146
+ }
1147
+ }
1148
+ }
1149
+
1150
+ // A live hand on the entity: its claim's session is awake — a managed
1151
+ // run still going, or an external door still open. The wip pip pulses
1152
+ // on this instead of sitting half-filled; a stale claim doesn't count.
1153
+ export let crewed = (e: Ent) => {
1154
+ let s = e.claim && ent(e.claim.session)
1155
+ return !!s?.session && awake(s)
1156
+ } // A cache peek, exposed for eyes (a CDP probe, the console) to verify what
1157
+ // the DOM does not show. Not load-bearing.
1158
+ ;(globalThis as { __peek?: (eid: string) => unknown }).__peek = (eid) =>
1159
+ paint.value[eid]
1160
+
1161
+ // Land a batch in the cache with the same patch semantics the db uses:
1162
+ // comps merge per-column, comp: null deletes the component, entity: null
1163
+ // deletes the entity and every edge touching it. Returns the eids and edges
1164
+ // it touched (an entity death touches the eid AND every edge it swept).
1165
+ // Package row observation publishes the compatibility signals; persistence
1166
+ // and retention belong to that same replica, never to this facade.
1167
+ export let applyLocal = (changes: Change[]) => {
1168
+ let client = ensureClient()
1169
+ let edges = moves(changes, (e) => depOf(cache.peek()[e])).map((m) => m.dep)
1170
+ for (let c of changes) {
1171
+ if (c.name === 'entity' && c.comp === null) {
1172
+ edges.push(
1173
+ ...deps.peek().filter((d) => d.parent === c.eid || d.child === c.eid),
1174
+ )
1175
+ }
1176
+ }
1177
+ batch(() => client.patch(changes))
1178
+ return { eids: [...new Set(changes.map((c) => c.eid))], edges }
1179
+ }
1180
+ let publishLocal = (
1181
+ changes: Change[],
1182
+ complete: Set<string>,
1183
+ deaths: Set<string>,
1184
+ ) => {
1185
+ syncIds()
1186
+ syncIx()
1187
+ let graph = paint.peek()
1188
+ let eids = new Set<string>()
1189
+ let edges: Dep[] = []
1190
+ let changedRows = new Set<string>()
1191
+ let changedParents = new Set<string>()
1192
+ let changedChildren = new Set<string>()
1193
+ let depsMoved = false
1194
+ let changedCensus = false
1195
+ let changed = false
1196
+ // Camera motion renders from camera.value + hear(), not the graph cache.
1197
+ // Keep its facade row current without publishing a whole-graph signal.
1198
+ let motion = ({ eid, name, comp }: Change) =>
1199
+ !!paint.value[eid]?.camera && comp != null &&
1200
+ (name == 'camera' || name == 'updated')
1201
+ // Stacking is its own live partition too: raising one card must repaint
1202
+ // pins, not every entity and board mounted around them.
1203
+ let stacking = ({ eid, name, comp }: Change) =>
1204
+ !!paint.value[eid]?.pin && comp != null &&
1205
+ (name == 'updated' ||
1206
+ (name == 'pin' && Object.keys(comp).every((p) => p == 'z')))
1207
+ let quiet = changes.length > 0 &&
1208
+ changes.every((c) => motion(c) || stacking(c))
1209
+ let next = quiet ? cache.value : { ...cache.value }
1210
+ let zs = new Map<string, number>()
1211
+ // An edge is an ENTITY, so its rows land through the ordinary loop below —
1212
+ // but the edge TABLE this client renders from is keyed by the sentence, so
1213
+ // read the sentences out first, while the cache still holds what an unlink
1214
+ // is about to take away. The stream itself is the holder.
1215
+ let said = moves(changes, (e) => depOf(graph[e]))
1216
+ for (let { eid, name, comp } of changes) {
1217
+ if (name == 'entity' && comp == null) {
1218
+ let before = next[eid]
1219
+ let lived = !!before
1220
+ eids.add(eid)
1221
+ if (lived) {
1222
+ delete next[eid]
1223
+ pinZs.delete(eid)
1224
+ changed = true
1225
+ changedCensus = true
1226
+ changedRows.add(eid)
1227
+ }
1228
+ // Only an authoritative tombstone cascades. Storage-only eviction of a
1229
+ // peer's payload says nothing about independently held edge sentences.
1230
+ for (let d of deaths.has(eid) ? edgesAt(eid) : []) {
1231
+ edges.push(d)
1232
+ reindexEdge(ix, d, true)
1233
+ changedParents.add(d.parent)
1234
+ changedChildren.add(d.child)
1235
+ depsMoved = true
1236
+ }
1237
+ continue
1238
+ }
1239
+ eids.add(eid)
1240
+ let before = next[eid] as Record<string, unknown> | undefined
1241
+ if (comp == null) {
1242
+ if (!before || !(name in before)) continue
1243
+ let row = { ...before }
1244
+ delete row[name]
1245
+ next[eid] = row as Comps
1246
+ changed = true
1247
+ changedRows.add(eid)
1248
+ continue
1249
+ }
1250
+ let prior = before?.[name] as Record<string, unknown> | undefined
1251
+ // Full confirmations replace retained component values, not just their
1252
+ // present columns: a column removed while unheld must not survive a merge.
1253
+ let after = complete?.has(eid) ? comp : { ...prior, ...comp }
1254
+ if (prior && sameProps(prior, after)) continue
1255
+ next[eid] = { ...before, [name]: after } as Comps
1256
+ if (!before) changedCensus = true
1257
+ if (name == 'pin' && after.z != null) zs.set(eid, Number(after.z))
1258
+ changed = true
1259
+ changedRows.add(eid)
1260
+ }
1261
+ if (changed && !quiet) {
1262
+ batch(() => {
1263
+ setCache(next)
1264
+ })
1265
+ // During a wholesale (re)seed the resetSignals() that follows in seedFrom
1266
+ // rebuilds the id-index and derived index in ONE pass (syncIds + indexAll)
1267
+ // and refreshes every partition — so the per-row maintenance and the batch
1268
+ // below are pure redundancy at seed, the dominant boot CPU (D-18055). Fill
1269
+ // the cache only; leaving idGraph/ixGraph stale makes resetSignals' single
1270
+ // build the one pass. Steady-state patches (!seeding) stay incremental.
1271
+ if (!seeding) {
1272
+ for (let eid of changedRows) {
1273
+ unindexId(eid, graph[eid])
1274
+ indexId(eid, next[eid])
1275
+ reindex(ix, eid, graph[eid], next[eid])
1276
+ }
1277
+ idGraph = paint.peek()
1278
+ }
1279
+ }
1280
+ for (let { dep, gone } of said) {
1281
+ edges.push(dep)
1282
+ let moved = gone
1283
+ ? holdEdges(LIVE_EDGES, [], [dep])
1284
+ : holdEdges(LIVE_EDGES, [dep], [])
1285
+ for (let x of [...moved.gained, ...moved.lost]) {
1286
+ reindexEdge(ix, x, gone)
1287
+ changedParents.add(x.parent)
1288
+ changedChildren.add(x.child)
1289
+ depsMoved = true
1290
+ }
1291
+ }
1292
+ if (depsMoved) {
1293
+ deps.value = heldDeps = [...edgeHolders.values()].map((h) => h.dep)
1294
+ }
1295
+ if (quiet) {
1296
+ for (let eid of eids) paint.peek()[eid] = next[eid]
1297
+ }
1298
+ if (seeding) return { eids: [...eids], edges }
1299
+ ixGraph = paint.peek()
1300
+ ixDeps = deps.peek()
1301
+ batch(() => {
1302
+ if (changedCensus) census.value = Object.keys(paint.peek())
1303
+ publish(changedRows, changedParents, changedChildren)
1304
+ refreshQueries(changedRows)
1305
+ refreshServerSets(changedRows)
1306
+ for (let [eid, z] of zs) {
1307
+ let live = pinZs.get(eid)
1308
+ if (live) live.value = z
1309
+ }
1310
+ })
1311
+ // The touched keys feed the disk checkpoint after every landing.
1312
+ return { eids: [...eids], edges }
1313
+ }
1314
+
1315
+ // Whether the host composed a plugin: `capable('spawn')` is @yaks/spawn.
1316
+ export let capable = (name: string) =>
1317
+ vocab.docs.some((d) => d.label == `@yaks/${name}`)
1318
+
1319
+ // Consumers that care about canonical live edits subscribe here.
1320
+ let listeners = new Set<(changes: Change[]) => void>()
1321
+ export let hear = (fn: (changes: Change[]) => void) => {
1322
+ listeners.add(fn)
1323
+ return () => listeners.delete(fn)
1324
+ }
1325
+ let tell = (changes: Change[]) => {
1326
+ for (let fn of listeners) fn(changes)
1327
+ }
1328
+
1329
+ // Bodies ride only on the payloads that ask for them (a `.fields=` projection
1330
+ // leaves them behind), and a patch that names no body leaves none either — so
1331
+ // a cached component can lack its body while the stored column holds one. An
1332
+ // ABSENT body means UNLOADED, never empty: nothing may render it as content or
1333
+ // arm an editor over it, because a commit would write a fragment over the
1334
+ // stored body. want() is the other end: the requested body column lands as an
1335
+ // ordinary patch through applyLocal and merges onto the cached component —
1336
+ // exactly what a live body edit does.
1337
+ //
1338
+ // One trip per PAINT, not per element: a card and all its comments ask
1339
+ // within the same render, so the queue drains on the next turn and they
1340
+ // travel together.
1341
+ let asked = new Set<string>()
1342
+ let queue = new Map<string, Set<string>>()
1343
+ let sweep = () => {
1344
+ let wants = [...queue]
1345
+ queue.clear()
1346
+ for (let [eid, fields] of wants) {
1347
+ let keys = [...fields].map((field) => `${eid}\0${field}`)
1348
+ for (let key of keys) asked.add(key)
1349
+ let projection = [...fields].join(',')
1350
+ oneShot(
1351
+ projection == 'doc.body' ? `want:${eid}` : `want:${eid}:${projection}`,
1352
+ `id=${eid}&.fields=${projection}`,
1353
+ () => {},
1354
+ () => {
1355
+ for (let key of keys) asked.delete(key)
1356
+ },
1357
+ )
1358
+ }
1359
+ }
1360
+ export let want = (eid: string, comp = 'doc', prop = 'body') => {
1361
+ let field = `${comp}.${prop}`
1362
+ let key = `${eid}\0${field}`
1363
+ // Mark even a successful absent field: it must not trigger a render/fetch
1364
+ // loop. Row eviction/epoch invalidation clears markers in onRows above.
1365
+ if (asked.has(key)) return
1366
+ if (queue.get(eid)?.has(field)) return
1367
+ if (!queue.size) setTimeout(sweep)
1368
+ let fields = queue.get(eid) ?? new Set<string>()
1369
+ queue.set(eid, fields.add(field))
1370
+ }
1371
+
1372
+ // Whether a view is still waiting on this entity's body (or another held-back
1373
+ // property) — and ASKING is what fetches it, so no placeholder outlives one
1374
+ // round trip. Fused for the same reason step() folds its bookkeeping into the
1375
+ // verb: a caller that could paint the placeholder without asking would paint
1376
+ // it forever.
1377
+ export let pending = (e: Ent, comp = 'doc', prop = 'body') => {
1378
+ let held = e[comp] as Record<string, unknown> | undefined
1379
+ if (!held || held[prop] !== undefined) return false
1380
+ want(e.eid, comp, prop)
1381
+ return true
1382
+ }
1383
+
1384
+ // Delivery belongs to the shared client: browse only projects its queue for
1385
+ // the standing sync indicator. Neither rendering nor reconnect sends a retry.
1386
+ let stopPending: (() => void) | undefined
1387
+ let stopAway: (() => void) | undefined
1388
+ // Whether the page lost its server and is reconnecting, from the socket's
1389
+ // drop until it opens again: the sync indicator says so.
1390
+ export let away = signal(false)
1391
+ export let unsent = () => outboxWrites.peek().map((w) => w.id)
1392
+ export let outboxWrites = signal<
1393
+ { id: string; since: number; count: number }[]
1394
+ >([])
1395
+ export let pendingDecisions = signal<ReadonlySet<string>>(new Set())
1396
+ let firstSeen = new Map<string, number>()
1397
+ let syncOutbox = (client = ensureClient()) => {
1398
+ let writes = client.box.wire?.pending() ?? []
1399
+ let keys = new Set(writes.map((w) => w.key))
1400
+ for (let id of firstSeen.keys()) if (!keys.has(id)) firstSeen.delete(id)
1401
+ let pending = writes.filter((w) => w.state === 'pending')
1402
+ let decisions = new Set(pending.flatMap((w) => {
1403
+ let answer = decisionWrite(w.sent)
1404
+ return answer ? [answer.eid] : []
1405
+ }))
1406
+ let prior = pendingDecisions.peek()
1407
+ if (
1408
+ decisions.size != prior.size || [...decisions].some((id) => !prior.has(id))
1409
+ ) {
1410
+ pendingDecisions.value = decisions
1411
+ }
1412
+ outboxWrites.value = pending.map((w) => {
1413
+ if (!firstSeen.has(w.key)) firstSeen.set(w.key, time.now())
1414
+ return {
1415
+ id: w.key,
1416
+ since: firstSeen.get(w.key)!,
1417
+ count: changesOf(w.sent).length,
1418
+ }
1419
+ })
1420
+ for (let w of writes) {
1421
+ if (w.state !== 'refused') continue
1422
+ refuse(
1423
+ w.key,
1424
+ w.refusal?.message ?? 'Write refused',
1425
+ changesOf(w.sent),
1426
+ w.refusal?.name,
1427
+ )
1428
+ }
1429
+ }
1430
+
1431
+ // The refusal ledger (T-21441, M-16612): a write the server REJECTED (a moved
1432
+ // precondition, a lease it can't hold) is durable and returnable. The user saw
1433
+ // it land in the optimistic cache, and a reload wipes the in-memory
1434
+ // `problem`; a refusal must not vanish with it. Each
1435
+ // is kept under the write's own delivery id — its stable identity — so it
1436
+ // survives the reload and surfaces again at boot for seven days unless the user
1437
+ // dismisses it. It names what failed (the batch), why (the server's reason), and
1438
+ // that success would have been the write reaching the server. localStorage backs
1439
+ // it by default; the TUI and the tests swap an in-memory double.
1440
+ export type Refusal = {
1441
+ id: string
1442
+ reason: string
1443
+ at: number
1444
+ summary: string
1445
+ name?: string
1446
+ }
1447
+ type RefusalStore = {
1448
+ record: (r: Refusal) => void
1449
+ clear: (id: string) => void
1450
+ all: () => Refusal[]
1451
+ }
1452
+ let LEDGER = 'tasks-refused'
1453
+ const REFUSAL_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000
1454
+ let readLedger = (): Refusal[] => {
1455
+ try {
1456
+ let rs: Refusal[] = JSON.parse(
1457
+ globalThis.localStorage?.getItem(storageKey(LEDGER)) ?? '[]',
1458
+ )
1459
+ let cutoff = time.now() - REFUSAL_MAX_AGE_MS
1460
+ return rs.filter((r) => r.at >= cutoff)
1461
+ } catch {
1462
+ return []
1463
+ }
1464
+ }
1465
+ let writeLedger = (rs: Refusal[]) => {
1466
+ try {
1467
+ globalThis.localStorage?.setItem(storageKey(LEDGER), JSON.stringify(rs))
1468
+ } catch { /* no storage — the in-memory signal still shows this session's */ }
1469
+ }
1470
+ let refusalStore: RefusalStore = {
1471
+ record: (r) =>
1472
+ writeLedger([...readLedger().filter((x) => x.id != r.id), r].slice(-50)),
1473
+ clear: (id) => writeLedger(readLedger().filter((x) => x.id != id)),
1474
+ all: () => readLedger(),
1475
+ }
1476
+ export let useRefusalStore = (s: RefusalStore): RefusalStore => {
1477
+ let prev = refusalStore
1478
+ refusalStore = s
1479
+ return prev
1480
+ }
1481
+ export let refused = signal<Refusal[]>([])
1482
+ let syncRefused = () => (refused.value = refusalStore.all())
1483
+
1484
+ // One line naming a refused batch: how many changes, which components, which
1485
+ // entities — enough for the user to know which edit the server threw away.
1486
+ let summarize = (changes: Change[]): string => {
1487
+ if (!changes.length) return ''
1488
+ let names = [...new Set(changes.map((c) => c.name))].join(', ')
1489
+ let ids = [...new Set(changes.map((c) => idOf(ent(c.eid))))].join(', ')
1490
+ let n = `${changes.length} change${changes.length > 1 ? 's' : ''}`
1491
+ return `${n}${names ? ` (${names})` : ''}${ids ? ` to ${ids}` : ''}`
1492
+ }
1493
+
1494
+ // Record a refusal durably and surface it now, under the delivery id the
1495
+ // outbox already keys, so a refused write reads the same after a reload.
1496
+ export let refuse = (
1497
+ id: string,
1498
+ reason: string,
1499
+ changes: Change[] = [],
1500
+ name = 'Refused',
1501
+ ) => {
1502
+ if (
1503
+ refused.peek().some((r) =>
1504
+ r.id == id && r.name == name && r.reason == reason
1505
+ )
1506
+ ) return
1507
+ refusalStore.record({
1508
+ id,
1509
+ reason,
1510
+ name,
1511
+ at: time.now(),
1512
+ summary: summarize(changes),
1513
+ })
1514
+ syncRefused()
1515
+ problem.value = reason
1516
+ failure(Object.assign(new Error(reason), { name }), 'web sync', {
1517
+ write: id,
1518
+ refusal: name,
1519
+ components: [...new Set(changes.map((c) => c.name))].join(','),
1520
+ entities: [...new Set(changes.map((c) => c.eid))].join(','),
1521
+ })
1522
+ }
1523
+ let clearStoredRefusal = (id: string) => {
1524
+ let said = refusalStore.all().find((r) => r.id == id)?.reason
1525
+ if (!said) return
1526
+ refusalStore.clear(id)
1527
+ syncRefused()
1528
+ if (problem.peek() == said) problem.value = ''
1529
+ }
1530
+ // Dismissed, a refusal takes the message it raised with it.
1531
+ export let clearRefusal = (id: string) => {
1532
+ void replica?.box.wire?.forget(id)
1533
+ clearStoredRefusal(id)
1534
+ }
1535
+ // Surface at boot what a prior life left refused — the post-reload half of the
1536
+ // durability guarantee.
1537
+ export let loadRefusals = () => syncRefused()
1538
+
1539
+ // Historical callers may ask for a replay; construction of the shared client
1540
+ // already loads and replays its durable queue, and notifies onPending on load.
1541
+ export let replayOutbox = () => {
1542
+ syncOutbox()
1543
+ return Promise.resolve()
1544
+ }
1545
+ let deliver = (changes: Change[]) => {
1546
+ void apply(bundlesOf(changes)).then(() => tell(changes), () => {})
1547
+ }
1548
+
1549
+ /** Optimistic visibility through the shared client, with its server receipt
1550
+ * or a refusal/unknown outcome. Drafts retain their own recovery copy. A write
1551
+ * whose outcome is unknown (the server away) is no problem to show: the
1552
+ * outbox keeps and resends it, and the sync indicator says it waits. */
1553
+ export let apply = (bundles: Bundle[]): Promise<Bundle[]> => {
1554
+ problem.value = ''
1555
+ if (!bundles.length) return Promise.resolve([])
1556
+ let result: Promise<Bundle[]>
1557
+ try {
1558
+ result = Promise.resolve(
1559
+ ensureClient().box.mutate(
1560
+ bundles,
1561
+ decisionWrite(bundles) ? { key: PERSON_OUTBOX + uuid() } : undefined,
1562
+ ),
1563
+ )
1564
+ } catch (error) {
1565
+ result = Promise.reject(error)
1566
+ }
1567
+ return result.catch((error) => {
1568
+ let outcome = (error as { outcome?: string })?.outcome
1569
+ if (outcome != 'unknown') {
1570
+ problem.value = error instanceof Error ? error.message : String(error)
1571
+ if (outcome != 'refused') {
1572
+ failure(error, 'web sync', {
1573
+ components: [...new Set(changesOf(bundles).map((c) => c.name))].join(
1574
+ ',',
1575
+ ),
1576
+ entities: [...new Set(bundles.map((b) => b.entity.eid))].join(','),
1577
+ })
1578
+ }
1579
+ }
1580
+ throw error
1581
+ })
1582
+ }
1583
+
1584
+ /** A held write: nothing shows until the server takes it, so it may name
1585
+ * what it makes by `$alias` and the answer says each eid. A refusal is the
1586
+ * caller's to show, where it belongs, so it stays out of the ledger. */
1587
+ export let submit = async (bundles: Bundle[]): Promise<Bundle[]> => {
1588
+ let key = `outbox:${uuid()}`
1589
+ try {
1590
+ return await ensureClient().box.mutate(bundles, {
1591
+ optimistic: false,
1592
+ key,
1593
+ })
1594
+ } catch (error) {
1595
+ clearRefusal(key)
1596
+ throw error
1597
+ }
1598
+ }
1599
+
1600
+ // Land a local edit: cache first (instant render), then the acked wire.
1601
+ export let mutate = (...changes: Change[]) => {
1602
+ problem.value = ''
1603
+ let parsed = normalizeChanges(changes, { resolve: findEid })
1604
+ if (!parsed.length) return
1605
+ deliver(parsed)
1606
+ }
1607
+
1608
+ type Catchup = { catchup: Change[]; cursor: number }
1609
+ type Reset = { reset?: boolean; snapshot: Snapshot; error?: string }
1610
+ export type Sub = {
1611
+ sub: string
1612
+ changes?: Change[]
1613
+ drop?: string[]
1614
+ replace?: boolean
1615
+ cursor?: number
1616
+ shadow?: boolean
1617
+ // An aggregate frame (T-21283): a value→count map instead of members. The
1618
+ // initial frame replaces the whole tally; later frames are deltas (n=0
1619
+ // drops the key). No row changes ride these, so the cache is untouched.
1620
+ agg?: Record<string, number>
1621
+ // The frame's stated WINDOW (D-22567 §4): the members are the newest `limit`
1622
+ // of `total` matches. Present exactly when the answer is a PREFIX, so its
1623
+ // ABSENCE on an unwindowed sub is itself the statement that the set is whole.
1624
+ // `total` is absent when no index could vouch for one (a declining filter).
1625
+ window?: { limit: number; total?: number }
1626
+ // The PROJECTION the server answered under (D-22567 §3), stated on the
1627
+ // replace frame: the columns these rows carry, and by omission the ones they
1628
+ // do NOT. Absent means full components. `loaded()` reads it.
1629
+ fields?: Field[]
1630
+ // The archetype descriptors this frame's rows wear that the socket had not
1631
+ // shipped before (T-37445); learned before the rows render.
1632
+ archetypes?: Change[]
1633
+ // An addressed read refusal. `reference` is stable enough to correlate the
1634
+ // visible failure with server read telemetry without marking the entity.
1635
+ error?: string
1636
+ reference?: string
1637
+ }
1638
+ // How a replica reaches its host: the page's /ws. A process with no host (a
1639
+ // test) has a socket that sends through the route seam and hears nothing: its
1640
+ // frames arrive through landSub.
1641
+ let socketFor = (url: string): Socket =>
1642
+ config.host ? new WebSocket(running(url)) as unknown as Socket : {
1643
+ ...quiet(),
1644
+ send: (text: string) => route(JSON.parse(text)),
1645
+ }
1646
+ export let useSocket = (fn: typeof socketFor): typeof socketFor => {
1647
+ let prev = socketFor
1648
+ socketFor = fn
1649
+ return prev
1650
+ }
1651
+
1652
+ // Put a batch the host answered back into the rows it touched: the host's
1653
+ // rows replace this side's, and a row the host does not have leaves.
1654
+ // The write seam: a test counts deliveries without a host. Returns the prior
1655
+ // route so the test can restore it.
1656
+ // The body is sent as text: `new Request(url, request)` carries a body over as
1657
+ // a stream, and Safari refuses to upload a ReadableStream.
1658
+ let defaultRoute = (frame: unknown, _id?: string): void | Promise<Response> => {
1659
+ let request = (frame as { request?: Request }).request
1660
+ if (request) {
1661
+ if (request.method == 'GET') return fetch(request)
1662
+ return request.clone().text().then((body) =>
1663
+ fetch(
1664
+ new Request(new URL(hosting().apply, base()), {
1665
+ method: request.method,
1666
+ headers: request.headers,
1667
+ body,
1668
+ }),
1669
+ )
1670
+ )
1671
+ }
1672
+ }
1673
+ let route: (frame: unknown, id?: string) => unknown = defaultRoute
1674
+ export let useRoute = (fn: typeof route): typeof route => {
1675
+ let prev = route
1676
+ route = fn
1677
+ return prev
1678
+ }
1679
+ // THE change-batch door — every write leaves through the outbox, so no caller
1680
+ // can fire and forget.
1681
+ export let send = (...changes: unknown[]) => deliver(changes as Change[])
1682
+
1683
+ // Query subscriptions (T-3683), the client half. The cache becomes a UNION of
1684
+ // subscription result sets: `subMembers` refcounts which eids each sub holds,
1685
+ // so an eid released by EVERY subscription becomes retained, not live. A
1686
+ // server-side removal instead drops it. A legacy client never subscribes, so
1687
+ // this map stays empty and nothing is ever evicted. A shadow sub tracks the set
1688
+ // without eviction while the complete stream remains the cache owner.
1689
+ let subQueries = new Map<string, string>()
1690
+ let shadowSubs = new Set<string>()
1691
+ let primeSub = (sub: string, q: string) => {
1692
+ let client = ensureClient()
1693
+ subQueries.set(sub, q)
1694
+ client.open(sub, yakLine(q))
1695
+ }
1696
+ // One version signal PER SUB (T-37445): a frame for sub A wakes only the
1697
+ // readers of A. One global version woke every subscription-holding view on
1698
+ // every frame, so a zero-row tally answer re-rendered the whole page.
1699
+ let subTicks = new Map<string, Signal<number>>()
1700
+ let tick = (sub: string) => {
1701
+ let found = subTicks.get(sub)
1702
+ if (!found) subTicks.set(sub, found = signal(0))
1703
+ return found
1704
+ }
1705
+ let ticked = (sub: string) => {
1706
+ let found = subTicks.get(sub)
1707
+ if (found) found.value = found.peek() + 1
1708
+ }
1709
+ // The same per ROW, for what the subs say about it: `loaded()` asks which
1710
+ // subs hold an eid and under what projection, so it wakes when a frame
1711
+ // carries that eid, not when any frame lands.
1712
+ let heldTicks = new Map<string, Signal<number>>()
1713
+ let holders = (eid: string) => {
1714
+ let found = heldTicks.get(eid)
1715
+ if (!found) heldTicks.set(eid, found = signal(0))
1716
+ return found
1717
+ }
1718
+ let heldMoved = (eids: Iterable<string>) => {
1719
+ for (let eid of eids) {
1720
+ let found = heldTicks.get(eid)
1721
+ if (found) found.value = found.peek() + 1
1722
+ }
1723
+ }
1724
+
1725
+ // What each sub's frames SAID about its bounds. A window is the server telling
1726
+ // a view "you hold the newest `limit` of `total`", so a face can say what it is
1727
+ // showing of what (M-16612) instead of quietly passing a page off as the set.
1728
+ // Absent = unbounded, which is the only thing an unwindowed sub ever says.
1729
+ export type Window = { limit: number; total?: number }
1730
+ let subWindows = new Map<string, Window>()
1731
+ export let subWindow = (sub: string): Window | undefined => {
1732
+ tick(sub).value
1733
+ return subWindows.get(sub)
1734
+ }
1735
+
1736
+ // What each PROJECTED sub declared it carries (D-22567 §3) — recorded from the
1737
+ // server's own statement on the reply, so the client believes the frame rather
1738
+ // than re-deriving the contract. A sub absent here streams FULL components.
1739
+ let subFields = new Map<string, Field[]>()
1740
+
1741
+ // Is this column actually LOADED — or is the cache holding a row whose
1742
+ // projection never named it? This is the cache's partiality contract one level
1743
+ // down: at the ENTITY level absence never means non-existence, and at the COLUMN
1744
+ // level absence never means null. A projected sub streams only its declared
1745
+ // columns, so `e.session.final_text` reading undefined under a `.fields=` sub
1746
+ // means UNLOADED — the same word a deferred body gets — and a
1747
+ // render that needs it subscribes for more (a fuller projection, or the
1748
+ // card/route sub that loads an entity whole).
1749
+ //
1750
+ // It answers off the SUBS, never a per-row mark: the same shape evict()'s own
1751
+ // `held` uses one level up, and it needs no maintenance on the patch path. The
1752
+ // bias is deliberate — an unprojected sub, or a row no projected sub holds (the
1753
+ // working-set seed, a want() fetch), is FULL and says true; anything else says
1754
+ // false. Erring toward "unloaded" costs a needless re-subscribe; erring the
1755
+ // other way is the masquerade this exists to prevent.
1756
+ export let loaded = (eid: string, comp: string, prop: string): boolean => {
1757
+ holders(eid).value
1758
+ row(eid).value
1759
+ let client = ensureClient()
1760
+ if (client.box.cache.loaded(eid, comp, prop)) return true
1761
+ // The location-less whole-graph host has no remote readiness contract. A
1762
+ // projected subscription still must not promote its omissions to known.
1763
+ if (!config.host && cached(eid)) {
1764
+ return ![...subFields].some(([sub]) => client.members(sub).includes(eid))
1765
+ }
1766
+ return false
1767
+ }
1768
+
1769
+ // Edges are HELD (T-22371): `edgeHolders` refcounts a triple across what holds
1770
+ // it, and `deps`, the client's whole edge table, is exactly the union. An edge
1771
+ // is an entity, so it arrives as an ordinary row, and the holders are the two
1772
+ // below.
1773
+ let edgeHolders = new Map<string, { dep: Dep; subs: Set<string> }>()
1774
+ let edgeKey = (d: Dep) => `${d.parent}\0${d.type}\0${d.child}`
1775
+
1776
+ // Two holders that are not subscriptions. LIVE_EDGES is the complete broadcast
1777
+ // itself — a shadow client (TUI, tests) still hears every edge write and
1778
+ // nothing else keeps those edges. SEED_EDGES is a legacy whole-graph snapshot's
1779
+ // `deps`, held forever because nothing ever hands them back.
1780
+ let LIVE_EDGES = '\0live'
1781
+ let SEED_EDGES = '\0seed'
1782
+
1783
+ // A wholesale `deps` replacement from OUTSIDE this table — a test that plants a
1784
+ // graph, a seed — is healed the way syncIx heals the derived index: `heldDeps`
1785
+ // marks the array the holder table last published, so an assignment nobody here
1786
+ // made re-derives the holders from it once, rather than leaving the table and
1787
+ // the signal quietly disagreeing about what the client holds.
1788
+ let heldDeps: Dep[] = deps.peek()
1789
+ let syncHolders = () => {
1790
+ let now = deps.peek()
1791
+ if (now === heldDeps) return
1792
+ edgeHolders.clear()
1793
+ for (let d of now) {
1794
+ edgeHolders.set(edgeKey(d), { dep: d, subs: new Set([SEED_EDGES]) })
1795
+ }
1796
+ heldDeps = now
1797
+ }
1798
+
1799
+ let release = (sub: string, key: string, lost: Dep[]) => {
1800
+ let h = edgeHolders.get(key)
1801
+ if (!h) return
1802
+ h.subs.delete(sub)
1803
+ if (h.subs.size) return
1804
+ edgeHolders.delete(key)
1805
+ lost.push(h.dep)
1806
+ }
1807
+
1808
+ // One holder's edge delta, folded into the shared table. Answers with the
1809
+ // triples whose HOLDING moved — the ones the union gained or lost — so the
1810
+ // caller reindexes and republishes exactly those endpoints, never the table.
1811
+ let holdEdges = (sub: string, add: Dep[], cut: Dep[]) => {
1812
+ syncHolders()
1813
+ let gained: Dep[] = []
1814
+ let lost: Dep[] = []
1815
+ for (let d of add) {
1816
+ let k = edgeKey(d)
1817
+ let h = edgeHolders.get(k)
1818
+ if (!h) {
1819
+ edgeHolders.set(k, h = { dep: d, subs: new Set() })
1820
+ gained.push(d)
1821
+ }
1822
+ h.subs.add(sub)
1823
+ }
1824
+ for (let d of cut) release(sub, edgeKey(d), lost)
1825
+ return { gained, lost }
1826
+ }
1827
+
1828
+ // An entity's death takes its edges from EVERY holder: the rows are gone from
1829
+ // the graph, so no subscription can still be said to hold them.
1830
+ let edgesAt = (eid: string): Dep[] => {
1831
+ syncHolders()
1832
+ let lost: Dep[] = []
1833
+ for (let [k, h] of [...edgeHolders]) {
1834
+ if (h.dep.parent != eid && h.dep.child != eid) continue
1835
+ edgeHolders.delete(k)
1836
+ lost.push(h.dep)
1837
+ }
1838
+ return lost
1839
+ }
1840
+
1841
+ // A subscription frame: land its changes like any batch (adds + updates flow
1842
+ // through the unchanged applyLocal), then track membership. A death rides in
1843
+ // `changes` as an entity-null (gone for everyone — applyLocal already removed
1844
+ // it); a `drop` eid left THIS query but still exists (gone for this query
1845
+ // only). Either way it leaves the sub's set, and an eid now in no set is
1846
+ // evicted from the cache. A control reply replaces the prior set wholesale;
1847
+ // maintenance frames patch it.
1848
+ let implicitQuery = (sub: string) => {
1849
+ if (sub.startsWith('entries:')) return `.entry.session=${sub.slice(8)}`
1850
+ if (sub.startsWith('route:')) {
1851
+ return routeLine(...sub.slice(6).split(':') as [string, string?])
1852
+ }
1853
+ if (sub.startsWith('rows:')) return `id=${sub.slice(5)}`
1854
+ if (sub.startsWith('q:')) {
1855
+ try {
1856
+ return predsToQuery(JSON.parse(sub.slice(2))) ?? `remote:${sub}`
1857
+ } catch { /* addressed host fixture */ }
1858
+ }
1859
+ return `remote:${sub}`
1860
+ }
1861
+ export let landSub = (f: Sub) =>
1862
+ batch(() => {
1863
+ let client = ensureClient()
1864
+ // A frame may land for a sub this side never opened (a test's server).
1865
+ if (!client.has(f.sub)) {
1866
+ let q = subQueries.get(f.sub)
1867
+ // An in-flight frame after final release must not create a new owner.
1868
+ if (!q && config.host) return
1869
+ client.open(f.sub, yakLine(q ?? implicitQuery(f.sub)))
1870
+ }
1871
+ client.receive(f)
1872
+ })
1873
+ let landSubFrame = (f: Sub & { changes: Change[] }) => {
1874
+ if (f.error) {
1875
+ answered(f.sub, true)
1876
+ subFailures.set(f.sub, {
1877
+ reason: f.error,
1878
+ reference: f.reference ?? f.sub,
1879
+ })
1880
+ // The failed replacement is NOT an authoritative empty answer. Preserve
1881
+ // any prior membership for cache ownership, but publish the failure so a
1882
+ // first read cannot remain silently undefined and an old read cannot pose
1883
+ // as current. Only a later successful replacement clears this state.
1884
+ ticked(f.sub)
1885
+ return
1886
+ }
1887
+ if (f.replace) subFailures.delete(f.sub)
1888
+ // An aggregate frame lands in its tally signal and nowhere else — it carries
1889
+ // no rows, so the cache, member sets and eviction all stay out of it.
1890
+ if (f.agg) {
1891
+ let s = aggSets.get(f.sub)
1892
+ if (s) {
1893
+ if (f.replace) {
1894
+ s.map.value = { ...f.agg }
1895
+ s.live.value = true
1896
+ } else {
1897
+ let next = { ...s.map.peek() }
1898
+ for (let [v, n] of Object.entries(f.agg)) {
1899
+ n > 0 ? next[v] = n : delete next[v]
1900
+ }
1901
+ s.map.value = next
1902
+ }
1903
+ }
1904
+ return
1905
+ }
1906
+ // A window rides any frame that has one to state; a REPLACE with none is the
1907
+ // server saying this answer is whole, which must clear a bound left by the
1908
+ // query this frame replaced.
1909
+ if (f.window) subWindows.set(f.sub, f.window)
1910
+ else if (f.replace) subWindows.delete(f.sub)
1911
+ // The projection is recorded BEFORE the rows land, so the cache is never
1912
+ // briefly holding projected columns while `loaded` still calls the row full.
1913
+ // The server states it on every replace; a maintenance frame inherits what
1914
+ // the sub was opened under.
1915
+ if (f.replace) {
1916
+ f.fields ? subFields.set(f.sub, f.fields) : subFields.delete(f.sub)
1917
+ }
1918
+ let set = [...queryUses.values()].find((s) => s.sub === f.sub)
1919
+ if (set) {
1920
+ let client = ensureClient()
1921
+ set.live = client.ready(f.sub)
1922
+ seedWake(set, client.members(f.sub))
1923
+ }
1924
+ ticked(f.sub)
1925
+ heldMoved([...f.changes.map((c) => c.eid), ...f.drop ?? []])
1926
+ if (f.replace) answered(f.sub)
1927
+ }
1928
+
1929
+ // A control frame is an OBJECT (design §1), distinct from the array batches
1930
+ // send() ships — a subscribe/replace or an unsubscribe.
1931
+ let subscribe = (sub: string, q: string) => {
1932
+ primeSub(sub, q)
1933
+ }
1934
+
1935
+ // A transient projection still uses the subscription protocol: one initial
1936
+ // replace lands through the normal cache seam, then the hold is returned. This
1937
+ // is how a deferred body (and other one-shot browser reads) avoids inventing a
1938
+ // fetch-only endpoint. It waits for its answer however long the server takes:
1939
+ // @yaks/sync resends the line after a reconnect, and a deadline here would only
1940
+ // close the line before a slow answer arrived, and so lose it. `fail` is the
1941
+ // server refusing the read.
1942
+ let oneShots = new Map<string, { done: () => void; fail: () => void }>()
1943
+ export let oneShot = (
1944
+ sub: string,
1945
+ q: string,
1946
+ done: () => void,
1947
+ fail: () => void,
1948
+ ) => {
1949
+ oneShots.set(sub, { done, fail })
1950
+ subscribe(sub, q)
1951
+ }
1952
+ // A one-shot's answer, or its refusal: the caller hears it, then the line
1953
+ // closes.
1954
+ let answered = (sub: string, refused = false) => {
1955
+ let one = oneShots.get(sub)
1956
+ if (!one) return
1957
+ oneShots.delete(sub)
1958
+ queueMicrotask(() => {
1959
+ refused ? one.fail() : one.done()
1960
+ unsubscribe(sub)
1961
+ })
1962
+ }
1963
+ let forget = (sub: string) => {
1964
+ let members = replica?.members(sub) ?? []
1965
+ replica?.close(sub)
1966
+ subQueries.delete(sub)
1967
+ shadowSubs.delete(sub)
1968
+ subWindows.delete(sub)
1969
+ subFields.delete(sub)
1970
+ agreement?.checked.delete(sub)
1971
+ ticked(sub)
1972
+ heldMoved(members)
1973
+ }
1974
+ // Close a line: what a released hold does, and how a test forgets a frame its
1975
+ // fake server landed. Closing never opens, so it needs no owner.
1976
+ export let unsubscribe = (sub: string) => forget(sub)
1977
+ export let subEids = (sub: string): Set<string> | undefined => {
1978
+ tick(sub).value
1979
+ return replica?.ready(sub) ? new Set(replica.members(sub)) : undefined
1980
+ }
1981
+
1982
+ type Agreement = {
1983
+ checked: Map<string, string>
1984
+ counts: { agreements: number; divergences: number; annotated: number }
1985
+ }
1986
+ let agreement: Agreement | undefined
1987
+ export let subscriptionChecks = () =>
1988
+ agreement ? { ...agreement.counts } : undefined
1989
+
1990
+ // Compare after adjacent full/sub frames have both had a turn. The scan stays
1991
+ // the caller's render source; this is only a diagnostic and probe counter.
1992
+ export let assertAgree = (
1993
+ sub: string,
1994
+ q: string,
1995
+ scan: Iterable<string>,
1996
+ members: Iterable<string>,
1997
+ ) => {
1998
+ if (!config.agreement) return
1999
+ let state = agreement ??= {
2000
+ checked: new Map(),
2001
+ counts: { agreements: 0, divergences: 0, annotated: 0 },
2002
+ }
2003
+ let expected = [...new Set(scan)].sort()
2004
+ let received = [...new Set(members)].sort()
2005
+ let signature = JSON.stringify([q, expected, received])
2006
+ if (state.checked.get(sub) == signature) return
2007
+ state.checked.set(sub, signature)
2008
+ time.after(20, () => {
2009
+ if (
2010
+ boardUses.get(sub)?.q != q || state.checked.get(sub) != signature
2011
+ ) return
2012
+ state.counts.agreements++
2013
+ let d = diff(expected, received)
2014
+ if (!d.scanOnly.length && !d.subOnly.length) return
2015
+ state.counts.divergences++
2016
+ let unsupported = gaps(parseQuery(q))
2017
+ let note = {
2018
+ sub,
2019
+ query: q,
2020
+ scanOnly: d.scanOnly,
2021
+ subOnly: d.subOnly,
2022
+ unsupported,
2023
+ }
2024
+ if (unsupported.length) {
2025
+ state.counts.annotated++
2026
+ console.warn('subscription agreement deferred —', note)
2027
+ } else {
2028
+ console.assert(false, 'subscription divergence', note)
2029
+ }
2030
+ })
2031
+ }
2032
+
2033
+ let boardUses = new Map<string, { n: number; q: string }>()
2034
+ let entryUses = new Map<string, number>()
2035
+ let subFailures = new Map<
2036
+ string,
2037
+ { reason: string; reference: string }
2038
+ >()
2039
+ // A board whose query NAMES the lazy partition (`.entry.session=S-3`) can't be
2040
+ // answered from the root cache — entries are omitted from the snapshot. So the
2041
+ // board holds an entry subscription per scoped session (the same door a Session
2042
+ // view opens), which streams those entries into the cache so boardScan's query
2043
+ // door resolves them. Keyed by board sub → session eid → its unsubscribe. A
2044
+ // cross-session lazy board (no `.entry.session=`, e.g. a `.generation.provider`
2045
+ // board) has no single session to subscribe and stays unrenderable in the
2046
+ // cache; the server query door answers it, board rendering waits on server-
2047
+ // paged membership.
2048
+ let boardEntrySubs = new Map<string, Map<string, () => void>>()
2049
+
2050
+ let ownBoard = (sub: string, q: string) => primeSub(sub, q)
2051
+ let dropBoard = (sub: string) => unsubscribe(sub)
2052
+
2053
+ // A fullscreen board opens a WINDOW over its membership, not the whole of it
2054
+ // (D-22567 §4). A board is a saved query, and the Everything board's `.task`
2055
+ // is ~24k rows — 4.7 MB onto one socket so a view can paint a page. The exact
2056
+ // per-status numbers still come from the tally sub beside it (T-22509), so the
2057
+ // face can say what it is showing of what rather than passing a page off as the
2058
+ // set. A query that names its OWN window keeps it; a bad query is left alone,
2059
+ // since the server refuses it and padding it would only change the error.
2060
+ export let BOARD_WINDOW = 400
2061
+ export let boardLine = (q: string): string => {
2062
+ if (!q.trim()) return q
2063
+ try {
2064
+ if (windowOf(parseQuery(q)).limit != null) return q
2065
+ } catch {
2066
+ return q
2067
+ }
2068
+ return `${q}&.limit=${BOARD_WINDOW}`
2069
+ }
2070
+
2071
+ // The window a board's member sub is holding, or undefined while it holds the
2072
+ // whole set — what a face reads to say "400 of 1248".
2073
+ export let boardWindow = (e: Ent): Window | undefined =>
2074
+ subWindow(`board:${e.eid}`)
2075
+
2076
+ // Several views in one tab share one ownership entry.
2077
+ let boardSub = (e: Ent) => {
2078
+ let sub = `board:${e.eid}`
2079
+ let q = boardLine(String(e.board?.query ?? ''))
2080
+ let use = boardUses.get(sub)
2081
+ if (use) use.n++
2082
+ else {
2083
+ boardUses.set(sub, { n: 1, q })
2084
+ ownBoard(sub, q)
2085
+ syncEntrySubs(sub, q)
2086
+ }
2087
+ return () => {
2088
+ let held = boardUses.get(sub)
2089
+ if (!held || --held.n > 0) return
2090
+ boardUses.delete(sub)
2091
+ dropBoard(sub)
2092
+ syncEntrySubs(sub, '')
2093
+ }
2094
+ }
2095
+
2096
+ // Entry entities are intentionally absent from the root snapshot. A Session
2097
+ // view asks for only its ordered partition; ownership is shared across views
2098
+ // and tabs just like a board subscription.
2099
+ let entrySub = (session: string) => {
2100
+ let sub = `entries:${session}`
2101
+ let n = entryUses.get(sub) ?? 0
2102
+ entryUses.set(sub, n + 1)
2103
+ if (!n) ownBoard(sub, `.entry.session=${session}`)
2104
+ return () => {
2105
+ let held = (entryUses.get(sub) ?? 1) - 1
2106
+ if (held > 0) return void entryUses.set(sub, held)
2107
+ entryUses.delete(sub)
2108
+ dropBoard(sub)
2109
+ }
2110
+ }
2111
+
2112
+ export type SubscriptionState =
2113
+ | { status: 'loading' }
2114
+ | { status: 'ready'; eids: Set<string> }
2115
+ | { status: 'failed'; reason: string; reference: string }
2116
+
2117
+ // Stable subscription state, independent of the row cache. Failures survive
2118
+ // unrelated renders, unmounts, cache reseeds, and reconnect attempts; the
2119
+ // successful replacement in landSub is the sole clearing event.
2120
+ export let subscriptionState = (sub: string): SubscriptionState => {
2121
+ tick(sub).value
2122
+ let failed = subFailures.get(sub)
2123
+ if (failed) return { status: 'failed', ...failed }
2124
+ let eids = subEids(sub)
2125
+ return eids ? { status: 'ready', eids: new Set(eids) } : { status: 'loading' }
2126
+ }
2127
+
2128
+ export type SubscriptionRead = { sub: string; state: SubscriptionState }
2129
+
2130
+ // The addressed state beside a direct query's result signal. A held shape
2131
+ // reads the exact ServerSet that queryEids reads; a shape no owner holds yet
2132
+ // reads as loading under its name, and the hold's first frame answers it. A
2133
+ // shape with no line to ride has no remote failure to report, but over a
2134
+ // PARTIAL cache its local answer is a miss (`unserved`), so it reads as loading
2135
+ // rather than as the server's own "nothing matches". A read never opens.
2136
+ export let querySubscription = (
2137
+ preds: Pred[],
2138
+ source?: string,
2139
+ ): SubscriptionRead | undefined => {
2140
+ let key = qkey(preds)
2141
+ if (!lineOf(preds, key, source)) {
2142
+ return unserved(preds)
2143
+ ? { sub: '', state: { status: 'loading' } }
2144
+ : undefined
2145
+ }
2146
+ let sub = `q:${key}`
2147
+ return { sub, state: subscriptionState(sub) }
2148
+ }
2149
+
2150
+ // Ask again for a line an owner holds. A line nobody holds has nothing to
2151
+ // retry: asking would open a subscription with no owner.
2152
+ export let retrySubscription = (sub: string) => {
2153
+ if (!replica?.has(sub)) return false
2154
+ replica.retry(sub)
2155
+ return true
2156
+ }
2157
+
2158
+ // The fullscreen root a client reaches by direct URL (or a peek) is one entity
2159
+ // that no defining set holds and the query grammar can't name (`.entity.eid=` is
2160
+ // refused) — so a partial cache has nothing to render and the view blanks. A
2161
+ // route sub loads it whole by id: `route:<eid>` streams that entity's comps and
2162
+ // keeps them live (server derives the target from the sub name). Ref-counted so
2163
+ // several views of one entity share a sub; a no-op under a whole-graph cache,
2164
+ // where the entity is already loaded. Same ownership path as entrySub.
2165
+ let routeUses = new Map<string, number>()
2166
+ export let routeName = (eid: string, fields?: string) =>
2167
+ `route:${eid}${fields ? `:${fields}` : ''}`
2168
+ // A tile paints one row and nothing about its neighbours: `ROW` asks for the
2169
+ // whole entity without the edge subs a bare route holds beside it.
2170
+ export let ROW = '*'
2171
+ let routeLine = (eid: string, fields?: string) =>
2172
+ fields && fields != ROW ? `id=${eid}&.fields=${fields}` : `id=${eid}`
2173
+
2174
+ export let entityRead = (
2175
+ eid: string,
2176
+ fields?: string,
2177
+ canonical = eid,
2178
+ ) => {
2179
+ let sub = routeName(eid, fields)
2180
+ let state = subscriptionState(sub)
2181
+ return {
2182
+ sub,
2183
+ state,
2184
+ ready: state.status == 'ready',
2185
+ loaded,
2186
+ value: state.status == 'ready' && !state.eids.has(canonical)
2187
+ ? undefined
2188
+ : row(canonical).value
2189
+ ? ent(canonical)
2190
+ : undefined,
2191
+ }
2192
+ }
2193
+
2194
+ let routeSub = (eid: string, fields?: string) => {
2195
+ let sub = routeName(eid, fields)
2196
+ let n = routeUses.get(sub) ?? 0
2197
+ routeUses.set(sub, n + 1)
2198
+ // The scope rides in the name (the server answers that one entity), but the
2199
+ // query says it explicitly too — an empty q is refused server-side, never a
2200
+ // silent match-all.
2201
+ // A whole route also holds the edges incident to the entity, each end its
2202
+ // own subscription: the edge rows land like any other, and the cache reads
2203
+ // the sentences off them. A store that keeps no edges is never asked. The
2204
+ // edges a page does not list are not asked for, so on an entity cited a
2205
+ // thousand times its hundred are the links it lists.
2206
+ let ends = fields || !vocab.comp('edge')
2207
+ ? []
2208
+ : ['from', 'to'].map((end) => `${sub}:${end}`)
2209
+ let unlisted = natureOf(UNLISTED)
2210
+ let skip = unlisted && vocab.comp(unlisted) ? `&!${unlisted}` : ''
2211
+ if (!n) {
2212
+ ownBoard(sub, routeLine(eid, fields))
2213
+ for (let end of ends) {
2214
+ ownBoard(end, `.edge.${end.split(':').at(-1)}=${eid}${skip}&.limit=100`)
2215
+ }
2216
+ }
2217
+ return () => {
2218
+ let held = (routeUses.get(sub) ?? 1) - 1
2219
+ if (held > 0) return void routeUses.set(sub, held)
2220
+ routeUses.delete(sub)
2221
+ dropBoard(sub)
2222
+ for (let end of ends) dropBoard(end)
2223
+ }
2224
+ }
2225
+
2226
+ // How many links an entity has, once either end of its route holds a prefix:
2227
+ // each end asks for the newest hundred, and its window states the total.
2228
+ export let edgeTotal = (eid: string): number | undefined => {
2229
+ let ends = ['from', 'to'].map((end) => `${routeName(eid)}:${end}`)
2230
+ if (!ends.some((sub) => subWindow(sub)?.total != null)) return undefined
2231
+ return ends.reduce(
2232
+ (n, sub) => n + (subWindow(sub)?.total ?? subEids(sub)?.size ?? 0),
2233
+ 0,
2234
+ )
2235
+ }
2236
+
2237
+ // Several tiles' rows in one sub. A reference list or a shelf of pins paints N
2238
+ // entities, and N `route:<eid>:*` subs cost N serves and N frames where one
2239
+ // `id=a,b,c` line answers the same rows together. Concurrent readers share an
2240
+ // immutable bounded request; each still owns its lifetime independently.
2241
+ let rowsSub = rowHolds(ownBoard, dropBoard)
2242
+
2243
+ // Bring a lazy board's scoped-session entry subscriptions into line with its
2244
+ // query `q` (`''` closes them all). Reuses the ref-counted entrySub, so a board
2245
+ // and an open Session view of the same session share one subscription. Sessions
2246
+ // are resolved to eids by resolveRefs, matching the Session view's own key.
2247
+ let syncEntrySubs = (sub: string, q: string) => {
2248
+ let want = new Set<string>()
2249
+ if (q) {
2250
+ let preds = resolveRefs(parseQuery(q), findEid)
2251
+ if (namesLazy(preds)) { for (let s of scopedSessions(preds)) want.add(s) }
2252
+ }
2253
+ let held = boardEntrySubs.get(sub) ?? new Map<string, () => void>()
2254
+ for (let [s, off] of held) {
2255
+ if (!want.has(s)) {
2256
+ off()
2257
+ held.delete(s)
2258
+ }
2259
+ }
2260
+ for (let s of want) if (!held.has(s)) held.set(s, entrySub(s))
2261
+ if (held.size) boardEntrySubs.set(sub, held)
2262
+ else boardEntrySubs.delete(sub)
2263
+ }
2264
+
2265
+ // Query edits replace the installed name without tearing down its ownership.
2266
+ let boardQuery = (e: Ent) => {
2267
+ let sub = `board:${e.eid}`
2268
+ let q = boardLine(String(e.board?.query ?? ''))
2269
+ let use = boardUses.get(sub)
2270
+ if (!use || use.q == q) return
2271
+ use.q = q
2272
+ ownBoard(sub, q)
2273
+ syncEntrySubs(sub, q)
2274
+ }
2275
+
2276
+ // Tests replace the cache wholesale; this rebuilds the replica around it.
2277
+ export let restore = () => {
2278
+ ensureClient()
2279
+ resetSignals()
2280
+ }
2281
+
2282
+ // Boot waits on nothing: there is no bootstrap frame. Every view opens its own
2283
+ // subscription and says loading until it answers. The writes a prior life
2284
+ // left undelivered, and the refusals it kept, come back first.
2285
+ let booted = false
2286
+ export let owner = signal<string | undefined>()
2287
+ let authenticatedOwner = async (initial = false) => {
2288
+ let url = new URL(hosting().owner, base()).href
2289
+ let identity =
2290
+ await (initial ? writeOwner.initial(url) : writeOwner.fresh(url))
2291
+ owner.value = identity
2292
+ return identity
2293
+ }
2294
+
2295
+ export let boot = async () => {
2296
+ if (booted) return
2297
+ booted = true
2298
+ ensureClient()
2299
+ if (config.host) {
2300
+ await authenticatedOwner(true)
2301
+ }
2302
+ loadRefusals()
2303
+ await replayOutbox()
2304
+ forgetLegacy()
2305
+ }
2306
+ // Probe hooks: subscription/membership/wire counters over the active adapter.
2307
+ // `store()` remains false: the legacy IDB resolver is no longer a live surface.
2308
+ // `resolve` is a diagnostic local lookup only, never an authoritative query.
2309
+ let probe = globalThis as {
2310
+ __probe?: {
2311
+ store: () => boolean
2312
+ resolve: (
2313
+ line: string,
2314
+ ) => Promise<{ store: boolean; ms: number; n: number }>
2315
+ served: (line: string) => boolean
2316
+ subN: () => number
2317
+ transportN: () => number
2318
+ subShapes: () => Record<string, number>
2319
+ subMembersOf: (line: string) => number
2320
+ cacheN: () => number
2321
+ retainedN: () => number
2322
+ }
2323
+ }
2324
+ probe.__probe = {
2325
+ store: () => false,
2326
+ resolve: (line) => {
2327
+ let preds = resolveRefs(parseQuery(line), findEid)
2328
+ let t0 = performance.now()
2329
+ let ids = mem.resolve(preds)
2330
+ return Promise.resolve({
2331
+ store: false,
2332
+ ms: performance.now() - t0,
2333
+ n: ids.length,
2334
+ })
2335
+ },
2336
+ // Whether THIS query opened a genuine server subscription (T-17126) — proof
2337
+ // the answer is server-authoritative, not a local cache scan; subN counts how
2338
+ // many are open across the tab.
2339
+ served: (line) => queryUses.has(qkey(resolveRefs(parseQuery(line), findEid))),
2340
+ subN: () => queryUses.size,
2341
+ transportN: () => replica?.active() ?? 0,
2342
+ // A histogram of open query subs by SHAPE (`comp.prop op`) — to see what a
2343
+ // page actually subscribes and prove the flip's sub count is bounded.
2344
+ subShapes: () => {
2345
+ let h: Record<string, number> = {}
2346
+ for (let s of queryUses.values()) {
2347
+ let p = s.preds[0]
2348
+ let key = !p
2349
+ ? 'empty'
2350
+ : p.refs
2351
+ ? '.refs'
2352
+ : `.${p.comp}${p.prop ? '.' + p.prop : ''}${
2353
+ p.op == EXISTS ? '!' : p.op ? p.op : '='
2354
+ }`
2355
+ h[key] = (h[key] ?? 0) + 1
2356
+ }
2357
+ return h
2358
+ },
2359
+ subMembersOf: (line) =>
2360
+ subEids(`q:${qkey(resolveRefs(parseQuery(line), findEid))}`)?.size ?? -1,
2361
+ // How many rows the partial cache holds — the T-21491 bound: working-set
2362
+ // floor + sub-held + demand-fetched, far below the server's row count.
2363
+ cacheN: () => Object.keys(cache.peek()).length,
2364
+ retainedN: () => replica?.box.cache.size() ?? 0,
2365
+ }
2366
+
2367
+ // The edges a page lists, and so every list of an entity's links reads
2368
+ // (`refs`, `kids`, `parents`): all but the kernel's `references`, written when
2369
+ // a transcript entry cites an entity or a session names its persona, which
2370
+ // say what mentioned it rather than how it relates. `yak graph show` leaves
2371
+ // them out too, and a route never asks for them (`routeSub`). Who cites what
2372
+ // is still read through `relations` itself (`references`).
2373
+ let UNLISTED = 'referenced'
2374
+ let listed = (d: Dep) => d.type != UNLISTED
2375
+
2376
+ // What the page calls an entity its prose names by eid (@yaks/markdown `Ids`):
2377
+ // its id, where the page already holds it numbered. The page never reads an
2378
+ // entity only to draw its id; one it does not hold draws as its handle.
2379
+ export let heldId = (eid: string): string | undefined => {
2380
+ let held = cache.peek()[eid] as Comps | undefined
2381
+ let { num, prefix } = held?.entity ?? {}
2382
+ return held && num
2383
+ ? idOf({ eid, kind: kindOf(held), num, prefix })
2384
+ : undefined
2385
+ }
2386
+
2387
+ // The whole entity, assembled for a renderer: spine, components present,
2388
+ // outgoing edge sentences, contained children (recursive — graphs stay
2389
+ // small; a view reads as deep as it wants).
2390
+ export let ent = (eid: string): Ent => {
2391
+ let { entity, ...comps } = row(eid).value ?? {}
2392
+ if (comps.pin) comps.pin = { ...comps.pin, z: pinZ(eid, comps.pin.z).value }
2393
+ let mine = relations(eid).value.filter(listed)
2394
+ return {
2395
+ ...comps, // whatever components the entity carries, verbatim —
2396
+ // created/updated (provenance) ride here like any other component now
2397
+ eid,
2398
+ entity,
2399
+ num: entity?.num ?? 0,
2400
+ ...entity?.prefix ? { prefix: String(entity.prefix) } : {},
2401
+ kind: kindOf(comps), // derived — the display convention, not data
2402
+ refs: mine
2403
+ .filter((d) => d.type != 'contains')
2404
+ .map((d) => ({ type: d.type, child: d.child }))
2405
+ .sort((a, b) =>
2406
+ Number(settled(statusOf(row(a.child).value ?? {}))) -
2407
+ Number(settled(statusOf(row(b.child).value ?? {})))
2408
+ ),
2409
+ kids: mine
2410
+ .filter((d) => d.type == 'contains')
2411
+ .map((d) => ent(d.child)),
2412
+ }
2413
+ }
2414
+
2415
+ // Markdown belongs to the project its entity speaks for. Follow only the
2416
+ // graph's explicit ownership/reference columns: task/memory → project,
2417
+ // comment → target, session → its actor, entry → its session. A seen set
2418
+ // makes malformed cycles inert.
2419
+ export let repoTrace = (start: Ent): { eids: string[]; url?: string } => {
2420
+ let seen = new Set<string>()
2421
+ let todo = [start]
2422
+ while (todo.length) {
2423
+ let e = todo.shift()!
2424
+ if (seen.has(e.eid)) continue
2425
+ seen.add(e.eid)
2426
+ if (e.repo?.url) return { eids: [...seen], url: e.repo.url }
2427
+ let next = [
2428
+ e.filed?.project,
2429
+ e.comment?.target,
2430
+ e.session?.actor,
2431
+ e.memory?.scope,
2432
+ e.entry?.session,
2433
+ ].filter((eid): eid is string => !!eid)
2434
+ todo.push(...next.map(ent))
2435
+ }
2436
+ return { eids: [...seen] }
2437
+ }
2438
+ export let repoUrl = (start: Ent): string | undefined => repoTrace(start).url
2439
+
2440
+ export let findEid = (id: string): string | undefined => {
2441
+ syncIds()
2442
+ let p = parse(id)
2443
+ if (p) {
2444
+ let eids = answering(
2445
+ [...numEids.get(p.num) ?? []],
2446
+ p.prefix,
2447
+ (eid) => idGraph[eid]?.entity ?? {},
2448
+ )
2449
+ if (eids.length > 1) {
2450
+ throw new IdError(
2451
+ `${id} is an ambiguous id — matches ${eids.join(', ')}`,
2452
+ )
2453
+ }
2454
+ return eids[0]
2455
+ }
2456
+ if (cached(id.toLowerCase())) return id.toLowerCase()
2457
+ let hex = shortHex(id)
2458
+ if (hex) {
2459
+ let hits = [...shortEids.get(hex.slice(0, 10)) ?? []]
2460
+ .filter((eid) => eid.replaceAll('-', '').startsWith(hex))
2461
+ if (hits.length > 1) {
2462
+ throw new IdError(
2463
+ `${id} is an ambiguous id — matches ${
2464
+ hits.join(', ')
2465
+ }; use more characters`,
2466
+ )
2467
+ }
2468
+ return hits[0]
2469
+ }
2470
+ if (id.includes('#')) {
2471
+ throw new IdError(`${id}: expected # followed by 6–64 hex characters`)
2472
+ }
2473
+ return aliasEids.get(id)
2474
+ }
2475
+
2476
+ // The addressed-subscription id-resolve fallback (T-18102). Once boot
2477
+ // serves a WORKING SET, the cache is partial: a token naming a live-but-
2478
+ // unloaded entity misses the vocabulary above, and navigation or a crumb
2479
+ // would silently 404. This sidecar is the miss path — it opens a one-row
2480
+ // subscription by address and reads the
2481
+ // two immutable facts a link or crumb needs: its num and kind. NAMING-ONLY,
2482
+ // never content — so nothing here reintroduces the content staleness a whole-
2483
+ // cache seed carried (jeff C-3528); content still rides subscriptions.
2484
+ //
2485
+ // The reads (serverEid/serverName) stay SYNC and O(1): they answer from this
2486
+ // sidecar and, on a first miss, KICK an async fetch and return "not yet". A
2487
+ // render therefore never blocks and a navigation never hangs on the wire —
2488
+ // resolveGen wakes the caller when an answer lands. A token has one resolve in
2489
+ // flight, however many renders read it, and it waits for the server's answer
2490
+ // however late it comes: a slow or hung server is asked once, never stormed,
2491
+ // and a slow answer still names the token. null means the server said "no
2492
+ // such entity" — an empty answer, or a refusal of the token itself (`T-998
2493
+ // names nothing`) — an honest Lost, not a pending spinner.
2494
+ type Named = { eid: string; num: number; kind: string }
2495
+ let named = new Map<string, Named | null>() // token OR eid -> naming (null = gone)
2496
+ // The gone tokens the server addressed without refusing: each names an entity
2497
+ // no query selects, a deleted one, whose page reads its history.
2498
+ let buried = new Set<string>()
2499
+ let resolvingIds = new Map<string, Promise<Named | null>>() // token -> in flight
2500
+ export let resolveGen = signal(0) // bumped when a resolve settles, to re-render
2501
+
2502
+ // Onto the code served now, once: the moment it last reloaded for it is kept
2503
+ // for the tab, and a page that reloaded within the minute says the trouble,
2504
+ // once. Every refusal after the first is the same trouble.
2505
+ let RELOADED = 'tasks-reloaded'
2506
+ let reloading = false
2507
+ let reload = (r: Parameters<typeof said>[0]) => {
2508
+ if (reloading) return
2509
+ reloading = true
2510
+ let last = Number(sessionStorage.getItem(storageKey(RELOADED)) ?? 0)
2511
+ if (time.now() - last < 60_000) return said(r)
2512
+ sessionStorage.setItem(storageKey(RELOADED), String(time.now()))
2513
+ location.reload()
2514
+ }
2515
+
2516
+ // Whether a refused line was refused for a token that names nothing: every
2517
+ // name holding it reads a token (its resolve, `resolve:T-998`, or a page's own
2518
+ // read of it, `route:T-998`) that this sidecar finds names nothing. Such a
2519
+ // refusal is the answer a page draws as Lost, not a failure of its code.
2520
+ let unnamed = async (names: string[] = []): Promise<boolean> => {
2521
+ let found = await Promise.all(names.map((sub) => {
2522
+ let [kind, token] = sub.split(':')
2523
+ if (kind != 'resolve' && kind != 'route') return undefined
2524
+ return named.has(token) ? named.get(token) : resolvingIds.get(token)
2525
+ }))
2526
+ return found.length > 0 && found.every((n) => n === null)
2527
+ }
2528
+
2529
+ let kickResolve = (token: string): Promise<Named | null> => {
2530
+ let found = resolvingIds.get(token)
2531
+ if (found) return found
2532
+ let settle = (n: Named | null) => {
2533
+ resolvingIds.delete(token)
2534
+ named.set(token, n)
2535
+ if (n) named.set(n.eid, n) // resolvable by eid too, for the reverse read
2536
+ resolveGen.value++
2537
+ return n
2538
+ }
2539
+ let sub = `resolve:${token}`
2540
+ let p = new Promise<Named | null>((resolve) => {
2541
+ oneShot(sub, `id=${token}`, () => {
2542
+ let eid = [...(subEids(sub) ?? [])][0]
2543
+ if (!eid) {
2544
+ buried.add(token)
2545
+ return resolve(settle(null))
2546
+ }
2547
+ let comps = paint.peek()[eid] ?? {}
2548
+ resolve(settle({
2549
+ eid,
2550
+ num: Number(comps.entity?.num ?? 0),
2551
+ kind: kindOf(comps),
2552
+ }))
2553
+ }, () => resolve(settle(null))) // refusing the token is its answer
2554
+ })
2555
+ resolvingIds.set(token, p)
2556
+ return p
2557
+ }
2558
+
2559
+ // The sync read: a token's naming if a prior addressed sub landed it, null if
2560
+ // server said it's gone, undefined while unknown or in flight — and a first
2561
+ // miss KICKS the fetch. Reading resolveGen keeps the caller live to the
2562
+ // landing.
2563
+ let nameFor = (token: string): Named | null | undefined => {
2564
+ resolveGen.value // subscribe: a landing re-runs the reader
2565
+ if (named.has(token)) return named.get(token)!
2566
+ kickResolve(token)
2567
+ return undefined
2568
+ }
2569
+
2570
+ // Forward: a token's eid via the server, or undefined while unknown/gone. The
2571
+ // cache-side vocabulary (eidOf/findEid) tries this only after it misses.
2572
+ export let serverEid = (token: string): string | undefined =>
2573
+ nameFor(token)?.eid
2574
+
2575
+ // The same resolution awaited, for a caller that runs once rather than on
2576
+ // every render: the cache first, then the server, as long as it takes.
2577
+ // undefined when nothing answers to the token.
2578
+ export let resolveEid = async (token: string): Promise<string | undefined> => {
2579
+ try {
2580
+ let eid = findEid(token)
2581
+ if (eid) return eid
2582
+ } catch {
2583
+ return undefined
2584
+ }
2585
+ return (await kickResolve(token))?.eid
2586
+ }
2587
+
2588
+ // Reverse: an unloaded eid's naming (num, kind) for a crumb chip — undefined
2589
+ // while resolving, null once the server says it's gone.
2590
+ export let serverName = (eid: string): Named | null | undefined => nameFor(eid)
2591
+
2592
+ // Whether a token is still being resolved — the "resolving" state a router
2593
+ // shows in place of a premature 404. A prior null (genuine miss) is NOT
2594
+ // resolving.
2595
+ export let resolvingId = (token: string): boolean => {
2596
+ resolveGen.value
2597
+ return !named.has(token) && resolvingIds.has(token)
2598
+ }
2599
+
2600
+ // Whether the server said a token names nothing: its resolve came back empty
2601
+ // or refused.
2602
+ export let goneId = (token: string): boolean => {
2603
+ resolveGen.value
2604
+ return named.get(token) === null
2605
+ }
2606
+
2607
+ // Whether a gone token names a deleted entity: the server addressed it, and
2608
+ // no query selects what it names.
2609
+ export let buriedId = (token: string): boolean => {
2610
+ resolveGen.value
2611
+ return named.get(token) === null && buried.has(token)
2612
+ }
2613
+
2614
+ // A wholesale reseed may hold what this client could not name before, so
2615
+ // resetSignals clears the sidecar and the next render re-resolves rather than
2616
+ // serving a stale miss.
2617
+ export let clearResolved = () => {
2618
+ named.clear()
2619
+ buried.clear()
2620
+ resolvingIds.clear()
2621
+ resolveGen.value++
2622
+ }
2623
+ // The same query over the WHOLE graph — the board's List face. No task
2624
+ // gate: sessions, memories, docs, web, people — anything that matches.
2625
+ // Chrome stays out (a camera's updated.at churns with every pan and
2626
+ // would drown any hot feed; cards/folds/shelves/clients are presence,
2627
+ // not content), comments surface through their targets (the lately
2628
+ // digest's rule), and a board is not news to itself.
2629
+ let CHROME = new Set([
2630
+ 'card',
2631
+ 'camera',
2632
+ 'fold',
2633
+ 'shelf',
2634
+ 'cursor',
2635
+ 'client',
2636
+ 'comment',
2637
+ ])
2638
+ let chrome = (r: Comps) => [...CHROME].some((name) => r[name as keyof Comps])
2639
+ export let boardPost = (
2640
+ e: Pick<Ent, 'eid'>,
2641
+ tasks: boolean,
2642
+ eids: Iterable<string>,
2643
+ ): string[] =>
2644
+ [...eids].filter((eid) => {
2645
+ // Each member read through its OWN row signal, never `paint.value` — the
2646
+ // filter stays asleep on an unrelated patch and wakes on a member's edit
2647
+ // (a row gaining/losing `task` moves the tasks-only face), where a whole-
2648
+ // cache read would wake the board on every patch.
2649
+ let r = row(eid).value
2650
+ // Facets are the truth: a shelf is also a canvas, so kindOf cannot name
2651
+ // the chrome component that keeps it out of the feed.
2652
+ return !!r && (tasks ? !!r.task : eid != e.eid && !chrome(r))
2653
+ })
2654
+
2655
+ // A board's parsed, ref-resolved query, rebuilt each render — it THROWS on a
2656
+ // bad query the way the scan did, so the consumers catch it and show the error.
2657
+ // resolveRefs turns id references (T-3, P-19) into the eids the sub is keyed by.
2658
+ let boardPreds = (e: Ent) =>
2659
+ resolveRefs(parseQuery(String(e.board?.query ?? '')), findEid)
2660
+
2661
+ // A board IS a saved query, so its membership is the SERVER's answer: the
2662
+ // subscription boardSub installed (subEids) is the live, complete set — the
2663
+ // server maintains the query, forward-path and reverse hops included, where a
2664
+ // per-patch local re-test can't keep a complex board live (that was the whole-
2665
+ // cache rescan this replaces), and it stays complete under a working-set boot
2666
+ // where a cache scan would silently under-report (T-18094). It updates as tasks
2667
+ // join or leave: a maintenance frame adds/drops the eid and wakes this read.
2668
+ //
2669
+ // Until the subscription's first frame lands (undefined — an empty Set is a
2670
+ // ready, empty result), the local index answers from the cache so a board never
2671
+ // flashes empty on mount. Opening a second server query here doubles every
2672
+ // board's initial transfer and defeats boardSub's window. boardPost splits the
2673
+ // one member set into
2674
+ // the tasks-only and whole-graph faces and drops chrome/self (a board is not
2675
+ // news to itself), reading each member through its own row signal — so the list
2676
+ // sleeps through an unrelated patch and wakes on a member's edit.
2677
+ let boardScan = (e: Ent, tasks: boolean): Ent[] => {
2678
+ let preds = boardPreds(e) // throws on a bad query, before either door
2679
+ let members = subEids(`board:${e.eid}`)
2680
+ if (!members) return boardPost(e, tasks, mem.resolve(preds)).map(ent)
2681
+ let post = boardPost(e, tasks, members)
2682
+ // Pre-flip agreement (probe only, config.agreement): the local query door
2683
+ // must answer the same set the server streamed. The scan that used to be the
2684
+ // render source is gone; this compares the two doors that outlive it, so a
2685
+ // divergence still surfaces before the boot flip trusts the sub alone.
2686
+ if (config.agreement) {
2687
+ assertAgree(
2688
+ `board:${e.eid}`,
2689
+ // The line the sub was OPENED with, window and all — the check is about
2690
+ // this subscription, and its window is what a divergence must be read
2691
+ // against (gaps() names it, so a prefix annotates instead of asserting).
2692
+ boardLine(String(e.board?.query ?? '')),
2693
+ boardPost(e, tasks, queryEids(preds).value),
2694
+ post,
2695
+ )
2696
+ }
2697
+ return post.map(ent)
2698
+ }
2699
+
2700
+ export let boardTasks = (e: Ent): Ent[] => boardScan(e, true)
2701
+ export let boardAll = (e: Ent): Ent[] => boardScan(e, false)
2702
+
2703
+ // The ephemeral filter's evaluator: a bar's line parsed and ref-resolved
2704
+ // ONCE, returned as a per-row test — Board and the Lists AND it into
2705
+ // whatever they already show. Throws like a saved query does; the bar
2706
+ // catches (mid-keystroke is no place to error) where a board would show.
2707
+ export let sieve = (line: string): (eid: string) => boolean => {
2708
+ // A blank filter BAR is "no screen" — the bar narrows what a view already
2709
+ // shows, it does not select. The empty QUERY selects nothing (parseQuery's
2710
+ // never-pred), so this caller states its own meaning before parsing.
2711
+ if (!line.trim()) return () => true
2712
+ let preds = resolveRefs(parseQuery(line), findEid)
2713
+ if (!preds.length) return () => true
2714
+ return (eid) =>
2715
+ matchQuery(
2716
+ paint.peek()[eid] ?? {},
2717
+ preds,
2718
+ (t) => paint.peek()[t],
2719
+ undefined,
2720
+ kidsVia((t) => paint.peek()[t]),
2721
+ )
2722
+ }
2723
+
2724
+ // The cache as client Rows — the shape the headless half's helpers speak
2725
+ // (find, the change builders, the command line's Ctx), so an id lookup or
2726
+ // a claim batch is written once and serves the CLI, the web and the TUI.
2727
+ export let rows = (): Row[] =>
2728
+ Object.entries(paint.value).filter(([, r]) => !r.quarantined).map((
2729
+ [eid, r],
2730
+ ) => ({
2731
+ eid,
2732
+ num: r.entity?.num ?? 0,
2733
+ ...r.entity?.prefix ? { prefix: String(r.entity.prefix) } : {},
2734
+ kind: kindOf(r),
2735
+ comps: r as Record<string, Record<string, unknown>>,
2736
+ }))
2737
+
2738
+ // The distinct domain census as an AGGREGATE sub (T-17504, then D-22567 §1):
2739
+ // the well asks the server for the VALUES, so the client never holds the tasks
2740
+ // they came from. This used to be a `.task` membership sub carrying a
2741
+ // wake-projected `filed.domain` — which streamed EVERY task into the cache
2742
+ // (23,992 change records, 4.7 MB measured on the live graph) so a render could
2743
+ // reduce them to a dozen strings. `.distinct=filed.domain` answers those strings
2744
+ // from the index and re-answers when a task moves Eng→Ops, the same fact the
2745
+ // projection was there to catch.
2746
+ //
2747
+ // Until the server answers, while no mounted picker holds it (wells.ts), and on
2748
+ // the socketless paths (the TUI, a test), the working set's own census serves: a suggestion well is best-effort by nature,
2749
+ // which is why this one may read locally where a board's membership may not.
2750
+ export let domains = {
2751
+ agg: 'agg:domains',
2752
+ line: '.task&.distinct=filed.domain',
2753
+ get value() {
2754
+ let t = aggRead(domains.agg)
2755
+ return t?.live ? Object.keys(t.map).sort() : distinctValues(
2756
+ localEids([has('task')]).value.map((eid) => paint.peek()[eid] ?? {}),
2757
+ { comp: 'filed', prop: 'domain' },
2758
+ )
2759
+ },
2760
+ }
2761
+
2762
+ // Presence/reference reads the query door answers directly: every project (by
2763
+ // num, unknown last), every managed session (each riding its own row signal so
2764
+ // a status change wakes it), and a client's single shelf (a unique client
2765
+ // equality). No bespoke census to keep — refreshQueries maintains all three, and
2766
+ // each face wakes only when ITS membership changes, not on a sibling facet.
2767
+ export let projects = (): Ent[] =>
2768
+ queryEids([has('project')]).value
2769
+ .toSorted((a, b) =>
2770
+ (paint.peek()[a]?.entity?.num ?? Infinity) -
2771
+ (paint.peek()[b]?.entity?.num ?? Infinity)
2772
+ )
2773
+ .map(ent)
2774
+ // What a face that renders a session row needs on top of the dot's columns —
2775
+ // its short account of its work. Held only while such a face is mounted (a
2776
+ // project's Dashboard), so the columns nobody is looking at stay off the wire.
2777
+ // A different projection is a different SUB with its own member set: that is
2778
+ // what "projection is part of sub identity" buys, and the cache merges the two
2779
+ // because the fuller one is a superset.
2780
+ export let sessionDetail = sessionQueries(vocab).detail
2781
+
2782
+ // THIS tab's own screen-state rows — cursor, camera, fold: the
2783
+ // components whose `client` names this browser — streamed by one small server
2784
+ // sub per component, held by the mounted app (App.tsx, `{client}` through
2785
+ // useHold). Named one by one, because another plugin declares a
2786
+ // `client` that is not this reference (@yaks/connections' integration). The
2787
+ // key space is exactly one value (this client's uuid), so the singleton readers
2788
+ // stay LOCAL lookups over the rows the subs stream in. A per-shape wire sub
2789
+ // here would accumulate (a fold sub per board visited); resolving locally
2790
+ // without the sub would under-report on a partial cache.
2791
+ let SCREEN = ['camera', 'cursor', 'fold']
2792
+ let screenOf = (comp: string, client: string) =>
2793
+ resolveRefs(parseQuery(`.${comp}.client=${client}`), findEid)
2794
+
2795
+ /** The read state of one of this tab's screen components (default its folds). */
2796
+ export let clientSubscription = (
2797
+ client: string,
2798
+ comp = 'fold',
2799
+ ): SubscriptionRead | undefined =>
2800
+ capable('canvas') ? querySubscription(screenOf(comp, client)) : undefined
2801
+
2802
+ let holdClientRows = (client: string): () => void => {
2803
+ if (!capable('canvas') || !client) return () => {}
2804
+ let drops = SCREEN.map((comp) => holdQuery(screenOf(comp, client)))
2805
+ return () => drops.forEach((drop) => drop())
2806
+ }
2807
+
2808
+ // The comments aimed HERE — every entity whose `comment.target` is this eid,
2809
+ // an eid EQUALITY the refs index answers in O(result). A face subscribes to its
2810
+ // own list (num-ordered) and tally; birth, death and retargeting update only the
2811
+ // targets they affect. `.map(ent)` rides each note's own row signal, so a note
2812
+ // edit wakes only the thread it is in. A RENDERED view must come through
2813
+ // useCommentsOn (components/useQuery.ts): the hook HOLDS the eid-keyed server
2814
+ // sub for the card's life and the last unmount tears it down (T-21489); this
2815
+ // plain door reuses a held set but, unheld, would leave the wire sub open for
2816
+ // the socket's life — it stays for tests and socketless imperative reads.
2817
+ export let commentsOn = (target: string): Ent[] =>
2818
+ queryEids([eq('comment', 'target', target)]).value
2819
+ .map(ent)
2820
+ .sort((a, b) => a.num - b.num)
2821
+
2822
+ // One actor's selected chat for one entity. chat(actor,target) is unique in
2823
+ // SQLite and both columns are indexed in every cache backend, so this is a
2824
+ // local lookup whose result alone wakes the aside. Rendered conversations
2825
+ // use useChatFor to hold the complete server answer for their lifetime.
2826
+ export let chatFor = (actor: string, target: string): Ent | undefined =>
2827
+ localEids([eq('chat', 'actor', actor), eq('chat', 'target', target)]).value
2828
+ .map(ent)[0]
2829
+ // Badges share one tally, restricted to the mounted targets. A graph-wide
2830
+ // tally is smaller than comment rows but still grows with history, not the UI.
2831
+ type AggSet = {
2832
+ live: Signal<boolean>
2833
+ map: Signal<Record<string, number>>
2834
+ line: string
2835
+ open: boolean
2836
+ n: number
2837
+ }
2838
+ let aggSets = new Map<string, AggSet>()
2839
+ // The local half: get-or-make the set a reader binds to. Bookkeeping only — it
2840
+ // dials nothing, so a render may reach it.
2841
+ let aggSet = (name: string, line: string): AggSet => {
2842
+ let found = aggSets.get(name)
2843
+ if (found) return found
2844
+ found = { live: signal(false), map: signal({}), line, open: false, n: 0 }
2845
+ aggSets.set(name, found)
2846
+ return found
2847
+ }
2848
+ // The wire half: ask the server for the set, and RE-ASK when the line moved
2849
+ // under a name that is already open (a board's query edited beneath its tile).
2850
+ // Re-asking keeps the SAME set, so every reader stays bound to it and simply
2851
+ // sees the answer go un-live and then land again — the way boardQuery replaces
2852
+ // a member sub without tearing down its ownership.
2853
+ // `keep` holds the last answer while the wider ask is out: the comment tally's
2854
+ // line GROWS as badges mount in layers, and every key it already answered stays
2855
+ // true, so blanking would flicker every badge three times per boot (T-37445).
2856
+ let aggQuery = (name: string, line: string, keep = false): AggSet => {
2857
+ let found = aggSet(name, line)
2858
+ if (!found.open) {
2859
+ found.open = true
2860
+ found.line = line
2861
+ ownBoard(name, line)
2862
+ } else if (found.line != line) {
2863
+ found.line = line
2864
+ if (!keep) {
2865
+ found.live.value = false
2866
+ found.map.value = {}
2867
+ }
2868
+ ownBoard(name, line)
2869
+ }
2870
+ return found
2871
+ }
2872
+ let COMMENTS = 'agg:comments'
2873
+ let COMMENT_TALLY = '.comment&.tally=comment.target'
2874
+ let commentTargets = new Map<string, number>()
2875
+ let commentScheduled = false
2876
+ let scheduleCommentTally = () => {
2877
+ if (commentScheduled) return
2878
+ commentScheduled = true
2879
+ queueMicrotask(() => {
2880
+ commentScheduled = false
2881
+ let targets = [...commentTargets.keys()].sort()
2882
+ if (!targets.length) {
2883
+ let set = aggSets.get(COMMENTS)
2884
+ if (set) {
2885
+ set.open = false
2886
+ set.live.value = false
2887
+ set.map.value = {}
2888
+ }
2889
+ dropBoard(COMMENTS)
2890
+ } else {
2891
+ aggQuery(
2892
+ COMMENTS,
2893
+ `${COMMENT_TALLY}&.comment.target=${targets.join(',')}`,
2894
+ true,
2895
+ )
2896
+ }
2897
+ })
2898
+ }
2899
+ // Effects hold badges; reads never dial during render. Batch adjacent mounts
2900
+ // into one subscription replacement rather than one round trip per row.
2901
+ let holdCommentCount = (target: string) => {
2902
+ let n = commentTargets.get(target) ?? 0
2903
+ commentTargets.set(target, n + 1)
2904
+ if (!n) scheduleCommentTally()
2905
+ return () => {
2906
+ let n = (commentTargets.get(target) ?? 1) - 1
2907
+ if (n) commentTargets.set(target, n)
2908
+ else {
2909
+ commentTargets.delete(target)
2910
+ scheduleCommentTally()
2911
+ }
2912
+ }
2913
+ }
2914
+ // A key the tally answered is the count; a target it has not (yet) named reads
2915
+ // the comments the cache holds, which is what it painted before the answer.
2916
+ export let commentCount = (target: string): Signal<number> =>
2917
+ computed(() => {
2918
+ let t = aggSet(COMMENTS, COMMENT_TALLY)
2919
+ return t.map.value[target] ??
2920
+ localEids([eq('comment', 'target', target)]).value.length
2921
+ })
2922
+
2923
+ // An aggregate held for an owner's lifetime. The comment tally above is one
2924
+ // shared shape held by mounted badges; an aggregate keyed by an ENTITY (a
2925
+ // board's status tally) has an unbounded key space, so it holds and releases
2926
+ // exactly like an eid-keyed query sub does (T-21489): the last release closes
2927
+ // the wire sub. `once` asks a single time: its answer lands in its set and the
2928
+ // line closes, so an aggregate that reads every entity (a census) is not
2929
+ // evaluated again after every commit.
2930
+ let holdAgg = (name: string, line: string, once = false): () => void => {
2931
+ let set = once ? aggSet(name, line) : aggQuery(name, line)
2932
+ if (!set.n++ && once) oneShot(name, line, () => {}, () => {})
2933
+ ticked(name)
2934
+ return () => {
2935
+ if (aggSets.get(name) != set || --set.n > 0) return
2936
+ aggSets.delete(name)
2937
+ dropBoard(name)
2938
+ }
2939
+ }
2940
+
2941
+ // A held aggregate's answer as it stands: whether it has landed, and each
2942
+ // value's count (`.count` answers under the empty value). Read in a render, a
2943
+ // new answer repaints it; undefined for a name nobody holds.
2944
+ export let aggRead = (
2945
+ name: string,
2946
+ ): { live: boolean; map: Record<string, number> } | undefined => {
2947
+ tick(name).value
2948
+ let set = aggSets.get(name)
2949
+ return set?.n ? { live: set.live.value, map: set.map.value } : undefined
2950
+ }
2951
+
2952
+ // One aggregate value for a view that owns the corresponding hold. Undefined
2953
+ // until the server has answered; callers must not paint that as a confident 0.
2954
+ export let aggValue = (name: string, value = ''): number | undefined => {
2955
+ let set = aggRead(name)
2956
+ return set?.live ? set.map[value] ?? 0 : undefined
2957
+ }
2958
+
2959
+ // What a mounted component holds open while it draws it: a query, a board's
2960
+ // members, an entity, a list's rows, a session's entries, an aggregate, a
2961
+ // comment badge's tally, or this tab's screen rows.
2962
+ export type Hold =
2963
+ | { query: Pred[]; source?: string; typed?: boolean }
2964
+ | { board: Ent }
2965
+ | { entity: string; fields?: string }
2966
+ | { rows: string[] }
2967
+ | { entries: string }
2968
+ | { agg: string; line: string; once?: boolean; typed?: boolean }
2969
+ | { comments: string }
2970
+ | { client: string }
2971
+
2972
+ // The subscriptions riding a line the person typed (a query page's), counted
2973
+ // by the holds that say so: a refusal of one answers their input, which the
2974
+ // page shows, and is not reported as a failure of its code.
2975
+ let typed = new Map<string, number>()
2976
+ let typing = (sub: string, hold: () => () => void): () => void => {
2977
+ typed.set(sub, (typed.get(sub) ?? 0) + 1)
2978
+ let off = hold()
2979
+ return () => {
2980
+ off()
2981
+ let n = typed.get(sub)! - 1
2982
+ if (n) typed.set(sub, n)
2983
+ else typed.delete(sub)
2984
+ }
2985
+ }
2986
+
2987
+ let holdKey = (h: Hold): string =>
2988
+ 'query' in h
2989
+ ? `q:${qkey(h.query)}:${h.source?.trim() ?? ''}${h.typed ? ':typed' : ''}`
2990
+ : 'board' in h
2991
+ ? `board:${h.board.eid}`
2992
+ : 'entity' in h
2993
+ ? routeName(h.entity, h.fields)
2994
+ : 'rows' in h
2995
+ ? `rows:${[...new Set(h.rows)].join(',')}`
2996
+ : 'entries' in h
2997
+ ? `entries:${h.entries}`
2998
+ : 'agg' in h
2999
+ ? `agg:${h.agg}:${h.once ? 'once' : 'live'}:${
3000
+ h.typed ? 'typed:' : ''
3001
+ }${h.line}`
3002
+ : 'comments' in h
3003
+ ? `comments:${h.comments}`
3004
+ : `client:${h.client}`
3005
+
3006
+ let open = (h: Hold): () => void =>
3007
+ 'query' in h
3008
+ ? h.typed
3009
+ ? typing(`q:${qkey(h.query)}`, () => holdQuery(h.query, h.source))
3010
+ : holdQuery(h.query, h.source)
3011
+ : 'board' in h
3012
+ ? boardSub(h.board)
3013
+ : 'entity' in h
3014
+ ? routeSub(h.entity, h.fields)
3015
+ : 'rows' in h
3016
+ ? rowsSub([...new Set(h.rows)])
3017
+ : 'entries' in h
3018
+ ? entrySub(h.entries)
3019
+ : 'agg' in h
3020
+ ? h.typed
3021
+ ? typing(h.agg, () => holdAgg(h.agg, h.line, h.once))
3022
+ : holdAgg(h.agg, h.line, h.once)
3023
+ : 'comments' in h
3024
+ ? holdCommentCount(h.comments)
3025
+ : holdClientRows(h.client)
3026
+
3027
+ // The one door to the server's live data (T-131877): a live query is owned by
3028
+ // the component that draws it. It opens when that component mounts and closes
3029
+ // when it unmounts, and reads (queryEids, querySubscription, aggRead, …) never
3030
+ // open one. A hold kept across renders stays open, so a view whose set of
3031
+ // holds shifts (a path discovered hop by hop) never closes and reopens the
3032
+ // ones it keeps. Identical holds from several components share one server
3033
+ // subscription, counted by owners.
3034
+ export let useHold = (...holds: (Hold | false | null | undefined | '')[]) => {
3035
+ let live = useRef(new Map<string, () => void>())
3036
+ let want = new Map(
3037
+ holds.filter((h): h is Hold => !!h).map((h) => [holdKey(h), h]),
3038
+ )
3039
+ let key = [...want.keys()].join('\n')
3040
+ // A board's query edit replaces its line under the same hold.
3041
+ let lines = [...want.values()].flatMap((h) =>
3042
+ 'board' in h ? [String(h.board.board?.query ?? '')] : []
3043
+ ).join('\n')
3044
+ useLayoutEffect(() => {
3045
+ for (let [k, off] of live.current) {
3046
+ if (want.has(k)) continue
3047
+ off()
3048
+ live.current.delete(k)
3049
+ }
3050
+ for (let [k, h] of want) {
3051
+ if (!live.current.has(k)) live.current.set(k, open(h))
3052
+ else if ('board' in h) boardQuery(h.board)
3053
+ }
3054
+ }, [key, lines])
3055
+ useLayoutEffect(() => () => {
3056
+ for (let off of live.current.values()) off()
3057
+ live.current.clear()
3058
+ }, [])
3059
+ }
3060
+
3061
+ // A board TILE renders status counts and nothing else, so it subscribes to the
3062
+ // COUNTS — never the members (T-22509: the Everything board streamed ~4.4k task
3063
+ // rows into every canvas showing its tile). The server maintains
3064
+ // `<query>&.tally=task.status` from the index; only a FULLSCREEN board opens the
3065
+ // member sub.
3066
+ //
3067
+ // Three answers, not two: a line to ask; `''` for the EMPTY query, which selects
3068
+ // nothing at every door, so its tally is known to be empty without asking; and
3069
+ // undefined for a query that does not PARSE — nothing to ask and nothing to
3070
+ // claim, which is what keeps a typo'd board from painting four confident zeros.
3071
+ export let boardTallyLine = (e: Ent): string | undefined => {
3072
+ let q = String(e.board?.query ?? '').trim()
3073
+ if (!q) return ''
3074
+ try {
3075
+ boardPreds(e)
3076
+ } catch {
3077
+ return undefined
3078
+ }
3079
+ return `${q}&.tally=task.status`
3080
+ }
3081
+ export let boardTallyName = (e: Ent) => `tally:${e.eid}`
3082
+
3083
+ // The board's status counts as the server answers them, or undefined until it
3084
+ // has. Undefined is NOT zero: a tile paints no stats rather than four wrong
3085
+ // ones (the rail's Asks tile showed 0/0/0/0 while the sub held 62 rows). Read
3086
+ // during a render, so the signals it touches wake the tile when the tally moves.
3087
+ export let boardTally = (e: Ent): Record<string, number> | undefined => {
3088
+ let line = boardTallyLine(e)
3089
+ if (line == null) return undefined
3090
+ if (!line) return {}
3091
+ let t = aggRead(boardTallyName(e))
3092
+ return t?.live ? t.map : undefined
3093
+ }
3094
+
3095
+ type Folded = { eid: string; statuses: string }
3096
+ // The fold row for a (client, board) — a unique (client, board) pair, so the two
3097
+ // eid EQUALITIES the refs index answers narrow to ≤1 row. Resolved LOCALLY over
3098
+ // the rows the tab's client sub streams (held by the app — a wire sub per
3099
+ // board visited would accumulate, T-21490); membership wakes the face, and the
3100
+ // live `statuses` field rides the fold's own row signal, so a collapse/expand
3101
+ // edit wakes the face too without re-testing the whole cache.
3102
+ export let foldFor = (client: string, board: string): Folded | undefined => {
3103
+ let eid = localEids([
3104
+ eq('fold', 'client', client),
3105
+ eq('fold', 'board', board),
3106
+ ]).value[0]
3107
+ if (!eid) return undefined
3108
+ let f = row(eid).value?.fold
3109
+ return f && { eid, statuses: String(f.statuses ?? '') }
3110
+ }
3111
+
3112
+ // The canvas working set: the carded pins on ONE canvas, scoped to it through
3113
+ // the query door so opening a canvas reads its own contents rather than
3114
+ // trusting the whole cache (T-18103) — under a partial cache a pin outside the
3115
+ // loaded set still counts, where a scan silently dropped it.
3116
+ //
3117
+ // The projection here is not about BYTES — `pinned()` builds a whole `Pinned`
3118
+ // out of each row and callers read the lot back off it (topZ, Run's spawn box,
3119
+ // pinsOn's own canvas), so every column of both components must ride. It is
3120
+ // about the WAKE signal: a change to any projected column re-fires the LIST —
3121
+ // the same rows the old refreshPins re-published — except `z`, marked VOLATILE,
3122
+ // whose value rides along (seeding pinZ) while a z-bump on every toFront
3123
+ // re-fires nothing, the raise binding straight to pinZ instead.
3124
+ //
3125
+ // So it is DERIVED from the vocabulary rather than listed: a pin column added
3126
+ // to types.ts rides automatically, where a hand-kept list would omit it and
3127
+ // leave a column nobody can read (M-17871 — one list, zero further edits). This
3128
+ // matters more now that a projected query rides a real SERVER sub (D-22567 §3):
3129
+ // the projected row is all a late-arriving pin has.
3130
+ let whole = (comp: string, volatile: string[] = []): Field[] =>
3131
+ Object.keys(comps[comp] ?? {}).map((prop) => ({
3132
+ comp,
3133
+ prop,
3134
+ wake: !volatile.includes(prop),
3135
+ }))
3136
+ // Read when asked and kept while the same vocabulary holds: learn() replaces
3137
+ // the tables, and a list built before it would project no columns.
3138
+ let pinFields = (() => {
3139
+ let seen: typeof comps | undefined
3140
+ let fields: Field[]
3141
+ return () => {
3142
+ if (seen != comps) {
3143
+ seen = comps
3144
+ fields = [...whole('pin', ['z']), ...whole('card')]
3145
+ }
3146
+ return fields
3147
+ }
3148
+ })()
3149
+ export let pinsOn = (canvas: string): Pred[] => [
3150
+ eq('pin', 'canvas', canvas),
3151
+ has('card'),
3152
+ { comp: '', prop: '', op: PROJECT, value: '', fields: pinFields() },
3153
+ ]
3154
+
3155
+ export let pinned = (canvas: string): Pinned[] =>
3156
+ (!canvas ? [] : queryEids(pinsOn(canvas)).value)
3157
+ .map((eid) => [eid, paint.peek()[eid]] as const)
3158
+ .filter((x): x is readonly [string, Comps] => !!x[1]?.pin && !!x[1].card)
3159
+ .map(([eid, r]) => ({
3160
+ ...r.pin!,
3161
+ // The cache key IS the identity: a pin cast from another client
3162
+ // carries no eid inside its comp, and a Pinned without one aims
3163
+ // every raise/drag write at eid undefined (T-7437).
3164
+ eid,
3165
+ target: r.card!.target,
3166
+ view: r.card!.view,
3167
+ }))
3168
+ .sort((a, b) => (a.z - b.z) || (a.eid < b.eid ? -1 : 1))
3169
+
3170
+ // Who points HERE, and via what, over the LOCAL working set. This door must
3171
+ // never dial from an imperative read or a per-entry render (T-37033). Open
3172
+ // cards and transcript roots hold useBacklinks for completeness; the session
3173
+ // entry sub supplies call/result rows. Layout gestures read their held rows.
3174
+ // linksVia rides each referrer's row so retargeting wakes the face too.
3175
+ export type Backlink = { from: string; via: string }
3176
+ export let linksVia = (from: string, target: string): Backlink[] => {
3177
+ let r = row(from).value
3178
+ return !r ? [] : vocab.refProps()
3179
+ .filter(([c, p]) =>
3180
+ (r[c as keyof typeof r] as Record<string, unknown>)?.[p] == target
3181
+ )
3182
+ .map(([c, p]) => ({ from, via: `${c}.${p}` }))
3183
+ }
3184
+ export let backlinks = (target: string): Backlink[] =>
3185
+ localEids([refsTo(target)]).value.flatMap((from) => linksVia(from, target))
3186
+
3187
+ // The task a session is ON: the newest task it holds a claim over, else its
3188
+ // managed request. The claims aimed at a session are an eid EQUALITY the refs
3189
+ // index answers in O(result); membership is the only reactive edge (at
3190
+ // is server-stamped at the claim's birth, never edited, and a release removes
3191
+ // the row), so the face wakes exactly when its session gains or loses a claimed
3192
+ // task — no bespoke per-session set to keep (T-17064). A view that draws it
3193
+ // holds the query (useJob).
3194
+ export let jobQuery = (session: string): Pred[] => [
3195
+ eq('claim', 'session', session),
3196
+ has('task'),
3197
+ ]
3198
+ export let jobOf = (e: Ent): string | null => {
3199
+ let g = paint.peek()
3200
+ return queryEids(jobQuery(e.eid)).value
3201
+ .toSorted((a, b) =>
3202
+ String(g[b]?.claim?.at ?? '').localeCompare(
3203
+ String(g[a]?.claim?.at ?? ''),
3204
+ )
3205
+ )[0] ?? null
3206
+ }
3207
+
3208
+ // The edges that hold an entity FROM ABOVE — every edge whose child
3209
+ // is this eid that a page lists (`listed`). refs/kids read downward; this is
3210
+ // the climb back up, how a task names the parents that contain or require it.
3211
+ export let parents = (eid: string) => childRelations(eid).value.filter(listed)
3212
+
3213
+ // A board query carries refs as TEXT, outside the schema's eid columns, so a
3214
+ // CONTAINS over `board.query` names every board mentioning this target. The pred
3215
+ // anchors on the boards (byComp) and screens by substring — the same `.includes`
3216
+ // the scan used, now through the one query door, so the target face watches only
3217
+ // board rows that gain or lose its eid. Local-only: rendered board lists
3218
+ // hold useBoardsOver (or the equivalent useQueryResult for read state).
3219
+ export let boardsOver = (target: string): string[] =>
3220
+ localEids([contains('board', 'query', target)]).value
3221
+
3222
+ // The highest stacking order on a canvas — a raised card gets topZ + 1. The
3223
+ // members come from the one canvas-scoped query (asleep on z-bumps), and each
3224
+ // pin's CURRENT z is read fresh off the cache: a z-only patch updates the row
3225
+ // in place without waking the list, so the max here is always live. A nullish
3226
+ // canvas names no query and matches nothing, the floor 0.
3227
+ export let topZ = (canvas: string) =>
3228
+ Math.max(
3229
+ 0,
3230
+ ...(!canvas ? [] : queryEids(pinsOn(canvas)).value
3231
+ .map((eid) => paint.peek()[eid]?.pin?.z ?? 0)),
3232
+ )
3233
+
3234
+ // Any interaction pulls a card to the front. Reads the pins fresh from the
3235
+ // cache, so a burst of events (a scroll's worth of wheels) raises once.
3236
+ // The card must clear every OTHER pin, not merely match the canvas top —
3237
+ // a tie at the top (fresh pins all land at 0) still raises.
3238
+ export let toFront = (pin: string) => {
3239
+ let p = paint.peek()[pin]?.pin
3240
+ if (!p) return
3241
+ let top = Math.max(
3242
+ -1,
3243
+ ...queryEids(pinsOn(p.canvas)).value
3244
+ .filter((eid) => eid != pin)
3245
+ .map((eid) => paint.peek()[eid]?.pin?.z ?? -1),
3246
+ )
3247
+ if (p.z <= top) mutate({ eid: pin, name: 'pin', comp: { z: top + 1 } })
3248
+ }
3249
+
3250
+ // Screen px → plane coords, through the camera over the given canvas rect.
3251
+ export let toPlane = (clientX: number, clientY: number, rect: DOMRect) => {
3252
+ let { x, y, zoom, w, h } = camera.value
3253
+ return {
3254
+ x: (clientX - rect.left - (w / 2 - x * zoom)) / zoom,
3255
+ y: (clientY - rect.top - (h / 2 - y * zoom)) / zoom,
3256
+ }
3257
+ }
3258
+
3259
+ // This client's camera over one canvas, if it exists yet — resolved LOCALLY
3260
+ // (both {eid} columns anchor the derived index) over the rows the tab's client
3261
+ // sub streams (T-21490), so a partial cache still finds the row the graph holds
3262
+ // without a wire sub per canvas visited.
3263
+ export let myCamera = (client: string, canvas: string) =>
3264
+ localEids([
3265
+ eq('camera', 'client', client),
3266
+ eq('camera', 'canvas', canvas),
3267
+ ])
3268
+ .value
3269
+ .map((eid) => paint.peek()[eid]?.camera)
3270
+ .find((c) => !!c)
3271
+
3272
+ // This client's cursor — WHERE it's looking, one row per client (T-12788).
3273
+ // Resolved LOCALLY (the client column anchors the derived unique index) over
3274
+ // the rows the tab's client sub streams (T-21490), never a whole-cache scan, so
3275
+ // mark()'s idempotency check and ui_state's tab report stay O(1) and the hot
3276
+ // render path never pays (M-17862). The cursor is UPDATE-ONLY: it is published,
3277
+ // never read back to drive navigation (nav.tsx), so no reader here yanks a tab.
3278
+ export let myCursor = (client: string) =>
3279
+ localEids([eq('cursor', 'client', client)])
3280
+ .value
3281
+ .map((eid) => row(eid).value?.cursor)
3282
+ .find((c) => !!c)
3283
+
3284
+ // Who this browser is: a client entity, its uuid minted into localStorage on
3285
+ // first visit. The db rows appear when the camera first persists.
3286
+ export let clientId = () => {
3287
+ let id = localStorage.getItem(storageKey('tasks-client'))
3288
+ if (!id) {
3289
+ id = uuid()
3290
+ localStorage.setItem(storageKey('tasks-client'), id)
3291
+ }
3292
+ return id
3293
+ }
3294
+
3295
+ // This tab's client where it has screen state (a canvas-capable browser); the
3296
+ // terminal has no client identity.
3297
+ export let myClient = (): string | null => {
3298
+ if (!capable('canvas')) return null
3299
+ try {
3300
+ return clientId()
3301
+ } catch {
3302
+ return null
3303
+ }
3304
+ }
3305
+
3306
+ // This tab's camera over the canvas it's viewing: x/y is the viewport CENTER
3307
+ // in plane coords, w/h the viewport size in screen px. Shared so drags can
3308
+ // convert screen px into plane px.
3309
+ export let camera = signal({ x: 0, y: 0, zoom: 1, w: 0, h: 0 })
3310
+
3311
+ // The vim mode this tab is in — per-tab UI state, never synced. Hotkeys
3312
+ // (space, 0, …) only fire in normal mode; the statusbar owns transitions.
3313
+ // visual is derived: a live selection outside a text input.
3314
+ export let mode = signal<'normal' | 'insert' | 'command' | 'visual'>('normal')
3315
+
3316
+ // Whether the search palette is up. Shell state so a hot swap of the
3317
+ // component graph can't shut it mid-search (Search.tsx owns the rest).
3318
+ export let searchOpen = signal(false)
3319
+
3320
+ // The one entity a pressed link shows over the page (components/Peek.tsx).
3321
+ // Shell state for the same reason as searchOpen: a hot swap must not shut
3322
+ // what the person is reading or typing into. `at` is the page it floats over,
3323
+ // `from` the link pressed, and `left`, `top`, `w`, `h` where it was moved or
3324
+ // sized to.
3325
+ export type Peeked = {
3326
+ eid: string
3327
+ at: string
3328
+ from?: Element
3329
+ left?: number
3330
+ top?: number
3331
+ w?: number
3332
+ h?: number
3333
+ }
3334
+ export let peeked = signal<Peeked | null>(null)