@almadar/core 11.3.0 → 11.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/behavior-package.js +1 -3
- package/dist/{builders-DXPLnmJy.d.ts → builders-JiXD6W1T.d.ts} +2266 -98
- package/dist/builders.d.ts +5 -5
- package/dist/builders.js +8 -10
- package/dist/{bus-CRxTnebm.d.ts → bus-__zVNcsp.d.ts} +133 -438
- package/dist/{chunk-DNS4GKQV.js → chunk-27Y5AXHB.js} +71 -45
- package/dist/chunk-2WLRKYD5.js +3823 -0
- package/dist/{chunk-B4MNHGBP.js → chunk-5IRZ6ROW.js} +0 -2
- package/dist/{chunk-7NDAXM2Z.js → chunk-6XYHVJ4J.js} +1 -3
- package/dist/{chunk-RGACZEYC.js → chunk-DDBAQMWA.js} +0 -2
- package/dist/{chunk-7GHJU5WI.js → chunk-GNLND5O2.js} +0 -2
- package/dist/{chunk-M4S2B5VJ.js → chunk-IU3WGC6Q.js} +0 -2
- package/dist/{chunk-LPJ7GKRM.js → chunk-J64IR3DR.js} +17 -9
- package/dist/{chunk-PYYHDYTD.js → chunk-J64YVVB4.js} +1 -3
- package/dist/{chunk-7B4JRMRL.js → chunk-JN3MMQTB.js} +15 -7
- package/dist/{chunk-VIHQKKTZ.js → chunk-LQZXCL47.js} +66 -32
- package/dist/{chunk-6H3UIZR2.js → chunk-OQ3Y5SL3.js} +4 -6
- package/dist/{chunk-3DZOFI53.js → chunk-Q4OJQNYY.js} +5 -4
- package/dist/{chunk-347APWFM.js → chunk-R3Y7ABF4.js} +2 -4
- package/dist/{chunk-N3CK4AYW.js → chunk-VC3HXUWQ.js} +7929 -404
- package/dist/{chunk-2NKK2X53.js → chunk-VQWE3FCB.js} +1 -3
- package/dist/{chunk-VG7BRFUD.js → chunk-W3UJRSYC.js} +0 -2
- package/dist/{chunk-XBWV3DXX.js → chunk-XYHBAUWE.js} +242 -10
- package/dist/{effect-C2VKm6kk.d.ts → effect-gddySYLX.d.ts} +215 -18
- package/dist/{effect-result-BFNANDJ-.d.ts → effect-result-BvBwmspK.d.ts} +131 -43
- package/dist/{expression-DirYKz-f.d.ts → expression-DxY6ct3t.d.ts} +1 -1
- package/dist/factory/index.d.ts +3 -3
- package/dist/factory/index.js +8 -10
- package/dist/factory-runtime/index.d.ts +3 -3
- package/dist/factory-runtime/index.js +15 -17
- package/dist/fixtures.d.ts +8 -7
- package/dist/fixtures.js +6 -8
- package/dist/i18n/index.js +2 -4
- package/dist/{index-DuHpwitt.d.ts → index-h6KrpmjR.d.ts} +23 -10
- package/dist/index.d.ts +15 -17
- package/dist/index.js +23 -25
- package/dist/kernel-wire.d.ts +3 -3
- package/dist/kernel-wire.js +3 -5
- package/dist/language/constructs.json +18 -3
- package/dist/language/program-types.json +28 -1
- package/dist/language/validation-codes.json +231 -1
- package/dist/language/vocabulary.json +63 -1
- package/dist/language-data.js +3 -5
- package/dist/lolo-document/index.js +0 -2
- package/dist/patterns/component-mapping.json +11 -1
- package/dist/patterns/definitions.d.ts +2 -2
- package/dist/patterns/definitions.js +1 -3
- package/dist/patterns/event-contracts.json +1 -1
- package/dist/patterns/index.d.ts +47 -3
- package/dist/patterns/index.js +3 -5
- package/dist/patterns/patterns-registry.json +7929 -402
- package/dist/patterns/registry.json +7929 -402
- package/dist/themes/index.js +2 -4
- package/dist/{trait-Cv3HTGFL.d.ts → trait-Oun4JgeZ.d.ts} +52 -22
- package/dist/types/index.d.ts +8 -8
- package/dist/types/index.js +12 -14
- package/dist/{types-wWEqi7vj.d.ts → types-B-r7Z7Lf.d.ts} +3 -3
- package/package.json +6 -6
- package/dist/behavior-package.js.map +0 -1
- package/dist/builders.js.map +0 -1
- package/dist/chunk-2NKK2X53.js.map +0 -1
- package/dist/chunk-347APWFM.js.map +0 -1
- package/dist/chunk-3DZOFI53.js.map +0 -1
- package/dist/chunk-6H3UIZR2.js.map +0 -1
- package/dist/chunk-7B4JRMRL.js.map +0 -1
- package/dist/chunk-7GHJU5WI.js.map +0 -1
- package/dist/chunk-7NDAXM2Z.js.map +0 -1
- package/dist/chunk-B4MNHGBP.js.map +0 -1
- package/dist/chunk-DNS4GKQV.js.map +0 -1
- package/dist/chunk-LPJ7GKRM.js.map +0 -1
- package/dist/chunk-M4S2B5VJ.js.map +0 -1
- package/dist/chunk-N3CK4AYW.js.map +0 -1
- package/dist/chunk-PYYHDYTD.js.map +0 -1
- package/dist/chunk-RGACZEYC.js.map +0 -1
- package/dist/chunk-VG7BRFUD.js.map +0 -1
- package/dist/chunk-VIHQKKTZ.js.map +0 -1
- package/dist/chunk-XBWV3DXX.js.map +0 -1
- package/dist/chunk-ZDIHVDTW.js +0 -3810
- package/dist/chunk-ZDIHVDTW.js.map +0 -1
- package/dist/factory/index.js.map +0 -1
- package/dist/factory-runtime/index.js.map +0 -1
- package/dist/fixtures.js.map +0 -1
- package/dist/i18n/index.js.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/kernel-wire.js.map +0 -1
- package/dist/language-data.js.map +0 -1
- package/dist/lolo-document/index.js.map +0 -1
- package/dist/patterns/definitions.js.map +0 -1
- package/dist/patterns/index.js.map +0 -1
- package/dist/themes/index.js.map +0 -1
- package/dist/types/index.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/builders/apply-config-overrides.ts","../src/builders/layout-trait.ts","../src/builders.ts"],"names":[],"mappings":";;;AAoBA,SAAS,aAAA,CAAc,OAAkC,MAAA,EAAgD;AACvG,EAAA,IAAI,aAAA,CAAc,KAAK,CAAA,EAAG;AAExB,IAAA,MAAM,SAAS,KAAA,CAAM,MAAA;AACrB,IAAA,IAAI,MAAA,KAAW,QAAW,OAAO,KAAA;AACjC,IAAA,MAAM,IAAA,GAA+C,EAAE,GAAG,MAAA,EAAO;AACjE,IAAA,KAAA,MAAW,CAAC,KAAA,EAAO,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,MAAM,CAAA,EAAG;AACnD,MAAA,MAAM,I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,QACV,KAAA,EAAO;AAAA,OACT;AACA,MAAA,MAAA,CAAO,UAAU,CAAC,GAAI,OAAO,OAAA,IAAW,IAAK,QAAQ,CAAA;AAAA,IACvD;AAAA,EACF;AAGA,EAAA,MAAM,KAAA,GAAgB,MAAA,CAAO,GAAA,CAAI,CAAC,GAAG,CAAA,KAAM;AACzC,IAAA,MAAM,UAAA,GAAa,2BAAA,CAA4B,CAAA,CAAE,MAAM,CAAA;AACvD,IAAA,MAAM,aAAc,CAAA,CAAE,MAAA,CAAmB,GAAA,CAAI,CAAA,CAAA,KAAK,EAAE,IAAI,CAAA;AACxD,IAAA,OAAO;AAAA,MACL,IAAA,EAAM,GAAG,UAAU,CAAA,IAAA,CAAA;AAAA,MACnB,MAAM,CAAA,CAAA,EAAI,MAAA,CAAO,UAAU,CAAA,CAAE,aAAa,CAAA,CAAA;AAAA,MAC1C,GAAI,CAAA,KAAM,CAAA,GAAI,EAAE,SAAA,EAAW,IAAA,KAAS,EAAC;AAAA,MACrC,QAAQ,UAAA,CAAW,GAAA,CAAI,CAAA,GAAA,MAAQ,EAAE,KAAI,CAAE;AAAA,KACzC;AAAA,EACF,CAAC,CAAA;AAGD,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,MAAA,CAAO,QAAQ,CAAA,EAAA,EAAK;AACtC,IAAA,MAAA,CAAO,CAAC,CAAA,CAAE,KAAA,GAAQ,CAAC,KAAA,CAAM,CAAC,CAAC,CAAA;AAAA,EAC7B;AAEA,EAAA,OAAO;AAAA,IACL,MAAM,OAAA,IAAW,aAAA;AAAA,IACjB,OAAA,EAAS,OAAA;AAAA,IACT,QAAA,EAAU;AAAA,GACZ;AACF","file":"chunk-2NKK2X53.js","sourcesContent":["/**\n * Apply trait config overrides to a schema — pure, returns a new schema.\n *\n * Used by config-driven preview surfaces (the playground property inspector and\n * the verify config-sweep) to render a behavior with different `config` values\n * WITHOUT recompiling: the override is written onto the matching trait, then the\n * schema is re-registered and re-rendered.\n *\n * The resolved schema's traits are inlined `Trait`s whose `config` is the\n * DECLARED schema (`{ field: { type, default, ... } }`), so an override patches\n * each field's `default`. A trait that instead carries call-site value config\n * (a `{ ref, config }` reference) gets the values merged directly.\n *\n * @packageDocumentation\n */\n\nimport type { OrbitalSchema } from '../types/schema.js';\nimport type { TraitRef, TraitConfig, ConfigFieldDeclaration } from '../types/trait.js';\nimport { isInlineTrait, mergeCallSiteConfigOverrides } from '../types/trait.js';\n\nfunction overrideTrait(trait: Exclude<TraitRef, string>, values: TraitConfig): Exclude<TraitRef, string> {\n if (isInlineTrait(trait)) {\n // Inlined Trait: `config` is the DECLARED schema → patch each field's `default`.\n const config = trait.config;\n if (config === undefined) return trait;\n const next: Record<string, ConfigFieldDeclaration> = { ...config };\n for (const [field, value] of Object.entries(values)) {\n const decl = config[field];\n if (decl !== undefined) {\n next[field] = { ...decl, default: value };\n }\n }\n return { ...trait, config: next };\n }\n\n return { ...trait, config: mergeCallSiteConfigOverrides(trait.config ?? {}, values) };\n}\n\nfunction traitIdentity(trait: Exclude<TraitRef, string>): string | undefined {\n if (trait.name !== undefined) return trait.name;\n return 'ref' in trait ? trait.ref : undefined;\n}\n\n/**\n * Return a new schema with `config` overrides applied to traits whose identity\n * (`name`, falling back to `ref`) matches a key in `overrides`. Fields not\n * declared on the trait are ignored — overrides never invent config.\n */\nexport function applyTraitConfigOverrides(\n schema: OrbitalSchema,\n overrides: Readonly<Record<string, TraitConfig>>,\n): OrbitalSchema {\n if (overrides === undefined || Object.keys(overrides).length === 0) return schema;\n return {\n ...schema,\n orbitals: schema.orbitals.map((orbital) => ({\n ...orbital,\n traits: orbital.traits.map((trait) => {\n if (typeof trait === 'string') return trait;\n const id = traitIdentity(trait);\n const values = id !== undefined ? overrides[id] : undefined;\n return values !== undefined ? overrideTrait(trait, values) : trait;\n }),\n })),\n };\n}\n","/**\n * Layout-Trait Builders\n *\n * Helpers for constructing the canonical inline LayoutTrait pattern that\n * std layout-shell molecules (`std-filtered-list`, `std-master-detail-layout`,\n * etc.) use to wrap a set of atom trait references in a `(render-ui main)`\n * effect with `@trait.X` slot embeds.\n *\n * The canonical LayoutTrait is stateless: ONE state (`composing`, initial),\n * ONE transition (`INIT` self-loop) carrying two effects — `(fetch Entity\n * {emit: {success, failure}})` and `(render-ui \"main\" <pattern-tree>)`. Atoms\n * embedded via `@trait.X` slot references react to the bus events the fetch\n * emits; the LayoutTrait owns no further state.\n *\n * Usage from a std layout-shell molecule:\n *\n * ```ts\n * import { makeSlot, makeLayoutTrait } from '@almadar/core/builders';\n *\n * const layout = makeLayoutTrait({\n * name: 'DashboardLayout',\n * linkedEntity: 'Metric',\n * fetchEntity: 'Metric',\n * loadedEvent: 'MetricLoaded',\n * loadFailedEvent: 'MetricLoadFailed',\n * renderUI: {\n * type: 'stack',\n * direction: 'vertical',\n * children: [\n * makeSlot('StatsRow'),\n * makeSlot('ChartsRow'),\n * makeSlot('FeedRow'),\n * ],\n * },\n * });\n * ```\n *\n * @packageDocumentation\n */\n\nimport type { AnyPatternConfig } from '../patterns/index.js';\nimport type { Trait } from '../types/trait.js';\nimport type { Effect, FetchEffect, RenderBinding, RenderUIEffect, UISlot } from '../types/effect.js';\n\n/**\n * Build a `@trait.<name>` slot reference string. Used as a child entry in a\n * pattern tree to embed another trait's render-ui at that position. The\n * runtime resolves `@trait.X` to the matching trait's render-ui inline.\n *\n * @example makeSlot('FilteredItemSearch') // \"@trait.FilteredItemSearch\"\n */\nexport function makeSlot(traitName: string): string {\n return `@trait.${traitName}`;\n}\n\n/**\n * Build a `(render-ui <slot> <root>)` effect tuple. Pattern-typed sugar over\n * the raw `RenderUIEffect` literal so callers don't have to spell out the\n * three-element tuple form.\n *\n * @param slot - Canonical UI slot name (`'main'`, `'header'`, etc. — see UI_SLOTS).\n * @param root - The pattern config for this slot's content, OR a `@`-binding\n * string ({@link RenderBinding}) pointing at a render tree in `config` /\n * `payload` (e.g. `'@config.bodyContent'`). Pass `null` to clear.\n */\nexport function makeRenderUI(\n slot: UISlot,\n root: AnyPatternConfig | RenderBinding | null,\n): RenderUIEffect {\n // Branch the return so TS narrows into the correct tuple variant of the\n // RenderUIEffect union (each arm is a distinct tuple shape).\n if (root === null) return ['render-ui', slot, null];\n if (typeof root === 'string') return ['render-ui', slot, root];\n return ['render-ui', slot, root];\n}\n\n/**\n * Options for {@link makeLayoutTrait}.\n */\nexport interface MakeLayoutTraitOpts {\n /** Trait name, e.g. `\"DashboardGridLayout\"`. */\n name: string;\n /** Entity this layout's emits/listens bind to. */\n linkedEntity: string;\n /** Optional human-readable description (carried through to `Trait.description`). */\n description?: string;\n /**\n * Entity name to fetch on INIT. When set, a `(fetch <Entity> {emit:\n * {success, failure}})` effect is prepended to the INIT transition. Omit\n * for purely-presentational layouts that don't load data themselves.\n */\n fetchEntity?: string;\n /**\n * Event name emitted on successful fetch. Required when `fetchEntity` is\n * set; the LayoutTrait declares this event in its `emits` and uses it as\n * the `success` emit-name in the fetch effect.\n * Convention: `\"<Entity>Loaded\"`.\n */\n loadedEvent?: string;\n /**\n * Event name emitted on fetch failure. Required when `fetchEntity` is\n * set. Convention: `\"<Entity>LoadFailed\"`.\n */\n loadFailedEvent?: string;\n /**\n * Payload schema for the loaded event. Defaults to `[{ name: \"data\", type:\n * \"[<Entity>]\" }]` when `fetchEntity` is set. Provide explicitly when the\n * payload should carry additional fields.\n */\n loadedPayloadSchema?: Array<{ name: string; type: string; required?: boolean }>;\n /**\n * The pattern tree for the layout's main slot. Children may include\n * `@trait.X` slot strings (built via {@link makeSlot}) interleaved with\n * inline pattern configs (`{ type: 'stack', ... }`). The shape conforms to\n * `AnyPatternConfig` from `@almadar/patterns`.\n */\n renderUI: AnyPatternConfig;\n /**\n * Override the slot the render-ui effect targets. Defaults to `'main'`.\n * Specify when the layout shell should render into a sub-slot (rare).\n */\n slot?: UISlot;\n /**\n * Additional effects appended to the INIT transition AFTER the fetch +\n * render-ui pair. Most layouts don't need this; provided for advanced\n * cases (analytics emit, persistence seed, etc.).\n */\n extraEffects?: Effect[];\n}\n\n/**\n * Build the canonical stateless LayoutTrait used by std layout-shell molecules.\n *\n * Result shape:\n * - `linkedEntity` set per the option\n * - `emits` declares the loaded + loadFailed events when `fetchEntity` is set\n * - One state: `'composing'` (`isInitial: true`)\n * - One transition: `composing → composing` on `INIT`, with effects:\n * - (when `fetchEntity` set) `['fetch', '<Entity>', { emit: { success, failure } }]`\n * - `['render-ui', slot, renderUI]`\n * - …`extraEffects` if provided\n *\n * Atoms whose trait names appear as `@trait.<name>` strings inside `renderUI`\n * get embedded by the runtime when the orbital instantiates. The LayoutTrait\n * itself stays stateless — all reactive behaviour lives in the embedded atoms.\n */\nexport function makeLayoutTrait(opts: MakeLayoutTraitOpts): Trait {\n const slot: UISlot = opts.slot ?? 'main';\n const effects: Effect[] = [];\n\n // Build emits list based on fetch configuration.\n const emits: Trait['emits'] = [];\n const eventDefs: NonNullable<Trait['stateMachine']>['events'] = [\n { key: 'INIT', name: 'Initialize' },\n ];\n\n if (opts.fetchEntity) {\n if (!opts.loadedEvent || !opts.loadFailedEvent) {\n throw new Error(\n `makeLayoutTrait: fetchEntity '${opts.fetchEntity}' set but loadedEvent / loadFailedEvent are required`,\n );\n }\n const payloadSchema =\n opts.loadedPayloadSchema ?? [{ name: 'data', type: `[${opts.fetchEntity}]` }];\n emits.push(\n { event: opts.loadedEvent, scope: 'internal', payloadSchema },\n {\n event: opts.loadFailedEvent,\n scope: 'internal',\n payloadSchema: [\n { name: 'error', type: 'string' },\n { name: 'code', type: 'string' },\n ],\n },\n );\n eventDefs.push(\n { key: opts.loadedEvent, name: `${opts.fetchEntity} loaded`, payloadSchema },\n {\n key: opts.loadFailedEvent,\n name: `${opts.fetchEntity} load failed`,\n payloadSchema: [\n { name: 'error', type: 'string' },\n { name: 'code', type: 'string' },\n ],\n },\n );\n // (fetch <Entity> { emit: { success, failure } })\n const fetchFx: FetchEffect = [\n 'fetch',\n opts.fetchEntity,\n { emit: { success: opts.loadedEvent, failure: opts.loadFailedEvent } },\n ];\n effects.push(fetchFx);\n }\n\n effects.push(makeRenderUI(slot, opts.renderUI));\n if (opts.extraEffects && opts.extraEffects.length > 0) {\n effects.push(...opts.extraEffects);\n }\n\n const trait: Trait = {\n name: opts.name,\n ...(opts.description ? { description: opts.description } : {}),\n linkedEntity: opts.linkedEntity,\n ...(emits.length > 0 ? { emits } : {}),\n stateMachine: {\n states: [{ name: 'composing', isInitial: true }],\n events: eventDefs,\n transitions: [\n {\n from: 'composing',\n to: 'composing',\n event: 'INIT',\n effects,\n },\n ],\n },\n };\n\n return trait;\n}\n","/**\n * Orbital Builders\n *\n * Pure functions for constructing and composing Orbitals.\n * No new types. Everything uses existing core types:\n * Entity, Trait, Page, OrbitalDefinition, OrbitalSchema.\n *\n * Three categories:\n * 1. Builders: construct Entity, Page from common params\n * 2. Utilities: ensureIdField, resolveDefaults\n * 3. Composition: connect, compose, pipe\n *\n * @packageDocumentation\n */\n\nimport type { Entity, EntityPersistence, EntityRow } from './types/entity.js';\nimport type { EntityField } from './types/field.js';\nimport type { Page } from './types/page.js';\nimport type { EntityRef, ExpectDeclaration, OrbitalDefinition, OrbitalRefTraitOverride, PageRef, PageRefObject, UseDeclaration } from './types/orbital.js';\nimport { isEntityCall, isEntityReference, parseEntityRef } from './types/orbital.js';\nimport type { OrbitalSchema } from './types/schema.js';\nimport type { TraitEventContract, TraitEventListener, Trait, TraitRef, TraitReference, TraitConfig, CallSiteConfig, DeclaredTraitConfig } from './types/trait.js';\nimport type { SExpr } from './types/expression.js';\nimport type { RuntimeValue } from './types/json.js';\nimport { isOrbitalValue, OrbitalValueSchema, type OrbitalValue } from './types/behavior-value.js';\nimport { mergeCallSiteConfigOverrides } from './types/trait.js';\nimport { parseOrbitalSchema } from './types/schema.js';\nimport type { EntityId } from './types/identity.js';\n\nexport { applyTraitConfigOverrides } from './builders/apply-config-overrides.js';\nexport type { LayoutStrategy } from './builders/layout-strategy.js';\nexport type { EventWiringEntry } from './builders/event-wiring.js';\n// LayoutTrait + slot-embedding helpers (Phase 7.6 — atom-composition recipe path).\nexport {\n type MakeLayoutTraitOpts,\n makeSlot,\n makeRenderUI,\n makeLayoutTrait,\n} from './builders/layout-trait.js';\n\n// ============================================================================\n// Utilities\n// ============================================================================\n\n/**\n * Ensure the fields array has an `id` field. Prepends one if missing.\n */\nexport function ensureIdField(fields?: EntityField[]): EntityField[] {\n if (!fields || fields.length === 0) return [{ name: 'id', type: 'string', required: true }];\n if (fields.some(f => f.name === 'id')) return fields;\n return [{ name: 'id', type: 'string', required: true }, ...fields];\n}\n\n/**\n * Simple pluralization: append 's'.\n */\nexport function plural(name: string): string {\n return name + 's';\n}\n\n/**\n * Resolve a printable entity name from any EntityRef shape.\n *\n * Handles:\n * - inline Entity object (uses `name`)\n * - bare string reference like \"Modal.entity\" (uses the alias)\n * - EntityCall { extends: \"Modal.entity\", name? } (uses `name` if set, else the alias)\n */\nfunction resolveEntityNameForBuilder(ref: EntityRef): string {\n if (isEntityReference(ref)) {\n return parseEntityRef(ref)?.alias ?? ref;\n }\n if (isEntityCall(ref)) {\n if (ref.name) return ref.name;\n return parseEntityRef(ref.extends)?.alias ?? ref.extends;\n }\n return ref.name;\n}\n\n// ============================================================================\n// Entity Builder\n// ============================================================================\n\nexport interface MakeEntityOpts {\n name: string;\n fields: EntityField[];\n persistence?: EntityPersistence;\n collection?: string;\n /** Pre-authored seed data instances */\n instances?: EntityRow[];\n}\n\n/**\n * Build an Entity from options. Auto-adds id field, auto-derives collection.\n */\nexport function makeEntity(opts: MakeEntityOpts): Entity {\n const fields = ensureIdField(opts.fields);\n const persistence = opts.persistence ?? 'runtime';\n return {\n name: opts.name,\n persistence,\n ...(persistence === 'persistent'\n ? { collection: opts.collection ?? plural(opts.name).toLowerCase() }\n : {}),\n fields,\n ...(opts.instances && opts.instances.length > 0 ? { instances: opts.instances } : {}),\n };\n}\n\n// ============================================================================\n// Page Builder\n// ============================================================================\n\nexport interface MakePageOpts {\n name: string;\n path: string;\n traitName: string;\n isInitial?: boolean;\n}\n\n/**\n * Build a Page that binds to a single trait.\n */\nexport function makePage(opts: MakePageOpts): Page {\n return {\n name: opts.name,\n path: opts.path,\n ...(opts.isInitial ? { isInitial: true } : {}),\n traits: [{ ref: opts.traitName }],\n };\n}\n\n// ============================================================================\n// Orbital Builder\n// ============================================================================\n\n/**\n * Build an OrbitalDefinition from its three components.\n */\nexport function makeOrbital(\n name: string,\n entity: Entity,\n traits: Trait[],\n pages: Page[],\n): OrbitalDefinition {\n return { name, entity, traits, pages } as OrbitalDefinition;\n}\n\n// ============================================================================\n// Reference-form Builders (Phase 4.2)\n// ============================================================================\n//\n// The atom/molecule/organism composition model (see CLAUDE.md \"Std Behaviors\")\n// treats every imported orbital as a callable unit: a reference site is a call\n// site whose sibling fields are call arguments. The compiler's inline pass\n// applies overrides from the reference to a cloned copy of the imported unit.\n//\n// These four helpers are convenience factories for constructing the reference\n// payloads (TraitReference, PageRefObject) and the orbital skeleton that\n// holds them. They exist to compress the otherwise ~200-line-per-behavior TS\n// rewrite down to ~30 lines. They purely pass-through fields: undefined\n// optionals are omitted (the emitted object never contains `key: undefined`),\n// so the result stays compatible with the inliner's \"present-means-override\"\n// semantics.\n\n/**\n * Options for {@link makeTraitRef}.\n */\nexport interface MakeTraitRefOpts {\n /**\n * Optional registry path disambiguator that pairs with {@link ref}\n * (see {@link TraitReference.from}).\n */\n from?: string;\n /** Trait reference string, e.g. \"Browse.traits.BrowseItemBrowse\". */\n ref: string;\n /** Rename the inlined trait at the call site. */\n name?: string;\n /** Rebind the trait to a different linkedEntity. */\n linkedEntity?: string;\n /** Dual-carry id sibling of {@link linkedEntity} (V4 identity graph). */\n linkedEntityId?: EntityId;\n /** Per-key rename map, e.g. `{ OPEN: \"ADD_ITEM\" }`. */\n events?: Record<string, string>;\n /**\n * 3-II trait type-parameter arguments (`:: p SomeType`): declared-param\n * name → type-vocabulary name. Mirrors {@link TraitReference.typeArgs}.\n */\n typeArgs?: Record<string, string>;\n /**\n * Entity-field remap, e.g. `{ name: \"title\", folder: \"parentId\" }`. Rewrites\n * the inlined trait's canonical `@entity.X` / `@payload.row.X` references to\n * the consumer entity's field names. Mirrors {@link TraitReference.fields}.\n */\n fields?: Record<string, string>;\n /**\n * Per-event SExpression effect replacement. Keys are POST-rename event\n * names. See {@link TraitReference.effects} for the full contract.\n */\n effects?: Record<string, SExpr[]>;\n /** Replace the imported trait's `listens` array entirely. */\n listens?: TraitEventListener[];\n /** Set every emit's scope. */\n emitsScope?: 'internal' | 'external';\n /**\n * Call-site config overrides. Each entry is either a plain wiring value\n * (`TraitConfigValue`) or a fully-annotated re-declaration\n * (`ConfigFieldDeclaration`). Matches {@link TraitReference.config}.\n */\n config?: CallSiteConfig;\n}\n\n/**\n * Typed-narrowing variant of {@link MakeTraitRefOpts} for callers that know\n * the imported atom's overridable surfaces — its event-key set, listen-key\n * set, and config shape. Generated std factories use this variant so an LLM\n * tool consumer (orbital-agent) sees the closed event-name set and the\n * config field schema instead of the un-narrowed `Record<string, string>` /\n * `TraitConfig` defaults.\n *\n * Type parameters:\n * - `EventKey` — string union of the atom's emit event names. Narrows the\n * `events` rename map's keys to legal originals only.\n * - `ConfigShape` — typed shape of the trait's `config { ... }` block (literal\n * unions intact). Narrows the `config` override to the atom's actual fields.\n * Extends `CallSiteConfig` to allow both plain wiring values and annotated\n * declarations. Existing callers using plain `TraitConfig` shapes are\n * unaffected (TraitConfig ⊆ CallSiteConfig).\n * - `ListenKey` — string union of the atom's listen-key contract. Narrows\n * each listens entry's `event` against the atom's real subscription set.\n *\n * Runtime behavior is unchanged — {@link makeTraitRef} accepts both the\n * narrow and wide forms via the standard structural-typing rules. This is\n * a type-level narrowing only; widening at the call boundary is intentional.\n */\nexport interface MakeTraitRefOptsTyped<\n EventKey extends string = string,\n ConfigShape extends CallSiteConfig = Record<string, never>,\n ListenKey extends string = string,\n> extends Omit<\n MakeTraitRefOpts,\n 'events' | 'effects' | 'listens' | 'config'\n > {\n /** Per-key rename map, narrowed to the atom's actual event keys. */\n events?: Partial<Record<EventKey, string>>;\n /**\n * Per-event SExpression effect replacement. Keys are POST-rename event\n * names so they're caller-defined (no narrowing here); values stay typed\n * as `SExpr[]`.\n */\n effects?: Partial<Record<string, SExpr[]>>;\n /**\n * Replace the imported trait's `listens` array entirely. Each entry's\n * `event` field is narrowed to {@link ListenKey} where the atom's\n * subscription set is fixed; otherwise this widens to plain string.\n */\n listens?: Array<TraitEventListener & { event?: ListenKey }>;\n /** Typed call-site config overrides — narrowed to {@link ConfigShape}. */\n config?: ConfigShape;\n}\n\n/**\n * Build a {@link TraitReference} from options.\n *\n * Pass-through factory: copies only the fields that are actually provided,\n * so optionals stay absent (no `key: undefined` slots) and the emitted\n * object matches the inliner's expectation that \"present = override\".\n */\nexport function makeTraitRef(opts: MakeTraitRefOpts): TraitReference {\n const ref: TraitReference = { ref: opts.ref };\n if (opts.from !== undefined) ref.from = opts.from;\n if (opts.name !== undefined) ref.name = opts.name;\n if (opts.linkedEntity !== undefined) ref.linkedEntity = opts.linkedEntity;\n if (opts.linkedEntityId !== undefined) ref.linkedEntityId = opts.linkedEntityId;\n if (opts.events !== undefined) ref.events = opts.events;\n if (opts.typeArgs !== undefined) ref.typeArgs = opts.typeArgs;\n if (opts.fields !== undefined) ref.fields = opts.fields;\n if (opts.effects !== undefined) ref.effects = opts.effects;\n if (opts.listens !== undefined) ref.listens = opts.listens;\n if (opts.emitsScope !== undefined) ref.emitsScope = opts.emitsScope;\n if (opts.config !== undefined) ref.config = opts.config;\n return ref;\n}\n\n/**\n * Options for {@link makePageRef}.\n */\nexport interface MakePageRefOpts {\n /**\n * Optional registry path disambiguator that pairs with {@link ref}\n * (see {@link PageRefObject.from}).\n */\n from?: string;\n /** Page reference string, e.g. \"Browse.pages.BrowseItemPage\". */\n ref: string;\n /** URL path override. */\n path?: string;\n /** Rebind the page's primary entity. */\n linkedEntity?: string;\n /** Replace the page's trait list. */\n traits?: TraitRef[];\n}\n\n/**\n * Typed-narrowing variant of {@link MakePageRefOpts}. Narrows the `traits`\n * override array's entries to the orbital's known trait-name union — so the\n * agent can't pass a trait name that doesn't exist on the page's owning\n * orbital. Generated std page-helpers use this variant to surface the\n * trait set in the tool schema; un-narrowed call sites stay compatible.\n *\n * Type parameter:\n * - `TraitName` — string union of trait names the page may reference.\n */\nexport interface MakePageRefOptsTyped<TraitName extends string = string>\n extends Omit<MakePageRefOpts, 'traits'> {\n traits?: Array<{ ref: TraitName } | TraitRef>;\n}\n\n/**\n * Build a {@link PageRefObject} from options. Pass-through factory — omits\n * optional keys that are `undefined`.\n */\nexport function makePageRef(opts: MakePageRefOpts): PageRefObject {\n const ref: PageRefObject = { ref: opts.ref };\n if (opts.from !== undefined) ref.from = opts.from;\n if (opts.path !== undefined) ref.path = opts.path;\n if (opts.linkedEntity !== undefined) ref.linkedEntity = opts.linkedEntity;\n if (opts.traits !== undefined) ref.traits = opts.traits;\n return ref;\n}\n\n/**\n * Options for {@link makeOrbitalWithUses}.\n */\nexport interface MakeOrbitalWithUsesOpts {\n /** Orbital name. */\n name: string;\n /**\n * Per-orbital `uses:` header entries (see CLAUDE.md \"uses: lives inside\n * the orbital\").\n */\n uses: UseDeclaration[];\n /** Entity (inline or reference form). */\n entity: EntityRef;\n /**\n * Derived `expects` declarations (consumer-side requirements). Threaded\n * verbatim — derivation lives in `orb` (`orb behaviors expects`); builders never\n * compute it. Omitted from the result when not provided.\n */\n expects?: ExpectDeclaration[];\n /**\n * Auxiliary entities (name-resolution side channel for un-rebound atom\n * imports — see {@link OrbitalDefinition.auxiliaryEntities}). Threaded\n * verbatim; omitted from the result when not provided.\n */\n auxiliaryEntities?: EntityRef[];\n /** Trait references. */\n traits: TraitRef[];\n /** Optional page references (omitted entirely when not provided). */\n pages?: PageRef[];\n /** The orbital's own declared config knobs, threaded verbatim; omitted when not provided. */\n config?: DeclaredTraitConfig;\n}\n\n/**\n * Build an {@link OrbitalDefinition} with the `uses:` header set. Follows\n * the convention that `uses:` lives on the orbital (not the schema).\n *\n * When `pages` is omitted, the result has no `pages` property (matches the\n * existing {@link OrbitalDefinition.pages} optionality in descriptors that\n * carry trait-only atoms).\n */\nexport function makeOrbitalWithUses(opts: MakeOrbitalWithUsesOpts): OrbitalDefinition {\n const orbital: OrbitalDefinition = {\n name: opts.name,\n uses: opts.uses,\n ...(opts.expects !== undefined ? { expects: opts.expects } : {}),\n entity: opts.entity,\n ...(opts.auxiliaryEntities !== undefined ? { auxiliaryEntities: opts.auxiliaryEntities } : {}),\n traits: opts.traits,\n pages: opts.pages ?? [],\n ...(opts.config !== undefined ? { config: opts.config } : {}),\n };\n return orbital;\n}\n\n/** The alias an orbital value's import binds its source under (one import per orbital, so a fixed name is unambiguous). */\nexport const ORBITAL_VALUE_IMPORT_ALIAS = 'Source';\n\n/**\n * The import orbital an orbital value stands for (LOLO §8b): the value's\n * behavior imported under {@link ORBITAL_VALUE_IMPORT_ALIAS}, its orbital\n * referenced, and its recorded body as the reference body. Plain config values\n * are wrapped into the IR's declaration form here.\n */\nexport function orbitalImportFromValue(value: OrbitalValue): OrbitalDefinition {\n const { behavior, orbital, name, app, config, traits, uses, siblings, ...body } = value;\n const ref = `${ORBITAL_VALUE_IMPORT_ALIAS}.orbitals.${orbital}`;\n const clash = (uses ?? []).find((u) => u.as === ORBITAL_VALUE_IMPORT_ALIAS);\n if (clash !== undefined) {\n throw new Error(`orbital value ${orbital}: an import aliased '${ORBITAL_VALUE_IMPORT_ALIAS}' (from ${clash.from}) collides with the value's own source alias`);\n }\n const traitOverrides =\n traits === undefined\n ? undefined\n : Object.fromEntries(\n Object.entries(traits).map(([trait, overrides]): [string, OrbitalRefTraitOverride] => {\n const { config: traitConfig, ...rest } = overrides;\n return [trait, { ...rest, ...(traitConfig !== undefined ? { config: mergeCallSiteConfigOverrides({}, traitConfig) } : {}) }];\n }),\n );\n return {\n name: name ?? orbital,\n uses: [{ from: behavior, as: ORBITAL_VALUE_IMPORT_ALIAS, ...(app !== undefined ? { config: mergeCallSiteConfigOverrides({}, app) } : {}) }, ...(uses ?? [])],\n entity: `${ref}.entity`,\n traits: (siblings ?? []).map((sibling) => ({\n name: sibling.name,\n ref: sibling.ref,\n ...(sibling.linkedEntity !== undefined ? { linkedEntity: sibling.linkedEntity } : {}),\n ...(sibling.config !== undefined ? { config: mergeCallSiteConfigOverrides({}, sibling.config) } : {}),\n })),\n pages: [],\n reference: {\n ref,\n ...body,\n ...(config !== undefined ? { config: mergeCallSiteConfigOverrides({}, config) } : {}),\n ...(traitOverrides !== undefined ? { traits: traitOverrides } : {}),\n },\n };\n}\n\n/**\n * Parse a program held as data: an orbital value at `orbitals[i]` is the import\n * orbital it stands for ({@link orbitalImportFromValue}); everything else must\n * already be IR.\n */\nexport function parseProgram(data: RuntimeValue): OrbitalSchema {\n if (data === null || typeof data !== 'object' || Array.isArray(data) || !('orbitals' in data) || !Array.isArray(data.orbitals)) {\n return parseOrbitalSchema(data);\n }\n return parseOrbitalSchema({\n ...data,\n orbitals: data.orbitals.map((entry) => (isOrbitalValue(entry) ? orbitalImportFromValue(OrbitalValueSchema.parse(entry)) : entry)),\n });\n}\n\n/**\n * Options for {@link makeAtomOrbital}.\n *\n * Overrides for the single trait reference. Mirrors the {@link MakeTraitRefOpts}\n * subset that is meaningful at the atom-wrapping call site.\n */\nexport interface MakeAtomOrbitalTraitOverrides {\n name?: string;\n events?: Record<string, string>;\n effects?: Record<string, SExpr[]>;\n listens?: TraitEventListener[];\n emitsScope?: 'internal' | 'external';\n config?: CallSiteConfig;\n}\n\n/**\n * Options for {@link makeAtomOrbital}.\n */\nexport interface MakeAtomOrbitalOpts {\n /** Orbital name, e.g. `${entityName}Orbital`. */\n name: string;\n /** Atom registry path, e.g. `std/behaviors/atoms/std-browse`. */\n atomPath: string;\n /** Import alias (PascalCase), e.g. `Browse`. */\n alias: string;\n /** Entity definition to attach to the orbital. */\n entity: Entity;\n /** Trait reference string, e.g. `Browse.traits.BrowseItemBrowse`. */\n traitRef: string;\n /** Optional trait-level overrides applied at the call site. */\n traitOverrides?: MakeAtomOrbitalTraitOverrides;\n /** Optional page reference string, e.g. `Browse.pages.BrowseItemPage`. */\n pageRef?: string;\n /** Optional page-level overrides applied at the call site. */\n pageOverrides?: { path?: string };\n}\n\n/**\n * Build a single-atom {@link OrbitalDefinition}.\n *\n * The common atom shape: one entity + one trait reference + (optionally) one\n * page reference, all under a single `uses:` import. Wraps\n * {@link makeTraitRef}, {@link makePageRef}, and {@link makeOrbitalWithUses}.\n *\n * The trait reference is linkedEntity-bound to `entity.name` by default so\n * that the inliner's entity-substitution pass rewrites every `[\"fetch\", X]`\n * and `@X.path` reference inside the atom.\n */\nexport function makeAtomOrbital(opts: MakeAtomOrbitalOpts): OrbitalDefinition {\n const traitRef = makeTraitRef({\n from: opts.atomPath,\n ref: opts.traitRef,\n linkedEntity: opts.entity.name,\n ...(opts.traitOverrides?.name !== undefined ? { name: opts.traitOverrides.name } : {}),\n ...(opts.traitOverrides?.events !== undefined ? { events: opts.traitOverrides.events } : {}),\n ...(opts.traitOverrides?.effects !== undefined ? { effects: opts.traitOverrides.effects } : {}),\n ...(opts.traitOverrides?.listens !== undefined ? { listens: opts.traitOverrides.listens } : {}),\n ...(opts.traitOverrides?.emitsScope !== undefined\n ? { emitsScope: opts.traitOverrides.emitsScope }\n : {}),\n ...(opts.traitOverrides?.config !== undefined ? { config: opts.traitOverrides.config } : {}),\n });\n\n const pages: PageRef[] | undefined = opts.pageRef\n ? [\n makePageRef({\n from: opts.atomPath,\n ref: opts.pageRef,\n linkedEntity: opts.entity.name,\n ...(opts.pageOverrides?.path !== undefined ? { path: opts.pageOverrides.path } : {}),\n }),\n ]\n : undefined;\n\n return makeOrbitalWithUses({\n name: opts.name,\n uses: [{ from: opts.atomPath, as: opts.alias }],\n entity: opts.entity,\n traits: [traitRef],\n ...(pages !== undefined ? { pages } : {}),\n });\n}\n\n/**\n * Wrap one or more OrbitalDefinitions into an OrbitalSchema.\n * Every .orb file should be a full OrbitalSchema — this is the builder for that.\n */\nexport function makeSchema(name: string, ...definitions: OrbitalDefinition[]): OrbitalSchema {\n return { name, version: '1.0.0', orbitals: definitions };\n}\n\n/**\n * Unwrap inputs that may be OrbitalSchema or OrbitalDefinition into a flat\n * array of OrbitalDefinitions. Used internally by compose/pipe/connect/extractTrait\n * so they accept both types.\n */\nfunction asDefinitions(inputs: (OrbitalDefinition | OrbitalSchema)[]): OrbitalDefinition[] {\n return inputs.flatMap(input => {\n if ('orbitals' in input && Array.isArray((input as OrbitalSchema).orbitals)) {\n return (input as OrbitalSchema).orbitals as OrbitalDefinition[];\n }\n return [input as OrbitalDefinition];\n });\n}\n\n/** Unwrap a single OrbitalSchema | OrbitalDefinition to OrbitalDefinition. */\nfunction asDefinition(input: OrbitalDefinition | OrbitalSchema): OrbitalDefinition {\n if ('orbitals' in input && Array.isArray((input as OrbitalSchema).orbitals)) {\n return (input as OrbitalSchema).orbitals[0] as OrbitalDefinition;\n }\n return input as OrbitalDefinition;\n}\n\n// ============================================================================\n// Intra-Orbital Composition\n// ============================================================================\n\n/**\n * Merge multiple OrbitalDefinitions into one.\n * Collects all traits from all sources into a single orbital with a shared entity.\n * Pure: clones all traits, no mutation.\n */\nexport function mergeOrbitals(\n name: string,\n entity: Entity,\n sources: OrbitalDefinition[],\n pages: Page[],\n): OrbitalDefinition {\n const allTraits = sources.flatMap(s =>\n (s.traits as Trait[]).map(t => structuredClone(t)),\n );\n return { name, entity, traits: allTraits, pages } as OrbitalDefinition;\n}\n\n/**\n * Wire an intra-orbital event between two traits.\n * Adds emits to the source trait, listens to the target trait.\n * Pure: returns cloned traits, no mutation.\n */\nexport function wire(\n source: Trait,\n target: Trait,\n event: TraitEventContract,\n triggers: string,\n): [Trait, Trait] {\n const s = structuredClone(source);\n const t = structuredClone(target);\n\n s.emits = [...(s.emits ?? []), { ...event, scope: event.scope ?? ('internal' as const) }];\n t.listens = [...(t.listens ?? []), {\n event: event.event,\n triggers,\n scope: 'internal' as const,\n }];\n\n return [s, t];\n}\n\n/**\n * Extract the first trait from an OrbitalDefinition or OrbitalSchema.\n * If given an OrbitalSchema, unwraps to the first orbital inside it.\n */\nexport function extractTrait(input: OrbitalDefinition | OrbitalSchema): Trait {\n const orbital = asDefinition(input);\n return structuredClone((orbital.traits as Trait[])[0]);\n}\n\n// ============================================================================\n// Composition: connect\n// ============================================================================\n\n/**\n * Wire a cross-orbital event between two orbitals.\n * Adds emits to a's first trait, listens to b's first trait.\n * Pure: returns new orbitals, no mutation.\n */\nexport function connect(\n a: OrbitalDefinition | OrbitalSchema,\n b: OrbitalDefinition | OrbitalSchema,\n event: TraitEventContract,\n triggers?: string,\n): [OrbitalDefinition, OrbitalDefinition] {\n const aClone = structuredClone(asDefinition(a));\n const bClone = structuredClone(asDefinition(b));\n\n // Add emit to first trait of a\n const aTrait = (aClone.traits as Trait[])[0];\n if (aTrait) {\n const emitContract: TraitEventContract = {\n ...event,\n scope: event.scope ?? 'external',\n };\n aTrait.emits = [...(aTrait.emits ?? []), emitContract];\n }\n\n // Add listen to first trait of b\n const bTrait = (bClone.traits as Trait[])[0];\n if (bTrait) {\n const listener: TraitEventListener = {\n event: event.event,\n triggers: triggers ?? 'INIT',\n scope: 'external',\n };\n bTrait.listens = [...(bTrait.listens ?? []), listener];\n }\n\n return [aClone, bClone];\n}\n\n// ============================================================================\n// Composition: compose\n// ============================================================================\n\nexport interface ComposeConnection {\n from: string;\n to: string;\n event: TraitEventContract;\n triggers?: string;\n}\n\nexport interface ComposePage {\n name: string;\n path: string;\n traits: string[];\n isInitial?: boolean;\n}\n\n/**\n * Compose multiple orbitals into a single OrbitalSchema (application).\n * Applies connections (cross-orbital event wiring) and page assignments.\n */\nexport function compose(\n orbitals: (OrbitalDefinition | OrbitalSchema)[],\n pages: ComposePage[],\n connections: ComposeConnection[],\n appName?: string,\n): OrbitalSchema {\n const cloned = structuredClone(asDefinitions(orbitals));\n\n // Apply connections\n for (const conn of connections) {\n const emitter = cloned.find(o => {\n const traits = o.traits as Trait[];\n return traits.some(t => t.name === conn.from);\n });\n const listener = cloned.find(o => {\n const traits = o.traits as Trait[];\n return traits.some(t => t.name === conn.to);\n });\n\n if (emitter && listener) {\n const eTrait = (emitter.traits as Trait[]).find(t => t.name === conn.from);\n const lTrait = (listener.traits as Trait[]).find(t => t.name === conn.to);\n\n if (eTrait) {\n const emitContract: TraitEventContract = { ...conn.event, scope: conn.event.scope ?? 'external' };\n eTrait.emits = [...(eTrait.emits ?? []), emitContract];\n }\n if (lTrait) {\n const listenContract: TraitEventListener = {\n event: conn.event.event,\n triggers: conn.triggers ?? 'INIT',\n scope: 'external',\n };\n lTrait.listens = [...(lTrait.listens ?? []), listenContract];\n }\n }\n }\n\n // Assign pages to orbitals\n for (const orbital of cloned) {\n const traitNames = (orbital.traits as Trait[]).map(t => t.name);\n const matchingPages = pages.filter(p =>\n p.traits.some(t => traitNames.includes(t)),\n );\n orbital.pages = matchingPages.map(p => ({\n name: p.name,\n path: p.path,\n ...(p.isInitial ? { isInitial: true } : {}),\n traits: p.traits\n .filter(t => traitNames.includes(t))\n .map(ref => ({ ref })),\n }));\n }\n\n return {\n name: appName ?? 'Application',\n version: '1.0.0',\n orbitals: cloned,\n };\n}\n\n// ============================================================================\n// Composition: pipe\n// ============================================================================\n\n/**\n * Chain orbitals in sequence with automatic event wiring.\n * Sugar over connect + compose: wires events[0] from orbital[0] to orbital[1], etc.\n */\nexport function pipe(\n orbitals: (OrbitalDefinition | OrbitalSchema)[],\n events: TraitEventContract[],\n appName?: string,\n): OrbitalSchema {\n if (events.length !== orbitals.length - 1) {\n throw new Error(`pipe requires exactly ${orbitals.length - 1} events for ${orbitals.length} orbitals`);\n }\n\n const cloned = structuredClone(asDefinitions(orbitals));\n\n // Wire adjacent pairs\n for (let i = 0; i < events.length; i++) {\n const aTrait = (cloned[i].traits as Trait[])[0];\n const bTrait = (cloned[i + 1].traits as Trait[])[0];\n\n if (aTrait) {\n const emitContract: TraitEventContract = { ...events[i], scope: events[i].scope ?? 'external' };\n aTrait.emits = [...(aTrait.emits ?? []), emitContract];\n }\n if (bTrait) {\n const listener: TraitEventListener = {\n event: events[i].event,\n triggers: 'INIT',\n scope: 'external',\n };\n bTrait.listens = [...(bTrait.listens ?? []), listener];\n }\n }\n\n // Auto-generate pages: one per orbital, first is initial\n const pages: Page[] = cloned.map((o, i) => {\n const entityName = resolveEntityNameForBuilder(o.entity);\n const traitNames = (o.traits as Trait[]).map(t => t.name);\n return {\n name: `${entityName}Page`,\n path: `/${plural(entityName).toLowerCase()}`,\n ...(i === 0 ? { isInitial: true } : {}),\n traits: traitNames.map(ref => ({ ref })),\n };\n });\n\n // Assign pages back to orbitals\n for (let i = 0; i < cloned.length; i++) {\n cloned[i].pages = [pages[i]];\n }\n\n return {\n name: appName ?? 'Application',\n version: '1.0.0',\n orbitals: cloned,\n };\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types/expression.ts"],"names":["value"],"mappings":";;;;AA2DO,IAAM,kBAAoC,CAAA,CAAE,IAAA;AAAA,EAAK,MACtD,EAAE,KAAA,CAAM,CAAC,iBAAiB,CAAA,CAAE,KAAA,CAAM,eAAe,CAAC,CAAC;AACrD;AAMO,IAAM,eAAA,GAAwC,EAAE,KAAA,CAAM;AAAA,EAC3D,EAAE,MAAA,EAAO;AAAA,EACT,EAAE,MAAA,EAAO;AAAA,EACT,EAAE,OAAA,EAAQ;AAAA,EACV,EAAE,IAAA,EAAK;AAAA,EACP,CAAA,CAAE,MAAA,CAAO,CAAA,CAAE,MAAA,IAAU,eAAe;AAAA;AACtC,CAAC;AAQM,IAAM,cAAgC,CAAA,CAAE,IAAA;AAAA,EAAK,MAClD,EAAE,KAAA,CAAM;AAAA,IACN,eAAA;AAAA,IACA,EACG,KAAA,CAAM,eAAe,CAAA,CACrB,GAAA,CAAI,CAAC,CAAA,CACL,MAAA;AAAA,MACC,CAAC,GAAA,KAAQ,OAAO,GAAA,CAAI,CAAC,CAAA,KAAM,QAAA;AAAA,MAC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,CAAC,CAAA,EAAA,CAAA;AAAA,EAC9D;AACA,EAAA,OAAO,YAAY,IAAI,CAAA;AACzB","file":"chunk-347APWFM.js","sourcesContent":["/**\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 { setOwn } from './own-key.js';\nimport { JsonValueSchema, type JsonValue, 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: a JSON value. A date is its ISO string, an absent\n * field is an absent key; `Date` and `undefined` never travel on the wire.\n */\nexport type EventPayloadValue = JsonValue;\n\n/**\n * Typed event payload: a JSON object, assignable to the bus's `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) return true;\n const kind = typeof value;\n if (kind === 'string' || kind === 'number' || kind === 'boolean') return true;\n if (Array.isArray(value)) return value.every((item: RuntimeValue) => isEventPayloadValue(item));\n if (kind === 'object' && typeof value === 'object' && !(value instanceof Date)) {\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> = JsonValueSchema;\n\n/** Zod twin of `EventPayload` — the wire shape of a bus event's `payload`. */\nexport const EventPayloadSchema: z.ZodType<EventPayload> = z.record(z.string(), JsonValueSchema);\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()) setOwn(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()) setOwn(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)) setOwn(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)) setOwn(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"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/factory/knob-defs.ts","../src/factory/questions/generate.ts","../src/factory/questions/reducer.ts","../src/factory/mutate.ts","../src/factory/params-schema.ts"],"names":[],"mappings":";;;;AAgBO,SAAS,kBAAkB,OAAA,EA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AAA,EAAU,aAAa,oBAAA,EAAqB;AAAA,IAC1D,YAAA,EAAc,EAAE,IAAA,EAAM,QAAA,EAAU,aAAa,4BAAA;AAA6B;AAE9E,CAAA","file":"chunk-3DZOFI53.js","sourcesContent":["import type { FactoryConfigParam, FactorySignatureCatalog } from './types.js';\n\n/**\n * Rehydrate `overridableConfigKeys` from a catalog's `knobDefs` table,\n * in place, and drop the wire-only `overridableConfigKeyRefs`.\n *\n * Call this immediately after parsing a catalog and before handing it to any\n * consumer — every consumer reads `overridableConfigKeys` and must never see\n * a signature mid-rehydration.\n *\n * A catalog with no `knobDefs` is returned untouched, which is what makes the\n * format change backward compatible: old catalogs still carry their knobs\n * inline. An out-of-range or missing ref is skipped rather than throwing —\n * a truncated table should degrade to fewer knobs, not take down every\n * consumer of the catalog.\n */\nexport function rehydrateKnobDefs(catalog: FactorySignatureCatalog): FactorySignatureCatalog {\n const table = catalog.knobDefs;\n if (table === undefined || table.length === 0) return catalog;\n for (const sig of catalog.signatures) {\n for (const trait of sig.traits ?? []) {\n const refs = trait.overridableConfigKeyRefs;\n if (refs === undefined) continue;\n const knobs: FactoryConfigParam[] = [];\n for (const i of refs) {\n const knob = table[i];\n if (knob !== undefined) knobs.push(knob);\n }\n const mutable = trait as {\n overridableConfigKeys: ReadonlyArray<FactoryConfigParam>;\n overridableConfigKeyRefs?: ReadonlyArray<number>;\n };\n mutable.overridableConfigKeys = knobs;\n delete mutable.overridableConfigKeyRefs;\n }\n // Orbital-level `config` — same table, same ref/rehydrate shape as the\n // per-trait `overridableConfigKeyRefs` above.\n const configRefs = sig.configRefs;\n if (configRefs === undefined) continue;\n const configKnobs: FactoryConfigParam[] = [];\n for (const i of configRefs) {\n const knob = table[i];\n if (knob !== undefined) configKnobs.push(knob);\n }\n const mutableSig = sig as {\n config?: ReadonlyArray<FactoryConfigParam>;\n configRefs?: ReadonlyArray<number>;\n };\n mutableSig.config = configKnobs;\n delete mutableSig.configRefs;\n }\n return catalog;\n}\n","/**\n * `generateQuestions(plan, catalog, ruleOverlay?)`.\n *\n * Deterministic, no LLM call. Walks each `FactoryCallSite` in the\n * durable plan against its matching `FactorySignature` and emits one\n * open question per advertised knob the user hasn't already filled.\n *\n * Two families of questions, both source-derived:\n *\n * 1. CONFIG-KEY — one question per\n * `signature.traits[*].overridableConfigKeys[*]`. Each entry is a\n * `FactoryConfigParam` carrying `{ key, type, default?, label?,\n * description?, enumValues?, items?, properties?, tier? }` lifted\n * directly from the source `.lolo` `config { }` block. The widget\n * choice falls out of `deriveInputType` (reads `items.properties`\n * and `properties` so structured types render proper editors, not\n * JSON textareas); the prompt comes from `label` (or a humanized\n * fallback of `key`); the default value pre-fills the widget.\n * Knobs tagged `tier: 'internal'` are filtered out entirely.\n *\n * 2. CAPABILITY-DRIVEN — one question per unique\n * `signature.traits[*].capabilities[*]` tag NOT already covered\n * by `ruleOverlay.rules[].capability`. Surfaces a `set-rule`\n * mutation template scoped to the bound entity.\n *\n * @packageDocumentation\n */\n\nimport type {\n FactoryCallSite,\n FactoryConfigParam,\n FactoryParamValue,\n FactorySignature,\n FactorySignatureEntityField,\n FactoryTraitSignature,\n} from '../types.js';\nimport type { RuleOverlay } from '../overlays.js';\nimport type { EntityField } from '../../types/field.js';\nimport type {\n DomainQuestion,\n DomainQuestionInputType,\n} from './types.js';\n\nexport function generateQuestions(\n plan: ReadonlyArray<FactoryCallSite>,\n catalog: ReadonlyArray<FactorySignature>,\n ruleOverlay?: RuleOverlay,\n /**\n * Optional user-authored prompt from the current session. Carried\n * through so downstream consumers (route handlers, ranking passes)\n * can re-order questions by relevance without re-generating. Does\n * not affect the emitted set — only threading and ordering.\n */\n _userPrompt?: string,\n): DomainQuestion[] {\n const out: DomainQuestion[] = [];\n const ruleCapabilities = collectRuleCapabilities(ruleOverlay);\n\n for (const call of plan) {\n const signature = findSignature(catalog, call.organism, call.orbital);\n if (!signature) continue;\n out.push(...configKeyQuestions(call, signature));\n out.push(...entityFieldQuestions(call, signature));\n out.push(...capabilityQuestions(call, signature, ruleCapabilities));\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Config-key questions — derived from the source `config { }` declaration\n// ---------------------------------------------------------------------------\n\nconst TIER_D_NAMED_PRIMITIVES = new Set([\n 'layoutMode',\n 'layoutPattern',\n 'viewPattern',\n 'detailPattern',\n 'detailSlot',\n 'contentTrait',\n]);\n\nconst TIER_D_TYPES = new Set(['trait', 'slot', 'pattern', 'event']);\n\nfunction configKeyQuestions(\n call: FactoryCallSite,\n signature: FactorySignature,\n): DomainQuestion[] {\n const out: DomainQuestion[] = [];\n for (const trait of signature.traits) {\n for (const param of trait.overridableConfigKeys) {\n if (param.tier === 'internal') continue;\n if (TIER_D_TYPES.has(param.type)) continue;\n if (TIER_D_NAMED_PRIMITIVES.has(param.key)) continue;\n out.push(buildConfigKeyQuestion(call, trait, param));\n }\n }\n return out;\n}\n\nfunction buildConfigKeyQuestion(\n call: FactoryCallSite,\n trait: FactoryTraitSignature,\n param: FactoryConfigParam,\n): DomainQuestion {\n // `@label` renders verbatim; the fallback is a type guard, not inference —\n // a domain-tier knob reaching it is a missing-`@label` source defect.\n const question = param.label ?? humanizeKey(param.key);\n // Call-site override (organism pre-pinned this knob) takes precedence\n // over the atom-author's default. The question still renders so the\n // user can confirm or change the pre-pinned value.\n const callSiteOverride = callSiteOverrideValue(call, trait.name, param.key);\n const effectiveDefault =\n callSiteOverride !== undefined ? callSiteOverride : param.default;\n\n // `helpText` carries the param's authored description (how to answer).\n // `reason` is the distinct \"why you're seeing this\" — only set when it\n // adds information beyond what helpText already says.\n const helpText = param.description;\n const syntheticReason =\n `Customizes \"${param.key}\" on the ${trait.name} trait. ` +\n (effectiveDefault !== undefined\n ? `Default: ${stringifyDefault(effectiveDefault)}.`\n : `No default — leave blank to inherit the factory's behavior.`);\n const reason = helpText !== undefined ? undefined : syntheticReason;\n\n const isAdvanced = !isPrimaryTier(param.tier);\n\n const out: DomainQuestion = {\n id: `${factoryCallPlanOrbitalName(call)}.${trait.name}.${param.key}`,\n orbitalName: factoryCallPlanOrbitalName(call),\n question,\n inputType: deriveInputType(param),\n mutationTemplate: {\n kind: 'set-trait-override-config',\n orbitalName: factoryCallPlanOrbitalName(call),\n traitName: trait.name,\n configKey: param.key,\n },\n };\n if (reason !== undefined) {\n out.reason = reason;\n }\n if (helpText !== undefined) {\n out.helpText = helpText;\n }\n if (effectiveDefault !== undefined) {\n out.defaultValue = effectiveDefault;\n }\n if (param.enumValues && param.enumValues.length > 0) {\n out.suggestedAnswers = param.enumValues;\n }\n if (param.items) {\n out.itemSchema = param.items;\n }\n if (param.properties) {\n out.objectSchema = param.properties;\n }\n if (param.tier) {\n out.tier = param.tier;\n }\n if (isAdvanced) {\n out.advanced = true;\n }\n const weight = tierWeight(param.tier);\n out.weight = weight;\n out.priority = weight;\n return out;\n}\n\n/**\n * Impact weight by decision kind — the spine of both the wizard's\n * prescient-first ordering and its Confidence score. policy/domain are the\n * decisions that change what the business does; infra is operational wiring;\n * presentation is polish. Untagged defaults to presentation (1). `internal`\n * never reaches here (filtered in `configKeyQuestions`).\n */\nfunction tierWeight(tier: FactoryConfigParam['tier']): number {\n switch (tier) {\n case 'domain':\n case 'policy':\n return 3;\n case 'infra':\n return 2;\n case 'internal':\n return 0;\n case 'presentation':\n default:\n return 1;\n }\n}\n\n/** `true` only for the two tiers that render inline (not collapsed). */\nfunction isPrimaryTier(tier: FactoryConfigParam['tier']): boolean {\n return tier === 'domain' || tier === 'policy';\n}\n\nfunction callSiteOverrideValue(\n call: FactoryCallSite,\n traitName: string,\n configKey: string,\n): FactoryParamValue | undefined {\n const override = call.params.traitOverrides?.[traitName];\n if (!override?.config) return undefined;\n if (!Object.prototype.hasOwnProperty.call(override.config, configKey)) {\n return undefined;\n }\n return override.config[configKey] as FactoryParamValue;\n}\n\n/**\n * Pick a widget for a config-key question from the param's typed\n * declaration + its structural carriers. The type tag is lifted\n * verbatim from `.lolo`; `items.properties` and `properties` carry the\n * per-element / per-property schema for structured types so the studio\n * can render a real form instead of a JSON textarea.\n *\n * - `[T]` with `items.properties` → `listOfObjects` (repeatable form)\n * - `[T]` with `enumValues` → `multiselect` (closed checkboxes)\n * - `[T]` otherwise → `tagList` (free-form chips)\n * - `object` with `properties` → `objectForm` (per-property form)\n * - `object` otherwise → `text` (rare; flagged by tests)\n * - `number` / `integer` → `number`\n * - `boolean` → `boolean`\n * - `enum` → `enum`\n * - `string` with `enumValues` → `enum`\n * - `string` → `text`\n */\nexport function deriveInputType(\n param: FactoryConfigParam,\n): DomainQuestionInputType {\n if (param.type.startsWith('[')) {\n if (\n param.items?.properties &&\n Object.keys(param.items.properties).length > 0\n ) {\n return 'listOfObjects';\n }\n if (param.enumValues && param.enumValues.length > 0) {\n return 'multiselect';\n }\n return 'tagList';\n }\n // Typed map (`Map<K,V>`) — a dynamic-key dictionary; edited as an object.\n if (param.type.startsWith('Map<')) {\n return 'objectForm';\n }\n if (param.type === 'object') {\n if (param.properties && Object.keys(param.properties).length > 0) {\n return 'objectForm';\n }\n return 'text';\n }\n switch (param.type) {\n case 'number':\n case 'integer':\n return 'number';\n case 'boolean':\n return 'boolean';\n case 'enum':\n return 'enum';\n case 'string':\n return param.enumValues && param.enumValues.length > 0 ? 'enum' : 'text';\n default:\n return 'text';\n }\n}\n\n/**\n * Humanize a camelCase / kebab-case key into a question prompt\n * fallback when the source `.lolo` doesn't author an explicit label.\n *\n * `itemActions` → `\"Item Actions\"`\n * `owner-field` → `\"Owner Field\"`\n * `URL` → `\"URL\"` (preserves all-caps runs)\n */\nexport function humanizeKey(key: string): string {\n const parts = key\n .replace(/[-_]+/g, ' ')\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')\n .split(' ')\n .filter((s) => s.length > 0);\n return parts\n .map((p) => (/^[A-Z]+$/.test(p) ? p : p.charAt(0).toUpperCase() + p.slice(1)))\n .join(' ');\n}\n\nfunction stringifyDefault(v: FactoryParamValue): string {\n if (typeof v === 'string') return JSON.stringify(v);\n if (typeof v === 'number' || typeof v === 'boolean') return String(v);\n if (Array.isArray(v)) return `${v.length} item${v.length === 1 ? '' : 's'}`;\n return 'object';\n}\n\n// ---------------------------------------------------------------------------\n// Entity-field question — lets the user add or override data model fields\n// ---------------------------------------------------------------------------\n\n/**\n * Emit one multiselect question per call site that has a canonical entity.\n *\n * The widget shows the entity's canonical fields as labelled checkboxes;\n * the user confirms or deselects them. The answer (selected field names)\n * flows through the UI's name→EntityField lookup via `fieldCandidates`,\n * then into `answersToMutations` → `set-orbital-entity-fields` → `applyEntityFields`\n * in `translate.ts` (additive/override semantics).\n *\n * `suggestedAnswers` = candidate field name strings (drives checkbox list).\n * `defaultValue` = the canonical field-name set pre-selected.\n * `fieldCandidates` = name → EntityField for the UI's resolution step.\n * `fieldDescriptions` = name → description for checkbox sub-labels.\n *\n * Phrased without an article so no \"a\"/\"an\" guess is needed: no\n * source-tagged noun phrase for an entity exists yet — the only\n * candidate, `defaultLabels.entitySingular`, lives on a different\n * registry AND defaults to the raw entity name, so it would not help.\n * An authored `@entityLabel` on the entity is the real fix.\n *\n * Type note: `FactorySignatureEntityField.type` is `SchemaFieldType` while\n * `EntityField` is a discriminated union. `signatureFieldToEntityField` maps\n * each variant faithfully.\n */\nfunction entityFieldQuestions(\n call: FactoryCallSite,\n signature: FactorySignature,\n): DomainQuestion[] {\n if (signature.entities.length === 0) return [];\n const entity = signature.entities[0];\n const entityName = call.params.entityName ?? entity.name;\n\n const candidateFields = entity.fields.map(signatureFieldToEntityField);\n const fieldCandidates: Record<string, EntityField> = {};\n const fieldDescriptions: Record<string, string> = {};\n const candidateNames: string[] = [];\n\n for (let i = 0; i < entity.fields.length; i++) {\n const sig = entity.fields[i];\n const ef = candidateFields[i];\n const name = sig.name;\n candidateNames.push(name);\n fieldCandidates[name] = ef;\n if (sig.description) {\n fieldDescriptions[name] = sig.description;\n }\n }\n\n const weight = tierWeight('domain');\n const q: DomainQuestion = {\n id: `${factoryCallPlanOrbitalName(call)}.__entityFields`,\n orbitalName: factoryCallPlanOrbitalName(call),\n question: `Fields for ${entityName}`,\n reason: `Defines the data model for ${entityName}. Pick the fields that matter for your use case.`,\n inputType: 'multiselect',\n mutationTemplate: {\n kind: 'set-orbital-entity-fields',\n orbitalName: factoryCallPlanOrbitalName(call),\n },\n suggestedAnswers: candidateNames,\n defaultValue: candidateNames,\n fieldCandidates,\n tier: 'domain',\n weight,\n priority: weight,\n };\n if (Object.keys(fieldDescriptions).length > 0) {\n q.fieldDescriptions = fieldDescriptions;\n }\n return [q];\n}\n\n/**\n * Map a `FactorySignatureEntityField` to an `EntityField` without unsafe casts.\n * Scalar types translate directly to `ScalarEntityField`. `array` and `object`\n * translate to their variants (no extra required fields). `enum` produces an\n * `EnumEntityField` when `values` is present, otherwise falls back to `string`.\n * `relation` produces a `RelationEntityField` when `relation` is present, otherwise\n * falls back to `string`.\n */\nfunction signatureFieldToEntityField(f: FactorySignatureEntityField): EntityField {\n const base = {\n name: f.name,\n required: f.required,\n description: f.description,\n synonyms: f.synonyms,\n intrinsic: f.intrinsic,\n } as const;\n switch (f.type) {\n case 'string':\n case 'number':\n case 'boolean':\n case 'date':\n case 'timestamp':\n case 'datetime':\n // Semantic string domains carry no dependent payload, so they pass through\n // as-is and the question widget narrows the input accordingly.\n case 'email':\n case 'url':\n case 'phone':\n case 'uuid':\n case 'image':\n return { ...base, type: f.type };\n case 'array':\n return { ...base, type: 'array' };\n case 'object':\n return { ...base, type: 'object' };\n case 'enum':\n if (Array.isArray(f.values) && f.values.length > 0) {\n return { ...base, type: 'enum', values: f.values };\n }\n // No values present — safe fallback; payload would be invalid without them.\n return { ...base, type: 'string' };\n case 'relation':\n if (f.relation !== undefined) {\n return { ...base, type: 'relation', relation: f.relation };\n }\n // No relation config present — safe fallback.\n return { ...base, type: 'string' };\n case 'node':\n // Renderable content is computed by the trait's effects, never asked\n // for in a questionnaire — no question payload beyond the tag.\n return { ...base, type: 'node' };\n case 'event':\n // Event-name reference (struct-alias member, e.g. `ItemAction.event`)\n // — authored by the trait, never asked for in a questionnaire, same\n // posture as `node`.\n return { ...base, type: 'event' };\n case 'money':\n case 'instant':\n case 'file':\n case 'bytes':\n // No type-dependent payload — same posture as the semantic string\n // domains above.\n return { ...base, type: f.type };\n default: {\n const _exhaustive: never = f.type;\n return { ...base, type: 'string' };\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Capability-driven questions\n// ---------------------------------------------------------------------------\n\n/**\n * Emit one yes/no question per unique capability not already covered by\n * the ruleOverlay. Capabilities whose name matches a `policy`-tier config\n * knob on the same trait are skipped — that knob already gives the user\n * a direct toggle for the governance behavior, so a second question adds\n * noise. Only capabilities with no backing policy knob get a question.\n *\n * The emitted question uses `inputType: 'boolean'` (a plain yes/no toggle)\n * with a plain-English prompt and `helpText` explaining what enabling it\n * does. The `set-rule` mutation template remains unchanged.\n */\nfunction capabilityQuestions(\n call: FactoryCallSite,\n signature: FactorySignature,\n ruleCapabilities: ReadonlySet<string>,\n): DomainQuestion[] {\n const entityName =\n call.params.entityName ?? signature.entities[0]?.name ?? factoryCallPlanOrbitalName(call);\n const seen = new Set<string>();\n const out: DomainQuestion[] = [];\n for (const trait of signature.traits) {\n const policyKnobKeys = new Set(\n trait.overridableConfigKeys\n .filter((p) => p.tier === 'policy')\n .map((p) => p.key),\n );\n for (const cap of trait.capabilities) {\n if (seen.has(cap)) continue;\n seen.add(cap);\n if (ruleCapabilities.has(cap)) continue;\n // Skip if a policy-tier knob on this trait already surfaces the toggle.\n if (policyKnobKeys.has(cap)) continue;\n out.push({\n id: `${factoryCallPlanOrbitalName(call)}.capability.${cap}`,\n orbitalName: factoryCallPlanOrbitalName(call),\n question: capabilityPrompt(cap, entityName),\n helpText: capabilityHelp(cap, trait),\n capability: cap,\n inputType: 'boolean',\n mutationTemplate: {\n kind: 'set-rule',\n capability: cap,\n appliesTo: [entityName],\n },\n // Capabilities encode governance/policy decisions — high impact.\n weight: 3,\n priority: 3,\n });\n }\n }\n return out;\n}\n\n/** Plain-English yes/no prompt for a capability toggle. */\nfunction capabilityPrompt(capability: string, entity: string): string {\n const label = humanizeKey(capability);\n return `Enable ${label} for ${entity}?`;\n}\n\n/** How-to-answer help text for a capability question. */\nfunction capabilityHelp(\n capability: string,\n trait: FactoryTraitSignature,\n): string {\n return `Turns on the \"${capability}\" behavior from the ${trait.name} trait. Say yes to wire a governance rule into the schema.`;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction findSignature(\n catalog: ReadonlyArray<FactorySignature>,\n organism: string,\n orbital: string,\n): FactorySignature | undefined {\n return catalog.find((s) => s.organism === organism && s.orbital === orbital);\n}\n\nfunction collectRuleCapabilities(\n overlay: RuleOverlay | undefined,\n): ReadonlySet<string> {\n const out = new Set<string>();\n for (const r of overlay?.rules ?? []) {\n if (typeof r.capability === 'string') out.add(r.capability);\n }\n return out;\n}\n\n/** The plan's name for a call site's orbital — `orbitalName` when it differs from the catalog `orbital`. */\nexport function factoryCallPlanOrbitalName(call: FactoryCallSite): string {\n return call.orbitalName ?? call.orbital;\n}\n","/**\n * `answersToMutations(answers, questions)` — turns a\n * `DomainQuestionAnswers` record into a typed\n * `FactoryCallPlanMutation[]`. Each question's `mutationTemplate`\n * matches one variant of the union; the answer fills in the value.\n * `null` (or omitted) answers produce no mutation.\n *\n * @packageDocumentation\n */\n\nimport type { EntityField } from '../../types/field.js';\nimport type { EntityPersistence } from '../../types/entity.js';\nimport type { TraitReference } from '../../types/trait.js';\nimport type { FactoryParamValue } from '../types.js';\nimport type { RuleOverlayEntry } from '../overlays.js';\nimport type { FactoryCallPlanMutation } from '../mutate.js';\nimport type {\n DomainQuestion,\n DomainQuestionAnswer,\n DomainQuestionAnswers,\n FactoryCallPlanMutationTemplate,\n} from './types.js';\n\nconst PERSISTENCE_VALUES: ReadonlyArray<EntityPersistence> = [\n 'persistent',\n 'runtime',\n];\n\nexport function answersToMutations(\n answers: DomainQuestionAnswers,\n questions: ReadonlyArray<DomainQuestion>,\n): FactoryCallPlanMutation[] {\n const out: FactoryCallPlanMutation[] = [];\n for (const q of questions) {\n const answer = answers[q.id];\n if (answer === undefined || answer === null) continue;\n out.push(...answerToMutations(q.mutationTemplate, answer, q));\n }\n return out;\n}\n\nexport function answerToMutations(\n template: FactoryCallPlanMutationTemplate,\n answer: DomainQuestionAnswer,\n _question: DomainQuestion,\n): FactoryCallPlanMutation[] {\n switch (template.kind) {\n case 'set-orbital-entity-name': {\n if (typeof answer !== 'string' || answer.length === 0) return [];\n return [\n {\n kind: 'set-orbital-entity-name',\n orbitalName: template.orbitalName,\n name: answer,\n },\n ];\n }\n case 'set-orbital-entity-fields': {\n if (!isEntityFieldArray(answer)) return [];\n if (answer.length === 0) return [];\n return [\n {\n kind: 'set-orbital-entity-fields',\n orbitalName: template.orbitalName,\n fields: answer,\n },\n ];\n }\n case 'set-orbital-persistence': {\n if (!isPersistence(answer)) return [];\n return [\n {\n kind: 'set-orbital-persistence',\n orbitalName: template.orbitalName,\n persistence: answer,\n },\n ];\n }\n case 'set-orbital-collection': {\n if (typeof answer !== 'string' || answer.length === 0) return [];\n return [\n {\n kind: 'set-orbital-collection',\n orbitalName: template.orbitalName,\n collection: answer,\n },\n ];\n }\n case 'set-orbital-page-path': {\n if (typeof answer !== 'string' || answer.length === 0) return [];\n return [\n {\n kind: 'set-orbital-page-path',\n orbitalName: template.orbitalName,\n pageName: template.pageName,\n path: answer,\n },\n ];\n }\n case 'set-trait-override-config': {\n if (!isFactoryParamValue(answer)) return [];\n return [\n {\n kind: 'set-trait-override-config',\n orbitalName: template.orbitalName,\n traitName: template.traitName,\n key: template.configKey,\n value: answer,\n },\n ];\n }\n case 'add-extra-trait': {\n if (!isTraitReference(answer)) return [];\n return [\n {\n kind: 'add-extra-trait',\n orbitalName: template.orbitalName,\n trait: answer,\n },\n ];\n }\n case 'remove-extra-trait': {\n if (typeof answer !== 'string' || answer.length === 0) return [];\n return [\n {\n kind: 'remove-extra-trait',\n orbitalName: template.orbitalName,\n ref: answer,\n },\n ];\n }\n case 'set-rule': {\n if (typeof answer !== 'string') return [];\n if (answer !== 'yes') return [];\n const rule: RuleOverlayEntry = {\n id: `${template.capability}::${template.appliesTo.join(',')}`,\n capability: template.capability,\n description: `User accepted ${template.capability} for ${template.appliesTo.join(', ')}.`,\n appliesTo: template.appliesTo,\n };\n return [{ kind: 'set-rule', rule }];\n }\n case 'remove-rule': {\n return [{ kind: 'remove-rule', ruleId: template.ruleId }];\n }\n }\n}\n\nfunction isEntityFieldArray(\n a: DomainQuestionAnswer,\n): a is ReadonlyArray<EntityField> {\n if (!Array.isArray(a)) return false;\n for (const x of a) {\n if (typeof x !== 'object' || x === null) return false;\n if (!('name' in x) || !('type' in x)) return false;\n if (typeof x.name !== 'string' || typeof x.type !== 'string') return false;\n }\n return true;\n}\n\nfunction isPersistence(a: DomainQuestionAnswer): a is EntityPersistence {\n return (\n typeof a === 'string' &&\n (PERSISTENCE_VALUES as ReadonlyArray<string>).includes(a)\n );\n}\n\nfunction isFactoryParamValue(a: DomainQuestionAnswer): a is FactoryParamValue {\n if (a === null) return false;\n const t = typeof a;\n if (t === 'string' || t === 'number' || t === 'boolean') return true;\n if (Array.isArray(a)) return true;\n if (t === 'object') return true;\n return false;\n}\n\nfunction isTraitReference(a: DomainQuestionAnswer): a is TraitReference {\n if (typeof a !== 'object' || a === null || Array.isArray(a)) return false;\n if (!('ref' in a)) return false;\n return typeof a.ref === 'string';\n}\n","import type { EntityField } from '../types/field.js';\nimport type { TraitReference } from '../types/trait.js';\nimport type { EntityPersistence } from '../types/entity.js';\nimport type { RuleOverlay, RuleOverlayEntry } from './overlays.js';\nimport type { FactoryParamValue } from './types.js';\n\n/**\n * One slot the agent emits per orbital. Slim shape — agent-facing,\n * carries only what factory dispatch needs. The studio renders forms\n * over this; the projector turns it into a `FactoryCallSite`.\n */\nexport interface OrbitalCallInput {\n orbitalName: string;\n organism?: string;\n orbital?: string;\n entityName?: string;\n entityFields?: ReadonlyArray<EntityField>;\n persistence?: EntityPersistence;\n collection?: string;\n pagePaths?: Readonly<Record<string, string>>;\n traitOverlay?: Readonly<\n Record<\n string,\n {\n config?: Readonly<Record<string, FactoryParamValue>>;\n linkedEntity?: string;\n name?: string;\n }\n >\n >;\n extraTraits?: ReadonlyArray<TraitReference>;\n}\n\n/**\n * Discriminated union of typed edits. Each variant carries only the\n * payload pieces that change. The reducer is total over the union.\n */\nexport type FactoryCallPlanMutation =\n | {\n kind: 'set-orbital-entity-fields';\n orbitalName: string;\n fields: ReadonlyArray<EntityField>;\n }\n | { kind: 'set-orbital-entity-name'; orbitalName: string; name: string }\n | {\n kind: 'set-orbital-persistence';\n orbitalName: string;\n persistence: EntityPersistence;\n }\n | { kind: 'set-orbital-collection'; orbitalName: string; collection: string }\n | {\n kind: 'set-orbital-page-path';\n orbitalName: string;\n pageName: string;\n path: string;\n }\n | {\n kind: 'set-trait-override-config';\n orbitalName: string;\n traitName: string;\n key: string;\n value: FactoryParamValue;\n }\n | {\n kind: 'add-extra-trait';\n orbitalName: string;\n trait: TraitReference;\n }\n | { kind: 'remove-extra-trait'; orbitalName: string; ref: string }\n | { kind: 'set-rule'; rule: RuleOverlayEntry }\n | { kind: 'remove-rule'; ruleId: string };\n\n/**\n * State shape the reducer operates on. Mirrors the slice of the\n * agent's analysis result that incremental edits target.\n */\nexport interface FactoryCallPlanState {\n orbitals: ReadonlyArray<OrbitalCallInput>;\n ruleOverlay?: RuleOverlay;\n}\n\n/**\n * Immutable reducer. Returns a new state; never mutates input.\n */\nexport function applyFactoryCallPlanMutation(\n state: FactoryCallPlanState,\n m: FactoryCallPlanMutation,\n): FactoryCallPlanState {\n switch (m.kind) {\n case 'set-orbital-entity-fields':\n return patchOrbital(state, m.orbitalName, (o) => ({\n ...o,\n entityFields: m.fields,\n }));\n case 'set-orbital-entity-name':\n return patchOrbital(state, m.orbitalName, (o) => ({\n ...o,\n entityName: m.name,\n }));\n case 'set-orbital-persistence':\n return patchOrbital(state, m.orbitalName, (o) => ({\n ...o,\n persistence: m.persistence,\n }));\n case 'set-orbital-collection':\n return patchOrbital(state, m.orbitalName, (o) => ({\n ...o,\n collection: m.collection,\n }));\n case 'set-orbital-page-path':\n return patchOrbital(state, m.orbitalName, (o) => ({\n ...o,\n pagePaths: { ...(o.pagePaths ?? {}), [m.pageName]: m.path },\n }));\n case 'set-trait-override-config':\n return patchOrbital(state, m.orbitalName, (o) => {\n const overlay = o.traitOverlay ?? {};\n const existing = overlay[m.traitName] ?? {};\n const existingConfig = existing.config ?? {};\n return {\n ...o,\n traitOverlay: {\n ...overlay,\n [m.traitName]: {\n ...existing,\n config: { ...existingConfig, [m.key]: m.value },\n },\n },\n };\n });\n case 'add-extra-trait':\n return patchOrbital(state, m.orbitalName, (o) => {\n const existing = o.extraTraits ?? [];\n if (existing.some((t) => t.ref === m.trait.ref)) return o;\n return { ...o, extraTraits: [...existing, m.trait] };\n });\n case 'remove-extra-trait':\n return patchOrbital(state, m.orbitalName, (o) => ({\n ...o,\n extraTraits: (o.extraTraits ?? []).filter((t) => t.ref !== m.ref),\n }));\n case 'set-rule': {\n const rules = state.ruleOverlay?.rules ?? [];\n const idx = rules.findIndex((r) => r.id === m.rule.id);\n const next = idx >= 0\n ? rules.map((r, i) => (i === idx ? m.rule : r))\n : [...rules, m.rule];\n return {\n ...state,\n ruleOverlay: { ...(state.ruleOverlay ?? { rules: [] }), rules: next },\n };\n }\n case 'remove-rule': {\n const rules = state.ruleOverlay?.rules ?? [];\n const next = rules.filter((r) => r.id !== m.ruleId);\n return {\n ...state,\n ruleOverlay: { ...(state.ruleOverlay ?? { rules: [] }), rules: next },\n };\n }\n }\n}\n\nfunction patchOrbital(\n state: FactoryCallPlanState,\n orbitalName: string,\n patch: (o: OrbitalCallInput) => OrbitalCallInput,\n): FactoryCallPlanState {\n return {\n ...state,\n orbitals: state.orbitals.map((o) =>\n o.orbitalName === orbitalName ? patch(o) : o,\n ),\n };\n}\n","/**\n * FactorySignature → JsonSchema generator.\n *\n * Walks a resolved `FactorySignature` (post `inheritCallSiteOverrideTypes`)\n * and emits a JSON Schema for the corresponding `AnalysisOrbitalParams`\n * shape: `entityName / pagePath / fields / traitOverrides / extraTraits\n * / pages / theme`. The `traitOverrides` property is the densest part — one\n * entry per trait with a typed `config` sub-schema reflecting\n * `overridableConfigKeys` (type + enum + items + properties + label +\n * synonyms metadata).\n *\n * The output is consumed by V2's tool-calling layer\n * (`@almadar-io/agent`'s coordinator + per-orbital subagent) via\n * OpenAI's `tool.parameters` with `strict: true` — the LLM is masked\n * to the schema and physically cannot emit unknown trait names,\n * invented knob keys, or out-of-set enum values.\n *\n * `additionalProperties: false` is set at every level so unknown keys\n * are rejected. Inherited descriptive metadata (label, description,\n * synonyms) flows into `description` / `x-label` / `x-synonyms`\n * extension keywords so studio UIs + prompt rendering can use the\n * same single artifact.\n */\nimport { getAllPatternTypes } from '../patterns/helpers/prompt-helpers.js';\nimport { persistenceModeAllowsOverrides } from '../types/entity.js';\nimport { UI_SLOTS } from '../types/effect.js';\nimport type { EntityField } from '../types/field.js';\nimport { NUM_WIDTH_TAGS } from '../types/field.js';\nimport type {\n FactoryConfigParam,\n FactoryParamValue,\n FactorySignature,\n FactoryTraitSignature,\n JsonSchema,\n JsonSchemaType,\n JsonValue,\n} from './types.js';\n\n// ============================================================================\n// Top-level: signature → params schema\n// ============================================================================\n\nexport function signatureToParamsSchema(\n signature: FactorySignature,\n options?: { readonly themeNames?: readonly string[] },\n): JsonSchema {\n // `trait`-typed knobs must hold `@trait.<TraitName>` naming a trait on\n // THIS orbital — the exact contract rabit's `validateTraitTypedConfigRefs`\n // enforces at fill time with a retry. Baking the same values as an enum\n // makes the invalid reference inexpressible instead of caught-and-retried\n // (SCAN-TRAITREF-KNOB-1: the fill spent its attempts on\n // `sidebarTrait = \"AuthorDirectory\"` and the HIT demoted).\n const traitRefValues = signature.traits.map((t) => `@trait.${t.name}`).sort();\n const traitProps: { [key: string]: JsonSchema } = {};\n for (const trait of signature.traits) {\n // An imported trait is carried, not overridable at the call site.\n if (trait.importedFrom !== undefined) continue;\n // A trait can never be its OWN content/sidebar slot — the compiler rejects\n // it as `ORB_BINDING_TRAIT_SELF_REFERENCE`. Offering it is an always-invalid\n // value in a closed enum: measured 1,238 of 1,238 trait-typed knobs carried\n // their own trait, and a fill that picked it demoted a factory HIT\n // (std-lms/AppointmentPolicyFromStdOrbital). Excluded per-trait rather than\n // globally — a SIBLING trait remains a legitimate value.\n const selectableRefs = traitRefValues.filter((v) => v !== `@trait.${trait.name}`);\n const traitSchema = traitToOverrideSchema(trait, selectableRefs);\n if (traitSchema !== null) {\n traitProps[trait.name] = traitSchema;\n }\n }\n\n const allowPersistenceOverride = persistenceModeAllowsOverrides(\n signature.entities[0]?.persistence,\n signature.entities[0]?.dataBearing ?? false,\n );\n\n const properties: { [key: string]: JsonSchema } = {\n entityName: {\n type: 'string',\n description: 'PascalCase singular entity rename (e.g. \"Listing\", \"Member\"). Renames the DOMAIN concept and rewrites every `@Entity.*` reference. Use this when the user wants to rename the THING, not where it\\'s stored.',\n },\n pagePath: {\n type: 'string',\n description: \"URL path override for the orbital's first page.\",\n },\n fields: {\n type: 'array',\n description: 'Extra entity fields appended to the canonical entity. Caller wins on name collision.',\n items: ENTITY_FIELD_SCHEMA,\n },\n traitOverrides: Object.keys(traitProps).length > 0\n ? {\n type: 'object',\n additionalProperties: false,\n description:\n 'Per-trait knob overrides keyed on the canonical trait name. Each value can include `config` (knob values), `linkedEntity` (rebind), `events` (per-key rename map), `listens` (cross-orbital subscriptions), `emitsScope` (`internal` keeps emits local; `external` lets sibling orbitals listen), and `name` (rename the inlined trait). Only the traits + knobs shown here are valid — the schema rejects unknown keys.',\n properties: traitProps,\n }\n : { type: 'object', additionalProperties: false, properties: {} },\n extraTraits: {\n type: 'array',\n description: 'Sibling traits to compose beyond the factory-authored stack.',\n items: EXTRA_TRAIT_SCHEMA,\n },\n pages: {\n type: 'array',\n description: 'Per-page overrides keyed by canonical page name.',\n items: PAGE_OVERRIDE_SCHEMA,\n },\n theme: {\n type: 'string',\n // Theme names are injected by the caller rather than harvested from\n // `@almadar-ui/themes/*.css` — core is UPSTREAM of `@almadar/ui`, which\n // owns the theme CSS, and cannot read the filesystem to discover it.\n ...(options?.themeNames !== undefined && options.themeNames.length > 0\n ? { enum: [...options.themeNames] }\n : {}),\n description:\n 'Theme key — the full `data-theme` value applied to the layout root (e.g. linear-clean-light, terminal-dark, game-adventure-dark). Plan-level: pick ONE for the whole app — it is threaded to every orbital. Omit to leave the factory default.',\n },\n };\n\n if (signature.config && signature.config.length > 0) {\n const configProps: { [key: string]: JsonSchema } = {};\n for (const knob of signature.config) {\n configProps[knob.key] = knobToSchema(knob, undefined, traitRefValues);\n }\n properties.config = {\n type: 'object',\n additionalProperties: false,\n description: \"This orbital's own declared knobs (Orbital.config). Only the keys shown are valid.\",\n properties: configProps,\n };\n }\n\n if (allowPersistenceOverride) {\n properties.collection = {\n type: 'string',\n description: 'Override the persistence collection / table name. Defaults to `plural(entityName).toLowerCase()`. Use this when the user names the database/table/storage location (\"save them under X\", \"the table is called X\", \"in our database it\\'s X\") — NOT when they rename the domain concept (that\\'s `entityName`).',\n };\n properties.persistence = {\n type: 'string',\n enum: ['persistent', 'runtime'],\n description: 'Override the entity persistence mode. `persistent` = stored in the configured backend; `runtime` = in-memory session-scoped only.',\n };\n }\n\n const schema: JsonSchema = {\n type: 'object',\n additionalProperties: false,\n description: `Typed params for ${signature.organism} / ${signature.orbital}. Empty {} = factory defaults.`,\n properties,\n };\n assertNoUnsatisfiableEnum(schema, `${signature.organism}/${signature.orbital}`);\n return schema;\n}\n\n/**\n * The standing form of the self-reference bug: **a closed enum must not be\n * empty.** An empty `enum` permits nothing, so every value the model can\n * produce is rejected and the HIT demotes with no path back — strictly worse\n * than a wrong default, and invisible because each individual construct is\n * still legal JSON Schema.\n *\n * This is deliberately the GENERAL check rather than a second per-slot filter.\n * Each enum here is built by projecting one candidate list across many slots\n * (traits, entities, events, patterns, themes), and every such projection can\n * narrow to nothing for some signature — the trait case did, at 1,238 of 1,238\n * offers, and was found only because a scan happened to trip on it. Anything\n * that empties a candidate set now fails the bake loudly instead of shipping a\n * schema the compiler will always reject.\n */\nexport function assertNoUnsatisfiableEnum(node: JsonSchema, where: string, path = ''): void {\n if (Array.isArray(node.enum) && node.enum.length === 0) {\n throw new Error(\n `[signatures] ${where}: empty enum at \"${path || '<root>'}\" — the schema permits no value, ` +\n 'so every fill for this knob is rejected. Omit the knob instead of offering an unsatisfiable one.',\n );\n }\n for (const [key, child] of Object.entries(node.properties ?? {})) {\n assertNoUnsatisfiableEnum(child, where, path === '' ? key : `${path}.${key}`);\n }\n if (node.items !== undefined) assertNoUnsatisfiableEnum(node.items, where, `${path}[]`);\n}\n\n// ============================================================================\n// Trait override schema — one entry per trait in the signature\n// ============================================================================\n\nfunction traitToOverrideSchema(\n trait: FactoryTraitSignature,\n traitRefValues?: ReadonlyArray<string>,\n): JsonSchema | null {\n // Skip traits with zero overridable knobs AND no other override surface.\n // A `@rebindable` trait always has an override surface (linkedEntity), so\n // it keeps an entry even with zero config knobs.\n if (trait.overridableConfigKeys.length === 0 && trait.entityRebindable !== true) return null;\n\n const knobProps: { [key: string]: JsonSchema } = {};\n for (const knob of trait.overridableConfigKeys) {\n // A trait-typed knob on a trait with no SELECTABLE sibling has no valid\n // value at all — the only candidate was the enclosing trait, which the\n // compiler rejects as ORB_BINDING_TRAIT_SELF_REFERENCE. Omit it, the same\n // way `listens` is omitted for render-only traits below: an unsatisfiable\n // knob must not be offered.\n //\n // Without this the self-reference filter would silently DEGRADE such a\n // knob to a free string (`knobToSchema` only builds the enum when the set\n // is non-empty), reopening SCAN-TRAITREF-KNOB-1 for exactly the orbitals\n // the filter was meant to protect. `undefined` still means \"topology\n // unknown\" (legacy catalog) and keeps the free-string surface; only a\n // DEFINED-and-empty set is unsatisfiable.\n if (knob.type === 'trait' && traitRefValues !== undefined && traitRefValues.length === 0) {\n continue;\n }\n knobProps[knob.key] = knobToSchema(knob, trait, traitRefValues);\n }\n\n // `linkedEntity` is ONLY offered for traits whose binding the atom author\n // marked `@rebindable`. For fixed-binding traits it's omitted entirely so\n // the LLM physically cannot author a rebind the validator would reject.\n // rabit narrows the value to a closed enum of the organism's entities.\n const properties: { [key: string]: JsonSchema } = {\n config: {\n type: 'object',\n additionalProperties: false,\n properties: knobProps,\n },\n };\n if (trait.entityRebindable === true) {\n properties.linkedEntity = {\n type: 'string',\n description: \"Rebind this trait to a different entity in the organism (rewrites every @entity.* / ref / fetch / persist binding inside it).\",\n };\n }\n\n // `listens[].triggers` must name an event THIS trait's own state machine\n // transitions on (ORB_X_LISTEN_TRIGGER_UNMATCHED otherwise). When the\n // signature carries the trait's topology, mask the LLM to it: enum the\n // triggers when transitions exist, and omit `listens` entirely for\n // render-only traits (zero transitions — no listen entry can ever be\n // valid; target the sibling trait that owns the transition instead).\n // Unknown topology (legacy catalogs) keeps the free-string surface.\n const triggersSchema: JsonSchema =\n trait.transitionEvents !== undefined && trait.transitionEvents.length > 0\n ? {\n type: 'string',\n enum: [...trait.transitionEvents],\n description: 'Local state-machine event fired when the subscription matches. Must be one of the events this trait\\'s own transitions already react to.',\n }\n : {\n type: 'string',\n description: 'Local state-machine event fired when the subscription matches.',\n };\n const listensProperty: { [key: string]: JsonSchema } =\n trait.transitionEvents !== undefined && trait.transitionEvents.length === 0\n ? {}\n : {\n listens: {\n type: 'array',\n items: {\n type: 'object',\n additionalProperties: false,\n required: ['event', 'triggers'],\n properties: {\n event: { type: 'string', description: 'Event key to subscribe to (bare name, no orbital prefix).' },\n triggers: triggersSchema,\n scope: { type: 'string', enum: ['internal', 'external'], description: '`internal` = same-orbital events. `external` = events from sibling orbitals (use this for cross-orbital reactivity).' },\n },\n },\n description: 'Replace this trait\\'s `listens` entirely. Empty array clears upstream listeners. For cross-orbital reactivity, add an entry with `scope: \"external\"` matching the source orbital\\'s emit event.',\n },\n };\n\n return {\n type: 'object',\n additionalProperties: false,\n description: `Override knobs for ${trait.name}.`,\n properties: {\n ...properties,\n name: {\n type: 'string',\n description: \"Rename the inlined trait at the call site. Does NOT change topology — just the trait's local name.\",\n },\n events: {\n type: 'object',\n additionalProperties: { type: 'string' },\n description: 'Per-key event rename map (e.g. `{ \"OPEN\": \"ADD_ITEM\" }`). Rewrites the events array, transition triggers, emit/listen event keys, and `[\"emit\", X]` SExpression literals inside the trait.',\n },\n ...listensProperty,\n emitsScope: {\n type: 'string',\n enum: ['internal', 'external'],\n description: '`internal` = emits stay local to this orbital. `external` = sibling orbitals can listen. Set to `external` when another orbital needs to react to this trait\\'s events (counter updates, list refreshes, badges, etc.).',\n },\n },\n };\n}\n\n// ============================================================================\n// Knob schema — FactoryConfigParam → JsonSchema for one knob\n// ============================================================================\n\nfunction knobToSchema(\n knob: FactoryConfigParam,\n trait?: FactoryTraitSignature,\n traitRefValues?: ReadonlyArray<string>,\n): JsonSchema {\n const out: JsonSchema = {};\n\n // Map the knob's declared type tag to a JSON Schema type.\n const baseType = mapKnobType(knob.type);\n if (baseType !== null) out.type = baseType;\n\n // Enum constraint — knob.enumValues becomes JSON Schema's `enum`.\n if (knob.enumValues && knob.enumValues.length > 0) {\n out.enum = [...knob.enumValues];\n // If type wasn't already string-ish, pin it to string for enum.\n if (!out.type) out.type = 'string';\n }\n\n // `slot`-typed knobs are a CLOSED registry (UI_SLOTS) — unconstrained,\n // the fill invents values like 'inline' that hard-fail the validator\n // (ORB_T_INVALID_SLOT_DEFAULT) and demote the whole HIT. Same posture\n // as the listens-triggers enum: constrain at the schema so an invalid\n // value can't reach the factory.\n if (knob.type === 'slot' && out.enum === undefined) {\n out.enum = [...UI_SLOTS];\n }\n\n // `pattern`-typed knobs are the same closed-registry shape as slots —\n // unconstrained, the fill invents names like 'full' that hard-fail\n // ORB_T_INVALID_PATTERN_DEFAULT + ORB_RUI_INVALID_PATTERN and demote the\n // HIT (SCAN-PATTERN-KNOB-1, organism-scan run12). Enum over the pattern\n // registry's type names; same self-consistency guard as the other pins.\n if (knob.type === 'pattern' && out.enum === undefined) {\n const patternTypes: readonly string[] = getAllPatternTypes();\n const selfConsistent =\n typeof knob.default !== 'string' ||\n knob.default === '' ||\n patternTypes.includes(knob.default);\n if (patternTypes.length > 0 && selfConsistent) {\n out.enum = [...patternTypes].sort();\n }\n }\n\n // `trait`-typed knobs: enum over the orbital's canonical `@trait.<name>`\n // references — the same value set `validateTraitTypedConfigRefs` accepts.\n // Same guards as the other reference pins: skip when unavailable or when\n // the knob's own non-empty default is missing from the set.\n if (\n knob.type === 'trait' &&\n out.enum === undefined &&\n traitRefValues !== undefined &&\n traitRefValues.length > 0\n ) {\n const selfConsistent =\n typeof knob.default !== 'string' ||\n knob.default === '' ||\n traitRefValues.includes(knob.default);\n if (selfConsistent) {\n out.enum =\n typeof knob.default === 'string' && knob.default === ''\n ? ['', ...traitRefValues]\n : [...traitRefValues];\n }\n }\n\n // `event`-DECLARED knobs (the `.lolo` type, never inferred) reference an\n // event in the owning trait's vocabulary — unconstrained, the fill\n // invents literals like 'note.search' that fail\n // ORB_T_INVALID_EVENT_DEFAULT and demote the HIT (SCAN-EVENT-KNOB-1).\n // Enum = the trait's event union from the signature, plus '' (the\n // validator's default-off outlet). Canonical names stay correct under\n // call-site renames because the inline pass rename-folds event-typed\n // knob values (event_typed_knob_rename_fold.rs). Guards: skip when the\n // union is empty (vacuous, compiler parity) or when the knob's own\n // non-empty default is missing from it (an enum that forbids its own\n // default is wrong by construction).\n //\n // A-UNIFY: a DEFINER knob (A-UNIFY spells it `: event` same as a\n // reference knob) is exempt — its value CREATES the event name rather\n // than referencing one, so pinning it to the trait's existing vocabulary\n // would forbid the very name it's meant to introduce. Left UNPINNED is\n // deliberate and correct: any name is valid by construction, a definer\n // cannot go stale. Do not \"fix\" this back to a pin.\n const isDefinerKnob = trait?.definerKnobs?.includes(knob.key) ?? false;\n if (knob.type === 'event' && isDefinerKnob) {\n out['x-role'] = 'definer';\n }\n if (knob.type === 'event' && !isDefinerKnob && out.enum === undefined && trait !== undefined) {\n const vocabulary = new Set<string>([\n ...trait.emittedEvents,\n ...trait.listenedEvents,\n ...(trait.transitionEvents ?? []),\n ]);\n vocabulary.delete('');\n const selfConsistent =\n typeof knob.default !== 'string' ||\n knob.default === '' ||\n vocabulary.has(knob.default);\n if (vocabulary.size > 0 && selfConsistent) {\n out.enum = ['', ...[...vocabulary].sort()];\n }\n }\n\n // Recursive shape for arrays: `items` shape from EntityField.\n if (knob.items !== undefined) {\n out.items = entityFieldToSchema(knob.items);\n if (!out.type) out.type = 'array';\n }\n\n // Recursive shape for objects / structs.\n if (knob.properties !== undefined && Object.keys(knob.properties).length > 0) {\n const props: { [key: string]: JsonSchema } = {};\n for (const [k, ef] of Object.entries(knob.properties)) {\n props[k] = entityFieldToSchema(ef);\n }\n out.properties = props;\n if (!out.type) out.type = 'object';\n }\n\n // Default value (if any) — passes through as JsonValue.\n if (knob.default !== undefined) {\n out.default = toJsonValue(knob.default);\n }\n\n // Descriptive metadata — surfaced for prompt rendering + studio UIs.\n if (knob.description) out.description = knob.description;\n if (knob.label) out['x-label'] = knob.label;\n if (knob.synonyms) out['x-synonyms'] = knob.synonyms;\n if (knob.tier) out['x-tier'] = knob.tier;\n\n return out;\n}\n\n// ============================================================================\n// EntityField → JsonSchema (used by knob.items / knob.properties / fields)\n// ============================================================================\n\nfunction entityFieldToSchema(field: EntityField): JsonSchema {\n // A union's `properties` are its VARIANTS by name, not members: offer one\n // closed shape per variant so a value is exactly one of them.\n if (field.type === 'union') {\n const variants = field.values\n .map((name) => field.properties?.[name])\n .filter((v): v is EntityField => v !== undefined);\n if (variants.length === 0) return {};\n return { oneOf: variants.map((v) => ({ ...entityFieldToSchema(v), additionalProperties: false })) };\n }\n const out: JsonSchema = {};\n const baseType = mapEntityFieldType(field.type);\n if (baseType !== null) out.type = baseType;\n\n // Enum / scalar vocabulary hint — both `enum` and scalar variants\n // carry an optional `values: string[]` in the discriminated union.\n if (\n (field.type === 'enum' ||\n field.type === 'string' ||\n field.type === 'number' ||\n field.type === 'boolean' ||\n field.type === 'date' ||\n field.type === 'timestamp' ||\n field.type === 'datetime') &&\n Array.isArray(field.values) &&\n field.values.length > 0\n ) {\n out.enum = field.values.filter(isEnumLeaf);\n if (!out.type) out.type = 'string';\n }\n if (field.type === 'array' && field.items !== undefined) {\n out.items = entityFieldToSchema(field.items);\n if (!out.type) out.type = 'array';\n }\n // Struct shape — a named struct like `[ItemAction]` lowers to an object\n // EntityField whose `properties` carry the per-field sub-tree with\n // `required` flags. Projecting them (plus `required`) lets the ajv\n // contract boundary reject a wrong field name (e.g. `action` instead of\n // `event`) at fill time instead of the factory type-check failing the\n // build afterwards and demoting the orbital.\n if (field.properties !== undefined && Object.keys(field.properties).length > 0) {\n const props: { [key: string]: JsonSchema } = {};\n const required: string[] = [];\n for (const [k, ef] of Object.entries(field.properties)) {\n props[k] = entityFieldToSchema(ef);\n if (ef.required === true) required.push(k);\n }\n out.properties = props;\n if (required.length > 0) out.required = required;\n if (!out.type) out.type = 'object';\n }\n if (field.default !== undefined) {\n out.default = toJsonValue(field.default);\n }\n return out;\n}\n\nfunction isEnumLeaf(v: JsonValue): v is string | number | boolean {\n return typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean';\n}\n\n// ============================================================================\n// Type mappers\n// ============================================================================\n\nfunction mapKnobType(knobType: string): JsonSchemaType | null {\n // Strip array bracket wrapper for `[T]` types.\n if (knobType.startsWith('[') && knobType.endsWith(']')) return 'array';\n switch (knobType) {\n case 'string':\n return 'string';\n case 'number':\n case 'integer':\n case 'float':\n return knobType === 'integer' ? 'integer' : 'number';\n case 'boolean':\n case 'bool':\n return 'boolean';\n case 'object':\n // An orbital value is `{ behavior, orbital, …import body }` on the wire; a behavior value is `{ behavior }`.\n case 'orbital':\n case 'behavior':\n return 'object';\n case 'array':\n return 'array';\n case 'enum':\n return 'string';\n // String-valued reference tags: a trait ref is \"@trait.<Name>\", a\n // slot/pattern/icon/asset is a registry name, an event is an event\n // key, a date is an ISO string. These were mis-emitted as `object`\n // (11k knobs catalog-wide carried an object type with a string\n // default), which was harmless while tool schemas were advisory but\n // breaks hard validation.\n case 'trait':\n case 'slot':\n case 'pattern':\n case 'secret':\n case 'icon':\n case 'asset':\n case 'event':\n case 'EventAddress':\n case 'CallKey':\n case 'field':\n case 'date':\n return 'string';\n case 'render-ui':\n // First-class render-ui SExpr tree (Layer 3 variant-body knob).\n // The runtime substitutes the value into the parent atom's\n // `(render-ui main @config.X)` body verbatim. Schema-wise it's a\n // recursive object with `type: \"<pattern-name>\"` + nested\n // `children`; for LLM JSON Schema we surface it as `object` and\n // rely on the knob description + pattern-registry awareness for\n // shape guidance.\n return 'object';\n // Polymorphic values: a `node` accepts a string leaf OR a render-ui\n // tree; `json`/`unknown` carry arbitrary JSON. No `type` — the\n // schema stays structurally honest instead of over-constraining.\n case 'node':\n case 'json':\n case 'unknown':\n return null;\n default:\n // Custom struct types (e.g. `FormatOption`) — `knobToSchema` pins\n // `object` iff `knob.properties` captured a shape; otherwise the\n // knob stays untyped rather than claiming a shape we don't know.\n return null;\n }\n}\n\nexport function mapEntityFieldType(fieldType: string): JsonSchemaType | null {\n switch (fieldType) {\n case 'string':\n case 'date':\n case 'timestamp':\n case 'datetime':\n // JSON Schema has no email/url/phone/uuid/image primitive — the declared\n // domain is carried on the signature's own `type` field (see\n // `asSchemaFieldType`), not here. This maps to the WIRE shape only.\n case 'email':\n case 'url':\n case 'phone':\n case 'uuid':\n case 'image':\n case 'bytes':\n return 'string';\n case 'number':\n case 'instant':\n return 'number';\n case 'boolean':\n return 'boolean';\n case 'array':\n return 'array';\n case 'object':\n case 'relation':\n case 'orbital':\n case 'behavior':\n return 'object';\n case 'enum':\n return 'string';\n case 'trait':\n case 'slot':\n case 'pattern':\n case 'secret':\n return 'string';\n // Phase B (SCAN-EVENT-KNOB-2): event-name reference — a string at the\n // wire level, same as `mapKnobType`'s `case 'event'` (that asymmetry\n // — this function fell to `default: null`, leaving struct-field\n // `event` members with NO json-schema type — was the bug).\n case 'event':\n case 'EventAddress':\n case 'CallKey':\n case 'field':\n return 'string';\n // Polymorphic renderable content: a node accepts a string leaf OR a\n // render-ui tree — no JSON-Schema `type` constraint, mirroring\n // `mapKnobType`'s `case 'node'`. (The default would return null too;\n // explicit for parity and self-documentation.)\n case 'node':\n return null;\n default:\n return null;\n }\n}\n\n// ============================================================================\n// Coerce arbitrary value into JsonValue (no unknown leaks)\n// ============================================================================\n\n/**\n * Widen the two JSON-shaped value types the signature carries\n * (`FactoryConfigParam.default` is `FactoryParamValue`, `EntityField.default`\n * is `JsonValue`) into the mutable `JsonValue` a schema `default` holds.\n *\n * Typed as their union rather than `unknown`: both are already JSON by\n * construction, so no escape hatch is needed and the recursion stays checked.\n * Non-finite numbers become `null` because `NaN`/`Infinity` have no JSON\n * encoding and would serialise as `null` anyway — better to say so here than\n * to let `JSON.stringify` decide silently.\n */\nfunction toJsonValue(value: FactoryParamValue | JsonValue): JsonValue {\n if (value === null) return null;\n if (typeof value === 'string') return value;\n if (typeof value === 'number') return Number.isFinite(value) ? value : null;\n if (typeof value === 'boolean') return value;\n if (Array.isArray(value)) {\n return value.map(toJsonValue);\n }\n const out: { [key: string]: JsonValue } = {};\n for (const [k, v] of Object.entries(value)) {\n out[k] = toJsonValue(v);\n }\n return out;\n}\n\n// ============================================================================\n// Shared schemas for entity field / extra trait / page override entries\n// ============================================================================\n\n/**\n * Discriminated-union shape for an entity field. Each `oneOf` branch\n * pins `type` to a literal and lists its dependent required slots:\n * - `type === 'enum'` REQUIRES `values: string[]`\n * - `type === 'relation'` REQUIRES `relation: { entity, cardinality }`\n * - `type === 'array'` MAY carry `items` (optional for legacy\n * codegen emit; lolo + Rust validator handle typed-element cases)\n * - other scalars accept the base shape\n *\n * `additionalProperties: false` at every level rejects unknown keys at\n * the LLM tool-call layer. Mirrors `EntityField` discriminated union\n * from `@almadar/core` (8.6.2).\n */\nconst ENTITY_FIELD_BASE_PROPS = {\n name: { type: 'string' as JsonSchemaType, description: 'Field name (camelCase).' },\n required: { type: 'boolean' as JsonSchemaType },\n primaryKey: { type: 'boolean' as JsonSchemaType },\n intrinsic: { type: 'boolean' as JsonSchemaType },\n min: { type: 'number' as JsonSchemaType },\n max: { type: 'number' as JsonSchemaType },\n description: { type: 'string' as JsonSchemaType },\n synonyms: { type: 'string' as JsonSchemaType },\n mock: { type: 'string' as JsonSchemaType },\n mergedFrom: { type: 'string' as JsonSchemaType },\n projectedFrom: {\n type: 'object' as JsonSchemaType,\n additionalProperties: false,\n required: ['type'],\n properties: { type: { type: 'string' as JsonSchemaType }, field: { type: 'string' as JsonSchemaType } },\n },\n properties: { type: 'object' as JsonSchemaType, additionalProperties: { $ref: 'urn:almadar:entity-field#/$defs/field' } },\n values: { type: 'array' as JsonSchemaType, items: { type: 'string' as JsonSchemaType } },\n default: {\n type: ['string', 'number', 'boolean', 'null', 'array', 'object'] as ReadonlyArray<JsonSchemaType>,\n } as JsonSchema,\n};\n// Includes the semantic domains: without them an L1 factory HIT cannot express\n// an email field at all, so `fill_params` could never produce one.\nconst SCALAR_FIELD_TYPES: ReadonlyArray<string> = [\n 'string', 'number', 'int', ...NUM_WIDTH_TAGS, 'boolean', 'date', 'timestamp', 'datetime', 'instant',\n 'email', 'url', 'phone', 'uuid', 'image', 'money',\n 'file', 'bytes', 'trait', 'slot', 'pattern', 'node', 'event', 'EventAddress', 'CallKey', 'SExpr',\n];\nconst SCALAR_FIELD_BRANCH: JsonSchema = {\n type: 'object',\n additionalProperties: false,\n required: ['name', 'type'],\n properties: {\n ...ENTITY_FIELD_BASE_PROPS,\n type: { type: 'string', enum: SCALAR_FIELD_TYPES, description: 'Field type tag.' },\n },\n};\nconst ENUM_FIELD_BRANCH: JsonSchema = {\n type: 'object',\n additionalProperties: false,\n required: ['name', 'type', 'values'],\n properties: {\n ...ENTITY_FIELD_BASE_PROPS,\n type: { type: 'string', enum: ['enum'], description: 'Enum field.' },\n values: {\n type: 'array',\n description: 'Closed string vocabulary. e.g. [\"active\",\"inactive\",\"pending\"].',\n minItems: 1,\n items: { type: 'string' },\n },\n },\n};\nconst RELATION_FIELD_BRANCH: JsonSchema = {\n type: 'object',\n additionalProperties: false,\n required: ['name', 'type', 'relation'],\n properties: {\n ...ENTITY_FIELD_BASE_PROPS,\n type: { type: 'string', enum: ['relation'], description: 'Relation (FK) field.' },\n relation: {\n type: 'object',\n additionalProperties: false,\n required: ['entity'],\n properties: {\n entity: { type: 'string', description: 'Sibling entity name (PascalCase singular).' },\n entityId: { type: 'string' },\n cardinality: { type: 'string', enum: ['one', 'many'] },\n field: { type: 'string' },\n onDelete: { type: 'string', enum: ['cascade', 'nullify', 'restrict'] },\n },\n description: 'Relation target. `cardinality: \"one\"` for FK (customerId → one Customer); \"many\" for collection (tags → many Tag).',\n },\n },\n};\nconst ARRAY_FIELD_BRANCH: JsonSchema = {\n type: 'object',\n additionalProperties: false,\n required: ['name', 'type'],\n properties: {\n ...ENTITY_FIELD_BASE_PROPS,\n type: { type: 'string', enum: ['array'], description: 'Array field.' },\n items: { $ref: 'urn:almadar:entity-field#/$defs/field' },\n },\n};\n// A nested structure within the entity: an `object` declares its members\n// (struct) or its value type (map). A shapeless `object` is not offered —\n// `orb validate` rejects it (ORB_T_GENERIC_TYPE_DEPRECATED).\nconst OBJECT_FIELD_BRANCH: JsonSchema = {\n type: 'object',\n additionalProperties: false,\n required: ['name', 'type'],\n anyOf: [{ required: ['properties'] }, { required: ['items'] }],\n properties: {\n ...ENTITY_FIELD_BASE_PROPS,\n type: { type: 'string', enum: ['object'], description: 'Struct members or map value shape.' },\n items: { $ref: 'urn:almadar:entity-field#/$defs/field' },\n },\n};\nconst UNION_FIELD_BRANCH: JsonSchema = {\n type: 'object',\n additionalProperties: false,\n required: ['name', 'type', 'values'],\n properties: {\n ...ENTITY_FIELD_BASE_PROPS,\n type: { type: 'string', enum: ['union'] },\n values: { ...ENTITY_FIELD_BASE_PROPS.values, minItems: 1 },\n },\n};\nconst TUPLE_FIELD_BRANCH: JsonSchema = {\n type: 'object',\n additionalProperties: false,\n required: ['name', 'type', 'properties'],\n properties: {\n ...ENTITY_FIELD_BASE_PROPS,\n type: { type: 'string', enum: ['tuple'] },\n properties: { ...ENTITY_FIELD_BASE_PROPS.properties, minProperties: 1 },\n },\n};\nconst ENTITY_FIELD_BRANCHES: ReadonlyArray<JsonSchema> = [\n SCALAR_FIELD_BRANCH,\n ENUM_FIELD_BRANCH,\n RELATION_FIELD_BRANCH,\n ARRAY_FIELD_BRANCH,\n OBJECT_FIELD_BRANCH,\n UNION_FIELD_BRANCH,\n TUPLE_FIELD_BRANCH,\n];\nexport const ENTITY_FIELD_SCHEMA: JsonSchema = {\n $id: 'urn:almadar:entity-field',\n oneOf: ENTITY_FIELD_BRANCHES,\n $defs: {\n field: {\n oneOf: ENTITY_FIELD_BRANCHES.map(branch => ({ ...branch, required: branch.required?.filter(key => key !== 'name') })),\n },\n },\n};\n\nconst EXTRA_TRAIT_SCHEMA: JsonSchema = {\n type: 'object',\n additionalProperties: false,\n required: ['from', 'as', 'ref'],\n properties: {\n from: { type: 'string', description: 'Registry path (e.g. std/behaviors/std-approval-request).' },\n as: { type: 'string', description: 'Local alias used in `ref`.' },\n ref: { type: 'string', description: 'Trait reference (Alias.traits.X).' },\n name: { type: 'string', description: 'Optional rename of the inlined trait.' },\n linkedEntity: { type: 'string', description: 'Optional entity rebinding.' },\n emitsScope: { type: 'string', enum: ['internal', 'external'] },\n },\n};\n\nconst PAGE_OVERRIDE_SCHEMA: JsonSchema = {\n type: 'object',\n additionalProperties: false,\n required: ['name'],\n properties: {\n name: { type: 'string', description: 'Canonical page name from the orbital.' },\n path: { type: 'string', description: 'URL path override.' },\n linkedEntity: { type: 'string', description: 'Rebind the primary entity.' },\n },\n};\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types/bus.ts"],"names":[],"mappings":";;;;;;AA8MO,IAAM,oBAAA,GAA0D,EAAE,MAAA,CAAO;AAAA,E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AAA,EAAS;AAAA,EAC7B,UAAU,CAAA,CAAE,KAAA,CAAM,EAAE,MAAA,EAAQ,EAAE,QAAA,EAAS;AAAA,EACvC,KAAA,EAAO,CAAA,CAAE,MAAA,EAAO,CAAE,QAAA;AACpB,CAAC;AAyBM,IAAM,uBAAA,GAAgE,EAAE,MAAA,CAAO;AAAA,EACpF,KAAA,EAAO,EAAE,MAAA,EAAO;AAAA,EAChB,OAAA,EAAS,mBAAmB,QAAA,EAAS;AAAA,EACrC,MAAA,EAAQ,oBAAA;AAAA,EACR,cAAA,EAAgB,CAAA,CAAE,MAAA,EAAO,CAAE,QAAA;AAC7B,CAAC","file":"chunk-6H3UIZR2.js","sourcesContent":["/**\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 { RawUserClaimsSchema, type RawUserClaims, type UserContext } from \"./user.js\";\nimport type { RowQueryPage } from \"../service-types.js\";\nimport { ServerEffectResultSchema, type ServerEffectResult } from \"./effect-result.js\";\nimport type { ExternalInput } from \"../access/contract.js\";\nimport { JsonValueSchema, type JsonObject, type JsonValue } from \"./json.js\";\nimport { isEventResponse, type ClientEffectByTrait, type HostAskCompletion, type EventRequest, type EventResponse, type FrameDelta, type HopEffect, type HopEffectStatus, type TransitionHop, type TransitionRejection, type TransitionRejectionCode } from \"../generated/kernel-wire.js\";\n\nexport type { ClientEffectByTrait, HopEffect, HopEffectStatus, TransitionHop, TransitionRejection, TransitionRejectionCode };\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 type 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 `EventRequest.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 * The row of the emitting trait's entity that made the emit, when the trait's rows are addressed by a `per`\n * listener. A listener with a `per` clause evaluates its own key; one without ignores this.\n */\n instanceKey?: string;\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 type 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 type DispatchLog = {\n prevEvents: DeliveryRecord[];\n prevStates: string[];\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 instanceKey: z.string().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 type 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 type 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 `EventResponse.clientEffectsByTrait`.\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, JsonObject | 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\n/** A `runsOn: client` host-port effect (`auth/sign-out`, `audio/*`) the client host answers; its arguments are resolved. */\nexport type ClientHostAskTuple = ['host-ask', string, JsonValue[]] | ['host-ask', string, JsonValue[], HostAskCompletion];\n\n/** The return address of a `host-ask` (EXEC-DIST-13/14): the generated wire type, one copy. */\nexport type { HostAskCompletion };\n\nexport type ClientEffectTuple =\n | ClientRenderUITuple\n | ClientNavigateTuple\n | ClientNavigateBackTuple\n | ClientHostAskTuple;\n\n/** Zod twin of `ClientRenderUITuple`. */\nexport const ClientRenderUITupleSchema = z.tuple([z.literal('render-ui'), z.string(), z.record(z.string(), JsonValueSchema).nullable()]);\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 `ClientHostAskTuple`. */\nexport const HostAskCompletionSchema = z.object({\n trait: z.string(),\n entityId: z.string().optional(),\n key: z.string().optional(),\n success: z.string().optional(),\n failure: z.string().optional(),\n onMessage: z.string().optional(),\n}).strict();\n\nexport const ClientHostAskTupleSchema = z.union([\n z.tuple([z.literal('host-ask'), z.string(), z.array(JsonValueSchema)]),\n z.tuple([z.literal('host-ask'), z.string(), z.array(JsonValueSchema), HostAskCompletionSchema]),\n]);\n\n/** Zod twin of `ClientEffectTuple`. */\nexport const ClientEffectTupleSchema: z.ZodType<ClientEffectTuple> = z.union([\n ClientRenderUITupleSchema,\n ClientNavigateTupleSchema,\n ClientNavigateBackTupleSchema,\n ClientHostAskTupleSchema,\n]);\n\n// ============================================================================\n// Event dispatch wire (single owner — canonical = the TS runtime)\n// ============================================================================\n\n/** The lifecycle events a trait runs when it enters a page (the first it handles). */\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 (`EventRequest.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 type MountSeed = {\n trait: string;\n event: LifecycleEvent;\n};\n\nexport const MountSeedSchema = z.object({ trait: z.string(), event: z.enum(LIFECYCLE_EVENTS) });\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 type 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: EventResponse; 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.custom<EventResponse>((v) => JsonValueSchema.safeParse(v).success && isEventResponse(JsonValueSchema.parse(v))), 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: EventResponse; 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<EventResponse>;\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` is what the kernel\n * parsed (`EventRequest::from_dispatch`); its `user` is the dispatch's viewer when the call names one.\n * A host that does not serve event requests leaves it out.\n */\n supportsDispatchStream?: true;\n dispatchRequest?(orbital: string, request: EventRequest, 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 /** A `program/resolve-rows` ask: `reference` resolved for the identity bound to `clientId`'s session (none: the anonymous viewer), `@read` applied by the kernel's one resolver. */\n resolveRows?(reference: RowSetRef, clientId: string | undefined): Promise<RowQueryPage>;\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// 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"]}
|