@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/query.ts ADDED
@@ -0,0 +1,1113 @@
1
+ // The FILTER grammar — dot-params in URL query-param form. One parser for
2
+ // every reader: a board's saved query, `task list`, MCP task_list, and
3
+ // the search box. (Writes keep the plain `.comp.prop=value` setter grammar in
4
+ // client.ts — a setter's comma is a literal comma; only filters interpret
5
+ // value forms.)
6
+ //
7
+ // .status=open&.priority<=1&.domain=Ops,Eng
8
+ // runner exit .status=done .updated.at=today (search-style mix)
9
+ //
10
+ // .prop=v equals (string-compared, like everything on the wire)
11
+ // .prop=a,b,c any of
12
+ // .prop=1..5 range, inclusive (1...5 excludes the end; ISO dates
13
+ // compare fine lexicographically)
14
+ // !prop null / absent
15
+ // .prop present (including an empty string)
16
+ // ?prop carried beside the filter, never filtered on
17
+ // .prop!=v not — negates any value form above
18
+ // .prop~=v contains, case-insensitive
19
+ // .prop~= present — an empty needle asks for the COLUMN, the same
20
+ // thing `.prop` asks (never "every row contains ''")
21
+ // .prop<v <=v >v >=v comparisons — a number column compares numerically,
22
+ // everything else as text (an ISO stamp compares right as
23
+ // text); an operand the column's type cannot hold selects
24
+ // nothing, the same mismatch @yaks/sql declines to compile
25
+ //
26
+ // .limit=200 a WINDOW: 200 matches, not the whole set
27
+ // .after=13882 continue that window past one entity, named by its number
28
+ // or eid — the next page, in whatever order was asked for
29
+ //
30
+ // Bare words are TEXT preds — FTS5 terms over the doc (title or body), with a
31
+ // trailing `*` for token-prefix matching; "quoted words" stay one phrase pred.
32
+ // Separators are '&' and
33
+ // whitespace both: every term stands alone; quote multiword values
34
+ // (.title~="two words"). Single/double quotes and escaping are shared grammar.
35
+ //
36
+ // When the ROW value is an ISO timestamp, the filter value may be a time
37
+ // PHRASE (see span): today, yesterday, tomorrow, now, this|last|next
38
+ // minute|hour|day|week|month|year, "5 minutes ago", "in 2 days" (short
39
+ // units too: in 60m, after 8h), a clock time on today or a named day
40
+ // (9am, 9:30pm, 14:00, noon, "9am tomorrow"), a date, or a full stamp
41
+ // (2026-07-25T09:00) — with '-'/'_' glue where quoting is awkward:
42
+ // 1-hour-ago. A phrase names a
43
+ // RANGE and the op picks its edge: = within, >= from its start, <= until
44
+ // its end, > strictly after, < strictly before. So .updated.at=today is
45
+ // midnight-to-midnight, .updated.at>="1 hour ago" is the last hour.
46
+ // Schedulers want one moment instead — that's instant(), below span.
47
+ //
48
+ // Names resolve the way the host resolves them, through @yaks/vocab `aim`: a
49
+ // property is named with its component (`.task.status=open`), and a name by
50
+ // itself tests the component: `!proposed` means absent, `.proposed` present.
51
+ //
52
+ // References are ordinary props: `.filed.assignee=jeff`; the VALUE resolves
53
+ // like any id (alias, T-3, raw eid) at whichever door or evaluator holds the
54
+ // graph (resolveRefs). A path is an N-hop CHAIN of `comp.prop` pairs: each
55
+ // `{eid}` deref moves to the target entity and the next pair reads there, so
56
+ // `.comment.target.doc.title~=foo` walks comment→target then tests doc.title,
57
+ // arbitrarily deep.
58
+ import { IdError } from './types.js'
59
+ import { anyRef, isRef, parseProp, type Prop, typed } from './props.js'
60
+ import { edges, kindOrder, kindWord, lazy, statusOf, vocab } from './types.js'
61
+ import { Unknown, unknownWord, valueless } from '@yaks/vocab'
62
+ import { term as ftsTerm } from '@yaks/fts'
63
+ import { type Check, check } from '@yaks/match'
64
+ import { literals, type Tag, tagOf } from '@yaks/sql'
65
+ import {
66
+ bare,
67
+ type Clause,
68
+ compares,
69
+ parse,
70
+ scalar,
71
+ type Value,
72
+ } from '@yaks/query'
73
+ import { frozen } from '@yaks/fp'
74
+ export { ftsTerm }
75
+ export { WALK_DEPTH, WALK_LIMIT } from '@yaks/query'
76
+
77
+ // One rung of a path predicate: a component's column read on the entity this
78
+ // hop lands on. Every hop but the last is an `{eid}` deref; the last is the
79
+ // leaf tested against op/value.
80
+ export type Hop = { comp: string; prop: string }
81
+
82
+ export type Pred = {
83
+ comp: string
84
+ prop: string
85
+ op: string
86
+ value: string
87
+ /** Structured property operand; value remains its display text. */
88
+ operand?: Value
89
+ // A path predicate's chain: deref the reference at `comp.prop`, then follow
90
+ // each hop in `at` in turn — every hop but the LAST is another `{eid}` deref
91
+ // — and test the final hop's column against op/value. A single-element `at`
92
+ // is one deref: `.comment.target.doc.title` derefs comment.target and tests
93
+ // the target's doc.title.
94
+ at?: Hop[]
95
+ // What the LEAF column is, so the value rules (@yaks/match check()) compare a
96
+ // number as a number and read a time phrase only where a time is stored. The
97
+ // binder stamps it because only the binder holds the asking store's own
98
+ // vocabulary; a pred built by hand is typed against the platform's.
99
+ tag?: Tag
100
+ // An OR (`.a=1|.b=2&.c=3`, op OR): alternatives, each an AND list, and no
101
+ // comp/prop/value of its own. Only filters live inside — a directive (order,
102
+ // fields, tally, edges, window) rides the top level, where every reader of
103
+ // the list looks for it.
104
+ alts?: Pred[][]
105
+ // A REVERSE hop: the entities whose `rev.comp.rev.prop` reference points BACK
106
+ // at this one (`.comments` = the comments whose comment.target is me). The
107
+ // mirror of `at` — one-to-many instead of one deref — so it carries the
108
+ // existential/count semantics `at` never needs. See Rev.
109
+ rev?: Rev
110
+ // A MULTI-COLUMN reverse-union: match any entity that references `value`
111
+ // through SOME `{eid}` column — the backlinks of `value`, the union of every
112
+ // reverse lookup the vocabulary implies (`.refs=T-3`). comp/prop stay empty:
113
+ // the union spans every reference property, so anchor unions the reverse
114
+ // index and sql.ts unions the ref tables. `.comment.target=T-3` is one
115
+ // column of this.
116
+ refs?: boolean
117
+ // An AGGREGATE projection rather than a filter: `agg` names the reduction
118
+ // over this pred's column — `distinct` its non-empty values, `tally` each
119
+ // value's count. `count` reduces the SELECTION itself, so it names no column
120
+ // and leaves comp/prop empty. op is AGG, so matchQuery passes it through (the
121
+ // filter part selects the universe); aggOf()/tally()/aggregateSql() read it.
122
+ agg?: 'distinct' | 'tally' | 'count'
123
+ // A FIELD PROJECTION rather than a filter: the columns each result row carries
124
+ // beyond its eid (`.fields=pin.x,pin.z~`), so a partial-cache subscription
125
+ // reads live values without holding the whole graph. op is PROJECT, matchQuery
126
+ // passes it through; fieldsOf() reads it and select() (sql.ts) selects the
127
+ // columns. comp/prop stay empty — the columns live in `fields`, each carrying
128
+ // its own `wake` (a `~`-marked column is projected but excluded from the
129
+ // change-signal, so a churny value like a pin's z delivers yet never re-fires).
130
+ fields?: Field[]
131
+ // A WINDOW rather than a filter: `.limit=200` bounds the answer to a prefix,
132
+ // `.after=<id>` continues it past an entity. op is WINDOW, so matchQuery
133
+ // passes it through (the filter part selects the whole set) and windowOf()
134
+ // reads the bound; comp/prop stay empty. A window states a SIZE, never a
135
+ // membership — which is why a reply that carries one also states the total it
136
+ // is a prefix of.
137
+ win?: Win
138
+ // A WALK rather than a column read: `.requires[<=3]->T-42` selects
139
+ // the entities that reach `value` through at most `depth` hops of one step —
140
+ // an edge type, or a reference column (`via`) — and `<-` walks the other way.
141
+ // op is REACHES. No bracket means depth-free with a WALK_LIMIT row valve;
142
+ // only an explicit [<=N] brings the hop cap back.
143
+ reach?: Reach
144
+ }
145
+
146
+ // A window: how many of the selection to answer with, and where to continue.
147
+ // Both optional — `.limit=` alone is the first page, `.after=` alone continues
148
+ // an unbounded read below a cursor. A window states a SIZE, never a sequence:
149
+ // with no `.order` the sequence is spine order; with one (`.order=hot`,
150
+ // `.order=similar`) the asked-for order
151
+ // survives and `after` names the entity to continue past IN THAT ORDER.
152
+ // One cursor spelling — the entity's number or eid — serves
153
+ // every ordering, so a caller pages without learning the order key.
154
+ export type Win = { limit?: number; after?: number | string }
155
+
156
+ // A window over a RANKING (`.order=hot`, `.order=similar`) rather than over the
157
+ // spine. An explicit order SURVIVES a window — a window says how much of a
158
+ // sequence to answer with, never which sequence — so the cursor is the anchor's
159
+ // place in the RANKING, not a num to compare against. The cursor spelling never
160
+ // changes: `.after=<num>` names an entity, and each evaluator derives where that
161
+ // entity sits in the order it was asked for (the same rule @yaks/sql compiles as
162
+ // a keyset and @yaks/match answers in memory). An anchor the ranking does not
163
+ // hold restarts from the front, which is what a first page already is.
164
+ export let pageRanked = <T extends { num?: number; eid?: string }>(
165
+ rows: T[],
166
+ win: Win,
167
+ ): T[] => {
168
+ let at = win.after == null
169
+ ? -1
170
+ : rows.findIndex((r) =>
171
+ typeof win.after == 'number' ? r.num == win.after : r.eid == win.after
172
+ )
173
+ let rest = rows.slice(at + 1)
174
+ return win.limit == null ? rest : rest.slice(0, win.limit)
175
+ }
176
+
177
+ // One projected column: which component column a result row carries, and whether
178
+ // a change to it WAKES the subscription. `wake: false` (a `~`-suffixed field) is
179
+ // VOLATILE — its value still rides in the row, but a live layer excludes it from
180
+ // the change-signal it wakes on. Membership always wakes; volatility only mutes
181
+ // this one column's own edits. A column reached through references
182
+ // (`.fields=_change.tx._tx.at`) is the row's own reference column, `comp.prop`,
183
+ // with the hops beyond it in `at`: the row carries the reference, and the far
184
+ // values ride beside it as peers.
185
+ export type Field = { comp: string; prop: string; wake: boolean; at?: Hop[] }
186
+
187
+ // A reverse hop resolved: the child component + ref column whose value the
188
+ // parent's eid must equal, and how the many children collapse to a yes/no.
189
+ // Existential (the default): keep the parent if ANY child matches `preds` —
190
+ // `[]` is "any child at all". `not` flips it to NOT EXISTS, which is NONE, and
191
+ // with a negated leaf it is ALL by De Morgan (`.comments!.status!=done` = no
192
+ // child is un-done = every child is done). `count` instead compares the NUMBER
193
+ // of children to the outer pred's op/value (`.comments>=5`), ignoring preds.
194
+ export type Rev = {
195
+ comp: string
196
+ prop: string
197
+ // the association's own name (`comments`), the spelling a line writes back
198
+ name: string
199
+ preds: Pred[]
200
+ not: boolean
201
+ count?: boolean
202
+ }
203
+
204
+ // A path's leaf — the far column op/value tests — is the last hop; a plain
205
+ // pred is its own leaf. Every reader resolving the tested column (its type,
206
+ // ref-resolution, quarantine reveal) reads THROUGH this, never `p.comp`.
207
+ export let leafOf = (p: Pred): Hop => p.at ? p.at[p.at.length - 1] : p
208
+
209
+ /** A property predicate's structured operand, including hand-built scalars. */
210
+ export let operandOf = (p: Pred): Value | undefined =>
211
+ p.prop && ['', '!', '~', '<', '<=', '>', '>='].includes(p.op)
212
+ ? p.operand ?? scalar(p.value)
213
+ : undefined
214
+
215
+ // What a pred evaluates against: an entity's components, merged — the
216
+ // shape of both a live-cache row and a client Row's `.comps`.
217
+ export type Comps = Record<string, Record<string, unknown> | undefined>
218
+
219
+ // One token — '.filed.priority<=1', '.filed.domain=Ops,Eng' — to a Pred; null if the
220
+ // string isn't a dot-param at all.
221
+ export let EXISTS = 'exists'
222
+ // `?loan` asks for a component WITHOUT filtering on it: an optional
223
+ // presence, requested. It selects nothing and screens nothing — `.book` says
224
+ // which entities the answer is about, `.book&?loan` says the answer should
225
+ // carry their loans too, where they have one. A door that projects reads it
226
+ // (workers/yak/graph.ts); every evaluator lets it through like a ranking.
227
+ export let WANT = 'want'
228
+ let OPS: Record<string, string> = {
229
+ '=': '',
230
+ '!': EXISTS,
231
+ '!=': '!',
232
+ '~=': '~',
233
+ '<': '<',
234
+ '<=': '<=',
235
+ '>': '>',
236
+ '>=': '>=',
237
+ }
238
+
239
+ // `.order=hot`, `.order=search`, and `.order=similar` are rankings, not
240
+ // filters: matchQuery lets them through, adopt() ignores them, and orderOf()
241
+ // hands the value to whoever sorts. The server answers a window of words best
242
+ // match first (@yaks/fts); a filter with no words stays newest first.
243
+ // Similar asks the evaluator that owns the embedding service for
244
+ // vector-neighbor rank.
245
+ export let ORDER = 'order'
246
+ export let RANKS = ['hot', 'search', 'similar']
247
+
248
+ export let orderOf = (preds: Pred[]) => preds.find((p) => p.op == ORDER)?.value
249
+
250
+ // `.near=T-3` names the entity whose doc supplies a similarity query. It is a
251
+ // ranking input beside ORDER, never graph membership: the evaluator resolves
252
+ // it and projects transient rank onto the selected neighbors.
253
+ export let NEAR = 'near'
254
+ export let nearOf = (preds: Pred[]) => preds.find((p) => p.op == NEAR)?.value
255
+
256
+ // An AGGREGATE directive rides the pred list like ORDER —
257
+ // `.distinct=filed.domain`, `.tally=filed.domain`, `.count`. matchQuery passes AGG through (true), so the OTHER
258
+ // preds select the universe the aggregate reduces; a reader pulls the projection
259
+ // with aggOf() and computes it with tally() (or aggregateSql server-side).
260
+ export let AGG = 'agg'
261
+
262
+ // `count` names no column, so its `at` is the empty hop — a reader branches on
263
+ // `op`, never on whether `at` is populated.
264
+ export let aggOf = (
265
+ preds: Pred[],
266
+ ): { op: 'distinct' | 'tally' | 'count'; at: Hop } | undefined => {
267
+ let p = preds.find((p) => p.op == AGG)
268
+ return p?.agg ? { op: p.agg, at: { comp: p.comp, prop: p.prop } } : undefined
269
+ }
270
+
271
+ // A WINDOW directive rides the pred list like ORDER/AGG/PROJECT —
272
+ // `.limit=200&.after=13882`. matchQuery passes WINDOW through (true), so the
273
+ // OTHER preds select the whole membership and the window only bounds how much
274
+ // of it a door answers with.
275
+ export let WINDOW = 'window'
276
+
277
+ // The window a query asks for, folded from every WINDOW pred it carries — so
278
+ // `.limit=50&.after=900` reads as one bound however it was spelled, and a later
279
+ // pred wins a repeated one. `{}` when the query names no window: a door reads
280
+ // `limit == null` as "the whole answer", which is what keeps an unwindowed
281
+ // query's frame semantics exactly what they were.
282
+ export let windowOf = (preds: Pred[]): Win => {
283
+ let out: Win = {}
284
+ for (let p of preds) {
285
+ if (p.op != WINDOW || !p.win) continue
286
+ if (p.win.limit != null) out.limit = p.win.limit
287
+ if (p.win.after != null) out.after = p.win.after
288
+ }
289
+ return out
290
+ }
291
+
292
+ // The components a pred list READS — the dirty test an aggregate subscription
293
+ // applies to a committed batch: a change dirties the aggregate iff it touches a
294
+ // component the selection or the aggregated column reads. `null` means "every
295
+ // batch dirties it": a path hop, a reverse hop or a `.refs` union reads columns
296
+ // on OTHER entities, which no comp-name overlap can name, so those recompute
297
+ // unconditionally rather than answer stale. The spine (`entity`) and
298
+ // `quarantined` are the caller's to add — every query reads them.
299
+ export let predComps = (preds: Pred[]): Set<string> | null => {
300
+ let out = new Set<string>()
301
+ for (let p of preds) {
302
+ if (p.op == OR) {
303
+ for (let alt of p.alts!) {
304
+ let inner = predComps(alt)
305
+ if (!inner) return null
306
+ for (let c of inner) out.add(c)
307
+ }
308
+ continue
309
+ }
310
+ if (p.refs || p.at || p.rev) return null
311
+ if (p.op == ORDER && p.value == 'hot') return null
312
+ // A column order reads its column: a write to it can move a row across a
313
+ // window's edge. One through a reference reads another entity.
314
+ if (p.op == ORDER && !RANKS.includes(p.value)) {
315
+ let path = p.value.replace(/^-/, '').split('.')
316
+ if (path.length > 2) return null
317
+ out.add(path[0])
318
+ }
319
+ if (
320
+ p.op == NEVER || p.op == ORDER || p.op == NEAR || p.op == PROJECT
321
+ ) continue
322
+ if (p.op == WINDOW) continue
323
+ // `.count` aggregates the selection, naming no column of its own.
324
+ if (p.op == AGG && !p.comp) continue
325
+ if (!p.comp) return null
326
+ // task.status is virtual: a filter/window/aggregate over it reads all four
327
+ // lifecycle facets, not only the task row that owns the public spelling.
328
+ // Without this expansion a claim or terminal mark changes the answer but
329
+ // never dirties a standing tally or exact window.
330
+ if (p.comp == 'task' && p.prop == 'status') {
331
+ for (let comp of ['task', 'completed', 'cancelled', 'claim']) {
332
+ out.add(comp)
333
+ }
334
+ } else out.add(p.comp)
335
+ }
336
+ return out
337
+ }
338
+
339
+ // The aggregate itself, over the rows a query matched: value → count, empties
340
+ // (null and '') dropped exactly as the census always has. Distinct values are
341
+ // its keys; a reader that wants them sorted takes `[...tally(rows, at).keys()]`.
342
+ export let tally = (
343
+ rows: Iterable<Comps>,
344
+ at: Hop,
345
+ ): Map<string, number> => {
346
+ let m = new Map<string, number>()
347
+ for (let c of rows) {
348
+ // read() so a DERIVED column (task.status) tallies its computed value, not
349
+ // the absent stored one — board column counts stay honest (D-24102).
350
+ let v = read(c, at.comp, at.prop)
351
+ if (v == null || v === '') continue
352
+ let k = String(v)
353
+ m.set(k, (m.get(k) ?? 0) + 1)
354
+ }
355
+ return m
356
+ }
357
+
358
+ // The census in one line: the sorted distinct values of a column over `rows`.
359
+ export let distinctValues = (rows: Iterable<Comps>, at: Hop): string[] =>
360
+ [...tally(rows, at).keys()].sort()
361
+
362
+ // A FIELD PROJECTION directive rides the pred list like AGG/ORDER —
363
+ // `.fields=pin.x,pin.z~`. matchQuery passes PROJECT through (true), so the OTHER
364
+ // preds select the membership; fieldsOf() reads which columns each row carries
365
+ // (and which are volatile), and select() (sql.ts) selects them.
366
+ export let PROJECT = 'project'
367
+
368
+ // The projected columns of a query, or undefined when it names none — a plain
369
+ // membership query. The waking subset is `f.wake`; a caller that only cares which
370
+ // changes should re-fire reads `fields.filter((f) => f.wake)`.
371
+ export let fieldsOf = (preds: Pred[]): Field[] | undefined =>
372
+ preds.find((p) => p.op == PROJECT)?.fields
373
+
374
+ // A WALK pred — `.requires[<=3]->T-42` — is a real filter, not a rider: it
375
+ // SELECTS a transitive closure over one step, optionally capped by hops.
376
+ // sql.ts compiles it to a recursive CTE over the indexed dep table (or the
377
+ // reference column); the JS matcher answers it from a `walk` that resolves the
378
+ // same closure once per query rather than per row.
379
+ export let REACHES = 'reaches'
380
+
381
+ // The walk's step and shape: `type` is the edge type walked, or the raw path of
382
+ // a reference column, which `via` then names; `dir` is the arrow — `->` the
383
+ // candidate reaches the target, `<-` the target reaches the candidate.
384
+ export type Reach = {
385
+ type: string
386
+ depth?: number
387
+ dir: '->' | '<-'
388
+ via?: Hop
389
+ }
390
+
391
+ // The traversal closures a pred list asks for, deduped — what a door precomputes
392
+ // before matching so the walk happens once, not per candidate row.
393
+ export let reachesOf = (preds: Pred[]): Pred[] =>
394
+ preds.filter((p) => p.op == REACHES)
395
+
396
+ // Who reaches a walk's target: the eids within `depth` steps of `value`, along
397
+ // the arrow. One per query — every row then tests with a Set lookup.
398
+ export type Walk = (reach: Reach, target: string) => Set<string>
399
+
400
+ // A query addresses the LAZY entry partition when it names a component the
401
+ // kernel declares `lazy` — `.entry.session`, `.entry`. Those entities are omitted from the root
402
+ // snapshot, so a door reaches them only when the query OPTS IN by naming the
403
+ // partition; that is an explicit scope, not a silent boundary. Every query
404
+ // door reads this one predicate to decide whether entries are in its universe.
405
+ //
406
+ // A component-ABSENCE assertion (`p.prop == '' && p.op == ''`) does not opt in:
407
+ // it selects eager entities that LACK the comp, the opposite of wanting entries.
408
+ // kindPreds emits one per kindOrder-earlier comp, so `kind=comment` carries a
409
+ // synthetic `.entry absent` — without this guard it flipped every eager kind
410
+ // past `entry` into entry-partition mode and orderedEntries dropped every row.
411
+ // A positive reference (`.entry` EXISTS, `.entry.session=S-1`) still scopes in.
412
+ export let namesLazy = (preds: Pred[]) =>
413
+ preds.some((p) => lazy(p.comp) && !(p.prop == '' && p.op == ''))
414
+
415
+ // The sessions an entry query is scoped to — the eids of every scalar
416
+ // `.entry.session=` equality (a comma list is any-of). A range cannot name
417
+ // keyed partitions, so it stays unscoped and the bounded scan refines it.
418
+ // resolveRefs has already turned S-16765 into its eid by the time a door asks.
419
+ export let scopedSessions = (preds: Pred[]): string[] =>
420
+ preds
421
+ .filter((p) => p.comp == 'entry' && p.prop == 'session' && p.op == '')
422
+ .flatMap((p) => literals(operandOf(p) ?? null) ?? [])
423
+ .filter(Boolean)
424
+
425
+ // Quarantine is invisible by default, but mentioning the facet is the
426
+ // deliberate extra step that lets a list ask about it. This stays beside
427
+ // matchQuery rather than inside it: writers and keyed internals still need to
428
+ // reason about a row without silently changing the question they asked.
429
+ export let reveals = (preds: Pred[]) =>
430
+ preds.some((p) => p.comp == 'quarantined' || leafOf(p).comp == 'quarantined')
431
+
432
+ export let listed = (comps: Comps, preds: Pred[]) =>
433
+ !comps.quarantined || reveals(preds)
434
+
435
+ // A `blob` is content-addressed STORAGE wearing an entity's clothes: every doc
436
+ // body lands as one, and an attachment's bytes as another, so
437
+ // the store's own rows sit in the spine a filter selects from. They carry no
438
+ // doc and no kind, so a listing that catches one renders nothing for it — which
439
+ // is what a person saw (C-32498 item 4). Naming the component is the deliberate
440
+ // opt-in, the same step `quarantined` asks for.
441
+ //
442
+ // `image` names them too: dimensions belong to the content (its row keys on
443
+ // artifact), so a filter that asks for one can be asking for nothing else,
444
+ // and a photo wall reading what its pictures measure should not have to say
445
+ // `.artifact` to be allowed the answer (C-32706 item 1).
446
+ let ON_BLOB = ['artifact', 'image']
447
+
448
+ export let namesBlobs = (preds: Pred[]) =>
449
+ preds.some((p) =>
450
+ ON_BLOB.includes(p.comp) || ON_BLOB.includes(leafOf(p).comp)
451
+ )
452
+
453
+ // Does this row belong in the answer a FILTER selects? The caller's own preds
454
+ // decided that; these are the two screens every listing carries beside them.
455
+ // `id=` addresses entities instead of selecting them, so it keeps `listed`
456
+ // alone — naming a blob's sha IS asking for it.
457
+ export let selected = (comps: Comps, preds: Pred[]) =>
458
+ listed(comps, preds) && (!comps.artifact || namesBlobs(preds))
459
+
460
+ // The pred list a COMPILED membership statement should carry: the caller's
461
+ // filter plus the universal screens a door otherwise applies in JS after the
462
+ // statement — quarantine and the store's blob rows (selected) and the lazy
463
+ // entry partition (namesLazy). All three are spelled as ordinary
464
+ // component-ABSENCE preds, so the existing compiler answers them from the same
465
+ // LEFT JOIN it gives any facet, and namesLazy's `.prop == '' && .op == ''`
466
+ // guard keeps the entry screen from reading as an opt-IN to the partition.
467
+ //
468
+ // Why it matters beyond tidiness: a JS filter that runs AFTER a statement's
469
+ // LIMIT under-fills the page, so a window can only be exact once the screens
470
+ // the answer depends on are inside the same statement.
471
+ let absent = (comp: string): Pred => ({ comp, prop: '', op: '', value: '' })
472
+ export let screened = (preds: Pred[], entries: boolean): Pred[] => [
473
+ ...preds,
474
+ ...reveals(preds) ? [] : [absent('quarantined')],
475
+ ...namesBlobs(preds) ? [] : [absent('artifact')],
476
+ ...entries || preds.some((p) => p.op == TEXT) ? [] : [absent('entry')],
477
+ ]
478
+
479
+ // kind=K as a filter, not a JS screen. kindOf is "the first kindOrder
480
+ // component present", so kind=K is K present AND every earlier component
481
+ // absent — a synthetic Pred[] the SQL compiler answers from the index, where
482
+ // a lone kind= otherwise built the whole 27 MB snapshot to screen it in JS.
483
+ // The absence clauses are what make it EXACT: an entity wearing both `memory`
484
+ // and `comment` is a comment (comment is earlier), so kind=memory must skip
485
+ // it — presence (`.memory`) cannot, and overcounts. null for a word naming
486
+ // no kind (kind=entity, a typo): the derived `entity` fallback is every
487
+ // kindOrder comp absent, and its only reader is the JS screen that stays.
488
+ export let kindPreds = (kind: string): Pred[] | null => {
489
+ let i = kindOrder.indexOf(kind)
490
+ if (i < 0) return null
491
+ return [
492
+ { comp: kind, prop: '', op: EXISTS, value: '' },
493
+ ...kindOrder.slice(0, i).map((c) => ({
494
+ comp: c,
495
+ prop: '',
496
+ op: '',
497
+ value: '',
498
+ })),
499
+ ]
500
+ }
501
+
502
+ // `.kind=memory` is a SCOPE, not a column: kind is derived (the first
503
+ // kindOrder component an entity wears), so it reads as the exact presence
504
+ // clauses kindPreds builds, as @yaks/sql reads it. kindWord folds the plural
505
+ // in (`.kind=projects` reads like `.kind=project`).
506
+ let kindScope = (value: string): Pred[] => {
507
+ let out = kindPreds(kindWord(value) ?? value)
508
+ if (!out) throw new Error(`no such kind: ${value || '(empty)'}`)
509
+ return out
510
+ }
511
+
512
+ // Time operands stay authored; the shared matcher resolves their phrases and
513
+ // literal scalars. Other property input sugar uses the same parser writes use.
514
+ let atom = (p: Prop, value: string): string => {
515
+ if (!value) return value
516
+ if (tagFor(p) == 'time') return value
517
+ if (tagFor(p) == 'eid') {
518
+ try {
519
+ return String(parseProp(p, value))
520
+ } catch {
521
+ return value // aliases need the evaluator's graph
522
+ }
523
+ }
524
+ return String(parseProp(p, value))
525
+ }
526
+
527
+ let mapValue = (value: Value, f: (raw: string) => string): Value =>
528
+ value.kind == 'list'
529
+ ? { ...value, items: value.items.map((v) => mapValue(v, f)) }
530
+ : value.kind == 'range'
531
+ ? { ...value, lo: mapValue(value.lo, f), hi: mapValue(value.hi, f) }
532
+ : { ...value, raw: f(value.raw) }
533
+
534
+ // Grammar belongs to @yaks/query. This pass binds its schema-free clauses to
535
+ // the fleet's routed predicates (also consumed by browser matching, reference
536
+ // resolution and partition screens). Never stringify a clause to parse it again.
537
+ let flatValue = (v: Value | null): string => {
538
+ if (!v) return ''
539
+ if (v.kind == 'scalar' || v.kind == 'time') return v.raw
540
+ if (v.kind == 'list') return v.items.map(flatValue).join(',')
541
+ return `${flatValue(v.lo)}..${v.exclusiveEnd ? '.' : ''}${flatValue(v.hi)}`
542
+ }
543
+
544
+ // What a column is to a value comparison, as @yaks/sql reads it: a shared
545
+ // reference names entities, and a column no component declares is text.
546
+ let tagFor = (hop: Hop): Tag => {
547
+ if (!hop.comp) return 'eid'
548
+ let p = vocab.prop(hop.comp, hop.prop)
549
+ return p ? tagOf(p) : 'text'
550
+ }
551
+
552
+ let columnOf = (path: string[], directive: string): Hop => {
553
+ let hops = vocab.aim(path.join('.'))
554
+ let at = hops[hops.length - 1]
555
+ if (hops.length != 1 || !at.prop) {
556
+ throw new Error(
557
+ `${directive} names one column, not a path: ${path.join('.')}`,
558
+ )
559
+ }
560
+ return at
561
+ }
562
+
563
+ // A projected column: the row's own, or a path through its references to a
564
+ // column of the entity each one names.
565
+ let fieldOf = (path: string[], wake: boolean): Field => {
566
+ let hops = vocab.aim(path.join('.'))
567
+ let [first, ...at] = hops
568
+ if (
569
+ hops.length == 1 && !first.prop && !vocab.props(first.comp).length &&
570
+ !vocab.comp(first.comp)?.computed
571
+ ) {
572
+ return { ...first, wake }
573
+ }
574
+ let through = (h: Hop, i: number) =>
575
+ !!h.prop &&
576
+ (i == hops.length - 1 || vocab.prop(h.comp, h.prop)?.category == 'ref')
577
+ if (!hops.every(through)) {
578
+ throw new Error(
579
+ `.fields names a column, or one through references: ${path.join('.')}`,
580
+ )
581
+ }
582
+ return {
583
+ comp: first.comp,
584
+ prop: first.prop,
585
+ wake,
586
+ ...at.length ? { at } : {},
587
+ }
588
+ }
589
+
590
+ // A directive inside an alternative would be read by nobody: orderOf, fieldsOf
591
+ // and the riders scan the top-level list. Refuse it there rather than let
592
+ // `(.a=1&.order=hot|.b=2)` quietly drop the order.
593
+ let alternative = (preds: Pred[]): Pred[] => {
594
+ let rider = preds.find((p) =>
595
+ [ORDER, NEAR, AGG, WINDOW, PROJECT, WANT].includes(p.op)
596
+ )
597
+ if (rider) {
598
+ throw new Error(`.${rider.op} belongs outside the | alternatives`)
599
+ }
600
+ return preds
601
+ }
602
+
603
+ let bindClause = (c: Clause): Pred[] => {
604
+ switch (c.kind) {
605
+ case 'and':
606
+ return c.clauses.flatMap((c) => bindClause(c))
607
+ case 'or':
608
+ return [{
609
+ comp: '',
610
+ prop: '',
611
+ op: OR,
612
+ value: '',
613
+ alts: c.clauses.map((a) => alternative(bindClause(a))),
614
+ }]
615
+ case 'never':
616
+ return [never()]
617
+ case 'text':
618
+ return [text(c.value)]
619
+ case 'resource':
620
+ if (/^[0-9a-f]{6,64}$/i.test(c.comp)) {
621
+ return bindClause(parse(`.entity.eid=#${c.comp}`))
622
+ }
623
+ throw new Error(`a fleet read cannot evaluate resource #${c.comp}`)
624
+ case 'every':
625
+ return [] // full rows are the fleet's default projection
626
+ case 'order':
627
+ return [{ comp: '', prop: 'order', op: ORDER, value: c.value }]
628
+ case 'near':
629
+ return [{ comp: '', prop: 'near', op: NEAR, value: c.value }]
630
+ case 'refs':
631
+ return [{
632
+ comp: '',
633
+ prop: '',
634
+ op: c.op == '!' ? EXISTS : '',
635
+ value: c.value,
636
+ refs: true,
637
+ }]
638
+ case 'count':
639
+ return [{ comp: '', prop: '', op: AGG, value: '', agg: 'count' }]
640
+ case 'distinct':
641
+ case 'tally':
642
+ return [{
643
+ ...columnOf(c.path, `.${c.kind}`),
644
+ op: AGG,
645
+ value: '',
646
+ agg: c.kind,
647
+ }]
648
+ case 'fields':
649
+ return [{
650
+ comp: '',
651
+ prop: '',
652
+ op: PROJECT,
653
+ value: '',
654
+ fields: c.fields
655
+ .filter((f) => f.path.join('.') != 'entity.eid')
656
+ .map((f) => fieldOf(f.path, f.wake)),
657
+ }]
658
+ case 'limit':
659
+ case 'after': {
660
+ let cursor = 'n' in c ? c.n : c.eid
661
+ return [{
662
+ comp: '',
663
+ prop: '',
664
+ op: WINDOW,
665
+ value: String(cursor),
666
+ win: { [c.kind]: cursor },
667
+ }]
668
+ }
669
+ case 'walk': {
670
+ let path = c.path.join('.')
671
+ let reach: Reach = { type: path, depth: c.depth, dir: c.dir }
672
+ if (!(edges as readonly string[]).includes(path)) {
673
+ let via = columnOf(c.path, 'a walk')
674
+ if (!isRef(via.comp, via.prop)) {
675
+ throw new Error(
676
+ `a walk follows an edge type (${
677
+ edges.join(', ')
678
+ }) or a reference column — not ${path}`,
679
+ )
680
+ }
681
+ reach.via = via
682
+ }
683
+ return [{ comp: '', prop: '', op: REACHES, value: c.target, reach }]
684
+ }
685
+ case 'pred':
686
+ break
687
+ default:
688
+ throw new Error(`a fleet read cannot evaluate ${c.kind}`)
689
+ }
690
+ let segs = c.path, op = c.op, value = flatValue(c.value)
691
+ let assoc = vocab.assoc(segs[0])
692
+ if (assoc) {
693
+ let inner = c.where
694
+ ? bindClause(c.where)
695
+ : segs.length > 1
696
+ ? bindClause({ ...c, path: segs.slice(1), not: undefined })
697
+ : []
698
+ let count = !inner.length &&
699
+ !(op == '!' || (op == '~=' && !value) || (op == '=' && !value))
700
+ if (count && !/^\d+$/.test(value)) {
701
+ throw new Error(
702
+ `.${segs[0]} needs a sub-path (.${segs[0]}.<prop>) or a count (.${
703
+ segs[0]
704
+ }>=N)`,
705
+ )
706
+ }
707
+ return [{
708
+ ...assoc,
709
+ op: count ? OPS[op] : EXISTS,
710
+ value: count ? value : '',
711
+ rev: {
712
+ ...assoc,
713
+ name: segs[0],
714
+ preds: inner,
715
+ not: inner.length ? !!c.not : op == '=' && !value,
716
+ ...(count ? { count: true } : {}),
717
+ },
718
+ }]
719
+ }
720
+ if (c.not || c.where) {
721
+ throw new Error(`.${segs[0]} is not a reverse association`)
722
+ }
723
+ if (segs.length == 1 && segs[0] == 'kind') return kindScope(value)
724
+ if (op == '?') return [{ ...wanted(c), op: WANT, value: '' }]
725
+ let hops = aimed(c)
726
+ let leaf = hops[hops.length - 1], derefs = hops.slice(0, -1)
727
+ if (!leaf.prop && compares(c)) {
728
+ throw new Unknown(leaf.comp, valueless(vocab, segs.join('.'), op, value))
729
+ }
730
+ for (let d of derefs) {
731
+ if (!isRef(d.comp, d.prop)) {
732
+ throw new Error(
733
+ `.${
734
+ d.prop || d.comp
735
+ } is not a reference — paths walk reference columns`,
736
+ )
737
+ }
738
+ }
739
+ let p: Pred = derefs.length
740
+ ? { ...derefs[0], op: OPS[op], value, at: [...derefs.slice(1), leaf] }
741
+ : { ...leaf, op: OPS[op], value }
742
+ if (!p.prop) {
743
+ if (p.value || (p.op != '' && p.op != '~' && p.op != EXISTS)) {
744
+ throw new Error(
745
+ `component filters are presence tests: !${p.comp} is absent, .${p.comp} is present`,
746
+ )
747
+ }
748
+ return [p]
749
+ }
750
+ p.tag = tagFor(leaf)
751
+ p.operand = c.value ?? scalar('')
752
+ let type = typed(leaf.comp, leaf.prop)
753
+ if (type && p.op != '~' && p.value != '') {
754
+ p.operand = mapValue(p.operand, (raw) => atom(type, raw))
755
+ p.value = flatValue(p.operand)
756
+ }
757
+ return [p]
758
+ }
759
+
760
+ // A clause's path as the hops it names (@yaks/vocab `aim`). A presence test
761
+ // naming a component nothing declares is refused, as @yaks/sql refuses it.
762
+ let aimed = (c: Clause & { kind: 'pred' }): Hop[] => {
763
+ let hops = vocab.aim(c.path.join('.'), bare(c))
764
+ let leaf = hops[hops.length - 1]
765
+ if (!leaf.prop && !vocab.comp(leaf.comp)) {
766
+ throw new Unknown(leaf.comp, unknownWord(vocab, leaf.comp))
767
+ }
768
+ return hops
769
+ }
770
+
771
+ // `?loan` asks for a whole component beside the filter. A component this
772
+ // vocabulary does not declare is still a fair question: a store without it
773
+ // answers by leaving it off the row.
774
+ let wanted = (c: Clause & { kind: 'pred' }): Hop => {
775
+ let hop = c.path.length == 1 && !c.value
776
+ ? vocab.aim(c.path[0], true)[0]
777
+ : undefined
778
+ if (!hop || hop.prop) {
779
+ throw new Error(
780
+ `?${
781
+ c.path.join('.')
782
+ }: ? asks for a whole component beside the filter, as .book&?loan does`,
783
+ )
784
+ }
785
+ return hop
786
+ }
787
+
788
+ // A bare word: an FTS5 term over doc title/body. comp/prop are for show —
789
+ // matchQuery treats TEXT specially (one pred, two columns).
790
+ export let TEXT = 'text'
791
+ let text = (value: string): Pred => ({
792
+ comp: 'doc',
793
+ prop: '*',
794
+ op: TEXT,
795
+ value,
796
+ })
797
+
798
+ // The safe MATCH spelling shared by ranked retrieval and the membership SQL.
799
+ // User text is always a quoted phrase, never FTS operator syntax; only a
800
+ // trailing `*` has grammar meaning and prefix-matches the phrase's final token.
801
+ export let ftsQuery = (preds: Pred[]): string =>
802
+ preds.filter((p) => p.op == TEXT).map((p) => ftsTerm(p.value))
803
+ .filter(Boolean).join(' ')
804
+
805
+ // TEXT may sit inside a reverse association's child filter. A client without
806
+ // SQLite must treat the WHOLE query as server-owned rather than locally
807
+ // approximating only the top-level terms.
808
+ export let textual = (preds: Pred[]): boolean =>
809
+ preds.some((p) => p.op == TEXT || !!p.rev && textual(p.rev.preds))
810
+
811
+ // TEXT membership belongs to SQLite's unicode61 tokenizer. Callers with no
812
+ // graph index cannot safely approximate it in JavaScript; they match no text
813
+ // until an indexed answer arrives rather than inventing a wider membership.
814
+ export type Fts = (eid: string, pred: Pred) => boolean
815
+
816
+ // Empty reads select nothing. Whitespace, & and comma separation, quoting,
817
+ // escaping and malformed-clause refusals are all owned by the package parser.
818
+ export let NEVER = 'never'
819
+ // The OR pred: see Pred.alts. Every evaluator (matchQuery, sql.ts, predComps)
820
+ // recurses into the alternatives; every reader of directives ignores it.
821
+ export let OR = 'or'
822
+ export let never = (): Pred => ({ comp: '', prop: '', op: NEVER, value: '' })
823
+ // Like the parser's AST, a bound query is immutable and belongs to its
824
+ // vocabulary. Repainting a board should not bind its projection again.
825
+ let bound = new WeakMap<typeof vocab, WeakMap<Clause, Pred[]>>()
826
+ export let parseQuery = (q: string): Pred[] => {
827
+ let ast = parse(q)
828
+ let queries = bound.get(vocab)
829
+ if (!queries) bound.set(vocab, queries = new WeakMap())
830
+ let preds = queries.get(ast)
831
+ if (!preds) queries.set(ast, preds = frozen(bindClause(ast)))
832
+ return preds
833
+ }
834
+
835
+ // The column's declared type, as the value rules read it: the tag its binder
836
+ // resolved, or for a pred built by hand, the vocabulary's.
837
+ let tagAt = (p: Pred): Tag => p.tag ?? tagFor(leafOf(p))
838
+
839
+ // One compile per pred, because a sweep asks the same question of every row in
840
+ // the set and the answer depends only on op, operand and tag. A time column is
841
+ // the exception: its operand is a PHRASE read against the clock, which moves
842
+ // (the subscription sweep hands the matcher a later moment on purpose).
843
+ let checks = new WeakMap<Pred, Check | null>()
844
+ let compiled = (p: Pred, tag: Tag): Check | null => {
845
+ if (!checks.has(p)) {
846
+ checks.set(p, check(p.op, operandOf(p) ?? p.value, tag, 0))
847
+ }
848
+ return checks.get(p)!
849
+ }
850
+
851
+ // One value against one predicate. Equality and its absent/list/range forms,
852
+ // not-equals, contains, the comparisons and the time phrases all belong to
853
+ // @yaks/match, which answers them exactly as the SQL lowering does — by the
854
+ // column's DECLARED type, never by whether both sides happen to look numeric.
855
+ // A question the type cannot answer (`.filed.priority>soon`, `.doc.title>5`)
856
+ // selects
857
+ // nothing: @yaks/sql declines the same compile, and a board mid-render is
858
+ // no place to throw.
859
+ let test = (v: unknown, p: Pred, now?: number, tag = tagAt(p)): boolean => {
860
+ let hit = tag == 'time'
861
+ ? check(p.op, operandOf(p) ?? p.value, tag, now ?? Date.now())
862
+ : compiled(p, tag)
863
+ return !!hit && hit(v ?? null)
864
+ }
865
+
866
+ // The sugar's other half: a board-stored query carries values as typed
867
+ // ('jeff', 'T-3') — the door resolvers never saw it, so whoever EVALUATES
868
+ // resolves, against whatever graph they hold. Only reference columns with
869
+ // equality-shaped ops resolve; each part of an any-of list resolves
870
+ // alone; a miss stays as typed and matches nothing, because a board
871
+ // mid-render is no place to throw.
872
+ export let resolveRefs = (
873
+ preds: Pred[],
874
+ lookup: (id: string) => string | undefined,
875
+ ): Pred[] =>
876
+ preds.map((p) => {
877
+ if (p.op == OR) {
878
+ return { ...p, alts: p.alts!.map((a) => resolveRefs(a, lookup)) }
879
+ }
880
+ // A multi-column reverse-union's value is an id like any reference — but it
881
+ // owns no comp/prop to type it, so resolve it through the entity target. A
882
+ // traversal's target is the same shape: one entity, no column to type it.
883
+ if (p.refs || p.op == REACHES) {
884
+ if ((p.op != '' && p.op != REACHES) || !p.value) return p
885
+ try {
886
+ let value = String(parseProp(anyRef, p.value, { resolve: lookup }))
887
+ return value == p.value ? p : { ...p, value }
888
+ } catch (error) {
889
+ if (error instanceof IdError) throw error
890
+ return p
891
+ }
892
+ }
893
+ // A reverse hop's own value is a count, never a ref — but its sub-filter
894
+ // carries the same typed values, so resolve THROUGH it (recursively).
895
+ if (p.rev) {
896
+ let inner = resolveRefs(p.rev.preds, lookup)
897
+ return inner == p.rev.preds
898
+ ? p
899
+ : { ...p, rev: { ...p.rev, preds: inner } }
900
+ }
901
+ let { comp, prop: target } = leafOf(p)
902
+ // The spine's `.entity.eid=` names entities, so its operands are ids like a
903
+ // reference's — resolved at the door the same way, so `.entity.eid=T-3` lands.
904
+ let spine = comp == 'entity' && target == 'eid'
905
+ if ((!spine && !isRef(comp, target)) || (p.op != '' && p.op != '!')) {
906
+ return p
907
+ }
908
+ let operand = operandOf(p)
909
+ if (!operand || !literals(operand)?.length) return p
910
+ let type = spine ? anyRef : typed(comp, target)
911
+ if (!type) return p
912
+ let next = mapValue(operand, (part) => {
913
+ if (!part) return part
914
+ try {
915
+ return String(parseProp(type, part, { resolve: lookup }))
916
+ } catch (error) {
917
+ if (error instanceof IdError) throw error
918
+ return part // a live saved query may name an entity not here yet
919
+ }
920
+ })
921
+ let value = flatValue(next)
922
+ return value == p.value ? p : { ...p, value, operand: next }
923
+ })
924
+
925
+ // Does an entity satisfy every pred? A TEXT pred reads the doc itself —
926
+ // one pred, either column. A path pred dereferences through `ent` (the
927
+ // evaluator's graph), folding hop after hop; no ent, no ref, or no target
928
+ // anywhere along the chain reads as an absent value — so
929
+ // `.comment.target.doc.title=x` misses and `!=x` holds, same as any null
930
+ // column.
931
+ //
932
+ // `now` is the clock a time phrase reads. It defaults to the wall clock,
933
+ // which is what every door wants — a saved `today` must advance tomorrow.
934
+ // It is a parameter because a moving phrase names a window the clock moves
935
+ // THROUGH, so the only way to state "this row has aged out" as a test is to
936
+ // hand the matcher a later moment (see the subscription sweep).
937
+ // A bare component name (empty prop) is a presence test: `!`/`~=` hold when the
938
+ // bag wears the component, `=` when it does not — the same rule at depth 0 and
939
+ // at a path leaf (`.blocked` and `.filed.project.archived` mean the same thing
940
+ // one hop apart). A broken link hands in an undefined bag, which reads as absent.
941
+ let present = (bag: Comps | undefined, comp: string, op: string): boolean =>
942
+ op == '~' || op == EXISTS ? !!bag?.[comp] : !bag?.[comp]
943
+
944
+ // The reverse-hop accessor: the children whose `comp.prop` reference equals
945
+ // `eid`, as their component bags. The mirror of `ent` (forward deref) — a caller
946
+ // with a reverse index (live's index.ts refs, a server snapshot) supplies it; a
947
+ // caller without one leaves reverse hops matching nothing (the null reading, the
948
+ // same graceful absence a missing `ent` gives a forward path).
949
+ export type Kids = (
950
+ eid: string,
951
+ comp: string,
952
+ prop: string,
953
+ ) => (Comps | undefined)[]
954
+
955
+ // A Kids accessor over an in-memory universe (a byEid map). Lazily builds and
956
+ // caches the reverse map for each ref column a hop asks about, so a caller that
957
+ // holds the whole graph (the server's snapshot fallback, mcp, tests) answers a
958
+ // reverse hop the same way the live index and the SQL EXISTS do — one door, no
959
+ // per-caller reverse index. Generic over the row so a Map<eid, comps> of any
960
+ // exact shape passes without the Map-variance friction.
961
+ export let kidsOf = <
962
+ R extends Record<string, Record<string, unknown> | undefined>,
963
+ >(byEid: Map<string, R>): Kids => {
964
+ let cache = new Map<string, Map<string, string[]>>()
965
+ return (eid, comp, prop) => {
966
+ let key = `${comp}.${prop}`
967
+ let m = cache.get(key)
968
+ if (!m) {
969
+ m = new Map()
970
+ for (let [ce, cc] of byEid) {
971
+ let v = cc[comp]?.[prop]
972
+ if (v == null) continue
973
+ let k = String(v)
974
+ m.set(k, [...(m.get(k) ?? []), ce])
975
+ }
976
+ cache.set(key, m)
977
+ }
978
+ return (m.get(eid) ?? []).map((k) => byEid.get(k))
979
+ }
980
+ }
981
+
982
+ // An entity's own eid, read off any component bag it wears (every bag carries
983
+ // `eid`, readable's first column). A reverse hop needs it to ask "who points at
984
+ // ME"; the forward grammar never did, so matchQuery never took it as an argument.
985
+ let eidOf = (c: Comps): string | undefined => {
986
+ let e = c.entity?.eid
987
+ if (e != null) return String(e)
988
+ for (let k in c) {
989
+ let v = c[k]?.eid
990
+ if (v != null) return String(v)
991
+ }
992
+ }
993
+
994
+ export let matchQuery = (
995
+ c: Comps,
996
+ preds: Pred[],
997
+ ent?: (eid: string) => Comps | undefined,
998
+ now?: number,
999
+ kids?: Kids,
1000
+ walk?: Walk,
1001
+ fts?: Fts,
1002
+ ): boolean =>
1003
+ preds.every((p) => {
1004
+ if (p.op == NEVER) return false // the empty query: selects nothing
1005
+ if (p.op == OR) {
1006
+ return p.alts!.some((alt) =>
1007
+ matchQuery(c, alt, ent, now, kids, walk, fts)
1008
+ )
1009
+ }
1010
+ if (
1011
+ p.op == ORDER || p.op == NEAR || p.op == AGG || p.op == PROJECT ||
1012
+ p.op == WANT
1013
+ ) {
1014
+ return true
1015
+ }
1016
+ // A window bounds the ANSWER, never membership: every match still matches,
1017
+ // and the door that answers is what cuts the page.
1018
+ if (p.op == WINDOW) return true
1019
+ if (p.op == REACHES) {
1020
+ // The bounded closure, resolved ONCE per query by the caller's walk and
1021
+ // tested here with a Set lookup — never a per-row traversal. No walk means
1022
+ // no closure, the same reading a reverse hop gives a missing accessor.
1023
+ let self = eidOf(c)
1024
+ return !!self && !!walk && !!p.reach && walk(p.reach, p.value).has(self)
1025
+ }
1026
+ if (p.refs) {
1027
+ // The multi-column reverse-union: read every {eid} column this bag
1028
+ // carries. `.refs=X` holds when any equals X; `.refs` when any is set;
1029
+ // `!refs` when none is — the same tri-state a reverse association marks.
1030
+ let vals = vocab.refProps()
1031
+ .map(([comp, prop]) => c[comp]?.[prop])
1032
+ .filter((v) => v != null)
1033
+ if (p.op == EXISTS) return vals.length > 0
1034
+ if (p.value == '') return vals.length == 0
1035
+ return vals.some((v) => String(v) == p.value)
1036
+ }
1037
+ if (p.op == TEXT) {
1038
+ let self = eidOf(c)
1039
+ return !!self && !!fts && fts(self, p)
1040
+ }
1041
+ if (p.rev) {
1042
+ // The reverse hop: resolve the children pointing back at me, then collapse
1043
+ // the many to a yes/no — a count comparison, or ANY child matching the
1044
+ // sub-filter (`not` flips that to NONE). No accessor → no children.
1045
+ let self = eidOf(c)
1046
+ let children = self && kids ? kids(self, p.rev.comp, p.rev.prop) : []
1047
+ // The cardinality half: the same value road, over a count — which is a
1048
+ // number whatever the reference column it counts happens to be.
1049
+ if (p.rev.count) return test(children.length, p, now, 'number')
1050
+ let hit = children.some((k) =>
1051
+ !!k && matchQuery(k, p.rev!.preds, ent, now, kids, walk, fts)
1052
+ )
1053
+ return p.rev.not ? !hit : hit
1054
+ }
1055
+ if (!p.prop) return present(c, p.comp, p.op)
1056
+ if (p.at) {
1057
+ // Deref the near ref, then every intermediate hop, carrying the set of
1058
+ // component-bags forward; test the leaf on each. A broken link yields one
1059
+ // absent bag so absence tests still hold — the null-column reading.
1060
+ let hops = [{ comp: p.comp, prop: p.prop }, ...p.at.slice(0, -1)]
1061
+ let leaf = p.at[p.at.length - 1]
1062
+ let bags: (Comps | undefined)[] = [c]
1063
+ for (let h of hops) {
1064
+ bags = bags.flatMap((b) =>
1065
+ reads(b ?? {}, h.comp, h.prop).map((ref) =>
1066
+ ref != null ? ent?.(String(ref)) : undefined
1067
+ )
1068
+ )
1069
+ }
1070
+ // A leaf with no prop is a component-presence test on the far entity —
1071
+ // the depth-0 grammar one hop out, not a null column read that always fails.
1072
+ return bags.some((b) =>
1073
+ leaf.prop
1074
+ ? reads(b ?? {}, leaf.comp, leaf.prop).some((value) =>
1075
+ test(value, p, now)
1076
+ )
1077
+ : present(b, leaf.comp, p.op)
1078
+ )
1079
+ }
1080
+ return reads(c, p.comp, p.prop).some((value) => test(value, p, now))
1081
+ })
1082
+
1083
+ // One column read. A shared route has no component, so reads() below tests
1084
+ // every component carrying that property; an entity may wear several.
1085
+ //
1086
+ // `updated.at` falls back to `created.at`, because the `updated` row is only
1087
+ // stamped by a LATER write: an entity made and never touched since carries
1088
+ // `created` and no `updated` at all. 1,656 of the graph's 10,767 entities are
1089
+ // in that state, and every one of them was invisible to `.updated.at>=…` —
1090
+ // including the two boards whose whole job is showing recent activity, which
1091
+ // silently omitted anything filed and not revisited. Being made IS the last
1092
+ // time a thing changed, so this is what the column already meant.
1093
+ //
1094
+ // Only `at`. Whether `.updated.by` should name the creator of an untouched
1095
+ // entity is a different question about authorship, and nothing is broken by
1096
+ // leaving it alone.
1097
+ let read = (c: Comps, comp: string, prop: string): unknown => {
1098
+ // The one DERIVED column (D-24102): task.status is computed from the
1099
+ // completed/cancelled/claim comps, never stored — the same value statusOf
1100
+ // gives every renderer, so a filter, projection or tally reads it identically.
1101
+ if (comp == 'task' && prop == 'status') {
1102
+ return c.task ? statusOf(c) : undefined
1103
+ }
1104
+ let v = c[comp]?.[prop]
1105
+ return v == null && comp == 'updated' && prop == 'at' ? c.created?.at : v
1106
+ }
1107
+
1108
+ let reads = (c: Comps, comp: string, prop: string): unknown[] => {
1109
+ if (comp) return [read(c, comp, prop)]
1110
+ let values = Object.values(c).map((v) => v?.[prop])
1111
+ .filter((v) => v != null)
1112
+ return values.length ? values : [undefined]
1113
+ }