@niscorp/moss 0.1.0

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 (96) hide show
  1. package/DESIGN.md +592 -0
  2. package/DOCS.md +943 -0
  3. package/LICENSE +202 -0
  4. package/README.md +155 -0
  5. package/dist/chunk-2AHJ6VDR.js +3314 -0
  6. package/dist/chunk-2AHJ6VDR.js.map +1 -0
  7. package/dist/chunk-EMRDIZLY.js +99 -0
  8. package/dist/chunk-EMRDIZLY.js.map +1 -0
  9. package/dist/chunk-HF6IGQ74.js +3342 -0
  10. package/dist/chunk-HF6IGQ74.js.map +1 -0
  11. package/dist/chunk-J72N3EMJ.js +238 -0
  12. package/dist/chunk-J72N3EMJ.js.map +1 -0
  13. package/dist/chunk-SK4PDGEE.js +55 -0
  14. package/dist/chunk-SK4PDGEE.js.map +1 -0
  15. package/dist/chunk-ZOEUEMDX.js +251 -0
  16. package/dist/chunk-ZOEUEMDX.js.map +1 -0
  17. package/dist/client/node.cjs +42 -0
  18. package/dist/client/node.cjs.map +1 -0
  19. package/dist/client/node.d.cts +9 -0
  20. package/dist/client/node.d.ts +9 -0
  21. package/dist/client/node.js +40 -0
  22. package/dist/client/node.js.map +1 -0
  23. package/dist/client.cjs +275 -0
  24. package/dist/client.cjs.map +1 -0
  25. package/dist/client.d.cts +52 -0
  26. package/dist/client.d.ts +52 -0
  27. package/dist/client.js +4 -0
  28. package/dist/client.js.map +1 -0
  29. package/dist/document-BEn2zXah.d.cts +993 -0
  30. package/dist/document-BEn2zXah.d.ts +993 -0
  31. package/dist/index.cjs +3716 -0
  32. package/dist/index.cjs.map +1 -0
  33. package/dist/index.d.cts +104 -0
  34. package/dist/index.d.ts +104 -0
  35. package/dist/index.js +96 -0
  36. package/dist/index.js.map +1 -0
  37. package/dist/node.cjs +3309 -0
  38. package/dist/node.cjs.map +1 -0
  39. package/dist/node.d.cts +28 -0
  40. package/dist/node.d.ts +28 -0
  41. package/dist/node.js +64 -0
  42. package/dist/node.js.map +1 -0
  43. package/dist/slots-Do9ScG7v.d.cts +37 -0
  44. package/dist/slots-Do9ScG7v.d.ts +37 -0
  45. package/dist/terminal/dom/index.cjs +34 -0
  46. package/dist/terminal/dom/index.cjs.map +1 -0
  47. package/dist/terminal/dom/index.d.cts +11 -0
  48. package/dist/terminal/dom/index.d.ts +11 -0
  49. package/dist/terminal/dom/index.js +32 -0
  50. package/dist/terminal/dom/index.js.map +1 -0
  51. package/dist/terminal/dom/server.cjs +16 -0
  52. package/dist/terminal/dom/server.cjs.map +1 -0
  53. package/dist/terminal/dom/server.d.cts +14 -0
  54. package/dist/terminal/dom/server.d.ts +14 -0
  55. package/dist/terminal/dom/server.js +14 -0
  56. package/dist/terminal/dom/server.js.map +1 -0
  57. package/dist/terminal/index.cjs +346 -0
  58. package/dist/terminal/index.cjs.map +1 -0
  59. package/dist/terminal/index.d.cts +32 -0
  60. package/dist/terminal/index.d.ts +32 -0
  61. package/dist/terminal/index.js +100 -0
  62. package/dist/terminal/index.js.map +1 -0
  63. package/dist/terminal/ink/index.d.ts +33 -0
  64. package/dist/terminal/ink/index.js +189 -0
  65. package/dist/terminal/ink/index.js.map +1 -0
  66. package/dist/terminal/react/index.cjs +87 -0
  67. package/dist/terminal/react/index.cjs.map +1 -0
  68. package/dist/terminal/react/index.d.cts +15 -0
  69. package/dist/terminal/react/index.d.ts +15 -0
  70. package/dist/terminal/react/index.js +35 -0
  71. package/dist/terminal/react/index.js.map +1 -0
  72. package/dist/terminal/react/server.cjs +79 -0
  73. package/dist/terminal/react/server.cjs.map +1 -0
  74. package/dist/terminal/react/server.d.cts +16 -0
  75. package/dist/terminal/react/server.d.ts +16 -0
  76. package/dist/terminal/react/server.js +28 -0
  77. package/dist/terminal/react/server.js.map +1 -0
  78. package/dist/terminal/tty/index.cjs +201 -0
  79. package/dist/terminal/tty/index.cjs.map +1 -0
  80. package/dist/terminal/tty/index.d.cts +18 -0
  81. package/dist/terminal/tty/index.d.ts +18 -0
  82. package/dist/terminal/tty/index.js +199 -0
  83. package/dist/terminal/tty/index.js.map +1 -0
  84. package/dist/terminal/vue/index.cjs +104 -0
  85. package/dist/terminal/vue/index.cjs.map +1 -0
  86. package/dist/terminal/vue/index.d.cts +23 -0
  87. package/dist/terminal/vue/index.d.ts +23 -0
  88. package/dist/terminal/vue/index.js +3 -0
  89. package/dist/terminal/vue/index.js.map +1 -0
  90. package/dist/terminal/vue/server.cjs +88 -0
  91. package/dist/terminal/vue/server.cjs.map +1 -0
  92. package/dist/terminal/vue/server.d.cts +18 -0
  93. package/dist/terminal/vue/server.d.ts +18 -0
  94. package/dist/terminal/vue/server.js +21 -0
  95. package/dist/terminal/vue/server.js.map +1 -0
  96. package/package.json +213 -0
package/DOCS.md ADDED
@@ -0,0 +1,943 @@
1
+ # Moss — API Reference
2
+
3
+ Seven entry points: `@niscorp/moss` (the server), `@niscorp/moss/node` (the Node
4
+ listener), `@niscorp/moss/client` (the wire), `@niscorp/moss/terminal` (the
5
+ terminal), `@niscorp/moss/terminal/react`, `@niscorp/moss/terminal/vue` and
6
+ `@niscorp/moss/terminal/dom` (the render targets). API is pre-1.0 and moves.
7
+
8
+ ## `@niscorp/moss`
9
+
10
+ ### The manifest
11
+
12
+ #### `defineApp(app: NiscApp): NiscApp`
13
+
14
+ Identity today, a validation seam tomorrow. The one name an app file needs
15
+ besides its artifacts.
16
+
17
+ #### `NiscApp`
18
+
19
+ ```typescript
20
+ type NiscApp = {
21
+ charter: Charter; // resolved per principal
22
+ assignments: Record<string, readonly string[]>; // principal → roles
23
+ actions: Record<string, ActionDefinition>; // the app's actions
24
+ layouts?: Record<string, LayoutVariant>; // ring 2: variant id → { action, layout }
25
+ behaviors?: ScopeBehaviors; // row-level scope semantics, per table or per profile
26
+ entries?: readonly (SeedEntry | SeedMutation)[]; // the prewarmed API surface
27
+ resources?: Record<string, readonly string[] | { entities: readonly string[] }>;
28
+ shell?: ShellManifest; // the server shell, as data — THE APP
29
+ pages?: Record<string, PageManifest>; // what is drawn at a path and kept by nothing
30
+ functions?: (session: FunctionSession) => Record<string, FunctionHandler>;
31
+ };
32
+ ```
33
+
34
+ Every field is an artifact (authored data) except `functions`, which is the code
35
+ escape hatch. Absent `shell`, the app serves data only (no server shells). Absent
36
+ `functions`, `fn:` endpoints fail loudly.
37
+
38
+ A `LayoutVariant` is `{ action: string; layout: LayoutNode }` — ring 2: the
39
+ charter's `layouts` section selects who holds which variant id, and moss
40
+ substitutes the granted variant's layout onto the definition at shell build. The
41
+ base is the floor; variants enrich upward as grants.
42
+
43
+ #### `ShellManifest`
44
+
45
+ ```typescript
46
+ type ShellManifest = {
47
+ canvases: ShellCanvas[]; // a canvas's `initial` may be a CANDIDATE list
48
+ layout?: LayoutNode; // the frame — CanvasSlot markers, served verbatim
49
+ fragments?: Record<string, ActionFragment>;
50
+ inputs?: (session: { principal, actions, roles }) => Record<string, Record<string, unknown>>;
51
+ components?: Record<string, { meta?: { description?; propsSchema? } }>;
52
+ };
53
+ ```
54
+
55
+ `inputs` is the app's one per-principal boot-derivation hook (nav flags, user
56
+ chips), merged over each canvas's static seed.
57
+
58
+ #### `PageManifest` — `app.pages`
59
+
60
+ ```typescript
61
+ type PageManifest = ShellManifest & {
62
+ path: string; // "/about", "/docs/:slug" — literal segments and `:name` parameters
63
+ params?: string; // the canvas whose seed receives the path's parameters as input
64
+ };
65
+ ```
66
+
67
+ `shell` is **the app**: one durable shell per signed-in person, the thing that
68
+ rearranges itself around them. A **page** is the other thing a path can lead
69
+ to — a welcome, the docs, a published talk. It is a shell manifest of its own
70
+ (a frame, canvases, what mounts on them), drawn for whoever asks and then let
71
+ go. It is the same machinery with the keeping taken out:
72
+
73
+ - **The same actions and the same charter.** What exists on a page for a given
74
+ person is ring 1, as everywhere: a strip saying who is signed in is an action
75
+ a member is granted, on a canvas whose candidate list a stranger holds none
76
+ of. Nothing in a layout asks who anybody is.
77
+ - **The same policy on every read.** A page's endpoints ride the server's own
78
+ surfaces as whoever asked — nobody, or the signed-in principal.
79
+ - **No shell is kept.** A page's shell lives for one read (the document) or one
80
+ connection (a terminal on a page that can still do something). A principal's
81
+ app shell is neither built nor touched by a page.
82
+ - **`onSession` does not run.** Session code is the app's. `functions` are
83
+ endpoints and serve a page's actions as they serve the app's.
84
+
85
+ A path matches a page when both have the same number of segments and every
86
+ literal one is equal; nothing else (no wildcards, no order). Two pages that
87
+ could both answer one path are refused at boot, as is a `params` canvas the page
88
+ does not have. Any path no page answers is the app's.
89
+
90
+ Whether a page may be kept by a cache, or written to a file, is not a property
91
+ of the page: see [`documentHeaders`](#the-document).
92
+
93
+ #### `phrases` / `phraseKeys` — the words a shell wears
94
+
95
+ The language twin of `scope`. Moss renders server-side and serializes; between
96
+ those two, every word the reader will see is present at once, so that is where a
97
+ language is applied — one pass over the frame with
98
+ [`@niscorp/nova/i18n`](../nova/src/i18n), source phrase in, translated phrase
99
+ out. Nothing downstream (the socket, the delta encoder, the terminal) learns a
100
+ language exists.
101
+
102
+ ```typescript
103
+ phrases?: (principal: string | null) => Phrasebook | undefined; // source phrase → translation
104
+ phraseKeys?: PhraseKeys; // which keys carry prose
105
+ ```
106
+
107
+ - Per **principal**, because a shell is per principal. Resolved once when the
108
+ shell is built, so changing somebody's language is a `reset`/rebuild — exactly
109
+ like changing their catalog.
110
+ - Returning `undefined` or `{}` is the **source language** and costs nothing: the
111
+ pass returns the same tree object and the frame serializes to the bytes it
112
+ always did.
113
+ - `phraseKeys` is how an app names its own prose-bearing keys — nova's defaults
114
+ plus, typically, a display-field suffix (`{ suffixes: ['_display'] }`) so the
115
+ closed-set words a query manufactures are translatable without listing them.
116
+
117
+ Moss supplies the *mechanism*; where the words come from is the app's business
118
+ (rows, files, an API). See [`/docs/I18N.md`](../../docs/I18N.md) for the whole
119
+ picture, including the three channels this pass deliberately does not cover.
120
+
121
+ #### `FunctionSession`
122
+
123
+ What the manifest's in-process functions close over:
124
+
125
+ ```typescript
126
+ type FunctionSession = {
127
+ shell: Shell; // the session's living, durable shell (a getter — a reset replaces it)
128
+ principal: string | null;
129
+ roles: readonly string[];
130
+ wire: FetchFn; // the server's own surfaces, as this session
131
+ runtime: NiscRuntime;
132
+ policy: ScopePolicy; // the caller's compiled scope policy
133
+ grant: (token: string) => void; // session GRANT (login): send it down, reconnect
134
+ revoke: () => void; // session REVOKE (sign-out): close 4403, evict
135
+ };
136
+ ```
137
+
138
+ ### The environment
139
+
140
+ #### `NiscRuntime`
141
+
142
+ ```typescript
143
+ type NiscRuntime = {
144
+ pool: PgPool; // SQL
145
+ db: MutationClient; // writes
146
+ cache?: CacheBackend; // defaults to vex's postgres cache on `pool`
147
+ session: SessionVerifier | 'sessions' | 'dev-open'; // REQUIRED — no default
148
+ shellIdleMs?: number; // idle shell eviction; default 30 min, `0` disables
149
+ sessionRevalidateMs?: number; // live-socket re-verify; default 60s, `0` disables
150
+ shellFrameDelta?: boolean; // send changed canvases as deltas; default off
151
+ socketCompression?: boolean | Record<string, unknown>; // permessage-deflate; default on
152
+ };
153
+ ```
154
+
155
+ `session` is required, deliberately — authentication is the one door that must
156
+ not default open, and it used to. Three answers: `'sessions'` uses moss's own
157
+ stored credential (below); `'dev-open'` trusts every well-formed token and says
158
+ so at boot — harnesses and demo floors; a function is the app's own identity
159
+ provider — return `null` for a token that has expired or been revoked. moss
160
+ never learns what expiry means — it only asks again, on both surfaces.
161
+
162
+ #### `mintSession(pool, principal, ttlMs)` / `sessionOf(pool, token)` / `revokeSession(pool, token)` / `revokeAllFor(pool, principal)`
163
+
164
+ The stored credential behind `session: 'sessions'` — the integration key's
165
+ standard, one table over: 256 bits behind an `st_` prefix, the row keeps only
166
+ the hash, `expires_at` is enforced on every read, and revocation is deleting
167
+ the row (one token, or every token a principal holds). The app mints at its
168
+ own door after its own identity check and hands the token to the terminal;
169
+ its table (`SESSIONS_SEQUENCE`) rides `createServer` boot automatically under
170
+ `'sessions'`. Expired rows are swept on every mint — no timer to run.
171
+
172
+ **Tables go through a ledger.** moss creates no table on its own: its tables are
173
+ [strata](../strata/README.md) sequences — `MOSS_SEQUENCE` (integrations, their
174
+ actions, the generation pointer), `SESSIONS_SEQUENCE`, `TIDE_SEQUENCE` for the
175
+ tide store — and `createServer` applies them with the vex cache's sequence in
176
+ one ledgered run before introspection: once, recorded in `strata_ledger`, and
177
+ refused if the ledger was edited or written by newer code. `migrations` on the
178
+ runtime picks the posture: `'apply'` (default) runs what is pending; `'verify'`
179
+ refuses to boot if anything is, for a deployment that migrates as a deploy step.
180
+ `initIntegrations` and `initSessions` remain for hosts that are not moss's
181
+ server, and go through the same ledger.
182
+
183
+ **Documents are read in this code's grammars.** Stored integration actions
184
+ carry a `grammar` stamp (`INTEGRATION_ACTIONS_STORE`). At boot, after the
185
+ tables, moss upgrades every stored action that is behind — through nova's and
186
+ Prism's grammar sequences plus the app's own (`NiscApp.grammars`: sequences
187
+ whose document steps are Prism configs, e.g. a kit renaming a component's
188
+ prop) — and a row written by newer code refuses the boot. A bundle may declare
189
+ the `grammar` it was built on; intake upgrades its actions from there before
190
+ parsing them, stores them stamped current, and refuses a bundle built on newer
191
+ grammars than the host (*the host must be updated first*). Reads upgrade too:
192
+ a row another process wrote since boot is read current, and one it cannot read
193
+ is left out with a logged sentence. Migration 1 of each sequence is the DDL
194
+ boots used to run, so a database from before the ledger adopts on its next boot.
195
+
196
+ `shellFrameDelta` and `socketCompression` are the two wire-size knobs. They are
197
+ environment settings, not manifest ones — an operational decision about a
198
+ deployment, never something an application is written against. See
199
+ [Wire size](#wire-size).
200
+
201
+ #### `mintDevToken(sub, claims?) : string` / `devSession(token) : string | null`
202
+
203
+ The dev token pair — base64url JSON, `sub` is the principal, no signature and
204
+ no expiry. Reachable only through `session: 'dev-open'`, never by default:
205
+ anybody who can spell a principal's id can be them, which is a property a
206
+ harness wants and a deployment must opt into out loud.
207
+
208
+ ### The server
209
+
210
+ #### `createServer(app, runtime): Promise<MossServer>`
211
+
212
+ Stands up the data layer, **refuses to boot** on an incoherent charter
213
+ (`verifyCharter` + nova's closure audit), memoizes per-principal policy,
214
+ catalogs, and ring-2 variant bindings, mounts the vex surfaces and `/catalog`, and — when the manifest
215
+ declares a shell — the shell host behind the socket. Returns a Hono app extended
216
+ with `{ socket, shells? }`.
217
+
218
+ #### `MossServer`
219
+
220
+ `Hono<Env> & { socket: SocketAccept; shells?: ShellHost; principalOf; page; … }`.
221
+ It's a Hono app — mount it, extend it, or hand it to a listener.
222
+
223
+ - `principalOf(token): Promise<string | null>` — the deployment's own session
224
+ verifier, the one every surface already asks. For an app's route that receives
225
+ a credential some other way than a Bearer header (a page request carries a
226
+ cookie). `null` is a refusal.
227
+ - `pages: readonly { name, path }[]` — every page the manifest declares, with
228
+ the path it is drawn at: what a build walks to know which paths exist besides
229
+ the app's own.
230
+ - `page(path): { name, host, inputs } | undefined` — the page a path leads to
231
+ (its name, the `ShellHost` that draws it, the input its path carries), or
232
+ `undefined` for a path that is the app's. The document route and the socket
233
+ ask the same question here.
234
+
235
+ ### The document
236
+
237
+ A page request is answered with the screen the socket would have streamed a
238
+ moment later: the caller's shell is read as it stands, drawn to a string by the
239
+ app's kit, and written into the app's own `index.html` beside the snapshot it
240
+ was drawn from. The browser's terminal starts from that snapshot and adopts the
241
+ elements already there. Nothing about the socket changes; a drawn page is a
242
+ first frame delivered early.
243
+
244
+ #### `shells.snapshot(token, principal, options?): Promise<ShellSnapshot>`
245
+
246
+ ```typescript
247
+ type ShellSnapshot = {
248
+ frame: RenderNode[];
249
+ trees: Record<string, RenderNode[]>; // by canvas id — what `attach` would send
250
+ seed?: string; // an ephemeral shell's id seed (see below)
251
+ settled: boolean; // false: the wait ran out and the screen went as it stood
252
+ live: boolean; // can anything on this screen still happen
253
+ why: string[]; // one line per reason it is live
254
+ drawnWith: string[]; // reads whose answers are already in the trees
255
+ };
256
+ ```
257
+
258
+ The current screen for whoever this is, without attaching anything. Read-only:
259
+ the attached connections' baseline is untouched.
260
+
261
+ - **A principal's app shell is built if it is not standing, and kept** — the
262
+ socket would have built it a moment later, and the one the page was drawn from
263
+ is the one the socket attaches to (same shell, same instance ids).
264
+ - **Nobody's shell, and any page's, is built, read and disposed.** It is built
265
+ under a random `seed`, and mints its instance ids in order under it
266
+ (`act-<seed>-<n>`). A terminal names that seed on the socket (`?seed=`); the
267
+ throwaway shell built for its connection mints the same ids, so its first
268
+ frames match the page. The seed is random per document: ids stay unguessable,
269
+ and a stale origin from another shell still names nothing.
270
+ - **It waits for the screen to settle**, for at most `options.waitMs` (default
271
+ 300): the manifest's `seeds` pushed, and no instance still `initializing` —
272
+ nova marks an instance `active` only after its mount hook has been awaited.
273
+ Past the wait the screen goes out as it stands (`settled: false`), with
274
+ whatever is still loading drawn as loading.
275
+ - `options.inputs` — input for canvas seeds, by canvas id, merged over the
276
+ manifest's `inputs`. A page's path parameters arrive here.
277
+
278
+ #### `live`, and `shellNeedOf(definition, entries): ShellNeed`
279
+
280
+ `live` is asked of the instances actually mounted for this principal. A screen
281
+ is live when something on it can still happen:
282
+
283
+ | Reason | Read off |
284
+ |---|---|
285
+ | a person can act on it | a `ui:` trigger, or a two-way `model` binding |
286
+ | it waits on a channel | a `message:` trigger |
287
+ | a read keeps answering | an endpoint whose entry is `refresh: 'reactive'` |
288
+ | it calls code | a `fn:` endpoint that anything calls — code is not read |
289
+ | it cannot be read | a layout kept in the store; a fingerprint the manifest does not carry |
290
+
291
+ A read made while the action opened is **finished**: its answer is in the tree
292
+ (and listed in `drawnWith`). The app's own shell is always live for a signed-in
293
+ principal — it is the thing that is kept. nova supplies the facts
294
+ (`livenessOf`, `@niscorp/nova/reflect`); moss composes the verdict, because it
295
+ holds the entries behind each fingerprint.
296
+
297
+ When `live` is false the trees are the whole of the screen, and the terminal
298
+ opens no socket.
299
+
300
+ #### `renderDocument(config): Promise<DrawnDocument>`
301
+
302
+ ```typescript
303
+ const page = await renderDocument({
304
+ server, // the MossServer
305
+ template, // the app's index.html, as it would go out undrawn
306
+ request: { path, cookie }, // what the request named and carried
307
+ draw: (snapshot) => renderSnapshot({ snapshot, registry, slotWrapper }),
308
+ htmlAttributes: (snapshot) => ({ 'data-accent': … }), // optional
309
+ });
310
+ // → { html, headers, drawn, principal, page?, live?, why?, drawnWith?, settled? }
311
+ ```
312
+
313
+ - **Which shell**: the page `server.page(path)` names, else the app's.
314
+ - **For whom**: the principal behind the cookie named by the wire's token key
315
+ (`tokenKey`, default `nisc.token`), or nobody. A cookie that no longer
316
+ resolves is nobody, and the response takes it back (`Set-Cookie`, `Max-Age=0`).
317
+ A verifier that *throws* is a fault, not a sign-out: the page goes out
318
+ undrawn and the cookie stays.
319
+ - **`draw`** is a terminal that draws to a string — the app's kit bound to
320
+ `renderSnapshot` from `terminal/react/server`, `terminal/vue/server` or
321
+ `terminal/dom/server`. It may be async.
322
+ - **`htmlAttributes`** is for what a kit would otherwise set on `<html>` from an
323
+ effect, which never runs on a server: a palette, a colour scheme. Read it off
324
+ the same node the effect reads it from. Values are escaped.
325
+ - **`template`** must hold the empty root (`root`, default
326
+ `<div id="root"></div>`). The screen goes inside it, the snapshot element
327
+ straight after.
328
+ - **Nothing here can fail a page.** A kit component that throws, a shell that
329
+ will not build: the answer is the template as it is (`drawn: false`), and the
330
+ terminal paints it the way it did before any of this existed.
331
+
332
+ The route is the app's own — in production `mountSite` from `@niscorp/moss/node`
333
+ (what `nisc start` mounts), in dev a vite middleware that runs
334
+ `index.html` through `transformIndexHtml` first so the drawn page still carries
335
+ vite's client.
336
+
337
+ #### `documentHeaders(principal)` — who may keep a page
338
+
339
+ | Drawn for | `Cache-Control` | `Vary` |
340
+ |---|---|---|
341
+ | nobody | `no-cache` | `Cookie` |
342
+ | somebody | `private, no-store` | `Cookie` |
343
+
344
+ This is the whole rule, and it is in one place: who may keep a page follows from
345
+ who asked. A page drawn for nobody is the same for everybody; a page drawn for
346
+ somebody is theirs. No page declares which it is.
347
+
348
+ #### `exportDocuments(config): Promise<ExportedDocument[]>`
349
+
350
+ The same draw, for nobody, once per path in `config.paths` — what a static host
351
+ serves. There is no credential to pass and no way to pass one: a file is the
352
+ page as nobody in particular sees it, which is the only page that may be kept.
353
+ Each result carries `{ path, html, page?, drawn, live, why, drawnWith, settled }`.
354
+ A page that is `live` is still written, and says why — its file is a true first
355
+ screen and its terminal will look for a socket. Whether that is acceptable (a
356
+ server stands beside the files) or a mistake (there is none) is the build's to
357
+ decide, from the report. Writing the files, and listing a parameterised page's
358
+ paths (`server.executeAs` runs a seeded read as a charter role), are the
359
+ caller's.
360
+
361
+ #### `embedSnapshot(snapshot, principal, path?)`, `tokenFromCookie(header, tokenKey?)`
362
+
363
+ The two halves `renderDocument` is made of, for a host that assembles its own
364
+ page. `embedSnapshot` writes the snapshot as a
365
+ `<script type="application/json" id="nisc-snapshot">` element with every `<`
366
+ (and U+2028/2029) escaped: a tree carries what people typed, and nothing in it
367
+ can close the element or open another.
368
+
369
+ #### `createPageRouter(pages): PageRouter`
370
+
371
+ `{ match(path): { name, params } | undefined }` — the matching rule above, for a
372
+ tool that needs it without a server.
373
+
374
+ ### Reacting to writes
375
+
376
+ Vex is the choke point every application write passes through, so its write
377
+ observer is where a host learns about all of them. Moss subscribes once and
378
+ splits the news down two lanes with deliberately different privileges.
379
+
380
+ #### `app.reactions` — the app's lane, row-less
381
+
382
+ ```ts
383
+ reactions: [
384
+ { table: 'notifications', op: 'insert',
385
+ run: ({ fingerprint, table, op, count, scope }, { deliver }) => { … } },
386
+ { table: 'studio_integrations', run: () => resync() },
387
+ ]
388
+ ```
389
+
390
+ Interest is **declared**, not discovered: moss routes each committed statement
391
+ to the reactions whose `table` (and optional `op`) match, so app code never
392
+ hears about writes it did not ask for and never string-matches a fingerprint
393
+ to work out what happened. `deliver(principal, channel, payload?)` publishes
394
+ onto a principal's live durable shell over the socket the shells already run.
395
+
396
+ Two rules hold this lane honest:
397
+
398
+ - **A reaction is told THAT a write landed, never what it wrote.** No rows.
399
+ A receiver that wants the data re-reads it under its own policy — a row
400
+ handed to imperative code is a row outside every fence the stack builds,
401
+ and `deliver` payloads are pings for the same reason.
402
+ - **Zero-row statements fire nothing.** An update the scope narrowed to
403
+ nothing, an insert a conflict clause skipped: nothing changed, so there is
404
+ no news. A reaction is never told about a write that did not happen.
405
+
406
+ A reaction naming a table nothing writes is not an error anywhere — it simply
407
+ never fires. Derive the names from `mutationEffect` over your own entries and
408
+ assert them in a check.
409
+
410
+ #### `app.facts` — the tide lane, rows and all
411
+
412
+ ```ts
413
+ facts: {
414
+ tide: () => driver, // the waking intake
415
+ identity: (scope) => `automation@${scope['studioId']}`,
416
+ chain: (scope, hints) => (isRobot(scope) ? hints : undefined),
417
+ }
418
+ ```
419
+
420
+ Each committed row becomes one `{ kind: 'write', entity, op, row }` fact.
421
+ Rows travel here because tide has the fence that makes it safe: `identity`
422
+ stamps each fact from the **write's own scope**, and tide offers a fact only
423
+ to reflexes running under the same identity — so whose write it was decides
424
+ who may be woken by it. Returning `undefined` mints nothing (an operator
425
+ surface, a write with no tenant).
426
+
427
+ `chain` is the causality gate. A tide effect writing back through vex names
428
+ its chain position in `x-tide-cause` / `x-tide-depth`; this decides whether
429
+ that caller's word is good, so the chain-depth ceiling survives the trip
430
+ through the database. Absent = hints are always dropped, which is the safe
431
+ default: a forged depth could park an innocent chain.
432
+
433
+ #### `createTideDriver({ tide, janitorMs?, retention? }) : TideDriver`
434
+
435
+ Tide reads no clocks and paces nothing; this is the thing that does.
436
+
437
+ - **Wake** — `ingest` and `fire` advance the engine immediately, to
438
+ quiescence: a chain advances one committed hop per step, so the driver
439
+ loops until a step reports nothing moved. `wake()` returns the promise of
440
+ that drain, so a "run it now" button can await a settled world.
441
+ - **Sleep** — after quiescence, `tide.nextDue(now)` names the next instant
442
+ worth waking for and one timer sleeps until exactly then, preempted by any
443
+ ingest. No beat, no polling for work.
444
+ - **Janitor** — a slow fallback wake plus the retention sweep. It finds
445
+ nothing when nothing is broken; it exists because a durable multi-worker
446
+ design needs the scan that notices work committed by a process that died
447
+ before its own wake ran. It is how work is *recovered*, never how it moves.
448
+
449
+ Hand `app.facts.tide` the **driver**, not bare tide, so a minted fact wakes
450
+ the engine instead of waiting for somebody's beat.
451
+
452
+ ### Resolution (exposed for tools)
453
+
454
+ - `resolveRoles(app, principal): readonly string[]` — assignment rows; anonymous/
455
+ unassigned wears `['public']`.
456
+ - `resolvePolicy(app, grants, principal): ScopePolicy` — the compiled vex policy
457
+ this principal reads and writes under. **One policy per role, merged** — a
458
+ person may hold several (an instructor who also trains here), and reach belongs
459
+ to the role rather than to the person. The merge is a union: broadest wins.
460
+ - `resolvePolicyAtReach(app, grants, principal, reach): ScopePolicy` — the same
461
+ principal's grants recompiled under a named profile, for entries that declare
462
+ a `reach` (vex). Wired into the vex surfaces automatically; narrows rows,
463
+ never widens verbs.
464
+ - `resolveCatalog(app, principal): Catalog` — `{ ids, hash }`, granted action ids
465
+ sorted, with a content-hash version token (equal hash, equal application).
466
+ - `resolveVariants(app, principal): ReadonlyMap<string, LayoutNode>` — action id →
467
+ the granted variant's layout (ring 2; empty map = every action serves its base).
468
+ - `verifyVariants(app): string[]` — the ring-2 boot gate: every variant reshapes a
469
+ shipped action, and no wearable role combination holds two variants of one
470
+ action. Non-empty = refuse to boot.
471
+ - `createDataLayer(runtime, entries?): Promise<DataLayer>` — `{ engine, schema,
472
+ grants }`, stood up from what's present.
473
+ - `createShellHost(ctx): ShellHost` — the durable per-principal shell host.
474
+ `ctx.idleMs` bounds how long a shell may sit unattached (default
475
+ `DEFAULT_IDLE_MS`, 30 minutes; `0` disables the sweep).
476
+ - `ShellHost` — `{ session, adopt, list, reset, stop }`.
477
+ - `list(): ShellReport[]` — every durable shell alive right now:
478
+ `{ principal, connections, since, idleSince, canvases }`. moss owns the map,
479
+ so moss enumerates it; an app keeping its own note beside it can only drift.
480
+ - `reset(principal): boolean` — dispose that principal's shell and stand its
481
+ replacement in the same slot, carrying the attached connections across.
482
+ `false` = they hold no shell, which is an answer, not an error.
483
+ - `stop()` — stop the idle sweep (the timer is unref'd, so a plain process
484
+ needn't call it).
485
+ - `ShellSession` — what `ShellHost.session(token, principal)` returns:
486
+ `{ shell, attach, detach, resync, dispatch, publish, back, reset }`. The living nova `Shell`,
487
+ for in-process hosts (dev checks, embedded tools) that drive it directly;
488
+ remote clients ride `attach`/`dispatch`. `shell` is a **getter** — `reset`
489
+ replaces the shell under a session already held, so a snapshot of the field
490
+ would go on addressing the disposed one.
491
+ - `auditClosure(definitions, variants?): ClosureAuditor` — nova's action audit as
492
+ the charter's injected closure hook (cross-action wiring breaks only), over each
493
+ role's effective definitions (granted variants substituted).
494
+
495
+ ### The socket protocol
496
+
497
+ - `createSocket(ctx): SocketAccept` — `ctx = { session, catalog, shells?, page?,
498
+ revalidateMs? }`. One `accept(url, connection)` per connection; `accept.stop()`
499
+ ends revalidation (the timer is unref'd, so a plain process needn't call it).
500
+ - **Identity is asked twice.** At upgrade, and then every `revalidateMs`
501
+ (default `DEFAULT_REVALIDATE_MS`, 60s; `0` disables) for as long as the
502
+ connection lives. A token that stops resolving — or starts resolving to
503
+ somebody else — gets an `invalid_token` error frame and a `4401` close, which
504
+ is the recovery the terminal already performs: drop the token, reconnect
505
+ anonymous, land on the served lock screen.
506
+ - Anonymous connections are never revalidated: nothing they hold can expire.
507
+ - A verifier that **throws** is a fault, not a sign-out — the connection is
508
+ left alone and asked again next pass, so a database blip cannot become an
509
+ outage. Only an explicit `null` (or a changed principal) closes.
510
+ - Without this the socket was the asymmetry: the HTTP surfaces re-ask on
511
+ every request, so an expired credential left the socket open and rendering
512
+ while every endpoint the server shell called came back 401 — a live
513
+ interface whose every load silently fails.
514
+ - `Connection` — the transport seam: `{ send, close, onMessage, onClose }`.
515
+ - `ServerMessage` — `hello | catalog | frame | render | render-delta | session | error`.
516
+ - `ClientMessage` — `event | publish | resync | reset | back`.
517
+ - `render-delta` is only ever sent to a connection that advertised `?delta=1`
518
+ on the upgrade, and only when the server is configured for it. Everything
519
+ else is served whole frames, unchanged. See [Wire size](#wire-size).
520
+ - `resync` says *this connection's copy of a canvas is not what you think it
521
+ is* — a delta failed its checksum, or arrived with no base. It is answered
522
+ with whole frames, the state both ends can always agree on. Distinct from
523
+ `reset`: the shell is fine, only this connection's copy drifted, so nothing
524
+ is torn down and no other terminal notices.
525
+ - `reset` names no canvas, deliberately: it is the recovery for a session whose
526
+ canvases are the broken thing, so it must not travel through one. It is
527
+ protocol-level, not app-level — no action declares it and no charter grants
528
+ it — and it is answered by the frames it produces, not by an envelope of its
529
+ own.
530
+ - `back` names no canvas either, and for a related reason: back is one gesture
531
+ over the whole shell, and the terminal that sends it has no idea which canvas
532
+ moved last — it is served trees, not stacks. The shell decides what back
533
+ means (nova's navigation journal, SHELL_DOCS § `back()`), and it is answered
534
+ by whatever canvases moved. Protocol-level, so a browser's back button, a
535
+ TUI's Escape and an app's own control are one message on one wire, and an app
536
+ authors nothing to receive it.
537
+ - `CLOSE_INVALID_TOKEN = 4401`, `CLOSE_SIGNED_OUT = 4403`,
538
+ `CLOSE_PROTOCOL_MISMATCH = 4426`.
539
+ - **Protocol version.** `PROTOCOL` is the wire protocol this server speaks and
540
+ `PROTOCOL_MIN` the oldest it still serves. A terminal names its protocol on
541
+ the upgrade (`?protocol=N`, beside the token); one that names none speaks `1`,
542
+ which is every terminal built before the question existed. Outside the range
543
+ the connection is refused before anything is served: an `error` frame
544
+ (`client_too_old` or `server_too_old`) and a `4426` close. `hello` carries
545
+ `protocol`, so a terminal can refuse a server older than it can speak to.
546
+ Bump `PROTOCOL` when a message changes shape; raise `PROTOCOL_MIN` only when
547
+ the server stops speaking an old one.
548
+ - **`?path=`** — the path the terminal is on. A path that leads to a page is
549
+ served that page's shell, built for this connection alone and seeded with the
550
+ path's parameters; any other path (and no path) is the app's shell. A
551
+ signed-in terminal on a page does not build its principal's app shell.
552
+ - **`?seed=`** — the id seed of the page the terminal was drawn from (see
553
+ [`shells.snapshot`](#the-document)). An ephemeral shell built under it mints
554
+ the same instance ids as the page's. Ignored for a kept shell, and ignored
555
+ unless it is 8–40 hex characters.
556
+ - Both are optional and unknown to older servers, which ignore them: `PROTOCOL`
557
+ is unchanged.
558
+ - A canvas whose layout renders no visible content is served as an empty
559
+ tree (`[]`), so a terminal collapses chrome on `length` alone. An
560
+ `ActionSlot` is a boundary, not content — visibility is decided by what's
561
+ inside it.
562
+
563
+ ### Wire size
564
+
565
+ Two independent reductions, both optional, both invisible to an application.
566
+ Neither changes a rendered tree, and an app that sets neither behaves exactly
567
+ as it did before they existed. The reasoning and the measurements are in
568
+ DESIGN.md § What a frame costs.
569
+
570
+ #### Compression — `runtime.socketCompression`, default **on**
571
+
572
+ `permessage-deflate` (RFC 7692), negotiated by the transport below the
573
+ `Connection` seam. Nothing in moss or in an app sees it, and every browser
574
+ understands it.
575
+
576
+ ```typescript
577
+ socketCompression: true // the default
578
+ socketCompression: false // off
579
+ socketCompression: { threshold: 4096 } // passed through to `ws`
580
+ ```
581
+
582
+ Roughly 3–4× on render trees. The cost is memory: about **260 KB resident per
583
+ connection** at the `ws` defaults, against about 43 KB for the shell being
584
+ served. Turn it off — or tune `zlibDeflateOptions.memLevel` / `windowBits`
585
+ through the object form — when connection count matters more than bandwidth.
586
+ An object is handed to `ws` verbatim; see its `perMessageDeflate` options.
587
+
588
+ #### Frame deltas — `runtime.shellFrameDelta`, default **off**
589
+
590
+ A changed canvas, described against the frame that connection already holds:
591
+ copy runs from the old frame plus literal inserts, checksummed.
592
+
593
+ ```typescript
594
+ // server
595
+ const server = await serve(app, { pool, db, shellFrameDelta: true });
596
+
597
+ // terminal — both ends have to want it
598
+ const wire = createWire({ delta: true });
599
+ ```
600
+
601
+ **Both ends must opt in.** The terminal advertises `?delta=1` on the upgrade
602
+ url; the server sends deltas only if `shellFrameDelta` is on *and* the delta is
603
+ at most 60% of the whole frame. A terminal that never advertises — including
604
+ every terminal built before this existed — receives whole frames forever, from
605
+ the same shell, in the same pass. The two kinds of connection coexist.
606
+
607
+ What it buys, measured on Lyra:
608
+
609
+ | change | delta, as a share of the whole frame |
610
+ | --- | --- |
611
+ | in-place (keystroke, one row's badge) | 1–4% |
612
+ | navigation (a genuinely different tree) | ~80% — over the threshold, so sent whole |
613
+
614
+ Correctness, which matters more than the saving:
615
+
616
+ - Every `render-delta` carries `hash`, a checksum of the frame it must rebuild.
617
+ A terminal that lands anywhere else — bad ops, missing base, a decode that
618
+ throws — **discards the result**, keeps the tree it was already showing, and
619
+ sends `resync`. It never renders a partially applied frame and never throws
620
+ on the connection.
621
+ - Bases are dropped on every reconnect: attaching is served whole frames, so a
622
+ base carried across a reconnect is one the server never assumed.
623
+ - A `reset` carries the capability across to the replacement shell.
624
+ - `src/delta.ts` is the whole implementation — `encodeDelta`, `applyDelta`,
625
+ `frameHash` — with no dependency, small enough to read in full. A delta layer
626
+ that cannot be audited is a desync you cannot diagnose.
627
+
628
+ ## `@niscorp/moss/node`
629
+
630
+ - `serve(app, runtime & { port? }): Promise<MossServer>` — boots and listens:
631
+ `createServer` runs inside (boot refusal included), then HTTP + the socket
632
+ in one process. `port` defaults to 8787.
633
+ - `attachSocket(httpServer, accept, path?, options?)` — embed the socket on an
634
+ existing server (raw `ws`, `noServer`, path-matched — coexists with vite
635
+ HMR). `path` defaults to `/socket`. `options = { compression? }` is the same
636
+ value as `runtime.socketCompression` and defaults to `true`; `serve()` passes
637
+ the runtime's through for you, so only a host running its own listener (a
638
+ vite plugin, a dev check) ever needs it.
639
+
640
+ - `mountSite(server, { dist, draw, htmlAttributes?, tokenKey?, waitMs?, owned? })`
641
+ — the built terminal, served by the same process as the app. Every GET that
642
+ nothing registered earlier answers is a file from `dist`, or a page:
643
+ `index.html` with the caller's screen drawn into it (`renderDocument`) — the
644
+ app's own for `/`, one of the manifest's pages for a path that leads to one.
645
+ `index.html` itself never goes out as a file. Register the app's own routes
646
+ first; this is the catch-all. `owned` (default: moss's own prefixes) names
647
+ what is never a page — an unknown path under one is a 404, not a screen.
648
+
649
+ ## `@niscorp/moss/client`
650
+
651
+ - `createWire(config?): Wire` — the app end of the socket. `config = { url?,
652
+ env?, delta?, initial?, path? }`. Plain TypeScript, no React, no globals — everything
653
+ host-shaped comes in as a `WireEnv`. `delta` (default `false`) advertises
654
+ that this terminal can rebuild frame deltas; the snapshot it produces is
655
+ identical either way. See [Wire size](#wire-size).
656
+ - `WireEnv` — the host seam: `{ tokens: { load, save, clear }, socket(url),
657
+ defaultUrl() }`. The socket API is WHATWG-standard in every host (browser,
658
+ Node ≥22, Bun); an env only constructs it.
659
+ - `browserEnv({ tokenKey?, cookie? }?): WireEnv` — the default host: token in
660
+ localStorage (`nisc.token`), url derived from `window.location`, the
661
+ page's WebSocket. `cookie: true` keeps a **copy** of the token in a cookie of
662
+ the same name (`Path=/; SameSite=Lax`, `Secure` on https), written and
663
+ cleared with the stored one and levelled with it on every load — so a token
664
+ put in localStorage by something else (a sign-in handoff page) reaches the
665
+ cookie on the first load after it. A page request carries cookies and nothing
666
+ else; this is what lets a server draw the page for whoever is asking. The
667
+ cookie is only ever read to draw a page — every other surface still wants the
668
+ token itself — so it adds no way in.
669
+ - `readDocumentSnapshot(doc?): DocumentSnapshot | undefined` — the snapshot a
670
+ server-drawn page carries (`{ frame, trees, principal, seed?, path?, live? }`),
671
+ or `undefined` for a page that carries none. Never throws.
672
+ - `initial` — pass what `readDocumentSnapshot()` returned. The wire starts from
673
+ it instead of from nothing, so the first render matches the page's HTML and
674
+ the first frames off the socket confirm it. It is used only when it was drawn
675
+ for who this terminal is — signed in and holding a token, or neither;
676
+ anything else is somebody else's screen and the wire starts empty. Its `seed`
677
+ is named on the first connect only. Its `path` is named on every connect
678
+ (`config.path` overrides it; a page that was not drawn on the server passes
679
+ `location.pathname` there).
680
+ - **A page with nothing left to happen opens no socket.** When `initial.live`
681
+ is `false`, the wire does not connect and `status()` is `'static'`. `reset()`,
682
+ or a token arriving, connects after all.
683
+ - `Wire` — `{ subscribe, snapshot, status, dispatch(canvas, event), publish,
684
+ reset, back, dispose }`. `snapshot()` is `{ frame, trees }`; `status()` is
685
+ `'connecting' | 'open' | 'closed' | 'incompatible' | 'static'` and changes notify subscribers like
686
+ snapshot changes do (a renderer must be able to tell a dead socket from an
687
+ empty app). Hand it to a renderer.
688
+
689
+ Reconnect is exponential backoff with jitter, capped at 30s, reset when a
690
+ connection opens and on any principal change (a session grant or a close-code
691
+ recovery starts the backoff clean). Two close codes are recoveries, not retries: `4403`
692
+ (signed out) and `4401` (invalid token) both drop the stored token and
693
+ reconnect anonymous — retrying with a stale token would loop forever. A
694
+ `4426` (protocol mismatch, either direction) is neither: the wire stops and
695
+ reports status `incompatible`, because every retry would speak the same
696
+ protocol again — a browser terminal needs a reload for the current build. Server
697
+ `error` frames and unknown message types are `console.warn`ed; `hello` and
698
+ `catalog` are deliberately ignored (the terminal is grant-blind).
699
+
700
+ `reset()` is the escape from a wedged shell, and the only one that can work:
701
+ the shell is server state keyed by principal, so dropping the token here hands
702
+ you a throwaway anonymous shell and signing back in reattaches to the same
703
+ wreck. On an open socket it sends `{ type: 'reset' }` and the fresh frame
704
+ arrives on that same socket — same session, same token, nothing signed out. On
705
+ a dead one it reconnects immediately instead of waiting out the backoff, which
706
+ is the same recovery a layer down.
707
+
708
+ **Nothing is sent on a socket that is not open, and nothing is queued.**
709
+ `dispatch` and `publish` are dropped unless `status()` is `'open'` — the posture
710
+ `back` and `popTo` always had. A server-drawn page is on screen before its
711
+ socket is, so there is a moment in which something can be pressed with nothing
712
+ to send it over; an intention replayed against a screen that may have moved is
713
+ worse than one lost, and a browser socket that is still connecting throws on
714
+ `send`.
715
+
716
+ `back()` sends `{ type: 'back' }` and nothing else — no location is held here,
717
+ so what comes back is whatever canvases moved, over the same stream every other
718
+ change arrives on. It is dropped on a closed socket rather than queued: a back
719
+ pressed during an outage is about a screen the person is no longer being served,
720
+ and replaying it on reconnect would move them somewhere they asked to go one
721
+ outage ago.
722
+
723
+ ```typescript
724
+ import { createWire } from '@niscorp/moss/client';
725
+ const wire = createWire(); // browser host; token from localStorage
726
+ wire.subscribe(() => render(wire.snapshot()));
727
+ wire.dispatch('main', { type: 'ui:click', ref: 'save' });
728
+ ```
729
+
730
+ ## `@niscorp/moss/client/node`
731
+
732
+ - `nodeEnv({ url, tokenFile? }): WireEnv` — the wire on a plain Node (or Bun)
733
+ process: token in a file (default `~/.moss/token`), the runtime's WHATWG
734
+ WebSocket, `url` explicit (a process has no location to derive one from).
735
+ Its own entry so node builtins never enter a browser bundle.
736
+
737
+ ```typescript
738
+ import { createWire } from '@niscorp/moss/client';
739
+ import { nodeEnv } from '@niscorp/moss/client/node';
740
+ const wire = createWire({ env: nodeEnv({ url: 'ws://127.0.0.1:8787/socket' }) });
741
+ ```
742
+
743
+ ## `@niscorp/moss/terminal`
744
+
745
+ The terminal: the wire plus a **render target**. Framework-blind — targets live
746
+ in the subpaths.
747
+
748
+ - `createTerminal({ target, wire }): { destroy }` — the conductor: one
749
+ target, one wire. Subscribes the target's `update` to the wire and routes
750
+ events back.
751
+ - `mountTerminal(config): { swap, reset, back, destroy }` — the switcher:
752
+ hot-swaps render targets over ONE wire, so the socket, session, and current
753
+ trees survive the swap. `config = { targets, swapKey?, resetKey?, trapBack?,
754
+ initial?, wire?, url? }` — targets by name, cycled in insertion order;
755
+ `swapKey` (e.g. `"ctrl+shift+y"`) binds the hotkey, and `swap` is returned for
756
+ a host's own control. Omit `wire` and the terminal makes (and owns) one; `url`
757
+ seeds it. `resetKey` binds `wire.reset()` — the escape hatch, on a keystroke
758
+ because it has to work when every surface on screen is dead. Both hotkeys are
759
+ browser-only (they listen on `window`); a TTY or Node host binds `swap` and
760
+ `reset` to its own control instead.
761
+ - **The back gesture.** `trapBack` (default **on**) catches the browser's back
762
+ button and sends it up the wire instead of letting it unload the page. It
763
+ keeps one spare history entry ahead of the page and spends it on every press,
764
+ putting another straight back — so the URL never changes and the application
765
+ is never left. Nothing at all where there is no history to catch (a TTY, a
766
+ TUI, a plain process), so the conductor asks for it unconditionally. `back` is
767
+ returned for a host's own control, and `trapBack: false` leaves the page's
768
+ back button to the host.
769
+
770
+ It does not touch the address bar, and that is the honest position while
771
+ location lives on the server: a shell is keyed by principal, not by tab, so a
772
+ URL would be a per-tab claim on state two tabs share. Deep links, when they
773
+ come, are a projection of the shell's own location — and the gesture is
774
+ already here.
775
+ - `TerminalApi` — what a target renders against: nova core's `RenderApi`
776
+ (`frame`, `canvasTree`, `dispatch`, `publish`), aliased not redeclared — the
777
+ DOM adapter, the React adapter, and the conductor share one contract. A
778
+ target never touches the wire directly.
779
+ - `Target` — `(api) => TerminalMount` where `TerminalMount = { update,
780
+ destroy }`. The render surface (a DOM root, a stdio pair) is construction
781
+ config on the concrete target, never part of the contract — the conductor
782
+ is surface-blind and runs anywhere the wire does. Renders once on mount;
783
+ the conductor calls `update` on every wire change.
784
+
785
+ ```typescript
786
+ import { mountTerminal } from '@niscorp/moss/terminal';
787
+ import { reactTarget } from '@niscorp/moss/terminal/react';
788
+ import { domTarget } from '@niscorp/moss/terminal/dom';
789
+
790
+ const root = document.getElementById('root')!;
791
+ mountTerminal({
792
+ targets: { react: reactTarget({ root, registry, slotWrapper }), dom: domTarget({ root }) },
793
+ swapKey: 'ctrl+shift+y',
794
+ resetKey: 'ctrl+shift+u', // ask the server for a fresh shell
795
+ });
796
+ ```
797
+
798
+ ## `@niscorp/moss/terminal/react`
799
+
800
+ Requires the optional `react`/`react-dom` peers.
801
+
802
+ - `reactTarget({ root, registry, slotWrapper? }): Target` — the app's
803
+ component registry bound to the wire via nova's React adapter, rendered
804
+ into `root`. Registers wire-backed `CanvasSlot` and `ActionSlot` (the
805
+ terminal has no shell for nova's shell-backed ones).
806
+ - `registerWireSlots(registry, { slotWrapper?, fallback?, textWrapper?,
807
+ errorMarker?, canvasProvider?, instanceProvider? })` + `TerminalApiContext` — the wire-backed
808
+ slots themselves, shared by every react-shaped target (`terminal/ink`
809
+ imports them); a custom react-shaped target starts here.
810
+ - `TerminalSlotWrapper` — an app component wrapping each action instance at
811
+ the `ActionSlot` boundary; the terminal twin of nova's client-shell
812
+ SlotWrapper. Served trees carry identity only, so the props are
813
+ `{ canvasId, instanceId, definitionId }` — `definitionId`, not `action`.
814
+ - **Adoption.** A `root` that already holds elements, on a wire that has a
815
+ frame, was drawn on the server from the snapshot the wire started from: the
816
+ target adopts those elements (`hydrateRoot`) instead of replacing them. An
817
+ empty root, or a wire with no frame (the page was drawn for somebody else),
818
+ is rendered as before.
819
+
820
+ ### `@niscorp/moss/terminal/react/server`
821
+
822
+ - `renderSnapshot({ snapshot, registry, slotWrapper? }): string` — the React
823
+ target, drawing to a string: the same registry, the same wire slots and the
824
+ same tree as the browser's target, so what a server writes is what the browser
825
+ adopts. Its own entry, so a browser bundle never carries `react-dom/server`.
826
+
827
+ **What a kit owes a server-drawn page.** The first pass in the browser must
828
+ draw exactly what the server drew, so nothing that differs between the two may
829
+ decide a component's first render:
830
+
831
+ - The window (its width, a media query, `localStorage`) — read it through
832
+ `useSyncExternalStore` with a server snapshot, or in an effect, never in a
833
+ `useState` initialiser guarded by `typeof window`. That guard is the bug: it
834
+ makes the two sides disagree about the same render.
835
+ - A portal — only after the first pass (the server has no `document.body`).
836
+ - What a component puts on `<html>` from an effect is not in the page until the
837
+ script runs; give it to `renderDocument`'s `htmlAttributes`.
838
+
839
+ An app holds this with a check: draw the page, open it in a DOM with the real
840
+ wire and target, and assert React said nothing (atrium's and lyra's `ssr-check`).
841
+
842
+ ## `@niscorp/moss/terminal/vue`
843
+
844
+ Requires the optional `vue` peer.
845
+
846
+ - `vueTarget({ root, registry, slotWrapper? }): Target` — the app's Vue
847
+ component registry bound to the wire via nova's Vue adapter, mounted on
848
+ `root` with `createApp`. Registers wire-backed `CanvasSlot` and
849
+ `ActionSlot` — the same origin rule as the react target (an event from
850
+ inside an instance boundary carries that instance as `origin` unless it
851
+ already has one). `update` never remounts: the target's reads of the wire
852
+ depend on a revision the conductor bumps, so only the frame and the canvas
853
+ slots re-render and Vue patches in place — focus and input drafts survive.
854
+ - `TerminalApiKey` — the injection key of the live `TerminalApi` (a kit
855
+ component reading `frame()` / `canvasTree()` in its render re-renders on
856
+ wire updates).
857
+ - `TerminalSlotWrapper` — a Vue component wrapping each action instance at
858
+ the `ActionSlot` boundary, handed `{ canvasId, instanceId, definitionId }`
859
+ as props and the content as its default slot.
860
+ - **Adoption**, as the react target: a root that holds server-drawn elements,
861
+ on a wire with a frame, is mounted with `createSSRApp` and adopted.
862
+ - `registerWireSlots(registry, slotWrapper?)`, `terminalFrame(api, registry)` —
863
+ the wire slots and the frame component, shared with the server entry.
864
+
865
+ ### `@niscorp/moss/terminal/vue/server`
866
+
867
+ - `renderSnapshot({ snapshot, registry, slotWrapper? }): Promise<string>` — the
868
+ Vue target, drawing to a string through Vue's own server renderer (which is
869
+ asynchronous, so this is).
870
+
871
+ ## `@niscorp/moss/terminal/dom`
872
+
873
+ - `domTarget({ root, registry? }): Target` — nova's DOM adapter plus nova's
874
+ default component kit rendered into `root`, stylesheet injected once per
875
+ document. Zero framework; pass a registry to restyle. It needs no adoption:
876
+ nova's DOM adapter rebuilds its root on every render, so its first render
877
+ replaces server-drawn elements with the same elements in one synchronous step.
878
+
879
+ ### `@niscorp/moss/terminal/dom/server`
880
+
881
+ - `renderSnapshot({ snapshot, registry?, window }): string` — the DOM target,
882
+ drawing to a string. A DOM kit builds real elements, so the host hands in a
883
+ DOM to build them in (`window`: jsdom, happy-dom, linkedom — moss depends on
884
+ none). A kit's components name `document` as a global, so for the length of
885
+ one draw — synchronous, start to end — the window's names are lent to the
886
+ global scope and taken back whatever happens.
887
+
888
+ ## `@niscorp/moss/terminal/tty`
889
+
890
+ - `ttyTarget({ input, output, registry?, fallback?, onQuit?, status?,
891
+ debounceMs?, prompt? }): Target` — the line-terminal target: a REPL over
892
+ the wire. Pass `status: wire.status` and the REPL reports connection
893
+ transitions (`… connecting`, `✓ connected`, `× connection lost — retrying`)
894
+ — once per real transition, never the backoff flap.
895
+ nova's TTY adapter renders each served frame to text with numbered `[n]`
896
+ markers; commands map onto them with the same event vocabulary every other
897
+ target dispatches. Runs on any Readable/Writable pair — a real TTY, a
898
+ test's PassThrough, a pipe. `onQuit` fires on `quit`/EOF (the host owns
899
+ the wire and the process); `debounceMs` (default 80) coalesces a burst of
900
+ wire updates into one repaint.
901
+
902
+ Typing IS the input scheme — numbers act, words fill: a bare number taps
903
+ `[n]` (click a button or row, flip a toggle, focus an input — the next line
904
+ typed is the focused input's value, verbatim; an empty line cancels), and
905
+ bare words go straight into the only input on screen. Explicit forms
906
+ (`click/set/toggle/key <n> …`) plus `refs`, `show`, `publish <ch> [json]`,
907
+ `help`, `quit`. All of it is target policy — the wire sees ordinary events.
908
+
909
+ ```typescript
910
+ import { createWire } from '@niscorp/moss/client';
911
+ import { nodeEnv } from '@niscorp/moss/client/node';
912
+ import { createTerminal } from '@niscorp/moss/terminal';
913
+ import { ttyTarget } from '@niscorp/moss/terminal/tty';
914
+
915
+ const wire = createWire({ env: nodeEnv({ url: 'ws://127.0.0.1:8787/socket' }) });
916
+ createTerminal({ target: ttyTarget({ input: process.stdin, output: process.stdout }), wire });
917
+ ```
918
+
919
+ ## `@niscorp/moss/terminal/ink`
920
+
921
+ - `inkTarget({ registry?, slotWrapper?, stdin?, stdout?, status?, onQuit?, patchConsole? }):
922
+ Target` — the full-screen terminal target: nova's Ink kit
923
+ (`@niscorp/nova/adapters/ink`) on the React adapter's walker, mounted with
924
+ ink's renderer. Interaction is the TTY REPL's numbered addressing plus
925
+ live focus: every interactive shows a `[n]` marker (the numbering is the
926
+ TTY walker run over the same served trees — `[7]` is the same thing in
927
+ the REPL and the TUI), and typed digits act on it — buttons and rows
928
+ click, toggles flip, an input takes focus and typing types (a focused
929
+ input claims digits as text; multi-digit numbers accumulate for a beat,
930
+ unambiguous ones act at once). Tab/Shift+Tab and ↑/↓ still walk the focus
931
+ ring; Enter activates; Ctrl+C leaves (`onQuit` fires). Inputs are
932
+ draft-preserving and `debounce`-honoring (ADAPTER.md §6). `status:
933
+ wire.status` renders a dim connection line while the socket is not open.
934
+ The wire-backed slots are shared with `terminal/react` — same seam,
935
+ different renderer. `patchConsole` (default on) routes the process's
936
+ console above the frame; a host rendering several targets in one process
937
+ (an SSH server, one per connection) turns it off, so its own logs never
938
+ reach whoever is connected. ESM-only, like ink.
939
+
940
+ ```typescript
941
+ import { inkTarget } from '@niscorp/moss/terminal/ink';
942
+ createTerminal({ target: inkTarget({ status: wire.status }), wire });
943
+ ```