@almadar/core 10.129.0 → 11.0.1

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 (135) hide show
  1. package/dist/behavior-package.d.ts +49 -11
  2. package/dist/behavior-package.js +1 -1
  3. package/dist/{orbital-CkFdDS9f.d.ts → builders-BdgbY7Th.d.ts} +5828 -6917
  4. package/dist/builders.d.ts +6 -6
  5. package/dist/builders.js +7 -6
  6. package/dist/{bus-CcbB__oo.d.ts → bus-C0hFDNFR.d.ts} +262 -354
  7. package/dist/chunk-347APWFM.js +286 -0
  8. package/dist/chunk-347APWFM.js.map +1 -0
  9. package/dist/chunk-5WQ3U7NJ.js +2363 -0
  10. package/dist/chunk-5WQ3U7NJ.js.map +1 -0
  11. package/dist/chunk-5YTPYMPZ.js +99 -0
  12. package/dist/chunk-5YTPYMPZ.js.map +1 -0
  13. package/dist/chunk-66Q5VX2F.js +3810 -0
  14. package/dist/chunk-66Q5VX2F.js.map +1 -0
  15. package/dist/chunk-7GHJU5WI.js +39 -0
  16. package/dist/chunk-7GHJU5WI.js.map +1 -0
  17. package/dist/chunk-B4MNHGBP.js +8 -0
  18. package/dist/chunk-B4MNHGBP.js.map +1 -0
  19. package/dist/chunk-E4T2MQAV.js +24 -0
  20. package/dist/chunk-E4T2MQAV.js.map +1 -0
  21. package/dist/chunk-ENOCKYGA.js +412 -0
  22. package/dist/chunk-ENOCKYGA.js.map +1 -0
  23. package/dist/chunk-FGT5OS2Y.js +918 -0
  24. package/dist/chunk-FGT5OS2Y.js.map +1 -0
  25. package/dist/chunk-GF7KCLNR.js +3284 -0
  26. package/dist/chunk-GF7KCLNR.js.map +1 -0
  27. package/dist/chunk-PNGFWLHD.js +1567 -0
  28. package/dist/chunk-PNGFWLHD.js.map +1 -0
  29. package/dist/{chunk-X4SC7FGF.js → chunk-RGACZEYC.js} +99 -96
  30. package/dist/chunk-RGACZEYC.js.map +1 -0
  31. package/dist/{chunk-RYPVOI6H.js → chunk-SNZYN7UA.js} +2541 -433
  32. package/dist/{chunk-RYPVOI6H.js.map → chunk-SNZYN7UA.js.map} +1 -1
  33. package/dist/{chunk-KDMV222Q.js → chunk-TDNQT3M3.js} +304 -373
  34. package/dist/chunk-TDNQT3M3.js.map +1 -0
  35. package/dist/chunk-VG7BRFUD.js +152 -0
  36. package/dist/chunk-VG7BRFUD.js.map +1 -0
  37. package/dist/chunk-Z7BI7DE7.js +1293 -0
  38. package/dist/chunk-Z7BI7DE7.js.map +1 -0
  39. package/dist/{domain-Dz3jP-UM.d.ts → domain-Cpmja5ak.d.ts} +55 -55
  40. package/dist/{effect-CiEVLsZz.d.ts → effect-DZaXwSAz.d.ts} +283 -453
  41. package/dist/{effect-result-Bebwu9yT.d.ts → effect-result-1HpXgeBc.d.ts} +656 -851
  42. package/dist/{expression-D0Fs0riG.d.ts → expression-DirYKz-f.d.ts} +5 -13
  43. package/dist/factory/index.d.ts +7 -144
  44. package/dist/factory/index.js +8 -8
  45. package/dist/factory-runtime/index.d.ts +7 -6
  46. package/dist/factory-runtime/index.js +527 -8
  47. package/dist/factory-runtime/index.js.map +1 -1
  48. package/dist/fixtures.d.ts +9 -11
  49. package/dist/fixtures.js +12 -8
  50. package/dist/fixtures.js.map +1 -1
  51. package/dist/i18n/index.d.ts +15 -19
  52. package/dist/i18n/index.js +2 -1
  53. package/dist/{index-BC-Jycqj.d.ts → index-D7SxwNdv.d.ts} +34 -734
  54. package/dist/index.d.ts +92 -247
  55. package/dist/index.js +322 -986
  56. package/dist/index.js.map +1 -1
  57. package/dist/kernel-wire.d.ts +3 -3
  58. package/dist/kernel-wire.js +3 -79
  59. package/dist/kernel-wire.js.map +1 -1
  60. package/dist/language/constructs.json +22 -2
  61. package/dist/language/program-types.json +203 -22
  62. package/dist/language/protocols.json +46 -0
  63. package/dist/language/ui-vocabulary.json +1697 -0
  64. package/dist/language/validation-codes.json +1222 -1212
  65. package/dist/language/vocabulary.json +44 -8
  66. package/dist/language-data.d.ts +7 -4
  67. package/dist/language-data.js +20 -14
  68. package/dist/language-data.js.map +1 -1
  69. package/dist/patterns/component-mapping.json +11 -1
  70. package/dist/patterns/definitions.d.ts +2 -2
  71. package/dist/patterns/definitions.js +1 -1
  72. package/dist/patterns/event-contracts.json +1 -15
  73. package/dist/patterns/game-font-families.json +13 -0
  74. package/dist/patterns/index.d.ts +24 -120
  75. package/dist/patterns/index.js +3 -3
  76. package/dist/patterns/pattern-tile-geometry.json +1065 -0
  77. package/dist/patterns/patterns-registry.json +2539 -431
  78. package/dist/patterns/registry.json +2539 -431
  79. package/dist/trait-sRjIivFq.d.ts +3519 -0
  80. package/dist/types/index.d.ts +9 -10
  81. package/dist/types/index.js +11 -5
  82. package/dist/{types-DGwrltUF.d.ts → types-C6_yPMpn.d.ts} +3 -3
  83. package/fixtures/events-wire/client-effects-by-trait/response.json +0 -18
  84. package/fixtures/events-wire/client-effects-provenance/response.json +0 -18
  85. package/fixtures/events-wire/effect-results-every-kind/response.json +2 -27
  86. package/fixtures/events-wire/navigate-1/response.json +8 -5
  87. package/fixtures/events-wire/navigate-2/response.json +11 -8
  88. package/fixtures/events-wire/navigate-3/response.json +14 -11
  89. package/fixtures/events-wire/navigate-back/response.json +7 -4
  90. package/fixtures/events-wire/render-ui-3/response.json +12 -9
  91. package/fixtures/events-wire/render-ui-clear/response.json +0 -7
  92. package/fixtures/events-wire/sse-stream/response.json +0 -20
  93. package/fixtures/events-wire/sse-stream/stream.json +0 -20
  94. package/fixtures/events-wire/stateless-traits/response.json +14 -5
  95. package/fixtures/kernel-wire/golden/basic-entity.json +1687 -0
  96. package/fixtures/kernel-wire/golden/entity-rerender.json +743 -0
  97. package/fixtures/kernel-wire/golden/rollback.json +793 -0
  98. package/fixtures/kernel-wire/golden/tick-counter.json +1538 -0
  99. package/fixtures/kernel-wire/golden/two-orbital-chore.json +847 -0
  100. package/fixtures/kernel-wire/golden/two-orbital-task.json +457 -0
  101. package/fixtures/kernel-wire/played-step.json +136 -0
  102. package/fixtures/kernel-wire/scripts/basic-entity.json +28 -0
  103. package/fixtures/kernel-wire/scripts/entity-rerender.json +13 -0
  104. package/fixtures/kernel-wire/scripts/rollback.json +53 -0
  105. package/fixtures/kernel-wire/scripts/tick-counter.json +26 -0
  106. package/fixtures/kernel-wire/scripts/two-orbital-chore.json +9 -0
  107. package/fixtures/kernel-wire/scripts/two-orbital-task.json +9 -0
  108. package/package.json +28 -19
  109. package/dist/builders-DmZE5By0.d.ts +0 -2663
  110. package/dist/chunk-45I2O4SJ.js +0 -4646
  111. package/dist/chunk-45I2O4SJ.js.map +0 -1
  112. package/dist/chunk-6LR43Z5E.js +0 -3061
  113. package/dist/chunk-6LR43Z5E.js.map +0 -1
  114. package/dist/chunk-GIUA3NUJ.js +0 -809
  115. package/dist/chunk-GIUA3NUJ.js.map +0 -1
  116. package/dist/chunk-GTY53NS5.js +0 -1908
  117. package/dist/chunk-GTY53NS5.js.map +0 -1
  118. package/dist/chunk-JOHDVS6J.js +0 -1614
  119. package/dist/chunk-JOHDVS6J.js.map +0 -1
  120. package/dist/chunk-KDMV222Q.js.map +0 -1
  121. package/dist/chunk-QRHJUS3D.js +0 -23
  122. package/dist/chunk-QRHJUS3D.js.map +0 -1
  123. package/dist/chunk-QUOTJULD.js +0 -4009
  124. package/dist/chunk-QUOTJULD.js.map +0 -1
  125. package/dist/chunk-V5VNGRVU.js +0 -66
  126. package/dist/chunk-V5VNGRVU.js.map +0 -1
  127. package/dist/chunk-X4SC7FGF.js.map +0 -1
  128. package/dist/entityAccess-BPSz1i2n.d.ts +0 -80
  129. package/dist/mock/index.d.ts +0 -153
  130. package/dist/mock/index.js +0 -190
  131. package/dist/mock/index.js.map +0 -1
  132. package/dist/schema-T5RT5s6H.d.ts +0 -282
  133. package/dist/state-machine/index.d.ts +0 -359
  134. package/dist/state-machine/index.js +0 -3
  135. package/dist/state-machine/index.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/types/identity.ts","../src/types/projection.ts","../src/types/field.ts","../src/types/asset.ts","../src/types/expression.ts","../src/types/entity.ts","../src/types/effect.ts","../src/row-query.ts","../src/types/row-set.ts","../src/types/user.ts","../src/types/effect-result.ts","../src/types/bus.ts"],"names":["z","value","row","index","ref"],"mappings":";;;AA8BA,IAAM,WAAA,GAAc;AAAA,EAClB,OAAA,EAAS,MAAA;AAAA,EACT,MAAA,EAAQ,MAAA;AAAA,EACR,KAAA,EAAO,MAAA;AAAA,EACP,KAAA,EAAO,MAAA;AAAA,EACP,IAAA,EAAM,MAAA;AAAA,EACN,OAAA,EAAS,MAAA;AAAA,EACT,KAAA,EAAO,MAAA;AAAA,EACP,OAAA,EAAS;AACX,CAAA;AAoBA,SAAS,MAAyB,KAAA,EAAmB;AACnD,EAAA,OAAO,KAAA;AACT;AAYA,SAAS,WAA8B,IAAA,EAA6B;AAClE,EAAA,MAAM,MAAA,GAAS,YAAY,IAAI,CAAA;AAC/B,EAAA,MAAM,EAAA,GAAK,CAAC,KAAA,KACV,KAAA,CAAM,WAAW,MAAM,CAAA,IAAK,KAAA,CAAM,MAAA,GAAS,MAAA,CAAO,MAAA;AACpD,EAAA,MAAM,EAAA,GAAK,CAAC,KAAA,KAAsB;AAChC,IAAA,IAAI,CAAC,EAAA,CAAG,KAAK,CAAA,EAAG;AACd,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,CAAA,SAAA,EAAY,IAAI,CAAA,aAAA,EAAgB,MAAM,YAAY,IAAA,CAAK,SAAA,CAAU,KAAK,CAAC,CAAA;AAAA,OACzE;AAAA,IACF;AACA,IAAA,OAAO,MAAU,KAAK,CAAA;AAAA,EACxB,CAAA;AACA,EAAA,OAAO,EAAE,MAAA,EAAQ,EAAA,EAAI,EAAA,EAAG;AAC1B;AAEA,IAAM,WAAA,GAAc,WAAsB,SAAS,CAAA;AACnD,IAAM,UAAA,GAAa,WAAqB,QAAQ,CAAA;AAChD,IAAM,SAAA,GAAY,WAAoB,OAAO,CAAA;AAC7C,IAAM,SAAA,GA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Aa,UAAU,CAAC;AAW7D,IAAM,6BAAA,GAA4EA,EAAE,MAAA,CAAO;AAAA,EAChG,OAAA,EAASA,EAAE,OAAA,EAAQ;AAAA,EACnB,QAAA,EAAU,qBAAqB,QAAA,EAAS;AAAA,EACxC,OAAA,EAASA,CAAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAAS;AAAA,EAC7B,UAAUA,CAAAA,CAAE,KAAA,CAAMA,EAAE,MAAA,EAAQ,EAAE,QAAA,EAAS;AAAA,EACvC,KAAA,EAAOA,CAAAA,CAAE,MAAA,EAAO,CAAE,QAAA;AACpB,CAAC;AAyBM,IAAM,uBAAA,GAAgEA,EAAE,MAAA,CAAO;AAAA,EACpF,KAAA,EAAOA,EAAE,MAAA,EAAO;AAAA,EAChB,OAAA,EAAS,mBAAmB,QAAA,EAAS;AAAA,EACrC,MAAA,EAAQ,oBAAA;AAAA,EACR,cAAA,EAAgBA,CAAAA,CAAE,MAAA,EAAO,CAAE,QAAA;AAC7B,CAAC;AAMM,IAAM,0BAAA,GAA6B;AAMnC,IAAM,2BAAA,GAA8B","file":"chunk-GTY53NS5.js","sourcesContent":["/**\n * Identity model (Almadar Rabit V4, Phase 1 — types only).\n *\n * Branded, prefix-tagged node ids + a workspace-scoped name ledger. Ids are\n * the durable edge keys of the identity-keyed schema graph; the ledger is the\n * sole name↔id map (names are display labels, one row per rename). This module\n * is pure: no I/O, no side effects. Minting is the only impurity (clock +\n * crypto randomness for the ULID suffix).\n *\n * @packageDocumentation\n */\n\nimport { z } from 'zod';\n\n// ============================================================================\n// Branded id types\n// ============================================================================\n\ntype Branded<K extends string> = string & { readonly __idBrand: K };\n\nexport type OrbitalId = Branded<'OrbitalId'>;\nexport type EntityId = Branded<'EntityId'>;\nexport type TraitId = Branded<'TraitId'>;\nexport type EventId = Branded<'EventId'>;\nexport type PageId = Branded<'PageId'>;\nexport type ServiceId = Branded<'ServiceId'>;\nexport type ThemeId = Branded<'ThemeId'>;\nexport type PaletteEntryId = Branded<'PaletteEntryId'>;\n\n/** Node kind ↔ id-prefix table. The single source of truth for every prefix. */\nconst ID_PREFIXES = {\n orbital: 'orb_',\n entity: 'ent_',\n trait: 'trt_',\n event: 'evt_',\n page: 'pag_',\n service: 'svc_',\n theme: 'thm_',\n palette: 'pal_',\n} as const;\n\nexport type IdKind = keyof typeof ID_PREFIXES;\n\n/** Compile-time map from kind to its branded id type. */\nexport interface IdForKind {\n orbital: OrbitalId;\n entity: EntityId;\n trait: TraitId;\n event: EventId;\n page: PageId;\n service: ServiceId;\n theme: ThemeId;\n palette: PaletteEntryId;\n}\n\n/**\n * The one controlled brand assertion in this module. A prefix-checked string\n * is asserted into its branded form here and nowhere else.\n */\nfunction brand<Id extends string>(value: string): Id {\n return value as Id;\n}\n\n// ============================================================================\n// Kind guards + constructors (one shared factory, eight kinds)\n// ============================================================================\n\ninterface IdKindApi<Id extends string> {\n readonly prefix: string;\n is(value: string): value is Id;\n as(value: string): Id;\n}\n\nfunction makeIdKind<Id extends string>(kind: IdKind): IdKindApi<Id> {\n const prefix = ID_PREFIXES[kind];\n const is = (value: string): value is Id =>\n value.startsWith(prefix) && value.length > prefix.length;\n const as = (value: string): Id => {\n if (!is(value)) {\n throw new Error(\n `Expected ${kind} id (prefix \"${prefix}\"), got: ${JSON.stringify(value)}`,\n );\n }\n return brand<Id>(value);\n };\n return { prefix, is, as };\n}\n\nconst orbitalKind = makeIdKind<OrbitalId>('orbital');\nconst entityKind = makeIdKind<EntityId>('entity');\nconst traitKind = makeIdKind<TraitId>('trait');\nconst eventKind = makeIdKind<EventId>('event');\nconst pageKind = makeIdKind<PageId>('page');\nconst serviceKind = makeIdKind<ServiceId>('service');\nconst themeKind = makeIdKind<ThemeId>('theme');\nconst paletteKind = makeIdKind<PaletteEntryId>('palette');\n\nexport const isOrbitalId = orbitalKind.is;\nexport const asOrbitalId = orbitalKind.as;\nexport const isEntityId = entityKind.is;\nexport const asEntityId = entityKind.as;\nexport const isTraitId = traitKind.is;\nexport const asTraitId = traitKind.as;\nexport const isEventId = eventKind.is;\nexport const asEventId = eventKind.as;\nexport const isPageId = pageKind.is;\nexport const asPageId = pageKind.as;\nexport const isServiceId = serviceKind.is;\nexport const asServiceId = serviceKind.as;\nexport const isThemeId = themeKind.is;\nexport const asThemeId = themeKind.as;\nexport const isPaletteEntryId = paletteKind.is;\nexport const asPaletteEntryId = paletteKind.as;\n\n/**\n * The id-prefix for a node kind (`'entity' → 'ent_'`). The JS mirror of the\n * Rust `IdKind::prefix`. Single source of truth is {@link ID_PREFIXES}.\n */\nexport function idPrefix(kind: IdKind): string {\n return ID_PREFIXES[kind];\n}\n\n/**\n * The node kind an id's prefix denotes, or `null` for an unrecognized /\n * bare-prefix string. The JS mirror of the Rust `id_kind_of`. Prefixes are\n * mutually non-overlapping, so match order is irrelevant.\n */\nexport function idKindOf(id: string): IdKind | null {\n for (const kind of Object.keys(ID_PREFIXES) as IdKind[]) {\n const prefix = ID_PREFIXES[kind];\n if (id.startsWith(prefix) && id.length > prefix.length) return kind;\n }\n return null;\n}\n\n// ============================================================================\n// Minting — prefix + ULID\n// ============================================================================\n\nconst CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';\nconst TIME_LEN = 10;\nconst RANDOM_LEN = 16;\n\nfunction randomBytes(len: number): Uint8Array {\n const g = globalThis as { crypto?: { getRandomValues?: (a: Uint8Array) => Uint8Array } };\n if (g.crypto?.getRandomValues) {\n return g.crypto.getRandomValues(new Uint8Array(len));\n }\n throw new Error('mintId: no crypto.getRandomValues available in this runtime');\n}\n\nfunction encodeTime(now: number): string {\n let value = now;\n let out = '';\n for (let i = 0; i < TIME_LEN; i++) {\n const mod = value % 32;\n out = CROCKFORD[mod] + out;\n value = (value - mod) / 32;\n }\n return out;\n}\n\nfunction encodeRandom(): string {\n const bytes = randomBytes(RANDOM_LEN);\n let out = '';\n for (let i = 0; i < RANDOM_LEN; i++) {\n out += CROCKFORD[bytes[i] & 31];\n }\n return out;\n}\n\n/** A 26-char Crockford-base32 ULID: 48-bit ms timestamp + 80 bits of randomness. */\nfunction ulid(): string {\n return encodeTime(Date.now()) + encodeRandom();\n}\n\n/** Mint a fresh, opaque, kind-tagged id: `<prefix><ULID>`. */\nexport function mintId<K extends IdKind>(kind: K): IdForKind[K] {\n return brand<IdForKind[K]>(ID_PREFIXES[kind] + ulid());\n}\n\n// ============================================================================\n// Deterministic derivation — JS twin of Rust `derive_id`\n// ============================================================================\n\nconst U64_MASK = (1n << 64n) - 1n;\nconst BODY_TIME_MASK = (1n << 50n) - 1n;\nconst BODY_RANDOM_MASK = (1n << 80n) - 1n;\nconst FNV_PRIME_64 = 0x100000001b3n;\nconst FNV_OFFSET_1 = 0xcbf29ce484222325n;\nconst FNV_OFFSET_2 = (0x100000001b3n ^ 0xdeadbeefn) & U64_MASK;\n\n/** SplitMix64 — a small, well-distributed non-cryptographic mixer. */\nfunction splitmix64(x: bigint): bigint {\n let z = (x + 0x9e3779b97f4a7c15n) & U64_MASK;\n z = ((z ^ (z >> 30n)) * 0xbf58476d1ce4e5b9n) & U64_MASK;\n z = ((z ^ (z >> 27n)) * 0x94d049bb133111ebn) & U64_MASK;\n return (z ^ (z >> 31n)) & U64_MASK;\n}\n\n/** FNV-1a 64-bit over `data` starting from `offset`. */\nfunction fnv1a64(data: Uint8Array, offset: bigint): bigint {\n let h = offset & U64_MASK;\n for (const b of data) {\n h = (h ^ BigInt(b)) & U64_MASK;\n h = (h * FNV_PRIME_64) & U64_MASK;\n }\n return h;\n}\n\n/** Emit the low `nChars * 5` bits of `value` as base32, most-significant char first. */\nfunction pushBase32(value: bigint, nChars: number): string {\n let v = value;\n const chars = new Array<string>(nChars);\n for (let i = nChars - 1; i >= 0; i--) {\n chars[i] = CROCKFORD[Number(v & 0x1fn)];\n v >>= 5n;\n }\n return chars.join('');\n}\n\n/**\n * Deterministically derive a child id rooted in `parentId` — no entropy, no\n * clock, so re-deriving from the same inputs never churns. JS twin of the\n * Rust `derive_id` in `orbital-core/src/identity.rs`; used ONLY for synthetic\n * nodes produced by deterministic materialization (orbital-import\n * prefixing), never for author-facing fresh ids (use {@link mintId} there).\n */\nexport function deriveId(parentId: string, discriminator: string): string {\n const kind = idKindOf(parentId) ?? 'trait';\n const encoder = new TextEncoder();\n const parentBytes = encoder.encode(parentId);\n const discBytes = encoder.encode(discriminator);\n const data = new Uint8Array(parentBytes.length + 1 + discBytes.length);\n data.set(parentBytes, 0);\n data[parentBytes.length] = 0x1f;\n data.set(discBytes, parentBytes.length + 1);\n\n const h1 = splitmix64(fnv1a64(data, FNV_OFFSET_1));\n const h2 = splitmix64(fnv1a64(data, FNV_OFFSET_2));\n const timeBits = (((h1 << 64n) | h2) & BODY_TIME_MASK);\n const randBits = (((h2 << 64n) | h1) & BODY_RANDOM_MASK);\n\n return ID_PREFIXES[kind] + pushBase32(timeBits, 10) + pushBase32(randBits, 16);\n}\n\n// ============================================================================\n// Identity ledger\n// ============================================================================\n\n/** Ledger row kind. `palette` entries are manifest ids, not name-ledger rows. */\nexport type LedgerKind =\n | 'orbital'\n | 'entity'\n | 'trait'\n | 'event'\n | 'page'\n | 'service'\n | 'theme';\n\n/**\n * One ledger row: the workspace's name history for a single node id.\n *\n * For kind `'event'` the row is minted per-(trait, declared event) per the\n * Phase-0 freeze — the owning trait is recorded in `parent`; a call-site event\n * rename is a one-row edit on this same id (the baked-vs-current key namespaces\n * collapse into `bakedName` vs `curName`).\n */\nexport interface LedgerEntry {\n id: string;\n kind: LedgerKind;\n bakedName: string;\n curName: string;\n renames: ReadonlyArray<{ from: string; to: string; at: string }>;\n owner: 'std' | 'io' | 'workspace';\n /** Owning trait for kind `'event'` (per-trait event-id namespace). */\n parent?: TraitId;\n}\n\nexport interface IdentityLedger {\n schemaVersion: 1;\n entries: Record<string, LedgerEntry>;\n}\n\n/** Resolve a name to its id via exact `curName` match within `kind`, else null. */\nexport function ledgerResolveName(\n ledger: IdentityLedger,\n kind: LedgerKind,\n name: string,\n): string | null {\n for (const [id, entry] of Object.entries(ledger.entries)) {\n if (entry.kind === kind && entry.curName === name) return id;\n }\n return null;\n}\n\n/** Immutable rename: returns a new ledger with the id's `curName` + `renames` updated; renaming to the current name is a no-op. */\nexport function ledgerRename(\n ledger: IdentityLedger,\n id: string,\n to: string,\n at: string,\n): IdentityLedger {\n const entry = ledger.entries[id];\n if (entry === undefined || entry.curName === to) return ledger;\n const updated: LedgerEntry = {\n ...entry,\n curName: to,\n renames: [...entry.renames, { from: entry.curName, to, at }],\n };\n return { ...ledger, entries: { ...ledger.entries, [id]: updated } };\n}\n\n/** Current display name for an id, or null when the id is not in the ledger. */\nexport function ledgerCurName(ledger: IdentityLedger, id: string): string | null {\n return ledger.entries[id]?.curName ?? null;\n}\n\n// ============================================================================\n// Zod schemas — the `.orb` load-time activation surface (Rabit V4, Phase 4)\n// ============================================================================\n\n/**\n * Prefix-checked, kind-tagged id schemas. Each narrows a validated string to\n * its branded id type via the module's own kind guard, so a schema that reads\n * `TraitIdSchema.optional()` yields `TraitId | undefined` with no cast. The\n * guard is the single source of prefix truth (`ID_PREFIXES`); the schema is a\n * thin zod wrapper over it.\n */\nexport const OrbitalIdSchema = z\n .string()\n .refine(isOrbitalId, { message: `Expected an orbital id (prefix \"${ID_PREFIXES.orbital}\")` });\nexport const EntityIdSchema = z\n .string()\n .refine(isEntityId, { message: `Expected an entity id (prefix \"${ID_PREFIXES.entity}\")` });\nexport const TraitIdSchema = z\n .string()\n .refine(isTraitId, { message: `Expected a trait id (prefix \"${ID_PREFIXES.trait}\")` });\nexport const EventIdSchema = z\n .string()\n .refine(isEventId, { message: `Expected an event id (prefix \"${ID_PREFIXES.event}\")` });\nexport const PageIdSchema = z\n .string()\n .refine(isPageId, { message: `Expected a page id (prefix \"${ID_PREFIXES.page}\")` });\nexport const ServiceIdSchema = z\n .string()\n .refine(isServiceId, { message: `Expected a service id (prefix \"${ID_PREFIXES.service}\")` });\nexport const ThemeIdSchema = z\n .string()\n .refine(isThemeId, { message: `Expected a theme id (prefix \"${ID_PREFIXES.theme}\")` });\nexport const PaletteEntryIdSchema = z\n .string()\n .refine(isPaletteEntryId, { message: `Expected a palette-entry id (prefix \"${ID_PREFIXES.palette}\")` });\n\nexport const LedgerKindSchema = z.enum([\n 'orbital',\n 'entity',\n 'trait',\n 'event',\n 'page',\n 'service',\n 'theme',\n]);\n\nexport const LedgerEntrySchema = z.object({\n id: z.string(),\n kind: LedgerKindSchema,\n bakedName: z.string(),\n curName: z.string(),\n renames: z.array(\n z.object({ from: z.string(), to: z.string(), at: z.string() }),\n ),\n owner: z.enum(['std', 'io', 'workspace']),\n parent: TraitIdSchema.optional(),\n});\n\nexport const IdentityLedgerSchema = z.object({\n schemaVersion: z.literal(1),\n entries: z.record(z.string(), LedgerEntrySchema),\n});\n","import { z } from 'zod';\n\n/**\n * `.lolo` `T` or `T.f` in any type position: the authored entity or struct type `type`, or its declared field `field`.\n * A field carrying it holds that type itself; `projectedFrom` records where it came from, so a value can be drawn from\n * `T`'s own rows or `f` (the mock seeder draws from `T`'s seeded rows). Mirrors Rust `FieldProjection`, whose `field`\n * is absent for a named type.\n */\nexport type FieldProjection = {\n type: string;\n field?: string;\n};\n\nexport const FieldProjectionSchema: z.ZodType<FieldProjection> = z.object({\n type: z.string().min(1),\n field: z.string().min(1).optional(),\n});\n","/**\n * Field Types for Orbital Units\n *\n * Extracted from schema/data-entities.ts for the orbitals module.\n * These types define the field structure within orbital entities.\n *\n * @packageDocumentation\n */\n\nimport { FieldProjectionSchema, type FieldProjection } from './projection.js';\nimport { z } from 'zod';\nimport type { EntityId } from './identity.js';\nimport { EntityIdSchema } from './identity.js';\nimport type { JsonValue, RuntimeValue } from './json.js';\nimport { JsonValueSchema } from './json.js';\n\n// ============================================================================\n// Field Types\n// ============================================================================\n\n/**\n * Supported field types for entity fields.\n *\n * @example\n * { name: 'status', type: 'enum', values: ['draft', 'published'] }\n * { name: 'authorId', type: 'relation', relation: { entity: 'User', cardinality: 'one' } }\n */\nexport type FieldType = FieldTag | TypeVariable;\n\n/** An unbound type variable (`t` of `type Page t` or a trait's `(t : Type)`),\n * written `$t` — the `.orb` spelling the Rust `FieldType::TypeVar` serializes to. */\nexport type TypeVariable = `$${string}`;\n\n/** The concrete field-type tags (every `FieldType` but a type variable). */\nexport type FieldTag =\n | 'string'\n | 'number'\n | 'int'\n | 'boolean'\n | 'date'\n | 'timestamp'\n | 'datetime'\n | 'instant'\n // Semantic string domains. `.lolo` already types `date`/`datetime` rather\n // than annotating them, so these belong in the type system for the same\n // reason: a field's domain is a declared fact, not a decoration. They\n // replaced the optional `format` property, which had zero producers.\n | 'email'\n | 'url'\n | 'phone'\n | 'uuid'\n | 'image'\n // Promoted value types (2026-08-20). `money` is numeric at rest - the\n // declared type (never a field-name heuristic) drives currency inputs\n // and formatting. `file` is the canonical struct value\n // {name, url, mimeType, sizeBytes} - an uploaded artifact, not a\n // validated string; `url` is a data: URI in mock mode.\n | 'money'\n | 'file'\n // `bytes` is binary data; at rest a standard padded base64 string.\n | 'bytes'\n | 'array'\n | 'object'\n | 'enum'\n | 'relation'\n | 'trait'\n | 'orbital'\n | 'behavior'\n | 'slot'\n | 'pattern'\n // Renderable UI content — a pattern node (or array of them), the same\n // shape `render-ui` effects carry (`PatternNode` in render-ui-edit.ts).\n // First-class so view-fragment fields stop hiding behind `object`/`json`.\n | 'node'\n // Event-name reference — a string at rest, but the TYPE marks it as an\n // event key rather than free text (Phase B / SCAN-EVENT-KNOB-2). Legal\n // on struct-alias fields consumed by config knobs (e.g. `ItemAction.event`).\n | 'event'\n // A value addressing a declared external input (`Trait.EVENT`,\n // `Orbital.Trait.EVENT`) — never a bare name. See `EventAddress` in access/externalInputs.\n | 'EventAddress'\n // A call key — a string at rest, but nominal: a bare string never converts to it\n // implicitly, only `(as v CallKey)` does. Names the keyed call a `cancel-call` aborts.\n | 'CallKey'\n // An S-expression as data — atom, list or options object (a transition's\n // guard / effect args); config-only (G-ORB-093).\n | 'SExpr'\n // Tagged struct union (`type DrawItem = DrawShape | DrawText`) — a real\n // .lolo/.orb type the Rust compiler accepts; the TS mirror must carry it\n // or generated factories fail DTS (docs/Almadar_LOLO_Gaps.md L-6).\n | 'union'\n // Fixed-length tuple (`.lolo` `[T1, T2, …]`); slots ride `properties`, keyed by index.\n | 'tuple'\n // The name of a field of a record (`.lolo` `field R T`); a string at rest. `record` is `R`, `items` the type\n // the named field must have, absent for any field. Config-only.\n | 'field';\n\n/** Every `FieldType`, as a runtime array. Downstream imports this instead of\n * re-listing the union — five copies had already drifted apart. */\nexport const FIELD_TYPES = [\n 'string',\n 'number',\n 'int',\n 'boolean',\n 'date',\n 'timestamp',\n 'datetime',\n 'instant',\n 'email',\n 'url',\n 'phone',\n 'uuid',\n 'image',\n 'money',\n 'file',\n 'bytes',\n 'array',\n 'object',\n 'enum',\n 'relation',\n 'trait',\n 'orbital',\n 'behavior',\n 'slot',\n 'pattern',\n 'node',\n 'event',\n 'EventAddress',\n 'CallKey',\n 'SExpr',\n 'union',\n 'tuple',\n 'field',\n] as const satisfies readonly FieldTag[];\n\n/** The semantic string domains — constrained strings, validatable by value. */\nexport const SEMANTIC_STRING_TYPES = ['email', 'url', 'phone', 'uuid', 'image'] as const;\n\nexport type SemanticStringType = (typeof SEMANTIC_STRING_TYPES)[number];\n\n/** Is this a semantic string domain (as opposed to a bare `string`)? */\nexport function isSemanticStringType(type: FieldType): type is SemanticStringType {\n return (SEMANTIC_STRING_TYPES as readonly string[]).includes(type);\n}\n\nexport const FieldTagSchema = z.enum(FIELD_TYPES);\n\nexport function isTypeVariable(type: string): type is TypeVariable {\n return /^\\$.+$/.test(type);\n}\n\nexport const TypeVariableSchema = z.custom<TypeVariable>(\n (v) => typeof v === 'string' && isTypeVariable(v),\n { message: 'a type variable is `$<name>`' },\n);\n\nexport const FieldTypeSchema = z.union([FieldTagSchema, TypeVariableSchema]);\n\n/** Words legal in a `.lolo`/`.orb` TYPE POSITION that are not entity field\n * types (config/param/return annotations, primitives with no field-level\n * meaning, etc.) — declared so the i18n `types` vocabulary section is\n * `FIELD_TYPES ∪ TYPE_POSITION_ONLY` exactly, not a hand-maintained superset\n * held together by a one-directional pinned test (see G-i18n-5). */\nexport const TYPE_POSITION_ONLY = [\n 'Map',\n 'any',\n 'asset',\n 'bool',\n 'component',\n 'duration',\n 'entity',\n 'float',\n 'icon',\n 'null',\n 'secret',\n 'void',\n] as const;\n\n// ============================================================================\n// Relation Configuration\n// ============================================================================\n\n/**\n * Cardinality for relation fields.\n * Matches Rust compiler's Cardinality enum.\n */\nexport type RelationCardinality = \n | 'one' \n | 'many' \n | 'one-to-many' \n | 'many-to-one' \n | 'many-to-many';\n\nexport const RelationCardinalitySchema = z.enum([\n 'one',\n 'many',\n 'one-to-many',\n 'many-to-one',\n 'many-to-many',\n]);\n\n/**\n * Configuration for relation fields (foreign keys).\n * Matches Rust compiler's RelationDefinition format.\n */\nexport type RelationConfig = {\n /** Target entity name (e.g., 'User', 'Task') - matches Rust's `entity` field */\n entity: string;\n /** V4 dual-carry id sibling of `entity` — optional until the Phase-7 flip. */\n entityId?: EntityId;\n /** Field on target entity (defaults to 'id') */\n field?: string;\n /** \n * Cardinality: one, many, one-to-many, many-to-one, many-to-many\n * Matches Rust compiler's cardinality format\n */\n cardinality?: RelationCardinality;\n /** Delete behavior */\n onDelete?: 'cascade' | 'nullify' | 'restrict';\n /** \n * Foreign key field name (for legacy compatibility).\n * @deprecated Use field instead\n */\n foreignKey?: string;\n /**\n * Target entity name (for legacy compatibility).\n * @deprecated Use entity instead\n */\n target?: string;\n /**\n * Cardinality type alias (for legacy compatibility).\n * @deprecated Use cardinality instead\n */\n type?: RelationCardinality;\n};\n\nexport const RelationConfigSchema = z.object({\n entity: z.string().min(1, 'Target entity is required'),\n entityId: EntityIdSchema.optional(),\n field: z.string().optional(),\n cardinality: RelationCardinalitySchema.optional(),\n onDelete: z.enum(['cascade', 'nullify', 'restrict']).optional(),\n // Legacy compatibility fields\n foreignKey: z.string().optional(),\n target: z.string().optional(),\n type: RelationCardinalitySchema.optional(),\n}).transform((data) => {\n // Normalize legacy format to standard format\n const cardinality = data.cardinality || data.type;\n const normalized: RelationConfig = {\n entity: data.entity || data.target || '',\n ...(data.entityId !== undefined ? { entityId: data.entityId } : {}),\n ...(cardinality !== undefined ? { cardinality } : {}),\n ...(data.field !== undefined ? { field: data.field } : {}),\n ...(data.onDelete !== undefined ? { onDelete: data.onDelete } : {}),\n };\n return normalized;\n});\n\nexport type RelationConfigInput = z.input<typeof RelationConfigSchema>;\n\n// ============================================================================\n// Field Format\n// ============================================================================\n\n/**\n * Value rules for the semantic string domains — one owner, so the seeders, the\n * validators and the verifiers cannot drift apart on what counts as valid.\n *\n * These replaced the old optional `format` property, which had zero producers\n * anywhere in the repo and no Rust counterpart at all: `format` was unreachable\n * from `.lolo`, so every consumer fell back to guessing from field names.\n */\n/**\n * The one definition of the semantic string patterns, in the shared regex dialect (`validate/pattern`). The\n * `@almadar/std` `validate/email|url|phone|uuid` operators carry these exact strings in `canonical-operators.json`\n * (generated from here), so the kernel's validators and these readers cannot disagree. `image` is a URL.\n */\nexport const SEMANTIC_STRING_PATTERNS = {\n email: '^[^\\\\s@]+@[^\\\\s@.]+\\\\.[^\\\\s@]+$',\n url: '^https?://[^\\\\s]+$',\n phone: '^[+]?[\\\\d\\\\s().-]{7,}$',\n uuid: '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$',\n} as const;\n\nconst EMAIL_RE = new RegExp(SEMANTIC_STRING_PATTERNS.email);\nconst URL_RE = new RegExp(SEMANTIC_STRING_PATTERNS.url);\nconst PHONE_RE = new RegExp(SEMANTIC_STRING_PATTERNS.phone);\nconst UUID_RE = new RegExp(SEMANTIC_STRING_PATTERNS.uuid);\n\nexport function isEmailValue(value: string): boolean {\n return EMAIL_RE.test(value);\n}\n\nexport function isUrlValue(value: string): boolean {\n return URL_RE.test(value);\n}\n\nexport function isPhoneValue(value: string): boolean {\n return PHONE_RE.test(value);\n}\n\nexport function isUuidValue(value: string): boolean {\n return UUID_RE.test(value);\n}\n\n// ============================================================================\n// File value — the canonical struct a `file`-typed field holds at rest.\n// ONE owner for the shape; mirrors `file_value_fields()` in orbital-core\n// (ir/render.rs) and the codegen zod emitter.\n// ============================================================================\n\n/** The value a `file`-typed entity field holds: an uploaded artifact.\n * `url` is a `data:` URI in mock/playground mode (size-ceilinged by the\n * mock adapter) or an object-storage URL in production. */\nexport type FileValue = {\n name: string;\n url: string;\n mimeType: string;\n sizeBytes: number;\n};\n\n/** Zod schema for {@link FileValue}. */\nexport const FileValueSchema = z.object({\n name: z.string(),\n url: z.string(),\n mimeType: z.string(),\n sizeBytes: z.number(),\n});\n\n/** Is `value` a well-formed {@link FileValue}? The `file` twin of\n * `isSemanticStringValue` — the seeder's output must satisfy this. */\nexport function isFileValue(value: unknown): value is FileValue {\n return FileValueSchema.safeParse(value).success;\n}\n\n/** Does `value` satisfy the declared semantic domain? `image` is a URL. */\nexport function isSemanticStringValue(type: SemanticStringType, value: string): boolean {\n switch (type) {\n case 'email':\n return isEmailValue(value);\n case 'url':\n case 'image':\n return isUrlValue(value);\n case 'phone':\n return isPhoneValue(value);\n case 'uuid':\n return isUuidValue(value);\n }\n}\n\n// ============================================================================\n// Entity Field — discriminated union by `type`\n// ============================================================================\n\n/**\n * Field-type tags that don't carry a type-dependent payload. The base\n * `EntityField` shape applies as-is.\n */\ntype ScalarFieldType =\n | 'string'\n | 'number'\n | 'int'\n | 'boolean'\n | 'date'\n | 'timestamp'\n | 'datetime'\n | 'instant'\n | 'email'\n | 'url'\n | 'phone'\n | 'uuid'\n | 'image'\n | 'money'\n | 'file'\n | 'bytes'\n | 'trait'\n | 'orbital'\n | 'behavior'\n | 'slot'\n | 'pattern'\n | 'node'\n | 'event'\n | 'EventAddress'\n | 'CallKey'\n | 'SExpr';\n\n/** Fields shared across every variant. */\ntype EntityFieldBase = {\n /**\n * Field name (camelCase). Optional for nested item/property descriptors\n * where the name is implied by the parent (`items`, `properties[k]`).\n * Mirrors Rust's `FieldDefinition.name: Option<String>`.\n */\n name?: string;\n /** Whether the field is required */\n required?: boolean;\n nullable?: boolean;\n additionalProperties?: EntityField;\n /** Primary-key marker. Mirrors Rust's `FieldDefinition.primary_key`\n * (serde `primaryKey`). */\n primaryKey?: boolean;\n /** Default value — parsed from `.orb`, always JSON-shaped. */\n default?: JsonValue;\n /** Minimum value (for number) or length (for string) */\n min?: number;\n /** Maximum value or length */\n max?: number;\n /** Object property schemas keyed by property name (for object type).\n * Mirrors Rust's `FieldDefinition.properties: Option<HashMap<String,\n * FieldDefinition>>`. Populated by the lolo lowerer when a field /\n * config slot's type expression resolves to a struct shape\n * (`TypeExpr::Object`), including named-type aliases like `[MetricSpec]`. */\n properties?: Record<string, EntityField>;\n /** Runtime-managed widget state (authored `@intrinsic` in `.lolo`). Exempt\n * from the explicit-binding rule and never a domain-data bind target. */\n intrinsic?: boolean;\n /** Human/semantic description (authored `@description \"...\"` in `.lolo`).\n * Authoring/build-time metadata — factory-signature catalog, embeddings,\n * curation field-matching; the runtime ignores it. */\n description?: string;\n /** User-vocabulary synonyms (authored `@synonyms \"...\"` in `.lolo`).\n * Free text feeding catalog search / curation field-matching. */\n synonyms?: string;\n /** Declared mock value(s) (authored `@mock \"...\"` in `.lolo`), used\n * LITERALLY by the seeder (`sampleValue.ts`, `seed.rs`) — never mapped\n * through a domain-name lookup table. Comma-separated is an explicit\n * candidate list rotated by row index (`@mock \"Acme Corp, Globex Inc\"`);\n * no comma is a single literal value, index-suffixed per row\n * (`@mock \"person-name\"` -> \"person-name-1\", \"person-name-2\", ...). */\n mock?: string;\n /**\n * The imported entity this field was merged from on a rebind (sibling\n * pull / entity contract). Absent on author-declared fields — a merged\n * field's `required` is the ATOM's own write contract, never the host\n * writer's.\n */\n mergedFrom?: string;\n /** `.lolo` `T.f`: the declared field this field's type was projected from. */\n projectedFrom?: FieldProjection;\n};\n\n/**\n * Scalar / structural fields — no type-dependent payload required.\n * `values?` is permitted as an OPTIONAL UI/validation hint (e.g. lolo's\n * `'a' | 'b' | 'c'` string-union sugar lowers to `type: 'string', values:\n * [...]`). Only `EnumEntityField` MANDATES values.\n */\nexport type ScalarEntityField = EntityFieldBase & {\n type: ScalarFieldType;\n /** Optional vocabulary hint for scalar fields (e.g. string unions\n * authored as `'a'|'b'|'c'` in lolo). Not required at this variant. */\n values?: string[];\n};\n\n/** `type: 'enum'` REQUIRES the closed vocabulary in `values`. */\nexport type EnumEntityField = EntityFieldBase & {\n type: 'enum';\n /** Closed string vocabulary the field accepts. */\n values: string[];\n};\n\n/** `type: 'relation'` REQUIRES the relation target binding. */\nexport type RelationEntityField = EntityFieldBase & {\n type: 'relation';\n /** Relation target binding (entity + cardinality). */\n relation: RelationConfig;\n};\n\n/**\n * `type: 'union'` — a TAGGED union of struct variants (`.lolo`\n * `type DrawItem = DrawShape | DrawText`). `values` carries the variant NAMES\n * in declaration order; `properties` (from the base shape) carries each\n * variant's shape keyed by that name. A value selects its variant by the\n * variant's literal-typed tag field, else by the one closed shape it fits\n * (orbital-core `select_union_variant`). Recursion is carried\n * BY NAME: a variant referring back to the union gets `values` with no\n * `properties` (mirrors `FieldType::Union` in orbital-core).\n */\nexport type UnionEntityField = EntityFieldBase & {\n type: 'union';\n /** Variant type names in declaration order. */\n values: string[];\n};\n\n/** `type: 'array'` — element schema in `items` strongly preferred but\n * optional for legacy compatibility with codegen-emitted scalar-array\n * fields (e.g. `{type: 'array', default: []}`). The lolo lowerer + Rust\n * validator catch typed-element-required cases downstream. */\nexport type ArrayEntityField = EntityFieldBase & {\n type: 'array';\n /** Element schema for the array. */\n items?: EntityField;\n};\n\n/** `type: 'tuple'` — a fixed-length tuple (`.lolo` `[T1, T2, …]`, Rust\n * `FieldType::Tuple`): each slot's schema rides `properties`, keyed `\"0\"`, `\"1\"`, …. */\nexport type TupleEntityField = EntityFieldBase & {\n type: 'tuple';\n properties: Record<string, EntityField>;\n};\n\n/** `type: 'field'` — the name of a field of the record `record` (`.lolo` `field R T`); `items` is the type that field\n * must have (absent: any field). `record` is `R` as a type string: `@entity`, `@entity(knob)`, `@payload(knob)`, an\n * entity or alias name, or `$r`; an alias's shape rides `properties`. Mirrors Rust's `FieldType::Field`. */\nexport type FieldRefEntityField = EntityFieldBase & {\n type: 'field';\n record?: string;\n items?: EntityField;\n};\n\n/**\n * `type: 'object'` — a fixed-key struct (fields in `properties`) OR a\n * dynamic-key map (`Map K V` in `.lolo`; the uniform value schema lives in\n * `items`, mirroring an array's element schema). A distinct variant so `items`\n * is statically allowed only on object/array fields, never on scalars.\n */\nexport type ObjectEntityField = EntityFieldBase & {\n type: 'object';\n /** Uniform value schema for a dynamic-key map (`Map K V`). */\n items?: EntityField;\n};\n\n/**\n * Entity field definition — discriminated union by `type`. Each variant\n * statically enforces its dependent payload (`values` for enum,\n * `relation` for relation, `items` for array) so TS / Zod / JSON Schema\n * consumers all agree on the dependency, not just the Rust validator.\n *\n * @example\n * { name: 'status', type: 'enum', values: ['draft', 'published'] }\n * { name: 'authorId', type: 'relation', relation: { entity: 'User', cardinality: 'one' } }\n * { name: 'tags', type: 'array', items: { type: 'string' } }\n */\n/** A field typed by an unbound type variable; binding substitutes it. */\nexport type TypeVariableEntityField = EntityFieldBase & {\n type: TypeVariable;\n};\n\nexport function isTypeVariableField(f: EntityField): f is TypeVariableEntityField {\n return isTypeVariable(f.type);\n}\n\nexport type EntityField =\n | TypeVariableEntityField\n | ScalarEntityField\n | EnumEntityField\n | RelationEntityField\n | UnionEntityField\n | ArrayEntityField\n | TupleEntityField\n | FieldRefEntityField\n | ObjectEntityField;\n\n/**\n * Alias map for legacy/loose field-type spellings. Preprocessed into the\n * canonical `FieldType` enum before zod validates. Without this, agent-produced\n * schemas using `text`/`int`/`float`/`ts` were rejected at parse time — this\n * normalizes them so the rest of the pipeline sees only canonical types.\n */\nconst FIELD_TYPE_ALIASES: Record<string, FieldType> = {\n text: 'string',\n float: 'number',\n ts: 'timestamp',\n};\n\n/**\n * Zod schema for `EntityField`. Preprocess normalizes:\n * - legacy `type` aliases (text → string, int → number, etc.)\n * - legacy `enum: string[]` alias → `values: string[]`\n *\n * Branches on `type` so TS narrows the parsed output to the matching\n * discriminated-union variant.\n */\n// The input type param stays `unknown`: `z.preprocess` bakes `unknown` into\n// its input type, and the recursion needs the explicit annotation.\nexport const EntityFieldSchema: z.ZodType<EntityField, unknown> = z.lazy(() => {\n const baseFieldShape = {\n name: z.string().min(1, 'Field name is required').optional(),\n required: z.boolean().optional(),\n nullable: z.boolean().optional(),\n additionalProperties: EntityFieldSchema.optional(),\n primaryKey: z.boolean().optional(),\n default: JsonValueSchema.optional(),\n min: z.number().optional(),\n max: z.number().optional(),\n properties: z.record(z.string(), EntityFieldSchema).optional(),\n intrinsic: z.boolean().optional(),\n description: z.string().optional(),\n synonyms: z.string().optional(),\n mock: z.string().optional(),\n mergedFrom: z.string().optional(),\n projectedFrom: FieldProjectionSchema.optional(),\n };\n\n /** Build a scalar variant schema. `values?` is permitted as a hint;\n * only the enum variant mandates a non-empty values array. */\n function scalarVariant<T extends ScalarFieldType>(t: T) {\n return z.object({\n ...baseFieldShape,\n type: z.literal(t),\n values: z.array(z.string()).optional(),\n });\n }\n\n return z.preprocess(\n (input) => {\n if (\n input === null ||\n typeof input !== 'object' ||\n !('type' in input) ||\n typeof (input as { type?: RuntimeValue }).type !== 'string'\n ) {\n return input;\n }\n const obj = input as { type: string; enum?: RuntimeValue; values?: RuntimeValue };\n const next: { type: string; enum?: RuntimeValue; values?: RuntimeValue } = { ...obj };\n const aliased = FIELD_TYPE_ALIASES[obj.type];\n if (aliased !== undefined) next.type = aliased;\n // Fold legacy `enum: string[]` into `values: string[]`.\n if (next.enum !== undefined && next.values === undefined) {\n next.values = next.enum;\n }\n delete next.enum;\n return next;\n },\n z.union([\n z.object({ ...baseFieldShape, type: TypeVariableSchema }),\n z.discriminatedUnion('type', [\n scalarVariant('string'),\n scalarVariant('number'),\n scalarVariant('int'),\n scalarVariant('boolean'),\n scalarVariant('date'),\n scalarVariant('timestamp'),\n scalarVariant('datetime'),\n scalarVariant('instant'),\n scalarVariant('email'),\n scalarVariant('url'),\n scalarVariant('phone'),\n scalarVariant('uuid'),\n scalarVariant('image'),\n scalarVariant('trait'),\n scalarVariant('orbital'),\n scalarVariant('behavior'),\n scalarVariant('slot'),\n scalarVariant('pattern'),\n scalarVariant('node'),\n scalarVariant('event'),\n scalarVariant('EventAddress'),\n scalarVariant('CallKey'),\n scalarVariant('money'),\n scalarVariant('file'),\n scalarVariant('bytes'),\n scalarVariant('SExpr'),\n // Enum variant — REQUIRES non-empty values.\n z.object({\n ...baseFieldShape,\n type: z.literal('enum'),\n values: z.array(z.string()).min(1, 'Enum field requires a non-empty `values` array'),\n }),\n // Union variant — tagged struct union; values = variant names,\n // per-variant shapes in `properties` (absent on named recursion).\n z.object({\n ...baseFieldShape,\n type: z.literal('union'),\n values: z.array(z.string()).min(1, 'Union field requires a non-empty `values` array'),\n }),\n // Relation variant — REQUIRES relation config.\n z.object({\n ...baseFieldShape,\n type: z.literal('relation'),\n relation: RelationConfigSchema,\n }),\n // Array variant — items optional to match relaxed TS shape.\n z.object({\n ...baseFieldShape,\n type: z.literal('array'),\n items: EntityFieldSchema.optional(),\n }),\n // Field-reference variant — `items` is the type the named field must have.\n z.object({\n ...baseFieldShape,\n type: z.literal('field'),\n record: z.string().optional(),\n items: EntityFieldSchema.optional(),\n }),\n // Tuple variant — slots in `properties`, keyed by index (at least one).\n z.object({\n ...baseFieldShape,\n type: z.literal('tuple'),\n properties: z.record(z.string(), EntityFieldSchema).refine((p) => Object.keys(p).length > 0, 'Tuple field requires slots in `properties`'),\n }),\n // Object variant — fixed-key struct (`properties`) or dynamic-key\n // map (`Map K V`, uniform value schema in `items`).\n z.object({\n ...baseFieldShape,\n type: z.literal('object'),\n items: EntityFieldSchema.optional(),\n values: z.array(z.string()).optional(),\n }),\n ]),\n ]),\n );\n});\n\nexport type EntityFieldInput = z.input<typeof EntityFieldSchema>;\n\n// ============================================================================\n// Type Aliases (for cleaner imports)\n// ============================================================================\n\n/** Alias for EntityField - preferred name */\nexport type Field = EntityField;\n\n/** Alias for EntityFieldSchema - preferred name */\nexport const FieldSchema = EntityFieldSchema;\n","/**\n * Asset Types for Semantic Asset References\n *\n * Defines types for abstracting asset paths into semantic references.\n * Assets are resolved from SemanticAssetRef to actual paths at compile time.\n *\n * @packageDocumentation\n */\n\nimport { z } from 'zod';\n\n// ============================================================================\n// Entity Roles\n// ============================================================================\n\n/**\n * Entity roles in game contexts\n */\nexport const ENTITY_ROLES = [\n 'player',\n 'enemy',\n 'npc',\n 'item',\n 'tile',\n 'projectile',\n 'effect',\n 'ui',\n 'decoration',\n 'vehicle',\n] as const;\n\nexport type EntityRole = (typeof ENTITY_ROLES)[number];\n\nexport const EntityRoleSchema = z.enum(ENTITY_ROLES);\n\n// ============================================================================\n// Visual Styles\n// ============================================================================\n\n/**\n * Visual art styles for games\n */\nexport const VISUAL_STYLES = ['pixel', 'vector', 'hd', '1-bit', 'isometric'] as const;\n\nexport type VisualStyle = (typeof VISUAL_STYLES)[number];\n\nexport const VisualStyleSchema = z.enum(VISUAL_STYLES);\n\n// ============================================================================\n// Asset Dimension + Aspect (render metadata carried with the asset / the need)\n// ============================================================================\n\n/**\n * Whether the asset is a 2D sprite/image or a 3D model. Set by the consuming\n * canvas: the same entity role is a 2D sprite-sheet on a tile board and a 3D\n * rigged model on a 3D board.\n */\nexport const ASSET_DIMENSIONS = ['2d', '3d'] as const;\n\nexport type AssetDimension = (typeof ASSET_DIMENSIONS)[number];\n\nexport const AssetDimensionSchema = z.enum(ASSET_DIMENSIONS);\n\n/**\n * Rendering aspect ratio of an asset: square (tiles/sprites/portraits/icons),\n * 16:9 (scene backdrops), 5:7 (cards), 8:1 (effect frame strips),\n * 4:1 (wide paddles/bars), 5:3 (wide scenes), 1:2 (tall banners).\n */\nexport const ASSET_ASPECTS = ['1:1', '16:9', '5:7', '8:1', '4:1', '5:3', '1:2'] as const;\n\nexport type AssetAspect = (typeof ASSET_ASPECTS)[number];\n\nexport const AssetAspectSchema = z.enum(ASSET_ASPECTS);\n\n// ============================================================================\n// Effect Kind\n// ============================================================================\n\n/**\n * Stage-table kind of an effect (`role: 'effect'`) asset. Absent means `burst`.\n */\nexport const FX_KINDS = ['slash', 'puff', 'heal', 'trap', 'burst'] as const;\n\nexport type FxKind = (typeof FX_KINDS)[number];\n\nexport const FxKindSchema = z.enum(FX_KINDS);\n\n// ============================================================================\n// Animation Name + Sheet Direction\n// ============================================================================\n\n/**\n * Animation names matching a sprite sheet's row layout. Canonical home for\n * this vocabulary — `@almadar/ui`'s `spriteAnimationTypes.ts` re-exports it\n * rather than redeclaring, so board `.lolo` config and the render library\n * agree on one enum.\n */\nexport const ANIMATION_NAMES = ['idle', 'walk', 'skate', 'jump', 'fall', 'attack', 'hit', 'death'] as const;\n\nexport type AnimationName = (typeof ANIMATION_NAMES)[number];\n\nexport const AnimationNameSchema = z.enum(ANIMATION_NAMES);\n\n/**\n * Sheet file directions (physical PNG files a sprite sheet ships as).\n * Legacy hand-drawn packs ship only se/sw and mirror-flip for ne/nw (a cheat\n * that shows the face while walking away); 3D-baked sheets ship all four real\n * directions — the renderer prefers a real sheet and keeps the flip only as\n * the legacy fallback.\n */\nexport const SPRITE_DIRECTIONS = ['se', 'sw', 'ne', 'nw'] as const;\n\nexport type SpriteDirection = (typeof SPRITE_DIRECTIONS)[number];\n\nexport const SpriteDirectionSchema = z.enum(SPRITE_DIRECTIONS);\n\n/**\n * Camera projections a baked sprite sheet can ship. `iso` is directional\n * (se/sw physical sheets, ne/nw by mirror); `front`/`top`/`perspective` are\n * single fixed-camera sheets (the mesh reference-sheet camera vocabulary).\n */\nexport const SHEET_PROJECTIONS = ['iso', 'front', 'back', 'top', 'perspective'] as const;\n\nexport type SheetProjection = (typeof SHEET_PROJECTIONS)[number];\n\nexport const SheetProjectionSchema = z.enum(SHEET_PROJECTIONS);\n\n// ============================================================================\n// Animation Definition\n// ============================================================================\n\n/**\n * Definition for a single named animation within a sprite sheet: which row\n * it occupies, how many frames it has, and its playback rate. This is the\n * shape actually consumed by `@almadar/ui`'s sprite-sheet renderer\n * (`spriteAnimation.ts`'s `frameRect`/`getCurrentFrameFromDef`) — moved here\n * verbatim rather than reconciled with a differently-shaped guess, since\n * `@almadar/ui`'s version is the one with real production consumers.\n */\nexport interface AnimationDef {\n /** Row index in the sprite sheet (0-based; each animation occupies one row). */\n row: number;\n /** Number of frames in this animation. */\n frames: number;\n /** Frames per second. */\n frameRate: number;\n /** Whether the animation loops. */\n loop: boolean;\n}\n\nexport const AnimationDefSchema = z.object({\n row: z.number().int().nonnegative(),\n frames: z.number().int().positive(),\n frameRate: z.number().positive(),\n loop: z.boolean(),\n});\n\n// ============================================================================\n// Sprite Sheet Atlas\n// ============================================================================\n\n/**\n * Parsed sprite-sheet atlas JSON — the contract a `spriteSheet`-role `Asset.url`\n * resolves to when fetched (see `Asset.url` usage in `@almadar/ui`'s\n * `useUnitSpriteAtlas`). A unit's `sprite?: Asset` stays the static single-pose\n * image; `spriteSheet?: Asset` is a SEPARATE reference whose URL points at a\n * `SpriteSheetAtlas`-shaped JSON manifest (e.g. `.../guardian-sprite-sheet.json`),\n * not a PNG. Frame-cutting geometry lives here, not inlined onto `Asset` — an\n * `Asset` traveling through `render-ui` every tick stays small.\n */\nexport interface SpriteSheetAtlas {\n /** Unit archetype key. */\n unit?: string;\n /** Visual type key. */\n type?: string;\n /** Width of a single frame in pixels. */\n frameWidth: number;\n /** Height of a single frame in pixels. */\n frameHeight: number;\n /** Number of columns (frames per row). */\n columns: number;\n /** Number of rows (animations). */\n rows: number;\n /** Directions present as physical PNG files. */\n directions: SpriteDirection[];\n /** Relative PNG sheet paths per direction. */\n sheets: Partial<Record<SpriteDirection, string>>;\n /** Animation row layout keyed by animation name. Unit sheets use the canonical `AnimationName` rows; one-shot fx sheets declare their own names (e.g. `burst`) — the manifest is authoritative for its rows. */\n animations: Partial<Record<string, AnimationDef>>;\n /**\n * Per-projection sheet PNGs (additive; absent on legacy atlases). `iso`\n * mirrors `sheets` (directional se/sw); the fixed cameras carry one sheet\n * each. `sheets` remains the iso back-compat alias — writers emit both.\n */\n projections?: {\n iso?: Partial<Record<SpriteDirection, string>>;\n front?: string;\n back?: string;\n top?: string;\n perspective?: string;\n };\n}\n\nexport const SpriteSheetAtlasSchema = z.object({\n unit: z.string().optional(),\n type: z.string().optional(),\n frameWidth: z.number().positive(),\n frameHeight: z.number().positive(),\n columns: z.number().int().positive(),\n rows: z.number().int().positive(),\n directions: z.array(SpriteDirectionSchema),\n sheets: z.partialRecord(SpriteDirectionSchema, z.string()),\n animations: z.record(z.string(), AnimationDefSchema),\n projections: z\n .object({\n iso: z.partialRecord(SpriteDirectionSchema, z.string()).optional(),\n front: z.string().optional(),\n back: z.string().optional(),\n top: z.string().optional(),\n perspective: z.string().optional(),\n })\n .optional(),\n});\n\n// ============================================================================\n// Texture Atlas — named-subrect packed sheet (the industry standard)\n// ============================================================================\n\n/**\n * One named sub-rectangle inside a packed sheet. Mirrors the ShoeBox /\n * TexturePacker `<SubTexture>` element every Kenney `Spritesheet/*.xml` ships\n * (`x`/`y`/`width`/`height` = the rect in the sheet PNG; `frameX`/`frameY`/\n * `frameWidth`/`frameHeight` = the trim/pad offsets for sprites packed with\n * transparent edges removed — optional, present only on trimmed atlases).\n */\nexport interface SubTexture {\n x: number;\n y: number;\n width: number;\n height: number;\n frameX?: number;\n frameY?: number;\n frameWidth?: number;\n frameHeight?: number;\n}\n\nexport const SubTextureSchema = z.object({\n x: z.number().nonnegative(),\n y: z.number().nonnegative(),\n width: z.number().positive(),\n height: z.number().positive(),\n frameX: z.number().optional(),\n frameY: z.number().optional(),\n frameWidth: z.number().positive().optional(),\n frameHeight: z.number().positive().optional(),\n});\n\n/**\n * A packed sheet + its named sub-rectangles — the canonical parse target for a\n * Kenney `Spritesheet/*.xml` atlas. A STATIC tile/prop/UI Asset references one\n * of these: `{ url: <sheet.png>, atlas: <this.json>, sprite: \"grass.png\" }` →\n * the renderer fetches the sheet + atlas ONCE and blits the named sub-rect,\n * instead of loading N individual PNGs. (Animated actors use `SpriteSheetAtlas`\n * instead; a uniform-grid tile page uses `Tilesheet`.)\n */\nexport interface TextureAtlas {\n /** Relative path to the sheet PNG the sub-rects index into (the atlas's own `imagePath`). */\n imagePath: string;\n /** Sub-rectangles keyed by their atlas name (e.g. `\"grass.png\"`). */\n subTextures: Record<string, SubTexture>;\n}\n\nexport const TextureAtlasSchema = z.object({\n imagePath: z.string(),\n subTextures: z.record(z.string(), SubTextureSchema),\n});\n\n// ============================================================================\n// Tilesheet — uniform-grid packed page (cut by index)\n// ============================================================================\n\n/**\n * A uniform-grid tile page — the shape a Kenney `Tilesheet/` sheet takes (e.g.\n * Pirate Pack: \"each tile is 64×64, no margin\"). Tiles are cut by `(col,row)`\n * index rather than by named rect. `names` is present only when a sibling\n * `.xml`/`.txt` supplies an index→name list; otherwise a tile is addressed by\n * its `\"col,row\"` (or flat index) via `Asset.sprite`.\n */\nexport interface Tilesheet {\n /** Relative path to the tile sheet PNG. */\n imagePath: string;\n /** Width of one tile cell in pixels. */\n tileWidth: number;\n /** Height of one tile cell in pixels. */\n tileHeight: number;\n /** Number of columns in the grid. */\n columns: number;\n /** Number of rows in the grid. */\n rows: number;\n /** Outer margin before the first tile, in pixels (default 0). */\n margin?: number;\n /** Gap between adjacent tiles, in pixels (default 0). */\n spacing?: number;\n /** Optional index→name labels when a descriptor supplies them. */\n names?: string[];\n}\n\nexport const TilesheetSchema = z.object({\n imagePath: z.string(),\n tileWidth: z.number().positive(),\n tileHeight: z.number().positive(),\n columns: z.number().int().positive(),\n rows: z.number().int().positive(),\n margin: z.number().nonnegative().optional(),\n spacing: z.number().nonnegative().optional(),\n names: z.array(z.string()).optional(),\n});\n\n// ============================================================================\n// Semantic Asset Reference\n// ============================================================================\n\n/**\n * Semantic reference to an asset (not a hardcoded path).\n * Resolved to actual paths at compile time via asset maps.\n */\nexport type SemanticAssetRef = {\n /**\n * Entity role — a free string. Core no longer constrains the vocabulary to\n * `EntityRole` (that enum stays an exported shared reference for the asset\n * tool + renderer); genre boards may use their own roles (`boss`, `tower`, …).\n */\n role: string;\n /** Sub-category within role (hero, slime, coin, etc.) */\n category: string;\n /** Required animations for this entity */\n animations?: string[];\n /** Visual style preference */\n style?: VisualStyle;\n /** Variant identifier (for multiple versions) */\n variant?: string;\n /** 2D sprite vs 3D model — the rendering dimension the consuming canvas needs. */\n dimension?: AssetDimension;\n /** Rendering aspect ratio (square sprite/portrait/tile, 16:9 backdrop, 5:7 card, 8:1 fx-strip). */\n aspect?: AssetAspect;\n};\n\nexport const SemanticAssetRefSchema = z.object({\n role: z.string().min(1),\n category: z.string().min(1),\n animations: z.array(z.string()).optional(),\n style: VisualStyleSchema.optional(),\n variant: z.string().optional(),\n dimension: AssetDimensionSchema.optional(),\n aspect: AssetAspectSchema.optional(),\n});\n\n// ============================================================================\n// Asset — the UNIFIED asset type\n// ============================================================================\n\n/**\n * The single asset type: a `SemanticAssetRef` (role/dimension/animations/aspect/style)\n * WITH its resolved URL folded in. Used everywhere an asset is referenced — a lolo\n * board `assetManifest` (`Map string Asset`), every `@almadar/ui` game prop, the\n * asset-workflow's resolved/pool assets, and the inspector picker. Replaces the bare\n * `AssetUrl`-string asset field so the render metadata travels WITH the asset (no\n * pixel-dimension or filename heuristics needed to know sheet-vs-frame / 2d-vs-3d).\n */\nexport interface Asset extends SemanticAssetRef {\n /** The resolved asset URL. When `atlas`/`sprite` are set this is the SHEET png; otherwise a standalone image. */\n url: AssetUrl;\n /**\n * Optional atlas JSON (a `TextureAtlas` or `Tilesheet`) that slices `url`.\n * When present with `sprite`, the renderer fetches sheet + atlas once and\n * blits one sub-rect instead of loading a standalone PNG. Absent → `url` is\n * a plain whole-image asset (the existing, non-atlas path).\n */\n atlas?: AssetUrl;\n /**\n * The sub-texture selector within `atlas`: a `SubTexture` name for a\n * `TextureAtlas` (e.g. `\"grass.png\"`), or a `\"col,row\"`/flat index for a\n * `Tilesheet`. Only meaningful alongside `atlas`.\n */\n sprite?: string;\n /** Optional display name (inspector picker). */\n name?: string;\n /** Optional thumbnail URL (inspector picker grid). */\n thumbnailUrl?: string;\n /** Authored generation subject (visualDNA) for asset-workflow regeneration. */\n prompt?: string;\n /** Authored per-animation frame choreography — the exact pose per frame, the only pose source for animated slots. */\n choreography?: Record<string, string[]>;\n /** Effect stage-table kind for an `effect` asset; absent → `burst`. */\n fxKind?: FxKind;\n}\n\nexport const AssetSchema = SemanticAssetRefSchema.extend({\n url: z.string(),\n atlas: z.string().optional(),\n sprite: z.string().optional(),\n name: z.string().optional(),\n thumbnailUrl: z.string().optional(),\n prompt: z.string().optional(),\n choreography: z.record(z.string(), z.array(z.string())).optional(),\n fxKind: FxKindSchema.optional(),\n});\n\n// ============================================================================\n// Asset Pack Manifest\n// ============================================================================\n\n/**\n * One board's asset pack, shipped as `assets.json` beside its `board.meta.json`.\n * The board declares `assetPack` (this `pack` id); asset generation writes ONLY\n * this file, never the board `.lolo`. `assets` is keyed `<group>/<name>`\n * (`units/guardian`, `ui/panel-frame`); each entry's `url` is relative to `base`.\n */\nexport interface AssetPackManifest {\n /** Pack id, `<brand>/<board>` (e.g. `kflow/ui-battle-board`). */\n pack: string;\n version: number;\n /** URL prefix every entry `url`/`atlas` is relative to. */\n base: string;\n assets: Record<string, Asset>;\n}\n\nexport const AssetPackManifestSchema = z.object({\n pack: z.string().min(1),\n version: z.number().int().nonnegative(),\n base: z.string(),\n assets: z.record(z.string(), AssetSchema),\n});\n\n// ============================================================================\n// Asset Catalog\n// ============================================================================\n\n/**\n * Single browsable asset in the inspector picker catalog.\n * Backs the asset/icon pickers — a flat list the inspector renders for\n * the user to choose from when a config field's type is `'asset'`.\n */\nexport interface AssetCatalogEntry {\n /** Resolvable URL to the asset. */\n url: string;\n /** Display name for the asset. */\n name: string;\n /** Grouping category within the catalog. */\n category: string;\n /** Asset kind the picker dispatches on. */\n kind: 'image' | 'spritesheet' | 'audio' | 'scene' | 'portrait' | 'model' | 'other';\n /** Optional thumbnail URL for grid previews. */\n thumbnailUrl?: string;\n /** 2D sprite vs 3D model — the asset's actual rendering dimension. */\n dimension?: AssetDimension;\n /** The asset's actual rendering aspect ratio. */\n aspect?: AssetAspect;\n}\n\nexport const AssetCatalogEntrySchema = z.object({\n url: z.string(),\n name: z.string(),\n category: z.string(),\n kind: z.enum(['image', 'spritesheet', 'audio', 'scene', 'portrait', 'model', 'other']),\n thumbnailUrl: z.string().optional(),\n dimension: AssetDimensionSchema.optional(),\n aspect: AssetAspectSchema.optional(),\n});\n\n/**\n * Flat list of browsable assets surfaced by the inspector pickers.\n */\nexport type AssetCatalog = AssetCatalogEntry[];\n\nexport const AssetCatalogSchema = z.array(AssetCatalogEntrySchema);\n\n/**\n * Asset-reference URL marker. A plain alias over `string` — the value is a\n * resolvable asset URL — but the named type lets the pattern-sync tool\n * (`tools/almadar-pattern-sync/parser.ts`) detect a component prop as an asset\n * field (tagged `asset`) the same way `EventKey`/`LucideIcon` are detected by\n * type identity. Components annotate image/url props as `AssetUrl` (`src`,\n * `backgroundImage`, `avatar`, …); the generator emits a `string` config knob\n * declared as the `asset` config type, which the property inspector dispatches\n * an AssetPicker on. Not branded — asset urls originate from user data, so cast\n * friction would buy nothing; the value is the marker the tool finds.\n */\nexport type AssetUrl = string;\n\n// ============================================================================\n// ScenePos — neutral scene coordinate\n// ============================================================================\n\n/**\n * A neutral position in scene space: 2D (`x`,`y`) or optionally 3D (`x`,`y`,`z`).\n * The single coordinate type shared by every drawable descriptor and camera pose\n * across the 2D and 3D canvas hosts, so a scene composes from the same `{x,y,z?}`\n * regardless of projection or painter. Logical, not pixel — the host's projector\n * maps a `ScenePos` to screen space.\n */\nexport interface ScenePos {\n x: number;\n y: number;\n z?: number;\n}\n\nexport const ScenePosSchema = z.object({\n x: z.number(),\n y: z.number(),\n z: z.number().optional(),\n});\n\n// ============================================================================\n// Camera — neutral camera pose shared by the 2D and 3D canvas hosts\n// ============================================================================\n\n/**\n * Camera behaviors, unifying the former per-host vocab (2D `camera` string +\n * 3D `cameraMode`). `isometric`/`top-down`/`front` are fixed framings (`front` =\n * the straight-on flat elevation — side-scroller / reference-sheet view);\n * `follow`/`chase` track a target; `perspective` is the 3D dramatic framing.\n */\nexport const CAMERA_MODES = ['isometric', 'perspective', 'top-down', 'front', 'follow', 'chase'] as const;\n\nexport type CameraMode = (typeof CAMERA_MODES)[number];\n\nexport const CameraModeSchema = z.enum(CAMERA_MODES);\n\n/**\n * A neutral camera pose shared by the 2D and 3D canvas hosts, so `type: canvas`\n * carries one camera object regardless of painter. `pos`/`target` are `ScenePos`\n * (logical scene space, not pixels); `zoom` scales the view (the former `scale`);\n * `fov` is the 3D field of view; `mode` selects the framing/tracking behavior.\n * Every field is optional — an omitted camera means the host's default framing.\n */\nexport interface Camera {\n pos?: ScenePos;\n target?: ScenePos;\n zoom?: number;\n fov?: number;\n mode?: CameraMode;\n /** Orbit the mode's framing position around the vertical axis through the target, in radians (3D hosts only). */\n azimuth?: number;\n /** Orbit height angle above the ground plane, in radians (3D hosts only). */\n elevation?: number;\n /** Whether the viewer may orbit, pan or zoom the camera. `false` holds the authored framing: a decorative backdrop the page scrolls through. Default true. */\n controls?: boolean;\n}\n\nexport const CameraSchema = z.object({\n pos: ScenePosSchema.optional(),\n target: ScenePosSchema.optional(),\n zoom: z.number().optional(),\n fov: z.number().optional(),\n mode: CameraModeSchema.optional(),\n azimuth: z.number().optional(),\n elevation: z.number().optional(),\n controls: z.boolean().optional(),\n});\n\n// ============================================================================\n// Type Exports\n// ============================================================================\n\nexport type SemanticAssetRefInput = z.input<typeof SemanticAssetRefSchema>;\nexport type AnimationDefInput = z.input<typeof AnimationDefSchema>;\nexport type AssetCatalogEntryInput = z.input<typeof AssetCatalogEntrySchema>;\nexport type SpriteSheetAtlasInput = z.input<typeof SpriteSheetAtlasSchema>;\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Creates a semantic asset key from role and category.\n * \n * Generates a unique asset identifier by combining role and category\n * with a colon separator. Used for asset management and lookup.\n * \n * @param {EntityRole} role - Entity role (e.g., 'player', 'enemy')\n * @param {string} category - Asset category (e.g., 'sprite', 'animation')\n * @returns {string} Asset key in format 'role:category'\n * \n * @example\n * createAssetKey('player', 'sprite'); // returns 'player:sprite'\n * createAssetKey('enemy', 'animation'); // returns 'enemy:animation'\n */\nexport function createAssetKey(role: EntityRole, category: string): string {\n return `${role}:${category}`;\n}\n\n/**\n * Parses an asset key into role and category components.\n * \n * Deconstructs an asset key string (format 'role:category') into its\n * constituent parts. Returns null if the key format is invalid.\n * \n * @param {string} key - Asset key in format 'role:category'\n * @returns {{ role: string; category: string } | null} Parsed components or null\n * \n * @example\n * parseAssetKey('player:sprite'); // returns { role: 'player', category: 'sprite' }\n * parseAssetKey('enemy:animation'); // returns { role: 'enemy', category: 'animation' }\n * parseAssetKey('invalid'); // returns null\n */\nexport function parseAssetKey(key: string): { role: string; category: string } | null {\n const parts = key.split(':');\n if (parts.length !== 2) return null;\n return { role: parts[0], category: parts[1] };\n}\n\n/**\n * Gets common animations for an entity role.\n * \n * Returns an array of default animation names appropriate for the\n * specified entity role. Used for asset configuration and validation.\n * \n * @param {EntityRole} role - Entity role\n * @returns {string[]} Array of default animation names\n * \n * @example\n * getDefaultAnimationsForRole('player'); // returns ['idle', 'run', 'jump', 'fall', 'attack', 'hurt', 'die']\n * getDefaultAnimationsForRole('enemy'); // returns ['idle', 'walk', 'attack', 'hurt', 'die']\n */\nexport function getDefaultAnimationsForRole(role: EntityRole): string[] {\n switch (role) {\n case 'player':\n return ['idle', 'run', 'jump', 'fall', 'attack', 'hurt', 'die'];\n case 'enemy':\n return ['idle', 'walk', 'attack', 'hurt', 'die'];\n case 'npc':\n return ['idle', 'walk', 'talk'];\n case 'item':\n return ['idle', 'collected'];\n case 'tile':\n return ['static'];\n case 'projectile':\n return ['fly', 'hit', 'expire'];\n case 'effect':\n return ['play'];\n case 'ui':\n return ['normal', 'hover', 'pressed', 'disabled'];\n case 'decoration':\n return ['idle'];\n case 'vehicle':\n return ['idle', 'move', 'brake'];\n default:\n return ['idle'];\n }\n}\n\n/**\n * Validates that an asset reference has required animations.\n * \n * Checks if an asset reference contains all required animations.\n * Returns an error message if validation fails, or null if valid.\n * \n * @param {SemanticAssetRef} assetRef - Asset reference to validate\n * @param {string[]} requiredAnimations - Required animation names\n * @returns {string | null} Error message or null if valid\n * \n * @example\n * validateAssetAnimations(assetRef, ['idle', 'run']); // returns null if valid\n * validateAssetAnimations(assetRef, ['missing-animation']); // returns error message\n */\nexport function validateAssetAnimations(\n assetRef: SemanticAssetRef,\n requiredAnimations: string[]\n): { valid: boolean; missing: string[] } {\n const provided = assetRef.animations || [];\n const missing = requiredAnimations.filter((anim) => !provided.includes(anim));\n return { valid: missing.length === 0, missing };\n}\n\n// ============================================================================\n// Sprite Sheet Layout — the canonical unit sheet convention (owner-approved\n// \"Sheet convergence\": 8 cols x 5 rows @ 256px, dark charcoal background).\n// `tools/asset-workflow`'s `spritesheet-bake.ts` (SPRITE_LAYOUT) and\n// `prompt-composer.ts` derive from this; this is the single source.\n// ============================================================================\n\nexport const SPRITE_SHEET_LAYOUT = {\n frameWidth: 256,\n frameHeight: 256,\n columns: 8,\n rows: 5,\n background: '#20202E',\n} as const;\n\nexport type SpriteSheetLayout = typeof SPRITE_SHEET_LAYOUT;\n\n/**\n * The canonical unit animation row table (idle/walk/attack/hit/death), one\n * row per `AnimationName`, in sheet-row order. Mirrors\n * `tools/asset-workflow/src/spritesheet-bake.ts`'s `SPRITE_LAYOUT`.\n */\nexport const DEFAULT_UNIT_ANIMATION_ROWS: ReadonlyArray<{ name: AnimationName } & AnimationDef> = [\n { name: 'idle', row: 0, frames: 4, loop: true, frameRate: 6 },\n { name: 'walk', row: 1, frames: 8, loop: true, frameRate: 10 },\n { name: 'attack', row: 2, frames: 6, loop: false, frameRate: 12 },\n { name: 'hit', row: 3, frames: 3, loop: false, frameRate: 8 },\n { name: 'death', row: 4, frames: 6, loop: false, frameRate: 8 },\n] as const;\n\n/**\n * Builds the canonical unit `SpriteSheetAtlas` from `SPRITE_SHEET_LAYOUT` +\n * `DEFAULT_UNIT_ANIMATION_ROWS` for a given set of direction sheets. Directions\n * default to whichever keys `sheets` actually carries (legacy se/sw-only packs\n * included), or the caller can force a specific set via `opts.directions`.\n */\nexport function defaultUnitAtlas(\n sheets: SpriteSheetAtlas['sheets'],\n opts?: { directions?: SpriteDirection[] }\n): SpriteSheetAtlas {\n const directions = opts?.directions ?? SPRITE_DIRECTIONS.filter((direction) => sheets[direction] !== undefined);\n const animations: Partial<Record<string, AnimationDef>> = {};\n for (const { name, ...def } of DEFAULT_UNIT_ANIMATION_ROWS) {\n animations[name] = def;\n }\n return {\n frameWidth: SPRITE_SHEET_LAYOUT.frameWidth,\n frameHeight: SPRITE_SHEET_LAYOUT.frameHeight,\n columns: SPRITE_SHEET_LAYOUT.columns,\n rows: SPRITE_SHEET_LAYOUT.rows,\n directions,\n sheets,\n animations,\n };\n}\n\n// ============================================================================\n// Manifest Entry — the kflow-assets `manifest.json` row shape. Core is the\n// owner; `tools/asset-workflow`'s `ExtendedManifestEntry` converges onto this\n// (mirrors `tools/asset-workflow/src/asset-schema.ts`'s `CanvasAffinity`,\n// `FrameSpec`, `AssetLicense`, `SourceCatalog` literal unions).\n// ============================================================================\n\nexport const MANIFEST_ENTRY_KINDS = ['model', 'image', 'spritesheet', 'audio', 'json'] as const;\n\nexport type ManifestEntryKind = (typeof MANIFEST_ENTRY_KINDS)[number];\n\nexport const ManifestEntryKindSchema = z.enum(MANIFEST_ENTRY_KINDS);\n\n// ============================================================================\n// Game audio\n// ============================================================================\n\n/**\n * One entry of a game's sound manifest, keyed by logical cue name. Core owns\n * the shape so both the render substrate (`useGameAudio` / the `game-audio-cue`\n * pattern) and the generated `.lolo` factories resolve the SAME declaration —\n * a hook-local interface is invisible to the pattern extractor and lowers to a\n * shapeless `object`, which the `.lolo` type system rejects outright.\n */\nexport interface SoundEntry {\n /** Single path, or several to pick from at random on each play. */\n path: string | string[];\n /** Volume 0-1, multiplied by the master volume. */\n volume?: number;\n /** Whether this sound loops (background music). */\n loop?: boolean;\n /** Concurrent Audio instances kept in the pool. */\n poolSize?: number;\n /** Start automatically on the first user interaction. */\n autostart?: boolean;\n /** Use crossfade transitions when played as music. */\n crossfade?: boolean;\n /** Crossfade duration in milliseconds. */\n crossfadeDurationMs?: number;\n}\n\nexport const SoundEntrySchema = z.object({\n path: z.union([z.string(), z.array(z.string())]),\n volume: z.number().optional(),\n loop: z.boolean().optional(),\n poolSize: z.number().optional(),\n autostart: z.boolean().optional(),\n crossfade: z.boolean().optional(),\n crossfadeDurationMs: z.number().optional(),\n});\n\n/** A game's sound manifest: logical cue name → its definition. */\nexport type AudioManifest = Record<string, SoundEntry>;\n\nexport const AudioManifestSchema = z.record(z.string(), SoundEntrySchema);\n\nexport const MANIFEST_CANVAS_AFFINITIES = ['isometric', 'hex', 'flat', 'side', '3d', 'none'] as const;\n\nexport type ManifestCanvasAffinity = (typeof MANIFEST_CANVAS_AFFINITIES)[number];\n\nexport const ManifestCanvasAffinitySchema = z.enum(MANIFEST_CANVAS_AFFINITIES);\n\nexport const MANIFEST_SOURCE_CATALOGS = ['kenny', 'kekec-assets', 'iram-assets', 'trait-wars-assets', 'kflow-assets'] as const;\n\nexport type ManifestSourceCatalog = (typeof MANIFEST_SOURCE_CATALOGS)[number];\n\nexport const ManifestSourceCatalogSchema = z.enum(MANIFEST_SOURCE_CATALOGS);\n\nexport const MANIFEST_ASSET_LICENSES = ['CC0', 'proprietary'] as const;\n\nexport type ManifestAssetLicense = (typeof MANIFEST_ASSET_LICENSES)[number];\n\nexport const ManifestAssetLicenseSchema = z.enum(MANIFEST_ASSET_LICENSES);\n\n/**\n * Path of the sheet's `atlas.json` relative to the pack's `shared/` root\n * (`riya-platformer/units/riya/atlas.json`) — the executable frame truth for\n * unit sheets whose rows are not uniform.\n */\nexport type ManifestAtlasRef = string;\n\n/** Tile/sprite-sheet frame layout for a manifest row, an atlas reference, else `null`. */\nexport type ManifestFrameSpec =\n | { kind: 'iso-tile'; w: number; h: number }\n | { kind: 'sprite-sheet'; frame: number; cols: number; rows: number }\n | ManifestAtlasRef\n | null;\n\nexport const ManifestFrameSpecSchema = z.union([\n z.object({ kind: z.literal('iso-tile'), w: z.number(), h: z.number() }),\n z.object({ kind: z.literal('sprite-sheet'), frame: z.number(), cols: z.number(), rows: z.number() }),\n z.string().min(1),\n z.null(),\n]);\n\n/**\n * One row of `almadar-assets/kflow-assets/manifest.json`. Core owns this\n * shape; `tools/asset-workflow`'s `ExtendedManifestEntry` converges onto it.\n */\nexport interface ManifestEntry {\n url: string;\n name: string;\n category: string;\n kind: ManifestEntryKind;\n width: number;\n height: number;\n canvasAffinity: ManifestCanvasAffinity;\n genreAffinity: string[];\n swapClass: string;\n sourceCatalog: ManifestSourceCatalog;\n frameSpec: ManifestFrameSpec;\n /** Provenance-extended field: present on the promote/register path only. */\n license?: ManifestAssetLicense;\n}\n\nexport const ManifestEntrySchema = z.object({\n url: z.string(),\n name: z.string(),\n category: z.string(),\n kind: ManifestEntryKindSchema,\n width: z.number(),\n height: z.number(),\n canvasAffinity: ManifestCanvasAffinitySchema,\n genreAffinity: z.array(z.string()),\n swapClass: z.string(),\n sourceCatalog: ManifestSourceCatalogSchema,\n frameSpec: ManifestFrameSpecSchema,\n license: ManifestAssetLicenseSchema.optional(),\n});\n\nexport type ManifestEntryInput = z.input<typeof ManifestEntrySchema>;\n\n// ============================================================================\n// Manifest -> Asset Catalog adapter\n// ============================================================================\n\nconst ASSET_CATALOG_ENTRY_KINDS: readonly AssetCatalogEntry['kind'][] = [\n 'image',\n 'spritesheet',\n 'audio',\n 'scene',\n 'portrait',\n 'model',\n 'other',\n];\n\nconst MODEL_URL_EXTENSIONS = ['.glb', '.gltf'];\nconst AUDIO_URL_EXTENSIONS = ['.mp3', '.ogg', '.wav'];\n\nfunction urlEndsWithAny(url: string, extensions: readonly string[]): boolean {\n const lower = url.toLowerCase();\n return extensions.some((extension) => lower.endsWith(extension));\n}\n\n/**\n * Declared, order-sensitive rule for deriving the catalog `kind` from a\n * manifest row: `frameSpec`/`kind==='spritesheet'` beats extension, which\n * beats the manifest's own `kind`. No filename-keyword guessing.\n */\nfunction deriveManifestAssetKind(entry: ManifestEntry): AssetCatalogEntry['kind'] {\n if (typeof entry.frameSpec === 'string' || entry.frameSpec?.kind === 'sprite-sheet' || entry.kind === 'spritesheet') return 'spritesheet';\n if (entry.kind === 'model' || urlEndsWithAny(entry.url, MODEL_URL_EXTENSIONS)) return 'model';\n if (entry.kind === 'audio' || urlEndsWithAny(entry.url, AUDIO_URL_EXTENSIONS)) return 'audio';\n if (entry.kind === 'image') return 'image';\n return 'other';\n}\n\nfunction parseAssetAspectRatio(aspect: AssetAspect): number {\n const [w, h] = aspect.split(':').map(Number);\n return w / h;\n}\n\nconst ASSET_ASPECT_RATIO_TOLERANCE = 0.01;\n\n/**\n * The asset's aspect only when width/height are both known (> 0) and their\n * ratio matches exactly one `ASSET_ASPECTS` entry within 1%; otherwise\n * omitted (never guessed).\n */\nfunction deriveManifestAssetAspect(width: number, height: number): AssetAspect | undefined {\n if (width <= 0 || height <= 0) return undefined;\n const ratio = width / height;\n for (const aspect of ASSET_ASPECTS) {\n const expected = parseAssetAspectRatio(aspect);\n if (Math.abs(ratio / expected - 1) <= ASSET_ASPECT_RATIO_TOLERANCE) return aspect;\n }\n return undefined;\n}\n\nconst ABSOLUTE_URL_PATTERN = /^[a-z][a-z0-9+.-]*:\\/\\//i;\n\n/** Prefixes a relative manifest url with `cdnPrefix`; leaves an absolute url untouched. */\nfunction resolveManifestUrl(url: string, cdnPrefix?: string): string {\n if (!cdnPrefix || ABSOLUTE_URL_PATTERN.test(url)) return url;\n const prefix = cdnPrefix.endsWith('/') ? cdnPrefix : `${cdnPrefix}/`;\n const rest = url.startsWith('/') ? url.slice(1) : url;\n return `${prefix}${rest}`;\n}\n\n/**\n * Adapts kflow-assets manifest rows into the inspector picker's\n * `AssetCatalog`. The ONE deterministic derivation the Kura assets server\n * route (`GET /api/assets/catalog`) and any other manifest consumer share.\n */\nexport function manifestToAssetCatalog(entries: ReadonlyArray<ManifestEntry>, opts?: { cdnPrefix?: string }): AssetCatalog {\n return entries.map((entry) => {\n const kind = deriveManifestAssetKind(entry);\n const dimension: AssetDimension = entry.canvasAffinity === '3d' ? '3d' : '2d';\n const aspect = deriveManifestAssetAspect(entry.width, entry.height);\n const url = resolveManifestUrl(entry.url, opts?.cdnPrefix);\n const catalogEntry: AssetCatalogEntry = {\n url,\n name: entry.name,\n category: entry.category,\n kind,\n dimension,\n };\n if (aspect !== undefined) catalogEntry.aspect = aspect;\n if (kind === 'image' || kind === 'spritesheet') catalogEntry.thumbnailUrl = url;\n return catalogEntry;\n });\n}\n\n// ============================================================================\n// Asset query grammar — Unity-style `t:<kind>` / `l:<label>` + free text.\n// The ONE grammar `parseAssetQuery`/`matchAssetQuery` implement; every\n// consumer (the Kura assets server route, the client's `asset-query.ts`)\n// imports these instead of re-parsing.\n// ============================================================================\n\nconst ASSET_QUERY_TYPE_PREFIX = 't:';\nconst ASSET_QUERY_LABEL_PREFIX = 'l:';\n\nfunction isAssetCatalogEntryKind(value: string): value is AssetCatalogEntry['kind'] {\n return ASSET_CATALOG_ENTRY_KINDS.some((kind) => kind === value);\n}\n\ninterface ParsedAssetQuery {\n text: string;\n kind?: AssetCatalogEntry['kind'];\n labels: string[];\n /** A `t:` token whose value is not a known `AssetCatalogEntry['kind']` — the query matches nothing. */\n unknownKind: boolean;\n}\n\nfunction parseAssetQueryTokens(q: string): ParsedAssetQuery {\n const tokens = q.trim().length > 0 ? q.trim().split(/\\s+/) : [];\n const textParts: string[] = [];\n const labels: string[] = [];\n let kind: AssetCatalogEntry['kind'] | undefined;\n let unknownKind = false;\n for (const token of tokens) {\n if (token.startsWith(ASSET_QUERY_TYPE_PREFIX)) {\n const value = token.slice(ASSET_QUERY_TYPE_PREFIX.length);\n if (isAssetCatalogEntryKind(value)) kind = value;\n else unknownKind = true;\n } else if (token.startsWith(ASSET_QUERY_LABEL_PREFIX)) {\n const value = token.slice(ASSET_QUERY_LABEL_PREFIX.length);\n if (value.length > 0) labels.push(value);\n } else {\n textParts.push(token);\n }\n }\n return { text: textParts.join(' '), kind, labels, unknownKind };\n}\n\n/**\n * Parses a `t:<kind>` / `l:<label>` / free-text asset search query. An\n * unrecognized `t:` value is dropped from the returned `kind` (there is no\n * value of `AssetCatalogEntry['kind']` to report) — `matchAssetQuery`, which\n * shares this same tokenizer internally, is the authority that turns it into\n * \"matches nothing\".\n */\nexport function parseAssetQuery(q: string): { text: string; kind?: AssetCatalogEntry['kind']; labels: string[] } {\n const parsed = parseAssetQueryTokens(q);\n return parsed.kind === undefined ? { text: parsed.text, labels: parsed.labels } : { text: parsed.text, kind: parsed.kind, labels: parsed.labels };\n}\n\n/**\n * Matches one catalog entry against a `t:`/`l:`/free-text query. `l:` labels\n * are ANDed against `entry.category` (exact, case-insensitive); free text is\n * an ANDed case-insensitive substring over `name`+`category`. An unrecognized\n * `t:` kind matches nothing.\n */\nexport function matchAssetQuery(entry: AssetCatalogEntry, q: string): boolean {\n const parsed = parseAssetQueryTokens(q);\n if (parsed.unknownKind) return false;\n if (parsed.kind !== undefined && entry.kind !== parsed.kind) return false;\n for (const label of parsed.labels) {\n if (entry.category.toLowerCase() !== label.toLowerCase()) return false;\n }\n if (parsed.text.length > 0) {\n const haystack = `${entry.name} ${entry.category}`.toLowerCase();\n if (!haystack.includes(parsed.text.toLowerCase())) return false;\n }\n return true;\n}\n","/**\n * S-Expression Types\n *\n * Defines the S-Expression type system for guards, effects, and computed values.\n * S-expressions are JSON arrays where the first element is an operator string.\n *\n * @example\n * // Guard: health > 0\n * [\">\", \"@entity.health\", 0]\n *\n * // Effect: set x to x + vx\n * [\"set\", \"@entity.x\", [\"+\", \"@entity.x\", \"@entity.vx\"]]\n *\n * @packageDocumentation\n */\n\nimport { z } from 'zod';\nimport type { RuntimeValue } from './json.js';\n\n// ============================================================================\n// S-Expression Type\n// ============================================================================\n\n/**\n * S-Expression type - recursive structure representing expressions.\n *\n * An S-expression is either:\n * - A literal value (string, number, boolean, null)\n * - An object literal (for payload data, props, etc.)\n * - A binding reference (string starting with @)\n * - A call expression (array with operator as first element)\n */\n/** Object literal branch of an S-expression atom (payload data, props, etc.). */\nexport interface SExprObject {\n [key: string]: SExpr;\n}\nexport type SExprAtom = string | number | boolean | null | SExprObject;\nexport type SExpr = SExprAtom | SExpr[];\n\n/**\n * Expression type - S-expressions only.\n * Used for guards, computed values, and effect expressions.\n *\n * NOTE: Legacy string format is no longer supported.\n * All expressions must be S-expression arrays.\n */\nexport type Expression = SExpr;\n\n// ============================================================================\n// S-Expression Schema (Zod)\n// ============================================================================\n\n/**\n * Recursive schema for s-expr-shaped DATA in literal positions (object\n * values, effect arguments). Unlike `SExprSchema`, arrays may be empty or\n * non-operator-headed — literal data lists (`children: []`, `tiles: [...]`)\n * are valid here; only call positions get the operator-head refine.\n */\nexport const SExprDataSchema: z.ZodType<SExpr> = z.lazy(() =>\n z.union([SExprAtomSchema, z.array(SExprDataSchema)]),\n);\n\n/**\n * Schema for atomic S-expression values (non-array)\n * Includes objects for payload data, props, etc.\n */\nexport const SExprAtomSchema: z.ZodType<SExprAtom> = z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.null(),\n z.record(z.string(), SExprDataSchema), // Objects for payload data\n]);\n\n/**\n * Recursive schema for S-expressions: an atom, or a call — an array whose first element is its\n * string operator. A call's arguments are data (`SExprDataSchema`): an argument array without\n * an operator head is a literal list, as both evaluators read it (an inlined config list in\n * `[\"array/nth\", [{…}, {…}], \"@entity.i\"]`).\n */\nexport const SExprSchema: z.ZodType<SExpr> = z.lazy(() =>\n z.union([\n SExprAtomSchema,\n z\n .array(SExprDataSchema)\n .min(1)\n .refine(\n (arr) => typeof arr[0] === 'string',\n { message: 'S-expression array must have a string operator as first element' }\n ),\n ])\n);\n\n/**\n * Schema for Expression type - S-expressions only.\n * S-expressions are arrays with operator as first element.\n *\n * NOTE: Legacy string format is no longer supported.\n */\nexport const ExpressionSchema: z.ZodType<Expression> = SExprSchema;\n\n/** A list of propositions (`@invariant`, `@ensures`), named so declaration emit does not expand it at every use. */\nexport const SExprListSchema: z.ZodType<SExpr[]> = z.array(SExprSchema);\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\n/**\n * Type guard for S-expression detection.\n * 100% reliable - structural check, no regex or keyword matching.\n *\n * @param value - Value to check\n * @returns true if value is an S-expression (array with string operator)\n */\nexport function isSExpr(value: RuntimeValue): value is SExpr[] {\n return (\n Array.isArray(value) &&\n value.length > 0 &&\n typeof value[0] === 'string'\n );\n}\n\n/**\n * Type guard for S-expression atoms (non-array values).\n * \n * Validates that a value is an S-expression atom (literal value).\n * Includes null, strings, numbers, booleans, and objects. Used to\n * distinguish atomic values from S-expression calls (arrays).\n * \n * @param {RuntimeValue} value - Value to check\n * @returns {boolean} True if value is an S-expression atom, false otherwise\n *\n * @example\n * isSExprAtom('hello'); // returns true\n * isSExprAtom(42); // returns true\n * isSExprAtom(null); // returns true\n * isSExprAtom({ key: 'value' }); // returns true\n * isSExprAtom(['+', 1, 2]); // returns false\n */\nexport function isSExprAtom(value: RuntimeValue): value is SExprAtom {\n if (value === null) return true;\n if (Array.isArray(value)) return false;\n const type = typeof value;\n return type === 'string' || type === 'number' || type === 'boolean' || type === 'object';\n}\n\n/**\n * Checks if a value is a binding reference.\n * \n * Validates that a string is a binding reference (starts with @).\n * Bindings reference runtime values like @entity.health, @payload.amount, @now.\n * Used for identifying bindings in S-expressions and validation.\n * \n * @param {RuntimeValue} value - Value to check\n * @returns {boolean} True if value is a binding reference, false otherwise\n *\n * @example\n * isBinding('@entity.health'); // returns true\n * isBinding('@payload.amount'); // returns true\n * isBinding('not-a-binding'); // returns false\n * isBinding(123); // returns false\n */\nexport function isBinding(value: RuntimeValue): value is string {\n return typeof value === 'string' && value.startsWith('@');\n}\n\n/**\n * Checks if a value is a valid S-expression call (array with operator).\n * \n * Alias for isSExpr() - validates S-expression call structure.\n * Used to distinguish between S-expression calls and atom values.\n * \n * @param {RuntimeValue} value - Value to check\n * @returns {boolean} True if value is a valid S-expression call, false otherwise\n *\n * @example\n * isSExprCall(['+', 1, 2]); // returns true\n * isSExprCall(['set', '@entity.health', 100]); // returns true\n * isSExprCall('not-a-call'); // returns false\n */\nexport function isSExprCall(value: RuntimeValue): value is SExpr[] {\n return isSExpr(value);\n}\n\n// ============================================================================\n// Binding Parsing\n// ============================================================================\n\n/**\n * Parsed binding reference\n */\nexport interface ParsedBinding {\n /** Type of binding: core (@entity, @payload, @state, @now) or entity (@EntityName) */\n type: 'core' | 'entity';\n /** The root binding name (entity, payload, state, now, or EntityName) */\n root: string;\n /** Path segments after the root (e.g., ['health'] for @entity.health) */\n path: string[];\n /** Full original binding string */\n original: string;\n}\n\n/**\n * Core bindings that are always available.\n * Phase 4.5 adds: config, computed, trait (for behavior support).\n * `user` is the authenticated user / agent context (see binding.ts) and is\n * read-only in guards/effects/ticks — atoms reference `@user.id` and\n * `@user.role` for ownership / role-based gating.\n * `callsitePayload` is the call-site-captured event payload emitted by the\n * compiler's inline-trait hoisting; the runtime BindingResolver resolves it\n * at the composing effect.\n * `pages` / `currentTheme` are render-resolved schema sigils (effect-only,\n * see `orbital-rust/crates/orbital-compiler/src/phases/resolve.rs`):\n * substituted from the host orbital's schema (`@pages` → its `NavItem[]`\n * nav array, `@currentTheme` → its `data-theme` key) before codegen — they\n * never survive as live bindings past that substitution pass.\n */\nexport const CORE_BINDINGS = ['entity', 'payload', 'state', 'now', 'config', 'computed', 'trait', 'user', 'callsitePayload', 'pages', 'currentTheme'] as const;\nexport type CoreBinding = (typeof CORE_BINDINGS)[number];\n\n/**\n * Parses a binding reference into its components.\n * \n * Deconstructs a binding string (e.g., '@entity.health') into its constituent\n * parts: type, root, path, and original string. Does NOT use regex - uses\n * structured string operations for reliability and maintainability.\n * \n * @param {string} binding - Binding string starting with @\n * @returns {ParsedBinding | null} Parsed binding object or null if invalid\n * \n * @example\n * parseBinding('@entity.health'); // returns { type: 'core', root: 'entity', path: ['health'], original: '@entity.health' }\n * parseBinding('@User.name'); // returns { type: 'entity', root: 'User', path: ['name'], original: '@User.name' }\n * parseBinding('not-a-binding'); // returns null\n */\nexport function parseBinding(binding: string): ParsedBinding | null {\n if (!binding.startsWith('@')) {\n return null;\n }\n\n // Remove @ prefix\n const withoutPrefix = binding.slice(1);\n\n // Split by dots\n const parts = withoutPrefix.split('.');\n\n if (parts.length === 0 || parts[0] === '') {\n return null;\n }\n\n const root = parts[0];\n const path = parts.slice(1);\n\n // Determine if core binding or entity reference\n const isCore = (CORE_BINDINGS as readonly string[]).includes(root);\n\n return {\n type: isCore ? 'core' : 'entity',\n root,\n path,\n original: binding,\n };\n}\n\n/**\n * Validate a binding reference format.\n *\n * @param binding - Binding string to validate\n * @returns true if valid binding format\n */\nexport function isValidBinding(binding: string): boolean {\n const parsed = parseBinding(binding);\n if (!parsed) return false;\n\n // Core bindings: @entity, @payload, @state, @now (optionally with path)\n // @state and @now don't have paths\n if (parsed.type === 'core') {\n if (parsed.root === 'state' || parsed.root === 'now') {\n return parsed.path.length === 0;\n }\n // @entity and @payload can have paths\n return true;\n }\n\n // Entity bindings: @EntityName.field - must have at least one path segment\n return parsed.path.length > 0;\n}\n\n// ============================================================================\n// S-Expression Utilities\n// ============================================================================\n\n/**\n * Get the operator from an S-expression call.\n *\n * @param expr - S-expression array\n * @returns The operator string or null if not a valid call\n */\nexport function getOperator(expr: SExpr): string | null {\n if (!isSExpr(expr)) return null;\n return expr[0] as string;\n}\n\n/** Where a node sits in its S-expression: argument indices of calls/arrays, keys of object literals. */\nexport type SExprPath = ReadonlyArray<number | string>;\n\n/**\n * One step of a traced evaluation. `enter`/`exit` bracket a node's evaluation\n * (`exit` carries its value or error); `iter` marks a node re-entered (a lambda\n * body per item); `skip` marks an argument the operator never evaluated\n * (short-circuited `and`/`or`, the untaken `if` branch).\n */\nexport interface EvalStep {\n kind: 'enter' | 'exit' | 'iter' | 'skip';\n path: SExprPath;\n value?: RuntimeValue;\n error?: string;\n}\n\nexport type EvalTrace = EvalStep[];\n\n/**\n * Print an S-expression in `.lolo` surface form: calls as `(op args…)`,\n * bindings bare, strings quoted, objects `{ k: v }` (keys sorted), literal arrays `[a b]`.\n * Structural only — a string-headed array is a call, as in {@link isSExpr}.\n */\nexport function formatSExpr(expr: SExpr): string {\n if (expr === null) return 'null';\n if (typeof expr === 'string') return isBinding(expr) ? expr : JSON.stringify(expr);\n if (typeof expr === 'number' || typeof expr === 'boolean') return String(expr);\n if (Array.isArray(expr)) {\n const quoted = quoteBodyOf(expr);\n if (quoted !== undefined) return `(${QUOTE_HEAD} ${formatSExpr(decodeQuoteBody(quoted))})`;\n const qq = quasiquoteOf(expr);\n if (qq !== undefined) return `(${QUASIQUOTE_HEAD} ${formatTemplate(decodeQuoteBody(qq.body), qq.holes)})`;\n const op = getOperator(expr);\n if (op !== null) return `(${[op, ...expr.slice(1).map(formatSExpr)].join(' ')})`;\n return `[${expr.map(formatSExpr).join(' ')}]`;\n }\n const entries = Object.keys(expr).sort().map((k) => `${k}: ${formatSExpr(expr[k])}`);\n return entries.length === 0 ? '{}' : `{ ${entries.join(', ')} }`;\n}\n\n/**\n * Get the arguments from an S-expression call.\n *\n * @param expr - S-expression array\n * @returns Array of arguments (empty if not a valid call)\n */\nexport function getArgs(expr: SExpr): SExpr[] {\n if (!isSExpr(expr)) return [];\n return expr.slice(1);\n}\n\n/**\n * Create an S-expression call.\n *\n * @param operator - The operator string\n * @param args - Arguments to the operator\n * @returns S-expression array\n */\nexport function sexpr(operator: string, ...args: SExpr[]): SExpr[] {\n return [operator, ...args];\n}\n\n/**\n * Walk an S-expression tree and apply a visitor function to each node.\n *\n * @param expr - S-expression to walk\n * @param visitor - Function to call on each node\n */\nexport function walkSExpr(\n expr: SExpr,\n visitor: (node: SExpr, parent: SExpr[] | null, index: number) => void,\n parent: SExpr[] | null = null,\n index: number = 0\n): void {\n visitor(expr, parent, index);\n\n if (isSExpr(expr)) {\n for (let i = 0; i < expr.length; i++) {\n walkSExpr(expr[i], visitor, expr, i);\n }\n }\n}\n\n/**\n * Collect all bindings referenced in an S-expression.\n *\n * @param expr - S-expression to analyze\n * @returns Array of binding strings found\n */\nexport function collectBindings(expr: SExpr): string[] {\n const bindings: string[] = [];\n\n walkSExpr(expr, (node) => {\n if (isBinding(node)) {\n bindings.push(node);\n }\n });\n\n return bindings;\n}\n\n// ============================================================================\n// Type Exports\n// ============================================================================\n\nexport type SExprInput = z.input<typeof SExprSchema>;\nexport type ExpressionInput = z.input<typeof ExpressionSchema>;\n\n// ============================================================================\n// Runtime Evaluation Types\n// ============================================================================\n\n/** Evaluation context for guards and s-expressions. Recursive. */\nexport interface EvalContext {\n [key: string]: string | number | boolean | Date | null | string[] | EvalContext | undefined;\n}\n\n/**\n * A single value carried by an event payload field. The top-level payload\n * is always an object; the VALUES in that object can be primitives, nested\n * objects, or arrays of the same. Arrays are allowed so real-world emits\n * like `{ files: [{ name, size, type }, ...] }` or `{ selected: string[] }`\n * are typed natively instead of forcing consumers to wrap at every call.\n *\n * `Date` is included so `EntityRow` (whose values are `FieldValue`, which\n * includes `Date`) is assignable to a payload field without a cast —\n * emitted entity rows flow through the bus without boundary widening.\n */\nexport type EventPayloadValue =\n | string\n | number\n | boolean\n | Date\n | null\n | undefined\n | EventPayload\n | readonly EventPayloadValue[];\n\n/**\n * Typed event payload. Object-shaped so it's assignable to the bus's\n * `EventPayload` parameter without casts.\n */\nexport interface EventPayload {\n [key: string]: EventPayloadValue;\n}\n\n/**\n * Runtime guard for `EventPayloadValue` — narrows interpreter-produced\n * `unknown` values at typed substrate boundaries (e.g. `TraceContext.emit`).\n */\nexport function isEventPayloadValue(value: RuntimeValue): value is EventPayloadValue {\n if (value === null || value === undefined) return true;\n const kind = typeof value;\n if (kind === 'string' || kind === 'number' || kind === 'boolean') return true;\n if (value instanceof Date) return true;\n if (Array.isArray(value)) return value.every((item: RuntimeValue) => isEventPayloadValue(item));\n if (kind === 'object' && value !== null && typeof value === 'object') {\n return Object.values(value).every((item: RuntimeValue) => isEventPayloadValue(item));\n }\n return false;\n}\n\n/** Zod twin of `EventPayloadValue` — the one runtime validator for a bus-emit payload slot. */\nexport const EventPayloadValueSchema: z.ZodType<EventPayloadValue> = z.lazy(() =>\n z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.date(),\n z.null(),\n z.undefined(),\n EventPayloadSchema,\n z.array(EventPayloadValueSchema),\n ]),\n);\n\n/** Zod twin of `EventPayload` — the wire shape of a bus event's `payload`. */\nexport const EventPayloadSchema: z.ZodType<EventPayload> = z.lazy(() => z.record(z.string(), EventPayloadValueSchema));\n\n/**\n * Allowed leaf value for `LogMeta`. Mirrors `EventPayloadValue` shape so\n * the same row/list data flows through logs without manual flattening,\n * with `Error` added since structured logs carry exception detail.\n */\nexport type LogMetaValue =\n | string\n | number\n | boolean\n | Date\n | null\n | undefined\n | Error\n | LogMeta\n | readonly LogMetaValue[];\n\n/** Structured log/event metadata. Recursive to support nested log data. */\nexport interface LogMeta {\n [key: string]: LogMetaValue;\n}\n\n/**\n * True when `expr` provably evaluates falsy — the twin of orbital-core's\n * `SExpression::is_statically_false`, one table on both paths. Conservative:\n * anything undecidable returns `false` (\"not provably false\"). `resolve`\n * turns a binding (`@config.selfFetch`) into its known literal value, or\n * `undefined` when unknown — the JS path keeps config bindings in guards\n * where Rust inlines them.\n */\nexport function isStaticallyFalse(expr: SExpr, resolve?: (binding: string) => SExprAtom | undefined): boolean {\n const known = (e: SExpr): SExpr => {\n if (typeof e === 'string' && e.startsWith('@') && resolve !== undefined) {\n const value = resolve(e);\n return value === undefined ? e : value;\n }\n return e;\n };\n const isLiteral = (e: SExpr): boolean =>\n e === null || typeof e === 'boolean' || typeof e === 'number' || (typeof e === 'string' && !e.startsWith('@'));\n const value = known(expr);\n if (value === false || value === null) return true;\n if (typeof value === 'number') return value === 0;\n if (typeof value === 'string') return value === '';\n if (Array.isArray(value)) {\n const op = value[0];\n if (typeof op !== 'string') return value.length === 0;\n const args = value.slice(1);\n switch (op) {\n case 'and': return args.some((a) => isStaticallyFalse(a, resolve));\n case 'or': return args.length > 0 && args.every((a) => isStaticallyFalse(a, resolve));\n case 'not': return args.length === 1 && known(args[0]) === true;\n case '==':\n case '!=': {\n if (args.length !== 2) return false;\n const [l, r] = [known(args[0]), known(args[1])];\n if (!isLiteral(l) || !isLiteral(r)) return false;\n return (l === r) === (op === '!=');\n }\n default: return false;\n }\n }\n if (typeof value === 'object') return Object.keys(value).length === 0;\n return false;\n}\n\n\n// ============================================================================\n// quote — an S-expression held as data (G-CROSS-041)\n// ============================================================================\n\n/** The special form that holds an S-expression as data: `(quote x)`. */\nexport const QUOTE_HEAD = 'quote';\n\nfunction canonicalQuoteValue(expr: SExpr): SExpr {\n if (Array.isArray(expr)) return expr.map(canonicalQuoteValue);\n if (expr !== null && typeof expr === 'object') {\n const out: SExprObject = {};\n for (const key of Object.keys(expr).sort()) out[key] = canonicalQuoteValue(expr[key]);\n return out;\n }\n return expr;\n}\n\n/**\n * The IR body of `(quote x)`: canonical JSON of `x` (object keys sorted) with\n * every `@` written as the JSON escape `@`. The body therefore carries no\n * raw `@`, so no binding interpolation, scan or rewrite can reach inside it;\n * any JSON parser restores the original. orbital-core's\n * `schema::quote::encode_quote_body` produces the same bytes.\n */\nexport function encodeQuoteBody(expr: SExpr): string {\n return JSON.stringify(canonicalQuoteValue(expr)).replace(/@/g, '\\\\u0040');\n}\n\n/** Decode a `(quote x)` body back to `x`. */\nexport function decodeQuoteBody(body: string): SExpr {\n const value: SExpr = JSON.parse(body);\n return value;\n}\n\n/** The IR call `[\"quote\", <body>]` for `expr`. */\nexport function quoteExpr(expr: SExpr): [typeof QUOTE_HEAD, string] {\n return [QUOTE_HEAD, encodeQuoteBody(expr)];\n}\n\n/**\n * The data a quoted value stands for: `decodeQuoteBody` of the body when\n * `expr` is a `(quote x)` call, else `expr` unchanged. One level per call —\n * binding path resolution applies it per step, so `(quote …)` nested inside\n * the decoded data decodes there when the path reaches it.\n */\nexport function decodeQuotedValue(expr: SExpr): SExpr;\nexport function decodeQuotedValue(expr: RuntimeValue): RuntimeValue;\nexport function decodeQuotedValue(expr: RuntimeValue): RuntimeValue {\n const body = quoteBodyOf(expr);\n return body === undefined ? expr : decodeQuoteBody(body);\n}\n\n/** The encoded body when `expr` is a `(quote x)` call, else undefined. */\nexport function quoteBodyOf(expr: RuntimeValue): string | undefined {\n return Array.isArray(expr) && expr.length === 2 && expr[0] === QUOTE_HEAD && typeof expr[1] === 'string'\n ? expr[1]\n : undefined;\n}\n\n// ============================================================================\n// quasiquote — a quoted template with live `(unquote e)` holes\n// ============================================================================\n\n/** A quoted template: `(quasiquote x)`. */\nexport const QUASIQUOTE_HEAD = 'quasiquote';\n/** A live hole inside a quasiquote template: `(unquote e)`. */\nexport const UNQUOTE_HEAD = 'unquote';\n\nfunction isHeadedCall(expr: SExpr, head: string): expr is SExpr[] {\n return Array.isArray(expr) && expr.length > 0 && expr[0] === head;\n}\n\nfunction containsHead(expr: SExpr, head: string): boolean {\n if (isHeadedCall(expr, head)) return true;\n if (Array.isArray(expr)) return expr.some((e) => containsHead(e, head));\n if (expr !== null && typeof expr === 'object') return Object.values(expr).some((e) => containsHead(e, head));\n return false;\n}\n\nfunction extractHoles(expr: SExpr, holes: SExpr[]): SExpr {\n if (isHeadedCall(expr, QUASIQUOTE_HEAD)) throw new Error('quasiquote: nested quasiquote is not supported');\n if (isHeadedCall(expr, UNQUOTE_HEAD)) {\n if (expr.length !== 2) throw new Error('quasiquote: (unquote e) takes exactly one expression');\n if (containsHead(expr[1], UNQUOTE_HEAD)) throw new Error('quasiquote: unquote inside an unquote');\n holes.push(expr[1]);\n return [UNQUOTE_HEAD, holes.length - 1];\n }\n if (Array.isArray(expr)) return expr.map((e) => extractHoles(e, holes));\n if (expr !== null && typeof expr === 'object') {\n // Canonical key order, so hole numbering matches the body bytes on every path.\n const out: SExprObject = {};\n for (const k of Object.keys(expr).sort()) out[k] = extractHoles(expr[k], holes);\n return out;\n }\n return expr;\n}\n\n/**\n * The IR call `[\"quasiquote\", <body>, hole0, hole1, …]` for `template`. The\n * body is a quote body in which each `(unquote e)` became the marker\n * `[\"unquote\", i]`; hole `i` is `e`, left live so bindings resolve in it.\n * orbital-core's `schema::quote::quasiquote_expr` produces the same IR.\n */\nexport function quasiquoteExpr(template: SExpr): [typeof QUASIQUOTE_HEAD, string, ...SExpr[]] {\n const holes: SExpr[] = [];\n const body = encodeQuoteBody(extractHoles(template, holes));\n return [QUASIQUOTE_HEAD, body, ...holes];\n}\n\n/** The body and holes when `expr` is a `(quasiquote x)` call, else undefined. */\nexport function quasiquoteOf(expr: SExpr): { body: string; holes: SExpr[] } | undefined {\n if (!Array.isArray(expr) || expr.length < 2 || expr[0] !== QUASIQUOTE_HEAD || typeof expr[1] !== 'string') {\n return undefined;\n }\n return { body: expr[1], holes: expr.slice(2) };\n}\n\nfunction countMarkers(expr: SExpr): number {\n if (isHeadedCall(expr, UNQUOTE_HEAD) && expr.length === 2 && typeof expr[1] === 'number') return 1;\n if (Array.isArray(expr)) return expr.reduce<number>((n, e) => n + countMarkers(e), 0);\n if (expr !== null && typeof expr === 'object') return Object.values(expr).reduce<number>((n, e) => n + countMarkers(e), 0);\n return 0;\n}\n\nfunction fillMarkers(expr: SExpr, values: readonly SExpr[]): SExpr {\n if (isHeadedCall(expr, UNQUOTE_HEAD) && expr.length === 2 && typeof expr[1] === 'number') return values[expr[1]];\n if (Array.isArray(expr)) return expr.map((e) => fillMarkers(e, values));\n if (expr !== null && typeof expr === 'object') {\n const out: SExprObject = {};\n for (const [k, v] of Object.entries(expr)) out[k] = fillMarkers(v, values);\n return out;\n }\n return expr;\n}\n\n/**\n * A hole's evaluated value as program data: JSON scalars, arrays and plain\n * objects pass; anything a program cannot hold (a function, a Date, …) throws.\n * Both paths guard `(quasiquote …)` holes with this — orbital-core's\n * `QuasiquoteOp` refuses a lambda the same way.\n */\nexport function toProgramData(value: RuntimeValue): SExpr {\n if (value === null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n return value;\n }\n if (Array.isArray(value)) return value.map((v: RuntimeValue) => toProgramData(v));\n if (typeof value === 'object' && !(value instanceof Date) && Object.getPrototypeOf(value) === Object.prototype) {\n const out: SExprObject = {};\n for (const [k, v] of Object.entries(value)) out[k] = toProgramData(v);\n return out;\n }\n throw new Error(`quasiquote: a hole evaluated to a ${typeof value} value, which cannot be held as program data`);\n}\n\n/** Decode a quasiquote body and splice `values` (the evaluated holes, in order) into it. */\nexport function instantiateQuasiquote(body: string, values: readonly SExpr[]): SExpr {\n const template = decodeQuoteBody(body);\n const holes = countMarkers(template);\n if (holes !== values.length) {\n throw new Error(`quasiquote: template has ${holes} hole(s), got ${values.length} value(s)`);\n }\n return fillMarkers(template, values);\n}\n\nfunction formatTemplate(expr: SExpr, holes: readonly SExpr[]): string {\n if (isHeadedCall(expr, UNQUOTE_HEAD) && expr.length === 2 && typeof expr[1] === 'number') {\n return `(${UNQUOTE_HEAD} ${formatSExpr(holes[expr[1]])})`;\n }\n if (Array.isArray(expr)) {\n const op = getOperator(expr);\n if (op !== null) return `(${[op, ...expr.slice(1).map((e) => formatTemplate(e, holes))].join(' ')})`;\n return `[${expr.map((e) => formatTemplate(e, holes)).join(' ')}]`;\n }\n if (expr !== null && typeof expr === 'object') {\n const entries = Object.keys(expr).sort().map((k) => `${k}: ${formatTemplate(expr[k], holes)}`);\n return entries.length === 0 ? '{}' : `{ ${entries.join(', ')} }`;\n }\n return formatSExpr(expr);\n}\n","/**\n * Entity Types for Orbital Units\n *\n * Defines the OrbitalEntity type - the nucleus of an Orbital Unit.\n *\n * @packageDocumentation\n */\n\nimport { z } from 'zod';\nimport { EntityIdSchema } from './identity.js';\nimport type { EntityId } from './identity.js';\nimport { EntityFieldSchema, type EntityField, type FileValue } from './field.js';\nimport { SemanticAssetRefSchema, type SemanticAssetRef } from './asset.js';\nimport { JsonValueSchema, type RuntimeValue } from './json.js';\nimport { SExprListSchema, SExprSchema, type SExpr } from './expression.js';\n\n// ============================================================================\n// Entity Persistence\n// ============================================================================\n\n/**\n * Entity persistence types.\n *\n * - persistent: Stored in database (has collection)\n * - runtime: Exists only at runtime (not persisted)\n */\nexport type EntityPersistence = 'persistent' | 'runtime';\n\nexport const EntityPersistenceSchema = z.enum([\n 'persistent',\n 'runtime',\n]);\n\n// ============================================================================\n// Orbital Entity\n// ============================================================================\n\n/**\n * OrbitalEntity - the nucleus of an Orbital Unit.\n *\n * This is a simplified entity definition optimized for orbital composition.\n * Collection names are derived automatically from persistence type if not provided.\n */\nexport type OrbitalEntity = {\n /** V4 dual-carry id sibling of `name` — optional until the Phase-7 flip. */\n id?: EntityId;\n\n /** Entity name (PascalCase, e.g., \"Task\", \"User\") */\n name: string;\n\n /** Entity persistence type (defaults to 'persistent' if not specified) */\n persistence?: EntityPersistence;\n\n /** Whether this entity's state is shared across all bound traits (vs per-trait copy). Orthogonal to persistence. */\n shared?: boolean;\n\n /**\n * Whether this entity types the ambient `@user` viewer. Orthogonal to both\n * `persistence` and `shared`: `[persistent: people, identity]` is an\n * app-owned user directory, `[runtime, identity]` the provider-supplied\n * current viewer. At most one per composed program.\n */\n identity?: boolean;\n\n /**\n * `[persistent: x, browser]` — the rows live in the browser (IndexedDB), so\n * `fetch`/`persist` on this entity run client-side on both paths. Orthogonal\n * like `shared`; meaningful only on a persistent entity.\n */\n browser?: boolean;\n\n /**\n * `[store: Driver]` — the store-driver orbital that answers this entity's row\n * asks (EXEC-STORE-4); wins over the app's `store`.\n */\n store?: string;\n\n /**\n * `@read` — a per-row predicate (`@entity` = candidate row, `@user` =\n * viewer) ANDed with any call-site `filter:`. The un-bypassable twin of\n * `filter:`, enforced once for every trait that fetches this entity.\n */\n read_policy?: SExpr;\n\n /** `@create` — `@entity` binds the incoming data about to become a row. */\n create_policy?: SExpr;\n\n /** `@update` — `@entity` binds the existing row before mutation. */\n update_policy?: SExpr;\n\n /** `@delete` — same binding shape as `@update`. */\n delete_policy?: SExpr;\n\n /**\n * `@<op> none \"<reason>\"` — a directive's omission, DECLARED.\n *\n * Runtime behaviour is identical to leaving the directive out (an absent\n * policy is allow-all). It records that the author concluded no per-row\n * predicate can express the rule — usually because visibility depends on a\n * DIFFERENT entity, which a per-row predicate cannot join across. Without\n * it a lint must flag considered and forgotten omissions alike, and a lint\n * that flags correct code is one people learn to ignore.\n */\n access_waivers?: {\n read?: string;\n create?: string;\n update?: string;\n delete?: string;\n };\n\n /** `@invariant <expr>`: every stored row satisfies each, proved by `orb validate` over the program's writes. No runtime effect. */\n invariants?: SExpr[];\n\n /** Collection name (auto-derived if not provided for persistent entities) */\n collection?: string;\n\n /** Entity fields */\n fields: EntityField[];\n\n /** Pre-authored instances (seed data or static reference data) */\n instances?: EntityRow[];\n\n /**\n * A browser-stored entity's first rows per locale (`instances ar [ … ]`),\n * keyed by a declared locale; a locale with no block takes `instances`.\n */\n localeInstances?: Record<string, EntityRow[]>;\n\n /** Auto-add createdAt/updatedAt timestamps */\n timestamps?: boolean;\n\n /** Soft delete support */\n softDelete?: boolean;\n\n /** Human-readable description */\n description?: string;\n\n /** Visual prompt for AI generation */\n visual_prompt?: string;\n\n /** Semantic asset reference for visual representation (games) */\n assetRef?: SemanticAssetRef;\n};\n\nexport const OrbitalEntitySchema = z.object({\n name: z.string().min(1, 'Entity name is required'),\n // V4 arena id (`EntityDefinition.id`); declared so the strip-mode zod gate\n // carries an imported entity's id through instead of erasing it.\n id: EntityIdSchema.optional(),\n persistence: EntityPersistenceSchema.default('persistent'),\n shared: z.boolean().optional(),\n // Must stay in step with the Rust serde field (`EntityDefinition.identity`,\n // orbital-core/src/schema/types.rs). `z.object()` STRIPS unknown keys rather\n // than rejecting them, so a Rust-only field works on the compiled path and\n // silently vanishes on the interpreter path.\n identity: z.boolean().optional(),\n // Rust twin: `EntityDefinition.browser`.\n browser: z.boolean().optional(),\n // Rust twin: `EntityDefinition.store`.\n store: z.string().min(1).optional(),\n // Same \"must stay in step with Rust serde\" hazard as `identity` above —\n // these four mirror `EntityDefinition.{read,create,update,delete}_policy`.\n // Rust has no `rename_all` on this struct, so the wire key IS snake_case\n // (unlike this file's other camelCase fields, which are Rust-side-absent\n // and so never hit this cross-language constraint — see `visual_prompt`\n // just below for the existing precedent).\n read_policy: SExprSchema.optional(),\n create_policy: SExprSchema.optional(),\n update_policy: SExprSchema.optional(),\n delete_policy: SExprSchema.optional(),\n // Snake_case for the same cross-language reason as the four policies above.\n access_waivers: z\n .object({\n read: z.string().optional(),\n create: z.string().optional(),\n update: z.string().optional(),\n delete: z.string().optional(),\n })\n .optional(),\n invariants: SExprListSchema.optional(),\n collection: z.string().optional(),\n fields: z.array(EntityFieldSchema),\n instances: z.array(z.record(z.string(), JsonValueSchema)).optional(),\n localeInstances: z.record(z.string(), z.array(z.record(z.string(), JsonValueSchema))).optional(),\n timestamps: z.boolean().optional(),\n softDelete: z.boolean().optional(),\n description: z.string().optional(),\n visual_prompt: z.string().optional(),\n assetRef: SemanticAssetRefSchema.optional(),\n});\n\nexport type OrbitalEntityInput = z.input<typeof OrbitalEntitySchema>;\n\n// ============================================================================\n// Type Aliases (for cleaner imports)\n// ============================================================================\n\n/** Alias for OrbitalEntity - preferred name */\nexport type Entity = OrbitalEntity;\n\n/** Alias for OrbitalEntitySchema - preferred name */\nexport const EntitySchema = OrbitalEntitySchema;\n\n/** The rows an entity starts with for a viewer's locale: its locale block, else `instances`. */\nexport function instancesForLocale(entity: Pick<OrbitalEntity, 'instances' | 'localeInstances'>, locale: string | undefined): EntityRow[] {\n const localized = locale !== undefined ? entity.localeInstances?.[locale] : undefined;\n return localized ?? entity.instances ?? [];\n}\n\n// ============================================================================\n// Utility Functions\n// ============================================================================\n\n/**\n * Derives the collection name for a persistent entity.\n * \n * Generates the database collection name by converting the entity name\n * to lowercase and adding an 's' suffix (simple pluralization).\n * Returns undefined for non-persistent (runtime) entities.\n * \n * @param {OrbitalEntity} entity - Entity to derive collection name for\n * @returns {string | undefined} Collection name or undefined for non-persistent entities\n * \n * @example\n * deriveCollection({ name: 'User', persistence: 'persistent' }); // returns 'users'\n * deriveCollection({ name: 'Task', persistence: 'runtime' }); // returns undefined\n */\nexport function deriveCollection(entity: OrbitalEntity): string | undefined {\n if (entity.persistence !== 'persistent') {\n return undefined;\n }\n // Lowercase + 's' suffix (simple pluralization)\n return entity.name.toLowerCase() + 's';\n}\n\n/**\n * Checks if an entity is runtime-only (not persisted).\n * \n * Type guard to determine if an entity exists only at runtime\n * and is not stored in the database.\n * \n * @param {OrbitalEntity} entity - Entity to check\n * @returns {boolean} True if entity is runtime-only, false otherwise\n * \n * @example\n * isRuntimeEntity({ persistence: 'runtime' }); // returns true\n * isRuntimeEntity({ persistence: 'persistent' }); // returns false\n */\nexport function isRuntimeEntity(entity: OrbitalEntity): boolean {\n return entity.persistence === 'runtime';\n}\n\n/**\n * Whether an entity's rows live in the client: `[runtime]` (in memory) or\n * `[persistent: x, browser]` (the browser's IndexedDB). Data effects on such an\n * entity run in the client. Twin of Rust `EntityDefinition::is_client_resident`.\n */\nexport function isClientResident(entity: Pick<OrbitalEntity, 'persistence' | 'browser'>): boolean {\n return entity.persistence === 'runtime' || entity.browser === true;\n}\n\n/**\n * Whether an entity's ROWS live in the browser (`[persistent: x, browser]`), so\n * `fetch`/`persist` on it run client-side. A `[runtime]` entity's rows stay in\n * the server's per-session store. Twin of Rust `Residence` (`effects/runs_on.rs`).\n */\nexport function storesRowsInBrowser(entity: Pick<OrbitalEntity, 'browser'>): boolean {\n return entity.browser === true;\n}\n\n/**\n * Checks whether an entity's persistence mode allows `persistence` /\n * `collection` overrides at the factory call site.\n *\n * Only `persistent` entities (explicit or default) support these overrides.\n * Runtime entities are fixed; callers must not expose `persistence` or\n * `collection` params for them.\n *\n * @param persistence - The entity persistence mode (undefined = default persistent)\n * @returns True when overrides are allowed, false otherwise\n *\n * @example\n * persistenceModeAllowsOverrides('persistent'); // returns true\n * persistenceModeAllowsOverrides('runtime'); // returns false\n * persistenceModeAllowsOverrides(undefined); // returns true (default persistent)\n */\nexport function persistenceModeAllowsOverrides(\n persistence: EntityPersistence | undefined,\n dataBearing = false,\n): boolean {\n // A runtime record a data atom fetches or persists may be saved; other runtime state may not.\n return persistence === 'persistent' || persistence === undefined || (persistence === 'runtime' && dataBearing);\n}\n\n// ============================================================================\n// Entity Instance Data (Runtime)\n// ============================================================================\n\n/**\n * A single field value at runtime.\n * Union of all possible types from FieldType: string, number, boolean, date, array, nested.\n * The nested-record branch's index signature tolerates `undefined` so that\n * TypeScript optional properties (`x?: string`, carrying `string | undefined`)\n * on EntityRow extenders typecheck without ceremony. At JSON serialization\n * time `undefined` is equivalent to \"key absent\" and never appears on the\n * wire; the inclusion here is a pure type-surface accommodation.\n */\nexport type FieldValue = string | number | boolean | Date | null | string[] | FieldValue[] | { [key: string]: FieldValue | undefined };\n\n/** Zod twin of `FieldValue` — the one runtime validator for a stored field slot. */\nexport const FieldValueSchema: z.ZodType<FieldValue> = z.lazy(() =>\n z.union([z.string(), z.number(), z.boolean(), z.date(), z.null(), z.array(FieldValueSchema), z.record(z.string(), FieldValueSchema.optional())]),\n);\n\n/**\n * What a FORM CONTROL puts on the event bus — the closed set of shapes an\n * Input / Select / Checkbox / Date / multi-select / file field actually\n * produces.\n *\n * A TRANSPORT type, deliberately distinct from `FieldValue`, and the separation\n * is the point. `FieldValue` conflated two jobs: what a control emits, and what\n * an entity field holds. The second never needed it — an entity field always\n * has one declared type (`email : email!`, `age : number`) — so the openness\n * only travelled outward, degrading every generated `.lolo` payload to a\n * shapeless `object`.\n *\n * NOT recursive, and the variants are enumerated from what is actually emitted\n * rather than guessed. `FileValue` is here because the compiler put it here: a\n * scalar-only draft failed against the file field, which hands\n * `Form.handleChange` a `{ name, url, mimeType, sizeBytes }` record.\n *\n * The rule is Aeson's — enumerate the shapes that occur, keep the open type at\n * the boundary, convert on the way in. In `.lolo` that boundary is the\n * `(set @entity.X ?value)` of the receiving transition, where the entity\n * field's own declared type does the checking.\n */\nexport type ControlValue = string | number | boolean | null | string[] | FileValue;\n\n/**\n * Runtime guard for `FieldValue` — narrows interpreter-produced `unknown`\n * values at typed substrate boundaries (e.g. sampled values).\n */\nexport function isFieldValue(value: RuntimeValue): value is FieldValue {\n if (value === null) return true;\n const kind = typeof value;\n if (kind === 'string' || kind === 'number' || kind === 'boolean') return true;\n if (value instanceof Date) return true;\n if (Array.isArray(value)) return value.every((item: RuntimeValue) => isFieldValue(item));\n if (kind === 'object' && value !== null && typeof value === 'object') {\n return Object.values(value).every((item: RuntimeValue) => item === undefined || isFieldValue(item));\n }\n return false;\n}\n\n/**\n * One instance of an entity with actual field values.\n * The shape is determined by the Entity definition at schema time.\n *\n * @example\n * // Entity defines: Patient { fullName: string, age: number, active: boolean }\n * // EntityRow is: { id: \"p1\", fullName: \"Sarah\", age: 34, active: true }\n */\nexport type EntityRow = { id?: string } & Record<string, FieldValue | undefined>;\n\n/** Zod twin of `EntityRow` — the one runtime validator for an `@entity` wire row. */\nexport const EntityRowSchema: z.ZodType<EntityRow> = z\n .object({ id: z.string().optional() })\n .catchall(FieldValueSchema.optional());\n\n/**\n * A field-TYPED `EntityRow` — the SINGLE entity type, refined with a concrete\n * field SHAPE `S`. Non-optional members of `S` are REQUIRED, each with its real\n * type; the result stays `& EntityRow`, so the index signature is intact and\n * every other field is still field-open — any domain entity that provides those\n * fields satisfies it.\n *\n * One declaration, two jobs: (1) TypeScript enforces the bound entity has the\n * fields WITH their types (a behavior binding a thinner/mistyped entity fails to\n * typecheck); and (2) pattern-sync reads the same type and writes the entity\n * prop's field shape (`properties` + `requiredFields`) onto the registry, so\n * lolo-ui emits a COMPLETE `entity { … }` (every field, typed + demo-seeded) and\n * the `ORB_X_ENTITY_PROP_CONTRACT` validator rejects an incompatible bind at\n * `orbital validate`. (A raw `EntityRow & { rating: number }` intersection is\n * equivalent for one-off shapes.)\n *\n * @example\n * // HeroOrganism renders entity.title / entity.subtitle:\n * entity?: EntityWith<{ title: string; subtitle?: string }>;\n * // entity.title → string (required)\n * // entity.subtitle → string | undefined (optional)\n * // entity.other → FieldValue | undefined (still field-open)\n */\n// `S extends object` (not `Record<string, FieldValue>`) so a plain `interface`\n// row shape satisfies it — interfaces lack the implicit index signature `Record`\n// requires. FieldValue-compatibility is still enforced structurally: `& EntityRow`\n// intersects every field with the `FieldValue | undefined` index signature, so a\n// non-FieldValue field (e.g. a React `LucideIcon`) collapses to `never` at use.\nexport type EntityWith<S extends object> = EntityRow & S;\n\n/**\n * Collection of entity instances keyed by entity name.\n * Used by OrbPreview mockData, OrbitalServerRuntime state, data grids, etc.\n *\n * @example\n * const data: EntityData = {\n * Patient: [{ id: \"1\", fullName: \"Sarah\", age: 34 }],\n * QueueEntry: [{ id: \"1\", patientName: \"Sarah\", waitMinutes: 12 }],\n * };\n */\nexport type EntityData = Record<string, EntityRow[]>;\n","/**\n * Effect Types (Self-Contained)\n *\n * Defines effect types for trait transitions and ticks.\n * Effects are S-expressions (arrays) that describe actions to perform.\n *\n * @packageDocumentation\n */\n\nimport { z } from 'zod';\nimport { type SExpr, type Expression, type EventPayload, SExprDataSchema } from './expression.js';\nimport type { RuntimeValue, JsonValue, JsonObject } from './json.js';\nimport { type ServiceParams } from './service.js';\nimport { type EntityRow, type FieldValue } from './entity.js';\n\n// ============================================================================\n// UI Slots\n// ============================================================================\n\n/**\n * Known UI slots where content can be rendered\n */\nexport const UI_SLOTS = [\n // App slots\n 'main',\n 'sidebar',\n 'dock', // Right inline panel that pushes main (narrow screens: a drawer)\n 'modal',\n 'drawer',\n 'overlay',\n 'center',\n 'toast',\n 'floating',\n 'system', // For invisible system components (InputListener, CollisionDetector)\n 'content',\n 'screen',\n // Game HUD slots\n 'hud',\n 'hud-top',\n 'hud-bottom',\n 'hud.health',\n 'hud.score',\n 'hud.inventory',\n 'hud.stamina',\n // Game overlay slots\n 'overlay.inventory',\n 'overlay.dialogue',\n 'overlay.menu',\n 'overlay.pause',\n] as const;\n\nexport type UISlot = (typeof UI_SLOTS)[number];\n\n/** The slots a renderer mounts as `#slot-{name}`: every slot except the HUD group key, the `screen` alias and dotted sub-slots. */\nexport const RENDERED_SLOTS: readonly UISlot[] = UI_SLOTS.filter(\n (slot) => !slot.includes('.') && slot !== 'hud' && slot !== 'screen',\n);\n\nexport const UISlotSchema = z.enum(UI_SLOTS);\n\n// ============================================================================\n// Pattern Config (for render-ui effects)\n// ============================================================================\n\n// Import pattern types for local use and re-export for consumers\nimport type {\n PatternType,\n PatternConfig,\n PatternProps,\n PatternPropsMap,\n AnyPatternConfig,\n} from '../patterns/index.js';\n\n/**\n * Type-safe pattern configuration for render-ui effects.\n *\n * Re-exported from @almadar/patterns. Generated from patterns-registry.json.\n *\n * @example\n * // Type-safe with specific pattern type\n * const config: PatternConfig<'table-view'> = {\n * patternType: 'table-view',\n * columns: [{ key: 'name', header: 'Name' }], // ✅ Required prop\n * entity: 'User',\n * };\n *\n * // Error: Property 'columns' is missing (required prop)\n * const bad: PatternConfig<'table-view'> = { patternType: 'table-view' };\n *\n * // Error: 'fake-pattern' is not assignable to PatternType\n * const invalid: PatternConfig = { patternType: 'fake-pattern' };\n */\nexport type {\n PatternType,\n PatternConfig,\n PatternProps,\n PatternPropsMap,\n AnyPatternConfig,\n};\n\n// ============================================================================\n// Service Config (for call-service effects)\n// ============================================================================\n\n/**\n * Configuration extracted from call-service effects\n */\nexport type CallServiceConfig = {\n service: string;\n action: string;\n endpoint?: string;\n method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n params?: ServiceParams;\n onSuccess?: string;\n onError?: string;\n};\n\n// ============================================================================\n// Typed Effect Tuples\n// ============================================================================\n\n/**\n * A binding reference to a render tree stored elsewhere — a trait `config`\n * knob or a payload field — e.g. `\"@config.bodyContent\"`. Resolved to a pattern\n * node at render time. This is how an atom renders a tree that contains data\n * bindings (`entity: \"@payload.data\"`, `fields: \"@config.fields\"`): the tree is\n * a permissive `TraitConfigValue` stored in `config` (a binding string is not a\n * valid `AnyPatternConfig` prop value), and the render-ui effect points at it.\n * Worked example: `std-browse`'s loaded transition is `['render-ui', 'main',\n * '@config.bodyContent']`. The Rust validator accepts this form; this variant\n * lets the TS effect type express it.\n */\nexport type RenderBinding = `@${string}`;\n\n/**\n * A binding reference resolving to a {@link UISlot} at inline time — a trait\n * `config` knob holding the slot name, e.g. `\"@config.reviewSlot\"`. Mirrors\n * {@link RenderBinding} for the SLOT position: the compiler's inline phase\n * substitutes the config value before anything renders, and the Rust\n * validator accepts the pre-substitution form (worked example:\n * `std-approval-gate`'s review queue renders into `@config.reviewSlot`).\n * This variant lets the TS effect type express the template-layer form.\n */\nexport type SlotBinding = `@config.${string}`;\n\n/**\n * Template-layer pattern node: a render tree whose discriminant and/or props\n * are still bindings (`type: '@config.viewPattern'`, `title: '@config.title'`)\n * or loose nested descriptors the compiler's inline phase resolves. The\n * resolved layer is {@link AnyPatternConfig}; this variant lets generated\n * behavior descriptors (std-ts) carry the pre-substitution form the Rust\n * validator accepts (worked example: `std-graphs` renders\n * `{ type: '@config.viewPattern', chartType: '@config.chartType', … }`).\n */\nexport type TemplatePatternConfig = { type: PatternType | RenderBinding } & Record<string, JsonValue>;\n\n/**\n * Render UI effect - displays a pattern in a UI slot.\n * @example ['render-ui', 'main', { patternType: 'table-view', columns: [{ key: 'name', header: 'Name' }] }]\n * @example ['render-ui', 'main', '@config.bodyContent'] // a {@link RenderBinding} target\n * @example ['render-ui', '@config.reviewSlot', { patternType: 'table-view' }] // a {@link SlotBinding} slot\n */\nexport type RenderUIEffect =\n | ['render-ui', UISlot | SlotBinding, AnyPatternConfig]\n | ['render-ui', UISlot | SlotBinding, TemplatePatternConfig]\n | ['render-ui', UISlot | SlotBinding, RenderBinding]\n | ['render-ui', UISlot | SlotBinding, null];\n\n/**\n * Lambda expression for per-item rendering in data-grid/data-list.\n * The compiler generates: {(paramName: Record<string, unknown>) => (<>JSX</>)}\n * where @{paramName}.field bindings reference the current iteration item.\n *\n * @example [\"fn\", \"item\", { \"type\": \"stack\", \"children\": [{ \"type\": \"typography\", \"content\": \"@item.title\" }] }]\n */\nexport type RenderItemLambda = ['fn', string, AnyPatternConfig];\n\n/**\n * Dynamic-collection children entry: renders one child per item of a collection\n * expression, authored inline in a `children:` position and kept verbatim as IR\n * (no new node kind). The collection expression is an {@link SExpr} evaluated at\n * render time; the {@link RenderItemLambda} body is instantiated per item with\n * the lambda param bound as an `@item`-scope binding. Both execution paths lower\n * onto the one lambda + `@item` + splice machinery.\n *\n * @example [\"array/map\", \"@entity.tasks\", [\"fn\", \"item\", { \"type\": \"typography\", \"content\": \"@item.title\" }]]\n */\nexport type RenderChildrenMap = ['array/map', SExpr, RenderItemLambda];\n\n/**\n * Trailing options object on navigate effects. `crumb` labels the navigation\n * stack entry the client pushes for the target page (e.g. the record title a\n * list router has in `?row` at push time); without it the entry falls back to\n * the target page's declared/derived label.\n */\nexport type NavigateOptions = { crumb?: string | SExpr };\n\n/**\n * Navigate effect - navigates to an internal page path or an external URL.\n * @example ['navigate', '/tasks'] or ['navigate', '/tasks/:id', { id: '123' }]\n * @example ['navigate', 'https://example.com']\n * @example ['navigate', '/contracts/42', { id: '42' }, { crumb: '@payload.row.title' }]\n */\nexport type NavigateEffect =\n | ['navigate', string | SExpr]\n | ['navigate', string | SExpr, Record<string, string | SExpr>]\n | ['navigate', string | SExpr, Record<string, string | SExpr>, NavigateOptions];\n\n/**\n * Navigate-back effect - pops the current entry off the orbital-scoped\n * navigation stack and navigates to the previous one. The stack is\n * client-session state (cold loads are seeded from declared page-path\n * prefixes), so an ancestor always exists on nested paths; the validator\n * rejects `navigate-back` reachable only from pages with no path ancestor.\n * @example ['navigate-back']\n */\nexport type NavigateBackEffect = ['navigate-back'];\n\n/**\n * Emit effect - emits an event, optionally with payload.\n * @example ['emit', 'SAVE'] or ['emit', 'PLAYER_DIED', { playerId: '@entity.id' }]\n * @example ['emit', 'FILTER_CHANGED', '@entity.filters']\n */\nexport type EmitEffect = ['emit', string] | ['emit', string, EventPayload | string];\n\n/**\n * `emit:` config block attached to async / reactive data operators.\n *\n * Each key names an event the runtime should fire on the bus when the\n * effect reaches the corresponding lifecycle point. The set of keys an\n * operator actually supports is enforced by the compiler validator:\n *\n * | Operator | Supported keys |\n * |------------------|---------------------------|\n * | `fetch` | `success`, `failure` |\n * | `persist` | `success`, `failure` |\n * | `call-service` | `success`, `failure`, `cancelled` |\n * | `set` | `success` |\n * | `ref` | `on_change`, `failure` |\n * | `fetch-stream` | `on_message`, `success`, `failure` |\n *\n * Payload convention:\n * - `success` / `on_change` → the effect's result (fetched entity, new value)\n * - `failure` → `{ error: string, code?: string }`\n * - `on_message` → the incoming chunk (`fetch-stream`)\n *\n * See `docs/Almadar_Std_Gaps.md` §3.1 for the close-the-circuit design.\n */\nexport interface EmitConfig {\n /** Fires after a one-shot async effect resolves successfully. */\n success?: string;\n /** Fires when the effect throws; payload is `{ error: string }`. */\n failure?: string;\n /** `call-service` only: fires when `cancel-call` aborts the call; payload is `{ key }`. */\n cancelled?: string;\n /** Reactive-subscription event (per update for `ref`). */\n on_change?: string;\n /** Per-chunk fire for `fetch-stream`. */\n on_message?: string;\n}\n\n/**\n * Set effect - sets a binding to a value.\n *\n * Two forms are supported to match the runtime's `set` handler signature\n * `(targetId, field, value)`:\n *\n * - 3-element binding form (legacy / std behaviors): ['set', '@entity.field', value]\n * - 4-element target form (canonical runtime): ['set', entityId, fieldName, value]\n *\n * The 4-element form is what `OrbitalServerRuntime`'s set handler\n * dispatches directly (`update(entityType, targetId, { field: value })`).\n * Prefer the 4-element form when authoring schemas in TypeScript that\n * load directly into the runtime.\n *\n * @example ['set', '@entity.health', 100] // 3-element\n * @example ['set', '@entity.id', 'health', 100] // 4-element\n * @example ['set', '@entity.id', 'count', ['+', '@entity.count', 1]]\n */\nexport type SetEffect =\n | ['set', string, SExpr]\n | ['set', string, string, SExpr];\n\n/**\n * Trailing config object on persist effects. When present, it carries the\n * `emit` map specifying which events to fire on persist success/failure.\n * Mirrors what the runtime's `EffectExecutor` reads at the 5th tuple\n * position. See `(persist create Entity @payload.data { emit: { success:\n * \"Saved\", failure: \"SaveFailed\" } })` in `.lolo` source.\n */\nexport type PersistEmitConfig = {\n emit?: { success?: string; failure?: string };\n};\n\n/**\n * Persist effect data argument: an entity row literal (field map), a\n * binding string referencing a row in scope (e.g. `@payload.data`,\n * `@entity`), or an expression form that evaluates to a row (e.g.\n * `[\"object/merge\", \"@payload.data\", { sender: \"@user.id\" }]`). At\n * runtime, binding strings and expressions resolve to `EntityRow` values\n * before the persist op runs — both paths evaluate the expression first.\n */\nexport type PersistRowInput = { id?: string | SExpr } & Record<string, FieldValue | SExpr | undefined>;\n\nexport type PersistData = EntityRow | PersistRowInput | string | SExpr[];\n\n/**\n * One EVALUATED operation of the runtime path's `[\"persist\", \"batch\", [...ops]]`\n * form, as `EffectExecutor` hands it to `handlers.persist('batch', '', { operations })`\n * and both server persist handlers execute it. The row is optional on\n * create/update (an absent row persists `{}`), exactly as the handlers always\n * tolerated. The compiled path has no batch persist — ledger §169.\n */\nexport type PersistBatchOperation =\n | ['create', string, EntityRow?]\n | ['update', string, string, EntityRow?]\n | ['delete', string, string];\n\nfunction isRowObject(value: RuntimeValue): value is EntityRow {\n return typeof value === 'object' && value !== null && !Array.isArray(value) && !(value instanceof Date);\n}\n\n/** The ONE structural check for a batch operation — every consumer narrows through it. */\nexport function isPersistBatchOperation(value: RuntimeValue): value is PersistBatchOperation {\n if (!Array.isArray(value) || typeof value[1] !== 'string') return false;\n switch (value[0]) {\n case 'create':\n return value.length === 2 || (value.length === 3 && isRowObject(value[2]));\n case 'update':\n return typeof value[2] === 'string' && (value.length === 3 || (value.length === 4 && isRowObject(value[3])));\n case 'delete':\n return value.length === 3 && typeof value[2] === 'string';\n default:\n return false;\n }\n}\n\n/**\n * Persist effect - creates, updates, deletes, or clears entities.\n *\n * Each operation accepts an optional trailing `PersistEmitConfig` so the\n * runtime can fire success / failure events when the operation completes.\n *\n * @example ['persist', 'create', 'Task', { title: '@payload.title' }]\n * @example ['persist', 'update', '@entity.entityType', '@payload.data']\n * @example ['persist', 'create', 'Task', '@payload.data', { emit: { success: 'TaskCreated' } }]\n */\nexport type PersistEffect =\n | ['persist', 'create', string, PersistData]\n | ['persist', 'create', string, PersistData, PersistEmitConfig]\n | ['persist', 'upsert', string, PersistData]\n | ['persist', 'upsert', string, PersistData, PersistEmitConfig]\n | ['persist', 'update', string, PersistData]\n | ['persist', 'update', string, PersistData, PersistEmitConfig]\n | ['persist', 'delete', string]\n | ['persist', 'delete', string, PersistData]\n | ['persist', 'delete', string, PersistData, PersistEmitConfig]\n | ['persist', 'clear', string]\n | ['persist', 'clear', string, PersistData]\n | ['persist', 'clear', string, PersistData, PersistEmitConfig]\n | ['persist', 'batch', SExpr]\n | ['persist', 'batch', SExpr, PersistEmitConfig];\n\n/**\n * Call service effect - invokes an external service.\n *\n * Two shapes are accepted:\n *\n * 1. Flat form (what the runtime reads and every .orb file uses):\n * `['call-service', serviceName, action, params?]` — args[0]=service,\n * args[1]=action, args[2]=params. This is the canonical form; the\n * runtime's EffectExecutor decodes exactly these positions.\n *\n * 2. Legacy config-object form (kept for the `callService()` helper):\n * `['call-service', serviceName, CallServiceConfig]` — retained so\n * older call sites using the builder helper continue to typecheck.\n *\n * @example ['call-service', 'my-service', 'run', { target: '@entity.target', event: 'order.placed' }]\n * @example ['call-service', 'my-service', 'run', { target: '...', event: '...' }, { emit: { success: 'OK', failure: 'ERR' } }]\n * @example ['call-service', 'WeatherAPI', { service: 'weather', action: 'get', onSuccess: 'OK' }]\n */\n/** Trailing config on `call-service`: outcome events, plus `onMessage` for\n * the live messages a running call delivers to the requesting client. */\nexport type CallServiceEmitConfig = {\n /** Expression evaluated at call time to a string; names the call for `cancel-call`. */\n key?: SExpr;\n emit?: { success?: string; failure?: string; cancelled?: string; onMessage?: string };\n};\n\n/**\n * Cancel-call effect - aborts the in-flight keyed call (`call-service`, `http`,\n * `browser/prompt` or `browser/embed`) started with that key in the same running\n * app; no-op when none is in flight. The cancelled call emits its `emit.cancelled`\n * event with `{ key }`, never success/failure, and a reply that arrives later is dropped.\n * @example ['cancel-call', '@entity.id']\n */\nexport type CancelCallEffect = ['cancel-call', SExpr];\n\n/** Trailing config of `random-bytes`, `credential-status` and `credential-forget`: outcome events only. */\nexport type HostCallEmitConfig = {\n emit?: { success?: string; failure?: string };\n};\n\n/**\n * Random-bytes effect - `n` bytes (an integer from 1 to 1024) of the host CSPRNG, journaled on the kernel path.\n * Success carries {@link RandomBytesPayload}; failure carries `{ error }`. Server-only.\n * @example ['random-bytes', 32, { emit: { success: 'STATE_DRAWN' } }]\n */\nexport type RandomBytesEffect =\n | ['random-bytes', SExpr]\n | ['random-bytes', SExpr, HostCallEmitConfig & { key?: SExpr }];\n\n/** Success payload of `random-bytes`: the bytes as base64url without padding; a keyed call adds its `key`. */\nexport interface RandomBytesPayload {\n value: string;\n key?: string;\n}\n\n/**\n * Credential-status effect - a bare secret knob checks the signed-in viewer's credential. An explicit\n * `{ credential: knob, scope: 'app' | 'user' }` selects a scope; app checks need no viewer and empty is absent.\n * Success carries {@link CredentialPayload}; user checks fail when nobody is signed in. Server-only.\n * @example ['credential-status', '@config.googleToken', { emit: { success: 'STATUS_KNOWN' } }]\n */\nexport type CredentialStatusEffect =\n | ['credential-status', SExpr]\n | ['credential-status', SExpr, HostCallEmitConfig];\n\n/**\n * Credential-forget effect - drops the signed-in viewer's credential a `secret` knob names; success carries\n * `{ connected: false }`. Server-only.\n * @example ['credential-forget', '@config.googleToken', { emit: { success: 'DISCONNECTED' } }]\n */\nexport type CredentialForgetEffect =\n | ['credential-forget', SExpr]\n | ['credential-forget', SExpr, HostCallEmitConfig];\n\n/** Success payload of `credential-status` and `credential-forget`. */\nexport interface CredentialPayload {\n connected: boolean;\n /** The non-secret account label stored beside the credential (the email it was signed in as); empty text when it has none. Never the value. */\n label: string;\n}\n\n/**\n * Access-check effect - the kernel's verdict on an entity's declared access policy for `viewer` (`null` for nobody) on\n * `row`, through the evaluator fetch and persist enforce. Success carries {@link AccessCheckPayload}; an undeclared entity,\n * an unknown action or a missing key fails with `{ error }`. Server-only.\n * @example ['access-check', { entity: 'Task', action: 'create', row: { ownerId: 'u1' }, viewer: { id: 'u1' } }, { emit: { success: 'CHECKED' } }]\n */\nexport type AccessCheckEffect =\n | ['access-check', AccessCheckRequest]\n | ['access-check', AccessCheckRequest, HostCallEmitConfig];\n\n/** The request of `access-check`. */\nexport interface AccessCheckRequest {\n entity: SExpr;\n action: SExpr;\n row: SExpr;\n viewer: SExpr;\n}\n\n/** Success payload of `access-check`. */\nexport interface AccessCheckPayload {\n allowed: boolean;\n}\n\n/** The credential administration operators: the kernel owns the role gate, the declared-name check and the masking. */\nexport type CredentialAdminOperator =\n | 'credential-list'\n | 'credential-set'\n | 'credential-remove'\n | 'credential-test'\n | 'credential-mode'\n | 'credential-rotate';\n\n/**\n * Credential administration effect - `(credential-<verb> request { emit })`. `credential-list` is open; `set`,\n * `remove`, `test`, `mode` and `rotate` need the caller's `@user.role` among `ALMADAR_CREDENTIAL_ADMIN_ROLES` (default\n * admin, owner). Failures carry\n * {@link CredentialAdminFailure}. Server-only.\n * @example ['credential-set', { service: 'KeysOrbital', envVar: 'ALMADAR_API_KEY_SALT', value: '@payload.value' }, { emit: { success: 'SAVED' } }]\n */\nexport type CredentialAdminEffect =\n | [CredentialAdminOperator, SExpr]\n | [CredentialAdminOperator, SExpr, HostCallEmitConfig];\n\n/** One credential in the masked inventory: where it resolves from and its last four characters, never its value. */\nexport interface CredentialListEntry {\n id: string;\n service: string;\n envVar: string;\n required: boolean;\n description: string;\n configured: boolean;\n source: 'store' | 'env' | 'none';\n last4: string;\n}\n\n/** One service's row of the inventory. */\nexport interface CredentialServiceStatus {\n id: string;\n service: string;\n configured: boolean;\n mocked: boolean;\n status: 'real' | 'emulated' | 'mocked' | 'not configured';\n backend: string;\n needs: string;\n}\n\n/** Success payload of `credential-list`. */\nexport interface CredentialListPayload {\n enabled: boolean;\n mode: 'mock' | 'real';\n services: CredentialServiceStatus[];\n entries: CredentialListEntry[];\n}\n\n/** Success payload of `credential-set`. */\nexport interface CredentialSetPayload {\n saved: true;\n service: string;\n envVar: string;\n last4: string;\n}\n\n/** Success payload of `credential-remove`. */\nexport interface CredentialRemovePayload {\n removed: boolean;\n}\n\n/** Success payload of `credential-test`: presence only, never a live probe. */\nexport interface CredentialTestPayload {\n service: string;\n configured: boolean;\n missing: string[];\n probed: false;\n ok: boolean;\n message: string;\n}\n\n/** Success payload of `credential-mode`. */\nexport interface CredentialModePayload {\n mode: 'mock' | 'real';\n}\n\n/** Success payload of `credential-rotate`. */\nexport interface CredentialRotatePayload {\n rotated: number;\n alreadyCurrent: number;\n unreadable: number;\n}\n\n/** Failure payload of every credential administration effect: `AUTH_ERROR` for a refused role, `VALIDATION_ERROR` for a bad request. */\nexport interface CredentialAdminFailure {\n error: string;\n code: 'AUTH_ERROR' | 'VALIDATION_ERROR' | null;\n}\n\n/** The provider words an OAuth connection can be kept for. */\nexport type OAuthProviderWord = 'google' | 'github' | 'auth0';\n\n/** The operations an `oauth-client` auth performs (closed set). */\nexport type OAuthOp = 'discovery' | 'code' | 'connect' | 'refresh' | 'revoke' | 'userinfo';\n\n/** The `oauth-endpoint` target words: the URL comes from the client's metadata. */\nexport type OAuthEndpointWord = 'token' | 'revocation' | 'userinfo';\n\n/**\n * An OAuth client object: where the authorization server is described (`issuer` XOR `endpoints`) and which\n * `secret` knobs hold the client credentials. `mode: 'mock'` has no runtime on the kernel host.\n */\nexport type OAuthClient = {\n tag: OAuthProviderWord;\n mode: 'real' | 'mock';\n clientId: SExpr;\n clientSecret?: SExpr;\n clientAuth: 'basic' | 'post' | 'none';\n} & (\n | { issuer: SExpr; endpoints?: never }\n | { issuer?: never; endpoints: { authorization: SExpr; token: SExpr; revocation?: SExpr; userinfo?: SExpr } }\n);\n\n/** The options of `oauth-authorize`: the redirect, the scopes, the subject that must complete it, extra authorization params. */\nexport interface OAuthAuthorizeOptions {\n redirectUri: SExpr;\n scope?: SExpr;\n subject?: SExpr;\n params?: Record<string, SExpr>;\n}\n\n/**\n * OAuth-authorize effect - builds the authorization URL and keeps the pending grant (PKCE verifier included)\n * with the host; success carries {@link OAuthAuthorizePayload}, failure {@link OAuthEffectFailurePayload}. Server-only.\n * @example ['oauth-authorize', { tag: 'google', mode: 'real', issuer: '@config.issuer', clientId: '@config.id', clientAuth: 'post' }, { redirectUri: '@config.redirect' }, { emit: { success: 'AUTH_URL' } }]\n */\nexport type OAuthAuthorizeEffect =\n | ['oauth-authorize', OAuthClient, OAuthAuthorizeOptions]\n | ['oauth-authorize', OAuthClient, OAuthAuthorizeOptions, HostCallEmitConfig & { key?: SExpr }];\n\n/**\n * OAuth-connection-status effect - the signed-in viewer's connection to a provider; success carries\n * {@link OAuthConnectionPayload}. Server-only.\n * @example ['oauth-connection-status', 'google', { emit: { success: 'CONNECTION' } }]\n */\nexport type OAuthConnectionStatusEffect =\n | ['oauth-connection-status', OAuthProviderWord]\n | ['oauth-connection-status', OAuthProviderWord, HostCallEmitConfig];\n\n/**\n * OAuth-connection-forget effect - drops the signed-in viewer's connection to a provider; success carries the\n * disconnected {@link OAuthConnectionPayload}. Server-only.\n * @example ['oauth-connection-forget', 'google', { emit: { success: 'DISCONNECTED' } }]\n */\nexport type OAuthConnectionForgetEffect =\n | ['oauth-connection-forget', OAuthProviderWord]\n | ['oauth-connection-forget', OAuthProviderWord, HostCallEmitConfig];\n\n/** Success payload of `oauth-authorize`. */\nexport interface OAuthAuthorizePayload {\n authUrl: string;\n state: string;\n /** The authorization code the person's consent returned on a host that asked them itself; empty text on every other host. */\n code: string;\n /** The call's evaluated `key` option; null when unkeyed. */\n key: string | null;\n}\n\n/** Success payload of `oauth-connection-status` and `oauth-connection-forget`, and of an `oauth-client` `connect`. */\nexport interface OAuthConnectionPayload {\n provider: OAuthProviderWord;\n connected: boolean;\n account: string;\n avatarUrl: string;\n scope: string[];\n connectedAt: string;\n}\n\n/** Failure payload of the OAuth effects: a fixed safe message, the public code and the closed reason. */\nexport interface OAuthEffectFailurePayload {\n error: string;\n code: HttpOAuthFailureCode;\n reason: HttpOAuthFailureReason;\n}\n\n/** Failure payload of `oauth-authorize`: the OAuth failure (or a bare `error`) beside the call's `key`. */\nexport type OAuthAuthorizeFailurePayload = (OAuthEffectFailurePayload | { error: string }) & { key: string | null };\n\n/** Success payloads of the `oauth-client` ops (each also carries the call's `key`). */\nexport interface OAuthDiscoveryPayload { issuer: string; key: string | null }\nexport interface OAuthCodePayload {\n accessToken: string;\n refreshToken: string | null;\n expiresIn: number;\n tokenType: string;\n scope: string[];\n subject: string | null;\n key: string | null;\n}\nexport interface OAuthRefreshPayload { accessToken: string; expiresIn: number; key: string | null }\nexport interface OAuthRevokePayload { revoked: boolean; key: string | null }\nexport interface OAuthUserinfoPayload { sub: string; email: string; name: string; picture: string; key: string | null }\nexport type OAuthConnectPayload = OAuthConnectionPayload & { key: string | null };\n\nexport type CallServiceEffect =\n | ['call-service', string, string]\n | ['call-service', string, string, ServiceParams]\n | ['call-service', string, string, ServiceParams, CallServiceEmitConfig]\n | ['call-service', string, CallServiceConfig];\n\n/** HTTP method word of the `http` effect. */\nexport type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\n/**\n * Http effect - one HTTP request to a declared egress origin (server-only).\n * `request` carries the closed keys query/headers/body/auth/timeoutMs/responseAs/paginate/stream.\n * @example ['http', 'GET', 'https://api.iconify.design', '/search', { query: { query: '@payload.q' } }, { key: '@entity.id', emit: { success: 'OK', failure: 'ERR' } }]\n */\nexport type HttpEffect =\n | ['http', HttpMethod, string, SExpr]\n | ['http', HttpMethod, string, SExpr, SExpr]\n | ['http', HttpMethod, string, SExpr, SExpr, CallServiceEmitConfig];\n\n/**\n * Redis effect - one command to a declared `redis://`/`rediss://` egress origin (server-only); the kernel owns RESP.\n * @example ['redis', 'redis://cache.internal:6379', ['GET', '@payload.key'], { auth: '@config.password' }, { emit: { success: 'GOT', failure: 'ERR' } }]\n */\nexport type RedisEffect =\n | ['redis', string, SExpr]\n | ['redis', string, SExpr, SExpr]\n | ['redis', string, SExpr, SExpr, SExpr];\n\n/**\n * Postgres effect - one parameterised read-only query to a declared `postgres://` egress origin (server-only); the kernel owns the wire protocol.\n * @example ['postgres', 'postgres://db.internal:5432', 'select id from t where a = $1', ['@payload.a'], { user: 'app' }, { emit: { success: 'ROWS', failure: 'ERR' } }]\n */\nexport type PostgresEffect =\n | ['postgres', string, SExpr, SExpr]\n | ['postgres', string, SExpr, SExpr, SExpr]\n | ['postgres', string, SExpr, SExpr, SExpr, SExpr];\n\n/** Success payload of an `http` effect; a non-2xx status is still a success reply. */\nexport interface HttpReplyPayload {\n status: number;\n /** Lower-cased header names. */\n headers: Record<string, string>;\n body: string;\n /** The call's evaluated `key` option; null when unkeyed. */\n key: string | null;\n}\n\n/** Success payload of an `http` effect with `paginate`. */\nexport interface HttpPagedPayload<T> {\n pages: number;\n items: T[];\n last: HttpReplyPayload;\n /** The call's evaluated `key` option; null when unkeyed. */\n key: string | null;\n}\n\nexport interface HttpPresignedPayload {\n url: string;\n key: string | null;\n}\n\n/** Evaluated HTTP input; clock metadata belongs to the dispatch, never the authored request. */\nexport interface HttpCall {\n method: string;\n origin: string;\n path: string;\n request: JsonObject;\n key?: string | null;\n nowMs?: number;\n /** `beacon` hands the built request to the host's beacon port instead of an exchange; absent is `fetch`. */\n delivery?: 'fetch' | 'beacon';\n}\n\n/** Success payload of a `browser/beacon` effect: how the host took the request, never a collector reply. */\nexport interface HttpBeaconPayload {\n /** Queue accepted, or the keepalive fetch answered 2xx. */\n sent: boolean;\n via: 'queue' | 'fetch';\n /** The keepalive fetch's status; null when the queue accepted or the fetch threw. */\n status: number | null;\n /** The call's evaluated `key`; null when unkeyed. */\n key: string | null;\n}\n\n/** A page fact `browser/page-facts` can read; the list order is the read order. */\nexport type PageFactField = 'hostname' | 'referrer' | 'screenWidth';\n\n/** Success payload of `browser/page-facts`: a fact that was not requested carries its default. */\nexport interface BrowserPageFacts {\n /** False when there is no page (no window or document). */\n available: boolean;\n hostname: string;\n referrer: string;\n screenWidth: number | null;\n}\n\n/**\n * Page-facts effect - read the requested page facts (client-only).\n * @example ['browser/page-facts', ['referrer', 'screenWidth'], { emit: { success: 'FACTS', failure: 'FACTS_FAILED' } }]\n */\nexport type BrowserPageFactsEffect =\n | ['browser/page-facts', PageFactField[]]\n | ['browser/page-facts', PageFactField[], CallServiceEmitConfig];\n\n/** The on-device model's surface; the host (a browser, the chrome-extension shell) supplies it. */\nexport interface OnDeviceModelPort {\n availability(): Promise<'available' | 'downloadable' | 'downloading' | 'unavailable'>;\n /** Run one prompt whose reply must satisfy the JSON schema; returns the raw reply text. An aborted `signal` stops it. */\n prompt(text: string, schema: object, signal?: AbortSignal): Promise<string>;\n}\n\n/** The on-device text embedder: one vector per text, in input order. An aborted `signal` stops it. */\nexport interface OnDeviceEmbedderPort {\n embed(texts: string[], signal?: AbortSignal): Promise<number[][]>;\n}\n\n/** The on-device model and embedder a host wires in; each is absent when the host has none. */\nexport interface OnDeviceModelPorts {\n model?: OnDeviceModelPort;\n embedder?: OnDeviceEmbedderPort;\n}\n\n/**\n * Why an on-device call gave no answer: the host wires none (`unconfigured`), has one that cannot answer now\n * (`unavailable`), or it answered with an error (`failed`).\n */\nexport type OnDeviceFailureKind = 'unconfigured' | 'unavailable' | 'failed';\n\n/** Success payload of `browser/prompt`: the model's raw reply text and the call's key (null unkeyed). */\nexport interface BrowserPromptPayload {\n reply: string;\n key: string | null;\n}\n\n/** Success payload of `browser/embed`: one vector per text, in input order, and the call's key (null unkeyed). */\nexport interface BrowserEmbedPayload {\n embeddings: number[][];\n key: string | null;\n}\n\n/** Failure payload of `browser/prompt` and `browser/embed`. */\nexport interface OnDeviceFailurePayload {\n error: string;\n kind: OnDeviceFailureKind;\n key: string | null;\n}\n\n/**\n * Prompt effect - ask the host's on-device model for a reply satisfying the JSON Schema text (client-only,\n * keyed and cancellable by `cancel-call`).\n * @example ['browser/prompt', '@payload.text', '{\"type\":\"object\"}', { key: '@entity.batchId', emit: { success: 'REPLIED', failure: 'FAILED', cancelled: 'CANCELLED' } }]\n */\nexport type BrowserPromptEffect =\n | ['browser/prompt', string, string]\n | ['browser/prompt', string, string, CallServiceEmitConfig];\n\n/**\n * Embed effect - ask the host's on-device embedder for one vector per text (client-only, keyed and cancellable).\n * @example ['browser/embed', ['a', 'b'], { key: '@entity.batchId', emit: { success: 'EMBEDDED', failure: 'FAILED', cancelled: 'CANCELLED' } }]\n */\nexport type BrowserEmbedEffect =\n | ['browser/embed', string[]]\n | ['browser/embed', string[], CallServiceEmitConfig];\n\n/**\n * Beacon effect - fire-and-forget text/plain POST to an absolute http(s) URL through the browser's beacon queue,\n * then one keepalive fetch (client-only).\n * @example ['browser/beacon', 'https://collector.example.com/e', { text: '@entity.body', key: '@entity.id' }, { emit: { success: 'DONE', failure: 'FAILED', cancelled: 'CANCELLED' } }]\n */\nexport type BrowserBeaconEffect =\n | ['browser/beacon', string, SExpr]\n | ['browser/beacon', string, SExpr, CallServiceEmitConfig];\n\n/** Why a `browser/tab-*` call failed: refused before any ask, no tabs on the host, no page script, a vanished element, or another error. */\nexport type BrowserTabFailureKind = 'invalid' | 'unavailable' | 'not-ready' | 'not-found' | 'failed';\n\n/** Failure payload of every `browser/tab-*` effect. */\nexport interface BrowserTabFailurePayload {\n error: string;\n kind: BrowserTabFailureKind;\n /** The call's evaluated `key`; null when unkeyed. */\n key: string | null;\n}\n\n/** One element a `browser/tab-query` read, with the fields its call declared. */\nexport interface BrowserTabElement {\n elementId: string;\n fields: Record<string, string>;\n}\n\n/** What a `browser/tab-capture` hands back: the tab, the image format and the image as standard base64. */\nexport interface BrowserTabCapture {\n tab: number;\n format: 'png' | 'jpeg';\n image: string;\n /** The call's evaluated `key`; null when unkeyed. */\n key: string | null;\n}\n\n/** One element a `browser/tab-apply-many` named, in the tab it was named in. */\nexport interface BrowserTabElementRef {\n tab: number;\n elementId: string;\n}\n\n/**\n * Tab effects - drive the browser's tabs (client-only, keyed and cancellable). The request is the op's closed\n * object; the kernel validates it and shapes the result.\n * @example ['browser/tab-query', { tab: '@entity.tab', selector: '.result', fields: { title: { selector: 'h2' } } }, { emit: { success: 'RESULTS_READ', failure: 'QUERY_FAILED' } }]\n */\nexport type BrowserTabEffect =\n | [BrowserTabOperator, SExpr]\n | [BrowserTabOperator, SExpr, CallServiceEmitConfig];\n\n/** The `browser/tab-*` operator names. */\nexport type BrowserTabOperator =\n | 'browser/tab-list'\n | 'browser/tab-open'\n | 'browser/tab-close'\n | 'browser/tab-navigate'\n | 'browser/tab-query'\n | 'browser/tab-watch'\n | 'browser/tab-unwatch'\n | 'browser/tab-apply'\n | 'browser/tab-apply-many'\n | 'browser/tab-act'\n | 'browser/tab-capture';\n\n/** The leg of an `http` call that failed: its token-exchange grant or the authored request. */\nexport type HttpFailurePhase = 'grant' | 'request';\n\n/** Public AUTH code of an `oauth` failure. */\nexport type HttpOAuthFailureCode = 'AUTH_ERROR' | 'VALIDATION_ERROR' | 'NOT_CONFIGURED' | 'SERVICE_ERROR' | 'NETWORK_ERROR';\n\n/** Closed reason set of an `oauth` failure. */\nexport type HttpOAuthFailureReason =\n | 'state-unknown'\n | 'state-expired'\n | 'subject-mismatch'\n | 'provider-mismatch'\n | 'not-signed-in'\n | 'store-unavailable'\n | 'metadata-invalid'\n | 'response-invalid'\n | 'token-rejected'\n | 'userinfo-mismatch'\n | 'unconfigured-client';\n\n/**\n * Failure payload of an `http` effect; `refused` = rejected before sending, `unavailable` = the host has no port\n * for a capability the call needs. `phase` names the failed leg (null for a refusal or other failure) and\n * `grantStatus`/`grantBody` the status and raw body text of a non-2xx grant reply (never a 2xx body, which carries tokens); `code`/`reason` are set only for `oauth`.\n */\nexport type HttpFailurePayload = {\n error: string;\n /** The call's evaluated `key` option; null when unkeyed. */\n key: string | null;\n} & (\n | { kind: 'unconfigured'; credential: string; phase: HttpFailurePhase | null; grantStatus: number | null; grantBody: string | null; code: null; reason: null }\n | { kind: 'timeout' | 'failed' | 'refused' | 'unavailable'; credential: null; phase: HttpFailurePhase | null; grantStatus: number | null; grantBody: string | null; code: null; reason: null }\n | { kind: 'oauth'; credential: null; phase: null; grantStatus: null; grantBody: null; code: HttpOAuthFailureCode; reason: HttpOAuthFailureReason }\n);\n\n/** One `onMessage` delivery of an `http` effect with `stream` (json-lines: `event`/`id` null). */\nexport interface HttpStreamEvent {\n data: string;\n event: string | null;\n id: string | null;\n /** The call's evaluated `key` option; null when unkeyed. */\n key: string | null;\n}\n\n/**\n * Spawn effect - creates a new entity instance (games).\n * @example ['spawn', 'Bullet', { x: '@entity.x', y: '@entity.y' }]\n */\nexport type SpawnEffect = ['spawn', string] | ['spawn', string, EntityRow];\n\n/**\n * Despawn effect - removes an entity instance (games).\n * @example ['despawn', '@entity.id']\n */\nexport type DespawnEffect = ['despawn', string];\n\n/**\n * Do effect - executes multiple effects in sequence.\n * Uses SExpr to allow deeply nested conditionals.\n * @example ['do', ['set', '@entity.x', 0], ['set', '@entity.y', 0]]\n */\nexport type DoEffect = ['do', ...SExpr[]];\n\n/**\n * Options accepted by `fetch` / `ref` / `deref` effects. Mirrors what\n * `OrbitalServerRuntime`'s fetch handler reads at runtime: `id`, `filter`,\n * `limit`, `offset`, `include`, plus the trailing `emit:` map for\n * success/failure event names.\n */\nexport type FetchOptions = {\n /** Fetch a single entity by ID */\n id?: string;\n /** Filter expression (S-expression) */\n filter?: SExpr;\n /** Maximum number of entities to return. The template layer may carry a\n * binding (`'@config.pageSize'`) or a computed S-expression — the\n * compiler's inline phase resolves it to a number. */\n limit?: number | RenderBinding | SExpr[];\n /** Number of entities to skip — same template-layer forms as `limit`. */\n offset?: number | RenderBinding | SExpr[];\n /** `\"field\"` or `\"field:asc|desc\"`, applied after the filter and before offset/limit; missing values sort last. */\n orderBy?: string | RenderBinding | SExpr[];\n /** Relations to populate (entity field names). The template layer may\n * carry a binding (`'@config.include'`) — same as `limit`/`offset`, the\n * compiler's inline phase resolves it to the concrete list. */\n include?: string[] | RenderBinding;\n /** `rows` (absent) delivers the rows; `ids` delivers a `RowSetMarker`, only passed whole as a `render-ui` prop. */\n deliver?: 'rows' | 'ids';\n /** `exact` (absent) counts every match for `totalCount`; `none` skips the count. */\n total?: 'exact' | 'none';\n /** Lifecycle events to emit on resolve / reject */\n emit?: { success?: string; failure?: string };\n};\n\n/**\n * Fetch effect - retrieves entity data (server-side).\n * @example ['fetch', 'User'] or ['fetch', 'User', { id: '@payload.userId' }]\n */\nexport type FetchEffect = ['fetch', string] | ['fetch', string, FetchOptions];\n\n/** Options for `fetch-stream` — mirror of the compiler's `OirEffect::FetchStream`\n * (`orbital-core/src/ir/effects.rs`) and the runtime's `fetchStream` handler. */\nexport type FetchStreamOptions = {\n id?: string | SExpr;\n filter?: SExpr;\n /** `on_message` fires per chunk; `success` on completion. */\n emit?: { on_message?: string; success?: string; failure?: string };\n};\n\n/**\n * Fetch-stream effect - streams entity rows (server-side), one `on_message`\n * emit per chunk. The compiled path (`OirEffect::FetchStream`) and the\n * runtime (`EffectExecutor` `'fetch-stream'`) both execute it.\n * @example ['fetch-stream', 'Message', { filter: ['=', '@entity.roomId', '@payload.roomId'], emit: { on_message: 'CHUNK' } }]\n */\nexport type FetchStreamEffect = ['fetch-stream', string] | ['fetch-stream', string, FetchStreamOptions];\n\n/**\n * Result returned by a fetch / ref / deref handler.\n *\n * `rows` carries the entity (or entities) that survived `filter` AND\n * pagination (`offset`/`limit`). `total` is the count of rows that\n * matched the filter BEFORE pagination, so paginating consumers can\n * compute `totalPages = ceil(total / pageSize)` without a second\n * round-trip. Single-entity fetches by id return `total: 1` (or `0`\n * if not found, in which case the handler returns `null` instead).\n */\nexport interface FetchResult {\n rows: EntityRow | EntityRow[];\n total: number;\n}\n\n/**\n * If effect - conditional effect execution.\n * Uses SExpr to allow deeply nested conditionals.\n * @example ['if', ['>', '@entity.health', 0], ['emit', 'ALIVE'], ['emit', 'DEAD']]\n */\nexport type IfEffect = ['if', Expression, SExpr] | ['if', Expression, SExpr, SExpr];\n\n/**\n * When effect - conditional effect similar to if but without else.\n * Uses SExpr to allow deeply nested conditionals.\n * @example ['when', ['>', '@entity.health', 0], ['emit', 'ALIVE']]\n */\nexport type WhenEffect = ['when', Expression, SExpr];\n\n/**\n * Let effect - creates local bindings for effects.\n * Uses SExpr to allow deeply nested conditionals.\n * @example ['let', ['temp', ['get', '@payload.value']], ['set', '@entity.value', 'temp']]\n */\nexport type LetEffect = ['let', [string, SExpr][], ...SExpr[]];\n\n/**\n * Log effect - logs a message for debugging.\n * @example ['log', 'User created:', '@entity.name']\n */\nexport type LogEffect = ['log', ...SExpr[]];\n\n/**\n * Wait effect - delays execution.\n * @example ['wait', 1000] - wait 1 second\n */\nexport type WaitEffect = ['wait', number];\n\n// ============================================================================\n// Resource Effects (reactive entity subscriptions and atomic operations)\n// ============================================================================\n\n/**\n * Ref effect - creates a reactive entity subscription.\n * Returns a reactive reference that auto-updates when the entity changes.\n * @example ['ref', '@entity.health'] - reactive subscription to health\n * @example ['ref', 'User', { id: '@payload.userId' }] - reactive ref to specific user\n */\nexport type RefEffect =\n | ['ref', string]\n | ['ref', string, FetchOptions];\n\n/**\n * Deref effect - snapshot read of an entity value.\n * Returns the current value without subscribing to changes.\n * @example ['deref', '@entity.health'] - read current health value\n * @example ['deref', 'User', { id: '@payload.userId' }] - read specific user snapshot\n */\nexport type DerefEffect =\n | ['deref', string]\n | ['deref', string, FetchOptions];\n\n/**\n * Swap! effect - atomic compare-and-swap on an entity field.\n * Only updates if the current value matches the expected value.\n * @example ['swap', '@entity.health', ['fn', ['old'], ['-', 'old', '@payload.damage']]]\n * @example ['swap', '@entity.counter', ['+', '@entity.counter', 1]]\n */\nexport type SwapEffect = ['swap', string, SExpr];\n\n/**\n * Options accepted by `watch` effects. Mirrors what the runtime reads when\n * registering the change callback: `debounce` and the trailing `emit:` map.\n */\nexport type WatchOptions = {\n /** Debounce duration in milliseconds */\n debounce?: number;\n /** Lifecycle events to emit on update / failure */\n emit?: { on_message?: string; failure?: string };\n};\n\n/**\n * Watch effect - registers a callback for entity changes.\n * Emits an event whenever the watched binding changes.\n * @example ['watch', '@entity.health', 'HEALTH_CHANGED']\n * @example ['watch', '@entity.status', 'STATUS_UPDATED', { debounce: 100 }]\n */\nexport type WatchEffect =\n | ['watch', string, string]\n | ['watch', string, string, WatchOptions];\n\n/**\n * Atomic effect - groups multiple effects into an atomic transaction.\n * All effects either succeed together or are rolled back.\n * @example ['atomic', ['set', '@entity.x', 10], ['set', '@entity.y', 20]]\n * @example ['atomic', ['persist', 'update', 'User', { balance: 100 }], ['emit', 'BALANCE_UPDATED']]\n */\nexport type AtomicEffect = ['atomic', ...SExpr[]];\n\n// ============================================================================\n// Agent Effects (from agent/* operator namespace)\n// ============================================================================\n\n/**\n * Agent effect - invokes an agent/* operator.\n * Covers all 22 operators in the std-agent category.\n * @example ['agent/memorize', 'use data-grid for tables', 'preference']\n * @example ['agent/recall', 'user preferences']\n * @example ['agent/generate', 'Summarize this schema']\n */\nexport type AgentEffect = [`agent/${string}`, ...SExpr[]];\n\n/**\n * OS effect - invokes an os/* operator.\n *\n * The `os/` family declared in `@almadar/std` (`modules/os.ts`): one-shot operations and\n * streams that answer through a trailing `EmitConfig` block.\n *\n * @example ['os/read-file', '/etc/hosts', { emit: { success: 'FILE_READ', failure: 'READ_FAILED' } }]\n */\nexport type OsEffect = [`os/${string}`, ...SExpr[]];\n\n/**\n * Browser effect - invokes a browser/* device operator (client host path).\n * User-initiated, async, resolves via the standard trailing emit envelope.\n * Concrete operators (browser/open-file-picker, browser/clipboard-read,\n * browser/clipboard-write, browser/geolocation-current) and their arity /\n * payload shapes live in @almadar/std BROWSER_OPERATORS.\n * @example ['browser/open-file-picker', { multiple: false }, { emit: { success: 'FILES_PICKED', failure: 'PICK_CANCELLED' } }]\n */\nexport type BrowserEffect = [`browser/${string}`, ...SExpr[]];\n\n/**\n * LLM effect - invokes an llm/* operator (agent path).\n * @example ['llm/generate', '@entity.request', { emit: { success: 'PLANNED', failure: 'PLAN_FAILED' } }]\n */\nexport type LlmEffect = [`llm/${string}`, ...SExpr[]];\n\n/**\n * Behavior reflection effects: list installed behaviors by registry folder,\n * describe a trait value, read a behavior's source. They read the host's\n * installed packages through `orb`, so they run on the server.\n * @example ['behavior/catalog', { paths: ['std/ui/core/molecules'] }, { emit: { success: 'LISTED', failure: 'LIST_FAILED' } }]\n */\nexport type BehaviorReflectionEffect = ['behavior/catalog' | 'behavior/describe' | 'behavior/source' | 'behavior/resolve' | 'behavior/dependencies', ...SExpr[]];\n\n/**\n * Program effects: read `.lolo` text into a quoted program, print one back,\n * evaluate one (validate, then instantiate). Run `orb` on the server.\n * @example ['program/eval', '@entity.program', { emit: { success: 'BUILT', failure: 'BUILD_FAILED' } }]\n */\nexport type ProgramEffect = ['program/read' | 'program/print' | 'program/eval' | 'program/validate' | 'program/compose' | 'program/step' | 'program/live', ...SExpr[]];\n\n/**\n * Agent-port effects, the three abilities an LLM tool loop is written with: `program/inputs` lists the\n * running program's declared external inputs, `program/dispatch` fires one AS THE CALLER through the ordinary\n * dispatch (guards, grants and policies apply), `persist/read-named` reads an entity named at run time through\n * its `@read` policy for the caller. Success carries `{ result }`, failure `{ error, errors? }`.\n * @example ['program/dispatch', '@payload.address', '@payload.arguments', { emit: { success: 'DISPATCHED', failure: 'DISPATCH_FAILED' } }]\n */\nexport type AgentPortEffect = ['program/inputs' | 'program/dispatch' | 'persist/read-named', ...SExpr[]];\n\n/**\n * Remaining agent-path operator effects: session/* (workspace session ops),\n * trace/* (trace emission), memory/* (agent memory), application/* (app\n * lifecycle). Expression-only namespaces (array/, math/, object/, str/, …)\n * are deliberately NOT effect heads.\n * @example ['session/write-spec', '@entity.spec']\n */\nexport type SessionEffect = [`session/${string}`, ...SExpr[]];\nexport type TraceEffect = [`trace/${string}`, ...SExpr[]];\nexport type MemoryEffect = [`memory/${string}`, ...SExpr[]];\nexport type ApplicationEffect = [`application/${string}`, ...SExpr[]];\n\n/** Effect operators the std registry declares that had no typed tuple (arity from the registry). */\nexport type NotifyEffect = ['notify', SExpr] | ['notify', SExpr, SExpr];\nexport type SendServerEffect = ['send-server', SExpr] | ['send-server', SExpr, SExpr];\nexport type ProbSeedEffect = ['prob/seed', SExpr];\nexport type ProbConditionEffect = ['prob/condition', SExpr];\nexport type WorkspaceWriteOrbitalEffect = ['workspace/write-orbital', SExpr, SExpr];\nexport type WorkspaceWriteFileEffect = ['workspace/write-file', SExpr, SExpr];\nexport type WorkspaceWriteSchemaEffect = ['workspace/write-schema', SExpr];\nexport type WorkspaceWritePlanEffect = ['workspace/write-plan', SExpr];\nexport type WorkspaceArchiveOrbitalEffect = ['workspace/archive-orbital', SExpr];\n\n/**\n * Union of all typed effects.\n * Provides compile-time validation for common effect types.\n */\nexport type TypedEffect =\n | RenderUIEffect\n | NavigateEffect\n | NavigateBackEffect\n | EmitEffect\n | SetEffect\n | PersistEffect\n | CallServiceEffect\n | CancelCallEffect\n | RandomBytesEffect\n | CredentialStatusEffect\n | CredentialForgetEffect\n | CredentialAdminEffect\n | AccessCheckEffect\n | OAuthAuthorizeEffect\n | OAuthConnectionStatusEffect\n | OAuthConnectionForgetEffect\n | HttpEffect\n | RedisEffect\n | PostgresEffect\n | SpawnEffect\n | DespawnEffect\n | DoEffect\n | FetchEffect\n | FetchStreamEffect\n | IfEffect\n | WhenEffect\n | LetEffect\n | LogEffect\n | WaitEffect\n | RefEffect\n | DerefEffect\n | SwapEffect\n | WatchEffect\n | AtomicEffect\n | AgentEffect\n | OsEffect\n | BrowserEffect\n | LlmEffect\n | BehaviorReflectionEffect\n | ProgramEffect\n | AgentPortEffect\n | SessionEffect\n | TraceEffect\n | MemoryEffect\n | ApplicationEffect\n | NotifyEffect\n | SendServerEffect\n | ProbSeedEffect\n | ProbConditionEffect\n | WorkspaceWriteOrbitalEffect\n | WorkspaceWriteFileEffect\n | WorkspaceWriteSchemaEffect\n | WorkspaceWritePlanEffect\n | WorkspaceArchiveOrbitalEffect;\n\n// ============================================================================\n// Effect Type (Strictly Typed)\n// ============================================================================\n\n/**\n * Effect type - typed S-expression format.\n *\n * Effects are strongly typed tuples that enforce:\n * - Valid effect operators (render-ui, emit, set, persist, navigate, call-service)\n * - Valid UISlots for render-ui\n * - Valid PatternTypes and props for render-ui\n * - Correct argument types for each effect\n *\n * Available typed effects:\n * - RenderUIEffect: ['render-ui', UISlot, PatternConfig]\n * - NavigateEffect: ['navigate', path] or ['navigate', path, params]\n * - EmitEffect: ['emit', eventName] or ['emit', eventName, payload]\n * - SetEffect: ['set', binding, value]\n * - PersistEffect: ['persist', operation, entity, data?]\n * - CallServiceEffect: ['call-service', serviceName, config]\n *\n * @example\n * [\"set\", \"@entity.health\", 100]\n * [\"emit\", \"PLAYER_DIED\", { \"playerId\": \"@entity.id\" }]\n * [\"render-ui\", \"main\", { \"patternType\": \"table-view\", \"columns\": [{ \"key\": \"name\", \"header\": \"Name\" }] }]\n * [\"call-service\", \"WeatherAPI\", { \"action\": \"getWeather\", \"onSuccess\": \"OK\" }]\n * [\"navigate\", \"/tasks\"]\n * [\"persist\", \"create\", \"Task\", { \"title\": \"@payload.title\" }]\n */\nexport type Effect = TypedEffect;\n\n/** Every literal effect operator the {@link Effect} union declares, as runtime data. */\nexport const EFFECT_OPERATORS = [\n 'render-ui', 'navigate', 'navigate-back', 'emit', 'set', 'persist', 'call-service', 'cancel-call', 'random-bytes', 'credential-status', 'credential-forget', 'credential-list', 'credential-set', 'credential-remove', 'credential-test', 'credential-mode', 'credential-rotate', 'access-check', 'oauth-authorize', 'oauth-connection-status', 'oauth-connection-forget', 'http', 'redis', 'postgres', 'spawn',\n 'despawn', 'do', 'fetch', 'fetch-stream', 'if', 'when', 'let', 'log', 'wait', 'ref', 'deref',\n 'swap', 'watch', 'atomic', 'notify', 'send-server',\n 'prob/seed', 'prob/condition', 'workspace/write-orbital', 'workspace/write-file',\n 'workspace/write-schema', 'workspace/write-plan', 'workspace/archive-orbital', 'behavior/catalog',\n 'behavior/describe', 'behavior/source', 'behavior/resolve', 'behavior/dependencies', 'program/read', 'program/print', 'program/eval', 'program/validate', 'program/compose', 'program/step',\n 'program/inputs', 'program/dispatch', 'program/live', 'persist/read-named',\n] as const;\n\n/** Namespaced effect families (`<family>/<name>`, e.g. `llm/generate`) the {@link Effect} union declares. */\nexport const EFFECT_OPERATOR_FAMILIES = [\n 'agent', 'os', 'browser', 'llm', 'session', 'trace', 'memory',\n 'application',\n] as const;\n\nexport type EffectOperator = (typeof EFFECT_OPERATORS)[number];\nexport type EffectOperatorFamily = (typeof EFFECT_OPERATOR_FAMILIES)[number];\n\ntype EffectHead = Effect[0];\ntype FamilyOfHead<H> = H extends `${infer P}/${string}` ? (`${P}/\\u0000` extends H ? P : never) : never;\ntype LiteralOfHead<H> = H extends `${infer P}/${string}` ? (`${P}/\\u0000` extends H ? never : H) : H;\ntype AssertTrue<T extends true> = T;\n/** Fails to compile when the runtime lists and the {@link Effect} union drift apart, in either direction. */\nexport type EffectOperatorsInSync = AssertTrue<\n [Exclude<LiteralOfHead<EffectHead>, EffectOperator>, Exclude<EffectOperator, LiteralOfHead<EffectHead>>,\n Exclude<FamilyOfHead<EffectHead>, EffectOperatorFamily>, Exclude<EffectOperatorFamily, FamilyOfHead<EffectHead>>] extends [never, never, never, never]\n ? true : false\n>;\n\n/**\n * The effects a server reports an outcome for on\n * `OrbitalEventResponse.effectResults` (`ServerEffectResult.effect`). Every\n * member is checked against the effect heads above at compile time, so a\n * name that is not an effect cannot be listed and a new server-reported\n * effect is added HERE only — the wire type, its zod twin and the\n * `events-wire` fixture case all derive from this array.\n */\nexport const SERVER_REPORTED_EFFECTS = [\n 'set',\n 'persist',\n 'call-service',\n 'http',\n 'fetch',\n 'fetch-stream',\n 'ref',\n 'deref',\n 'swap',\n 'atomic',\n 'emit',\n] as const satisfies readonly Effect[0][];\n\nexport type ServerReportedEffect = (typeof SERVER_REPORTED_EFFECTS)[number];\n\n/** A namespaced effect head (`trace/emit`, `memory/store`, `llm/…`) — what a\n * `substrate` result's `name` carries. Derived from the union, never listed. */\nexport type NamespacedEffectName = Extract<Effect[0], `${string}/${string}`>;\n\n/**\n * Schema for Effect - validates S-expression format. Arguments validate as\n * s-expr-shaped DATA (`SExprDataSchema`) — literal data arrays (empty or\n * non-operator-headed) are valid argument values; the operator-head refine\n * applies to the effect itself, not to every argument.\n */\nconst EffectShapeSchema = z.array(SExprDataSchema).min(1).refine(\n (arr) => typeof arr[0] === 'string',\n { message: 'Effect must be an S-expression with a string operator as first element' }\n);\n\n/** Validates the S-expression shape and yields the typed `Effect` (the claim `isEffect` makes). */\nexport const EffectSchema: z.ZodType<Effect> = z.custom<Effect>(\n (value) => EffectShapeSchema.safeParse(value).success,\n { message: 'Effect must be an S-expression with a string operator as first element' }\n);\n\nexport type EffectInput = z.input<typeof EffectSchema>;\n\n/**\n * Type guard to check if a value is a valid Effect (S-expression).\n * \n * Validates that a value conforms to the Effect structure. Effects are\n * represented as arrays where the first element is a string (effect type)\n * and subsequent elements are parameters. Used for runtime validation\n * of effect structures.\n * \n * @param {RuntimeValue} value - Value to check\n * @returns {boolean} True if value is a valid Effect, false otherwise\n *\n * @example\n * isEffect(['set', '@entity.health', 100]); // returns true\n * isEffect('not-an-effect'); // returns false\n * isEffect([]); // returns false\n */\nexport function isEffect(value: RuntimeValue): value is Effect {\n return Array.isArray(value) && value.length > 0 && typeof value[0] === 'string';\n}\n\n/**\n * Alias for isEffect (for clarity when working with S-expressions)\n */\nexport const isSExprEffect = isEffect;\n\n// ============================================================================\n// Effect Builder Helpers\n// ============================================================================\n\n/**\n * Creates a set effect for state updates.\n * \n * Generates an effect that sets a binding to a value. Used in state\n * machine transitions to update entity fields, UI state, or other\n * mutable data.\n * \n * @param {string} binding - Target binding (e.g., '@entity.health')\n * @param {SExpr} value - Value to set (can be literal or expression)\n * @returns {Effect} Set effect array\n * \n * @example\n * set('@entity.health', 100); // returns [\"set\", \"@entity.health\", 100]\n * set('@state.loading', false); // returns [\"set\", \"@state.loading\", false]\n */\nexport function set(binding: string, value: SExpr): Effect {\n return ['set', binding, value];\n}\n\n/**\n * Creates an emit effect for event dispatching.\n * \n * Generates an effect that emits an event with optional payload.\n * Used in state machine transitions to trigger events that can be\n * handled by other traits, services, or external systems.\n * \n * @param {string} event - Event name to emit\n * @param {EventPayload} [payload] - Optional event payload\n * @returns {Effect} Emit effect array\n * \n * @example\n * emit('PLAYER_DIED', { playerId: '@entity.id' }); // returns [\"emit\", \"PLAYER_DIED\", { playerId: \"@entity.id\" }]\n * emit('GAME_STARTED'); // returns [\"emit\", \"GAME_STARTED\"]\n */\nexport function emit(event: string, payload?: EventPayload): Effect {\n return payload ? ['emit', event, payload] : ['emit', event];\n}\n\n/**\n * Creates a navigation effect for page routing.\n * \n * Generates an effect that navigates to a specified path with optional\n * parameters. Used in state machine transitions to change pages or\n * update URL parameters.\n * \n * @param {string} path - Target path (e.g., '/tasks')\n * @param {Record<string, string>} [params] - Optional URL parameters\n * @returns {NavigateEffect} Navigation effect array\n * \n * @example\n * navigate('/tasks'); // returns [\"navigate\", \"/tasks\"]\n * navigate('/user', { id: '123' }); // returns [\"navigate\", \"/user\", { id: \"123\" }]\n */\nexport function navigate(path: string): NavigateEffect;\nexport function navigate(path: string, params: Record<string, string>): NavigateEffect;\nexport function navigate(path: string, params: Record<string, string>, options: NavigateOptions): NavigateEffect;\nexport function navigate(path: string, params?: Record<string, string>, options?: NavigateOptions): NavigateEffect {\n if (params && options) return ['navigate', path, params, options];\n return params ? ['navigate', path, params] : ['navigate', path];\n}\n\n/**\n * Creates a navigate-back effect: pop the orbital's navigation stack and\n * navigate to the previous entry.\n *\n * @example\n * navigateBack(); // returns [\"navigate-back\"]\n */\nexport function navigateBack(): NavigateBackEffect {\n return ['navigate-back'];\n}\n\n/**\n * Create a render-ui effect\n * @example [\"render-ui\", \"main\", { \"patternType\": \"table-view\", \"columns\": [{ \"key\": \"name\", \"header\": \"Name\" }] }]\n */\nexport function renderUI(target: UISlot, pattern: AnyPatternConfig): RenderUIEffect {\n return ['render-ui', target, pattern];\n}\n\n/**\n * Create a persist effect\n * @example [\"persist\", \"create\", \"Task\", { \"title\": \"@payload.title\" }]\n */\nexport function persist(\n action: 'create' | 'upsert' | 'update',\n entity: string,\n data: PersistData\n): PersistEffect;\nexport function persist(\n action: 'delete' | 'clear',\n entity: string,\n data?: PersistData\n): PersistEffect;\nexport function persist(\n action: 'create' | 'upsert' | 'update' | 'delete' | 'clear',\n entity: string,\n data?: PersistData\n): PersistEffect {\n if (action === 'create' || action === 'upsert' || action === 'update') {\n return ['persist', action, entity, data!] as PersistEffect;\n }\n return data\n ? ['persist', action, entity, data] as PersistEffect\n : ['persist', action, entity] as PersistEffect;\n}\n\n/**\n * Create a call-service effect\n * @example [\"call-service\", \"my-service\", { \"service\": \"my-service\", \"action\": \"run\", \"onSuccess\": \"OK\", \"onError\": \"ERR\" }]\n */\nexport function callService(\n serviceName: string,\n config: CallServiceConfig\n): CallServiceEffect {\n return ['call-service', serviceName, config];\n}\n\n/**\n * Create a spawn effect (games)\n * @example [\"spawn\", \"Bullet\", { \"x\": \"@entity.x\", \"y\": \"@entity.y\" }]\n */\nexport function spawn(entity: string): SpawnEffect;\nexport function spawn(entity: string, initialState: EntityRow): SpawnEffect;\nexport function spawn(entity: string, initialState?: EntityRow): SpawnEffect {\n return initialState ? ['spawn', entity, initialState] : ['spawn', entity];\n}\n\n/**\n * Create a despawn effect (games)\n * @example [\"despawn\", \"@entity.id\"]\n */\nexport function despawn(entityId: string): DespawnEffect {\n return ['despawn', entityId];\n}\n\n/**\n * Create a do effect (multiple effects)\n * @example [\"do\", [\"set\", \"@entity.x\", 0], [\"set\", \"@entity.y\", 0]]\n */\nexport function doEffects(...effects: SExpr[]): DoEffect {\n return ['do', ...effects];\n}\n\n/**\n * Create a fetch effect (server-side data retrieval)\n * @example [\"fetch\", \"User\"] - fetch all users\n * @example [\"fetch\", \"User\", { \"id\": \"@payload.userId\" }] - fetch by ID\n * @example [\"fetch\", \"User\", { \"filter\": [\"=\", \"@entity.status\", \"active\"], \"limit\": 10 }]\n */\nexport function fetch(entity: string): FetchEffect;\nexport function fetch(entity: string, options: FetchOptions): FetchEffect;\nexport function fetch(entity: string, options?: FetchOptions): FetchEffect {\n return options ? ['fetch', entity, options] : ['fetch', entity];\n}\n\n// ============================================================================\n// Resource Effect Builder Helpers\n// ============================================================================\n\n/**\n * Create a ref effect (reactive entity subscription).\n *\n * @param {string} binding - Binding or entity name to subscribe to\n * @param {FetchOptions} [selector] - Optional selector for specific entity\n * @returns {RefEffect} Ref effect array\n *\n * @example\n * ref('@entity.health'); // returns [\"ref\", \"@entity.health\"]\n * ref('User', { id: '@payload.userId' }); // returns [\"ref\", \"User\", { id: \"@payload.userId\" }]\n */\nexport function ref(binding: string): RefEffect;\nexport function ref(binding: string, selector: FetchOptions): RefEffect;\nexport function ref(binding: string, selector?: FetchOptions): RefEffect {\n return selector ? ['ref', binding, selector] : ['ref', binding];\n}\n\n/**\n * Create a deref effect (snapshot read).\n *\n * @param {string} binding - Binding or entity name to read\n * @param {FetchOptions} [selector] - Optional selector for specific entity\n * @returns {DerefEffect} Deref effect array\n *\n * @example\n * deref('@entity.health'); // returns [\"deref\", \"@entity.health\"]\n * deref('User', { id: '@payload.userId' }); // returns [\"deref\", \"User\", { id: \"@payload.userId\" }]\n */\nexport function deref(binding: string): DerefEffect;\nexport function deref(binding: string, selector: FetchOptions): DerefEffect;\nexport function deref(binding: string, selector?: FetchOptions): DerefEffect {\n return selector ? ['deref', binding, selector] : ['deref', binding];\n}\n\n/**\n * Create a swap effect (atomic compare-and-swap).\n *\n * @param {string} binding - Binding to atomically update\n * @param {SExpr} transform - Transformation expression applied to the current value\n * @returns {SwapEffect} Swap effect array\n *\n * @example\n * swap('@entity.counter', ['+', '@entity.counter', 1]);\n * // returns [\"swap\", \"@entity.counter\", [\"+\", \"@entity.counter\", 1]]\n */\nexport function swap(binding: string, transform: SExpr): SwapEffect {\n return ['swap', binding, transform];\n}\n\n/**\n * Create a watch effect (entity change callback).\n *\n * @example\n * watch('@entity.health', 'HEALTH_CHANGED');\n * watch('@entity.status', 'STATUS_UPDATED', { debounce: 100 });\n */\nexport function watch(binding: string, event: string): WatchEffect;\nexport function watch(binding: string, event: string, options: WatchOptions): WatchEffect;\nexport function watch(binding: string, event: string, options?: WatchOptions): WatchEffect {\n return options\n ? ['watch', binding, event, options]\n : ['watch', binding, event];\n}\n\n/**\n * Create an atomic effect (transaction group).\n *\n * @param {...SExpr[]} effects - Effects to execute atomically\n * @returns {AtomicEffect} Atomic effect array\n *\n * @example\n * atomic(['set', '@entity.x', 10], ['set', '@entity.y', 20]);\n * // returns [\"atomic\", [\"set\", \"@entity.x\", 10], [\"set\", \"@entity.y\", 20]]\n */\nexport function atomic(...effects: SExpr[]): AtomicEffect {\n return ['atomic', ...effects];\n}\n\n// ============================================================================\n// Runtime Pattern Types\n// ============================================================================\n\n/** Resolved pattern props for render-ui effects at runtime. Recursive for nested pattern configs. */\nexport type ResolvedPatternProps = {\n [prop: string]:\n | string\n | number\n | boolean\n | null\n | undefined\n | ResolvedPatternProps\n | RenderChildrenMap\n | Array<ResolvedPatternProps | RenderChildrenMap>;\n};\n\n/**\n * Zod twin of `PatternConfig`/`AnyPatternConfig` — validates the WIRE SHAPE\n * (a plain object, or `null` for an unset render-ui target) only. Per-pattern\n * prop shape (the hundreds of generated `PatternPropsMap` variants) is\n * enforced by the patterns registry at `orb validate` / lolo parse time, not\n * re-validated here — a second, drifting copy of that registry is exactly\n * the duplicate this schema must not become.\n */\nexport const PatternConfigSchema: z.ZodType<AnyPatternConfig | null> = z.custom<AnyPatternConfig | null>(\n (value) => value === null || (typeof value === 'object' && value !== null && !Array.isArray(value)),\n { message: 'Expected a pattern config object or null' },\n);\n\n/** A pattern config that must be present — the non-null twin of {@link PatternConfigSchema}. */\nexport const PatternObjectSchema: z.ZodType<AnyPatternConfig> = z.custom<AnyPatternConfig>(\n (value) => typeof value === 'object' && value !== null && !Array.isArray(value),\n { message: 'Expected a pattern config object' },\n);\n\n/** Zod twin of `ResolvedPatternProps` — validates the wire shape (a plain object) only, see {@link PatternConfigSchema}. */\nexport const ResolvedPatternPropsSchema: z.ZodType<ResolvedPatternProps> = z.custom<ResolvedPatternProps>(\n (value) => typeof value === 'object' && value !== null && !Array.isArray(value),\n { message: 'Expected a resolved pattern props object' },\n);\n\n/** A node in a render-ui effect tree. */\nexport interface RenderUINode {\n type: string;\n props?: ResolvedPatternProps;\n /** Static child nodes and/or dynamic-collection map entries. A\n * {@link RenderChildrenMap} entry expands at render time into resolved\n * `RenderUINode`s, so components always receive a flat, fully-resolved list. */\n children?: Array<RenderUINode | RenderChildrenMap>;\n content?: string;\n entity?: string;\n renderItem?: RenderUINode;\n}\n\n","/**\n * The one TypeScript definition of `RowPredicate` / `RowQuery` semantics. Every store that runs a\n * query in process (the memory adapter, the IndexedDB cursor pass, test oracles) goes through here;\n * stores that translate the query (SQL, Mango, Firestore) are tested against the same shared cases.\n */\nimport { z } from 'zod';\nimport { EntityRowSchema, FieldValueSchema, type EntityRow, type FieldValue } from './types/entity.js';\nimport type {\n QueryCapabilities,\n RowIdPage,\n RowPredicate,\n RowQuery,\n RowQueryPage,\n RowWriteBatch,\n RowWriteOp,\n RowWriteOutcome,\n WriteCapabilities,\n RowCommit,\n} from './service-types.js';\n\nconst CompareOpSchema = z.enum(['==', '!=', '<', '<=', '>', '>=']);\n\nexport const RowPredicateSchema: z.ZodType<RowPredicate> = z.lazy(() =>\n z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('compare'), field: z.string(), op: CompareOpSchema, value: FieldValueSchema }),\n z.object({ kind: z.literal('member'), field: z.string(), values: z.array(FieldValueSchema) }),\n z.object({ kind: z.literal('hasElement'), field: z.string(), value: FieldValueSchema }),\n z.object({ kind: z.literal('contains'), field: z.string(), text: z.string(), caseSensitive: z.boolean() }),\n z.object({ kind: z.literal('isNull'), field: z.string(), isNull: z.boolean() }),\n z.object({ kind: z.literal('all'), of: z.array(RowPredicateSchema) }),\n z.object({ kind: z.literal('any'), of: z.array(RowPredicateSchema) }),\n z.object({ kind: z.literal('not'), of: RowPredicateSchema }),\n z.object({ kind: z.literal('const'), value: z.boolean() }),\n ]),\n);\n\nexport const RowQuerySchema: z.ZodType<RowQuery> = z.object({\n policy: RowPredicateSchema.optional(),\n filter: RowPredicateSchema.optional(),\n order: z.object({ field: z.string(), direction: z.enum(['asc', 'desc']) }).optional(),\n offset: z.number().int().nonnegative().optional(),\n limit: z.number().int().nonnegative().optional(),\n total: z.enum(['exact', 'none']).optional(),\n nearest: z.object({ field: z.string(), vector: z.array(z.number()), k: z.number().int().positive() }).optional(),\n});\n\nexport const RowIdPageSchema: z.ZodType<RowIdPage> = z.object({\n ids: z.array(z.string()),\n total: z.number().int().nonnegative(),\n});\n\nexport const RowWriteOpSchema: z.ZodType<RowWriteOp> = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('create'), entityType: z.string(), data: EntityRowSchema }),\n z.object({ kind: z.literal('upsert'), entityType: z.string(), data: EntityRowSchema }),\n z.object({ kind: z.literal('update'), entityType: z.string(), id: z.string(), data: EntityRowSchema, guard: RowPredicateSchema.optional() }),\n z.object({ kind: z.literal('delete'), entityType: z.string(), id: z.string(), guard: RowPredicateSchema.optional() }),\n z.object({ kind: z.literal('rekey'), entityType: z.string(), id: z.string(), newId: z.string().min(1), guard: RowPredicateSchema.optional() }),\n]);\n\nexport const RowWriteOutcomeSchema: z.ZodType<RowWriteOutcome> = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('created'), row: EntityRowSchema }),\n z.object({ kind: z.literal('updated'), row: EntityRowSchema, before: EntityRowSchema.optional() }),\n z.object({ kind: z.literal('deleted'), before: EntityRowSchema.optional() }),\n z.object({ kind: z.literal('not-found') }),\n z.object({ kind: z.literal('duplicate-id') }),\n z.object({ kind: z.literal('refused') }),\n z.object({ kind: z.literal('failed'), message: z.string() }),\n z.object({ kind: z.literal('rolled-back') }),\n]);\n\nexport const RowWriteBatchSchema: z.ZodType<RowWriteBatch> = z.object({\n ops: z.array(RowWriteOpSchema),\n onFailure: z.enum(['atomic', 'stop']),\n});\n\nconst LeafKindSchema = z.enum(['compare', 'member', 'hasElement', 'contains', 'isNull']);\nconst CombinatorSchema = z.enum(['all', 'any', 'not']);\nconst RowOperatorSchema = z.enum(['==', '!=', '<', '<=', '>', '>=', 'member', 'hasElement', 'contains']);\nconst RowValueKindSchema = z.enum(['string', 'number', 'boolean', 'date', 'null']);\n\nexport const RowCommitSchema: z.ZodType<RowCommit> = z.object({\n entityType: z.string(),\n id: z.string(),\n expected: EntityRowSchema.nullable(),\n write: z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('keep') }),\n z.object({ kind: z.literal('put'), row: EntityRowSchema }),\n z.object({ kind: z.literal('delete') }),\n ]),\n});\n\nexport const QueryCapabilitiesSchema: z.ZodType<QueryCapabilities> = z.object({\n leaves: z.array(LeafKindSchema),\n combinators: z.array(CombinatorSchema),\n compareOps: z.array(CompareOpSchema),\n operatorValueKinds: z.array(z.object({ operator: RowOperatorSchema, valueKinds: z.array(RowValueKindSchema) })).optional(),\n orderableFields: z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('every-field') }),\n z.object({ kind: z.literal('listed'), fields: z.array(z.string()) }),\n ]),\n window: z.boolean(),\n exactTotal: z.boolean(),\n idsOnly: z.boolean().optional(),\n nearest: z.boolean().optional(),\n});\n\nexport const WriteCapabilitiesSchema: z.ZodType<WriteCapabilities> = z.object({\n guards: z.object({ leaves: z.array(LeafKindSchema), combinators: z.array(CombinatorSchema), compareOps: z.array(CompareOpSchema) }),\n conditional: z.boolean(),\n returnsRow: z.boolean(),\n stopRuns: z.boolean(),\n atomicBatch: z.boolean(),\n rekey: z.boolean().optional(),\n commitRows: z.boolean().optional(),\n});\n\nexport const RowQueryPageSchema: z.ZodType<RowQueryPage> = z.object({\n rows: z.array(EntityRowSchema),\n total: z.number().int().nonnegative(),\n});\n\ntype Comparable = string | number | boolean | Date;\n\nfunction isMissing(value: FieldValue | undefined): value is null | undefined {\n return value === null || value === undefined;\n}\n\nfunction comparable(value: FieldValue | undefined): value is Comparable {\n return typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' || value instanceof Date;\n}\n\nfunction codePointOrder(a: string, b: string): number {\n const x = Array.from(a);\n const y = Array.from(b);\n const n = Math.min(x.length, y.length);\n for (let i = 0; i < n; i++) {\n const cx = x[i].codePointAt(0) ?? 0;\n const cy = y[i].codePointAt(0) ?? 0;\n if (cx !== cy) return cx < cy ? -1 : 1;\n }\n return x.length === y.length ? 0 : x.length < y.length ? -1 : 1;\n}\n\n/** Order of two present values of one kind (binary order for strings); null when the kinds differ. */\nfunction orderValues(a: Comparable, b: Comparable): number | null {\n if (typeof a === 'string' && typeof b === 'string') return codePointOrder(a, b);\n if (typeof a === 'number' && typeof b === 'number') return a === b ? 0 : a < b ? -1 : 1;\n if (typeof a === 'boolean' && typeof b === 'boolean') return a === b ? 0 : a ? 1 : -1;\n if (a instanceof Date && b instanceof Date) {\n const x = a.getTime();\n const y = b.getTime();\n return x === y ? 0 : x < y ? -1 : 1;\n }\n return null;\n}\n\nfunction sameValue(a: FieldValue | undefined, b: FieldValue | undefined): boolean {\n if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();\n return a === b;\n}\n\nfunction compareLeaf(value: FieldValue | undefined, op: RowPredicate & { kind: 'compare' }): boolean {\n const target = op.value;\n if (isMissing(value)) return op.op === '!=' && !isMissing(target);\n switch (op.op) {\n case '==': return sameValue(value, target);\n case '!=': return !sameValue(value, target);\n default: {\n if (!comparable(value) || !comparable(target)) return false;\n const c = orderValues(value, target);\n if (c === null) return false;\n if (op.op === '<') return c < 0;\n if (op.op === '<=') return c <= 0;\n if (op.op === '>') return c > 0;\n return c >= 0;\n }\n }\n}\n\n/** Full Unicode case folding as `toUpperCase` then `toLowerCase` gives it: `ß` = `SS` = `ss`, `ς` = `σ`. */\nfunction foldCase(text: string): string {\n return text.toUpperCase().toLowerCase();\n}\n\ninterface MemberLookup {\n plain: Set<FieldValue>;\n times: Set<number>;\n}\n\n// A member list is scanned once per predicate, not once per row.\nconst memberLookups = new WeakMap<RowPredicate & { kind: 'member' }, MemberLookup>();\n\nfunction memberLookup(predicate: RowPredicate & { kind: 'member' }): MemberLookup {\n const cached = memberLookups.get(predicate);\n if (cached !== undefined) return cached;\n const lookup: MemberLookup = { plain: new Set(), times: new Set() };\n for (const v of predicate.values) {\n if (v instanceof Date) lookup.times.add(v.getTime());\n else lookup.plain.add(v);\n }\n memberLookups.set(predicate, lookup);\n return lookup;\n}\n\nexport function rowMatchesPredicate(row: EntityRow, predicate: RowPredicate): boolean {\n switch (predicate.kind) {\n case 'const': return predicate.value;\n case 'all': return predicate.of.every((p) => rowMatchesPredicate(row, p));\n case 'any': return predicate.of.some((p) => rowMatchesPredicate(row, p));\n case 'not': return !rowMatchesPredicate(row, predicate.of);\n case 'compare': return compareLeaf(row[predicate.field], predicate);\n case 'isNull': return isMissing(row[predicate.field]) === predicate.isNull;\n case 'member': {\n const value = row[predicate.field];\n if (isMissing(value)) return false;\n const lookup = memberLookup(predicate);\n if (value instanceof Date) return lookup.times.has(value.getTime());\n return !Number.isNaN(value) && lookup.plain.has(value);\n }\n case 'hasElement': {\n const value = row[predicate.field];\n return Array.isArray(value) && value.some((v) => sameValue(v, predicate.value));\n }\n case 'contains': {\n const value = row[predicate.field];\n if (typeof value !== 'string') return false;\n return predicate.caseSensitive\n ? value.includes(predicate.text)\n : foldCase(value).includes(foldCase(predicate.text));\n }\n }\n}\n\nexport interface RowWriteResult {\n rows: EntityRow[];\n outcome: RowWriteOutcome;\n}\n\nfunction rowIdOf(row: EntityRow): string | null {\n return typeof row.id === 'string' ? row.id : null;\n}\n\n/** The reference run of one write over a full row set; the input is not mutated. */\nexport function runRowWrite(rows: readonly EntityRow[], op: RowWriteOp): RowWriteResult {\n if (op.kind === 'rekey') return { rows: [...rows], outcome: { kind: 'failed', message: 'rekey is unsupported by this store' } };\n if (op.kind === 'create') {\n const id = rowIdOf(op.data);\n if (id === null) return { rows: [...rows], outcome: { kind: 'failed', message: 'create needs a string id' } };\n if (rows.some((r) => r.id === id)) return { rows: [...rows], outcome: { kind: 'duplicate-id' } };\n const row: EntityRow = { ...op.data };\n return { rows: [...rows, row], outcome: { kind: 'created', row } };\n }\n if (op.kind === 'upsert') {\n const id = rowIdOf(op.data);\n if (id === null) return { rows: [...rows], outcome: { kind: 'failed', message: 'upsert needs a string id' } };\n const index = rows.findIndex((r) => r.id === id);\n if (index < 0) {\n const row: EntityRow = { ...op.data };\n return { rows: [...rows, row], outcome: { kind: 'created', row } };\n }\n const kept = rows[index].createdAt;\n const row: EntityRow = kept === undefined ? { ...op.data } : { ...op.data, createdAt: kept };\n return { rows: rows.map((r, i) => (i === index ? row : r)), outcome: { kind: 'updated', row } };\n }\n const index = rows.findIndex((r) => r.id === op.id);\n if (index < 0) return { rows: [...rows], outcome: { kind: 'not-found' } };\n const before = rows[index];\n if (op.guard !== undefined && !rowMatchesPredicate(before, op.guard)) return { rows: [...rows], outcome: { kind: 'refused' } };\n const guarded = op.guard !== undefined ? { before } : {};\n if (op.kind === 'delete') {\n return { rows: rows.filter((_, i) => i !== index), outcome: { kind: 'deleted', ...guarded } };\n }\n const row: EntityRow = { ...before, ...op.data, id: op.id };\n return { rows: rows.map((r, i) => (i === index ? row : r)), outcome: { kind: 'updated', row, ...guarded } };\n}\n\nfunction applied(outcome: RowWriteOutcome): boolean {\n return outcome.kind === 'created' || outcome.kind === 'updated' || outcome.kind === 'deleted';\n}\n\nexport interface RowWriteBatchResult {\n rows: EntityRow[];\n outcomes: RowWriteOutcome[];\n}\n\n/** Capabilities of a store that runs every query form, vector search included; a store that cannot rank by similarity overrides `nearest: false`. */\nconst FULL_QUERY_CAPABILITIES: QueryCapabilities = {\n leaves: ['compare', 'member', 'hasElement', 'contains', 'isNull'],\n combinators: ['all', 'any', 'not'],\n compareOps: ['==', '!=', '<', '<=', '>', '>='],\n orderableFields: { kind: 'every-field' },\n window: true,\n exactTotal: true,\n nearest: true,\n};\n\n/** Capabilities for conditional writes, ordered runs and transactional batches; rekey requires an explicit declaration. */\nexport const FULL_WRITE_CAPABILITIES: WriteCapabilities = {\n guards: { leaves: FULL_QUERY_CAPABILITIES.leaves, combinators: FULL_QUERY_CAPABILITIES.combinators, compareOps: FULL_QUERY_CAPABILITIES.compareOps },\n conditional: true,\n returnsRow: true,\n stopRuns: true,\n atomicBatch: true,\n};\n\nexport type QueryUnsupportedReason =\n | 'leaf-unsupported'\n | 'combinator-unsupported'\n | 'value-kind-unsupported'\n | 'order-field'\n | 'window'\n | 'exact-total'\n | 'nearest';\n\nexport type QueryDeclinedReason = QueryUnsupportedReason | 'ids-only';\n\n/** What a store throws when it declines a pushed-down query it cannot run; nothing was read. */\nexport class QueryDeclinedError extends Error {\n readonly reason: QueryDeclinedReason;\n\n constructor(reason: QueryDeclinedReason, message?: string) {\n super(message ?? `query declined: ${reason}`);\n this.name = 'QueryDeclinedError';\n this.reason = reason;\n }\n}\n\nexport type WriteDeclinedReason = 'atomic-batch' | 'no-transaction' | 'guard-value-kind';\n\n/** What a store throws when it declines a pushed-down write shape it did not declare; nothing was written. */\nexport class WriteDeclinedError extends Error {\n readonly reason: WriteDeclinedReason;\n\n constructor(reason: WriteDeclinedReason, message?: string) {\n super(message ?? `write declined: ${reason}`);\n this.name = 'WriteDeclinedError';\n this.reason = reason;\n }\n}\n","import { z } from \"zod\";\nimport { RowQuerySchema } from \"../row-query.js\";\nimport type { RowQuery } from \"../service-types.js\";\nimport type { RuntimeValue } from \"./json.js\";\n\n/**\n * A fetched page by reference: `ids` = the window in order, `total` = matches before the window at\n * dispatch time, `query` = what produced it (its predicates, incl. the @read policy, re-count `total`; order and window are ignored).\n */\nexport interface RowSetRef {\n entityType: string;\n ids: string[];\n total: number;\n query: RowQuery;\n}\n\nexport const RowSetRefSchema: z.ZodType<RowSetRef> = z.object({\n entityType: z.string(),\n ids: z.array(z.string()),\n total: z.number().int().nonnegative(),\n query: RowQuerySchema,\n});\n\n/** Tag property of a `RowSetMarker`; `$`-prefixed so it never collides with a pattern prop key. */\nexport const ROW_SET_MARKER = \"$rowSet\" as const;\n\n/** A render prop leaf resolved to rows at paint time by the kernel (`@read` applied there). */\nexport type RowSetMarker = {\n readonly [ROW_SET_MARKER]: true;\n readonly ref: RowSetRef;\n};\n\nexport function rowSetMarker(ref: RowSetRef): RowSetMarker {\n return { [ROW_SET_MARKER]: true, ref };\n}\n\nexport function isRowSetMarker(value: RuntimeValue): value is RowSetMarker {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n ROW_SET_MARKER in value &&\n value[ROW_SET_MARKER] === true &&\n \"ref\" in value &&\n RowSetRefSchema.safeParse(value.ref).success\n );\n}\n","/**\n * Authenticated user context — what `@user.x` resolves against.\n *\n * The canonical shape for the `user` binding root, shared by both execution\n * paths: the JS interpreter resolves `@user.id` through\n * `EvaluationContext.user`, and the compiled shell emits `user?.id` against the\n * `UserContext` its `@app/shared` re-exports from here.\n *\n * `id` is the field the behavior library reads for ownership scoping and `role`\n * the field it reads for capability gating. Auth providers that name the subject\n * `uid` must normalize at their boundary — {@link normalizeUserContext} does that.\n *\n * @packageDocumentation\n */\n\nimport { z } from 'zod';\nimport { FieldValueSchema, type FieldValue } from './entity.js';\nimport { JsonValueSchema } from './json.js';\nimport type { Claim, Viewer } from '../generated/kernel-wire.js';\n\nexport type { Claim, Viewer };\n\n/**\n * What a host's auth provider has resolved the viewer to be — from session\n * resolution only, never from an interactive sign-in action: `pending` until\n * the session is known; `anonymous` / `authenticated` once it is; `failed`\n * when connecting or resolving the session failed; `unavailable` when the host\n * has no sign-in configured. An `access: authenticated` page mounts only on\n * `authenticated`.\n */\nexport type ViewerAuthority = 'pending' | 'anonymous' | 'authenticated' | 'failed' | 'unavailable';\n\n/**\n * The `@user` binding: a {@link Viewer} held flat. Its named fields are the viewer's; each claim is a key holding its\n * JSON value, readable as `@user.<claim>`. The Rust twin of the conversion is `orbital_core_base::viewer`\n * (`Viewer::from_user` / `Viewer::to_user`).\n */\nexport interface UserContext extends Omit<Viewer, 'claims'> {\n [key: string]: FieldValue | undefined;\n}\n\nconst ClaimSchema: z.ZodType<Claim> = z.object({ name: z.string(), value: JsonValueSchema });\n\n/** Zod twin of the generated {@link Viewer}: the record a `.lolo` program names as `Viewer`. */\nexport const ViewerSchema: z.ZodType<Viewer> = z.object({\n id: z.string(),\n email: z.string().nullish(),\n name: z.string().nullish(),\n role: z.string().optional(),\n permissions: z.array(z.string()).optional(),\n claims: z.array(ClaimSchema),\n});\n\n/**\n * The identity of an unauthenticated viewer. A resolvable object rather than\n * `undefined` so a role predicate evaluates to a definite `false` instead of\n * comparing against nothing.\n */\nexport const ANONYMOUS_USER: UserContext = {\n id: 'anonymous',\n role: 'anonymous',\n permissions: [],\n};\n\n/** Provider-shaped identity claims, before normalization. */\nexport interface RawUserClaims {\n id?: string;\n uid?: string;\n email?: string | null;\n name?: string | null;\n displayName?: string | null;\n /** Absent or `null` when the token carries none, as the kernel's `Viewer.role` (`Option`). */\n role?: string | null;\n permissions?: string[] | null;\n [key: string]: FieldValue | undefined;\n}\n\n/** Zod twin of `RawUserClaims` — the wire shape of `OrbitalEventRequest.user`. */\nexport const RawUserClaimsSchema: z.ZodType<RawUserClaims> = z\n .object({\n id: z.string().optional(),\n uid: z.string().optional(),\n email: z.string().nullable().optional(),\n name: z.string().nullable().optional(),\n displayName: z.string().nullable().optional(),\n role: z.string().nullable().optional(),\n permissions: z.array(z.string()).nullable().optional(),\n })\n .catchall(FieldValueSchema.optional());\n\n/** Claim keys a `null` leaves absent, as the kernel's `Viewer` reads them (`Option`). */\nconst NONE_WHEN_NULL_CLAIM_KEYS: readonly string[] = ['role', 'permissions'];\n\n/** Claim keys {@link normalizeUserContext} derives rather than copies verbatim. */\nconst DERIVED_CLAIM_KEYS: readonly string[] = ['id', 'name', 'displayName', 'email'];\n\n/**\n * Normalize provider claims into a {@link UserContext}.\n *\n * Firebase (and most OIDC providers) name the subject `uid` and the display name\n * `displayName`, while every `.lolo` behavior reads `@user.id` / `@user.name`.\n * Without this normalization `@user.id` is `undefined` against a fully\n * authenticated request and every ownership filter silently matches no rows.\n * `uid` is preserved so `@user.uid` keeps working.\n *\n * Returns `undefined` for absent or subject-less claims so callers can\n * distinguish \"no auth ran\" from \"anonymous\"; use {@link ANONYMOUS_USER} where a\n * definite identity is required.\n */\nexport function normalizeUserContext(\n claims: RawUserClaims | null | undefined,\n): UserContext | undefined {\n if (!claims) return undefined;\n const id = claims.id ?? claims.uid;\n if (typeof id !== 'string' || id.length === 0) return undefined;\n\n const user: UserContext = { id };\n for (const [key, value] of Object.entries(claims)) {\n if (value === undefined || DERIVED_CLAIM_KEYS.includes(key)) continue;\n if (value === null && NONE_WHEN_NULL_CLAIM_KEYS.includes(key)) continue;\n user[key] = value;\n }\n\n const name = claims.name ?? claims.displayName;\n if (typeof name === 'string' && name.length > 0) user.name = name;\n if (typeof claims.email === 'string' && claims.email.length > 0) user.email = claims.email;\n\n return user;\n}\n\n/**\n * Turn a row of an app's `[identity]` entity into a viewer.\n *\n * There is no separate persona shape: an identity row IS the persona\n * (`Almadar_LOLO_Identity.md` §4.3), so this only guards the one field the\n * behavior library requires — a non-empty string `id` — and passes every other\n * declared field through as a `@user.<field>` claim. Rows without a usable id\n * yield `undefined` rather than a persona nobody can own rows as.\n */\nexport function personaFromIdentityRow(\n row: Record<string, FieldValue | undefined>,\n): UserContext | undefined {\n const id = row['id'];\n if (typeof id !== 'string' || id.length === 0) return undefined;\n const persona: UserContext = { id };\n for (const [key, value] of Object.entries(row)) {\n if (key === 'id' || value === undefined) continue;\n persona[key] = value;\n }\n return persona;\n}\n\n/** Look a persona up in a roster by id, or by role when no id matches. */\nexport function findPersonaInRoster(\n roster: readonly UserContext[],\n idOrRole: string,\n): UserContext | undefined {\n return (\n roster.find((p) => p.id === idOrRole) ??\n roster.find((p) => p.role === idOrRole)\n );\n}\n\n/**\n * Resolve a persona spec — a bare id/role (`Person Id 3`, `moderator`) or a full\n * JSON `UserContext` — into a viewer. This is the `ALMADAR_PERSONA` contract,\n * shared by every host that presents an app as somebody.\n *\n * The roster is the app's OWN declared personas — the seeded rows of its\n * `[identity]` entity (`Almadar_LOLO_Identity.md` §4.3) — supplied by the host\n * that has them in hand (the runtime's live store on the interpreter path, the\n * schema-derived seed rows on the compiled path). There is no global roster:\n * an app without an `[identity]` entity resolves only JSON-form specs.\n *\n * Throws on anything unresolvable rather than returning `undefined`: \"no persona\"\n * and \"persona silently ignored\" look identical on screen, so a bad spec must\n * fail at boot instead of rendering as nobody.\n */\nexport function resolvePersonaSpec(spec: string, roster: readonly UserContext[]): UserContext {\n const raw = spec.trim();\n if (!raw.startsWith('{')) {\n const declared = findPersonaInRoster(roster, raw);\n if (!declared) {\n const known = roster.map((p) => `${p.id}/${p.role ?? '-'}`).join(', ');\n throw new Error(\n `Persona \"${raw}\" is not a declared persona id or role. ` +\n (roster.length > 0\n ? `Known: ${known}`\n : 'This app declares no [identity] entity, so only the JSON persona form is accepted.'),\n );\n }\n return declared;\n }\n let claims: RawUserClaims;\n try {\n claims = JSON.parse(raw);\n } catch {\n throw new Error(`Persona is not valid JSON: ${raw}`);\n }\n const user = normalizeUserContext(claims);\n if (!user) {\n throw new Error(`Persona needs an \"id\" (or \"uid\"): ${raw}`);\n }\n return user;\n}\n","/**\n * Server-side effect result — the wire shape a server-executed effect\n * (`SERVER_REPORTED_EFFECTS` in `effect.ts`) reports back to the client,\n * closing the circuit on `OrbitalEventResponse.effectResults`.\n *\n * Promoted from `@almadar/runtime`'s `ServerEffectHandlers.ts` (the JS\n * interpreter's own definition, canonical per `CLAUDE.md`'s \"converge on\n * the TypeScript implementation\" ruling) so `@almadar/core` owns the one\n * shape both execution paths report against.\n *\n * @packageDocumentation\n */\n\nimport { z } from 'zod';\nimport { EntityRowSchema, type EntityRow } from './entity.js';\nimport { SERVER_REPORTED_EFFECTS, type ServerReportedEffect, type NamespacedEffectName } from './effect.js';\nimport { EventPayloadValueSchema, type EventPayloadValue } from './expression.js';\n\n/**\n * Result entry recorded for each effect invocation. Mirrors the server\n * runtime's `EffectResult`. Callers who want telemetry pass an array that\n * the factory appends to; otherwise it's unused.\n */\nexport interface ServerBatchSummary {\n operations: EntityRow[];\n completedCount: number;\n totalCount: number;\n}\n\n/** Zod twin of `ServerBatchSummary`. */\nexport const ServerBatchSummarySchema: z.ZodType<ServerBatchSummary> = z.object({\n operations: z.array(EntityRowSchema),\n completedCount: z.number(),\n totalCount: z.number(),\n});\n\nexport interface ServerEffectResult {\n /**\n * The reported effect's head (`SERVER_REPORTED_EFFECTS`, derived from the\n * effect union in `effect.ts`), or `\"substrate\"` — the one wire grouping\n * for the namespaced operators (`trace/*`, `memory/*`, `session/*`,\n * `behavior/*`, `compose/*`), whose head rides `name`.\n */\n effect: ServerReportedEffect | \"substrate\";\n action?: string;\n entityType?: string;\n /** The invoked namespaced operator (e.g. `\"memory/store\"`), set only on `effect: \"substrate\"`. */\n name?: NamespacedEffectName;\n /** Entity row for CRUD/set/swap, the batch summary for `persist batch`, the raw service/substrate result. */\n data?: EntityRow | ServerBatchSummary | EventPayloadValue;\n success: boolean;\n /**\n * Set when a persist failed because an access policy rejected it or the\n * write resolved no row key — mirrors `OrbitalServerRuntime.EffectResult`\n * so the offline-preview and real-server persist paths report the same\n * denial discriminator to the verification trace.\n */\n denied?: true;\n error?: string;\n /** Coded failure reason for a persist that resolved no target row (`not-found`, `no-row-key`), created on a taken id (`duplicate-id`), or was refused by a declared policy (`denied`, EXEC-STEP-8). */\n code?: \"not-found\" | \"no-row-key\" | \"duplicate-id\" | \"denied\";\n /** What the effect addressed: an `http` effect's `<METHOD> <origin><path>`, an `emit` entry's event name. */\n target?: string;\n /** The declared `emit.failure` event the program routed this effect's failure to; absent when it declares none. */\n routed?: string;\n}\n\n/** Zod twin of `ServerEffectResult`. */\nexport const ServerEffectResultSchema: z.ZodType<ServerEffectResult> = z.object({\n effect: z.union([z.enum(SERVER_REPORTED_EFFECTS), z.literal(\"substrate\")]),\n action: z.string().optional(),\n entityType: z.string().optional(),\n name: z.custom<NamespacedEffectName>((v) => typeof v === \"string\" && /^[^/]+\\/.+$/.test(v)).optional(),\n data: z.union([EntityRowSchema, ServerBatchSummarySchema, EventPayloadValueSchema]).optional(),\n success: z.boolean(),\n denied: z.literal(true).optional(),\n error: z.string().optional(),\n code: z.enum([\"not-found\", \"no-row-key\", \"duplicate-id\", \"denied\"]).optional(),\n target: z.string().optional(),\n routed: z.string().optional(),\n});\n","/**\n * Bus Event Types (framework concept)\n *\n * Canonical event shape for Almadar's cross-package event bus. Hoisted into\n * `@almadar/core` so `@almadar/ui`, `@almadar/runtime`, and generated code\n * all agree on the same structure. Replaces the previously divergent\n * `KFlowEvent` (ui) and `RuntimeEvent` (runtime) definitions.\n *\n * @packageDocumentation\n */\n\nimport { z } from \"zod\";\nimport { EventPayloadSchema, SExprDataSchema, type EventPayload, type SExpr } from \"./expression.js\";\nimport { OrbitalIdSchema, TraitIdSchema, EventIdSchema, type OrbitalId, type TraitId, type EventId } from \"./identity.js\";\nimport { RowSetRefSchema, type RowSetRef } from \"./row-set.js\";\nimport { EntityRowSchema, type EntityRow } from \"./entity.js\";\nimport { PatternConfigSchema, type PatternConfig } from \"./effect.js\";\nimport { RawUserClaimsSchema, type RawUserClaims } from \"./user.js\";\nimport { ServerEffectResultSchema, type ServerEffectResult } from \"./effect-result.js\";\nimport type { ExternalInput } from \"../access/externalInputs.js\";\nimport type { JsonValue } from \"./json.js\";\nimport type { HopObservation, RepaintReason } from \"../generated/kernel-wire.js\";\n\n/**\n * Declared event key. A trait's event names (INIT, SAVE, CLOSE,\n * CONFIRM_REMOVE, ...) flow through the orbital schema and the UI as\n * strings; this alias marks \"this string is a declared event key, not\n * arbitrary text.\"\n *\n * Component props typed as `EventKey` are detected by the pattern-sync\n * tool (`tools/almadar-pattern-sync/parser.ts`) via a TS-type lookup and\n * marked as `kind: \"event\"` in the patterns registry\n * (`@almadar/patterns`). Consumers of the registry — the Rust compiler's\n * inline phase and the `@almadar/runtime` preprocess — read that marker\n * to apply call-site `events: { OLD: NEW }` renames to render-ui trees\n * without name-matching heuristics.\n *\n * Plain alias over `string`. Not branded because event keys originate\n * from user data at runtime (orb schema literals, bus emits), so cast\n * friction would buy nothing. The value of the alias is at the type\n * surface — it's a marker the pattern-sync tool can find via\n * `getSymbolAtLocation`.\n */\nexport type EventKey = string;\n\n/**\n * Phantom-typed brand for declarative bus-emit props on UI components.\n *\n * Used by component authors to BOTH mark a prop as a bus-event reference\n * AND document the payload shape that the component will fire onto the\n * bus when that prop is bound. Authors write:\n *\n * // Tabs.tsx\n * export interface TabsProps {\n * tabChangeEvent?: EventEmit<{ tabId: string }>;\n * }\n *\n * Consumers see only the structural `string` (no UX impact: passing a\n * literal `\"TAB_CHANGED\"` keeps working). The phantom `P` parameter\n * carries the bus-payload schema at the type level for pattern-sync to\n * extract.\n *\n * Pattern-sync (`tools/almadar-pattern-sync/parser.ts`) detects this\n * brand via TS type-lookup (mirrors how it detects `EventKey`) and\n * writes two registry fields per prop:\n * - `kind: \"event-ref\"` — the discriminant rules read in lolo / orb\n * validator to know \"this prop's string value is a bus event name.\"\n * - `emitPayloadSchema` — the structural shape of `P`, serialized as\n * the same JSON-Schema-shaped record Almadar uses for trait\n * `payloadSchema`. Validator rules cross-check this against the\n * trait's declared `emits { EVENT { ... } }` payload to catch mismatches\n * at parse / validate time instead of runtime.\n *\n * Example payload bus emission inside the component (no wrapper —\n * `EventEmit<P>` erases to `string`):\n *\n * if (tabChangeEvent) eventBus.emit(`UI:${tabChangeEvent}`, { tabId });\n *\n * The brand is structurally an unused optional readonly property; TS\n * never asks for it at construction, so authors and consumers never\n * see it.\n */\nexport type EventEmit<P> = string & { readonly __emitPayload?: P };\n\n/**\n * Phantom-typed brand for declarative bus-listen props on UI components.\n *\n * Mirror of `EventEmit<P>`. Used by future patterns where a UI component\n * subscribes to a bus event and forwards its payload upward via prop\n * (e.g. an editor pattern that listens for `EXTERNAL_RESET` and exposes\n * the consumed payload to the parent). Pattern-sync detects this brand\n * the same way as `EventEmit<P>` and writes:\n * - `kind: \"event-listen\"` (or a sub-discriminant of `event-ref`)\n * - `listenPayloadSchema` with the structural shape of `P`\n *\n * Validator rules use this to verify the trait the prop is bound to\n * actually emits a payload of the expected shape.\n *\n * Reserved for symmetry; no @almadar/ui component uses it as of this\n * commit. Add usages incrementally as patterns require them.\n */\nexport type EventListen<P> = string & { readonly __listenPayload?: P };\n\n// NOTE: The phantom entity-inlet brands `EntityInlet`/`EntityRecord`/\n// `EntityCollection` were removed in the entity-row clean slate. There is now\n// ONE entity type — `EntityRow` (`./entity`), used directly: a single record is\n// `EntityRow`, a collection is `readonly EntityRow[]`. pattern-sync detects an\n// entity prop by the `EntityRow` type identity and derives record-vs-collection\n// from array-vs-not, so no brand is needed.\n\n/**\n * Identifies the origin of a bus event. Used by cross-trait listeners to\n * filter emits from specific orbitals, traits, transitions, or ticks.\n *\n * `transition` and `tick` are optional runtime-internal details; most\n * consumers only care about `orbital` and `trait`.\n */\nexport interface BusEventSource {\n orbital?: string;\n /** V4 dual-carry id sibling of `orbital` — stable across an orbital rename. */\n orbitalId?: OrbitalId;\n trait?: string;\n /** V4 dual-carry id sibling of `trait` — stable across a trait rename. */\n traitId?: TraitId;\n /** V4 dual-carry id of the emitted event — stable across an event rename. */\n eventId?: EventId;\n transition?: string;\n tick?: string;\n /**\n * True when the orbital bridge re-broadcasts an event onto the bus\n * (any source — both echoes of the dispatched event and server-side\n * cascade emits via `(emit X)` / `fetch.emit.success`). Cross-trait\n * listeners filter on this flag so the click-time qualified emit\n * (which has no `fromBridge`) doesn't double-fire alongside the\n * post-server bridge confirmation. See `dispatched` for the narrower\n * \"echo of the just-dispatched event\" signal.\n */\n fromBridge?: boolean;\n /**\n * True ONLY for bridge echoes the receiving tab already processed, so\n * the originating trait's self-subscription skips them instead of\n * re-dispatching its own echo (infinite loop / double execution).\n * Set by path 1 of useOrbitalBridge (compiled shell — echo of the\n * just-dispatched event; server-side cascade emits there carry\n * `fromBridge: true` but NOT `dispatched`, so they still reach the\n * source trait's transition handler, e.g. `loading -> browsing` on a\n * fetch's `emit.success`) and by ServerBridge (runtime path — stamped\n * on exactly one response-cascade echo per event the dispatch delivered\n * locally on the bare key, `stampLocallyDeliveredEchoes`; server-only\n * results stay unstamped). Cross-trait `listens` never filter on this\n * flag, so their delivery is unaffected. Push-leg events from OTHER\n * tabs (multiplayer) are never stamped.\n */\n dispatched?: boolean;\n /**\n * The client that originated the dispatch whose effects emitted this\n * event (from `OrbitalEventRequest.clientId`); absent for headless\n * dispatches (ticks, circuit-router probes, walkers). The server-side\n * listens fan-out skips client-originated cascade emits — under dual\n * execution the originating client relays every cascade hop through the\n * bridge itself, so the server dispatching the same hop double-ran it\n * (one Send persisted two rows). Headless topology keeps the fan-out:\n * there is no client to drive the circuit.\n */\n originClientId?: string;\n /**\n * Per-activation key a UI control stamps on the event it emits, so it can\n * show its own busy state for exactly as long as the dispatches that event\n * started are in flight (`@almadar/ui` lib/pendingDispatch). Never set by\n * the bridge or the server.\n */\n pendingKey?: string;\n /**\n * Set by a server-role kernel on a `persist` effect's `emit.success` envelope: the one emit a live-push\n * host (`setLiveBroadcastSink`) also fans out to every other connected client.\n */\n persistSuccess?: boolean;\n}\n\n// The third type param is `object` on schemas nesting a branded-id\n// `.refine(<type predicate>)` field: the refine's parsed INPUT is a plain\n// `string`, not the branded output type, so the input/output-equal default\n// `z.ZodType<T>` mis-typechecks. `object` is what the wire actually carries\n// (a JSON body) — never `unknown`.\n\n/** The delivery a transition is processing: `@event`, and one element of `@prevEvents` (Runtime Spec Clause 5.5). */\nexport interface DeliveryRecord {\n event: string;\n payload?: EventPayload;\n source: BusEventSource;\n}\n\n/** A trait's log so far in a dispatch that began elsewhere (`@prevEvents` / `@prevStates`), carried on the request. */\nexport interface DispatchLog {\n prevEvents: DeliveryRecord[];\n prevStates: string[];\n}\n\n/** The evaluator value of a delivery record: `source` carries exactly the ten `BusEventSource` fields that are set. */\nexport function deliveryRecordValue(record: DeliveryRecord): EventPayload {\n const s = record.source;\n const source: EventPayload = {\n ...(s.orbital !== undefined ? { orbital: s.orbital } : {}),\n ...(s.orbitalId !== undefined ? { orbitalId: s.orbitalId } : {}),\n ...(s.trait !== undefined ? { trait: s.trait } : {}),\n ...(s.traitId !== undefined ? { traitId: s.traitId } : {}),\n ...(s.eventId !== undefined ? { eventId: s.eventId } : {}),\n ...(s.transition !== undefined ? { transition: s.transition } : {}),\n ...(s.tick !== undefined ? { tick: s.tick } : {}),\n ...(s.fromBridge !== undefined ? { fromBridge: s.fromBridge } : {}),\n ...(s.dispatched !== undefined ? { dispatched: s.dispatched } : {}),\n ...(s.originClientId !== undefined ? { originClientId: s.originClientId } : {}),\n };\n return { event: record.event, payload: record.payload ?? null, source };\n}\n\n/** Zod twin of `BusEventSource`. */\nexport const BusEventSourceSchema: z.ZodType<BusEventSource, object> = z.object({\n orbital: z.string().optional(),\n orbitalId: OrbitalIdSchema.optional(),\n trait: z.string().optional(),\n traitId: TraitIdSchema.optional(),\n eventId: EventIdSchema.optional(),\n transition: z.string().optional(),\n tick: z.string().optional(),\n fromBridge: z.boolean().optional(),\n dispatched: z.boolean().optional(),\n originClientId: z.string().optional(),\n pendingKey: z.string().optional(),\n persistSuccess: z.boolean().optional(),\n});\n\n/** Zod twin of `DeliveryRecord`. */\nexport const DeliveryRecordSchema: z.ZodType<DeliveryRecord, object> = z.object({\n event: z.string(),\n payload: EventPayloadSchema.optional(),\n source: BusEventSourceSchema,\n});\n\n/** Zod twin of `DispatchLog`. */\nexport const DispatchLogSchema: z.ZodType<DispatchLog, object> = z.object({\n prevEvents: z.array(DeliveryRecordSchema),\n prevStates: z.array(z.string()),\n});\n\n/**\n * An event flowing on the bus.\n *\n * The `source` field is structured so cross-trait listeners can match\n * `event.source?.orbital === 'X' && event.source?.trait === 'Y'` without\n * parsing a delimiter.\n */\nexport interface BusEvent {\n /** Event type identifier (e.g., 'CartItemLoaded', 'TASK_COMPLETED') */\n type: EventKey;\n /** Optional structured payload */\n payload?: EventPayload;\n /** Timestamp when the event was emitted */\n timestamp: number;\n /** Optional origin info for filtering */\n source?: BusEventSource;\n}\n\n/** Bus event listener callback. */\nexport type BusEventListener = (event: BusEvent) => void;\n\n/** Returned by `on()` / `once()` to detach a listener. */\nexport type Unsubscribe = () => void;\n\n/**\n * One event a transition's effects emitted, carried back to the client to\n * re-dispatch (in order) so the state machine advances through the\n * cascade without server-side recursion. Named/shaped to match the\n * generated compiled-path `EmittedEvent` (orbital-shell-typescript's\n * `shared/types.ts`) so the two execution paths agree on one shape.\n */\nexport interface EmittedEvent {\n event: string;\n payload?: EventPayload;\n source?: BusEventSource;\n}\n\n/** Zod twin of `EmittedEvent`. Third type param `object`, see `BusEventSourceSchema`. */\nexport const EmittedEventSchema: z.ZodType<EmittedEvent, object> = z.object({\n event: z.string(),\n payload: EventPayloadSchema.optional(),\n source: BusEventSourceSchema.optional(),\n});\n\n// ============================================================================\n// Client-effect wire grammar\n// ============================================================================\n\n/**\n * Client-side effect tuple shipped in `OrbitalEventResponse.clientEffects`.\n * Restricted to the effect kinds the client knows how to apply to the\n * UI: render-ui (slot mutation, including the `toast` slot that carries\n * what used to be the separate notify effect) and navigate (route change).\n * Server-only effects (persist, set, fetch, ...) execute on the server and\n * surface their results via `effectResults` and `emittedEvents`, not here.\n *\n * Shape note: `render-ui` takes a slot and a pattern (G-CROSS-257); `navigate`'s\n * optional argument may surface as `null` rather than absent (an empty slot is `null` on the wire: `JSON.stringify` and the Rust serializer both write it). The local union spells those\n * variants out explicitly so consumers (ServerBridge.tsx parser, debugger\n * inspector) get accurate completions instead of `unknown[]`.\n *\n * `slot` is a plain `string` in this wire shape (not `UISlot`'s literal\n * union) because the runtime forwards the raw string from the trait's\n * `(render-ui slot ...)` SExpr without re-validating against the registry —\n * registry validation lives in `orbital validate` / `lolo` parse, not here.\n */\nexport type ClientRenderUITuple = ['render-ui', string, PatternConfig | null];\n\nexport type ClientNavigateTuple =\n | ['navigate', string]\n | ['navigate', string, Record<string, string> | null]\n | ['navigate', string, Record<string, string> | null, { crumb?: string }];\n\nexport type ClientNavigateBackTuple = ['navigate-back'];\n\nexport type ClientEffectTuple =\n | ClientRenderUITuple\n | ClientNavigateTuple\n | ClientNavigateBackTuple;\n\n/** Zod twin of `ClientRenderUITuple`. */\nexport const ClientRenderUITupleSchema = z.tuple([z.literal('render-ui'), z.string(), PatternConfigSchema]);\n\n/** Zod twin of `ClientNavigateTuple` — one variant per fixed arity (2/3/4), unioned. */\nexport const ClientNavigateTupleSchema = z.union([\n z.tuple([z.literal('navigate'), z.string()]),\n z.tuple([z.literal('navigate'), z.string(), z.record(z.string(), z.string()).nullable()]),\n z.tuple([\n z.literal('navigate'),\n z.string(),\n z.record(z.string(), z.string()).nullable(),\n z.object({ crumb: z.string().optional() }),\n ]),\n]);\n\n/** Zod twin of `ClientNavigateBackTuple`. */\nexport const ClientNavigateBackTupleSchema = z.tuple([z.literal('navigate-back')]);\n\n/** Zod twin of `ClientEffectTuple`. */\nexport const ClientEffectTupleSchema: z.ZodType<ClientEffectTuple> = z.union([\n ClientRenderUITupleSchema,\n ClientNavigateTupleSchema,\n ClientNavigateBackTupleSchema,\n]);\n\n// ============================================================================\n// Event dispatch wire (single owner — canonical = the TS runtime)\n// ============================================================================\n\n/**\n * Client → server event dispatch request. The single upstream owner of\n * this shape — both the JS interpreter (`@almadar/runtime`'s\n * `OrbitalEventRequest`) and the compiled path's generated `EventRequest`\n * (orbital-shell-typescript's `shared/types.ts`, mirrored 1:1 in\n * `orbital-core`) carry the same fields, so the two execution paths cannot\n * drift.\n */\nexport interface OrbitalEventRequest {\n event: string;\n /**\n * V4 dual-carry id sibling of `event` — the fired event's id, when known\n * (e.g. threaded from a `listens[].triggersId`). Optional; absent means\n * the state machine dispatches by name only (legacy).\n */\n eventId?: EventId;\n payload?: EventPayload;\n entityId?: string;\n /**\n * Scoped-listen delivery: dispatch to THIS trait only. A listens-matched\n * trigger is addressed to the listening trait; without this, a trigger\n * renamed to INIT broadcast orbital-wide and re-ran every trait's\n * initializer (R-SCOPED-LISTEN-INIT-RENAME-FREEZE re-fire cascade).\n */\n targetTrait?: string;\n /** Provider claims for `@user` bindings, normalized by `normalizeUserContext`. */\n user?: RawUserClaims;\n /** Per-tab client identity (UUID) — excludes this request's origin from live-broadcast delivery. */\n clientId?: string;\n /**\n * The viewer's locale (one of the program's declared `locales`): servers\n * evaluate `i18n/t` and `@locale` with it. Absent means the program's first\n * declared locale.\n */\n locale?: string;\n /**\n * Broadcast-class marker (T6, docs/Almadar_Tick_Loop.md §3a): the name of\n * the tick that emitted this event. Tick-stamped dispatches are\n * latest-state broadcasts — the client fires them without awaiting the\n * response, and the server relays them to OTHER tabs coalesced\n * (newest-per-key) at a snapshot rate instead of 1:1.\n */\n tick?: string;\n /** Emitting trait for a tick-stamped dispatch — builds the relay's BusEventSource (sourceless emits are dropped client-side). */\n sourceTrait?: string;\n /**\n * Run one firing of a tick at the data authority: the trait's tick named `tick` runs its\n * effects there, as `event` + `targetTrait` runs a transition. A browser-run tick sends one\n * for its data effects on browser-stored entities (a tick has no event to replay under);\n * `event` is the tick's synthetic key `$TICK_<tick>`. Owner ruling 2026-10-12 (drift D-1).\n */\n runTick?: { trait: string; tick: string };\n /**\n * Stateless addressing: the traits this dispatch runs against, each with\n * the scope it dispatches `from` (a single-element array is the common\n * case; a listens fan-out that crosses traits carries more than one). The\n * compiled server is stateless-per-trait too (`handlers.rs:510-532` seeds\n * state from `currentState`) — this generalizes that mechanism instead of\n * the retired single `currentState`/`fields` pair. `event` is the event\n * that trait fired on in a cascade (the seed's own is `event` above); where\n * the leg runs follows it.\n */\n traits?: Array<{ trait: string; from: string; event?: string }>;\n /**\n * The dispatching traits' current `@entity` frames (declared defaults <\n * fetched row < `[shared]` frame), keyed by trait name. The server layers\n * each row over the one it resolves via `resolveEntityView` so guards and\n * effects read the same values the client does.\n */\n entityByTrait?: Record<string, EntityRow>;\n /** The orbital/behavior name this dispatch targets, for stateless multi-orbital addressing. */\n behavior?: string;\n /** `@event` for the target when this request continues a dispatch that began on the client; absent = a direct dispatch. */\n delivery?: DeliveryRecord;\n /** The target trait's log so far in that dispatch; absent = empty. */\n dispatchLog?: DispatchLog;\n /**\n * A mount batch: one request mounts several traits of the orbital, each\n * running its OWN lifecycle event, in list order, with the shared\n * `payload`. `traits`/`entityByTrait` keep their stateless-addressing\n * meaning; `event` carries the first seed's event.\n */\n mount?: MountSeed[];\n /** Where this leg runs, set by the kernel (EXEC-DIST-6): `browser` for browser-stored rows only, else `server`. */\n residence?: 'browser' | 'server';\n}\n\n/** The lifecycle events a trait runs when it enters a page (the first it handles). */\n/**\n * Host-level UI events: handled by the app host, never by a trait, so a\n * component inside a trait scope emits them bare (`UI:NAVIGATE`), not\n * qualified to its trait. `NAVIGATE` moves the router; `SIGN_OUT` ends the\n * viewer's session.\n */\nexport const SYSTEM_UI_EVENTS = [\"NAVIGATE\", \"SIGN_OUT\"] as const;\nexport type SystemUiEvent = (typeof SYSTEM_UI_EVENTS)[number];\n\nexport function isSystemUiEvent(event: string): event is SystemUiEvent {\n return (SYSTEM_UI_EVENTS as readonly string[]).includes(event);\n}\n\nexport const LIFECYCLE_EVENTS = [\"INIT\", \"LOAD\", \"$MOUNT\"] as const;\n\n/** Wire-only event a client sends when a trait leaves the page; the server stops counting it as mounted. */\nexport const UNMOUNT_EVENT = '$UNMOUNT';\n\n/** An event key without its `UI:` bus prefix. */\nexport function normalizeEventKey(eventKey: string): string {\n if (!eventKey) return '';\n return eventKey.startsWith('UI:') ? eventKey.slice(3) : eventKey;\n}\n\n/** The event a tick firing carries on the wire (`OrbitalEventRequest.event` of a `runTick` leg). */\nexport function tickEventKey(tickName: string): string {\n return `$TICK_${tickName}`;\n}\nexport type LifecycleEvent = (typeof LIFECYCLE_EVENTS)[number];\n\n/** One trait of a mount batch and the lifecycle event it runs. */\nexport interface MountSeed {\n trait: string;\n event: LifecycleEvent;\n}\n\nexport const MountSeedSchema = z.object({ trait: z.string(), event: z.enum(LIFECYCLE_EVENTS) });\n\n/** Structured reason one trait (or the whole dispatch) did not transition. */\nexport type TransitionRejectionCode =\n | 'no-matching-transition'\n | 'guard-rejected'\n | 'no-dispatchable-traits'\n | 'not-an-external-input'\n | 'inbound-only-event'\n /** An effect of the trait's transition threw; its later effects did not run. */\n | 'effect-failed';\n\n/**\n * A request on the outside-client input channel (`POST /:orbital/inputs`): an\n * API caller, an agent acting as the user, an MCP client. Only an event the\n * target trait declares as an external input (`listens { EVENT -> external { … } }`)\n * is dispatched; anything else is refused with `not-an-external-input`.\n */\nexport interface ExternalInputRequest {\n targetTrait: string;\n event: string;\n payload?: EventPayload;\n user?: RawUserClaims;\n entityId?: string;\n}\n\nexport type EventStreamItem =\n | { type: 'event'; data: EmittedEvent; timestamp: number }\n | { type: 'effect'; data: ClientEffectTuple; timestamp: number }\n | { type: 'complete'; data: OrbitalEventResponse; timestamp: number }\n | { type: 'error'; data: { message: string }; timestamp: number };\n\nexport const EventStreamItemSchema = z.union([\n z.object({ type: z.literal('event'), data: EmittedEventSchema, timestamp: z.number() }),\n z.object({ type: z.literal('effect'), data: ClientEffectTupleSchema, timestamp: z.number() }),\n z.object({ type: z.literal('complete'), data: z.lazy(() => OrbitalEventResponseSchema), timestamp: z.number() }),\n z.object({ type: z.literal('error'), data: z.object({ message: z.string() }), timestamp: z.number() }),\n]);\n\n/** How a host answered a `program/dispatch` event request: the response, or the route's failure code and status. */\nexport type DispatchRequestOutcome =\n | { ok: true; response: OrbitalEventResponse; streamItems?: EventStreamItem[] }\n | { ok: false; error: string; code: string; status: number };\n\n/**\n * What a host lends one service call so the service can act in the running app\n * AS THE CALLER (an agent operating the app for the signed-in user): the\n * declared inputs, the outside-client input channel, and a read that applies the\n * entity's `@read` policy. Built per call, bound to the caller's identity and\n * position; every dispatch is a full, ordinary dispatch (guards, policies,\n * listens). The interpreter and the compiled server each supply one.\n */\nexport interface ServiceHostPorts {\n /** The orbital and trait whose `call-service` is running. */\n caller: { orbital: string; trait: string };\n inputs(): ExternalInput[];\n /** The entities `read` serves: every persisted entity of the program (`readableEntitiesOf`). */\n readableEntities(): string[];\n dispatchInput(orbital: string, request: Omit<ExternalInputRequest, 'user'>): Promise<OrbitalEventResponse>;\n read(entity: string): Promise<EntityRow[]>;\n /**\n * A `program/dispatch` event request (owner, 2026-10-21): dispatch `request` on `orbital` as the HTTP events\n * route does (`input: true` admits only a declared external input, as the inputs route). `request.user` is the\n * dispatch's viewer when the call names one. A host that does not serve event requests leaves it out.\n */\n supportsDispatchStream?: true;\n dispatchRequest?(orbital: string, request: OrbitalEventRequest, input: boolean, stream?: boolean): Promise<DispatchRequestOutcome>;\n /** A `program/dispatch { inbound }` delivery through the inbound route, credential check and answer path. */\n deliverInbound?(name: string, delivery: { headers: Readonly<Record<string, string>>; rawBody: string }): Promise<{ status: number; body: string }>;\n /** The host's last `steps` traced dispatch steps, oldest first; a host that keeps no trace leaves it out. */\n trace?(steps: number): JsonValue[];\n /**\n * Deliver one message of the running call to the caller's tab, live, as the\n * call site's `emit.onMessage` event source-stamped to the caller. A no-op\n * when the call site declares no `onMessage`.\n */\n message(payload: EventPayload): void;\n}\n\n/**\n * Why a dispatched trait (or the whole request) did not transition —\n * G-RUNTIME-023. `statesDeclaringEvent` lists the states whose transition\n * table DOES declare the event, which makes a stale client-supplied `from`\n * self-explanatory in a stateless response.\n */\nexport interface TransitionRejection {\n code: TransitionRejectionCode;\n trait?: string;\n from?: string;\n event?: string;\n statesDeclaringEvent?: string[];\n transition?: string;\n guard?: unknown;\n /** `effect-failed`: the thrown error's message. */\n error?: string;\n}\n\n/** How one authored effect of an executed hop ran. */\nexport type HopEffectStatus = 'executed' | 'failed' | 'skipped';\n\n/** One authored effect of a hop: its operator head, its arguments as authored, and how it ran. */\nexport interface HopEffect {\n type: string;\n args: SExpr[];\n status: HopEffectStatus;\n error?: string;\n}\n\n/**\n * One executed hop of a dispatch (the seed's, a same-trait cascade step's, a listener delivery's), in\n * dispatch order: what a `TransitionObserver` hears. `guardResult` is `true` when the fired arm's guard\n * held and absent for an unguarded arm.\n */\nexport interface TransitionHop {\n trait: string;\n from: string;\n to: string;\n event: string;\n /** The arm that fired, by its position among the state's arms for the event. */\n firedArm?: number;\n guardResult?: boolean;\n effects: HopEffect[];\n /** The payload and `@entity` before and after the hop, when a verifier asked the kernel to record them. */\n observed?: HopObservation;\n}\n\n/**\n * One client effect paired with the trait that produced it and, when the\n * producer knows it, the transition that fired: that transition's own event\n * key (for a listens delivery, the triggered event, not the source emit) and\n * the state it fired from. A client stamps render provenance from these.\n */\nexport interface ClientEffectByTrait {\n traitName: string;\n effect: ClientEffectTuple;\n event?: string;\n fromState?: string;\n /** The payload an embedded `@callsitePayload` child was composed with — sticky, so a later repaint of the child resolves its captures the same way. */\n callsitePayload?: EventPayload;\n /** Set when the paint is a repaint a renderer must act on beyond the content: the rows a reference in it points at changed (EXEC-RENDER-3). */\n repaint?: RepaintReason;\n}\n\n/**\n * Server → client event dispatch response. Mirrors the compiled path's\n * generated `EventResponse` (orbital-shell-typescript's `shared/types.ts`,\n * mirrored 1:1 in `orbital-core`'s `effects/response.rs`) — canonical = the\n * TS runtime's `OrbitalEventResponse` (`@almadar/runtime`'s\n * `OrbitalServerRuntime.ts`).\n */\nexport interface OrbitalEventResponse {\n success: boolean;\n transitioned: boolean;\n /** Whole-orbital state snapshot, keyed by trait name. */\n states: Record<string, string>;\n /**\n * Events emitted during processing, in declaration order. ALWAYS present\n * (`[]` when none) — the compiled Hono path used to omit this field on a\n * no-cascade response, which forced every consumer to optional-chain a\n * field that is really always there.\n *\n * Each entry carries a `source: BusEventSource` so the client-side\n * ServerBridge can re-broadcast on the qualified `UI:Orbital.Trait.EVENT`\n * bus key. Without source the re-broadcast skips the entry and downstream\n * listeners (e.g. ContactBrowse waiting for ContactLoaded after a fetch)\n * never fire — the dashboard-layout that ContactLoaded renders disappears.\n */\n emittedEvents: EmittedEvent[];\n /** Fetched/queried entity collections this response carries, keyed by entity name. */\n data?: Record<string, EntityRow[]>;\n /** Fetched pages delivered by reference (`deliver: ids`), keyed by entity name. */\n dataRefs?: Record<string, RowSetRef>;\n /**\n * `@entity` fields this transition's server-side `set` effects wrote,\n * post-effect, keyed by trait name — the response-side twin of the\n * request's `entityByTrait`. The client merges them over its own effect\n * results (server wins).\n */\n entityByTrait?: Record<string, EntityRow>;\n /** Client-side effects to execute (render-ui, navigate). */\n clientEffects?: ClientEffectTuple[];\n /**\n * Same effects as `clientEffects`, paired with the producing trait name.\n * Consumers that need per-trait attribution (e.g. `<TraitFrame>` resolving\n * `@trait.X` bindings) read from this field; legacy consumers ignore it\n * and continue with the flat `clientEffects` array unchanged.\n *\n * Same length and ordering as `clientEffects`; entries are 1:1 by index.\n */\n clientEffectsByTrait?: ClientEffectByTrait[];\n /** Results from server-side effects (persist, call-service, set). */\n effectResults?: ServerEffectResult[];\n /** Guard that failed, addressed as `\"<Trait>.<event>\"`, for debugging. */\n guardFailed?: string;\n /**\n * Structured per-trait / per-request rejection reasons (G-RUNTIME-023) —\n * present only when nothing transitioned. Supersedes the `guardFailed`\n * string (kept for backcompat) with a machine-readable shape.\n */\n rejections?: TransitionRejection[];\n /**\n * Names of traits DROPPED from a stateless cascade because the cross-trait\n * worklist hit its safety-valve cap (G-RUNTIME-027) — the response's\n * states/effects/entity rows are INCOMPLETE for these traits. Absent when\n * the whole worklist ran. Surfaced so the truncation is observable\n * (previously the tail of any page over ~20 traits silently never\n * executed).\n */\n cascadeTruncated?: string[];\n /** Every executed hop of the dispatch, in order (the server role's trace); absent when none ran. */\n transitions?: TransitionHop[];\n error?: string;\n}\n\n/** Zod twin of `OrbitalEventRequest`. Third type param `object`, see `BusEventSourceSchema`. */\nexport const OrbitalEventRequestSchema: z.ZodType<OrbitalEventRequest, object> = z.object({\n event: z.string(),\n eventId: EventIdSchema.optional(),\n payload: EventPayloadSchema.optional(),\n entityId: z.string().optional(),\n targetTrait: z.string().optional(),\n user: RawUserClaimsSchema.optional(),\n clientId: z.string().optional(),\n locale: z.string().optional(),\n tick: z.string().optional(),\n sourceTrait: z.string().optional(),\n runTick: z.object({ trait: z.string(), tick: z.string() }).optional(),\n traits: z.array(z.object({ trait: z.string(), from: z.string() })).optional(),\n entityByTrait: z.record(z.string(), EntityRowSchema).optional(),\n behavior: z.string().optional(),\n delivery: DeliveryRecordSchema.optional(),\n dispatchLog: DispatchLogSchema.optional(),\n mount: z.array(MountSeedSchema).optional(),\n});\n\n/** Zod twin of `OrbitalEventResponse`. Third type param `object`, see `BusEventSourceSchema`. */\nexport const OrbitalEventResponseSchema: z.ZodType<OrbitalEventResponse, object> = z.object({\n success: z.boolean(),\n transitioned: z.boolean(),\n states: z.record(z.string(), z.string()),\n emittedEvents: z.array(EmittedEventSchema),\n data: z.record(z.string(), z.array(EntityRowSchema)).optional(),\n dataRefs: z.record(z.string(), RowSetRefSchema).optional(),\n entityByTrait: z.record(z.string(), EntityRowSchema).optional(),\n clientEffects: z.array(ClientEffectTupleSchema).optional(),\n clientEffectsByTrait: z\n .array(z.object({\n traitName: z.string(),\n effect: ClientEffectTupleSchema,\n event: z.string().optional(),\n fromState: z.string().optional(),\n callsitePayload: EventPayloadSchema.optional(),\n repaint: z.literal(\"rows-changed\").optional(),\n }))\n .optional(),\n effectResults: z.array(ServerEffectResultSchema).optional(),\n guardFailed: z.string().optional(),\n rejections: z\n .array(\n z.object({\n code: z.enum(['no-matching-transition', 'guard-rejected', 'no-dispatchable-traits', 'not-an-external-input', 'inbound-only-event', 'effect-failed']),\n trait: z.string().optional(),\n from: z.string().optional(),\n event: z.string().optional(),\n statesDeclaringEvent: z.array(z.string()).optional(),\n transition: z.string().optional(),\n guard: z.unknown().optional(),\n error: z.string().optional(),\n }),\n )\n .optional(),\n cascadeTruncated: z.array(z.string()).optional(),\n transitions: z\n .array(\n z.object({\n trait: z.string(),\n from: z.string(),\n to: z.string(),\n event: z.string(),\n guardResult: z.boolean().optional(),\n effects: z.array(\n z.object({\n type: z.string(),\n args: z.array(SExprDataSchema),\n status: z.enum(['executed', 'failed', 'skipped']),\n error: z.string().optional(),\n }),\n ),\n }),\n )\n .optional(),\n error: z.string().optional(),\n});\n\n// ============================================================================\n// Register wire (client → server schema registration)\n// ============================================================================\n\n/**\n * Where circuit state lives between events (`docs/Almadar_Runtime_Stateless_Stateful_PLAN.md` §1a):\n * `'stateless'` = the client carries it on every request, `'stateful'` = the server holds it.\n */\nexport type ServerTopology = 'stateless' | 'stateful';\n\nexport const ServerTopologySchema = z.enum(['stateless', 'stateful']);\n\n/** `POST /register` response. `topology` absent = a server that predates the declaration. */\nexport interface OrbitalRegisterResponse {\n success: boolean;\n topology?: ServerTopology;\n message?: string;\n orbitals?: string[];\n error?: string;\n}\n\nexport const OrbitalRegisterResponseSchema: z.ZodType<OrbitalRegisterResponse, object> = z.object({\n success: z.boolean(),\n topology: ServerTopologySchema.optional(),\n message: z.string().optional(),\n orbitals: z.array(z.string()).optional(),\n error: z.string().optional(),\n});\n\n// ============================================================================\n// Live broadcast wire (server → other connected clients)\n// ============================================================================\n\n/**\n * One persist-envelope success emit, handed to the live-broadcast sink\n * (`OrbitalServerRuntime.setLiveBroadcastSink`) and relayed to every OTHER\n * connected client. Fired only from the `persist` effect's `emit:{success}`\n * envelope (batch and single-op) — never from the generic emit funnel — so\n * transport layers can fan it out without matching on event names. Promoted\n * from `@almadar/runtime`'s own `LiveBroadcastItem` (canonical per Program\n * A's \"converge on the TS runtime\" ruling) so `orbital-server`'s `GET\n * /api/events` broadcast mirrors the same shape.\n */\nexport interface LiveBroadcastItem {\n event: string;\n payload?: EventPayload;\n source: BusEventSource;\n /** `clientId` of the request that produced this emit; excluded from delivery by the transport. */\n originClientId?: string;\n}\n\n/** Zod twin of `LiveBroadcastItem`. Third type param `object`, see `BusEventSourceSchema`. */\nexport const LiveBroadcastItemSchema: z.ZodType<LiveBroadcastItem, object> = z.object({\n event: z.string(),\n payload: EventPayloadSchema.optional(),\n source: BusEventSourceSchema,\n originClientId: z.string().optional(),\n});\n\n/** @deprecated use {@link OrbitalEventRequest}. Kept until every referrer migrates (Program A wave A8). */\nexport type EventDispatchRequest = OrbitalEventRequest;\n\n/** @deprecated use {@link OrbitalEventRequestSchema}. */\nexport const EventDispatchRequestSchema = OrbitalEventRequestSchema;\n\n/** @deprecated use {@link OrbitalEventResponse}. Kept until every referrer migrates (Program A wave A8). */\nexport type EventDispatchResponse = OrbitalEventResponse;\n\n/** @deprecated use {@link OrbitalEventResponseSchema}. */\nexport const EventDispatchResponseSchema = OrbitalEventResponseSchema;\n"]}