@niscorp/moss 0.4.0 → 0.5.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 (175) hide show
  1. package/CHANGELOG.md +481 -0
  2. package/DESIGN.md +265 -49
  3. package/DOCS.md +1524 -341
  4. package/README.md +37 -20
  5. package/dist/app-BoVB0_0j.d.ts +143 -0
  6. package/dist/app-Cc8VnOz8.d.cts +143 -0
  7. package/dist/chunk-3RIWTXGI.cjs +174 -0
  8. package/dist/chunk-3RIWTXGI.cjs.map +1 -0
  9. package/dist/chunk-4ZGAFZGS.js +152 -0
  10. package/dist/chunk-4ZGAFZGS.js.map +1 -0
  11. package/dist/chunk-5U2ZZUI5.cjs +137 -0
  12. package/dist/chunk-5U2ZZUI5.cjs.map +1 -0
  13. package/dist/chunk-6QPTMKRE.cjs +53 -0
  14. package/dist/chunk-6QPTMKRE.cjs.map +1 -0
  15. package/dist/chunk-BQRPR2F7.js +2704 -0
  16. package/dist/chunk-BQRPR2F7.js.map +1 -0
  17. package/dist/chunk-BZK37HR3.cjs +2716 -0
  18. package/dist/chunk-BZK37HR3.cjs.map +1 -0
  19. package/dist/chunk-FTFME3HS.cjs +383 -0
  20. package/dist/chunk-FTFME3HS.cjs.map +1 -0
  21. package/dist/{chunk-U3UR5AOQ.js → chunk-FTZ6NFKZ.js} +43 -16
  22. package/dist/chunk-FTZ6NFKZ.js.map +1 -0
  23. package/dist/chunk-IUJ2TRNB.cjs +57 -0
  24. package/dist/chunk-IUJ2TRNB.cjs.map +1 -0
  25. package/dist/chunk-IW3A2YIC.js +49 -0
  26. package/dist/chunk-IW3A2YIC.js.map +1 -0
  27. package/dist/chunk-JYBHJDT7.cjs +30 -0
  28. package/dist/chunk-JYBHJDT7.cjs.map +1 -0
  29. package/dist/chunk-NRZ3Z2FF.js +61 -0
  30. package/dist/chunk-NRZ3Z2FF.js.map +1 -0
  31. package/dist/chunk-PCPQMC7A.js +26 -0
  32. package/dist/chunk-PCPQMC7A.js.map +1 -0
  33. package/dist/chunk-T5BRTFKP.js +53 -0
  34. package/dist/chunk-T5BRTFKP.js.map +1 -0
  35. package/dist/chunk-TGKDS2T7.cjs +330 -0
  36. package/dist/chunk-TGKDS2T7.cjs.map +1 -0
  37. package/dist/chunk-TLNRFAQ6.js +326 -0
  38. package/dist/chunk-TLNRFAQ6.js.map +1 -0
  39. package/dist/chunk-VKQPOZDJ.cjs +72 -0
  40. package/dist/chunk-VKQPOZDJ.cjs.map +1 -0
  41. package/dist/chunk-ZWB6QDGF.js +374 -0
  42. package/dist/chunk-ZWB6QDGF.js.map +1 -0
  43. package/dist/client/node.cjs.map +1 -1
  44. package/dist/client/node.d.cts +3 -1
  45. package/dist/client/node.d.ts +3 -1
  46. package/dist/client/node.js.map +1 -1
  47. package/dist/client.cjs +14 -302
  48. package/dist/client.cjs.map +1 -1
  49. package/dist/client.d.cts +9 -33
  50. package/dist/client.d.ts +9 -33
  51. package/dist/client.js +2 -2
  52. package/dist/document-CU3muGbz.d.cts +169 -0
  53. package/dist/document-UFbAd-Ka.d.ts +169 -0
  54. package/dist/env-CY8EGWnD.d.cts +24 -0
  55. package/dist/env-DEPqqHEb.d.ts +24 -0
  56. package/dist/index-BuDuOSyx.d.cts +130 -0
  57. package/dist/index-BuDuOSyx.d.ts +130 -0
  58. package/dist/index.cjs +45 -3916
  59. package/dist/index.cjs.map +1 -1
  60. package/dist/index.d.cts +46 -100
  61. package/dist/index.d.ts +46 -100
  62. package/dist/index.js +4 -94
  63. package/dist/index.js.map +1 -1
  64. package/dist/integrations.cjs +975 -0
  65. package/dist/integrations.cjs.map +1 -0
  66. package/dist/integrations.d.cts +63 -0
  67. package/dist/integrations.d.ts +63 -0
  68. package/dist/integrations.js +972 -0
  69. package/dist/integrations.js.map +1 -0
  70. package/dist/messages-CSwCJgH3.d.cts +51 -0
  71. package/dist/messages-CSwCJgH3.d.ts +51 -0
  72. package/dist/node.cjs +17 -3455
  73. package/dist/node.cjs.map +1 -1
  74. package/dist/node.d.cts +13 -10
  75. package/dist/node.d.ts +13 -10
  76. package/dist/node.js +5 -3
  77. package/dist/protocol.cjs +24 -0
  78. package/dist/protocol.cjs.map +1 -0
  79. package/dist/protocol.d.cts +11 -0
  80. package/dist/protocol.d.ts +11 -0
  81. package/dist/protocol.js +3 -0
  82. package/dist/protocol.js.map +1 -0
  83. package/dist/slots-96gNc9uH.d.cts +12 -0
  84. package/dist/slots-BX5N0Juv.d.ts +14 -0
  85. package/dist/slots-CU-AbnJg.d.cts +14 -0
  86. package/dist/slots-sLXDrlbG.d.ts +12 -0
  87. package/dist/socket-D90h1xSV.d.cts +24 -0
  88. package/dist/socket-D90h1xSV.d.ts +24 -0
  89. package/dist/targets-DInbLzff.d.cts +9 -0
  90. package/dist/targets-DInbLzff.d.ts +9 -0
  91. package/dist/terminal/dom/index.cjs +8 -3
  92. package/dist/terminal/dom/index.cjs.map +1 -1
  93. package/dist/terminal/dom/index.d.cts +3 -0
  94. package/dist/terminal/dom/index.d.ts +3 -0
  95. package/dist/terminal/dom/index.js +8 -3
  96. package/dist/terminal/dom/index.js.map +1 -1
  97. package/dist/terminal/dom/server.cjs +2 -7
  98. package/dist/terminal/dom/server.cjs.map +1 -1
  99. package/dist/terminal/dom/server.d.cts +3 -5
  100. package/dist/terminal/dom/server.d.ts +3 -5
  101. package/dist/terminal/dom/server.js +2 -7
  102. package/dist/terminal/dom/server.js.map +1 -1
  103. package/dist/terminal/index.cjs +22 -300
  104. package/dist/terminal/index.cjs.map +1 -1
  105. package/dist/terminal/index.d.cts +7 -2
  106. package/dist/terminal/index.d.ts +7 -2
  107. package/dist/terminal/index.js +21 -22
  108. package/dist/terminal/index.js.map +1 -1
  109. package/dist/terminal/ink/index.d.ts +3 -2
  110. package/dist/terminal/ink/index.js +149 -106
  111. package/dist/terminal/ink/index.js.map +1 -1
  112. package/dist/terminal/react/index.cjs +21 -71
  113. package/dist/terminal/react/index.cjs.map +1 -1
  114. package/dist/terminal/react/index.d.cts +5 -2
  115. package/dist/terminal/react/index.d.ts +5 -2
  116. package/dist/terminal/react/index.js +17 -20
  117. package/dist/terminal/react/index.js.map +1 -1
  118. package/dist/terminal/react/server.cjs +4 -68
  119. package/dist/terminal/react/server.cjs.map +1 -1
  120. package/dist/terminal/react/server.d.cts +9 -6
  121. package/dist/terminal/react/server.d.ts +9 -6
  122. package/dist/terminal/react/server.js +3 -18
  123. package/dist/terminal/react/server.js.map +1 -1
  124. package/dist/terminal/tty/index.cjs +147 -130
  125. package/dist/terminal/tty/index.cjs.map +1 -1
  126. package/dist/terminal/tty/index.d.cts +4 -2
  127. package/dist/terminal/tty/index.d.ts +4 -2
  128. package/dist/terminal/tty/index.js +147 -130
  129. package/dist/terminal/tty/index.js.map +1 -1
  130. package/dist/terminal/vue/index.cjs +20 -72
  131. package/dist/terminal/vue/index.cjs.map +1 -1
  132. package/dist/terminal/vue/index.d.cts +8 -12
  133. package/dist/terminal/vue/index.d.ts +8 -12
  134. package/dist/terminal/vue/index.js +45 -1
  135. package/dist/terminal/vue/index.js.map +1 -1
  136. package/dist/terminal/vue/server.cjs +4 -76
  137. package/dist/terminal/vue/server.cjs.map +1 -1
  138. package/dist/terminal/vue/server.d.cts +7 -6
  139. package/dist/terminal/vue/server.d.ts +7 -6
  140. package/dist/terminal/vue/server.js +3 -10
  141. package/dist/terminal/vue/server.js.map +1 -1
  142. package/dist/tide.cjs +41 -0
  143. package/dist/tide.cjs.map +1 -0
  144. package/dist/tide.d.cts +25 -0
  145. package/dist/tide.d.ts +25 -0
  146. package/dist/tide.js +39 -0
  147. package/dist/tide.js.map +1 -0
  148. package/dist/unverified.cjs +12 -0
  149. package/dist/unverified.cjs.map +1 -0
  150. package/dist/unverified.d.cts +7 -0
  151. package/dist/unverified.d.ts +7 -0
  152. package/dist/unverified.js +10 -0
  153. package/dist/unverified.js.map +1 -0
  154. package/dist/vite.cjs +96 -232
  155. package/dist/vite.cjs.map +1 -1
  156. package/dist/vite.d.cts +6 -8
  157. package/dist/vite.d.ts +6 -8
  158. package/dist/vite.js +97 -71
  159. package/dist/vite.js.map +1 -1
  160. package/package.json +51 -8
  161. package/dist/chunk-4T6KAXBP.js +0 -256
  162. package/dist/chunk-4T6KAXBP.js.map +0 -1
  163. package/dist/chunk-EMRDIZLY.js +0 -99
  164. package/dist/chunk-EMRDIZLY.js.map +0 -1
  165. package/dist/chunk-HOZID4EM.js +0 -366
  166. package/dist/chunk-HOZID4EM.js.map +0 -1
  167. package/dist/chunk-R3QMJ3JF.js +0 -3404
  168. package/dist/chunk-R3QMJ3JF.js.map +0 -1
  169. package/dist/chunk-SK4PDGEE.js +0 -55
  170. package/dist/chunk-SK4PDGEE.js.map +0 -1
  171. package/dist/chunk-U3UR5AOQ.js.map +0 -1
  172. package/dist/document-DhWxieUc.d.cts +0 -1024
  173. package/dist/document-DhWxieUc.d.ts +0 -1024
  174. package/dist/slots-Do9ScG7v.d.cts +0 -37
  175. package/dist/slots-Do9ScG7v.d.ts +0 -37
package/dist/node.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/follow.ts","../src/grammar.ts","../src/telemetry.ts","../src/fabric.ts","../src/closure.ts","../src/runtime.ts","../src/sessions.ts","../src/data.ts","../src/generation.ts","../src/assert.ts","../src/integrations.ts","../src/migrate.ts","../src/tide.ts","../src/principal.ts","../src/session-cookie.ts","../src/socket.ts","../src/delta.ts","../src/shells.ts","../src/pages.ts","../src/liveness.ts","../src/identity.ts","../src/server.ts","../src/document.ts","../src/node.ts"],"names":["NOVA_SEQUENCE","PRISM_SEQUENCE","createUpgrader","evaluate","collectChannels","auditAction","createHash","createPostgresAdapter","createPostgresCache","seedCache","createQueryEngine","scopeGrants","createPrivateKey","createPublicKey","generateKeyPairSync","cryptoSign","randomBytes","z","LayoutNodeSchema","ActionDefinitionSchema","isBinding","isRecord","StrataError","exceedsDepth","depthRefusal","walkNodes","chainCycles","paletteEntryOf","mergeScopePolicies","createScopePolicy","resolvePrincipal","resolveScoping","DefinitionValidationError","CANVAS_SLOT_NAME","ACTION_SLOT_NAME","componentsOf","canvasTreeOf","createComponentRegistry","token","createLayoutStore","createShell","frame","resolve","shellSettled","read","snapshotShell","livenessOf","SWEEP_EVERY_MS","timingSafeEqual","migrate","upgradeStore","verifyCharter","scopeProfiles","handleQuery","keyOf","Hono","AsyncLocalStorage","vex","VEX_LIVE_ENV","headOf","placeHead","WebSocketServer","relative","serveStatic","extname","readFile","join","listen"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCO,IAAM,kBAAA,GAAqB,CAAC,UAAA,KAA0C;AAC3E,EAAA,MAAM,UAAA,GAAa,IAAI,eAAA,EAAgB;AACvC,EAAA,MAAM,MAAM,MAAY;AACtB,IAAA,UAAA,CAAW,KAAA,EAAM;AAAA,EACnB,CAAA;AACA,EAAA,IAAI,UAAA,CAAW,SAAS,GAAA,EAAI;AAAA,kBACZ,gBAAA,CAAiB,OAAA,EAAS,KAAK,EAAE,IAAA,EAAM,MAAM,CAAA;AAE7D,EAAA,MAAM,QAAA,uBAAe,GAAA,EAA6B;AAIlD,EAAA,IAAI,MAAA;AAEJ,EAAA,MAAM,IAAA,GAAgB;AAAA,IACpB,QAAQ,UAAA,CAAW,MAAA;AAAA,IACnB,QAAA,EAAU,CAAC,QAAA,KAAa;AACtB,MAAA,IAAI,QAAA,CAAS,SAAS,CAAA,EAAG;AACvB,QAAA,MAAA,GAAS,EAAE,IAAA,EAAM,QAAA,CAAS,MAAA,EAAO;AACjC,QAAA;AAAA,MACF;AACA,MAAA,KAAA,MAAW,WAAW,CAAC,GAAG,QAAQ,CAAA,EAAG,OAAA,CAAQ,SAAS,MAAM,CAAA;AAAA,IAC9D;AAAA,GACF;AAEA,EAAA,MAAM,QAAA,GAAW,CAAC,OAAA,KAAkD;AAClE,IAAA,IAAI,UAAA,CAAW,MAAA,CAAO,OAAA,EAAS,OAAO,MAAM;AAAA,IAAC,CAAA;AAC7C,IAAA,QAAA,CAAS,IAAI,OAAO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sB,MAAA,GAAY,EAAE,aAAa,OAAA,CAAQ,iBAAA,EAAkB,GAAI,IAAK,CAAA;AACrJ,EAAA,OAAA,CAAQ,GAAA,CAAI,CAAA,8BAAA,EAAiC,IAAI,CAAA,CAAE,CAAA;AACnD,EAAA,OAAA,CAAQ,GAAA,CAAI,CAAA,oGAAA,EAA8F,IAAI,CAAA,OAAA,CAAS,CAAA;AACvH,EAAA,OAAO,MAAA;AACT","file":"node.cjs","sourcesContent":["import type { VexLive } from '@niscorp/vex';\nimport type { Unsubscribe } from '@niscorp/nova';\n\n// ═══════════════════════════════════════════════════════════════\n// A SHELL'S READ THAT KEEPS ANSWERING.\n//\n// A server shell reads vex through the session's wire — an in-process\n// request against this server's own mounts. For an entry with\n// `refresh: 'reactive'`, vex can keep answering that read after it returned:\n// every committed write to a table the query reads, it refetches (once for\n// everybody who would get the same rows) and calls back with the caller's\n// new answer if it changed.\n//\n// This is the seam between the two halves. Toward vex it is a `VexLive` —\n// a signal and a callback, carried in the in-process request's env where no\n// network request can reach. Toward nova it is the response's `onChange`:\n// nova applies each later body exactly as it applied the first (`response`,\n// then `target`) and never learns why it came. Nothing else in moss knows.\n//\n// Lifetime is the caller's. The follow ends when the call's own signal\n// aborts (nova aborts it when the instance unmounts), when the last\n// subscriber unsubscribes (nova does that when a newer call to the same\n// endpoint lands), or — for a caller that never subscribes at all, like a\n// server function reading through the wire — as soon as the response has\n// been handed over and nobody took it up.\n// ═══════════════════════════════════════════════════════════════\n\nexport type WireFollower = {\n // Handed to vex with the request.\n live: VexLive;\n // Offered to the caller on the response.\n onChange: (handler: (body: unknown) => void) => Unsubscribe;\n // The response has been handed over: a follow nobody took up ends now.\n handedOver: () => void;\n // The read did not succeed: there is nothing to follow.\n end: () => void;\n};\n\nexport const createWireFollower = (callSignal: AbortSignal): WireFollower => {\n const controller = new AbortController();\n const end = (): void => {\n controller.abort();\n };\n if (callSignal.aborted) end();\n else callSignal.addEventListener('abort', end, { once: true });\n\n const handlers = new Set<(body: unknown) => void>();\n // An answer that changed between the response and the first subscriber —\n // a write landing in that gap — is held and handed over on subscribe,\n // after the caller has applied the first body. Only the newest is kept.\n let missed: { body: unknown } | undefined;\n\n const live: VexLive = {\n signal: controller.signal,\n onChange: (response) => {\n if (handlers.size === 0) {\n missed = { body: response.result };\n return;\n }\n for (const handler of [...handlers]) handler(response.result);\n },\n };\n\n const onChange = (handler: (body: unknown) => void): Unsubscribe => {\n if (controller.signal.aborted) return () => {};\n handlers.add(handler);\n if (missed !== undefined) {\n const { body } = missed;\n missed = undefined;\n handler(body);\n }\n return () => {\n handlers.delete(handler);\n if (handlers.size === 0) end();\n };\n };\n\n // The caller's own continuation — parse, shape, write the first body,\n // subscribe — runs in microtasks after the response resolves; a macrotask\n // later, anybody who meant to follow has.\n const handedOver = (): void => {\n setTimeout(() => {\n if (handlers.size === 0) end();\n }, 0);\n };\n\n return { live, onChange, handedOver, end };\n};\n","import { createUpgrader, type Sequence, type Upgrader } from '@niscorp/strata';\nimport { NOVA_SEQUENCE } from '@niscorp/nova/migrations';\nimport { evaluate } from '@niscorp/prism';\nimport { PRISM_SEQUENCE } from '@niscorp/prism/migrations';\n\n// ═══════════════════════════════════════════════════════════════\n// The grammars a moss deployment reads and writes documents in: nova's (its\n// actions, fragments and layouts), Prism's (the configs inside them), and the\n// app's own (`NiscApp.grammars` — its component kit's props, say). One upgrader\n// over all of them, built at boot: it brings stored rows current, upgrades what\n// an add-on submits from the stamp the add-on declares, and stamps what moss\n// writes.\n//\n// A document migration is a Prism config, evaluated by Prism's own migration\n// transform — the engine that runs an endpoint's request, the same safety (no\n// code runs).\n// ═══════════════════════════════════════════════════════════════\n\n// nova's and Prism's grammars, then the app's own, in that order.\nexport const grammarsOf = (app: { grammars?: readonly Sequence[] }): readonly Sequence[] => [\n NOVA_SEQUENCE,\n PRISM_SEQUENCE,\n ...(app.grammars ?? []),\n];\n\nexport const createGrammarUpgrader = (app: { grammars?: readonly Sequence[] }): Promise<Upgrader> =>\n createUpgrader(grammarsOf(app), { transform: evaluate });\n","// ═══════════════════════════════════════════════════════════════\n// Telemetry — moss's one observability surface, and the SOLE owner of the\n// span shape. Every service a Midas deployment runs is a moss process; moss\n// is the choke point every engine fact passes through, so moss is where a\n// deployment learns how long a vex execution took, which fingerprint is slow,\n// how often a policy refuses, how many shells are resident. Instrumenting here\n// means a service written tomorrow is observed the day it boots, with no code\n// in the service — the same argument the engine boundary makes for queries.\n//\n// The sink is a deployment decision, not an application one, so the hook lives\n// on the runtime (runtime.ts) beside the other operational knobs. Unset, no\n// span is ever built: every emission site guards on `emit !== undefined`, and\n// an optional call short-circuits its argument, so a hot path with no sink\n// allocates nothing.\n//\n// STRUCTURAL FACTS ONLY. A span carries identifiers and measurements — a\n// fingerprint, a duration, a status — never a payload, a context value, a row,\n// or a principal beyond presence (`hasPrincipal`). The stream must be safe to\n// ship to a third-party backend without a privacy review per span. moss builds\n// every span here from what a seam reports; a seam reports facts, moss decides\n// what of them is safe to name.\n// ═══════════════════════════════════════════════════════════════\n\n// The span, shaped after the OpenTelemetry data model — not the SDK, just the\n// shape, so any OTLP backend ingests a JSON mapping of it with no translation.\nexport type TelemetrySpan = {\n // 'vex.execute' | 'fn.call' | 'shell.build' | 'socket.upgrade' |\n // 'socket.close' | 'integration.call' | …\n name: string;\n // Epoch nanoseconds, millisecond-anchored with a sub-millisecond monotonic\n // span between them. JS numbers cannot hold epoch nanos exactly — the low\n // ~8 bits are lossy — which is far below the millisecond scale of what is\n // measured here, and an exporter re-quantises anyway.\n startUnixNano: number;\n endUnixNano: number;\n // 'refused' is a policy/intake NO — a normal outcome, distinct from a fault.\n status: 'ok' | 'error' | 'refused';\n // Identifiers and measurements. Never a payload, name, address, or context\n // value; a principal appears only as `hasPrincipal`.\n attributes: Record<string, string | number | boolean>;\n // Trace stitching — unused in v1 (no cross-process traceparent yet), carried\n // so a sampler and a propagator can arrive without a shape change.\n traceId?: string;\n spanId?: string;\n parentSpanId?: string;\n};\n\n// The runtime hook. `emit` is fire-and-forget: never awaited, and wrapped\n// (`emitterOf`) so a slow or throwing sink costs the request nothing.\nexport type Telemetry = {\n emit: (span: TelemetrySpan) => void;\n};\n\nexport type Emit = (span: TelemetrySpan) => void;\n\n// The one safe emitter every seam derives. `undefined` when no sink is\n// configured — the signal each site guards on to build no span at all. When a\n// sink is present, its throw is contained here, never the caller's.\nexport const emitterOf = (telemetry: Telemetry | undefined): Emit | undefined =>\n telemetry === undefined\n ? undefined\n : (span) => {\n try {\n telemetry.emit(span);\n } catch (err) {\n console.error('[moss:telemetry]', err);\n }\n };\n\n// A span's clock: the start stamped once, elapsed read on demand — so one clock\n// serves both a short handshake span and a whole-connection span from the same\n// origin. Millisecond-anchored start, sub-millisecond monotonic elapsed.\nexport type SpanClock = { startUnixNano: number; endUnixNano: () => number };\n\nconst elapsedClock = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now());\n\nexport const spanClock = (): SpanClock => {\n const startUnixNano = Date.now() * 1e6;\n const t0 = elapsedClock();\n return { startUnixNano, endUnixNano: () => startUnixNano + (elapsedClock() - t0) * 1e6 };\n};\n","// ═══════════════════════════════════════════════════════════════\n// THE CLUSTER FABRIC — invalidations and nudges that travel between\n// processes. Additive, off by default: no hook, and every path behaves\n// exactly as it does in one process today.\n//\n// Moss holds per-process state that is a feature, not an accident — durable\n// shells, the identity cache, nudge channels. Three calls mutate it from the\n// outside, and the moment two moss processes serve one deployment, a call in\n// process A must reach state resident in process B: a role change resetting a\n// shell over there, a tenant install forgetting records over there, a reaction\n// waking a channel over there. This is the wire it travels.\n//\n// WHY THESE SIGNALS AND NOT `refresh`. `refresh` already crosses processes —\n// the generation counter (generation.ts) is a persistent, readable, always-on\n// pointer, and a process converges by READING it, even after a restart. It has\n// to be, because the thing it guards — the loaded action set — has no other\n// heal clock: miss the signal and you serve the wrong manifest indefinitely.\n// The three signals here are the opposite kind: every one targets state with a\n// bounded heal clock of its own — an identity record re-resolves at\n// `revalidateMs`, a shell rebuilds on idle, a nudge is moot by the next render.\n// A signal lost to a dropped connection is healed by that clock; the fabric\n// only NARROWS the window, it is not a correctness dependency. That is exactly\n// what lets this be best-effort, ephemeral, and off by default where the\n// generation pointer could be none of the three.\n//\n// THE TRANSPORT IS THE HOST'S. The seam takes functions, not a connection\n// string: a Postgres `LISTEN/NOTIFY` pair on the pool moss already holds is the\n// expected implementation, but a test uses an in-memory pair and the raw\n// connection (and its own dropped-connection monitoring) never reaches moss's\n// pool/client-abstract boundary — which is the whole reason a correctness-grade\n// mechanism like generation could not have used NOTIFY, and this one can.\n// ═══════════════════════════════════════════════════════════════\n\n// What crosses: an idempotent, order-independent invalidation or wake. A nudge\n// carries no payload — it names the principal whose shell to wake and the\n// channel to wake, and that shell re-reads under its own policy, exactly as an\n// in-process reaction's `deliver` does. Per-principal, not per-tenant,\n// deliberately: `deliver` is per-principal, and a by-tenant fan-out would need\n// a readable tag→principals index the identity cache refuses to be (identity.ts\n// \"no by-tenant lookup\"). A shell lives in one process, so a nudge for a\n// principal resident elsewhere is a no-op here and lands there.\nexport type FabricSignal =\n | { kind: 'invalidate-identity'; principal: string }\n | { kind: 'invalidate-tenant'; tag: string }\n | { kind: 'nudge'; principal: string; channel: string };\n\n// The wire form: a signal stamped with the origin process, so a process ignores\n// its own echoes (`LISTEN/NOTIFY` delivers to the sender too). moss stamps and\n// checks it; the transport carries it opaquely and understands none of it.\nexport type FabricMessage = FabricSignal & { origin: string };\n\n// The host's transport, as two functions. `publish` is fire-and-forget — never\n// awaited, and moss contains a throw so a slow or dead transport costs the\n// mutating call nothing. `subscribe` is called once, with the applier moss\n// wants run for every REMOTE message.\nexport type Fabric = {\n publish: (message: FabricMessage) => void;\n subscribe: (apply: (message: FabricMessage) => void) => void;\n};\n\n// The three local-only appliers — what a remote signal runs, and what the\n// server's own methods run before they publish. LOCAL-ONLY is load-bearing:\n// applying a remote signal must not re-publish it, or a signal would amplify\n// A → B → C without end. So these mutate what this process holds and stop.\nexport type FabricApply = {\n invalidateIdentity: (principal: string) => void;\n invalidateTenant: (tag: string) => void;\n nudge: (principal: string, channel: string) => void;\n};\n\n// Wire moss to a fabric. Subscribes the remote-apply router (echo-suppressed,\n// contained) and returns the `publish` the mutating paths call AFTER applying\n// locally. With no fabric, `publish` is a no-op and nothing is subscribed —\n// every path behaves exactly as it does in one process.\nexport const wireFabric = (\n fabric: Fabric | undefined,\n origin: string,\n apply: FabricApply,\n): ((signal: FabricSignal) => void) => {\n if (fabric === undefined) return () => {};\n\n fabric.subscribe((message) => {\n // Our own echo: this process already applied it before publishing. Dropping\n // it here means a signal is never applied twice on the process that sent it,\n // whatever the transport does with self-delivery.\n if (message.origin === origin) return;\n // Contained: a remote signal is somebody else's news, and a throw applying\n // it must not take down the subscriber the transport is driving.\n try {\n switch (message.kind) {\n case 'invalidate-identity':\n apply.invalidateIdentity(message.principal);\n break;\n case 'invalidate-tenant':\n apply.invalidateTenant(message.tag);\n break;\n case 'nudge':\n apply.nudge(message.principal, message.channel);\n break;\n }\n } catch (err) {\n console.error('[moss:fabric] a remote signal failed to apply', err);\n }\n });\n\n return (signal) => {\n // Fire-and-forget, and contained: a mutating call has already done its local\n // work, and a dead transport must not turn a successful local invalidation\n // into a thrown error.\n try {\n fabric.publish({ ...signal, origin });\n } catch (err) {\n console.error('[moss:fabric] publish failed', err);\n }\n };\n};\n","import { auditAction, collectChannels } from '@niscorp/nova';\nimport type { ActionDefinition } from '@niscorp/nova';\nimport type { ClosureAuditor } from '@niscorp/charter';\nimport type { LayoutVariant } from './app';\n\n// The per-role closure auditor — nova's own action audit, run over a\n// role's granted set: each granted definition is checked against a world\n// containing ONLY that set, and the issues kept are the CROSS-ACTION ones\n// (a push target outside the closure). A definition-level wart (a loose\n// bind, a dead ref) is not a closure break — the audit's other findings\n// stay with the definition tooling. What this returns lands in the charter\n// report's `perRole[].issues`; boot refuses on the report's `errors` only,\n// so a closure break does not stop a boot.\n//\n// The role's granted variant ids ride in as the auditor's second argument\n// (the charter verifier passes them): substituted before auditing, so the\n// closure sees the role's EFFECTIVE definitions — a variant's push targets\n// and channels are audited for exactly the roles that hold it.\nexport const auditClosure = (definitions: Record<string, ActionDefinition>, variants: Record<string, LayoutVariant> = {}): ClosureAuditor => {\n return (grantedIds, layoutIds = []) => {\n const bindings = new Map<string, ActionDefinition['layout']>();\n for (const id of layoutIds) {\n const variant = variants[id];\n if (variant !== undefined) bindings.set(variant.action, variant.layout);\n }\n const granted = grantedIds\n .map((id) => {\n const definition = definitions[id];\n if (definition === undefined) return undefined;\n const layout = bindings.get(id);\n return layout === undefined ? definition : { ...definition, layout };\n })\n .filter((definition): definition is ActionDefinition => definition !== undefined);\n const catalog = granted.map((definition) => ({ id: definition.id, input: definition.input ?? {} }));\n const channels = [\n ...new Set(\n granted.flatMap((definition) => {\n const found = collectChannels(definition);\n return [...found.emits, ...found.listens];\n }),\n ),\n ];\n const issues: string[] = [];\n for (const definition of granted) {\n const audit = auditAction(definition, { catalog, channels });\n if (audit.ok) continue;\n for (const issue of audit.issues) {\n // Cross-action wiring only — and a TEMPLATE target ({{…}}) is\n // resolved at runtime, not a static closure break.\n if (issue.includes('which is not in the catalog') && !issue.includes('{{')) issues.push(`${definition.id}: ${issue}`);\n }\n }\n return issues;\n };\n};\n","import type { Context, Next } from 'hono';\nimport type { MutationClient, PgPool, CacheBackend, QueryEngineConfig } from '@niscorp/vex';\nimport type { Sequence } from '@niscorp/strata';\nimport type { Telemetry } from './telemetry';\nimport type { Fabric } from './fabric';\n\n// ═══════════════════════════════════════════════════════════════\n// What the app runs ON — the environment, not the application: a database\n// (pool for SQL, client for mutations), optionally a cache backend\n// (defaults to vex's postgres cache on the same pool — the seeded-cache\n// posture) and a session verifier, which has NO default: authentication is\n// the one door that must not default open.\n// ═══════════════════════════════════════════════════════════════\n\n// Token in, principal out — or null, which is a refusal. Asked on every HTTP\n// request and re-asked on live sockets every `sessionRevalidateMs`.\nexport type SessionVerifier = (token: string) => string | null | Promise<string | null>;\n\nexport type NiscRuntime = {\n pool: PgPool;\n db: MutationClient;\n cache?: CacheBackend;\n // THE QUERY ENGINE'S OWN SETTINGS, handed to vex as its `config` and not read\n // here: how many rows a query that states no limit gets, the most a\n // generated one may ask for, how long a read may run. Here rather than on\n // the manifest for the reason every knob below is: these are decisions about\n // a deployment's database, not something an application is written against.\n // Unset, the engine runs on its defaults.\n vexConfig?: QueryEngineConfig['config'];\n // WHO A TOKEN IS. Required, deliberately — every other door in moss fails\n // closed, and this is the one where forgetting a field used to open it for\n // everyone. Three answers:\n // 'sessions' — moss's own stored credential (sessions.ts): 256-bit token,\n // hashed at rest, expiring, revoked by deleting its row.\n // 'dev-open' — the dev stub below: every well-formed token is trusted and\n // the boot says so out loud. Harnesses and demo floors.\n // a function — the app's own identity provider.\n session: SessionVerifier | 'sessions' | 'dev-open';\n // The origins that are this app's own page, beside the host a request is\n // addressed to — for a proxy that rewrites `Host`. A browser's session\n // cookie is read and written for the app's own page only\n // (session-cookie.ts).\n origins?: readonly string[];\n // The tables moss, vex and a chosen credential own go through ONE ledgered\n // run at boot (strata), before introspection. 'apply' (default): run what is\n // pending, once, recorded. 'verify': refuse to boot if anything is pending —\n // for a deployment whose migrations are a deploy step, not a side effect of\n // starting a process. Either way an edited or too-new ledger refuses.\n migrations?: 'apply' | 'verify';\n // THE APP'S OWN TABLES, as strata sequences. They join that same run, after\n // the engine's: one transaction, one lock, one `migrations` posture — so\n // 'verify' covers them, and the step that migrates (`migrateTables`) checks\n // the app's entries against what THEY leave. Absent, the app migrates its own\n // tables itself, as before.\n tables?: readonly Sequence[];\n // How long a durable server shell may sit with no terminal attached before\n // it is disposed (default: 30 minutes; `0` disables the sweep). An\n // environment knob rather than a manifest one, because it trades memory\n // against a rebuild on the next connect — an operational decision about a\n // deployment, not something an application is written against.\n shellIdleMs?: number;\n // How long a server shell's endpoint call waits for its reply before it\n // fails to the action's `onError` (default: nova's, 30 seconds). An\n // endpoint that is slow by nature says so itself (`timeoutMs`); this is the\n // deployment's floor for everything else.\n endpointTimeoutMs?: number;\n // How often a live socket's credential is re-verified through `session`\n // (default: 60 seconds; `0` disables it). The HTTP surfaces re-ask on every\n // request; this is what makes the socket ask too, so a `session` that gives\n // its tokens an expiry has that expiry mean something on a connection\n // somebody is holding open. Costs one `session` call per authenticated\n // connection per interval — the knob is here for a verifier that is\n // expensive to ask.\n sessionRevalidateMs?: number;\n // Ceiling on resident identity records (default 10,000), and how long one may\n // sit unread before the sweep drops it (default: 30 minutes, `0` disables).\n //\n // Here rather than on the manifest for the reason `shellIdleMs` is: this\n // trades memory against a re-resolution on the next request, which is an\n // operational decision about a deployment and not something an application is\n // written against. Reaching the ceiling evicts the least recently read and\n // increments a meter — an unbounded map works beautifully at demo scale and\n // dies at production scale with no signal in between, and the meter is the\n // signal.\n //\n // Revalidation deliberately has no knob of its own: an identity record goes\n // stale on exactly the clock a live socket credential does, so it reuses\n // `sessionRevalidateMs` above.\n identityMax?: number;\n identityIdleMs?: number;\n // Send each canvas frame as a DELTA against the last one this connection\n // received, rather than whole (default: off).\n //\n // A shell re-sends a canvas whenever its tree changes, and most changes are\n // small against a large tree — a keystroke filtering a list rewrites a few\n // hundred bytes of several thousand. Measured on Lyra: an in-place update\n // falls to 1–4% of the frame, a navigation to about 80% before the\n // transport's own compression. It costs one encode per changed canvas per\n // flush and one previous frame held per canvas, which the host keeps anyway\n // for its unchanged-frame check. The encode's cost follows the frame's size,\n // so a canvas whose frame is over 64 KB is sent whole and never encoded.\n //\n // Off by default because it is a protocol change: a terminal that does not\n // advertise support keeps receiving whole frames, and a delta that fails its\n // checksum makes the terminal ask for a whole one. See DOCS.md § Frame\n // deltas.\n shellFrameDelta?: boolean;\n // WebSocket permessage-deflate (default: on).\n //\n // Compresses every frame — roughly 3–4× on rendered trees, which are mostly\n // repeated keys. The cost is memory, and it is not small: measured at ~260 KB\n // of resident memory per connection at the `ws` defaults, against ~43 KB for\n // the shell being served. That trade is right at hundreds of connections and\n // wrong at a hundred thousand, which is why it is a knob and not a constant.\n // `false` disables it; an object is passed through to `ws` for tuning.\n socketCompression?: boolean | Record<string, unknown>;\n // THE OPERATOR KEY — the whole authentication story for the seam below.\n //\n // Registering an integration is a PLATFORM act, not a tenant one: it points\n // the deployment at a service and approves what that service may read. No\n // principal should be able to do it, which means it cannot live on a\n // principal-authenticated surface at all.\n //\n // Absent = the seam does not exist. Every route under it answers 404, which is\n // also what a wrong key gets: a tool cannot tell an unset key from a bad one,\n // and neither can anybody else.\n operatorKey?: string;\n\n // A GATE THE APP RUNS OVER THE WHOLE OPERATOR PREFIX — its own authentication,\n // rate limiting, and audit, wrapped AROUND moss's key check and its routes.\n //\n // It runs BEFORE the key check, so an app credential can refuse first; and it\n // may `await next()` to observe the OUTCOME, so approving an integration —\n // which decides what code the deployment mints assertions for — is auditable\n // with its real result, not just the attempt. Returning a Response refuses;\n // returning nothing falls through to the key check.\n //\n // It can only HARDEN the prefix: moss's key check still runs on every path the\n // gate lets through, so a gate adds a second lock and never removes moss's.\n // Absent, moss's key check is the only gate and the prefix behaves as it did.\n operatorGate?: (c: Context, next: Next) => Response | void | Promise<Response | void>;\n\n // THE CLUSTER FABRIC — how an invalidation or a nudge reaches a SECOND moss\n // process (fabric.ts). Off by default, and needed only when a deployment\n // grows past one process per service: a role change in process A resets the\n // shell resident in B, a nudge in A wakes a channel subscriber in B. The seam\n // takes functions, not a connection — `LISTEN/NOTIFY` on the pool moss holds\n // is the expected implementation, but the transport (and its own dropped-\n // connection monitoring) is the host's, never moss's. Unset, every path\n // behaves exactly as it does in one process.\n fabric?: Fabric;\n\n // WHERE STRUCTURED TELEMETRY GOES — the deployment's one observability sink,\n // and off by default. moss emits one span per vex execution, fn call,\n // integration call, shell build, and socket upgrade/close, each shaped for an\n // OTLP backend to ingest without translation (telemetry.ts). Unset, no span\n // is built and no hot path pays anything; set, the substrate wires it to a\n // ring buffer and/or an exporter. Operational, not application: a service is\n // observed by virtue of running moss, never by anything it authors.\n telemetry?: Telemetry;\n\n // A FIXED SEED FOR THE ASSERTION SIGNING KEYPAIR — dev only, and off by\n // default (assert.ts). Without it the keypair regenerates every boot, which\n // on an in-memory database means an integration's held public key goes stale\n // on every restart and it starts refusing calls. Setting it makes the public\n // half stable, so a separate service's environment stays valid across\n // restarts. A deployment leaves this unset and keeps the ephemeral key.\n signingSeed?: string;\n};\n\n// The dev token pair — mint on the client stub, verify on the server;\n// base64url JSON, `sub` is the principal. No signature, no expiry: anybody\n// who can spell a principal's id can be them. Reachable ONLY through\n// `session: 'dev-open'`, which announces itself at boot — this used to be\n// the silent default, and one app ran production on it for its whole life\n// before a review noticed. Real credentials live in sessions.ts.\nexport const mintDevToken = (sub: string, claims: Record<string, unknown> = {}): string =>\n btoa(JSON.stringify({ sub, ...claims, iat: Date.now() }))\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '');\n\nexport const devSession = (token: string): string | null => {\n try {\n const parsed: unknown = JSON.parse(atob(token.replace(/-/g, '+').replace(/_/g, '/')));\n const sub = (parsed as Record<string, unknown> | null)?.['sub'];\n return typeof sub === 'string' ? sub : null;\n } catch {\n return null;\n }\n};\n","import { randomBytes, createHash } from 'node:crypto';\nimport type { Sequence } from '@niscorp/strata';\nimport { migrate } from '@niscorp/strata/postgres';\nimport type { PgPool } from '@niscorp/vex';\nimport { devSession } from './runtime';\nimport type { NiscRuntime, SessionVerifier } from './runtime';\n\n// ═══════════════════════════════════════════════════════════════\n// SESSIONS — the human credential, at the standard the machine one set.\n//\n// This server already answers \"who is calling\" three ways: an integration\n// presents a 256-bit key stored hashed (integrations.ts), a deployment signs\n// 30-second assertions with ed25519 (assert.ts) — and until this file, a\n// person presented a JSON field anybody could author. Nothing about a person\n// makes the weaker answer appropriate; this is the same credential the\n// integration key is, one table over:\n//\n// MINTED ONCE, SHOWN ONCE. 256 bits of CSPRNG behind an `st_` prefix; the\n// row keeps only the hash, so a stolen database does not hold a live\n// session. Presenting the token is the only way to produce the hash again.\n//\n// EXPIRING. `expires_at` is written at mint and enforced on every read.\n// The socket already re-asks the verifier on a timer (sessionRevalidateMs)\n// precisely so an expiry can mean something on a held-open connection —\n// this is the verifier that gives that clock something to say.\n//\n// REVOKED BY DELETING THE ROW. One token (sign out here) or every token a\n// principal holds (sign out everywhere, a role change, an offboarding).\n// No second mechanism to forget.\n//\n// The app mints at its own door (after ITS identity check — a password, an\n// SSO callback, a magic link) and hands the token to the terminal. Moss\n// never learns how the app decided; the app never touches token mechanics.\n// ═══════════════════════════════════════════════════════════════\n\nconst hashSessionToken = (token: string): string => createHash('sha256').update(token).digest('hex');\n\n// The sessions table, as a strata sequence. Its own sequence rather than part of\n// `nisc.moss` because it exists only for a deployment that chose moss's own\n// credential (`runtime.session: 'sessions'`). HISTORY: an applied migration is\n// never edited — change the table by appending one (see test/baselines.test.ts).\nexport const SESSIONS_SEQUENCE: Sequence = {\n id: 'nisc.moss.sessions',\n migrations: [\n {\n description: 'The sessions table: a token is stored only as its hash',\n steps: [\n {\n kind: 'sql',\n // THE HASH, NEVER THE TOKEN (see the header, and assert.ts for the rule).\n sql: `CREATE TABLE IF NOT EXISTS sessions (\n token_hash text PRIMARY KEY,\n principal text NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now(),\n expires_at timestamptz NOT NULL\n )`,\n },\n ],\n },\n ],\n};\n\n// Through the ledger, for a host that is not moss's server (which runs every\n// owner's sequence in one pass).\nexport const initSessions = async (pool: PgPool): Promise<void> => {\n await migrate(pool, [SESSIONS_SEQUENCE]);\n};\n\n// The broom rides the mint: every new session sweeps the expired ones, so\n// the table is self-maintaining at exactly the rate it grows and no\n// deployment needs a timer for it.\nexport const mintSession = async (pool: PgPool, principal: string, ttlMs: number): Promise<string> => {\n await pool.query('DELETE FROM sessions WHERE expires_at < now()');\n const token = `st_${randomBytes(32).toString('base64url')}`;\n await pool.query('INSERT INTO sessions (token_hash, principal, expires_at) VALUES ($1, $2, $3)', [\n hashSessionToken(token),\n principal,\n new Date(Date.now() + ttlMs),\n ]);\n return token;\n};\n\nexport const sessionOf = async (pool: PgPool, token: string): Promise<string | null> => {\n const res = await pool.query('SELECT principal FROM sessions WHERE token_hash = $1 AND expires_at > now()', [hashSessionToken(token)]);\n const principal = (res.rows[0] as { principal?: unknown } | undefined)?.principal;\n return typeof principal === 'string' ? principal : null;\n};\n\n// How much longer a session resolves — how long a browser is told to keep the\n// cookie that carries it.\nexport const sessionRemainingMs = async (pool: PgPool, token: string): Promise<number | null> => {\n const res = await pool.query('SELECT extract(epoch from expires_at - now()) * 1000 AS remaining FROM sessions WHERE token_hash = $1 AND expires_at > now()', [hashSessionToken(token)]);\n const remaining = Number(res.rows[0]?.['remaining']);\n return res.rows.length > 0 && Number.isFinite(remaining) ? remaining : null;\n};\n\nexport const revokeSession = async (pool: PgPool, token: string): Promise<void> => {\n await pool.query('DELETE FROM sessions WHERE token_hash = $1', [hashSessionToken(token)]);\n};\n\nexport const revokeAllFor = async (pool: PgPool, principal: string): Promise<void> => {\n await pool.query('DELETE FROM sessions WHERE principal = $1', [principal]);\n};\n\n// The three-way choice, resolved once at boot (server.ts). Typed callers\n// cannot reach the refusal — the field is required — but a JS config can,\n// and the sentence names the choices rather than assuming the reader has\n// the type open.\nexport const sessionVerifierOf = (runtime: Pick<NiscRuntime, 'session' | 'pool'>): SessionVerifier => {\n const chosen = runtime.session as NiscRuntime['session'] | undefined;\n if (chosen === undefined) {\n throw new Error(\n \"moss: `runtime.session` is unset — authentication is the one door that must not default open. Choose: 'sessions' (moss's stored credential: mintSession/sessionOf/revokeSession), 'dev-open' (every token is trusted; development only), or your own verifier function.\",\n );\n }\n if (chosen === 'sessions') return (token) => sessionOf(runtime.pool, token);\n if (chosen === 'dev-open') {\n console.error('[moss] session: dev-open — every well-formed token is trusted, and a forged principal walks in. Development only.');\n return devSession;\n }\n return chosen;\n};\n","import { createPostgresAdapter, createPostgresCache, createQueryEngine, scopeGrants, seedCache } from '@niscorp/vex';\nimport type { QueryEngine, DatabaseSchema, SeedEntry, SeedMutation } from '@niscorp/vex';\nimport type { NiscRuntime } from './runtime';\n\n// ═══════════════════════════════════════════════════════════════\n// The data layer stands up from what's present (DESIGN.md § Derivation\n// over configuration): the database's seeded vex_cache IS the API\n// surface — nothing generates here — and the grantable set is the\n// introspected schema × vex's verb leaves. No table list is ever authored.\n// ═══════════════════════════════════════════════════════════════\n\nexport type DataLayer = {\n engine: QueryEngine;\n schema: DatabaseSchema;\n // every `<table>.<verb>` grant this schema can carry — the data\n // section's resolution set, and the input to policy compilation\n grants: string[];\n};\n\nexport const createDataLayer = async (runtime: NiscRuntime, entries: readonly (SeedEntry | SeedMutation)[] = []): Promise<DataLayer> => {\n const adapter = createPostgresAdapter({ pool: runtime.pool });\n const cache = runtime.cache ?? createPostgresCache({ pool: runtime.pool });\n await cache.init?.();\n // The authored API surface lands as protected rows; a db that already\n // carries them is left untouched (idempotent).\n await seedCache(cache, entries);\n const engine = createQueryEngine({ adapter, cache, ...(runtime.vexConfig !== undefined ? { config: runtime.vexConfig } : {}) });\n const schema = await engine.introspect();\n\n // THE ENGINE'S OWN TABLES ARE ORDINARY TABLES, and it is worth saying why\n // they are not special-cased.\n //\n // The first instinct was to hide them: tide's four tables carry no tenancy\n // of their own, so `tide_run.read` looks like a grant that reads every\n // tenant's ledger at once. But that is true of ANY table with no scope\n // rule, and it is the scope rule — not the grant list — that has always\n // been what makes `memberships.read` safe. Hiding them would have closed\n // the door as well as the hole: an authored, scoped entry over the run\n // ledger is exactly how an operator's automations screen should read, and\n // it cannot compile against a table vex has never heard of.\n //\n // So they introspect, they are grantable, and a host that grants one\n // authors a scope rule for it like everything else. Lyra scopes `tide_run`\n // on the identity the run declared.\n return { engine, schema, grants: scopeGrants(schema.entities.map((e) => e.name)) };\n};\n","import type { PgPool } from '@niscorp/vex';\n\n// ═══════════════════════════════════════════════════════════════\n// THE GENERATION POINTER — how a second process finds out.\n//\n// Every per-principal resolution in this server is derived from rows: which\n// integrations a tenant has installed, what rung somebody stands on, what a\n// studio's theme is. A write changes those rows and the writing process drops\n// its memos. Every OTHER process goes on serving the old answer until it is\n// restarted, which at two processes is a correctness bug rather than a scaling\n// concern: an integration installed via A leaves B refusing that integration's keyed calls,\n// and nothing says so.\n//\n// This is a counter and a clock, deliberately, and NOT `LISTEN/NOTIFY`:\n//\n// - `NiscRuntime` takes a pool and a mutation client, both abstract. LISTEN\n// needs a raw dedicated connection held outside the pool for the life of\n// the process — a new capability at the environment boundary, for one\n// feature.\n// - A dropped listener stops invalidating and says nothing. That is a SILENT\n// correctness failure, which is the failure mode this whole design refuses\n// (\"breaks rather than degrades\"). A counter that cannot be read raises.\n// - It converges on where the plan is going instead of being thrown away by\n// it: \"a new generation is a new manifest, and other processes observe a\n// pointer move\" (moss DESIGN.md) IS this counter, and Move 4 replaces what\n// the pointer points AT rather than the mechanism.\n//\n// The cost is that staleness is bounded by a poll rather than instant. It is\n// bounded by `sessionRevalidateMs`, a knob already being tuned for exactly this\n// class of question. Today it is bounded by nothing.\n// ═══════════════════════════════════════════════════════════════\n\nexport type Generation = {\n /** This process changed something every process should forget. */\n bump: () => void;\n /** The generation last observed — for checks and operator surfaces. */\n current: () => number;\n stop: () => void;\n};\n\n// TWO STATEMENTS, SENT SEPARATELY. A driver that prepares its statements refuses\n// a string carrying more than one command, and the failure arrives as a\n// DatabaseError at boot rather than as anything about generations.\nexport const GENERATION_DDL: readonly string[] = [\n /* sql */ `CREATE TABLE IF NOT EXISTS moss_generation (id INT PRIMARY KEY, n BIGINT NOT NULL DEFAULT 0)`,\n /* sql */ `INSERT INTO moss_generation (id, n) VALUES (1, 0) ON CONFLICT (id) DO NOTHING`,\n];\n\nexport const DEFAULT_GENERATION_POLL_MS = 60 * 1000;\n\nexport const createGeneration = (\n pool: PgPool,\n ctx: { onMoved: () => void | Promise<void>; everyMs?: number },\n): Generation => {\n const everyMs = ctx.everyMs ?? DEFAULT_GENERATION_POLL_MS;\n // Starts at -1 rather than 0 so the first read establishes a baseline instead\n // of reporting a move that never happened.\n let seen = -1;\n let checking = false;\n\n const read = async (): Promise<void> => {\n // Never two reads at once: a poll that outlives its interval would otherwise\n // stack, and a stacked poll on a slow database is how a timer becomes a\n // load generator.\n if (checking) return;\n checking = true;\n try {\n const result = await pool.query('SELECT n FROM moss_generation WHERE id = 1');\n const n = Number((result.rows[0] as { n?: unknown } | undefined)?.n ?? 0);\n if (!Number.isFinite(n)) return;\n const first = seen === -1;\n const moved = !first && n !== seen;\n seen = n;\n if (moved) await ctx.onMoved();\n } catch (err) {\n // LOUD. A counter nobody can read means this process has stopped hearing\n // about other processes' writes, which is precisely the condition the\n // whole mechanism exists to prevent. Silence here would reproduce the bug\n // in the shape of its own fix.\n console.error('[moss:generation] could not read the generation pointer — this process may be serving stale resolutions', err);\n } finally {\n checking = false;\n }\n };\n\n void read();\n const timer = everyMs > 0 ? setInterval(() => void read(), everyMs) : undefined;\n timer?.unref?.();\n\n return {\n bump: () => {\n void pool\n .query('UPDATE moss_generation SET n = n + 1 WHERE id = 1')\n .then(async () => {\n // Adopt our own bump immediately, so `seen` cannot lag behind a value\n // this process itself wrote and then \"discover\" it a minute later.\n const result = await pool.query('SELECT n FROM moss_generation WHERE id = 1');\n seen = Number((result.rows[0] as { n?: unknown } | undefined)?.n ?? seen);\n })\n .catch((err: unknown) => console.error('[moss:generation] could not move the pointer', err));\n },\n current: () => seen,\n stop: () => {\n if (timer !== undefined) clearInterval(timer);\n },\n };\n};\n","import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes, sign as cryptoSign, verify as cryptoVerify } from 'node:crypto';\nimport type { KeyObject } from 'node:crypto';\n\n// ═══════════════════════════════════════════════════════════════\n// THE CREDENTIAL RULE, in one module: the verifier mints, stores at most a\n// hash, and the presenter keeps the plaintext. Two credentials fall out of it,\n// mirror images of each other:\n//\n// IDENTITY ASSERTIONS (outbound — the deployment tells an integration who is\n// calling). The deployment holds a signing keypair; the public half is\n// served openly and verifying is all an integration can do with it. Identity\n// travels INSIDE the signed token — principal, scope, expiry — so a forged\n// header is not \"refused\", it is meaningless: there is no identity outside a\n// verified envelope. A leaked token impersonates one principal for seconds,\n// not every tenant forever, which is the whole argument against the shared\n// secret this replaced.\n//\n// INTEGRATION KEYS (inbound — an integration acts when nobody is driving).\n// Minted by the deployment at registration, shown once, stored only as a\n// hash. Presenting it resolves to a principal the APP names, whose charter\n// rung bounds what it may do. Deleting the integration row kills the key,\n// and with it every assertion story the row anchored — one act, both\n// directions.\n//\n// Ed25519 because there is nothing to configure: no digest choice, no padding\n// mode, no parameter that can be set wrong. The token is two base64url parts —\n// JSON payload, then the signature over exactly those payload bytes. That IS\n// the wire contract; an integration verifies it with node:crypto in a dozen\n// lines and imports nothing of ours to do so.\n// ═══════════════════════════════════════════════════════════════\n\nexport type Assertion = {\n // Which integration this token is FOR. A service hosting several bundles\n // must check it names the one being called — a token minted for `belts`\n // presented to `stripe` is somebody replaying credentials sideways.\n integration: string;\n principal: string;\n scope: Record<string, unknown>;\n iat: number;\n exp: number;\n};\n\nconst b64url = (buffer: Buffer): string => buffer.toString('base64').replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\nconst fromB64url = (text: string): Buffer => Buffer.from(text.replace(/-/g, '+').replace(/_/g, '/'), 'base64');\n\nexport type AssertionSigner = {\n // SPKI DER, base64. Public material — served on the discovery surface,\n // pasted into an environment, cached by anyone. Holding it verifies;\n // nothing about it mints.\n verifyKey: string;\n mint: (claims: { integration: string; principal: string; scope: Record<string, unknown> }, ttlMs?: number) => string;\n};\n\n// Generated at boot, held in memory, never persisted — UNLESS a seed is handed\n// in. That default is the right one for production: assertions live seconds, so\n// a restart invalidating tokens in flight costs one retry, and a key never\n// written down is a key nothing can exfiltrate at rest.\n//\n// THE SEED IS A DEV AFFORDANCE, and it earns its keep. On an in-memory database\n// every restart regenerates this keypair, which invalidates the public half an\n// integration is holding — so a separate service (the payments integration) starts\n// answering \"who are you?\" to every call until somebody re-copies the new key.\n// Seeding the keypair from a fixed value makes the public half STABLE across\n// restarts, so the integration's env stays valid. A deployment leaves the seed\n// unset and keeps the ephemeral key; a dev sets one and stops re-copying.\n//\n// The seed is 32 bytes, base64 — an ed25519 private scalar. It never leaves the\n// deployment; only the public half is ever served.\nconst signerFromSeed = (seed: Buffer): { publicKey: KeyObject; privateKey: KeyObject } => {\n // ed25519 private keys are a fixed 32-byte scalar; PKCS8 wraps them in a\n // constant DER prefix, so a deterministic key is that prefix plus the seed.\n const pkcs8 = Buffer.concat([Buffer.from('302e020100300506032b657004220420', 'hex'), seed.subarray(0, 32)]);\n const privateKey = createPrivateKey({ key: pkcs8, format: 'der', type: 'pkcs8' });\n // node derives the public half from a private KeyObject at runtime; the type\n // overloads do not advertise the KeyObject input, hence the cast.\n const asInput = privateKey as unknown as Parameters<typeof createPublicKey>[0];\n return { privateKey, publicKey: createPublicKey(asInput) };\n};\n\nexport const createAssertionSigner = (seedB64?: string): AssertionSigner => {\n const seed = seedB64 !== undefined && seedB64 !== '' ? Buffer.from(seedB64, 'base64') : undefined;\n const { publicKey, privateKey } =\n seed !== undefined && seed.length >= 32 ? signerFromSeed(seed) : generateKeyPairSync('ed25519');\n const verifyKey = publicKey.export({ type: 'spki', format: 'der' }).toString('base64');\n return {\n verifyKey,\n mint: (claims, ttlMs = 30_000): string => {\n const iat = Date.now();\n const body = Buffer.from(JSON.stringify({ ...claims, iat, exp: iat + ttlMs }));\n return `${b64url(body)}.${b64url(cryptoSign(null, body, privateKey))}`;\n },\n };\n};\n\n// The other end of `mint` — exported for checks and for any service written in\n// this workspace. A service in its own repository implements these same lines\n// against its own runtime's crypto; the contract is the token format, not this\n// function.\nexport const verifyAssertion = (token: string, verifyKey: string, now: number = Date.now()): Assertion | undefined => {\n const dot = token.indexOf('.');\n if (dot <= 0) return undefined;\n try {\n const body = fromB64url(token.slice(0, dot));\n const signature = fromB64url(token.slice(dot + 1));\n const key = createPublicKey({ key: fromB64url(verifyKey), format: 'der', type: 'spki' });\n if (!cryptoVerify(null, body, key, signature)) return undefined;\n const parsed = JSON.parse(body.toString()) as Assertion;\n if (typeof parsed.integration !== 'string' || typeof parsed.principal !== 'string') return undefined;\n if (typeof parsed.exp !== 'number' || parsed.exp <= now) return undefined;\n return parsed;\n } catch {\n return undefined;\n }\n};\n\n// ── the inbound key ──────────────────────────────────────────\n//\n// `ik_` + 32 random bytes: the prefix is what lets the identity middleware\n// route it without guessing, and the entropy is not a choice anybody gets to\n// make. Minted once at registration, returned once, and the row keeps only\n// the hash — a lost key is re-registered, not recovered.\nexport const mintIntegrationKey = (): string => `ik_${randomBytes(32).toString('hex')}`;\nexport const hashIntegrationKey = (key: string): string => createHash('sha256').update(key).digest('hex');\n","import type { Sequence } from '@niscorp/strata';\nimport { migrate, type DocumentStore } from '@niscorp/strata/postgres';\nimport { StrataError, depthRefusal, exceedsDepth, type Upgrader } from '@niscorp/strata';\nimport { GENERATION_DDL } from './generation';\nimport { z } from 'zod';\nimport { ActionDefinitionSchema, LayoutNodeSchema, paletteEntryOf } from '@niscorp/nova';\nimport type { ActionDefinition, ComponentMeta, LayoutPaletteEntry } from '@niscorp/nova';\nimport { chainCycles, walkNodes, isRecord } from '@niscorp/nova/reflect';\nimport { isBinding } from '@niscorp/nova/i18n';\nimport type { PgPool } from '@niscorp/vex';\nimport { hashIntegrationKey } from './assert';\nimport type { NiscApp } from './app';\nimport { emitterOf, spanClock } from './telemetry';\nimport type { Telemetry } from './telemetry';\n\n// ═══════════════════════════════════════════════════════════════\n// INTEGRATIONS — actions and layouts that arrive from somewhere else.\n//\n// An integration is a SEPARATE SERVICE. Its own repository, its own storage,\n// its own deploy cycle, on its own machine. It shares no code with the app it\n// extends: everything crosses a wire.\n//\n// That constraint decides the whole design, and most of it is subtraction:\n//\n// IT SHIPS ACTIONS AND LAYOUTS. Nothing else. It cannot ship a vex entry,\n// because an entry is a compiled query authored against a schema it cannot\n// import, and the generation path is deliberately unwired. It calls what\n// discovery advertises, and if it needs a read that does not exist, that is a\n// change to the app rather than to the integration.\n//\n// IT BRINGS ITS OWN STORAGE. A feature needing a column beside the app's is a\n// migration in the app, not an integration. Anything else lives on the other\n// side of the wire, keyed by identifiers we hand over.\n//\n// IT ANNOUNCES; WE FETCH. There is no poll and no boot-time sweep. Registering\n// IS the announcement, it is idempotent, and re-importing is the same call.\n//\n// IT REACHES EXACTLY TWO PLACES. A fingerprint the app already serves, or a\n// URL under its own prefix. Every endpoint on every action it ships is checked\n// against that at intake.\n//\n// Two credentials, revocable at different granularities. The integration's own\n// KEY is long-lived: it acts as itself, as a principal with a charter rung, for\n// work nobody asked for (a nightly sync). A per-request TOKEN is minted by the\n// proxy when a person is driving: it acts on behalf of them, it lasts seconds,\n// and it is only valid while the key that owns it is — so revoking one key\n// kills every token it holds without storing any of them.\n// ═══════════════════════════════════════════════════════════════\n\nexport type IntegrationRow = {\n id: string;\n url: string;\n status: 'pending' | 'approved' | 'revoked';\n title: string;\n tagline: string;\n adds: string;\n settingsAction: string;\n requestedActions: readonly string[];\n requestedData: readonly string[];\n approvedData: readonly string[];\n offers: readonly string[];\n needs: readonly string[];\n capabilities: readonly { id: string; title: string }[];\n configuration: readonly ConfigurationField[];\n documents: readonly DocumentDeclaration[];\n assistants: readonly AssistantDeclaration[];\n lastImportAt: number | null;\n lastError: string | null;\n actionCount: number;\n};\n\n// What an integration publishes at `<url>/bundle`. Deliberately small — the\n// argument for every field it does NOT have is above. Four kinds of content,\n// each its own field: WORDS (meta — for the store card, validated against\n// nothing), REQUESTS (grants — approved once), ARTIFACTS (actions — pure nova,\n// the schema untouched by any of this), and BINDINGS (attachments, placements,\n// settings — machine-checked against what the host advertises, refused when\n// wrong). Bindings live beside the artifacts, never on them: the binding names\n// the action, the action never names its bindings — the same direction layout\n// variants point.\n// WHAT A BUILDER MAY SET — the add-on's declaration of its own configurable\n// behaviour, so the host renders a settings form per add-on the way it renders\n// the role editor from `capabilities`. moss validates the DECLARATION and\n// carries it; the values a builder sets, where they are stored, how they are\n// checked against this on write, and how they reach the service are the host's,\n// exactly as with capability ids and fact kinds. moss never reads a value.\n//\n// EVERY FIELD IS A CLOSED SET — the kit's second law (kit/PRINCIPLES.md): a\n// `toggle`, a bounded `number`, a `pick` from declared options, or a\n// length-capped `line`. An open number or a free string is a hole with a nicer\n// name, and a service made to interpret one has to validate it itself. The kind\n// names are the subset of the shared field vocabulary (FieldKind) a builder\n// setting may use.\n//\n// `default` is required on every kind: the form must show a value before a\n// builder has touched anything, and the absence of a stored value has to mean\n// something definite to the service — the declared default. A bundle that\n// declares a field declares what it is when nobody has set it.\nconst configurationBase = {\n key: z.string().regex(/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/, 'a configuration key is lowercase words joined by single hyphens'),\n title: z.string().min(1),\n description: z.string().default(''),\n};\n\nconst configurationSchema = z\n .array(\n z.discriminatedUnion('kind', [\n z.object({ ...configurationBase, kind: z.literal('toggle'), default: z.boolean() }).strict(),\n z.object({ ...configurationBase, kind: z.literal('number'), min: z.number().int(), max: z.number().int(), default: z.number().int() }).strict(),\n z\n .object({\n ...configurationBase,\n kind: z.literal('pick'),\n options: z.array(z.object({ value: z.string().min(1), label: z.string().min(1) }).strict()).min(2),\n default: z.string().min(1),\n })\n .strict(),\n z.object({ ...configurationBase, kind: z.literal('line'), maxLength: z.number().int().positive().max(200), default: z.string() }).strict(),\n ]),\n )\n // Coherence the shape alone cannot state — refused with a sentence, the same\n // posture as the capability-id and settings-action checks, and surfaced\n // through runIntake's own `safeParse` mapping. One key per bundle; a default\n // that sits inside the thing it is a default FOR; options that do not repeat.\n .superRefine((fields, ctx) => {\n const seen = new Set<string>();\n fields.forEach((field, i) => {\n if (seen.has(field.key)) ctx.addIssue({ code: 'custom', path: [i, 'key'], message: `configuration \"${field.key}\": declared twice` });\n seen.add(field.key);\n if (field.kind === 'number') {\n if (field.min >= field.max) ctx.addIssue({ code: 'custom', path: [i], message: `configuration \"${field.key}\": min ${field.min} is not below max ${field.max}` });\n if (field.default < field.min || field.default > field.max) {\n ctx.addIssue({ code: 'custom', path: [i, 'default'], message: `configuration \"${field.key}\": default ${field.default} is outside [${field.min}, ${field.max}]` });\n }\n } else if (field.kind === 'pick') {\n const values = field.options.map((o) => o.value);\n if (new Set(values).size !== values.length) ctx.addIssue({ code: 'custom', path: [i, 'options'], message: `configuration \"${field.key}\": option values repeat` });\n if (!values.includes(field.default)) ctx.addIssue({ code: 'custom', path: [i, 'default'], message: `configuration \"${field.key}\": default \"${field.default}\" is not one of its options` });\n } else if (field.kind === 'line') {\n if (field.default.length > field.maxLength) ctx.addIssue({ code: 'custom', path: [i, 'default'], message: `configuration \"${field.key}\": default is longer than maxLength ${field.maxLength}` });\n }\n });\n })\n .default([]);\n\nexport type ConfigurationField = z.infer<typeof configurationSchema>[number];\n\n// ── WHAT AN ADD-ON LETS A PERSON EDIT ────────────────────────\n//\n// The host ships ONE editor and ONE assistant — generic machinery an add-on\n// cannot ship and must not copy. This declaration is where an add-on puts the\n// content those two read: a `document` is section types (each a set of fields\n// and a fragment that draws them over `$.content`) plus a section model. moss\n// validates the declaration against what the host holds — the kit registry, the\n// bundle's own capabilities and actions, the host's regions and checks — and\n// carries it; what the host does with a declared document (which rows hold its\n// draft, how publish is delivered) is the host's, exactly as with\n// `capabilities` and `configuration`. moss never reads it after intake.\n\n// THE ONE FIELD VOCABULARY. `configuration`'s kinds are the subset\n// `toggle | number | pick | line`; a document or block field may be any of\n// these. A field is a descriptor for the host's form — flat, unlike a\n// configuration entry, which additionally carries a default and per-kind\n// bounds because the host has to render a value before a builder sets one.\nconst FieldKind = z.enum(['line', 'long', 'url', 'pick', 'asset', 'color', 'number', 'toggle', 'list']);\n\nconst documentFieldSchema = z\n .object({\n // A data key, or a CSS custom property (`--color-brand`) for a theme token.\n key: z.string().regex(/^[a-z][a-z0-9-]*$|^--[a-z][a-z0-9-]*$/, 'a field key is lowercase-hyphen, optionally a `--` custom property'),\n label: z.string().min(1),\n kind: FieldKind,\n hint: z.string().default(''),\n placeholder: z.string().default(''),\n group: z.string().default(''),\n advanced: z.boolean().default(false),\n // Only meaningful for `pick`; intake refuses a `pick` with fewer than two.\n options: z.array(z.object({ value: z.string().min(1), label: z.string().min(1) }).strict()).default([]),\n max: z.number().int().positive().optional(),\n })\n .strict();\n\nconst sectionTypeSchema = z\n .object({\n type: z.string().min(1),\n label: z.string().min(1),\n fields: z.array(documentFieldSchema).min(1),\n // The default content a new section of this type starts with.\n starter: z.record(z.string(), z.unknown()).default({}),\n // The nova layout that draws this section over `$.content`. Typed as the\n // real layout schema (not `unknown`) so a malformed fragment is refused at\n // intake by SHAPE, and then walked by `validateLayout` for component/prop\n // existence — the exact rigor an action's own layout gets.\n fragment: LayoutNodeSchema,\n })\n .strict();\n\n// The section model: a FIXED list (the theme's base + dark halves, dark\n// extending base) or an OPEN list a person adds to, capped.\nconst sectionsSchema = z.union([\n z\n .object({\n fixed: z\n .array(\n z.object({ id: z.string().min(1), type: z.string().min(1), label: z.string().min(1), extends: z.string().optional() }).strict(),\n )\n .min(1),\n })\n .strict(),\n z.object({ open: z.object({ max: z.number().int().positive().max(40) }).strict() }).strict(),\n]);\n\nconst documentDeclarationSchema = z\n .object({\n id: z.string().regex(/^[a-z][a-z0-9-]*$/, 'a document id is lowercase words joined by single hyphens'),\n title: z.string().min(1),\n // The capability that opens the editor on this document — one of the\n // bundle's own `capabilities`, so the host's charter can grant it.\n capability: z.string().min(1),\n registry: z.array(sectionTypeSchema).min(1),\n sections: sectionsSchema,\n // Region actions the editor wants when the host's defaults do not fit (a\n // product's stage is a live shell, not fragments). Each is one of the\n // bundle's own actions or a region the host offers.\n regions: z.object({ bar: z.string().optional(), outline: z.string().optional(), stage: z.string().optional(), inspector: z.string().optional() }).strict().default({}),\n // Checks that run before publish (the theme's readability floors), each one\n // the host holds.\n checks: z.array(z.string().min(1)).default([]),\n // Where a published document is delivered: a route under the integration's\n // own prefix. The add-on owns the live rows and the public renderer; the\n // host owns the draft and the revisions.\n publish: z.object({ path: z.string().min(1) }).strict(),\n })\n .strict();\n\nexport type DocumentDeclaration = z.infer<typeof documentDeclarationSchema>;\n\n// ── WHAT AN ADD-ON'S ASSISTANT KNOWS ─────────────────────────\n//\n// The host ships ONE assistant — one thread on every screen, one `say` that\n// derives most of its context from the screen itself. What it cannot derive is\n// the add-on's own knowledge: its instructions, the reads it may run\n// (`grounding`, each a host vex fingerprint under a heading), the block types\n// it may render beyond the host's core, its opening offers, the host tools it\n// may call, and what it applies to. moss validates the declaration against the\n// host's fingerprints and tools and the bundle's own documents and actions, and\n// carries it; which thread and which `say` consume it is the host's.\n\n// A block type an assistant may render beyond the host's core — a palette with\n// swatches and a \"Use this\", a section proposal. Fields from the same\n// vocabulary as a document's (a `list` IS allowed here — that is the one place\n// it is), and a fragment drawn like any other, walked at intake.\nconst blockTypeSchema = z\n .object({\n type: z.string().min(1),\n label: z.string().min(1),\n fields: z.array(documentFieldSchema).default([]),\n // Data keys the block reads — carried, the block's own contract with its\n // fragment; moss does not resolve them.\n refs: z.array(z.string().min(1)).default([]),\n fragment: LayoutNodeSchema,\n })\n .strict();\n\nconst assistantDeclarationSchema = z\n .object({\n id: z.string().regex(/^[a-z][a-z0-9-]*$/, 'an assistant id is lowercase words joined by single hyphens'),\n title: z.string().min(1),\n intro: z.string().default(''),\n instructions: z.string().min(1),\n // The reads it may run — each a host vex fingerprint the session may already\n // call, under a heading (`as`) the rows appear beneath. `upfront` fetches at\n // thread start rather than on demand.\n grounding: z\n .array(\n z.object({ as: z.string().min(1), fingerprint: z.string().min(1), context: z.record(z.string(), z.unknown()).default({}), upfront: z.boolean().default(false) }).strict(),\n )\n .default([]),\n // Host tools it may call, from the host's closed set (`floors`, `derive`).\n tools: z.array(z.string().min(1)).default([]),\n blocks: z.array(blockTypeSchema).default([]),\n starters: z.array(z.string().min(1)).max(6).default([]),\n // One of the bundle's own documents, or one of its own screens (actions),\n // so the host can find the row from what is on screen. An add-on attaches an\n // assistant to its own surfaces only.\n applies: z.object({ document: z.string().optional(), screen: z.string().optional() }).strict(),\n modelRole: z.string().optional(),\n // Data keys of the screen the thread is keyed by, and the keys sent to the\n // model (absent = all). Carried; the host's `say` is the consumer.\n subject: z.array(z.string().min(1)).default([]),\n describe: z.array(z.string().min(1)).optional(),\n })\n .strict();\n\nexport type AssistantDeclaration = z.infer<typeof assistantDeclarationSchema>;\n\nconst BundleSchema = z\n .object({\n integration: z.string().min(1),\n // The store card's words, and the listing page's long form. Title, a\n // line, a paragraph — then the story (sections a page renders in order),\n // the highlight lines, and the press images. Story and highlights are\n // text, enforced as nothing more; press is the one field with teeth: each\n // entry is a path under the integration's own prefix, fetched ONCE at\n // intake and copied to the host (copyPress), never fetched at render\n // time. Strict, unlike before: a typo'd key here used to strip silently,\n // which is not what \"intake refuses anything outside the vocabulary\"\n // means.\n meta: z\n .object({\n title: z.string().default(''),\n tagline: z.string().default(''),\n description: z.string().default(''),\n story: z.array(z.object({ heading: z.string(), prose: z.string() }).strict()).default([]),\n highlights: z.array(z.string()).default([]),\n press: z.array(z.string()).default([]),\n })\n .strict()\n .default({ title: '', tagline: '', description: '', story: [], highlights: [], press: [] }),\n // What it needs, which an operator approves once at registration. A bundle\n // asking for more than it was approved for goes back to pending rather than\n // silently keeping the old grants and half-working.\n grants: z\n .object({\n actions: z.array(z.string()).default([]),\n data: z.array(z.string()).default([]),\n })\n .default({ actions: [], data: [] }),\n // THE VERBS THIS INTEGRATION GATES ON — the other direction from `grants`.\n // Grants are what it ASKS OF the host (surfaces it may call); a capability\n // is what it OFFERS the host's role editor to grant to PEOPLE, and its own\n // service is the code that checks the grant (`can(who, '<integration>.<id>')`).\n // moss validates shape and carries them, nothing more: WHICH endpoints a\n // capability gates is the integration's contract with its own service,\n // exactly as a fact kind's meaning and `meta`'s words are checked against\n // nothing here. The host composes the full grant string as `<integration>.\n // <id>` — a bundle cannot claim another integration's namespace — which is\n // why the id forbids a dot: it has to stay splittable, the same reason the\n // action namespace does. A capability carries no statement about WHO should\n // hold it: no face, no audience, no population marker. Every role grants it\n // identically, and who holds one is authored data in the host (its role\n // grants), never a declaration here. There is deliberately no gates list —\n // moss could name-check one (it name-checks every other cross-reference\n // below) but no consumer needs it; the field is additive if one appears.\n capabilities: z\n .array(\n z\n .object({\n id: z.string().regex(/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/, 'a capability id is lowercase words joined by single hyphens, and never a dot'),\n title: z.string().min(1),\n })\n .strict(),\n )\n .default([]),\n // WHAT IT TELLS AND WHAT IT HEARS — the fact kinds this integration\n // publishes and the kinds it consumes. moss validates shape and carries\n // them; what a kind MEANS is the host's contract vocabulary, exactly as\n // `meta` is words validated against nothing. There is no optional flag\n // to declare: the host's laws forbid a hard dependency between\n // integrations, so every need is soft by construction — absence\n // degrades, and the store says so in a sentence the HOST prints.\n offers: z.array(z.string()).default([]),\n needs: z.array(z.string()).default([]),\n // THE GRAMMARS THE ADD-ON WAS BUILT ON — how far along each grammar sequence\n // (nova's, Prism's, the host's kit) its documents are written. The host\n // upgrades them from here before anything else reads them, and refuses a\n // bundle written in a grammar newer than its own. Absent: before stamps.\n grammar: z.record(z.string(), z.number().int().nonnegative()).optional(),\n actions: z.record(z.string(), ActionDefinitionSchema),\n // action id → HOST action it rides on (a panel on the member detail). The\n // host must have declared itself attachable — see IntakeContext. The long\n // form adds a `preview`: an endpoint under the integration's own prefix that the\n // host calls with the offered identifiers while deriving its strip, and\n // that answers with display atoms — `bands` (colors) and `hint` (a line) —\n // so the rider's row can SHOW the belt, not the word for it, while the\n // host still learns nothing about what a belt is.\n attachments: z\n .record(\n z.string(),\n z.union([z.string(), z.object({ to: z.string(), preview: z.string().default('') }).strict()]),\n )\n .default({}),\n // action id → the MENU HUB it lists under (a roster under People). The hub\n // must be one the host offers to integrations.\n placements: z.record(z.string(), z.string()).default({}),\n // PAGES THE INTEGRATION SERVES AND THE HOST FRAMES. Lyra validates every layout\n // against a fixed component vocabulary, so an integration cannot ship UI — which is\n // right until a vendor's own browser SDK is the only way to render\n // something (a payment onboarding form). The answer is not to teach the\n // host's kit about the vendor: it is for the integration to serve a page and the\n // host to frame it, at its own origin, gated by exactly what every other\n // integration call is gated by.\n //\n // Named lyra-side, like `preview`, and under the integration's own prefix. What is\n // inside a frame the host does NOT validate — that is the real cost, and it\n // is why this is a declaration rather than an iframe a layout can conjure.\n //\n // PATH → THE ACTION IT BELONGS TO, and the second half is not decoration.\n // A grant is minted for whoever asks, so without an owner the only questions\n // this door could ask were \"signed in?\" and \"installed here?\" — which a\n // member of the gym passes. Naming the action makes the grant answerable\n // against the charter: a page belonging to a desk screen is mintable by\n // somebody who holds that desk screen, and by nobody else.\n frames: z.record(z.string(), z.string()).default({}),\n // The ONE action allowed to surface in the store: this integration's own\n // settings screen, reachable from its tile and from nowhere else. Add-ons\n // is a store; nothing functional lives there.\n settings: z.string().default(''),\n // THE INTEGRATION'S OWN WORDS, in the languages it speaks — the same\n // `(language, source, text)` shape the host's book uses, keyed by\n // LANGUAGE, never by full locale: Vienna and Hamburg read the same\n // sentences, and region is money and dates, which never come from a\n // book. A malformed key refuses the whole bundle at intake, exactly as a\n // placement outside the vocabulary does. The host merges these under its\n // own book, so an integration can never rename a host word.\n phrasebook: z.record(z.string().regex(/^[a-z]{2}$/, 'a phrasebook is keyed by LANGUAGE (`de`), never by locale (`de-AT`)'), z.record(z.string(), z.string())).default({}),\n // WHAT A BUILDER MAY SET per product — a closed vocabulary of settings the\n // host renders a form from. Carried, never read: the value's meaning is the\n // integration's contract with its own service. See `configurationSchema`.\n configuration: configurationSchema,\n // WHAT AN ADD-ON LETS A PERSON EDIT in the host's editor — section types,\n // fields, fragments, and a section model. See `documentDeclarationSchema`.\n documents: z.array(documentDeclarationSchema).default([]),\n // WHAT AN ADD-ON'S ASSISTANT KNOWS AND MAY DO — instructions, grounding,\n // blocks, tools, and what it applies to. See `assistantDeclarationSchema`.\n assistants: z.array(assistantDeclarationSchema).default([]),\n })\n .strict();\n\nexport type Bundle = z.infer<typeof BundleSchema>;\n\nexport type IntakeResult = { ok: true; bundle: Bundle } | { ok: false; reasons: string[] };\n\n// ── WHAT A BUNDLE MAY BE CALLED AT ───────────────────────────\n//\n// The intake checks below constrain what a bundle DECLARES. They never\n// constrained what the proxy FORWARDS — which forwarded any path under an integration's\n// prefix, for any signed-in principal at an installed studio. For a rank tracker\n// that exposes rank data. For a payments service it exposes a payments service.\n//\n// So the declaration becomes the perimeter: the union of every endpoint a\n// bundle's actions name under its own prefix, plus every preview an attachment\n// rides on. Anything else is not a route this integration has, and the proxy\n// answers as if it were not there.\n//\n// DERIVED, NEVER AUTHORED. An integration cannot widen its own reach without shipping\n// the screen or the strip that uses it, and re-importing is the only thing that\n// moves it — the same call an operator already makes.\nconst normalizeReach = (path: string): string => (path.split('?')[0] ?? '').replace(/\\/+$/, '');\n\n// ENDPOINT → THE ACTIONS THAT DECLARE IT, and the second half is the whole\n// point of this shape.\n//\n// This used to be a flat list of paths, and the loop below threw the action id\n// away — which made \"is this path declared?\" the only question the proxy could\n// ask. It is the wrong question. The charter draws its fences per ACTION\n// (`ext.desk.*` for a desk, `ext.member.*` for a member), so a perimeter that\n// cannot name the action cannot enforce them, and being signed in at a studio\n// that installed a payments integration was permission to call its merchant\n// onboarding endpoint.\n//\n// Several actions may name one endpoint, which is why the value is a list. Any\n// held action admits the call — the union, exactly as the charter itself\n// resolves — and the integration's own declaration is what states it, printed\n// on the approval card before anybody turns it on.\nexport type Reach = Record<string, string[]>;\n\nexport const reachOf = (bundle: Bundle, integrationId: string): Reach => {\n const own = `/integrations/${integrationId}/`;\n const reach: Reach = {};\n const admit = (url: string, actionId: string): void => {\n // A `/api/*/vex` endpoint is a call to the HOST, checked against the\n // fingerprints above. Only the integration's own prefix is reach.\n if (!url.startsWith(own)) return;\n const key = normalizeReach(url);\n const held = (reach[key] ??= []);\n if (!held.includes(actionId)) held.push(actionId);\n };\n for (const [actionId, raw] of Object.entries(bundle.actions)) {\n for (const endpoint of Object.values((raw as ActionDefinition).endpoints ?? {})) {\n admit((endpoint as { url?: string }).url ?? '', actionId);\n }\n }\n // A preview belongs to the action that rides the strip, so it inherits that\n // action's audience rather than being reachable by everybody who can see the\n // host screen it hangs off.\n for (const [actionId, binding] of Object.entries(bundle.attachments)) {\n if (typeof binding !== 'string') admit(binding.preview, actionId);\n }\n return Object.fromEntries(Object.entries(reach).sort(([a], [b]) => a.localeCompare(b)));\n};\n\n// FAIL CLOSED TWICE: a path this integration never declared, and a path no\n// action the CALLER HOLDS declares. A row with no reach — one written before\n// this column existed — still forwards nothing, because an empty object admits\n// nothing either. A silent widening is the failure mode worth paying a\n// re-import to avoid, and re-importing is one operator call.\nexport const reachAdmits = (reach: Reach, path: string, held: ReadonlySet<string>): boolean =>\n (reach[normalizeReach(path)] ?? []).some((actionId) => held.has(actionId));\n\n// WITHOUT A CALLER. The operator's probe asks whether this integration declared\n// a path at all, which is a question about the bundle rather than about\n// anybody's grants — an operator holds no catalog and needs none, and filtering\n// their diagnostic by a member's screens would make \"the screen is empty\"\n// harder to answer rather than safer.\nexport const reachDeclares = (reach: Reach, path: string): boolean => reach[normalizeReach(path)] !== undefined;\n\n// The same question at the other door. A frame names one owner rather than a\n// list: a page is served by the screen that opens it, and two screens wanting\n// one page is a bundle that should say so twice.\nexport const frameAdmits = (frames: Readonly<Record<string, string>>, path: string, held: ReadonlySet<string>): boolean => {\n const owner = frames[path];\n return owner !== undefined && held.has(owner);\n};\n\n// ── the gate ──────────────────────────────────────────────────\n//\n// Everything here exists to make a mistake fail loudly at import, naming\n// itself, instead of half-landing. Refusal is whole-payload: either the bundle\n// is coherent and all of it lands, or none of it does and the rows from the\n// last good import keep serving.\n\nexport type IntakeContext = {\n integrationId: string;\n // Component names the terminal can render, each with the props SCHEMA the app\n // carried for it (moss's strict Zod schema, filled from the kit) when it did.\n // The name is the floor — a layout naming anything else renders nothing, and\n // at the moment somebody opens it rather than the moment it arrived. The\n // schema is what lets intake refuse a prop the component has no place for (see\n // runIntake). A component with no schema is checked by name alone, exactly as\n // this set used to be.\n components: ReadonlyMap<string, { propsSchema?: unknown }>;\n // Fingerprints the app serves. An action calling one that does not exist is a\n // typo now and a 404 in front of a customer later.\n fingerprints: ReadonlySet<string>;\n // Host actions that accept attachments (`NiscApp.attachable`). An\n // integration cannot ride a screen that never offered a seat.\n attachable: ReadonlySet<string>;\n // Menu hubs that accept placed screens (`NiscApp.menuSlots`). Who owns a\n // menu is the host's question; this set is its answer.\n menuSlots: ReadonlySet<string>;\n // Region actions the host's editor offers a document (`bar`, `outline`,\n // `stage`, `inspector` defaults), the host's closed assistant tool set, and\n // the publish checks the host runs. A document/assistant naming one the host\n // does not hold fails at intake, not in front of a person. Optional and\n // empty-by-default: a bundle declaring no documents/assistants needs none,\n // and a host that has not enumerated them yet fails those names closed.\n regions?: ReadonlySet<string>;\n tools?: ReadonlySet<string>;\n checks?: ReadonlySet<string>;\n // The host's grammars (see grammar.ts). With it, a bundle's actions are\n // upgraded from the bundle's `grammar` stamp BEFORE they are parsed — an\n // action in an older grammar would fail today's strict schema otherwise.\n upgrader?: Upgrader;\n // The host's own actions — a bundle's triggers can close a loop through\n // them (the host emits what the integration listens to, and back).\n hostActions?: Readonly<Record<string, ActionDefinition>>;\n};\n\n// THE HOST'S VOCABULARY, gathered from the manifest for one intake. The one\n// place the registration route learns what this app offers a bundle to name —\n// components, fingerprints, attachment seats, menu hubs, and the assistant\n// tools / publish checks / editor regions a `documents`/`assistants`\n// declaration is checked against. Pure over the app plus the fingerprints the\n// route reads from the engine, so it is testable without a running server.\nexport const intakeContextOf = (\n app: NiscApp,\n integrationId: string,\n fingerprints: ReadonlySet<string>,\n upgrader?: Upgrader,\n): IntakeContext => ({\n integrationId,\n ...(upgrader === undefined ? {} : { upgrader }),\n components: new Map(Object.entries(app.shell?.components ?? {}).map(([name, def]) => [name, { propsSchema: def.meta?.propsSchema }])),\n fingerprints,\n attachable: new Set(Object.keys(app.attachable ?? {})),\n menuSlots: new Set(app.menuSlots ?? []),\n tools: new Set(app.assistantTools ?? []),\n checks: new Set(app.publishChecks ?? []),\n regions: new Set(app.editorRegions ?? []),\n hostActions: app.actions,\n});\n\nconst AUDIENCE = /^[a-z][a-z0-9-]*$/;\n\n// The host surface a screen calls to be handed a framed page's URL. Named once\n// here because intake admits it and the frame route serves it, and two spellings\n// of the same path is how a seam stops working for one caller.\nexport const FRAME_GRANT_URL = '/api/integrations/frame';\n\n// A prop VALUE that resolves at RENDER time, so intake cannot know its type: a\n// binding string (`$.x`, `{{ }}`, `@scope` — nova's own isBinding), or a\n// directive object (`$if`, `$eq`, `$prism` — a record carrying a `$`-prefixed\n// key). Its KEY is still checked; only the value is skipped. Top-level by design\n// — a binding buried inside an otherwise-static object value is not unwound, the\n// same line the case draws.\nconst isDeferred = (value: unknown): boolean =>\n (typeof value === 'string' && isBinding(value)) || (isRecord(value) && Object.keys(value).some((key) => key.startsWith('$')));\n\nconst isPlainRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\n// A bundle's actions, brought to the host's grammar. Only the stamp and the\n// actions are touched; everything else is parsed as it arrived.\nconst upgradeBundle = (payload: unknown, upgrader: Upgrader | undefined): { ok: true; payload: unknown } | { ok: false; reasons: string[] } => {\n if (upgrader === undefined || !isPlainRecord(payload) || !isPlainRecord(payload['actions'])) return { ok: true, payload };\n const declared = payload['grammar'];\n const stamp = isPlainRecord(declared) ? Object.fromEntries(Object.entries(declared).map(([k, v]) => [k, Number(v)])) : {};\n try {\n const actions = Object.fromEntries(\n Object.entries(payload['actions']).map(([id, definition]) => [id, upgrader.upgrade(definition, { kind: 'nisc.nova/action', stamp }).document]),\n );\n return { ok: true, payload: { ...payload, actions, grammar: upgrader.stamp } };\n } catch (error) {\n if (!(error instanceof StrataError)) throw error;\n return {\n ok: false,\n reasons:\n error.code === 'TOO_NEW'\n ? ['This integration was built on newer nisc grammars than this host runs — the host must be updated first.', ...error.details]\n : [error.message.split('\\n')[0] ?? error.code, ...error.details],\n };\n }\n};\n\nexport const runIntake = (payload: unknown, ctx: IntakeContext): IntakeResult => {\n // Before anything reads it — the upgrader walks it and the schema recurses\n // on it, and either overflows the stack on a deep enough payload.\n if (exceedsDepth(payload)) return { ok: false, reasons: [depthRefusal()] };\n const upgraded = upgradeBundle(payload, ctx.upgrader);\n if (!upgraded.ok) return upgraded;\n const parsed = BundleSchema.safeParse(upgraded.payload);\n if (!parsed.success) {\n return { ok: false, reasons: parsed.error.issues.map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`) };\n }\n const bundle = parsed.data;\n const reasons: string[] = [];\n\n // Validate a layout the way an action's own layout is validated: the\n // component name against what the app can render, and each prop against the\n // component's strict schema (a deferred binding/directive value has its key\n // checked and its value skipped). Reused for section and block fragments — a\n // fragment is a layout over `$.content` and earns the same refusal at the\n // same moment as an action layout.\n const validateLayout = (node: unknown, label: string): void => {\n const found = new Set<string>();\n walkNodes(node, (record) => {\n const name = record['component'];\n if (typeof name !== 'string') return;\n const spec = ctx.components.get(name);\n if (spec === undefined) {\n found.add(`${label}: layout uses \"${name}\", which this app has no component for`);\n return;\n }\n const schema = spec.propsSchema;\n const props = record['props'];\n if (!(schema instanceof z.ZodObject) || !isRecord(props)) return; // name-only\n const shape = schema.shape as Record<string, z.ZodTypeAny>;\n for (const [key, value] of Object.entries(props)) {\n if (!(key in shape)) {\n found.add(`${label}: \"${name}\" has no prop \"${key}\"`);\n continue;\n }\n if (isDeferred(value)) continue;\n const check = shape[key]?.safeParse(value);\n if (check !== undefined && !check.success) {\n found.add(`${label}: \"${name}\" prop \"${key}\" — ${check.error.issues[0]?.message ?? 'invalid'}`);\n }\n }\n });\n for (const reason of found) reasons.push(reason);\n };\n\n if (bundle.integration !== ctx.integrationId) {\n reasons.push(`bundle says it is \"${bundle.integration}\" but was fetched as \"${ctx.integrationId}\"`);\n }\n\n for (const [id, raw] of Object.entries(bundle.actions)) {\n const action = raw as ActionDefinition;\n // ── the namespace ──\n //\n // `ext.<audience>.<integration>.<name>`. The charter grants the GLOB, once\n // per audience, so a new action needs no charter edit — and an integration\n // can only ever land inside a fence drawn before it existed.\n const parts = id.split('.');\n if (parts[0] !== 'ext' || parts.length < 4 || !AUDIENCE.test(parts[1] ?? '')) {\n reasons.push(`action ${id}: not namespaced ext.<audience>.<integration>.<name>`);\n } else if (parts[2] !== ctx.integrationId) {\n reasons.push(`action ${id}: claims the \"${parts[2]}\" namespace, which belongs to somebody else`);\n }\n\n if (action.id !== id) reasons.push(`action ${id}: its own id says \"${action.id}\"`);\n\n // ── the layout composes what the kit has, and sets props the kit knows ──\n //\n // The name is the floor: a component the terminal cannot render shows\n // nothing, and at the moment somebody opens the screen rather than the moment\n // it arrived. When the app carried a props schema for the component, the\n // props are checked too — an unknown prop (`Choice` has no `submitRef`) is\n // the failure that installs cleanly and does nothing under a customer's\n // finger, and a strict schema is exactly what refuses it. A prop whose value\n // is deferred (a binding or directive) has its KEY checked and its value\n // skipped. Only authored layouts reach here — a served or flattened tree is\n // never validated against an authoring schema (ADAPTER.md).\n validateLayout(action.layout, `action ${id}`);\n\n // ── it reaches two places and no others ──\n for (const [name, endpoint] of Object.entries(action.endpoints ?? {})) {\n const ep = endpoint as { url?: string; fn?: string; request?: { fingerprint?: string } };\n if (ep.fn !== undefined) {\n // `fn:` runs IN the app's process, next to the session's shell. An\n // integration cannot ship code that runs here — that is the whole\n // point of it being a separate service.\n reasons.push(`action ${id}: endpoint \"${name}\" uses fn:, which runs in this app's process`);\n continue;\n }\n const url = ep.url ?? '';\n const own = `/integrations/${ctx.integrationId}/`;\n // The one HOST surface an action may name without a fingerprint: asking\n // for a frame grant. It reads nothing and writes nothing — it hands back\n // a URL the integration's own page is served at — so there is no fingerprint for\n // it to name, and the alternative is every integration inventing its own way to\n // reach a door that already exists.\n if (url === FRAME_GRANT_URL) continue;\n if (url.startsWith(own)) {\n // `/hook/` IS RESERVED. It is the one path on this server that requires\n // no principal (server.ts, the webhook door) — a vendor calling in has\n // no session and could not have one. An action endpoint declared there\n // would be a screen's call riding the unauthenticated door, which is\n // how a door meant for one thing becomes a way around everything else.\n if (url.startsWith(`${own}hook/`)) {\n reasons.push(`action ${id}: endpoint \"${name}\" is under /hook/, which is the unauthenticated webhook path`);\n }\n // `/frame/` is where a grant is REDEEMED — a browser GET carrying a\n // token instead of a session. An action endpoint there would be a\n // screen's call spending a credential meant for a document.\n if (url.startsWith(`${own}frame/`)) {\n reasons.push(`action ${id}: endpoint \"${name}\" is under /frame/, which redeems frame grants`);\n }\n continue;\n }\n if (!url.startsWith('/api/')) {\n reasons.push(`action ${id}: endpoint \"${name}\" calls \"${url}\" — only ${own}* or /api/*/vex`);\n continue;\n }\n const fingerprint = ep.request?.fingerprint;\n if (typeof fingerprint !== 'string') {\n reasons.push(`action ${id}: endpoint \"${name}\" calls the app without naming a fingerprint`);\n } else if (!ctx.fingerprints.has(fingerprint)) {\n reasons.push(`action ${id}: endpoint \"${name}\" calls \"${fingerprint}\", which this app does not serve`);\n }\n }\n }\n\n // ── no chain of steps that never ends ──\n //\n // A trigger that re-emits its own channel is valid data, and nova stops it\n // at its budget when it runs — but a bundle is a stranger's code path into\n // every principal's shell, so a loop is refused here rather than run. Walked\n // with the host's actions, since a loop can close through the host's\n // triggers; a loop the host has on its own is the host's to answer (boot\n // names it) and does not refuse somebody else's bundle.\n for (const cycle of chainCycles({ ...(ctx.hostActions ?? {}), ...bundle.actions })) {\n if (cycle.steps.some((step) => bundle.actions[step.action] !== undefined)) {\n reasons.push(`a chain of steps that never ends: ${cycle.path}`);\n }\n }\n\n // ── the bindings point at things that exist, on both ends ────\n for (const [actionId, binding] of Object.entries(bundle.attachments)) {\n const host = typeof binding === 'string' ? binding : binding.to;\n const preview = typeof binding === 'string' ? '' : binding.preview;\n if (bundle.actions[actionId] === undefined) reasons.push(`attachment ${actionId}: no such action in this bundle`);\n if (!ctx.attachable.has(host)) reasons.push(`attachment ${actionId}: attaches to \"${host}\", which offers nothing`);\n if (preview !== '' && !preview.startsWith(`/integrations/${ctx.integrationId}/`)) {\n reasons.push(`attachment ${actionId}: preview \"${preview}\" is not under this integration's own prefix`);\n }\n }\n for (const [actionId, hub] of Object.entries(bundle.placements)) {\n if (bundle.actions[actionId] === undefined) reasons.push(`placement ${actionId}: no such action in this bundle`);\n if (!ctx.menuSlots.has(hub)) reasons.push(`placement ${actionId}: targets \"${hub}\", which accepts no integrations`);\n }\n // A FRAMED PAGE IS STILL THE INTEGRATION'S OWN GROUND. Same prefix rule as a\n // preview, and neither reserved door: `/hook/` needs no principal and\n // `/frame/` is where a grant is spent, so a page served at either would be\n // reachable by something other than the grant that was minted for it.\n const ownPrefix = `/integrations/${ctx.integrationId}/`;\n for (const [path, actionId] of Object.entries(bundle.frames)) {\n if (!path.startsWith(ownPrefix)) {\n reasons.push(`frame \"${path}\": not under this integration's own prefix`);\n } else if (path.startsWith(`${ownPrefix}hook/`) || path.startsWith(`${ownPrefix}frame/`)) {\n reasons.push(`frame \"${path}\": /hook/ and /frame/ are reserved`);\n }\n // The owner has to be real, or the grant check below it can never pass and\n // the page is simply unreachable — a refusal at intake beats a screen that\n // opens onto nothing.\n if (bundle.actions[actionId] === undefined) {\n reasons.push(`frame \"${path}\": belongs to \"${actionId}\", which is not an action in this bundle`);\n }\n }\n // PRESS IS FETCHED ONCE, AT INTAKE — it is never reach (reachOf sweeps\n // declarations; these are deliberately not among them) and the proxy never\n // forwards it. The paths still obey the same fences as every other\n // declaration: the integration's own ground, neither reserved door.\n for (const path of bundle.meta.press) {\n if (!path.startsWith(ownPrefix)) {\n reasons.push(`press \"${path}\": not under this integration's own prefix`);\n } else if (path.startsWith(`${ownPrefix}hook/`) || path.startsWith(`${ownPrefix}frame/`)) {\n reasons.push(`press \"${path}\": /hook/ and /frame/ are reserved`);\n }\n }\n // TWO CAPABILITIES WITH ONE ID compose to the same grant string, so the\n // host's role editor could never tell them apart — a bundle-coherence fault,\n // caught here beside the other cross-reference checks. Shape is the schema's;\n // uniqueness is the only thing about a capability moss can know is wrong.\n const seenCapability = new Set<string>();\n for (const capability of bundle.capabilities) {\n if (seenCapability.has(capability.id)) {\n reasons.push(`capability \"${capability.id}\": declared twice`);\n }\n seenCapability.add(capability.id);\n }\n if (bundle.settings !== '' && bundle.actions[bundle.settings] === undefined) {\n reasons.push(`settings: \"${bundle.settings}\" is not an action in this bundle`);\n }\n\n // ── WHAT AN ADD-ON LETS A PERSON EDIT ────────────────────────\n //\n // Cross-references the host holds or the bundle itself declares — the same\n // posture as every check above. Shape is the schema's; these are the things\n // only the surrounding bundle and the host can know are wrong.\n const ownActions = new Set(Object.keys(bundle.actions));\n const ownCapabilities = new Set(bundle.capabilities.map((c) => c.id));\n const hostRegions = ctx.regions ?? new Set<string>();\n const hostChecks = ctx.checks ?? new Set<string>();\n const seenDocument = new Set<string>();\n for (const doc of bundle.documents) {\n if (seenDocument.has(doc.id)) reasons.push(`document \"${doc.id}\": declared twice`);\n seenDocument.add(doc.id);\n if (!ownCapabilities.has(doc.capability)) {\n reasons.push(`document \"${doc.id}\": capability \"${doc.capability}\" is not one this bundle declares`);\n }\n if (!doc.publish.path.startsWith(ownPrefix)) {\n reasons.push(`document \"${doc.id}\": publish path \"${doc.publish.path}\" is not under this integration's own prefix`);\n }\n for (const [region, actionId] of Object.entries(doc.regions)) {\n if (actionId === undefined) continue;\n if (!ownActions.has(actionId) && !hostRegions.has(actionId)) {\n reasons.push(`document \"${doc.id}\": region \"${region}\" names \"${actionId}\", which is neither an action in this bundle nor a region the host offers`);\n }\n }\n for (const check of doc.checks) {\n if (!hostChecks.has(check)) reasons.push(`document \"${doc.id}\": check \"${check}\" is not one the host offers`);\n }\n const registryTypes = new Set(doc.registry.map((s) => s.type));\n const seenType = new Set<string>();\n for (const section of doc.registry) {\n if (seenType.has(section.type)) reasons.push(`document \"${doc.id}\": section type \"${section.type}\" declared twice`);\n seenType.add(section.type);\n const seenKey = new Set<string>();\n for (const field of section.fields) {\n if (seenKey.has(field.key)) reasons.push(`document \"${doc.id}\" section \"${section.type}\": field key \"${field.key}\" declared twice`);\n seenKey.add(field.key);\n if (field.kind === 'pick' && field.options.length < 2) {\n reasons.push(`document \"${doc.id}\" section \"${section.type}\": pick field \"${field.key}\" needs at least two options`);\n }\n if (field.kind === 'list') {\n reasons.push(`document \"${doc.id}\" section \"${section.type}\": a list field is only allowed inside an assistant block`);\n }\n }\n validateLayout(section.fragment, `document \"${doc.id}\" section \"${section.type}\" fragment`);\n }\n if ('fixed' in doc.sections) {\n const siblingIds = new Set(doc.sections.fixed.map((f) => f.id));\n for (const f of doc.sections.fixed) {\n if (!registryTypes.has(f.type)) reasons.push(`document \"${doc.id}\": fixed section \"${f.id}\" has type \"${f.type}\", which is not in the registry`);\n if (f.extends !== undefined && !siblingIds.has(f.extends)) {\n reasons.push(`document \"${doc.id}\": fixed section \"${f.id}\" extends \"${f.extends}\", which is not a sibling`);\n }\n }\n }\n }\n\n // ── WHAT AN ADD-ON'S ASSISTANT KNOWS ─────────────────────────\n const documentIds = new Set(bundle.documents.map((d) => d.id));\n const hostTools = ctx.tools ?? new Set<string>();\n const seenAssistant = new Set<string>();\n for (const assistant of bundle.assistants) {\n if (seenAssistant.has(assistant.id)) reasons.push(`assistant \"${assistant.id}\": declared twice`);\n seenAssistant.add(assistant.id);\n // It attaches to its OWN ground: a document of this bundle or a screen\n // (action) of this bundle, and it must attach to one of them.\n if (assistant.applies.document === undefined && assistant.applies.screen === undefined) {\n reasons.push(`assistant \"${assistant.id}\": applies to neither a document nor a screen`);\n }\n if (assistant.applies.document !== undefined && !documentIds.has(assistant.applies.document)) {\n reasons.push(`assistant \"${assistant.id}\": applies to document \"${assistant.applies.document}\", which this bundle does not declare`);\n }\n if (assistant.applies.screen !== undefined && !ownActions.has(assistant.applies.screen)) {\n reasons.push(`assistant \"${assistant.id}\": applies to screen \"${assistant.applies.screen}\", which is not an action in this bundle`);\n }\n for (const read of assistant.grounding) {\n if (!ctx.fingerprints.has(read.fingerprint)) {\n reasons.push(`assistant \"${assistant.id}\": grounding \"${read.as}\" reads \"${read.fingerprint}\", which this app does not serve`);\n }\n }\n for (const tool of assistant.tools) {\n if (!hostTools.has(tool)) reasons.push(`assistant \"${assistant.id}\": tool \"${tool}\" is not one the host offers`);\n }\n const seenBlock = new Set<string>();\n for (const block of assistant.blocks) {\n if (seenBlock.has(block.type)) reasons.push(`assistant \"${assistant.id}\": block type \"${block.type}\" declared twice`);\n seenBlock.add(block.type);\n const seenKey = new Set<string>();\n for (const field of block.fields) {\n if (seenKey.has(field.key)) reasons.push(`assistant \"${assistant.id}\" block \"${block.type}\": field key \"${field.key}\" declared twice`);\n seenKey.add(field.key);\n // A `list` field IS allowed in a block — this is the one place it is.\n if (field.kind === 'pick' && field.options.length < 2) {\n reasons.push(`assistant \"${assistant.id}\" block \"${block.type}\": pick field \"${field.key}\" needs at least two options`);\n }\n }\n validateLayout(block.fragment, `assistant \"${assistant.id}\" block \"${block.type}\" fragment`);\n }\n }\n\n return reasons.length > 0 ? { ok: false, reasons } : { ok: true, bundle };\n};\n\n// The sentence both decision screens print — the approval card and the store\n// tile say WHAT APPEARS WHERE from the same declarations, derived once here so\n// neither can drift from what intake actually accepted.\nexport const describePlacements = (bundle: Bundle, names: Readonly<Record<string, string>> = {}): string => {\n // IDS ARE FOR WIRES; THIS SENTENCE IS FOR A PERSON.\n //\n // It is printed on the approval card and on the store tile — both read by\n // somebody deciding whether to turn an integration on — and `hub.money` told them\n // nothing they did not already have to guess. The host supplies the words for\n // its own hubs and screens (`NiscApp.placementNames`); anything it has no word\n // for falls back to the id, which is honest rather than blank.\n const say = (id: string): string => names[id] ?? id;\n const parts: string[] = [];\n for (const [actionId, binding] of Object.entries(bundle.attachments)) {\n const host = typeof binding === 'string' ? binding : binding.to;\n parts.push(`a \"${bundle.actions[actionId]?.title ?? actionId}\" panel on ${say(host)}`);\n }\n for (const [actionId, hub] of Object.entries(bundle.placements)) {\n parts.push(`\"${bundle.actions[actionId]?.title ?? actionId}\" under ${say(hub)}`);\n }\n if (bundle.settings !== '') parts.push('a settings screen on its store tile');\n return parts.length === 0 ? '' : `Adds ${parts.join(' · ')}.`;\n};\n\n// ── press, copied at intake ──────────────────────────────────\n//\n// A listing sells with images, and the store never fetches from a service at\n// render time — a dead add-on degrades its screens (injection stays an\n// attempt), never its listing. So the bytes cross ONCE, here: each declared\n// path is fetched from the service through the same mapping the proxy uses,\n// handed to the host's seam (NiscApp.storePress), and the URL the host\n// answers with is what the row keeps.\n//\n// Refusal is whole-payload, like everything else at this gate: a dead path, a\n// non-image answer, a seam that throws — or press declared on a deployment\n// with no seam to hold it — refuses the bundle with a sentence naming the\n// path, and the last good import keeps serving. The engine invents no bounds\n// of its own: too big and too many are the seam's to refuse, and its refusal\n// arrives here as any other.\n//\n// The stored NAME is the path under the prefix, deterministic per\n// (integration, path): a re-import overwrites its own images rather than\n// accumulating copies.\n\nexport type StorePress = (integrationId: string, name: string, bytes: Uint8Array, contentType: string) => Promise<string>;\n\nexport type PressResult = { ok: true; urls: string[] } | { ok: false; reasons: string[] };\n\nexport const copyPress = async (\n bundle: Bundle,\n integrationId: string,\n serviceUrl: string,\n store: StorePress | undefined,\n fetchImpl: typeof fetch = fetch,\n): Promise<PressResult> => {\n const declared = bundle.meta.press;\n if (declared.length === 0) return { ok: true, urls: [] };\n if (store === undefined) {\n return { ok: false, reasons: [`press: the bundle declares ${declared.length} image(s), and this deployment has no storePress seam to hold them`] };\n }\n const own = `/integrations/${integrationId}/`;\n const urls: string[] = [];\n for (const path of declared) {\n const rest = path.slice(own.length);\n try {\n const response = await fetchImpl(`${serviceUrl.replace(/\\/$/, '')}/${rest}`);\n if (!response.ok) return { ok: false, reasons: [`press \"${path}\": the service answered ${response.status}`] };\n const contentType = (response.headers.get('content-type') ?? '').split(';')[0]?.trim() ?? '';\n if (!contentType.startsWith('image/')) {\n return { ok: false, reasons: [`press \"${path}\": answered \"${contentType === '' ? 'nothing' : contentType}\", which is not an image`] };\n }\n const bytes = new Uint8Array(await response.arrayBuffer());\n urls.push(await store(integrationId, rest, bytes, contentType));\n } catch (err) {\n return { ok: false, reasons: [`press \"${path}\": ${String(err)}`] };\n }\n }\n return { ok: true, urls };\n};\n\n// ── the outbound act ─────────────────────────────────────────\n//\n// Call an installed integration when nobody is driving — the outbound mirror\n// of `executeAs`. Auth, the outbox sweep, an erase propagating across every\n// ledger: acts the DEPLOYMENT performs, with no request in flight and no\n// principal mid-click. The proxy cannot carry them (it needs both), and\n// handing an app the signer would hand it the two gates below to re-implement\n// wrongly once — so the narrow verb is the surface.\n//\n// Two deliberate differences from the proxy:\n//\n// NOT GATED BY REACH. Reach fences what a screen may cause a browser to\n// reach — a fence around actions — and a lifecycle verb is not an action\n// and has no screen. Reach is derived from declared endpoints, so it could\n// never admit an undeclared verb anyway; the integration gates the call\n// itself, on the verified claims (principal and scope — there is no other\n// field in the envelope; see assert.ts).\n//\n// THE PRINCIPAL IS THE PERSON WHO ACTED, so the owner who pressed erase is\n// who the other ledger sees. A machinery principal would make every\n// integration's owner check pass or fail on a name that belongs to no one.\n//\n// The two gates that stay: approved, and installed for this principal's\n// tenant. Refusals THROW with a sentence — the caller is the deployment's own\n// orchestrator, and a state error is something it must see, not a status to\n// mistake for the integration's answer. What the integration answers comes\n// back as the Response, whatever it is; an unreachable service rejects, and a\n// sweep's whole job is to retry.\n//\n// One ordering the gate forces on the app: an erase retried after the\n// integration was UNINSTALLED refuses forever — rightly, no credential for an\n// uninstalled integration — so an orchestrator sequences erasure ahead of\n// uninstall's row retirement, or drains pending erases first.\n\nexport type CallIntegration = (\n id: string,\n path: string,\n init: { principal: string; method?: string; body?: unknown; scope?: Record<string, unknown> },\n) => Promise<Response>;\n\nexport const callIntegrationWith = (deps: {\n pool: PgPool;\n // The app's install answer for this principal's tenant — undefined means\n // the app has no install seam, which admits (the proxy's rule, mirrored).\n installedFor: (principal: string) => Promise<readonly string[] | undefined>;\n // The same scope values the resolver gives vex for `$scope`; `init.scope`\n // merges OVER them — extras the deployment explicitly vouches for.\n scopeValuesFor: (principal: string) => Promise<Record<string, unknown>>;\n mint: (claims: { integration: string; principal: string; scope: Record<string, unknown> }) => string;\n fetchImpl?: typeof fetch;\n // The deployment's telemetry sink, if any — one `integration.call` span per\n // outbound call, naming the add-on, the path, and the answer's status. The\n // operator surface's ad-hoc `watchCalls` tap is the proof this seam is the\n // right one; this generalises it.\n telemetry?: Telemetry;\n}): CallIntegration => {\n const fetchImpl = deps.fetchImpl ?? fetch;\n const emit = emitterOf(deps.telemetry);\n return async (id, path, init) => {\n const clock = emit === undefined ? undefined : spanClock();\n // A refusal or answer, as one span. `httpStatus` is present only when the\n // add-on actually answered; a guard refusal and an unreachable service both\n // carry none, distinguished by `status`.\n const done = (status: 'ok' | 'error' | 'refused', httpStatus?: number): void => {\n if (emit === undefined || clock === undefined) return;\n emit({\n name: 'integration.call',\n startUnixNano: clock.startUnixNano,\n endUnixNano: clock.endUnixNano(),\n status,\n attributes: { addon: id, path, ...(httpStatus !== undefined ? { httpStatus } : {}) },\n });\n };\n\n const row = await deps.pool.query('SELECT url, status FROM integrations WHERE id = $1', [id]);\n const found = row.rows[0] as { url?: string; status?: string } | undefined;\n if (found === undefined) {\n done('refused');\n throw new Error(`moss: callIntegration(\"${id}\"): no such integration.`);\n }\n if (found.status !== 'approved') {\n done('refused');\n throw new Error(`moss: callIntegration(\"${id}\"): not approved (status \"${String(found.status)}\").`);\n }\n const installed = await deps.installedFor(init.principal);\n if (installed !== undefined && !installed.includes(id)) {\n done('refused');\n throw new Error(`moss: callIntegration(\"${id}\"): not installed for \"${init.principal}\".`);\n }\n const scope = { ...(await deps.scopeValuesFor(init.principal)), ...(init.scope ?? {}) };\n const target = `${String(found.url).replace(/\\/$/, '')}/${path.replace(/^\\/+/, '')}`;\n let response: Response;\n try {\n response = await fetchImpl(target, {\n method: init.method ?? 'POST',\n headers: {\n 'content-type': 'application/json',\n authorization: `Bearer ${deps.mint({ integration: id, principal: init.principal, scope })}`,\n },\n ...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),\n });\n } catch (err) {\n done('error');\n throw err;\n }\n done(response.ok ? 'ok' : 'error', response.status);\n return response;\n };\n};\n\n// ── the tables moss owns ─────────────────────────────────────\n//\n// Defined here, on the app's pool, for the same reason vex defines `vex_cache`:\n// an app that had to author them would author them differently each time, and\n// the shape is not application knowledge.\n\n// THE TABLES MOSS OWNS, as one strata sequence. Migration 1 is the DDL every\n// boot used to run, verbatim and in order — CREATE … IF NOT EXISTS, then the\n// ADD COLUMN IF NOT EXISTS that caught older tables up — so it converges any\n// earlier deployment to the current shape, once, and the ledger remembers.\n// The generation pointer rides the same migration: it too existed on every\n// boot. HISTORY: never edit an applied migration; append one (see\n// test/baselines.test.ts, which pins the checksum).\nexport const MOSS_SEQUENCE: Sequence = {\n id: 'nisc.moss',\n migrations: [\n {\n description: 'Integrations, their actions and the generation pointer, converged from any earlier shape',\n steps: [\n { kind: 'sql', sql: `CREATE TABLE IF NOT EXISTS integrations (\n id text PRIMARY KEY,\n url text NOT NULL,\n -- THE HASH, NEVER THE KEY. The integration key is minted at registration\n -- (see assert.ts for the credential rule), returned once in that response,\n -- and this is all that remains of it here. Presenting the key is the only\n -- way to produce this value again, so a stolen database does not hold a\n -- credential — and a lost key is re-registered, not recovered.\n key_hash text,\n status text NOT NULL DEFAULT 'pending',\n -- The store card's words, straight from the bundle's meta. Columns\n -- rather than jsonb so an app's vex read can select them like anything\n -- else on this table.\n title text NOT NULL DEFAULT '',\n tagline text NOT NULL DEFAULT '',\n description text NOT NULL DEFAULT '',\n -- The listing page's long form, re-imported whole like everything else\n -- about a bundle. press holds the URLS THE HOST ANSWERED WITH at\n -- intake (copyPress), never the paths the bundle declared — the listing\n -- composes from host ground alone.\n story jsonb NOT NULL DEFAULT '[]'::jsonb,\n highlights jsonb NOT NULL DEFAULT '[]'::jsonb,\n press jsonb NOT NULL DEFAULT '[]'::jsonb,\n -- WHAT APPEARS WHERE, as one derived sentence (describePlacements) —\n -- printed by the approval card and the store tile from this one place.\n adds text NOT NULL DEFAULT '',\n -- The one integration action the store may open: its settings screen.\n settings_action text NOT NULL DEFAULT '',\n requested_actions jsonb NOT NULL DEFAULT '[]'::jsonb,\n requested_data jsonb NOT NULL DEFAULT '[]'::jsonb,\n approved_data jsonb NOT NULL DEFAULT '[]'::jsonb,\n -- What it tells and hears (bundle offers/needs), beside the grants\n -- because they are the same kind of thing: the integration's declared\n -- statement, written at import, replaced on re-registration. moss\n -- never reads them; the host's bus does.\n offers jsonb NOT NULL DEFAULT '[]'::jsonb,\n needs jsonb NOT NULL DEFAULT '[]'::jsonb,\n -- The verbs the integration gates on ({id, title}), for the host's role\n -- editor to grant. Beside offers/needs because it is the same kind of\n -- thing: a declaration written at import, replaced on re-registration,\n -- that moss never reads — the host does.\n capabilities jsonb NOT NULL DEFAULT '[]'::jsonb,\n -- WHAT A BUILDER MAY SET per product — the closed-set field declaration,\n -- beside capabilities because it is the same kind of thing: a declaration\n -- written at import, replaced on re-registration, that moss never reads.\n -- The host renders a settings form from it and stores the values itself.\n configuration jsonb NOT NULL DEFAULT '[]'::jsonb,\n -- WHAT AN ADD-ON LETS A PERSON EDIT — section types, fields, fragments,\n -- and a section model the host's editor renders. Beside configuration\n -- because it is the same kind of thing: a declaration written at import,\n -- replaced on re-registration, that moss never reads — the host does.\n documents jsonb NOT NULL DEFAULT '[]'::jsonb,\n -- WHAT AN ADD-ON'S ASSISTANT KNOWS AND MAY DO — instructions, grounding,\n -- blocks, tools, what it applies to. Same kind of thing, same lifecycle;\n -- the host's assistant is the consumer.\n assistants jsonb NOT NULL DEFAULT '[]'::jsonb,\n -- EVERY PATH THE PROXY MAY FORWARD, derived from the bundle at intake\n -- (reachOf). Beside the grants because it is one: a grant of reach, held\n -- by the same row, revoked by the same delete.\n reach jsonb NOT NULL DEFAULT '[]'::jsonb,\n -- Pages this integration serves and the host frames. Kept apart from reach\n -- because they are spent differently: reach is a screen's call carrying a\n -- session, a frame is a document GET carrying a grant.\n frames jsonb NOT NULL DEFAULT '[]'::jsonb,\n last_import_at timestamptz,\n last_error text\n)\n` },\n { kind: 'sql', sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS reach jsonb NOT NULL DEFAULT '[]'::jsonb` },\n { kind: 'sql', sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS frames jsonb NOT NULL DEFAULT '[]'::jsonb` },\n { kind: 'sql', sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS phrasebook jsonb NOT NULL DEFAULT '{}'::jsonb` },\n { kind: 'sql', sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS story jsonb NOT NULL DEFAULT '[]'::jsonb` },\n { kind: 'sql', sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS highlights jsonb NOT NULL DEFAULT '[]'::jsonb` },\n { kind: 'sql', sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS press jsonb NOT NULL DEFAULT '[]'::jsonb` },\n { kind: 'sql', sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS offers jsonb NOT NULL DEFAULT '[]'::jsonb` },\n { kind: 'sql', sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS needs jsonb NOT NULL DEFAULT '[]'::jsonb` },\n { kind: 'sql', sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS capabilities jsonb NOT NULL DEFAULT '[]'::jsonb` },\n { kind: 'sql', sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS configuration jsonb NOT NULL DEFAULT '[]'::jsonb` },\n { kind: 'sql', sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS documents jsonb NOT NULL DEFAULT '[]'::jsonb` },\n { kind: 'sql', sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS assistants jsonb NOT NULL DEFAULT '[]'::jsonb` },\n { kind: 'sql', sql: `CREATE TABLE IF NOT EXISTS integration_actions (\n integration_id text NOT NULL REFERENCES integrations(id) ON DELETE CASCADE,\n action_id text NOT NULL,\n definition jsonb NOT NULL,\n -- The bindings, beside the artifact and never inside it: which host\n -- action this one rides (a panel), or which menu hub lists it. Empty\n -- means neither — reachable only through whatever else names it.\n -- preview is the rider's display endpoint (own-prefix, validated at\n -- intake): the host calls it with the offered ids to paint the strip.\n attach_to text NOT NULL DEFAULT '',\n preview text NOT NULL DEFAULT '',\n place_in text NOT NULL DEFAULT '',\n PRIMARY KEY (integration_id, action_id)\n)\n` },\n ...GENERATION_DDL.map((sql) => ({ kind: 'sql' as const, sql })),\n ],\n },\n {\n description: 'Stored integration actions carry the grammar stamp their definition is written in',\n steps: [{ kind: 'sql', sql: `ALTER TABLE integration_actions ADD COLUMN grammar jsonb NOT NULL DEFAULT '{}'::jsonb` }],\n },\n ],\n};\n\n// The rows that hold documents: every integration action's definition is a\n// nova action, stamped with the grammars it was written in (`{}` — a row from\n// before stamps — reads as the start of every grammar). Brought current at boot\n// by strata's upgradeStore; see grammar.ts.\nexport const INTEGRATION_ACTIONS_STORE: DocumentStore = {\n table: 'integration_actions',\n column: 'definition',\n stamp: 'grammar',\n kind: 'nisc.nova/action',\n key: ['integration_id', 'action_id'],\n};\n\n// Through the ledger, for a host that is not moss's server (which runs every\n// owner's sequence in one pass).\nexport const initIntegrations = async (pool: PgPool): Promise<void> => {\n await migrate(pool, [MOSS_SEQUENCE]);\n};\n\n// ── the bindings, read back for the host's derivations ───────\n//\n// Approved only, like everything else served from these tables. The app's own\n// functions consume these: a hub asks which placed screens it lists, a host\n// action asks which panels ride it. The app never parses a bundle.\n\nexport const listAttachments = async (pool: PgPool, hostAction: string): Promise<{ actionId: string; preview: string }[]> => {\n const res = await pool.query(\n `SELECT a.action_id, a.preview FROM integration_actions a JOIN integrations i ON i.id = a.integration_id\n WHERE i.status = 'approved' AND a.attach_to = $1 ORDER BY a.action_id`,\n [hostAction],\n );\n return res.rows.map((r) => {\n const row = r as { action_id: string; preview: string };\n return { actionId: String(row.action_id), preview: String(row.preview ?? '') };\n });\n};\n\nexport const listPlacements = async (pool: PgPool): Promise<Record<string, string>> => {\n const res = await pool.query(\n `SELECT a.action_id, a.place_in FROM integration_actions a JOIN integrations i ON i.id = a.integration_id\n WHERE i.status = 'approved' AND a.place_in <> ''`,\n );\n const out: Record<string, string> = {};\n for (const r of res.rows) {\n const row = r as { action_id: string; place_in: string };\n out[String(row.action_id)] = String(row.place_in);\n }\n return out;\n};\n\n// A presented key, resolved to the integration it names — or nothing.\n//\n// Approved only: a pending integration holds a key (minted at registration so\n// the operator ceremony is one step) but the key opens nothing until somebody\n// has said yes, and a revoked or deleted row stops answering here, which is\n// what makes removal kill the credential in the same act.\nexport const integrationByKey = async (pool: PgPool, key: string): Promise<string | undefined> => {\n const res = await pool.query(\"SELECT id FROM integrations WHERE key_hash = $1 AND status = 'approved'\", [hashIntegrationKey(key)]);\n const id = (res.rows[0] as { id?: string } | undefined)?.id;\n return id === undefined ? undefined : String(id);\n};\n\nexport const listIntegrations = async (pool: PgPool): Promise<IntegrationRow[]> => {\n const res = await pool.query(`\n SELECT i.id, i.url, i.status, i.title, i.tagline, i.adds, i.settings_action,\n i.requested_actions, i.requested_data, i.approved_data,\n i.offers, i.needs, i.capabilities, i.configuration, i.documents, i.assistants,\n i.last_import_at, i.last_error,\n (SELECT count(*) FROM integration_actions a WHERE a.integration_id = i.id) AS action_count\n FROM integrations i ORDER BY i.id\n `);\n return res.rows.map((r: unknown) => {\n const row = r as Record<string, unknown>;\n // A TIMESTAMP IS NOT ALWAYS A DATE. Different drivers hand back a Date, an\n // ISO string, or a number for the same column — PGlite returns a string\n // here, so the Date-only branch this had made every row read 'never', on a\n // field whose entire job is saying when it last worked.\n const at = row['last_import_at'];\n return {\n id: String(row['id']),\n url: String(row['url']),\n status: String(row['status']) as IntegrationRow['status'],\n title: String(row['title'] ?? ''),\n tagline: String(row['tagline'] ?? ''),\n adds: String(row['adds'] ?? ''),\n settingsAction: String(row['settings_action'] ?? ''),\n requestedActions: (row['requested_actions'] ?? []) as string[],\n requestedData: (row['requested_data'] ?? []) as string[],\n approvedData: (row['approved_data'] ?? []) as string[],\n offers: (row['offers'] ?? []) as string[],\n needs: (row['needs'] ?? []) as string[],\n capabilities: (row['capabilities'] ?? []) as { id: string; title: string }[],\n configuration: (row['configuration'] ?? []) as ConfigurationField[],\n documents: (row['documents'] ?? []) as DocumentDeclaration[],\n assistants: (row['assistants'] ?? []) as AssistantDeclaration[],\n lastImportAt: at instanceof Date ? at.getTime() : typeof at === 'string' || typeof at === 'number' ? new Date(at).getTime() : null,\n lastError: (row['last_error'] as string | null) ?? null,\n actionCount: Number(row['action_count'] ?? 0),\n };\n });\n};\n\n// Every approved integration's actions, as the manifest wants them.\n// With an upgrader, each definition is read in the host's grammar: boot brings\n// the table current (upgradeStore), but a row another process wrote since — one\n// running older code — is upgraded here. A row written by NEWER code is not\n// served: the action is left out with a sentence, never rendered half-read.\nexport const loadIntegrationActions = async (pool: PgPool, upgrader?: Upgrader): Promise<Record<string, ActionDefinition>> => {\n const res = await pool.query(\n `SELECT a.action_id, a.definition, a.grammar FROM integration_actions a\n JOIN integrations i ON i.id = a.integration_id\n WHERE i.status = 'approved'`,\n );\n const out: Record<string, ActionDefinition> = {};\n for (const r of res.rows) {\n const row = r as Record<string, unknown>;\n const id = String(row['action_id']);\n if (upgrader === undefined) {\n out[id] = row['definition'] as ActionDefinition;\n continue;\n }\n const stamp = isPlainRecord(row['grammar']) ? Object.fromEntries(Object.entries(row['grammar']).map(([k, v]) => [k, Number(v)])) : {};\n try {\n out[id] = upgrader.upgrade(row['definition'], { kind: 'nisc.nova/action', stamp }).document as ActionDefinition;\n } catch (error) {\n if (!(error instanceof StrataError)) throw error;\n console.error(`[moss] integration action \"${id}\" is not served: ${error.message.split('\\n')[0] ?? error.code}`);\n }\n }\n return out;\n};\n\n// ── which integration an action belongs to ───────────────────\n//\n// `ext.<audience>.<integration>.<name>` → the integration. Derived, never\n// stored twice.\nexport const integrationOfAction = (id: string): string | undefined =>\n id.startsWith('ext.') ? id.split('.')[2] : undefined;\n\n// INSTALLATION IS PER TENANT, and this is where that lands.\n//\n// The charter grants `ext.desk.*` once, to every desk in the deployment — so\n// without this, one studio installing an integration puts it on every studio's front\n// desk. Moss cannot filter that itself: it does not know what a studio is, on\n// purpose. The app answers, and the answer is a list of ids.\nexport const filterInstalled = (ids: readonly string[], installed: ReadonlySet<string> | undefined): readonly string[] => {\n if (installed === undefined) return ids;\n return ids.filter((id) => {\n const owner = integrationOfAction(id);\n return owner === undefined || installed.has(owner);\n });\n};\n\n// ── the contract an integration is built against ─────────────\n//\n// With no shared code, an author cannot import a fingerprint constant or a\n// component name. This is what replaces those imports: the same information,\n// over the wire, in the two formats somebody might want it in.\nexport type Contract = {\n // Each component the author may compose, with its description and — where the\n // app carried one — its props as a draft-7 JSON Schema derived from the same\n // Zod schema the renderer validates against. A component the app registered\n // with no meta appears as its name alone, exactly as the whole list used to.\n components: readonly LayoutPaletteEntry[];\n audiences: readonly string[];\n namespace: string;\n actionSchema: string;\n // The placement vocabulary: which host actions offer a seat (and what they\n // hand a rider), and which menu hubs accept placed screens.\n attachable: Record<string, readonly string[]>;\n menuSlots: readonly string[];\n};\n\nexport const buildContract = (app: NiscApp, integrationId: string): Contract => {\n // Name + description + props schema per component, from the same converter the\n // layout agent's palette uses — the contract is that palette asked for a\n // person instead of an agent. Unfiltered on purpose: what intake will enforce\n // (the sibling props check) is the whole schema, so the docs must show the\n // whole schema, or an author reads one contract and is judged against another.\n const registered = app.shell?.components ?? {};\n const components = Object.keys(registered)\n .sort()\n .map((name) => paletteEntryOf(name, (registered[name]?.meta ?? {}) as ComponentMeta));\n // Every audience the charter has drawn an `ext.` fence for. An integration\n // may claim a namespace under these and nowhere else.\n const audiences = new Set<string>();\n for (const def of Object.values(app.charter)) {\n if (def === undefined || Array.isArray(def)) continue;\n const selection = def.actions;\n const list = Array.isArray(selection) ? selection : ((selection as { allow?: string[] } | undefined)?.allow ?? []);\n for (const entry of list) {\n const parts = String(entry).split('.');\n if (parts[0] === 'ext' && parts[1] !== undefined && parts[1] !== '*') audiences.add(parts[1]);\n }\n }\n // Only the offered KEYS are advertised — the host's data paths are its\n // private wiring, not part of any contract an author builds against.\n const attachable: Record<string, readonly string[]> = {};\n for (const [action, offers] of Object.entries(app.attachable ?? {})) attachable[action] = Object.keys(offers);\n return {\n components,\n audiences: [...audiences].sort(),\n namespace: `ext.<audience>.${integrationId}.<name>`,\n actionSchema: 'nova ActionDefinition',\n attachable,\n menuSlots: [...(app.menuSlots ?? [])],\n };\n};\n\n// One prop's TYPE column, from its JSON Schema node. The closed sets are the\n// point — an enum (`emphasis` is one of four) and a union of literals surface as\n// `enum` / `anyOf` of consts, neither of which is a bare `type`, so an author\n// told only \"string\" learns nothing about which strings. A numeric range (a kit\n// whose gaps are steps 0–6) rides along.\nconst describeProp = (schema: Record<string, unknown>): string => {\n const enumValues = schema['enum'];\n if (Array.isArray(enumValues)) return `one of: ${enumValues.map((v) => String(v)).join(', ')}`;\n const anyOf = schema['anyOf'];\n if (Array.isArray(anyOf)) {\n const consts = anyOf.map((s) => (s as Record<string, unknown>)['const']).filter((v) => v !== undefined);\n if (consts.length === anyOf.length && consts.length > 0) return `one of: ${consts.map((v) => String(v)).join(', ')}`;\n }\n const type = schema['type'];\n const base = typeof type === 'string' ? type : Array.isArray(type) ? type.map((t) => String(t)).join(' | ') : 'value';\n const min = schema['minimum'];\n const max = schema['maximum'];\n if (typeof min === 'number' || typeof max === 'number') return `${base} (${typeof min === 'number' ? min : '…'}–${typeof max === 'number' ? max : '…'})`;\n return base;\n};\n\n// One component: its name, its description, and — where it carried a schema — a\n// small table of props (name · type · required · meaning). A component with no\n// props renders as its name alone, which is what the whole list used to be.\nconst componentAsMarkdown = (component: LayoutPaletteEntry): string => {\n const head = component.description !== '' ? `**${component.name}** — ${component.description}` : `**${component.name}**`;\n const schema = component.propsSchema as { properties?: Record<string, Record<string, unknown>>; required?: readonly string[] } | undefined;\n const properties = schema?.properties;\n if (properties === undefined || Object.keys(properties).length === 0) return head;\n const required = new Set(schema?.required ?? []);\n const rows = Object.entries(properties).map(\n ([prop, spec]) => `| ${prop} | ${describeProp(spec)} | ${required.has(prop) ? 'yes' : 'no'} | ${String(spec['description'] ?? '')} |`,\n );\n return [head, ``, `| prop | type | required | meaning |`, `| --- | --- | --- | --- |`, ...rows].join('\\n');\n};\n\nexport const contractAsMarkdown = (contract: Contract, fingerprints: readonly string[]): string =>\n [\n `# What you can build against`,\n ``,\n `## Your namespace`,\n ``,\n ` ${contract.namespace}`,\n ``,\n `Every action you ship must be named this way. Audiences available: ${contract.audiences.join(', ') || '(none)'}.`,\n ``,\n `## Components your layouts may use`,\n ``,\n contract.components.map(componentAsMarkdown).join('\\n\\n') || '(none)',\n ``,\n `## Fingerprints you may call`,\n ``,\n `Endpoints may target \\`/api/<resource>/vex\\` with one of these, or any URL under`,\n `\\`/integrations/<your id>/\\`. Nothing else.`,\n ``,\n fingerprints.map((f) => `- ${f}`).join('\\n') || '(none — your grants reach nothing yet)',\n ``,\n `## Where your screens may appear`,\n ``,\n `Declare \\`attachments\\` (action → host action) to ride a host screen, and`,\n `\\`placements\\` (action → hub) to list under a menu hub. \\`settings\\` names the one`,\n `action the store tile opens. Anything else is refused.`,\n ``,\n `Attachable, with what each hands you as input:`,\n ``,\n Object.entries(contract.attachable)\n .map(([action, offers]) => `- ${action} — offers ${offers.join(', ') || '(nothing)'}`)\n .join('\\n') || '(none)',\n ``,\n `Menu hubs accepting placements:`,\n ``,\n contract.menuSlots.map((hub) => `- ${hub}`).join('\\n') || '(none)',\n ``,\n `## What you cannot ship`,\n ``,\n `- vex entries or mutations. Call what is listed above; if you need a read that`,\n ` does not exist, it is a change to the app.`,\n `- \\`fn:\\` endpoints. Those run in the app's process.`,\n `- components. Layouts compose what is listed above.`,\n `- tables. Bring your own storage; we hand you identifiers.`,\n ``,\n ].join('\\n');\n","import { createPostgresAdapter, createPostgresCache, mutationMisfits, pruneOptional, resolve } from '@niscorp/vex';\nimport type { CacheBackend, DatabaseSchema, PgPool, SeedEntry, SeedMutation } from '@niscorp/vex';\nimport { migrate } from '@niscorp/strata/postgres';\nimport type { MigrateReport } from '@niscorp/strata/postgres';\nimport type { Sequence } from '@niscorp/strata';\nimport type { NiscApp } from './app';\nimport type { NiscRuntime } from './runtime';\nimport { MOSS_SEQUENCE } from './integrations';\nimport { SESSIONS_SEQUENCE } from './sessions';\n\n// ═══════════════════════════════════════════════════════════════\n// THE STEP THAT CHANGES TABLES — one strata run over every owner's sequence,\n// and a question asked of what it leaves before it may commit: does the code\n// being deployed still fit?\n//\n// What an app reads and writes is data (its entries), and the schema is there\n// to be read, so the question has an answer. A read is resolved against the\n// schema as the transaction sees it; a write is put to the gate vex puts it\n// to before it runs. An entry that does not fit refuses the run, and nothing\n// was applied — so the migration is corrected where it is written, because\n// it never ran.\n//\n// ONE EXCEPTION, or the check would hold a deploy hostage to an old bug: an\n// entry that already did not fit BEFORE this run, and that the database\n// already holds seeded exactly as it is now, is not this run's doing. It is\n// said, not refused. A new or changed entry gets no such pass — \"the code\n// needs something no migration provides\" is the mistake this exists to catch.\n//\n// What it cannot see: SQL written by hand, columns a scope rule stamps, what\n// a value means. A run that passes says the entries fit, and nothing more.\n// ═══════════════════════════════════════════════════════════════\n\ntype Entry = SeedEntry | SeedMutation;\n\n// Every table sequence a boot runs, in the order it runs them: moss's own, the\n// sessions table when the deployment chose moss's credential, the vex cache's,\n// then the app's own (`runtime.tables`).\nexport const tableSequencesOf = (runtime: NiscRuntime): readonly Sequence[] => {\n const cacheSequence = (runtime.cache ?? createPostgresCache({ pool: runtime.pool })).sequence;\n return [\n MOSS_SEQUENCE,\n ...(runtime.session === 'sessions' ? [SESSIONS_SEQUENCE] : []),\n ...(cacheSequence === undefined ? [] : [cacheSequence]),\n ...(runtime.tables ?? []),\n ];\n};\n\n// Why an entry does not fit a schema — undefined when it does.\nconst misfitOf = (entry: Entry, schema: DatabaseSchema): string | undefined => {\n if (!('mutation' in entry)) {\n try {\n // every optional condition kept, as the engine itself compiles an entry\n resolve(pruneOptional(entry.dsl, 'all'), schema);\n return undefined;\n } catch (error) {\n return error instanceof Error ? error.message : String(error);\n }\n }\n // the gate every write goes through before it runs, asked without running\n return mutationMisfits(entry.mutation, schema)[0];\n};\n\nconst misfitsOf = (entries: readonly Entry[], schema: DatabaseSchema): Map<string, string> => {\n const misfits = new Map<string, string>();\n for (const entry of entries) {\n const why = misfitOf(entry, schema);\n if (why !== undefined) misfits.set(entry.fingerprint, why);\n }\n return misfits;\n};\n\n// A stored definition has been through jsonb, which reorders keys: equality is\n// by value, keys sorted.\nconst canonical = (value: unknown): string => {\n if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;\n if (value === null || typeof value !== 'object') return JSON.stringify(value);\n const keys = Object.keys(value).filter((key) => Reflect.get(value, key) !== undefined).sort();\n return `{${keys.map((key) => `${JSON.stringify(key)}:${canonical(Reflect.get(value, key))}`).join(',')}}`;\n};\n\n// Does the database already hold this entry, seeded, exactly as the code has it?\nconst isSeededAs = async (cache: CacheBackend, entry: Entry): Promise<boolean> => {\n const held = await cache.get(entry.fingerprint);\n if (held === undefined || held.protected !== true) return false;\n if ('mutation' in entry) return held.kind === 'mutation' && canonical(held.mutation) === canonical(entry.mutation);\n return held.kind === 'ok' && canonical(held.dsl) === canonical(entry.dsl);\n};\n\n// What a run takes away: tables and columns that were there and are not, and\n// columns whose type is no longer what it was.\nconst changesBetween = (before: DatabaseSchema, after: DatabaseSchema): { removed: string[]; retyped: string[] } => {\n const removed: string[] = [];\n const retyped: string[] = [];\n for (const was of before.entities) {\n const now = after.entities.find((entity) => entity.table === was.table);\n if (now === undefined) {\n removed.push(was.table);\n continue;\n }\n for (const field of was.fields) {\n const kept = now.fields.find((f) => f.name === field.name);\n if (kept === undefined) removed.push(`${was.table}.${field.name}`);\n else if (kept.type !== field.type) retyped.push(`${was.table}.${field.name} (${field.type} → ${kept.type})`);\n }\n }\n return { removed, retyped };\n};\n\n// vex's introspection sends its queries at once; a transaction is ONE\n// connection, and a driver that is asked a second question while it is\n// answering the first either queues it or refuses. So they go one at a time.\nconst oneAtATime = (query: PgPool['query']): PgPool['query'] => {\n let last: Promise<unknown> = Promise.resolve();\n return (text, values) => {\n const next = last.then(() => query(text, values));\n last = next.catch(() => undefined);\n return next;\n };\n};\n\nexport type TablesReport = MigrateReport & {\n // Tables and columns the run removes.\n removed: readonly string[];\n // Columns whose type the run changes, as \"table.column (was → now)\".\n retyped: readonly string[];\n // Entries that did not fit before this run and still do not, already seeded\n // as they are — each as \"fingerprint: why\". Said, never refused.\n alreadyBroken: readonly string[];\n};\n\n// Apply every pending table migration — or, with `dryRun`, do all of it and roll\n// it back. Refuses (strata's DOES_NOT_FIT, naming each entry and why) when an\n// entry of `app` would not fit what the run leaves.\nexport const migrateTables = async (runtime: NiscRuntime, app: NiscApp, options: { dryRun?: boolean } = {}): Promise<TablesReport> => {\n const entries = app.entries ?? [];\n const cache = runtime.cache ?? createPostgresCache({ pool: runtime.pool });\n\n // As the database stands now — read before the run, on the pool: a single-\n // connection database (PGlite) cannot answer the pool while a transaction is\n // open.\n const before = await createPostgresAdapter({ pool: runtime.pool }).introspect();\n const misfitsBefore = misfitsOf(entries, before);\n const excused = new Set<string>();\n for (const entry of entries) {\n // a database never started on has no cache table to ask: nothing is seeded\n if (misfitsBefore.has(entry.fingerprint) && (await isSeededAs(cache, entry).catch(() => false))) excused.add(entry.fingerprint);\n }\n\n let found: Pick<TablesReport, 'removed' | 'retyped' | 'alreadyBroken'> = { removed: [], retyped: [], alreadyBroken: [] };\n const report = await migrate(runtime.pool, tableSequencesOf(runtime), {\n ...(options.dryRun === true ? { dryRun: true } : {}),\n guard: async (tx) => {\n const after = await createPostgresAdapter({ pool: { query: oneAtATime((text, values) => tx.query(text, values)) } }).introspect();\n const refused: string[] = [];\n const alreadyBroken: string[] = [];\n for (const [fingerprint, why] of misfitsOf(entries, after)) {\n if (excused.has(fingerprint)) alreadyBroken.push(`${fingerprint}: ${why}`);\n else refused.push(`${fingerprint}: ${why}`);\n }\n found = { ...changesBetween(before, after), alreadyBroken };\n return refused;\n },\n });\n // A run that applied nothing took nothing away: what differs from `before`\n // then landed from another run, while this one waited for the lock.\n return { ...report, ...found, ...(report.applied.length === 0 ? { removed: [], retyped: [] } : {}) };\n};\n","import type { Sequence } from '@niscorp/strata';\nimport { migrate as migrateLedger } from '@niscorp/strata/postgres';\nimport { PRIMARY_KEY, UNIQUE_BY } from '@niscorp/tide';\nimport type { ClaimSpec, Comparison, Mutation, Order, QuerySpec, RemoveSpec, TableName, Tide, TideStore, TideTables, Where } from '@niscorp/tide';\nimport type { PgPool, WriteEvent } from '@niscorp/vex';\n\n// ═══════════════════════════════════════════════════════════════\n// TIDE, MADE DURABLE — and it lives HERE, not in tide.\n//\n// Tide has no dependencies and that is deliberate: it must not be\n// able to import a host. Storage was the one seam moss did not\n// fill, so a tide under moss kept its ledger in memory and lost a\n// half-finished run to every deploy.\n//\n// The engine's own writes go through the POOL, not through vex's\n// mutation pipeline, and the reason is worth stating because the\n// opposite looks tidier. A vex mutation is an AUTHORED, scope-\n// compiled statement replayed on behalf of a principal — the right\n// shape for an application write, and the wrong shape for an\n// engine claiming its own task: there is no principal, no tenant\n// to scope to, and no user input to police. Routing bookkeeping\n// through a policy compiler would add a scope rule that permits\n// everything, which is a way of saying the rule is not doing\n// anything.\n//\n// The LEDGER READS are the other half and they DO go through vex —\n// in the app, as ordinary entries over these tables, scoped on\n// `as`. That is why a run carries the identity it ran under.\n// ═══════════════════════════════════════════════════════════════\n\n// One table per guarantee. `tide_run` and `tide_work` are the two that grow\n// with events; `tide_fact` is the intake, swept on its own horizon; and\n// `tide_reflex_state` holds one row per reflex, forever.\n//\n// The CHECK constraints are not decoration. The last hand-written store read\n// state back through a blind cast, so a run whose state was `'sttled'` was\n// constructible — and its work was never claimed and it hung there.\nexport const TIDE_TABLES = ['tide_fact', 'tide_run', 'tide_work', 'tide_reflex_state'] as const;\n\n// HISTORY. This text is migration 1 of `nisc.moss.tide` (TIDE_SEQUENCE below),\n// and databases have run it: editing it makes every one of them refuse to boot\n// (strata: EDITED). Change the tables by appending a migration to the sequence;\n// test/baselines.test.ts pins this one's checksum so the edit is caught here.\nexport const TIDE_DDL = `\nCREATE TABLE IF NOT EXISTS tide_fact (\n id text PRIMARY KEY,\n kind text NOT NULL CHECK (kind IN ('write','signal','manual','run')),\n entity text,\n op text CHECK (op IN ('insert','update','delete')),\n row jsonb,\n name text,\n payload jsonb,\n reflex text,\n run_id text,\n occurrence text,\n stats jsonb,\n target text,\n by text,\n at bigint NOT NULL,\n not_before bigint,\n dedupe_key text,\n cause text,\n depth integer NOT NULL DEFAULT 0,\n delivered_at bigint,\n parked text,\n released boolean,\n -- WHOSE FACT THIS IS. The identity of the reflex that minted it, absent on\n -- anything the host ingested. The matcher refuses to hand a fact minted\n -- under one identity to a reflex running under another, which is the only\n -- thing standing between a carried row and somebody else's effect — tide is\n -- the one place a row travels without being read, so no scope policy is\n -- consulted on the way.\n as_who text\n);\n\n-- A PARTIAL index, because a fact with no dedupeKey is not claiming to be\n-- unique: it is a distinct occurrence of something, not a repeat of it.\n-- entity is in the key: without it, two producers over different tables\n-- that agreed on a key value silently ate each other's rows.\nCREATE UNIQUE INDEX IF NOT EXISTS tide_fact_dedupe\n ON tide_fact (kind, coalesce(entity,''), coalesce(name,''), dedupe_key)\n WHERE dedupe_key IS NOT NULL;\n\n-- The matcher's query, every advance.\nCREATE INDEX IF NOT EXISTS tide_fact_due\n ON tide_fact (at) WHERE delivered_at IS NULL AND parked IS NULL;\nCREATE INDEX IF NOT EXISTS tide_fact_swept ON tide_fact (delivered_at);\n\nCREATE TABLE IF NOT EXISTS tide_run (\n id text PRIMARY KEY,\n reflex_id text NOT NULL,\n version text NOT NULL,\n as_who text,\n cause text NOT NULL,\n occurrence text,\n fact_ids jsonb,\n state text NOT NULL CHECK (state IN ('pending','fanned','settled','skipped')),\n depth integer NOT NULL DEFAULT 0,\n selected integer,\n total integer NOT NULL DEFAULT 0,\n done integer NOT NULL DEFAULT 0,\n failed integer NOT NULL DEFAULT 0,\n due_at bigint NOT NULL,\n created_at bigint NOT NULL,\n settled_at bigint,\n drained boolean,\n note text,\n -- THE IDEMPOTENCY. One constraint, every trigger kind: an occurrence\n -- cannot open twice, a replayed fact cannot open twice, and two instances\n -- ticking at the same moment contend instead of duplicating.\n UNIQUE (reflex_id, cause)\n);\n\nCREATE INDEX IF NOT EXISTS tide_run_pending ON tide_run (state, due_at);\nCREATE INDEX IF NOT EXISTS tide_run_ledger ON tide_run (reflex_id, created_at DESC);\nCREATE INDEX IF NOT EXISTS tide_run_swept ON tide_run (settled_at);\n\nCREATE TABLE IF NOT EXISTS tide_work (\n id text PRIMARY KEY,\n -- ON DELETE CASCADE, because a run and its work are one fact about the\n -- world. Sweeping runs and leaving work destroys the UNIQUE(run_id, unit)\n -- row that IS the \"this unit already ran\" record — and a restore then\n -- re-charges the invoice.\n run_id text NOT NULL REFERENCES tide_run(id) ON DELETE CASCADE,\n reflex_id text NOT NULL,\n unit text NOT NULL,\n cause text NOT NULL,\n env jsonb NOT NULL,\n depth integer NOT NULL DEFAULT 0,\n state text NOT NULL CHECK (state IN ('pending','claimed','retrying','done','failed')),\n attempt integer NOT NULL DEFAULT 0,\n token text,\n -- Zero, never null, when unclaimed: \"never claimed or lapsed\" is then one\n -- comparison rather than a disjunction.\n claimed_until bigint NOT NULL DEFAULT 0,\n not_before bigint NOT NULL,\n input jsonb,\n output jsonb,\n error text,\n created_at bigint NOT NULL,\n settled_at bigint,\n UNIQUE (run_id, unit)\n);\n\nCREATE INDEX IF NOT EXISTS tide_work_claimable ON tide_work (state, not_before, claimed_until);\nCREATE INDEX IF NOT EXISTS tide_work_run ON tide_work (run_id);\nCREATE INDEX IF NOT EXISTS tide_work_swept ON tide_work (settled_at);\n\nCREATE TABLE IF NOT EXISTS tide_reflex_state (\n reflex_id text PRIMARY KEY,\n armed_at bigint NOT NULL DEFAULT 0,\n materialized_through bigint\n);\n\n-- Polls are gone (the vex bridge pushes writes — a poll could only\n-- re-discover them late), and their cursor state goes with them. IF EXISTS,\n-- so a store created after the removal is not asked to drop what it never had.\nALTER TABLE tide_reflex_state DROP COLUMN IF EXISTS poll_cursor;\nALTER TABLE tide_reflex_state DROP COLUMN IF EXISTS poll_seen;\nALTER TABLE tide_reflex_state DROP COLUMN IF EXISTS polled_at;\n`;\n\n// ── the mapping ─────────────────────────────────────────────────\n//\n// One place, both directions. Hand-written per-table row builders are how\n// the last store ended up reading `started_at` off the wrong column in one\n// direction and not at all in the other.\n\nconst SQL_TABLE: Record<TableName, string> = {\n fact: 'tide_fact',\n run: 'tide_run',\n task: 'tide_work',\n state: 'tide_reflex_state',\n};\n\n// `as` and `row` are SQL keywords; everything else is the ordinary\n// camel → snake rule.\nconst COLUMN_OVERRIDES: Record<string, string> = { as: 'as_who' };\n\nconst snake = (field: string): string => COLUMN_OVERRIDES[field] ?? field.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);\n\nconst camel = (column: string): string => {\n for (const [field, mapped] of Object.entries(COLUMN_OVERRIDES)) if (mapped === column) return field;\n return column.replace(/_([a-z])/g, (_all, c: string) => c.toUpperCase());\n};\n\n// Which columns hold JSON. Anything else round-trips as a scalar.\nconst JSON_COLUMNS = new Set(['row', 'payload', 'stats', 'fact_ids', 'env', 'input', 'output']);\nconst BIGINT_COLUMNS = new Set([\n 'at',\n 'not_before',\n 'delivered_at',\n 'depth',\n 'descendants',\n 'due_at',\n 'created_at',\n 'settled_at',\n 'claimed_until',\n 'armed_at',\n 'materialized_through',\n 'attempt',\n 'selected',\n 'total',\n 'done',\n 'failed',\n]);\n\nconst toColumn = (column: string, value: unknown): unknown => {\n if (value === undefined) return null;\n if (JSON_COLUMNS.has(column)) return JSON.stringify(value);\n return value;\n};\n\nconst fromColumn = (column: string, value: unknown): unknown => {\n if (value === null) return undefined;\n if (JSON_COLUMNS.has(column)) return typeof value === 'string' ? JSON.parse(value) : value;\n // `bigint` comes back as a string on some drivers and a number on others.\n // Tide compares these with `<`, so the difference is not cosmetic.\n if (BIGINT_COLUMNS.has(column)) return Number(value);\n return value;\n};\n\nconst rowToEntity = <T extends TableName>(table: T, row: Record<string, unknown>): TideTables[T] => {\n const entity: Record<string, unknown> = {};\n for (const [column, value] of Object.entries(row)) {\n const mapped = fromColumn(column, value);\n if (mapped !== undefined) entity[camel(column)] = mapped;\n }\n return entity as TideTables[T];\n};\n\n// ── the WHERE compiler ──────────────────────────────────────────\n\nconst COMPARATORS: Record<string, string> = { eq: '=', ne: '<>', lt: '<', lte: '<=', gt: '>', gte: '>=' };\n\ntype Bind = { sql: string; params: unknown[] };\n\nconst compileWhere = (where: Where<Record<string, unknown>> | undefined, start: number, alias = ''): Bind => {\n const clauses: string[] = [];\n const params: unknown[] = [];\n const prefix = alias === '' ? '' : `${alias}.`;\n const slot = (value: unknown): string => {\n params.push(value);\n return `$${start + params.length - 1}`;\n };\n\n for (const [field, test] of Object.entries(where ?? {})) {\n const column = `${prefix}${snake(field)}`;\n const bare = snake(field);\n if (test === null || typeof test !== 'object' || Array.isArray(test)) {\n // An equality on `undefined` means IS NULL, which is what the engine\n // means when it filters on a column it just cleared.\n clauses.push(test === undefined ? `${column} IS NULL` : `${column} = ${slot(toColumn(bare, test))}`);\n continue;\n }\n\n const comparison = test as Comparison<unknown>;\n for (const [op, symbol] of Object.entries(COMPARATORS)) {\n const operand = comparison[op as keyof Comparison<unknown>];\n if (operand === undefined) continue;\n // `ne` must be true for a NULL column: a run that has never been\n // drained is not drained, and plain SQL `<>` answers NULL there.\n clauses.push(op === 'ne' ? `(${column} IS NULL OR ${column} <> ${slot(toColumn(bare, operand))})` : `${column} ${symbol} ${slot(toColumn(bare, operand))}`);\n }\n if (comparison.in !== undefined) clauses.push(`${column} = ANY(${slot(comparison.in.map((value) => toColumn(bare, value)))})`);\n if (comparison.notIn !== undefined) clauses.push(`NOT (${column} = ANY(${slot(comparison.notIn.map((value) => toColumn(bare, value)))}))`);\n if (comparison.isNull !== undefined) clauses.push(comparison.isNull ? `${column} IS NULL` : `${column} IS NOT NULL`);\n }\n\n return { sql: clauses.length === 0 ? 'TRUE' : clauses.join(' AND '), params };\n};\n\nconst compileOrder = (order: Order<Record<string, unknown>> | undefined, alias = ''): string => {\n if (order === undefined || order.length === 0) return '';\n const prefix = alias === '' ? '' : `${alias}.`;\n return ` ORDER BY ${order.map((key) => `${prefix}${snake(String(key.by))} ${key.dir === 'desc' ? 'DESC' : 'ASC'}`).join(', ')}`;\n};\n\n// The same comparison SQL made, applied to what came back. Kept beside the\n// compiler so the two cannot drift.\nconst sortRows = <R>(rows: readonly R[], order: Order<Record<string, unknown>> | undefined): R[] => {\n if (order === undefined || order.length === 0) return [...rows];\n return [...rows].sort((left, right) => {\n for (const key of order) {\n const a = (left as Record<string, unknown>)[String(key.by)];\n const b = (right as Record<string, unknown>)[String(key.by)];\n const compared = typeof a === 'number' && typeof b === 'number' ? a - b : String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0;\n if (compared !== 0) return compared * (key.dir === 'desc' ? -1 : 1);\n }\n return 0;\n });\n};\n\nconst compileSet = (set: Mutation<Record<string, unknown>>, start: number): Bind => {\n const assignments: string[] = [];\n const params: unknown[] = [];\n for (const [field, value] of Object.entries(set)) {\n const column = snake(field);\n if (value !== null && typeof value === 'object' && 'inc' in value) {\n // Column arithmetic, so two settling tasks cannot lose an increment\n // between a read and a write.\n assignments.push(`${column} = coalesce(${column}, 0) + ${Number((value as { inc: number }).inc)}`);\n continue;\n }\n params.push(toColumn(column, value));\n assignments.push(`${column} = $${start + params.length - 1}`);\n }\n return { sql: assignments.join(', '), params };\n};\n\n// ── the store ───────────────────────────────────────────────────\n\n// A counter, in the closure that owns it rather than at module scope. Same\n// value, same monotonicity; what changes is that it is no longer process-global\n// state a second store would silently share.\nconst mintId = ((): ((table: TableName) => string) => {\n let sequence = 0;\n return (table) => {\n sequence += 1;\n return `${table}_${Date.now().toString(36)}_${sequence.toString(36)}`;\n };\n})();\n\n// One statement per step — a prepared statement carries exactly one command\n// (PGlite says so outright; `pg` under parameters too). The comments ride\n// along: strata hashes a step without its full-line comments, so rewording\n// one is not an edit.\nconst statementsOf = (ddl: string): { kind: 'sql'; sql: string }[] =>\n ddl\n .split(';')\n .map((chunk) => chunk.trim())\n .filter((chunk) => chunk.split('\\n').some((line) => line.trim() !== '' && !line.trim().startsWith('--')))\n .map((sql) => ({ kind: 'sql', sql }));\n\nexport const TIDE_SEQUENCE: Sequence = {\n id: 'nisc.moss.tide',\n migrations: [\n { description: 'The tide store: facts, runs, work and reflex state, converged from any earlier shape', steps: statementsOf(TIDE_DDL) },\n {\n // A fact's chain: the root it belongs to, and — on a root — how many facts\n // the chain has minted beneath it. Nullable: every existing fact is a\n // root nothing has been counted against yet.\n description: 'A fact carries its chain root, and a root counts what its chain minted (tide maxChainFacts)',\n steps: [\n { kind: 'sql', sql: 'ALTER TABLE tide_fact ADD COLUMN IF NOT EXISTS root text' },\n { kind: 'sql', sql: 'ALTER TABLE tide_fact ADD COLUMN IF NOT EXISTS descendants integer' },\n ],\n },\n ],\n};\n\nexport type TideStoreOptions = {\n // Run the DDL on construction. On by default because a store that cannot\n // create its own tables makes the host responsible for a schema it does\n // not author.\n migrate?: boolean;\n};\n\nexport const createTideStore = (pool: PgPool, options: TideStoreOptions = {}): TideStore & { ready: Promise<void> } => {\n // EVERY method awaits this. The last store had three transactional methods\n // that did not, so on a real pool they raced the DDL and threw\n // `42P01 undefined_table` INSIDE a transaction — which the fan-out then\n // turned into a permanently skipped run.\n // THROUGH THE LEDGER (strata): the sequence runs once, in one transaction,\n // and is recorded — a boot that has already run finds nothing pending. Its\n // one migration is the DDL every boot used to run, IF NOT EXISTS throughout,\n // so a store created before the ledger existed converges instead of failing.\n const ready: Promise<void> = options.migrate === false ? Promise.resolve() : migrateLedger(pool, [TIDE_SEQUENCE]).then(() => undefined);\n // An unhandled rejection here is process-fatal on Node ≥ 15, and the\n // failure it reports would be a database that is not up yet.\n ready.catch(() => undefined);\n\n const build = (client: PgPool): TideStore => {\n const store: TideStore = {\n query: async <T extends TableName>(spec: QuerySpec<T>) => {\n await ready;\n const where = compileWhere(spec.where as Where<Record<string, unknown>>, 1);\n const limit = spec.limit === undefined ? '' : ` LIMIT ${Math.max(0, Math.floor(spec.limit))}`;\n const result = await client.query(\n `SELECT * FROM ${SQL_TABLE[spec.table]} WHERE ${where.sql}${compileOrder(spec.order as Order<Record<string, unknown>>)}${limit}`,\n where.params,\n );\n return result.rows.map((row) => rowToEntity(spec.table, row));\n },\n\n // ON CONFLICT DO NOTHING, which is the whole point: the refusal is the\n // DATABASE's, decided under the constraint, not a read the caller races.\n appendIfAbsent: async <T extends TableName>(table: T, input: Omit<TideTables[T], 'id'> & { id?: string }) => {\n await ready;\n const withId = PRIMARY_KEY[table] === 'id' ? { ...(input as Record<string, unknown>), id: input.id ?? mintId(table) } : { ...(input as Record<string, unknown>) };\n const entries = Object.entries(withId).filter(([, value]) => value !== undefined);\n const columns = entries.map(([field]) => snake(field));\n const params = entries.map(([field, value]) => toColumn(snake(field), value));\n\n // The conflict target is the table's declared unique key — the same\n // constant the memory store reads, so the two cannot drift.\n const unique = UNIQUE_BY[table];\n const target =\n unique.when === undefined\n ? `(${unique.by.map((column) => snake(String(column))).join(', ')})`\n : `(${unique.by.map((column) => (column === 'entity' || column === 'name' ? `coalesce(${snake(String(column))},'')` : snake(String(column)))).join(', ')}) WHERE ${snake(String(unique.when))} IS NOT NULL`;\n\n const result = await client.query(\n `INSERT INTO ${SQL_TABLE[table]} (${columns.join(', ')}) VALUES (${params.map((_value, index) => `$${index + 1}`).join(', ')})\n ON CONFLICT ${target} DO NOTHING RETURNING *`,\n params,\n );\n const row = result.rows[0];\n return row === undefined ? undefined : rowToEntity(table, row);\n },\n\n // Selection and mutation in ONE statement. `FOR UPDATE SKIP LOCKED`\n // makes N instances ticking at once ordinary contention rather than a\n // lock service — it is a throughput choice; the exactly-once promise is\n // the single statement.\n claim: async <T extends TableName>(spec: ClaimSpec<T>) => {\n await ready;\n const table = SQL_TABLE[spec.table];\n const order = compileOrder(spec.order as Order<Record<string, unknown>>, 'c');\n\n // Selection and mutation in ONE statement, which is the promise.\n // `FOR UPDATE SKIP LOCKED` makes N instances ticking at once ordinary\n // contention rather than a lock service — a throughput choice; the\n // exactly-once part is that it is one statement.\n const take = async (extra: Where<Record<string, unknown>>, limit: number) => {\n if (limit <= 0) return [];\n const where = compileWhere({ ...(spec.where as Where<Record<string, unknown>>), ...extra }, 1, 'c');\n const set = compileSet(spec.set as Mutation<Record<string, unknown>>, where.params.length + 1);\n const result = await client.query(\n `UPDATE ${table} SET ${set.sql}\n WHERE ctid IN (\n SELECT c.ctid FROM ${table} c WHERE ${where.sql}${order}\n LIMIT ${Math.floor(limit)} FOR UPDATE SKIP LOCKED\n )\n RETURNING *`,\n [...where.params, ...set.params],\n );\n // RE-SORTED, and this is not belt-and-braces. `ORDER BY` inside the\n // subquery decides WHICH rows are taken; it says nothing about the\n // order `RETURNING` hands them back, which is the order the UPDATE\n // happened to scan in. The engine executes tasks in the order a claim\n // returns them, so without this a fan-out ran in heap order here and\n // insertion order in memory — two stores, two answers, and a headless\n // check that cannot assert on either.\n return sortRows(result.rows.map((row) => rowToEntity(spec.table, row)), spec.order as Order<Record<string, unknown>> | undefined);\n };\n\n if (spec.onePer === undefined) return take({}, spec.limit);\n\n // `order: 'serial'` — at most one held row per group, counting what\n // an earlier claim already holds.\n //\n // A window function would say this in one statement, and Postgres\n // refuses to combine one with `FOR UPDATE`. So the restricted groups\n // are claimed one at a time — there are as many of those as there are\n // serial reflexes, which is a handful — and everything else is taken\n // in the single bulk statement above.\n const { column, held, only } = spec.onePer;\n const restricted = [...only];\n // Room is RESERVED for the serial groups before the bulk claim runs.\n // Taking the full limit first and topping up afterwards is how a busy\n // parallel reflex starves every serial one — the mirror of the defect\n // where a serial reflex with five thousand due tasks starved\n // everybody else because LIMIT was applied before the serial filter.\n const claimed = await take({ [String(column)]: { notIn: restricted } }, spec.limit - restricted.length);\n\n for (const group of restricted) {\n if (claimed.length >= spec.limit) break;\n const busy = compileWhere({ ...(held as Where<Record<string, unknown>>), [String(column)]: group }, 1, 'c');\n const taken = await client.query(`SELECT c.id FROM ${table} c WHERE ${busy.sql} LIMIT 1`, busy.params);\n if (taken.rows.length > 0) continue;\n claimed.push(...(await take({ [String(column)]: group }, 1)));\n }\n\n return claimed;\n },\n\n cas: async <T extends TableName>(table: T, id: string, expect: Where<TideTables[T]>, set: Mutation<TideTables[T]>) => {\n await ready;\n const key = snake(String(PRIMARY_KEY[table]));\n const where = compileWhere(expect as Where<Record<string, unknown>>, 2);\n const patch = compileSet(set as Mutation<Record<string, unknown>>, where.params.length + 2);\n const result = await client.query(\n `UPDATE ${SQL_TABLE[table]} SET ${patch.sql} WHERE ${key} = $1 AND ${where.sql} RETURNING ${key}`,\n [id, ...where.params, ...patch.params],\n );\n return result.rows.length > 0;\n },\n\n remove: async <T extends TableName>(spec: RemoveSpec<T>) => {\n await ready;\n const where = compileWhere(spec.where as Where<Record<string, unknown>>, 1);\n // Work goes with its run through the foreign key, not through a\n // second statement somebody can forget.\n const result = await client.query(`DELETE FROM ${SQL_TABLE[spec.table]} WHERE ${where.sql} RETURNING ${snake(String(PRIMARY_KEY[spec.table]))}`, where.params);\n return result.rows.length;\n },\n\n transact: async <T>(fn: (tx: TideStore) => Promise<T>): Promise<T> => {\n await ready;\n if (client.transaction === undefined)\n throw new Error('tide store: this pool cannot transact — fan-out and attempt recording are transactions, not conventions');\n // `query` is called ON the transaction, never taken off it: where the\n // pool hands a checked-out client through, it is a method that needs\n // its receiver, and taken off it failed inside the driver — which the\n // fan-out then recorded as a deferred run, and nothing ever ran.\n return client.transaction((tx) => fn(build({ ...client, query: (text, values) => tx.query(text, values) })));\n },\n };\n return store;\n };\n\n return { ...build(pool), ready };\n};\n\n// ═══════════════════════════════════════════════════════════════\n// The write-fact bridge — vex's write observer, minted into tide.\n//\n// One fact per (statement × returned row): a two-statement mutation\n// is two stimuli, and an UPDATE the scope narrowed to nothing is\n// none — zero rows mint zero facts, so \"a write landed\" is never\n// said about a write that changed nothing.\n//\n// `as` is the fact's identity fence. Tide offers a fact only to\n// reflexes running AS the same identity, and consults no scope\n// policy on the way (the row travels unread) — so the stamp here,\n// derived from the WRITE's own scope by the app's naming rule, is\n// what keeps one tenant's row out of another tenant's automation.\n// Stamping by anything else (a listener's interest, a default)\n// would walk data across that fence.\n// ═══════════════════════════════════════════════════════════════\n// `chain` is the causality thread: when the write came from a tide effect\n// (the handler forwarded its task and depth, the app's gate vouched for the\n// caller), the minted facts carry `cause: task:<id>` and `depth + 1` — the\n// same stamps an in-engine emit gets — so the chain ceiling holds across a\n// trip through the database instead of resetting at every hop.\nexport const mintWrites = async (\n intake: Pick<Tide, 'ingest'>,\n event: WriteEvent,\n as: string,\n at: number,\n chain?: { cause: string; depth: number },\n): Promise<void> => {\n for (const write of event.writes) {\n for (const row of write.rows) {\n await intake.ingest(\n { kind: 'write', entity: write.table, op: write.op, row, at },\n { as, ...(chain !== undefined ? { cause: chain.cause, depth: chain.depth + 1 } : {}) },\n );\n }\n }\n};\n","import { createScopePolicy, mergeScopePolicies } from '@niscorp/vex';\nimport type { ScopePolicy } from '@niscorp/vex';\nimport { resolvePrincipal, resolveScoping } from '@niscorp/charter';\nimport type { LayoutNode } from '@niscorp/nova';\nimport { filterInstalled } from './integrations';\nimport type { NiscApp } from './app';\n\n// ═══════════════════════════════════════════════════════════════\n// Per-principal resolution — what the catalog service does at login:\n// roles from the assignment rows, the granted action ids (with the\n// resolved-set version token), and the compiled vex ScopePolicy. All\n// pure; the server memoizes (the documents are static per process).\n// ═══════════════════════════════════════════════════════════════\n\nexport const resolveRoles = (app: NiscApp, principal: string | null): readonly string[] =>\n principal === null ? ['public'] : (app.assignments?.[principal] ?? ['public']);\n\n// The role combinations this application can produce — declared if the app says\n// so, derived from the assignment map if it does not. Deduplicated, because the\n// derived form yields one entry per PERSON and every consumer wants one entry\n// per COMBINATION: at Lyra's scale that is 600k entries collapsing to about a\n// dozen, and it is the same dozen either way.\nexport const wearableOf = (app: NiscApp): readonly (readonly string[])[] => {\n const declared = app.wearable;\n const source = declared ?? Object.values(app.assignments ?? {});\n const seen = new Map<string, readonly string[]>();\n for (const roles of source) {\n const key = [...roles].sort().join('\\0');\n if (!seen.has(key)) seen.set(key, roles);\n }\n return [...seen.values()];\n};\n\n// THE MEMO KEY every per-principal resolution below actually depends on.\n//\n// `resolvePolicy`, `resolveVariants` and `resolvePolicyAtReach` read the\n// principal ONLY to reach its roles; `resolveCatalog` reads its roles and its\n// installed integrations. Nothing reads the principal itself. Keying the memos\n// by principal therefore stored one entry per person for an answer that has as\n// many distinct values as there are (combination × install-set) pairs — about\n// ten in a real deployment, and unbounded in a map that is never evicted.\n// ONE SPELLING of the key, so the identity path and the older seams cannot\n// disagree about what counts as the same principal-shape.\n//\n// NUL separators, the same reason `policyAtReach` uses one: no id can contain\n// it, so `['a','b']` cannot spell itself the same way as `['a b']`.\n//\n// `undefined` is \"every registered integration is live\" and the empty list is\n// \"none are\" — different answers, and a key that conflated them would serve one\n// tenant's catalog to the other.\nexport const memoKey = (roles: readonly string[], installed: readonly string[] | undefined): string =>\n `${[...roles].sort().join('\\0')}\\0\\0${installed === undefined ? '*' : [...installed].sort().join('\\0')}`;\n\nexport const memoKeyOf = (app: NiscApp, principal: string | null): string => memoKey(resolveRoles(app, principal), undefined);\n\n// The compiled ScopePolicy this principal reads and writes under: their\n// resolved `data` grants × the app's row behaviors. An ungranted phase is\n// absent, and vex's default-deny refuses it.\nexport const resolvePolicy = (app: NiscApp, grants: readonly string[], principal: string | null): ScopePolicy => {\n // ONE POLICY PER ROLE, then merged — because a principal may hold several,\n // and reach belongs to the role rather than to the person.\n //\n // Compiling once for the principal assumed one role each. That holds until\n // somebody is two things at once: an instructor who also trains is staff on\n // the roster and a member in the class, and no single reach describes both —\n // studio-wide on the read they do as staff, their own rows on the write they\n // do as a member. Per role, each with its own scoping, and the union is what\n // they may do.\n return resolvePolicyForRoles(app, grants, resolveRoles(app, principal));\n};\n\n// THE SAME COMPILATION, given the roles directly — for a caller that has already\n// resolved who somebody is and should not have to ask a second time. The\n// principal was only ever a way to reach `roles`; taking it as the argument is\n// what lets identity resolve once per session instead of once per request.\nexport const resolvePolicyForRoles = (app: NiscApp, grants: readonly string[], roles: readonly string[]): ScopePolicy => {\n const behaviors = app.behaviors ?? {};\n return mergeScopePolicies(\n roles.map((role) =>\n createScopePolicy(resolvePrincipal(app.charter, grants, [role], 'data'), behaviors, resolveScoping(app.charter, role)),\n ),\n );\n};\n\n// THE SAME PRINCIPAL, COMPILED AT A REACH THE READ DEMANDS.\n//\n// The merge above is a union, so a principal holding two roles reaches as wide\n// as either grants. That is right for the roster somebody is paid to read and\n// wrong for the screen that says \"yours\" — an instructor who also trains would\n// read every booking at the studio under \"what you have booked\".\n//\n// So an entry may name a profile (`OkCacheEntry.reach`) and vex asks for the\n// policy at that reach instead. GRANTS ARE UNCHANGED — the union of every role's\n// verbs, so this can only narrow rows, never widen phases. A caller with no verb\n// for the table is still refused.\nexport const resolvePolicyAtReach = (\n app: NiscApp,\n grants: readonly string[],\n principal: string | null,\n reach: string,\n): ScopePolicy => resolvePolicyAtReachForRoles(app, grants, resolveRoles(app, principal), reach);\n\nexport const resolvePolicyAtReachForRoles = (\n app: NiscApp,\n grants: readonly string[],\n roles: readonly string[],\n reach: string,\n): ScopePolicy => createScopePolicy(resolvePrincipal(app.charter, grants, roles, 'data'), app.behaviors ?? {}, reach);\n\nexport type Catalog = { ids: readonly string[]; hash: string };\n\n// The application, resolved for one principal — granted action ids plus\n// the version token (equal hash, equal application; pushed over the\n// socket as the catalog-change signal).\n// THE SAME RESOLUTIONS, given roles rather than a principal — for callers that\n// have already resolved who somebody is. The principal was only ever a way to\n// reach `roles` (and, for the catalog, the tenant's install list).\nexport const resolveCatalogForRoles = (app: NiscApp, roles: readonly string[], installed: readonly string[] | undefined): Catalog => {\n const granted = [...resolvePrincipal(app.charter, Object.keys(app.actions), roles, 'actions')].sort();\n const ids = [...filterInstalled(granted, installed === undefined ? undefined : new Set(installed))];\n return { ids, hash: versionToken(ids) };\n};\n\nexport const resolveVariantsForRoles = (app: NiscApp, roles: readonly string[]): ReadonlyMap<string, LayoutNode> => {\n const variants = app.layouts ?? {};\n const granted = resolvePrincipal(app.charter, Object.keys(variants), roles, 'layouts');\n const bindings = new Map<string, LayoutNode>();\n for (const id of granted) {\n const variant = variants[id];\n if (variant !== undefined) bindings.set(variant.action, variant.layout);\n }\n return bindings;\n};\n\nexport const resolveCatalog = (app: NiscApp, principal: string | null): Catalog =>\n resolveCatalogForRoles(app, resolveRoles(app, principal), undefined);\n\n// The principal's layout bindings — action id → the granted variant's\n// layout (ring 2). Grants come from the charter's `layouts` section over\n// the variant-id universe. Two granted variants of one action is\n// incoherence `verifyVariants` refused at boot, so resolution never picks.\nexport const resolveVariants = (app: NiscApp, principal: string | null): ReadonlyMap<string, LayoutNode> => {\n const variants = app.layouts ?? {};\n const granted = resolvePrincipal(app.charter, Object.keys(variants), resolveRoles(app, principal), 'layouts');\n const bindings = new Map<string, LayoutNode>();\n for (const id of granted) {\n const variant = variants[id];\n if (variant !== undefined) bindings.set(variant.action, variant.layout);\n }\n return bindings;\n};\n\n// The boot-time coherence gate for ring 2 (server.ts throws on anything\n// returned): every variant reshapes a shipped action, and no wearable\n// combination the documents describe — each role alone, each assignment's\n// union, the anonymous principal — resolves to two variants of one action.\nexport const verifyVariants = (app: NiscApp): string[] => {\n const variants = app.layouts ?? {};\n const ids = Object.keys(variants);\n if (ids.length === 0) return [];\n const errors: string[] = [];\n for (const [id, variant] of Object.entries(variants)) {\n if (app.actions[variant.action] === undefined) {\n errors.push(`layout variant \"${id}\" reshapes unknown action \"${variant.action}\"`);\n }\n }\n const wearers = new Map<string, readonly string[]>();\n for (const role of Object.keys(app.charter)) wearers.set(`role \"${role}\"`, [role]);\n // COMBINATIONS, not people. This gate asks \"can anything wearable resolve to\n // two variants of one action\" — a question about the set of combinations,\n // which walking the population answered only by accident. `wearable` declares\n // them; absent, they are derived from the assignment map exactly as before.\n for (const roles of wearableOf(app)) wearers.set(`the combination [${[...roles].join(', ')}]`, roles);\n wearers.set('the anonymous principal', ['public']);\n for (const [who, roles] of wearers) {\n let granted: ReadonlySet<string>;\n try {\n granted = resolvePrincipal(app.charter, ids, roles, 'layouts');\n } catch {\n continue; // an unknown or cyclic role is the charter verifier's finding, not this one\n }\n const byAction = new Map<string, string[]>();\n for (const id of granted) {\n const variant = variants[id];\n if (variant !== undefined) byAction.set(variant.action, [...(byAction.get(variant.action) ?? []), id]);\n }\n for (const [action, held] of byAction) {\n if (held.length > 1) {\n errors.push(`${who} holds ${held.length} variants of \"${action}\" (${held.sort().join(', ')}) — one variant per action per principal`);\n }\n }\n }\n return errors;\n};\n\n// A content hash of the resolved id set — identity, not cryptography\n// (FNV-1a, hex).\nconst versionToken = (ids: readonly string[]): string => {\n const s = ids.join('\\n');\n let h = 0x811c9dc5;\n for (let i = 0; i < s.length; i += 1) {\n h ^= s.charCodeAt(i);\n h = Math.imul(h, 0x01000193) >>> 0;\n }\n return h.toString(16).padStart(8, '0');\n};\n","// ═══════════════════════════════════════════════════════════════\n// A BROWSER'S SESSION, KEPT WHERE ITS PAGE CANNOT READ IT.\n//\n// A terminal served by the app it talks to does not hold its session: the\n// browser does, in a cookie no script can read, and sends it by itself with\n// the two requests that need to know who is asking — the page, and the\n// upgrade that opens the socket. The server writes it in its answer to that\n// upgrade (socket.ts), or to a sign-in the app answers over HTTP\n// (`sessionCookies`, below). Any other terminal — a process, a page served\n// from somewhere else — holds its own token and offers it, as before.\n//\n// THE NAME is the terminal's token key (`nisc.token`, or a seat's own), so\n// several people can be signed in on one origin, each in a seat. It ends with\n// the port when the page is on one: a browser keeps cookies by host and not by\n// port, and two apps on localhost would otherwise sign each other out. Over\n// https it is `__Host-` prefixed and `Secure`, which a browser lets nothing\n// but this host set.\n//\n// BESIDE IT, `<name>.held=1`, which script CAN read and which says nothing but\n// that the browser holds a session — how a terminal knows to let go of a token\n// it was holding, and that a page drawn for somebody was drawn for it.\n//\n// NO ROUTE ANSWERS TO THIS COOKIE. It is read for a page request, which every\n// site may link to and none can read the answer of, and on an upgrade from the\n// app's own page — never from another origin's, which a browser would send it\n// with all the same.\n// ═══════════════════════════════════════════════════════════════\n\nexport const DEFAULT_TOKEN_KEY = 'nisc.token';\n\n// The token under one name in a `Cookie` header.\nexport const tokenFromCookie = (header: string | null | undefined, name = DEFAULT_TOKEN_KEY): string | null => {\n if (header === undefined || header === null) return null;\n const wanted = encodeURIComponent(name);\n for (const part of header.split(';')) {\n const at = part.indexOf('=');\n if (at < 0 || part.slice(0, at).trim() !== wanted) continue;\n try {\n const value = decodeURIComponent(part.slice(at + 1).trim());\n return value === '' ? null : value;\n } catch {\n return null;\n }\n }\n return null;\n};\n\n// Is this the app's own page asking? Its origin's host is the host the request\n// was addressed to — or one the deployment lists, behind a proxy that rewrites\n// `Host`. A sibling subdomain, another port, an opaque origin: not it.\nexport const isOwnOrigin = (origin: string | null | undefined, host: string | null | undefined, listed: readonly string[] = []): origin is string => {\n if (origin === undefined || origin === null || !URL.canParse(origin)) return false;\n const asked = new URL(origin);\n return asked.host === host?.toLowerCase() || listed.some((entry) => URL.canParse(entry) && new URL(entry).origin === asked.origin);\n};\n\nconst nameOf = (key: string, port: string): string => `${key}${port === '' ? '' : `.${port}`}`;\n\n// The flag's name, as a terminal on `port` reads it out of `document.cookie`.\nexport const heldCookieName = (key = DEFAULT_TOKEN_KEY, port = ''): string => encodeURIComponent(`${nameOf(key, port)}.held`);\n\nconst cookiesAt = (where: { port: string; secure: boolean }, key: string, token: string | null, lastsMs?: number | null): string[] => {\n const name = encodeURIComponent(nameOf(key, where.port));\n const life = token === null ? '; Max-Age=0' : typeof lastsMs === 'number' ? `; Max-Age=${Math.max(0, Math.floor(lastsMs / 1000))}` : '';\n const kept = `Path=/; SameSite=Lax${where.secure ? '; Secure' : ''}${life}`;\n return [`${where.secure ? '__Host-' : ''}${name}=${encodeURIComponent(token ?? '')}; HttpOnly; ${kept}`, `${name}.held=${token === null ? '' : '1'}; ${kept}`];\n};\n\n// The page's origin as its browser sees it: what the request says, else where\n// it was addressed and how a proxy in front says it arrived.\nconst originOf = (request: Request): string => {\n const said = request.headers.get('origin');\n if (said !== null && URL.canParse(said)) return said;\n const here = new URL(request.url);\n const scheme = request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim() || here.protocol.slice(0, -1);\n return `${scheme}://${request.headers.get('host') ?? here.host}`;\n};\n\n// THE `Set-Cookie` VALUES that keep `token` in the browser of the page at this\n// origin — or, for `null`, take it back. For a sign-in the app answers over\n// HTTP (a link redeemed, a provider's callback): set these on the response and\n// the page that follows is signed in, having never held the token. `lastsMs`\n// is how long the browser keeps it; left out, until the browser closes.\nexport const sessionCookies = (page: string | Request, token: string | null, options: { key?: string; lastsMs?: number | null } = {}): string[] => {\n const at = new URL(typeof page === 'string' ? page : originOf(page));\n return cookiesAt({ port: at.port, secure: at.protocol === 'https:' }, options.key ?? DEFAULT_TOKEN_KEY, token, options.lastsMs);\n};\n\n// What the browser holds for this key, out of a request's `Cookie` header.\n// `secure` says which of the two names to read; unknown (a page request does\n// not say how it arrived), the one only this host can have set is read first.\nexport const sessionTokenOf = (\n cookies: string | null | undefined,\n where: { port: string; secure?: boolean },\n key = DEFAULT_TOKEN_KEY,\n): { token: string; clear: string[] } | null => {\n const name = nameOf(key, where.port);\n for (const secure of where.secure === undefined ? [true, false] : [where.secure]) {\n const token = tokenFromCookie(cookies, `${secure ? '__Host-' : ''}${name}`);\n if (token !== null) return { token, clear: cookiesAt({ port: where.port, secure }, key, null) };\n }\n return null;\n};\n\n// ═══════════════════════════════════════════════════════════════\n// THE SEAL — how a sign-in made over the socket reaches that cookie.\n//\n// Only an HTTP answer can write a cookie, and a sign-in over the socket is not\n// one: the token has to travel through the page to the next upgrade. It\n// travels SEALED — encrypted with a key the page's browser holds in a second\n// cookie no script can read, set by the answer to its first upgrade. The page\n// can hand it back and cannot open it; neither can anybody it is shown to, on\n// this machine or another. It is good for a minute.\n//\n// The seal rides only the socket's own path: no page request carries it, so a\n// page drawn for nobody is still the same for everybody. It lasts until the\n// browser closes, and is never stored or looked up here — a key, not a name.\n//\n// ITS NAME IS WHAT KEEPS A SCRIPT FROM SUPPLYING IT. A request shows a cookie's\n// name and value and nothing of who set it, so a seal a script planted before\n// the browser's first upgrade would look like one given here — and the script\n// would hold the key. Over https the seal is `__Http-` prefixed: a name a\n// browser lets only an HTTP answer set, never script. A browser that does not\n// know the prefix treats it as any other name, and is where that is still open.\n//\n// WebCrypto, so this is the same on every runtime and nothing here is Node's.\n// ═══════════════════════════════════════════════════════════════\n\nconst SEALED_FOR_MS = 60_000;\nconst sealName = (secure: boolean): string => `${secure ? '__Http-' : ''}nisc.seal`;\nconst toBase64Url = (bytes: Uint8Array): string => btoa(String.fromCharCode(...bytes)).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\nconst fromBase64Url = (text: string): Uint8Array<ArrayBuffer> => Uint8Array.from(atob(text.replace(/-/g, '+').replace(/_/g, '/')), (char) => char.charCodeAt(0));\nconst keyOf = async (seal: string): Promise<CryptoKey> => crypto.subtle.importKey('raw', await crypto.subtle.digest('SHA-256', new TextEncoder().encode(seal)), 'AES-GCM', false, ['encrypt', 'decrypt']);\n\nexport const newSeal = (): string => toBase64Url(crypto.getRandomValues(new Uint8Array(32)));\n\n// The seal a browser sent with an upgrade, and the `Set-Cookie` value that\n// gives it one: for the socket's own `path` only, unreadable to script.\nexport const sealOf = (cookies: string | null | undefined, secure: boolean): string | null => tokenFromCookie(cookies, sealName(secure));\nexport const sealCookie = (seal: string, where: { secure: boolean; path: string }): string => `${sealName(where.secure)}=${seal}; HttpOnly; Path=${where.path}; SameSite=Lax${where.secure ? '; Secure' : ''}`;\n\nexport const sealSession = async (seal: string, token: string, forMs = SEALED_FOR_MS): Promise<string> => {\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const sealed = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, await keyOf(seal), new TextEncoder().encode(JSON.stringify({ token, until: Date.now() + forMs })));\n return toBase64Url(new Uint8Array([...iv, ...new Uint8Array(sealed)]));\n};\n\n// The token in a sealed sign-in — or null: not sealed with this seal, altered, or too old.\nexport const openSealed = async (seal: string, sealed: string): Promise<string | null> => {\n try {\n const bytes = fromBase64Url(sealed);\n const opened = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: bytes.slice(0, 12) }, await keyOf(seal), bytes.slice(12));\n const { token, until } = JSON.parse(new TextDecoder().decode(opened)) as { token?: unknown; until?: unknown };\n return typeof token === 'string' && typeof until === 'number' && until > Date.now() ? token : null;\n } catch {\n return null;\n }\n};\n","import { DefinitionValidationError } from '@niscorp/nova';\nimport type { RenderNode } from '@niscorp/nova';\nimport type { Catalog } from './principal';\nimport type { DeltaOp } from './delta';\nimport type { ShellHost } from './shells';\nimport { emitterOf, spanClock } from './telemetry';\nimport type { Telemetry } from './telemetry';\nimport { DEFAULT_TOKEN_KEY, isOwnOrigin, newSeal, openSealed, sealCookie, sealOf, sealSession, sessionCookies, sessionTokenOf } from './session-cookie';\n\n// ═══════════════════════════════════════════════════════════════\n// The socket — the authority channel (DESIGN.md § The socket), protocol layer.\n//\n// The socket invents nothing: JSON frames, every canvas-bound message\n// carries its canvas id, reconnect just re-sends current state. This\n// module is transport-blind — it speaks through the four-function\n// `Connection` seam; the RFC 6455 plumbing lives with each runtime's\n// entry (`ws` on Node in ./node, Bun-native later) and is never\n// hand-written.\n//\n// What rides it: connection lifecycle, token auth at upgrade, the CATALOG\n// channel (`hello` on connect — the resolved application + its version\n// token; equal hash, equal application), and the canvas streams (`render`\n// down, `event` up) fed by the server shell host. An app whose manifest\n// declares no shell has no streams, and an event envelope aimed at one is\n// answered honestly with `no_shell` rather than silently dropped.\n//\n// Identity is asked twice: once at upgrade, and then on a timer for as long\n// as the connection lives (see DEFAULT_REVALIDATE_MS). The second is what\n// lets a `session` verifier's expiry mean anything here — the HTTP surfaces\n// re-ask on every request, and a socket that asked once would be the hole\n// every long-lived credential leaks through.\n// ═══════════════════════════════════════════════════════════════\n\n// The transport seam — what a runtime's websocket must provide. Four\n// functions, and what the request that opened the connection offered;\n// everything above them is identical on every runtime.\nexport type Connection = {\n send: (text: string) => void;\n close: (code?: number, reason?: string) => void;\n onMessage: (fn: (text: string) => void) => void;\n onClose: (fn: () => void) => void;\n // The upgrade request, as far as it says who is asking: the subprotocols it\n // offered (`Sec-WebSocket-Protocol`, split), and — for a browser's session\n // (session-cookie.ts) — where the page is, where the request was addressed,\n // and the cookies it carried. A transport that leaves this out serves every\n // terminal as nobody.\n //\n // `answer`: a transport that has NOT answered the request yet says so by\n // giving this, and is told — once who is asking is decided, before the\n // connection is used at all — the `Set-Cookie` values its answer is to\n // carry: the one moment a cookie can be written. It answers when the\n // connection is first used.\n // Without it nothing is written, and a browser's terminal goes on holding\n // its own token.\n upgrade?: {\n offered: readonly string[];\n origin?: string | null;\n host?: string | null;\n cookie?: string | null;\n answer?: (cookies: readonly string[]) => void;\n };\n // Set here, not by a transport: how this connection's terminal is handed a\n // session when its browser holds a seal (session-cookie.ts) — sealed, so the\n // page carries it to the next upgrade and cannot open it. Absent, a session\n // is handed over as its token.\n seal?: (token: string) => Promise<string>;\n};\n\n// ── The envelope ──\nexport type ServerMessage =\n | { type: 'hello'; protocol: number; principal: string | null; catalog: { actions: readonly string[]; hash: string } }\n | { type: 'catalog'; actions: readonly string[]; hash: string }\n // the shell's canvas ARRANGEMENT — a rendered layout whose CanvasSlot\n // markers the terminal resolves against its per-canvas trees\n | { type: 'frame'; tree: RenderNode[] }\n | { type: 'render'; canvas: string; tree: RenderNode[] }\n // The same render, as a DELTA against the last frame this connection was\n // sent for this canvas. Only ever sent to a terminal that asked for deltas\n // (`?delta=1` on the upgrade) and only when a previous frame exists, so a\n // terminal that does not understand this never receives one.\n //\n // `hash` is over the rebuilt message text: a terminal that applies the ops\n // and does not land on it has diverged, and asks for a whole frame instead\n // of rendering something the server never meant.\n | { type: 'render-delta'; canvas: string; ops: DeltaOp[]; hash: number }\n // session GRANT (login succeeded server-side): store the token and\n // reconnect authenticated — the twin of the 4403 SIGNED_OUT revoke\n // A sign-in: the terminal comes back as that principal. As the token, for a\n // terminal that keeps its own; SEALED, for one whose browser keeps the\n // session — it offers it on its next upgrade, where its browser's seal opens it.\n | { type: 'session'; token: string }\n | { type: 'session'; sealed: string }\n | { type: 'error'; code: string; message: string; canvas?: string };\n\nexport type ClientMessage =\n | { type: 'event'; canvas: string; event: Record<string, unknown> }\n | { type: 'publish'; channel: string; payload?: unknown }\n // RESYNC: this terminal's frame for a canvas is not what the server thinks\n // it is — a delta failed its checksum, or arrived with no base to apply it\n // to. Answered with whole frames, which is the state both ends can always\n // agree on. Distinct from `reset`: the SHELL is fine, only this connection's\n // copy of it drifted, so nothing is torn down.\n | { type: 'resync' }\n // BACK: undo this session's last navigation. It names no canvas for the same\n // reason `reset` does not — back is one gesture over the whole shell, and the\n // terminal that sends it has no idea which canvas moved last (it is served\n // trees, not stacks). Protocol-level, so a browser's back button, a TUI's\n // Escape and a REPL word are the same message on one wire, and the app has to\n // author nothing to receive it.\n | { type: 'back' }\n // POP TO: jump straight to an ancestor already on a canvas's stack. Back\n // undoes ONE navigation; a breadcrumb that names a screen three levels down\n // is one intention, not three gestures. Sending three `back`s instead raced\n // the browser's own history repair and dropped presses — the shell can walk\n // its own stack atomically, so it should be asked to.\n | { type: 'popTo'; canvas: string; instance: string }\n // RESET: throw this session's shell away and serve its replacement. The one\n // message that names no canvas, deliberately — it is the recovery for a\n // shell whose canvases are the broken thing, so it must not have to travel\n // through one. Protocol-level, not app-level: no action declares it, no\n // charter grants it, and it reaches a terminal whose every surface is dead.\n | { type: 'reset' };\n\n// The wire protocol this server speaks, and the oldest a terminal may speak to\n// it. A terminal says which it speaks on the upgrade (`?protocol=N` — known\n// before the first frame is sent); one that says nothing speaks 1, which is\n// every terminal built before the question existed. Outside the range the\n// connection is refused with a sentence and CLOSE_PROTOCOL_MISMATCH, never\n// served frames it would misread. Bump PROTOCOL when a message changes shape;\n// raise PROTOCOL_MIN only when the server stops speaking an old one.\n//\n// 2: the token left the address. A terminal at 1 put it in `?token=`, and an\n// address is what every proxy on the way writes into its log. A server that\n// went on reading it there would keep that open for as long as anything used\n// it, so 1 is no longer spoken: a terminal built before is told to reload.\nexport const PROTOCOL = 2;\nexport const PROTOCOL_MIN = 2;\n\n// WHO A TERMINAL IS rides the upgrade request, in the one header every host\n// lets a terminal set, a browser included: the subprotocols it offers. It\n// offers `nisc`, and beside it its token when it holds one — base64url,\n// because a subprotocol is an HTTP token and a session token need not be. The\n// server answers `nisc`, never the other. Decided on the request, so no\n// connection is ever open and waiting to be told who it is.\nexport const SUBPROTOCOL = 'nisc';\nconst TOKEN_OFFER = 'nisc.token.';\nconst SEALED_OFFER = 'nisc.sealed.';\n\n// `sealed`: a sign-in the terminal was handed sealed, offered back as it is.\nexport const offerToken = (token: string | null, sealed: string | null = null): string[] => {\n const offer = sealed === null ? [SUBPROTOCOL] : [SUBPROTOCOL, `${SEALED_OFFER}${sealed}`];\n if (token === null) return offer;\n const bytes = String.fromCharCode(...new TextEncoder().encode(token));\n return [...offer, `${TOKEN_OFFER}${btoa(bytes).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')}`];\n};\n\nexport const offeredToken = (offered: readonly string[] = []): string | null => {\n const offer = offered.find((entry) => entry.startsWith(TOKEN_OFFER));\n if (offer === undefined) return null;\n try {\n const bytes = atob(offer.slice(TOKEN_OFFER.length).replace(/-/g, '+').replace(/_/g, '/'));\n return new TextDecoder('utf-8', { fatal: true }).decode(Uint8Array.from(bytes, (char) => char.charCodeAt(0))) || null;\n } catch {\n return null;\n }\n};\n\n// Application close code: the token did not resolve to a principal.\nexport const CLOSE_INVALID_TOKEN = 4401;\n// Application close code: the session ended (sign-out, from any of the\n// principal's terminals) — the terminal clears its token instead of\n// reconnecting.\nexport const CLOSE_SIGNED_OUT = 4403;\n// Application close code: the server could not open a session for THIS\n// connection — commonest cause: a definition failing validation reached the\n// live catalog (a dev edit mid-reload). The refusal is this terminal's alone;\n// the process and every other session stay up, and reconnecting later is\n// reasonable — the next build is attempted fresh.\nexport const CLOSE_SHELL_FAILED = 4500;\n// Application close code: terminal and server speak protocols the other cannot\n// (see PROTOCOL). Not a retry: reconnecting speaks the same protocol again. A\n// browser terminal needs a reload to fetch the current build; the preceding\n// `error` says which side is behind (`client_too_old` / `server_too_old`).\nexport const CLOSE_PROTOCOL_MISMATCH = 4426;\n\nexport type SocketContext = {\n session: (token: string) => string | null | Promise<string | null>;\n catalog: (principal: string | null) => Catalog | Promise<Catalog>;\n // The shell host — when the manifest declares a shell, events route into\n // the session's server shell and render frames flow back.\n shells?: ShellHost;\n // WHICH HOST A PATH LEADS TO. A terminal on a page names the path it is on\n // (`?path=`); this answers with that page's host and the input its path\n // carries, or undefined for a path that is the app's. Absent: every\n // connection is the app's, as before pages existed.\n page?: (path: string) => { host: ShellHost; inputs: Record<string, Record<string, unknown>> } | undefined;\n // How often a LIVE connection's credential is re-verified. Default\n // `DEFAULT_REVALIDATE_MS`; `0` or `Infinity` disables it, and a token\n // checked once at upgrade is then trusted for the life of the connection.\n revalidateMs?: number;\n // The deployment's telemetry sink, if any — a `socket.upgrade` span per\n // connection admitted or refused, and a `socket.close` span carrying the\n // whole connection's lifetime. See telemetry.ts.\n telemetry?: Telemetry;\n // Origins that are this app's own page beside the host a request is\n // addressed to (`runtime.origins`) — a proxy that rewrites `Host`.\n origins?: readonly string[];\n // How much longer a token resolves, when the credential knows — how long a\n // browser is told to keep the cookie that carries it. Unknown: until the\n // browser closes.\n sessionLastsMs?: (token: string) => number | null | Promise<number | null>;\n};\n\n// ── Revalidation ──\n// The HTTP surfaces re-ask \"who is this\" on every request; the socket asked\n// once, at upgrade, and never again. That asymmetry is why an app could not\n// give its tokens an expiry that meant anything: the verifier seam is\n// perfectly able to say a token has died (return null), but on a live socket\n// nobody was listening for the answer.\n//\n// It also failed in a shape worth naming. The server shell's own wire rides\n// the HTTP middleware carrying the session's token, so an expired credential\n// used to leave the socket open and cheerful — frames flowing, screen alive —\n// while every endpoint the shell called came back 401. A live interface whose\n// every load silently fails is strictly worse than a lock screen.\n//\n// The recovery for this already existed and is untouched: a `4401` close is a\n// recovery, not a retry, and the terminal drops its token and reconnects\n// anonymous onto the served lock screen. All that was missing was something\n// asking the question. This is that.\nexport const DEFAULT_REVALIDATE_MS = 60 * 1000;\n\n// One accept per new connection: authenticate (the token rides the upgrade\n// URL — browsers cannot set websocket headers; absent = the anonymous\n// principal, invalid = closed with 4401), then say hello with the resolved\n// catalog and settle into the message loop. `stop` ends revalidation, for\n// hosts that outlive their server (dev checks, embedded tools) — the timer is\n// unref'd, so a plain process needn't call it.\nexport type SocketAccept = ((url: string, connection: Connection) => Promise<void>) & { stop: () => void };\n\nconst parse = (text: string): Record<string, unknown> | null => {\n try {\n const value: unknown = JSON.parse(text);\n return value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : null;\n } catch {\n return null;\n }\n};\n\nexport const createSocket = (ctx: SocketContext): SocketAccept => {\n const emit = emitterOf(ctx.telemetry);\n let saidNotOwn = false;\n // Every live connection, with the credential it authenticated under (null =\n // anonymous, which has nothing that can expire). One structure: the future\n // catalog-push fan-out wants the keys, revalidation wants the values.\n const live = new Map<Connection, { token: string; principal: string } | null>();\n\n const expire = (connection: Connection): void => {\n // Diagnostics before authority, as at upgrade — the close code is what\n // the terminal acts on; this is what a person reads in a log.\n connection.send(JSON.stringify({ type: 'error', code: 'invalid_token', message: 'The session token no longer resolves to this principal.' } satisfies ServerMessage));\n connection.close(CLOSE_INVALID_TOKEN, 'session expired');\n live.delete(connection);\n };\n\n const revalidate = async (): Promise<void> => {\n for (const [connection, credential] of [...live]) {\n if (credential === null) continue; // anonymous — nothing to expire\n let resolved: string | null;\n try {\n resolved = await ctx.session(credential.token);\n } catch {\n // The verifier is unreachable — a database blip, a network hiccup.\n // That is not evidence a session ended, and signing everybody out on\n // it would turn a transient fault into an outage. Ask again next pass.\n continue;\n }\n // Unchanged is the overwhelmingly common answer. A token that stops\n // resolving has expired or been revoked; one that resolves to somebody\n // ELSE is not the session that attached, and both are the same close.\n if (resolved === credential.principal) continue;\n if (!live.has(connection)) continue; // it closed while we were awaiting\n expire(connection);\n }\n };\n\n const revalidateMs = ctx.revalidateMs ?? DEFAULT_REVALIDATE_MS;\n let sweeper: ReturnType<typeof setInterval> | undefined;\n if (revalidateMs > 0 && Number.isFinite(revalidateMs)) {\n sweeper = setInterval(() => void revalidate(), revalidateMs);\n // Revalidation must never be the reason a process stays alive.\n (sweeper as unknown as { unref?: () => void }).unref?.();\n }\n\n // REFUSING ONE SESSION MUST NEVER COST THE OTHERS. Every await in the body\n // below can throw — the verifier on a database blip, the shell build on a\n // definition that fails validation — and the runtime transport calls accept\n // without awaiting it, so an escaped rejection is an unhandled one and Node\n // kills the whole process: one bad definition, every session on the box\n // disconnected. So accept NEVER rejects. A failure to open this session is\n // answered to this terminal — a sentence naming the failing definitions\n // when there are any, then a 4500 close — and logged where somebody can\n // read it. The durable map is only written after a successful build, so a\n // refused terminal poisons nothing: the next connect builds fresh.\n const accept = async (url: string, connection: Connection): Promise<void> => {\n const send = (message: ServerMessage): void => connection.send(JSON.stringify(message));\n try {\n await open(url, connection, send);\n } catch (error) {\n console.error('[moss/socket] refused a session:', error);\n live.delete(connection);\n const failures =\n error instanceof DefinitionValidationError\n ? ((error.context as { failures?: { id: string }[] } | undefined)?.failures ?? []).map((f) => f.id)\n : [];\n const detail = failures.length > 0 ? `${String(error instanceof Error ? error.message : error)}: ${failures.join(', ')}` : String(error);\n try {\n send({ type: 'error', code: 'session_failed', message: `This session could not be opened — ${detail}. The refusal is this terminal's alone; the server is up.` });\n connection.close(CLOSE_SHELL_FAILED, 'session failed');\n } catch {\n // The transport is already gone — there is nobody left to tell.\n }\n }\n };\n\n const open = async (url: string, connection: Connection, send: (message: ServerMessage) => void): Promise<void> => {\n // One clock stamped at the handshake serves both the short `socket.upgrade`\n // span and the whole-connection `socket.close` span from the same origin.\n const upClock = emit === undefined ? undefined : spanClock();\n const params = new URL(url, 'http://nisc.local').searchParams;\n const spoken = Number(params.get('protocol') ?? '1');\n if (!Number.isInteger(spoken) || spoken < PROTOCOL_MIN || spoken > PROTOCOL) {\n const behind = spoken > PROTOCOL ? 'server' : 'client';\n send({\n type: 'error',\n code: `${behind}_too_old`,\n message: `This terminal speaks protocol ${params.get('protocol') ?? '1'}; this server speaks ${PROTOCOL_MIN}–${PROTOCOL}. ${behind === 'client' ? 'Reload the terminal to get the current build.' : 'The server has not been updated yet.'}`,\n });\n connection.close(CLOSE_PROTOCOL_MISMATCH, 'protocol mismatch');\n return;\n }\n const upgrade = connection.upgrade;\n // THE APP'S OWN PAGE does not hold its session: its browser does, in a\n // cookie the page cannot read (session-cookie.ts), and sent it with this\n // request. From any other origin the cookie is not looked at — a browser\n // sends it with a stranger's page all the same. `key` is which of the\n // browser's sessions this terminal is (a seat); a name, not a secret.\n const key = /^[\\w.-]{1,64}$/.test(params.get('key') ?? '') ? (params.get('key') as string) : DEFAULT_TOKEN_KEY;\n const page = upgrade !== undefined && isOwnOrigin(upgrade.origin, upgrade.host, ctx.origins) ? new URL(upgrade.origin) : undefined;\n const secure = page?.protocol === 'https:';\n const held = page === undefined ? null : sessionTokenOf(upgrade?.cookie, { port: page.port, secure }, key);\n // A SIGN-IN OVER THE SOCKET REACHES THAT COOKIE SEALED. A terminal whose\n // browser can keep a session says so (`sealed=1`), and its browser is given\n // a seal — a key in a second cookie no script can read — by the answer to\n // its first upgrade. A sign-in is then handed to the page sealed with it;\n // the page offers it back here, and only this browser's seal opens it.\n const sealing = page !== undefined && params.get('sealed') === '1';\n // A browser terminal that is not on the app's own page works as it always\n // did, holding its own token — which is right for a page served from\n // somewhere else, and is what a proxy that rewrites `Host` looks like too.\n // Said once: nothing else would tell a deployment it is in the second case.\n if (page === undefined && params.get('sealed') === '1' && typeof upgrade?.origin === 'string' && !saidNotOwn) {\n saidNotOwn = true;\n console.warn(`[moss] a terminal on ${upgrade.origin} holds its own session token: this server was addressed as ${upgrade.host ?? 'nothing'}, so that is not the app’s own page. If the app is served there, behind a proxy that rewrites Host, list it in runtime.origins.`);\n }\n const hadSeal = sealing ? sealOf(upgrade?.cookie, secure) : null;\n const sealedOffer = upgrade?.offered.find((entry) => entry.startsWith(SEALED_OFFER))?.slice(SEALED_OFFER.length) ?? null;\n // A sealed sign-in that came back with no seal to open it: this browser\n // does not keep the cookie, and is not handed another sign-in that way.\n const sealLost = sealing && sealedOffer !== null && hadSeal === null;\n const seal = !sealing || sealLost ? null : (hadSeal ?? (upgrade?.answer === undefined ? null : newSeal()));\n const offered = offeredToken(upgrade?.offered) ?? (sealedOffer === null || hadSeal === null ? null : await openSealed(hadSeal, sealedOffer));\n // A token the terminal offers comes first. `leave`: it was signed out, and\n // says so because what its browser holds may be a token that still\n // resolves — an app's own provider's is not moss's to revoke.\n let token = offered ?? (params.get('leave') === '1' ? null : (held?.token ?? null));\n let principal = token === null ? null : await ctx.session(token);\n if (offered !== null && principal === null) {\n if (emit !== undefined && upClock !== undefined) {\n emit({ name: 'socket.upgrade', startUnixNano: upClock.startUnixNano, endUnixNano: upClock.endUnixNano(), status: 'refused', attributes: { hasPrincipal: false } });\n }\n send({ type: 'error', code: 'invalid_token', message: 'The session token did not resolve to a principal.' });\n connection.close(CLOSE_INVALID_TOKEN, 'invalid token');\n return;\n }\n // What the browser held and no longer resolves is nobody — not a refusal:\n // the page cannot read it to drop it, so a 4401 would be one it could\n // never stop getting.\n if (principal === null) token = null;\n // THE ANSWER makes the browser hold who this turned out to be. A token the\n // page offered — left in storage by an earlier build, or just handed to it\n // at sign-in — is moved into the cookie, and that was the last time the\n // page held it; a session that ended is taken back. An offered token is\n // written even when the browser sent the same one: over plain http on the\n // default port the copy an earlier build kept, readable by script, has\n // this cookie's name.\n const answered = [\n ...(page === undefined || (offered === null && (held?.token ?? null) === token) ? [] : token === null ? (held?.clear ?? []) : sessionCookies(page.origin, token, { key, lastsMs: (await ctx.sessionLastsMs?.(token)) ?? null })),\n ...(seal !== null && hadSeal === null ? [sealCookie(seal, { secure, path: new URL(url, 'http://nisc.local').pathname })] : []),\n ];\n if (answered.length > 0) upgrade?.answer?.(answered);\n if (seal !== null) connection.seal = (granted) => sealSession(seal, granted);\n // The terminal is told, and stops asking to be handed sign-ins sealed —\n // the next one reaches it as a token, on this connection already.\n if (sealLost) {\n send({ type: 'error', code: 'seal_not_kept', message: 'This browser did not keep the cookie a sealed sign-in is opened with. Sign in again: it will be handed over as a token.' });\n }\n\n // Remembered WITH its credential — revalidation has to re-ask the same\n // question this connection was admitted on, and the token is not\n // recoverable from anything else here.\n live.set(connection, token !== null && token !== '' && principal !== null ? { token, principal } : null);\n connection.onClose(() => live.delete(connection));\n // The connection's whole life, closed by the same clock — how long\n // terminals stay, and under a principal or anonymous. Registered here so it\n // fires however the connection ends (graceful, expiry, transport drop).\n if (emit !== undefined && upClock !== undefined) {\n const hadPrincipal = principal !== null;\n connection.onClose(() => emit({ name: 'socket.close', startUnixNano: upClock.startUnixNano, endUnixNano: upClock.endUnixNano(), status: 'ok', attributes: { hasPrincipal: hadPrincipal } }));\n }\n\n // The catalog channel: the application, resolved for YOU, on every\n // (re)connect — reconnect re-sends current state, no replay machinery.\n const { ids, hash } = await ctx.catalog(principal);\n send({ type: 'hello', protocol: PROTOCOL, principal, catalog: { actions: ids, hash } });\n\n // The canvas streams: attach to the session's shell (durable per\n // principal — the shell outlives this connection) and it re-sends the\n // current trees; every change fans out to every attached connection.\n // Frame deltas are OPT-IN by the terminal, on the upgrade URL beside the\n // token — browsers cannot set websocket headers, and the capability has to\n // be known before the first frame is sent. A terminal that says nothing is\n // served whole frames forever, which is what every terminal built before\n // this existed does.\n const wantsDelta = params.get('delta') === '1';\n\n // An anonymous terminal whose page was rendered server-side names the id\n // seed that page's shell was built under, so this connection's throwaway\n // shell mints the same instance ids and its first frames match the page.\n // Shape-checked, never trusted further: it only ever names ids inside the\n // caller's own shell.\n const named = params.get('seed');\n const seed = named !== null && /^[0-9a-f]{8,40}$/.test(named) ? named : undefined;\n\n // The path the terminal is on decides which shell it is served: a page's,\n // built for this connection alone, or the app's.\n const path = params.get('path');\n const route = path === null ? undefined : ctx.page?.(path);\n const host = route?.host ?? ctx.shells;\n\n const session = await host?.session(token, principal, { ...(seed === undefined ? {} : { seed }), ...(route === undefined ? {} : { inputs: route.inputs }) });\n if (session !== undefined) {\n session.attach(connection, { delta: wantsDelta });\n connection.onClose(() => session.detach(connection));\n }\n\n // Admitted: the handshake resolved a principal, said hello, and attached a\n // shell. The span measures that, not the connection's life (that is\n // `socket.close`).\n if (emit !== undefined && upClock !== undefined) {\n emit({ name: 'socket.upgrade', startUnixNano: upClock.startUnixNano, endUnixNano: upClock.endUnixNano(), status: 'ok', attributes: { hasPrincipal: principal !== null } });\n }\n\n connection.onMessage((text) => {\n const message = parse(text);\n // Reset first, and answered on its own terms: a wedged session is\n // exactly the one whose other paths cannot be trusted to run.\n if (message !== null && message['type'] === 'reset') {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.reset();\n return;\n }\n // Resync before the ordinary paths, for the reason reset is: a terminal\n // asking for this has already decided it cannot trust what it is holding.\n if (message !== null && message['type'] === 'resync') {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.resync(connection);\n return;\n }\n if (message !== null && message['type'] === 'back') {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.back();\n return;\n }\n if (\n message !== null &&\n message['type'] === 'popTo' &&\n typeof message['canvas'] === 'string' &&\n typeof message['instance'] === 'string'\n ) {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.popTo(message['canvas'], message['instance']);\n return;\n }\n if (message !== null && message['type'] === 'publish' && typeof message['channel'] === 'string') {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.publish(message['channel'], message['payload']);\n return;\n }\n if (message === null || message['type'] !== 'event' || typeof message['canvas'] !== 'string') {\n send({ type: 'error', code: 'invalid_message', message: 'Messages are JSON { type: \"event\", canvas, event }.' });\n return;\n }\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.', canvas: message['canvas'] });\n return;\n }\n const event = message['event'];\n if (event === null || typeof event !== 'object' || Array.isArray(event)) {\n send({ type: 'error', code: 'invalid_message', message: 'The event field must be a NovaEvent object.', canvas: message['canvas'] });\n return;\n }\n session.dispatch(message['canvas'], event as Record<string, unknown>);\n });\n };\n\n return Object.assign(accept, {\n stop: () => {\n if (sweeper !== undefined) clearInterval(sweeper);\n sweeper = undefined;\n },\n });\n};\n","// Frame deltas — send what changed, not the frame.\n//\n// A shell re-sends a whole canvas tree whenever that tree changes. Most changes\n// are small against a large tree (a keystroke filters a list, one badge flips),\n// so the new frame is mostly a rearrangement of bytes the client already holds.\n//\n// This encodes the new frame as COPY runs from the old one plus literal\n// inserts. It is deliberately not a structural diff over the tree: a\n// navigation produces a genuinely different tree, and a path-based diff then\n// costs MORE than the frame it replaces, while a byte matcher still finds the\n// shared vocabulary. It is also not zlib's preset dictionary, which would be\n// two lines here and does not exist in a browser.\n//\n// No dependency, both directions in one file, and small enough to read in\n// full — a delta layer that cannot be audited is a desync you cannot diagnose.\n\n/** A run copied from the base frame: offset, length. */\ntype Copy = [0, number, number];\n/** Bytes that are not in the base at all. */\ntype Insert = [1, string];\nexport type DeltaOp = Copy | Insert;\n\n// Matches shorter than this cost more to describe than to inline. 16 is a\n// compromise: low enough to catch a changed cell inside a row, high enough that\n// the index does not match noise.\nconst BLOCK = 16;\n\n/**\n * Encode `target` as operations against `base`.\n *\n * Greedy and single-pass: at each position look for a block that already exists\n * in the base, extend the match as far as it runs, and emit a copy. Anything\n * unmatched accumulates into a literal. Not optimal — an optimal encoder needs\n * a suffix automaton — but it captures the long shared runs that dominate a\n * render tree, which is where the bytes are.\n */\nexport const encodeDelta = (base: string, target: string): DeltaOp[] => {\n if (base.length < BLOCK) return [[1, target]];\n\n const index = new Map<string, number>();\n for (let i = 0; i + BLOCK <= base.length; i += 1) {\n // First position wins: earlier offsets tend to extend further in a tree\n // whose head is stable chrome.\n const key = base.slice(i, i + BLOCK);\n if (!index.has(key)) index.set(key, i);\n }\n\n const ops: DeltaOp[] = [];\n let literal = '';\n let at = 0;\n\n while (at < target.length) {\n const key = target.slice(at, at + BLOCK);\n const found = key.length === BLOCK ? index.get(key) : undefined;\n if (found === undefined) {\n literal += target[at];\n at += 1;\n continue;\n }\n let length = BLOCK;\n while (found + length < base.length && at + length < target.length && base[found + length] === target[at + length]) {\n length += 1;\n }\n if (literal !== '') {\n ops.push([1, literal]);\n literal = '';\n }\n ops.push([0, found, length]);\n at += length;\n }\n if (literal !== '') ops.push([1, literal]);\n return ops;\n};\n\n/** Rebuild the frame. Throws on a malformed op rather than returning a\n * half-applied string — a silently wrong frame is the failure this whole\n * layer has to not have. */\nexport const applyDelta = (base: string, ops: readonly DeltaOp[]): string => {\n let out = '';\n for (const op of ops) {\n if (op[0] === 1) {\n out += op[1];\n continue;\n }\n const [, offset, length] = op;\n if (offset < 0 || length < 0 || offset + length > base.length) {\n throw new Error(`moss/delta: copy ${offset}+${length} is outside a base of ${base.length}`);\n }\n out += base.slice(offset, offset + length);\n }\n return out;\n};\n\n/**\n * A cheap, order-sensitive checksum of a frame.\n *\n * Carried on every delta so a client can prove it rebuilt the frame the server\n * meant. A delta protocol without this is one dropped message away from a\n * client that is permanently and silently wrong, with no error anywhere — which\n * is strictly worse than sending whole frames forever.\n */\nexport const frameHash = (text: string): number => {\n let hash = 0x811c9dc5;\n for (let i = 0; i < text.length; i += 1) {\n hash ^= text.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n return hash >>> 0;\n};\n","import { createShell, createComponentRegistry, createLayoutStore, canvasTreeOf, shellSettled, CANVAS_SLOT_NAME, ACTION_SLOT_NAME } from '@niscorp/nova';\nimport { componentsOf, snapshotShell } from '@niscorp/nova/reflect';\nimport type { ActionDefinition, Shell, CanvasConfig, FetchFn, FunctionHandler, LayoutNode, RenderNode } from '@niscorp/nova';\nimport { emitterOf, spanClock } from './telemetry';\nimport type { Emit } from './telemetry';\nimport { randomBytes } from 'node:crypto';\nimport { evaluate } from '@niscorp/prism';\nimport type { ScopePolicy } from '@niscorp/vex';\nimport type { FunctionSession, NiscApp, ShellManifest } from './app';\nimport type { ShellNeed } from './liveness';\nimport type { NiscRuntime } from './runtime';\nimport type { Catalog } from './principal';\nimport { CLOSE_SIGNED_OUT } from './socket';\nimport type { Connection, ServerMessage } from './socket';\nimport { encodeDelta, frameHash } from './delta';\nimport { revokeAllFor } from './sessions';\n\n// ═══════════════════════════════════════════════════════════════\n// The shell host (DESIGN.md § The shell runs on the server): the shell\n// runs here, the client is a canvas terminal. One durable shell per authenticated\n// principal (the socket is ephemeral: connections attach and detach, the\n// shell survives — reattach just re-sends current trees, and N attached\n// connections receive the same frames: shared canvases are the same\n// mechanism). Anonymous connections get a throwaway shell, disposed with\n// the connection.\n//\n// The shell is built from the manifest's `shell` artifacts: canvases and\n// fragments are data; `inputs` is the app's one derivation hook (per-\n// principal boot input — nav flags, user chips). Everything else is\n// derived here: the granted action set from the catalog (an ungranted\n// initial simply doesn't mount — ring 1), ambient transform context from\n// the session, and every endpoint call rides the server's OWN surfaces\n// with the session's token — the server shell is just another\n// principal-bound client of the same wire, enforcement included.\n//\n// Because the shell is durable and keyed by PRINCIPAL, a wedged one is not\n// something a client can escape: dropping the token and reconnecting gets\n// you a throwaway anonymous shell, and signing back in hands you the same\n// wreck. Recovery is therefore a server verb, not a client gesture — hence\n// `reset`, which disposes a shell and builds its replacement from the same\n// derivation boot ran, carrying the attached connections across so every\n// terminal simply receives a fresh frame. `list` is the truthful roster\n// that makes an operator able to find the shell to reset; the idle sweep is\n// the same disposal on a timer, and safe for the reason DESIGN.md gives —\n// the database is the durable thing, a shell is a warm cache.\n// ═══════════════════════════════════════════════════════════════\n\n// WHO A SHELL IS BEING BUILT FOR, resolved ONCE.\n//\n// A shell used to ask four separate synchronous questions about its principal,\n// every one of them ultimately answered by a resident map of the whole\n// population. One async answer replaces all four. This seam arrives last in the\n// migration because `inputs` decides what MOUNTS and so cannot be deferred the\n// way `seeds` can — which is exactly why it was the last thing still forcing an\n// application to hold a directory.\nexport type ShellPrincipal = {\n roles: readonly string[];\n // The app's own scope values, passed back to `inputs` untouched. Moss never\n // looks inside; it is the app's record, on its way back to the app.\n scope: Record<string, unknown>;\n // The tenant's live integrations. Carried because `adopt` has to recompute a\n // catalog when the ACTIONS change, and a catalog that forgot which integrations were\n // installed would hand every studio every integration's screens.\n installed: readonly string[] | undefined;\n catalog: Catalog;\n variants: ReadonlyMap<string, LayoutNode>;\n policy: ScopePolicy;\n};\n\nexport type ShellHostContext = {\n app: NiscApp;\n // WHICH SHELL THIS HOST BUILDS. Default: the app's own (`app.shell`). A PAGE\n // is the other answer — a manifest of its own, drawn per request.\n manifest?: ShellManifest;\n // Whether a principal's shell is KEPT. Default true: the app's shell is one\n // durable shell per person, the thing that rearranges itself around them. A\n // page's is not — `false` builds a shell for the length of one read or one\n // connection, whoever is asking, and runs no `onSession` (session code is the\n // app's; a page has none).\n kept?: boolean;\n // What one definition needs once drawn (./liveness). Absent, every screen is\n // counted live — a host that cannot ask must not conclude a page is finished.\n needOf?: (definition: ActionDefinition) => ShellNeed;\n // The one resolution, awaited once per shell build.\n resolve: (principal: string | null) => Promise<ShellPrincipal>;\n // The same derivations keyed by ROLES rather than by principal, for `adopt`.\n // Adopting is for changed ARTIFACTS, not changed people: the roles a live\n // shell was built with are still its roles, so re-resolving them would be a\n // round trip to learn what the cell already knows.\n catalogFor: (roles: readonly string[], installed: readonly string[] | undefined) => Catalog;\n variantsFor: (roles: readonly string[]) => ReadonlyMap<string, LayoutNode>;\n // The internal wire: the server's own fetch, authorized as the session.\n wire: (token: string | null) => FetchFn;\n // The environment and the per-principal policy — what the manifest's\n // in-process functions close over (agents read data under the policy).\n runtime: NiscRuntime;\n // How long a durable shell may sit with NOTHING attached before it is\n // disposed. Default `DEFAULT_IDLE_MS`; `0` or `Infinity` disables the sweep\n // and shells live until sign-out or process exit. Only the idle clock is\n // swept — there is deliberately no absolute cap, because that would discard\n // the state of somebody who is working.\n idleMs?: number;\n // Send a changed canvas as a delta against the frame the connection last\n // received, instead of whole. Default off; a connection is only ever sent one\n // if it asked at attach. See `runtime.shellFrameDelta` and DOCS.md.\n delta?: boolean;\n};\n\n// ── THE FLOOR UNDER A FAILING INTEGRATION ───────────────────────────\n//\n// A third-party service being down is the steady state of a marketplace, and\n// the screen in front of it belongs to a studio owner, not an operator. A\n// integration reply carrying no `message` falls through to the terminal's bare\n// `HTTP 500` — a status code in front of a customer. So the session's wire\n// puts a SENTENCE under every integration call: naming the integration, saying it\n// is the integration, saying the studio is otherwise fine. A reply that DOES carry\n// a message passes through untouched — the integration's own words always win —\n// and no other path pays anything.\nconst INTEGRATION_PATH = /^\\/integrations\\/([a-z][a-z0-9-]*)\\//;\n\nconst flooredWire = (inner: FetchFn): FetchFn => async (url, init) => {\n const integration = INTEGRATION_PATH.exec(url)?.[1];\n if (integration === undefined) return inner(url, init);\n\n const floor = (status: number): Awaited<ReturnType<FetchFn>> => {\n const body = { message: `The ${integration} add-on is not answering right now. The rest of the studio is unaffected.` };\n return { ok: false, status, json: async () => body, text: async () => JSON.stringify(body) };\n };\n\n let reply: Awaited<ReturnType<FetchFn>>;\n try {\n reply = await inner(url, init);\n } catch {\n return floor(502);\n }\n if (reply.ok) return reply;\n\n try {\n const body: unknown = await reply.json();\n const message = (body as { message?: unknown } | null)?.message;\n // The proxy's own generic phrase gets the same upgrade as silence — it\n // knows no integration name; this seam does. The literal belongs to the proxy\n // (server.ts) and the naming should move there with its next edit.\n if (typeof message === 'string' && message !== 'The integration is unreachable.') {\n // Re-serve the consumed body — `json()` reads once.\n return { ok: false, status: reply.status, json: async () => body, text: async () => JSON.stringify(body) };\n }\n } catch {\n // Unparseable is the same case as silent.\n }\n return floor(reply.status);\n};\n\nexport type ShellSession = {\n // The living nova Shell — for in-process hosts (dev checks, embedded\n // tools) that drive it directly. Remote clients ride attach/dispatch.\n // A GETTER, not a field: `reset` replaces the shell under a session that\n // callers already hold, and a snapshot taken at session time would go on\n // addressing the disposed one.\n readonly shell: Shell;\n // `options.delta` is the terminal declaring it can apply frame deltas. Absent\n // means whole frames, which is what every terminal predating them expects.\n attach: (connection: Connection, options?: { delta?: boolean }) => void;\n detach: (connection: Connection) => void;\n // This connection's copy of a canvas drifted from the server's — send whole\n // frames until it is level again. The shell is untouched.\n resync: (connection: Connection) => void;\n dispatch: (canvas: string, event: Record<string, unknown>) => void;\n publish: (channel: string, payload?: unknown) => void;\n // Undo the shell's last navigation (nova's journal — see its `back`). Nothing\n // is sent in answer: the shell's own state change flushes the canvases that\n // moved, which is how every other change reaches a terminal. `false` when\n // there was nothing left to undo — the answer a landing screen gives.\n back: () => boolean;\n // Unmount everything above `instance` on `canvas` — the breadcrumb's jump,\n // done in one step by the shell that owns the stack.\n popTo: (canvas: string, instance: string) => void;\n // Throw this shell away and build its replacement, carrying every attached\n // connection across. The session object stays valid; the terminals receive a\n // fresh frame and current trees, exactly as on (re)attach.\n reset: () => void;\n};\n\n// One living shell, as an operator needs to see it. Structural facts only —\n// who holds it, how many terminals are attached, how long it has been there,\n// and the action ids on its canvases. Naming the principal is the app's job.\nexport type ShellReport = {\n principal: string;\n // terminals attached right now\n connections: number;\n // when this shell was BUILT — a reset moves it, because what stands after a\n // reset is a new shell\n since: number;\n // when the last connection detached; null while one is attached\n idleSince: number | null;\n // canvases with anything mounted, top of stack first\n canvases: { id: string; actions: readonly string[] }[];\n};\n\n// What a terminal would be sent on attach, as one value: the frame and every\n// canvas's current tree. A DOCUMENT is rendered from it (server-side, with the\n// app's kit) and carries it, so the terminal starts from the screen the page\n// already shows instead of from nothing.\nexport type ShellSnapshot = {\n frame: RenderNode[];\n trees: Record<string, RenderNode[]>;\n // Set for an anonymous snapshot: the id seed its shell was built under. The\n // terminal names it on the socket (`?seed=`), the throwaway shell built for\n // that connection mints the same ids, and the first frames match the page.\n seed?: string;\n // False when the wait ran out with something still loading — the snapshot is\n // then the screen as it stood (its skeletons included), which is still a\n // screen and still correct.\n settled: boolean;\n // WHETHER ANYTHING ON THIS SCREEN CAN STILL HAPPEN (./liveness), asked of the\n // actions actually mounted for whoever this is. False: the trees are the whole\n // of it, and a terminal has no reason to open a socket. `why` says what makes\n // it live, one line per reason; `drawnWith` names the reads whose answers are\n // already in the trees.\n live: boolean;\n why: string[];\n drawnWith: string[];\n};\n\n// What a session or a snapshot may be given beside who it is for.\nexport type ShellOpening = {\n // Build an ephemeral shell under this id seed (see ShellSnapshot.seed).\n seed?: string;\n // Input for canvas seeds, by canvas id — merged over the manifest's own\n // `inputs`. A page's path parameters arrive here.\n inputs?: Record<string, Record<string, unknown>>;\n};\n\nexport type ShellHost = {\n // `options.seed`: build an EPHEMERAL session's shell under this id seed (see\n // ShellSnapshot). Ignored for a kept shell — it is durable, and the one a\n // document was rendered from is the one the socket attaches to.\n session: (token: string | null, principal: string | null, options?: ShellOpening) => Promise<ShellSession>;\n // The current screen for whoever this is, without attaching anything. A\n // principal's durable shell is built if it is not standing (the socket would\n // have built it a moment later) and kept; an anonymous one is built, read and\n // disposed. Waits for the screen to settle — `seeds` pushed, no instance\n // still mounting — for at most `waitMs`, then serves what is there.\n snapshot: (token: string | null, principal: string | null, options?: { waitMs?: number; inputs?: ShellOpening['inputs'] }) => Promise<ShellSnapshot>;\n // Artifacts changed (the app mutated its `actions`, the server dropped its\n // memos): every LIVING durable shell adopts its freshly-resolved granted\n // definitions in place — nova's registerAction adds or replaces, mounted\n // instances keep their state, and new actions become pushable without a\n // rebuild. Ring 1 is re-applied per principal; ring 2 substitutes exactly\n // as at build.\n adopt: () => void;\n // Publish a message into one principal's LIVE durable shell — the push half\n // of the socket the shells already run. Whatever action is mounted and\n // listening on the channel reacts, re-renders, and the change fans out to\n // every attached terminal over the existing wire. `false` when they hold no\n // living shell, which is an answer, not an error: offline people read the\n // rows later. Nothing here builds a shell.\n deliver: (principal: string, channel: string, payload?: unknown) => boolean;\n // Every durable shell alive right now. The honest roster: moss owns the map,\n // so moss is the only thing that can enumerate it without keeping a\n // second, drifting note beside it.\n list: () => ShellReport[];\n // Reset one principal's durable shell. `false` if they hold none — which is\n // not an error, it is the answer to \"is Rosa's shell stuck?\" when Rosa is\n // not connected. Anonymous shells are not addressable here (they are\n // per-connection and die on detach); a terminal resets its own via the\n // session's `reset`.\n reset: (principal: string) => boolean;\n // Stop the idle sweep. For hosts that outlive their server (dev checks,\n // embedded tools); the timer is unref'd, so a plain process needn't call it.\n stop: () => void;\n};\n\n// A shell nobody has been attached to for half an hour is a warm cache with no\n// reader. Rebuilding costs one derivation pass on the next connect.\nexport const DEFAULT_IDLE_MS = 30 * 60 * 1000;\n\n// The sweep never runs less often than this, so a short `idleMs` is honoured\n// closely and a long one doesn't cost a wakeup per minute.\nconst SWEEP_EVERY_MS = 60 * 1000;\n\nconst today = (): string => new Date().toISOString().slice(0, 10);\n\n// Each in-process function wrapped to emit one `fn.call` span — the fn name,\n// principal presence, duration, and whether it threw. The in-process dispatch\n// is where server functions run today (`/fns`, the URL layer, is still\n// unbuilt); a service written against either is observed the same way. Built\n// only when a sink is present (the caller guards), so an unobserved session\n// pays nothing per call. The span names the function, never its data.\nexport const instrumentFunctions = (\n fns: Record<string, FunctionHandler>,\n emit: Emit,\n principal: string | null,\n): Record<string, FunctionHandler> =>\n Object.fromEntries(\n Object.entries(fns).map(([name, handler]): [string, FunctionHandler] => [\n name,\n async (data, signal) => {\n const clock = spanClock();\n const hasPrincipal = principal !== null;\n try {\n const out = await handler(data, signal);\n emit({ name: 'fn.call', startUnixNano: clock.startUnixNano, endUnixNano: clock.endUnixNano(), status: 'ok', attributes: { fn: name, hasPrincipal } });\n return out;\n } catch (err) {\n emit({ name: 'fn.call', startUnixNano: clock.startUnixNano, endUnixNano: clock.endUnixNano(), status: 'error', attributes: { fn: name, hasPrincipal } });\n throw err;\n }\n },\n ]),\n );\n\nexport const createShellHost = (ctx: ShellHostContext): ShellHost => {\n // The deployment's telemetry sink, if any — read off the runtime this host\n // already carries, so no signature grows. `undefined` when unset, which the\n // build and dispatch sites guard on.\n const emit = emitterOf(ctx.runtime.telemetry);\n const manifest = ctx.manifest ?? ctx.app.shell;\n if (manifest === undefined) throw new Error('createShellHost: the app manifest has no `shell`.');\n const shellManifest = manifest;\n const kept = ctx.kept ?? true;\n\n // Every component NAME the app's layouts mention — nova's registry holds\n // opaque components (generic, unknown), so the server registers name-only\n // stubs: the render pipeline validates names and serializes trees; actual\n // components live in the terminal. `componentsOf` (nova/reflect) is the one\n // walk; no component list is ever authored. nova's own slot markers come\n // from default layouts, not the app's, so the walk can't find them — seed\n // them first.\n const componentNames = new Set<string>([CANVAS_SLOT_NAME, ACTION_SLOT_NAME]);\n for (const source of [ctx.app.actions, ctx.app.layouts ?? {}, shellManifest.canvases, shellManifest.layout ?? {}, shellManifest.layoutStore ?? {}, shellManifest.fragments ?? {}]) {\n for (const name of componentsOf(source)) componentNames.add(name);\n }\n // Declared contracts register even when no authored layout mentions them\n // (generated layouts may name them; the palette must see them).\n const contracts = shellManifest.components ?? {};\n for (const name of Object.keys(contracts)) componentNames.add(name);\n\n type Live = {\n shell: Shell;\n connections: Set<Connection>;\n // last frame per canvas — only changes are sent\n sent: Map<string, string>;\n // last FRAME (the arrangement) sent to the set — the frame's own `sent`\n // baseline, so a `setLayout` re-sends it only when it actually changed.\n sentFrame?: string;\n // Connections that asked for deltas at attach. Every connection is level\n // with `sent` (attach hands a newcomer the current frames, and a change\n // fans out to all of them), so one baseline serves the whole set — but a\n // connection that has NOT asked still gets whole frames from the same pass.\n deltaReady: Set<Connection>;\n flushing: boolean;\n // set when the session ends (sign-out, reset, eviction) — pending flush\n // passes must not render a disposed shell\n ended: boolean;\n // built at; and when the last connection left (null while attached)\n since: number;\n idleSince: number | null;\n // Resolves when the manifest's `seeds` have been pushed (at once when there\n // are none). A snapshot waits on it: seeds land a tick after the build, and\n // a document rendered before them would be missing the screen's cards.\n seeded: Promise<void>;\n };\n\n // The indirection `reset` needs. A session, a socket and the durable map all\n // address a principal's shell through ONE mutable cell, so replacing the\n // shell reaches every holder at once and nobody is left pointing at a\n // disposed one. The token is kept beside it because a rebuild has to\n // re-authorize the server's own wire as the same session, and it is\n // refreshed on reattach so a rebuild uses the newest one the principal\n // arrived with rather than the one they first appeared with.\n type Cell = { live: Live; token: string | null; principal: string | null; roles: readonly string[]; installed: readonly string[] | undefined; hash: string };\n\n // No visible content = empty tree over the wire, so a terminal collapses chrome\n // on `length` alone. The rule is nova's (`canvasTreeOf`): a canvas is handed to\n // an adapter the same way whether it is served from here or lives beside it.\n\n // Flatten, then serialize. No language step here any more: the shell was\n // built with its book, and nova applies it where a RenderNode is minted, so\n // what comes out of `getCanvasRenderTree` is already in the reader's\n // language. Everything downstream — the delta encoder, the socket, the\n // terminal — is handed a finished frame and never learns a language was\n // involved, exactly as before; there is simply one fewer walk to get there.\n const treeOf = (live: Live, canvasId: string): RenderNode[] => canvasTreeOf(live.shell, canvasId);\n\n const frame = (live: Live, canvasId: string): string => {\n const message: ServerMessage = { type: 'render', canvas: canvasId, tree: treeOf(live, canvasId) };\n return JSON.stringify(message);\n };\n\n // A canvas whose tree throws while rendering must not take the session with\n // it. Unguarded, one bad tree killed the entire flush pass: every canvas\n // after it never rendered, the throw escaped a microtask with nobody to\n // catch it, and — because `sent` was never updated for the canvas that threw\n // — every later pass hit the same node again. That is a shell wedged for the\n // life of the process, and no reconnect could clear it, since reattaching a\n // durable shell finds the same wreck. Now the failing canvas holds its last\n // good tree, its neighbours keep rendering, and `reset` is the way out.\n const frameOf = (live: Live, canvasId: string): string | null => {\n try {\n return frame(live, canvasId);\n } catch (error) {\n console.error(`[moss/shells] canvas \"${canvasId}\" failed to render — holding its last tree:`, error);\n return null;\n }\n };\n\n const delta = ctx.delta ?? false;\n\n // A delta is only worth sending when it is DECISIVELY smaller. The transport\n // compresses whatever it is handed, and a delta that saves 20% of the bytes\n // saves nothing once both go through deflate — while still costing the\n // terminal a rebuild and a checksum. Measured on Lyra: an in-place update\n // (keystroke, one row's badge) lands at 1–4% and is far under this; a\n // navigation lands near 80% and is deliberately left whole.\n const DELTA_CEILING = 0.6;\n\n // And only between frames small enough to be worth comparing. The encode's\n // cost follows the size of the frames, not of the change, and it is paid on\n // the thread every session shares: about 7 ms for an in-place change at\n // 64 KB, a second at 2.7 MB, and at 20 MB eight seconds and a gigabyte to\n // fail and send the frame whole anyway. Past this length — of the frame the\n // connections hold, or of the one replacing it — the answer is \"whole\"\n // before anything is spent on finding out.\n const DELTA_MAX_FRAME = 64 * 1024;\n\n // The delta message, or null to send the frame whole. Never throws: a frame\n // failing to encode is a reason to fall back, not a reason to lose the frame.\n const shorterAsDelta = (previous: string, next: string, canvasId: string): string | null => {\n if (previous.length > DELTA_MAX_FRAME || next.length > DELTA_MAX_FRAME) return null;\n try {\n const ops = encodeDelta(previous, next);\n const message: ServerMessage = { type: 'render-delta', canvas: canvasId, ops, hash: frameHash(next) };\n const text = JSON.stringify(message);\n return text.length <= next.length * DELTA_CEILING ? text : null;\n } catch (error) {\n console.error(`[moss/shells] canvas \"${canvasId}\" failed to encode as a delta — sending it whole:`, error);\n return null;\n }\n };\n\n const durable = new Map<string, Cell>(); // principal → the one living shell\n\n const build = async (token: string | null, principal: string | null, reset = false, idSeed?: string, given?: ShellOpening['inputs']): Promise<Live> => {\n const buildClock = emit === undefined ? undefined : spanClock();\n const who = await ctx.resolve(principal);\n const { ids } = who.catalog;\n const granted = new Set(ids);\n const bindings = who.variants;\n // ASYNC AND WIRE-BEARING, matching `seeds`. This file's own manifest called\n // the two twins while handing one the governed wire and not the other, and\n // that asymmetry is the whole origin of the resident directory: a hook that\n // cannot await, asked a question about rows, has exactly one implementation\n // available to it.\n const inputs = (await shellManifest.inputs?.({ principal, actions: ids, roles: who.roles, identity: who.scope, wire: ctx.wire(token) })) ?? {};\n\n // Canvases are data; mounting is derivation: of the declared seed (or\n // CANDIDATE list) the first action the principal holds mounts — none\n // held, nothing mounts. Per-principal inputs merge over the static seed.\n const canvases: CanvasConfig[] = shellManifest.canvases.map((canvas) => {\n const declared = canvas.initial;\n const candidates = declared === undefined ? [] : Array.isArray(declared) ? declared : [declared];\n const seed = candidates.find((c) => granted.has(typeof c === 'string' ? c : c.action));\n if (seed === undefined) {\n const { initial: _dropped, ...rest } = canvas;\n return rest;\n }\n const action = typeof seed === 'string' ? seed : seed.action;\n const staticInput = typeof seed === 'string' ? {} : (seed.input ?? {});\n const withFragments = typeof seed === 'string' ? undefined : seed.with;\n return {\n ...canvas,\n initial: { action, input: { ...staticInput, ...(inputs[canvas.id] ?? {}), ...(given?.[canvas.id] ?? {}) }, ...(withFragments !== undefined ? { with: withFragments } : {}) },\n };\n });\n\n const wire = flooredWire(ctx.wire(token));\n const userId = principal ?? 'anonymous';\n\n const registry = createComponentRegistry();\n for (const name of componentNames) registry.register(name, (contracts[name] ?? {}) as Parameters<typeof registry.register>[1]);\n\n // The manifest's in-process functions, built for THIS session — the\n // shell and the live connection set land in the closures just after\n // creation (a function that somehow runs before then fails loudly).\n let built: Shell | undefined;\n let liveRef: Live | undefined;\n const session: FunctionSession = {\n principal,\n roles: who.roles,\n identity: who.scope,\n actions: ids,\n wire,\n runtime: ctx.runtime,\n policy: who.policy,\n get shell(): Shell {\n if (built === undefined) throw new Error('moss: a function touched the shell before the session finished building.');\n return built;\n },\n // GRANT: the minted token to every terminal of this session — they\n // reconnect as the new principal; this (anonymous) session stays\n // ephemeral and dies on detach.\n grant: (token) => {\n const message = JSON.stringify({ type: 'session', token } satisfies ServerMessage);\n for (const connection of liveRef?.connections ?? []) {\n if (connection.seal === undefined) connection.send(message);\n // its browser keeps the session: sealed, so the page that carries it back cannot open it (socket.ts)\n else {\n void connection.seal(token).then(\n (sealed) => connection.send(JSON.stringify({ type: 'session', sealed } satisfies ServerMessage)),\n (error: unknown) => console.error('[moss] a sign-in could not be sealed, and was not handed over:', error),\n );\n }\n }\n },\n // REVOKE: forget the credential, close every terminal SIGNED_OUT,\n // evict the durable shell. Under moss's own credential the rows go\n // first — closing the terminals clears the tokens THEY held, not a\n // copy anywhere else. The shell is the principal's and every one of\n // its terminals closes, so every session the principal holds is\n // deleted, not only the one this shell was built with. A custom\n // verifier's credential is the app's to revoke; 'dev-open' stores\n // none. The teardown is deferred a microtask so the calling trigger\n // finishes before its own shell is disposed.\n revoke: () => {\n const forgotten = ctx.runtime.session === 'sessions' && principal !== null ? revokeAllFor(ctx.runtime.pool, principal) : Promise.resolve();\n // Loud when it fails — a sign-out that left the credential alive is\n // a security fault, not a detail — and never an unhandled rejection\n // for a caller that did not await it. A caller that does still sees\n // the failure.\n forgotten.catch((error: unknown) => console.error(`[moss] sign-out of ${principal ?? 'anonymous'} did not revoke its sessions:`, error));\n queueMicrotask(() => {\n if (liveRef === undefined) return;\n liveRef.ended = true;\n // Only if the map still holds THIS shell — a reset between the\n // sign-out and this microtask has already replaced it, and the\n // replacement belongs to whoever caused it.\n if (principal !== null && durable.get(principal)?.live === liveRef) durable.delete(principal);\n for (const connection of [...liveRef.connections]) connection.close(CLOSE_SIGNED_OUT, 'signed out');\n liveRef.connections.clear();\n if (principal !== null) liveRef.shell.dispose();\n });\n return forgotten;\n },\n // The session's own fields are stamped here so a caller cannot get them\n // wrong, and the shell id is read lazily — a run cannot happen before\n // the shell exists, but this object is built before it does.\n recordRun: (run) => {\n if (ctx.app.runs === undefined) return;\n ctx.app.runs({ ...run, at: Date.now(), principal, shellId: built?.id ?? '' }, session);\n },\n };\n\n // THE WORDS THIS SHELL WEARS, resolved before it exists — because they are\n // a property of the shell now, not of the frames it emits. Nova's renderer\n // applies them where a RenderNode is minted, so moss hands the book over\n // once and never touches a tree again.\n //\n // Resolved with the rest of the per-principal derivation. A principal whose\n // language changes gets a `rebuild`, which re-reads this alongside their\n // catalog and inputs — one path, so a language can never be a release\n // behind the screen it is painting.\n const phrases = (await ctx.app.phrases?.({ principal, identity: who.scope, wire: ctx.wire(token) })) ?? {};\n\n // NOTHING AWAITS BETWEEN THESE SEAMS AND `built = shell`. Both run before\n // the shell exists, so app code defers its first touch of `session.shell`\n // — and the cheapest deferral, a microtask, has to be enough: it is the\n // only one that lands before the shell's mount calls answer, so it is the\n // only one an observer (`shell.onEndpoint`) can use without missing them.\n // The phrases used to be awaited right here, after `onSession`; a\n // microtask landed inside that await, the getter threw, and an observer\n // written to the documented contract watched nothing. Every await of this\n // build belongs above this line or below the shell.\n //\n // Endpoints first, then the non-endpoints. Both get the same session; only\n // the first produces handlers. Wrapped for telemetry when a sink is present\n // — one `fn.call` span per invocation, transparently to the handler.\n const rawFunctions = ctx.app.functions?.(session) ?? {};\n const functions = emit === undefined ? rawFunctions : instrumentFunctions(rawFunctions, emit, principal);\n // Session code is the app's: it rides the shell that is kept. A page's shell\n // lives for one read or one connection and runs none.\n if (kept) ctx.app.onSession?.(session);\n\n // THE FRAME'S LAYOUT STORE, seeded from the manifest so a `{ ref }` in the\n // frame resolves at the FIRST render — before any `setLayout`. A malformed\n // seed throws here (store.set validates), failing this build closed and\n // named, exactly as a bad definition does; the socket refuses this terminal\n // and the process stays up.\n const layoutStore = createLayoutStore();\n for (const [refId, node] of Object.entries(shellManifest.layoutStore ?? {})) layoutStore.set(refId, node);\n\n // A SEEDED shell mints its instance ids in order under the seed, so two\n // builds from one seed name their instances alike: the shell a document was\n // rendered from, and the throwaway one the socket builds a moment later for\n // the same anonymous visitor. The seed is random per document, so ids stay\n // unguessable and a stale origin from another shell still names nothing.\n let minted = 0;\n const shell = createShell({\n registry,\n canvases,\n layoutStore,\n ...(idSeed === undefined ? {} : { instanceIdFn: () => `act-${idSeed}-${(minted += 1)}` }),\n ...(shellManifest.layout !== undefined ? { canvasLayout: shellManifest.layout } : {}),\n // Ring 1 then ring 2: an ungranted action doesn't exist; a granted one\n // carries the principal's variant layout when they hold one — the swap\n // happens on the definition, before the shell exists, so everything\n // downstream (render, serialize, the wire) is already per-principal.\n actions: Object.fromEntries(\n Object.entries(ctx.app.actions)\n .filter(([id]) => granted.has(id))\n .map(([id, definition]) => {\n const layout = bindings.get(id);\n return [id, layout === undefined ? definition : { ...definition, layout }];\n }),\n ),\n ...(shellManifest.fragments !== undefined ? { fragments: shellManifest.fragments } : {}),\n // The same seam the client shell used: prism evaluates endpoint\n // request/response transforms; `$.userId` and `$.today` are ambient,\n // never authorable by a request. The config is the action's own object\n // on every call, so evaluate checks it once (the source is new each time).\n transform: (config, source) =>\n evaluate(config, source !== null && typeof source === 'object' && !Array.isArray(source) ? { ...source, userId, today: today() } : source),\n fetch: wire,\n functions,\n ...(ctx.runtime.endpointTimeoutMs === undefined ? {} : { endpointTimeoutMs: ctx.runtime.endpointTimeoutMs }),\n // An EMPTY book is withheld rather than passed: the pass is active when\n // either of these is present, and an app that does no i18n at all should\n // not pay a matcher per render for a dictionary with nothing in it.\n // `phraseKeys` alone is the source language, which still fills counted\n // phrases — the one job that survives having nothing to translate.\n ...(Object.keys(phrases).length === 0 ? {} : { phrases }),\n ...(ctx.app.phraseKeys === undefined ? {} : { phraseKeys: ctx.app.phraseKeys }),\n });\n built = shell;\n\n // Born idle: a shell exists before anything attaches to it, and a shell\n // nothing ever attaches to is exactly what the sweep should collect.\n const live: Live = { shell, connections: new Set(), sent: new Map(), deltaReady: new Set(), flushing: false, ended: false, since: Date.now(), idleSince: Date.now(), seeded: Promise.resolve() };\n liveRef = live;\n\n // Per-principal canvas SEEDING — the instance twin of `inputs`. The app\n // derives which actions to push where (usually from resolved rows over\n // the session's own wire), moss pushes them in order: ring 1 filters\n // exactly as `initial` does, an unknown action or canvas skips rather\n // than kills the session, and seeds landing after attach simply render —\n // the same progressive path every later push takes.\n const declaredSeeds = shellManifest.seeds?.({ principal, actions: ids, roles: who.roles, wire });\n if (declaredSeeds !== undefined) {\n live.seeded = Promise.resolve(declaredSeeds)\n .then((byCanvas) => {\n if (live.ended) return;\n for (const [canvasId, seeds] of Object.entries(byCanvas ?? {})) {\n for (const seed of seeds) {\n const action = typeof seed === 'string' ? seed : seed.action;\n if (!granted.has(action)) continue;\n const input = typeof seed === 'string' ? undefined : seed.input;\n const withFragments = typeof seed === 'string' ? undefined : seed.with;\n try {\n // NOT A NAVIGATION. A seed is the screen this principal arrives\n // on, derived a tick late because it had to be read; `back`\n // undoing it would empty the canvas somebody just landed on.\n shell.push(canvasId, action, input, withFragments, { history: false });\n } catch {\n // an unknown canvas or definition is a skipped seed, not a\n // dead session\n }\n }\n }\n })\n .catch(() => {\n // a failed derivation seeds nothing — the canvas stays empty and\n // the rest of the shell is untouched\n });\n }\n\n // Any state or data change → re-render, send what changed, to every\n // attached connection. Microtask-coalesced, with one trailing pass a\n // tick later: some transitions (instance status settling after its\n // loads) land AFTER the last notification, and the trailing pass\n // catches the settled tree.\n const pass = (): void => {\n if (live.ended) return;\n for (const canvas of shellManifest.canvases) {\n const next = frameOf(live, canvas.id);\n const previous = live.sent.get(canvas.id);\n if (next === null || previous === next) continue;\n live.sent.set(canvas.id, next);\n // Encoded ONCE for the whole set: every connection holds `sent`, so\n // they share a baseline and therefore a delta.\n const short = delta && previous !== undefined && live.deltaReady.size > 0 ? shorterAsDelta(previous, next, canvas.id) : null;\n for (const connection of live.connections) {\n connection.send(short !== null && live.deltaReady.has(connection) ? short : next);\n }\n }\n // THE FRAME too — re-rendered and diffed like a canvas, so a `setLayout`\n // (or `setCanvasLayout`) that changes the arrangement reaches every\n // attached terminal, not only the next one to attach. Sent AFTER the\n // canvases, so a frame that references a canvas seeded this same pass finds\n // its tree already delivered. Guarded like attach: a frame that fails to\n // render leaves the last one standing rather than taking the pass down.\n let frame: string | undefined;\n try {\n frame = JSON.stringify({ type: 'frame', tree: live.shell.getShellRenderTree() } satisfies ServerMessage);\n } catch (error) {\n console.error('[moss/shells] the shell frame failed to render on a flush — leaving the last one in place:', error);\n }\n if (frame !== undefined && frame !== live.sentFrame) {\n live.sentFrame = frame;\n for (const connection of live.connections) connection.send(frame);\n }\n };\n const flush = (): void => {\n if (live.flushing) return;\n live.flushing = true;\n queueMicrotask(() => {\n live.flushing = false;\n pass();\n setTimeout(pass, 0);\n });\n };\n shell.onStateChange(flush);\n shell.onDataChange(flush);\n\n // Built — the per-principal derivation, inputs, phrases and shell all stood\n // up. `reset` distinguishes a recovery rebuild from a first build; residency\n // and eviction counts come from the identity/shell meters, not from here.\n if (emit !== undefined && buildClock !== undefined) {\n emit({ name: 'shell.build', startUnixNano: buildClock.startUnixNano, endUnixNano: buildClock.endUnixNano(), status: 'ok', attributes: { reset, hasPrincipal: principal !== null } });\n }\n\n return live;\n };\n\n // (Re)attach: the frame first — the canvas arrangement, CanvasSlot markers\n // the terminal resolves — then every canvas's current tree, no replay\n // machinery. Both are guarded, because the one moment a terminal MOST needs\n // to be served is when the shell it is attaching to is the broken one: a\n // throw here would leave the connection open with nothing on it, which is\n // the failure that has no diagnosis.\n const attach = (live: Live, connection: Connection, options?: { delta?: boolean }): void => {\n live.connections.add(connection);\n if (delta && options?.delta === true) live.deltaReady.add(connection);\n live.idleSince = null;\n let frameTree: RenderNode[] = [];\n try {\n // The arrangement carries words too — a canvas's own chrome, a Sheet's\n // title — and gets them from the same place: the shell it was rendered by.\n frameTree = live.shell.getShellRenderTree();\n } catch (error) {\n console.error('[moss/shells] the shell frame failed to render — serving an empty arrangement:', error);\n }\n // The newcomer joins the frame's shared baseline the same way it joins each\n // canvas's below — so the next flush re-sends the frame only if it changes.\n const frameMessage = JSON.stringify({ type: 'frame', tree: frameTree } satisfies ServerMessage);\n connection.send(frameMessage);\n live.sentFrame = frameMessage;\n for (const canvas of shellManifest.canvases) {\n const next = frameOf(live, canvas.id);\n if (next === null) continue;\n // Attaching RENDERS, and rendering can pick up a change the flush pass\n // has not sent yet — `sent` would then move to a frame only the newcomer\n // holds, and the next pass would skip it as unchanged, leaving everyone\n // else stale. So the newcomer's frame is the whole room's frame. Deltas\n // depend on this being true: one baseline, or the encode is a lie.\n if (live.sent.get(canvas.id) !== next) {\n for (const other of live.connections) if (other !== connection) other.send(next);\n }\n live.sent.set(canvas.id, next);\n connection.send(next);\n }\n };\n\n // Dispose a shell and stand its replacement in the same cell, carrying the\n // attached connections across. Everything a shell is derived from — the\n // catalog, the variants, `inputs`, `seeds` — is re-read by `build`, so what\n // comes back is the screen boot would have served this principal now. The\n // terminals are not told anything: they receive a frame and current trees,\n // the same two messages a reconnect brings.\n // ASYNC, and its callers deliberately do not await it. `reset` answers \"did\n // they hold a shell\", which is knowable at once; the replacement lands a tick\n // later and every attached terminal receives a fresh frame when it does —\n // exactly as `seeds` already behaves. A reset that blocked its caller on a\n // round trip would make a role change slower than the write that caused it.\n const rebuild = async (cell: Cell): Promise<void> => {\n const old = cell.live;\n // The replacement is built BEFORE the old one is torn down. `build` runs\n // app code — `inputs`, `functions`, `onSession` — and if that throws, a\n // reset that had already disposed the old shell would leave the session\n // holding nothing at all: strictly worse than the wedged shell it was\n // called to fix. Built first, a failed reset changes nothing.\n const next = await build(cell.token, cell.principal, true);\n const carried = [...old.connections].map((connection) => ({ connection, delta: old.deltaReady.has(connection) }));\n old.ended = true;\n old.connections.clear();\n old.shell.dispose();\n cell.live = next;\n for (const { connection, delta: wants } of carried) attach(next, connection, { delta: wants });\n };\n\n const sessionOn = (cell: Cell, ephemeral: boolean): ShellSession => ({\n // Read through the cell, always: after a reset the shell behind this\n // session is a different object.\n get shell(): Shell {\n return cell.live.shell;\n },\n attach: (connection, options) => attach(cell.live, connection, options),\n // Whole frames for this one connection — the state both ends can always\n // agree on. It stays delta-capable: it is level with `sent` again the\n // moment this returns, and the checksum will catch it if it is not.\n resync: (connection) => {\n const live = cell.live;\n if (!live.connections.has(connection)) return;\n let frameTree: RenderNode[] = [];\n try {\n frameTree = live.shell.getShellRenderTree();\n } catch (error) {\n console.error('[moss/shells] the shell frame failed to render on resync — serving an empty arrangement:', error);\n }\n connection.send(JSON.stringify({ type: 'frame', tree: frameTree } satisfies ServerMessage));\n for (const canvas of shellManifest.canvases) {\n const current = live.sent.get(canvas.id) ?? frameOf(live, canvas.id);\n if (current === null || current === undefined) continue;\n connection.send(current);\n }\n },\n detach: (connection) => {\n const live = cell.live;\n live.connections.delete(connection);\n live.deltaReady.delete(connection);\n if (live.connections.size > 0) return;\n live.idleSince = Date.now();\n if (!ephemeral) return;\n live.ended = true;\n live.shell.dispose();\n },\n // Transport → shell addressing: the wire tags the canvas, and nova's own\n // origin filter delivers the event to one instance's triggers alone.\n //\n // A terminal NAMES the instance when it knows it — a list canvas renders\n // several live cards, and the ActionSlot around the press says which. That\n // claim comes off the wire, so it is held to the canvas the event is\n // tagged with: an instance that is not on it (gone since the render, or on\n // another canvas altogether) drops the event — firing it anywhere else\n // would run triggers the person never pressed. With no claim, the canvas's\n // ACTIVE instance is the origin: on a card deck that is the only one\n // rendered. A canvas with nothing mounted dispatches unstamped (global).\n dispatch: (canvas, event) => {\n const { shell } = cell.live;\n const state = shell.getState().canvases[canvas];\n const claimed = event['origin'];\n if (claimed !== undefined) {\n if (typeof claimed !== 'string' || !(state?.stack ?? []).some((item) => item.id === claimed)) return;\n shell.dispatch(event as Parameters<Shell['dispatch']>[0]);\n return;\n }\n const active = state?.active;\n shell.dispatch((active === undefined ? event : { ...event, origin: active.id }) as Parameters<Shell['dispatch']>[0]);\n },\n publish: (channel, payload) => cell.live.shell.publish(channel, payload),\n back: () => cell.live.shell.back(),\n popTo: (canvas: string, instance: string) => cell.live.shell.popTo(canvas, instance),\n reset: () => void rebuild(cell).catch((err: unknown) => console.error('[moss/shells] a reset failed to rebuild', err)),\n });\n\n // ── the document's read ──\n // SETTLED: the seeds are in and nothing is still mounting. nova marks an\n // instance `active` only after its mount hook — the loads and their\n // onSuccess chains — has been awaited, so no instance `initializing` is the\n // shell saying its first screen is whole. A mount can push another action,\n // which starts `initializing` in turn, so the question is asked again on\n // every state change, and answered true only when it holds a macrotask later.\n const settle = async (live: Live, waitMs: number): Promise<boolean> => {\n const started = Date.now();\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(false), waitMs);\n });\n // The seeds are moss's (the manifest's `seeds` hook); the rest of the\n // question — is anything still mounting — is nova's, asked with what is left\n // of the wait.\n const whole = live.seeded.then(() => shellSettled(live.shell, { waitMs: Math.max(0, waitMs - (Date.now() - started)), stopped: () => live.ended }));\n const settled = await Promise.race([whole, deadline]);\n clearTimeout(timer);\n return settled;\n };\n\n // Read-only: `sent` is not touched, so the connections already attached keep\n // their baseline and a snapshot can never make a flush skip a frame.\n const read = (live: Live): Pick<ShellSnapshot, 'frame' | 'trees'> => {\n let frameTree: RenderNode[] = [];\n try {\n frameTree = live.shell.getShellRenderTree();\n } catch (error) {\n console.error('[moss/shells] the shell frame failed to render for a snapshot — serving an empty arrangement:', error);\n }\n const trees: Record<string, RenderNode[]> = {};\n for (const canvas of shellManifest.canvases) {\n try {\n trees[canvas.id] = treeOf(live, canvas.id);\n } catch (error) {\n console.error(`[moss/shells] canvas \"${canvas.id}\" failed to render for a snapshot — leaving it out:`, error);\n }\n }\n return { frame: frameTree, trees };\n };\n\n // Asked of the instances ON SCREEN, not of the catalog: what a screen needs is\n // a fact about what mounted for this principal, composed definitions included.\n const needOf = (live: Live, principal: string | null): Pick<ShellSnapshot, 'live' | 'why' | 'drawnWith'> => {\n const why: string[] = [];\n const drawnWith: string[] = [];\n const ask = ctx.needOf;\n if (ask === undefined) return { live: true, why: ['this host was given no way to ask what its actions need'], drawnWith };\n // The app's shell IS the thing that stays: whoever is signed in has one.\n if (kept && principal !== null) why.push('the app’s shell is kept for whoever is signed in');\n for (const canvas of Object.values(live.shell.getState().canvases)) {\n for (const instance of canvas.stack) {\n const definition = live.shell.getRuntime(instance.id)?.definition;\n if (definition === undefined) continue;\n const need = ask(definition);\n for (const reason of need.why) why.push(`${definition.id}: ${reason}`);\n for (const read of need.drawnWith) drawnWith.push(read);\n }\n }\n return { live: why.length > 0, why, drawnWith };\n };\n\n // A document should not wait on a slow integration: past this the page ships\n // with whatever is still loading drawn as loading.\n const DEFAULT_SNAPSHOT_WAIT_MS = 300;\n\n const durableCell = async (token: string | null, principal: string): Promise<Cell> => {\n const existing = durable.get(principal);\n if (existing !== undefined) {\n existing.token = token; // a rebuild should re-authorize as the newest session\n return existing;\n }\n const who = await ctx.resolve(principal);\n const cell: Cell = { live: await build(token, principal), token, principal, roles: who.roles, installed: who.installed, hash: who.catalog.hash };\n durable.set(principal, cell);\n return cell;\n };\n\n // ── the idle sweep ──\n // A durable shell with nothing attached for `idleMs` is disposed. Safe by\n // the same argument that makes a process restart safe (DESIGN.md § The\n // socket, Durability): the\n // database is durable, a shell is a warm cache, and the next connection\n // rebuilds it from definitions and rows. The clock is the IDLE one — a shell\n // somebody is looking at is never collected, however old.\n const idleMs = ctx.idleMs ?? DEFAULT_IDLE_MS;\n\n const sweep = (): void => {\n const now = Date.now();\n for (const [principal, cell] of [...durable]) {\n const live = cell.live;\n if (live.ended) {\n durable.delete(principal);\n continue;\n }\n if (live.connections.size > 0 || live.idleSince === null) continue;\n if (now - live.idleSince < idleMs) continue;\n live.ended = true;\n live.shell.dispose();\n durable.delete(principal);\n }\n };\n\n let sweeper: ReturnType<typeof setInterval> | undefined;\n if (idleMs > 0 && Number.isFinite(idleMs)) {\n sweeper = setInterval(sweep, Math.min(idleMs, SWEEP_EVERY_MS));\n // The sweep must never be the reason a process stays alive.\n (sweeper as unknown as { unref?: () => void }).unref?.();\n }\n\n return {\n session: async (token, principal, options) => {\n if (principal === null || !kept) {\n const who = await ctx.resolve(principal);\n return sessionOn({ live: await build(token, principal, false, options?.seed, options?.inputs), token, principal, roles: who.roles, installed: who.installed, hash: who.catalog.hash }, true);\n }\n return sessionOn(await durableCell(token, principal), false);\n },\n snapshot: async (token, principal, options) => {\n const waitMs = options?.waitMs ?? DEFAULT_SNAPSHOT_WAIT_MS;\n if (principal !== null && kept) {\n const cell = await durableCell(token, principal);\n const settled = await settle(cell.live, waitMs);\n return { ...read(cell.live), settled, ...needOf(cell.live, principal) };\n }\n // Nobody in particular, or a page: a shell for the length of one read.\n const seed = randomBytes(9).toString('hex');\n const live = await build(token, principal, false, seed, options?.inputs);\n try {\n const settled = await settle(live, waitMs);\n return { ...read(live), seed, settled, ...needOf(live, principal) };\n } finally {\n live.ended = true;\n live.shell.dispose();\n }\n },\n // RE-RESOLVED, not re-read off the cell. Adopting happens because something\n // the derivations were made FROM changed, and the commonest such change is a\n // tenant installing an integration — so the install list a shell was born with is\n // exactly the thing that must not be trusted here. Asynchronous and\n // unawaited: definitions landing a tick late simply register, which is the\n // same progressive path `seeds` already takes.\n adopt: () => {\n void (async () => {\n for (const [, cell] of durable) {\n if (cell.live.ended) continue;\n const who = await ctx.resolve(cell.principal);\n cell.roles = who.roles;\n cell.installed = who.installed;\n cell.hash = who.catalog.hash;\n const granted = new Set(who.catalog.ids);\n for (const [id, definition] of Object.entries(ctx.app.actions)) {\n if (!granted.has(id)) continue;\n const layout = who.variants.get(id);\n cell.live.shell.registerAction(layout === undefined ? definition : { ...definition, layout });\n }\n }\n })().catch((err: unknown) => console.error('[moss/shells] adopt failed', err));\n },\n deliver: (principal, channel, payload) => {\n // Into the LIVE shell only. A principal with no durable shell hears\n // nothing and that is correct — this is push over shells that already\n // exist, never a reason to build one for somebody who is not there. The\n // rows the message points at are still in the database; their screen\n // reads them the next time it opens.\n const cell = durable.get(principal);\n if (cell === undefined || cell.live.ended) return false;\n try {\n cell.live.shell.publish(channel, payload);\n return true;\n } catch {\n return false;\n }\n },\n list: () => {\n const reports: ShellReport[] = [];\n for (const [principal, cell] of durable) {\n const live = cell.live;\n if (live.ended) continue;\n try {\n // nova's own read of a running shell — top of stack first.\n const canvases = snapshotShell(live.shell)\n .canvases.filter((canvas) => canvas.items.length > 0)\n .map((canvas) => ({ id: canvas.id, actions: canvas.items.map((item) => item.definitionId) }));\n reports.push({ principal, connections: live.connections.size, since: live.since, idleSince: live.idleSince, canvases });\n } catch {\n // unreadable (disposed under us) — not a shell anybody can be shown\n }\n }\n return reports;\n },\n reset: (principal) => {\n const cell = durable.get(principal);\n if (cell === undefined || cell.live.ended) return false;\n void rebuild(cell).catch((err: unknown) => console.error('[moss/shells] a reset failed to rebuild', err));\n return true;\n },\n stop: () => {\n if (sweeper !== undefined) clearInterval(sweeper);\n sweeper = undefined;\n },\n };\n};\n","import type { PageManifest } from './app';\n\n// ═══════════════════════════════════════════════════════════════\n// Which page a path leads to. A page's `path` is literal segments and `:name`\n// parameters (\"/docs/:slug\"); a path matches a page when they have the same\n// number of segments and every literal one is equal. Nothing else — no\n// wildcards, no optional segments, no order to remember: two pages that could\n// both answer one path are refused when the router is made, so which page a\n// path leads to never depends on the order they were written in.\n// ═══════════════════════════════════════════════════════════════\n\nexport type PageMatch = { name: string; params: Record<string, string> };\nexport type PageRouter = { match: (path: string) => PageMatch | undefined };\n\ntype Segment = { literal: string } | { param: string };\ntype Compiled = { name: string; segments: Segment[] };\n\nconst segmentsOf = (path: string): string[] => path.split('?')[0]?.split('/').filter((part) => part !== '') ?? [];\n\nconst compile = (name: string, page: PageManifest): Compiled => {\n if (!page.path.startsWith('/')) throw new Error(`moss: page \"${name}\" has the path \"${page.path}\" — a page's path starts with \"/\".`);\n const segments = segmentsOf(page.path).map((part): Segment => (part.startsWith(':') ? { param: part.slice(1) } : { literal: part }));\n for (const segment of segments) {\n if ('param' in segment && !/^[A-Za-z_][A-Za-z0-9_]*$/.test(segment.param)) {\n throw new Error(`moss: page \"${name}\" names the parameter \":${segment.param}\" in \"${page.path}\" — a parameter is a plain name.`);\n }\n }\n if (page.params !== undefined && !page.canvases.some((canvas) => canvas.id === page.params)) {\n throw new Error(`moss: page \"${name}\" sends its path's parameters to the canvas \"${page.params}\", which it does not have.`);\n }\n return { name, segments };\n};\n\n// Two patterns collide when some path satisfies both: same length, and no\n// position where both are literal and differ.\nconst collide = (a: Compiled, b: Compiled): boolean =>\n a.segments.length === b.segments.length &&\n a.segments.every((segment, index) => {\n const other = b.segments[index];\n return other === undefined || 'param' in segment || 'param' in other || segment.literal === other.literal;\n });\n\nexport const createPageRouter = (pages: Record<string, PageManifest>): PageRouter => {\n const compiled = Object.entries(pages).map(([name, page]) => compile(name, page));\n for (const [index, page] of compiled.entries()) {\n const other = compiled.slice(index + 1).find((candidate) => collide(page, candidate));\n if (other !== undefined) {\n throw new Error(`moss: pages \"${page.name}\" and \"${other.name}\" can both answer one path — give them paths that differ in a literal segment.`);\n }\n }\n\n return {\n match: (path) => {\n const parts = segmentsOf(path);\n for (const page of compiled) {\n if (page.segments.length !== parts.length) continue;\n const params: Record<string, string> = {};\n let matches = true;\n for (const [index, segment] of page.segments.entries()) {\n const part = parts[index];\n if (part === undefined) {\n matches = false;\n break;\n }\n if ('param' in segment) {\n try {\n params[segment.param] = decodeURIComponent(part);\n } catch {\n matches = false;\n break;\n }\n } else if (segment.literal !== part) {\n matches = false;\n break;\n }\n }\n if (matches) return { name: page.name, params };\n }\n return undefined;\n },\n };\n};\n","import { livenessOf } from '@niscorp/nova/reflect';\nimport type { ActionDefinition } from '@niscorp/nova';\nimport type { SeedEntry, SeedMutation } from '@niscorp/vex';\n\n// ═══════════════════════════════════════════════════════════════\n// DOES THIS SCREEN NEED A SHELL — the verdict, composed.\n//\n// nova reports what an action can still do once it has been drawn (its\n// `livenessOf`: gestures, channels, endpoints and when each is called). It\n// cannot say what answers a url. Moss can: the entries behind each fingerprint\n// are in the manifest, so \"this read keeps answering\" is a lookup, not a guess.\n//\n// A screen is LIVE when something on it can still happen — and then it needs a\n// shell standing behind it and a socket to reach it. Otherwise its tree is the\n// whole of it: drawn once, kept by nothing.\n//\n// Everything here is read off artifacts. The one thing that is not an artifact\n// is code — a `fn:` endpoint — and code is counted live without being read:\n// what a function does later is not written anywhere this can look.\n// ═══════════════════════════════════════════════════════════════\n\nexport type ShellNeed = {\n live: boolean;\n // one sentence per reason, for a report a person reads before choosing how a\n // page is served (\"docs.search: a person can act on it\")\n why: string[];\n // reads made while the action opened: their answers are IN the drawn tree, so\n // a page kept after it was drawn shows them as they were then\n drawnWith: string[];\n};\n\nconst fingerprintOf = (request: unknown): string | undefined => {\n if (request === null || typeof request !== 'object' || Array.isArray(request)) return undefined;\n const fingerprint: unknown = Reflect.get(request, 'fingerprint');\n return typeof fingerprint === 'string' ? fingerprint : undefined;\n};\n\nexport const shellNeedOf = (definition: ActionDefinition, entries: ReadonlyMap<string, SeedEntry | SeedMutation>): ShellNeed => {\n const facts = livenessOf(definition);\n const why: string[] = [];\n const drawnWith: string[] = [];\n\n if (facts.gestures) why.push('a person can act on it');\n if (facts.opaqueLayout) why.push('its layout is kept in the store, so what can be pressed on it is not readable');\n for (const channel of facts.listens) why.push(`it waits on the channel \"${channel}\"`);\n\n for (const use of facts.endpoints) {\n if (!use.onOpen && !use.later) continue;\n if (use.kind === 'fn') {\n why.push(`it calls the function endpoint \"${use.name}\", which is code`);\n continue;\n }\n const fingerprint = fingerprintOf(use.request);\n const entry = fingerprint === undefined ? undefined : entries.get(fingerprint);\n if (entry !== undefined && !('mutation' in entry) && entry.refresh === 'reactive') {\n why.push(`its read \"${use.name}\" keeps answering (${entry.fingerprint} is reactive)`);\n continue;\n }\n // A replay of something the manifest does not carry (an entry seeded into\n // the database some other way) may be reactive too. It cannot be read here,\n // so it is not concluded finished.\n if (fingerprint !== undefined && entry === undefined) {\n why.push(`its read \"${use.name}\" replays \"${fingerprint}\", which the manifest does not carry — whether it keeps answering is not readable`);\n continue;\n }\n // Called only because of something that happens later: the gesture or the\n // channel that calls it is already a reason above.\n if (use.onOpen) drawnWith.push(fingerprint ?? use.url ?? use.name);\n }\n\n return { live: why.length > 0, why, drawnWith };\n};\n","// ═══════════════════════════════════════════════════════════════\n// IDENTITY — the one read that cannot be authorised, held once.\n//\n// A vex read needs a compiled ScopePolicy; a policy is compiled from a\n// principal's roles; roles come from identity. The read that RESOLVES a\n// principal therefore cannot be authorised, because authorisation needs its\n// answer. Every system has this, and it is the only honest reason for a lookup\n// that does not pass through the engine (DESIGN Part 4).\n//\n// What that licenses is exactly one row, on demand, for the principal\n// presenting a token. It does not license a resident copy of the population,\n// which is what six synchronous seams forced on Lyra: a hook that cannot await\n// has exactly one implementation available to it, and that implementation is a\n// map of everybody.\n//\n// So the seam is async, and the cache lives HERE rather than in eight\n// module-level maps across three application files. Moss already holds four\n// per-principal caches of compiled objects it never interprets; this is that\n// responsibility, held with bounds and a roster it did not have.\n//\n// WHAT THIS DELIBERATELY DOES NOT HAVE:\n//\n// - an enumerator for application code. `get` takes a principal and returns\n// one record. There is no `everyone()`, because size was never what made\n// the directory a database — being listable was. You cannot scan what you\n// cannot list. `list()` below is an OPERATOR surface, on the same model as\n// the shell roster, and it returns structural facts rather than records.\n// - a secondary index you can READ through. No by-email, no by-tenant lookup.\n// A second index that answers \"who is X\" is a query planner, and a query\n// planner is a database. The tag map below is the one exception and it is\n// write-only: it can forget a group, and it cannot return one.\n// - any inspection of what it holds. Not one line here reads a field off a\n// record's `scope`. The moment moss says `.studioId`, moss has learned what\n// a tenant is and the boundary this whole design rests on is gone.\n// ═══════════════════════════════════════════════════════════════\n\n// What an application says a principal IS. Opaque: `roles` goes to charter,\n// `installed` is filtered against, `scope` is merged into vex's scope values\n// without moss ever looking inside it.\nexport type IdentityRecord = {\n // The rungs this principal wears. Charter compiles a policy from them.\n roles: readonly string[];\n // Everything else a principal is — a tenant, a region, a locale. Merged into\n // the engine's scope values server-side and unforgeable by a request.\n scope: Record<string, unknown>;\n // Integration ids live for this principal's tenant. `undefined` means every\n // registered integration is live, which is right for a single-tenant app and\n // wrong the moment there are two.\n installed?: readonly string[];\n // WHAT THIS PRINCIPAL SHARES A FATE WITH — an opaque string the application\n // chooses, and the only reason moss keeps a second map.\n //\n // This is NOT the secondary index invariant 2 bans, and the difference is the\n // whole justification: `BY_EMAIL` was a way to FIND somebody, and a way to\n // find somebody is a query planner. This supports exactly one operation —\n // FORGET everyone wearing this tag — and no operation that returns a record.\n // You cannot read anything through it, which is what invariant 1 is actually\n // protecting.\n //\n // It exists because \"a tenant-local write invalidates that tenant, not the\n // deployment\" is otherwise unachievable: dropping one tenant's records means\n // naming them, and naming them without enumerating the population needs the\n // application to have said, at resolve time, which ones go together. Moss\n // never interprets the string — it is a tenant id here, and it could be an\n // org, a region, or nothing at all.\n tag?: string;\n};\n\n// One resident identity, as an operator needs to see it: structural facts only.\n// Naming the principal is the application's job, and what the record CONTAINS\n// is never any of moss's business.\nexport type IdentityReport = {\n principal: string;\n // when this record was last resolved from the application\n since: number;\n // when it was last read; the idle sweep works off this\n lastSeen: number;\n};\n\nexport type IdentityCache = {\n // THE ONLY WAY IN. One principal, one record.\n get: (principal: string) => Promise<IdentityRecord>;\n // Forget one principal. `false` if they were not held — an answer, not an\n // error. Called wherever a shell is reset today: a role change, a language\n // change, an install landing.\n invalidate: (principal: string) => boolean;\n // Forget everybody. The generation pointer moved, or an artifact changed\n // under the whole deployment.\n invalidateAll: () => void;\n // Forget everybody who shares a tag — one tenant, not the deployment. Answers\n // WHO was forgotten, because the caller's next move is to reset exactly those\n // shells: a count would leave it guessing, and guessing here means resetting\n // the whole deployment to be safe, which is the thing this exists to stop.\n invalidateTag: (tag: string) => readonly string[];\n // Every identity resident right now — the operator roster, on the shell-list\n // model. Structural facts, never records.\n list: () => IdentityReport[];\n // What it is costing, so that \"breaks rather than degrades\" has something to\n // break on: an unbounded map works beautifully at demo scale and dies at\n // production scale with no signal in between. This is the signal.\n meter: () => { size: number; max: number; resolved: number; evicted: number; expired: number };\n // Stop the sweep. For hosts that outlive their server (dev checks, embedded\n // tools); the timer is unref'd, so a plain process needn't call it.\n stop: () => void;\n};\n\nexport type IdentityCacheContext = {\n // The application's seam: one principal in, one record out. Async and\n // wire-bearing at the call site — this module never sees the wire, it only\n // sees the promise.\n resolve: (principal: string) => Promise<IdentityRecord>;\n // Hard ceiling on resident records. Reaching it evicts the least recently\n // read, and increments the eviction meter so that pressure is visible before\n // it is fatal.\n max?: number;\n // Drop a record nobody has read for this long. `0` disables the sweep.\n idleMs?: number;\n // Re-resolve a record older than this on its next read. `0` disables it.\n // The same clock and the same reasoning as `sessionRevalidateMs`: a verifier\n // whose answers can change needs its answers to expire.\n revalidateMs?: number;\n // Injected so the sweep and the clock are testable without waiting.\n now?: () => number;\n};\n\n// Big enough that no real deployment reaches it by accident, small enough that\n// a leak announces itself long before the process dies. A deployment with more\n// concurrent sessions than this is a deployment that should have said so.\nexport const DEFAULT_IDENTITY_MAX = 10_000;\n\n// A record nobody has read for half an hour is a warm answer with no reader.\n// Re-resolving costs one round trip on their next request. Same number and same\n// reasoning as the durable-shell sweep.\nexport const DEFAULT_IDENTITY_IDLE_MS = 30 * 60 * 1000;\n\n// The sweep never runs less often than this, so a short `idleMs` is honoured\n// closely and a long one doesn't cost a wakeup per minute.\nconst SWEEP_EVERY_MS = 60 * 1000;\n\nexport const createIdentityCache = (ctx: IdentityCacheContext): IdentityCache => {\n const max = ctx.max ?? DEFAULT_IDENTITY_MAX;\n const idleMs = ctx.idleMs ?? DEFAULT_IDENTITY_IDLE_MS;\n const revalidateMs = ctx.revalidateMs ?? 0;\n const now = ctx.now ?? Date.now;\n\n type Held = {\n record: IdentityRecord;\n since: number;\n lastSeen: number;\n };\n\n // Insertion order IS the eviction order, and a Map preserves it — so\n // \"least recently read\" is maintained by deleting and re-setting on every\n // read rather than by a second structure that could disagree with this one.\n const held = new Map<string, Held>();\n\n // tag -> the principals wearing it. Maintained beside `held` and never read\n // out of: `invalidateTag` deletes through it and nothing else touches it.\n // Kept honest by pruning on every removal, so a tag whose last principal was\n // evicted does not linger as an empty set.\n const tagged = new Map<string, Set<string>>();\n\n const untag = (principal: string, record: IdentityRecord): void => {\n const tag = record.tag;\n if (tag === undefined) return;\n const group = tagged.get(tag);\n if (group === undefined) return;\n group.delete(principal);\n if (group.size === 0) tagged.delete(tag);\n };\n\n const forget = (principal: string): boolean => {\n const entry = held.get(principal);\n if (entry === undefined) return false;\n untag(principal, entry.record);\n held.delete(principal);\n return true;\n };\n\n // IN FLIGHT, so that a burst of requests for one principal at login resolves\n // ONCE. Without this the first request's latency is paid by every request\n // that arrives while it is outstanding, which is precisely the moment a\n // browser opens six connections at once.\n const pending = new Map<string, Promise<IdentityRecord>>();\n\n let resolved = 0;\n let evicted = 0;\n let expired = 0;\n\n const evictOldest = (): void => {\n const oldest = held.keys().next();\n if (oldest.done === true) return;\n forget(oldest.value);\n evicted += 1;\n };\n\n const remember = (principal: string, record: IdentityRecord, at: number): void => {\n forget(principal);\n // Evict AFTER the delete above, so re-resolving somebody already held never\n // evicts a stranger to make room for a record that needs none.\n while (held.size >= max) evictOldest();\n held.set(principal, { record, since: at, lastSeen: at });\n if (record.tag !== undefined) {\n const group = tagged.get(record.tag) ?? new Set<string>();\n group.add(principal);\n tagged.set(record.tag, group);\n }\n };\n\n const get = async (principal: string): Promise<IdentityRecord> => {\n const at = now();\n const hit = held.get(principal);\n if (hit !== undefined) {\n const stale = revalidateMs > 0 && at - hit.since >= revalidateMs;\n if (!stale) {\n // Re-set to move it to the young end of the eviction order.\n held.delete(principal);\n hit.lastSeen = at;\n held.set(principal, hit);\n return hit.record;\n }\n expired += 1;\n }\n\n const inFlight = pending.get(principal);\n if (inFlight !== undefined) return inFlight;\n\n const work = ctx\n .resolve(principal)\n .then((record) => {\n resolved += 1;\n remember(principal, record, now());\n return record;\n })\n .finally(() => {\n pending.delete(principal);\n });\n pending.set(principal, work);\n return work;\n };\n\n // The idle sweep. Unref'd: a warm cache with no reader must not be the reason\n // a process refuses to exit.\n const sweep = idleMs > 0 ? setInterval(() => {\n const at = now();\n for (const [principal, entry] of [...held]) {\n if (at - entry.lastSeen >= idleMs) {\n forget(principal);\n evicted += 1;\n }\n }\n }, Math.min(SWEEP_EVERY_MS, idleMs)) : undefined;\n sweep?.unref?.();\n\n return {\n get,\n invalidate: (principal) => {\n pending.delete(principal);\n return forget(principal);\n },\n invalidateAll: () => {\n held.clear();\n tagged.clear();\n pending.clear();\n },\n invalidateTag: (tag) => {\n const group = tagged.get(tag);\n if (group === undefined) return [];\n // Copied before iterating: `forget` mutates the set this is walking.\n const principals = [...group];\n for (const principal of principals) {\n pending.delete(principal);\n forget(principal);\n }\n return principals;\n },\n list: () => [...held].map(([principal, entry]) => ({ principal, since: entry.since, lastSeen: entry.lastSeen })),\n meter: () => ({ size: held.size, max, resolved, evicted, expired }),\n stop: () => {\n if (sweep !== undefined) clearInterval(sweep);\n },\n };\n};\n","import { randomBytes, createHash, timingSafeEqual } from 'node:crypto';\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { Hono } from 'hono';\nimport { vex, VEX_LIVE_ENV } from '@niscorp/vex/hono';\nimport { createWireFollower } from './follow';\nimport { handleQuery } from '@niscorp/vex';\nimport { migrate, upgradeStore } from '@niscorp/strata/postgres';\nimport { createGrammarUpgrader } from './grammar';\nimport { scopeProfiles } from '@niscorp/vex';\nimport type { ScopePolicy, WriteEvent, ExecuteRecord, SeedEntry, SeedMutation } from '@niscorp/vex';\nimport { emitterOf } from './telemetry';\nimport type { TelemetrySpan } from './telemetry';\nimport { wireFabric } from './fabric';\nimport { verifyCharter } from '@niscorp/charter';\nimport type { VerifyReport } from '@niscorp/charter';\nimport { auditClosure } from './closure';\nimport type { NiscApp } from './app';\nimport type { NiscRuntime } from './runtime';\nimport { sessionRemainingMs, sessionVerifierOf } from './sessions';\nimport { createDataLayer } from './data';\nimport { tableSequencesOf } from './migrate';\nimport { mintWrites } from './tide';\nimport { memoKey, memoKeyOf, resolveCatalogForRoles, resolvePolicyAtReachForRoles, resolvePolicyForRoles, resolveVariantsForRoles, verifyVariants, wearableOf } from './principal';\nimport type { Catalog } from './principal';\nimport type { LayoutNode } from '@niscorp/nova';\nimport { chainCycles } from '@niscorp/nova/reflect';\nimport {\n buildContract,\n callIntegrationWith,\n contractAsMarkdown,\n copyPress,\n describePlacements,\n INTEGRATION_ACTIONS_STORE,\n integrationByKey,\n listIntegrations,\n loadIntegrationActions,\n frameAdmits,\n reachAdmits,\n reachDeclares,\n reachOf,\n runIntake,\n intakeContextOf,\n} from './integrations';\nimport type { Reach, CallIntegration } from './integrations';\nimport { createAssertionSigner, hashIntegrationKey, mintIntegrationKey } from './assert';\nimport { createSocket, DEFAULT_REVALIDATE_MS } from './socket';\nimport type { SocketAccept } from './socket';\nimport { createShellHost } from './shells';\nimport type { ShellHostContext } from './shells';\nimport { createPageRouter } from './pages';\nimport { shellNeedOf } from './liveness';\nimport { createIdentityCache } from './identity';\nimport { createGeneration } from './generation';\nimport type { Generation } from './generation';\nimport type { IdentityRecord, IdentityReport } from './identity';\nimport type { ShellHost } from './shells';\nimport { resolveRoles } from './principal';\n\n// ═══════════════════════════════════════════════════════════════\n// moss — the nisc app server: the data/policy plane over plain HTTP.\n// Surfaces standing so far:\n//\n// /catalog — the application, resolved for the session's principal\n// /api/<resource>/vex — reads and writes, locked, scoped per principal\n// /api/vex — the cross-resource base surface\n//\n// The socket stands beside them (socket.ts); `/fns` — side-effect-free\n// server functions behind plain URLs — is still unbuilt.\n//\n// The app hands over its ARTIFACTS (app.ts) and an environment\n// (runtime.ts); everything mechanical is derived — the data layer\n// (data.ts), per-principal resolutions (principal.ts) — and the server\n// refuses to boot incoherent (DESIGN.md § Derivation over configuration:\n// coherence is refused, not documented).\n// ═══════════════════════════════════════════════════════════════\n\n// WHO THIS REQUEST IS, resolved ONCE at the door.\n//\n// `principal` alone was never enough: every consumer downstream immediately\n// asked the application three more questions to turn it into roles, scope\n// values and an install list — per request, and twice per request for anything\n// that compiled a policy at a reach. Resolving it here and carrying it means\n// the seams are asked once per SESSION, which is the whole point of the cache\n// behind them. `key` is the memo key, derived once with the record rather than\n// recomputed by every lookup.\ntype Resolved = {\n roles: readonly string[];\n scope: Record<string, unknown>;\n installed: readonly string[] | undefined;\n key: string;\n // The record itself, handed back to the app's `scope` hook so a per-request\n // value can be COMPUTED from a per-session fact without a second lookup.\n // Absent when no `identity` seam is declared.\n record?: IdentityRecord;\n};\n\n// The capability lent to no-principal machinery: execute a seeded entry as a\n// declared charter role. See `createServer` for the four bounds that make it\n// tighter than the raw SQL it replaces.\nexport type ExecuteAs = (role: string, fingerprint: string, context: Record<string, unknown>, scope?: Record<string, unknown>) => Promise<unknown>;\n\ntype Env = { Variables: { principal: string | null; resolved: Resolved } };\n\n// The composed app — hono (so a host mounts, extends or listens with any\n// runtime adapter; it's the escape hatch for classic routing, too) plus\n// the socket's accept, which the runtime's transport feeds new\n// connections (see ./node's attachSocket).\nexport type MossServer = Hono<Env> & {\n socket: SocketAccept;\n shells?: ShellHost;\n // WHO A TOKEN IS — the deployment's own verifier, the one every surface here\n // already asks. For an app's own route that receives a credential some other\n // way than a Bearer header (a page request carries a cookie): null is a\n // refusal, exactly as it is everywhere else.\n principalOf: (token: string) => Promise<string | null>;\n // THE PAGE A PATH LEADS TO (app.ts § pages) — its name, the host that draws\n // it, and the input its path carries — or undefined for a path that is the\n // app's. The document route and the socket ask the same question here, so a\n // page is drawn and then served by one answer.\n page: (path: string) => { name: string; host: ShellHost; inputs: Record<string, Record<string, unknown>> } | undefined;\n // Every page the manifest declares, by name, with the path it is drawn at —\n // what a build walks to know which paths exist besides the app's own.\n pages: readonly { name: string; path: string }[];\n // Artifacts changed at runtime (an app that loads actions from rows and just\n // wrote new ones): re-verify coherence, drop every per-principal memo, and\n // have living shells adopt their re-resolved definitions. Throws on an\n // incoherent charter/variant set — a bad publish refuses, exactly like boot.\n refresh: () => void;\n // THE REPORT THIS SERVER WAS VERIFIED BY — `verifyCharter`'s, from boot, then\n // from each `refresh` that passed. Boot and refresh read its `errors` and\n // nothing else, so the rest was computed and dropped: the warnings (an action\n // no role grants, an allow that matches nothing) and each role's closure\n // issues. Nothing here prints them; a host that wants them reads them — over\n // the universes boot resolved against, which it cannot rebuild without the\n // database. `errors` is always empty: a report with one never got this far.\n charterReport: () => VerifyReport;\n // ONE PERSON'S identity, forgotten — for a change that concerns them and\n // nobody else (their role moved, their tenant installed an integration). `false` if\n // they were not held, which is an answer rather than an error. `refresh()`\n // above is the deployment-wide hammer; this is the scalpel, and a tenant-local\n // write should reach for it rather than dropping every principal's record.\n invalidateIdentity: (principal: string) => boolean;\n // The resolved record for one principal — the app reading back what its own\n // seam and entries produced, through the same cache the request path uses.\n // Not an enumerator: one principal in, one record out.\n identity: (principal: string | null) => Promise<IdentityRecord>;\n // Execute a seeded entry as a declared charter role — for surfaces that have\n // no principal by nature. In-process, replay-only, charter-bounded; see the\n // construction inside `createServer`.\n executeAs: ExecuteAs;\n // Call an installed integration when nobody is driving — the outbound half\n // of `executeAs`. Resolves the row, refuses (throws) unless approved and\n // installed for this principal's tenant, mints the assertion, returns what\n // the integration answered — whatever it answered. Deliberately not gated\n // by reach: a lifecycle verb is not an action and has no screen; the\n // integration gates it itself, on the verified claims. The deployment's own\n // act, not a screen's. See integrations.ts, callIntegrationWith.\n callIntegration: CallIntegration;\n // FORGET ONE TENANT, not the deployment. The application tags each identity\n // record it resolves (`IdentityRecord.tag`); this drops every record wearing\n // one and answers how many it held. Moss never interprets the tag.\n //\n // This is what makes a tenant-local write tenant-local. `refresh()` is still\n // the right hammer for a changed ARTIFACT, because artifacts are deployment\n // -wide; a tenant installing an integration is not.\n invalidateTenant: (tag: string) => number;\n // WAKE ONE PRINCIPAL'S SHELL ON A CHANNEL — the outward, cross-process twin\n // of a reaction's `deliver`. The shell, wherever it is resident, is published\n // to payload-less so it re-reads under its own policy; the nudge crosses the\n // fabric so it lands in whichever process holds that principal. No fabric, no\n // second process: it is just the local `deliver`. Payload-less by the\n // row-less doctrine — a nudge says a channel changed, never what to.\n nudge: (principal: string, channel: string) => void;\n // The generation this process has observed. Moves when any process calls\n // `refresh`; every process drops its derivations within one poll of it.\n generation: () => number;\n // RETIRE EVERYTHING THIS SERVER STARTED that outlives a request — the\n // generation poll, the identity idle sweep, the socket's revalidation, the\n // shell idle sweep. ONE call, because the alternative is what leaked: a host\n // retiring a runtime IN-PROCESS (a dev floor rebuilding on a server-file\n // edit) had to enumerate moss's timers by reaching into each handle, and\n // could only ever stop the ones it could see — the poller and the identity\n // sweep were never surfaced, so a rebuild left them polling an ended pool.\n // The thing that started a timer owns stopping it; the host calls this and\n // learns nothing about how many there are. A deployment that boots ONCE\n // needs none of this: nothing retires it in-process, and every timer here is\n // `unref`'d, so the process carries them off on its own exit.\n close: () => void;\n // Every identity resident right now, and what the cache is costing —\n // structural facts only, on the shell-roster model. Absent when the app\n // declares no `identity` seam.\n identities?: { list: () => IdentityReport[]; meter: () => { size: number; max: number; resolved: number; evicted: number; expired: number } };\n};\n\n// Constant-time credential comparison. Both sides are hashed to a fixed 32-byte\n// width first, so the compare never branches on length: a short guess is refused\n// in the same time as a correct-length one (a bare length check would leak the\n// key's length), and `timingSafeEqual` — which throws on a length mismatch — is\n// always handed two equal-width digests. The timing signal a REMOTE attacker\n// could read here is nanoseconds under microseconds of network jitter and is not\n// the point; D6 co-locates add-on containers on a shared network, and the least\n// -trusted code in the deployment facing far less jitter is.\nexport const secretsEqual = (a: string, b: string): boolean =>\n timingSafeEqual(createHash('sha256').update(a).digest(), createHash('sha256').update(b).digest());\n\n// THE TWO GATES GUARDING THE OPERATOR PREFIX, installed in the order they must\n// run. Registration order IS the security property: Hono composes matched\n// handlers in the order they were added, so the app's gate has to be added\n// before moss's key check to run before it, and both before the routes to wrap\n// them. Without this, an app that mounted its own `/operator/*` middleware got a\n// gate that ran AFTER moss's and, on moss's own routes, never — moss answered\n// every refusal and the app's gate was unreachable on the one path that matters.\n//\n// The app's gate (if any) runs first: returning a Response refuses; calling\n// `next()` and returning falls through to moss's key check. Either way moss's\n// own check still runs on every path the gate lets through, so the seam can only\n// HARDEN the prefix — add a second lock, never remove moss's. Awaiting `next()`\n// lets the gate observe the OUTCOME (moss's own 404, an approval's 422), which\n// is what makes auditing the consequential acts here honest rather than a log of\n// attempts.\nexport const guardOperator = (operator: Hono<Env>, opts: { key: string; gate?: NiscRuntime['operatorGate'] }): void => {\n const gate = opts.gate;\n if (gate !== undefined) operator.use('*', (c, next) => Promise.resolve(gate(c, next)));\n operator.use('*', async (c, next) => {\n const presented = c.req.header('x-operator-key') ?? '';\n if (opts.key === '' || !secretsEqual(presented, opts.key)) return c.json({ message: 'Not found.' }, 404);\n return next();\n });\n};\n\n// A vex execution record → a telemetry span. The one place a vex fact becomes\n// a span: vex reports in its own vocabulary (handler.ts, ExecuteRecord) and\n// knows nothing of OTLP; moss decides what of it is safe to name. Principal\n// PRESENCE is derived from the composed scope's `userId` (moss's own\n// convention — machinery carries none), never the value itself; no other scope\n// value crosses into the span.\nexport const vexRecordToSpan = (rec: ExecuteRecord): TelemetrySpan => ({\n name: 'vex.execute',\n startUnixNano: rec.startUnixNano,\n endUnixNano: rec.endUnixNano,\n status: rec.status,\n attributes: {\n op: rec.kind,\n hasPrincipal: (rec.scope['userId'] ?? 'anonymous') !== 'anonymous',\n ...(rec.fingerprint !== undefined ? { fingerprint: rec.fingerprint } : {}),\n ...(rec.reach !== undefined ? { reach: rec.reach } : {}),\n ...(rec.cacheHit !== undefined ? { cache: rec.cacheHit ? 'hit' : 'miss' } : {}),\n ...(rec.rows !== undefined ? { rows: rec.rows } : {}),\n },\n});\n\nexport const createServer = async (app: NiscApp, runtime: NiscRuntime): Promise<MossServer> => {\n // WHO A TOKEN IS, resolved before anything else boots: an unset verifier\n // refuses HERE, with a sentence, instead of serving every forged principal\n // silently (which is what the old `?? devSession` default did, for every\n // app that never set the field). 'dev-open' announces itself on this line.\n const session = sessionVerifierOf(runtime);\n\n // The deployment's one safe emitter, derived once — `undefined` when no sink\n // is configured, which every emission site below guards on to build nothing.\n // `vexOnExecute` is moss wiring vex's execution observer to it: vex reports a\n // record, moss maps it to a span and emits. Passed to every vex mount and to\n // `executeAs`, so one seam covers the request path and all machinery.\n const emit = emitterOf(runtime.telemetry);\n const vexOnExecute = emit === undefined ? undefined : (rec: ExecuteRecord) => emit(vexRecordToSpan(rec));\n\n // THE INTEGRATIONS TABLES EXIST BEFORE INTROSPECTION. The data layer's\n // introspected schema is the grant universe policies compile from — a table\n // created after it is a table no grant can reach, silently: an app granting\n // `integrations.read` compiled a policy that denied the very screen the\n // grant existed for, and nothing said so until somebody opened it.\n //\n // ONE LEDGERED RUN (strata) for every owner's tables: moss's own, the\n // sessions table when the deployment chose moss's credential, and the vex\n // cache's — in one transaction, recorded, refused if the ledger was edited\n // or written by newer code. The data layer's `cache.init()` below then finds\n // its sequence already applied.\n await migrate(runtime.pool, tableSequencesOf(runtime), { mode: runtime.migrations ?? 'apply' });\n // THE DOCUMENTS IN THOSE TABLES, brought to this code's grammars — nova's,\n // Prism's and the app's own (grammar.ts). Rows carry the stamp they were\n // written at; what they have not seen runs now, once, and they are written\n // back current. A row written by newer code refuses the boot, as a ledger\n // written by newer code does.\n const grammars = await createGrammarUpgrader(app);\n await upgradeStore(runtime.pool, INTEGRATION_ACTIONS_STORE, grammars);\n const data = await createDataLayer(runtime, app.entries ?? []);\n\n // ── Refuse to start incoherent — the charter engine verifies,\n // nova audits each role's closure (over effective definitions: granted\n // variants substituted). Only the report's errors refuse: closure\n // findings sit under perRole[].issues and are not read here.\n const report = verifyCharter(\n app.charter,\n { actions: Object.keys(app.actions), data: data.grants, layouts: Object.keys(app.layouts ?? {}) },\n wearableOf(app),\n auditClosure(app.actions, app.layouts),\n );\n if (report.errors.length > 0) {\n throw new Error(`Charter is incoherent — refusing to serve:\\n${report.errors.map((e) => ` ${e.rule}: ${e.detail}`).join('\\n')}`);\n }\n // Kept for `charterReport()`; a refresh that passes replaces it.\n let verifiedReport: VerifyReport = report;\n // CHAINS THAT NEVER END, said at boot. A trigger that re-emits its own\n // channel (or a mount that reloads itself, …) is valid data; nova stops it\n // at its budget when it runs, and this names it before anybody opens it.\n // Said, not refused: the app still serves, as it would have before.\n for (const cycle of chainCycles(app.actions)) {\n console.error(`[moss] a chain of steps that never ends: ${cycle.path} — nova stops it at its budget when it runs (RUNAWAY_CHAIN)`);\n }\n // A DECLARED REACH HAS TO NAME A PROFILE THAT EXISTS.\n //\n // An entry's `reach` is a string, matched at request time against the profiles\n // the behaviors declare. A typo fails CLOSED — an unknown profile denies every\n // table — which is the right runtime posture and a terrible way to find out:\n // the screen comes back empty or refused and nothing says why. Every other\n // string in this file is checked against its universe at boot; so is this one.\n const profiles = new Set(scopeProfiles(app.behaviors ?? {}));\n const badReach = (app.entries ?? [])\n .filter((e) => typeof (e as { reach?: unknown }).reach === 'string')\n .filter((e) => !profiles.has((e as { reach: string }).reach))\n .map((e) => ` ${e.fingerprint} declares reach \"${(e as { reach: string }).reach}\"`);\n if (badReach.length > 0) {\n throw new Error(\n `Entries declare a reach no table offers — refusing to serve:\\n${badReach.join('\\n')}\\n known profiles: ${[...profiles].join(', ') || '(none)'}`,\n );\n }\n\n // Ring-2 coherence: variants reference shipped actions, one variant per\n // action per wearable combination. Same posture, second gate.\n const variantErrors = verifyVariants(app);\n if (variantErrors.length > 0) {\n throw new Error(`Layout variants are incoherent — refusing to serve:\\n${variantErrors.map((e) => ` ${e}`).join('\\n')}`);\n }\n\n // ── Per-principal resolutions, computed at first sight (login) and\n // memoized: the documents are static for the process.\n //\n // KEYED BY WHAT THEY DEPEND ON, not by who asked. Every resolution here is a\n // function of (role combination + installed set) - see `memoKeyOf` - so\n // keying by principal stored one entry per PERSON for an answer that has\n // about ten distinct values, in four maps nothing ever evicted. Two people on\n // the same rung at the same tenant now share one compiled policy, which is\n // what they always had; there are simply no longer two copies of it.\n // IDENTITY, held by moss when the application declares the seam. Bounded,\n // evicted, revalidated on the same clock a live socket credential runs on,\n // and enumerable only by an operator. Absent, the three older synchronous\n // seams answer and nothing below changes shape.\n // THE GENERATION POINTER. Created before the memos it protects, polled on the\n // same clock a socket credential is re-verified on, and moved by `refresh`.\n // A process that observes a move re-reads the integration actions and drops\n // every derivation, which is exactly what a restart used to be for.\n // (Its table is part of MOSS_SEQUENCE, applied with the rest at the top.)\n let generation: Generation | undefined;\n\n // ONE RESOLUTION, TWO HALVES. The app's `resolve` answers what cannot be\n // read under any policy (roles, the tag, an actor's pre-auth scope). Then\n // moss executes the entries the manifest declares — through its own engine,\n // as the charter role `identity.as` names, locked to replay — and merges\n // each mapped object into the record's scope, in order, so a later entry may\n // be pinned by a value an earlier one established. Every value the engine\n // pins by was resolved engine-side; no request authored any of it.\n //\n // FAIL CLOSED, twice: a scope entry that cannot be read merges nothing, so\n // tenant-scoped reads match no rows; a declared `installed` that cannot be\n // read is NO integrations, never every integration.\n // EXECUTE A SEEDED ENTRY AS A DECLARED CHARTER ROLE — the one mechanism for\n // every surface that has no principal by nature: identity resolution, the\n // sign-in credential, a mail provider's callback, the lab's picker.\n //\n // Strictly tighter than the raw SQL it replaces, on four counts: in-process\n // only (never a route); locked to REPLAY (only seeded entries run — no\n // caller-authored query); the policy is compiled from a charter role with\n // declared grants and a declared reach, like any principal's; and the scope\n // values are supplied by server code, never by a request. Widening what a\n // machinery role can touch is a charter diff somebody reviews.\n const executeAs = async (role: string, fingerprint: string, context: Record<string, unknown>, scope: Record<string, unknown> = {}): Promise<unknown> => {\n const roles = [role];\n const outcome = await handleQuery(\n {\n engine: data.engine,\n locked: true,\n scopePolicy: resolvePolicyForRoles(app, data.grants, roles),\n policyForReach: (reach) => resolvePolicyAtReachForRoles(app, data.grants, roles, reach),\n // Mutation replay under the same role policy — write gates and scope\n // pins apply exactly as they would for a person.\n mutations: { client: runtime.db, policy: resolvePolicyForRoles(app, data.grants, roles) },\n // Machinery is observed too: a seeded entry run as a charter role is a\n // vex execution, and its scope carries no principal, so it reports as\n // `hasPrincipal: false` — which is the truth about it.\n ...(vexOnExecute !== undefined ? { onExecute: vexOnExecute } : {}),\n },\n { fingerprint, context },\n scope,\n );\n if (outcome.status !== 200) {\n console.error(`[moss:executeAs] \"${fingerprint}\" as \"${role}\" refused (${outcome.status})`, outcome.body);\n return undefined;\n }\n const body = outcome.body as Record<string, unknown>;\n return 'result' in body ? body['result'] : undefined;\n };\n\n const identityEntry = async (roles: readonly string[], fingerprint: string, scope: Record<string, unknown>): Promise<unknown> =>\n executeAs(roles[0] ?? '', fingerprint, {}, scope);\n\n const composedResolve = async (principal: string): Promise<IdentityRecord> => {\n const config = app.identity;\n if (config === undefined) throw new Error('moss: identity resolved with no seam');\n const reader = config.as === undefined ? undefined : [config.as];\n const read = async (fingerprint: string, scope: Record<string, unknown>): Promise<unknown> => {\n if (reader === undefined) throw new Error('moss: identity.read needs identity.as — name the charter role the reader executes as');\n return identityEntry(reader, fingerprint, scope);\n };\n return config.resolve(principal, read);\n };\n\n const identities = app.identity !== undefined\n ? createIdentityCache({\n resolve: composedResolve,\n ...(runtime.identityMax !== undefined ? { max: runtime.identityMax } : {}),\n ...(runtime.identityIdleMs !== undefined ? { idleMs: runtime.identityIdleMs } : {}),\n revalidateMs: runtime.sessionRevalidateMs ?? DEFAULT_REVALIDATE_MS,\n })\n : undefined;\n\n // The memo key derived ONCE per record rather than per lookup. A WeakMap\n // because the cache hands back the same object for the life of a session, and\n // because a key held here must not be the reason a record cannot be collected.\n const keys = new WeakMap<object, string>();\n const keyOf = (record: IdentityRecord): string => {\n const hit = keys.get(record);\n if (hit !== undefined) return hit;\n const key = memoKey(record.roles, record.installed);\n keys.set(record, key);\n return key;\n };\n\n // THE SCOPE VALUES A PRINCIPAL CARRIES — one spelling, used everywhere.\n //\n // The session's stable half from the identity record, then the clock's from\n // the `scope` hook, applied last and per request. There used to be four\n // spellings of this composition — one at the vex mount and three around the\n // integration surfaces — and a value that reached one but not the others is\n // exactly how an integration learns a member's studio on one route and nothing on the\n // next.\n const composeScope = (principal: string | null, resolved: Resolved): Record<string, unknown> => ({\n userId: principal ?? 'anonymous',\n ...resolved.scope,\n ...(app.scope?.(principal, resolved.record) ?? {}),\n });\n\n // The same, for the surfaces that have a principal but no request context —\n // the integration proxy and the assertion it signs.\n const scopeValuesFor = async (principal: string | null): Promise<Record<string, unknown>> =>\n composeScope(principal, await resolveIdentity(principal));\n\n const resolveIdentity = async (principal: string | null): Promise<Resolved> => {\n if (identities !== undefined && principal !== null) {\n const record = await identities.get(principal);\n return { roles: record.roles, scope: record.scope, installed: record.installed, key: keyOf(record), record };\n }\n return fromSeams(principal);\n };\n\n // The three older seams, asked together — which is what the identity seam\n // above exists to stop doing per request. Still the answer for an application\n // that has not declared `identity`, and still the answer on the two paths\n // below that are per-SESSION rather than per-request and so cost nothing:\n // building a durable shell, and listing an integration's contract.\n function fromSeams(principal: string | null): Resolved {\n const roles = resolveRoles(app, principal);\n const installed = undefined;\n // `scope` is EMPTY here rather than `app.scope(principal)`, because the\n // scope hook is applied at the mount below in both cases — once, per\n // request, over whatever the record carried. Calling it here as well would\n // ask a synchronous seam twice for one answer.\n return { roles, scope: {}, installed, key: memoKey(roles, installed) };\n }\n\n const policies = new Map<string, ScopePolicy>();\n const policy = (resolved: Resolved): ScopePolicy => {\n const hit = policies.get(resolved.key);\n if (hit !== undefined) return hit;\n const compiled = resolvePolicyForRoles(app, data.grants, resolved.roles);\n policies.set(resolved.key, compiled);\n return compiled;\n };\n\n // The same principal at a reach an ENTRY demands — same grants, narrower\n // rows. Memoized per (principal, reach) for the same reason the policy above\n // is: the documents are static for the process.\n const reachPolicies = new Map<string, ScopePolicy>();\n const policyAtReach = (resolved: Resolved, reach: string): ScopePolicy => {\n const key = `${resolved.key}\\u0000${reach}`;\n const hit = reachPolicies.get(key);\n if (hit !== undefined) return hit;\n const compiled = resolvePolicyAtReachForRoles(app, data.grants, resolved.roles, reach);\n reachPolicies.set(key, compiled);\n return compiled;\n };\n\n // Approved integrations' actions, folded into the running manifest. Called\n // after an import and after an approval; `refresh()` is what makes living\n // shells adopt.\n const staticActions = { ...app.actions };\n const reloadIntegrations = async (): Promise<void> => {\n const fromRows = await loadIntegrationActions(runtime.pool, grammars);\n app.actions = { ...staticActions, ...fromRows };\n refresh();\n };\n\n const catalogs = new Map<string, Catalog>();\n const catalog = (resolved: Resolved): Catalog => {\n const hit = catalogs.get(resolved.key);\n if (hit !== undefined) return hit;\n const built = resolveCatalogForRoles(app, resolved.roles, resolved.installed);\n catalogs.set(resolved.key, built);\n return built;\n };\n const variantBindings = new Map<string, ReadonlyMap<string, LayoutNode>>();\n const variants = (resolved: Resolved): ReadonlyMap<string, LayoutNode> => {\n const hit = variantBindings.get(resolved.key);\n if (hit !== undefined) return hit;\n const built = resolveVariantsForRoles(app, resolved.roles);\n variantBindings.set(resolved.key, built);\n return built;\n };\n\n // The same two, keyed by ROLES alone — what `adopt` needs. Adopting is for\n // changed artifacts, not changed people, so a live shell's roles are still\n // its roles and re-resolving the principal would be a round trip to learn\n // what the shell already knows.\n const asRoles = (roles: readonly string[], installed: readonly string[] | undefined): Resolved => ({ roles, scope: {}, installed, key: memoKey(roles, installed) });\n\n\n // THE DEPLOYMENT'S SIGNING IDENTITY — how an integration knows a call is\n // ours. Generated at boot, never persisted; the public half is served below\n // and verifying it is all anybody can do with it. See assert.ts for the\n // credential rule this and the integration key both follow.\n const assertions = createAssertionSigner(runtime.signingSeed);\n\n // The outbound act (integrations.ts, callIntegrationWith): the same row\n // refusals and identity machinery the proxy uses, minus the request the\n // proxy needs — because the signer never leaves this function, this is the\n // one place the verb can be built.\n const callIntegration = callIntegrationWith({\n pool: runtime.pool,\n installedFor: async (principal) => (await resolveIdentity(principal)).installed,\n scopeValuesFor,\n mint: assertions.mint,\n ...(runtime.telemetry !== undefined ? { telemetry: runtime.telemetry } : {}),\n });\n\n // ── The surfaces ──\n const server = new Hono<Env>();\n\n // Identity, once, for every surface: Bearer token → principal. Absent\n // header → the anonymous principal (anonymity is a principal, not an\n // error). Invalid token → 401 (an explicit reject beats a silent\n // downgrade to anonymous).\n //\n // An INTEGRATION KEY is the second way in, routed by its prefix. It resolves\n // through the integrations table (hash match, approved only) to a principal\n // the APP names for whoever the key acts for — and from that line on nothing\n // downstream can tell it from a person: same policy compilation, same scope\n // values, same engine stamping its writes. Deleting the integration is what\n // revokes it; there is no second mechanism to forget.\n server.use('*', async (c, next) => {\n const header = c.req.header('Authorization');\n if (header === undefined) {\n c.set('principal', null);\n c.set('resolved', await resolveIdentity(null));\n return next();\n }\n const token = header.startsWith('Bearer ') ? header.slice('Bearer '.length) : header;\n if (token.startsWith('ik_')) {\n const integration = await integrationByKey(runtime.pool, token);\n if (integration === undefined) {\n return c.json({ error: 'invalid_key', message: 'The integration key did not resolve.' }, 401);\n }\n const actor = (await app.integrationActor?.(integration, c.req.header('x-nisc-acts-for') ?? '')) ?? null;\n if (actor === null) {\n return c.json({ error: 'no_actor', message: 'This integration has no actor there.' }, 403);\n }\n // The seam may now be PURE (composing the actor id from its parts) —\n // whether the install is live is identity's question, so an actor that\n // resolves to nobody is refused here, where null used to be.\n const resolved = await resolveIdentity(actor);\n if (resolved.roles.length === 1 && resolved.roles[0] === 'public') {\n return c.json({ error: 'no_actor', message: 'This integration has no actor there.' }, 403);\n }\n c.set('principal', actor);\n c.set('resolved', resolved);\n return next();\n }\n const principal = await session(token);\n if (principal === null) {\n return c.json({ error: 'invalid_token', message: 'The session token did not resolve to a principal.' }, 401);\n }\n c.set('principal', principal);\n // ONE resolution, here, for everything downstream. A token that verifies to\n // a principal the application cannot resolve is a 401 rather than a crash:\n // an unknown principal is a failed sign-in, not a server fault.\n try {\n c.set('resolved', await resolveIdentity(principal));\n } catch {\n return c.json({ error: 'no_identity', message: 'The session token did not resolve to a principal.' }, 401);\n }\n return next();\n });\n\n // /catalog — the application, resolved for YOU.\n server.get('/catalog', (c) => {\n const principal = c.get('principal');\n const { ids, hash } = catalog(c.get('resolved'));\n return c.json({ principal, actions: ids, hash });\n });\n\n // THE CHAIN CHANNEL. A tide effect writing back through vex names its\n // chain position in two headers; they ride an AsyncLocalStorage context so\n // the write observer — which fires deep inside the handler, far from any\n // request object — can read them without vex ever learning tide exists.\n // Untrusted at this point: the app's `facts.chain` gate decides whether\n // the caller's word is good.\n const chainContext = new AsyncLocalStorage<{ cause: string; depth: number }>();\n server.use('/api/*', async (c, next) => {\n const cause = c.req.header('x-tide-cause');\n const depth = Number(c.req.header('x-tide-depth'));\n if (cause === undefined || cause === '' || !Number.isInteger(depth) || depth < 0) return next();\n return chainContext.run({ cause, depth }, () => next());\n });\n\n // The vex surfaces — the adapter does the work; the server resolves WHO.\n // Locked always; scope values and the compiled policy both come from the\n // principal, never from the request.\n const mount = (path: string, entities?: readonly string[]): void => {\n server.route(\n path,\n vex<Env>({\n engine: data.engine,\n ...(entities !== undefined ? { entities: [...entities] } : {}),\n locked: true,\n // `userId` is always the principal; the app's `scope` hook contributes\n // whatever else a principal is (a tenant, an org). Merged server-side,\n // unforgeable by the request — a `to:` in a behavior resolves here.\n // The session's stable values, then the clock's. `scope` is applied\n // last and per request so a value derived from today's date cannot be\n // held for the life of a session that began yesterday.\n getScope: (c) => composeScope(c.get('principal'), c.get('resolved')),\n getPolicy: (c) => policy(c.get('resolved')),\n // An entry that names a reach is served at it, not at the caller's own.\n getPolicyForReach: (c, reach) => policyAtReach(c.get('resolved'), reach),\n // One span per read and write on this surface — the busiest emission\n // point, and the reason vex has an observer at all.\n ...(vexOnExecute !== undefined ? { onExecute: vexOnExecute } : {}),\n mutations: {\n client: runtime.db,\n // Vex's write observer, fired once per committed mutation with\n // per-statement writes. Two consumers, in order of record:\n //\n // 1. The FACT lane — rows ride here and into tide's ledger only,\n // stamped with the identity the app derives from the write's\n // own scope. That stamp is the tenancy fence (see mintWrites).\n // 2. The REACTIONS — row-less by design and routed by declared\n // interest: table, op, count, scope, with `deliver` to push\n // onto living shells. A receiver that wants data re-reads it\n // under its own policy.\n //\n // Late-bound throughout: shells and tide stand up after the mounts.\n ...(app.reactions !== undefined || app.facts !== undefined\n ? {\n onWrite: (event: WriteEvent) => {\n const tide = app.facts?.tide();\n const as = tide !== undefined ? app.facts?.identity(event.scope) : undefined;\n if (tide !== undefined && as !== undefined) {\n const hints = chainContext.getStore();\n const chain = hints === undefined ? undefined : app.facts?.chain?.(event.scope, hints);\n mintWrites(tide, event, as, Date.now(), chain).catch((err) => console.error('[moss:facts]', err));\n }\n const tools = {\n // Local delivery carries the payload — an optimisation for a\n // shell resident in THIS process. The cross-process nudge is\n // payload-less: a shell in another process re-reads under its\n // own policy, which is the row-less doctrine and the only safe\n // thing to send off-box. No fabric → the publish is a no-op and\n // this is exactly today's local deliver.\n deliver: (principal: string, channel: string, payload?: unknown) => {\n const local = (server as MossServer).shells?.deliver(principal, channel, payload) ?? false;\n publishFabric({ kind: 'nudge', principal, channel });\n return local;\n },\n };\n for (const write of event.writes) {\n if (write.rows.length === 0) continue;\n for (const reaction of app.reactions ?? []) {\n if (reaction.table !== write.table || (reaction.op !== undefined && reaction.op !== write.op)) continue;\n try {\n reaction.run({ fingerprint: event.fingerprint, table: write.table, op: write.op, count: write.rows.length, scope: event.scope }, tools);\n } catch (err) {\n console.error('[moss:reactions]', err);\n }\n }\n }\n },\n }\n : {}),\n },\n }),\n );\n };\n mount('/api/vex');\n for (const [name, resource] of Object.entries(app.resources ?? {})) {\n mount(`/api/${name}/vex`, 'entities' in resource ? resource.entities : resource);\n }\n\n // ── INTEGRATIONS ─────────────────────────────────────────────\n //\n // An integration announces; we fetch. There is no poll and no boot sweep:\n // `POST /api/integrations` IS the announcement, it is idempotent, and\n // re-importing after a deploy is the same call with the same body.\n // (The tables were created before the data layer stood up — see the top of\n // this function for why the order is load-bearing.)\n\n // Everything an integration is built against, in the two formats somebody\n // might want. With no shared code an author cannot import a component name or\n // a fingerprint constant — this is what replaces those imports.\n const contractFingerprints = async (principal: string | null): Promise<string[]> => {\n const discovery = await data.engine.cache.entries?.();\n if (discovery === undefined) return [];\n const compiled = policy(await resolveIdentity(principal));\n return discovery\n .filter(({ entry }) => entry.kind === 'ok' || entry.kind === 'mutation')\n .map(({ key }) => key)\n .filter((key) => !key.startsWith('neg:'))\n .sort()\n .filter(() => compiled !== undefined);\n };\n\n server.get('/api/integrations/contract', async (c) => {\n const id = c.req.query('id') ?? '<your id>';\n const contract = buildContract(app, id);\n const fingerprints = await contractFingerprints(c.get('principal'));\n if (c.req.query('format') === 'md') {\n return new Response(contractAsMarkdown(contract, fingerprints), {\n headers: { 'content-type': 'text/markdown; charset=utf-8' },\n });\n }\n return c.json({ ...contract, fingerprints, verifyKey: assertions.verifyKey });\n });\n\n // The public half of the deployment's signing key — OPEN, because holding it\n // only verifies. An integration reads it once (an env var an operator sets,\n // or a fetch it caches) and every identity claim it will ever trust is\n // checked against it. One key serves every integration; there is no\n // per-integration outbound credential to store, paste, or rotate.\n server.get('/api/integrations/verify-key', (c) => c.json({ alg: 'ed25519', key: assertions.verifyKey }));\n\n // ── THE OPERATOR SEAM ────────────────────────────────────────\n //\n // Everything that decides WHICH integrations this deployment trusts. Keyed,\n // principal-less, and 404 without — a stranger who finds the path gets the\n // same answer as a stranger with a wrong key, which is nothing.\n //\n // What is deliberately NOT here: installing one for a studio. That is a\n // tenant decision made by somebody signed in, so it lives on the app's own\n // surfaces under the charter, where it can be audited against a person.\n const operator = new Hono<Env>();\n // The constant-time key check, plus the app's own gate over the whole prefix\n // if it supplied one (runtime.operatorGate). See guardOperator.\n guardOperator(operator, { key: runtime.operatorKey ?? '', gate: runtime.operatorGate });\n\n operator.get('/integrations', async (c) => c.json({ integrations: await listIntegrations(runtime.pool) }));\n\n // Register / announce / re-import — one verb.\n //\n // THE ORDER HERE IS THE WHOLE SAFETY STORY. Intake validates the payload, the\n // candidate action set is verified against the charter, and only then do rows\n // land. A bundle that would make the manifest incoherent is refused with a\n // sentence while the previous import keeps serving — because `refresh()`\n // throws on an incoherent charter, and a bundle committed before that check\n // would take the app down until somebody deleted rows by hand.\n operator.post('/integrations', async (c) => {\n const body = (await c.req.json().catch(() => ({}))) as { id?: unknown; url?: unknown };\n const id = typeof body.id === 'string' ? body.id : '';\n const url = typeof body.url === 'string' ? body.url : '';\n if (id === '' || url === '') return c.json({ message: 'Give an id and a url.' }, 400);\n\n let payload: unknown;\n try {\n const response = await fetch(`${url.replace(/\\/$/, '')}/bundle`);\n if (!response.ok) throw new Error(String(response.status));\n payload = await response.json();\n } catch {\n await runtime.pool.query(\n `INSERT INTO integrations (id, url, last_error) VALUES ($1, $2, $3)\n ON CONFLICT (id) DO UPDATE SET url = EXCLUDED.url, last_error = EXCLUDED.last_error`,\n [id, url, 'the service did not answer with a bundle'],\n );\n return c.json({ message: 'The integration did not answer with a bundle.' }, 502);\n }\n\n const fingerprints = new Set((await data.engine.cache.keys?.()) ?? []);\n const result = runIntake(payload, intakeContextOf(app, id, fingerprints, grammars));\n if (!result.ok) {\n await runtime.pool.query(\n `INSERT INTO integrations (id, url, last_error) VALUES ($1, $2, $3)\n ON CONFLICT (id) DO UPDATE SET url = EXCLUDED.url, last_error = EXCLUDED.last_error`,\n [id, url, result.reasons.join('; ')],\n );\n return c.json({ message: 'Refused.', reasons: result.reasons }, 422);\n }\n\n // Press crosses HERE — after the gate, before the dry-run below touches\n // the live manifest — so a press refusal leaves the app exactly as it\n // found it. Blobs written before a later refusal are orphans in the\n // host's store, which is cheaper than any coherence they could buy.\n const press = await copyPress(result.bundle, id, url, app.storePress);\n if (!press.ok) {\n await runtime.pool.query(\n `INSERT INTO integrations (id, url, last_error) VALUES ($1, $2, $3)\n ON CONFLICT (id) DO UPDATE SET url = EXCLUDED.url, last_error = EXCLUDED.last_error`,\n [id, url, press.reasons.join('; ')],\n );\n return c.json({ message: 'Refused.', reasons: press.reasons }, 422);\n }\n\n // The candidate manifest, verified BEFORE anything is written.\n const existing = await runtime.pool.query('SELECT status, key_hash FROM integrations WHERE id = $1', [id]);\n const existingRow = existing.rows[0] as { status?: unknown; key_hash?: unknown } | undefined;\n const wasApproved = String(existingRow?.status ?? '') === 'approved';\n const holdsKey = typeof existingRow?.key_hash === 'string' && existingRow.key_hash !== '';\n if (wasApproved) {\n const restore = { ...app.actions };\n app.actions = { ...app.actions, ...result.bundle.actions };\n try {\n refresh();\n } catch (err) {\n app.actions = restore;\n refresh();\n return c.json({ message: 'Refused — the app would not serve this.', reasons: [String(err)] }, 422);\n }\n }\n\n await runtime.pool.query(\n `INSERT INTO integrations (id, url, title, tagline, description, adds, settings_action, requested_actions, requested_data, reach, frames, phrasebook, story, highlights, press, offers, needs, capabilities, configuration, documents, assistants, last_import_at, last_error)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8::jsonb, $9::jsonb, $10::jsonb, $11::jsonb, $12::jsonb, $13::jsonb, $14::jsonb, $15::jsonb, $16::jsonb, $17::jsonb, $18::jsonb, $19::jsonb, $20::jsonb, $21::jsonb, now(), NULL)\n ON CONFLICT (id) DO UPDATE SET url = EXCLUDED.url,\n title = EXCLUDED.title, tagline = EXCLUDED.tagline, description = EXCLUDED.description,\n adds = EXCLUDED.adds, settings_action = EXCLUDED.settings_action,\n requested_actions = EXCLUDED.requested_actions,\n requested_data = EXCLUDED.requested_data,\n reach = EXCLUDED.reach, frames = EXCLUDED.frames,\n phrasebook = EXCLUDED.phrasebook,\n story = EXCLUDED.story, highlights = EXCLUDED.highlights, press = EXCLUDED.press,\n offers = EXCLUDED.offers, needs = EXCLUDED.needs,\n capabilities = EXCLUDED.capabilities,\n configuration = EXCLUDED.configuration,\n documents = EXCLUDED.documents,\n assistants = EXCLUDED.assistants,\n last_import_at = now(), last_error = NULL`,\n [\n id,\n url,\n result.bundle.meta.title,\n result.bundle.meta.tagline,\n result.bundle.meta.description,\n describePlacements(result.bundle, app.placementNames ?? {}),\n result.bundle.settings,\n JSON.stringify(result.bundle.grants.actions),\n JSON.stringify(result.bundle.grants.data),\n // Re-derived on every import, so a screen an integration DROPPED takes its\n // endpoint's reach with it. An allow-list that only ever grows is a\n // list of everything the integration has ever been able to do.\n JSON.stringify(reachOf(result.bundle, id)),\n JSON.stringify(result.bundle.frames),\n // The integration's own words, in the languages it speaks — stored beside\n // its actions so the app's language pass can reach them, and\n // re-imported whole like everything else about a bundle.\n JSON.stringify(result.bundle.phrasebook),\n JSON.stringify(result.bundle.meta.story),\n JSON.stringify(result.bundle.meta.highlights),\n // The urls the HOST answered with at copyPress — the declared paths\n // died the moment the bytes crossed.\n JSON.stringify(press.urls),\n // What it tells and hears — carried, never read here; the host's bus\n // is the consumer.\n JSON.stringify(result.bundle.offers),\n JSON.stringify(result.bundle.needs),\n // The verbs it gates on — carried the same way; the host's role editor\n // is the consumer.\n JSON.stringify(result.bundle.capabilities),\n // What a builder may set — carried the same way; the host's per-product\n // settings form is the consumer, and the delivery is the assertion's.\n JSON.stringify(result.bundle.configuration),\n // What an add-on lets a person edit — carried the same way; the host's\n // editor is the consumer.\n JSON.stringify(result.bundle.documents),\n // What an add-on's assistant knows — carried the same way; the host's\n // assistant is the consumer.\n JSON.stringify(result.bundle.assistants),\n ],\n );\n await runtime.pool.query('DELETE FROM integration_actions WHERE integration_id = $1', [id]);\n for (const [actionId, definition] of Object.entries(result.bundle.actions)) {\n const binding = result.bundle.attachments[actionId];\n const attachTo = binding === undefined ? '' : typeof binding === 'string' ? binding : binding.to;\n const preview = binding === undefined || typeof binding === 'string' ? '' : binding.preview;\n await runtime.pool.query(\n // Stamped current: runIntake upgraded every definition to this code's grammars.\n 'INSERT INTO integration_actions (integration_id, action_id, definition, attach_to, preview, place_in, grammar) VALUES ($1, $2, $3::jsonb, $4, $5, $6, $7::jsonb)',\n [id, actionId, JSON.stringify(definition), attachTo, preview, result.bundle.placements[actionId] ?? '', JSON.stringify(grammars.stamp)],\n );\n }\n\n // MINTED ONCE, SHOWN ONCE. Registration is a GRANTING ceremony — the\n // deployment issues the integration its identity, never the other way\n // around — so the first registration answers with the key and the row\n // keeps only the hash. A re-import repeats neither: the key is not stored,\n // so there is nothing to repeat. Losing it is not recovery, it is removal\n // and re-registration, which also re-fences everything the old key held.\n const key = holdsKey ? undefined : mintIntegrationKey();\n if (key !== undefined) {\n await runtime.pool.query('UPDATE integrations SET key_hash = $2 WHERE id = $1', [id, hashIntegrationKey(key)]);\n }\n\n await reloadIntegrations();\n const status = wasApproved ? 'approved' : 'pending';\n return c.json({ id, status, actions: Object.keys(result.bundle.actions).length, ...(key === undefined ? {} : { key }) });\n });\n\n // APPROVAL IS WHERE THE GRANTS BECOME REAL.\n //\n // Registration only records what an integration ASKED for. Nothing it ships\n // is served until somebody looks at the two lists side by side and says yes —\n // which is what keeps \"the charter denies what it does not know\" true while\n // still letting an integration name what it needs.\n //\n // Approving is also the moment its actions join the manifest, so this is the\n // second place the candidate set is verified before anything is served.\n operator.post('/integrations/:id/approve', async (c) => {\n const id = c.req.param('id');\n const row = await runtime.pool.query('SELECT requested_data FROM integrations WHERE id = $1', [id]);\n if (row.rows[0] === undefined) return c.json({ message: 'No such integration.' }, 404);\n const requested = ((row.rows[0] as { requested_data?: unknown }).requested_data ?? []) as string[];\n await runtime.pool.query(\n \"UPDATE integrations SET status = 'approved', approved_data = $2::jsonb WHERE id = $1\",\n [id, JSON.stringify(requested)],\n );\n try {\n await reloadIntegrations();\n } catch (err) {\n await runtime.pool.query(\"UPDATE integrations SET status = 'pending', last_error = $2 WHERE id = $1\", [id, String(err)]);\n await reloadIntegrations();\n return c.json({ message: 'Refused — the app would not serve this.', reasons: [String(err)] }, 422);\n }\n return c.json({ id, status: 'approved', granted: requested });\n });\n\n // Uninstalling for good: the rows go, the actions leave the manifest, and a\n // living shell adopts. What the integration stored stays with the integration\n // — which is why reinstalling restores it.\n operator.delete('/integrations/:id', async (c) => {\n const id = c.req.param('id');\n await runtime.pool.query('DELETE FROM integrations WHERE id = $1', [id]);\n await reloadIntegrations();\n return c.json({ id, removed: true });\n });\n\n // A LIVE CALL, because \"the screen is empty\" has three causes in three\n // systems and an operator should not have to guess which. This says what the\n // integration answered, right now, without a browser or a signed-in person.\n //\n // It probes what the integration DECLARED, plus `bundle` — which is the\n // answer to \"the screen is empty\" most of the time and is open by design\n // anyway. It used to take an operator-chosen arbitrary path, which made this\n // a second door into the integration's service beside the proxy, and one that minted\n // no assertion at all. An operator wanting a path the integration never declared is\n // asking a question about somebody else's service, not about this one.\n operator.post('/integrations/:id/probe', async (c) => {\n const id = c.req.param('id');\n const row = await runtime.pool.query('SELECT url, reach FROM integrations WHERE id = $1', [id]);\n const found = row.rows[0] as { url?: string; reach?: unknown } | undefined;\n const url = found?.url;\n if (url === undefined) return c.json({ message: 'No such integration.' }, 404);\n const body = (await c.req.json().catch(() => ({}))) as { path?: unknown };\n const path = typeof body.path === 'string' ? body.path : 'bundle';\n // The declaration holds lyra-side paths (`/integrations/<id>/roster`); a\n // probe names the integration-side tail (`roster`), the same tail the proxy\n // forwards. One spelling to compare, derived rather than stored twice.\n if (path !== 'bundle' && !reachDeclares((found?.reach ?? {}) as Reach, `/integrations/${id}/${path}`)) {\n return c.json({ message: 'That path is not one this integration declared.' }, 404);\n }\n const started = Date.now();\n try {\n const response = await fetch(`${url.replace(/\\/$/, '')}/${path}`);\n const text = await response.text();\n return c.json({ status: response.status, ms: Date.now() - started, body: text.slice(0, 2000) });\n } catch (err) {\n return c.json({ status: 0, ms: Date.now() - started, body: String(err) });\n }\n });\n\n server.route('/operator', operator);\n\n // ── THE FRAME SEAM ───────────────────────────────────────────\n //\n // Lyra validates every layout against a fixed component vocabulary and\n // refuses a bundle naming anything else, which is what stops an untrusted\n // integration rendering arbitrary UI. That holds until a vendor's own browser SDK is\n // the only way to draw something — a payment onboarding form nobody else may\n // collect the fields for. The alternative to this seam is the HOST importing\n // that vendor's SDK, which is worse: it makes every app that ever installs\n // the integration carry the dependency.\n //\n // So the integration serves a page and the host frames it, at the host's own origin.\n //\n // AN IFRAME CARRIES NO AUTHORIZATION HEADER. The session token lives in\n // localStorage and `src=` is a plain browser GET, so the one thing every\n // other surface here relies on is exactly what this path cannot have. The\n // screen therefore asks for a GRANT over its own authenticated wire, and the\n // iframe spends it.\n //\n // THE GRANT IS OPAQUE AND LOCAL — deliberately NOT a signed assertion. It\n // travels in a URL, where things linger: history, logs, a Referer. Anything\n // this deployment's key signs is something an integration accepts as identity, so a\n // signed grant leaking from a URL bar would be an identity token leaking. A\n // random string in a Map cannot be replayed as anything; it is redeemed here,\n // and what crosses to the integration is a fresh assertion exactly like every other\n // call. Held in memory for the same reason the signing keypair is: it lives\n // two minutes, and a restart costs one reload.\n //\n // Reusable within its life rather than strictly once — a reload must not\n // break the screen somebody is halfway through.\n const grants = new Map<string, { integration: string; principal: string; path: string; expires: number }>();\n // LONG ENOUGH TO FINISH THE FORM. Two minutes was the first guess and it is\n // wrong for the thing this exists for: a payment onboarding form asks a\n // business for its details, and somebody goes and finds a document. Re-minting\n // mid-way is not an option either — the src changing remounts the frame and\n // takes the half-filled form with it.\n //\n // It stays cheap to hold: opaque, single-principal, single-path, redeemable\n // only at this origin, and gone on restart.\n const GRANT_TTL_MS = 30 * 60_000;\n const sweepGrants = (now: number): void => {\n for (const [token, grant] of grants) if (now >= grant.expires) grants.delete(token);\n };\n\n server.post('/api/integrations/frame', async (c) => {\n const principal = c.get('principal');\n if (principal === null) return c.json({ message: 'Sign in first.' }, 401);\n const body = (await c.req.json().catch(() => ({}))) as { path?: unknown };\n const path = typeof body.path === 'string' ? body.path : '';\n const id = path.split('/')[2] ?? '';\n const row = await runtime.pool.query('SELECT status, frames FROM integrations WHERE id = $1', [id]);\n const found = row.rows[0] as { status?: string; frames?: unknown } | undefined;\n if (found === undefined || found.status !== 'approved') return c.json({ message: 'No such integration.' }, 404);\n const resolved = await resolveIdentity(principal);\n if (resolved.installed !== undefined && !resolved.installed.includes(id)) return c.json({ message: 'Not installed here.' }, 404);\n // THE DECLARATION IS THE PERIMETER HERE TOO. A grant is only ever minted\n // for a page the bundle named at intake, so a screen cannot frame a path\n // the integration never published — including one it serves but did not declare.\n //\n // AND FOR THE SCREEN THAT OWNS IT. This door had the same hole the proxy\n // did, and a worse one to have: `frames` was a bare list of paths with no\n // owner at all, so the only questions askable were \"signed in?\" and\n // \"installed here?\". A member of the gym passed both and could be served the\n // page that mounts a payment provider's onboarding form against the\n // studio's merchant account. The bundle names the owning action now, and a\n // grant is minted only for somebody who holds it.\n const held = new Set(catalog(resolved).ids);\n if (!frameAdmits((found.frames ?? {}) as Record<string, string>, path, held)) return c.json({ message: 'No such frame.' }, 404);\n\n const now = Date.now();\n sweepGrants(now);\n const token = randomBytes(24).toString('hex');\n grants.set(token, { integration: id, principal, path, expires: now + GRANT_TTL_MS });\n return c.json({ src: `/integrations/${id}/frame/${token}`, expiresIn: GRANT_TTL_MS });\n });\n\n // Redeeming: a document GET, no session, one token. Registered before the\n // proxy so `/integrations/:id/*` does not match first and demand a principal.\n server.get('/integrations/:id/frame/:token', async (c) => {\n const id = c.req.param('id');\n const now = Date.now();\n sweepGrants(now);\n const grant = grants.get(c.req.param('token'));\n // One answer for expired, unknown, and minted-for-another-integration. A grant is\n // a URL somebody may still have; what it opens is nothing.\n if (grant === undefined || grant.integration !== id || now >= grant.expires) {\n return c.json({ message: 'Not found.' }, 404);\n }\n // Re-checked at REDEEM, not just at mint: an uninstall between the two is\n // exactly the moment a stale tab must stop working.\n const row = await runtime.pool.query('SELECT url, status FROM integrations WHERE id = $1', [id]);\n const found = row.rows[0] as { url?: string; status?: string } | undefined;\n if (found === undefined || found.status !== 'approved') return c.json({ message: 'Not found.' }, 404);\n const installed = (await resolveIdentity(grant.principal)).installed;\n if (installed !== undefined && !installed.includes(id)) return c.json({ message: 'Not found.' }, 404);\n\n const scope = await scopeValuesFor(grant.principal);\n const rest = grant.path.split('/').slice(3).join('/');\n try {\n const response = await fetch(`${String(found.url).replace(/\\/$/, '')}/${rest}`, {\n headers: { authorization: `Bearer ${assertions.mint({ integration: id, principal: grant.principal, scope })}` },\n });\n // THE INTEGRATION'S OWN CONTENT TYPE TRAVELS. A framed page is HTML; forcing\n // `application/json` the way the proxy below used to would hand the\n // browser a document it will not render.\n return new Response(response.body, {\n status: response.status,\n headers: { 'content-type': response.headers.get('content-type') ?? 'text/html; charset=utf-8' },\n });\n } catch {\n return c.json({ message: 'The integration is unreachable.' }, 502);\n }\n });\n\n // A FRAMED PAGE CALLING BACK ON ITS OWN GRANT.\n //\n // The page is sandboxed without `allow-same-origin` (lyra's Frame component),\n // so it has an opaque origin and no session — it cannot call the proxy, and it\n // has nothing to authenticate with but the grant it was opened by. Without\n // this it is a dead-end document, which is not enough for the thing frames\n // exist for: a vendor's embedded component asks the server for a fresh\n // short-lived session while somebody is mid-form.\n //\n // BOUNDED TO ONE SEGMENT BESIDE THE DECLARED PAGE. `embed/onboarding` may call\n // `embed/session` and nothing else — no slashes, no dots, no climbing. The\n // grant already fixes which integration, which principal and which page; this fixes\n // how far a page may reach from where it was let in.\n const CALLBACK = /^[a-z0-9][a-z0-9-]*$/;\n\n server.post('/integrations/:id/frame/:token/:call', async (c) => {\n const id = c.req.param('id');\n const call = c.req.param('call');\n const now = Date.now();\n sweepGrants(now);\n const grant = grants.get(c.req.param('token'));\n if (grant === undefined || grant.integration !== id || now >= grant.expires) return c.json({ message: 'Not found.' }, 404);\n if (!CALLBACK.test(call)) return c.json({ message: 'Not found.' }, 404);\n\n const row = await runtime.pool.query('SELECT url, status FROM integrations WHERE id = $1', [id]);\n const found = row.rows[0] as { url?: string; status?: string } | undefined;\n if (found === undefined || found.status !== 'approved') return c.json({ message: 'Not found.' }, 404);\n const installed = (await resolveIdentity(grant.principal)).installed;\n if (installed !== undefined && !installed.includes(id)) return c.json({ message: 'Not found.' }, 404);\n\n // Beside the page, never above it: the declared frame's own directory.\n const rest = grant.path.split('/').slice(3);\n rest.pop();\n const target = [...rest, call].join('/');\n\n const scope = await scopeValuesFor(grant.principal);\n try {\n const response = await fetch(`${String(found.url).replace(/\\/$/, '')}/${target}`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n authorization: `Bearer ${assertions.mint({ integration: id, principal: grant.principal, scope })}`,\n },\n body: await c.req.text(),\n });\n return new Response(response.body, {\n status: response.status,\n headers: {\n 'content-type': response.headers.get('content-type') ?? 'application/json',\n // THE CALLER IS AN OPAQUE ORIGIN, and that is deliberate: the framed\n // page is sandboxed WITHOUT `allow-same-origin` so it cannot reach\n // this app's storage or session. The cost is that its `Origin` is\n // literally `null`, and a browser refuses the response without a\n // matching allowance — which is what a vendor's embedded component\n // hits the moment it asks for a fresh session.\n //\n // CORS IS NOT THE FENCE HERE, so opening it costs nothing. The\n // credential is the unguessable, short-lived, single-path grant in the\n // URL; anybody holding it can call this from a server where CORS does\n // not apply at all. Refusing the browser only breaks the one caller\n // this route exists for.\n 'access-control-allow-origin': 'null',\n vary: 'origin',\n },\n });\n } catch {\n return c.json({ message: 'The integration is unreachable.' }, 502);\n }\n });\n\n // ── THE WEBHOOK DOOR ─────────────────────────────────────────\n //\n // The only unauthenticated surface on this server that DOES something, and it\n // is narrow on purpose.\n //\n // A vendor calling in has no session and no key — it could not have one, since\n // nobody is driving. So identity does not travel here at all: no principal is\n // required and NO ASSERTION IS MINTED. The integration authenticates the\n // caller itself, against the vendor's own signature, which is the only party\n // that can vouch for a call moss cannot.\n //\n // THE BODY ARRIVES BYTE-IDENTICAL. A signature is computed over exact bytes,\n // and a JSON round-trip through this process would re-order one key and break\n // every verification downstream. Nothing on this path parses the body — it is\n // read as an ArrayBuffer and handed on.\n //\n // Registered BEFORE the proxy below, because `server.all('/integrations/:id/*')`\n // would otherwise match first and demand a principal.\n //\n // A DOOR WE DID NOT LOCK NEEDS A LIMIT. Every other surface is bounded by a\n // credential; this one is bounded by the vendor behaving. In-process and per\n // integration, so a deployment on two machines gets two ceilings — the honest\n // cost of not putting a shared store behind this yet.\n const hookHits = new Map<string, { count: number; resets: number }>();\n const HOOK_LIMIT = 240;\n const HOOK_WINDOW_MS = 60_000;\n const hookAllows = (id: string, now: number): boolean => {\n const seen = hookHits.get(id);\n if (seen === undefined || now >= seen.resets) {\n hookHits.set(id, { count: 1, resets: now + HOOK_WINDOW_MS });\n return true;\n }\n seen.count += 1;\n return seen.count <= HOOK_LIMIT;\n };\n\n server.post('/integrations/:id/hook/*', async (c) => {\n const id = c.req.param('id');\n const row = await runtime.pool.query('SELECT url, status FROM integrations WHERE id = $1', [id]);\n const found = row.rows[0] as { url?: string; status?: string } | undefined;\n // 404 for \"no such integration\" AND for \"not approved yet\" — the same\n // answer, so a stranger probing this learns nothing about which integrations a\n // deployment is currently considering.\n if (found === undefined || found.status !== 'approved') return c.json({ message: 'Not found.' }, 404);\n if (!hookAllows(id, Date.now())) return c.json({ message: 'Too many.' }, 429);\n\n const here = new URL(c.req.url);\n const rest = `${here.pathname.split('/').slice(3).join('/')}${here.search}`;\n // Every header the vendor set travels, because the signature is in one of\n // them and moss does not know which. `authorization` is dropped: this path\n // mints no identity, and a bearer arriving here must not read as one on the\n // other side. `host` would name us rather than them.\n const headers = new Headers(c.req.raw.headers);\n headers.delete('authorization');\n headers.delete('host');\n try {\n const response = await fetch(`${String(found.url).replace(/\\/$/, '')}/${rest}`, {\n method: 'POST',\n headers,\n body: await c.req.arrayBuffer(),\n });\n return new Response(response.body, {\n status: response.status,\n headers: { 'content-type': response.headers.get('content-type') ?? 'application/json' },\n });\n } catch {\n // A vendor reads 502 as \"retry me\", which is what we want: the delivery\n // is not lost, it is deferred until the integration is back.\n return c.json({ message: 'The integration is unreachable.' }, 502);\n }\n });\n\n // THE PROXY.\n //\n // Identity travels INSIDE a signed assertion, never as bare headers. The\n // token carries the integration it is for, the principal, the same scope\n // values the resolver gives vex for `$scope`, and an expiry seconds out —\n // signed with the deployment's key, whose public half the integration holds.\n // A claim outside a verified envelope is not refused over there; it simply\n // is not identity, which is what makes the safe path the only path. The\n // body stays caller-controlled and untrusted, exactly as a vex `$context`\n // is: an integration reading `studio_id` from the body has reintroduced the\n // hole whatever we sign.\n server.all('/integrations/:id/*', async (c) => {\n const principal = c.get('principal');\n if (principal === null) return c.json({ message: 'Sign in first.' }, 401);\n const id = c.req.param('id');\n const row = await runtime.pool.query('SELECT url, status, reach FROM integrations WHERE id = $1', [id]);\n const found = row.rows[0] as { url?: string; status?: string; reach?: unknown } | undefined;\n if (found === undefined || found.status !== 'approved') return c.json({ message: 'No such integration.' }, 404);\n const resolved = await resolveIdentity(principal);\n if (resolved.installed !== undefined && !resolved.installed.includes(id)) return c.json({ message: 'Not installed here.' }, 404);\n\n // THE DECLARATION IS THE PERIMETER (integrations.ts, reachOf). Before this,\n // being signed in at a studio that installed an integration was permission to call\n // ANY path the integration's service happened to serve — its internals, its\n // admin verbs, whatever it grew next release. Now it is permission to call\n // the paths the integration declared, and nothing is forwarded for the rest.\n //\n // AND ONLY THE ONES THIS CALLER'S OWN SCREENS DECLARE. The path check alone\n // was half the fence: reach is the union over every action in the bundle, so\n // a member at a studio with payments installed reached the merchant\n // onboarding endpoint — the charter's `ext.desk.*` fence decided which\n // SCREENS rendered and nothing about which endpoints answered. The catalog\n // is the same one the shell is built from, so a door and the screen that\n // opens it can no longer disagree.\n //\n // Checked BEFORE the assertion is minted: an inadmissible path gets no\n // credential, not even one that would have died at the other end. And 404\n // rather than 403, like the branches above it — what somebody may not reach,\n // they do not learn the existence of.\n const held = new Set(catalog(resolved).ids);\n if (!reachAdmits((found.reach ?? {}) as Reach, c.req.path, held)) return c.json({ message: 'No such integration.' }, 404);\n\n const scope = await scopeValuesFor(principal);\n // The QUERY TRAVELS. `c.req.path` drops it, so an endpoint declared with\n // `?view=summary` arrived at the integration without it — the integration answered a\n // different question than the screen asked, and nothing said so.\n const here = new URL(c.req.url);\n const rest = `${here.pathname.split('/').slice(3).join('/')}${here.search}`;\n const headers: Record<string, string> = {\n 'content-type': 'application/json',\n authorization: `Bearer ${assertions.mint({ integration: id, principal, scope })}`,\n };\n try {\n const response = await fetch(`${String(found.url).replace(/\\/$/, '')}/${rest}`, {\n method: c.req.method,\n headers,\n ...(c.req.method === 'GET' ? {} : { body: await c.req.text() }),\n });\n // What the integration answered WITH, not what we assumed it answered with.\n return new Response(response.body, {\n status: response.status,\n headers: { 'content-type': response.headers.get('content-type') ?? 'application/json' },\n });\n } catch {\n // An integration that is down is an ordinary condition: the action's\n // onError shows the sentence and nothing is claimed.\n return c.json({ message: 'The integration is unreachable.' }, 502);\n }\n });\n\n // The socket speaks for the same principals the HTTP surfaces serve —\n // one session verifier, one catalog resolution, one version token. When\n // the manifest declares a shell, server shells stand behind it: their\n // endpoint calls ride the server's OWN surfaces with the session's token\n // (same wire, same enforcement — the shell is just another client).\n //\n // ONE CONTEXT, for the app's host and for every page's: who a principal is,\n // the governed wire and the environment are the same wherever a shell is\n // built. What differs is the manifest it is built from and whether it is kept.\n const entriesNow = (): ReadonlyMap<string, SeedEntry | SeedMutation> => new Map((app.entries ?? []).map((entry) => [entry.fingerprint, entry]));\n const shellContext: ShellHostContext = {\n app,\n needOf: (definition) => shellNeedOf(definition, entriesNow()),\n // ONE resolution per shell build, awaited. This was four synchronous\n // questions, and every one of them was ultimately answered out of a\n // resident map of the population.\n resolve: async (principal) => {\n const resolved = await resolveIdentity(principal);\n // THE INSTALL LIST IS RE-READ AT BUILD. A shell is the long-lived\n // thing here: an identity record may have been resolved before the\n // tenant installed an integration, and a shell built from it would be missing\n // that integration's screens for the life of the session. Once per shell,\n // not once per request — the seam this consults is synchronous and\n // cheap, and it is the same one `adopt` re-reads for the same reason.\n // The record IS the install list now — resolved through the same\n // engine entries as everything else, revalidated on the identity\n // cache's own clock.\n return { roles: resolved.roles, scope: resolved.scope, installed: resolved.installed, catalog: catalog(resolved), variants: variants(resolved), policy: policy(resolved) };\n },\n catalogFor: (roles, installed) => catalog(asRoles(roles, installed)),\n variantsFor: (roles) => variants(asRoles(roles, undefined)),\n runtime,\n ...(runtime.shellIdleMs !== undefined ? { idleMs: runtime.shellIdleMs } : {}),\n ...(runtime.shellFrameDelta !== undefined ? { delta: runtime.shellFrameDelta } : {}),\n wire: (token) => async (url, init) => {\n const isVex = url.split('?')[0]?.endsWith('/vex') === true;\n // A vex read made for a caller that can be told when to stop — a\n // nova endpoint passes its instance's signal — may keep answering\n // (`refresh: 'reactive'`; see ./follow.ts). The follower rides the\n // in-process request's env, where no network request can put one.\n const follower = isVex && init?.signal !== undefined ? createWireFollower(init.signal) : undefined;\n const res = await server.request(\n url,\n {\n method: init?.method ?? 'GET',\n headers: { ...(init?.headers ?? {}), ...(token !== null ? { Authorization: `Bearer ${token}` } : {}) },\n ...(init?.body !== undefined ? { body: init.body } : {}),\n },\n follower === undefined ? undefined : { [VEX_LIVE_ENV]: follower.live },\n );\n // Vex replies `{ result, meta }`; endpoints want the data — the\n // same unwrap the client wire applies, so an action behaves\n // identically under either shell.\n if (!isVex || !res.ok) {\n follower?.end();\n return res;\n }\n const body = (await res.json()) as Record<string, unknown> | null;\n const result = body !== null && typeof body === 'object' && 'result' in body ? body['result'] : body;\n follower?.handedOver();\n return {\n ok: res.ok,\n status: res.status,\n json: () => Promise.resolve(result),\n text: () => Promise.resolve(JSON.stringify(result)),\n ...(follower === undefined ? {} : { onChange: follower.onChange }),\n };\n },\n };\n const shells = app.shell !== undefined ? createShellHost(shellContext) : undefined;\n\n // PAGES: a host each, built from the page's own manifest and keeping nothing\n // (app.ts § pages). The router refuses two pages that could answer one path,\n // here, at boot — like every other incoherence.\n const pageManifests = app.pages ?? {};\n const pageRouter = createPageRouter(pageManifests);\n const pageHosts = new Map(Object.entries(pageManifests).map(([name, manifest]) => [name, createShellHost({ ...shellContext, manifest, kept: false })]));\n const pageAt = (path: string): { name: string; host: ShellHost; inputs: Record<string, Record<string, unknown>> } | undefined => {\n const matched = pageRouter.match(path);\n if (matched === undefined) return undefined;\n const host = pageHosts.get(matched.name);\n const manifest = pageManifests[matched.name];\n if (host === undefined || manifest === undefined) return undefined;\n return { name: matched.name, host, inputs: manifest.params === undefined ? {} : { [manifest.params]: matched.params } };\n };\n\n // THE CLUSTER FABRIC. One origin per process, stamped on every signal so a\n // process ignores its own echoes. The three appliers below are LOCAL-ONLY —\n // they mutate what this process holds and never publish — and are shared by\n // two callers: a remote signal (through `wireFabric`'s subscriber) and this\n // server's own methods, which run the applier THEN publish. Absent a fabric,\n // `publishFabric` is a no-op and nothing is subscribed. `refresh` is\n // deliberately not here: it rides the generation pointer, which is persistent\n // and survives a restart, because the manifest it guards has no other heal\n // clock (fabric.ts, generation.ts).\n const fabricOrigin = randomBytes(8).toString('hex');\n const applyInvalidateIdentity = (principal: string): boolean => {\n const held = identities?.invalidate(principal) ?? false;\n shells?.reset(principal);\n return held;\n };\n const applyInvalidateTenant = (tag: string): number => (identities?.invalidateTag(tag) ?? []).length;\n // Wake one principal's shell, payload-less — the shell re-reads. If that\n // principal is resident here it wakes; if not, this is a no-op and the process\n // that holds them applies the same signal. No tag lookup: `deliver` is\n // per-principal, and the identity cache is deliberately not a by-tenant index.\n const applyNudge = (principal: string, channel: string): void => {\n shells?.deliver(principal, channel);\n };\n const publishFabric = wireFabric(runtime.fabric, fabricOrigin, {\n invalidateIdentity: applyInvalidateIdentity,\n invalidateTenant: applyInvalidateTenant,\n nudge: applyNudge,\n });\n\n // Artifacts changed at runtime — an app that loads actions from rows and\n // just wrote new ones. Same gates as boot (an incoherent publish REFUSES and\n // the process keeps serving the old resolution), then the memos drop and\n // living shells adopt their re-resolved definitions in place: no rebuild,\n // no lost canvas state, new actions simply become pushable.\n const refresh = (): void => {\n refreshLocal();\n // EVERY OTHER PROCESS TOO. `refresh` means rows changed under a derivation,\n // and this process is not the only one holding derivations from them.\n generation?.bump();\n };\n\n // The same drop, without moving the pointer -- what a process does when it\n // OBSERVES a move somebody else made. Bumping here would have every process\n // bump every other process forever.\n const refreshLocal = (): void => {\n const nextReport = verifyCharter(\n app.charter,\n { actions: Object.keys(app.actions), data: data.grants, layouts: Object.keys(app.layouts ?? {}) },\n wearableOf(app),\n auditClosure(app.actions, app.layouts),\n );\n if (nextReport.errors.length > 0) {\n throw new Error(`Refresh refused — charter incoherent over the new artifacts:\\n${nextReport.errors.map((e) => ` ${e.rule}: ${e.detail}`).join('\\n')}`);\n }\n const nextVariantErrors = verifyVariants(app);\n if (nextVariantErrors.length > 0) {\n throw new Error(`Refresh refused — layout variants incoherent:\\n${nextVariantErrors.map((e) => ` ${e}`).join('\\n')}`);\n }\n verifiedReport = nextReport;\n // IDENTITY GOES WITH THEM. `refresh` exists because something the\n // resolutions were derived FROM changed — an approval, a role, an artifact.\n // Dropping the compiled policies while keeping the records they were\n // compiled from is keeping the stale half: a promoted instructor would hold\n // their old rung until the record expired on its own clock.\n identities?.invalidateAll();\n policies.clear();\n // `reachPolicies` too — it is compiled from the same grants as `policies`\n // and went stale with it. Leaving it standing meant an approval or a role\n // change was honoured at the caller's own reach and ignored at every reach\n // an entry declared, for the life of the process.\n reachPolicies.clear();\n catalogs.clear();\n variantBindings.clear();\n shells?.adopt();\n };\n\n // WHATEVER WAS APPROVED BEFORE THIS PROCESS STARTED is part of the\n // application, so it is folded in before anything is served — not on first\n // request and not on a timer. It happens here rather than beside the routes\n // because it calls `refresh`, which is declared below them.\n {\n const fromRows = await loadIntegrationActions(runtime.pool, grammars);\n if (Object.keys(fromRows).length > 0) {\n app.actions = { ...staticActions, ...fromRows };\n refresh();\n }\n }\n\n generation = createGeneration(runtime.pool, {\n ...(runtime.sessionRevalidateMs !== undefined ? { everyMs: runtime.sessionRevalidateMs } : {}),\n onMoved: async () => {\n // Somebody else wrote. Re-read what is loaded FROM rows (an approval lands\n // as new actions), then drop every derivation without moving the pointer\n // again.\n const fromRows = await loadIntegrationActions(runtime.pool, grammars);\n app.actions = { ...staticActions, ...fromRows };\n refreshLocal();\n },\n });\n\n // Held in a local, not inlined below, because `close` has to reach its\n // `stop` — the socket's revalidation timer is one of the four this server\n // retires.\n const socket = createSocket({\n session,\n catalog: async (principal) => catalog(await resolveIdentity(principal)),\n ...(shells !== undefined ? { shells } : {}),\n page: pageAt,\n ...(runtime.sessionRevalidateMs !== undefined ? { revalidateMs: runtime.sessionRevalidateMs } : {}),\n ...(runtime.telemetry !== undefined ? { telemetry: runtime.telemetry } : {}),\n ...(runtime.origins !== undefined ? { origins: runtime.origins } : {}),\n ...(runtime.session === 'sessions' ? { sessionLastsMs: (token: string) => sessionRemainingMs(runtime.pool, token) } : {}),\n });\n\n return Object.assign(server, {\n socket,\n principalOf: async (token: string) => session(token),\n page: pageAt,\n pages: Object.entries(pageManifests).map(([name, manifest]) => ({ name, path: manifest.path })),\n ...(shells !== undefined ? { shells } : {}),\n refresh,\n charterReport: () => verifiedReport,\n generation: () => generation?.current() ?? -1,\n // Every timer this server owns, stopped once. Absent pieces (an app with no\n // identity seam, no shells) simply have nothing to stop — the `?.` is the\n // whole guard. See the type above for why this is one call and not four.\n close: () => {\n generation?.stop();\n identities?.stop();\n socket.stop();\n shells?.stop();\n for (const host of pageHosts.values()) host.stop();\n },\n executeAs,\n callIntegration,\n identity: async (principal: string | null) => {\n const resolved = await resolveIdentity(principal);\n return { roles: resolved.roles, scope: resolved.scope, ...(resolved.installed !== undefined ? { installed: resolved.installed } : {}) };\n },\n invalidateTenant: (tag: string) => {\n // FORGETS, AND DOES NOT RESET.\n //\n // Resetting throws a shell away and builds its replacement, which is\n // right for a ROLE change — the landing surface and the nav were seeded\n // from the old rung — and wrong here. A tenant installing an integration changes\n // what its people may REACH, not who they are, and `adopt` (called by\n // `refresh` alongside this) re-resolves every live shell and registers\n // the new definitions in place. Resetting as well would discard whatever\n // anybody at that studio was in the middle of, to arrive at the same\n // screen.\n //\n // A caller who does mean \"rebuild theirs\" has `invalidateIdentity`, which\n // is what a role change uses.\n //\n // Applied locally, then published: a second process forgets the same\n // tenant's records, and its live shells pick up the changed actions\n // through the generation pointer's own adopt — the fabric carries the\n // record-forget, generation carries the manifest.\n const forgotten = applyInvalidateTenant(tag);\n publishFabric({ kind: 'invalidate-tenant', tag });\n return forgotten;\n },\n invalidateIdentity: (principal: string) => {\n // The compiled memos are keyed by (roles + installed), not by principal,\n // so they need no clearing here: a re-resolved record either lands on the\n // same key — in which case the memo was already right — or on a different\n // one, which was never this principal's to begin with.\n //\n // Applied locally, then published: the process where this principal's\n // shell is resident resets it, whichever process that is.\n const held = applyInvalidateIdentity(principal);\n publishFabric({ kind: 'invalidate-identity', principal });\n return held;\n },\n nudge: (principal: string, channel: string) => {\n applyNudge(principal, channel);\n publishFabric({ kind: 'nudge', principal, channel });\n },\n ...(identities !== undefined ? { identities: { list: identities.list, meter: identities.meter } } : {}),\n });\n};\n","import { headOf, placeHead } from '@niscorp/nova/document';\nimport type { ScreenHead } from '@niscorp/nova/document';\nimport type { ShellSnapshot } from './shells';\nimport type { MossServer } from './server';\nimport { DEFAULT_TOKEN_KEY, sessionTokenOf, tokenFromCookie } from './session-cookie';\n\n// ═══════════════════════════════════════════════════════════════\n// The document — what a page request is answered with when the server draws\n// the first screen itself.\n//\n// A page request names a path and carries, at most, a cookie. From those two:\n// WHICH shell (a page's, if the path leads to one; otherwise the app's), for\n// WHOM (the cookie's principal, or nobody), read as it stands\n// (`shells.snapshot`), drawn to a string by a terminal the app hands in\n// (./terminal/react/server and its siblings), and written into the app's own\n// index.html beside the snapshot it was drawn from. The browser's terminal\n// starts from that snapshot (../client's `readDocumentSnapshot`) and adopts the\n// elements already there.\n//\n// Moss holds no opinion about the page around the screen: the template is the\n// app's file, the kit is the app's, and so is the route this is called from.\n//\n// The page's <head> is a node in a layout too (nova's `nova:head`, holding the\n// elements a head holds), so it is in the snapshot's trees like everything\n// else on the screen, and is written into the template's <head> as the screen\n// is written into its root.\n//\n// TWO RULES LIVE HERE, each in one place:\n//\n// WHO MAY KEEP A PAGE follows from who asked, and from nothing else\n// (`documentHeaders`). A page drawn for nobody is the same for everybody; a\n// page drawn for somebody is theirs. No page declares which it is.\n//\n// NOTHING HERE CAN FAIL A PAGE. Whatever goes wrong — a kit component that\n// throws, a shell that will not build — the answer is the template as it is,\n// and the terminal paints it the way it did before any of this existed.\n// ═══════════════════════════════════════════════════════════════\n\n// The element id the terminal looks for — the same constant ../client reads by.\nexport const SNAPSHOT_ELEMENT_ID = 'nisc-snapshot';\n\nconst DEFAULT_ROOT = '<div id=\"root\"></div>';\n\nexport { tokenFromCookie };\n\n// The snapshot, as an element to put in the page. A tree carries what people\n// typed (a name, a note), and it sits inside a <script>: every `<` is written\n// as its escape, so nothing in a tree can close the element or open another.\n// U+2028/2029 go the same way — legal in JSON, line breaks to an HTML parser.\nexport const embedSnapshot = (snapshot: ShellSnapshot, principal: string | null, path?: string): string => {\n const { frame, trees, seed, live } = snapshot;\n const text = JSON.stringify({ frame, trees, principal: principal !== null, live, ...(seed !== undefined ? { seed } : {}), ...(path !== undefined ? { path } : {}) })\n .replace(/</g, '\\\\u003c')\n .replace(/\\u2028/g, '\\\\u2028')\n .replace(/\\u2029/g, '\\\\u2029');\n return `<script type=\"application/json\" id=\"${SNAPSHOT_ELEMENT_ID}\">${text}</script>`;\n};\n\n// A page drawn for somebody is theirs alone: nothing between here and their\n// browser may keep it. A page drawn for nobody is the same for everybody and\n// may be kept — but it must never be handed to a request that carried a\n// credential, so the two are told apart on the cookie.\nexport const documentHeaders = (principal: string | null): Record<string, string> =>\n principal === null ? { 'cache-control': 'no-cache', vary: 'Cookie' } : { 'cache-control': 'private, no-store', vary: 'Cookie' };\n\nconst escapeAttribute = (value: string): string => value.replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;');\n\nexport type DocumentConfig = {\n server: MossServer;\n // The app's index.html, as it would be served undrawn. It must hold the empty\n // root (`root`, default `<div id=\"root\"></div>`) exactly once — that is where\n // the screen goes.\n template: string;\n // What the request named and carried. `host` is its `Host` header: the\n // session cookie's name ends with the port a page is on (session-cookie.ts),\n // so without it a page on a port is drawn for nobody.\n request: { path: string; cookie?: string | null; host?: string | null };\n // A terminal that draws to a string: the app's kit, bound to one of moss's\n // server targets (`renderSnapshot` from ./terminal/react/server, /vue/server,\n // /dom/server).\n draw: (snapshot: ShellSnapshot) => string | Promise<string>;\n // Attributes for the page's <html>, read off the screen — what a kit would\n // otherwise set from an effect that never runs here (a palette, a scheme).\n // Names are the app's and are written as given; values are escaped.\n htmlAttributes?: (snapshot: ShellSnapshot) => Record<string, string>;\n // The address the site is served at (\"https://example.com\"). With it, every\n // path's document says its own canonical address. Without it, where a\n // document lives is left as the template says.\n site?: string;\n // The wire's token key, which the session cookie is named by. Default `nisc.token`.\n tokenKey?: string;\n // How long the screen may take to settle before it is drawn as it stands.\n waitMs?: number;\n root?: string;\n};\n\nexport type DrawnDocument = {\n html: string;\n headers: Record<string, string>;\n // whether the screen is in the page (false: the template went out as it is)\n drawn: boolean;\n // who it was drawn for\n principal: string | null;\n // the page the path led to, when it led to one\n page?: string;\n // what the screen's head held, and the actions that said it — absent when\n // the screen has no head and the document's is the template's own\n head?: ScreenHead;\n // the snapshot's own account of itself (see ShellSnapshot) — present when drawn\n live?: boolean;\n why?: string[];\n drawnWith?: string[];\n settled?: boolean;\n};\n\nexport const renderDocument = async (config: DocumentConfig): Promise<DrawnDocument> => {\n const { server, template, request, draw } = config;\n const tokenKey = config.tokenKey ?? DEFAULT_TOKEN_KEY;\n const root = config.root ?? DEFAULT_ROOT;\n const undrawn: DrawnDocument = { html: template, headers: documentHeaders(null), drawn: false, principal: null };\n if (!template.includes(root)) return undrawn;\n\n try {\n // The session the browser holds (session-cookie.ts). A page request does\n // not say how it arrived, so the name only this host can have set is read\n // before the plain one. Its name ends with the port the page is on: the\n // one the request was addressed to, and — behind a proxy that rewrote\n // `Host` to its own upstream — the one the site says it is served at.\n const ports = [/:(\\d+)$/.exec(request.host ?? '')?.[1] ?? '', ...(config.site !== undefined && URL.canParse(config.site) ? [new URL(config.site).port] : [])];\n const token = ports.map((port) => sessionTokenOf(request.cookie, { port }, tokenKey)?.token ?? null).find((found) => found !== null) ?? null;\n // A token that no longer resolves is nobody: the page is drawn for nobody.\n // Nothing is written here — the upgrade is where a browser's cookie is set\n // and taken back (socket.ts), and one writer cannot disagree with itself. A\n // verifier that THROWS is a fault, not a sign-out — the page goes out\n // undrawn and the socket, which asks again, is where it is settled.\n const principal = token === null ? null : await server.principalOf(token);\n const route = server.page(request.path);\n const host = route?.host ?? server.shells;\n if (host === undefined) return undrawn;\n\n const snapshot = await host.snapshot(principal === null ? null : token, principal, {\n ...(config.waitMs !== undefined ? { waitMs: config.waitMs } : {}),\n ...(route !== undefined ? { inputs: route.inputs } : {}),\n });\n const screen = await draw(snapshot);\n const attributes = Object.entries(config.htmlAttributes?.(snapshot) ?? {})\n .map(([name, value]) => ` ${name}=\"${escapeAttribute(value)}\"`)\n .join('');\n const placed = template\n // functions, both, so nothing in the screen is read as a replacement pattern\n .replace(root, () => `${root.replace('></div>', () => `>${screen}</div>`)}${embedSnapshot(snapshot, principal, request.path)}`)\n .replace(/<html([^>]*)>/, (whole, existing: string) => (attributes === '' ? whole : `<html${existing}${attributes}>`));\n const head = headOf({ frame: () => snapshot.frame, canvasTree: (id) => snapshot.trees[id] ?? [] });\n // what a head may not hold was left out: say so, where somebody can see it\n for (const why of head?.refused ?? []) console.error(`[moss/document] \"${request.path}\" — ${why}`);\n const html = placeHead(placed, head?.elements, { ...(config.site !== undefined ? { site: config.site } : {}), path: request.path });\n\n return {\n html,\n ...(head !== undefined ? { head } : {}),\n headers: documentHeaders(principal),\n drawn: true,\n principal,\n ...(route !== undefined ? { page: route.name } : {}),\n live: snapshot.live,\n why: snapshot.why,\n drawnWith: snapshot.drawnWith,\n settled: snapshot.settled,\n };\n } catch (error) {\n console.error(`[moss/document] \"${request.path}\" could not be drawn — serving it undrawn:`, error);\n return undrawn;\n }\n};\n\n// ── pages, as files ──\n//\n// The same draw, for NOBODY, once per path: what a static host serves. There is\n// no credential to pass and no way to pass one — a file is the page as nobody\n// in particular sees it, which is the only page that may be kept.\n//\n// A page that is LIVE is still written, and said so: its file is a true first\n// screen, and its terminal will look for a socket. Whether that is acceptable\n// (a server stands beside the files) or a mistake (there is no server) is the\n// build's to decide, from the report — nothing here guesses.\n\nexport type ExportedDocument = {\n path: string;\n html: string;\n page?: string;\n head?: ScreenHead;\n drawn: boolean;\n live: boolean;\n why: string[];\n // reads whose answers are in the file as they were when it was written\n drawnWith: string[];\n settled: boolean;\n};\n\nexport const exportDocuments = async (config: Omit<DocumentConfig, 'request'> & { paths: readonly string[] }): Promise<ExportedDocument[]> => {\n const { paths, ...rest } = config;\n const out: ExportedDocument[] = [];\n for (const path of paths) {\n const page = await renderDocument({ ...rest, request: { path, cookie: null } });\n out.push({\n path,\n html: page.html,\n ...(page.page !== undefined ? { page: page.page } : {}),\n ...(page.head !== undefined ? { head: page.head } : {}),\n drawn: page.drawn,\n // undrawn is not concluded finished\n live: page.live ?? true,\n why: page.why ?? (page.drawn ? [] : ['the page could not be drawn']),\n drawnWith: page.drawnWith ?? [],\n settled: page.settled ?? false,\n });\n }\n return out;\n};\n","import { readFile } from 'node:fs/promises';\nimport { extname, join, relative } from 'node:path';\nimport { serve as listen } from '@hono/node-server';\nimport { serveStatic } from '@hono/node-server/serve-static';\nimport { WebSocketServer } from 'ws';\nimport type { WebSocket as ServerSocket } from 'ws';\nimport type { IncomingMessage } from 'node:http';\nimport type { Duplex } from 'node:stream';\nimport { createServer } from './server';\nimport type { MossServer } from './server';\nimport type { NiscApp } from './app';\nimport type { NiscRuntime } from './runtime';\nimport { SUBPROTOCOL } from './socket';\nimport type { SocketAccept } from './socket';\nimport { renderDocument } from './document';\nimport type { DocumentConfig } from './document';\n\n// ═══════════════════════════════════════════════════════════════\n// The Node entry — runtime-specific by design: the transport is a seam, so\n// the Bun flip swaps this file, never the app. Two exports: the\n// websocket transport for hosts that run their own listener (the dev\n// checks, vite), and the batteries-included `serve`.\n// ═══════════════════════════════════════════════════════════════\n\n// Anything that emits Node upgrade events — http.Server structurally, so\n// the @hono/node-server return type needs no narrowing.\ntype Upgradeable = {\n on: (event: 'upgrade', handler: (req: IncomingMessage, socket: Duplex, head: Buffer) => void) => unknown;\n};\n\n// THE LARGEST MESSAGE A CONNECTION MAY SEND, in bytes, unless the host says\n// otherwise (`options.maxMessageBytes`). Told nothing, `ws` takes 100 MiB — and\n// what a terminal sends is an event: a press, a typed value, one row handed\n// back. A few KB. Whatever a message carries, the server then keeps (the value\n// in the shell, and again in the last frame it sent) and sends back down in\n// every later frame of that canvas, so this is what ONE connection, signed in\n// or not, can make the process hold and re-send: about 1.5 MB at this limit,\n// 48 MB for a 16 MiB value. Compression is no bound — 64 MB of one letter is\n// 60 KB on the wire — so the count is of the message once inflated. A message\n// over it closes that connection with 1009, and nothing else.\nconst MAX_MESSAGE_BYTES = 256 * 1024;\n\n// The `ws` half of the transport seam: RFC 6455 stays library-handled\n// (permessage-deflate on by default — see `runtime.socketCompression`); the\n// protocol above the seam is nisc's own (../socket.ts) and identical on every\n// runtime.\nexport const attachSocket = (\n httpServer: Upgradeable,\n accept: SocketAccept,\n path = '/socket',\n options?: { compression?: boolean | Record<string, unknown>; maxMessageBytes?: number },\n): void => {\n const wss = new WebSocketServer({\n noServer: true,\n perMessageDeflate: options?.compression ?? true,\n maxPayload: options?.maxMessageBytes ?? MAX_MESSAGE_BYTES,\n // Of what a terminal offers, `nisc` is answered and nothing else: the\n // other entry is its token (socket.ts), which is not said back.\n handleProtocols: (offered) => (offered.has(SUBPROTOCOL) ? SUBPROTOCOL : false),\n });\n // The cookies moss answers an upgrade with ride the 101 itself.\n const answers = new WeakMap<IncomingMessage, readonly string[]>();\n wss.on('headers', (headers, req) => {\n for (const cookie of answers.get(req) ?? []) headers.push(`Set-Cookie: ${cookie}`);\n });\n httpServer.on('upgrade', (req, socket, head) => {\n const url = req.url ?? '/';\n // Not ours: leave it for whichever other listener owns it (vite's HMR\n // upgrade rides the same server in dev).\n if (new URL(url, 'http://nisc.local').pathname !== path) return;\n // THE REQUEST IS ANSWERED ONCE MOSS HAS DECIDED WHO IS ASKING, because the\n // answer is the one thing that can write a browser's session cookie\n // (session-cookie.ts). Until then the raw socket is nobody's to listen to,\n // and a peer that resets it would be an 'error' thrown out of Node — the\n // whole process. Heard here, it is that request's alone.\n socket.on('error', () => {});\n let ws: ServerSocket | undefined;\n let answered = false;\n // The first use of the connection answers the request, with the cookies\n // moss has named by then — which is as soon as it has decided who is\n // asking, or is refusing the terminal outright. A request `ws` will not\n // upgrade (a bad key, a peer already gone) leaves no websocket: nothing is\n // sent to it, and it is closed already.\n let cookies: readonly string[] = [];\n const answer = (): ServerSocket | undefined => {\n if (answered) return ws;\n answered = true;\n answers.set(req, cookies);\n wss.handleUpgrade(req, socket, head, (opened) => {\n ws = opened;\n // `ws` reports what it refuses from a client — a malformed frame, a\n // message over its size limit — as an 'error' on that connection, having\n // already closed it with the status that says why (1002, 1009). An\n // 'error' nobody listens for is thrown by Node, out of the socket's own\n // data handler where nothing can catch it: one bad frame from one\n // client took the process, and every session on it, down. Heard here it\n // is that connection's alone, and the close it already got is the answer.\n opened.on('error', (error) => {\n console.warn(`[moss/node] a connection was closed on what it sent: ${error.message}`);\n });\n });\n return ws;\n };\n // accept promises to handle its own failures (see socket.ts). This is\n // the floor under that promise: an await added there without a guard\n // degrades to one logged close here instead of an unhandled rejection\n // taking every session on the box down with it.\n accept(url, {\n send: (text) => void answer()?.send(text),\n close: (code, reason) => void answer()?.close(code, reason),\n onMessage: (fn) => void answer()?.on('message', (data) => fn(String(data))),\n onClose: (fn) => {\n const opened = answer();\n if (opened === undefined) queueMicrotask(fn);\n else opened.on('close', () => fn());\n },\n upgrade: {\n offered: String(req.headers['sec-websocket-protocol'] ?? '').split(',').map((entry) => entry.trim()),\n origin: req.headers.origin ?? null,\n host: req.headers.host ?? null,\n cookie: req.headers.cookie ?? null,\n answer: (given) => void (cookies = given),\n },\n }).catch((error: unknown) => {\n console.error('[moss/node] a connection escaped accept:', error);\n try {\n answer()?.close(1011, 'accept failed');\n } catch {\n // already gone\n }\n });\n });\n};\n\n// THE BUILT TERMINAL, served by the same process as the app — one origin, so the\n// socket is `/socket` wherever the page came from.\n//\n// `dist` is what the app's bundler wrote: index.html and its assets. Every GET\n// that nothing registered earlier answers is a file from it, or a PAGE:\n// index.html with the caller's screen drawn into it (./document) — the app's own\n// for `/`, one of the manifest's pages for a path that leads to one. index.html\n// itself is never served as a file: it is the template, and goes out drawn.\n//\n// A name with an extension that is neither a file in `dist` nor a page of the\n// manifest is a MISSING FILE, and is answered 404 — not with a screen. A browser\n// holding a page from before a deploy asks for that page's script by its old\n// name; what it needs back is \"gone\", not a document that is not a script.\n//\n// Register the app's own routes FIRST; this is the catch-all. `owned` names the\n// prefixes that are never a page (default: moss's own surfaces) — an unknown\n// path under one is a 404, not a screen.\nexport type SiteConfig = Pick<DocumentConfig, 'draw' | 'htmlAttributes' | 'site' | 'tokenKey' | 'waitMs'> & {\n dist: string;\n owned?: RegExp;\n};\n\n// The paths the app server answers itself; everything else is the site's.\nexport const MOSS_PATHS = /^\\/(api|catalog|socket|operator|integrations)(\\/|$)/;\n\nexport const mountSite = (server: MossServer, config: SiteConfig): void => {\n const { dist, owned = MOSS_PATHS, ...drawing } = config;\n // serveStatic resolves `root` against the working directory.\n const root = relative(process.cwd(), dist) || '.';\n const files = serveStatic({ root });\n server.use('/*', async (c, next) => {\n const path = c.req.path;\n if (owned.test(path) || path === '/' || path === '/index.html' || server.page(path) !== undefined) return next();\n return files(c, next);\n });\n server.get('*', async (c) => {\n if (owned.test(c.req.path)) return c.notFound();\n // the static server above found no such file, and no page is at this path\n if (extname(c.req.path) !== '' && c.req.path !== '/index.html' && server.page(c.req.path) === undefined) return c.notFound();\n const template = await readFile(join(dist, 'index.html'), 'utf8');\n const page = await renderDocument({\n ...drawing,\n server,\n template,\n request: { path: c.req.path === '/index.html' ? '/' : c.req.path, cookie: c.req.header('cookie') ?? null, host: c.req.header('host') ?? null },\n });\n return c.html(page.html, 200, page.headers);\n });\n};\n\nexport const serve = async (app: NiscApp, runtime: NiscRuntime & { port?: number }): Promise<MossServer> => {\n const server = await createServer(app, runtime);\n const port = runtime.port ?? 8787;\n const httpServer = listen({ fetch: server.fetch, port });\n attachSocket(httpServer, server.socket, '/socket', { ...(runtime.socketCompression !== undefined ? { compression: runtime.socketCompression } : {}) });\n console.log(`moss serving http://localhost:${port}`);\n console.log(`surfaces: GET /catalog · GET|POST /api/vex · GET|POST /api/<resource>/vex · ws://localhost:${port}/socket`);\n return server;\n};\n"]}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"node.cjs"}