@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/client.ts ADDED
@@ -0,0 +1,734 @@
1
+ // The headless client half — what the CLI and the MCP server share. Talks
2
+ // to a running tasks server over HTTP (/query to read, /apply
3
+ // to write; writes broadcast to every live client), assembles entities
4
+ // the same way live.ts does, and owns the dot-param grammar:
5
+ // `.doc.title=Hello` sets doc.title; a property is always named with its
6
+ // component. Values that look like numbers become numbers.
7
+ import { IdError } from './types.js'
8
+ import { answering, parse } from '@yaks/id'
9
+ import { identityEid } from '@yaks/graph/identity'
10
+ import { ownsSessionBranch } from './session_worktree.js'
11
+ import {
12
+ byName,
13
+ type Change,
14
+ comps,
15
+ deaths,
16
+ type Hit,
17
+ kindOf,
18
+ shapeOf,
19
+ stamped,
20
+ statusOf,
21
+ uuid,
22
+ vocab,
23
+ } from './types.js'
24
+ import { aliasOf, idOf, shortHex } from './types.js'
25
+ import { fieldOp, parseProp, propAt, refOf } from './props.js'
26
+ import { nearest, offer } from './near.js'
27
+ import { catalog, type Provider, spawnDefault } from './providers.js'
28
+ export { idOf }
29
+
30
+ export type Row = {
31
+ eid: string
32
+ num: number
33
+ /** the letter of the series `num` is in (@yaks/id) */
34
+ prefix?: string
35
+ kind: string
36
+ comps: Record<string, Record<string, unknown>>
37
+ }
38
+
39
+ // Task status is DERIVED (D-24102): read it off the comps a row carries. A
40
+ // non-task row has no task comp, so this stays undefined the way `.task?.status`
41
+ // did — every caller that guarded on truthiness keeps its meaning.
42
+ export let taskStatus = (r: { comps: Record<string, unknown> }) =>
43
+ r.comps.task ? statusOf(r.comps) : undefined
44
+
45
+ // The changes a UI picker sends to set a task to a chosen DERIVED status
46
+ // (D-24102): each move retracts conflicting facets before minting its own, so
47
+ // cancelled→done and done→wip are real transitions rather than precedence
48
+ // accidents. A session's wip is its live claim; anyone else's is the `started`
49
+ // mark. Open retracts both.
50
+ export let statusChanges = (
51
+ eid: string,
52
+ status: string,
53
+ session?: string,
54
+ ): Change[] =>
55
+ status == 'done'
56
+ ? [
57
+ { eid, name: 'cancelled', comp: null },
58
+ { eid, name: 'completed', comp: {} },
59
+ ]
60
+ : status == 'cancelled'
61
+ ? [
62
+ { eid, name: 'completed', comp: null },
63
+ { eid, name: 'cancelled', comp: {} },
64
+ ]
65
+ : status == 'wip'
66
+ ? [
67
+ { eid, name: 'completed', comp: null },
68
+ { eid, name: 'cancelled', comp: null },
69
+ session
70
+ ? { eid, name: 'claim', comp: { session } }
71
+ : { eid, name: 'started', comp: {} },
72
+ ]
73
+ : [
74
+ { eid, name: 'completed', comp: null },
75
+ { eid, name: 'cancelled', comp: null },
76
+ { eid, name: 'started', comp: null },
77
+ { eid, name: 'claim', comp: null },
78
+ ]
79
+
80
+ export let rowOf = (r: Record<string, unknown>): Row => {
81
+ let { kind, ...comps } = r
82
+ let entity = comps.entity as Record<string, unknown>
83
+ return {
84
+ eid: String(entity.eid),
85
+ num: Number(entity.num ?? 0),
86
+ ...entity.prefix ? { prefix: String(entity.prefix) } : {},
87
+ kind: kind ? String(kind) : kindOf(comps),
88
+ comps: comps as Row['comps'],
89
+ }
90
+ }
91
+
92
+ // The graph as rows: one per entity, components merged in; kind derived.
93
+ // Quarantine is absent unless the caller takes the explicit reveal branch.
94
+ export let rows = ({ changes }: { changes: Change[] }, quarantined = false) => {
95
+ let out = new Map<string, Row>()
96
+ for (let { eid, name, comp } of changes) {
97
+ if (!comp) continue
98
+ let row = out.get(eid)
99
+ if (!row) {
100
+ row = { eid, num: 0, kind: 'entity', comps: {} }
101
+ out.set(eid, row)
102
+ }
103
+ if (name == 'entity') {
104
+ if ('num' in comp) row.num = Number(comp.num ?? 0)
105
+ if (comp.prefix) row.prefix = String(comp.prefix)
106
+ // A presence transition echoes only the derived archetype pointer.
107
+ // Keep the identity stamped earlier in the same batch.
108
+ row.comps.entity = { ...row.comps.entity, ...comp }
109
+ } else row.comps[name] = comp
110
+ }
111
+ for (let r of out.values()) r.kind = kindOf(r.comps)
112
+ let rows = [...out.values()]
113
+ return quarantined ? rows : rows.filter((r) => !r.comps.quarantined)
114
+ }
115
+
116
+ // One row per eid, oldest first — a snapshot walks the entity table in num
117
+ // order, so a set stitched from several queries answers in that same order.
118
+ export let uniq = (all: Row[]) =>
119
+ [...new Map(all.map((r) => [r.eid, r])).values()]
120
+ .sort((a, b) => a.num - b.num)
121
+
122
+ // A search by meaning (`.near`) ranks each row it answers (`rank.score`).
123
+ export let hitOf = (r: Row): Hit => ({
124
+ eid: r.eid,
125
+ num: r.num,
126
+ kind: r.kind,
127
+ title: String(r.comps.doc?.title ?? ''),
128
+ score: Number(r.comps.rank?.score ?? 0),
129
+ })
130
+
131
+ // The pipe, as a seam. Reading is sync because inflate is, and `taken`
132
+ // rides the seam because consumability is a fact about the resource, not
133
+ // about the caller — every door that asks for stdin in one command asks
134
+ // the same object, so the second ask can be refused instead of served an
135
+ // empty string. `taken` holds the TOKEN that drank it, not the prop: the
136
+ // refusal names a door the caller can recognize, whichever spelling they
137
+ // reached for.
138
+ export type Stdin = {
139
+ terminal: () => boolean
140
+ read: () => string
141
+ taken?: string
142
+ }
143
+
144
+ // ---- dot-params (the WRITE grammar: values are literal; the filter
145
+ // grammar with operators/lists/ranges lives in query.ts) ----
146
+
147
+ export type Param = { comp: string; prop: string; value: unknown }
148
+ export type ComponentPatches = Record<
149
+ string,
150
+ Record<string, unknown> | null
151
+ >
152
+
153
+ // '.doc.title=Hello' → {comp, prop, value}; null if the argument isn't a
154
+ // dot-param at all (a bare word). A property is named with its component, as
155
+ // in a query: '.filed.assignee=jeff' patches filed.assignee and derefParams
156
+ // turns the value into an eid at the door. A name alone is a component, and a
157
+ // property named alone is refused with the forms that name it (@yaks/vocab
158
+ // `aim`).
159
+ // A hyphen is admitted into the NAME so a hyphenated spelling reaches
160
+ // aim() and earns the same `unknown prop` error as any other unknown.
161
+ // No column is hyphenated, so nothing new routes — but before this, a
162
+ // name the pattern rejected returned null, and cli.ts's split() files
163
+ // every non-param token under `words`: `.blocked-by=T-1` became part of
164
+ // a task's TITLE. Silence, not an edge and not an error.
165
+ // `read` is the door's value convention (inflate, where there's a filesystem)
166
+ // and it runs HERE, before the value is READ: `.doc.body=@edit.json` routes a
167
+ // $edit operator exactly as `--body=@edit.json` does. Applied after param()
168
+ // it only ever saw an already-parsed value, so the file's text landed as prose.
169
+ export let param = (
170
+ arg: string,
171
+ read: (p: Param) => Param = (p) => p,
172
+ ): Param | null => {
173
+ let m = arg.match(/^\.([A-Za-z_-]+)(?:\.([A-Za-z_-]+))?=(.*)$/s)
174
+ if (!m) return null
175
+ let [, a, b, raw] = m
176
+ let p: Param
177
+ if (b) {
178
+ if (!(b in (comps[a] ?? {}))) {
179
+ // The same teaching the query door gives: a refusal names the
180
+ // component's columns and their types.
181
+ throw new Error(
182
+ `no such prop: .${a}.${b}${
183
+ comps[a]
184
+ ? ` — ${shapeOf(a, Object.keys(comps[a]), (col) => comps[a][col])}`
185
+ : ''
186
+ }`,
187
+ )
188
+ }
189
+ p = { comp: a, prop: b, value: raw }
190
+ } else {
191
+ p = { ...vocab.aim(a)[0], value: raw }
192
+ }
193
+ if (!p.prop) {
194
+ // A component name is a presence mark, not a column. Column-bearing marks
195
+ // keep their explicit write spelling; stamped-only marks stay protected.
196
+ // A genuinely empty writable component speaks Boolean presence so the
197
+ // same dot-param compiler can add ({}) or remove (null) it at every door.
198
+ let cols = Object.keys(comps[p.comp] ?? {})
199
+ if (cols.length) {
200
+ throw new Error(
201
+ `.${p.comp} is a mark — write it as .${p.comp}.${
202
+ cols[0]
203
+ }=<value> (e.g. .${p.comp}.${cols[0]}=now)`,
204
+ )
205
+ }
206
+ if (Object.keys(stamped[p.comp] ?? {}).length) {
207
+ throw new Error(
208
+ `.${p.comp} is a server-stamped mark; it isn't set through a dot-param`,
209
+ )
210
+ }
211
+ let present = parseProp(
212
+ { comp: p.comp, prop: '', name: p.comp, type: 'bool' },
213
+ raw,
214
+ )
215
+ return { ...p, value: !!present }
216
+ }
217
+ // The @file / @- doors first: what the door reads is what gets read below.
218
+ let val = String(read({ ...p, value: raw }).value)
219
+ // A `$`-sigil object value is a field OPERATOR, not a literal — the same
220
+ // value graph_apply takes as a comp value, so the update doors speak the one
221
+ // operator too. It rides through untouched (no scalar parse, no deref) for
222
+ // apply() to resolve against the CURRENT stored value; apply() also owns
223
+ // every refusal — an unknown `$op`, a non-text column, a hunk that misses.
224
+ let op = fieldOp(val)
225
+ if (op) return { ...p, value: op }
226
+ let declared = propAt(p.comp, p.prop)!
227
+ p.value = typeof declared.type == 'object' && 'eid' in declared.type
228
+ ? val
229
+ : parseProp(declared, val)
230
+ return p
231
+ }
232
+
233
+ // Reference values at a door: uuids pass through, '' clears, anything
234
+ // else must resolve — an alias (jeff), a human id (T-3), a bare num — or
235
+ // the door throws, never a silent FK failure later. One resolver for
236
+ // every write door (CLI, MCP task_new/update/command, graph_apply).
237
+ export let UUID =
238
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
239
+ // The near match, offered only once the handle it prints RESOLVES here —
240
+ // find() is the same reading of "what names an entity" the caller just
241
+ // failed, so a suggestion can never route somewhere the retry won't.
242
+ // `comp` narrows to the reference's declared target, so a bad
243
+ // `.filed.project=` is only ever answered with a project.
244
+ //
245
+ // A title is MATCHED only for the kinds it names (types.ts byName), though
246
+ // every title still shows. Untargeted, the pool is the whole graph and a
247
+ // common word opens somebody's ticket every time — `tasks` reached T-801
248
+ // ("Tasks: add cancelled state…") ahead of the project called Task Graph.
249
+ // An alias always rides: it is a typed handle whatever wears it.
250
+ export let nearby = (all: Row[]) => (v: string, comp = '') => {
251
+ let names = aliasNames(all)
252
+ let hit = nearest(
253
+ v,
254
+ all.filter((r) => !comp || r.comps[comp]).map((r) => ({
255
+ eid: r.eid,
256
+ id: idOf(r),
257
+ alias: names.get(r.eid),
258
+ title: r.comps.doc?.title as string | undefined,
259
+ named: byName.has(r.kind),
260
+ })),
261
+ )
262
+ if (!hit) return
263
+ return find(all, hit.alias ?? hit.id)?.eid == hit.eid ? offer(hit) : undefined
264
+ }
265
+ // find(), where a miss is the door's error. One message for every lookup,
266
+ // so a mistyped handle teaches at whichever door heard it.
267
+ export let need = (all: Row[], id: string, where = '', comp = '') => {
268
+ let hit = find(all, id)
269
+ if (hit) return hit
270
+ let near = nearby(all)(id, comp)
271
+ throw new Error(
272
+ `no entity: ${id}${where}${near ? ` — did you mean ${near}?` : ''}`,
273
+ )
274
+ }
275
+
276
+ // The collateral of a delete: the entities the host tombstones ALONGSIDE
277
+ // the target, because they exist ABOUT it — comments aimed at it, cards and
278
+ // knocks/wakes viewing it — walked transitively down the same
279
+ // `deaths('cascade')` worklist the reaper uses, so a delete guard names
280
+ // exactly what the wire would take. The target itself is never in the list:
281
+ // it's the thing you asked to delete; this is what rides along.
282
+ //
283
+ // Two doors read this: a PURE pass over rows already in hand (the palette
284
+ // verb, which is wire-free), and an async pass that QUERIES the live graph
285
+ // (the CLI, whose reader diet is bounded and so can't see every comment on an
286
+ // arbitrary target). Same closure, two sources.
287
+ export let cascade = (all: Row[], eid: string): Row[] => {
288
+ let aimed = deaths('cascade')
289
+ let doomed = [eid]
290
+ for (let i = 0; i < doomed.length; i++) {
291
+ for (let [comp, col] of aimed) {
292
+ for (let r of all) {
293
+ if (r.comps[comp]?.[col] == doomed[i] && !doomed.includes(r.eid)) {
294
+ doomed.push(r.eid)
295
+ }
296
+ }
297
+ }
298
+ }
299
+ return doomed.slice(1).flatMap((d) => all.find((r) => r.eid == d) ?? [])
300
+ }
301
+
302
+ export let deref = (all: Row[], v: string, where = '', comp = '') =>
303
+ !v || UUID.test(v) ? v : need(all, v, where, comp).eid
304
+ // Deref a change batch through a resolver — one core, two sources. `resolve`
305
+ // turns a human id (or an eid) into the eid it names, throwing the door's
306
+ // error on a miss; a uuid/empty passes through untouched (its callers own that
307
+ // short-circuit). rows-backed derefChanges reads a materialized Row[]; the
308
+ // db-backed command executor hands a resolver keyed off the live graph, so a
309
+ // verb's output resolves its refs without a whole-graph corpus (M-21143).
310
+ export let derefWith = (
311
+ resolve: (v: string, where?: string, comp?: string) => string,
312
+ changes: Change[],
313
+ ) =>
314
+ changes.map((c) => ({
315
+ ...c,
316
+ eid: resolve(c.eid, ' (eid)'),
317
+ comp: c.comp == null ? c.comp : Object.fromEntries(
318
+ Object.entries(c.comp).map(([prop, value]) => {
319
+ let target = refOf(c.name, prop)
320
+ return [
321
+ prop,
322
+ target != null &&
323
+ (typeof value == 'string' || typeof value == 'number')
324
+ ? resolve(String(value), ` (.${prop})`, target)
325
+ : value,
326
+ ]
327
+ }),
328
+ ),
329
+ }))
330
+
331
+ export let derefChanges = (all: Row[], changes: Change[]) =>
332
+ derefWith((v, where, comp) => deref(all, v, where, comp), changes)
333
+
334
+ // Group routed params into per-component patches.
335
+ export let patches = (params: Param[]): ComponentPatches => {
336
+ let out: ComponentPatches = {}
337
+ for (let { comp, prop, value } of params) {
338
+ if (!prop) {
339
+ out[comp] = value ? {} : null
340
+ continue
341
+ }
342
+ ;(out[comp] ??= {})[prop] = value
343
+ }
344
+ return out
345
+ }
346
+
347
+ // A task, TYPED: 'P1 .filed.domain=Eng Build a thing\nnotes…' — the first line
348
+ // is setters + title, every later line is body. Dot-params parse
349
+ // anywhere in the line (their syntax can't be prose); the P1 shorthand
350
+ // only parses while it LEADS, so a title like 'Fix the P2 endpoint'
351
+ // keeps its words. One parser for every door that takes a typed task —
352
+ // the board's quick-add, :new, whatever comes next. A malformed
353
+ // dot-param stays a word rather than throwing: mid-typing is not an
354
+ // error, and Enter files what the preview showed. `read` is the door's
355
+ // value convention (inflate, where there's a filesystem) — it runs
356
+ // OUTSIDE the not-a-param catch, so a missing @file is an error and
357
+ // never a word swallowed into the title.
358
+ export let spec = (text: string, read: (p: Param) => Param = (p) => p) => {
359
+ let [line, ...rest] = text.split('\n')
360
+ let words: string[] = []
361
+ let ps: Param[] = []
362
+ let leading = true
363
+ for (let w of line.trim().split(/\s+/).filter(Boolean)) {
364
+ let priority = leading &&
365
+ /^[Pp][+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(w)
366
+ if (priority) {
367
+ ps.push(param(`.filed.priority=${w}`)!)
368
+ continue
369
+ }
370
+ if (w.startsWith('.')) {
371
+ let d: Param | null = null
372
+ try {
373
+ d = param(w)
374
+ } catch { /* not a real prop: a word after all */ }
375
+ // A param, so parse it again through the door's value convention —
376
+ // OUTSIDE the catch, so a missing @file is an error and never a word
377
+ // swallowed into the title.
378
+ if (d) {
379
+ ps.push(param(w, read)!)
380
+ continue
381
+ }
382
+ }
383
+ leading = false
384
+ words.push(w)
385
+ }
386
+ return {
387
+ title: words.join(' '),
388
+ body: rest.join('\n').trim(),
389
+ grouped: patches(ps),
390
+ }
391
+ }
392
+
393
+ // The standard task-create batch: a doc face, workflow state, then any
394
+ // other grouped components verbatim. Callers put title/body into
395
+ // grouped.doc first.
396
+ export let taskChanges = (
397
+ eid: string,
398
+ grouped: ComponentPatches,
399
+ number = false,
400
+ ): Change[] => [
401
+ {
402
+ eid,
403
+ name: 'doc',
404
+ comp: { body: '', ...(grouped.doc ?? {}) },
405
+ ...(number ? { $num: true } : {}),
406
+ },
407
+ // A new task is born open — no mark (D-24102). status is derived, not
408
+ // writable, so drop any that rode in on the spec (`.task.status=` on new).
409
+ {
410
+ eid,
411
+ name: 'task',
412
+ comp: (({ status: _drop, ...task }) => task)(grouped.task ?? {}),
413
+ },
414
+ ...Object.entries(grouped)
415
+ .filter(([n]) => n != 'doc' && n != 'task')
416
+ .map(([name, comp]) => ({ eid, name, comp })),
417
+ ]
418
+
419
+ // Each entity's alias among these rows, from the alias keys that name it.
420
+ export let aliasNames = (all: Row[]) =>
421
+ new Map(all.flatMap((r) => {
422
+ let a = aliasOf(r.comps)
423
+ return a ? [[a.eid, a.name] as const] : []
424
+ }))
425
+
426
+ // Resolve 'T-3' / a bare num / a full eid / a SHORT-eid handle / an alias to a
427
+ // row among these. A human id first, as @yaks/id's `answering` reads it, then
428
+ // exact eid, then a sigilled hex prefix, then an alias key's name. An id or a
429
+ // handle several rows answer to throws, naming them.
430
+ export let find = (all: Row[], id: string) => {
431
+ let p = parse(id)
432
+ if (p) {
433
+ let held = answering(all.filter((r) => r.num == p.num), p.prefix, (r) => r)
434
+ if (held.length > 1) {
435
+ throw new IdError(
436
+ `${id} is an ambiguous id — matches ${
437
+ held.map((r) => `${idOf(r)} (${r.eid})`).join(', ')
438
+ }`,
439
+ )
440
+ }
441
+ return held[0]
442
+ }
443
+ let exact = all.find((r) => r.eid == id.toLowerCase())
444
+ if (exact) return exact
445
+ let hex = shortHex(id)
446
+ if (hex) {
447
+ let hits = all.filter((r) => r.eid.replaceAll('-', '').startsWith(hex))
448
+ if (hits.length > 1) {
449
+ throw new IdError(
450
+ `${id} is an ambiguous id — matches ${
451
+ hits.map((r) => `${idOf(r)} (${r.eid})`).join(', ')
452
+ }; use more characters`,
453
+ )
454
+ }
455
+ return hits[0]
456
+ }
457
+ if (id.includes('#')) {
458
+ throw new IdError(`${id}: expected # followed by 6–64 hex characters`)
459
+ }
460
+ let named = all.map((r) => aliasOf(r.comps)).find((a) => a?.name == id)
461
+ return named && all.find((r) => r.eid == named.eid)
462
+ }
463
+
464
+ // A spawn as @yaks/spawn writes it (packages/spawn/tools.ts session_spawn):
465
+ // the session, its first entry carrying the instruction and the `using` it
466
+ // runs on, and the claim on the task it works. A native session (@yaks/harness,
467
+ // as `yak session new` begins one) is marked so, with the persona it wears
468
+ // where it was sent to one and the topic it is opened on; the harness admits
469
+ // that persona's instructions and the topic's tree before its first turn
470
+ // (packages/harness/effects.ts). The host reads the
471
+ // entry and starts the run; anything it cannot honor shows on the session.
472
+ export let sessionFrames = (
473
+ session: string,
474
+ body: string,
475
+ using: { provider: string; model?: string; effort?: string },
476
+ opening: {
477
+ operator: boolean
478
+ task?: string
479
+ persona?: string
480
+ topic?: string
481
+ native?: boolean
482
+ },
483
+ ): Change[] => {
484
+ let { operator, task, persona, topic, native } = opening
485
+ let entry = uuid()
486
+ return [
487
+ {
488
+ eid: session,
489
+ name: 'session',
490
+ comp: {
491
+ operator,
492
+ ...(persona ? { persona } : {}),
493
+ ...(topic ? { topic } : {}),
494
+ },
495
+ },
496
+ ...(native ? [{ eid: session, name: 'native', comp: {} }] : []),
497
+ { eid: entry, name: 'entry', comp: { session } },
498
+ { eid: entry, name: 'content', comp: { body } },
499
+ { eid: entry, name: 'using', comp: using },
500
+ ...(task ? [{ eid: task, name: 'claim', comp: { session } }] : []),
501
+ ]
502
+ }
503
+
504
+ // Find-or-mint the session entity for an external session id: its eid
505
+ // plus the change that creates or refreshes it. cwd is where it runs; pid
506
+ // is the provider process it runs IN (the SessionStart hook walks /proc for
507
+ // it) — liveness for every provider, and the anchor that lets Claude's
508
+ // channel follow a /clear rotation under the same process.
509
+ export let sessionFor = (
510
+ all: Row[],
511
+ session: string,
512
+ cwd?: string,
513
+ pid?: number,
514
+ self?: {
515
+ agent_type?: string
516
+ source?: string
517
+ transcript?: string
518
+ operator?: boolean
519
+ actor?: string
520
+ pane?: string | null
521
+ turn?: string
522
+ parent?: string
523
+ },
524
+ ) => {
525
+ let s = all.find((r) => r.comps.session && r.comps.session.id == session)
526
+ let eid = s?.eid ?? uuid()
527
+ let comp: Record<string, unknown> = s ? {} : { id: session }
528
+ // A swept branch is still ours to regrow. Hooks
529
+ // may refresh a provider pid, but never relocate a tree the server cut.
530
+ let tree = s?.comps.worktree
531
+ let owned = s?.comps.session.origin == 'managed' && tree &&
532
+ ownsSessionBranch(s.eid, tree.branch, s.num)
533
+ if (cwd && !owned && s?.comps.session.cwd != cwd) comp.cwd = cwd
534
+ if (pid && s?.comps.session.pid != pid) comp.pid = pid
535
+ for (let k of ['agent_type', 'source', 'transcript', 'turn'] as const) {
536
+ if (self?.[k] && s?.comps.session[k] != self[k]) comp[k] = self[k]
537
+ }
538
+ if (self?.pane !== undefined && s?.comps.session.pane != self.pane) {
539
+ comp.pane = self.pane
540
+ }
541
+ if (
542
+ self?.operator != undefined &&
543
+ (s?.comps.session.operator == null ||
544
+ !!s.comps.session.operator != self.operator)
545
+ ) {
546
+ comp.operator = Number(self.operator)
547
+ }
548
+ // A tool-only session has no cwd to place it. Its first task interaction
549
+ // anchors it to that venture; an identity it already wears always wins.
550
+ if (self?.actor && !s?.comps.session.actor) {
551
+ comp.actor = self.actor
552
+ }
553
+ // Who spawned this run — set once, at birth: lineage is history, not a
554
+ // field a later reify should relabel.
555
+ if (self?.parent && !s?.comps.session.parent) {
556
+ comp.parent = self.parent
557
+ }
558
+ let changes: Change[] = Object.keys(comp).length
559
+ ? [{ eid, name: 'session', comp }]
560
+ : []
561
+ return { eid, changes }
562
+ }
563
+
564
+ let taskActor = (all: Row[], target: string) =>
565
+ String(all.find((r) => r.eid == target)?.comps.filed?.project ?? '') ||
566
+ undefined
567
+
568
+ // The claim pointing at a session entity — one batch, atomic on the server.
569
+ // Set or clear this actor's standing instruction about one entity. A
570
+ // subscription needs its own entity because MANY actors subscribe to one
571
+ // target — unlike a claim, which is a comp on the task itself. Reusing
572
+ // the existing row's eid is what makes saying it twice idempotent, and
573
+ // what makes watch→mute a change of mind rather than a second opinion.
574
+ export let subChanges = (
575
+ all: Row[],
576
+ actor: string,
577
+ target: string,
578
+ mode: 'watch' | 'mute' | null,
579
+ ): Change[] => {
580
+ let had = all.find((r) =>
581
+ r.comps.subscription &&
582
+ String(r.comps.subscription.actor) == actor &&
583
+ String(r.comps.subscription.target) == target
584
+ )
585
+ if (!mode) {
586
+ return had
587
+ ? [{ eid: had.eid, name: 'subscription', comp: { mode: null } }]
588
+ : []
589
+ }
590
+ return [{
591
+ eid: had?.eid ?? uuid(),
592
+ name: 'subscription',
593
+ comp: { actor: actor, target: target, mode },
594
+ }]
595
+ }
596
+
597
+ // One launch spec: a provider and model by name, and an effort.
598
+ export type SpawnAsk = {
599
+ provider?: string
600
+ model?: string
601
+ effort?: string
602
+ }
603
+
604
+ // THE precedence every spawn door shares, so the browser and the TUI never
605
+ // resolve a launch differently: the explicit ask (a :fix dot-param, the Run
606
+ // form), then the provider table's own default, model→provider inference and
607
+ // readiness both. An explicit model without a provider leaves the transport
608
+ // to readiness. Effort falls to the chosen model's own default, then medium
609
+ // when the model has the axis at all.
610
+ export let spawnPlan = (
611
+ ps: Provider[],
612
+ ask: SpawnAsk = {},
613
+ blocked?: (name: string) => boolean,
614
+ ): SpawnAsk => {
615
+ let d = spawnDefault(ps, ask, blocked)
616
+ let provider = ask.provider ?? d.provider
617
+ let model = ask.model ?? d.model
618
+ let axis = catalog(ps).find((p) => p.model == model)?.efforts ?? []
619
+ return {
620
+ provider,
621
+ model,
622
+ effort: ask.effort ??
623
+ (model
624
+ ? ps.find((p) => p.name == provider)?.defaults?.[model]
625
+ : undefined) ??
626
+ (axis.length
627
+ ? (axis.includes('medium') ? 'medium' : axis[0])
628
+ : undefined),
629
+ }
630
+ }
631
+
632
+ // A comment: a doc aimed at the target. The session reification lets the
633
+ // server stamp its instrument; `event` marks machinery speaking (M-4062)
634
+ // so the mail relay skips it. A verdict adds review judgment to the same
635
+ // entity — rationale, aim, and authorship stay the comment's.
636
+ export let commentChanges = (
637
+ all: Row[],
638
+ target: string,
639
+ body: string,
640
+ session?: string,
641
+ mark: { verdict?: string } = {},
642
+ ): Change[] => {
643
+ let s = session
644
+ ? sessionFor(all, session, undefined, undefined, {
645
+ actor: taskActor(all, target),
646
+ })
647
+ : undefined
648
+ let eid = uuid()
649
+ return [
650
+ ...(s?.changes ?? []),
651
+ { eid, name: 'doc', comp: { title: '', body } },
652
+ {
653
+ eid,
654
+ name: 'comment',
655
+ comp: { target: target },
656
+ },
657
+ ...(mark.verdict == null
658
+ ? []
659
+ : [{ eid, name: 'review', comp: { verdict: mark.verdict } }]),
660
+ ]
661
+ }
662
+
663
+ // A commit message's first line — what a compact row shows of it.
664
+ export let subject = (message: unknown) => String(message ?? '').split('\n')[0]
665
+
666
+ // The send batch: a mail is a document that travels — subject rides
667
+ // doc.title, the body doc.body, and WHERE it goes the shared `deliver {to}`.
668
+ // `to` stays AS GIVEN (a raw address or a graph reference) — a graph
669
+ // reference resolves at the door, a raw @-address is find-or-minted into its
670
+ // address-book entity there, never here.
671
+ export let mailChanges = (m: {
672
+ to: string
673
+ subject: string
674
+ body?: string
675
+ replyTo?: string
676
+ }) => {
677
+ let eid = uuid()
678
+ let changes: Change[] = [
679
+ { eid, name: 'doc', comp: { title: m.subject, body: m.body ?? '' } },
680
+ { eid, name: 'deliver', comp: { to: m.to } },
681
+ {
682
+ eid,
683
+ name: 'mail',
684
+ comp: m.replyTo ? { reply_to: m.replyTo } : {},
685
+ },
686
+ ]
687
+ return { eid, changes }
688
+ }
689
+
690
+ // The mail tool owns addressing, threading and the caller's attention. The
691
+ // command submits its words through that boundary so every door answers the
692
+ // same way, with the runner supplying the caller's identity.
693
+ export let replyChanges = (row: Row, body: string) => {
694
+ let eid = uuid()
695
+ let changes: Change[] = [{
696
+ eid,
697
+ name: 'call',
698
+ comp: {
699
+ to: identityEid('tool', ['mail_reply']),
700
+ args: { letter: row.eid, body },
701
+ },
702
+ }]
703
+ return { eid, changes }
704
+ }
705
+
706
+ // The dream batch (T-12800): a venture's consolidation cursor plus the first
707
+ // cadence wake that starts it. `scope` is the project the dream combs; `floor`
708
+ // starts a week back so the first run has a window. The wake is UNTARGETED
709
+ // (deliver.to = the dream), so replaceWakes keeps one cadence clock and the
710
+ // server arms it on apply; its knock hooks dreamComb, which re-arms
711
+ // the next at each run's end. One dream per venture — a second on the same
712
+ // project is refused, so `task dream` is safe to run twice.
713
+ export let dreamChanges = (
714
+ all: Row[],
715
+ d: { project: string; floor?: string },
716
+ ) => {
717
+ let project = find(all, d.project)
718
+ if (!project?.comps.project) throw new Error(`not a project: ${d.project}`)
719
+ let had = all.find((r) => r.comps.dream?.scope == project.eid)
720
+ if (had) throw new Error(`${idOf(had)} already dreams ${idOf(project)}`)
721
+ let eid = uuid()
722
+ let w = uuid()
723
+ let floor = d.floor ?? new Date(Date.now() - 7 * 86_400_000).toISOString()
724
+ let changes: Change[] = [
725
+ { eid, name: 'dream', comp: { scope: project.eid, floor } },
726
+ {
727
+ eid: w,
728
+ name: 'wake',
729
+ comp: { at: new Date(Date.now() + 1000).toISOString() },
730
+ },
731
+ { eid: w, name: 'deliver', comp: { to: eid } },
732
+ ]
733
+ return { eid, changes }
734
+ }