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