@almadar/core 10.13.0 → 10.14.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/builders.d.ts +3 -3
- package/dist/builders.js +38 -0
- package/dist/builders.js.map +1 -1
- package/dist/{compose-behaviors-CmTHzC3Z.d.ts → compose-behaviors-Ds6d_mMY.d.ts} +1 -1
- package/dist/factory/index.d.ts +3 -3
- package/dist/factory-runtime/index.d.ts +3 -3
- package/dist/factory-runtime/index.js +38 -0
- package/dist/factory-runtime/index.js.map +1 -1
- package/dist/index.d.ts +7 -7
- package/dist/index.js +39 -1
- package/dist/index.js.map +1 -1
- package/dist/{schema-DisJeRQc.d.ts → schema-BVcq7eXk.d.ts} +1459 -1459
- package/dist/{trait-Bwhkhv3V.d.ts → trait-Ctj2l6ma.d.ts} +271 -2
- package/dist/types/index.d.ts +6 -6
- package/dist/types/index.js +39 -1
- package/dist/types/index.js.map +1 -1
- package/dist/{types-CIi6Vxmc.d.ts → types-QQ9BTzkx.d.ts} +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types/field.ts","../src/types/asset.ts","../src/types/entity.ts","../src/types/effect.ts","../src/types/expression.ts","../src/types/state-machine.ts","../src/types/trait.ts","../src/types/page.ts","../src/types/domain.ts","../src/types/service.ts","../src/types/orbital.ts","../src/types/schema.ts","../src/types/bindings.ts","../src/types/binding.ts","../src/types/interaction-model.ts","../src/types/pattern.ts","../src/service-types.ts","../src/types/ir.ts","../src/types/json.ts","../src/types/validation.ts","../src/types/living.ts","../src/render-ui-edit.ts","../src/resolver.ts","../src/diff.ts","../src/summarize.ts","../src/factory/questions/generate.ts","../src/factory/questions/reducer.ts","../src/factory/translate.ts","../src/factory/diff.ts","../src/factory/mutate.ts","../src/builders/layout-strategy.ts","../src/builders/event-wiring.ts","../src/builders/compose-behaviors.ts","../src/state-machine/graph.ts","../src/state-machine/bfs.ts","../src/state-machine/guard-payloads.ts","../src/state-machine/replay-paths.ts","../src/state-machine/edge-walk.ts"],"names":["z","ref","_PATTERN_TYPES","inferTsType"],"mappings":";;;;;AAqCO,IAAM,eAAA,GAAkB,EAAE,IAAA,CAAK;AAAA,EAClC,QAAA;AAAA,EACA,QAAA;AAAA,EACA,SAAA;AAAA,EACA,MAAA;AAAA,EACA,WAAA;AAAA,EACA,UAAA;AAAA,EACA,OAAA;AAAA,EACA,QAAA;AAAA,EACA,MAAA;AAAA,EACA,UAAA;AAAA,EACA,OAAA;AAAA,EACA,MAAA;AAAA,EACA;AACJ,CAAC;AAiBM,IAAM,yBAAA,GAA4B,EAAE,IAAA,CAAK;AAAA,EAC5C,KAAA;AAAA,EACA,MAAA;AAAA,EACA,aAAA;AAAA,EACA,aAAA;AAAA,EACA;AACJ,CAAC,CAAA;AAmCM,IAAM,oBAAA,GAAuB,EAAE,MAAA,CAAO;AAAA,EACzC,QAAQ,CAAA,CAAE,MAAA,EAAO,CAAE,GAAA,CAAI,GAAG,2BAA2B,CAAA;AAAA,EACrD,KAAA,EAAO,CAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAAS;AAAA,EAC3B,WAAA,EAAa,0BAA0B,QAAA,EAAS;AAAA,EAChD,QAAA,EAAU,EAAE,IAAA,CAAK,CAAC,WAAW,SAAA,EAAW,UAAU,CAAC,CAAA,CAAE,QAAA,EAAS;AAAA;AAAA,EAE9D,UAAA,EAAY,CAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAAS;AAAA,EAChC,MAAA,EAAQ,CAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAAS;AAAA,EAC5B,IAAA,EAAM,0BAA0B,QAAA;AACpC,CAAC,CAAA,CAAE,SAAA,CAAU,CAAC,IAAA,KAAS;AAEnB,EAAA,MAAM,UAAA,GAA6B;AAAA,IAC/B,MAAA,EAAQ,IAAA,CAAK,MAAA,IAAU,IAAA,CAAK,MAAA,IAAU,EAAA;AAAA,IACt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,CAAA,MAAA,IAAW,KAAA,CAAM,IAAA,KAAS,QAAA,EAAU;AAClC,QAAA,OAAA,CAAQ,KAAA,CAAM,IAAI,CAAA,GAAI,CAAA,KAAA,EAAQ,MAAM,IAAI,CAAA,CAAA;AAAA,MAC1C,CAAA,MAAA,IAAW,KAAA,CAAM,IAAA,KAAS,QAAA,EAAU;AAClC,QAAA,OAAA,CAAQ,KAAA,CAAM,IAAI,CAAA,GAAI,CAAA;AAAA,MACxB,CAAA,MAAA,IAAW,KAAA,CAAM,IAAA,KAAS,SAAA,EAAW;AACnC,QAAA,OAAA,CAAQ,KAAA,CAAM,IAAI,CAAA,GAAI,IAAA;AAAA,MACxB,WAAW,KAAA,CAAM,IAAA,KAAS,QAAA,IAAY,KAAA,CAAM,SAAS,KAAA,EAAO;AAQ1D,QAAA,OAAA,CAAQ,KAAA,CAAM,IAAI,CAAA,GAAI,EAAC;AAAA,MACzB,CAAA,MAAO;AACL,QAAA,OAAA,CAAQ,KAAA,CAAM,IAAI,CAAA,GAAI,CAAA,KAAA,EAAQ,MAAM,IAAI,CAAA,CAAA;AAAA,MAC1C;AAAA,IACF;AACA,IAAA,OAAO,OAAA;AAAA,EACT;AAEA,EAAA,OAAO,EAAC;AACV","file":"index.js","sourcesContent":["/**\n * Field Types for Orbital Units\n *\n * Extracted from schema/data-entities.ts for the orbitals module.\n * These types define the field structure within orbital entities.\n *\n * @packageDocumentation\n */\n\nimport { z } from 'zod';\n\n// ============================================================================\n// Field Types\n// ============================================================================\n\n/**\n * Supported field types for entity fields.\n *\n * @example\n * { name: 'status', type: 'enum', values: ['draft', 'published'] }\n * { name: 'authorId', type: 'relation', relation: { entity: 'User', cardinality: 'one' } }\n */\nexport type FieldType =\n | 'string'\n | 'number'\n | 'boolean'\n | 'date'\n | 'timestamp'\n | 'datetime'\n | 'array'\n | 'object'\n | 'enum'\n | 'relation'\n | 'trait'\n | 'slot'\n | 'pattern';\n\nexport const FieldTypeSchema = z.enum([\n 'string',\n 'number',\n 'boolean',\n 'date',\n 'timestamp',\n 'datetime',\n 'array',\n 'object',\n 'enum',\n 'relation',\n 'trait',\n 'slot',\n 'pattern',\n]);\n\n// ============================================================================\n// Relation Configuration\n// ============================================================================\n\n/**\n * Cardinality for relation fields.\n * Matches Rust compiler's Cardinality enum.\n */\nexport type RelationCardinality = \n | 'one' \n | 'many' \n | 'one-to-many' \n | 'many-to-one' \n | 'many-to-many';\n\nexport const RelationCardinalitySchema = z.enum([\n 'one',\n 'many',\n 'one-to-many',\n 'many-to-one',\n 'many-to-many',\n]);\n\n/**\n * Configuration for relation fields (foreign keys).\n * Matches Rust compiler's RelationDefinition format.\n */\nexport interface RelationConfig {\n /** Target entity name (e.g., 'User', 'Task') - matches Rust's `entity` field */\n entity: string;\n /** Field on target entity (defaults to 'id') */\n field?: string;\n /** \n * Cardinality: one, many, one-to-many, many-to-one, many-to-many\n * Matches Rust compiler's cardinality format\n */\n cardinality?: RelationCardinality;\n /** Delete behavior */\n onDelete?: 'cascade' | 'nullify' | 'restrict';\n /** \n * Foreign key field name (for legacy compatibility).\n * @deprecated Use field instead\n */\n foreignKey?: string;\n /**\n * Target entity name (for legacy compatibility).\n * @deprecated Use entity instead\n */\n target?: string;\n /**\n * Cardinality type alias (for legacy compatibility).\n * @deprecated Use cardinality instead\n */\n type?: RelationCardinality;\n}\n\nexport const RelationConfigSchema = z.object({\n entity: z.string().min(1, 'Target entity is required'),\n field: z.string().optional(),\n cardinality: RelationCardinalitySchema.optional(),\n onDelete: z.enum(['cascade', 'nullify', 'restrict']).optional(),\n // Legacy compatibility fields\n foreignKey: z.string().optional(),\n target: z.string().optional(),\n type: RelationCardinalitySchema.optional(),\n}).transform((data) => {\n // Normalize legacy format to standard format\n const normalized: RelationConfig = {\n entity: data.entity || data.target || '',\n cardinality: data.cardinality || data.type,\n field: data.field,\n onDelete: data.onDelete,\n };\n return normalized;\n});\n\nexport type RelationConfigInput = z.input<typeof RelationConfigSchema>;\n\n// ============================================================================\n// Field Format\n// ============================================================================\n\n/**\n * Field format validators for string fields.\n */\nexport type FieldFormat =\n | 'email'\n | 'url'\n | 'phone'\n | 'date'\n | 'datetime'\n | 'uuid'\n /** Render hint: this string field stores an image URL. Mock adapters\n * generate a deterministic picsum.photos URL; UI patterns can branch\n * to an `<img>` instead of a `<typography>`. */\n | 'image'\n /** Render hint: avatar-shaped image (square, small). */\n | 'avatar'\n /** Render hint: thumbnail image (small landscape). */\n | 'thumbnail';\n\nexport const FieldFormatSchema = z.enum([\n 'email',\n 'url',\n 'phone',\n 'date',\n 'datetime',\n 'uuid',\n 'image',\n 'avatar',\n 'thumbnail',\n]);\n\n// ============================================================================\n// Entity Field — discriminated union by `type`\n// ============================================================================\n\n/**\n * Field-type tags that don't carry a type-dependent payload. The base\n * `EntityField` shape applies as-is.\n */\ntype ScalarFieldType =\n | 'string'\n | 'number'\n | 'boolean'\n | 'date'\n | 'timestamp'\n | 'datetime'\n | 'trait'\n | 'slot'\n | 'pattern';\n\n/** Fields shared across every variant. */\ninterface EntityFieldBase {\n /**\n * Field name (camelCase). Optional for nested item/property descriptors\n * where the name is implied by the parent (`items`, `properties[k]`).\n * Mirrors Rust's `FieldDefinition.name: Option<String>`.\n */\n name?: string;\n /** Whether the field is required */\n required?: boolean;\n /** Default value */\n default?: unknown;\n /** Validation format */\n format?: FieldFormat;\n /** Minimum value (for number) or length (for string) */\n min?: number;\n /** Maximum value or length */\n max?: number;\n /** Object property schemas keyed by property name (for object type).\n * Mirrors Rust's `FieldDefinition.properties: Option<HashMap<String,\n * FieldDefinition>>`. Populated by the lolo lowerer when a field /\n * config slot's type expression resolves to a struct shape\n * (`TypeExpr::Object`), including named-type aliases like `[MetricSpec]`. */\n properties?: Record<string, EntityField>;\n /** Runtime-managed widget state (authored `@intrinsic` in `.lolo`). Exempt\n * from the explicit-binding rule and never a domain-data bind target. */\n intrinsic?: boolean;\n /** Human/semantic description (authored `@description \"...\"` in `.lolo`).\n * Authoring/build-time metadata — factory-signature catalog, embeddings,\n * curation field-matching; the runtime ignores it. */\n description?: string;\n /** User-vocabulary synonyms (authored `@synonyms \"...\"` in `.lolo`).\n * Free text feeding catalog search / curation field-matching. */\n synonyms?: string;\n}\n\n/**\n * Scalar / structural fields — no type-dependent payload required.\n * `values?` is permitted as an OPTIONAL UI/validation hint (e.g. lolo's\n * `'a' | 'b' | 'c'` string-union sugar lowers to `type: 'string', values:\n * [...]`). Only `EnumEntityField` MANDATES values.\n */\nexport interface ScalarEntityField extends EntityFieldBase {\n type: ScalarFieldType;\n /** Optional vocabulary hint for scalar fields (e.g. string unions\n * authored as `'a'|'b'|'c'` in lolo). Not required at this variant. */\n values?: string[];\n}\n\n/** `type: 'enum'` REQUIRES the closed vocabulary in `values`. */\nexport interface EnumEntityField extends EntityFieldBase {\n type: 'enum';\n /** Closed string vocabulary the field accepts. */\n values: string[];\n}\n\n/** `type: 'relation'` REQUIRES the relation target binding. */\nexport interface RelationEntityField extends EntityFieldBase {\n type: 'relation';\n /** Relation target binding (entity + cardinality). */\n relation: RelationConfig;\n}\n\n/** `type: 'array'` — element schema in `items` strongly preferred but\n * optional for legacy compatibility with codegen-emitted scalar-array\n * fields (e.g. `{type: 'array', default: []}`). The lolo lowerer + Rust\n * validator catch typed-element-required cases downstream. */\nexport interface ArrayEntityField extends EntityFieldBase {\n type: 'array';\n /** Element schema for the array. */\n items?: EntityField;\n}\n\n/**\n * `type: 'object'` — a fixed-key struct (fields in `properties`) OR a\n * dynamic-key map (`Map K V` in `.lolo`; the uniform value schema lives in\n * `items`, mirroring an array's element schema). A distinct variant so `items`\n * is statically allowed only on object/array fields, never on scalars.\n */\nexport interface ObjectEntityField extends EntityFieldBase {\n type: 'object';\n /** Uniform value schema for a dynamic-key map (`Map K V`). */\n items?: EntityField;\n}\n\n/**\n * Entity field definition — discriminated union by `type`. Each variant\n * statically enforces its dependent payload (`values` for enum,\n * `relation` for relation, `items` for array) so TS / Zod / JSON Schema\n * consumers all agree on the dependency, not just the Rust validator.\n *\n * @example\n * { name: 'status', type: 'enum', values: ['draft', 'published'] }\n * { name: 'authorId', type: 'relation', relation: { entity: 'User', cardinality: 'one' } }\n * { name: 'tags', type: 'array', items: { type: 'string' } }\n */\nexport type EntityField =\n | ScalarEntityField\n | EnumEntityField\n | RelationEntityField\n | ArrayEntityField\n | ObjectEntityField;\n\n/**\n * Alias map for legacy/loose field-type spellings. Preprocessed into the\n * canonical `FieldType` enum before zod validates. Without this, agent-produced\n * schemas using `text`/`int`/`float`/`ts` were rejected at parse time — this\n * normalizes them so the rest of the pipeline sees only canonical types.\n */\nconst FIELD_TYPE_ALIASES: Record<string, FieldType> = {\n text: 'string',\n int: 'number',\n float: 'number',\n ts: 'timestamp',\n};\n\n/**\n * Zod schema for `EntityField`. Preprocess normalizes:\n * - legacy `type` aliases (text → string, int → number, etc.)\n * - legacy `enum: string[]` alias → `values: string[]`\n *\n * Branches on `type` so TS narrows the parsed output to the matching\n * discriminated-union variant.\n */\nexport const EntityFieldSchema: z.ZodType<EntityField, z.ZodTypeDef, unknown> = z.lazy(() => {\n const baseFieldShape = {\n name: z.string().min(1, 'Field name is required').optional(),\n required: z.boolean().optional(),\n default: z.unknown().optional(),\n format: FieldFormatSchema.optional(),\n min: z.number().optional(),\n max: z.number().optional(),\n properties: z.record(EntityFieldSchema).optional(),\n intrinsic: z.boolean().optional(),\n description: z.string().optional(),\n synonyms: z.string().optional(),\n };\n\n /** Build a scalar variant schema. `values?` is permitted as a hint;\n * only the enum variant mandates a non-empty values array. */\n function scalarVariant<T extends ScalarFieldType>(t: T) {\n return z.object({\n ...baseFieldShape,\n type: z.literal(t),\n values: z.array(z.string()).optional(),\n });\n }\n\n return z.preprocess(\n (input) => {\n if (\n input === null ||\n typeof input !== 'object' ||\n !('type' in input) ||\n typeof (input as { type: unknown }).type !== 'string'\n ) {\n return input;\n }\n const obj = input as { type: string; enum?: unknown; values?: unknown };\n const next: { type: string; enum?: unknown; values?: unknown } = { ...obj };\n const aliased = FIELD_TYPE_ALIASES[obj.type];\n if (aliased !== undefined) next.type = aliased;\n // Fold legacy `enum: string[]` into `values: string[]`.\n if (next.enum !== undefined && next.values === undefined) {\n next.values = next.enum;\n }\n delete next.enum;\n return next;\n },\n z.discriminatedUnion('type', [\n scalarVariant('string'),\n scalarVariant('number'),\n scalarVariant('boolean'),\n scalarVariant('date'),\n scalarVariant('timestamp'),\n scalarVariant('datetime'),\n scalarVariant('trait'),\n scalarVariant('slot'),\n scalarVariant('pattern'),\n // Enum variant — REQUIRES non-empty values.\n z.object({\n ...baseFieldShape,\n type: z.literal('enum'),\n values: z.array(z.string()).min(1, 'Enum field requires a non-empty `values` array'),\n }),\n // Relation variant — REQUIRES relation config.\n z.object({\n ...baseFieldShape,\n type: z.literal('relation'),\n relation: RelationConfigSchema,\n }),\n // Array variant — items optional to match relaxed TS shape.\n z.object({\n ...baseFieldShape,\n type: z.literal('array'),\n items: EntityFieldSchema.optional(),\n }),\n // Object variant — fixed-key struct (`properties`) or dynamic-key\n // map (`Map K V`, uniform value schema in `items`).\n z.object({\n ...baseFieldShape,\n type: z.literal('object'),\n items: EntityFieldSchema.optional(),\n values: z.array(z.string()).optional(),\n }),\n ]),\n );\n});\n\nexport type EntityFieldInput = z.input<typeof EntityFieldSchema>;\n\n// ============================================================================\n// Type Aliases (for cleaner imports)\n// ============================================================================\n\n/** Alias for EntityField - preferred name */\nexport type Field = EntityField;\n\n/** Alias for EntityFieldSchema - preferred name */\nexport const FieldSchema = EntityFieldSchema;\n","/**\n * Asset Types for Semantic Asset References\n *\n * Defines types for abstracting asset paths into semantic references.\n * Assets are resolved from SemanticAssetRef to actual paths at compile time.\n *\n * @packageDocumentation\n */\n\nimport { z } from 'zod';\n\n// ============================================================================\n// Entity Roles\n// ============================================================================\n\n/**\n * Entity roles in game contexts\n */\nexport const ENTITY_ROLES = [\n 'player',\n 'enemy',\n 'npc',\n 'item',\n 'tile',\n 'projectile',\n 'effect',\n 'ui',\n 'decoration',\n 'vehicle',\n] as const;\n\nexport type EntityRole = (typeof ENTITY_ROLES)[number];\n\nexport const EntityRoleSchema = z.enum(ENTITY_ROLES);\n\n// ============================================================================\n// Visual Styles\n// ============================================================================\n\n/**\n * Visual art styles for games\n */\nexport const VISUAL_STYLES = ['pixel', 'vector', 'hd', '1-bit', 'isometric'] as const;\n\nexport type VisualStyle = (typeof VISUAL_STYLES)[number];\n\nexport const VisualStyleSchema = z.enum(VISUAL_STYLES);\n\n// ============================================================================\n// Asset Dimension + Aspect (render metadata carried with the asset / the need)\n// ============================================================================\n\n/**\n * Whether the asset is a 2D sprite/image or a 3D model. Set by the consuming\n * canvas: the same entity role is a 2D sprite-sheet on a tile board and a 3D\n * rigged model on a 3D board.\n */\nexport const ASSET_DIMENSIONS = ['2d', '3d'] as const;\n\nexport type AssetDimension = (typeof ASSET_DIMENSIONS)[number];\n\nexport const AssetDimensionSchema = z.enum(ASSET_DIMENSIONS);\n\n/**\n * Rendering aspect ratio of an asset: square (tiles/sprites/portraits/icons),\n * 16:9 (scene backdrops), 5:7 (cards), 8:1 (effect frame strips).\n */\nexport const ASSET_ASPECTS = ['1:1', '16:9', '5:7', '8:1'] as const;\n\nexport type AssetAspect = (typeof ASSET_ASPECTS)[number];\n\nexport const AssetAspectSchema = z.enum(ASSET_ASPECTS);\n\n// ============================================================================\n// Game Types\n// ============================================================================\n\n/**\n * Game type classifications\n */\nexport const GAME_TYPES = [\n 'platformer',\n 'roguelike',\n 'top-down',\n 'puzzle',\n 'racing',\n 'card',\n 'board',\n 'shooter',\n 'rpg',\n] as const;\n\nexport type GameType = (typeof GAME_TYPES)[number];\n\nexport const GameTypeSchema = z.enum(GAME_TYPES);\n\n// ============================================================================\n// Animation Name + Sheet Direction\n// ============================================================================\n\n/**\n * Animation names matching a sprite sheet's row layout. Canonical home for\n * this vocabulary — `@almadar/ui`'s `spriteAnimationTypes.ts` re-exports it\n * rather than redeclaring, so board `.lolo` config and the render library\n * agree on one enum.\n */\nexport const ANIMATION_NAMES = ['idle', 'walk', 'attack', 'hit', 'death'] as const;\n\nexport type AnimationName = (typeof ANIMATION_NAMES)[number];\n\nexport const AnimationNameSchema = z.enum(ANIMATION_NAMES);\n\n/** Sheet file directions (physical PNG files a sprite sheet ships as). */\nexport const SPRITE_DIRECTIONS = ['se', 'sw'] as const;\n\nexport type SpriteDirection = (typeof SPRITE_DIRECTIONS)[number];\n\nexport const SpriteDirectionSchema = z.enum(SPRITE_DIRECTIONS);\n\n// ============================================================================\n// Animation Definition\n// ============================================================================\n\n/**\n * Definition for a single named animation within a sprite sheet: which row\n * it occupies, how many frames it has, and its playback rate. This is the\n * shape actually consumed by `@almadar/ui`'s sprite-sheet renderer\n * (`spriteAnimation.ts`'s `frameRect`/`getCurrentFrameFromDef`) — moved here\n * verbatim rather than reconciled with a differently-shaped guess, since\n * `@almadar/ui`'s version is the one with real production consumers.\n */\nexport interface AnimationDef {\n /** Row index in the sprite sheet (0-based; each animation occupies one row). */\n row: number;\n /** Number of frames in this animation. */\n frames: number;\n /** Frames per second. */\n frameRate: number;\n /** Whether the animation loops. */\n loop: boolean;\n}\n\nexport const AnimationDefSchema = z.object({\n row: z.number().int().nonnegative(),\n frames: z.number().int().positive(),\n frameRate: z.number().positive(),\n loop: z.boolean(),\n});\n\n// ============================================================================\n// Sprite Sheet Atlas\n// ============================================================================\n\n/**\n * Parsed sprite-sheet atlas JSON — the contract a `spriteSheet`-role `Asset.url`\n * resolves to when fetched (see `Asset.url` usage in `@almadar/ui`'s\n * `useUnitSpriteAtlas`). A unit's `sprite?: Asset` stays the static single-pose\n * image; `spriteSheet?: Asset` is a SEPARATE reference whose URL points at a\n * `SpriteSheetAtlas`-shaped JSON manifest (e.g. `.../guardian-sprite-sheet.json`),\n * not a PNG. Frame-cutting geometry lives here, not inlined onto `Asset` — an\n * `Asset` traveling through `render-ui` every tick stays small.\n */\nexport interface SpriteSheetAtlas {\n /** Unit archetype key. */\n unit?: string;\n /** Visual type key. */\n type?: string;\n /** Width of a single frame in pixels. */\n frameWidth: number;\n /** Height of a single frame in pixels. */\n frameHeight: number;\n /** Number of columns (frames per row). */\n columns: number;\n /** Number of rows (animations). */\n rows: number;\n /** Directions present as physical PNG files. */\n directions: SpriteDirection[];\n /** Relative PNG sheet paths per direction. */\n sheets: Partial<Record<SpriteDirection, string>>;\n /** Animation row layout keyed by animation name. */\n animations: Partial<Record<AnimationName, AnimationDef>>;\n}\n\nexport const SpriteSheetAtlasSchema = z.object({\n unit: z.string().optional(),\n type: z.string().optional(),\n frameWidth: z.number().positive(),\n frameHeight: z.number().positive(),\n columns: z.number().int().positive(),\n rows: z.number().int().positive(),\n directions: z.array(SpriteDirectionSchema),\n sheets: z.record(SpriteDirectionSchema, z.string()),\n animations: z.record(AnimationNameSchema, AnimationDefSchema),\n});\n\n// ============================================================================\n// Semantic Asset Reference\n// ============================================================================\n\n/**\n * Semantic reference to an asset (not a hardcoded path).\n * Resolved to actual paths at compile time via asset maps.\n */\nexport interface SemanticAssetRef {\n /** Entity role (player, enemy, item, etc.) */\n role: EntityRole;\n /** Sub-category within role (hero, slime, coin, etc.) */\n category: string;\n /** Required animations for this entity */\n animations?: string[];\n /** Visual style preference */\n style?: VisualStyle;\n /** Variant identifier (for multiple versions) */\n variant?: string;\n /** 2D sprite vs 3D model — the rendering dimension the consuming canvas needs. */\n dimension?: AssetDimension;\n /** Rendering aspect ratio (square sprite/portrait/tile, 16:9 backdrop, 5:7 card, 8:1 fx-strip). */\n aspect?: AssetAspect;\n}\n\nexport const SemanticAssetRefSchema = z.object({\n role: EntityRoleSchema,\n category: z.string().min(1),\n animations: z.array(z.string()).optional(),\n style: VisualStyleSchema.optional(),\n variant: z.string().optional(),\n dimension: AssetDimensionSchema.optional(),\n aspect: AssetAspectSchema.optional(),\n});\n\n// ============================================================================\n// Asset — the UNIFIED asset type\n// ============================================================================\n\n/**\n * The single asset type: a `SemanticAssetRef` (role/dimension/animations/aspect/style)\n * WITH its resolved URL folded in. Used everywhere an asset is referenced — a lolo\n * board `assetManifest` (`Map string Asset`), every `@almadar/ui` game prop, the\n * asset-workflow's resolved/pool assets, and the inspector picker. Replaces the bare\n * `AssetUrl`-string asset field so the render metadata travels WITH the asset (no\n * pixel-dimension or filename heuristics needed to know sheet-vs-frame / 2d-vs-3d).\n */\nexport interface Asset extends SemanticAssetRef {\n /** The resolved asset URL. */\n url: AssetUrl;\n /** Optional display name (inspector picker). */\n name?: string;\n /** Optional thumbnail URL (inspector picker grid). */\n thumbnailUrl?: string;\n}\n\nexport const AssetSchema = SemanticAssetRefSchema.extend({\n url: z.string(),\n name: z.string().optional(),\n thumbnailUrl: z.string().optional(),\n});\n\n// ============================================================================\n// Resolved Asset\n// ============================================================================\n\n/**\n * Result of resolving a SemanticAssetRef to actual asset paths\n */\nexport interface ResolvedAsset {\n /** Base path to the asset pack */\n basePath: string;\n /** Relative path within the pack */\n path: string;\n /** Tile indices for tilesheet-based assets */\n tiles?: number[];\n /** Size of each tile in pixels */\n tileSize?: number;\n /** List of individual files (for non-tilesheet assets) */\n files?: string[];\n /** Animation definitions by name */\n animations?: Record<string, AnimationDef>;\n}\n\nexport const ResolvedAssetSchema = z.object({\n basePath: z.string(),\n path: z.string(),\n tiles: z.array(z.number()).optional(),\n tileSize: z.number().positive().optional(),\n files: z.array(z.string()).optional(),\n animations: z.record(AnimationDefSchema).optional(),\n});\n\n// ============================================================================\n// Asset Mapping\n// ============================================================================\n\n/**\n * Single asset mapping entry in an asset map\n */\nexport interface AssetMapping {\n /** Relative path to the asset */\n path: string;\n /** Tile indices for tilesheets */\n tiles?: number[];\n /** Tile size in pixels */\n tileSize?: number;\n /** Individual file patterns */\n files?: string[];\n /** Animation definitions */\n animations?: Record<string, AnimationDef>;\n}\n\nexport const AssetMappingSchema = z.object({\n path: z.string(),\n tiles: z.array(z.number()).optional(),\n tileSize: z.number().positive().optional(),\n files: z.array(z.string()).optional(),\n animations: z.record(AnimationDefSchema).optional(),\n});\n\n// ============================================================================\n// Asset Map\n// ============================================================================\n\n/**\n * Asset map for a specific game type and visual style.\n * Maps semantic keys (role:category) to asset paths.\n */\nexport interface AssetMap {\n /** Game type this map is for */\n gameType: GameType;\n /** Visual style this map is for */\n style: VisualStyle;\n /** Base path to the asset pack */\n basePath: string;\n /** Mappings from semantic keys to asset paths */\n mappings: Record<string, AssetMapping>;\n}\n\nexport const AssetMapSchema = z.object({\n gameType: GameTypeSchema,\n style: VisualStyleSchema,\n basePath: z.string(),\n mappings: z.record(AssetMappingSchema),\n});\n\n// ============================================================================\n// Asset Catalog\n// ============================================================================\n\n/**\n * Single browsable asset in the inspector picker catalog.\n * Backs the asset/icon pickers — a flat list the inspector renders for\n * the user to choose from when a config field's type is `'asset'`.\n */\nexport interface AssetCatalogEntry {\n /** Resolvable URL to the asset. */\n url: string;\n /** Display name for the asset. */\n name: string;\n /** Grouping category within the catalog. */\n category: string;\n /** Asset kind the picker dispatches on. */\n kind: 'image' | 'spritesheet' | 'audio' | 'scene' | 'portrait' | 'model' | 'other';\n /** Optional thumbnail URL for grid previews. */\n thumbnailUrl?: string;\n /** 2D sprite vs 3D model — the asset's actual rendering dimension. */\n dimension?: AssetDimension;\n /** The asset's actual rendering aspect ratio. */\n aspect?: AssetAspect;\n}\n\nexport const AssetCatalogEntrySchema = z.object({\n url: z.string(),\n name: z.string(),\n category: z.string(),\n kind: z.enum(['image', 'spritesheet', 'audio', 'scene', 'portrait', 'model', 'other']),\n thumbnailUrl: z.string().optional(),\n dimension: AssetDimensionSchema.optional(),\n aspect: AssetAspectSchema.optional(),\n});\n\n/**\n * Flat list of browsable assets surfaced by the inspector pickers.\n */\nexport type AssetCatalog = AssetCatalogEntry[];\n\nexport const AssetCatalogSchema = z.array(AssetCatalogEntrySchema);\n\n/**\n * Asset-reference URL marker. A plain alias over `string` — the value is a\n * resolvable asset URL — but the named type lets the pattern-sync tool\n * (`tools/almadar-pattern-sync/parser.ts`) detect a component prop as an asset\n * field (tagged `asset`) the same way `EventKey`/`LucideIcon` are detected by\n * type identity. Components annotate image/url props as `AssetUrl` (`src`,\n * `backgroundImage`, `avatar`, …); the generator emits a `string` config knob\n * declared as the `asset` config type, which the property inspector dispatches\n * an AssetPicker on. Not branded — asset urls originate from user data, so cast\n * friction would buy nothing; the value is the marker the tool finds.\n */\nexport type AssetUrl = string;\n\n// ============================================================================\n// Type Exports\n// ============================================================================\n\nexport type SemanticAssetRefInput = z.input<typeof SemanticAssetRefSchema>;\nexport type ResolvedAssetInput = z.input<typeof ResolvedAssetSchema>;\nexport type AssetMappingInput = z.input<typeof AssetMappingSchema>;\nexport type AssetMapInput = z.input<typeof AssetMapSchema>;\nexport type AnimationDefInput = z.input<typeof AnimationDefSchema>;\nexport type AssetCatalogEntryInput = z.input<typeof AssetCatalogEntrySchema>;\nexport type SpriteSheetAtlasInput = z.input<typeof SpriteSheetAtlasSchema>;\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Creates a semantic asset key from role and category.\n * \n * Generates a unique asset identifier by combining role and category\n * with a colon separator. Used for asset management and lookup.\n * \n * @param {EntityRole} role - Entity role (e.g., 'player', 'enemy')\n * @param {string} category - Asset category (e.g., 'sprite', 'animation')\n * @returns {string} Asset key in format 'role:category'\n * \n * @example\n * createAssetKey('player', 'sprite'); // returns 'player:sprite'\n * createAssetKey('enemy', 'animation'); // returns 'enemy:animation'\n */\nexport function createAssetKey(role: EntityRole, category: string): string {\n return `${role}:${category}`;\n}\n\n/**\n * Parses an asset key into role and category components.\n * \n * Deconstructs an asset key string (format 'role:category') into its\n * constituent parts. Returns null if the key format is invalid.\n * \n * @param {string} key - Asset key in format 'role:category'\n * @returns {{ role: string; category: string } | null} Parsed components or null\n * \n * @example\n * parseAssetKey('player:sprite'); // returns { role: 'player', category: 'sprite' }\n * parseAssetKey('enemy:animation'); // returns { role: 'enemy', category: 'animation' }\n * parseAssetKey('invalid'); // returns null\n */\nexport function parseAssetKey(key: string): { role: string; category: string } | null {\n const parts = key.split(':');\n if (parts.length !== 2) return null;\n return { role: parts[0], category: parts[1] };\n}\n\n/**\n * Gets common animations for an entity role.\n * \n * Returns an array of default animation names appropriate for the\n * specified entity role. Used for asset configuration and validation.\n * \n * @param {EntityRole} role - Entity role\n * @returns {string[]} Array of default animation names\n * \n * @example\n * getDefaultAnimationsForRole('player'); // returns ['idle', 'run', 'jump', 'fall', 'attack', 'hurt', 'die']\n * getDefaultAnimationsForRole('enemy'); // returns ['idle', 'walk', 'attack', 'hurt', 'die']\n */\nexport function getDefaultAnimationsForRole(role: EntityRole): string[] {\n switch (role) {\n case 'player':\n return ['idle', 'run', 'jump', 'fall', 'attack', 'hurt', 'die'];\n case 'enemy':\n return ['idle', 'walk', 'attack', 'hurt', 'die'];\n case 'npc':\n return ['idle', 'walk', 'talk'];\n case 'item':\n return ['idle', 'collected'];\n case 'tile':\n return ['static'];\n case 'projectile':\n return ['fly', 'hit', 'expire'];\n case 'effect':\n return ['play'];\n case 'ui':\n return ['normal', 'hover', 'pressed', 'disabled'];\n case 'decoration':\n return ['idle'];\n case 'vehicle':\n return ['idle', 'move', 'brake'];\n default:\n return ['idle'];\n }\n}\n\n/**\n * Validates that an asset reference has required animations.\n * \n * Checks if an asset reference contains all required animations.\n * Returns an error message if validation fails, or null if valid.\n * \n * @param {SemanticAssetRef} assetRef - Asset reference to validate\n * @param {string[]} requiredAnimations - Required animation names\n * @returns {string | null} Error message or null if valid\n * \n * @example\n * validateAssetAnimations(assetRef, ['idle', 'run']); // returns null if valid\n * validateAssetAnimations(assetRef, ['missing-animation']); // returns error message\n */\nexport function validateAssetAnimations(\n assetRef: SemanticAssetRef,\n requiredAnimations: string[]\n): { valid: boolean; missing: string[] } {\n const provided = assetRef.animations || [];\n const missing = requiredAnimations.filter((anim) => !provided.includes(anim));\n return { valid: missing.length === 0, missing };\n}\n","/**\n * Entity Types for Orbital Units\n *\n * Defines the OrbitalEntity type - the nucleus of an Orbital Unit.\n *\n * @packageDocumentation\n */\n\nimport { z } from 'zod';\nimport { EntityFieldSchema, type EntityField } from './field.js';\nimport { SemanticAssetRefSchema, type SemanticAssetRef } from './asset.js';\n\n// ============================================================================\n// Entity Persistence\n// ============================================================================\n\n/**\n * Entity persistence types.\n *\n * - persistent: Stored in database (has collection)\n * - runtime: Exists only at runtime (not persisted)\n * - singleton: Single global instance\n * - instance: Static data (read-only instances)\n */\nexport type EntityPersistence = 'persistent' | 'runtime' | 'singleton' | 'instance' | 'local';\n\nexport const EntityPersistenceSchema = z.enum([\n 'persistent',\n 'runtime',\n 'singleton',\n 'instance',\n 'local',\n]);\n\n// ============================================================================\n// Orbital Entity\n// ============================================================================\n\n/**\n * OrbitalEntity - the nucleus of an Orbital Unit.\n *\n * This is a simplified entity definition optimized for orbital composition.\n * Collection names are derived automatically from persistence type if not provided.\n */\nexport interface OrbitalEntity {\n /** Entity name (PascalCase, e.g., \"Task\", \"User\") */\n name: string;\n\n /** Entity persistence type (defaults to 'persistent' if not specified) */\n persistence?: EntityPersistence;\n\n /** Collection name (auto-derived if not provided for persistent entities) */\n collection?: string;\n\n /** Entity fields */\n fields: EntityField[];\n\n /** Pre-authored instances (seed data or static reference data) */\n instances?: EntityRow[];\n\n /** Auto-add createdAt/updatedAt timestamps */\n timestamps?: boolean;\n\n /** Soft delete support */\n softDelete?: boolean;\n\n /** Human-readable description */\n description?: string;\n\n /** Visual prompt for AI generation */\n visual_prompt?: string;\n\n /** Semantic asset reference for visual representation (games) */\n assetRef?: SemanticAssetRef;\n}\n\nexport const OrbitalEntitySchema = z.object({\n name: z.string().min(1, 'Entity name is required'),\n persistence: EntityPersistenceSchema.default('persistent'),\n collection: z.string().optional(),\n fields: z.array(EntityFieldSchema).min(1, 'At least one field is required'),\n instances: z.array(z.record(z.unknown())).optional(),\n timestamps: z.boolean().optional(),\n softDelete: z.boolean().optional(),\n description: z.string().optional(),\n visual_prompt: z.string().optional(),\n assetRef: SemanticAssetRefSchema.optional(),\n});\n\nexport type OrbitalEntityInput = z.input<typeof OrbitalEntitySchema>;\n\n// ============================================================================\n// Type Aliases (for cleaner imports)\n// ============================================================================\n\n/** Alias for OrbitalEntity - preferred name */\nexport type Entity = OrbitalEntity;\n\n/** Alias for OrbitalEntitySchema - preferred name */\nexport const EntitySchema = OrbitalEntitySchema;\n\n// ============================================================================\n// Utility Functions\n// ============================================================================\n\n/**\n * Derives the collection name for a persistent entity.\n * \n * Generates the database collection name by converting the entity name\n * to lowercase and adding an 's' suffix (simple pluralization).\n * Returns undefined for non-persistent entities (runtime/singleton).\n * \n * @param {OrbitalEntity} entity - Entity to derive collection name for\n * @returns {string | undefined} Collection name or undefined for non-persistent entities\n * \n * @example\n * deriveCollection({ name: 'User', persistence: 'persistent' }); // returns 'users'\n * deriveCollection({ name: 'Task', persistence: 'runtime' }); // returns undefined\n */\nexport function deriveCollection(entity: OrbitalEntity): string | undefined {\n if (entity.persistence !== 'persistent') {\n return undefined;\n }\n // Lowercase + 's' suffix (simple pluralization)\n return entity.name.toLowerCase() + 's';\n}\n\n/**\n * Checks if an entity is runtime-only (not persisted).\n * \n * Type guard to determine if an entity exists only at runtime\n * and is not stored in the database.\n * \n * @param {OrbitalEntity} entity - Entity to check\n * @returns {boolean} True if entity is runtime-only, false otherwise\n * \n * @example\n * isRuntimeEntity({ persistence: 'runtime' }); // returns true\n * isRuntimeEntity({ persistence: 'persistent' }); // returns false\n */\nexport function isRuntimeEntity(entity: OrbitalEntity): boolean {\n return entity.persistence === 'runtime';\n}\n\n/**\n * Checks if an entity is a singleton.\n * \n * Type guard to determine if an entity has a single global instance\n * rather than multiple records in a collection.\n * \n * @param {OrbitalEntity} entity - Entity to check\n * @returns {boolean} True if entity is a singleton, false otherwise\n * \n * @example\n * isSingletonEntity({ persistence: 'singleton' }); // returns true\n * isSingletonEntity({ persistence: 'persistent' }); // returns false\n */\nexport function isSingletonEntity(entity: OrbitalEntity): boolean {\n return entity.persistence === 'singleton';\n}\n\n/**\n * Checks whether an entity's persistence mode allows `persistence` /\n * `collection` overrides at the factory call site.\n *\n * Only `persistent` entities (explicit or default) support these overrides.\n * Runtime, singleton, instance, and local entities are fixed; callers must\n * not expose `persistence` or `collection` params for them.\n *\n * @param persistence - The entity persistence mode (undefined = default persistent)\n * @returns True when overrides are allowed, false otherwise\n *\n * @example\n * persistenceModeAllowsOverrides('persistent'); // returns true\n * persistenceModeAllowsOverrides('runtime'); // returns false\n * persistenceModeAllowsOverrides(undefined); // returns true (default persistent)\n */\nexport function persistenceModeAllowsOverrides(\n persistence: EntityPersistence | undefined,\n): boolean {\n return persistence === 'persistent' || persistence === undefined;\n}\n\n// ============================================================================\n// Entity Instance Data (Runtime)\n// ============================================================================\n\n/**\n * A single field value at runtime.\n * Union of all possible types from FieldType: string, number, boolean, date, array, nested.\n * The nested-record branch's index signature tolerates `undefined` so that\n * TypeScript optional properties (`x?: string`, carrying `string | undefined`)\n * on EntityRow extenders typecheck without ceremony. At JSON serialization\n * time `undefined` is equivalent to \"key absent\" and never appears on the\n * wire; the inclusion here is a pure type-surface accommodation.\n */\nexport type FieldValue = string | number | boolean | Date | null | string[] | FieldValue[] | { [key: string]: FieldValue | undefined };\n\n/**\n * One instance of an entity with actual field values.\n * The shape is determined by the Entity definition at schema time.\n *\n * @example\n * // Entity defines: Patient { fullName: string, age: number, active: boolean }\n * // EntityRow is: { id: \"p1\", fullName: \"Sarah\", age: 34, active: true }\n */\nexport type EntityRow = { id?: string } & Record<string, FieldValue | undefined>;\n\n/**\n * A field-TYPED `EntityRow` — the SINGLE entity type, refined with a concrete\n * field SHAPE `S`. Non-optional members of `S` are REQUIRED, each with its real\n * type; the result stays `& EntityRow`, so the index signature is intact and\n * every other field is still field-open — any domain entity that provides those\n * fields satisfies it.\n *\n * One declaration, two jobs: (1) TypeScript enforces the bound entity has the\n * fields WITH their types (a behavior binding a thinner/mistyped entity fails to\n * typecheck); and (2) pattern-sync reads the same type and writes the entity\n * prop's field shape (`properties` + `requiredFields`) onto the registry, so\n * lolo-ui emits a COMPLETE `entity { … }` (every field, typed + demo-seeded) and\n * the `ORB_X_ENTITY_PROP_CONTRACT` validator rejects an incompatible bind at\n * `orbital validate`. (A raw `EntityRow & { rating: number }` intersection is\n * equivalent for one-off shapes.)\n *\n * @example\n * // HeroOrganism renders entity.title / entity.subtitle:\n * entity?: EntityWith<{ title: string; subtitle?: string }>;\n * // entity.title → string (required)\n * // entity.subtitle → string | undefined (optional)\n * // entity.other → FieldValue | undefined (still field-open)\n */\n// `S extends object` (not `Record<string, FieldValue>`) so a plain `interface`\n// row shape satisfies it — interfaces lack the implicit index signature `Record`\n// requires. FieldValue-compatibility is still enforced structurally: `& EntityRow`\n// intersects every field with the `FieldValue | undefined` index signature, so a\n// non-FieldValue field (e.g. a React `LucideIcon`) collapses to `never` at use.\nexport type EntityWith<S extends object> = EntityRow & S;\n\n/**\n * Collection of entity instances keyed by entity name.\n * Used by OrbPreview mockData, OrbitalServerRuntime state, data grids, etc.\n *\n * @example\n * const data: EntityData = {\n * Patient: [{ id: \"1\", fullName: \"Sarah\", age: 34 }],\n * QueueEntry: [{ id: \"1\", patientName: \"Sarah\", waitMinutes: 12 }],\n * };\n */\nexport type EntityData = Record<string, EntityRow[]>;\n","/**\n * Effect Types (Self-Contained)\n *\n * Defines effect types for trait transitions and ticks.\n * Effects are S-expressions (arrays) that describe actions to perform.\n *\n * @packageDocumentation\n */\n\nimport { z } from 'zod';\nimport { type SExpr, type Expression, type EventPayload } from './expression.js';\nimport { type ServiceParams } from './service.js';\nimport { type EntityRow } from './entity.js';\n\n// ============================================================================\n// UI Slots\n// ============================================================================\n\n/**\n * Known UI slots where content can be rendered\n */\nexport const UI_SLOTS = [\n // App slots\n 'main',\n 'sidebar',\n 'modal',\n 'drawer',\n 'overlay',\n 'center',\n 'toast',\n 'floating',\n 'system', // For invisible system components (InputListener, CollisionDetector)\n 'content',\n 'screen',\n // Game HUD slots\n 'hud',\n 'hud-top',\n 'hud-bottom',\n 'hud.health',\n 'hud.score',\n 'hud.inventory',\n 'hud.stamina',\n // Game overlay slots\n 'overlay.inventory',\n 'overlay.dialogue',\n 'overlay.menu',\n 'overlay.pause',\n] as const;\n\nexport type UISlot = (typeof UI_SLOTS)[number];\n\nexport const UISlotSchema = z.enum(UI_SLOTS);\n\n// ============================================================================\n// Pattern Config (for render-ui effects)\n// ============================================================================\n\n// Import pattern types for local use and re-export for consumers\nimport type {\n PatternType,\n PatternConfig,\n PatternProps,\n PatternPropsMap,\n AnyPatternConfig,\n} from '@almadar/patterns';\n\n/**\n * Type-safe pattern configuration for render-ui effects.\n *\n * Re-exported from @almadar/patterns. Generated from patterns-registry.json.\n *\n * @example\n * // Type-safe with specific pattern type\n * const config: PatternConfig<'entity-table'> = {\n * patternType: 'entity-table',\n * columns: ['name', 'email'], // ✅ Required prop\n * entity: 'User',\n * };\n *\n * // Error: Property 'columns' is missing (required prop)\n * const bad: PatternConfig<'entity-table'> = { patternType: 'entity-table' };\n *\n * // Error: 'fake-pattern' is not assignable to PatternType\n * const invalid: PatternConfig = { patternType: 'fake-pattern' };\n */\nexport type {\n PatternType,\n PatternConfig,\n PatternProps,\n PatternPropsMap,\n AnyPatternConfig,\n};\n\n/**\n * Configuration for render-ui effect.\n * Used in runtime to specify which slot and pattern to render.\n */\nexport interface RenderUIConfig {\n /** Target UI slot */\n slot: UISlot;\n /** Pattern configuration (null clears the slot) */\n pattern: AnyPatternConfig | null;\n /** Target element (trait name or entity ID) */\n target?: string;\n /** Additional props for the pattern */\n props?: ResolvedPatternProps;\n /** Optional priority for slot ordering */\n priority?: number;\n}\n\n// ============================================================================\n// Service Config (for call-service effects)\n// ============================================================================\n\n/**\n * Configuration extracted from call-service effects\n */\nexport interface CallServiceConfig {\n service: string;\n action: string;\n endpoint?: string;\n method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n params?: ServiceParams;\n onSuccess?: string;\n onError?: string;\n}\n\n// ============================================================================\n// Typed Effect Tuples\n// ============================================================================\n\n/**\n * A binding reference to a render tree stored elsewhere — a trait `config`\n * knob or a payload field — e.g. `\"@config.bodyContent\"`. Resolved to a pattern\n * node at render time. This is how an atom renders a tree that contains data\n * bindings (`entity: \"@payload.data\"`, `fields: \"@config.fields\"`): the tree is\n * a permissive `TraitConfigValue` stored in `config` (a binding string is not a\n * valid `AnyPatternConfig` prop value), and the render-ui effect points at it.\n * Worked example: `std-browse`'s loaded transition is `['render-ui', 'main',\n * '@config.bodyContent']`. The Rust validator accepts this form; this variant\n * lets the TS effect type express it.\n */\nexport type RenderBinding = `@${string}`;\n\n/**\n * Render UI effect - displays a pattern in a UI slot.\n * @example ['render-ui', 'main', { patternType: 'entity-table', columns: ['name'] }]\n * @example ['render-ui', 'main', '@config.bodyContent'] // a {@link RenderBinding} target\n */\nexport type RenderUIEffect =\n | ['render-ui', UISlot, AnyPatternConfig]\n | ['render-ui', UISlot, AnyPatternConfig, ResolvedPatternProps]\n | ['render-ui', UISlot, RenderBinding]\n | ['render-ui', UISlot, null];\n\n/**\n * Lambda expression for per-item rendering in data-grid/data-list.\n * The compiler generates: {(paramName: Record<string, unknown>) => (<>JSX</>)}\n * where @{paramName}.field bindings reference the current iteration item.\n *\n * @example [\"fn\", \"item\", { \"type\": \"stack\", \"children\": [{ \"type\": \"typography\", \"content\": \"@item.title\" }] }]\n */\nexport type RenderItemLambda = ['fn', string, AnyPatternConfig];\n\n/**\n * Navigate effect - navigates to a path.\n * @example ['navigate', '/tasks'] or ['navigate', '/tasks/:id', { id: '123' }]\n */\nexport type NavigateEffect = ['navigate', string] | ['navigate', string, Record<string, string>];\n\n/**\n * Emit effect - emits an event, optionally with payload.\n * @example ['emit', 'SAVE'] or ['emit', 'PLAYER_DIED', { playerId: '@entity.id' }]\n * @example ['emit', 'FILTER_CHANGED', '@entity.filters']\n */\nexport type EmitEffect = ['emit', string] | ['emit', string, EventPayload | string];\n\n/**\n * `emit:` config block attached to async / reactive data operators.\n *\n * Each key names an event the runtime should fire on the bus when the\n * effect reaches the corresponding lifecycle point. The set of keys an\n * operator actually supports is enforced by the compiler validator:\n *\n * | Operator | Supported keys |\n * |------------------|---------------------------|\n * | `fetch` | `success`, `failure` |\n * | `persist` | `success`, `failure` |\n * | `call-service` | `success`, `failure` |\n * | `set` | `success` |\n * | `ref` | `on_change`, `failure` |\n * | `os/watch-*` | `on_message`, `failure` |\n *\n * Payload convention:\n * - `success` / `on_change` → the effect's result (fetched entity, new value)\n * - `failure` → `{ error: string, code?: string }`\n * - `on_message` → the incoming message (os/watch-* streams)\n *\n * See `docs/Almadar_Std_Gaps.md` §3.1 for the close-the-circuit design.\n */\nexport interface EmitConfig {\n /** Fires after a one-shot async effect resolves successfully. */\n success?: string;\n /** Fires when the effect throws; payload is `{ error: string }`. */\n failure?: string;\n /** Reactive-subscription event (per update for `ref`). */\n on_change?: string;\n /** Per-event fire for `os/watch-*` streams. */\n on_message?: string;\n}\n\n/**\n * Set effect - sets a binding to a value.\n *\n * Two forms are supported to match the runtime's `set` handler signature\n * `(targetId, field, value)`:\n *\n * - 3-element binding form (legacy / std behaviors): ['set', '@entity.field', value]\n * - 4-element target form (canonical runtime): ['set', entityId, fieldName, value]\n *\n * The 4-element form is what `OrbitalServerRuntime`'s set handler\n * dispatches directly (`update(entityType, targetId, { field: value })`).\n * Prefer the 4-element form when authoring schemas in TypeScript that\n * load directly into the runtime.\n *\n * @example ['set', '@entity.health', 100] // 3-element\n * @example ['set', '@entity.id', 'health', 100] // 4-element\n * @example ['set', '@entity.id', 'count', ['+', '@entity.count', 1]]\n */\nexport type SetEffect =\n | ['set', string, unknown]\n | ['set', string, string, unknown];\n\n/**\n * Trailing config object on persist effects. When present, it carries the\n * `emit` map specifying which events to fire on persist success/failure.\n * Mirrors what the runtime's `EffectExecutor` reads at the 5th tuple\n * position. See `(persist create Entity @payload.data { emit: { success:\n * \"Saved\", failure: \"SaveFailed\" } })` in `.lolo` source.\n */\nexport interface PersistEmitConfig {\n emit?: { success?: string; failure?: string };\n}\n\n/**\n * Persist effect data argument: either an entity row literal (field map)\n * or a binding string referencing a row in scope (e.g. `@payload.data`,\n * `@entity`). At runtime, binding strings resolve to `EntityRow` values\n * before the persist op runs.\n */\nexport type PersistData = EntityRow | string;\n\n/**\n * Persist effect - creates, updates, deletes, or clears entities.\n *\n * Each operation accepts an optional trailing `PersistEmitConfig` so the\n * runtime can fire success / failure events when the operation completes.\n *\n * @example ['persist', 'create', 'Task', { title: '@payload.title' }]\n * @example ['persist', 'update', '@entity.entityType', '@payload.data']\n * @example ['persist', 'create', 'Task', '@payload.data', { emit: { success: 'TaskCreated' } }]\n */\nexport type PersistEffect =\n | ['persist', 'create', string, PersistData]\n | ['persist', 'create', string, PersistData, PersistEmitConfig]\n | ['persist', 'update', string, PersistData]\n | ['persist', 'update', string, PersistData, PersistEmitConfig]\n | ['persist', 'delete', string]\n | ['persist', 'delete', string, PersistData]\n | ['persist', 'delete', string, PersistData, PersistEmitConfig]\n | ['persist', 'clear', string]\n | ['persist', 'clear', string, PersistData]\n | ['persist', 'clear', string, PersistData, PersistEmitConfig];\n\n/**\n * Call service effect - invokes an external service.\n *\n * Two shapes are accepted:\n *\n * 1. Flat form (what the runtime reads and every .orb file uses):\n * `['call-service', serviceName, action, params?]` — args[0]=service,\n * args[1]=action, args[2]=params. This is the canonical form; the\n * runtime's EffectExecutor decodes exactly these positions.\n *\n * 2. Legacy config-object form (kept for the `callService()` helper):\n * `['call-service', serviceName, CallServiceConfig]` — retained so\n * older call sites using the builder helper continue to typecheck.\n *\n * @example ['call-service', 'llm', 'generate', { userPrompt: '@entity.inputText' }]\n * @example ['call-service', 'llm', 'generate', { userPrompt: '...' }, { emit: { success: 'OK', failure: 'ERR' } }]\n * @example ['call-service', 'WeatherAPI', { service: 'weather', action: 'get', onSuccess: 'OK' }]\n */\nexport type CallServiceEffect =\n | ['call-service', string, string]\n | ['call-service', string, string, ServiceParams]\n | ['call-service', string, string, ServiceParams, PersistEmitConfig]\n | ['call-service', string, CallServiceConfig];\n\n/**\n * Spawn effect - creates a new entity instance (games).\n * @example ['spawn', 'Bullet', { x: '@entity.x', y: '@entity.y' }]\n */\nexport type SpawnEffect = ['spawn', string] | ['spawn', string, EntityRow];\n\n/**\n * Despawn effect - removes an entity instance (games).\n * @example ['despawn', '@entity.id']\n */\nexport type DespawnEffect = ['despawn', string];\n\n/**\n * Do effect - executes multiple effects in sequence.\n * Uses SExpr to allow deeply nested conditionals.\n * @example ['do', ['set', '@entity.x', 0], ['set', '@entity.y', 0]]\n */\nexport type DoEffect = ['do', ...SExpr[]];\n\n/**\n * Notify effect - sends a notification.\n * @example ['notify', 'in_app', 'Task created successfully']\n * @example ['notify', 'in_app', ['str/concat', 'Item: ', '@entity.name']]\n */\nexport type NotifyEffect =\n | ['notify', string, string | SExpr]\n | ['notify', string, string | SExpr, string];\n\n/**\n * Options accepted by `fetch` / `ref` / `deref` effects. Mirrors what\n * `OrbitalServerRuntime`'s fetch handler reads at runtime: `id`, `filter`,\n * `limit`, `offset`, `include`, plus the trailing `emit:` map for\n * success/failure event names.\n */\nexport interface FetchOptions {\n /** Fetch a single entity by ID */\n id?: string;\n /** Filter expression (S-expression) */\n filter?: SExpr;\n /** Maximum number of entities to return */\n limit?: number;\n /** Number of entities to skip */\n offset?: number;\n /** Relations to populate (entity field names) */\n include?: string[];\n /** Lifecycle events to emit on resolve / reject */\n emit?: { success?: string; failure?: string };\n}\n\n/**\n * Fetch effect - retrieves entity data (server-side).\n * @example ['fetch', 'User'] or ['fetch', 'User', { id: '@payload.userId' }]\n */\nexport type FetchEffect = ['fetch', string] | ['fetch', string, FetchOptions];\n\n/**\n * Result returned by a fetch / ref / deref handler.\n *\n * `rows` carries the entity (or entities) that survived `filter` AND\n * pagination (`offset`/`limit`). `total` is the count of rows that\n * matched the filter BEFORE pagination, so paginating consumers can\n * compute `totalPages = ceil(total / pageSize)` without a second\n * round-trip. Single-entity fetches by id return `total: 1` (or `0`\n * if not found, in which case the handler returns `null` instead).\n */\nexport interface FetchResult {\n rows: EntityRow | EntityRow[];\n total: number;\n}\n\n/**\n * If effect - conditional effect execution.\n * Uses SExpr to allow deeply nested conditionals.\n * @example ['if', ['>', '@entity.health', 0], ['emit', 'ALIVE'], ['emit', 'DEAD']]\n */\nexport type IfEffect = ['if', Expression, SExpr] | ['if', Expression, SExpr, SExpr];\n\n/**\n * When effect - conditional effect similar to if but without else.\n * Uses SExpr to allow deeply nested conditionals.\n * @example ['when', ['>', '@entity.health', 0], ['emit', 'ALIVE']]\n */\nexport type WhenEffect = ['when', Expression, SExpr];\n\n/**\n * Let effect - creates local bindings for effects.\n * Uses SExpr to allow deeply nested conditionals.\n * @example ['let', ['temp', ['get', '@payload.value']], ['set', '@entity.value', 'temp']]\n */\nexport type LetEffect = ['let', [string, unknown][], ...SExpr[]];\n\n/**\n * Log effect - logs a message for debugging.\n * @example ['log', 'User created:', '@entity.name']\n */\nexport type LogEffect = ['log', ...unknown[]];\n\n/**\n * Wait effect - delays execution.\n * @example ['wait', 1000] - wait 1 second\n */\nexport type WaitEffect = ['wait', number];\n\n// ============================================================================\n// Resource Effects (reactive entity subscriptions and atomic operations)\n// ============================================================================\n\n/**\n * Ref effect - creates a reactive entity subscription.\n * Returns a reactive reference that auto-updates when the entity changes.\n * @example ['ref', '@entity.health'] - reactive subscription to health\n * @example ['ref', 'User', { id: '@payload.userId' }] - reactive ref to specific user\n */\nexport type RefEffect =\n | ['ref', string]\n | ['ref', string, FetchOptions];\n\n/**\n * Deref effect - snapshot read of an entity value.\n * Returns the current value without subscribing to changes.\n * @example ['deref', '@entity.health'] - read current health value\n * @example ['deref', 'User', { id: '@payload.userId' }] - read specific user snapshot\n */\nexport type DerefEffect =\n | ['deref', string]\n | ['deref', string, FetchOptions];\n\n/**\n * Swap! effect - atomic compare-and-swap on an entity field.\n * Only updates if the current value matches the expected value.\n * @example ['swap!', '@entity.health', ['fn', ['old'], ['-', 'old', '@payload.damage']]]\n * @example ['swap!', '@entity.counter', ['+', '@entity.counter', 1]]\n */\nexport type SwapEffect = ['swap!', string, SExpr];\n\n/**\n * Options accepted by `watch` effects. Mirrors what the runtime reads when\n * registering the change callback: `debounce` and the trailing `emit:` map.\n */\nexport interface WatchOptions {\n /** Debounce duration in milliseconds */\n debounce?: number;\n /** Lifecycle events to emit on update / failure */\n emit?: { on_message?: string; failure?: string };\n}\n\n/**\n * Watch effect - registers a callback for entity changes.\n * Emits an event whenever the watched binding changes.\n * @example ['watch', '@entity.health', 'HEALTH_CHANGED']\n * @example ['watch', '@entity.status', 'STATUS_UPDATED', { debounce: 100 }]\n */\nexport type WatchEffect =\n | ['watch', string, string]\n | ['watch', string, string, WatchOptions];\n\n/**\n * Atomic effect - groups multiple effects into an atomic transaction.\n * All effects either succeed together or are rolled back.\n * @example ['atomic', ['set', '@entity.x', 10], ['set', '@entity.y', 20]]\n * @example ['atomic', ['persist', 'update', 'User', { balance: 100 }], ['emit', 'BALANCE_UPDATED']]\n */\nexport type AtomicEffect = ['atomic', ...SExpr[]];\n\n// ============================================================================\n// ML Effects (from almadar-std/modules/nn, tensor, train)\n// ============================================================================\n\n/**\n * One layer in an NN architecture description. The set of valid layer kinds\n * lives in `almadar-std/modules/nn`; here we keep the wire shape generic\n * enough for the cross-package runtime + Python bridge to round-trip.\n */\nexport interface NnLayer {\n type: string;\n [key: string]: string | number | boolean | number[] | string[] | undefined;\n}\n\n/**\n * Hyperparameters for `train` and `evaluate`. Recursive to allow nested\n * optimizer / scheduler config blocks without falling back to `unknown`.\n */\nexport interface NnConfig {\n [key: string]: string | number | boolean | string[] | number[] | NnConfig | undefined;\n}\n\n/**\n * Forward-pass config: `input` is a binding string (`@payload.input`), and\n * `on-complete` names the event to fire when the prediction lands.\n */\nexport interface ForwardConfig {\n architecture: NnLayer[];\n input: string;\n 'on-complete'?: string;\n config?: NnConfig;\n}\n\n/**\n * Training-loop config. `dataset` is a binding string referencing the rows\n * to train on. Optimizer / loss / scheduler land inside `config`.\n */\nexport interface TrainConfig {\n architecture: NnLayer[];\n dataset: string;\n config?: NnConfig;\n 'on-complete'?: string;\n}\n\n/**\n * Evaluation config. `metrics` lists named metrics the Python backend\n * computes (`accuracy`, `precision`, ...).\n */\nexport interface EvaluateConfig {\n architecture: NnLayer[];\n dataset: string;\n metrics: string[];\n config?: NnConfig;\n 'on-complete'?: string;\n}\n\n/**\n * Forward effect - runs a neural network forward pass (Python backend).\n * @example ['forward', 'primary', { architecture: [...], input: '@payload.input', 'on-complete': 'PREDICTION_READY' }]\n */\nexport type ForwardEffect = ['forward', string, ForwardConfig];\n\n/**\n * Train effect - runs a training loop (Python backend).\n * @example ['train', { architecture: [...], dataset: '@entity.data', config: { epochs: 10 }, 'on-complete': 'TRAINING_DONE' }]\n */\nexport type TrainEffect = ['train', TrainConfig];\n\n/**\n * Evaluate effect - runs model evaluation (Python backend).\n * @example ['evaluate', { architecture: [...], dataset: '@entity.testData', metrics: ['accuracy'], 'on-complete': 'EVAL_DONE' }]\n */\nexport type EvaluateEffect = ['evaluate', EvaluateConfig];\n\n/**\n * Checkpoint save effect - saves model weights.\n * @example ['checkpoint/save', '/path/to/model.pt', '@entity.weights']\n */\nexport type CheckpointSaveEffect = ['checkpoint/save', string, unknown];\n\n/**\n * Checkpoint load effect - loads model weights.\n * @example ['checkpoint/load', '/path/to/model.pt']\n */\nexport type CheckpointLoadEffect = ['checkpoint/load', string];\n\n// ============================================================================\n// Agent Effects (from agent/* operator namespace)\n// ============================================================================\n\n/**\n * Agent effect - invokes an agent/* operator.\n * Covers all 22 operators in the std-agent category.\n * @example ['agent/memorize', 'use data-grid for tables', 'preference']\n * @example ['agent/recall', 'user preferences']\n * @example ['agent/generate', 'Summarize this schema']\n */\nexport type AgentEffect = [`agent/${string}`, ...SExpr[]];\n\n/**\n * OS effect - invokes an os/* operator.\n *\n * Covers reactive subscriptions to OS / network resources:\n * - `os/watch-http`, `os/watch-ws`, `os/watch-sse` — long-lived streams\n * that fire `on_message` / `failure` events through a trailing\n * `EmitConfig` block (see `EmitConfig` for the supported keys).\n * - `os/read-file`, `os/exec`, etc. — one-shot OS operations.\n *\n * @example ['os/watch-http', 'wss://push.example.com', { emit: { on_message: 'PUSH_RECEIVED', failure: 'PUSH_DISCONNECTED' } }]\n * @example ['os/read-file', '/etc/hosts']\n */\nexport type OsEffect = [`os/${string}`, ...SExpr[]];\n\n// ============================================================================\n// Async Effects (from almadar-std/modules/async)\n// ============================================================================\n\n/**\n * Async delay effect - wait then execute effects.\n * @example ['async/delay', 2000, ['emit', 'TIMEOUT']]\n */\nexport type AsyncDelayEffect = ['async/delay', number | string, ...Effect[]];\n\n/**\n * Async debounce effect - debounce then execute effect.\n * @example ['async/debounce', 300, ['emit', 'SEARCH_COMPLETE']]\n * @example ['async/debounce', '@entity.debounceMs', ['emit', 'SEARCH_COMPLETE']]\n */\nexport type AsyncDebounceEffect = ['async/debounce', number | string, SExpr];\n\n/**\n * Async throttle effect - throttle then execute effect.\n * @example ['async/throttle', 100, ['emit', 'SCROLL_HANDLED']]\n * @example ['async/throttle', '@entity.throttleMs', ['emit', 'SCROLL_HANDLED']]\n */\nexport type AsyncThrottleEffect = ['async/throttle', number | string, SExpr];\n\n/**\n * Async interval effect - execute effect at intervals.\n * @example ['async/interval', 1000, ['emit', 'TICK']]\n * @example ['async/interval', '@entity.intervalMs', ['emit', 'POLL_TICK']]\n */\nexport type AsyncIntervalEffect = ['async/interval', number | string, SExpr];\n\n/**\n * Async race effect - first effect to complete wins.\n * @example ['async/race', ['call', 'api1'], ['call', 'api2']]\n */\nexport type AsyncRaceEffect = ['async/race', ...Effect[]];\n\n/**\n * Async all effect - wait for all effects to complete.\n * @example ['async/all', ['call', 'api1'], ['call', 'api2']]\n */\nexport type AsyncAllEffect = ['async/all', ...Effect[]];\n\n/**\n * Async sequence effect - execute effects in sequence.\n * @example ['async/sequence', ['call', 'validate'], ['call', 'save']]\n */\nexport type AsyncSequenceEffect = ['async/sequence', ...Effect[]];\n\n/**\n * Union of all typed effects.\n * Provides compile-time validation for common effect types.\n */\nexport type TypedEffect =\n | RenderUIEffect\n | NavigateEffect\n | EmitEffect\n | SetEffect\n | PersistEffect\n | CallServiceEffect\n | SpawnEffect\n | DespawnEffect\n | DoEffect\n | NotifyEffect\n | FetchEffect\n | IfEffect\n | WhenEffect\n | LetEffect\n | LogEffect\n | WaitEffect\n | RefEffect\n | DerefEffect\n | SwapEffect\n | WatchEffect\n | AtomicEffect\n | AsyncDelayEffect\n | AsyncDebounceEffect\n | AsyncThrottleEffect\n | AsyncIntervalEffect\n | AsyncRaceEffect\n | AsyncAllEffect\n | AsyncSequenceEffect\n | ForwardEffect\n | TrainEffect\n | EvaluateEffect\n | CheckpointSaveEffect\n | CheckpointLoadEffect\n | AgentEffect\n | OsEffect;\n\n// ============================================================================\n// Effect Type (Strictly Typed)\n// ============================================================================\n\n/**\n * Effect type - typed S-expression format.\n *\n * Effects are strongly typed tuples that enforce:\n * - Valid effect operators (render-ui, emit, set, persist, navigate, call-service)\n * - Valid UISlots for render-ui\n * - Valid PatternTypes and props for render-ui\n * - Correct argument types for each effect\n *\n * Available typed effects:\n * - RenderUIEffect: ['render-ui', UISlot, PatternConfig]\n * - NavigateEffect: ['navigate', path] or ['navigate', path, params]\n * - EmitEffect: ['emit', eventName] or ['emit', eventName, payload]\n * - SetEffect: ['set', binding, value]\n * - PersistEffect: ['persist', operation, entity, data?]\n * - CallServiceEffect: ['call-service', serviceName, config]\n *\n * @example\n * [\"set\", \"@entity.health\", 100]\n * [\"emit\", \"PLAYER_DIED\", { \"playerId\": \"@entity.id\" }]\n * [\"render-ui\", \"main\", { \"patternType\": \"entity-table\", \"columns\": [\"name\"] }]\n * [\"call-service\", \"WeatherAPI\", { \"action\": \"getWeather\", \"onSuccess\": \"OK\" }]\n * [\"navigate\", \"/tasks\"]\n * [\"persist\", \"create\", \"Task\", { \"title\": \"@payload.title\" }]\n */\nexport type Effect = TypedEffect;\n\n/**\n * Schema for Effect - validates S-expression format\n */\nexport const EffectSchema = z.array(z.unknown()).min(1).refine(\n (arr) => typeof arr[0] === 'string',\n { message: 'Effect must be an S-expression with a string operator as first element' }\n);\n\nexport type EffectInput = z.input<typeof EffectSchema>;\n\n/**\n * Type guard to check if a value is a valid Effect (S-expression).\n * \n * Validates that a value conforms to the Effect structure. Effects are\n * represented as arrays where the first element is a string (effect type)\n * and subsequent elements are parameters. Used for runtime validation\n * of effect structures.\n * \n * @param {unknown} value - Value to check\n * @returns {boolean} True if value is a valid Effect, false otherwise\n * \n * @example\n * isEffect(['set', '@entity.health', 100]); // returns true\n * isEffect('not-an-effect'); // returns false\n * isEffect([]); // returns false\n */\nexport function isEffect(value: unknown): value is Effect {\n return Array.isArray(value) && value.length > 0 && typeof value[0] === 'string';\n}\n\n/**\n * Alias for isEffect (for clarity when working with S-expressions)\n */\nexport const isSExprEffect = isEffect;\n\n// ============================================================================\n// Effect Builder Helpers\n// ============================================================================\n\n/**\n * Creates a set effect for state updates.\n * \n * Generates an effect that sets a binding to a value. Used in state\n * machine transitions to update entity fields, UI state, or other\n * mutable data.\n * \n * @param {string} binding - Target binding (e.g., '@entity.health')\n * @param {SExpr} value - Value to set (can be literal or expression)\n * @returns {Effect} Set effect array\n * \n * @example\n * set('@entity.health', 100); // returns [\"set\", \"@entity.health\", 100]\n * set('@state.loading', false); // returns [\"set\", \"@state.loading\", false]\n */\nexport function set(binding: string, value: SExpr): Effect {\n return ['set', binding, value];\n}\n\n/**\n * Creates an emit effect for event dispatching.\n * \n * Generates an effect that emits an event with optional payload.\n * Used in state machine transitions to trigger events that can be\n * handled by other traits, services, or external systems.\n * \n * @param {string} event - Event name to emit\n * @param {EventPayload} [payload] - Optional event payload\n * @returns {Effect} Emit effect array\n * \n * @example\n * emit('PLAYER_DIED', { playerId: '@entity.id' }); // returns [\"emit\", \"PLAYER_DIED\", { playerId: \"@entity.id\" }]\n * emit('GAME_STARTED'); // returns [\"emit\", \"GAME_STARTED\"]\n */\nexport function emit(event: string, payload?: EventPayload): Effect {\n return payload ? ['emit', event, payload] : ['emit', event];\n}\n\n/**\n * Creates a navigation effect for page routing.\n * \n * Generates an effect that navigates to a specified path with optional\n * parameters. Used in state machine transitions to change pages or\n * update URL parameters.\n * \n * @param {string} path - Target path (e.g., '/tasks')\n * @param {Record<string, string>} [params] - Optional URL parameters\n * @returns {NavigateEffect} Navigation effect array\n * \n * @example\n * navigate('/tasks'); // returns [\"navigate\", \"/tasks\"]\n * navigate('/user', { id: '123' }); // returns [\"navigate\", \"/user\", { id: \"123\" }]\n */\nexport function navigate(path: string): NavigateEffect;\nexport function navigate(path: string, params: Record<string, string>): NavigateEffect;\nexport function navigate(path: string, params?: Record<string, string>): NavigateEffect {\n return params ? ['navigate', path, params] : ['navigate', path];\n}\n\n/**\n * Create a render-ui effect\n * @example [\"render-ui\", \"main\", { \"patternType\": \"entity-table\", \"columns\": [\"name\"] }]\n */\nexport function renderUI(\n target: UISlot,\n pattern: AnyPatternConfig\n): RenderUIEffect;\nexport function renderUI(\n target: UISlot,\n pattern: AnyPatternConfig,\n props: ResolvedPatternProps\n): RenderUIEffect;\nexport function renderUI(\n target: UISlot,\n pattern: AnyPatternConfig,\n props?: ResolvedPatternProps\n): RenderUIEffect {\n return props\n ? ['render-ui', target, pattern, props]\n : ['render-ui', target, pattern];\n}\n\n/**\n * Create a persist effect\n * @example [\"persist\", \"create\", \"Task\", { \"title\": \"@payload.title\" }]\n */\nexport function persist(\n action: 'create' | 'update',\n entity: string,\n data: PersistData\n): PersistEffect;\nexport function persist(\n action: 'delete' | 'clear',\n entity: string,\n data?: PersistData\n): PersistEffect;\nexport function persist(\n action: 'create' | 'update' | 'delete' | 'clear',\n entity: string,\n data?: PersistData\n): PersistEffect {\n if (action === 'create' || action === 'update') {\n return ['persist', action, entity, data!] as PersistEffect;\n }\n return data\n ? ['persist', action, entity, data] as PersistEffect\n : ['persist', action, entity] as PersistEffect;\n}\n\n/**\n * Create a call-service effect\n * @example [\"call-service\", \"stripe\", { \"service\": \"stripe\", \"action\": \"charge\", \"onSuccess\": \"OK\", \"onError\": \"ERR\" }]\n */\nexport function callService(\n serviceName: string,\n config: CallServiceConfig\n): CallServiceEffect {\n return ['call-service', serviceName, config];\n}\n\n/**\n * Create a spawn effect (games)\n * @example [\"spawn\", \"Bullet\", { \"x\": \"@entity.x\", \"y\": \"@entity.y\" }]\n */\nexport function spawn(entity: string): SpawnEffect;\nexport function spawn(entity: string, initialState: EntityRow): SpawnEffect;\nexport function spawn(entity: string, initialState?: EntityRow): SpawnEffect {\n return initialState ? ['spawn', entity, initialState] : ['spawn', entity];\n}\n\n/**\n * Create a despawn effect (games)\n * @example [\"despawn\", \"@entity.id\"]\n */\nexport function despawn(entityId: string): DespawnEffect {\n return ['despawn', entityId];\n}\n\n/**\n * Create a do effect (multiple effects)\n * @example [\"do\", [\"set\", \"@entity.x\", 0], [\"set\", \"@entity.y\", 0]]\n */\nexport function doEffects(...effects: SExpr[]): DoEffect {\n return ['do', ...effects];\n}\n\n/**\n * Create a notify effect\n * @example [\"notify\", \"in_app\", \"Task created successfully\"]\n */\nexport function notify(\n channel: 'email' | 'push' | 'sms' | 'in_app',\n message: string\n): NotifyEffect;\nexport function notify(\n channel: 'email' | 'push' | 'sms' | 'in_app',\n message: string,\n recipient: string\n): NotifyEffect;\nexport function notify(\n channel: 'email' | 'push' | 'sms' | 'in_app',\n message: string,\n recipient?: string\n): NotifyEffect {\n return recipient\n ? ['notify', channel, message, recipient]\n : ['notify', channel, message];\n}\n\n/**\n * Create a fetch effect (server-side data retrieval)\n * @example [\"fetch\", \"User\"] - fetch all users\n * @example [\"fetch\", \"User\", { \"id\": \"@payload.userId\" }] - fetch by ID\n * @example [\"fetch\", \"User\", { \"filter\": [\"=\", \"@entity.status\", \"active\"], \"limit\": 10 }]\n */\nexport function fetch(entity: string): FetchEffect;\nexport function fetch(entity: string, options: FetchOptions): FetchEffect;\nexport function fetch(entity: string, options?: FetchOptions): FetchEffect {\n return options ? ['fetch', entity, options] : ['fetch', entity];\n}\n\n// ============================================================================\n// Resource Effect Builder Helpers\n// ============================================================================\n\n/**\n * Create a ref effect (reactive entity subscription).\n *\n * @param {string} binding - Binding or entity name to subscribe to\n * @param {FetchOptions} [selector] - Optional selector for specific entity\n * @returns {RefEffect} Ref effect array\n *\n * @example\n * ref('@entity.health'); // returns [\"ref\", \"@entity.health\"]\n * ref('User', { id: '@payload.userId' }); // returns [\"ref\", \"User\", { id: \"@payload.userId\" }]\n */\nexport function ref(binding: string): RefEffect;\nexport function ref(binding: string, selector: FetchOptions): RefEffect;\nexport function ref(binding: string, selector?: FetchOptions): RefEffect {\n return selector ? ['ref', binding, selector] : ['ref', binding];\n}\n\n/**\n * Create a deref effect (snapshot read).\n *\n * @param {string} binding - Binding or entity name to read\n * @param {FetchOptions} [selector] - Optional selector for specific entity\n * @returns {DerefEffect} Deref effect array\n *\n * @example\n * deref('@entity.health'); // returns [\"deref\", \"@entity.health\"]\n * deref('User', { id: '@payload.userId' }); // returns [\"deref\", \"User\", { id: \"@payload.userId\" }]\n */\nexport function deref(binding: string): DerefEffect;\nexport function deref(binding: string, selector: FetchOptions): DerefEffect;\nexport function deref(binding: string, selector?: FetchOptions): DerefEffect {\n return selector ? ['deref', binding, selector] : ['deref', binding];\n}\n\n/**\n * Create a swap! effect (atomic compare-and-swap).\n *\n * @param {string} binding - Binding to atomically update\n * @param {SExpr} transform - Transformation expression applied to the current value\n * @returns {SwapEffect} Swap effect array\n *\n * @example\n * swap('@entity.counter', ['+', '@entity.counter', 1]);\n * // returns [\"swap!\", \"@entity.counter\", [\"+\", \"@entity.counter\", 1]]\n */\nexport function swap(binding: string, transform: SExpr): SwapEffect {\n return ['swap!', binding, transform];\n}\n\n/**\n * Create a watch effect (entity change callback).\n *\n * @example\n * watch('@entity.health', 'HEALTH_CHANGED');\n * watch('@entity.status', 'STATUS_UPDATED', { debounce: 100 });\n */\nexport function watch(binding: string, event: string): WatchEffect;\nexport function watch(binding: string, event: string, options: WatchOptions): WatchEffect;\nexport function watch(binding: string, event: string, options?: WatchOptions): WatchEffect {\n return options\n ? ['watch', binding, event, options]\n : ['watch', binding, event];\n}\n\n/**\n * Create an atomic effect (transaction group).\n *\n * @param {...SExpr[]} effects - Effects to execute atomically\n * @returns {AtomicEffect} Atomic effect array\n *\n * @example\n * atomic(['set', '@entity.x', 10], ['set', '@entity.y', 20]);\n * // returns [\"atomic\", [\"set\", \"@entity.x\", 10], [\"set\", \"@entity.y\", 20]]\n */\nexport function atomic(...effects: SExpr[]): AtomicEffect {\n return ['atomic', ...effects];\n}\n\n// ============================================================================\n// Runtime Pattern Types\n// ============================================================================\n\n/** Resolved pattern props for render-ui effects at runtime. Recursive for nested pattern configs. */\nexport interface ResolvedPatternProps {\n [prop: string]: string | number | boolean | null | undefined | ResolvedPatternProps | ResolvedPatternProps[];\n}\n\n/** A node in a render-ui effect tree. */\nexport interface RenderUINode {\n type: string;\n props?: ResolvedPatternProps;\n children?: RenderUINode[];\n content?: string;\n entity?: string;\n renderItem?: RenderUINode;\n}\n\n","/**\n * S-Expression Types\n *\n * Defines the S-Expression type system for guards, effects, and computed values.\n * S-expressions are JSON arrays where the first element is an operator string.\n *\n * @example\n * // Guard: health > 0\n * [\">\", \"@entity.health\", 0]\n *\n * // Effect: set x to x + vx\n * [\"set\", \"@entity.x\", [\"+\", \"@entity.x\", \"@entity.vx\"]]\n *\n * @packageDocumentation\n */\n\nimport { z } from 'zod';\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// eslint-disable-next-line almadar/no-record-string-unknown -- SExprAtom defines the base type for object literals in S-expressions\nexport type SExprAtom = string | number | boolean | null | Record<string, unknown>;\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 * 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.unknown()), // Objects for payload data\n]);\n\n/**\n * Recursive schema for S-expressions.\n * Validates that arrays have at least one element and first element is a string (operator).\n */\nexport const SExprSchema: z.ZodType<SExpr> = z.lazy(() =>\n z.union([\n SExprAtomSchema,\n z\n .array(z.lazy(() => SExprSchema))\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// ============================================================================\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: unknown): 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 {unknown} 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: unknown): 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 {unknown} 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: unknown): 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 {unknown} 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: unknown): 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 */\nexport const CORE_BINDINGS = ['entity', 'payload', 'state', 'now', 'config', 'computed', 'trait', 'user'] 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/**\n * Get the arguments from an S-expression call.\n *\n * @param expr - S-expression array\n * @returns Array of arguments (empty if not a valid call)\n */\nexport function getArgs(expr: SExpr): SExpr[] {\n if (!isSExpr(expr)) return [];\n return expr.slice(1);\n}\n\n/**\n * Create an S-expression call.\n *\n * @param operator - The operator string\n * @param args - Arguments to the operator\n * @returns S-expression array\n */\nexport function sexpr(operator: string, ...args: SExpr[]): SExpr[] {\n return [operator, ...args];\n}\n\n/**\n * Walk an S-expression tree and apply a visitor function to each node.\n *\n * @param expr - S-expression to walk\n * @param visitor - Function to call on each node\n */\nexport function walkSExpr(\n expr: SExpr,\n visitor: (node: SExpr, parent: SExpr[] | null, index: number) => void,\n parent: SExpr[] | null = null,\n index: number = 0\n): void {\n visitor(expr, parent, index);\n\n if (isSExpr(expr)) {\n for (let i = 0; i < expr.length; i++) {\n walkSExpr(expr[i], visitor, expr, i);\n }\n }\n}\n\n/**\n * Collect all bindings referenced in an S-expression.\n *\n * @param expr - S-expression to analyze\n * @returns Array of binding strings found\n */\nexport function collectBindings(expr: SExpr): string[] {\n const bindings: string[] = [];\n\n walkSExpr(expr, (node) => {\n if (isBinding(node)) {\n bindings.push(node);\n }\n });\n\n return bindings;\n}\n\n// ============================================================================\n// Type Exports\n// ============================================================================\n\nexport type SExprInput = z.input<typeof SExprSchema>;\nexport type ExpressionInput = z.input<typeof ExpressionSchema>;\n\n// ============================================================================\n// Runtime Evaluation Types\n// ============================================================================\n\n/** Evaluation context for guards and s-expressions. Recursive. */\nexport interface EvalContext {\n [key: string]: string | number | boolean | Date | null | string[] | EvalContext | undefined;\n}\n\n/**\n * A single value carried by an event payload field. The top-level payload\n * is always an object; the VALUES in that object can be primitives, nested\n * objects, or arrays of the same. Arrays are allowed so real-world emits\n * like `{ files: [{ name, size, type }, ...] }` or `{ selected: string[] }`\n * are typed natively instead of forcing consumers to wrap at every call.\n *\n * `Date` is included so `EntityRow` (whose values are `FieldValue`, which\n * includes `Date`) is assignable to a payload field without a cast —\n * emitted entity rows flow through the bus without boundary widening.\n */\nexport type EventPayloadValue =\n | string\n | number\n | boolean\n | Date\n | null\n | undefined\n | EventPayload\n | readonly EventPayloadValue[];\n\n/**\n * Typed event payload. Object-shaped so it's assignable to the bus's\n * `EventPayload` parameter without casts.\n */\nexport interface EventPayload {\n [key: string]: EventPayloadValue;\n}\n\n/**\n * 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 * State Machine Types (Self-Contained)\n *\n * Defines state machine types for traits.\n * Copied from schema/state-machine.ts to make orbitals/ self-contained.\n *\n * @packageDocumentation\n */\n\nimport { z } from \"zod\";\nimport type { Effect } from \"./effect.js\";\nimport { EffectSchema } from \"./effect.js\";\nimport type { Expression } from \"./expression.js\";\nimport { ExpressionSchema } from \"./expression.js\";\n\n// ============================================================================\n// State\n// ============================================================================\n\n/**\n * Represents a state in the state machine\n */\nexport interface State {\n /** State name (unique identifier) */\n name: string;\n /** Whether this is the initial state */\n isInitial?: boolean;\n /** Whether this is a terminal state (no outgoing transitions expected) */\n isTerminal?: boolean;\n /** Whether this is a final state (legacy alias for isTerminal) */\n isFinal?: boolean;\n /** Human-readable description */\n description?: string;\n /** Effect names to run on entry */\n onEntry?: string[];\n /** Effect names to run on exit */\n onExit?: string[];\n}\n\nexport const StateSchema = z.object({\n name: z.string().min(1, \"State name is required\"),\n isInitial: z.boolean().optional(),\n isTerminal: z.boolean().optional(),\n isFinal: z.boolean().optional(),\n description: z.string().optional(),\n onEntry: z.array(z.string()).optional(),\n onExit: z.array(z.string()).optional(),\n});\n\n// ============================================================================\n// Event\n// ============================================================================\n\n/**\n * Payload field definition for events\n */\nexport interface PayloadField {\n name: string;\n /**\n * Field type. Mirrors the Rust validator's acceptance: any non-empty\n * string. Primitives ('string' | 'number' | 'boolean' | 'object' |\n * 'array') are the canonical values; entity-name references like\n * 'CartItem' and array-of-entity references like '[CartItem]' are also\n * valid because the Rust IR's PayloadField.field_type is just a String.\n */\n type: string;\n required?: boolean;\n}\n\nexport const PayloadFieldSchema = z.object({\n name: z.string().min(1),\n type: z.string().min(1),\n required: z.boolean().optional(),\n});\n\n/**\n * Represents an event that can trigger transitions\n */\nexport interface Event {\n /** Event key (UPPER_SNAKE_CASE) */\n key: string;\n /** Human-readable name */\n name: string;\n /** Description (authored `@description` on the emit/listen). */\n description?: string;\n /** User-vocabulary synonyms (comma-separated) — per-event analogue of a\n * field/config `@synonyms`. Feeds the curation event matcher. */\n synonyms?: string;\n /** Authoring tier (`essential`/`customization`/`advanced`/`internal`). */\n tier?: string;\n /** Expected payload structure */\n payloadSchema?: PayloadField[];\n /** Domain vs System classification (optional, for analysis) */\n classification?: \"domain\" | \"system\";\n /** Semantic role of this event (optional, for analysis) */\n semanticRole?: string;\n}\n\nexport const EventSchema = z.object({\n key: z.string().min(1, \"Event key is required\"),\n name: z.string().min(1, \"Event name is required\"),\n description: z.string().optional(),\n synonyms: z.string().optional(),\n tier: z.string().optional(),\n payloadSchema: z.array(PayloadFieldSchema).optional(),\n classification: z.enum([\"domain\", \"system\"]).optional(),\n semanticRole: z.string().optional(),\n});\n\n// ============================================================================\n// Guard\n// ============================================================================\n\n/**\n * Represents a named guard condition.\n * Expression must be an S-expression.\n *\n * @example\n * {\n * name: \"hasHealth\",\n * expression: [\">\", \"@entity.health\", 0],\n * description: \"Check if entity has health remaining\"\n * }\n */\nexport interface Guard {\n name: string;\n /** Guard expression - S-expression array only */\n expression: Expression;\n description?: string;\n}\n\nexport const GuardSchema = z.object({\n name: z.string().min(1, \"Guard name is required\"),\n expression: ExpressionSchema,\n description: z.string().optional(),\n});\n\n// ============================================================================\n// Transition (Effect imported separately to avoid circular deps)\n// ============================================================================\n\n/**\n * Represents a transition between states.\n * Guards and effects must be S-expressions.\n *\n * @example\n * {\n * from: \"idle\",\n * to: \"running\",\n * event: \"START\",\n * guard: [\">\", \"@entity.fuel\", 0],\n * effects: [\n * [\"set\", \"@entity.status\", \"running\"],\n * [\"emit\", \"ENGINE_STARTED\"]\n * ]\n * }\n */\nexport interface Transition {\n /** Source state name */\n from: string;\n /** Target state name */\n to: string;\n /** Event key that triggers this transition */\n event: string;\n /** Guard expression - S-expression array */\n guard?: Expression | null;\n /** Effects to execute - S-expression arrays */\n effects?: Effect[];\n /** Description */\n description?: string | null;\n}\n\nexport const TransitionSchema = z.object({\n from: z.string().min(1, \"Transition source state is required\"),\n to: z.string().min(1, \"Transition target state is required\"),\n event: z.string().min(1, \"Transition event is required\"),\n guard: ExpressionSchema.nullish(),\n effects: z.array(EffectSchema).optional(),\n description: z.string().nullish(),\n});\n\n// ============================================================================\n// State Machine\n// ============================================================================\n\n/**\n * Complete state machine definition\n */\nexport interface StateMachine {\n /** All states in the machine */\n states: State[];\n /** All events that can be triggered */\n events: Event[];\n /** All transitions between states */\n transitions: Transition[];\n /** Named guard definitions */\n guards?: Guard[];\n}\n\nexport const StateMachineSchema = z.object({\n states: z.array(StateSchema).min(1, \"At least one state is required\"),\n events: z.array(EventSchema),\n transitions: z.array(TransitionSchema),\n guards: z.array(GuardSchema).optional(),\n});\n\n// ============================================================================\n// Type exports\n// ============================================================================\n\nexport type StateInput = z.input<typeof StateSchema>;\nexport type EventInput = z.input<typeof EventSchema>;\nexport type GuardInput = z.input<typeof GuardSchema>;\nexport type TransitionInput = z.input<typeof TransitionSchema>;\nexport type StateMachineInput = z.input<typeof StateMachineSchema>;\n\n// ============================================================================\n// Event Utilities\n// ============================================================================\n\n/**\n * Check if an event is a circuit event (not internal/system event).\n * Circuit events are user-defined events that participate in the closed circuit pattern.\n * Internal/system events start with underscore (e.g., _INIT, _TICK, _TIMER).\n *\n * @param {string} event - Event name to check\n * @returns {boolean} true if event is a circuit event (doesn't start with underscore)\n *\n * @example\n * isCircuitEvent('CREATE') // true\n * isCircuitEvent('SAVE') // true\n * isCircuitEvent('_INIT') // false (internal)\n * isCircuitEvent('_TICK') // false (internal)\n */\nexport function isCircuitEvent(event: string): boolean {\n return !event.startsWith('_');\n}\n","/**\n * Trait Types (Self-Contained)\n *\n * Defines trait types for behavioral patterns.\n * Self-contained - imports only from local orbital types.\n *\n * @packageDocumentation\n */\n\nimport { z } from 'zod';\nimport type { StateMachine } from './state-machine.js';\nimport { StateMachineSchema } from './state-machine.js';\nimport type { Effect } from './effect.js';\nimport { EffectSchema } from './effect.js';\nimport type { Entity } from './entity.js';\nimport { EntitySchema } from './entity.js';\nimport type { AnyPatternConfig } from '@almadar/patterns';\nimport type { Expression } from './expression.js';\nimport { ExpressionSchema } from './expression.js';\n\n// ============================================================================\n// Trait Configuration\n// ============================================================================\n\n/**\n * A single value in a trait's call-site `config: { ... }` block. Supports\n * scalars (string, number, boolean, null), arrays (e.g. `fields: [\"name\",\n * \"description\"]`), and nested objects. This is the authoring surface for\n * molecules to parameterize imported atoms: the atom's render-ui reads back\n * via `@config.<key>` bindings.\n */\nexport type TraitConfigValue =\n | string\n | number\n | boolean\n | null\n | ReadonlyArray<TraitConfigValue>\n | TraitConfigObject;\n\nexport interface TraitConfigObject {\n readonly [key: string]: TraitConfigValue;\n}\n\nexport type TraitConfig = TraitConfigObject;\n\n/** Zod schema for TraitConfig. Recursive via z.lazy to allow nested structures. */\nexport const TraitConfigValueSchema: z.ZodType<TraitConfigValue> = z.lazy(() =>\n z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.null(),\n z.array(TraitConfigValueSchema),\n z.record(TraitConfigValueSchema),\n ])\n);\n\nexport const TraitConfigSchema: z.ZodType<TraitConfig> = z.record(TraitConfigValueSchema);\n\n/**\n * A single entry in a call-site `config { }` override block. Either a plain\n * wiring value (`TraitConfigValue` — string, number, bool, array, object) or\n * a fully-annotated re-declaration (`ConfigFieldDeclaration` — carries `type`,\n * optional `label`/`description`/`synonyms`/`tier`). Disambiguated at runtime\n * by `isCallSiteConfigDeclaration`: the presence of a `\"type\"` string key\n * marks the annotated form.\n *\n * The `.orb` compiler emits plain values for wiring entries and\n * `{ type, default, ... }` objects for annotated entries. Consumers that only\n * need the value (e.g. `apply-params-to-orb.ts`) read `entry` directly for\n * primitives or `entry.default` for the declaration form.\n */\nexport type CallSiteConfigEntry = TraitConfigValue | ConfigFieldDeclaration;\n\n/** Typed map of call-site config entries (one per knob). */\nexport type CallSiteConfig = Readonly<Record<string, CallSiteConfigEntry>>;\n\n/**\n * Type guard: returns `true` when `entry` is an annotated `ConfigFieldDeclaration`\n * (a config-field SCHEMA: a `\"type\"` string key AND a `\"default\"` value slot)\n * rather than a plain wiring value or a render value object.\n *\n * The `\"default\"` requirement disambiguates a declaration from a `render-ui`\n * VALUE object (e.g. `{ type: \"tabs\", items: \"@entity.items\", ... }`) that\n * coincidentally carries a UI-component `type` key — such a value has no\n * `default` slot and is a `TraitConfigValue`, not a schema declaration. Every\n * annotated config field lowered from `.lolo` carries a `default`; misreading a\n * render value as a declaration drops it straight into the `config` map where\n * Rust's `serde` rejects its inner fields (e.g. `items` is a binding string,\n * not a `FieldDefinition`).\n */\nexport function isCallSiteConfigDeclaration(\n entry: CallSiteConfigEntry,\n): entry is ConfigFieldDeclaration {\n return (\n typeof entry === 'object' &&\n entry !== null &&\n !Array.isArray(entry) &&\n 'type' in entry &&\n typeof entry.type === 'string' &&\n 'default' in entry\n );\n}\n\n/**\n * Per-field entry in a trait's DECLARED `config { }` schema as it lives\n * on the `.orb` JSON: `{ type: \"string\" | \"[string]\" | \"object\" | ...,\n * default?: <value> }`. Distinct from `TraitConfigValue` (which is the\n * resolved runtime value). The runtime reads `default` to seed the\n * `@config.X` binding context when no call-site override is supplied.\n *\n * Authored as `config { foo : string = \"bar\" }` in `.lolo`; lowered to\n * `{ foo: { type: \"string\", default: \"bar\" } }` in `.orb`. The optional\n * metadata fields below (`label`/`description`/`tier`/`values`/`synonyms`)\n * carry the `.lolo` `@label`/`@description`/`@tier`/`@synonyms` annotations and\n * the enum member list through lowering — consumed by config-driven UI\n * (e.g. the playground property inspector) to render typed controls.\n */\nexport interface ConfigFieldDeclaration {\n readonly type: string;\n readonly default?: TraitConfigValue;\n /** `@label` — human-readable control label. */\n readonly label?: string;\n /** `@description` — help/tooltip text for the field. */\n readonly description?: string;\n /** `@tier` — disclosure tier: `presentation`|`domain`|`policy`|`infra`|`internal`. */\n readonly tier?: string;\n /** Enum members when the field's type is a string union — drives a select control. */\n readonly values?: ReadonlyArray<string>;\n /** `@synonyms` — comma-separated vocabulary synonyms (metadata). */\n readonly synonyms?: string;\n}\n\nexport const ConfigFieldDeclarationSchema: z.ZodType<ConfigFieldDeclaration> = z.object({\n type: z.string(),\n default: TraitConfigValueSchema.optional(),\n label: z.string().optional(),\n description: z.string().optional(),\n tier: z.string().optional(),\n values: z.array(z.string()).optional(),\n synonyms: z.string().optional(),\n});\n\n/**\n * Map of declared config fields keyed by name. Lives on `Trait.config`\n * and `ResolvedTrait.config` for atoms/molecules that expose typed\n * configuration to consumers.\n */\nexport type DeclaredTraitConfig = Readonly<Record<string, ConfigFieldDeclaration>>;\n\nexport const DeclaredTraitConfigSchema: z.ZodType<DeclaredTraitConfig> = z.record(\n ConfigFieldDeclarationSchema,\n);\n\n// ============================================================================\n// Trait Categories\n// ============================================================================\n\n/**\n * Categories for organizing traits\n */\nexport type TraitCategory =\n | 'lifecycle'\n | 'temporal'\n | 'validation'\n | 'notification'\n | 'integration'\n | 'interaction'\n | 'agent'\n | 'game-core'\n | 'game-character'\n | 'game-ai'\n | 'game-combat'\n | 'game-items'\n | 'game-cards'\n | 'game-board'\n | 'game-puzzle';\n\nexport const TraitCategorySchema = z.enum([\n 'lifecycle',\n 'temporal',\n 'validation',\n 'notification',\n 'integration',\n 'interaction',\n 'agent',\n 'game-core',\n 'game-character',\n 'game-ai',\n 'game-combat',\n 'game-items',\n 'game-cards',\n 'game-board',\n 'game-puzzle',\n]);\n\n// ============================================================================\n// Trait Entity Field (simplified)\n// ============================================================================\n\n/**\n * Field types for trait data entities\n */\nexport type TraitFieldType = 'string' | 'number' | 'boolean' | 'date' | 'array' | 'object' | 'timestamp' | 'datetime' | 'enum';\n\n/**\n * Simplified field for trait data entities\n */\nexport interface TraitEntityField {\n name: string;\n type: TraitFieldType;\n required?: boolean;\n default?: unknown;\n values?: string[];\n}\n\nexport const TraitEntityFieldSchema = z.object({\n name: z.string().min(1),\n type: z.enum([\n 'string',\n 'number',\n 'boolean',\n 'date',\n 'array',\n 'object',\n 'timestamp',\n 'datetime',\n 'enum',\n ]),\n required: z.boolean().optional(),\n default: z.unknown().optional(),\n values: z.array(z.string()).optional(),\n});\n\n// ============================================================================\n// Trait Data Entity\n// ============================================================================\n\n/**\n * Simplified data entity for traits\n */\nexport interface TraitDataEntity {\n name: string;\n collection?: string;\n fields: TraitEntityField[];\n timestamps?: boolean;\n description?: string;\n runtime?: boolean;\n singleton?: boolean;\n pages?: string[];\n}\n\nexport const TraitDataEntitySchema = z.object({\n name: z.string().min(1),\n collection: z.string().optional(),\n fields: z.array(TraitEntityFieldSchema).min(1),\n timestamps: z.boolean().optional(),\n description: z.string().optional(),\n runtime: z.boolean().optional(),\n singleton: z.boolean().optional(),\n pages: z.array(z.string()).optional(),\n});\n\n// ============================================================================\n// Trait Tick\n// ============================================================================\n\n/**\n * Tick rule for traits.\n * Guards can be legacy strings or S-expressions.\n * Effects can be typed Effect objects or S-expressions.\n */\nexport interface TraitTick {\n name: string;\n description?: string;\n priority?: number;\n interval: string | number;\n appliesTo?: string[];\n pages?: string[];\n /** Guard expression - string (legacy) or S-expression array */\n guard?: Expression;\n /** Effects to execute (S-expressions) */\n effects: Effect[];\n /**\n * Events this tick emits.\n * Must reference events defined in trait's emits array.\n * Used for validation and documentation.\n */\n emits?: string[];\n}\n\nexport const TraitTickSchema = z.object({\n name: z.string().min(1),\n description: z.string().optional(),\n priority: z.number().optional(),\n interval: z.union([z.literal('frame'), z.number().positive()]),\n appliesTo: z.array(z.string()).optional(),\n pages: z.array(z.string()).optional(),\n guard: ExpressionSchema.optional(),\n effects: z.array(EffectSchema).min(1),\n emits: z.array(z.string()).optional(),\n});\n\n// ============================================================================\n// Event Scope\n// ============================================================================\n\n/**\n * Event scope determines visibility:\n * - 'internal': Trait-to-trait within same orbital (default)\n * - 'external': Exposed for cross-orbital communication\n */\nexport type EventScope = 'internal' | 'external';\n\nexport const EventScopeSchema = z.enum(['internal', 'external']);\n\n// ============================================================================\n// Event Payload Field\n// ============================================================================\n\n/**\n * Payload field definition for events.\n * Defines the structure of data carried by events.\n */\nexport interface EventPayloadField {\n /** Field name */\n name: string;\n /**\n * Field type. Any non-empty string, mirroring the Rust validator's\n * acceptance (Zod schema below uses `z.string().min(1)`). Well-known\n * values include the primitives (`string`, `number`, `boolean`,\n * `object`, `array`, `entity`), date variants (`date`, `datetime`,\n * `timestamp`), entity-name references (`User`), and array-of-entity\n * shorthand (`[User]`). Narrowing happens at the call sites that care\n * (e.g. `orbital-compiler/phases/validation/emit_payload.rs`), not at\n * the structural type level — this keeps `.orb`-emitted payloads\n * round-trippable through TypeScript without losing precision.\n */\n type: string;\n /** Whether field is required in payload */\n required?: boolean;\n /** Human-readable description */\n description?: string;\n /** For 'entity' type: the entity type name */\n entityType?: string;\n}\n\nexport const EventPayloadFieldSchema = z.object({\n name: z.string().min(1),\n /**\n * Field type. Mirrors the Rust validator's acceptance: any non-empty\n * string. Primitives ('string' | 'number' | 'boolean' | 'object' |\n * 'array') are the canonical values; entity-name references like\n * 'ModalRecord' and array-of-entity references like '[ModalRecord]'\n * are also valid because the Rust IR's PayloadField.field_type is\n * just a String. Only enforced narrowly at the call site (e.g.\n * emit-literal type-mismatch warnings in\n * orbital-compiler/phases/validation/emit_payload.rs) — not here.\n */\n type: z.string().min(1),\n required: z.boolean().optional(),\n description: z.string().optional(),\n entityType: z.string().optional(),\n});\n\n// ============================================================================\n// Trait Event Contract\n// ============================================================================\n\n/**\n * Event contract for events a trait emits.\n * Declares the event name, scope, and payload schema.\n */\nexport interface TraitEventContract {\n /** Event name (UPPER_SNAKE_CASE) */\n event: string;\n /** Human-readable description */\n description?: string;\n /** User-vocabulary synonyms (comma-separated) — the per-event analogue of a\n * field/config `@synonyms`. Feeds the curation event matcher. */\n synonyms?: string;\n /** Authoring tier (`essential`/`customization`/`advanced`/`internal`). */\n tier?: string;\n /** Payload schema — declarative type info for the event's payload.\n * Distinct from the runtime payload value (`@payload.X` bindings,\n * `EventPayload`) which is a separate concept. */\n payloadSchema?: EventPayloadField[];\n /**\n * Event scope:\n * - 'internal': Trait-to-trait within same orbital (default)\n * - 'external': Exposed for cross-orbital communication\n */\n scope?: EventScope;\n}\n\nexport const TraitEventContractSchema = z.object({\n /**\n * Event name. Mirrors the Rust validator's `is_valid_event_identifier`:\n * starts with a letter, then any letters / digits / underscores. Both\n * UPPER_SNAKE_CASE and PascalCase shapes are valid identifiers in the\n * post-Phase 2.5 nominal-event type system (events declared via\n * `type X = Event<T>`).\n */\n event: z.string().min(1).regex(\n /^[A-Za-z][A-Za-z0-9_]*$/,\n 'Event name must start with a letter and contain only letters, digits, and underscores'\n ),\n description: z.string().optional(),\n synonyms: z.string().optional(),\n tier: z.string().optional(),\n payloadSchema: z.array(EventPayloadFieldSchema).optional(),\n scope: EventScopeSchema.optional(),\n});\n\n// ============================================================================\n// Trait Event Listener\n// ============================================================================\n\n/**\n * Event listener for trait communication.\n * Guards can be legacy strings or S-expressions.\n * Enhanced with scope and payloadMapping for cross-orbital communication.\n */\n/**\n * Source-scoping for a `listens {}` entry. Determines which emitters the\n * listener responds to.\n *\n * - `{ kind: \"any\" }`: wildcard (`* EVENT -> TRIGGER`). Any trait, any orbital.\n * - `{ kind: \"trait\", trait: \"X\" }`: intra-orbital (`X EVENT -> TRIGGER`).\n * Only emits from the same orbital's trait `X`.\n * - `{ kind: \"orbital\", orbital: \"O\", trait: \"X\" }`: cross-orbital\n * (`O.X EVENT -> TRIGGER`). Only emits from orbital `O`'s trait `X`.\n *\n * Absent (undefined) means the listener is a local payload-declaration only\n * — pure type metadata, no bus subscription.\n */\nexport type ListenSource =\n | { kind: 'any' }\n | { kind: 'trait'; trait: string }\n | { kind: 'orbital'; orbital: string; trait: string };\n\nexport const ListenSourceSchema = z.union([\n z.object({ kind: z.literal('any') }),\n z.object({ kind: z.literal('trait'), trait: z.string().min(1) }),\n z.object({\n kind: z.literal('orbital'),\n orbital: z.string().min(1),\n trait: z.string().min(1),\n }),\n]);\n\nexport interface TraitEventListener {\n /** Event key to listen for (bare event name, no source prefix in the new shape) */\n event: string;\n /** State machine event to trigger */\n triggers: string;\n /** Human-readable description (authored `@description` on the listen). */\n description?: string;\n /** User-vocabulary synonyms (comma-separated). */\n synonyms?: string;\n /** Authoring tier (`essential`/`customization`/`advanced`/`internal`). */\n tier?: string;\n /** Guard expression - string (legacy) or S-expression array */\n guard?: Expression;\n /**\n * Listener scope:\n * - 'internal': Listen to events within same orbital (default)\n * - 'external': Listen to events from other orbitals\n */\n scope?: EventScope;\n /** Map event payload fields to transition payload */\n payloadMapping?: Record<string, string>;\n /**\n * Source scoping (see `ListenSource`). Undefined when the listen entry is\n * a local payload declaration rather than a bus subscription.\n */\n source?: ListenSource;\n}\n\nexport const TraitEventListenerSchema = z.object({\n event: z.string().min(1),\n triggers: z.string().min(1),\n description: z.string().optional(),\n synonyms: z.string().optional(),\n tier: z.string().optional(),\n guard: ExpressionSchema.optional(),\n scope: EventScopeSchema.optional(),\n payloadMapping: z.record(z.string()).optional(),\n source: ListenSourceSchema.optional(),\n});\n\n// ============================================================================\n// Required Field\n// ============================================================================\n\n/**\n * Field required by a trait from its linkedEntity\n */\nexport interface RequiredField {\n name: string;\n type: 'string' | 'number' | 'boolean' | 'date' | 'array' | 'object' | 'timestamp' | 'datetime' | 'enum';\n description?: string;\n}\n\nexport const RequiredFieldSchema = z.object({\n name: z.string().min(1),\n type: z.enum(['string', 'number', 'boolean', 'date', 'array', 'object', 'timestamp', 'datetime', 'enum']),\n description: z.string().optional(),\n});\n\n// ============================================================================\n// Trait Reference\n// ============================================================================\n\n/**\n * Reference to a trait from an entity or page.\n *\n * Phase F treats a trait reference as a function call: `ref` names the\n * imported trait and the sibling fields are arguments. The compiler's\n * identifier-substitution pass uses these arguments to rewrite the\n * inlined trait clone before lowering.\n */\nexport interface TraitReference {\n ref: string;\n /**\n * Phase 1.2: optional registry path disambiguator. Pairs with `ref` to\n * explicitly name which `uses` entry the alias was imported from\n * (e.g. \"std/behaviors/atoms/std-browse\"). Helpful for programmatic\n * descriptor construction and inline-phase disambiguation when multiple\n * registries expose the same alias prefix.\n */\n from?: string;\n linkedEntity?: string;\n /** Phase F: rename the inlined trait at the call site */\n name?: string;\n /** Phase F: rename atom event keys at the call site, e.g. {OPEN: \"ADD_ITEM\"} */\n events?: Record<string, string>;\n /**\n * Entity-field remap: rewrite the inlined trait's canonical `@entity.X` /\n * `@payload.row.X` field references to the consumer entity's field names,\n * e.g. `{ name: \"title\", folder: \"parentId\" }`. Mirrors `events` for\n * fields. Applied during inline substitution alongside `linkedEntity`.\n */\n fields?: Record<string, string>;\n /**\n * Call-site config overrides. Each entry is either a plain wiring value\n * (`TraitConfigValue`) or a fully-annotated re-declaration\n * (`ConfigFieldDeclaration` with `type`, optional `label`/`description`/\n * `synonyms`/`tier`). Use `isCallSiteConfigDeclaration` to discriminate.\n *\n * Plain wiring (existing callers): `config: { icon: \"star\", count: 5 }`.\n * Annotated (new): `config: { icon: { type: \"string\", default: \"star\",\n * label: \"Icon\", tier: \"presentation\" } }`.\n */\n config?: CallSiteConfig;\n appliesTo?: string[];\n /**\n * Phase F.7: replace the imported trait's `listens` array with the\n * caller-supplied list. Empty array clears all upstream listens. The\n * inliner applies this AFTER substitution, overwriting whatever the\n * upstream declared. Use sparingly: this drops external event wiring.\n */\n listens?: TraitEventListener[];\n /**\n * Phase F.7: set every emit's `scope` to the caller-supplied value.\n * `'internal'` confines emits to the orbital's internal bus; `'external'`\n * broadcasts them. Applied after substitution and listens replacement.\n */\n emitsScope?: 'internal' | 'external';\n /**\n * Phase F.8: per-transition effects override. The map's keys are event\n * names (the transition triggers, AFTER any rename via `events`). The\n * values are the SExpression effect lists that REPLACE the matching\n * transitions' `effects[]` arrays.\n *\n * This is the unified content + effect override mechanism. Whether the\n * override list contains `[\"render-ui\", ...]` (visual content),\n * `[\"fetch\", ...]` (data load), `[\"persist\", ...]` (mutation), or any\n * combination, the inliner just substitutes the whole list. Identifier\n * substitution (entity refs, event refs) still runs over the merged\n * trait body, so override effects can use either upstream or caller\n * identifiers and the F.3 walker will rewrite them consistently.\n *\n * Example:\n * ```json\n * \"effects\": {\n * \"ADD_ITEM\": [\n * [\"fetch\", \"CartItem\"],\n * [\"render-ui\", \"main\", { ... }]\n * ],\n * \"SAVE\": [\n * [\"persist\", \"create\", \"CartItem\", \"@payload.data\"]\n * ]\n * }\n * ```\n */\n effects?: Record<string, unknown[]>;\n}\n\nexport const TraitReferenceSchema = z\n .object({\n ref: z.string().min(1),\n // Phase 1.2: optional registry path disambiguator, pairs with `ref`.\n from: z.string().optional(),\n linkedEntity: z.string().optional(),\n name: z.string().optional(),\n events: z\n .record(\n z.string().min(1, \"events key (atom event name) must be non-empty\"),\n z.string().min(1, \"events value (caller event name) must be non-empty\"),\n )\n .optional(),\n fields: z\n .record(\n z.string().min(1, \"fields key (canonical field name) must be non-empty\"),\n z.string().min(1, \"fields value (consumer field name) must be non-empty\"),\n )\n .optional(),\n // Each value is either a plain wiring value (TraitConfigValue) or an\n // annotated ConfigFieldDeclaration. Declaration form is tried first\n // (it's more specific — has a `\"type\"` string key); plain values fall\n // through to the recursive TraitConfigValue union.\n config: z.record(z.union([ConfigFieldDeclarationSchema, TraitConfigValueSchema])).optional(),\n appliesTo: z.array(z.string()).optional(),\n // Phase F.7: zod accepts an array (the inliner validates element\n // shape). The full ListenDefinition shape isn't recursively encoded\n // here because TraitReference is the call-site form — listen entries\n // pasted in are already-resolved structured definitions, not nested\n // overrides.\n listens: z.array(z.unknown()).optional(),\n emitsScope: z.enum(['internal', 'external']).optional(),\n // Phase F.8: per-transition effects override. The keys are event\n // names (the transition triggers AFTER renames). Values are arrays\n // of SExpression-shaped data; the inliner validates the SExpression\n // shape during application, so the schema accepts loose `unknown[]`.\n effects: z\n .record(\n z.string().min(1, \"effects override key (event name) must be non-empty\"),\n z.array(z.unknown()),\n )\n .optional(),\n })\n .refine(\n (ref) => {\n if (!ref.events) return true;\n // Phase F.4: reject empty event-name strings on either side of\n // every entry. The substitution pass treats empty strings as\n // no-ops at runtime, but accepting them at the schema boundary\n // hides authoring errors. The per-entry .min(1) above already\n // rejects most cases; this refine is the belt-and-braces check\n // that survives any future relaxation of the inner validators.\n for (const [from, to] of Object.entries(ref.events)) {\n if (from.length === 0 || to.length === 0) return false;\n }\n return true;\n },\n {\n message:\n 'TraitReference \"events\" entries must have non-empty atom and caller event names',\n path: [\"events\"],\n },\n );\n\n/**\n * Simplified trait reference - supports string, reference object, or inline Trait definition\n * - string: \"TraitName\" - reference to a trait by name\n * - { ref: \"TraitName\" }: reference object with optional config / overrides\n * - { name: \"TraitName\", stateMachine: {...} }: inline trait definition\n *\n * Phase F adds `name` and `events` to the reference object form so callers\n * can rename the trait and remap atom event keys.\n */\nexport type TraitRef =\n | string\n | {\n ref: string;\n config?: CallSiteConfig;\n linkedEntity?: string;\n name?: string;\n events?: Record<string, string>;\n }\n | Trait;\n\n// TraitRefSchema is defined after TraitSchema (see below) to avoid forward reference\n\n// ============================================================================\n// Trait UI Binding\n// ============================================================================\n\nexport type PresentationType = 'modal' | 'drawer' | 'popover' | 'inline' | 'confirm-dialog';\n\nexport interface TraitUIBinding {\n [stateName: string]: {\n presentation: PresentationType;\n content: AnyPatternConfig | AnyPatternConfig[];\n props?: {\n size?: 'sm' | 'md' | 'lg' | 'xl' | 'full';\n position?: 'left' | 'right' | 'top' | 'bottom' | 'center';\n title?: string;\n closable?: boolean;\n width?: string;\n showProgress?: boolean;\n step?: number;\n totalSteps?: number;\n };\n };\n}\n\n// ============================================================================\n// Trait Definition\n// ============================================================================\n\n/**\n * A Trait is a reusable behavioral module with state machine.\n *\n * Traits declare their event contracts via `emits` and `listens`:\n * - `emits`: Events this trait can emit (with scope and payload schema)\n * - `listens`: Events this trait listens for (with optional payloadMapping)\n */\n/**\n * Instance vs collection scope for a trait.\n *\n * Mirrors the `.lolo` trait modifier list (`[interaction, instance]` /\n * `[interaction, collection]`). Instance traits own a single entity record\n * (typed by `linkedEntity`) and read/write `@entity.field`. Collection\n * traits render records of `linkedEntity` without owning any one; data flows\n * through `@payload.data` typed as `Array<linkedEntity>`.\n *\n * Optional today. A future phase (Almadar_Entity_V2_Plan.md Phase 4) makes\n * it required and adds static checks in the compiler.\n */\nexport type TraitScope = 'instance' | 'collection';\n\nexport const TraitScopeSchema = z.enum(['instance', 'collection']);\n\n/**\n * Inferred field contract for a `@rebindable` trait binding. `requires` =\n * entity fields the trait READS via `@entity.<field>`; `provides` = fields it\n * WRITES via `(set @entity.<field> ...)`. A consumer that rebinds the trait\n * (`linkedEntity`) must point at an entity whose fields ⊇ `requires`. Inferred\n * by the lolo lowerer from the trait's own SExpr usage; the orbital-rust L2\n * validator enforces it (`ORB_T_REBIND_MISSING_FIELDS`). Mirrors the Rust\n * `EntityFieldContract` serde shape exactly.\n */\nexport interface EntityFieldContract {\n requires: string[];\n provides: string[];\n}\n\nexport const EntityFieldContractSchema = z.object({\n requires: z.array(z.string()),\n provides: z.array(z.string()),\n});\n\nexport interface Trait {\n name: string;\n description?: string;\n description_visual_prompt?: string;\n category?: TraitCategory;\n /**\n * Opt-in marker authored as `-> @rebindable Entity` in `.lolo`. When\n * `true`, a consuming molecule/organism may rebind this trait's entity via\n * `linkedEntity`; otherwise the binding is fixed and the validator rejects\n * any rebind (`ORB_T_ENTITY_NOT_REBINDABLE`). Absent on traits that don't\n * bind an entity.\n */\n entityRebindable?: boolean;\n /**\n * Inferred field contract a rebind target must satisfy. Emitted only\n * alongside `entityRebindable: true`. See {@link EntityFieldContract}.\n */\n entityContract?: EntityFieldContract;\n /**\n * `@description \"...\"` authored on the `@rebindable` binding in `.lolo`.\n * Surfaced to catalog prose + knob-embeddings so the LLM can reach for the\n * binding from intent vocabulary (binding-discovery). Absent when unmarked.\n */\n entityBindingDescription?: string;\n /** `@synonyms \"...\"` authored on the `@rebindable` binding in `.lolo`. */\n entityBindingSynonyms?: string;\n /**\n * Author-supplied capability tags lifted from the `.lolo` trait header's\n * bracket list. Anything beyond the known scope tokens (`instance` /\n * `collection`) and the first category identifier accumulates here.\n * Free-form strings — the lolo parser does not validate them against a\n * known set. The Phase 4 translator overlay matches rules to traits by\n * exact set membership against this list. Empty when no capabilities\n * were declared. See `docs/Almadar_Domain_Language.md` Phase 3.\n */\n capabilities?: string[];\n /**\n * Instance or collection scope. Required in V2: every trait operates on\n * either a single record (`instance`) or a group (`collection`). Drives\n * payload-inference rules for emits declared via `type X = Event<T>` and\n * shapes the runtime's binding semantics. Authored in `.lolo` as the\n * `[instance]` / `[collection]` modifier on the trait header.\n */\n scope: TraitScope;\n /**\n * The entity this trait is linked to.\n * Required for inline trait definitions within an orbital.\n */\n linkedEntity?: string;\n requiredFields?: RequiredField[];\n dataEntities?: TraitDataEntity[];\n stateMachine?: StateMachine;\n initialEffects?: Effect[];\n ticks?: TraitTick[];\n /**\n * Events this trait emits.\n * Each event can be scoped as internal or external.\n * External events are namespaced at orbital level (TraitName.EVENT_NAME).\n */\n emits?: TraitEventContract[];\n /**\n * Events this trait listens for.\n * External listeners reference namespaced events (TraitName.EVENT_NAME).\n */\n listens?: TraitEventListener[];\n ui?: TraitUIBinding;\n /**\n * Declared `config { }` schema authored on the trait. Drives\n * `@config.X` substitution: each field's `default` seeds the\n * binding context behind any caller-supplied call-site\n * `config: { ... }` override.\n */\n config?: DeclaredTraitConfig;\n /**\n * Set by the resolve/inline phase when this trait was cloned from a\n * `uses[]` import. Absent for traits authored directly on the\n * orbital. Viewport-only metadata — runtime and codegen ignore it.\n * Drives Studio's L2 grouping (imported traits collapse under one\n * card per alias) and L3 drill (alias → that behavior's transitions).\n */\n sourceBehavior?: SourceBehaviorMetadata;\n /**\n * Set by the resolve/inline phase alongside `sourceBehavior`. Carries\n * the resolved `Entity` definition of the imported behavior so the\n * client-side mock-data generator can produce rows for the trait's\n * `linkedEntity` without re-walking the import graph at runtime.\n */\n sourceEntityDefinition?: Entity;\n}\n\n/**\n * Provenance attached to a trait that was cloned from a `uses[]` import\n * during the inline phase. The resolved schema carries this so Studio\n * can group L2 cards by source behavior and offer an L3 drill into the\n * import's own transitions.\n */\nexport interface SourceBehaviorMetadata {\n /** Behavior name (e.g. \"std-stat-card\") — the resolved `from:` value. */\n behavior: string;\n /** Alias used at the import site (e.g. \"Stat\"). Multiple imports of\n * the same atom group by alias, not by behavior. */\n alias: string;\n /** Original trait name inside the imported behavior, before any\n * call-site `name:` rename. */\n originalName: string;\n}\n\nexport const SourceBehaviorMetadataSchema = z.object({\n behavior: z.string().min(1),\n alias: z.string().min(1),\n originalName: z.string().min(1),\n});\n\nexport const TraitSchema = z.object({\n name: z.string().min(1),\n description: z.string().optional(),\n description_visual_prompt: z.string().optional(),\n category: TraitCategorySchema.optional(),\n entityRebindable: z.boolean().optional(),\n entityContract: EntityFieldContractSchema.optional(),\n entityBindingDescription: z.string().optional(),\n entityBindingSynonyms: z.string().optional(),\n capabilities: z.array(z.string()).optional(),\n scope: TraitScopeSchema,\n linkedEntity: z.string().optional(),\n requiredFields: z.array(RequiredFieldSchema).optional(),\n dataEntities: z.array(TraitDataEntitySchema).optional(),\n stateMachine: StateMachineSchema.optional(),\n initialEffects: z.array(EffectSchema).optional(),\n ticks: z.array(TraitTickSchema).optional(),\n emits: z.array(TraitEventContractSchema).optional(),\n listens: z.array(TraitEventListenerSchema).optional(),\n ui: z.record(z.unknown()).optional(),\n config: DeclaredTraitConfigSchema.optional(),\n sourceBehavior: SourceBehaviorMetadataSchema.optional(),\n sourceEntityDefinition: EntitySchema.optional(),\n});\n\n// TraitRefSchema defined here after TraitSchema to avoid forward reference\nexport const TraitRefSchema = z.union([\n z.string().min(1),\n z.object({\n ref: z.string().min(1),\n config: TraitConfigSchema.optional(),\n linkedEntity: z.string().optional(),\n name: z.string().optional(),\n // Phase F.4: same non-empty refine as TraitReferenceSchema.events.\n // Both schemas accept the same call-site argument shape, so the\n // validators should agree.\n events: z\n .record(\n z.string().min(1, \"events key (atom event name) must be non-empty\"),\n z.string().min(1, \"events value (caller event name) must be non-empty\"),\n )\n .optional(),\n }),\n TraitSchema, // Allow inline trait definitions\n]);\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Check if a trait ref is an inline Trait definition\n */\n/**\n * Checks if a trait reference is an inline trait definition.\n * \n * Type guard to determine if a TraitRef is an inline trait object\n * (with 'name' property) rather than a string reference or object reference.\n * \n * @param {TraitRef} traitRef - Trait reference to check\n * @returns {boolean} True if traitRef is an inline trait, false otherwise\n * \n * @example\n * isInlineTrait({ name: 'MyTrait' }); // returns true (inline)\n * isInlineTrait('MyTrait'); // returns false (string reference)\n * isInlineTrait({ ref: 'MyTrait' }); // returns false (object reference)\n */\nexport function isInlineTrait(traitRef: TraitRef): traitRef is Trait {\n return typeof traitRef === 'object' && 'name' in traitRef && !('ref' in traitRef);\n}\n\n/**\n * Extracts the trait name from a trait reference.\n * \n * Handles all trait reference formats (string, inline object, object reference)\n * and returns the canonical trait name.\n * \n * @param {TraitRef} traitRef - Trait reference to extract name from\n * @returns {string} Trait name\n * \n * @example\n * getTraitName('MyTrait'); // returns 'MyTrait'\n * getTraitName({ name: 'MyTrait' }); // returns 'MyTrait'\n * getTraitName({ ref: 'MyTrait' }); // returns 'MyTrait'\n */\nexport function getTraitName(traitRef: TraitRef): string {\n if (typeof traitRef === 'string') {\n return traitRef;\n }\n if (isInlineTrait(traitRef)) {\n return traitRef.name;\n }\n return traitRef.ref;\n}\n\n/**\n * Extracts the configuration from a trait reference.\n * \n * Returns the configuration object for trait references that support it\n * (object references with 'config' property). Returns undefined for\n * string references and inline traits.\n * \n * @param {TraitRef} traitRef - Trait reference to extract config from\n * @returns {TraitConfig | undefined} Trait configuration or undefined\n *\n * @example\n * getTraitConfig('MyTrait'); // returns undefined\n * getTraitConfig({ name: 'MyTrait' }); // returns undefined\n * getTraitConfig({ ref: 'MyTrait', config: { option: 'value' } }); // returns config object\n */\nexport function getTraitConfig(traitRef: TraitRef): CallSiteConfig | undefined {\n if (typeof traitRef === 'string') {\n return undefined;\n }\n if (isInlineTrait(traitRef)) {\n return undefined; // Inline traits don't have config\n }\n return traitRef.config;\n}\n\n/**\n * Normalizes a trait reference to object form.\n * \n * Converts any trait reference format (string, inline, object) to a\n * standardized object format with 'ref' and optional 'config' properties.\n * \n * @param {TraitRef} traitRef - Trait reference to normalize\n * @returns {{ ref: string; config?: TraitConfig }} Normalized trait reference\n *\n * @example\n * normalizeTraitRef('MyTrait'); // returns { ref: 'MyTrait' }\n * normalizeTraitRef({ name: 'MyTrait' }); // returns { ref: 'MyTrait' }\n * normalizeTraitRef({ ref: 'MyTrait', config: {...} }); // returns original\n */\nexport function normalizeTraitRef(traitRef: TraitRef): { ref: string; config?: CallSiteConfig } {\n if (typeof traitRef === 'string') {\n return { ref: traitRef };\n }\n if (isInlineTrait(traitRef)) {\n return { ref: traitRef.name };\n }\n return traitRef;\n}\n\n// ============================================================================\n// Type exports\n// ============================================================================\n\nexport type TraitInput = z.input<typeof TraitSchema>;\nexport type TraitReferenceInput = z.input<typeof TraitReferenceSchema>;\n\n// Backward compatibility aliases\nexport type OrbitalTraitRef = TraitRef;\nexport const OrbitalTraitRefSchema = TraitRefSchema;\n","/**\n * Page Types for Orbital Units\n *\n * Defines OrbitalPage type for pages within an Orbital Unit.\n *\n * IMPORTANT: Trait-driven UI architecture requires pages to have traits.\n * Static sections are NO LONGER SUPPORTED.\n *\n * @packageDocumentation\n */\n\nimport { z } from 'zod';\nimport { TraitConfigSchema, type TraitConfig } from './trait.js';\n\n// ============================================================================\n// View Type\n// ============================================================================\n\n/**\n * Page view types.\n * Note: viewType may be deprecated in favor of trait-driven UI.\n */\nexport type ViewType = 'list' | 'detail' | 'create' | 'edit' | 'dashboard' | 'custom';\n\nexport const ViewTypeSchema = z.enum([\n 'list',\n 'detail',\n 'create',\n 'edit',\n 'dashboard',\n 'custom',\n]);\n\n// ============================================================================\n// Trait Reference\n// ============================================================================\n\n/**\n * Trait reference on a page.\n */\nexport interface PageTraitRef {\n /** Trait name from library */\n ref: string;\n /** Entity this trait operates on */\n linkedEntity?: string;\n /** Additional trait configuration */\n config?: TraitConfig;\n}\n\nexport const PageTraitRefSchema = z.object({\n ref: z.string().min(1, 'Trait ref is required'),\n linkedEntity: z.string().optional(),\n config: TraitConfigSchema.optional(),\n});\n\n// ============================================================================\n// Orbital Page\n// ============================================================================\n\n/**\n * OrbitalPage - a page definition within an Orbital Unit.\n *\n * TRAIT-DRIVEN: Pages must have traits array. Sections are NOT supported.\n */\nexport interface OrbitalPage {\n /** Page name (PascalCase, e.g., \"TasksPage\") */\n name: string;\n\n /** URL path (e.g., \"/tasks\", \"/tasks/:id\") */\n path: string;\n\n /** View type (optional in trait-driven mode) */\n viewType?: ViewType;\n\n /** Page title (optional, defaults to derived from name) */\n title?: string;\n\n /** Primary entity for this page */\n primaryEntity?: string;\n\n /**\n * Traits that drive UI for this page.\n * REQUIRED in trait-driven architecture.\n */\n traits?: PageTraitRef[];\n\n /** Is this the initial page for navigation? */\n isInitial?: boolean;\n}\n\n/**\n * Strict Zod schema for trait-driven pages.\n * Rejects unknown properties like 'sections'.\n */\nexport const OrbitalPageStrictSchema = z.object({\n name: z.string().min(1, 'Page name is required'),\n path: z.string().min(1, 'Page path is required').startsWith('/', 'Path must start with /'),\n primaryEntity: z.string().min(1, 'Primary entity is required'),\n traits: z.array(PageTraitRefSchema).min(1, 'Page must have at least one trait'),\n title: z.string().optional(),\n}).strict(); // Reject unknown keys like 'sections'\n\n/**\n * Zod schema for OrbitalPage.\n * Trait-driven: pages have traits instead of static sections/patterns.\n * Uses .strict() to reject unknown keys like 'sections'.\n */\nexport const OrbitalPageSchema = z.object({\n name: z.string().min(1, 'Page name is required'),\n path: z.string().min(1, 'Page path is required').startsWith('/', 'Path must start with /'),\n viewType: ViewTypeSchema.optional(),\n title: z.string().optional(),\n primaryEntity: z.string().optional(),\n traits: z.array(PageTraitRefSchema).optional(),\n isInitial: z.boolean().optional(),\n}).strict(); // Reject unknown keys like 'sections' - use traits with render_ui effects\n\nexport type OrbitalPageInput = z.input<typeof OrbitalPageSchema>;\nexport type OrbitalPageStrictInput = z.input<typeof OrbitalPageStrictSchema>;\n\n// ============================================================================\n// Type Aliases (for cleaner imports)\n// ============================================================================\n\n/** Alias for OrbitalPage - preferred name */\nexport type Page = OrbitalPage;\n\n/** Alias for OrbitalPageSchema - preferred name */\nexport const PageSchema = OrbitalPageSchema;\n","/**\n * Domain Context Types (Self-Contained)\n *\n * Defines domain classification types for applications.\n * Copied from schema/domain-context.ts to make orbitals/ self-contained.\n *\n * @packageDocumentation\n */\n\nimport { z } from \"zod\";\n\n// ============================================================================\n// Domain Categories\n// ============================================================================\n\n/**\n * High-level domain categories\n */\nexport type DomainCategory =\n | \"healthcare\"\n | \"education\"\n | \"finance\"\n | \"ecommerce\"\n | \"real-estate\"\n | \"logistics\"\n | \"hospitality\"\n | \"hr-management\"\n | \"project-management\"\n | \"social\"\n | \"content-management\"\n | \"iot\"\n | \"analytics\"\n | \"game\"\n | \"custom\";\n\nexport const DomainCategorySchema = z.enum([\n \"healthcare\",\n \"education\",\n \"finance\",\n \"ecommerce\",\n \"real-estate\",\n \"logistics\",\n \"hospitality\",\n \"hr-management\",\n \"project-management\",\n \"social\",\n \"content-management\",\n \"iot\",\n \"analytics\",\n \"game\",\n \"custom\",\n]);\n\n// ============================================================================\n// Agent Domain Categories (simplified for LLM-based tools)\n// ============================================================================\n\n/**\n * Simplified domain categories used by the agent tools for application classification.\n * All agent tools and skill generators should derive from this constant.\n */\nexport const AGENT_DOMAIN_CATEGORIES = [\n \"game\",\n \"business\",\n \"dashboard\",\n \"form\",\n \"content\",\n \"social\",\n \"ecommerce\",\n \"workflow\",\n] as const;\n\nexport type AgentDomainCategory = (typeof AGENT_DOMAIN_CATEGORIES)[number];\n\nexport const AgentDomainCategorySchema = z.enum([...AGENT_DOMAIN_CATEGORIES]);\n\n// ============================================================================\n// Game Sub-Categories\n// ============================================================================\n\n/**\n * Game genre sub-categories\n */\nexport type GameSubCategory =\n | \"platformer\"\n | \"shooter\"\n | \"puzzle\"\n | \"rpg\"\n | \"board\"\n | \"racing\"\n | \"fighting\"\n | \"tower-defense\"\n | \"endless-runner\"\n | \"simulation\"\n | \"arcade\"\n | \"adventure\";\n\nexport const GameSubCategorySchema = z.enum([\n \"platformer\",\n \"shooter\",\n \"puzzle\",\n \"rpg\",\n \"board\",\n \"racing\",\n \"fighting\",\n \"tower-defense\",\n \"endless-runner\",\n \"simulation\",\n \"arcade\",\n \"adventure\",\n]);\n\n// ============================================================================\n// Node Classification\n// ============================================================================\n\n/**\n * Domain vs System classification\n */\nexport type NodeClassification = \"domain\" | \"system\";\n\nexport const NodeClassificationSchema = z.enum([\"domain\", \"system\"]);\n\n// ============================================================================\n// Semantic Roles\n// ============================================================================\n\nexport type StateSemanticRole =\n | \"pending\"\n | \"active\"\n | \"completed\"\n | \"cancelled\"\n | \"error\"\n | \"suspended\"\n | \"blocked\"\n | \"domain_workflow\"\n | \"domain_status\"\n | \"system_loading\"\n | \"system_error\"\n | \"system_idle\"\n | \"system_editing\"\n | \"system_confirming\";\n\nexport const StateSemanticRoleSchema = z.enum([\n \"pending\",\n \"active\",\n \"completed\",\n \"cancelled\",\n \"error\",\n \"suspended\",\n \"blocked\",\n \"domain_workflow\",\n \"domain_status\",\n \"system_loading\",\n \"system_error\",\n \"system_idle\",\n \"system_editing\",\n \"system_confirming\",\n]);\n\nexport type EventSemanticRole =\n | \"domain_action\"\n | \"domain_trigger\"\n | \"system_crud\"\n | \"system_navigation\"\n | \"system_form\"\n | \"system_ui\";\n\nexport const EventSemanticRoleSchema = z.enum([\n \"domain_action\",\n \"domain_trigger\",\n \"system_crud\",\n \"system_navigation\",\n \"system_form\",\n \"system_ui\",\n]);\n\nexport type EntitySemanticRole =\n | \"domain_core\"\n | \"domain_supporting\"\n | \"domain_reference\"\n | \"system_user\"\n | \"system_config\"\n | \"system_audit\";\n\nexport const EntitySemanticRoleSchema = z.enum([\n \"domain_core\",\n \"domain_supporting\",\n \"domain_reference\",\n \"system_user\",\n \"system_config\",\n \"system_audit\",\n]);\n\n// ============================================================================\n// Domain Vocabulary\n// ============================================================================\n\n/**\n * Domain-specific vocabulary for naming conventions.\n * Maps generic terms to domain-appropriate labels.\n */\nexport interface DomainVocabulary {\n /** Label for items (e.g., \"Task\", \"Cargo\", \"Patient\") */\n item?: string;\n /** Label for collections (e.g., \"Tasks\", \"Inventory\", \"Patients\") */\n collection?: string;\n /** Label for create action (e.g., \"Add\", \"Recruit\", \"Admit\") */\n create?: string;\n /** Label for delete action (e.g., \"Remove\", \"Discharge\", \"Archive\") */\n delete?: string;\n /** Label for container (e.g., \"List\", \"Hold\", \"Ward\") */\n container?: string;\n /** Additional custom vocabulary */\n [key: string]: string | undefined;\n}\n\nexport const DomainVocabularySchema = z\n .record(z.string(), z.string())\n .optional();\n\n// ============================================================================\n// Domain Context (Simplified for Design System)\n// ============================================================================\n\n/**\n * User persona for UX decisions\n */\nexport interface UserPersona {\n /** Persona name */\n name: string;\n /** Role for RBAC */\n role?: string;\n /** Primary device */\n device?: \"mobile\" | \"tablet\" | \"desktop\";\n}\n\nexport const UserPersonaSchema = z.object({\n name: z.string().min(1),\n role: z.string().optional(),\n device: z.enum([\"mobile\", \"tablet\", \"desktop\"]).optional(),\n});\n\n/**\n * Domain context - user request + classification\n */\nexport interface DomainContext {\n /** Original user request - verbatim (typically at schema level) */\n request: string;\n /**\n * The verbatim excerpt or summary of the user request that produced THIS orbital.\n *\n * Purpose: Traceability - know exactly what the user asked for that led to this orbital.\n *\n * Can be:\n * - Exact quote: \"...with a calendar that syncs with Google Calendar...\"\n * - Summarized: \"Calendar integration with Google Calendar sync\"\n *\n * Examples:\n * - Request: \"Build a project management app with tasks, team collaboration, and Gantt charts\"\n * - Task orbital: requestFragment: \"tasks\"\n * - Team orbital: requestFragment: \"team collaboration\"\n * - Timeline orbital: requestFragment: \"Gantt charts\"\n *\n * This enables:\n * - Understanding WHY this orbital exists\n * - Regenerating with original context preserved\n * - Validating the orbital matches user intent\n */\n requestFragment?: string;\n /** Domain category */\n category: AgentDomainCategory;\n /** Sub-domain for more specific classification */\n subDomain?: string;\n /** User personas */\n personas?: UserPersona[];\n /** Domain-specific vocabulary for naming */\n vocabulary?: DomainVocabulary;\n}\n\nexport const DomainContextSchema = z.object({\n request: z.string().min(1, \"Original request is required\"),\n requestFragment: z.string().optional(),\n category: AgentDomainCategorySchema,\n subDomain: z.string().optional(),\n personas: z.array(UserPersonaSchema).optional(),\n vocabulary: DomainVocabularySchema.optional(),\n});\n\n// ============================================================================\n// UX Hints\n// ============================================================================\n\n/**\n * UX hints for guiding UI generation.\n * These inform pattern selection and layout decisions.\n */\n/**\n * UX hints for guiding UI generation.\n * These inform pattern selection and layout decisions.\n *\n * Note: These are HINTS, not strict requirements. LLMs may use any string value\n * including 'dashboard-grid', 'none', etc. The subagent generator interprets these\n * flexibly to produce appropriate render-ui effects.\n */\nexport interface UXHints {\n /** Overall user flow pattern (e.g., 'hub-spoke', 'crud-cycle', 'linear') */\n flowPattern?: string;\n /** Pattern for displaying lists (e.g., 'entity-table', 'entity-cards', 'dashboard-grid', 'none') */\n listPattern?: string;\n /** Pattern for create/edit forms (e.g., 'modal', 'drawer', 'page', 'none') */\n formPattern?: string;\n /** Pattern for entity detail views (e.g., 'drawer', 'page', 'split', 'none') */\n detailPattern?: string;\n /** Cross-orbital navigation links */\n relatedLinks?: RelatedLink[];\n}\n\n// UX hints use flexible string types - they are guidance, not strict validation\nexport const UXHintsSchema = z.object({\n flowPattern: z.string().optional(),\n listPattern: z.string().optional(),\n formPattern: z.string().optional(),\n detailPattern: z.string().optional(),\n relatedLinks: z.array(z.lazy(() => RelatedLinkSchema)).optional(),\n});\n\n/**\n * Related link for cross-orbital navigation.\n */\nexport interface RelatedLink {\n /** Field name of the relation (e.g., \"customerId\") */\n relation: string;\n /** Button/link text (e.g., \"View Customer\") */\n label: string;\n /** Target view type */\n targetView?: \"list\" | \"detail\";\n}\n\nexport const RelatedLinkSchema = z.object({\n relation: z.string().min(1),\n label: z.string().min(1),\n targetView: z.enum([\"list\", \"detail\"]).optional(),\n});\n\n// ============================================================================\n// Suggested Guards (Pre-Generation)\n// ============================================================================\n\n/**\n * Suggested guard - natural language description for decomposition phase.\n * Generator converts these to S-expressions during generation.\n */\nexport interface SuggestedGuard {\n /** Unique identifier */\n id: string;\n /** Natural language description (e.g., \"Weight must be under 1000kg\") */\n description: string;\n /** Events this guard applies to (e.g., [\"Cargo.CREATE\", \"Cargo.UPDATE\"]) */\n appliesTo: string[];\n}\n\nexport const SuggestedGuardSchema = z.object({\n id: z.string().min(1),\n description: z.string().min(1),\n appliesTo: z.array(z.string().min(1)),\n});\n\n// ============================================================================\n// Design Preferences\n// ============================================================================\n\n/**\n * Design preferences for visual styling\n */\nexport interface DesignPreferences {\n /** Design style */\n style?: \"minimal\" | \"modern\" | \"playful\" | \"data-driven\" | \"immersive\";\n /** Primary color (hex) */\n primaryColor?: string;\n /** Target device */\n device?: \"mobile\" | \"tablet\" | \"desktop\" | \"all\";\n /** Dark mode */\n darkMode?: boolean;\n /** UX hints for pattern selection */\n uxHints?: UXHints;\n}\n\nexport const DesignPreferencesSchema = z.object({\n style: z\n .enum([\"minimal\", \"modern\", \"playful\", \"data-driven\", \"immersive\"])\n .optional(),\n primaryColor: z\n .string()\n .regex(/^#[0-9A-Fa-f]{6}$/, \"Must be valid hex color\")\n .optional(),\n device: z.enum([\"mobile\", \"tablet\", \"desktop\", \"all\"]).optional(),\n darkMode: z.boolean().optional(),\n uxHints: UXHintsSchema.optional(),\n});\n\n// ============================================================================\n// Theme Definition — Skin axes (Layer 1 visual variation, see docs/Almadar_Std_Variations.md)\n// ============================================================================\n\n/** Spacing scale entry — each step pairs with a CSS `--space-N` variable */\nexport interface SpacingScale {\n space0?: string;\n space1?: string;\n space2?: string;\n space3?: string;\n space4?: string;\n space5?: string;\n space6?: string;\n space7?: string;\n space8?: string;\n space9?: string;\n space10?: string;\n space11?: string;\n space12?: string;\n}\n\nexport const SpacingScaleSchema = z.object({\n space0: z.string().optional(),\n space1: z.string().optional(),\n space2: z.string().optional(),\n space3: z.string().optional(),\n space4: z.string().optional(),\n space5: z.string().optional(),\n space6: z.string().optional(),\n space7: z.string().optional(),\n space8: z.string().optional(),\n space9: z.string().optional(),\n space10: z.string().optional(),\n space11: z.string().optional(),\n space12: z.string().optional(),\n});\n\n/**\n * Density axis — spacing rhythm + per-element heights and paddings.\n * Determines whether a UI feels compact (Linear), cozy (default), or spacious (Notion).\n */\nexport interface DensityTokens {\n spacing?: SpacingScale;\n buttonHeightSm?: string;\n buttonHeightMd?: string;\n buttonHeightLg?: string;\n inputHeightSm?: string;\n inputHeightMd?: string;\n inputHeightLg?: string;\n rowHeightCompact?: string;\n rowHeightNormal?: string;\n rowHeightSpacious?: string;\n cardPaddingSm?: string;\n cardPaddingMd?: string;\n cardPaddingLg?: string;\n dialogPadding?: string;\n sectionGap?: string;\n}\n\nexport const DensityTokensSchema = z.object({\n spacing: SpacingScaleSchema.optional(),\n buttonHeightSm: z.string().optional(),\n buttonHeightMd: z.string().optional(),\n buttonHeightLg: z.string().optional(),\n inputHeightSm: z.string().optional(),\n inputHeightMd: z.string().optional(),\n inputHeightLg: z.string().optional(),\n rowHeightCompact: z.string().optional(),\n rowHeightNormal: z.string().optional(),\n rowHeightSpacious: z.string().optional(),\n cardPaddingSm: z.string().optional(),\n cardPaddingMd: z.string().optional(),\n cardPaddingLg: z.string().optional(),\n dialogPadding: z.string().optional(),\n sectionGap: z.string().optional(),\n});\n\n/** Single entry in the type scale — size + matching line-height */\nexport interface TypeScaleEntry {\n size: string;\n lineHeight: string;\n}\n\nexport const TypeScaleEntrySchema = z.object({\n size: z.string(),\n lineHeight: z.string(),\n});\n\n/** Type slot (which family the intent renders in) */\nexport type TypeSlot = \"display\" | \"body\" | \"mono\";\n\nexport const TypeSlotSchema = z.enum([\"display\", \"body\", \"mono\"]);\n\n/** Type size key from the scale */\nexport type TypeSizeKey =\n | \"xs\"\n | \"sm\"\n | \"base\"\n | \"lg\"\n | \"xl\"\n | \"2xl\"\n | \"3xl\"\n | \"4xl\"\n | \"display-1\"\n | \"display-2\";\n\nexport const TypeSizeKeySchema = z.enum([\n \"xs\",\n \"sm\",\n \"base\",\n \"lg\",\n \"xl\",\n \"2xl\",\n \"3xl\",\n \"4xl\",\n \"display-1\",\n \"display-2\",\n]);\n\n/** Type weight key */\nexport type TypeWeight = \"normal\" | \"medium\" | \"bold\";\n\nexport const TypeWeightSchema = z.enum([\"normal\", \"medium\", \"bold\"]);\n\n/** Intent → (slot, size, weight) mapping. Authors write intent in render-ui; skin resolves. */\nexport interface TypeIntent {\n slot: TypeSlot;\n size: TypeSizeKey;\n weight: TypeWeight;\n}\n\nexport const TypeIntentSchema = z.object({\n slot: TypeSlotSchema,\n size: TypeSizeKeySchema,\n weight: TypeWeightSchema,\n});\n\nexport interface TypeScale {\n xs?: TypeScaleEntry;\n sm?: TypeScaleEntry;\n base?: TypeScaleEntry;\n lg?: TypeScaleEntry;\n xl?: TypeScaleEntry;\n \"2xl\"?: TypeScaleEntry;\n \"3xl\"?: TypeScaleEntry;\n \"4xl\"?: TypeScaleEntry;\n \"display-1\"?: TypeScaleEntry;\n \"display-2\"?: TypeScaleEntry;\n}\n\nexport const TypeScaleSchema = z.object({\n xs: TypeScaleEntrySchema.optional(),\n sm: TypeScaleEntrySchema.optional(),\n base: TypeScaleEntrySchema.optional(),\n lg: TypeScaleEntrySchema.optional(),\n xl: TypeScaleEntrySchema.optional(),\n \"2xl\": TypeScaleEntrySchema.optional(),\n \"3xl\": TypeScaleEntrySchema.optional(),\n \"4xl\": TypeScaleEntrySchema.optional(),\n \"display-1\": TypeScaleEntrySchema.optional(),\n \"display-2\": TypeScaleEntrySchema.optional(),\n});\n\nexport interface TypeIntentMap {\n headingMajor?: TypeIntent;\n headingMinor?: TypeIntent;\n bodyEmphasis?: TypeIntent;\n bodyDefault?: TypeIntent;\n bodyQuiet?: TypeIntent;\n caption?: TypeIntent;\n numeric?: TypeIntent;\n}\n\nexport const TypeIntentMapSchema = z.object({\n headingMajor: TypeIntentSchema.optional(),\n headingMinor: TypeIntentSchema.optional(),\n bodyEmphasis: TypeIntentSchema.optional(),\n bodyDefault: TypeIntentSchema.optional(),\n bodyQuiet: TypeIntentSchema.optional(),\n caption: TypeIntentSchema.optional(),\n numeric: TypeIntentSchema.optional(),\n});\n\n/**\n * Type axis — family triplet, size scale, and intent mapping.\n * Determines whether a UI reads as editorial (serif display + sans body),\n * tech (sans + mono numeric), or dense (mono everywhere, tight leading).\n */\nexport interface TypeScaleTokens {\n displayFamily?: string;\n bodyFamily?: string;\n monoFamily?: string;\n scale?: TypeScale;\n intents?: TypeIntentMap;\n}\n\nexport const TypeScaleTokensSchema = z.object({\n displayFamily: z.string().optional(),\n bodyFamily: z.string().optional(),\n monoFamily: z.string().optional(),\n scale: TypeScaleSchema.optional(),\n intents: TypeIntentMapSchema.optional(),\n});\n\n/** Duration palette key */\nexport type MotionDurationKey =\n | \"instant\"\n | \"fast\"\n | \"normal\"\n | \"slow\"\n | \"dramatic\";\n\nexport const MotionDurationKeySchema = z.enum([\n \"instant\",\n \"fast\",\n \"normal\",\n \"slow\",\n \"dramatic\",\n]);\n\n/** Easing palette key */\nexport type MotionEasingKey = \"linear\" | \"standard\" | \"emphasized\" | \"spring\";\n\nexport const MotionEasingKeySchema = z.enum([\n \"linear\",\n \"standard\",\n \"emphasized\",\n \"spring\",\n]);\n\n/** Per-intent motion specification (duration + easing) */\nexport interface MotionIntent {\n duration: MotionDurationKey;\n easing: MotionEasingKey;\n}\n\nexport const MotionIntentSchema = z.object({\n duration: MotionDurationKeySchema,\n easing: MotionEasingKeySchema,\n});\n\nexport interface MotionDurationPalette {\n instant?: string;\n fast?: string;\n normal?: string;\n slow?: string;\n dramatic?: string;\n}\n\nexport const MotionDurationPaletteSchema = z.object({\n instant: z.string().optional(),\n fast: z.string().optional(),\n normal: z.string().optional(),\n slow: z.string().optional(),\n dramatic: z.string().optional(),\n});\n\nexport interface MotionEasingPalette {\n linear?: string;\n standard?: string;\n emphasized?: string;\n spring?: string;\n}\n\nexport const MotionEasingPaletteSchema = z.object({\n linear: z.string().optional(),\n standard: z.string().optional(),\n emphasized: z.string().optional(),\n spring: z.string().optional(),\n});\n\nexport interface MotionIntentMap {\n enter?: MotionIntent;\n exit?: MotionIntent;\n hover?: MotionIntent;\n press?: MotionIntent;\n expand?: MotionIntent;\n transition?: MotionIntent;\n}\n\nexport const MotionIntentMapSchema = z.object({\n enter: MotionIntentSchema.optional(),\n exit: MotionIntentSchema.optional(),\n hover: MotionIntentSchema.optional(),\n press: MotionIntentSchema.optional(),\n expand: MotionIntentSchema.optional(),\n transition: MotionIntentSchema.optional(),\n});\n\n/**\n * Motion axis — duration palette + easing palette + per-intent mapping.\n * Mechanical (linear, fast) vs organic (cubic-bezier, medium) vs dramatic (spring, slow).\n */\nexport interface MotionTokens {\n durations?: MotionDurationPalette;\n easings?: MotionEasingPalette;\n intents?: MotionIntentMap;\n}\n\nexport const MotionTokensSchema = z.object({\n durations: MotionDurationPaletteSchema.optional(),\n easings: MotionEasingPaletteSchema.optional(),\n intents: MotionIntentMapSchema.optional(),\n});\n\n/** Icon family selector */\nexport type IconFamily =\n | \"lucide\"\n | \"phosphor-outline\"\n | \"phosphor-fill\"\n | \"phosphor-duotone\"\n | \"tabler\"\n | \"fa-solid\";\n\nexport const IconFamilySchema = z.enum([\n \"lucide\",\n \"phosphor-outline\",\n \"phosphor-fill\",\n \"phosphor-duotone\",\n \"tabler\",\n \"fa-solid\",\n]);\n\n/**\n * Iconography axis — icon set + stroke + default size.\n * Outline (Lucide) vs filled (Phosphor-fill) vs duotone (Phosphor-duotone).\n */\nexport interface IconographyTokens {\n family?: IconFamily;\n strokeWidth?: string;\n defaultSize?: string;\n}\n\nexport const IconographyTokensSchema = z.object({\n family: IconFamilySchema.optional(),\n strokeWidth: z.string().optional(),\n defaultSize: z.string().optional(),\n});\n\n/**\n * Elevation axis — per-layer shadow mapping.\n * Each value references a `--shadow-*` token or a raw CSS shadow value.\n */\nexport interface ElevationTokens {\n cardElevation?: string;\n popoverElevation?: string;\n dialogElevation?: string;\n toastElevation?: string;\n}\n\nexport const ElevationTokensSchema = z.object({\n cardElevation: z.string().optional(),\n popoverElevation: z.string().optional(),\n dialogElevation: z.string().optional(),\n toastElevation: z.string().optional(),\n});\n\n/**\n * Geometry axis — radius rhythm + border-width rhythm with intent.\n * Sharp (radius 0) vs soft (radius 8/12) vs pill (radius full on interactive).\n */\nexport interface GeometryTokens {\n radiusContainer?: string;\n radiusInteractive?: string;\n radiusPill?: string;\n borderHairline?: string;\n borderStandard?: string;\n borderHeavy?: string;\n}\n\nexport const GeometryTokensSchema = z.object({\n radiusContainer: z.string().optional(),\n radiusInteractive: z.string().optional(),\n radiusPill: z.string().optional(),\n borderHairline: z.string().optional(),\n borderStandard: z.string().optional(),\n borderHeavy: z.string().optional(),\n});\n\n/**\n * Color axis — semantic + surface + feedback color tokens as a typed bundle.\n *\n * Replaces the free-form `colors: Record<string, string>` on `ThemeTokens` for\n * authors targeting the typed SkinSpec entrypoint. Every field maps 1:1 to a\n * `--color-*` CSS custom property emitted by themes. All fields are optional\n * so a partial slice can layer onto a default (light/dark mode pair, etc.).\n */\nexport interface ColorTokens {\n /* Brand / accent */\n primary?: string;\n primaryHover?: string;\n primaryForeground?: string;\n secondary?: string;\n secondaryHover?: string;\n secondaryForeground?: string;\n accent?: string;\n accentForeground?: string;\n muted?: string;\n mutedForeground?: string;\n\n /* Surface palette */\n background?: string;\n foreground?: string;\n card?: string;\n cardForeground?: string;\n surface?: string;\n border?: string;\n input?: string;\n ring?: string;\n\n /* Feedback */\n error?: string;\n errorForeground?: string;\n success?: string;\n successForeground?: string;\n warning?: string;\n warningForeground?: string;\n info?: string;\n infoForeground?: string;\n\n /* Optional table-specific (themes that ship them; default to neutrals) */\n tableHeader?: string;\n tableBorder?: string;\n tableRowHover?: string;\n surfaceHover?: string;\n borderHover?: string;\n placeholder?: string;\n}\n\nexport const ColorTokensSchema = z.object({\n primary: z.string().optional(),\n primaryHover: z.string().optional(),\n primaryForeground: z.string().optional(),\n secondary: z.string().optional(),\n secondaryHover: z.string().optional(),\n secondaryForeground: z.string().optional(),\n accent: z.string().optional(),\n accentForeground: z.string().optional(),\n muted: z.string().optional(),\n mutedForeground: z.string().optional(),\n background: z.string().optional(),\n foreground: z.string().optional(),\n card: z.string().optional(),\n cardForeground: z.string().optional(),\n surface: z.string().optional(),\n border: z.string().optional(),\n input: z.string().optional(),\n ring: z.string().optional(),\n error: z.string().optional(),\n errorForeground: z.string().optional(),\n success: z.string().optional(),\n successForeground: z.string().optional(),\n warning: z.string().optional(),\n warningForeground: z.string().optional(),\n info: z.string().optional(),\n infoForeground: z.string().optional(),\n tableHeader: z.string().optional(),\n tableBorder: z.string().optional(),\n tableRowHover: z.string().optional(),\n surfaceHover: z.string().optional(),\n borderHover: z.string().optional(),\n placeholder: z.string().optional(),\n});\n\n/**\n * Illustration style preset for empty/loading/error/onboarding states.\n *\n * - `minimal`: icon + short text, no imagery (current default)\n * - `illustrated`: svg illustration library (undraw-style)\n * - `photo`: stock photography\n * - `text-only`: clean text, no imagery\n * - `mascot`: branded character (Mailchimp-style)\n */\nexport type IllustrationStyle =\n | \"minimal\"\n | \"illustrated\"\n | \"photo\"\n | \"text-only\"\n | \"mascot\";\n\nexport const IllustrationStyleSchema = z.enum([\n \"minimal\",\n \"illustrated\",\n \"photo\",\n \"text-only\",\n \"mascot\",\n]);\n\n/**\n * Illustration axis — empty/loading/error/onboarding imagery style.\n * `style` selects the preset; the per-state `*Asset` fields are optional\n * overrides for skins that want to ship custom artwork.\n */\nexport interface IllustrationTokens {\n style?: IllustrationStyle;\n emptyAsset?: string;\n loadingAsset?: string;\n errorAsset?: string;\n onboardingAsset?: string;\n}\n\nexport const IllustrationTokensSchema = z.object({\n style: IllustrationStyleSchema.optional(),\n emptyAsset: z.string().optional(),\n loadingAsset: z.string().optional(),\n errorAsset: z.string().optional(),\n onboardingAsset: z.string().optional(),\n});\n\n/**\n * Theme tokens - CSS custom properties for design system.\n *\n * Layer 1 visual variation (see docs/Almadar_Std_Variations.md): the original\n * `colors`/`radii`/`spacing`/`typography`/`shadows` Record fields are kept for\n * backward compatibility. The new typed axes (`density`, `typeScale`, `motion`,\n * `iconography`, `elevation`, `geometry`) carry the structured token surface\n * that lets two themes feel like different products, not just different paint.\n */\nexport interface ThemeTokens {\n /**\n * Color axis — typed semantic + surface + feedback colors.\n * Replaces the free-form `colors` Record below for new authors.\n */\n color?: ColorTokens;\n /** Density axis — spacing rhythm, per-element heights and paddings */\n density?: DensityTokens;\n /** Type axis — family triplet, scale, intent mapping */\n typeScale?: TypeScaleTokens;\n /** Motion axis — duration palette, easing palette, intent mapping */\n motion?: MotionTokens;\n /** Iconography axis — icon family, stroke, default size */\n iconography?: IconographyTokens;\n /** Elevation axis — per-layer shadow mapping */\n elevation?: ElevationTokens;\n /** Geometry axis — radius rhythm, border-width rhythm with intent */\n geometry?: GeometryTokens;\n /** Illustration axis — empty/loading/error state imagery style */\n illustration?: IllustrationTokens;\n\n // ── Legacy free-form maps (pre-Layer-1). Kept for back-compat with\n // older callers that emit raw `--color-*` / `--radius-*` etc. as\n // string maps. New authors should use the typed axes above.\n /** @deprecated Use `color` (typed). */\n colors?: Record<string, string>;\n /** @deprecated Use `geometry.radius*` and theme CSS for full radius scale. */\n radii?: Record<string, string>;\n /** @deprecated Use `density.spacing` (typed scale). */\n spacing?: Record<string, string>;\n /** @deprecated Use `typeScale` (typed family + scale + intents). */\n typography?: Record<string, string>;\n /** @deprecated Use `elevation` (typed per-layer mapping). */\n shadows?: Record<string, string>;\n}\n\nexport const ThemeTokensSchema = z.object({\n color: ColorTokensSchema.optional(),\n density: DensityTokensSchema.optional(),\n typeScale: TypeScaleTokensSchema.optional(),\n motion: MotionTokensSchema.optional(),\n iconography: IconographyTokensSchema.optional(),\n elevation: ElevationTokensSchema.optional(),\n geometry: GeometryTokensSchema.optional(),\n illustration: IllustrationTokensSchema.optional(),\n // Legacy\n colors: z.record(z.string(), z.string()).optional(),\n radii: z.record(z.string(), z.string()).optional(),\n spacing: z.record(z.string(), z.string()).optional(),\n typography: z.record(z.string(), z.string()).optional(),\n shadows: z.record(z.string(), z.string()).optional(),\n});\n\n/**\n * Theme variant - overrides for a specific mode (e.g., dark mode).\n * Mirrors ThemeTokens fields with the same backward-compat + new-axis structure.\n */\nexport interface ThemeVariant {\n /** Color axis overrides */\n color?: ColorTokens;\n /** Density axis overrides */\n density?: DensityTokens;\n /** Type axis overrides */\n typeScale?: TypeScaleTokens;\n /** Motion axis overrides */\n motion?: MotionTokens;\n /** Iconography axis overrides */\n iconography?: IconographyTokens;\n /** Elevation axis overrides */\n elevation?: ElevationTokens;\n /** Geometry axis overrides */\n geometry?: GeometryTokens;\n /** Illustration axis overrides */\n illustration?: IllustrationTokens;\n\n // ── Legacy free-form maps (pre-Layer-1). See ThemeTokens for guidance.\n /** @deprecated Use `color`. */\n colors?: Record<string, string>;\n /** @deprecated */\n radii?: Record<string, string>;\n /** @deprecated */\n spacing?: Record<string, string>;\n /** @deprecated */\n typography?: Record<string, string>;\n /** @deprecated */\n shadows?: Record<string, string>;\n}\n\nexport const ThemeVariantSchema = z.object({\n color: ColorTokensSchema.optional(),\n density: DensityTokensSchema.optional(),\n typeScale: TypeScaleTokensSchema.optional(),\n motion: MotionTokensSchema.optional(),\n iconography: IconographyTokensSchema.optional(),\n elevation: ElevationTokensSchema.optional(),\n geometry: GeometryTokensSchema.optional(),\n illustration: IllustrationTokensSchema.optional(),\n colors: z.record(z.string(), z.string()).optional(),\n radii: z.record(z.string(), z.string()).optional(),\n spacing: z.record(z.string(), z.string()).optional(),\n typography: z.record(z.string(), z.string()).optional(),\n shadows: z.record(z.string(), z.string()).optional(),\n});\n\n/**\n * Theme definition - design system for an orbital.\n */\nexport interface ThemeDefinition {\n /** Theme name */\n name: string;\n /** Base tokens */\n tokens: ThemeTokens;\n /** Named variants (e.g., \"dark\", \"high-contrast\") */\n variants?: Record<string, ThemeVariant>;\n}\n\nexport const ThemeDefinitionSchema = z.object({\n name: z.string().min(1, \"Theme name is required\"),\n tokens: ThemeTokensSchema,\n variants: z.record(z.string(), ThemeVariantSchema).optional(),\n});\n\n/**\n * ThemeRef - Theme can be inline definition OR reference to imported theme.\n *\n * Reference format: \"Alias.theme\"\n */\nexport type ThemeRef = ThemeDefinition | string;\n\n/**\n * Checks if a theme reference is a string.\n * \n * Type guard to determine if a theme reference is a string reference\n * (format: \"Alias.theme\") rather than an inline theme definition.\n * \n * @param {ThemeRef} theme - Theme reference to check\n * @returns {boolean} True if theme is a string reference, false otherwise\n * \n * @example\n * isThemeReference(\"Ocean.theme\"); // returns true\n * isThemeReference({ name: \"ocean\", colors: {...} }); // returns false\n */\nexport function isThemeReference(theme: ThemeRef): theme is string {\n return typeof theme === \"string\";\n}\n\n/**\n * Validate theme reference format: \"Alias.theme\"\n */\nexport const ThemeRefStringSchema = z\n .string()\n .regex(\n /^[A-Z][a-zA-Z0-9]*\\.theme$/,\n 'Theme reference must be in format \"Alias.theme\" (e.g., \"Ocean.theme\")',\n );\n\nexport const ThemeRefSchema = z.union([\n ThemeDefinitionSchema,\n ThemeRefStringSchema,\n]);\n\n// ============================================================================\n// SkinSpec — Layer 1 visual variation vocabulary (docs/Almadar_Std_Variations.md §2.3)\n// ============================================================================\n\n/**\n * `SkinSpec` is an alias for `ThemeDefinition` — same object, doc-aligned\n * name. The doc refers to a complete eight-axis visual identity as a\n * \"SkinSpec\"; in the type system it's a `ThemeDefinition` whose `tokens`\n * field carries the eight typed slices (`color`, `density`, `typeScale`,\n * `geometry`, `elevation`, `motion`, `iconography`, `illustration`).\n *\n * There is no separate type — this alias prevents the two surfaces from\n * drifting.\n */\nexport type SkinSpec = ThemeDefinition;\nexport const SkinSpecSchema = ThemeDefinitionSchema;\n\n/**\n * Slice-name aliases — the doc and `_contract.md` refer to each axis as\n * `<Name>Slice`. The existing types use `<Name>Tokens`. These aliases let\n * skin authors write the doc's vocabulary while pointing at the single\n * canonical type definition. No forks.\n */\nexport type ColorSlice = ColorTokens;\nexport type DensitySlice = DensityTokens;\nexport type TypeSlice = TypeScaleTokens;\nexport type GeometrySlice = GeometryTokens;\nexport type ElevationSlice = ElevationTokens;\nexport type MotionSlice = MotionTokens;\nexport type IconographySlice = IconographyTokens;\nexport type IllustrationSlice = IllustrationTokens;\n\nexport const ColorSliceSchema = ColorTokensSchema;\nexport const DensitySliceSchema = DensityTokensSchema;\nexport const TypeSliceSchema = TypeScaleTokensSchema;\nexport const GeometrySliceSchema = GeometryTokensSchema;\nexport const ElevationSliceSchema = ElevationTokensSchema;\nexport const MotionSliceSchema = MotionTokensSchema;\nexport const IconographySliceSchema = IconographyTokensSchema;\nexport const IllustrationSliceSchema = IllustrationTokensSchema;\n\n// ============================================================================\n// Design Tokens (Legacy)\n// ============================================================================\n\n/**\n * Design tokens - reusable Tailwind class collections.\n * @deprecated Use ThemeDefinition instead for new code.\n *\n * Instead of repeating raw Tailwind classes everywhere, define once and reference by name.\n * Example: `token: \"surfaces.glass\"` resolves to the Tailwind classes defined here.\n */\nexport interface DesignTokens {\n /** Surface styles: backgrounds, borders, shadows */\n surfaces?: Record<string, string>;\n /** Text styles: typography, colors */\n text?: Record<string, string>;\n /** Interactive element styles: buttons, links */\n interactive?: Record<string, string>;\n /** Effect styles: shadows, animations, transitions */\n effects?: Record<string, string>;\n /** Additional custom categories */\n [category: string]: Record<string, string> | undefined;\n}\n\nexport const DesignTokensSchema = z\n .record(z.string(), z.record(z.string(), z.string()))\n .optional();\n\n// ============================================================================\n// Custom Pattern Definitions\n// ============================================================================\n\n/**\n * Allowed HTML elements for custom patterns.\n * These are safe, semantic elements for building custom UIs.\n */\nexport const ALLOWED_CUSTOM_COMPONENTS = [\n \"div\",\n \"span\",\n \"button\",\n \"a\",\n \"p\",\n \"h1\",\n \"h2\",\n \"h3\",\n \"h4\",\n \"h5\",\n \"h6\",\n \"header\",\n \"footer\",\n \"section\",\n \"article\",\n \"nav\",\n \"main\",\n \"aside\",\n \"ul\",\n \"ol\",\n \"li\",\n \"img\",\n \"label\",\n \"input\",\n \"form\",\n] as const;\n\nexport type AllowedCustomComponent = (typeof ALLOWED_CUSTOM_COMPONENTS)[number];\n\n/**\n * Custom pattern definition for app-specific reusable patterns.\n *\n * Register custom designs that can be referenced by name throughout the schema.\n */\nexport interface CustomPatternDefinition {\n /** Always 'custom' for custom patterns */\n type: \"custom\";\n /** HTML element to render */\n component: AllowedCustomComponent;\n /** Base Tailwind classes (can include {prop} placeholders) */\n className: string;\n /** Named content slots for nested content */\n slots?: string[];\n /** Configurable props that can be passed when using the pattern */\n props?: string[];\n}\n\nexport const CustomPatternDefinitionSchema = z.object({\n type: z.literal(\"custom\"),\n component: z.enum(ALLOWED_CUSTOM_COMPONENTS),\n className: z.string(),\n slots: z.array(z.string()).optional(),\n props: z.array(z.string()).optional(),\n});\n\n/**\n * Map of custom pattern names to their definitions.\n */\nexport type CustomPatternMap = Record<string, CustomPatternDefinition>;\n\nexport const CustomPatternMapSchema = z\n .record(z.string(), CustomPatternDefinitionSchema)\n .optional();\n\n// ============================================================================\n// Type exports\n// ============================================================================\n\nexport type DomainContextInput = z.input<typeof DomainContextSchema>;\nexport type DesignPreferencesInput = z.input<typeof DesignPreferencesSchema>;\nexport type UserPersonaInput = z.input<typeof UserPersonaSchema>;\nexport type DesignTokensInput = z.input<typeof DesignTokensSchema>;\nexport type CustomPatternDefinitionInput = z.input<\n typeof CustomPatternDefinitionSchema\n>;\nexport type CustomPatternMapInput = z.input<typeof CustomPatternMapSchema>;\n","/**\n * Service Types for Orbital Schema\n *\n * Defines external service integrations (REST APIs, WebSockets, MCP servers)\n * that can be used by orbital units via the `call_service` effect.\n *\n * @packageDocumentation\n */\n\nimport { z } from \"zod\";\n\n// ============================================================================\n// Service Type Enum\n// ============================================================================\n\n/**\n * Types of external services that can be integrated.\n */\nexport const SERVICE_TYPES = [\"rest\", \"socket\", \"mcp\"] as const;\n\nexport type ServiceType = (typeof SERVICE_TYPES)[number];\n\nexport const ServiceTypeSchema = z.enum(SERVICE_TYPES);\n\n// ============================================================================\n// REST Service Definition\n// ============================================================================\n\n/**\n * Configuration for a REST API service.\n *\n * @example\n * ```typescript\n * const weatherService: RestServiceDef = {\n * name: 'WeatherAPI',\n * type: 'rest',\n * baseUrl: 'https://api.openweathermap.org/data/2.5',\n * headers: {\n * 'Content-Type': 'application/json',\n * },\n * auth: {\n * type: 'api-key',\n * keyName: 'appid',\n * location: 'query',\n * },\n * };\n * ```\n */\nexport interface RestServiceDef {\n /** Unique service name (used in call_service effect) */\n name: string;\n\n /** Service type */\n type: \"rest\";\n\n /** Optional description */\n description?: string;\n\n /** Base URL for the API */\n baseUrl: string;\n\n /** Default headers to include in all requests */\n headers?: Record<string, string>;\n\n /** Authentication configuration */\n auth?: RestAuthConfig;\n\n /** Timeout in milliseconds (default: 30000) */\n timeout?: number;\n}\n\n/**\n * Authentication configuration for REST services.\n */\nexport interface RestAuthConfig {\n /** Authentication type */\n type: \"api-key\" | \"bearer\" | \"basic\" | \"oauth2\";\n\n /** For api-key: the query parameter or header name */\n keyName?: string;\n\n /** For api-key: where to place the key */\n location?: \"query\" | \"header\";\n\n /** Environment variable name containing the secret (for secure storage) */\n secretEnv?: string;\n}\n\nexport const RestAuthConfigSchema = z.object({\n type: z.enum([\"api-key\", \"bearer\", \"basic\", \"oauth2\"]),\n keyName: z.string().optional(),\n location: z.enum([\"query\", \"header\"]).optional(),\n secretEnv: z.string().optional(),\n});\n\nexport const RestServiceDefSchema = z.object({\n name: z.string().min(1, \"Service name is required\"),\n type: z.literal(\"rest\"),\n description: z.string().optional(),\n baseUrl: z.string().url(\"Base URL must be a valid URL\"),\n headers: z.record(z.string()).optional(),\n auth: RestAuthConfigSchema.optional(),\n timeout: z.number().positive().optional(),\n});\n\n// ============================================================================\n// Socket Service Definition\n// ============================================================================\n\n/**\n * Configuration for a WebSocket service.\n *\n * @example\n * ```typescript\n * const chatService: SocketServiceDef = {\n * name: 'ChatSocket',\n * type: 'socket',\n * url: 'wss://chat.example.com',\n * events: {\n * inbound: ['message_received', 'user_joined', 'user_left'],\n * outbound: ['send_message', 'join_room', 'leave_room'],\n * },\n * };\n * ```\n */\nexport interface SocketServiceDef {\n /** Unique service name */\n name: string;\n\n /** Service type */\n type: \"socket\";\n\n /** Optional description */\n description?: string;\n\n /** WebSocket URL */\n url: string;\n\n /** Event definitions */\n events: SocketEvents;\n\n /** Reconnection configuration */\n reconnect?: {\n /** Enable automatic reconnection */\n enabled: boolean;\n /** Maximum reconnection attempts */\n maxAttempts?: number;\n /** Delay between attempts in ms */\n delayMs?: number;\n };\n}\n\n/**\n * Socket event definitions.\n */\nexport interface SocketEvents {\n /** Events received from server (maps to orbital events) */\n inbound: string[];\n\n /** Events sent to server (triggered by effects) */\n outbound: string[];\n}\n\nexport const SocketEventsSchema = z.object({\n inbound: z.array(z.string()),\n outbound: z.array(z.string()),\n});\n\nexport const SocketServiceDefSchema = z.object({\n name: z.string().min(1, \"Service name is required\"),\n type: z.literal(\"socket\"),\n description: z.string().optional(),\n url: z.string().url(\"WebSocket URL must be valid\"),\n events: SocketEventsSchema,\n reconnect: z\n .object({\n enabled: z.boolean(),\n maxAttempts: z.number().positive().optional(),\n delayMs: z.number().positive().optional(),\n })\n .optional(),\n});\n\n// ============================================================================\n// MCP Service Definition\n// ============================================================================\n\n/**\n * Configuration for an MCP (Model Context Protocol) server.\n *\n * @example\n * ```typescript\n * const mcpService: McpServiceDef = {\n * name: 'DatabaseMCP',\n * type: 'mcp',\n * serverPath: './mcp-servers/database',\n * capabilities: ['query', 'insert', 'update'],\n * };\n * ```\n */\nexport interface McpServiceDef {\n /** Unique service name */\n name: string;\n\n /** Service type */\n type: \"mcp\";\n\n /** Optional description */\n description?: string;\n\n /** Path to MCP server executable or module */\n serverPath: string;\n\n /** List of capabilities/tools exposed by the MCP server */\n capabilities: string[];\n\n /** Environment variables to pass to the MCP server */\n env?: Record<string, string>;\n}\n\nexport const McpServiceDefSchema = z.object({\n name: z.string().min(1, \"Service name is required\"),\n type: z.literal(\"mcp\"),\n description: z.string().optional(),\n serverPath: z.string().min(1, \"Server path is required\"),\n capabilities: z\n .array(z.string())\n .min(1, \"At least one capability is required\"),\n env: z.record(z.string()).optional(),\n});\n\n// ============================================================================\n// Union Type: ServiceDefinition\n// ============================================================================\n\n/**\n * Union type for all service definitions.\n */\nexport type ServiceDefinition =\n | RestServiceDef\n | SocketServiceDef\n | McpServiceDef;\n\nexport const ServiceDefinitionSchema = z.discriminatedUnion(\"type\", [\n RestServiceDefSchema,\n SocketServiceDefSchema,\n McpServiceDefSchema,\n]);\n\n// ============================================================================\n// Service Reference (Inline OR Reference)\n// ============================================================================\n\n/**\n * ServiceRef - Service can be inline definition, reference object with overrides,\n * or bare string reference to an imported service.\n *\n * Reference format: \"Alias.services.ServiceName\"\n */\nexport type ServiceRef = ServiceDefinition | ServiceRefObject | string;\n\n/**\n * Phase F: Service reference object with override fields.\n *\n * Mirrors the Rust `ServiceRefObject` at\n * `orbital-rust/crates/orbital-core/src/schema/types.rs:353-375`. A caller\n * imports a service via `uses[]`, references it by `ref`, and supplies\n * any subset of these fields to override the imported service's defaults\n * during inlining.\n *\n * @example\n * ```typescript\n * const ref: ServiceRefObject = {\n * ref: \"Weather.services.openweather\",\n * baseUrl: \"https://staging.weather.example.com\",\n * headers: { \"X-Tenant\": \"acme\" },\n * };\n * ```\n */\nexport interface ServiceRefObject {\n /** Reference to imported service: \"Alias.services.ServiceName\" */\n ref: string;\n /** Override the service description */\n description?: string;\n /** Override the REST baseUrl */\n baseUrl?: string;\n /** Override or merge default headers (caller wins on key collision) */\n headers?: Record<string, string>;\n /** Override the WebSocket url */\n url?: string;\n /** Override the MCP server path */\n serverPath?: string;\n}\n\n/**\n * Checks if a service reference is a bare string reference.\n *\n * Type guard to determine if a service reference is a string reference\n * (format: \"Alias.services.ServiceName\") rather than an inline service\n * definition or a reference object.\n *\n * @param {ServiceRef} service - Service reference to check\n * @returns {boolean} True if service is a string reference, false otherwise\n *\n * @example\n * isServiceReference(\"Weather.services.openweather\"); // returns true\n * isServiceReference({ name: \"weather\", type: \"rest\" }); // returns false\n * isServiceReference({ ref: \"Weather.services.openweather\" }); // returns false\n */\nexport function isServiceReference(service: ServiceRef): service is string {\n return typeof service === \"string\";\n}\n\n/**\n * Phase F: Type guard for `ServiceRefObject` (the override-carrying form).\n *\n * @param {ServiceRef} service - Service reference to check\n * @returns {boolean} True if service is a ServiceRefObject\n */\nexport function isServiceReferenceObject(\n service: ServiceRef,\n): service is ServiceRefObject {\n return (\n typeof service === \"object\" &&\n service !== null &&\n \"ref\" in service &&\n !(\"type\" in service)\n );\n}\n\n/**\n * Validate service reference format: \"Alias.services.ServiceName\"\n */\nexport const ServiceRefStringSchema = z\n .string()\n .regex(\n /^[A-Z][a-zA-Z0-9]*\\.services\\.[a-zA-Z][a-zA-Z0-9]*$/,\n 'Service reference must be in format \"Alias.services.ServiceName\" (e.g., \"Weather.services.openweather\")',\n );\n\nexport const ServiceRefObjectSchema = z.object({\n ref: ServiceRefStringSchema,\n description: z.string().optional(),\n baseUrl: z.string().url(\"baseUrl override must be a valid URL\").optional(),\n headers: z.record(z.string()).optional(),\n url: z.string().url(\"url override must be a valid URL\").optional(),\n serverPath: z.string().optional(),\n});\n\nexport const ServiceRefSchema = z.union([\n ServiceDefinitionSchema,\n ServiceRefObjectSchema,\n ServiceRefStringSchema,\n]);\n\n/**\n * Parses a service reference into its components.\n * \n * Extracts the alias and service name from a service reference string\n * in format \"Alias.services.ServiceName\". Returns null if not a valid reference.\n * \n * @param {string} ref - Service reference string\n * @returns {{ alias: string; serviceName: string } | null} Parsed components or null\n * \n * @example\n * parseServiceRef(\"Weather.services.openweather\"); // returns { alias: \"Weather\", serviceName: \"openweather\" }\n * parseServiceRef(\"invalid\"); // returns null\n */\nexport function parseServiceRef(\n ref: string,\n): { alias: string; serviceName: string } | null {\n const match = ref.match(\n /^([A-Z][a-zA-Z0-9]*)\\.services\\.([a-zA-Z][a-zA-Z0-9]*)$/,\n );\n if (!match) return null;\n return { alias: match[1], serviceName: match[2] };\n}\n\n// ============================================================================\n// Utility Functions\n// ============================================================================\n\n/**\n * Checks if a service definition is a REST service.\n * \n * Type guard to determine if a service definition represents a REST API service.\n * Used for service type discrimination and validation.\n * \n * @param {ServiceDefinition} service - Service definition to check\n * @returns {boolean} True if service is a REST service, false otherwise\n * \n * @example\n * isRestService({ name: \"weather\", type: \"rest\", baseUrl: \"...\" }); // returns true\n * isRestService({ name: \"chat\", type: \"socket\" }); // returns false\n */\nexport function isRestService(\n service: ServiceDefinition,\n): service is RestServiceDef {\n return service.type === \"rest\";\n}\n\n/**\n * Checks if a service definition is a Socket service.\n * \n * Type guard to determine if a service definition represents a WebSocket service.\n * Used for service type discrimination and validation.\n * \n * @param {ServiceDefinition} service - Service definition to check\n * @returns {boolean} True if service is a Socket service, false otherwise\n * \n * @example\n * isSocketService({ name: \"chat\", type: \"socket\", url: \"wss://...\" }); // returns true\n * isSocketService({ name: \"weather\", type: \"rest\" }); // returns false\n */\nexport function isSocketService(\n service: ServiceDefinition,\n): service is SocketServiceDef {\n return service.type === \"socket\";\n}\n\n/**\n * Checks if a service definition is an MCP service.\n * \n * Type guard to determine if a service definition represents an MCP\n * (Multiplayer Control Protocol) service. Used for service type discrimination.\n * \n * @param {ServiceDefinition} service - Service definition to check\n * @returns {boolean} True if service is an MCP service, false otherwise\n * \n * @example\n * isMcpService({ name: \"game\", type: \"mcp\", serverUrl: \"...\" }); // returns true\n * isMcpService({ name: \"chat\", type: \"socket\" }); // returns false\n */\nexport function isMcpService(\n service: ServiceDefinition,\n): service is McpServiceDef {\n return service.type === \"mcp\";\n}\n\n/**\n * Get all service names from a list of services.\n */\nexport function getServiceNames(services: ServiceDefinition[]): string[] {\n return services.map((s) => s.name);\n}\n\n/**\n * Find a service by name.\n */\nexport function findService(\n services: ServiceDefinition[],\n name: string,\n): ServiceDefinition | undefined {\n return services.find((s) => s.name.toLowerCase() === name.toLowerCase());\n}\n\n/**\n * Check if a service name exists (case-insensitive).\n */\nexport function hasService(\n services: ServiceDefinition[],\n name: string,\n): boolean {\n return services.some((s) => s.name.toLowerCase() === name.toLowerCase());\n}\n\n/**\n * Allowed leaf value for `ServiceParams`. Mirrors `EventPayloadValue`'s\n * recursive-array shape so integration call signatures can express the\n * nested structures real services need (port mappings, volume mounts,\n * pagination cursors), and so a value satisfying `EventPayloadValue`\n * also satisfies `ServiceParamsValue` without a cast — the same data\n * flows through `call-service` and `emit` without boundary widening.\n */\nexport type ServiceParamsValue =\n | string\n | number\n | boolean\n | Date\n | null\n | undefined\n | ServiceParams\n | readonly ServiceParamsValue[];\n\n/** Parameters passed to call-service effects. Recursive for nested request shapes. */\nexport interface ServiceParams {\n [key: string]: ServiceParamsValue;\n}\n","/**\n * Orbital Type (Self-Contained)\n *\n * Defines the Orbital - the atomic building block of applications.\n * Formula: Orbital = Entity × Traits × Pages\n *\n * An Orbital is a module that exports { entity, traits, pages }.\n * Use `uses` to import other Orbitals and access their components via:\n * - Alias.entity\n * - Alias.traits.TraitName\n * - Alias.pages.PageName\n *\n * @packageDocumentation\n */\n\nimport { z } from \"zod\";\nimport type { Entity, EntityPersistence } from \"./entity.js\";\nimport { EntitySchema, EntityPersistenceSchema } from \"./entity.js\";\nimport type { EntityField } from \"./field.js\";\nimport { EntityFieldSchema } from \"./field.js\";\nimport type { Page } from \"./page.js\";\nimport { PageSchema } from \"./page.js\";\nimport type {\n TraitRef,\n EventPayloadField,\n EventScope,\n Trait,\n} from \"./trait.js\";\nimport {\n TraitRefSchema,\n EventPayloadFieldSchema,\n EventScopeSchema,\n TraitSchema,\n} from \"./trait.js\";\nimport type {\n DomainContext,\n DesignPreferences,\n SuggestedGuard,\n ThemeRef,\n} from \"./domain.js\";\nimport {\n DomainContextSchema,\n DesignPreferencesSchema,\n SuggestedGuardSchema,\n ThemeRefSchema,\n} from \"./domain.js\";\nimport type { ServiceRef } from \"./service.js\";\nimport { ServiceRefSchema } from \"./service.js\";\nimport type { Expression } from \"./expression.js\";\nimport { ExpressionSchema } from \"./expression.js\";\n\n// ============================================================================\n// Use Declaration (Import System)\n// ============================================================================\n\n/**\n * UseDeclaration - Import an external Orbital as a namespace.\n *\n * After importing, access components via:\n * - Alias.entity - The entity definition\n * - Alias.traits.TraitName - A specific trait\n * - Alias.pages.PageName - A specific page\n *\n * @example\n * ```json\n * {\n * \"uses\": [\n * { \"from\": \"./health.orb\", \"as\": \"Health\" },\n * { \"from\": \"std/behaviors/game-core\", \"as\": \"GameCore\" }\n * ]\n * }\n * ```\n */\nexport interface UseDeclaration {\n /**\n * Import source path:\n * - \"std/behaviors/game-core\" - Standard library\n * - \"./shared/health.orb\" - Local .orb file (relative path)\n * - \"../common/physics.orb\" - Parent directory .orb file\n * - \"@game-lib/enemies.orb\" - Scoped package (configured base)\n */\n from: string;\n\n /**\n * Alias for accessing imported components.\n * Used as namespace: Alias.entity, Alias.traits.X, Alias.pages.X\n */\n as: string;\n}\n\nexport const UseDeclarationSchema = z.object({\n from: z.string().min(1, \"Import source is required\"),\n as: z\n .string()\n .min(1, \"Alias is required\")\n .regex(\n /^[A-Z][a-zA-Z0-9]*$/,\n 'Alias must be PascalCase (e.g., \"Health\", \"GameCore\")',\n ),\n});\n\n// ============================================================================\n// Entity Reference (Inline OR Reference)\n// ============================================================================\n\n/**\n * EntityCall - Reference to an imported entity with optional override arguments.\n *\n * Treats the imported entity as a callable function: the atom's declared\n * fields are defaults and the caller can append extra fields, rename, or\n * override persistence/collection. The discriminator key is `extends` to\n * stay consistent with the Phase A.5 Rust schema (`EntityRef::Extends`).\n *\n * @example\n * ```json\n * // Inherit ModalRecord's fields, rename to CartItem, add pendingId\n * {\n * \"extends\": \"Modal.entity\",\n * \"name\": \"CartItem\",\n * \"fields\": [{ \"name\": \"pendingId\", \"type\": \"string\" }]\n * }\n * ```\n */\nexport interface EntityCall {\n /** Reference to the imported entity using the \"extends\" discriminator key */\n extends: string;\n /** Optional rename for the resulting entity */\n name?: string;\n /** Additional fields appended to the inherited set (caller wins on name collision) */\n fields?: EntityField[];\n /** Optional persistence override */\n persistence?: EntityPersistence;\n /** Optional collection override */\n collection?: string;\n}\n\n/**\n * EntityRef - Entity can be inline definition OR reference to imported entity.\n *\n * Reference formats:\n * - Simple string: \"Alias.entity\"\n * - Call form (with overrides): { extends: \"Alias.entity\", name?, fields?, persistence?, collection? }\n *\n * @example\n * ```json\n * // Inline\n * { \"entity\": { \"name\": \"Player\", \"fields\": [...] } }\n *\n * // Simple reference\n * { \"entity\": \"Goblin.entity\" }\n *\n * // Call form with overrides (Phase F)\n * { \"entity\": { \"extends\": \"Modal.entity\", \"name\": \"CartItem\", \"fields\": [...] } }\n * ```\n */\nexport type EntityRef = Entity | string | EntityCall;\n\n/**\n * Checks if an entity reference is a string reference.\n *\n * Type guard to determine if an EntityRef is a string reference\n * (format: \"Alias.entity\") rather than an inline entity definition or\n * an EntityCall object.\n *\n * Note: This guard intentionally narrows to `string` only. To check for\n * any non-inline form (string OR EntityCall), use `isEntityReferenceAny`.\n *\n * @param {EntityRef} entity - Entity reference to check\n * @returns {boolean} True if entity is a string reference, false otherwise\n *\n * @example\n * const ref1 = \"User.entity\"; // string reference\n * const ref2 = { name: \"User\", fields: [...] }; // inline definition\n * const ref3 = { extends: \"User.entity\" }; // EntityCall\n *\n * isEntityReference(ref1); // returns true\n * isEntityReference(ref2); // returns false\n * isEntityReference(ref3); // returns false\n */\nexport function isEntityReference(entity: EntityRef): entity is string {\n return typeof entity === \"string\";\n}\n\n/**\n * Checks if an entity reference is an EntityCall (extends form).\n *\n * Type guard for the call-form EntityRef introduced in Phase F. EntityCall\n * is identified by the presence of the \"extends\" discriminator key.\n *\n * @param {EntityRef} entity - Entity reference to check\n * @returns {boolean} True if entity is an EntityCall object\n *\n * @example\n * isEntityCall({ extends: \"Modal.entity\", name: \"CartItem\" }); // returns true\n * isEntityCall(\"Modal.entity\"); // returns false\n * isEntityCall({ name: \"Modal\", fields: [] }); // returns false\n */\nexport function isEntityCall(entity: EntityRef): entity is EntityCall {\n return typeof entity === \"object\" && entity !== null && \"extends\" in entity;\n}\n\n/**\n * Checks if an entity reference is any non-inline form (string or EntityCall).\n *\n * Broader companion to `isEntityReference` that recognizes both the bare\n * string reference and the Phase F EntityCall form.\n *\n * @param {EntityRef} entity - Entity reference to check\n * @returns {boolean} True if entity is a string reference or EntityCall\n */\nexport function isEntityReferenceAny(\n entity: EntityRef,\n): entity is string | EntityCall {\n return isEntityReference(entity) || isEntityCall(entity);\n}\n\n/**\n * Validate entity reference format: \"Alias.entity\"\n */\nexport const EntityRefStringSchema = z\n .string()\n .regex(\n /^[A-Z][a-zA-Z0-9]*\\.entity$/,\n 'Entity reference must be in format \"Alias.entity\" (e.g., \"Goblin.entity\")',\n );\n\n/**\n * Validate EntityCall (extends form) shape.\n *\n * Phase F.4 refines:\n * - The `fields` override array must not contain duplicate field names\n * (case-sensitive). Duplicates would silently shadow each other during\n * the inliner's field-merge step, so reject at the schema boundary.\n */\nexport const EntityCallSchema = z\n .object({\n extends: z\n .string()\n .regex(\n /^[A-Z][a-zA-Z0-9]*\\.entity$/,\n 'EntityCall \"extends\" must be in format \"Alias.entity\"',\n ),\n name: z.string().optional(),\n fields: z.array(EntityFieldSchema).optional(),\n persistence: EntityPersistenceSchema.optional(),\n collection: z.string().optional(),\n })\n .refine(\n (call) => {\n if (!call.fields) return true;\n const seen = new Set<string>();\n for (const field of call.fields) {\n if (field.name === undefined) continue;\n if (seen.has(field.name)) return false;\n seen.add(field.name);\n }\n return true;\n },\n {\n message:\n 'EntityCall \"fields\" override list must not contain duplicate field names',\n path: [\"fields\"],\n },\n );\n\nexport const EntityRefSchema = z.union([\n EntitySchema,\n EntityRefStringSchema,\n EntityCallSchema,\n]);\n\n// ============================================================================\n// Page Reference (Inline OR Reference)\n// ============================================================================\n\n/**\n * PageRefObject - Reference to imported page with optional override arguments.\n *\n * Phase F adds `linkedEntity` and `traits` arguments so a caller can rebind\n * the imported page's entity and trait set, treating the page as a callable\n * function.\n */\nexport interface PageRefObject {\n /**\n * Reference to imported page: \"Alias.pages.PageName\"\n */\n ref: string;\n\n /**\n * Phase 1.2: optional registry path disambiguator. Pairs with `ref` to\n * explicitly name which `uses` entry the alias was imported from\n * (e.g. \"std/behaviors/atoms/std-browse\"). Helpful for programmatic\n * descriptor construction and inline-phase disambiguation when multiple\n * registries expose the same alias prefix.\n */\n from?: string;\n\n /**\n * Optional path override.\n * If provided, overrides the original page's path.\n */\n path?: string;\n\n /**\n * Phase F: rebind the page's entity to the caller's entity.\n * Identifier-substitution pass rewrites references to the original\n * entity inside the imported page.\n */\n linkedEntity?: string;\n\n /**\n * Phase F: override the page's trait set with the caller-supplied list.\n * Each entry may be a string trait reference or an inline trait reference object.\n */\n traits?: TraitRef[];\n}\n\n/**\n * PageRef - Page can be inline definition OR reference to imported page.\n *\n * Reference formats:\n * - \"Alias.pages.PageName\" - Simple reference (keeps original path)\n * - { ref: \"Alias.pages.PageName\", path: \"/custom\" } - Reference with path override\n *\n * @example\n * ```json\n * // Inline\n * { \"name\": \"Dashboard\", \"path\": \"/\", ... }\n *\n * // Simple reference\n * \"User.pages.Profile\"\n *\n * // Reference with path override\n * { \"ref\": \"User.pages.Profile\", \"path\": \"/my-profile\" }\n * ```\n */\nexport type PageRef = Page | string | PageRefObject;\n\n/**\n * Checks if a page reference is a string reference.\n * \n * Type guard to determine if a PageRef is a simple string reference\n * (format: \"Alias.pages.PageName\") rather than an inline page definition or object reference.\n * \n * @param {PageRef} page - Page reference to check\n * @returns {boolean} True if page is a string reference, false otherwise\n * \n * @example\n * const ref1 = \"User.pages.Profile\"; // string reference\n * const ref2 = { name: \"Dashboard\", path: \"/\" }; // inline definition\n * \n * isPageReferenceString(ref1); // returns true\n * isPageReferenceString(ref2); // returns false\n */\nexport function isPageReferenceString(page: PageRef): page is string {\n return typeof page === \"string\";\n}\n\n/**\n * Checks if a page reference is a reference object.\n * \n * Type guard to determine if a PageRef is an object reference\n * with a 'ref' property rather than an inline page definition.\n * \n * @param {PageRef} page - Page reference to check\n * @returns {boolean} True if page is a reference object, false otherwise\n * \n * @example\n * const ref1 = { ref: \"User.pages.Profile\", path: \"/custom\" }; // reference object\n * const ref2 = { name: \"Dashboard\", path: \"/\" }; // inline definition\n * \n * isPageReferenceObject(ref1); // returns true\n * isPageReferenceObject(ref2); // returns false\n */\nexport function isPageReferenceObject(page: PageRef): page is PageRefObject {\n return typeof page === \"object\" && \"ref\" in page && !(\"name\" in page);\n}\n\n/**\n * Checks if a page reference is any type of reference.\n * \n * Type guard to determine if a PageRef is a reference (string or object)\n * rather than an inline page definition.\n * \n * @param {PageRef} page - Page reference to check\n * @returns {boolean} True if page is a reference, false if inline definition\n * \n * @example\n * const ref1 = \"User.pages.Profile\"; // string reference\n * const ref2 = { ref: \"User.pages.Profile\", path: \"/custom\" }; // object reference\n * const ref3 = { name: \"Dashboard\", path: \"/\" }; // inline definition\n * \n * isPageReference(ref1); // returns true\n * isPageReference(ref2); // returns true\n * isPageReference(ref3); // returns false\n */\nexport function isPageReference(page: PageRef): page is string | PageRefObject {\n return isPageReferenceString(page) || isPageReferenceObject(page);\n}\n\n/**\n * Validate page reference format: \"Alias.pages.PageName\"\n */\nexport const PageRefStringSchema = z\n .string()\n .regex(\n /^[A-Z][a-zA-Z0-9]*\\.pages\\.[A-Z][a-zA-Z0-9]*$/,\n 'Page reference must be in format \"Alias.pages.PageName\" (e.g., \"User.pages.Profile\")',\n );\n\nexport const PageRefObjectSchema = z.object({\n ref: PageRefStringSchema,\n // Phase 1.2: optional registry path disambiguator, pairs with `ref`.\n from: z.string().optional(),\n path: z.string().startsWith(\"/\").optional(),\n linkedEntity: z.string().optional(),\n traits: z.array(TraitRefSchema).optional(),\n});\n\nexport const PageRefSchema = z.union([\n PageSchema,\n PageRefStringSchema,\n PageRefObjectSchema,\n]);\n\n// ============================================================================\n// Trait Reference Extensions\n// ============================================================================\n\n/**\n * Extended trait reference format for imported traits.\n *\n * Formats:\n * - \"TraitName\" - Local trait (inline or from uses without alias)\n * - \"Alias.traits.TraitName\" - Imported trait with namespace\n *\n * The existing TraitRef type already supports these via string.\n */\n\n/**\n * Validate trait reference format for imported traits.\n */\nexport const ImportedTraitRefStringSchema = z\n .string()\n .regex(\n /^([A-Z][a-zA-Z0-9]*\\.traits\\.)?[A-Z][a-zA-Z0-9]*$/,\n 'Trait reference must be \"TraitName\" or \"Alias.traits.TraitName\"',\n );\n\n/**\n * Checks if a trait reference is an imported reference.\n * \n * Determines if a trait reference uses the imported format\n * \"Alias.traits.TraitName\" rather than a simple \"TraitName\".\n * \n * @param {string} ref - Trait reference to check\n * @returns {boolean} True if reference is imported format, false otherwise\n * \n * @example\n * isImportedTraitRef(\"User.traits.Profile\"); // returns true\n * isImportedTraitRef(\"Profile\"); // returns false\n */\nexport function isImportedTraitRef(ref: string): boolean {\n return /^[A-Z][a-zA-Z0-9]*\\.traits\\.[A-Z][a-zA-Z0-9]*$/.test(ref);\n}\n\n/**\n * Parses an imported trait reference.\n * \n * Extracts the alias and trait name from an imported trait reference\n * in format \"Alias.traits.TraitName\". Returns null if not a valid imported reference.\n * \n * @param {string} ref - Trait reference to parse\n * @returns {{ alias: string; traitName: string } | null} Parsed reference or null\n * \n * @example\n * parseImportedTraitRef(\"User.traits.Profile\"); // returns { alias: \"User\", traitName: \"Profile\" }\n * parseImportedTraitRef(\"Profile\"); // returns null\n */\nexport function parseImportedTraitRef(\n ref: string,\n): { alias: string; traitName: string } | null {\n const match = ref.match(/^([A-Z][a-zA-Z0-9]*)\\.traits\\.([A-Z][a-zA-Z0-9]*)$/);\n if (!match) return null;\n return { alias: match[1], traitName: match[2] };\n}\n\n/**\n * Parses an entity reference.\n * \n * Extracts the alias from an entity reference in format \"Alias.entity\".\n * Returns null if not a valid entity reference.\n * \n * @param {string} ref - Entity reference to parse\n * @returns {{ alias: string } | null} Parsed reference or null\n * \n * @example\n * parseEntityRef(\"User.entity\"); // returns { alias: \"User\" }\n * parseEntityRef(\"User\"); // returns null\n */\nexport function parseEntityRef(ref: string): { alias: string } | null {\n const match = ref.match(/^([A-Z][a-zA-Z0-9]*)\\.entity$/);\n if (!match) return null;\n return { alias: match[1] };\n}\n\n/**\n * Parses a page reference.\n * \n * Extracts the alias and page name from a page reference\n * in format \"Alias.pages.PageName\". Returns null if not a valid page reference.\n * \n * @param {string} ref - Page reference to parse\n * @returns {{ alias: string; pageName: string } | null} Parsed reference or null\n * \n * @example\n * parsePageRef(\"User.pages.Profile\"); // returns { alias: \"User\", pageName: \"Profile\" }\n * parsePageRef(\"Profile\"); // returns null\n */\nexport function parsePageRef(\n ref: string,\n): { alias: string; pageName: string } | null {\n const match = ref.match(/^([A-Z][a-zA-Z0-9]*)\\.pages\\.([A-Z][a-zA-Z0-9]*)$/);\n if (!match) return null;\n return { alias: match[1], pageName: match[2] };\n}\n\n// ============================================================================\n// Event Listener (Legacy)\n// ============================================================================\n\n/**\n * Event listener for cross-orbital communication (legacy format).\n * @deprecated Use trait-level listens with scope instead.\n */\nexport interface EventListener {\n /** Event key to listen for */\n event: string;\n /** Action to trigger */\n triggers: string;\n /** Optional guard condition */\n guard?: string;\n}\n\nexport const EventListenerSchema = z.object({\n event: z.string().min(1),\n triggers: z.string().min(1),\n guard: z.string().optional(),\n});\n\n// ============================================================================\n// Computed Event Contract (Trait-Centric Model)\n// ============================================================================\n\n/**\n * Source of an event - which trait/transition/tick emits it.\n */\nexport interface EventSource {\n /** Trait that emits this event */\n trait: string;\n /** Transition that emits this event (if applicable) */\n transition?: string;\n /** Tick that emits this event (if applicable) */\n tick?: string;\n}\n\nexport const EventSourceSchema = z.object({\n trait: z.string().min(1),\n transition: z.string().optional(),\n tick: z.string().optional(),\n});\n\n/**\n * Computed event contract with source tracking.\n * Generated by aggregating trait-level emits with namespacing.\n */\nexport interface ComputedEventContract {\n /** Namespaced event: \"TraitName.EVENT_NAME\" */\n event: string;\n /** Original event name without namespace */\n originalEvent: string;\n /** Source trait that emits this event */\n source: EventSource;\n /** Human-readable description */\n description?: string;\n /** Payload schema */\n payload?: EventPayloadField[];\n}\n\nexport const ComputedEventContractSchema = z.object({\n event: z.string().min(1),\n originalEvent: z.string().min(1),\n source: EventSourceSchema,\n description: z.string().optional(),\n payload: z.array(EventPayloadFieldSchema).optional(),\n});\n\n/**\n * Computed event listener with source tracking.\n * Generated by aggregating trait-level listens.\n */\nexport interface ComputedEventListener {\n /** Event to listen for (may be namespaced) */\n event: string;\n /** Source trait that defines this listener */\n source: EventSource;\n /** State machine event to trigger */\n triggers: string;\n /** Guard expression */\n guard?: Expression;\n /** Payload field mapping */\n payloadMapping?: Record<string, string>;\n}\n\nexport const ComputedEventListenerSchema = z.object({\n event: z.string().min(1),\n source: EventSourceSchema,\n triggers: z.string().min(1),\n guard: ExpressionSchema.optional(),\n payloadMapping: z.record(z.string()).optional(),\n});\n\n// ============================================================================\n// Orbital\n// ============================================================================\n\n/**\n * Orbital - The atomic building block of applications.\n *\n * Formula: Orbital = Entity × Traits × Pages\n *\n * An orbital is a self-contained feature unit that groups:\n * - One entity (the data nucleus) - inline OR referenced via \"Alias.entity\"\n * - Zero or more traits (behavioral patterns) - inline OR referenced via \"Alias.traits.X\"\n * - Zero or more pages (UI entry points) - inline OR referenced via \"Alias.pages.X\"\n *\n * Use `uses` to import other orbitals and access their components.\n */\nexport type Orbital = OrbitalDefinition;\n\nexport interface OrbitalDefinition {\n /** Human-readable name */\n name: string;\n\n /** Optional description */\n description?: string;\n\n /** Visual prompt override */\n visual_prompt?: string;\n\n // ========================================================================\n // Import System (Unified Reference)\n // ========================================================================\n\n /**\n * Import external orbitals as namespaces.\n *\n * After importing, access components via:\n * - Alias.entity - The entity definition\n * - Alias.traits.TraitName - A specific trait\n * - Alias.pages.PageName - A specific page\n * - Alias.theme - The theme definition\n * - Alias.services.ServiceName - A specific service\n *\n * @example\n * ```json\n * \"uses\": [\n * { \"from\": \"./health.orb\", \"as\": \"Health\" },\n * { \"from\": \"std/behaviors/game-core\", \"as\": \"GameCore\" }\n * ]\n * ```\n */\n uses?: UseDeclaration[];\n\n // ========================================================================\n // Theme & Services\n // ========================================================================\n\n /**\n * Theme definition (inline OR reference via \"Alias.theme\").\n *\n * @example\n * ```json\n * // Inline\n * \"theme\": { \"name\": \"ocean\", \"tokens\": { \"colors\": { \"primary\": \"#0ea5e9\" } } }\n *\n * // Reference\n * \"theme\": \"Ocean.theme\"\n * ```\n */\n theme?: ThemeRef;\n\n /**\n * Service definitions (inline OR reference via \"Alias.services.ServiceName\").\n *\n * @example\n * ```json\n * // Inline\n * \"services\": [{ \"name\": \"weather\", \"type\": \"rest\", \"baseUrl\": \"...\" }]\n *\n * // Reference\n * \"services\": [\"Weather.services.openweather\"]\n * ```\n */\n services?: ServiceRef[];\n\n // ========================================================================\n // Components (Inline OR Reference)\n // ========================================================================\n\n /**\n * Entity definition (nucleus).\n *\n * Can be:\n * - Inline: Full entity definition\n * - Reference: \"Alias.entity\" (from uses)\n *\n * Entity sharing depends on persistence type:\n * - persistent: Shared (same DB collection)\n * - runtime: Isolated (each orbital gets own instances)\n * - singleton: Shared (single global instance)\n */\n entity: EntityRef;\n\n /**\n * Imported atom entities surfaced into this orbital's resolution\n * scope WITHOUT modifying the primary `entity`. Populated by the\n * compiler's inline phase when a trait reference imports an atom\n * and OMITS the `-> Entity` linkedEntity rebind: the atom keeps its\n * own entity (e.g. `SearchResult` from std-search), and that entity\n * is registered here so validators / codegen / runtime can resolve\n * `linkedEntity = \"SearchResult\"` lookups, register persistence for\n * it, and emit its TypeScript type alongside the primary entity.\n * The orbital's per-trait entity arity stays 1:1 — this is purely a\n * NAME-RESOLUTION side channel for cross-import linkedEntity\n * references.\n */\n auxiliaryEntities?: EntityRef[];\n\n /** Trait references (local or imported via \"Alias.traits.TraitName\") */\n traits: TraitRef[];\n\n /**\n * Page definitions.\n *\n * Can be:\n * - Inline: Full page definition\n * - Reference string: \"Alias.pages.PageName\"\n * - Reference object: { ref: \"Alias.pages.PageName\", path: \"/custom\" }\n */\n pages: PageRef[];\n\n // ========================================================================\n // Event Interface (Trait-Centric Model)\n // ========================================================================\n\n /**\n * Events this orbital emits.\n *\n * COMPUTED from trait-level emits:\n * - Aggregated from all traits with `scope: 'external'`\n * - Namespaced as \"TraitName.EVENT_NAME\"\n * - Filtered by `exposes` if present\n *\n * Do not author directly - computed by resolver.\n */\n emits?: ComputedEventContract[];\n\n /**\n * Events this orbital listens for.\n *\n * COMPUTED from trait-level listens:\n * - Aggregated from all traits with `scope: 'external'`\n *\n * Do not author directly - computed by resolver.\n */\n listens?: ComputedEventListener[];\n\n /**\n * Filter which trait events are exposed externally.\n * If omitted, all external-scoped trait events are exposed.\n * Format: [\"TraitName.EVENT_NAME\", ...]\n */\n exposes?: string[];\n\n // ========================================================================\n // Context fields - persisted throughout orbital lifecycle\n // ========================================================================\n\n /** Domain context - category, vocabulary, personas */\n domainContext?: DomainContext;\n\n /** Design preferences - style, colors, UX hints */\n design?: DesignPreferences;\n\n /**\n * Suggested guards (decomposition phase only).\n * Natural language descriptions that generator converts to S-expressions.\n * Removed after generation - guards live in traits.\n */\n suggestedGuards?: SuggestedGuard[];\n}\n\nexport const OrbitalDefinitionSchema = z.object({\n name: z.string().min(1, \"Orbital name is required\"),\n description: z.string().optional(),\n visual_prompt: z.string().optional(),\n // Import system\n uses: z.array(UseDeclarationSchema).optional(),\n // Theme & Services\n theme: ThemeRefSchema.optional(),\n services: z.array(ServiceRefSchema).optional(),\n // Components (inline or reference)\n entity: EntityRefSchema,\n traits: z.array(TraitRefSchema),\n pages: z.array(PageRefSchema),\n // Event interface (trait-centric model) - computed by resolver\n emits: z.array(ComputedEventContractSchema).optional(),\n listens: z.array(ComputedEventListenerSchema).optional(),\n // Filter for exposed events (trait-centric model)\n exposes: z.array(z.string()).optional(),\n // Context fields - persisted throughout orbital lifecycle\n domainContext: DomainContextSchema.optional(),\n design: DesignPreferencesSchema.optional(),\n suggestedGuards: z.array(SuggestedGuardSchema).optional(),\n});\n\nexport const OrbitalSchema = OrbitalDefinitionSchema;\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\n/**\n * Type guard to check if an Orbital is a full definition.\n * @deprecated No longer needed since Orbital is always OrbitalDefinition now.\n */\nexport function isOrbitalDefinition(\n orbital: Orbital,\n): orbital is OrbitalDefinition {\n return \"entity\" in orbital;\n}\n\n// ============================================================================\n// Type exports\n// ============================================================================\n\nexport type OrbitalInput = z.input<typeof OrbitalSchema>;\n\n// Backward compatibility\nexport type OrbitalUnit = Orbital;\nexport const OrbitalUnitSchema = OrbitalSchema;\n","/**\n * Orbital Schema Type (Self-Contained)\n *\n * Defines the OrbitalSchema - the top-level application definition.\n * An application is a composition of orbitals: App = Σ(Orbitals)\n *\n * @packageDocumentation\n */\n\nimport { z } from \"zod\";\nimport type { Orbital } from \"./orbital.js\";\nimport { OrbitalSchema as OrbitalZodSchema } from \"./orbital.js\";\nimport type {\n DomainContext,\n DesignPreferences,\n DesignTokens,\n CustomPatternMap,\n} from \"./domain.js\";\nimport {\n DomainContextSchema,\n DesignPreferencesSchema,\n DesignTokensSchema,\n CustomPatternMapSchema,\n} from \"./domain.js\";\nimport type { ServiceDefinition } from \"./service.js\";\nimport { ServiceDefinitionSchema } from \"./service.js\";\nimport type { Trait } from \"./trait.js\";\n\n// ============================================================================\n// Orbital Config\n// ============================================================================\n\n/**\n * Global configuration for the application\n */\nexport interface OrbitalConfig {\n /** Theme configuration */\n theme?: {\n primary?: string;\n secondary?: string;\n mode?: \"light\" | \"dark\" | \"system\";\n };\n /** Feature flags */\n features?: Record<string, boolean>;\n /** API configuration */\n api?: {\n baseUrl?: string;\n timeout?: number;\n };\n}\n\nexport const OrbitalConfigSchema = z.object({\n theme: z\n .object({\n primary: z.string().optional(),\n secondary: z.string().optional(),\n mode: z.enum([\"light\", \"dark\", \"system\"]).optional(),\n })\n .optional(),\n features: z.record(z.boolean()).optional(),\n api: z\n .object({\n baseUrl: z.string().optional(),\n timeout: z.number().optional(),\n })\n .optional(),\n});\n\n// ============================================================================\n// Orbital Schema\n// ============================================================================\n\n/**\n * OrbitalSchema - The top-level application definition.\n *\n * An application is a composition of orbitals:\n * App = Σ(Orbitals)\n *\n * Custom traits can be defined at the schema level and referenced\n * by orbitals via TraitRef. This allows LLMs to generate custom\n * traits that aren't in the trait library.\n */\n/**\n * One `@config.<knob>` → render-ui prop substitution recorded by the inline\n * phase. Lets a consumer trace a resolved render-ui literal back to the config\n * knob it came from (the `@config.X` string is erased after substitution).\n * Mirrors the Rust `ConfigProvenanceRecord`.\n */\nexport interface ConfigProvenanceRecord {\n /** Resolved trait name (post call-site rename) owning the render-ui effect. */\n trait: string;\n /** Pattern path within the render-ui tree (e.g. `root.children.0`). */\n patternPath?: string;\n /** The pattern-node prop key whose value was a `@config.X` binding. */\n prop: string;\n /** The config knob name (`X` in `@config.X`). */\n knob: string;\n}\n\n/** Compiler-emitted schema metadata — the resolved `.orb` `_metadata` block. */\nexport interface SchemaMetadata {\n version?: number;\n createdAt?: number;\n source?: string;\n updatedAt?: number;\n /** Config→knob provenance keyed by orbital name. See {@link ConfigProvenanceRecord}. */\n configProvenance?: Record<string, ConfigProvenanceRecord[]>;\n}\n\nexport interface OrbitalSchema {\n /** Application name */\n name: string;\n\n /** Description */\n description?: string;\n\n /**\n * Short human-readable summary distinct from `description`. Typically an\n * AI-generated one-liner used by app list views, breadcrumbs, and the\n * `GET /graphs/:appId/domain-text` projection. Kept separate from\n * `description` (which may be longer / authored copy) so consumers can\n * present a stable short label without truncating.\n */\n summary?: string;\n\n /** Version (semver) */\n version?: string;\n\n /** Domain context - user request + classification */\n domainContext?: DomainContext;\n\n /** Design preferences */\n design?: DesignPreferences;\n\n /**\n * Design tokens - reusable Tailwind class collections.\n * Reference via `token: \"surfaces.glass\"` in patterns.\n */\n designTokens?: DesignTokens;\n\n /**\n * Custom pattern definitions for app-specific reusable patterns.\n * Register custom designs that can be referenced by name.\n */\n customPatterns?: CustomPatternMap;\n\n /** Array of orbitals */\n orbitals: Orbital[];\n\n /** External services */\n services?: ServiceDefinition[];\n\n /** Global config */\n config?: OrbitalConfig;\n\n /** Compiler-emitted metadata (resolved `.orb` `_metadata`). */\n _metadata?: SchemaMetadata;\n}\n\nexport const ConfigProvenanceRecordSchema = z.object({\n trait: z.string(),\n patternPath: z.string().optional(),\n prop: z.string(),\n knob: z.string(),\n});\n\nexport const SchemaMetadataSchema = z.object({\n version: z.number().optional(),\n createdAt: z.number().optional(),\n source: z.string().optional(),\n updatedAt: z.number().optional(),\n configProvenance: z.record(z.array(ConfigProvenanceRecordSchema)).optional(),\n});\n\nexport const OrbitalSchemaSchema = z.object({\n name: z.string().min(1, \"Schema name is required\"),\n description: z.string().optional(),\n summary: z.string().optional(),\n version: z.string().optional(),\n domainContext: DomainContextSchema.optional(),\n design: DesignPreferencesSchema.optional(),\n designTokens: DesignTokensSchema,\n customPatterns: CustomPatternMapSchema,\n orbitals: z\n .array(OrbitalZodSchema)\n .min(1, \"At least one orbital is required\"),\n services: z.array(ServiceDefinitionSchema).optional(),\n config: OrbitalConfigSchema.optional(),\n _metadata: SchemaMetadataSchema.optional(),\n});\n\n// ============================================================================\n// Persisted/Flattened View\n// ============================================================================\n\n/**\n * Flattened `OrbitalSchema` view used by the persistence/runtime layer.\n *\n * Canonical `OrbitalSchema` keeps every trait inside its owning\n * `OrbitalDefinition.traits`. Some runtime paths (e.g. the orbital-agent\n * stream, Firestore persistence) additionally roll the resolved trait set up\n * to the top level as `traits[]` so diffs and list views don't have to walk\n * every orbital.\n *\n * This is intentionally a LOSSY persisted view, NOT the canonical authoring\n * shape: it carries the rolled-up array alongside the per-orbital trait\n * lists, and consumers should prefer `OrbitalSchema` whenever the rolled-up\n * surface isn't required.\n */\nexport interface OrbitalSchemaWithTraits extends OrbitalSchema {\n /** Flattened trait set rolled up from all orbitals. Persisted-view only. */\n traits?: Trait[];\n}\n\n// ============================================================================\n// Parsing Functions\n// ============================================================================\n\n/**\n * Parses raw data into a validated OrbitalSchema.\n * \n * Uses Zod validation to ensure the data conforms to the OrbitalSchema structure.\n * Throws a ZodError if validation fails. For safe parsing that doesn't throw,\n * use `safeParseOrbitalSchema()` instead.\n * \n * @param {unknown} data - Raw data to parse (typically JSON)\n * @returns {OrbitalSchema} Validated orbital schema\n * @throws {z.ZodError} If data doesn't match OrbitalSchema structure\n * \n * @example\n * ```typescript\n * try {\n * const schema = parseOrbitalSchema(jsonData);\n * console.log('Valid schema:', schema.name);\n * } catch (error) {\n * console.error('Invalid schema:', error);\n * }\n * ```\n * \n * @see safeParseOrbitalSchema\n */\nexport function parseOrbitalSchema(data: unknown): OrbitalSchema {\n return OrbitalSchemaSchema.parse(data) as OrbitalSchema;\n}\n\n/**\n * Safely parses raw data into a validated OrbitalSchema without throwing.\n * \n * Uses Zod's safeParse method to validate data and return a result object\n * instead of throwing errors. This is useful for form validation and\n * user input handling where you want to gracefully handle invalid data.\n * \n * @param {unknown} data - Raw data to parse (typically JSON)\n * @returns {z.SafeParseReturnType<OrbitalSchema, OrbitalSchema>} Parse result with success/status\n * \n * @example\n * ```typescript\n * const result = safeParseOrbitalSchema(jsonData);\n * if (result.success) {\n * console.log('Valid schema:', result.data.name);\n * } else {\n * console.error('Validation errors:', result.error);\n * }\n * ```\n * \n * @see parseOrbitalSchema\n */\nexport function safeParseOrbitalSchema(data: unknown) {\n return OrbitalSchemaSchema.safeParse(data);\n}\n\n// ============================================================================\n// Type exports\n// ============================================================================\n\nexport type OrbitalSchemaInput = z.input<typeof OrbitalSchemaSchema>;\nexport type OrbitalConfigInput = z.input<typeof OrbitalConfigSchema>;\n","/**\n * S-Expression Bindings\n *\n * Defines binding types and utilities for S-expression context.\n * Bindings are references to values that are resolved at runtime.\n *\n * Core Bindings:\n * - @entity - The linked entity for this trait (e.g., @entity.health)\n * - @payload - Event payload data (e.g., @payload.amount)\n * - @state - Current state machine state\n * - @now - Current timestamp (Date.now())\n *\n * Entity Bindings:\n * - @EntityName.field - Reference to singleton/runtime entity (e.g., @GameConfig.gravity)\n *\n * @packageDocumentation\n */\n\nimport { z } from 'zod';\n\n// Re-export core binding utilities from expression.ts\nexport {\n isBinding,\n parseBinding,\n isValidBinding,\n CORE_BINDINGS,\n type CoreBinding,\n type ParsedBinding,\n} from './expression.js';\n\n// ============================================================================\n// Binding Schema\n// ============================================================================\n\n/**\n * Schema for a binding string.\n * Validates that the string starts with @ and has valid format.\n */\nexport const BindingSchema = z.string().refine(\n (val) => {\n if (!val.startsWith('@')) return false;\n const parts = val.slice(1).split('.');\n if (parts.length === 0 || parts[0] === '') return false;\n // All parts must be valid identifiers (letters, numbers, underscore)\n // supporting unicode characters for i18n\n return parts.every((part) => /^[\\p{L}_][\\p{L}0-9_]*$/u.test(part));\n },\n { message: 'Invalid binding format. Must be @name or @name.path.to.field' }\n);\n\n// ============================================================================\n// Binding Constants\n// ============================================================================\n\n/**\n * Binding documentation for LLM prompts and validation messages.\n * \n * IMPORTANT: Keep synchronized with CORE_BINDINGS in expression.ts\n */\nexport const BINDING_DOCS = {\n entity: {\n description: 'Reference to the linked entity for this trait',\n examples: ['@entity.health', '@entity.x', '@entity.status'],\n requiresPath: true,\n },\n payload: {\n description: 'Reference to the event payload data',\n examples: ['@payload.amount', '@payload.targetId', '@payload.action'],\n requiresPath: true,\n },\n state: {\n description: 'Current state machine state name',\n examples: ['@state'],\n requiresPath: false,\n },\n now: {\n description: 'Current timestamp in milliseconds',\n examples: ['@now'],\n requiresPath: false,\n },\n config: {\n description: 'Trait configuration values',\n examples: ['@config.apiEndpoint', '@config.theme'],\n requiresPath: true,\n },\n computed: {\n description: 'Computed/calculated values',\n examples: ['@computed.total', '@computed.isValid'],\n requiresPath: true,\n },\n trait: {\n description: 'Trait context data',\n examples: ['@trait.name', '@trait.category'],\n requiresPath: true,\n },\n user: {\n description: 'Authenticated user / agent context for ownership and role-based gating',\n examples: ['@user.id', '@user.role'],\n requiresPath: true,\n },\n} as const;\n\n/**\n * Validation rules for bindings in different contexts.\n */\nexport const BINDING_CONTEXT_RULES = {\n guard: {\n allowed: ['entity', 'payload', 'state', 'now', 'config', 'user'] as const,\n description:\n 'Guards can access entity fields, event payload, current state, time, the call-site trait config (@config.X), and the authenticated user context (@user.id, @user.role) for ownership / role gates. Config access lets atoms write mode-aware guards — e.g. std-modal\\'s OPEN can require @payload.row only when @config.mode equals \"edit\", letting create-mode legitimately fire OPEN with no row. Like effects, @config.X is substituted at molecule/organism inline time with the literal call-site value; at atom-scope validate, @config is allowed-but-unresolved.',\n },\n effect: {\n allowed: ['entity', 'payload', 'state', 'now', 'trait', 'config', 'user'] as const,\n description:\n 'Effects can access and modify entity fields, use payload data, embed another trait\\'s live frame via @trait.X inside render-ui children, read trait config values (@config.X) for atoms parameterized by their call-site, and read the authenticated user context (@user.id, @user.role). At molecule/organism inline time, @config.X is substituted with the literal value from the call-site config block; at atom-scope validate, @config is allowed-but-unresolved.',\n },\n tick: {\n allowed: ['entity', 'state', 'now', 'config', 'user'] as const,\n description: 'Ticks can access entity fields, current state, time, trait config (@config.X) for parameterized atoms, and the authenticated user context (@user.id, @user.role). Same substitution semantics as guards/effects.',\n },\n} as const;\n\nexport type BindingContext = keyof typeof BINDING_CONTEXT_RULES;\n\n// ============================================================================\n// Binding Validation Helpers\n// ============================================================================\n\n/**\n * Check if a binding is valid in a given context.\n *\n * @param binding - Parsed binding\n * @param context - Context where binding is used\n * @returns Error message if invalid, null if valid\n */\nexport function validateBindingInContext(\n binding: { type: 'core' | 'entity'; root: string },\n context: BindingContext\n): string | null {\n const rules = BINDING_CONTEXT_RULES[context];\n\n if (binding.type === 'core') {\n if (!(rules.allowed as readonly string[]).includes(binding.root)) {\n return `Binding @${binding.root} is not allowed in ${context} context. Allowed: ${rules.allowed.join(', ')}`;\n }\n }\n\n // Entity bindings are always allowed (they reference singletons/runtime entities)\n return null;\n}\n\n/**\n * Get all valid binding examples for a context.\n *\n * @param context - Context to get examples for\n * @returns Array of example binding strings\n */\nexport function getBindingExamples(context: BindingContext): string[] {\n const rules = BINDING_CONTEXT_RULES[context];\n const examples: string[] = [];\n\n for (const binding of rules.allowed) {\n const doc = BINDING_DOCS[binding];\n examples.push(...doc.examples);\n }\n\n // Add entity binding example\n examples.push('@GameConfig.gravity', '@Filter.searchTerm');\n\n return examples;\n}\n","/**\n * Binding root classification\n *\n * The prefix of an `@X.path` binding expression identifies which runtime\n * context resolves the rest of the path. This type is the TS-side mirror\n * of `OirBindingRoot` in `orbital-core`'s IR; publishing it from\n * `@almadar/core` lets the codegen, the runtime binding resolver, and\n * the verifier's schema walker all refer to the same narrow union.\n *\n * Distinct from {@link ParsedBinding.root} (which is a plain string): use\n * `BindingRoot` whenever you need exhaustiveness over the known prefixes.\n *\n * - `entity`: `@entity.field` — the trait's linked entity (first row on\n * the client, `getById` result on the server).\n * - `payload`: `@payload.x` — the last event's payload.\n * - `state`: `@state.x` — the state machine's `state` slot (rare;\n * mostly used for guard/effect contexts).\n * - `config`: `@config.x` — the trait ref's merged config from the\n * molecule call site.\n * - `user`: `@user.x` — authenticated user / agent context.\n * - `trait`: `@trait.x` — render-time reference to another trait's\n * mounted view. Resolved by `<TraitFrame>` at runtime, not by the\n * SExpression compiler.\n * - `item`: `@item.x` — iterator variable inside a `map` / repeat\n * pattern.\n * - `now`: `@now` — current timestamp (ISO string).\n * - `computed`: `@computed.x` — evaluator-computed value (Phase 4.5).\n * - `other`: catch-all for unknown prefixes or entity-reference\n * bindings (`@User.name`, `@_item`).\n *\n * @packageDocumentation\n */\n\nimport { z } from 'zod';\n\nexport type BindingRoot =\n | 'entity'\n | 'payload'\n | 'state'\n | 'config'\n | 'user'\n | 'trait'\n | 'item'\n | 'now'\n | 'computed'\n | 'other';\n\n/** Every known binding root, in a stable order — useful for exhaustiveness checks. */\nexport const BINDING_ROOTS: readonly BindingRoot[] = [\n 'entity',\n 'payload',\n 'state',\n 'config',\n 'user',\n 'trait',\n 'item',\n 'now',\n 'computed',\n 'other',\n] as const;\n\nconst KNOWN_ROOTS = new Set<string>(BINDING_ROOTS.filter((r) => r !== 'other'));\n\n/**\n * Narrow a raw binding-root string (e.g. the `root` field of\n * `ParsedBinding` from `./expression.ts`) to a `BindingRoot`. Returns\n * `'other'` for entity-reference roots like `@User.name` or unknown\n * prefixes.\n */\nexport function toBindingRoot(root: string): BindingRoot {\n return KNOWN_ROOTS.has(root) ? (root as BindingRoot) : 'other';\n}\n\n/**\n * A trait reference string of the form `@trait.<TraitName>`. Used as the\n * value type for `trait`-typed config fields. The runtime + compiled codegen\n * both substitute this with embedded trait UI at render time.\n *\n * Branded as a literal-template type so TS narrows on use; consumers should\n * call {@link isTraitFieldRef} to validate runtime values before assignment.\n */\nexport type TraitFieldRef = `@trait.${string}`;\n\nconst TRAIT_REF_PATTERN = /^@trait\\.[A-Z][a-zA-Z0-9]*$/;\n\n/** Type guard: narrow an unknown value to {@link TraitFieldRef}. */\nexport function isTraitFieldRef(value: unknown): value is TraitFieldRef {\n return typeof value === 'string' && TRAIT_REF_PATTERN.test(value);\n}\n\n/** Zod schema for {@link TraitFieldRef} values. Useful when validating analyzer\n * JSON or recipe overrides at runtime boundaries. */\nexport const TraitFieldRefSchema = z\n .string()\n .regex(TRAIT_REF_PATTERN, 'expected `@trait.<TraitName>` reference');\n","/**\n * Interaction Model Types\n *\n * Defines how users interact with entities in the application.\n * Used to drive trait selection and UI slot usage.\n *\n * @packageDocumentation\n */\n\nimport { z } from 'zod';\n\n// ============================================================================\n// Flow Types\n// ============================================================================\n\n/**\n * Create flow - how new items are created\n */\nexport type CreateFlow = 'modal' | 'page' | 'inline' | 'none';\n\n/**\n * Edit flow - how items are edited\n */\nexport type EditFlow = 'modal' | 'page' | 'inline' | 'none';\n\n/**\n * View flow - how item details are viewed\n */\nexport type ViewFlow = 'drawer' | 'page' | 'modal' | 'inline' | 'none';\n\n/**\n * Delete flow - how items are deleted\n */\nexport type DeleteFlow = 'confirm' | 'instant' | 'none';\n\n/**\n * List interaction - what happens when clicking list items\n */\nexport type ListInteraction = 'click-to-view' | 'click-to-edit' | 'inline-edit';\n\n// ============================================================================\n// Interaction Model\n// ============================================================================\n\n/**\n * InteractionModel - defines how users interact with entities.\n *\n * This drives:\n * - Which traits to attach (EntityManagement, ModalEdit, etc.)\n * - How render_ui effects target slots (modal, drawer, page)\n * - What UI patterns to use\n */\nexport interface InteractionModel {\n /** How new items are created */\n createFlow: CreateFlow;\n\n /** How items are edited */\n editFlow: EditFlow;\n\n /** How item details are viewed */\n viewFlow: ViewFlow;\n\n /** How items are deleted */\n deleteFlow: DeleteFlow;\n\n /** What happens when clicking list items */\n listInteraction?: ListInteraction;\n\n /** Enable bulk actions (select multiple, delete all) */\n bulkActions?: boolean;\n\n /** Enable real-time updates */\n realtime?: boolean;\n}\n\nexport const InteractionModelSchema = z.object({\n createFlow: z.enum(['modal', 'page', 'inline', 'none']),\n editFlow: z.enum(['modal', 'page', 'inline', 'none']),\n viewFlow: z.enum(['drawer', 'page', 'modal', 'inline', 'none']),\n deleteFlow: z.enum(['confirm', 'instant', 'none']),\n listInteraction: z.enum(['click-to-view', 'click-to-edit', 'inline-edit']).optional(),\n bulkActions: z.boolean().optional(),\n realtime: z.boolean().optional(),\n});\n\n// ============================================================================\n// Default Models per Domain\n// ============================================================================\n\n/**\n * Default interaction models for each domain type\n */\nexport const DEFAULT_INTERACTION_MODELS: Record<string, InteractionModel> = {\n business: {\n createFlow: 'modal',\n editFlow: 'modal',\n viewFlow: 'drawer',\n deleteFlow: 'confirm',\n listInteraction: 'click-to-view',\n bulkActions: true,\n },\n game: {\n createFlow: 'none',\n editFlow: 'none',\n viewFlow: 'none',\n deleteFlow: 'none',\n realtime: true,\n },\n form: {\n createFlow: 'inline',\n editFlow: 'inline',\n viewFlow: 'none',\n deleteFlow: 'none',\n },\n dashboard: {\n createFlow: 'modal',\n editFlow: 'modal',\n viewFlow: 'drawer',\n deleteFlow: 'confirm',\n listInteraction: 'click-to-view',\n },\n content: {\n createFlow: 'page',\n editFlow: 'page',\n viewFlow: 'page',\n deleteFlow: 'confirm',\n listInteraction: 'click-to-view',\n },\n};\n\n/**\n * Gets the interaction model for a domain.\n * \n * Retrieves the appropriate interaction model configuration based on the\n * specified domain. Falls back to the business model if no specific\n * domain match is found.\n * \n * @param {string} domain - Domain name (e.g., 'healthcare', 'education')\n * @returns {InteractionModel} Interaction model configuration\n * \n * @example\n * getInteractionModelForDomain('healthcare'); // returns healthcare-specific model\n * getInteractionModelForDomain('unknown'); // returns business fallback model\n */\nexport function getInteractionModelForDomain(domain: string): InteractionModel {\n return DEFAULT_INTERACTION_MODELS[domain] ?? DEFAULT_INTERACTION_MODELS.business;\n}\n\n// ============================================================================\n// Type exports\n// ============================================================================\n\nexport type InteractionModelInput = z.input<typeof InteractionModelSchema>;\n","/**\n * Pattern Type for Orbital Units\n *\n * Re-exports pattern type definitions from @almadar/patterns,\n * which is the single source of truth for all pattern types.\n *\n * @packageDocumentation\n */\n\nimport { z } from 'zod';\n\n// ============================================================================\n// Pattern Type - Re-exported from @almadar/patterns\n// ============================================================================\n\n/**\n * All valid pattern type names, imported from the almadar-patterns registry.\n * The authoritative list is auto-generated from patterns-registry.json.\n */\nexport {\n PATTERN_TYPES,\n isValidPatternType,\n} from '@almadar/patterns';\nexport type { PatternType } from '@almadar/patterns';\n\n/**\n * Zod schema for pattern types.\n * Accepts any string - validation against full registry happens at runtime.\n */\nexport const PatternTypeSchema = z.string();\n\n// Re-export for backward compatibility\nimport { PATTERN_TYPES as _PATTERN_TYPES } from '@almadar/patterns';\n\n/**\n * Get all valid pattern types from the registry.\n * \n * Returns a complete list of pattern type names from the canonical\n * @almadar/patterns registry. Use this to iterate over or validate\n * pattern types programmatically.\n * \n * @returns {string[]} Array of pattern type names\n * \n * @example\n * const types = getAllPatternTypes();\n * // Returns: ['data-table', 'detail-view', 'form-section', ...]\n */\nexport function getAllPatternTypes(): string[] {\n return [..._PATTERN_TYPES];\n}\n","/**\n * Service Contract Types\n *\n * Formalizes the two public surfaces of an Almadar service:\n * 1. Call-Service Contract — what the .orb schema can invoke on the TypeScript package\n * 2. Event Contract — what events enter/leave the service\n *\n * Plus internal-but-standardized patterns:\n * 3. StoreContract — database abstraction boundary\n * 4. LazyService — singleton lifecycle pattern\n *\n * @packageDocumentation\n */\n\nimport type { EventPayload, EventPayloadValue, LogMeta } from './types/expression.js';\nimport type { ServiceParams } from './types/service.js';\n\n// ============================================================================\n// Service Action Names (generated from services-registry.json)\n// ============================================================================\n\n/**\n * All known service action names across all contracts.\n * Kept in sync with `tools/almadar-service-sync/services-registry.json`.\n *\n * Persist operations are listed separately because they also appear\n * as `EffectResult.action` for persist effects.\n */\nexport type PersistActionName =\n | \"create\"\n | \"update\"\n | \"delete\"\n | \"list\"\n | \"query\";\n\n/**\n * Union of all service action names across all 22 service contracts.\n */\nexport type ServiceActionName =\n | PersistActionName\n // Data service\n | \"get\"\n | \"getById\"\n | \"set\"\n | \"remove\"\n | \"size\"\n // LLM\n | \"generate\"\n | \"classify\"\n | \"extract\"\n | \"summarize\"\n // Messaging\n | \"send\"\n | \"sendMessage\"\n | \"sendSMS\"\n | \"sendWhatsApp\"\n // Auth / Identity\n | \"authorize\"\n | \"revoke\"\n | \"token\"\n | \"refresh\"\n | \"userinfo\"\n | \"register\"\n // Git / VCS\n | \"cloneRepo\"\n | \"commit\"\n | \"createBranch\"\n | \"createPR\"\n | \"getPRComments\"\n | \"pull\"\n | \"push\"\n // CI / Build\n | \"build\"\n | \"compile\"\n | \"compileSchema\"\n | \"run\"\n | \"validate\"\n | \"validateSchema\"\n | \"publish\"\n // Queue / Jobs\n | \"enqueue\"\n | \"dequeue\"\n | \"cancel\"\n // Storage / Assets\n | \"upload\"\n | \"download\"\n | \"getSignedUrl\"\n // Search / Issues\n | \"search\"\n | \"getIssue\"\n | \"listIssues\"\n // Agent / Generation\n | \"generateAll\"\n | \"generateDomainLanguage\"\n | \"generateFix\"\n | \"generateOrbitals\"\n | \"cancelGeneration\"\n | \"getGenerationHistory\"\n | \"recordGeneration\"\n // Telemetry / Metrics\n | \"startSpan\"\n | \"endSpan\"\n | \"getSpan\"\n | \"recordMetric\"\n | \"getMetrics\"\n | \"increment\"\n | \"logs\"\n // Events / Channels\n | \"addEvent\"\n | \"emit\"\n | \"findEmitters\"\n | \"findListeners\"\n | \"getListenerCounts\"\n | \"getChannel\"\n | \"subscribe\"\n // User / Preferences\n | \"getUserPreferences\"\n | \"updateUserPreferences\"\n | \"getThreadHistory\"\n // Media\n | \"getVideo\"\n // Payments\n | \"createPaymentIntent\"\n | \"confirmPayment\"\n | \"refund\"\n // Lifecycle\n | \"complete\"\n | \"fail\"\n | \"expire\"\n | \"resume\"\n | \"status\"\n | \"stop\"\n | \"lock\"\n | \"unlock\"\n | \"clear\";\n\n// ============================================================================\n// Call-Service Contract\n// ============================================================================\n\n/**\n * Action definition for a service contract.\n *\n * - `params` is bus-payload-shaped (`ServiceParams`): JSON-serializable\n * key/value bag with optional nesting. Service contracts override this\n * with stricter shapes via the generic position on `ServiceContract`.\n *\n * - `result` is JSON-serializable too (`EventPayloadValue`): a primitive,\n * `null`/`undefined`, an array of values, or an `EventPayload` object.\n * This is the same recursive shape the bus accepts when an effect's\n * `success` event fires with the call-service result, so no boundary\n * widening is needed when the runtime forwards the value.\n */\nexport interface ServiceAction {\n params: ServiceParams;\n result: EventPayloadValue;\n}\n\n/**\n * What `[\"call-service\", \"name\", \"action\", {...}]` actually calls at runtime.\n * Each service defines its action map as a Record<string, ServiceAction>.\n *\n * @example\n * ```typescript\n * type LLMActions = {\n * generate: {\n * params: { userPrompt: string; model: string; maxTokens: number };\n * result: { content: string; tokensUsed: number; latencyMs: number };\n * };\n * };\n *\n * class LLMService implements ServiceContract<LLMActions> {\n * async execute(action, params) { ... }\n * }\n * ```\n */\nexport interface ServiceContract<\n Actions extends Record<string, ServiceAction>,\n> {\n execute<A extends keyof Actions & string>(\n action: A,\n params: Actions[A][\"params\"],\n ): Promise<Actions[A][\"result\"]>;\n}\n\n// ============================================================================\n// Event Contract\n// ============================================================================\n\n/**\n * Event contract — what events the service emits/listens with typed payloads.\n * Derived from the `.orb` schema's `emits` and `listens` declarations.\n *\n * @example\n * ```typescript\n * type LLMEventMap = {\n * AGENT_LLM_REQUEST: { requestId: string; prompt: string };\n * LLM_RESPONSE: { requestId: string; content: string; tokensUsed: number };\n * LLM_ERROR: { requestId: string; error: string };\n * };\n *\n * const events: ServiceEvents<LLMEventMap> = getEventBus();\n * events.emit('LLM_RESPONSE', { requestId: '1', content: '...', tokensUsed: 42 });\n * ```\n */\nexport interface ServiceEvents<\n EventMap extends Record<string, EventPayload>,\n> {\n emit<E extends keyof EventMap & string>(\n event: E,\n payload: EventMap[E],\n ): void;\n on<E extends keyof EventMap & string>(\n event: E,\n handler: (payload: EventMap[E]) => void,\n ): () => void;\n}\n\n/**\n * Create a typed view of an untyped EventBus. Wraps the raw EventBus\n * with compile-time type checking while keeping runtime behavior identical.\n *\n * @example\n * ```typescript\n * type LLMEventMap = {\n * LLM_RESPONSE: { requestId: string; content: string };\n * LLM_ERROR: { requestId: string; error: string };\n * };\n *\n * const typedBus = createTypedEventBus<LLMEventMap>(getServerEventBus());\n * typedBus.emit('LLM_RESPONSE', { requestId: '1', content: '...' }); // type-safe\n * typedBus.on('LLM_ERROR', (payload) => { payload.error; }); // payload is typed\n * ```\n */\n/**\n * Creates a typed event bus from an untyped bus implementation.\n * \n * This wrapper adds TypeScript type safety to event emission and listening.\n * The generic `EventMap` defines the shape of all events and their payloads.\n * \n * @template EventMap - Type mapping event names to their payload types\n * @param {Object} bus - Untyped event bus implementation\n * @param {Function} bus.emit - Function to emit events\n * @param {Function} bus.on - Function to listen to events\n * @returns {ServiceEvents<EventMap>} Typed event bus interface\n * \n * @example\n * interface MyEvents {\n * 'user.created': { id: string; name: string };\n * 'user.deleted': { id: string };\n * }\n * \n * const typedBus = createTypedEventBus<MyEvents>(rawBus);\n * typedBus.emit('user.created', { id: '123', name: 'Alice' });\n */\nexport function createTypedEventBus<\n EventMap extends Record<string, EventPayload>,\n>(bus: {\n emit(event: string, payload?: unknown, meta?: LogMeta): void;\n on(event: string, handler: (payload: unknown, meta?: LogMeta) => void): () => void;\n}): ServiceEvents<EventMap> {\n return {\n emit<E extends keyof EventMap & string>(event: E, payload: EventMap[E]): void {\n bus.emit(event, payload);\n },\n on<E extends keyof EventMap & string>(\n event: E,\n handler: (payload: EventMap[E]) => void,\n ): () => void {\n return bus.on(event, handler as (payload: unknown) => void);\n },\n };\n}\n\n// ============================================================================\n// Store Contract\n// ============================================================================\n\n/** Filter operator for store queries. */\nexport type StoreFilterOp =\n | \"==\"\n | \"!=\"\n | \"<\"\n | \"<=\"\n | \">\"\n | \">=\"\n | \"in\"\n | \"not-in\"\n | \"contains\";\n\n/** A single filter clause for store queries. */\nexport interface StoreFilter<T> {\n field: keyof T & string;\n op: StoreFilterOp;\n value: unknown;\n}\n\n/**\n * Database abstraction boundary. Services receive `StoreContract<T>`,\n * not raw database clients. Swappable per database engine.\n *\n * @example\n * ```typescript\n * interface LLMRequest { id: string; prompt: string; status: string }\n *\n * class FirestoreLLMRequestStore implements StoreContract<LLMRequest> {\n * async getById(id) { ... }\n * async create(data) { ... }\n * async update(id, data) { ... }\n * async delete(id) { ... }\n * async query(filters) { ... }\n * }\n * ```\n */\nexport interface StoreContract<T extends { id: string }> {\n getById(id: string): Promise<T | null>;\n create(data: Omit<T, \"id\">): Promise<T>;\n update(id: string, data: Partial<T>): Promise<T>;\n delete(id: string): Promise<void>;\n query(filters: StoreFilter<T>[]): Promise<T[]>;\n}\n\n// ============================================================================\n// Lazy Service (Singleton Pattern)\n// ============================================================================\n\n/**\n * Standardized singleton lifecycle. Replaces ad-hoc\n * `let x = null; export function getX()` patterns.\n *\n * @example\n * ```typescript\n * const llmClient = createLazyService(() => new LLMClient({ apiKey: process.env.LLM_KEY }));\n *\n * // In request handler:\n * const client = llmClient.get(); // created on first call, cached after\n *\n * // In test teardown:\n * llmClient.reset(); // next get() creates a fresh instance\n * ```\n */\nexport interface LazyService<T> {\n /** Get the singleton instance (creates on first call). */\n get(): T;\n /** Reset the singleton (next get() creates fresh). For test isolation. */\n reset(): void;\n}\n\n/**\n * Create a lazy singleton from a factory function.\n * \n * Creates a service that lazily initializes on first access and caches the instance.\n * Useful for expensive resources like database connections or API clients.\n * \n * @template T - The type of service to create\n * @param {() => T} factory - Factory function that creates the service instance\n * @returns {LazyService<T>} Lazy service with get() and reset() methods\n * \n * @example\n * const dbService = createLazyService(() => new DatabaseClient(config));\n * const db = dbService.get(); // Initializes on first call\n */\nexport function createLazyService<T>(factory: () => T): LazyService<T> {\n let instance: T | null = null;\n return {\n get(): T {\n if (instance === null) {\n instance = factory();\n }\n return instance;\n },\n reset(): void {\n instance = null;\n },\n };\n}\n","/**\n * Shared Intermediate Representation Types\n *\n * Unified IR types used by both the compiler and runtime.\n * This is the single source of truth for IR structures.\n *\n * @packageDocumentation\n */\n\nimport type { SExpr } from './expression.js';\nimport type { EntityRow, FieldValue } from './entity.js';\nimport type { AnyPatternConfig } from '@almadar/patterns';\n\n// ============================================================================\n// Transition Types\n// ============================================================================\n\n/**\n * Transition source state specification.\n * - string: Single state name (e.g., 'Idle')\n * - '*': Wildcard - matches any current state\n * - string[]: Array of states - matches any of the listed states\n */\nexport type TransitionFrom = string | '*' | string[];\n\n// ============================================================================\n// Field Types\n// ============================================================================\n\nexport interface ResolvedField {\n name: string;\n type: string;\n tsType: string;\n description?: string;\n default?: unknown;\n required: boolean;\n validation?: unknown;\n /** Enum values for enum or constrained string fields */\n values?: string[];\n /** Enum values (alias for values, for compatibility) */\n enumValues?: string[];\n /** Relation configuration for foreign key references */\n relation?: {\n entity: string;\n cardinality?: string;\n field?: string;\n };\n}\n\n// ============================================================================\n// Entity Types\n// ============================================================================\n\nexport interface ResolvedEntity {\n name: string;\n description?: string;\n icon?: string;\n collection: string;\n fields: ResolvedField[];\n\n /** Whether this entity only exists in runtime (not persisted to Firestore) */\n runtime?: boolean;\n\n /** Whether this is a singleton entity (only one instance exists) */\n singleton?: boolean;\n\n /** Whether this entity has pre-authored instances in the schema */\n hasInstances?: boolean;\n\n /** Pre-authored instances from the schema (seed data or static reference data) */\n instances?: EntityRow[];\n\n /** Default field values from schema (for spawning singletons) */\n defaults?: Record<string, FieldValue>;\n\n // Cross-references\n usedByTraits: string[];\n usedByPages: string[];\n}\n\nexport interface ResolvedEntityBinding {\n /** Binding name in code */\n name: string;\n\n /** Entity being bound */\n entity: ResolvedEntity;\n\n /** CRUD operations to generate */\n operations: ('list' | 'get' | 'create' | 'update' | 'delete')[];\n}\n\n// ============================================================================\n// Trait Types\n// ============================================================================\n\nexport interface ResolvedTraitState {\n name: string;\n isInitial: boolean;\n isFinal: boolean;\n}\n\nexport interface ResolvedTraitEvent {\n key: string;\n name: string;\n payload?: Record<string, string>;\n}\n\nexport interface ResolvedTraitTransition {\n /** Source state(s): string, '*' for wildcard, or array of states */\n from: TransitionFrom;\n to: string;\n event: string;\n guard?: SExpr;\n effects: SExpr[];\n}\n\nexport interface ResolvedTraitGuard {\n name: string;\n condition: SExpr;\n}\n\nexport interface ResolvedTraitTick {\n name: string;\n interval: number | 'frame';\n guard?: SExpr;\n effects: SExpr[];\n priority: number;\n appliesTo: string[];\n}\n\nexport interface ResolvedTraitListener {\n event: string;\n triggers: string;\n guard?: SExpr;\n}\n\nexport interface ResolvedTraitDataEntity {\n name: string;\n fields: ResolvedField[];\n runtime: boolean;\n singleton: boolean;\n}\n\n/**\n * UI binding for interaction traits - maps states to presentations\n */\nexport interface ResolvedTraitUIBinding {\n [stateName: string]: {\n /** Presentation type: modal, drawer, popover, inline, confirm-dialog */\n presentation: string;\n /** Content pattern(s) to render */\n content: AnyPatternConfig | AnyPatternConfig[];\n /** Presentation props */\n props?: {\n size?: string;\n position?: string;\n title?: string;\n closable?: boolean;\n width?: string;\n showProgress?: boolean;\n step?: number;\n totalSteps?: number;\n };\n };\n}\n\n/**\n * Fully resolved trait - expanded from schema OR library.\n * The compiler generates code from this structure universally,\n * without knowing which specific trait it is.\n */\nexport interface ResolvedTrait {\n /** Unique trait identifier */\n name: string;\n\n /** Human-readable description */\n description?: string;\n\n /** Where this trait came from */\n source: 'schema' | 'library' | 'inline';\n\n /** Category for organizing traits */\n category?: 'lifecycle' | 'temporal' | 'validation' | 'notification' | 'integration' | 'interaction' | 'agent' |\n 'game-core' | 'game-character' | 'game-ai' | 'game-combat' | 'game-items' | 'game-cards' | 'game-board' | 'game-puzzle';\n\n // State Machine (all optional - not all traits have state machines)\n states: ResolvedTraitState[];\n events: ResolvedTraitEvent[];\n transitions: ResolvedTraitTransition[];\n guards: ResolvedTraitGuard[];\n\n // Behavior\n ticks: ResolvedTraitTick[];\n\n // Communication\n listens: ResolvedTraitListener[];\n\n // Data\n dataEntities: ResolvedTraitDataEntity[];\n\n /**\n * Atom-declared linked entity. The atom (e.g. std-pagination)\n * declares which entity its `@entity.X` bindings resolve against\n * (e.g. `PagedItem`). Distinct from the call-site rebind on\n * `ResolvedTraitBinding.linkedEntity`, which a molecule may use\n * to override the atom's default. Either side may be undefined\n * for traits that don't bind any entity (pure interaction).\n */\n linkedEntity?: string;\n\n /**\n * The trait's DECLARED `config { }` schema (per-field\n * `{ type, default? }`). Drives `@config.X` substitution: each\n * field's `default` seeds the binding context behind any caller-\n * supplied call-site `config: { ... }` override on the trait\n * reference. Authored on the atom; flows through verbatim from\n * `Trait.config`.\n *\n * (Caller-supplied call-site overrides live on the page-trait\n * binding's `config: TraitConfig` — see `ResolvedTraitBinding`.)\n */\n config?: import('./trait.js').DeclaredTraitConfig;\n\n // UI Bindings for interaction traits\n ui?: ResolvedTraitUIBinding;\n}\n\n/**\n * Trait binding on a page - links a resolved trait to the page\n */\nexport interface ResolvedTraitBinding {\n /** Reference name */\n ref?: string;\n\n /** Fully resolved trait */\n trait: ResolvedTrait;\n\n /** Entity this trait operates on (if any) */\n linkedEntity?: string;\n\n /** Instance configuration */\n config?: import('./trait.js').TraitConfig;\n}\n\n// ============================================================================\n// Pattern & Section Types\n// ============================================================================\n\nexport interface ResolvedPattern {\n /** Pattern type (e.g., 'page-header', 'entity-list', 'game-canvas') */\n type: string;\n\n /** Pattern configuration */\n config: AnyPatternConfig;\n\n /** Shell component to use */\n shellComponent?: string;\n}\n\nexport interface ResolvedSectionEvent {\n event: string;\n action: string;\n target?: string;\n}\n\nexport interface ResolvedSection {\n /** Section identifier */\n id: string;\n\n /** Resolved pattern */\n pattern: ResolvedPattern;\n\n /** Events emitted by this section */\n events: ResolvedSectionEvent[];\n\n /** Position in page layout */\n position?: number;\n\n /** Entity binding for this section */\n binding?: ResolvedEntityBinding;\n}\n\n// ============================================================================\n// Page Types\n// ============================================================================\n\nexport interface ResolvedNavigation {\n event?: string;\n from?: string;\n to: string;\n trigger?: string;\n params?: Record<string, string>;\n label?: string;\n path?: string;\n icon?: string;\n}\n\nexport interface ResolvedPage {\n /** Page identifier */\n name: string;\n\n /** URL path */\n path: string;\n\n /** Feature folder name */\n featureName: string;\n\n /** Layout component */\n layout?: string;\n\n /** View type (dashboard, list, detail, create, edit) */\n viewType?: 'dashboard' | 'list' | 'detail' | 'create' | 'edit';\n\n /** Resolved sections */\n sections: ResolvedSection[];\n\n /** Resolved trait bindings */\n traits: ResolvedTraitBinding[];\n\n /** Entity data bindings */\n entityBindings: ResolvedEntityBinding[];\n\n /** Navigation wiring */\n navigation: ResolvedNavigation[];\n\n /** Singleton entities to spawn on this page (runtime singletons) */\n singletonEntities: ResolvedEntity[];\n}\n\n// ============================================================================\n// IR Types\n// ============================================================================\n\n/**\n * Complete resolved IR - all references expanded\n */\nexport interface ResolvedIR {\n /** App name */\n appName: string;\n\n /** App description */\n description?: string;\n\n /** App version */\n version?: string;\n\n /** All resolved entities (Map for lookup) */\n entities: Map<string, ResolvedEntity>;\n\n /** All resolved traits (Map for lookup) */\n traits: Map<string, ResolvedTrait>;\n\n /** All resolved pages (Map for lookup) */\n pages: Map<string, ResolvedPage>;\n\n /** Entity bindings (used for data hook generation) */\n entityBindings: ResolvedEntityBinding[];\n\n /** Raw data entities (used for instance data generation) */\n rawEntities?: unknown[];\n\n /** Generation timestamp */\n generatedAt: string;\n}\n\n// ============================================================================\n// Factory Functions\n// ============================================================================\n\n/**\n * Create an empty resolved trait with defaults\n */\nexport function createEmptyResolvedTrait(name: string, source: 'schema' | 'library' | 'inline'): ResolvedTrait {\n return {\n name,\n source,\n states: [],\n events: [],\n transitions: [],\n guards: [],\n ticks: [],\n listens: [],\n dataEntities: [],\n };\n}\n\n/**\n * Create an empty resolved page with defaults\n */\nexport function createEmptyResolvedPage(name: string): ResolvedPage {\n return {\n name,\n path: `/${name.toLowerCase()}`,\n featureName: name.toLowerCase(),\n sections: [],\n traits: [],\n entityBindings: [],\n navigation: [],\n singletonEntities: [],\n };\n}\n\n/**\n * Infer TypeScript type from schema type\n */\nexport function inferTsType(schemaType: string): string {\n const typeMap: Record<string, string> = {\n string: 'string',\n number: 'number',\n boolean: 'boolean',\n date: 'Date',\n datetime: 'Date',\n timestamp: 'number',\n array: 'unknown[]',\n object: 'Record<string, unknown>',\n any: 'unknown',\n };\n\n // Handle array types like \"string[]\"\n if (schemaType.endsWith('[]')) {\n const baseType = schemaType.slice(0, -2);\n return `${typeMap[baseType] || baseType}[]`;\n }\n\n // Handle the typed-map form `Map<K,V>` (the orbital `Map K V` type) →\n // `Record<K, V>`. Mirrors the Rust `parse_payload_field_type` map branch so\n // TS-land type derivation agrees with codegen. Key is comma-free (split on\n // the first comma; value may itself be `Map<…>`).\n if (schemaType.startsWith('Map<') && schemaType.endsWith('>')) {\n const inner = schemaType.slice(4, -1);\n const comma = inner.indexOf(',');\n if (comma !== -1) {\n const key = inferTsType(inner.slice(0, comma).trim());\n const value = inferTsType(inner.slice(comma + 1).trim());\n return `Record<${key}, ${value}>`;\n }\n }\n\n return typeMap[schemaType] || schemaType;\n}\n\n/**\n * Create a resolved field with TypeScript type inference\n */\nexport function createResolvedField(field: {\n name: string;\n type: string;\n description?: string;\n default?: unknown;\n required?: boolean;\n validation?: unknown;\n values?: string[];\n}): ResolvedField {\n return {\n name: field.name,\n type: field.type,\n tsType: inferTsType(field.type),\n description: field.description,\n default: field.default,\n required: field.required ?? false,\n validation: field.validation,\n values: field.values,\n };\n}\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\n/**\n * Type guard to check if an object is a ResolvedIR.\n * \n * Validates that an unknown value conforms to the ResolvedIR structure.\n * Checks for required properties and correct types. Used for runtime\n * type checking and validation.\n * \n * @param {unknown} ir - Value to check\n * @returns {boolean} True if value is ResolvedIR, false otherwise\n * \n * @example\n * if (isResolvedIR(schema)) {\n * // Type-safe access to ResolvedIR properties\n * console.log('Valid IR:', schema.appName);\n * }\n */\nexport function isResolvedIR(ir: unknown): ir is ResolvedIR {\n if (!ir || typeof ir !== 'object') return false;\n const r = ir as ResolvedIR;\n return typeof r.appName === 'string' && r.traits instanceof Map && r.pages instanceof Map;\n}\n","/**\n * JSON primitives — the universal \"data crossed a boundary\" type.\n *\n * Every value that arrives over the wire from an LLM (tool-call args),\n * from disk (workspace files), or from an HTTP body before\n * domain-specific validation is a `JsonValue`. Narrow with a typed\n * predicate (`is`-guard) at the boundary; don't widen back to `unknown`.\n *\n * `JsonObject` and `ToolArgs` are aliases for the common\n * `Record<string, JsonValue>` shape. `ToolArgs` is the name the\n * agent surface uses for LLM-emitted tool-call arguments; `JsonObject`\n * is the general-purpose alias. They are the same type — the alias\n * exists so call sites read at the right semantic level.\n *\n * Why not `Record<string, unknown>`? Two reasons. (1) `unknown` widens\n * back to anything, which defeats the purpose of typing the boundary.\n * (2) The `@almadar/eslint-plugin/no-record-string-unknown` rule blocks\n * the wider form — `JsonValue`-based records are the typed answer.\n *\n * @packageDocumentation\n */\n\n/**\n * Recursive JSON value union — every shape JSON can carry.\n */\nexport type JsonValue =\n | string\n | number\n | boolean\n | null\n | JsonValue[]\n | { [key: string]: JsonValue };\n\n/**\n * JSON object — keyed string→JsonValue. The wire form of arbitrary\n * structured data. Replaces `Record<string, unknown>` at typed\n * boundaries (LLM emits, file reads, HTTP bodies).\n */\nexport type JsonObject = { [key: string]: JsonValue };\n\n/**\n * LLM tool-call arguments — same shape as `JsonObject`, named for the\n * agent-surface call site. Each tool's `execute(args: ToolArgs)`\n * receives this and narrows via an `is`-guard predicate before any\n * field access.\n */\nexport type ToolArgs = JsonObject;\n\n/**\n * Type guard: is the given value a JSON primitive (non-array,\n * non-object)? Used by walkers that decide whether to recurse.\n */\nexport function isJsonPrimitive(\n value: JsonValue,\n): value is string | number | boolean | null {\n return (\n value === null\n || typeof value === 'string'\n || typeof value === 'number'\n || typeof value === 'boolean'\n );\n}\n\n/**\n * Type guard: is the given value a JSON object (non-array, non-null)?\n */\nexport function isJsonObject(value: JsonValue): value is JsonObject {\n return (\n value !== null\n && typeof value === 'object'\n && !Array.isArray(value)\n );\n}\n\n/**\n * Type guard: is the given value a JSON array?\n */\nexport function isJsonArray(value: JsonValue): value is JsonValue[] {\n return Array.isArray(value);\n}\n","/**\n * Validation error types — the shape emitted by every\n * `.orb` / `.lolo` validator pass.\n *\n * `ValidationError` is the wire shape: `{ code, path, message, suggestion? }`.\n * `code` is `ValidationErrorCode`, which is an OPEN `string` to let the\n * Rust validator emit new codes without an `@almadar/core` rev. The\n * `KNOWN_VALIDATION_ERROR_CODES` const documents the codes currently\n * emitted by the validator + lolo lower pipeline (extracted from\n * `orbital-rust/crates/orbital-compiler/src/phases/validation/` +\n * `orbital-rust/crates/orbital-lolo/src/`).\n *\n * Consumers that want to narrow a code to the closed known set use\n * `KnownValidationErrorCode`:\n *\n * ```ts\n * if (err.code in KNOWN_VALIDATION_ERROR_CODES) {\n * // err.code is now narrowable to KnownValidationErrorCode for\n * // exhaustive switch handling.\n * }\n * ```\n *\n * @packageDocumentation\n */\n\n/**\n * One validation diagnostic emitted by the validator / lolo lower pipeline.\n *\n * - `code`: machine-readable identifier (see `KNOWN_VALIDATION_ERROR_CODES`).\n * - `path`: JSON pointer-like path into the failing schema location,\n * e.g. `'orbitals[0].traits[2].stateMachine.transitions[1].effects[0]'`.\n * - `message`: human-readable description of the failure.\n * - `suggestion`: optional hint the validator may add to help the\n * author / LLM fix the issue.\n */\nexport interface ValidationError {\n code: ValidationErrorCode;\n path: string;\n message: string;\n suggestion?: string;\n}\n\n/**\n * Validation error code — open `string` for forward-compat with the\n * Rust validator's evolving code set. Narrow to the closed known set\n * via `KnownValidationErrorCode` when exhaustive handling is needed.\n */\nexport type ValidationErrorCode = string;\n\n/**\n * The result of a single validator pass: a boolean verdict plus the errors\n * and warnings (the validator wire shape, `ValidationError`).\n *\n * Distinct from `ValidationResults` (app.ts): that is the Firestore-persisted\n * app-document shape keyed on `ValidationIssue` (with `severity` + array path\n * + `validatedAt`). This `ValidationResult` is the in-process pass result keyed\n * on `ValidationError` (code + JSON-pointer string path + `suggestion`).\n * `ok === true` iff there are zero errors AND zero warnings.\n */\nexport interface ValidationResult {\n ok: boolean;\n errors: ValidationError[];\n warnings: ValidationError[];\n}\n\n/**\n * Closed set of validation codes the Rust validator + lolo lower\n * pipeline currently emit. Source-tagged: codes are extracted from\n * `orbital-rust/crates/orbital-compiler/src/phases/validation/**.rs`\n * and `orbital-rust/crates/orbital-lolo/src/**.rs`. Keep this in sync\n * with the Rust side; mismatches are caught by the Rust validator's\n * own unit tests, which assert the emitted code-set matches an\n * exported manifest.\n *\n * Categories (prefix → meaning):\n * - `ORB_BINDING_*` — binding (`@entity.X`, `@payload.Y`, ...) issues\n * - `ORB_E_*` / `ORB_EFF_*` / `ORB_EMIT_*` — entity / effect / emit\n * - `ORB_GEN_*` — generic / cross-cutting structure\n * - `ORB_O_*` / `ORB_P_*` / `ORB_S_*` / `ORB_SM_*` / `ORB_T_*` —\n * orbital / page / schema / state-machine / trait\n * - `ORB_QUERY_*` — query / search behaviors\n * - `ORB_RUI_*` — render-UI binding + prop validation\n * - `ORB_SLOT_*` — UI-slot conflict / contention\n * - `ORB_SVC_*` / `ORB_UI_*` — service / UI primitives\n * - `ORB_X_*` — cross-orbital constraints (listens, emits, IDs)\n */\nexport const KNOWN_VALIDATION_ERROR_CODES = {\n // Binding (`@entity.X`, `@payload.Y`, `@state.Z`, `@now`, ...)\n ORB_BINDING_ENTITY_FIELD_NEVER_SET: 'ORB_BINDING_ENTITY_FIELD_NEVER_SET',\n ORB_BINDING_ENTITY_FIELD_NOT_FOUND: 'ORB_BINDING_ENTITY_FIELD_NOT_FOUND',\n ORB_BINDING_INVALID_FIELD_NAME: 'ORB_BINDING_INVALID_FIELD_NAME',\n ORB_BINDING_INVALID_FORMAT: 'ORB_BINDING_INVALID_FORMAT',\n ORB_BINDING_INVALID_PATH: 'ORB_BINDING_INVALID_PATH',\n ORB_BINDING_NOW_NO_PATH: 'ORB_BINDING_NOW_NO_PATH',\n ORB_BINDING_PAYLOAD_FIELD_UNDECLARED: 'ORB_BINDING_PAYLOAD_FIELD_UNDECLARED',\n ORB_BINDING_PAYLOAD_IN_TICK: 'ORB_BINDING_PAYLOAD_IN_TICK',\n ORB_BINDING_PAYLOAD_TYPE_INCOMPATIBLE: 'ORB_BINDING_PAYLOAD_TYPE_INCOMPATIBLE',\n ORB_BINDING_SET_TARGET_MISSING_PATH: 'ORB_BINDING_SET_TARGET_MISSING_PATH',\n ORB_BINDING_STATE_NO_PATH: 'ORB_BINDING_STATE_NO_PATH',\n ORB_BINDING_TRAIT_CYCLE: 'ORB_BINDING_TRAIT_CYCLE',\n ORB_BINDING_TRAIT_INVALID_FORMAT: 'ORB_BINDING_TRAIT_INVALID_FORMAT',\n ORB_BINDING_TRAIT_INVALID_POSITION: 'ORB_BINDING_TRAIT_INVALID_POSITION',\n ORB_BINDING_TRAIT_MISSING_NAME: 'ORB_BINDING_TRAIT_MISSING_NAME',\n ORB_BINDING_TRAIT_SELF_REFERENCE: 'ORB_BINDING_TRAIT_SELF_REFERENCE',\n ORB_BINDING_TRAIT_UNKNOWN: 'ORB_BINDING_TRAIT_UNKNOWN',\n ORB_BINDING_UNKNOWN_ENTITY: 'ORB_BINDING_UNKNOWN_ENTITY',\n ORB_BINDING_UNKNOWN_ROOT: 'ORB_BINDING_UNKNOWN_ROOT',\n\n // Entity / field\n ORB_E_DUPLICATE_FIELD: 'ORB_E_DUPLICATE_FIELD',\n ORB_E_EMPTY_ENUM_VALUES: 'ORB_E_EMPTY_ENUM_VALUES',\n ORB_E_INVALID_FIELD_NAME: 'ORB_E_INVALID_FIELD_NAME',\n ORB_E_INVALID_FIELD_TYPE: 'ORB_E_INVALID_FIELD_TYPE',\n ORB_E_INVALID_RELATION: 'ORB_E_INVALID_RELATION',\n ORB_E_LITERAL_UNION_DEFAULT_MISMATCH: 'ORB_E_LITERAL_UNION_DEFAULT_MISMATCH',\n ORB_E_MISSING_COLLECTION: 'ORB_E_MISSING_COLLECTION',\n ORB_E_MISSING_NAME: 'ORB_E_MISSING_NAME',\n ORB_E_NO_FIELDS: 'ORB_E_NO_FIELDS',\n\n // Effect / emit\n ORB_EFF_CALL_SERVICE_MISSING_ACTION: 'ORB_EFF_CALL_SERVICE_MISSING_ACTION',\n ORB_EFF_CALL_SERVICE_MISSING_HANDLERS: 'ORB_EFF_CALL_SERVICE_MISSING_HANDLERS',\n ORB_EFF_CALL_SERVICE_MISSING_SERVICE: 'ORB_EFF_CALL_SERVICE_MISSING_SERVICE',\n ORB_EFF_EMIT_INVALID_NAME: 'ORB_EFF_EMIT_INVALID_NAME',\n ORB_EFF_EMIT_KEY_INVALID: 'ORB_EFF_EMIT_KEY_INVALID',\n ORB_EFF_EMIT_UNDECLARED_EVENT: 'ORB_EFF_EMIT_UNDECLARED_EVENT',\n ORB_EFF_FETCH_INVALID_ENTITY: 'ORB_EFF_FETCH_INVALID_ENTITY',\n ORB_EFF_FETCH_INVALID_INCLUDE: 'ORB_EFF_FETCH_INVALID_INCLUDE',\n ORB_EFF_MISSING_FETCH_FOR_ENTITY: 'ORB_EFF_MISSING_FETCH_FOR_ENTITY',\n ORB_EFF_MISSING_REQUIRED_EMIT: 'ORB_EFF_MISSING_REQUIRED_EMIT',\n ORB_EFF_NAVIGATE_MISSING_PAYLOAD: 'ORB_EFF_NAVIGATE_MISSING_PAYLOAD',\n ORB_EFF_NAVIGATE_TARGET_UNREACHABLE: 'ORB_EFF_NAVIGATE_TARGET_UNREACHABLE',\n ORB_EFF_SET_INVALID_BINDING: 'ORB_EFF_SET_INVALID_BINDING',\n ORB_EFF_SET_PAYLOAD_NOT_ALLOWED: 'ORB_EFF_SET_PAYLOAD_NOT_ALLOWED',\n ORB_EFF_SLOT_CONFLICT: 'ORB_EFF_SLOT_CONFLICT',\n ORB_EFF_UNKNOWN_TYPE: 'ORB_EFF_UNKNOWN_TYPE',\n ORB_EMIT_DECLARED_BUT_UNFIRED: 'ORB_EMIT_DECLARED_BUT_UNFIRED',\n ORB_EMIT_PAYLOAD_EXTRA_FIELD: 'ORB_EMIT_PAYLOAD_EXTRA_FIELD',\n ORB_EMIT_PAYLOAD_FIELD_TYPE_MISMATCH: 'ORB_EMIT_PAYLOAD_FIELD_TYPE_MISMATCH',\n ORB_EMIT_PAYLOAD_MISSING_REQUIRED: 'ORB_EMIT_PAYLOAD_MISSING_REQUIRED',\n ORB_EMIT_SUCCESS_PAYLOAD_RETURN_MISMATCH: 'ORB_EMIT_SUCCESS_PAYLOAD_RETURN_MISMATCH',\n\n // Generic / cross-cutting structure\n ORB_GEN_DUPLICATE: 'ORB_GEN_DUPLICATE',\n ORB_GEN_INVALID_REFERENCE: 'ORB_GEN_INVALID_REFERENCE',\n ORB_GEN_INVALID_VALUE: 'ORB_GEN_INVALID_VALUE',\n ORB_GEN_MISSING_FIELD: 'ORB_GEN_MISSING_FIELD',\n\n // Orbital\n ORB_O_MISSING_PAGES: 'ORB_O_MISSING_PAGES',\n\n // Page\n ORB_P_DUPLICATE_PATH: 'ORB_P_DUPLICATE_PATH',\n ORB_P_EMPTY_TRAITS: 'ORB_P_EMPTY_TRAITS',\n ORB_P_INVALID_PATH: 'ORB_P_INVALID_PATH',\n ORB_P_INVALID_TRAIT_REF: 'ORB_P_INVALID_TRAIT_REF',\n ORB_P_INVALID_VIEW_TYPE: 'ORB_P_INVALID_VIEW_TYPE',\n ORB_P_MISSING_NAME: 'ORB_P_MISSING_NAME',\n ORB_P_MISSING_PATH: 'ORB_P_MISSING_PATH',\n ORB_P_MISSING_TRAITS: 'ORB_P_MISSING_TRAITS',\n ORB_P_SECTIONS_FORBIDDEN: 'ORB_P_SECTIONS_FORBIDDEN',\n\n // Query / search behaviors\n ORB_QUERY_MISSING_RECOMMENDED: 'ORB_QUERY_MISSING_RECOMMENDED',\n ORB_QUERY_MISSING_SEARCH: 'ORB_QUERY_MISSING_SEARCH',\n ORB_QUERY_UNKNOWN_SINGLETON: 'ORB_QUERY_UNKNOWN_SINGLETON',\n ORB_QUERY_UNSUPPORTED_PATTERN: 'ORB_QUERY_UNSUPPORTED_PATTERN',\n ORB_QUERY_UNUSED_SINGLETON: 'ORB_QUERY_UNUSED_SINGLETON',\n\n // Render-UI binding + prop validation\n ORB_RUI_BINDING_TYPE_MISMATCH: 'ORB_RUI_BINDING_TYPE_MISMATCH',\n ORB_RUI_ELEMENT_SHAPE_MISMATCH: 'ORB_RUI_ELEMENT_SHAPE_MISMATCH',\n ORB_RUI_EVENT_BINDING_PAYLOAD_MISMATCH: 'ORB_RUI_EVENT_BINDING_PAYLOAD_MISMATCH',\n ORB_RUI_INVALID_FIELD_PATH: 'ORB_RUI_INVALID_FIELD_PATH',\n ORB_RUI_INVALID_ITEM_ACTION: 'ORB_RUI_INVALID_ITEM_ACTION',\n ORB_RUI_INVALID_PATTERN: 'ORB_RUI_INVALID_PATTERN',\n ORB_RUI_INVALID_PROP: 'ORB_RUI_INVALID_PROP',\n ORB_RUI_INVALID_SLOT: 'ORB_RUI_INVALID_SLOT',\n ORB_RUI_MISSING_ACTION: 'ORB_RUI_MISSING_ACTION',\n ORB_RUI_MISSING_PATTERN_TYPE: 'ORB_RUI_MISSING_PATTERN_TYPE',\n ORB_RUI_MISSING_REQUIRED_PROP: 'ORB_RUI_MISSING_REQUIRED_PROP',\n ORB_RUI_PROP_TYPE_MISMATCH: 'ORB_RUI_PROP_TYPE_MISMATCH',\n ORB_RUI_UNKNOWN_ITEM_ACTION_PROP: 'ORB_RUI_UNKNOWN_ITEM_ACTION_PROP',\n\n // Schema-level\n ORB_S_EMPTY_VERSION: 'ORB_S_EMPTY_VERSION',\n ORB_S_MISSING_NAME: 'ORB_S_MISSING_NAME',\n ORB_S_NO_ORBITALS: 'ORB_S_NO_ORBITALS',\n\n // UI slots\n ORB_SLOT_CONTENTION: 'ORB_SLOT_CONTENTION',\n ORB_SLOT_CONTENTION_RUNTIME: 'ORB_SLOT_CONTENTION_RUNTIME',\n ORB_SLOT_HUD_NON_GAME: 'ORB_SLOT_HUD_NON_GAME',\n ORB_SLOT_INVALID_NAME: 'ORB_SLOT_INVALID_NAME',\n ORB_SLOT_INVALID_NESTING: 'ORB_SLOT_INVALID_NESTING',\n ORB_SLOT_MAIN_NOT_COVERED: 'ORB_SLOT_MAIN_NOT_COVERED',\n ORB_SLOT_PRIORITY_CONFLICT: 'ORB_SLOT_PRIORITY_CONFLICT',\n\n // Service\n ORB_SVC_DUPLICATE_NAME: 'ORB_SVC_DUPLICATE_NAME',\n ORB_SVC_INVALID_INTEGRATOR: 'ORB_SVC_INVALID_INTEGRATOR',\n ORB_SVC_INVALID_URL: 'ORB_SVC_INVALID_URL',\n ORB_SVC_MISSING_BASE_URL: 'ORB_SVC_MISSING_BASE_URL',\n ORB_SVC_MISSING_CAPABILITIES: 'ORB_SVC_MISSING_CAPABILITIES',\n ORB_SVC_MISSING_EVENTS: 'ORB_SVC_MISSING_EVENTS',\n ORB_SVC_MISSING_SERVER_PATH: 'ORB_SVC_MISSING_SERVER_PATH',\n ORB_SVC_RESERVED_EVENT: 'ORB_SVC_RESERVED_EVENT',\n ORB_SVC_UNKNOWN_TYPE: 'ORB_SVC_UNKNOWN_TYPE',\n\n // Trait\n ORB_T_CONFIG_OBJECT_ARRAY_FORBIDDEN: 'ORB_T_CONFIG_OBJECT_ARRAY_FORBIDDEN',\n ORB_T_CONFIG_SHAPE_MISMATCH: 'ORB_T_CONFIG_SHAPE_MISMATCH',\n ORB_T_CONFIG_TIER_INVALID: 'ORB_T_CONFIG_TIER_INVALID',\n ORB_T_DEPRECATED_UI: 'ORB_T_DEPRECATED_UI',\n ORB_T_DUPLICATE_NAME: 'ORB_T_DUPLICATE_NAME',\n ORB_T_DUPLICATE_STATE: 'ORB_T_DUPLICATE_STATE',\n ORB_T_DUPLICATE_TRANSITION: 'ORB_T_DUPLICATE_TRANSITION',\n ORB_T_ENTITY_NAME_SHADOWS_TRAIT_UNION: 'ORB_T_ENTITY_NAME_SHADOWS_TRAIT_UNION',\n ORB_T_EVENT_TYPE_WRONG_KIND: 'ORB_T_EVENT_TYPE_WRONG_KIND',\n ORB_T_EVT_DUPLICATE: 'ORB_T_EVT_DUPLICATE',\n ORB_T_EVT_EXTERNAL_MISSING_PAYLOAD: 'ORB_T_EVT_EXTERNAL_MISSING_PAYLOAD',\n ORB_T_EVT_INVALID_NAME: 'ORB_T_EVT_INVALID_NAME',\n ORB_T_EVT_SCOPE_MISMATCH: 'ORB_T_EVT_SCOPE_MISMATCH',\n ORB_T_EVT_TICK_UNDECLARED: 'ORB_T_EVT_TICK_UNDECLARED',\n ORB_T_EVT_UNDECLARED: 'ORB_T_EVT_UNDECLARED',\n ORB_T_INIT_MISSING_FETCH: 'ORB_T_INIT_MISSING_FETCH',\n ORB_T_INVALID_CATEGORY: 'ORB_T_INVALID_CATEGORY',\n ORB_T_INVALID_FORMAT: 'ORB_T_INVALID_FORMAT',\n ORB_T_INVALID_PATTERN_DEFAULT: 'ORB_T_INVALID_PATTERN_DEFAULT',\n ORB_T_INVALID_SLOT_DEFAULT: 'ORB_T_INVALID_SLOT_DEFAULT',\n ORB_T_INVALID_TRANSITION: 'ORB_T_INVALID_TRANSITION',\n ORB_T_MISSING_INIT_TRANSITION: 'ORB_T_MISSING_INIT_TRANSITION',\n ORB_T_MISSING_RENDER_UI: 'ORB_T_MISSING_RENDER_UI',\n ORB_T_MULTIPLE_INITIAL_STATES: 'ORB_T_MULTIPLE_INITIAL_STATES',\n ORB_T_NO_INITIAL_STATE: 'ORB_T_NO_INITIAL_STATE',\n ORB_T_TYPE_ANNOTATION_MISMATCH: 'ORB_T_TYPE_ANNOTATION_MISMATCH',\n ORB_T_TYPE_COMPOSITION_CONFLICT: 'ORB_T_TYPE_COMPOSITION_CONFLICT',\n ORB_T_TYPE_CYCLE: 'ORB_T_TYPE_CYCLE',\n ORB_T_TYPE_KIND_MISMATCH: 'ORB_T_TYPE_KIND_MISMATCH',\n ORB_T_TYPE_UNKNOWN: 'ORB_T_TYPE_UNKNOWN',\n ORB_T_TYPE_UNKNOWN_PARAM: 'ORB_T_TYPE_UNKNOWN_PARAM',\n ORB_T_TYPE_WRONG_ARG_COUNT: 'ORB_T_TYPE_WRONG_ARG_COUNT',\n ORB_T_UNDEFINED_EVENT: 'ORB_T_UNDEFINED_EVENT',\n ORB_T_UNDEFINED_TRAIT: 'ORB_T_UNDEFINED_TRAIT',\n\n // UI primitives (icons, etc.)\n ORB_UI_ICON_EMPTY: 'ORB_UI_ICON_EMPTY',\n ORB_UI_ICON_INVALID_FORMAT: 'ORB_UI_ICON_INVALID_FORMAT',\n ORB_UI_ICON_NOT_FOUND: 'ORB_UI_ICON_NOT_FOUND',\n\n // Cross-orbital constraints (listens, emits, IDs, payloads)\n ORB_X_CIRCULAR_DEPENDENCY: 'ORB_X_CIRCULAR_DEPENDENCY',\n ORB_X_CROSS_EMITTER_DECLARED_PAYLOAD_MISMATCH: 'ORB_X_CROSS_EMITTER_DECLARED_PAYLOAD_MISMATCH',\n ORB_X_DUPLICATE_ENTITY: 'ORB_X_DUPLICATE_ENTITY',\n ORB_X_EVENT_COLLISION: 'ORB_X_EVENT_COLLISION',\n ORB_X_INTERNAL_EVENT_EXPOSED: 'ORB_X_INTERNAL_EVENT_EXPOSED',\n ORB_X_LISTEN_SOURCE_UNRESOLVED: 'ORB_X_LISTEN_SOURCE_UNRESOLVED',\n ORB_X_MISSING_ORBITAL_NAME: 'ORB_X_MISSING_ORBITAL_NAME',\n ORB_X_ORPHAN_LISTENER: 'ORB_X_ORPHAN_LISTENER',\n ORB_X_PAYLOAD_MISMATCH: 'ORB_X_PAYLOAD_MISMATCH',\n ORB_X_RENDER_UI_EVENT_LITERAL_STALE: 'ORB_X_RENDER_UI_EVENT_LITERAL_STALE',\n ORB_X_UNRESOLVED_PATTERN_FIELD_REF: 'ORB_X_UNRESOLVED_PATTERN_FIELD_REF',\n ORB_X_UNUSED_EMISSION: 'ORB_X_UNUSED_EMISSION',\n} as const;\n\n/**\n * Narrow union of the codes documented in `KNOWN_VALIDATION_ERROR_CODES`.\n * Use this in exhaustive `switch` handlers; use the broader\n * `ValidationErrorCode` (open `string`) anywhere a fresh validator-side\n * code could plausibly arrive.\n */\nexport type KnownValidationErrorCode =\n typeof KNOWN_VALIDATION_ERROR_CODES[keyof typeof KNOWN_VALIDATION_ERROR_CODES];\n\n/**\n * Type guard: is the given code a known one? After the guard returns\n * true, the code can be narrowed to `KnownValidationErrorCode` via a\n * separate cast, because the type system can't track `in` against\n * `as const` records without an explicit narrowing helper.\n */\nexport function isKnownValidationErrorCode(\n code: ValidationErrorCode,\n): boolean {\n return code in KNOWN_VALIDATION_ERROR_CODES;\n}\n","/**\n * Living Orbital Schema — Golden Data Structure type system.\n *\n * The Living layer treats an `OrbitalSchema` as a heterogeneous attributed\n * graph: every vertex (orbital, entity, trait, state, transition, page, field,\n * event, effect, config-knob) carries a `SemanticAnnotation` + an embedding\n * vector, and the whole object can embed / validate / compile / similarity-\n * search / evolve itself. These are the canonical TYPE definitions shared by\n * the masar (Python) implementation and any TS implementation (rabit, Phase 5);\n * the numeric implementation lives outside @almadar/core.\n *\n * See `docs/Almadar_Masar_Golden_Data_Structure.md` §II/§III/§VIII. Existing\n * core vocabulary is reused, never re-defined: `SchemaChange`/`SemanticChangeKind`\n * (changeset.ts) back the evolution delta, `ValidationError`/`ValidationResult`\n * (validation.ts) back `validate()`, and the per-vertex payloads ARE the existing\n * structural types.\n *\n * @packageDocumentation\n */\n\nimport type { OrbitalSchema } from \"./schema.js\";\nimport type { OrbitalDefinition } from \"./orbital.js\";\nimport type { Entity } from \"./entity.js\";\nimport type { EntityField } from \"./field.js\";\nimport type { Trait, TraitConfigValue, ConfigFieldDeclaration } from \"./trait.js\";\nimport type { State, Transition, Event } from \"./state-machine.js\";\nimport type { Page } from \"./page.js\";\nimport type { Effect } from \"./effect.js\";\nimport type { SExpr, EvalContext, EventPayload } from \"./expression.js\";\nimport type { SchemaChange } from \"./changeset.js\";\nimport type { ValidationError, ValidationResult } from \"./validation.js\";\n// Type-only import (erased at build): no runtime cycle even though factory/\n// imports from types/. `AnnotationTier` is the documented superset of this.\nimport type { FactoryConfigTier } from \"../factory/types.js\";\n\n// ============================================================================\n// Semantic annotation (the NL → typed bridge)\n// ============================================================================\n\n/**\n * Decision-kind tier for the annotation layer. SUPERSET of the validator-\n * enforced `FactoryConfigTier` (`domain`/`policy`/`infra`/`presentation`/\n * `internal`), adding `essential` and `customization` for non-knob (event)\n * vertices that still carry the old vocabulary. Every `FactoryConfigTier`\n * value must be a member so `widenTier` stays a valid identity widen.\n */\nexport type AnnotationTier =\n | \"essential\"\n | \"domain\"\n | \"policy\"\n | \"infra\"\n | \"presentation\"\n | \"customization\"\n | \"internal\";\n\n/** Widen a knob's `FactoryConfigTier` into the annotation-layer `AnnotationTier`. */\nexport function widenTier(tier: FactoryConfigTier): AnnotationTier {\n return tier;\n}\n\n/**\n * The natural-language metadata attached to every living vertex — the text that\n * gets embedded for `similar()`/`match_intent()`. Today these four members live\n * scattered inline across core types (`EntityField.description`/`synonyms`,\n * `Event`/`TraitEventContract`.`description`/`synonyms`/`tier`,\n * `FactoryConfigParam.label`/`description`/`synonyms`/`tier`); `SemanticAnnotation`\n * is the uniform bundle of them, generalized to every vertex.\n */\nexport interface SemanticAnnotation {\n description: string;\n synonyms: string[];\n label: string;\n tier: AnnotationTier;\n}\n\n// ============================================================================\n// ML scalar/vector aliases\n// ============================================================================\n\n/**\n * A dense semantic embedding. In-memory form is `Float32Array`; the at-rest\n * JSON form (e.g. rabit's `knob-embeddings.json`) is `number[]`.\n */\nexport type SemanticVector = Float32Array;\n\n/** A probability in `[0, 1]`. */\nexport type Probability = number;\n\n/** Whether a semantic gate's transition is open, closed, or ~0.5 ambiguous. */\nexport type GateState = \"open\" | \"closed\" | \"ambiguous\";\n\n// ============================================================================\n// Graph vertex / edge typing\n// ============================================================================\n\n/** The typed vertex kinds of the living attributed graph (§II.1 `V_*`). */\nexport type VertexType =\n | \"orbital\"\n | \"entity\"\n | \"trait\"\n | \"state\"\n | \"transition\"\n | \"page\"\n | \"field\"\n | \"event\"\n | \"effect\"\n | \"value\";\n\n/**\n * A stable, structural, embedding-independent vertex id (path style, e.g.\n * `orb:Cart/trt:AddItem/st:Open`). Re-embedding never changes it.\n */\nexport type VertexId = string;\n\n/** The typed directed edge kinds of the living attributed graph (§II.1 `E_*`). */\nexport type EdgeType =\n | \"belongs_to\"\n | \"has_trait\"\n | \"has_state\"\n | \"has_transition\"\n | \"from_state\"\n | \"to_state\"\n | \"on_event\"\n | \"emits\"\n | \"listens\"\n | \"cross_orbital\"\n | \"has_effect\"\n | \"effect_seq\"\n | \"data_flow\"\n | \"ref_in_effect\"\n | \"has_page\"\n | \"has_field\"\n | \"ref\";\n\n/**\n * An effect vertex's payload. Effects are positional S-expression tuples\n * (`Effect`), so the synthesized coordinates (operator, owning transition,\n * positional index) carry the addressing the raw tuple lacks.\n */\nexport interface EffectPayload {\n sexpr: Effect;\n operator: string;\n transitionId: VertexId;\n index: number;\n}\n\n/**\n * A config-knob vertex's payload — joins a `Trait.config` dict key with its\n * declaration (no single core type carries both).\n */\nexport interface KnobPayload {\n name: string;\n declaration: ConfigFieldDeclaration;\n traitId: VertexId;\n}\n\n/** The union of every kind of vertex payload (the existing structural types). */\nexport type VertexPayload =\n | OrbitalDefinition\n | Entity\n | Trait\n | State\n | Transition\n | Page\n | EntityField\n | Event\n | EffectPayload\n | KnobPayload;\n\n/**\n * One vertex of the living graph: a structural payload plus its annotation and\n * embedding. Identity is `id` (structural); annotation/embedding are derived.\n */\nexport interface LivingVertex<P extends VertexPayload = VertexPayload> {\n id: VertexId;\n vtype: VertexType;\n payload: P;\n annotation: SemanticAnnotation;\n /** Lazily populated — undefined until the schema's `embed()` runs. */\n embedding?: SemanticVector;\n}\n\nexport type LivingOrbital = LivingVertex<OrbitalDefinition>;\nexport type LivingEntity = LivingVertex<Entity>;\nexport type LivingTrait = LivingVertex<Trait>;\nexport type LivingState = LivingVertex<State>;\nexport type LivingTransition = LivingVertex<Transition>;\nexport type LivingPage = LivingVertex<Page>;\nexport type LivingField = LivingVertex<EntityField>;\nexport type LivingEvent = LivingVertex<Event>;\nexport type LivingEffect = LivingVertex<EffectPayload>;\nexport type LivingValue = LivingVertex<KnobPayload>;\n\n/**\n * One directed edge. `via` carries the transition vertex for the ternary\n * `has_transition(from, via, to)` decomposition; `seq` carries the ordering for\n * `effect_seq`.\n */\nexport interface LivingEdge {\n etype: EdgeType;\n src: VertexId;\n dst: VertexId;\n via?: VertexId;\n seq?: number;\n}\n\n// ============================================================================\n// Evolution + lineage (composes changeset.ts vocabulary)\n// ============================================================================\n\n/**\n * A single evolution step over the living graph. `modified` reuses the canonical\n * `SchemaChange` (changeset.ts) rather than inventing a parallel operation enum;\n * `intent` is the natural-language delta that caused the change.\n */\nexport interface EvolutionDelta {\n added: VertexId[];\n removed: VertexId[];\n modified: SchemaChange[];\n intent: string;\n}\n\n/** One immutable entry in a living schema's evolution lineage (§6.2). */\nexport interface LineageEntry {\n root: string;\n parent: string;\n delta: EvolutionDelta;\n intent: string;\n time: number;\n valid: boolean;\n}\n\n// ============================================================================\n// Effect-simulation results\n// ============================================================================\n\n/** The result of simulating one effect's S-expression (§4.6) — pure, no I/O. */\nexport interface EffectResult {\n result: SExpr;\n sideEffects: string[];\n emittedEvents: string[];\n}\n\n// ============================================================================\n// The living schema contract (§VIII) — implemented by masar (Python) + rabit (TS)\n// ============================================================================\n\n/**\n * The operation surface of a living orbital schema. This interface is the shared\n * CONTRACT; the numeric implementation (embedding, cosine, validator shelling)\n * is language-specific. `compile()` is the bridge back to the canonical\n * `OrbitalSchema` (the ML surface — annotations beyond `description`, embeddings,\n * gates — is stripped).\n */\nexport interface LivingOrbitalSchema {\n // Orbital container\n orbitals: LivingOrbital[];\n addOrbital(name: string): LivingOrbital;\n removeOrbital(name: string): void;\n getOrbital(name: string): LivingOrbital;\n\n // Semantic layer\n annotations: Map<VertexId, SemanticAnnotation>;\n embeddings: Map<VertexId, SemanticVector>;\n\n // Structural operations\n embed(): void;\n compile(): OrbitalSchema;\n validate(): ValidationResult;\n\n // Semantic retrieval\n similar(query: string | SemanticVector, k: number, type?: VertexType): LivingVertex[];\n matchIntent(intent: string, threshold?: number): { vertex: LivingVertex; score: number }[];\n\n // Predictive operations\n predictConfig(intent: string, trait: Trait): Record<string, TraitConfigValue>;\n predictPresence(intent: string): Set<string>;\n suggestOrbital(intent: string): LivingOrbital[];\n suggestEntity(intent: string): LivingEntity[];\n suggestTrait(intent: string): LivingTrait[];\n\n // Evolution\n evolve(intentDelta: string): LivingOrbitalSchema;\n compose(other: LivingOrbitalSchema): LivingOrbitalSchema;\n repair(errors: ValidationError[]): LivingOrbitalSchema;\n\n // Cross-orbital wiring\n wireEvents(source: LivingEvent, target: LivingEvent): void;\n findWiringGaps(): LivingEvent[];\n\n // Effect simulation\n simulateEffect(effect: LivingEffect, context: EvalContext): EffectResult;\n simulateInteraction(effect: LivingEffect, path: string[]): { event: LivingEvent; payload: EventPayload };\n traceDataFlow(transition: LivingTransition, inputEntity: LivingEntity): LivingEffect[];\n\n // Gates\n evaluateGates(intentEmbedding: SemanticVector): Map<VertexId, GateState[]>;\n sampleTrajectory(intentEmbedding: SemanticVector, steps: number): LivingVertex[];\n\n // Lineage\n lineage: LineageEntry[];\n checkout(hash: string): LivingOrbitalSchema;\n diff(hash1: string, hash2: string): EvolutionDelta;\n}\n","/**\n * Render-UI structural editing — the single canonical pattern-tree navigator,\n * mutators, and overlay application. Promoted out of apps/builder so the studio\n * client, rabit's contextual-edit path, and the overlay replay share ONE\n * implementation (no shadow copies).\n *\n * Operates on the SERIALIZABLE structural pattern node — the resolved `.orb`\n * render-ui shape (`{ type, children, ...props }`, props are strings/numbers/\n * booleans/bindings/arrays). It never holds function-typed props: those exist\n * only in the React-component `AnyPatternConfig`, never in resolved IR. A node\n * to insert/swap is built as a structural literal and validated against the\n * pattern registry by the caller — `AnyPatternConfig` is never assigned in.\n */\n\nimport type { OrbitalDefinition, Trait, Effect } from './types/index.js';\n\n// ----------------------------------------------------------------------------\n// Structural pattern node\n// ----------------------------------------------------------------------------\n\n/** A serializable value inside a render-ui pattern node. No functions. */\nexport type PatternValue =\n | string\n | number\n | boolean\n | Date\n | null\n | undefined\n | PatternNode\n | readonly PatternValue[];\n\n/** One node in a render-ui pattern tree as it appears in resolved `.orb`. */\nexport interface PatternNode {\n type?: string;\n children?: PatternNode[];\n [prop: string]: PatternValue | PatternNode[] | undefined;\n}\n\n// ----------------------------------------------------------------------------\n// EditFocus — a canvas selection resolved to an address in the resolved `.orb`\n// ----------------------------------------------------------------------------\n\nexport type EditFocusLevel =\n | 'node'\n | 'slot'\n | 'field'\n | 'effect'\n | 'trait'\n | 'page'\n | 'orbital';\n\n/** A pointed-at element. Plain data — constructible with or without a DOM. */\nexport interface EditFocus {\n level: EditFocusLevel;\n orbital: string;\n trait?: string;\n transition?: string;\n state?: string;\n slot?: string;\n path?: string;\n patternType?: string;\n entity?: string;\n source?: string;\n label: string;\n}\n\n// ----------------------------------------------------------------------------\n// RenderUiPatch — a structural render-ui edit, replayed after factory expansion\n// ----------------------------------------------------------------------------\n\nexport type RenderUiPatchOp = 'replace' | 'insert' | 'remove' | 'set-prop' | 'rebind';\n\nexport interface RenderUiPatchAddress {\n trait: string;\n transition: string;\n state?: string;\n slot: string;\n /** patternPath, e.g. `root.children.2`. For `insert`, the PARENT path. */\n path: string;\n}\n\nexport interface RenderUiPatch {\n op: RenderUiPatchOp;\n address: RenderUiPatchAddress;\n /** Structural fingerprint of the pre-edit node, used to re-anchor the patch\n * if a later factory rebuild shifts `address.path`. */\n fingerprint?: string;\n /** For `replace` / `insert`: the concrete node to place. */\n node?: PatternNode;\n /** For `insert`: index within the parent's children (default: append). */\n index?: number;\n /** For `set-prop` / `rebind`: the prop key. */\n prop?: string;\n /** For `set-prop`: the new value. For `rebind`: pass the binding via `value`. */\n value?: PatternValue;\n}\n\n// ----------------------------------------------------------------------------\n// Pure node primitives\n// ----------------------------------------------------------------------------\n\n/** Navigate a dot-separated path (`root`, `root.children.0`, …) to a node. */\nexport function navigatePatternPath(root: PatternNode, path: string): PatternNode | null {\n if (!path || path === 'root') return root;\n const parts = path.split('.');\n let current: PatternValue | PatternNode | readonly PatternValue[] | undefined = root;\n for (const part of parts) {\n if (current === null || current === undefined || typeof current !== 'object') return null;\n if (Array.isArray(current)) {\n const idx = Number.parseInt(part, 10);\n if (Number.isNaN(idx) || idx < 0 || idx >= current.length) return null;\n current = current[idx];\n } else {\n const record = current as PatternNode;\n if (part === 'children' && Array.isArray(record.children)) {\n current = record.children;\n } else {\n current = record[part];\n }\n }\n }\n return typeof current === 'object' && current !== null && !Array.isArray(current)\n ? (current as PatternNode)\n : null;\n}\n\nfunction splitChildPath(path: string): { parentPath: string; index: number } | null {\n const lastDot = path.lastIndexOf('.');\n if (lastDot === -1) return null;\n const index = Number.parseInt(path.slice(lastDot + 1), 10);\n if (Number.isNaN(index)) return null;\n return { parentPath: path.slice(0, lastDot), index };\n}\n\n/** Set a prop on the node at `path`. Returns false if the path misses. */\nexport function setPropAtPath(\n root: PatternNode,\n path: string,\n prop: string,\n value: PatternValue,\n): boolean {\n const node = navigatePatternPath(root, path);\n if (!node) return false;\n node[prop] = value;\n return true;\n}\n\n/** Replace the node at a child path (`<parent>.children.<i>`) with `node`. */\nexport function replaceChildAtPath(root: PatternNode, path: string, node: PatternNode): boolean {\n const split = splitChildPath(path);\n if (!split) return false;\n const parent = navigatePatternPath(root, split.parentPath);\n if (!parent || !Array.isArray(parent.children)) return false;\n if (split.index < 0 || split.index >= parent.children.length) return false;\n parent.children[split.index] = node;\n return true;\n}\n\n/** Insert `node` into the parent's `children` at `index` (clamped to end). */\nexport function insertChildAtPath(\n root: PatternNode,\n parentPath: string,\n index: number,\n node: PatternNode,\n): boolean {\n const parent = navigatePatternPath(root, parentPath);\n if (!parent) return false;\n const children = parent.children ?? [];\n const i = index < 0 || index > children.length ? children.length : index;\n children.splice(i, 0, node);\n parent.children = children;\n return true;\n}\n\n/** Remove the node at a child path. */\nexport function removeChildAtPath(root: PatternNode, path: string): boolean {\n const split = splitChildPath(path);\n if (!split) return false;\n const parent = navigatePatternPath(root, split.parentPath);\n if (!parent || !Array.isArray(parent.children)) return false;\n if (split.index < 0 || split.index >= parent.children.length) return false;\n parent.children.splice(split.index, 1);\n return true;\n}\n\n/** Replace a node's contents in place (used to swap the render-ui root). */\nfunction replaceNodeInPlace(target: PatternNode, source: PatternNode): void {\n for (const key of Object.keys(target)) {\n delete target[key];\n }\n Object.assign(target, source);\n}\n\n// ----------------------------------------------------------------------------\n// Fingerprint (re-anchor)\n// ----------------------------------------------------------------------------\n\nfunction stableValue(value: PatternValue | PatternNode[] | undefined): string {\n if (value === undefined) return 'u';\n if (value === null) return 'n';\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n return JSON.stringify(value);\n }\n if (value instanceof Date) return value.toISOString();\n if (Array.isArray(value)) return `[${value.map(stableValue).join(',')}]`;\n const nodeType = 'type' in value ? value.type : undefined;\n return `{${typeof nodeType === 'string' ? nodeType : ''}}`;\n}\n\n/** Deterministic structural fingerprint of a node (excludes child contents;\n * identifies the base node so a patch can re-anchor after a path shift). */\nexport function fingerprintNode(node: PatternNode): string {\n const props = Object.keys(node)\n .filter((k) => k !== 'children')\n .sort()\n .map((k) => `${k}=${stableValue(node[k])}`)\n .join(',');\n const childCount = Array.isArray(node.children) ? node.children.length : 0;\n return `t:${node.type ?? ''}|${props}|c:${childCount}`;\n}\n\nfunction findByFingerprint(node: PatternNode, path: string, fp: string): string | null {\n if (fingerprintNode(node) === fp) return path;\n if (Array.isArray(node.children)) {\n for (let i = 0; i < node.children.length; i++) {\n const r = findByFingerprint(node.children[i], `${path}.children.${i}`, fp);\n if (r) return r;\n }\n }\n return null;\n}\n\n// ----------------------------------------------------------------------------\n// Overlay application\n// ----------------------------------------------------------------------------\n\nexport interface RenderOverlayResult {\n applied: number;\n /** Patches whose target node could not be resolved (path gone + fingerprint\n * unmatched). Surfaced as `patch_stale` — never silently dropped. */\n stale: RenderUiPatch[];\n}\n\n/** A render-ui effect's slot + root pattern node, validated from the canonical\n * `Effect` tuple. The `['render-ui', slot, config]` form carries the structural\n * pattern node at index 2 in resolved `.orb`; we narrow `Effect` by its tag and\n * validate the payload is a concrete node (not a `@binding` string or null). */\nfunction readRenderUi(eff: Effect): { slot: string; node: PatternNode } | null {\n if (eff[0] !== 'render-ui') return null;\n const slot = eff[1];\n const config = eff[2];\n if (typeof slot !== 'string') return null;\n if (config === null || typeof config !== 'object' || Array.isArray(config)) return null;\n return { slot, node: config as PatternNode };\n}\n\n/** Narrow a trait reference to an inline `Trait` (the only `TraitRef` member\n * with a `stateMachine`). No cast — `in` narrows the union. */\nfunction asInlineTrait(ref: OrbitalDefinition['traits'][number]): Trait | null {\n if (typeof ref === 'object' && ref !== null && 'stateMachine' in ref) {\n return ref;\n }\n return null;\n}\n\n/** Find the render-ui root node for a patch address. Prefers the exact\n * transition match; falls back to the first trait+slot render-ui when the\n * transition is unknown (canvas selections at INIT carry no data-orb-transition,\n * so `address.transition` is empty and no real transition can match). */\nfunction findRenderUiRoot(\n orbital: OrbitalDefinition,\n address: RenderUiPatchAddress,\n): PatternNode | null {\n const wantTransition = address.transition !== '';\n const wantState = address.state !== undefined && address.state !== '';\n let fallback: PatternNode | null = null;\n for (const ref of orbital.traits) {\n const trait = asInlineTrait(ref);\n if (!trait || trait.name !== address.trait) continue;\n for (const t of trait.stateMachine?.transitions ?? []) {\n if (wantState && t.from !== address.state) continue;\n for (const eff of t.effects ?? []) {\n const ru = readRenderUi(eff);\n if (!ru || ru.slot !== address.slot) continue;\n if (wantTransition && t.event === address.transition) return ru.node;\n fallback ??= ru.node;\n }\n }\n }\n return fallback;\n}\n\n/** Resolve the effective path for a patch, re-anchoring by fingerprint. */\nfunction resolvePath(root: PatternNode, patch: RenderUiPatch): string | null {\n if (patch.op === 'insert') {\n return navigatePatternPath(root, patch.address.path) ? patch.address.path : null;\n }\n const atPath = navigatePatternPath(root, patch.address.path);\n if (atPath && (patch.fingerprint === undefined || fingerprintNode(atPath) === patch.fingerprint)) {\n return patch.address.path;\n }\n if (patch.fingerprint !== undefined) {\n return findByFingerprint(root, 'root', patch.fingerprint);\n }\n return null;\n}\n\nfunction applyOnePatch(orbital: OrbitalDefinition, patch: RenderUiPatch): boolean {\n const root = findRenderUiRoot(orbital, patch.address);\n if (!root) return false;\n const path = resolvePath(root, patch);\n if (path === null) return false;\n\n switch (patch.op) {\n case 'set-prop':\n case 'rebind':\n return patch.prop !== undefined && setPropAtPath(root, path, patch.prop, patch.value);\n case 'remove':\n return removeChildAtPath(root, path);\n case 'insert':\n return patch.node !== undefined\n && insertChildAtPath(root, path, patch.index ?? Number.MAX_SAFE_INTEGER, patch.node);\n case 'replace': {\n if (patch.node === undefined) return false;\n if (path === 'root') {\n const target = navigatePatternPath(root, 'root');\n if (!target) return false;\n replaceNodeInPlace(target, patch.node);\n return true;\n }\n return replaceChildAtPath(root, path, patch.node);\n }\n default:\n return false;\n }\n}\n\n/**\n * Replay render-ui patches onto a resolved orbital, in place. Deterministic:\n * given the same base + patches, produces the same tree. Patches that cannot be\n * anchored are returned in `stale` (never silently dropped or misapplied).\n */\nexport function applyRenderOverlay(\n orbital: OrbitalDefinition,\n patches: readonly RenderUiPatch[],\n): RenderOverlayResult {\n let applied = 0;\n const stale: RenderUiPatch[] = [];\n for (const patch of patches) {\n if (applyOnePatch(orbital, patch)) {\n applied += 1;\n } else {\n stale.push(patch);\n }\n }\n return { applied, stale };\n}\n","/**\n * Schema Resolver\n *\n * Converts OrbitalSchema to Intermediate Representation (IR).\n * Resolves all entity references, expands traits, and prepares schema for compilation/runtime.\n *\n * @packageDocumentation\n */\n\nimport type { OrbitalSchema } from './types/schema.js';\nimport type { Orbital, Trait, Page, PageTraitRef, Entity } from './types/index.js';\nimport type { ResolvedIR, ResolvedPage, ResolvedEntity, ResolvedTrait, ResolvedTraitEvent, ResolvedTraitTransition, ResolvedTraitTick } from './types/ir.js';\nimport type { EntityField } from './types/field.js';\nimport type { FieldValue } from './types/entity.js';\nimport type { State, Event, Transition } from './types/state-machine.js';\nimport type { TraitEventListener, TraitTick } from './types/trait.js';\n\n/**\n * Extended entity shape for schema data that may carry `defaults`.\n * The core Entity type does not include `defaults`, but parsed schemas\n * can attach it as extra data for singleton initialization.\n */\ninterface EntityWithDefaults extends Entity {\n defaults?: Record<string, FieldValue>;\n}\n\n// ============================================================================\n// Cache\n// ============================================================================\n\n/**\n * Cache for resolved schemas, keyed on the schema object reference.\n *\n * Identity-based caching (WeakMap) is the only correct shape here: two\n * versions of the same logical schema with the same `name` + `version`\n * can have different content (e.g. a palette drop adds a render-ui\n * pattern, an agent edit rewrites a trait's effects). The old\n * `${name}-${version}` key collided across content mutations and\n * returned a stale IR — fine for the compiler's one-shot path, fatal\n * for the runtime's live-editing path where downstream identity checks\n * (`traits` array refs, trait state-machine references) depend on the\n * IR being fresh when the schema's content moved.\n *\n * WeakMap also means we don't have to think about cache invalidation:\n * when the consumer drops its reference to the schema, the entry is\n * garbage-collected automatically.\n */\nlet schemaCache = new WeakMap<OrbitalSchema, ResolvedIR>();\n\n/**\n * Clear the schema resolution cache.\n *\n * With WeakMap-on-reference caching, cache entries die naturally when\n * the schema object is GC'd, so explicit clearing is rarely necessary.\n * Kept for hot-reload paths that want to force fresh resolution; since\n * WeakMap has no `clear()`, we swap in a fresh instance.\n */\nexport function clearSchemaCache(): void {\n schemaCache = new WeakMap<OrbitalSchema, ResolvedIR>();\n}\n\n/**\n * Get cache statistics (for debugging).\n *\n * WeakMap doesn't expose size or keys; the best we can do is signal\n * that the cache is identity-keyed. Kept for API parity with the old\n * Map-based cache.\n */\nexport function getSchemaCacheStats(): { size: number; keys: string[] } {\n return { size: -1, keys: [] };\n}\n\n// ============================================================================\n// Schema to IR Conversion\n// ============================================================================\n\n/**\n * Convert OrbitalSchema to Intermediate Representation (IR).\n *\n * This function:\n * 1. Resolves all entity references\n * 2. Expands trait definitions (inline or from library)\n * 3. Resolves page bindings\n * 4. Creates the IR structure used by compiler and runtime\n *\n * @param schema - OrbitalSchema to convert\n * @param useCache - Whether to use cached result (default: true)\n * @returns Fully resolved IR\n *\n * @example\n * const schema = { name: 'MyApp', orbitals: [...] };\n * const ir = schemaToIR(schema);\n * console.log(ir.entities.size); // Number of entities\n * console.log(ir.pages.size); // Number of pages\n */\nexport function schemaToIR(schema: OrbitalSchema, useCache: boolean = true): ResolvedIR {\n // Identity cache: same object reference → same IR. Caller is responsible\n // for handing us a fresh ref when content moved (e.g. immutable update).\n if (useCache) {\n const cached = schemaCache.get(schema);\n if (cached) return cached;\n }\n\n // Create empty IR structure\n const ir: ResolvedIR = {\n appName: schema.name,\n description: schema.description,\n version: schema.version || '1.0.0',\n entities: new Map<string, ResolvedEntity>(),\n traits: new Map<string, ResolvedTrait>(),\n pages: new Map<string, ResolvedPage>(),\n entityBindings: [],\n generatedAt: new Date().toISOString(),\n };\n\n // Process each orbital\n for (const orbital of schema.orbitals as Orbital[]) {\n // Resolve entity if present\n if (orbital.entity && typeof orbital.entity !== 'string') {\n const entityDef = orbital.entity as EntityWithDefaults;\n const entity: ResolvedEntity = {\n name: entityDef.name,\n description: entityDef.description,\n // eslint-disable-next-line almadar/no-record-string-unknown -- icon is an optional extension not on Entity type\n icon: (entityDef as unknown as { icon?: string }).icon,\n collection: entityDef.collection || entityDef.name.toLowerCase() + 's',\n fields: (entityDef.fields || [])\n .filter((field: EntityField): field is EntityField & { name: string } =>\n typeof field.name === 'string' && field.name.length > 0,\n )\n .map((field) => ({\n name: field.name,\n type: field.type,\n tsType: inferTsType(field.type),\n // eslint-disable-next-line almadar/no-record-string-unknown -- description is an optional extension not on EntityField type\n description: (field as unknown as { description?: string }).description,\n default: field.default,\n required: field.required ?? false,\n values: field.type === 'enum' ? field.values : undefined,\n enumValues: field.type === 'enum' ? field.values : undefined,\n relation: field.type === 'relation' ? field.relation : undefined,\n })),\n runtime: entityDef.persistence === 'runtime',\n singleton: entityDef.persistence === 'singleton',\n hasInstances: (entityDef.instances?.length ?? 0) > 0,\n instances: entityDef.instances,\n defaults: entityDef.defaults,\n usedByTraits: [],\n usedByPages: [],\n };\n ir.entities.set(entity.name, entity);\n }\n\n // Resolve traits. Preprocessed ref traits from @almadar/runtime's\n // preprocessSchema arrive as wrappers { ref, config, linkedEntity,\n // _resolved: <full trait> }. Unwrap those before projecting so the\n // page-level trait binding can find them by name in ir.traits.\n // Without this unwrap, `trait.name` on a ref wrapper is undefined,\n // and useTraitStateMachine subscribes to zero events for every ref.\n for (const rawTrait of (orbital.traits || [])) {\n const wrap = rawTrait as { _resolved?: Trait };\n const maybeResolved = wrap._resolved;\n const trait: Trait =\n maybeResolved && maybeResolved.stateMachine\n ? maybeResolved\n : (rawTrait as Trait);\n if (!trait.name) continue;\n const resolvedTrait: ResolvedTrait = {\n name: trait.name,\n description: trait.description,\n source: 'schema',\n category: trait.category,\n states: (trait.stateMachine?.states || []).map((s: State) => ({\n name: s.name,\n isInitial: s.isInitial ?? false,\n isFinal: s.isFinal ?? s.isTerminal ?? false,\n })),\n events: (trait.stateMachine?.events || []).map((e: Event) => ({\n key: e.key,\n name: e.name,\n payload: e.payloadSchema,\n })) as ResolvedTraitEvent[],\n transitions: (trait.stateMachine?.transitions || []).map((t: Transition) => ({\n from: t.from,\n to: t.to,\n event: t.event,\n guard: t.guard,\n effects: t.effects || [],\n })) as ResolvedTraitTransition[],\n guards: [],\n ticks: (trait.ticks || []).map((tk: TraitTick) => ({\n name: tk.name,\n interval: tk.interval,\n guard: tk.guard,\n effects: tk.effects,\n priority: tk.priority ?? 0,\n appliesTo: tk.appliesTo ?? [],\n })) as ResolvedTraitTick[],\n listens: (trait.listens || []).map((l: TraitEventListener) => ({\n event: l.event,\n triggers: l.triggers,\n guard: l.guard,\n })),\n dataEntities: [],\n linkedEntity: trait.linkedEntity,\n config: trait.config,\n };\n ir.traits.set(trait.name, resolvedTrait);\n }\n\n // Resolve pages\n for (const page of (orbital.pages || []) as Page[]) {\n const resolvedPage: ResolvedPage = {\n name: page.name,\n path: page.path,\n featureName: page.name.toLowerCase(),\n viewType: page.viewType && ['list', 'detail', 'create', 'edit', 'dashboard'].includes(page.viewType) ?\n page.viewType as ('list' | 'detail' | 'create' | 'edit' | 'dashboard') : undefined,\n sections: [],\n traits: (page.traits || []).map((traitRef: PageTraitRef) => {\n const resolvedTrait = resolveTraitRef(traitRef, ir.traits, orbital.traits as Trait[] || []);\n // Precedence: page-level rebind → orbital-trait-wrapper rebind →\n // atom's resolved trait linkedEntity (from `uses` import) →\n // orbital primary entity. Without walking past the wrapper to\n // the atom's _resolved, atoms imported via `uses` without an\n // explicit `-> Entity` rebind silently rebind to the orbital's\n // primary entity (gap #22 design said atoms keep their own\n // auxiliary entity).\n const orbitalTrait = (orbital.traits as Trait[] || []).find(\n (t): t is Trait => typeof t === 'object' && t !== null\n && (\n ('name' in t && (t as { name?: string }).name === traitRef.ref)\n || ('ref' in t && (t as { ref?: string }).ref === traitRef.ref)\n )\n );\n const orbitalTraitWrapped = orbitalTrait as (Trait & { _resolved?: Trait }) | undefined;\n const wrapperLinked = orbitalTraitWrapped?.linkedEntity ?? orbitalTraitWrapped?._resolved?.linkedEntity;\n const resolvedLinked = resolvedTrait?.linkedEntity;\n return {\n ref: traitRef.ref,\n trait: resolvedTrait,\n linkedEntity: traitRef.linkedEntity ?? wrapperLinked ?? resolvedLinked ??\n (orbital.entity ? (typeof orbital.entity === 'string' ? orbital.entity.replace('.entity', '') : (orbital.entity as Entity).name) : undefined),\n config: traitRef.config,\n };\n }),\n entityBindings: [],\n navigation: [],\n singletonEntities: [],\n };\n ir.pages.set(page.name, resolvedPage);\n }\n }\n\n // Cache result against the schema's object identity.\n if (useCache) {\n schemaCache.set(schema, ir);\n }\n\n return ir;\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Infers TypeScript type from schema type string\n * \n * Converts schema type strings to their TypeScript equivalents.\n * Handles primitive types, arrays, and custom types.\n * \n * @param {string} schemaType - Schema type string (e.g., 'string', 'number[]')\n * @returns {string} TypeScript type string\n * \n * @example\n * inferTsType('string') // returns 'string'\n * inferTsType('number[]') // returns 'number[]'\n * inferTsType('custom') // returns 'custom'\n */\nfunction inferTsType(schemaType: string): string {\n const typeMap: Record<string, string> = {\n string: 'string',\n number: 'number',\n boolean: 'boolean',\n date: 'Date',\n datetime: 'Date',\n timestamp: 'number',\n array: 'unknown[]',\n object: 'Record<string, unknown>',\n any: 'unknown',\n };\n\n // Handle array types like \"string[]\"\n if (schemaType.endsWith('[]')) {\n const baseType = schemaType.slice(0, -2);\n return `${typeMap[baseType] || baseType}[]`;\n }\n\n // Typed-map form `Map<K,V>` (the orbital `Map K V` type) → `Record<K, V>`.\n // Mirrors the Rust `parse_payload_field_type` map branch.\n if (schemaType.startsWith('Map<') && schemaType.endsWith('>')) {\n const inner = schemaType.slice(4, -1);\n const comma = inner.indexOf(',');\n if (comma !== -1) {\n const key = inferTsType(inner.slice(0, comma).trim());\n const value = inferTsType(inner.slice(comma + 1).trim());\n return `Record<${key}, ${value}>`;\n }\n }\n\n return typeMap[schemaType] || schemaType;\n}\n\n/**\n * Resolves a trait reference to a full trait definition\n * \n * Looks up trait references in the resolved traits map or schema traits array.\n * Creates appropriate trait structures for different reference types.\n * \n * @param {PageTraitRef} traitRef - Trait reference (string or object)\n * @param {Map<string, ResolvedTrait>} traitsMap - Map of resolved traits\n * @param {Trait[]} schemaTraits - Array of schema traits\n * @returns {ResolvedTrait} Resolved trait definition\n * \n * @example\n * const trait = resolveTraitRef('MyTrait', traitsMap, schemaTraits);\n * const trait = resolveTraitRef({ ref: 'MyTrait' }, traitsMap, schemaTraits);\n */\nfunction resolveTraitRef(\n traitRef: PageTraitRef,\n traitsMap: Map<string, ResolvedTrait>,\n schemaTraits: Trait[]\n): ResolvedTrait {\n const refName = typeof traitRef === 'string' ? traitRef : traitRef.ref || '';\n\n // Try to find in resolved traits\n if (traitsMap.has(refName)) {\n return traitsMap.get(refName)!;\n }\n\n // Try to find in schema traits\n const schemaTrait = schemaTraits.find((t: Trait) => t.name === refName);\n if (schemaTrait) {\n // This is a simplified inline trait\n return {\n name: refName,\n source: 'inline',\n states: [],\n events: [],\n transitions: [],\n guards: [],\n ticks: [],\n listens: [],\n dataEntities: [],\n };\n }\n\n // Fallback: create empty trait\n return {\n name: refName,\n source: 'schema',\n states: [],\n events: [],\n transitions: [],\n guards: [],\n ticks: [],\n listens: [],\n dataEntities: [],\n };\n}\n\n// ============================================================================\n// Page Helpers\n// ============================================================================\n\n/**\n * Get a specific page from resolved IR by name.\n * If no name is provided, returns the first page.\n *\n * @param ir - Resolved IR\n * @param pageName - Optional page name to find\n * @returns Resolved page or undefined\n *\n * @example\n * const ir = schemaToIR(schema);\n * const homePage = getPage(ir, 'HomePage');\n * const firstPage = getPage(ir); // No name = first page\n */\nexport function getPage(ir: ResolvedIR, pageName?: string): ResolvedPage | undefined {\n if (!pageName) {\n // Return first page if no name specified\n return ir.pages.values().next().value;\n }\n return ir.pages.get(pageName);\n}\n\n/**\n * Get all pages from resolved IR as an array\n *\n * @param ir - Resolved IR\n * @returns Array of resolved pages\n */\nexport function getPages(ir: ResolvedIR): ResolvedPage[] {\n return Array.from(ir.pages.values());\n}\n\n/**\n * Get a specific entity from resolved IR by name\n *\n * @param ir - Resolved IR\n * @param entityName - Entity name to find\n * @returns Resolved entity or undefined\n */\nexport function getEntity(ir: ResolvedIR, entityName: string): ResolvedEntity | undefined {\n return ir.entities.get(entityName);\n}\n\n/**\n * Get a specific trait from resolved IR by name\n *\n * @param ir - Resolved IR\n * @param traitName - Trait name to find\n * @returns Resolved trait or undefined\n */\nexport function getTrait(ir: ResolvedIR, traitName: string): ResolvedTrait | undefined {\n return ir.traits.get(traitName);\n}\n","/**\n * Schema Diffing & Protection\n *\n * Pure functions for comparing OrbitalSchema objects, detecting destructive changes,\n * and categorizing removals. No I/O — operates on in-memory schema objects.\n */\n\nimport type { OrbitalSchema } from './types/schema.js';\nimport type { OrbitalDefinition, PageRef } from './types/orbital.js';\nimport type { Trait, TraitRef } from './types/trait.js';\nimport type { Page } from './types/page.js';\n// EntityField used transitively through entity.fields\nimport type { State, Transition } from './types/state-machine.js';\nimport type { Effect } from './types/effect.js';\nimport type {\n SchemaChange,\n ChangeSetDocument,\n CategorizedRemovals,\n ChangesetValue,\n PageContentReduction,\n SemanticSchemaChange,\n} from './types/changeset.js';\nimport { isInlineTrait } from './types/trait.js';\n\n// ============================================================================\n// Schema Diffing\n// ============================================================================\n\n/**\n * Diff two OrbitalSchema objects and produce a list of changes.\n * Compares orbitals, entities, traits, pages, services, and top-level fields.\n */\nexport function diffSchemas(\n before: OrbitalSchema,\n after: OrbitalSchema,\n): { changes: SchemaChange[] } {\n const changes: SchemaChange[] = [];\n let changeId = 0;\n const nextId = () => `change-${++changeId}`;\n\n // Compare top-level fields\n if (before.name !== after.name) {\n changes.push({\n id: nextId(),\n operation: 'modify',\n target: 'schema',\n path: ['name'],\n before: before.name,\n after: after.name,\n description: `Renamed schema from \"${before.name}\" to \"${after.name}\"`,\n });\n }\n\n if (before.description !== after.description) {\n changes.push({\n id: nextId(),\n operation: 'modify',\n target: 'schema',\n path: ['description'],\n before: before.description,\n after: after.description,\n description: `Modified schema description`,\n });\n }\n\n // Compare orbitals by name\n const beforeOrbitals = new Map(\n (before.orbitals || []).map((o, i) => [o.name, { orbital: o, index: i }]),\n );\n const afterOrbitals = new Map(\n (after.orbitals || []).map((o, i) => [o.name, { orbital: o, index: i }]),\n );\n\n // Detect removed orbitals\n for (const [name, { index }] of beforeOrbitals) {\n if (!afterOrbitals.has(name)) {\n changes.push({\n id: nextId(),\n operation: 'remove',\n target: 'orbital',\n path: ['orbitals', index],\n before: name,\n description: `Removed orbital: ${name}`,\n });\n }\n }\n\n // Detect added orbitals\n for (const [name, { index }] of afterOrbitals) {\n if (!beforeOrbitals.has(name)) {\n changes.push({\n id: nextId(),\n operation: 'add',\n target: 'orbital',\n path: ['orbitals', index],\n after: name,\n description: `Added orbital: ${name}`,\n });\n }\n }\n\n // Detect modified orbitals (deep compare via JSON)\n for (const [name, { orbital: afterOrbital, index }] of afterOrbitals) {\n const beforeEntry = beforeOrbitals.get(name);\n if (beforeEntry) {\n const beforeJson = JSON.stringify(beforeEntry.orbital);\n const afterJson = JSON.stringify(afterOrbital);\n if (beforeJson !== afterJson) {\n changes.push({\n id: nextId(),\n operation: 'modify',\n target: 'orbital',\n path: ['orbitals', index],\n description: `Modified orbital: ${name}`,\n });\n\n // Drill into entity changes\n const beforeEntity = beforeEntry.orbital.entity;\n const afterEntity = afterOrbital.entity;\n if (JSON.stringify(beforeEntity) !== JSON.stringify(afterEntity)) {\n const entityName =\n typeof afterEntity === 'string'\n ? afterEntity\n : afterEntity && typeof afterEntity === 'object' && 'name' in afterEntity\n ? (afterEntity as { name: string }).name\n : 'entity';\n changes.push({\n id: nextId(),\n operation: 'modify',\n target: 'entity',\n path: ['orbitals', index, 'entity'],\n description: `Modified entity: ${entityName}`,\n });\n }\n\n // Drill into trait changes\n const beforeTraits = beforeEntry.orbital.traits || [];\n const afterTraits = afterOrbital.traits || [];\n if (JSON.stringify(beforeTraits) !== JSON.stringify(afterTraits)) {\n changes.push({\n id: nextId(),\n operation: 'modify',\n target: 'traits',\n path: ['orbitals', index, 'traits'],\n description: `Modified traits in orbital: ${name}`,\n });\n }\n\n // Drill into page changes\n const beforePages = beforeEntry.orbital.pages || [];\n const afterPages = afterOrbital.pages || [];\n if (JSON.stringify(beforePages) !== JSON.stringify(afterPages)) {\n changes.push({\n id: nextId(),\n operation: 'modify',\n target: 'pages',\n path: ['orbitals', index, 'pages'],\n description: `Modified pages in orbital: ${name}`,\n });\n }\n }\n }\n }\n\n // Compare services\n const beforeServices = JSON.stringify(before.services || []);\n const afterServices = JSON.stringify(after.services || []);\n if (beforeServices !== afterServices) {\n changes.push({\n id: nextId(),\n operation: 'modify',\n target: 'services',\n path: ['services'],\n description: 'Modified services',\n });\n }\n\n return { changes };\n}\n\n// ============================================================================\n// Destructive Change Detection\n// ============================================================================\n\n/**\n * Check if a changeset contains any removals.\n */\nexport function isDestructiveChange(changeSet: { changes: SchemaChange[] }): boolean {\n return changeSet.changes.some((c) => c.operation === 'remove');\n}\n\n/**\n * Extract all removal operations from a changeset.\n */\nexport function getRemovals(changeSet: { changes: SchemaChange[] }): SchemaChange[] {\n return changeSet.changes.filter((c) => c.operation === 'remove');\n}\n\n/**\n * Categorize removals by severity.\n *\n * - Critical: orbitals, entities, states, pages (require confirmation)\n * - Standard: fields, actions, traits (auto-snapshotted)\n * - Minor: transitions, guards (tracked)\n */\nexport function categorizeRemovals(changeSet: {\n changes: SchemaChange[];\n}): CategorizedRemovals {\n const critical: SchemaChange[] = [];\n const standard: SchemaChange[] = [];\n const minor: SchemaChange[] = [];\n\n for (const change of changeSet.changes) {\n if (change.operation !== 'remove') continue;\n\n const target = change.target.toLowerCase();\n if (\n target === 'orbital' ||\n target === 'entity' ||\n target === 'state' ||\n target === 'page'\n ) {\n critical.push(change);\n } else if (\n target === 'field' ||\n target === 'action' ||\n target === 'trait' ||\n target === 'traits'\n ) {\n standard.push(change);\n } else {\n minor.push(change);\n }\n }\n\n return { critical, standard, minor, pageContentReductions: [] };\n}\n\n/**\n * Check if critical removals require explicit confirmation.\n */\nexport function requiresConfirmation(removals: CategorizedRemovals): boolean {\n return removals.critical.length > 0;\n}\n\n// ============================================================================\n// Page Content Reduction\n// ============================================================================\n\n/**\n * Detect implicit content reduction within pages.\n * Catches cases where a page 'modify' reduces components/actions/displays\n * without an explicit 'remove' operation.\n */\nexport function detectPageContentReduction(\n beforePages: unknown[],\n afterPages: unknown[],\n): PageContentReduction[] {\n const reductions: PageContentReduction[] = [];\n\n const getPageName = (p: unknown): string | null => {\n if (p && typeof p === 'object' && 'name' in p) {\n return (p as { name: string }).name;\n }\n return null;\n };\n\n const countContent = (\n page: unknown,\n ): { sections: number; actions: number } => {\n if (!page || typeof page !== 'object') return { sections: 0, actions: 0 };\n const p = page as { traits?: unknown[] };\n const traits = Array.isArray(p.traits) ? p.traits : [];\n return { sections: traits.length, actions: 0 };\n };\n\n // Build maps by name\n const beforeMap = new Map<string, unknown>();\n for (const p of beforePages) {\n const name = getPageName(p);\n if (name) beforeMap.set(name, p);\n }\n\n for (const afterPage of afterPages) {\n const name = getPageName(afterPage);\n if (!name) continue;\n const beforePage = beforeMap.get(name);\n if (!beforePage) continue;\n\n const beforeContent = countContent(beforePage);\n const afterContent = countContent(afterPage);\n\n const sectionsRemoved = beforeContent.sections - afterContent.sections;\n const actionsRemoved = beforeContent.actions - afterContent.actions;\n\n if (sectionsRemoved > 0 || actionsRemoved > 0) {\n reductions.push({\n pageName: name,\n componentsRemoved: sectionsRemoved,\n actionsRemoved,\n displaysRemoved: 0,\n before: beforeContent,\n after: afterContent,\n isSignificant: sectionsRemoved > 0,\n });\n }\n }\n\n return reductions;\n}\n\n/**\n * Check if page content reductions are significant.\n */\nexport function hasSignificantPageReduction(\n reductions: PageContentReduction[],\n): boolean {\n return reductions.some((r) => r.isSignificant);\n}\n\n// ============================================================================\n// Semantic Schema Diffing\n// ============================================================================\n\n/** Stable JSON comparison. */\nfunction jsonEqual(a: unknown, b: unknown): boolean {\n return JSON.stringify(a) === JSON.stringify(b);\n}\n\nfunction setsEqual(a: Set<string>, b: Set<string>): boolean {\n if (a.size !== b.size) return false;\n for (const item of a) {\n if (!b.has(item)) return false;\n }\n return true;\n}\n\nfunction inlineTraitMap(refs: TraitRef[]): Map<string, Trait> {\n const map = new Map<string, Trait>();\n for (const r of refs) {\n if (isInlineTrait(r)) map.set((r as Trait).name, r as Trait);\n }\n return map;\n}\n\nfunction inlinePageMap(refs: PageRef[]): Map<string, Page> {\n const map = new Map<string, Page>();\n for (const r of refs) {\n if (typeof r === 'string') continue;\n if ('ref' in r && !('name' in r)) continue;\n const page = r as Page;\n if (page.path) map.set(page.path, page);\n }\n return map;\n}\n\nfunction isRenderUIEffect(effect: Effect): boolean {\n if (!Array.isArray(effect)) return false;\n return String(effect[0]) === 'render-ui' || String(effect[0]) === 'renderUI';\n}\n\nfunction tKey(t: Transition): string {\n return `${t.from ?? ''}+${t.event}`;\n}\n\nfunction diffSemanticTransitions(\n orbitalName: string, traitName: string,\n before: Transition[], after: Transition[],\n): SemanticSchemaChange[] {\n const changes: SemanticSchemaChange[] = [];\n const bMap = new Map(before.map(t => [tKey(t), t]));\n const aMap = new Map(after.map(t => [tKey(t), t]));\n\n for (const [key, aT] of aMap) {\n const bT = bMap.get(key);\n if (!bT) continue;\n\n if (!jsonEqual(bT.guard, aT.guard)) {\n changes.push({ kind: 'guard-changed', orbitalName, traitName, transitionEvent: aT.event });\n }\n\n if (!jsonEqual(bT.effects, aT.effects)) {\n const bEffects = bT.effects ?? [];\n const aEffects = aT.effects ?? [];\n const bRUI = bEffects.filter(isRenderUIEffect);\n const aRUI = aEffects.filter(isRenderUIEffect);\n\n if (bRUI.length !== aRUI.length || !jsonEqual(bRUI, aRUI)) {\n changes.push({ kind: 'render-ui-changed', orbitalName, traitName, transitionEvent: aT.event });\n } else {\n changes.push({ kind: 'effect-changed', orbitalName, traitName, transitionEvent: aT.event });\n }\n }\n }\n return changes;\n}\n\nfunction diffSemanticOrbital(\n name: string, before: OrbitalDefinition, after: OrbitalDefinition,\n): SemanticSchemaChange[] {\n const changes: SemanticSchemaChange[] = [];\n\n // Entity fields\n const bEntity = typeof before.entity === 'object' ? before.entity : null;\n const aEntity = typeof after.entity === 'object' ? after.entity : null;\n if (bEntity && aEntity) {\n if (!jsonEqual(bEntity.fields, aEntity.fields)) {\n changes.push({ kind: 'entity-fields-changed', orbitalName: name });\n }\n } else if (bEntity !== aEntity) {\n changes.push({ kind: 'entity-fields-changed', orbitalName: name });\n }\n\n // Traits\n const bTraits = inlineTraitMap(before.traits ?? []);\n const aTraits = inlineTraitMap(after.traits ?? []);\n\n for (const [tName] of aTraits) {\n if (!bTraits.has(tName)) changes.push({ kind: 'trait-added', orbitalName: name, traitName: tName });\n }\n for (const [tName] of bTraits) {\n if (!aTraits.has(tName)) changes.push({ kind: 'trait-removed', orbitalName: name, traitName: tName });\n }\n\n for (const [tName, aTrait] of aTraits) {\n const bTrait = bTraits.get(tName);\n if (!bTrait) continue;\n\n const bSM = bTrait.stateMachine;\n const aSM = aTrait.stateMachine;\n\n if (!bSM && !aSM) continue;\n if (!bSM || !aSM) {\n changes.push({ kind: 'state-machine-changed', orbitalName: name, traitName: tName });\n continue;\n }\n\n const bStates = new Set((bSM.states ?? []).map((s: State) => s.name));\n const aStates = new Set((aSM.states ?? []).map((s: State) => s.name));\n if (!setsEqual(bStates, aStates)) {\n changes.push({ kind: 'state-machine-changed', orbitalName: name, traitName: tName });\n }\n\n const bTKeys = new Set((bSM.transitions ?? []).map(tKey));\n const aTKeys = new Set((aSM.transitions ?? []).map(tKey));\n if (!setsEqual(bTKeys, aTKeys)) {\n if (!changes.some(c => c.kind === 'state-machine-changed' && c.traitName === tName)) {\n changes.push({ kind: 'state-machine-changed', orbitalName: name, traitName: tName });\n }\n }\n\n changes.push(...diffSemanticTransitions(name, tName, bSM.transitions ?? [], aSM.transitions ?? []));\n\n if (!jsonEqual(bTrait.emits, aTrait.emits) || !jsonEqual(bTrait.listens, aTrait.listens)) {\n changes.push({ kind: 'event-wiring-changed', orbitalName: name, traitName: tName });\n }\n }\n\n // Pages\n const bPages = inlinePageMap(before.pages ?? []);\n const aPages = inlinePageMap(after.pages ?? []);\n const bPaths = new Set(bPages.keys());\n const aPaths = new Set(aPages.keys());\n\n if (!setsEqual(bPaths, aPaths)) {\n changes.push({ kind: 'page-changed', orbitalName: name });\n } else {\n for (const [path, aPage] of aPages) {\n if (!jsonEqual(bPages.get(path), aPage)) {\n changes.push({ kind: 'page-changed', orbitalName: name });\n break;\n }\n }\n }\n\n return changes;\n}\n\n/**\n * Semantic diff: what .orb CONCEPTS changed between two schema versions.\n *\n * Unlike `diffSchemas()` which produces operational CRUD changes for persistence,\n * this produces concept-level changes (guard-changed, render-ui-changed, etc.)\n * for canvas focus derivation, CLI narration, and selective re-verification.\n */\nexport function diffSchemaSemantics(\n before: OrbitalSchema,\n after: OrbitalSchema,\n): SemanticSchemaChange[] {\n const changes: SemanticSchemaChange[] = [];\n\n const bOrbitals = new Map<string, OrbitalDefinition>();\n for (const o of before.orbitals ?? []) {\n const orb = o as OrbitalDefinition;\n bOrbitals.set(orb.name, orb);\n }\n\n const aOrbitals = new Map<string, OrbitalDefinition>();\n for (const o of after.orbitals ?? []) {\n const orb = o as OrbitalDefinition;\n aOrbitals.set(orb.name, orb);\n }\n\n const added: string[] = [];\n for (const [name] of aOrbitals) {\n if (!bOrbitals.has(name)) {\n changes.push({ kind: 'orbital-added', orbitalName: name });\n added.push(name);\n }\n }\n for (const [name] of bOrbitals) {\n if (!aOrbitals.has(name)) {\n changes.push({ kind: 'orbital-removed', orbitalName: name });\n }\n }\n if (added.length > 1) {\n changes.push({ kind: 'behavior-composed', orbitalName: added[0] });\n }\n\n for (const [name, aOrb] of aOrbitals) {\n const bOrb = bOrbitals.get(name);\n if (bOrb) changes.push(...diffSemanticOrbital(name, bOrb, aOrb));\n }\n\n return changes;\n}\n\n// ============================================================================\n// High-level Orbital Schema Diff (changeset envelope)\n// ============================================================================\n\n/**\n * Source label for a changeset. The persistence layer accepts the canonical\n * agent labels plus `skill-agent:<skill>`-style identifiers, so the type stays\n * open as a string.\n */\nexport type SchemaDiffSource =\n | 'requirements-agent'\n | 'builder-agent'\n | 'user'\n | 'auto-fix'\n | (string & {});\n\n/** Tracking granularity used when generating the diff. */\nexport type SchemaDiffMode = 'initial' | 'update';\n\n/** Author identification carried on the changeset envelope. */\nexport interface SchemaDiffAuthor {\n userId: string;\n name?: string;\n}\n\n/** Options that shape the resulting diff envelope. */\nexport interface SchemaDiffOptions {\n mode: SchemaDiffMode;\n author: SchemaDiffAuthor;\n source: SchemaDiffSource;\n}\n\n/** Per-change entry in the diff envelope. */\nexport interface SchemaDiffChange {\n operation: 'add' | 'modify' | 'remove' | 'rename' | 'merge' | 'set';\n path: string;\n value?: ChangesetValue;\n previousValue?: ChangesetValue;\n}\n\n/** Aggregate orbital/trait deltas surfaced by the diff. */\nexport interface SchemaDiffSummary {\n orbitalsAdded: string[];\n orbitalsRemoved: string[];\n orbitalsModified: string[];\n traitsAdded: string[];\n traitsModified: string[];\n traitsRemoved: string[];\n}\n\n/** Changeset envelope produced by `diffOrbitalSchemas`. */\nexport interface SchemaDiffChangeset {\n id: string;\n source: SchemaDiffSource;\n author: SchemaDiffAuthor;\n description: string;\n changes: SchemaDiffChange[];\n}\n\n/** Result of comparing two OrbitalSchema versions. */\nexport interface SchemaDiff {\n hasChanges: boolean;\n changeCount: number;\n changeset: SchemaDiffChangeset;\n summary: SchemaDiffSummary;\n}\n\n/**\n * Compare two `OrbitalSchema` versions and produce a changeset envelope.\n *\n * Higher-level companion to `diffSchemas`: where `diffSchemas` returns a flat\n * list of `SchemaChange` entries keyed by structural path, this returns the\n * envelope the persistence layer ships to Firestore (id, author, source,\n * summary buckets).\n *\n * Identifier generation: `changeset.id` is a deterministic `chg_<hex>` value\n * derived from the schema name + change count when `globalThis.crypto.randomUUID`\n * is unavailable; otherwise a UUID is used. Callers that need a stable id\n * across regenerations should supply one themselves.\n */\nexport function diffOrbitalSchemas(\n before: OrbitalSchema | null,\n after: OrbitalSchema,\n options: SchemaDiffOptions,\n): SchemaDiff {\n const summary: SchemaDiffSummary = {\n orbitalsAdded: [],\n orbitalsRemoved: [],\n orbitalsModified: [],\n traitsAdded: [],\n traitsModified: [],\n traitsRemoved: [],\n };\n const changes: SchemaDiffChange[] = [];\n\n if (!before) {\n for (const orbital of after.orbitals ?? []) {\n const orb = orbital as OrbitalDefinition;\n summary.orbitalsAdded.push(orb.name);\n changes.push({\n operation: 'add',\n path: `orbitals[${summary.orbitalsAdded.length - 1}]`,\n value: orb,\n });\n }\n } else {\n const beforeOrbitals = new Map<string, OrbitalDefinition>();\n for (const o of before.orbitals ?? []) {\n const orb = o as OrbitalDefinition;\n beforeOrbitals.set(orb.name, orb);\n }\n const afterOrbitals = new Map<string, OrbitalDefinition>();\n for (const o of after.orbitals ?? []) {\n const orb = o as OrbitalDefinition;\n afterOrbitals.set(orb.name, orb);\n }\n\n let idx = 0;\n for (const [name, orb] of afterOrbitals) {\n const prev = beforeOrbitals.get(name);\n if (!prev) {\n summary.orbitalsAdded.push(name);\n changes.push({\n operation: 'add',\n path: `orbitals[${idx}]`,\n value: orb,\n });\n } else if (JSON.stringify(prev) !== JSON.stringify(orb)) {\n summary.orbitalsModified.push(name);\n changes.push({\n operation: 'merge',\n path: `orbitals[${idx}]`,\n previousValue: prev,\n value: orb,\n });\n }\n idx++;\n }\n for (const [name, orb] of beforeOrbitals) {\n if (!afterOrbitals.has(name)) {\n summary.orbitalsRemoved.push(name);\n changes.push({\n operation: 'remove',\n path: `orbitals[${name}]`,\n previousValue: orb,\n });\n }\n }\n\n if (before.name !== after.name) {\n changes.push({\n operation: 'set',\n path: 'name',\n previousValue: before.name,\n value: after.name,\n });\n }\n if (before.version !== after.version) {\n changes.push({\n operation: 'set',\n path: 'version',\n previousValue: before.version,\n value: after.version,\n });\n }\n if (before.description !== after.description) {\n changes.push({\n operation: 'set',\n path: 'description',\n previousValue: before.description,\n value: after.description,\n });\n }\n if (before.summary !== after.summary) {\n changes.push({\n operation: 'set',\n path: 'summary',\n previousValue: before.summary,\n value: after.summary,\n });\n }\n }\n\n const hasChanges = changes.length > 0;\n const description = describeDiff(summary, options.mode, after.name);\n\n return {\n hasChanges,\n changeCount: changes.length,\n changeset: {\n id: generateChangesetId(after.name, changes.length),\n source: options.source,\n author: options.author,\n description,\n changes,\n },\n summary,\n };\n}\n\nfunction describeDiff(\n summary: SchemaDiffSummary,\n mode: SchemaDiffMode,\n schemaName: string,\n): string {\n const parts: string[] = [];\n if (summary.orbitalsAdded.length > 0) {\n parts.push(`+${summary.orbitalsAdded.length} orbital(s)`);\n }\n if (summary.orbitalsModified.length > 0) {\n parts.push(`~${summary.orbitalsModified.length} orbital(s)`);\n }\n if (summary.orbitalsRemoved.length > 0) {\n parts.push(`-${summary.orbitalsRemoved.length} orbital(s)`);\n }\n if (parts.length === 0) return 'No changes';\n return `${mode === 'initial' ? 'Initial' : 'Update'} ${schemaName}: ${parts.join(', ')}`;\n}\n\nfunction generateChangesetId(seed: string, count: number): string {\n const cryptoApi = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (cryptoApi?.randomUUID) return cryptoApi.randomUUID();\n let hash = 0;\n const source = `${seed}:${count}:${Date.now()}`;\n for (let i = 0; i < source.length; i++) {\n hash = (hash * 31 + source.charCodeAt(i)) | 0;\n }\n return `chg_${(hash >>> 0).toString(16)}_${count}`;\n}\n","/**\n * Orbital Summarization\n *\n * Deterministic orbital-to-orbital transformation:\n * full schema in → business skeleton out.\n *\n * Input: OrbitalSchema. Output: OrbitalSchema.\n * Same types — just stripped of implementation details.\n *\n * This module provides functions to extract the essential business structure\n * from a complete orbital schema, removing implementation details like\n * effects, guards, and visual styling while preserving the core entity,\n * trait, and page definitions.\n *\n * @packageDocumentation\n */\n\nimport type { OrbitalSchema } from './types/schema.js';\nimport type { OrbitalDefinition } from './types/orbital.js';\nimport { isEntityCall, isEntityReference, parseEntityRef } from './types/orbital.js';\nimport type { Entity } from './types/entity.js';\nimport type { EntityField } from './types/field.js';\nimport type { Trait } from './types/trait.js';\nimport { isInlineTrait } from './types/trait.js';\nimport type { Page } from './types/page.js';\nimport type { Transition, Event, State } from './types/state-machine.js';\n\n// ============================================================================\n// Workflow Type Detection\n// ============================================================================\n\n/**\n * Standard CRUD state names used for workflow classification.\n * @internal\n */\nconst CRUD_STATES = new Set(['browsing', 'creating', 'editing', 'viewing', 'deleting']);\n\n/**\n * Pattern for detecting wizard-style step states (step1, step2, etc).\n * @internal\n */\nconst STEP_PATTERN = /^step\\d+$/i;\n\n/**\n * Classify a workflow from its state machine states.\n *\n * - CRUD: 3+ states match {browsing, creating, editing, viewing, deleting}\n * - Wizard: 2+ states match /^step\\d+$/i, OR linear chain to terminal state\n * - Custom: everything else\n */\nexport function classifyWorkflow(states: State[]): 'crud' | 'wizard' | 'custom' {\n const names = states.map(s => s.name.toLowerCase());\n\n const crudMatch = names.filter(n => CRUD_STATES.has(n)).length;\n if (crudMatch >= 3) return 'crud';\n\n const stepCount = names.filter(n => STEP_PATTERN.test(n)).length;\n if (stepCount >= 2) return 'wizard';\n\n const hasTerminal = states.some(s => s.isTerminal || s.isFinal);\n const hasComplete = names.some(n =>\n n === 'complete' || n === 'completed' || n === 'done' || n === 'finished'\n );\n if ((hasTerminal || hasComplete) && states.length >= 4 && crudMatch <= 1) {\n return 'wizard';\n }\n\n return 'custom';\n}\n\n// ============================================================================\n// Entity Summarization\n// ============================================================================\n\n/**\n * Check if a field is a primary key.\n * @internal\n */\nfunction isPrimaryKey(field: EntityField): boolean {\n return (field as EntityField & { primaryKey?: boolean }).primaryKey === true;\n}\n\n/**\n * Check if a field is a business field (not primary key, has business meaning).\n * @internal\n */\nfunction isBusinessField(field: EntityField): boolean {\n if (isPrimaryKey(field)) return false;\n if (field.type === 'enum' || field.type === 'relation') return true;\n if (field.required) return true;\n return false;\n}\n\n/**\n * Summarize an entity to its business-relevant fields.\n * @internal\n */\nfunction summarizeEntity(entity: Entity): Entity {\n const fields: EntityField[] = entity.fields.filter(isBusinessField).map(summarizeField);\n return {\n name: entity.name,\n collection: entity.collection,\n fields,\n };\n}\n\nfunction summarizeField(f: EntityField): EntityField {\n if (f.type === 'enum') {\n return {\n ...(f.name !== undefined ? { name: f.name } : {}),\n type: 'enum',\n values: f.values,\n ...(f.required ? { required: true } : {}),\n };\n }\n if (f.type === 'relation') {\n return {\n ...(f.name !== undefined ? { name: f.name } : {}),\n type: 'relation',\n relation: f.relation,\n ...(f.required ? { required: true } : {}),\n };\n }\n if (f.type === 'array') {\n return {\n ...(f.name !== undefined ? { name: f.name } : {}),\n type: 'array',\n items: f.items,\n ...(f.required ? { required: true } : {}),\n };\n }\n return {\n ...(f.name !== undefined ? { name: f.name } : {}),\n type: f.type,\n ...(f.required ? { required: true } : {}),\n };\n}\n\n// ============================================================================\n// Transition Summarization\n// ============================================================================\n\n/**\n * Deduplicate transitions that are identical in (from, to, event).\n * Strips effects and guards.\n */\n/**\n * Deduplicate transitions that are identical in (from, to, event).\n * Strips effects and guards.\n * @internal\n */\nfunction summarizeTransitions(transitions: Transition[]): Transition[] {\n const seen = new Set<string>();\n const result: Transition[] = [];\n\n for (const t of transitions) {\n const key = `${t.from}::${t.to}::${t.event}`;\n if (!seen.has(key)) {\n seen.add(key);\n result.push({ from: t.from, to: t.to, event: t.event });\n }\n }\n\n return result;\n}\n\n// ============================================================================\n// Trait Summarization\n// ============================================================================\n\n/**\n * Summarize events to just their keys.\n * @internal\n */\nfunction summarizeEvents(events: Event[]): Event[] {\n return events.map(e => ({ key: e.key, name: e.key }));\n}\n\n/**\n * Summarize a trait to its essential structure.\n * @internal\n */\nfunction summarizeTrait(trait: Trait): Trait {\n const states = trait.stateMachine?.states ?? [];\n const events = trait.stateMachine?.events ?? [];\n const transitions = trait.stateMachine?.transitions ?? [];\n\n const result: Trait = { name: trait.name, scope: trait.scope };\n if (trait.category) result.category = trait.category;\n if (trait.linkedEntity) result.linkedEntity = trait.linkedEntity;\n\n if (trait.stateMachine) {\n result.stateMachine = {\n states: states.map(s => {\n const st: State = { name: s.name };\n if (s.isInitial) st.isInitial = true;\n if (s.isTerminal) st.isTerminal = true;\n if (s.isFinal) st.isFinal = true;\n return st;\n }),\n events: summarizeEvents(events),\n transitions: summarizeTransitions(transitions),\n };\n }\n\n if (trait.emits && trait.emits.length > 0) {\n result.emits = trait.emits.map(e => ({\n event: e.event,\n ...(e.scope ? { scope: e.scope } : {}),\n }));\n }\n\n if (trait.listens && trait.listens.length > 0) {\n result.listens = trait.listens.map(l => ({\n event: l.event,\n triggers: l.triggers,\n ...(l.scope ? { scope: l.scope } : {}),\n }));\n }\n\n return result;\n}\n\n// ============================================================================\n// Page Summarization\n// ============================================================================\n\n/**\n * Summarize a page to its essential structure.\n * @internal\n */\nfunction summarizePage(page: Page): Page {\n const result: Page = { name: page.name, path: page.path };\n if (page.traits && page.traits.length > 0) {\n result.traits = page.traits.map(t => ({ ref: t.ref }));\n }\n return result;\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Summarize a single orbital into its business skeleton.\n *\n * OrbitalDefinition in → OrbitalDefinition out.\n * Strips effects, guards, payloads, theme, optional fields.\n * Deduplicates transitions on (from, to, event).\n */\nexport function summarizeOrbital(orbital: OrbitalDefinition): OrbitalDefinition {\n let entity: Entity;\n if (isEntityReference(orbital.entity)) {\n entity = { name: orbital.entity, fields: [] };\n } else if (isEntityCall(orbital.entity)) {\n // EntityCall (Phase F): synthesize a placeholder Entity from the call shape.\n // The full inlined entity is only available after the compiler's inline phase.\n const call = orbital.entity;\n const name = call.name ?? parseEntityRef(call.extends)?.alias ?? call.extends;\n entity = {\n name,\n fields: call.fields ?? [],\n ...(call.persistence ? { persistence: call.persistence } : {}),\n ...(call.collection ? { collection: call.collection } : {}),\n };\n } else {\n entity = summarizeEntity(orbital.entity);\n }\n\n const traits = orbital.traits.map(traitRef => {\n if (isInlineTrait(traitRef)) {\n return summarizeTrait(traitRef);\n }\n return traitRef;\n });\n\n const pages = orbital.pages\n .filter((p): p is Page => typeof p === 'object' && 'name' in p && !('ref' in p))\n .map(summarizePage);\n\n return { name: orbital.name, entity, traits, pages };\n}\n\n/**\n * Summarize an entire OrbitalSchema into a business skeleton.\n *\n * OrbitalSchema in → OrbitalSchema out.\n * Strips schema-level metadata (domainContext, design, designTokens, customPatterns).\n */\nexport function summarizeSchema(schema: OrbitalSchema): OrbitalSchema {\n return {\n name: schema.name,\n description: schema.description,\n version: schema.version,\n orbitals: schema.orbitals.map(summarizeOrbital),\n };\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']);\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 (param.key.endsWith('Event')) 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 const label = param.label ?? humanizeKey(param.key);\n const question = `${label}?`;\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: `${call.orbital}.${trait.name}.${param.key}`,\n orbitalName: call.orbital,\n question,\n inputType: deriveInputType(param),\n mutationTemplate: {\n kind: 'set-trait-override-config',\n orbitalName: call.orbital,\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 */\nfunction 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 * 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: `${call.orbital}.__entityFields`,\n orbitalName: call.orbital,\n question: `Which fields should a ${entityName} have?`,\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: call.orbital,\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 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 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 ?? call.orbital;\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: `${call.orbital}.capability.${cap}`,\n orbitalName: call.orbital,\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 * `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 'singleton',\n 'instance',\n 'local',\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 { EntityPersistence } from '../types/entity.js';\nimport type { TraitReference } from '../types/trait.js';\nimport type {\n FactoryCallSite,\n FactoryCallSiteParams,\n FactoryParamValue,\n FactorySignature,\n FactoryTraitSignature,\n} from './types.js';\nimport type {\n OwnershipOverlayEntry,\n PresentationNavItem,\n PresentationOverlay,\n RuleOverlay,\n RuleOverlayEntry,\n TraitOverlay,\n TraitOverlayEntry,\n} from './overlays.js';\n\n/**\n * The per-orbital binding the agent assembles when it picks a\n * signature. Carries the user-authored overrides directly; no shared\n * domain ontology, no DomainDocument.\n */\nexport interface TranslationBinding {\n /** Entity name override. When equal to `signature.entities[0].name`,\n * no rename is emitted. */\n entityName: string;\n /** Extra fields beyond the signature's canonical entity surface. */\n entityFields?: ReadonlyArray<EntityField>;\n /** Persistence override. */\n persistence?: EntityPersistence;\n /** Collection name override. */\n collection?: string;\n /** Per-page path overrides keyed by `signature.pages[i].name`. */\n pagePaths?: Readonly<Record<string, string>>;\n}\n\nexport interface TranslationWarning {\n /** Dotted path of the binding field that couldn't be lowered. */\n field: string;\n /** Human-readable reason. */\n reason: string;\n}\n\nexport interface TranslationResult {\n callSite: FactoryCallSite;\n warnings: ReadonlyArray<TranslationWarning>;\n}\n\nexport function translateOverlaysToParams(\n binding: TranslationBinding,\n signature: FactorySignature,\n presentation?: PresentationOverlay,\n ruleOverlay?: RuleOverlay,\n traitOverlay?: TraitOverlay,\n catalog?: ReadonlyArray<FactorySignature>,\n): TranslationResult {\n const warnings: TranslationWarning[] = [];\n const params: FactoryCallSiteParams = {};\n\n applyEntityName(binding, signature, params);\n applyEntityFields(binding, signature, params);\n applyPersistence(binding, signature, params, warnings);\n applyCollection(binding, params);\n applyPagePaths(binding, signature, params, warnings);\n applyPresentation(presentation, signature, params, warnings);\n applyTraitOverlay(traitOverlay, signature, params, warnings);\n applyRuleOverlay(ruleOverlay, signature, binding, catalog, params, warnings);\n\n return {\n callSite: {\n organism: signature.organism,\n orbital: signature.orbital,\n factoryPath: signature.factoryPath,\n params,\n },\n warnings,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Per-field lowering\n// ---------------------------------------------------------------------------\n\nfunction applyEntityName(\n binding: TranslationBinding,\n signature: FactorySignature,\n params: FactoryCallSiteParams,\n): void {\n if (signature.entities.length === 0) return;\n if (binding.entityName === signature.entities[0].name) return;\n params.entityName = binding.entityName;\n}\n\nfunction applyEntityFields(\n binding: TranslationBinding,\n signature: FactorySignature,\n params: FactoryCallSiteParams,\n): void {\n if (!binding.entityFields || binding.entityFields.length === 0) return;\n if (signature.entities.length === 0) {\n params.entityFields = [...binding.entityFields];\n return;\n }\n const canonical = new Set(signature.entities[0].fields.map((f) => f.name));\n const extras: EntityField[] = [];\n for (const f of binding.entityFields) {\n if (f.name && canonical.has(f.name)) continue;\n extras.push(f);\n }\n if (extras.length > 0) params.entityFields = extras;\n}\n\nfunction applyPersistence(\n binding: TranslationBinding,\n signature: FactorySignature,\n params: FactoryCallSiteParams,\n warnings: TranslationWarning[],\n): void {\n if (!binding.persistence) return;\n if (signature.entities.length === 0) {\n warnings.push({\n field: `entity.${binding.entityName}.persistence`,\n reason: 'factory signature has no entity to apply persistence to',\n });\n return;\n }\n if (binding.persistence === signature.entities[0].persistence) return;\n params.persistence = binding.persistence;\n}\n\nfunction applyCollection(\n binding: TranslationBinding,\n params: FactoryCallSiteParams,\n): void {\n if (!binding.collection) return;\n params.collection = binding.collection;\n}\n\nfunction applyPagePaths(\n binding: TranslationBinding,\n signature: FactorySignature,\n params: FactoryCallSiteParams,\n warnings: TranslationWarning[],\n): void {\n if (!binding.pagePaths) return;\n const sigPages = new Map(signature.pages.map((p) => [p.name, p]));\n const overrides: Record<string, string> = {};\n for (const [pageName, url] of Object.entries(binding.pagePaths)) {\n const sig = sigPages.get(pageName);\n if (!sig) {\n warnings.push({\n field: `page.${pageName}.url`,\n reason: `factory signature has no page named \"${pageName}\"`,\n });\n continue;\n }\n if (sig.defaultPath !== url) overrides[pageName] = url;\n }\n if (Object.keys(overrides).length > 0) params.pagePaths = overrides;\n}\n\nfunction applyPresentation(\n overlay: PresentationOverlay | undefined,\n signature: FactorySignature,\n params: FactoryCallSiteParams,\n warnings: TranslationWarning[],\n): void {\n if (!overlay?.navAdditions || overlay.navAdditions.length === 0) return;\n const target = signature.traits.find((t) =>\n t.overridableConfigKeys.some((p) => p.key === 'navItems'),\n );\n if (!target) {\n warnings.push({\n field: 'presentation.navAdditions',\n reason:\n 'factory signature has no trait advertising a `navItems` config key',\n });\n return;\n }\n const existing = params.traitOverrides?.[target.name] ?? {};\n const existingConfig = existing.config ?? {};\n const items: ReadonlyArray<FactoryParamValue> = overlay.navAdditions.map(\n navItemToParamValue,\n );\n params.traitOverrides = {\n ...params.traitOverrides,\n [target.name]: {\n ...existing,\n config: { ...existingConfig, navItems: items },\n },\n };\n}\n\nfunction applyTraitOverlay(\n overlay: TraitOverlay | undefined,\n signature: FactorySignature,\n params: FactoryCallSiteParams,\n warnings: TranslationWarning[],\n): void {\n if (!overlay) return;\n const traitsByName = new Map(signature.traits.map((t) => [t.name, t]));\n for (const [traitName, entry] of Object.entries(overlay)) {\n const trait = traitsByName.get(traitName);\n if (!trait) {\n warnings.push({\n field: `traitOverlay.${traitName}`,\n reason: `factory signature has no trait named \"${traitName}\"`,\n });\n continue;\n }\n mergeTraitOverride(traitName, entry, trait, params, warnings);\n }\n}\n\nfunction mergeTraitOverride(\n traitName: string,\n entry: TraitOverlayEntry,\n trait: FactoryTraitSignature,\n params: FactoryCallSiteParams,\n warnings: TranslationWarning[],\n): void {\n const advertised = new Set(trait.overridableConfigKeys.map((p) => p.key));\n const existing = params.traitOverrides?.[traitName] ?? {};\n const existingConfig = existing.config ?? {};\n const mergedConfig: Record<string, FactoryParamValue> = { ...existingConfig };\n\n if (entry.config) {\n for (const [k, v] of Object.entries(entry.config)) {\n if (!advertised.has(k)) {\n const advertisedKeys = trait.overridableConfigKeys.map((p) => p.key).join(', ');\n warnings.push({\n field: `traitOverlay.${traitName}.config.${k}`,\n reason: `trait does not advertise config key \"${k}\" (overridableConfigKeys: [${advertisedKeys}])`,\n });\n continue;\n }\n mergedConfig[k] = v;\n }\n }\n\n // Thread every documented override field through verbatim — `config`\n // gets the merged + validated map; the rest pass through as the overlay\n // authored them. Pre-unification only `config` was preserved, so any\n // overlay-authored `linkedEntity` / `events` / `name` / `emitsScope` /\n // `listens` was silently dropped before reaching the factory.\n params.traitOverrides = {\n ...params.traitOverrides,\n [traitName]: {\n ...existing,\n ...(Object.keys(mergedConfig).length > 0 ? { config: mergedConfig } : {}),\n ...(entry.linkedEntity !== undefined ? { linkedEntity: entry.linkedEntity } : {}),\n ...(entry.events !== undefined ? { events: entry.events } : {}),\n ...(entry.name !== undefined ? { name: entry.name } : {}),\n ...(entry.emitsScope !== undefined ? { emitsScope: entry.emitsScope } : {}),\n ...(entry.listens !== undefined ? { listens: entry.listens } : {}),\n },\n };\n}\n\nfunction applyRuleOverlay(\n overlay: RuleOverlay | undefined,\n signature: FactorySignature,\n binding: TranslationBinding,\n catalog: ReadonlyArray<FactorySignature> | undefined,\n params: FactoryCallSiteParams,\n warnings: TranslationWarning[],\n): void {\n if (!overlay) return;\n\n // `rule.appliesTo` is frozen at the name in scope when the rule was\n // CAPTURED — typically the canonical entity name. If the caller later\n // rebinds via `params.entityName`, `binding.entityName` carries the\n // rebound name and a direct equality check fails. Match against BOTH\n // the rebound name (current binding) AND the canonical name (the\n // signature's authored entity) so cross-turn rule references survive\n // entity renames.\n const matchableNames = collectMatchableEntityNames(signature, binding);\n\n for (const rule of overlay.rules) {\n if (!ruleAppliesToAnyName(rule, matchableNames)) continue;\n if (!catalog) {\n warnings.push({\n field: `ruleOverlay.rules.${rule.id}`,\n reason: 'rule overlay supplied without a catalog — capability lookup requires one',\n });\n continue;\n }\n const match = findTraitByCapability(catalog, rule.capability);\n if (!match) {\n warnings.push({\n field: `ruleOverlay.rules.${rule.id}`,\n reason: `no trait in the catalog advertises capability \"${rule.capability}\"`,\n });\n continue;\n }\n appendRuleExtraTrait(rule, match, binding, params);\n if (rule.config) {\n threadRuleConfig(rule, match.trait, params, warnings);\n }\n }\n\n if (overlay.ownership) {\n for (const entry of overlay.ownership) {\n if (!matchableNames.includes(entry.entity)) continue;\n applyOwnership(entry, params, signature, catalog, warnings);\n }\n }\n}\n\n/**\n * Names the rule overlay may legitimately target for THIS binding.\n * Includes the rebound entity name (current `binding.entityName`) AND\n * every canonical name on `signature.entities[*]`. Deduped, empty-safe.\n */\nfunction collectMatchableEntityNames(\n signature: FactorySignature,\n binding: TranslationBinding,\n): ReadonlyArray<string> {\n const out = new Set<string>();\n if (binding.entityName.length > 0) out.add(binding.entityName);\n for (const ent of signature.entities) {\n if (typeof ent.name === 'string' && ent.name.length > 0) out.add(ent.name);\n }\n return [...out];\n}\n\nfunction ruleAppliesToAnyName(\n rule: RuleOverlayEntry,\n matchableNames: ReadonlyArray<string>,\n): boolean {\n if (rule.appliesTo.length === 0) return true;\n for (const n of rule.appliesTo) {\n if (matchableNames.includes(n)) return true;\n }\n return false;\n}\n\ninterface CapabilityMatch {\n signature: FactorySignature;\n trait: FactoryTraitSignature;\n}\n\nfunction findTraitByCapability(\n catalog: ReadonlyArray<FactorySignature>,\n capability: string,\n): CapabilityMatch | undefined {\n for (const sig of catalog) {\n for (const trait of sig.traits) {\n if (trait.capabilities.includes(capability)) {\n return { signature: sig, trait };\n }\n }\n }\n return undefined;\n}\n\nfunction appendRuleExtraTrait(\n _rule: RuleOverlayEntry,\n match: CapabilityMatch,\n binding: TranslationBinding,\n params: FactoryCallSiteParams,\n): void {\n const fromPath = `std/behaviors/${match.signature.organism}`;\n const alias = organismToAlias(match.signature.organism);\n const ref: TraitReference = {\n from: fromPath,\n ref: `${alias}.traits.${match.trait.name}`,\n linkedEntity: binding.entityName,\n };\n const existing = params.extraTraits ?? [];\n params.extraTraits = [...existing, ref];\n}\n\nfunction organismToAlias(organism: string): string {\n const trimmed = organism.startsWith('std-') ? organism.slice(4) : organism;\n return trimmed\n .split('-')\n .filter((s) => s.length > 0)\n .map((s) => s.charAt(0).toUpperCase() + s.slice(1))\n .join('');\n}\n\nfunction threadRuleConfig(\n rule: RuleOverlayEntry,\n trait: FactoryTraitSignature,\n params: FactoryCallSiteParams,\n warnings: TranslationWarning[],\n): void {\n if (!rule.config) return;\n const advertised = new Set(trait.overridableConfigKeys.map((p) => p.key));\n const existing = params.traitOverrides?.[trait.name] ?? {};\n const existingConfig = existing.config ?? {};\n const merged: Record<string, FactoryParamValue> = { ...existingConfig };\n for (const [k, v] of Object.entries(rule.config)) {\n if (!advertised.has(k)) {\n warnings.push({\n field: `ruleOverlay.rules.${rule.id}.config.${k}`,\n reason: `trait \"${trait.name}\" does not advertise config key \"${k}\"`,\n });\n continue;\n }\n merged[k] = v;\n }\n if (Object.keys(merged).length > 0) {\n params.traitOverrides = {\n ...params.traitOverrides,\n [trait.name]: { ...existing, config: merged },\n };\n }\n}\n\nfunction applyOwnership(\n entry: OwnershipOverlayEntry,\n params: FactoryCallSiteParams,\n signature: FactorySignature,\n catalog: ReadonlyArray<FactorySignature> | undefined,\n warnings: TranslationWarning[],\n): void {\n const local = signature.traits.find((t) =>\n t.overridableConfigKeys.some((p) => p.key === 'ownerField'),\n );\n if (local) {\n writeOwnerField(local.name, entry.ownerField, params);\n return;\n }\n if (catalog) {\n for (const sig of catalog) {\n const trait = sig.traits.find((t) =>\n t.overridableConfigKeys.some((p) => p.key === 'ownerField'),\n );\n if (trait) {\n writeOwnerField(trait.name, entry.ownerField, params);\n return;\n }\n }\n }\n warnings.push({\n field: `ruleOverlay.ownership.${entry.entity}`,\n reason: 'no trait in the bound signature or catalog advertises an `ownerField` config knob',\n });\n}\n\nfunction writeOwnerField(\n traitName: string,\n ownerField: string,\n params: FactoryCallSiteParams,\n): void {\n const existing = params.traitOverrides?.[traitName] ?? {};\n const existingConfig = existing.config ?? {};\n params.traitOverrides = {\n ...params.traitOverrides,\n [traitName]: {\n ...existing,\n config: { ...existingConfig, ownerField },\n },\n };\n}\n\nfunction navItemToParamValue(item: PresentationNavItem): FactoryParamValue {\n const out: Record<string, FactoryParamValue> = {\n label: item.label,\n path: item.path,\n };\n if (item.icon) out.icon = item.icon;\n return out;\n}\n","/**\n * Structural diff between two `FactoryCallSite[]` lists. Pure typed,\n * no side effects. Used by downstream consumers (agent planner, UI\n * cascade view) to turn a \"previous calls\" + \"next calls\" pair into a\n * minimal change set.\n *\n * Identity for diffing is `(organism, orbital)`. Renames are not\n * handled here — they show up as a delete + add. The agent layer is\n * expected to merge those back into a `'rename'` op if it can prove\n * the underlying domain entity was renamed.\n */\n\nimport type {\n FactoryCallSite,\n FactoryCallSiteParams,\n FactoryParamValue,\n} from './types.js';\n\nexport type CallSiteDiff =\n | { kind: 'add'; orbitalName: string; next: FactoryCallSite }\n | { kind: 'delete'; orbitalName: string; prior: FactoryCallSite }\n | {\n kind: 'edit';\n orbitalName: string;\n prior: FactoryCallSite;\n next: FactoryCallSite;\n }\n | { kind: 'keep'; orbitalName: string; call: FactoryCallSite };\n\nexport function diffFactoryCalls(\n prior: ReadonlyArray<FactoryCallSite>,\n next: ReadonlyArray<FactoryCallSite>,\n): ReadonlyArray<CallSiteDiff> {\n const out: CallSiteDiff[] = [];\n const priorByKey = new Map(prior.map((c) => [callKey(c), c]));\n const nextByKey = new Map(next.map((c) => [callKey(c), c]));\n\n for (const [key, p] of priorByKey) {\n const n = nextByKey.get(key);\n if (!n) {\n out.push({ kind: 'delete', orbitalName: p.orbital, prior: p });\n continue;\n }\n if (paramsEqual(p.params, n.params)) {\n out.push({ kind: 'keep', orbitalName: p.orbital, call: n });\n } else {\n out.push({ kind: 'edit', orbitalName: p.orbital, prior: p, next: n });\n }\n }\n for (const [key, n] of nextByKey) {\n if (!priorByKey.has(key)) {\n out.push({ kind: 'add', orbitalName: n.orbital, next: n });\n }\n }\n return out;\n}\n\nfunction callKey(c: FactoryCallSite): string {\n return `${c.organism}::${c.orbital}`;\n}\n\nfunction paramsEqual(a: FactoryCallSiteParams, b: FactoryCallSiteParams): boolean {\n return canonicalParams(a) === canonicalParams(b);\n}\n\nfunction canonicalParams(p: FactoryCallSiteParams): string {\n const keys: Array<keyof FactoryCallSiteParams> = [\n 'collection',\n 'entityFields',\n 'entityName',\n 'extraTraits',\n 'pagePaths',\n 'persistence',\n 'traitOverrides',\n ];\n const parts: string[] = [];\n for (const k of keys) {\n const v = p[k];\n if (v === undefined) continue;\n parts.push(`${k}:${canonicalNode(v)}`);\n }\n return `{${parts.join(',')}}`;\n}\n\nfunction canonicalNode(\n v:\n | string\n | FactoryCallSiteParams[keyof FactoryCallSiteParams],\n): string {\n if (v === undefined) return 'u';\n if (typeof v === 'string') return JSON.stringify(v);\n if (Array.isArray(v)) {\n return `[${v.map((x) => canonicalParamValue(x as FactoryParamValue)).join(',')}]`;\n }\n const keys = Object.keys(v).sort();\n const parts: string[] = [];\n for (const k of keys) {\n const child = (v as Readonly<Record<string, FactoryParamValue | { config?: Readonly<Record<string, FactoryParamValue>> }>>)[k];\n parts.push(`${JSON.stringify(k)}:${canonicalParamValue(child)}`);\n }\n return `{${parts.join(',')}}`;\n}\n\nfunction canonicalParamValue(\n v: FactoryParamValue | { config?: Readonly<Record<string, FactoryParamValue>> },\n): string {\n if (v === null || v === undefined) return 'u';\n if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') {\n return JSON.stringify(v);\n }\n if (Array.isArray(v)) {\n return `[${v.map(canonicalParamValue).join(',')}]`;\n }\n const keys = Object.keys(v).sort();\n const parts: string[] = [];\n for (const k of keys) {\n const child = (v as Readonly<Record<string, FactoryParamValue | undefined>>)[k];\n if (child === undefined) continue;\n parts.push(`${JSON.stringify(k)}:${canonicalParamValue(child)}`);\n }\n return `{${parts.join(',')}}`;\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 * Layout Strategy Detection\n *\n * Auto-detects the best layout strategy for a composed application\n * based on the number of orbitals and their event wiring topology.\n *\n * @packageDocumentation\n */\n\nimport type { OrbitalDefinition } from '../types/orbital.js';\nimport type { EventWiringEntry } from './event-wiring.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Layout strategy for the composed application.\n *\n * - 'single': One orbital, one page\n * - 'tabs': 2-4 orbitals with no sequential chain\n * - 'sidebar': 5+ orbitals (navigation-heavy)\n * - 'dashboard': Single page with all orbitals visible\n * - 'wizard-flow': Sequential event chain detected (A -> B -> C)\n */\nexport type LayoutStrategy =\n | 'sidebar'\n | 'tabs'\n | 'dashboard'\n | 'wizard-flow'\n | 'single';\n\n// ============================================================================\n// Chain Detection\n// ============================================================================\n\n/**\n * Detect whether the event wiring forms a sequential chain.\n *\n * A sequential chain exists when orbital A's `from` feeds into B's `to`,\n * and B's `from` feeds into C's `to`, forming A -> B -> C.\n *\n * We build a directed graph from wiring entries and look for a chain\n * that covers 3+ nodes (the minimum for a meaningful wizard flow).\n */\nfunction hasSequentialChain(wiring: EventWiringEntry[]): boolean {\n if (wiring.length < 2) {\n return false;\n }\n\n // Build adjacency: from -> Set<to>\n const adjacency = new Map<string, Set<string>>();\n const allTargets = new Set<string>();\n\n for (const entry of wiring) {\n let targets = adjacency.get(entry.from);\n if (!targets) {\n targets = new Set<string>();\n adjacency.set(entry.from, targets);\n }\n targets.add(entry.to);\n allTargets.add(entry.to);\n }\n\n // Find roots (nodes that are sources but never targets)\n const roots: string[] = [];\n for (const from of adjacency.keys()) {\n if (!allTargets.has(from)) {\n roots.push(from);\n }\n }\n\n // If no clear root, try all sources\n const starts = roots.length > 0 ? roots : [...adjacency.keys()];\n\n // Walk from each start and measure chain length\n for (const start of starts) {\n let current = start;\n let length = 1;\n const visited = new Set<string>([current]);\n\n while (true) {\n const nexts = adjacency.get(current);\n if (!nexts || nexts.size === 0) break;\n\n // Follow the first unvisited successor (linear chain)\n let advanced = false;\n for (const next of nexts) {\n if (!visited.has(next)) {\n visited.add(next);\n current = next;\n length++;\n advanced = true;\n break;\n }\n }\n\n if (!advanced) break;\n }\n\n // A chain of 3+ nodes qualifies as wizard-flow\n if (length >= 3) {\n return true;\n }\n }\n\n return false;\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Detect the best layout strategy based on orbital count and event wiring.\n *\n * Heuristic:\n * 1. Sequential event chain detected -> 'wizard-flow'\n * 2. 1 orbital -> 'single'\n * 3. 2-4 orbitals -> 'tabs'\n * 4. 5+ orbitals -> 'sidebar'\n */\nexport function detectLayoutStrategy(\n orbitals: OrbitalDefinition[],\n eventWiring?: EventWiringEntry[],\n): LayoutStrategy {\n // Check for sequential chain first (takes priority)\n if (eventWiring && eventWiring.length > 0 && hasSequentialChain(eventWiring)) {\n return 'wizard-flow';\n }\n\n const count = orbitals.length;\n\n if (count <= 1) {\n return 'single';\n }\n\n if (count <= 4) {\n return 'tabs';\n }\n\n return 'sidebar';\n}\n","/**\n * Event Wiring\n *\n * Applies cross-orbital event wiring to orbital definitions.\n * Adds emits/listens declarations to traits so they can communicate\n * across orbital boundaries.\n *\n * @packageDocumentation\n */\n\nimport type { OrbitalDefinition } from '../types/orbital.js';\nimport type { Trait, TraitEventContract, TraitEventListener } from '../types/trait.js';\nimport { isInlineTrait } from '../types/trait.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * A single event wiring entry connecting two traits across orbitals.\n */\nexport interface EventWiringEntry {\n /** Source trait name or orbital name */\n from: string;\n /** Event name (UPPER_SNAKE_CASE) */\n event: string;\n /** Target trait name or orbital name */\n to: string;\n /** Event to trigger on the listener side */\n triggers: string;\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/**\n * Find a trait by name across all orbitals.\n * Only inline traits can be mutated; string/ref traits are skipped.\n * Returns the inline Trait object if found, or null.\n */\nfunction findInlineTrait(\n orbitals: OrbitalDefinition[],\n name: string,\n): Trait | null {\n for (const orbital of orbitals) {\n for (const traitRef of orbital.traits) {\n if (isInlineTrait(traitRef) && traitRef.name === name) {\n return traitRef;\n }\n }\n }\n return null;\n}\n\n/**\n * Check if an emit already exists in the list.\n * @internal\n */\nfunction hasEmit(emits: TraitEventContract[], event: string): boolean {\n return emits.some((e) => e.event === event);\n}\n\n/**\n * Check if a listen already exists in the list.\n * @internal\n */\nfunction hasListen(\n listens: TraitEventListener[],\n event: string,\n triggers: string,\n): boolean {\n return listens.some((l) => l.event === event && l.triggers === triggers);\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Apply event wiring to orbital definitions.\n *\n * For each wiring entry:\n * 1. Find the source trait and add an external emit (if not already present)\n * 2. Find the target trait and add an external listen (if not already present)\n *\n * Returns a new array of orbitals with wiring applied (deep-cloned).\n */\nexport function applyEventWiring(\n orbitals: OrbitalDefinition[],\n wiring: EventWiringEntry[],\n): OrbitalDefinition[] {\n // Deep clone to avoid mutating input\n const cloned: OrbitalDefinition[] = JSON.parse(\n JSON.stringify(orbitals),\n ) as OrbitalDefinition[];\n\n for (const entry of wiring) {\n // Wire the source: add emit\n const sourceTrait = findInlineTrait(cloned, entry.from);\n if (sourceTrait) {\n if (!sourceTrait.emits) {\n sourceTrait.emits = [];\n }\n if (!hasEmit(sourceTrait.emits, entry.event)) {\n sourceTrait.emits.push({\n event: entry.event,\n scope: 'external',\n });\n }\n }\n\n // Wire the target: add listen\n const targetTrait = findInlineTrait(cloned, entry.to);\n if (targetTrait) {\n if (!targetTrait.listens) {\n targetTrait.listens = [];\n }\n if (!hasListen(targetTrait.listens, entry.event, entry.triggers)) {\n targetTrait.listens.push({\n event: entry.event,\n triggers: entry.triggers,\n scope: 'external',\n });\n }\n }\n }\n\n return cloned;\n}\n","/**\n * Compose Behaviors\n *\n * Main entry point for composing multiple orbital definitions into\n * a single OrbitalSchema application. Handles event wiring, layout\n * strategy detection, and page generation.\n *\n * @packageDocumentation\n */\n\nimport type { OrbitalDefinition } from '../types/orbital.js';\nimport type { OrbitalSchema } from '../types/schema.js';\n\n/** Unwrap OrbitalSchema | OrbitalDefinition inputs to a flat OrbitalDefinition[]. */\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}\nimport type { Page } from '../types/page.js';\nimport type { EventWiringEntry } from './event-wiring.js';\nimport { applyEventWiring } from './event-wiring.js';\nimport type { LayoutStrategy } from './layout-strategy.js';\nimport { detectLayoutStrategy } from './layout-strategy.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Input for composing behaviors into an application.\n */\nexport interface ComposeBehaviorsInput {\n /** Application name */\n appName: string;\n /** Orbital definitions (or schemas) to compose */\n orbitals: (OrbitalDefinition | OrbitalSchema)[];\n /** Layout strategy override, or 'auto' to detect */\n layoutStrategy?: LayoutStrategy | 'auto';\n /** Cross-orbital event wiring */\n eventWiring?: EventWiringEntry[];\n /** Optional entity name mappings (original -> renamed) */\n entityMappings?: Record<string, string>;\n}\n\n/**\n * Result of composing behaviors.\n */\nexport interface ComposeBehaviorsResult {\n /** The composed OrbitalSchema */\n schema: OrbitalSchema;\n /** Layout metadata */\n layout: { strategy: LayoutStrategy; pageCount: number };\n /** Wiring metadata */\n wiring: { connections: number };\n}\n\n// ============================================================================\n// Page Generation\n// ============================================================================\n\nfunction toKebabCase(name: string): string {\n return name\n .replace(/([a-z])([A-Z])/g, '$1-$2')\n .replace(/[\\s_]+/g, '-')\n .toLowerCase();\n}\n\n/**\n * Generate pages for each orbital based on the layout strategy.\n *\n * For strategies that produce one page per orbital (sidebar, tabs, wizard-flow),\n * each orbital gets a page at `/<kebab-name>` with `isInitial` on the first.\n *\n * For 'dashboard', all orbitals share a single page.\n * For 'single', the lone orbital gets a single root page.\n */\nfunction generatePages(\n orbitals: OrbitalDefinition[],\n strategy: LayoutStrategy,\n): Page[] {\n switch (strategy) {\n case 'single': {\n const orbital = orbitals[0];\n const name = orbital?.name ?? 'Main';\n return [\n {\n name: `${name}Page`,\n path: '/',\n isInitial: true,\n primaryEntity: getEntityName(orbital),\n },\n ];\n }\n\n case 'dashboard': {\n return [\n {\n name: 'DashboardPage',\n path: '/',\n viewType: 'dashboard',\n isInitial: true,\n },\n ];\n }\n\n case 'sidebar':\n case 'tabs':\n case 'wizard-flow': {\n return orbitals.map((orbital, index) => ({\n name: `${orbital.name}Page`,\n path: index === 0 ? '/' : `/${toKebabCase(orbital.name)}`,\n isInitial: index === 0,\n primaryEntity: getEntityName(orbital),\n }));\n }\n }\n}\n\n/**\n * Extract entity name from an orbital definition.\n * Handles both inline entities and string references.\n */\nfunction getEntityName(orbital: OrbitalDefinition | undefined): string | undefined {\n if (!orbital) return undefined;\n const entity = orbital.entity;\n if (typeof entity === 'string') {\n // Reference like \"Alias.entity\" - extract the alias as entity name\n return entity.replace('.entity', '');\n }\n return entity.name;\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Compose multiple orbital definitions into a single application schema.\n *\n * Steps:\n * 1. Apply event wiring (adds emits/listens to traits)\n * 2. Detect or use provided layout strategy\n * 3. Generate pages based on the strategy\n * 4. Build the final OrbitalSchema\n */\nexport function composeBehaviors(\n input: ComposeBehaviorsInput,\n): ComposeBehaviorsResult {\n const {\n appName,\n orbitals: rawInputs,\n layoutStrategy: strategyInput,\n eventWiring,\n } = input;\n\n // Unwrap any OrbitalSchema inputs to OrbitalDefinition[]\n const rawOrbitals = asDefinitions(rawInputs);\n\n // Step 1: Apply event wiring\n const wiredOrbitals =\n eventWiring && eventWiring.length > 0\n ? applyEventWiring(rawOrbitals, eventWiring)\n : rawOrbitals;\n\n // Step 2: Determine layout strategy\n const strategy: LayoutStrategy =\n !strategyInput || strategyInput === 'auto'\n ? detectLayoutStrategy(wiredOrbitals, eventWiring)\n : strategyInput;\n\n // Step 3: Generate pages\n const pages = generatePages(wiredOrbitals, strategy);\n\n // Step 4: Assign generated pages to orbitals (merge, don't replace existing)\n const orbitalsWithPages = wiredOrbitals.map((orbital, index) => {\n // If the orbital already has pages, keep them\n if (orbital.pages && orbital.pages.length > 0) {\n return orbital;\n }\n\n // Assign the generated page for this orbital\n const page = strategy === 'dashboard' || strategy === 'single'\n ? pages[0]\n : pages[index];\n\n return {\n ...orbital,\n pages: page ? [page] : [],\n };\n });\n\n // Step 5: Build the schema\n const schema: OrbitalSchema = {\n name: appName,\n version: '1.0.0',\n orbitals: orbitalsWithPages,\n };\n\n return {\n schema,\n layout: {\n strategy,\n pageCount: pages.length,\n },\n wiring: {\n connections: eventWiring?.length ?? 0,\n },\n };\n}\n","/**\n * State Graph Construction\n *\n * Build an adjacency list from state machine transitions.\n * Extracted from orbital-verify-unified/src/analyze.ts.\n *\n * @packageDocumentation\n */\n\nimport type { GraphTransition, StateEdge } from './types.js';\n\n/**\n * Builds an adjacency list from state machine transitions.\n * \n * Constructs a state transition graph where each state maps to an array\n * of outgoing edges (events and target states). Wildcard transitions\n * (from === '*') are excluded since they don't represent fixed edges.\n * Used as the foundation for state machine analysis, traversal, and verification.\n * \n * @param {GraphTransition[]} transitions - Array of state transitions\n * @returns {Map<string, StateEdge[]>} State transition graph\n * \n * @example\n * const graph = buildStateGraph(transitions);\n * const edgesFromInitial = graph.get('initial'); // Array of outgoing edges\n * console.log(`Initial state has ${edgesFromInitial?.length} transitions`);\n */\nexport function buildStateGraph(\n transitions: GraphTransition[]\n): Map<string, StateEdge[]> {\n const graph = new Map<string, StateEdge[]>();\n for (const t of transitions) {\n if (t.from === '*') continue;\n if (!graph.has(t.from)) graph.set(t.from, []);\n graph.get(t.from)!.push({ event: t.event, to: t.to });\n }\n return graph;\n}\n","/**\n * BFS Reachability Algorithms\n *\n * Breadth-first search over state machine graphs.\n * Extracted from orbital-verify-unified/src/analyze.ts and phase3-server.ts.\n *\n * @packageDocumentation\n */\n\nimport type { BFSNode, StateEdge } from './types.js';\nimport { buildStateGraph } from './graph.js';\nimport type { GraphTransition } from './types.js';\n\n/**\n * Collects all reachable states from an initial state using breadth-first search.\n * \n * Performs BFS traversal of the state machine to find all states reachable\n * from the initial state, up to the specified maximum depth. Used for\n * state machine analysis, verification, and test coverage assessment.\n * \n * @param {GraphTransition[]} transitions - Array of state transitions\n * @param {string} initialState - Starting state name\n * @param {number} [maxDepth=5] - Maximum search depth\n * @returns {Set<string>} Set of reachable state names\n * \n * @example\n * const reachable = collectReachableStates(transitions, 'initial', 10);\n * console.log('Reachable states:', Array.from(reachable));\n */\nexport function collectReachableStates(\n transitions: GraphTransition[],\n initialState: string,\n maxDepth = 5\n): Set<string> {\n const graph = buildStateGraph(transitions);\n const visited = new Set<string>([initialState]);\n const queue: BFSNode[] = [{ state: initialState, depth: 0 }];\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n if (current.depth >= maxDepth) continue;\n\n const edges = graph.get(current.state) ?? [];\n for (const edge of edges) {\n if (!visited.has(edge.to)) {\n visited.add(edge.to);\n queue.push({ state: edge.to, depth: current.depth + 1 });\n }\n }\n }\n\n return visited;\n}\n\n/**\n * Walks all reachable (state, event) pairs using BFS and invokes callback for each.\n * \n * Traverses the state machine using breadth-first search and calls the visitor\n * function for each (state, edge) pair encountered. Used by server verification\n * to test transitions by POSTing to endpoints and checking responses.\n * \n * @param {GraphTransition[]} transitions - Array of state transitions\n * @param {string} initialState - Starting state name\n * @param {number} maxDepth - Maximum BFS depth\n * @param {(state: string, edge: StateEdge, depth: number) => Promise<boolean>} visitor - Callback for each pair\n * @returns {Promise<{ visitedPairs: Set<string>; walkedEdges: number }>} Traversal statistics\n * \n * @example\n * const result = await walkStatePairs(transitions, 'initial', 5, async (state, edge) => {\n * console.log(`Transition: ${state} --${edge.event}--> ${edge.to}`);\n * return true; // Continue exploration\n * });\n * console.log(`Visited ${result.visitedPairs.size} state-event pairs`);\n */\nexport async function walkStatePairs(\n transitions: GraphTransition[],\n initialState: string,\n maxDepth: number,\n visitor: (state: string, edge: StateEdge, depth: number) => Promise<boolean>\n): Promise<{ visitedPairs: Set<string>; walkedEdges: number }> {\n const graph = buildStateGraph(transitions);\n const visitedPairs = new Set<string>();\n const queue: BFSNode[] = [{ state: initialState, depth: 0 }];\n let walkedEdges = 0;\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n if (current.depth >= maxDepth) continue;\n\n const edges = graph.get(current.state) ?? [];\n for (const edge of edges) {\n const pairKey = `${current.state}:${edge.event}`;\n if (visitedPairs.has(pairKey)) continue;\n visitedPairs.add(pairKey);\n\n const shouldEnqueue = await visitor(current.state, edge, current.depth);\n walkedEdges++;\n\n if (shouldEnqueue) {\n const stateVisited = [...visitedPairs].some((k) => k.startsWith(`${edge.to}:`));\n if (!stateVisited) {\n queue.push({ state: edge.to, depth: current.depth + 1 });\n }\n }\n }\n }\n\n return { visitedPairs, walkedEdges };\n}\n","/**\n * Guard Payload Builder\n *\n * Derive pass and fail payloads from guard s-expressions.\n * Extracted from orbital-verify-unified/src/analyze.ts.\n *\n * @packageDocumentation\n */\n\nimport type { GuardPayload } from './types.js';\n\n/**\n * Extracts the first segment of a payload field reference.\n * \n * Parses binding references in the format \"@payload.field\" and extracts\n * the first field name segment. Used for identifying payload fields in\n * guard conditions for test data generation.\n * \n * @param {unknown} ref - Binding reference to extract from\n * @returns {string | null} First field segment or null for non-payload references\n * \n * @example\n * extractPayloadFieldRef('@payload.item'); // returns 'item'\n * extractPayloadFieldRef('@payload.data.weight'); // returns 'data'\n * extractPayloadFieldRef('@entity.id'); // returns null\n * extractPayloadFieldRef('@user.name'); // returns null\n */\nexport function extractPayloadFieldRef(ref: unknown): string | null {\n if (typeof ref !== 'string') return null;\n const match = ref.match(/^@payload\\.([A-Za-z0-9_]+)/);\n return match ? match[1] : null;\n}\n\n/**\n * Builds test payloads that satisfy or violate guard conditions.\n * \n * Generates pass/fail test data for guard s-expressions used in state machine\n * transitions. Pass payloads satisfy the guard condition (allowing transition),\n * fail payloads violate it (blocking transition). Used for automated testing\n * and validation of state machine behavior.\n * \n * Supports operators: not-nil, nil, eq, not-eq, gt, gte, lt, lte, and, or, not\n * \n * @param {unknown} guard - Guard s-expression to analyze\n * @returns {GuardPayload} Object with pass and fail payloads\n * \n * @example\n * // Guard: ['not-nil', '@payload.completed']\n * buildGuardPayloads(['not-nil', '@payload.completed']);\n * // Returns: { pass: { completed: 'mock-test-value' }, fail: { completed: null } }\n * \n * @example\n * // Guard: ['eq', '@payload.status', 'active']\n * buildGuardPayloads(['eq', '@payload.status', 'active']);\n * // Returns: { pass: { status: 'active' }, fail: { status: 'not-active' } }\n * \n * @example\n * // Guard: ['and', ['not-nil', '@payload.id'], ['eq', '@payload.status', 'ready']]\n * buildGuardPayloads(['and', ['not-nil', '@payload.id'], ['eq', '@payload.status', 'ready']]);\n * // Returns: { pass: { id: 'mock-test-value', status: 'ready' }, fail: { id: null } }\n */\n/**\n * Evaluate a guard that is fully constant (no `@payload`/`@entity`/`@config`\n * bindings — e.g. after molecule/organism inlining folds `@config.mode` to a\n * literal). Returns the constant truth value, or `null` when the guard depends\n * on a binding (so a payload must be synthesized). This lets callers (a) emit\n * an empty payload for a constant guard (no field to satisfy) and (b) skip the\n * meaningless variant: an always-true guard has no fail case, an always-false\n * guard has no pass case. Without it, `(or (= \"create\" \"create\") @payload.row)`\n * (create-mode modal OPEN) was synthesized with a spurious `row`, which the\n * runtime read as edit-mode and rejected.\n */\nexport function constTruth(guard: unknown): boolean | null {\n if (typeof guard === 'boolean') return guard;\n if (typeof guard === 'string') {\n if (guard.startsWith('@')) return null; // a binding — not constant\n return guard.length > 0; // bare non-binding literal: truthy iff non-empty\n }\n if (!Array.isArray(guard) || guard.length === 0) return null;\n const op = String(guard[0]);\n const isLiteral = (x: unknown): boolean =>\n x === null ||\n typeof x === 'number' ||\n typeof x === 'boolean' ||\n (typeof x === 'string' && !x.startsWith('@'));\n if (op === '=' || op === '==' || op === 'eq') {\n return isLiteral(guard[1]) && isLiteral(guard[2]) ? guard[1] === guard[2] : null;\n }\n if (op === '!=' || op === 'ne' || op === 'not-eq' || op === 'neq') {\n return isLiteral(guard[1]) && isLiteral(guard[2]) ? guard[1] !== guard[2] : null;\n }\n if (op === 'not') {\n const inner = constTruth(guard[1]);\n return inner === null ? null : !inner;\n }\n if (op === 'or') {\n const subs = (guard.slice(1) as unknown[]).map(constTruth);\n if (subs.some((s) => s === true)) return true; // short-circuit\n if (subs.every((s) => s === false)) return false;\n return null;\n }\n if (op === 'and') {\n const subs = (guard.slice(1) as unknown[]).map(constTruth);\n if (subs.some((s) => s === false)) return false; // short-circuit\n if (subs.every((s) => s === true)) return true;\n return null;\n }\n return null;\n}\n\nexport function buildGuardPayloads(guard: unknown): GuardPayload {\n // A fully-constant guard (post-inline literal fold) is decided by its\n // literals, not by the payload — synthesize nothing for either case.\n if (constTruth(guard) !== null) {\n return { pass: {}, fail: {} };\n }\n // Bare-binding existence guard: e.g. `when @payload.row` lowers to\n // the string `\"@payload.row\"`. The transition fires iff that field is\n // truthy. Synthesize pass with a truthy mock and fail with null so\n // the verifier can drive both branches. Without this, std-confirmation\n // and std-modal's existence guards (REQUEST/EDIT requiring @payload.row)\n // get empty payloads in both cases — the pass case then fails the\n // server-side guard and the portal observer flags \"slot not mounted\".\n if (typeof guard === 'string') {\n const field = extractPayloadFieldRef(guard);\n if (field) return { pass: { [field]: { id: 'mock-test-id', name: 'mock-test-name' } }, fail: { [field]: null } };\n }\n\n if (!Array.isArray(guard) || guard.length === 0) {\n return { pass: {}, fail: {} };\n }\n\n const op = String(guard[0]);\n\n if (op === 'not-nil' || op === 'not_nil') {\n const field = extractPayloadFieldRef(guard[1]);\n if (field) return { pass: { [field]: 'mock-test-value' }, fail: { [field]: null } };\n }\n\n if (op === 'nil') {\n const field = extractPayloadFieldRef(guard[1]);\n if (field) return { pass: {}, fail: { [field]: 'mock-test-value' } };\n }\n\n if (op === 'eq' || op === '==' || op === '=') {\n const field = extractPayloadFieldRef(guard[1]);\n const val = guard[2];\n if (field && val !== undefined) {\n const failVal =\n typeof val === 'number' ? val + 1\n : typeof val === 'string' ? `not-${val}`\n : null;\n return { pass: { [field]: val }, fail: { [field]: failVal } };\n }\n }\n\n if (op === 'not-eq' || op === '!=' || op === 'neq') {\n const field = extractPayloadFieldRef(guard[1]);\n const val = guard[2];\n if (field && val !== undefined) {\n const passVal =\n typeof val === 'number' ? val + 1\n : typeof val === 'string' ? `not-${val}`\n : 'other';\n return { pass: { [field]: passVal }, fail: { [field]: val } };\n }\n }\n\n if (op === 'gt' || op === '>') {\n const field = extractPayloadFieldRef(guard[1]);\n const n = typeof guard[2] === 'number' ? guard[2] : 0;\n if (field) return { pass: { [field]: n + 1 }, fail: { [field]: n - 1 } };\n }\n\n if (op === 'gte' || op === '>=') {\n const field = extractPayloadFieldRef(guard[1]);\n const n = typeof guard[2] === 'number' ? guard[2] : 0;\n if (field) return { pass: { [field]: n }, fail: { [field]: n - 1 } };\n }\n\n if (op === 'lt' || op === '<') {\n const field = extractPayloadFieldRef(guard[1]);\n const n = typeof guard[2] === 'number' ? guard[2] : 0;\n if (field) return { pass: { [field]: n - 1 }, fail: { [field]: n + 1 } };\n }\n\n if (op === 'lte' || op === '<=') {\n const field = extractPayloadFieldRef(guard[1]);\n const n = typeof guard[2] === 'number' ? guard[2] : 0;\n if (field) return { pass: { [field]: n }, fail: { [field]: n + 1 } };\n }\n\n if (op === 'and') {\n // Accept BOTH array sub-guards and bare-binding string sub-guards\n // (e.g. `(and \"@payload.row\" (not-nil \"@payload.id\"))`). Dropping the\n // bare strings with filter(Array.isArray) lost their fields from the\n // pass payload. AND passes iff every sub-guard passes, so merge all\n // sub-guards' pass payloads; AND fails iff any sub-guard fails, so the\n // first sub-guard's fail payload is a sufficient violation.\n const subs = guard.slice(1) as unknown[];\n if (subs.length >= 2) {\n const built = subs.map(buildGuardPayloads);\n const pass = built.reduce<GuardPayload['pass']>((acc, b) => ({ ...acc, ...b.pass }), {});\n return { pass, fail: built[0].fail };\n }\n if (subs.length === 1) return buildGuardPayloads(subs[0]);\n }\n\n if (op === 'or') {\n // Accept BOTH array sub-guards and bare-binding string sub-guards\n // (post-substitution mode-aware guards like\n // `(or (= \"edit\" \"create\") \"@payload.row\")` mix array + string children).\n const subs = guard.slice(1) as unknown[];\n if (subs.length >= 2) {\n const s1 = buildGuardPayloads(subs[0]);\n const s2 = buildGuardPayloads(subs[1]);\n // For OR: pass if EITHER branch passes. Prefer the second branch's\n // pass payload if the first yields nothing useful — the literal-fold\n // case `(= \"edit\" \"create\") || @payload.row` has the first branch\n // return `{}` and the row-payload comes from the second.\n const combinedPass = Object.keys(s1.pass).length > 0 ? s1.pass : s2.pass;\n return { pass: combinedPass, fail: { ...s1.fail, ...s2.fail } };\n }\n if (subs.length === 1) return buildGuardPayloads(subs[0]);\n }\n\n if (op === 'not') {\n const inner = buildGuardPayloads(guard[1]);\n return { pass: inner.fail, fail: inner.pass };\n }\n\n // Agent pure operators used in guards\n if (op === 'agent/is-pinned') {\n const field = extractPayloadFieldRef(guard[1]);\n if (field) return { pass: { [field]: 'mem_test_unpinned' }, fail: { [field]: 'mem_test_pinned' } };\n }\n\n if (op === 'agent/memory-strength') {\n const field = extractPayloadFieldRef(guard[1]);\n if (field) return { pass: { [field]: 'mem_test_id' }, fail: { [field]: 'mem_nonexistent' } };\n }\n\n // Agent operators in comparison contexts (e.g., [\">=\", [\"agent/context-usage\"], 0.85])\n // These don't use @payload, they query agent state directly. Return empty payloads\n // since the guard result depends on agent context, not event payload.\n if (op.startsWith('agent/')) {\n return { pass: {}, fail: {} };\n }\n\n return { pass: {}, fail: {} };\n}\n","/**\n * Replay Path Builder\n *\n * Compute the shortest path (replay steps) from an initial state\n * to every reachable state in a state machine. Used by browser\n * verification to navigate through states before running assertions.\n *\n * Extracted from orbital-verify-unified/src/analyze.ts (collectDataMutationTests).\n *\n * @packageDocumentation\n */\n\nimport type { GraphTransition, ReplayStep, PayloadFieldSchema } from './types.js';\n\n/** Entity-data sentinel payload fields: presence means transition needs a selected row */\nconst ENTITY_PAYLOAD_FIELDS = new Set(['data', 'row', 'item', 'id']);\n\n/**\n * Extended transition with render and payload info needed for replay path building.\n * Compatible with orbital-verify's UnifiedTransition.\n */\nexport interface ReplayTransition extends GraphTransition {\n hasGuard: boolean;\n guard?: unknown[];\n payloadFields: string[];\n payloadSchema: PayloadFieldSchema[];\n renderEffects: Array<{\n slot: string;\n patternType: string | null;\n }>;\n}\n\n/**\n * Builds the shortest replay paths from initial state to all reachable states.\n * \n * Computes step-by-step navigation paths for state machine testing and verification.\n * Uses breadth-first search to find shortest paths up to specified depth limit.\n * Each path contains replay steps with event, state, and payload information\n * needed to reproduce state transitions in tests.\n * \n * @param {ReplayTransition[]} transitions - Transitions with render/payload information\n * @param {string} initialState - Starting state name\n * @param {number} [maxDepth=3] - Maximum path length (default: 3)\n * @returns {Map<string, ReplayStep[]>} Map of state names to replay step arrays\n * \n * @example\n * // Build paths from 'initial' state\n * const paths = buildReplayPaths(transitions, 'initial', 5);\n * \n * // Get steps to reach 'completed' state\n * const stepsToComplete = paths.get('completed');\n * \n * // Execute replay steps\n * for (const step of stepsToComplete) {\n * await dispatchEvent(step.event, step.payload);\n * }\n */\nexport function buildReplayPaths(\n transitions: ReplayTransition[],\n initialState: string,\n maxDepth = 3\n): Map<string, ReplayStep[]> {\n type QueueNode = { state: string; path: ReplayStep[] };\n\n const queue: QueueNode[] = [{ state: initialState, path: [] }];\n const replayPaths = new Map<string, ReplayStep[]>();\n replayPaths.set(initialState, []);\n\n while (queue.length > 0) {\n const { state, path } = queue.shift()!;\n if (path.length >= maxDepth) continue;\n\n const fromHere = transitions.filter(\n (t) => t.from === state && t.event !== 'INIT',\n );\n\n for (const transition of fromHere) {\n if (replayPaths.has(transition.to)) continue;\n\n const renderEffect = transition.renderEffects.find((re) => re.patternType !== null);\n const stepNeedsEntityData =\n transition.hasGuard ||\n transition.payloadFields.some((f) => ENTITY_PAYLOAD_FIELDS.has(f));\n\n const step: ReplayStep = {\n event: transition.event,\n fromState: state,\n toState: transition.to,\n slot: renderEffect?.slot ?? 'main',\n expectedPattern: renderEffect?.patternType ?? undefined,\n needsEntityData: stepNeedsEntityData,\n payloadSchema: transition.payloadSchema.length > 0 ? transition.payloadSchema : undefined,\n };\n\n const newPath = [...path, step];\n replayPaths.set(transition.to, newPath);\n queue.push({ state: transition.to, path: newPath });\n }\n }\n\n return replayPaths;\n}\n","/**\n * Edge-Covering Walk Algorithm\n *\n * Computes an ordered sequence of events (WalkStep[]) that attempts to cover\n * every transition (edge) in a state machine graph. This is a greedy chained\n * walk: it does NOT guarantee 100% coverage. With no reset concept it can\n * strand on absorbing states (no outgoing edges and no path back to uncovered\n * edges), and a guard-fail misprediction desyncs the chained walk so later\n * steps fire from the wrong state. Superseded by the hermetic per-frame walk\n * in @almadar-io/verify, which re-seeds each frame independently.\n *\n * Algorithm:\n * 1. Build adjacency list and edge universe (guarded transitions produce two edges)\n * 2. Precompute BFS shortest paths between all state pairs (for repositioning)\n * 3. Greedy DFS: at each state, prefer uncovered outgoing edges\n * 4. When stuck, insert repositioning steps to nearest state with uncovered edges\n * 5. Guard-fail steps don't advance state (guard blocks transition)\n *\n * Used by StateWalkEngine in @almadar-io/verify. Both orbital-verify and\n * runtime-verify share this algorithm for consistent coverage.\n *\n * @packageDocumentation\n */\n\nimport type { EdgeWalkTransition, WalkStep, StateEdge } from './types.js';\nimport type { EventPayload, EventPayloadValue } from '../types/expression.js';\nimport { buildGuardPayloads } from './guard-payloads.js';\n\n/**\n * Build an ordered walk that covers every edge in the state machine.\n *\n * @param transitions - All transitions in the state machine\n * @param initialState - Starting state\n * @returns Ordered walk steps covering every edge\n */\nexport function buildEdgeCoveringWalk(\n transitions: EdgeWalkTransition[],\n initialState: string,\n): WalkStep[] {\n // 1. Build adjacency list. Skip wildcards (pseudostates) and skip the\n // boot INIT (the runtime auto-fires INIT from the initial state on\n // mount, so the walker doesn't need to fire it). User-triggered INITs\n // from non-initial states (refresh, retry) ARE walkable edges and\n // stay in the graph so coverage can reach them.\n const filtered = transitions.filter(\n (t) => t.from !== '*' && !(t.event === 'INIT' && t.from === initialState),\n );\n\n const graph = new Map<string, Array<{ event: string; to: string; transition: EdgeWalkTransition }>>();\n const allStates = new Set<string>();\n\n for (const t of filtered) {\n allStates.add(t.from);\n allStates.add(t.to);\n if (!graph.has(t.from)) graph.set(t.from, []);\n graph.get(t.from)!.push({ event: t.event, to: t.to, transition: t });\n }\n\n // Ensure initial state is in the set\n allStates.add(initialState);\n\n // 2. Build edge universe. Guarded transitions produce pass + fail edges.\n const uncovered = new Set<string>();\n const edgeMeta = new Map<string, { transition: EdgeWalkTransition; guardCase: 'pass' | 'fail' | null }>();\n\n for (const t of filtered) {\n if (t.hasGuard) {\n const keyPass = `${t.from}+${t.event}->${t.to}[pass]`;\n const keyFail = `${t.from}+${t.event}->${t.to}[fail]`;\n uncovered.add(keyPass);\n uncovered.add(keyFail);\n edgeMeta.set(keyPass, { transition: t, guardCase: 'pass' });\n edgeMeta.set(keyFail, { transition: t, guardCase: 'fail' });\n } else {\n const key = `${t.from}+${t.event}->${t.to}`;\n uncovered.add(key);\n edgeMeta.set(key, { transition: t, guardCase: null });\n }\n }\n\n if (uncovered.size === 0) return [];\n\n // 3. Precompute BFS shortest paths between all state pairs\n const shortestPaths = new Map<string, Map<string, Array<{ event: string; to: string }>>>();\n for (const state of allStates) {\n shortestPaths.set(state, bfsShortestPaths(state, graph));\n }\n\n // 4. Greedy walk\n const walk: WalkStep[] = [];\n let currentState = initialState;\n const maxIterations = uncovered.size * allStates.size * 2; // safety bound\n let iterations = 0;\n\n while (uncovered.size > 0 && iterations < maxIterations) {\n iterations++;\n\n // Find uncovered edges from currentState\n const outgoing = findUncoveredEdges(currentState, graph, uncovered);\n\n if (outgoing.length > 0) {\n // Pick first uncovered edge\n const pick = outgoing[0];\n const payload = buildPayloadForEdge(pick.transition, pick.guardCase);\n\n walk.push({\n from: currentState,\n event: pick.transition.event,\n to: pick.transition.to,\n guardCase: pick.guardCase,\n payload,\n isRepositioning: false,\n });\n\n uncovered.delete(pick.key);\n\n // Guard-fail doesn't advance state\n if (pick.guardCase !== 'fail') {\n currentState = pick.transition.to;\n }\n } else {\n // Stuck: find nearest state with uncovered edges\n const target = findNearestUncoveredState(currentState, graph, uncovered, shortestPaths);\n\n if (!target) {\n // No reachable state with uncovered edges. Remaining edges are unreachable.\n break;\n }\n\n // Insert repositioning steps\n const repoPath = shortestPaths.get(currentState)?.get(target);\n if (!repoPath || repoPath.length === 0) break;\n\n for (const step of repoPath) {\n walk.push({\n from: currentState,\n event: step.event,\n to: step.to,\n guardCase: null,\n payload: {},\n isRepositioning: true,\n });\n currentState = step.to;\n }\n }\n }\n\n return walk;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\n/**\n * BFS from a source state, returning shortest paths to all reachable states.\n * Each path is an array of {event, to} steps.\n */\nfunction bfsShortestPaths(\n source: string,\n graph: Map<string, Array<{ event: string; to: string; transition: EdgeWalkTransition }>>,\n): Map<string, Array<{ event: string; to: string }>> {\n const paths = new Map<string, Array<{ event: string; to: string }>>();\n const visited = new Set<string>([source]);\n const queue: Array<{ state: string; path: Array<{ event: string; to: string }> }> = [\n { state: source, path: [] },\n ];\n\n while (queue.length > 0) {\n const { state, path } = queue.shift()!;\n const edges = graph.get(state) ?? [];\n\n for (const edge of edges) {\n if (visited.has(edge.to)) continue;\n visited.add(edge.to);\n const newPath = [...path, { event: edge.event, to: edge.to }];\n paths.set(edge.to, newPath);\n queue.push({ state: edge.to, path: newPath });\n }\n }\n\n return paths;\n}\n\n/**\n * Find uncovered edges from a given state.\n */\nfunction findUncoveredEdges(\n state: string,\n graph: Map<string, Array<{ event: string; to: string; transition: EdgeWalkTransition }>>,\n uncovered: Set<string>,\n): Array<{ key: string; transition: EdgeWalkTransition; guardCase: 'pass' | 'fail' | null }> {\n const edges = graph.get(state) ?? [];\n const result: Array<{ key: string; transition: EdgeWalkTransition; guardCase: 'pass' | 'fail' | null }> = [];\n\n for (const edge of edges) {\n if (edge.transition.hasGuard) {\n const keyPass = `${state}+${edge.event}->${edge.to}[pass]`;\n const keyFail = `${state}+${edge.event}->${edge.to}[fail]`;\n // Prefer pass first (advances state), then fail\n if (uncovered.has(keyPass)) {\n result.push({ key: keyPass, transition: edge.transition, guardCase: 'pass' });\n }\n if (uncovered.has(keyFail)) {\n result.push({ key: keyFail, transition: edge.transition, guardCase: 'fail' });\n }\n } else {\n const key = `${state}+${edge.event}->${edge.to}`;\n if (uncovered.has(key)) {\n result.push({ key, transition: edge.transition, guardCase: null });\n }\n }\n }\n\n return result;\n}\n\n/**\n * Find the nearest state (from currentState) that has uncovered outgoing edges.\n */\nfunction findNearestUncoveredState(\n currentState: string,\n graph: Map<string, Array<{ event: string; to: string; transition: EdgeWalkTransition }>>,\n uncovered: Set<string>,\n shortestPaths: Map<string, Map<string, Array<{ event: string; to: string }>>>,\n): string | null {\n // Collect states that have uncovered edges\n const statesWithUncovered = new Set<string>();\n for (const key of uncovered) {\n // Key format: \"state+EVENT->target\" or \"state+EVENT->target[pass]\"\n const fromState = key.split('+')[0];\n statesWithUncovered.add(fromState);\n }\n\n // If current state has uncovered edges, return it (shouldn't happen, but handle it)\n if (statesWithUncovered.has(currentState)) return currentState;\n\n // Find nearest reachable state with uncovered edges\n const paths = shortestPaths.get(currentState);\n if (!paths) return null;\n\n let nearestState: string | null = null;\n let nearestDist = Infinity;\n\n for (const target of statesWithUncovered) {\n const path = paths.get(target);\n if (path && path.length < nearestDist) {\n nearestDist = path.length;\n nearestState = target;\n }\n }\n\n return nearestState;\n}\n\n/**\n * Build a payload for a given edge based on its guard case and payload schema.\n * For guarded transitions, uses guard expressions to generate pass/fail payloads.\n * For unguarded transitions with payload schemas (e.g., EDIT/VIEW with { id }),\n * generates mock values so fetch-by-ID effects can resolve entity data.\n */\nfunction buildPayloadForEdge(\n transition: EdgeWalkTransition,\n guardCase: 'pass' | 'fail' | null,\n): EventPayload {\n // Guard-based payload generation (existing behavior)\n if (transition.hasGuard && transition.guard && guardCase) {\n const payloads = buildGuardPayloads(transition.guard);\n return guardCase === 'pass' ? payloads.pass : payloads.fail;\n }\n\n // Schema-based payload generation for events that declare required fields\n // (e.g., EDIT/VIEW declare { name: \"id\", type: \"string\", required: true })\n if (transition.payloadSchema && transition.payloadSchema.length > 0) {\n const payload: EventPayload = {};\n for (const field of transition.payloadSchema) {\n // Use caller-provided mockValue if available (set from entity context)\n if (field.mockValue !== undefined) {\n payload[field.name] = field.mockValue as EventPayloadValue;\n } else if (field.type === 'string') {\n payload[field.name] = `mock-${field.name}`;\n } else if (field.type === 'number') {\n payload[field.name] = 1;\n } else if (field.type === 'boolean') {\n payload[field.name] = true;\n } else if (field.type === 'object' || field.type === 'any') {\n // `mock-<name>` is a plain string; persisting that for an object\n // field (e.g. SAVE's `data: object` carrying a form row) spreads\n // the string's characters across numeric keys server-side and\n // the downstream grid renders blank cards. An empty object is a\n // safer default — callers that need entity-shaped mocks should\n // set `mockValue` at the call site (see orbital-verify-unified's\n // phase4-browser TraitWalkConfig builder).\n payload[field.name] = {};\n } else {\n payload[field.name] = `mock-${field.name}`;\n }\n }\n return payload;\n }\n\n return {};\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/types/field.ts","../src/types/asset.ts","../src/types/entity.ts","../src/types/effect.ts","../src/types/expression.ts","../src/types/state-machine.ts","../src/types/trait.ts","../src/types/page.ts","../src/types/domain.ts","../src/types/service.ts","../src/types/orbital.ts","../src/types/schema.ts","../src/types/bindings.ts","../src/types/binding.ts","../src/types/interaction-model.ts","../src/types/pattern.ts","../src/service-types.ts","../src/types/ir.ts","../src/types/json.ts","../src/types/validation.ts","../src/types/living.ts","../src/render-ui-edit.ts","../src/resolver.ts","../src/diff.ts","../src/summarize.ts","../src/factory/questions/generate.ts","../src/factory/questions/reducer.ts","../src/factory/translate.ts","../src/factory/diff.ts","../src/factory/mutate.ts","../src/builders/layout-strategy.ts","../src/builders/event-wiring.ts","../src/builders/compose-behaviors.ts","../src/state-machine/graph.ts","../src/state-machine/bfs.ts","../src/state-machine/guard-payloads.ts","../src/state-machine/replay-paths.ts","../src/state-machine/edge-walk.ts"],"names":["z","ref","_PATTERN_TYPES","inferTsType"],"mappings":";;;;;AAqCO,IAAM,eAAA,GAAkB,EAAE,IAAA,CAAK;AAAA,EAClC,QAAA;AAAA,EACA,QAAA;AAAA,EACA,SAAA;AAAA,EACA,MAAA;AAAA,EACA,WAAA;AAAA,EACA,UAAA;AAAA,EACA,OAAA;AAAA,EACA,QAAA;AAAA,EACA,MAAA;AAAA,EACA,UAAA;AAAA,EACA,OAAA;AAAA,EACA,MAAA;AAAA,EACA;AACJ,CAAC;AAiBM,IAAM,yBAAA,GAA4B,EAAE,IAAA,CAAK;AAAA,EAC5C,KAAA;AAAA,EACA,MAAA;AAAA,EACA,aAAA;AAAA,EACA,aAAA;AAAA,EACA;AACJ,CAAC,CAAA;AAmCM,IAAM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AO,EAAC;AACV","file":"index.js","sourcesContent":["/**\n * Field Types for Orbital Units\n *\n * Extracted from schema/data-entities.ts for the orbitals module.\n * These types define the field structure within orbital entities.\n *\n * @packageDocumentation\n */\n\nimport { z } from 'zod';\n\n// ============================================================================\n// Field Types\n// ============================================================================\n\n/**\n * Supported field types for entity fields.\n *\n * @example\n * { name: 'status', type: 'enum', values: ['draft', 'published'] }\n * { name: 'authorId', type: 'relation', relation: { entity: 'User', cardinality: 'one' } }\n */\nexport type FieldType =\n | 'string'\n | 'number'\n | 'boolean'\n | 'date'\n | 'timestamp'\n | 'datetime'\n | 'array'\n | 'object'\n | 'enum'\n | 'relation'\n | 'trait'\n | 'slot'\n | 'pattern';\n\nexport const FieldTypeSchema = z.enum([\n 'string',\n 'number',\n 'boolean',\n 'date',\n 'timestamp',\n 'datetime',\n 'array',\n 'object',\n 'enum',\n 'relation',\n 'trait',\n 'slot',\n 'pattern',\n]);\n\n// ============================================================================\n// Relation Configuration\n// ============================================================================\n\n/**\n * Cardinality for relation fields.\n * Matches Rust compiler's Cardinality enum.\n */\nexport type RelationCardinality = \n | 'one' \n | 'many' \n | 'one-to-many' \n | 'many-to-one' \n | 'many-to-many';\n\nexport const RelationCardinalitySchema = z.enum([\n 'one',\n 'many',\n 'one-to-many',\n 'many-to-one',\n 'many-to-many',\n]);\n\n/**\n * Configuration for relation fields (foreign keys).\n * Matches Rust compiler's RelationDefinition format.\n */\nexport interface RelationConfig {\n /** Target entity name (e.g., 'User', 'Task') - matches Rust's `entity` field */\n entity: string;\n /** Field on target entity (defaults to 'id') */\n field?: string;\n /** \n * Cardinality: one, many, one-to-many, many-to-one, many-to-many\n * Matches Rust compiler's cardinality format\n */\n cardinality?: RelationCardinality;\n /** Delete behavior */\n onDelete?: 'cascade' | 'nullify' | 'restrict';\n /** \n * Foreign key field name (for legacy compatibility).\n * @deprecated Use field instead\n */\n foreignKey?: string;\n /**\n * Target entity name (for legacy compatibility).\n * @deprecated Use entity instead\n */\n target?: string;\n /**\n * Cardinality type alias (for legacy compatibility).\n * @deprecated Use cardinality instead\n */\n type?: RelationCardinality;\n}\n\nexport const RelationConfigSchema = z.object({\n entity: z.string().min(1, 'Target entity is required'),\n field: z.string().optional(),\n cardinality: RelationCardinalitySchema.optional(),\n onDelete: z.enum(['cascade', 'nullify', 'restrict']).optional(),\n // Legacy compatibility fields\n foreignKey: z.string().optional(),\n target: z.string().optional(),\n type: RelationCardinalitySchema.optional(),\n}).transform((data) => {\n // Normalize legacy format to standard format\n const normalized: RelationConfig = {\n entity: data.entity || data.target || '',\n cardinality: data.cardinality || data.type,\n field: data.field,\n onDelete: data.onDelete,\n };\n return normalized;\n});\n\nexport type RelationConfigInput = z.input<typeof RelationConfigSchema>;\n\n// ============================================================================\n// Field Format\n// ============================================================================\n\n/**\n * Field format validators for string fields.\n */\nexport type FieldFormat =\n | 'email'\n | 'url'\n | 'phone'\n | 'date'\n | 'datetime'\n | 'uuid'\n /** Render hint: this string field stores an image URL. Mock adapters\n * generate a deterministic picsum.photos URL; UI patterns can branch\n * to an `<img>` instead of a `<typography>`. */\n | 'image'\n /** Render hint: avatar-shaped image (square, small). */\n | 'avatar'\n /** Render hint: thumbnail image (small landscape). */\n | 'thumbnail';\n\nexport const FieldFormatSchema = z.enum([\n 'email',\n 'url',\n 'phone',\n 'date',\n 'datetime',\n 'uuid',\n 'image',\n 'avatar',\n 'thumbnail',\n]);\n\n// ============================================================================\n// Entity Field — discriminated union by `type`\n// ============================================================================\n\n/**\n * Field-type tags that don't carry a type-dependent payload. The base\n * `EntityField` shape applies as-is.\n */\ntype ScalarFieldType =\n | 'string'\n | 'number'\n | 'boolean'\n | 'date'\n | 'timestamp'\n | 'datetime'\n | 'trait'\n | 'slot'\n | 'pattern';\n\n/** Fields shared across every variant. */\ninterface EntityFieldBase {\n /**\n * Field name (camelCase). Optional for nested item/property descriptors\n * where the name is implied by the parent (`items`, `properties[k]`).\n * Mirrors Rust's `FieldDefinition.name: Option<String>`.\n */\n name?: string;\n /** Whether the field is required */\n required?: boolean;\n /** Default value */\n default?: unknown;\n /** Validation format */\n format?: FieldFormat;\n /** Minimum value (for number) or length (for string) */\n min?: number;\n /** Maximum value or length */\n max?: number;\n /** Object property schemas keyed by property name (for object type).\n * Mirrors Rust's `FieldDefinition.properties: Option<HashMap<String,\n * FieldDefinition>>`. Populated by the lolo lowerer when a field /\n * config slot's type expression resolves to a struct shape\n * (`TypeExpr::Object`), including named-type aliases like `[MetricSpec]`. */\n properties?: Record<string, EntityField>;\n /** Runtime-managed widget state (authored `@intrinsic` in `.lolo`). Exempt\n * from the explicit-binding rule and never a domain-data bind target. */\n intrinsic?: boolean;\n /** Human/semantic description (authored `@description \"...\"` in `.lolo`).\n * Authoring/build-time metadata — factory-signature catalog, embeddings,\n * curation field-matching; the runtime ignores it. */\n description?: string;\n /** User-vocabulary synonyms (authored `@synonyms \"...\"` in `.lolo`).\n * Free text feeding catalog search / curation field-matching. */\n synonyms?: string;\n}\n\n/**\n * Scalar / structural fields — no type-dependent payload required.\n * `values?` is permitted as an OPTIONAL UI/validation hint (e.g. lolo's\n * `'a' | 'b' | 'c'` string-union sugar lowers to `type: 'string', values:\n * [...]`). Only `EnumEntityField` MANDATES values.\n */\nexport interface ScalarEntityField extends EntityFieldBase {\n type: ScalarFieldType;\n /** Optional vocabulary hint for scalar fields (e.g. string unions\n * authored as `'a'|'b'|'c'` in lolo). Not required at this variant. */\n values?: string[];\n}\n\n/** `type: 'enum'` REQUIRES the closed vocabulary in `values`. */\nexport interface EnumEntityField extends EntityFieldBase {\n type: 'enum';\n /** Closed string vocabulary the field accepts. */\n values: string[];\n}\n\n/** `type: 'relation'` REQUIRES the relation target binding. */\nexport interface RelationEntityField extends EntityFieldBase {\n type: 'relation';\n /** Relation target binding (entity + cardinality). */\n relation: RelationConfig;\n}\n\n/** `type: 'array'` — element schema in `items` strongly preferred but\n * optional for legacy compatibility with codegen-emitted scalar-array\n * fields (e.g. `{type: 'array', default: []}`). The lolo lowerer + Rust\n * validator catch typed-element-required cases downstream. */\nexport interface ArrayEntityField extends EntityFieldBase {\n type: 'array';\n /** Element schema for the array. */\n items?: EntityField;\n}\n\n/**\n * `type: 'object'` — a fixed-key struct (fields in `properties`) OR a\n * dynamic-key map (`Map K V` in `.lolo`; the uniform value schema lives in\n * `items`, mirroring an array's element schema). A distinct variant so `items`\n * is statically allowed only on object/array fields, never on scalars.\n */\nexport interface ObjectEntityField extends EntityFieldBase {\n type: 'object';\n /** Uniform value schema for a dynamic-key map (`Map K V`). */\n items?: EntityField;\n}\n\n/**\n * Entity field definition — discriminated union by `type`. Each variant\n * statically enforces its dependent payload (`values` for enum,\n * `relation` for relation, `items` for array) so TS / Zod / JSON Schema\n * consumers all agree on the dependency, not just the Rust validator.\n *\n * @example\n * { name: 'status', type: 'enum', values: ['draft', 'published'] }\n * { name: 'authorId', type: 'relation', relation: { entity: 'User', cardinality: 'one' } }\n * { name: 'tags', type: 'array', items: { type: 'string' } }\n */\nexport type EntityField =\n | ScalarEntityField\n | EnumEntityField\n | RelationEntityField\n | ArrayEntityField\n | ObjectEntityField;\n\n/**\n * Alias map for legacy/loose field-type spellings. Preprocessed into the\n * canonical `FieldType` enum before zod validates. Without this, agent-produced\n * schemas using `text`/`int`/`float`/`ts` were rejected at parse time — this\n * normalizes them so the rest of the pipeline sees only canonical types.\n */\nconst FIELD_TYPE_ALIASES: Record<string, FieldType> = {\n text: 'string',\n int: 'number',\n float: 'number',\n ts: 'timestamp',\n};\n\n/**\n * Zod schema for `EntityField`. Preprocess normalizes:\n * - legacy `type` aliases (text → string, int → number, etc.)\n * - legacy `enum: string[]` alias → `values: string[]`\n *\n * Branches on `type` so TS narrows the parsed output to the matching\n * discriminated-union variant.\n */\nexport const EntityFieldSchema: z.ZodType<EntityField, z.ZodTypeDef, unknown> = z.lazy(() => {\n const baseFieldShape = {\n name: z.string().min(1, 'Field name is required').optional(),\n required: z.boolean().optional(),\n default: z.unknown().optional(),\n format: FieldFormatSchema.optional(),\n min: z.number().optional(),\n max: z.number().optional(),\n properties: z.record(EntityFieldSchema).optional(),\n intrinsic: z.boolean().optional(),\n description: z.string().optional(),\n synonyms: z.string().optional(),\n };\n\n /** Build a scalar variant schema. `values?` is permitted as a hint;\n * only the enum variant mandates a non-empty values array. */\n function scalarVariant<T extends ScalarFieldType>(t: T) {\n return z.object({\n ...baseFieldShape,\n type: z.literal(t),\n values: z.array(z.string()).optional(),\n });\n }\n\n return z.preprocess(\n (input) => {\n if (\n input === null ||\n typeof input !== 'object' ||\n !('type' in input) ||\n typeof (input as { type: unknown }).type !== 'string'\n ) {\n return input;\n }\n const obj = input as { type: string; enum?: unknown; values?: unknown };\n const next: { type: string; enum?: unknown; values?: unknown } = { ...obj };\n const aliased = FIELD_TYPE_ALIASES[obj.type];\n if (aliased !== undefined) next.type = aliased;\n // Fold legacy `enum: string[]` into `values: string[]`.\n if (next.enum !== undefined && next.values === undefined) {\n next.values = next.enum;\n }\n delete next.enum;\n return next;\n },\n z.discriminatedUnion('type', [\n scalarVariant('string'),\n scalarVariant('number'),\n scalarVariant('boolean'),\n scalarVariant('date'),\n scalarVariant('timestamp'),\n scalarVariant('datetime'),\n scalarVariant('trait'),\n scalarVariant('slot'),\n scalarVariant('pattern'),\n // Enum variant — REQUIRES non-empty values.\n z.object({\n ...baseFieldShape,\n type: z.literal('enum'),\n values: z.array(z.string()).min(1, 'Enum field requires a non-empty `values` array'),\n }),\n // Relation variant — REQUIRES relation config.\n z.object({\n ...baseFieldShape,\n type: z.literal('relation'),\n relation: RelationConfigSchema,\n }),\n // Array variant — items optional to match relaxed TS shape.\n z.object({\n ...baseFieldShape,\n type: z.literal('array'),\n items: EntityFieldSchema.optional(),\n }),\n // Object variant — fixed-key struct (`properties`) or dynamic-key\n // map (`Map K V`, uniform value schema in `items`).\n z.object({\n ...baseFieldShape,\n type: z.literal('object'),\n items: EntityFieldSchema.optional(),\n values: z.array(z.string()).optional(),\n }),\n ]),\n );\n});\n\nexport type EntityFieldInput = z.input<typeof EntityFieldSchema>;\n\n// ============================================================================\n// Type Aliases (for cleaner imports)\n// ============================================================================\n\n/** Alias for EntityField - preferred name */\nexport type Field = EntityField;\n\n/** Alias for EntityFieldSchema - preferred name */\nexport const FieldSchema = EntityFieldSchema;\n","/**\n * Asset Types for Semantic Asset References\n *\n * Defines types for abstracting asset paths into semantic references.\n * Assets are resolved from SemanticAssetRef to actual paths at compile time.\n *\n * @packageDocumentation\n */\n\nimport { z } from 'zod';\n\n// ============================================================================\n// Entity Roles\n// ============================================================================\n\n/**\n * Entity roles in game contexts\n */\nexport const ENTITY_ROLES = [\n 'player',\n 'enemy',\n 'npc',\n 'item',\n 'tile',\n 'projectile',\n 'effect',\n 'ui',\n 'decoration',\n 'vehicle',\n] as const;\n\nexport type EntityRole = (typeof ENTITY_ROLES)[number];\n\nexport const EntityRoleSchema = z.enum(ENTITY_ROLES);\n\n// ============================================================================\n// Visual Styles\n// ============================================================================\n\n/**\n * Visual art styles for games\n */\nexport const VISUAL_STYLES = ['pixel', 'vector', 'hd', '1-bit', 'isometric'] as const;\n\nexport type VisualStyle = (typeof VISUAL_STYLES)[number];\n\nexport const VisualStyleSchema = z.enum(VISUAL_STYLES);\n\n// ============================================================================\n// Asset Dimension + Aspect (render metadata carried with the asset / the need)\n// ============================================================================\n\n/**\n * Whether the asset is a 2D sprite/image or a 3D model. Set by the consuming\n * canvas: the same entity role is a 2D sprite-sheet on a tile board and a 3D\n * rigged model on a 3D board.\n */\nexport const ASSET_DIMENSIONS = ['2d', '3d'] as const;\n\nexport type AssetDimension = (typeof ASSET_DIMENSIONS)[number];\n\nexport const AssetDimensionSchema = z.enum(ASSET_DIMENSIONS);\n\n/**\n * Rendering aspect ratio of an asset: square (tiles/sprites/portraits/icons),\n * 16:9 (scene backdrops), 5:7 (cards), 8:1 (effect frame strips).\n */\nexport const ASSET_ASPECTS = ['1:1', '16:9', '5:7', '8:1'] as const;\n\nexport type AssetAspect = (typeof ASSET_ASPECTS)[number];\n\nexport const AssetAspectSchema = z.enum(ASSET_ASPECTS);\n\n// ============================================================================\n// Game Types\n// ============================================================================\n\n/**\n * Game type classifications\n */\nexport const GAME_TYPES = [\n 'platformer',\n 'roguelike',\n 'top-down',\n 'puzzle',\n 'racing',\n 'card',\n 'board',\n 'shooter',\n 'rpg',\n] as const;\n\nexport type GameType = (typeof GAME_TYPES)[number];\n\nexport const GameTypeSchema = z.enum(GAME_TYPES);\n\n// ============================================================================\n// Animation Name + Sheet Direction\n// ============================================================================\n\n/**\n * Animation names matching a sprite sheet's row layout. Canonical home for\n * this vocabulary — `@almadar/ui`'s `spriteAnimationTypes.ts` re-exports it\n * rather than redeclaring, so board `.lolo` config and the render library\n * agree on one enum.\n */\nexport const ANIMATION_NAMES = ['idle', 'walk', 'attack', 'hit', 'death'] as const;\n\nexport type AnimationName = (typeof ANIMATION_NAMES)[number];\n\nexport const AnimationNameSchema = z.enum(ANIMATION_NAMES);\n\n/** Sheet file directions (physical PNG files a sprite sheet ships as). */\nexport const SPRITE_DIRECTIONS = ['se', 'sw'] as const;\n\nexport type SpriteDirection = (typeof SPRITE_DIRECTIONS)[number];\n\nexport const SpriteDirectionSchema = z.enum(SPRITE_DIRECTIONS);\n\n// ============================================================================\n// Animation Definition\n// ============================================================================\n\n/**\n * Definition for a single named animation within a sprite sheet: which row\n * it occupies, how many frames it has, and its playback rate. This is the\n * shape actually consumed by `@almadar/ui`'s sprite-sheet renderer\n * (`spriteAnimation.ts`'s `frameRect`/`getCurrentFrameFromDef`) — moved here\n * verbatim rather than reconciled with a differently-shaped guess, since\n * `@almadar/ui`'s version is the one with real production consumers.\n */\nexport interface AnimationDef {\n /** Row index in the sprite sheet (0-based; each animation occupies one row). */\n row: number;\n /** Number of frames in this animation. */\n frames: number;\n /** Frames per second. */\n frameRate: number;\n /** Whether the animation loops. */\n loop: boolean;\n}\n\nexport const AnimationDefSchema = z.object({\n row: z.number().int().nonnegative(),\n frames: z.number().int().positive(),\n frameRate: z.number().positive(),\n loop: z.boolean(),\n});\n\n// ============================================================================\n// Sprite Sheet Atlas\n// ============================================================================\n\n/**\n * Parsed sprite-sheet atlas JSON — the contract a `spriteSheet`-role `Asset.url`\n * resolves to when fetched (see `Asset.url` usage in `@almadar/ui`'s\n * `useUnitSpriteAtlas`). A unit's `sprite?: Asset` stays the static single-pose\n * image; `spriteSheet?: Asset` is a SEPARATE reference whose URL points at a\n * `SpriteSheetAtlas`-shaped JSON manifest (e.g. `.../guardian-sprite-sheet.json`),\n * not a PNG. Frame-cutting geometry lives here, not inlined onto `Asset` — an\n * `Asset` traveling through `render-ui` every tick stays small.\n */\nexport interface SpriteSheetAtlas {\n /** Unit archetype key. */\n unit?: string;\n /** Visual type key. */\n type?: string;\n /** Width of a single frame in pixels. */\n frameWidth: number;\n /** Height of a single frame in pixels. */\n frameHeight: number;\n /** Number of columns (frames per row). */\n columns: number;\n /** Number of rows (animations). */\n rows: number;\n /** Directions present as physical PNG files. */\n directions: SpriteDirection[];\n /** Relative PNG sheet paths per direction. */\n sheets: Partial<Record<SpriteDirection, string>>;\n /** Animation row layout keyed by animation name. */\n animations: Partial<Record<AnimationName, AnimationDef>>;\n}\n\nexport const SpriteSheetAtlasSchema = z.object({\n unit: z.string().optional(),\n type: z.string().optional(),\n frameWidth: z.number().positive(),\n frameHeight: z.number().positive(),\n columns: z.number().int().positive(),\n rows: z.number().int().positive(),\n directions: z.array(SpriteDirectionSchema),\n sheets: z.record(SpriteDirectionSchema, z.string()),\n animations: z.record(AnimationNameSchema, AnimationDefSchema),\n});\n\n// ============================================================================\n// Texture Atlas — named-subrect packed sheet (the industry standard)\n// ============================================================================\n\n/**\n * One named sub-rectangle inside a packed sheet. Mirrors the ShoeBox /\n * TexturePacker `<SubTexture>` element every Kenney `Spritesheet/*.xml` ships\n * (`x`/`y`/`width`/`height` = the rect in the sheet PNG; `frameX`/`frameY`/\n * `frameWidth`/`frameHeight` = the trim/pad offsets for sprites packed with\n * transparent edges removed — optional, present only on trimmed atlases).\n */\nexport interface SubTexture {\n x: number;\n y: number;\n width: number;\n height: number;\n frameX?: number;\n frameY?: number;\n frameWidth?: number;\n frameHeight?: number;\n}\n\nexport const SubTextureSchema = z.object({\n x: z.number().nonnegative(),\n y: z.number().nonnegative(),\n width: z.number().positive(),\n height: z.number().positive(),\n frameX: z.number().optional(),\n frameY: z.number().optional(),\n frameWidth: z.number().positive().optional(),\n frameHeight: z.number().positive().optional(),\n});\n\n/**\n * A packed sheet + its named sub-rectangles — the canonical parse target for a\n * Kenney `Spritesheet/*.xml` atlas. A STATIC tile/prop/UI Asset references one\n * of these: `{ url: <sheet.png>, atlas: <this.json>, sprite: \"grass.png\" }` →\n * the renderer fetches the sheet + atlas ONCE and blits the named sub-rect,\n * instead of loading N individual PNGs. (Animated actors use `SpriteSheetAtlas`\n * instead; a uniform-grid tile page uses `Tilesheet`.)\n */\nexport interface TextureAtlas {\n /** Relative path to the sheet PNG the sub-rects index into (the atlas's own `imagePath`). */\n imagePath: string;\n /** Sub-rectangles keyed by their atlas name (e.g. `\"grass.png\"`). */\n subTextures: Record<string, SubTexture>;\n}\n\nexport const TextureAtlasSchema = z.object({\n imagePath: z.string(),\n subTextures: z.record(z.string(), SubTextureSchema),\n});\n\n// ============================================================================\n// Tilesheet — uniform-grid packed page (cut by index)\n// ============================================================================\n\n/**\n * A uniform-grid tile page — the shape a Kenney `Tilesheet/` sheet takes (e.g.\n * Pirate Pack: \"each tile is 64×64, no margin\"). Tiles are cut by `(col,row)`\n * index rather than by named rect. `names` is present only when a sibling\n * `.xml`/`.txt` supplies an index→name list; otherwise a tile is addressed by\n * its `\"col,row\"` (or flat index) via `Asset.sprite`.\n */\nexport interface Tilesheet {\n /** Relative path to the tile sheet PNG. */\n imagePath: string;\n /** Width of one tile cell in pixels. */\n tileWidth: number;\n /** Height of one tile cell in pixels. */\n tileHeight: number;\n /** Number of columns in the grid. */\n columns: number;\n /** Number of rows in the grid. */\n rows: number;\n /** Outer margin before the first tile, in pixels (default 0). */\n margin?: number;\n /** Gap between adjacent tiles, in pixels (default 0). */\n spacing?: number;\n /** Optional index→name labels when a descriptor supplies them. */\n names?: string[];\n}\n\nexport const TilesheetSchema = z.object({\n imagePath: z.string(),\n tileWidth: z.number().positive(),\n tileHeight: z.number().positive(),\n columns: z.number().int().positive(),\n rows: z.number().int().positive(),\n margin: z.number().nonnegative().optional(),\n spacing: z.number().nonnegative().optional(),\n names: z.array(z.string()).optional(),\n});\n\n// ============================================================================\n// Pack classification — how a Kenney pack maps into the pipeline\n// ============================================================================\n\n/**\n * The three roles a source pack plays, decided by the systematic per-folder\n * scan (see `docs/Almadar_Std_Assets.md`):\n * - `board-tileset` — a genre/canvas-matched terrain/level set, often ~1:1 with a board.\n * - `character-kit` — modular layered character parts assembled into one figure.\n * - `shared-primitive` — backgrounds / effects / UI / particles fanned out to many boards.\n */\nexport const PACK_CLASSES = ['board-tileset', 'character-kit', 'shared-primitive'] as const;\n\nexport type PackClass = (typeof PACK_CLASSES)[number];\n\nexport const PackClassSchema = z.enum(PACK_CLASSES);\n\n/**\n * A modular character-kit layer: one selectable part (`head`/`hair`/`shirt`/…)\n * resolved to a sub-texture ref. Recorded now so the analysis can RECOGNIZE\n * modular packs; the layered compositor that stacks these is a later follow-up.\n */\nexport interface CharacterKitLayer {\n /** Which body slot this layer fills. */\n slot: 'body' | 'head' | 'face' | 'hair' | 'facialHair' | 'shirt' | 'pants' | 'shoes' | 'accessory';\n /** Sheet PNG the part lives on. */\n url: AssetUrl;\n /** Atlas JSON next to the sheet. */\n atlas?: AssetUrl;\n /** Sub-texture name within the atlas. */\n sprite?: string;\n}\n\nexport const CharacterKitLayerSchema = z.object({\n slot: z.enum(['body', 'head', 'face', 'hair', 'facialHair', 'shirt', 'pants', 'shoes', 'accessory']),\n url: z.string(),\n atlas: z.string().optional(),\n sprite: z.string().optional(),\n});\n\n/** A recognized modular-character pack: an ordered, back-to-front layer stack. */\nexport interface CharacterKit {\n /** Source pack slug the kit came from. */\n pack: string;\n /** Layers in back-to-front draw order. */\n layers: CharacterKitLayer[];\n}\n\nexport const CharacterKitSchema = z.object({\n pack: z.string(),\n layers: z.array(CharacterKitLayerSchema),\n});\n\n// ============================================================================\n// Semantic Asset Reference\n// ============================================================================\n\n/**\n * Semantic reference to an asset (not a hardcoded path).\n * Resolved to actual paths at compile time via asset maps.\n */\nexport interface SemanticAssetRef {\n /** Entity role (player, enemy, item, etc.) */\n role: EntityRole;\n /** Sub-category within role (hero, slime, coin, etc.) */\n category: string;\n /** Required animations for this entity */\n animations?: string[];\n /** Visual style preference */\n style?: VisualStyle;\n /** Variant identifier (for multiple versions) */\n variant?: string;\n /** 2D sprite vs 3D model — the rendering dimension the consuming canvas needs. */\n dimension?: AssetDimension;\n /** Rendering aspect ratio (square sprite/portrait/tile, 16:9 backdrop, 5:7 card, 8:1 fx-strip). */\n aspect?: AssetAspect;\n}\n\nexport const SemanticAssetRefSchema = z.object({\n role: EntityRoleSchema,\n category: z.string().min(1),\n animations: z.array(z.string()).optional(),\n style: VisualStyleSchema.optional(),\n variant: z.string().optional(),\n dimension: AssetDimensionSchema.optional(),\n aspect: AssetAspectSchema.optional(),\n});\n\n// ============================================================================\n// Asset — the UNIFIED asset type\n// ============================================================================\n\n/**\n * The single asset type: a `SemanticAssetRef` (role/dimension/animations/aspect/style)\n * WITH its resolved URL folded in. Used everywhere an asset is referenced — a lolo\n * board `assetManifest` (`Map string Asset`), every `@almadar/ui` game prop, the\n * asset-workflow's resolved/pool assets, and the inspector picker. Replaces the bare\n * `AssetUrl`-string asset field so the render metadata travels WITH the asset (no\n * pixel-dimension or filename heuristics needed to know sheet-vs-frame / 2d-vs-3d).\n */\nexport interface Asset extends SemanticAssetRef {\n /** The resolved asset URL. When `atlas`/`sprite` are set this is the SHEET png; otherwise a standalone image. */\n url: AssetUrl;\n /**\n * Optional atlas JSON (a `TextureAtlas` or `Tilesheet`) that slices `url`.\n * When present with `sprite`, the renderer fetches sheet + atlas once and\n * blits one sub-rect instead of loading a standalone PNG. Absent → `url` is\n * a plain whole-image asset (the existing, non-atlas path).\n */\n atlas?: AssetUrl;\n /**\n * The sub-texture selector within `atlas`: a `SubTexture` name for a\n * `TextureAtlas` (e.g. `\"grass.png\"`), or a `\"col,row\"`/flat index for a\n * `Tilesheet`. Only meaningful alongside `atlas`.\n */\n sprite?: string;\n /** Optional display name (inspector picker). */\n name?: string;\n /** Optional thumbnail URL (inspector picker grid). */\n thumbnailUrl?: string;\n}\n\nexport const AssetSchema = SemanticAssetRefSchema.extend({\n url: z.string(),\n atlas: z.string().optional(),\n sprite: z.string().optional(),\n name: z.string().optional(),\n thumbnailUrl: z.string().optional(),\n});\n\n// ============================================================================\n// Resolved Asset\n// ============================================================================\n\n/**\n * Result of resolving a SemanticAssetRef to actual asset paths\n */\nexport interface ResolvedAsset {\n /** Base path to the asset pack */\n basePath: string;\n /** Relative path within the pack */\n path: string;\n /** Tile indices for tilesheet-based assets */\n tiles?: number[];\n /** Size of each tile in pixels */\n tileSize?: number;\n /** List of individual files (for non-tilesheet assets) */\n files?: string[];\n /** Animation definitions by name */\n animations?: Record<string, AnimationDef>;\n}\n\nexport const ResolvedAssetSchema = z.object({\n basePath: z.string(),\n path: z.string(),\n tiles: z.array(z.number()).optional(),\n tileSize: z.number().positive().optional(),\n files: z.array(z.string()).optional(),\n animations: z.record(AnimationDefSchema).optional(),\n});\n\n// ============================================================================\n// Asset Mapping\n// ============================================================================\n\n/**\n * Single asset mapping entry in an asset map\n */\nexport interface AssetMapping {\n /** Relative path to the asset */\n path: string;\n /** Tile indices for tilesheets */\n tiles?: number[];\n /** Tile size in pixels */\n tileSize?: number;\n /** Individual file patterns */\n files?: string[];\n /** Animation definitions */\n animations?: Record<string, AnimationDef>;\n}\n\nexport const AssetMappingSchema = z.object({\n path: z.string(),\n tiles: z.array(z.number()).optional(),\n tileSize: z.number().positive().optional(),\n files: z.array(z.string()).optional(),\n animations: z.record(AnimationDefSchema).optional(),\n});\n\n// ============================================================================\n// Asset Map\n// ============================================================================\n\n/**\n * Asset map for a specific game type and visual style.\n * Maps semantic keys (role:category) to asset paths.\n */\nexport interface AssetMap {\n /** Game type this map is for */\n gameType: GameType;\n /** Visual style this map is for */\n style: VisualStyle;\n /** Base path to the asset pack */\n basePath: string;\n /** Mappings from semantic keys to asset paths */\n mappings: Record<string, AssetMapping>;\n}\n\nexport const AssetMapSchema = z.object({\n gameType: GameTypeSchema,\n style: VisualStyleSchema,\n basePath: z.string(),\n mappings: z.record(AssetMappingSchema),\n});\n\n// ============================================================================\n// Asset Catalog\n// ============================================================================\n\n/**\n * Single browsable asset in the inspector picker catalog.\n * Backs the asset/icon pickers — a flat list the inspector renders for\n * the user to choose from when a config field's type is `'asset'`.\n */\nexport interface AssetCatalogEntry {\n /** Resolvable URL to the asset. */\n url: string;\n /** Display name for the asset. */\n name: string;\n /** Grouping category within the catalog. */\n category: string;\n /** Asset kind the picker dispatches on. */\n kind: 'image' | 'spritesheet' | 'audio' | 'scene' | 'portrait' | 'model' | 'other';\n /** Optional thumbnail URL for grid previews. */\n thumbnailUrl?: string;\n /** 2D sprite vs 3D model — the asset's actual rendering dimension. */\n dimension?: AssetDimension;\n /** The asset's actual rendering aspect ratio. */\n aspect?: AssetAspect;\n}\n\nexport const AssetCatalogEntrySchema = z.object({\n url: z.string(),\n name: z.string(),\n category: z.string(),\n kind: z.enum(['image', 'spritesheet', 'audio', 'scene', 'portrait', 'model', 'other']),\n thumbnailUrl: z.string().optional(),\n dimension: AssetDimensionSchema.optional(),\n aspect: AssetAspectSchema.optional(),\n});\n\n/**\n * Flat list of browsable assets surfaced by the inspector pickers.\n */\nexport type AssetCatalog = AssetCatalogEntry[];\n\nexport const AssetCatalogSchema = z.array(AssetCatalogEntrySchema);\n\n/**\n * Asset-reference URL marker. A plain alias over `string` — the value is a\n * resolvable asset URL — but the named type lets the pattern-sync tool\n * (`tools/almadar-pattern-sync/parser.ts`) detect a component prop as an asset\n * field (tagged `asset`) the same way `EventKey`/`LucideIcon` are detected by\n * type identity. Components annotate image/url props as `AssetUrl` (`src`,\n * `backgroundImage`, `avatar`, …); the generator emits a `string` config knob\n * declared as the `asset` config type, which the property inspector dispatches\n * an AssetPicker on. Not branded — asset urls originate from user data, so cast\n * friction would buy nothing; the value is the marker the tool finds.\n */\nexport type AssetUrl = string;\n\n// ============================================================================\n// Type Exports\n// ============================================================================\n\nexport type SemanticAssetRefInput = z.input<typeof SemanticAssetRefSchema>;\nexport type ResolvedAssetInput = z.input<typeof ResolvedAssetSchema>;\nexport type AssetMappingInput = z.input<typeof AssetMappingSchema>;\nexport type AssetMapInput = z.input<typeof AssetMapSchema>;\nexport type AnimationDefInput = z.input<typeof AnimationDefSchema>;\nexport type AssetCatalogEntryInput = z.input<typeof AssetCatalogEntrySchema>;\nexport type SpriteSheetAtlasInput = z.input<typeof SpriteSheetAtlasSchema>;\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Creates a semantic asset key from role and category.\n * \n * Generates a unique asset identifier by combining role and category\n * with a colon separator. Used for asset management and lookup.\n * \n * @param {EntityRole} role - Entity role (e.g., 'player', 'enemy')\n * @param {string} category - Asset category (e.g., 'sprite', 'animation')\n * @returns {string} Asset key in format 'role:category'\n * \n * @example\n * createAssetKey('player', 'sprite'); // returns 'player:sprite'\n * createAssetKey('enemy', 'animation'); // returns 'enemy:animation'\n */\nexport function createAssetKey(role: EntityRole, category: string): string {\n return `${role}:${category}`;\n}\n\n/**\n * Parses an asset key into role and category components.\n * \n * Deconstructs an asset key string (format 'role:category') into its\n * constituent parts. Returns null if the key format is invalid.\n * \n * @param {string} key - Asset key in format 'role:category'\n * @returns {{ role: string; category: string } | null} Parsed components or null\n * \n * @example\n * parseAssetKey('player:sprite'); // returns { role: 'player', category: 'sprite' }\n * parseAssetKey('enemy:animation'); // returns { role: 'enemy', category: 'animation' }\n * parseAssetKey('invalid'); // returns null\n */\nexport function parseAssetKey(key: string): { role: string; category: string } | null {\n const parts = key.split(':');\n if (parts.length !== 2) return null;\n return { role: parts[0], category: parts[1] };\n}\n\n/**\n * Gets common animations for an entity role.\n * \n * Returns an array of default animation names appropriate for the\n * specified entity role. Used for asset configuration and validation.\n * \n * @param {EntityRole} role - Entity role\n * @returns {string[]} Array of default animation names\n * \n * @example\n * getDefaultAnimationsForRole('player'); // returns ['idle', 'run', 'jump', 'fall', 'attack', 'hurt', 'die']\n * getDefaultAnimationsForRole('enemy'); // returns ['idle', 'walk', 'attack', 'hurt', 'die']\n */\nexport function getDefaultAnimationsForRole(role: EntityRole): string[] {\n switch (role) {\n case 'player':\n return ['idle', 'run', 'jump', 'fall', 'attack', 'hurt', 'die'];\n case 'enemy':\n return ['idle', 'walk', 'attack', 'hurt', 'die'];\n case 'npc':\n return ['idle', 'walk', 'talk'];\n case 'item':\n return ['idle', 'collected'];\n case 'tile':\n return ['static'];\n case 'projectile':\n return ['fly', 'hit', 'expire'];\n case 'effect':\n return ['play'];\n case 'ui':\n return ['normal', 'hover', 'pressed', 'disabled'];\n case 'decoration':\n return ['idle'];\n case 'vehicle':\n return ['idle', 'move', 'brake'];\n default:\n return ['idle'];\n }\n}\n\n/**\n * Validates that an asset reference has required animations.\n * \n * Checks if an asset reference contains all required animations.\n * Returns an error message if validation fails, or null if valid.\n * \n * @param {SemanticAssetRef} assetRef - Asset reference to validate\n * @param {string[]} requiredAnimations - Required animation names\n * @returns {string | null} Error message or null if valid\n * \n * @example\n * validateAssetAnimations(assetRef, ['idle', 'run']); // returns null if valid\n * validateAssetAnimations(assetRef, ['missing-animation']); // returns error message\n */\nexport function validateAssetAnimations(\n assetRef: SemanticAssetRef,\n requiredAnimations: string[]\n): { valid: boolean; missing: string[] } {\n const provided = assetRef.animations || [];\n const missing = requiredAnimations.filter((anim) => !provided.includes(anim));\n return { valid: missing.length === 0, missing };\n}\n","/**\n * Entity Types for Orbital Units\n *\n * Defines the OrbitalEntity type - the nucleus of an Orbital Unit.\n *\n * @packageDocumentation\n */\n\nimport { z } from 'zod';\nimport { EntityFieldSchema, type EntityField } from './field.js';\nimport { SemanticAssetRefSchema, type SemanticAssetRef } from './asset.js';\n\n// ============================================================================\n// Entity Persistence\n// ============================================================================\n\n/**\n * Entity persistence types.\n *\n * - persistent: Stored in database (has collection)\n * - runtime: Exists only at runtime (not persisted)\n * - singleton: Single global instance\n * - instance: Static data (read-only instances)\n */\nexport type EntityPersistence = 'persistent' | 'runtime' | 'singleton' | 'instance' | 'local';\n\nexport const EntityPersistenceSchema = z.enum([\n 'persistent',\n 'runtime',\n 'singleton',\n 'instance',\n 'local',\n]);\n\n// ============================================================================\n// Orbital Entity\n// ============================================================================\n\n/**\n * OrbitalEntity - the nucleus of an Orbital Unit.\n *\n * This is a simplified entity definition optimized for orbital composition.\n * Collection names are derived automatically from persistence type if not provided.\n */\nexport interface OrbitalEntity {\n /** Entity name (PascalCase, e.g., \"Task\", \"User\") */\n name: string;\n\n /** Entity persistence type (defaults to 'persistent' if not specified) */\n persistence?: EntityPersistence;\n\n /** Collection name (auto-derived if not provided for persistent entities) */\n collection?: string;\n\n /** Entity fields */\n fields: EntityField[];\n\n /** Pre-authored instances (seed data or static reference data) */\n instances?: EntityRow[];\n\n /** Auto-add createdAt/updatedAt timestamps */\n timestamps?: boolean;\n\n /** Soft delete support */\n softDelete?: boolean;\n\n /** Human-readable description */\n description?: string;\n\n /** Visual prompt for AI generation */\n visual_prompt?: string;\n\n /** Semantic asset reference for visual representation (games) */\n assetRef?: SemanticAssetRef;\n}\n\nexport const OrbitalEntitySchema = z.object({\n name: z.string().min(1, 'Entity name is required'),\n persistence: EntityPersistenceSchema.default('persistent'),\n collection: z.string().optional(),\n fields: z.array(EntityFieldSchema).min(1, 'At least one field is required'),\n instances: z.array(z.record(z.unknown())).optional(),\n timestamps: z.boolean().optional(),\n softDelete: z.boolean().optional(),\n description: z.string().optional(),\n visual_prompt: z.string().optional(),\n assetRef: SemanticAssetRefSchema.optional(),\n});\n\nexport type OrbitalEntityInput = z.input<typeof OrbitalEntitySchema>;\n\n// ============================================================================\n// Type Aliases (for cleaner imports)\n// ============================================================================\n\n/** Alias for OrbitalEntity - preferred name */\nexport type Entity = OrbitalEntity;\n\n/** Alias for OrbitalEntitySchema - preferred name */\nexport const EntitySchema = OrbitalEntitySchema;\n\n// ============================================================================\n// Utility Functions\n// ============================================================================\n\n/**\n * Derives the collection name for a persistent entity.\n * \n * Generates the database collection name by converting the entity name\n * to lowercase and adding an 's' suffix (simple pluralization).\n * Returns undefined for non-persistent entities (runtime/singleton).\n * \n * @param {OrbitalEntity} entity - Entity to derive collection name for\n * @returns {string | undefined} Collection name or undefined for non-persistent entities\n * \n * @example\n * deriveCollection({ name: 'User', persistence: 'persistent' }); // returns 'users'\n * deriveCollection({ name: 'Task', persistence: 'runtime' }); // returns undefined\n */\nexport function deriveCollection(entity: OrbitalEntity): string | undefined {\n if (entity.persistence !== 'persistent') {\n return undefined;\n }\n // Lowercase + 's' suffix (simple pluralization)\n return entity.name.toLowerCase() + 's';\n}\n\n/**\n * Checks if an entity is runtime-only (not persisted).\n * \n * Type guard to determine if an entity exists only at runtime\n * and is not stored in the database.\n * \n * @param {OrbitalEntity} entity - Entity to check\n * @returns {boolean} True if entity is runtime-only, false otherwise\n * \n * @example\n * isRuntimeEntity({ persistence: 'runtime' }); // returns true\n * isRuntimeEntity({ persistence: 'persistent' }); // returns false\n */\nexport function isRuntimeEntity(entity: OrbitalEntity): boolean {\n return entity.persistence === 'runtime';\n}\n\n/**\n * Checks if an entity is a singleton.\n * \n * Type guard to determine if an entity has a single global instance\n * rather than multiple records in a collection.\n * \n * @param {OrbitalEntity} entity - Entity to check\n * @returns {boolean} True if entity is a singleton, false otherwise\n * \n * @example\n * isSingletonEntity({ persistence: 'singleton' }); // returns true\n * isSingletonEntity({ persistence: 'persistent' }); // returns false\n */\nexport function isSingletonEntity(entity: OrbitalEntity): boolean {\n return entity.persistence === 'singleton';\n}\n\n/**\n * Checks whether an entity's persistence mode allows `persistence` /\n * `collection` overrides at the factory call site.\n *\n * Only `persistent` entities (explicit or default) support these overrides.\n * Runtime, singleton, instance, and local entities are fixed; callers must\n * not expose `persistence` or `collection` params for them.\n *\n * @param persistence - The entity persistence mode (undefined = default persistent)\n * @returns True when overrides are allowed, false otherwise\n *\n * @example\n * persistenceModeAllowsOverrides('persistent'); // returns true\n * persistenceModeAllowsOverrides('runtime'); // returns false\n * persistenceModeAllowsOverrides(undefined); // returns true (default persistent)\n */\nexport function persistenceModeAllowsOverrides(\n persistence: EntityPersistence | undefined,\n): boolean {\n return persistence === 'persistent' || persistence === undefined;\n}\n\n// ============================================================================\n// Entity Instance Data (Runtime)\n// ============================================================================\n\n/**\n * A single field value at runtime.\n * Union of all possible types from FieldType: string, number, boolean, date, array, nested.\n * The nested-record branch's index signature tolerates `undefined` so that\n * TypeScript optional properties (`x?: string`, carrying `string | undefined`)\n * on EntityRow extenders typecheck without ceremony. At JSON serialization\n * time `undefined` is equivalent to \"key absent\" and never appears on the\n * wire; the inclusion here is a pure type-surface accommodation.\n */\nexport type FieldValue = string | number | boolean | Date | null | string[] | FieldValue[] | { [key: string]: FieldValue | undefined };\n\n/**\n * One instance of an entity with actual field values.\n * The shape is determined by the Entity definition at schema time.\n *\n * @example\n * // Entity defines: Patient { fullName: string, age: number, active: boolean }\n * // EntityRow is: { id: \"p1\", fullName: \"Sarah\", age: 34, active: true }\n */\nexport type EntityRow = { id?: string } & Record<string, FieldValue | undefined>;\n\n/**\n * A field-TYPED `EntityRow` — the SINGLE entity type, refined with a concrete\n * field SHAPE `S`. Non-optional members of `S` are REQUIRED, each with its real\n * type; the result stays `& EntityRow`, so the index signature is intact and\n * every other field is still field-open — any domain entity that provides those\n * fields satisfies it.\n *\n * One declaration, two jobs: (1) TypeScript enforces the bound entity has the\n * fields WITH their types (a behavior binding a thinner/mistyped entity fails to\n * typecheck); and (2) pattern-sync reads the same type and writes the entity\n * prop's field shape (`properties` + `requiredFields`) onto the registry, so\n * lolo-ui emits a COMPLETE `entity { … }` (every field, typed + demo-seeded) and\n * the `ORB_X_ENTITY_PROP_CONTRACT` validator rejects an incompatible bind at\n * `orbital validate`. (A raw `EntityRow & { rating: number }` intersection is\n * equivalent for one-off shapes.)\n *\n * @example\n * // HeroOrganism renders entity.title / entity.subtitle:\n * entity?: EntityWith<{ title: string; subtitle?: string }>;\n * // entity.title → string (required)\n * // entity.subtitle → string | undefined (optional)\n * // entity.other → FieldValue | undefined (still field-open)\n */\n// `S extends object` (not `Record<string, FieldValue>`) so a plain `interface`\n// row shape satisfies it — interfaces lack the implicit index signature `Record`\n// requires. FieldValue-compatibility is still enforced structurally: `& EntityRow`\n// intersects every field with the `FieldValue | undefined` index signature, so a\n// non-FieldValue field (e.g. a React `LucideIcon`) collapses to `never` at use.\nexport type EntityWith<S extends object> = EntityRow & S;\n\n/**\n * Collection of entity instances keyed by entity name.\n * Used by OrbPreview mockData, OrbitalServerRuntime state, data grids, etc.\n *\n * @example\n * const data: EntityData = {\n * Patient: [{ id: \"1\", fullName: \"Sarah\", age: 34 }],\n * QueueEntry: [{ id: \"1\", patientName: \"Sarah\", waitMinutes: 12 }],\n * };\n */\nexport type EntityData = Record<string, EntityRow[]>;\n","/**\n * Effect Types (Self-Contained)\n *\n * Defines effect types for trait transitions and ticks.\n * Effects are S-expressions (arrays) that describe actions to perform.\n *\n * @packageDocumentation\n */\n\nimport { z } from 'zod';\nimport { type SExpr, type Expression, type EventPayload } from './expression.js';\nimport { type ServiceParams } from './service.js';\nimport { type EntityRow } from './entity.js';\n\n// ============================================================================\n// UI Slots\n// ============================================================================\n\n/**\n * Known UI slots where content can be rendered\n */\nexport const UI_SLOTS = [\n // App slots\n 'main',\n 'sidebar',\n 'modal',\n 'drawer',\n 'overlay',\n 'center',\n 'toast',\n 'floating',\n 'system', // For invisible system components (InputListener, CollisionDetector)\n 'content',\n 'screen',\n // Game HUD slots\n 'hud',\n 'hud-top',\n 'hud-bottom',\n 'hud.health',\n 'hud.score',\n 'hud.inventory',\n 'hud.stamina',\n // Game overlay slots\n 'overlay.inventory',\n 'overlay.dialogue',\n 'overlay.menu',\n 'overlay.pause',\n] as const;\n\nexport type UISlot = (typeof UI_SLOTS)[number];\n\nexport const UISlotSchema = z.enum(UI_SLOTS);\n\n// ============================================================================\n// Pattern Config (for render-ui effects)\n// ============================================================================\n\n// Import pattern types for local use and re-export for consumers\nimport type {\n PatternType,\n PatternConfig,\n PatternProps,\n PatternPropsMap,\n AnyPatternConfig,\n} from '@almadar/patterns';\n\n/**\n * Type-safe pattern configuration for render-ui effects.\n *\n * Re-exported from @almadar/patterns. Generated from patterns-registry.json.\n *\n * @example\n * // Type-safe with specific pattern type\n * const config: PatternConfig<'entity-table'> = {\n * patternType: 'entity-table',\n * columns: ['name', 'email'], // ✅ Required prop\n * entity: 'User',\n * };\n *\n * // Error: Property 'columns' is missing (required prop)\n * const bad: PatternConfig<'entity-table'> = { patternType: 'entity-table' };\n *\n * // Error: 'fake-pattern' is not assignable to PatternType\n * const invalid: PatternConfig = { patternType: 'fake-pattern' };\n */\nexport type {\n PatternType,\n PatternConfig,\n PatternProps,\n PatternPropsMap,\n AnyPatternConfig,\n};\n\n/**\n * Configuration for render-ui effect.\n * Used in runtime to specify which slot and pattern to render.\n */\nexport interface RenderUIConfig {\n /** Target UI slot */\n slot: UISlot;\n /** Pattern configuration (null clears the slot) */\n pattern: AnyPatternConfig | null;\n /** Target element (trait name or entity ID) */\n target?: string;\n /** Additional props for the pattern */\n props?: ResolvedPatternProps;\n /** Optional priority for slot ordering */\n priority?: number;\n}\n\n// ============================================================================\n// Service Config (for call-service effects)\n// ============================================================================\n\n/**\n * Configuration extracted from call-service effects\n */\nexport interface CallServiceConfig {\n service: string;\n action: string;\n endpoint?: string;\n method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n params?: ServiceParams;\n onSuccess?: string;\n onError?: string;\n}\n\n// ============================================================================\n// Typed Effect Tuples\n// ============================================================================\n\n/**\n * A binding reference to a render tree stored elsewhere — a trait `config`\n * knob or a payload field — e.g. `\"@config.bodyContent\"`. Resolved to a pattern\n * node at render time. This is how an atom renders a tree that contains data\n * bindings (`entity: \"@payload.data\"`, `fields: \"@config.fields\"`): the tree is\n * a permissive `TraitConfigValue` stored in `config` (a binding string is not a\n * valid `AnyPatternConfig` prop value), and the render-ui effect points at it.\n * Worked example: `std-browse`'s loaded transition is `['render-ui', 'main',\n * '@config.bodyContent']`. The Rust validator accepts this form; this variant\n * lets the TS effect type express it.\n */\nexport type RenderBinding = `@${string}`;\n\n/**\n * Render UI effect - displays a pattern in a UI slot.\n * @example ['render-ui', 'main', { patternType: 'entity-table', columns: ['name'] }]\n * @example ['render-ui', 'main', '@config.bodyContent'] // a {@link RenderBinding} target\n */\nexport type RenderUIEffect =\n | ['render-ui', UISlot, AnyPatternConfig]\n | ['render-ui', UISlot, AnyPatternConfig, ResolvedPatternProps]\n | ['render-ui', UISlot, RenderBinding]\n | ['render-ui', UISlot, null];\n\n/**\n * Lambda expression for per-item rendering in data-grid/data-list.\n * The compiler generates: {(paramName: Record<string, unknown>) => (<>JSX</>)}\n * where @{paramName}.field bindings reference the current iteration item.\n *\n * @example [\"fn\", \"item\", { \"type\": \"stack\", \"children\": [{ \"type\": \"typography\", \"content\": \"@item.title\" }] }]\n */\nexport type RenderItemLambda = ['fn', string, AnyPatternConfig];\n\n/**\n * Navigate effect - navigates to a path.\n * @example ['navigate', '/tasks'] or ['navigate', '/tasks/:id', { id: '123' }]\n */\nexport type NavigateEffect = ['navigate', string] | ['navigate', string, Record<string, string>];\n\n/**\n * Emit effect - emits an event, optionally with payload.\n * @example ['emit', 'SAVE'] or ['emit', 'PLAYER_DIED', { playerId: '@entity.id' }]\n * @example ['emit', 'FILTER_CHANGED', '@entity.filters']\n */\nexport type EmitEffect = ['emit', string] | ['emit', string, EventPayload | string];\n\n/**\n * `emit:` config block attached to async / reactive data operators.\n *\n * Each key names an event the runtime should fire on the bus when the\n * effect reaches the corresponding lifecycle point. The set of keys an\n * operator actually supports is enforced by the compiler validator:\n *\n * | Operator | Supported keys |\n * |------------------|---------------------------|\n * | `fetch` | `success`, `failure` |\n * | `persist` | `success`, `failure` |\n * | `call-service` | `success`, `failure` |\n * | `set` | `success` |\n * | `ref` | `on_change`, `failure` |\n * | `os/watch-*` | `on_message`, `failure` |\n *\n * Payload convention:\n * - `success` / `on_change` → the effect's result (fetched entity, new value)\n * - `failure` → `{ error: string, code?: string }`\n * - `on_message` → the incoming message (os/watch-* streams)\n *\n * See `docs/Almadar_Std_Gaps.md` §3.1 for the close-the-circuit design.\n */\nexport interface EmitConfig {\n /** Fires after a one-shot async effect resolves successfully. */\n success?: string;\n /** Fires when the effect throws; payload is `{ error: string }`. */\n failure?: string;\n /** Reactive-subscription event (per update for `ref`). */\n on_change?: string;\n /** Per-event fire for `os/watch-*` streams. */\n on_message?: string;\n}\n\n/**\n * Set effect - sets a binding to a value.\n *\n * Two forms are supported to match the runtime's `set` handler signature\n * `(targetId, field, value)`:\n *\n * - 3-element binding form (legacy / std behaviors): ['set', '@entity.field', value]\n * - 4-element target form (canonical runtime): ['set', entityId, fieldName, value]\n *\n * The 4-element form is what `OrbitalServerRuntime`'s set handler\n * dispatches directly (`update(entityType, targetId, { field: value })`).\n * Prefer the 4-element form when authoring schemas in TypeScript that\n * load directly into the runtime.\n *\n * @example ['set', '@entity.health', 100] // 3-element\n * @example ['set', '@entity.id', 'health', 100] // 4-element\n * @example ['set', '@entity.id', 'count', ['+', '@entity.count', 1]]\n */\nexport type SetEffect =\n | ['set', string, unknown]\n | ['set', string, string, unknown];\n\n/**\n * Trailing config object on persist effects. When present, it carries the\n * `emit` map specifying which events to fire on persist success/failure.\n * Mirrors what the runtime's `EffectExecutor` reads at the 5th tuple\n * position. See `(persist create Entity @payload.data { emit: { success:\n * \"Saved\", failure: \"SaveFailed\" } })` in `.lolo` source.\n */\nexport interface PersistEmitConfig {\n emit?: { success?: string; failure?: string };\n}\n\n/**\n * Persist effect data argument: either an entity row literal (field map)\n * or a binding string referencing a row in scope (e.g. `@payload.data`,\n * `@entity`). At runtime, binding strings resolve to `EntityRow` values\n * before the persist op runs.\n */\nexport type PersistData = EntityRow | string;\n\n/**\n * Persist effect - creates, updates, deletes, or clears entities.\n *\n * Each operation accepts an optional trailing `PersistEmitConfig` so the\n * runtime can fire success / failure events when the operation completes.\n *\n * @example ['persist', 'create', 'Task', { title: '@payload.title' }]\n * @example ['persist', 'update', '@entity.entityType', '@payload.data']\n * @example ['persist', 'create', 'Task', '@payload.data', { emit: { success: 'TaskCreated' } }]\n */\nexport type PersistEffect =\n | ['persist', 'create', string, PersistData]\n | ['persist', 'create', string, PersistData, PersistEmitConfig]\n | ['persist', 'update', string, PersistData]\n | ['persist', 'update', string, PersistData, PersistEmitConfig]\n | ['persist', 'delete', string]\n | ['persist', 'delete', string, PersistData]\n | ['persist', 'delete', string, PersistData, PersistEmitConfig]\n | ['persist', 'clear', string]\n | ['persist', 'clear', string, PersistData]\n | ['persist', 'clear', string, PersistData, PersistEmitConfig];\n\n/**\n * Call service effect - invokes an external service.\n *\n * Two shapes are accepted:\n *\n * 1. Flat form (what the runtime reads and every .orb file uses):\n * `['call-service', serviceName, action, params?]` — args[0]=service,\n * args[1]=action, args[2]=params. This is the canonical form; the\n * runtime's EffectExecutor decodes exactly these positions.\n *\n * 2. Legacy config-object form (kept for the `callService()` helper):\n * `['call-service', serviceName, CallServiceConfig]` — retained so\n * older call sites using the builder helper continue to typecheck.\n *\n * @example ['call-service', 'llm', 'generate', { userPrompt: '@entity.inputText' }]\n * @example ['call-service', 'llm', 'generate', { userPrompt: '...' }, { emit: { success: 'OK', failure: 'ERR' } }]\n * @example ['call-service', 'WeatherAPI', { service: 'weather', action: 'get', onSuccess: 'OK' }]\n */\nexport type CallServiceEffect =\n | ['call-service', string, string]\n | ['call-service', string, string, ServiceParams]\n | ['call-service', string, string, ServiceParams, PersistEmitConfig]\n | ['call-service', string, CallServiceConfig];\n\n/**\n * Spawn effect - creates a new entity instance (games).\n * @example ['spawn', 'Bullet', { x: '@entity.x', y: '@entity.y' }]\n */\nexport type SpawnEffect = ['spawn', string] | ['spawn', string, EntityRow];\n\n/**\n * Despawn effect - removes an entity instance (games).\n * @example ['despawn', '@entity.id']\n */\nexport type DespawnEffect = ['despawn', string];\n\n/**\n * Do effect - executes multiple effects in sequence.\n * Uses SExpr to allow deeply nested conditionals.\n * @example ['do', ['set', '@entity.x', 0], ['set', '@entity.y', 0]]\n */\nexport type DoEffect = ['do', ...SExpr[]];\n\n/**\n * Notify effect - sends a notification.\n * @example ['notify', 'in_app', 'Task created successfully']\n * @example ['notify', 'in_app', ['str/concat', 'Item: ', '@entity.name']]\n */\nexport type NotifyEffect =\n | ['notify', string, string | SExpr]\n | ['notify', string, string | SExpr, string];\n\n/**\n * Options accepted by `fetch` / `ref` / `deref` effects. Mirrors what\n * `OrbitalServerRuntime`'s fetch handler reads at runtime: `id`, `filter`,\n * `limit`, `offset`, `include`, plus the trailing `emit:` map for\n * success/failure event names.\n */\nexport interface FetchOptions {\n /** Fetch a single entity by ID */\n id?: string;\n /** Filter expression (S-expression) */\n filter?: SExpr;\n /** Maximum number of entities to return */\n limit?: number;\n /** Number of entities to skip */\n offset?: number;\n /** Relations to populate (entity field names) */\n include?: string[];\n /** Lifecycle events to emit on resolve / reject */\n emit?: { success?: string; failure?: string };\n}\n\n/**\n * Fetch effect - retrieves entity data (server-side).\n * @example ['fetch', 'User'] or ['fetch', 'User', { id: '@payload.userId' }]\n */\nexport type FetchEffect = ['fetch', string] | ['fetch', string, FetchOptions];\n\n/**\n * Result returned by a fetch / ref / deref handler.\n *\n * `rows` carries the entity (or entities) that survived `filter` AND\n * pagination (`offset`/`limit`). `total` is the count of rows that\n * matched the filter BEFORE pagination, so paginating consumers can\n * compute `totalPages = ceil(total / pageSize)` without a second\n * round-trip. Single-entity fetches by id return `total: 1` (or `0`\n * if not found, in which case the handler returns `null` instead).\n */\nexport interface FetchResult {\n rows: EntityRow | EntityRow[];\n total: number;\n}\n\n/**\n * If effect - conditional effect execution.\n * Uses SExpr to allow deeply nested conditionals.\n * @example ['if', ['>', '@entity.health', 0], ['emit', 'ALIVE'], ['emit', 'DEAD']]\n */\nexport type IfEffect = ['if', Expression, SExpr] | ['if', Expression, SExpr, SExpr];\n\n/**\n * When effect - conditional effect similar to if but without else.\n * Uses SExpr to allow deeply nested conditionals.\n * @example ['when', ['>', '@entity.health', 0], ['emit', 'ALIVE']]\n */\nexport type WhenEffect = ['when', Expression, SExpr];\n\n/**\n * Let effect - creates local bindings for effects.\n * Uses SExpr to allow deeply nested conditionals.\n * @example ['let', ['temp', ['get', '@payload.value']], ['set', '@entity.value', 'temp']]\n */\nexport type LetEffect = ['let', [string, unknown][], ...SExpr[]];\n\n/**\n * Log effect - logs a message for debugging.\n * @example ['log', 'User created:', '@entity.name']\n */\nexport type LogEffect = ['log', ...unknown[]];\n\n/**\n * Wait effect - delays execution.\n * @example ['wait', 1000] - wait 1 second\n */\nexport type WaitEffect = ['wait', number];\n\n// ============================================================================\n// Resource Effects (reactive entity subscriptions and atomic operations)\n// ============================================================================\n\n/**\n * Ref effect - creates a reactive entity subscription.\n * Returns a reactive reference that auto-updates when the entity changes.\n * @example ['ref', '@entity.health'] - reactive subscription to health\n * @example ['ref', 'User', { id: '@payload.userId' }] - reactive ref to specific user\n */\nexport type RefEffect =\n | ['ref', string]\n | ['ref', string, FetchOptions];\n\n/**\n * Deref effect - snapshot read of an entity value.\n * Returns the current value without subscribing to changes.\n * @example ['deref', '@entity.health'] - read current health value\n * @example ['deref', 'User', { id: '@payload.userId' }] - read specific user snapshot\n */\nexport type DerefEffect =\n | ['deref', string]\n | ['deref', string, FetchOptions];\n\n/**\n * Swap! effect - atomic compare-and-swap on an entity field.\n * Only updates if the current value matches the expected value.\n * @example ['swap!', '@entity.health', ['fn', ['old'], ['-', 'old', '@payload.damage']]]\n * @example ['swap!', '@entity.counter', ['+', '@entity.counter', 1]]\n */\nexport type SwapEffect = ['swap!', string, SExpr];\n\n/**\n * Options accepted by `watch` effects. Mirrors what the runtime reads when\n * registering the change callback: `debounce` and the trailing `emit:` map.\n */\nexport interface WatchOptions {\n /** Debounce duration in milliseconds */\n debounce?: number;\n /** Lifecycle events to emit on update / failure */\n emit?: { on_message?: string; failure?: string };\n}\n\n/**\n * Watch effect - registers a callback for entity changes.\n * Emits an event whenever the watched binding changes.\n * @example ['watch', '@entity.health', 'HEALTH_CHANGED']\n * @example ['watch', '@entity.status', 'STATUS_UPDATED', { debounce: 100 }]\n */\nexport type WatchEffect =\n | ['watch', string, string]\n | ['watch', string, string, WatchOptions];\n\n/**\n * Atomic effect - groups multiple effects into an atomic transaction.\n * All effects either succeed together or are rolled back.\n * @example ['atomic', ['set', '@entity.x', 10], ['set', '@entity.y', 20]]\n * @example ['atomic', ['persist', 'update', 'User', { balance: 100 }], ['emit', 'BALANCE_UPDATED']]\n */\nexport type AtomicEffect = ['atomic', ...SExpr[]];\n\n// ============================================================================\n// ML Effects (from almadar-std/modules/nn, tensor, train)\n// ============================================================================\n\n/**\n * One layer in an NN architecture description. The set of valid layer kinds\n * lives in `almadar-std/modules/nn`; here we keep the wire shape generic\n * enough for the cross-package runtime + Python bridge to round-trip.\n */\nexport interface NnLayer {\n type: string;\n [key: string]: string | number | boolean | number[] | string[] | undefined;\n}\n\n/**\n * Hyperparameters for `train` and `evaluate`. Recursive to allow nested\n * optimizer / scheduler config blocks without falling back to `unknown`.\n */\nexport interface NnConfig {\n [key: string]: string | number | boolean | string[] | number[] | NnConfig | undefined;\n}\n\n/**\n * Forward-pass config: `input` is a binding string (`@payload.input`), and\n * `on-complete` names the event to fire when the prediction lands.\n */\nexport interface ForwardConfig {\n architecture: NnLayer[];\n input: string;\n 'on-complete'?: string;\n config?: NnConfig;\n}\n\n/**\n * Training-loop config. `dataset` is a binding string referencing the rows\n * to train on. Optimizer / loss / scheduler land inside `config`.\n */\nexport interface TrainConfig {\n architecture: NnLayer[];\n dataset: string;\n config?: NnConfig;\n 'on-complete'?: string;\n}\n\n/**\n * Evaluation config. `metrics` lists named metrics the Python backend\n * computes (`accuracy`, `precision`, ...).\n */\nexport interface EvaluateConfig {\n architecture: NnLayer[];\n dataset: string;\n metrics: string[];\n config?: NnConfig;\n 'on-complete'?: string;\n}\n\n/**\n * Forward effect - runs a neural network forward pass (Python backend).\n * @example ['forward', 'primary', { architecture: [...], input: '@payload.input', 'on-complete': 'PREDICTION_READY' }]\n */\nexport type ForwardEffect = ['forward', string, ForwardConfig];\n\n/**\n * Train effect - runs a training loop (Python backend).\n * @example ['train', { architecture: [...], dataset: '@entity.data', config: { epochs: 10 }, 'on-complete': 'TRAINING_DONE' }]\n */\nexport type TrainEffect = ['train', TrainConfig];\n\n/**\n * Evaluate effect - runs model evaluation (Python backend).\n * @example ['evaluate', { architecture: [...], dataset: '@entity.testData', metrics: ['accuracy'], 'on-complete': 'EVAL_DONE' }]\n */\nexport type EvaluateEffect = ['evaluate', EvaluateConfig];\n\n/**\n * Checkpoint save effect - saves model weights.\n * @example ['checkpoint/save', '/path/to/model.pt', '@entity.weights']\n */\nexport type CheckpointSaveEffect = ['checkpoint/save', string, unknown];\n\n/**\n * Checkpoint load effect - loads model weights.\n * @example ['checkpoint/load', '/path/to/model.pt']\n */\nexport type CheckpointLoadEffect = ['checkpoint/load', string];\n\n// ============================================================================\n// Agent Effects (from agent/* operator namespace)\n// ============================================================================\n\n/**\n * Agent effect - invokes an agent/* operator.\n * Covers all 22 operators in the std-agent category.\n * @example ['agent/memorize', 'use data-grid for tables', 'preference']\n * @example ['agent/recall', 'user preferences']\n * @example ['agent/generate', 'Summarize this schema']\n */\nexport type AgentEffect = [`agent/${string}`, ...SExpr[]];\n\n/**\n * OS effect - invokes an os/* operator.\n *\n * Covers reactive subscriptions to OS / network resources:\n * - `os/watch-http`, `os/watch-ws`, `os/watch-sse` — long-lived streams\n * that fire `on_message` / `failure` events through a trailing\n * `EmitConfig` block (see `EmitConfig` for the supported keys).\n * - `os/read-file`, `os/exec`, etc. — one-shot OS operations.\n *\n * @example ['os/watch-http', 'wss://push.example.com', { emit: { on_message: 'PUSH_RECEIVED', failure: 'PUSH_DISCONNECTED' } }]\n * @example ['os/read-file', '/etc/hosts']\n */\nexport type OsEffect = [`os/${string}`, ...SExpr[]];\n\n// ============================================================================\n// Async Effects (from almadar-std/modules/async)\n// ============================================================================\n\n/**\n * Async delay effect - wait then execute effects.\n * @example ['async/delay', 2000, ['emit', 'TIMEOUT']]\n */\nexport type AsyncDelayEffect = ['async/delay', number | string, ...Effect[]];\n\n/**\n * Async debounce effect - debounce then execute effect.\n * @example ['async/debounce', 300, ['emit', 'SEARCH_COMPLETE']]\n * @example ['async/debounce', '@entity.debounceMs', ['emit', 'SEARCH_COMPLETE']]\n */\nexport type AsyncDebounceEffect = ['async/debounce', number | string, SExpr];\n\n/**\n * Async throttle effect - throttle then execute effect.\n * @example ['async/throttle', 100, ['emit', 'SCROLL_HANDLED']]\n * @example ['async/throttle', '@entity.throttleMs', ['emit', 'SCROLL_HANDLED']]\n */\nexport type AsyncThrottleEffect = ['async/throttle', number | string, SExpr];\n\n/**\n * Async interval effect - execute effect at intervals.\n * @example ['async/interval', 1000, ['emit', 'TICK']]\n * @example ['async/interval', '@entity.intervalMs', ['emit', 'POLL_TICK']]\n */\nexport type AsyncIntervalEffect = ['async/interval', number | string, SExpr];\n\n/**\n * Async race effect - first effect to complete wins.\n * @example ['async/race', ['call', 'api1'], ['call', 'api2']]\n */\nexport type AsyncRaceEffect = ['async/race', ...Effect[]];\n\n/**\n * Async all effect - wait for all effects to complete.\n * @example ['async/all', ['call', 'api1'], ['call', 'api2']]\n */\nexport type AsyncAllEffect = ['async/all', ...Effect[]];\n\n/**\n * Async sequence effect - execute effects in sequence.\n * @example ['async/sequence', ['call', 'validate'], ['call', 'save']]\n */\nexport type AsyncSequenceEffect = ['async/sequence', ...Effect[]];\n\n/**\n * Union of all typed effects.\n * Provides compile-time validation for common effect types.\n */\nexport type TypedEffect =\n | RenderUIEffect\n | NavigateEffect\n | EmitEffect\n | SetEffect\n | PersistEffect\n | CallServiceEffect\n | SpawnEffect\n | DespawnEffect\n | DoEffect\n | NotifyEffect\n | FetchEffect\n | IfEffect\n | WhenEffect\n | LetEffect\n | LogEffect\n | WaitEffect\n | RefEffect\n | DerefEffect\n | SwapEffect\n | WatchEffect\n | AtomicEffect\n | AsyncDelayEffect\n | AsyncDebounceEffect\n | AsyncThrottleEffect\n | AsyncIntervalEffect\n | AsyncRaceEffect\n | AsyncAllEffect\n | AsyncSequenceEffect\n | ForwardEffect\n | TrainEffect\n | EvaluateEffect\n | CheckpointSaveEffect\n | CheckpointLoadEffect\n | AgentEffect\n | OsEffect;\n\n// ============================================================================\n// Effect Type (Strictly Typed)\n// ============================================================================\n\n/**\n * Effect type - typed S-expression format.\n *\n * Effects are strongly typed tuples that enforce:\n * - Valid effect operators (render-ui, emit, set, persist, navigate, call-service)\n * - Valid UISlots for render-ui\n * - Valid PatternTypes and props for render-ui\n * - Correct argument types for each effect\n *\n * Available typed effects:\n * - RenderUIEffect: ['render-ui', UISlot, PatternConfig]\n * - NavigateEffect: ['navigate', path] or ['navigate', path, params]\n * - EmitEffect: ['emit', eventName] or ['emit', eventName, payload]\n * - SetEffect: ['set', binding, value]\n * - PersistEffect: ['persist', operation, entity, data?]\n * - CallServiceEffect: ['call-service', serviceName, config]\n *\n * @example\n * [\"set\", \"@entity.health\", 100]\n * [\"emit\", \"PLAYER_DIED\", { \"playerId\": \"@entity.id\" }]\n * [\"render-ui\", \"main\", { \"patternType\": \"entity-table\", \"columns\": [\"name\"] }]\n * [\"call-service\", \"WeatherAPI\", { \"action\": \"getWeather\", \"onSuccess\": \"OK\" }]\n * [\"navigate\", \"/tasks\"]\n * [\"persist\", \"create\", \"Task\", { \"title\": \"@payload.title\" }]\n */\nexport type Effect = TypedEffect;\n\n/**\n * Schema for Effect - validates S-expression format\n */\nexport const EffectSchema = z.array(z.unknown()).min(1).refine(\n (arr) => typeof arr[0] === 'string',\n { message: 'Effect must be an S-expression with a string operator as first element' }\n);\n\nexport type EffectInput = z.input<typeof EffectSchema>;\n\n/**\n * Type guard to check if a value is a valid Effect (S-expression).\n * \n * Validates that a value conforms to the Effect structure. Effects are\n * represented as arrays where the first element is a string (effect type)\n * and subsequent elements are parameters. Used for runtime validation\n * of effect structures.\n * \n * @param {unknown} value - Value to check\n * @returns {boolean} True if value is a valid Effect, false otherwise\n * \n * @example\n * isEffect(['set', '@entity.health', 100]); // returns true\n * isEffect('not-an-effect'); // returns false\n * isEffect([]); // returns false\n */\nexport function isEffect(value: unknown): value is Effect {\n return Array.isArray(value) && value.length > 0 && typeof value[0] === 'string';\n}\n\n/**\n * Alias for isEffect (for clarity when working with S-expressions)\n */\nexport const isSExprEffect = isEffect;\n\n// ============================================================================\n// Effect Builder Helpers\n// ============================================================================\n\n/**\n * Creates a set effect for state updates.\n * \n * Generates an effect that sets a binding to a value. Used in state\n * machine transitions to update entity fields, UI state, or other\n * mutable data.\n * \n * @param {string} binding - Target binding (e.g., '@entity.health')\n * @param {SExpr} value - Value to set (can be literal or expression)\n * @returns {Effect} Set effect array\n * \n * @example\n * set('@entity.health', 100); // returns [\"set\", \"@entity.health\", 100]\n * set('@state.loading', false); // returns [\"set\", \"@state.loading\", false]\n */\nexport function set(binding: string, value: SExpr): Effect {\n return ['set', binding, value];\n}\n\n/**\n * Creates an emit effect for event dispatching.\n * \n * Generates an effect that emits an event with optional payload.\n * Used in state machine transitions to trigger events that can be\n * handled by other traits, services, or external systems.\n * \n * @param {string} event - Event name to emit\n * @param {EventPayload} [payload] - Optional event payload\n * @returns {Effect} Emit effect array\n * \n * @example\n * emit('PLAYER_DIED', { playerId: '@entity.id' }); // returns [\"emit\", \"PLAYER_DIED\", { playerId: \"@entity.id\" }]\n * emit('GAME_STARTED'); // returns [\"emit\", \"GAME_STARTED\"]\n */\nexport function emit(event: string, payload?: EventPayload): Effect {\n return payload ? ['emit', event, payload] : ['emit', event];\n}\n\n/**\n * Creates a navigation effect for page routing.\n * \n * Generates an effect that navigates to a specified path with optional\n * parameters. Used in state machine transitions to change pages or\n * update URL parameters.\n * \n * @param {string} path - Target path (e.g., '/tasks')\n * @param {Record<string, string>} [params] - Optional URL parameters\n * @returns {NavigateEffect} Navigation effect array\n * \n * @example\n * navigate('/tasks'); // returns [\"navigate\", \"/tasks\"]\n * navigate('/user', { id: '123' }); // returns [\"navigate\", \"/user\", { id: \"123\" }]\n */\nexport function navigate(path: string): NavigateEffect;\nexport function navigate(path: string, params: Record<string, string>): NavigateEffect;\nexport function navigate(path: string, params?: Record<string, string>): NavigateEffect {\n return params ? ['navigate', path, params] : ['navigate', path];\n}\n\n/**\n * Create a render-ui effect\n * @example [\"render-ui\", \"main\", { \"patternType\": \"entity-table\", \"columns\": [\"name\"] }]\n */\nexport function renderUI(\n target: UISlot,\n pattern: AnyPatternConfig\n): RenderUIEffect;\nexport function renderUI(\n target: UISlot,\n pattern: AnyPatternConfig,\n props: ResolvedPatternProps\n): RenderUIEffect;\nexport function renderUI(\n target: UISlot,\n pattern: AnyPatternConfig,\n props?: ResolvedPatternProps\n): RenderUIEffect {\n return props\n ? ['render-ui', target, pattern, props]\n : ['render-ui', target, pattern];\n}\n\n/**\n * Create a persist effect\n * @example [\"persist\", \"create\", \"Task\", { \"title\": \"@payload.title\" }]\n */\nexport function persist(\n action: 'create' | 'update',\n entity: string,\n data: PersistData\n): PersistEffect;\nexport function persist(\n action: 'delete' | 'clear',\n entity: string,\n data?: PersistData\n): PersistEffect;\nexport function persist(\n action: 'create' | 'update' | 'delete' | 'clear',\n entity: string,\n data?: PersistData\n): PersistEffect {\n if (action === 'create' || action === 'update') {\n return ['persist', action, entity, data!] as PersistEffect;\n }\n return data\n ? ['persist', action, entity, data] as PersistEffect\n : ['persist', action, entity] as PersistEffect;\n}\n\n/**\n * Create a call-service effect\n * @example [\"call-service\", \"stripe\", { \"service\": \"stripe\", \"action\": \"charge\", \"onSuccess\": \"OK\", \"onError\": \"ERR\" }]\n */\nexport function callService(\n serviceName: string,\n config: CallServiceConfig\n): CallServiceEffect {\n return ['call-service', serviceName, config];\n}\n\n/**\n * Create a spawn effect (games)\n * @example [\"spawn\", \"Bullet\", { \"x\": \"@entity.x\", \"y\": \"@entity.y\" }]\n */\nexport function spawn(entity: string): SpawnEffect;\nexport function spawn(entity: string, initialState: EntityRow): SpawnEffect;\nexport function spawn(entity: string, initialState?: EntityRow): SpawnEffect {\n return initialState ? ['spawn', entity, initialState] : ['spawn', entity];\n}\n\n/**\n * Create a despawn effect (games)\n * @example [\"despawn\", \"@entity.id\"]\n */\nexport function despawn(entityId: string): DespawnEffect {\n return ['despawn', entityId];\n}\n\n/**\n * Create a do effect (multiple effects)\n * @example [\"do\", [\"set\", \"@entity.x\", 0], [\"set\", \"@entity.y\", 0]]\n */\nexport function doEffects(...effects: SExpr[]): DoEffect {\n return ['do', ...effects];\n}\n\n/**\n * Create a notify effect\n * @example [\"notify\", \"in_app\", \"Task created successfully\"]\n */\nexport function notify(\n channel: 'email' | 'push' | 'sms' | 'in_app',\n message: string\n): NotifyEffect;\nexport function notify(\n channel: 'email' | 'push' | 'sms' | 'in_app',\n message: string,\n recipient: string\n): NotifyEffect;\nexport function notify(\n channel: 'email' | 'push' | 'sms' | 'in_app',\n message: string,\n recipient?: string\n): NotifyEffect {\n return recipient\n ? ['notify', channel, message, recipient]\n : ['notify', channel, message];\n}\n\n/**\n * Create a fetch effect (server-side data retrieval)\n * @example [\"fetch\", \"User\"] - fetch all users\n * @example [\"fetch\", \"User\", { \"id\": \"@payload.userId\" }] - fetch by ID\n * @example [\"fetch\", \"User\", { \"filter\": [\"=\", \"@entity.status\", \"active\"], \"limit\": 10 }]\n */\nexport function fetch(entity: string): FetchEffect;\nexport function fetch(entity: string, options: FetchOptions): FetchEffect;\nexport function fetch(entity: string, options?: FetchOptions): FetchEffect {\n return options ? ['fetch', entity, options] : ['fetch', entity];\n}\n\n// ============================================================================\n// Resource Effect Builder Helpers\n// ============================================================================\n\n/**\n * Create a ref effect (reactive entity subscription).\n *\n * @param {string} binding - Binding or entity name to subscribe to\n * @param {FetchOptions} [selector] - Optional selector for specific entity\n * @returns {RefEffect} Ref effect array\n *\n * @example\n * ref('@entity.health'); // returns [\"ref\", \"@entity.health\"]\n * ref('User', { id: '@payload.userId' }); // returns [\"ref\", \"User\", { id: \"@payload.userId\" }]\n */\nexport function ref(binding: string): RefEffect;\nexport function ref(binding: string, selector: FetchOptions): RefEffect;\nexport function ref(binding: string, selector?: FetchOptions): RefEffect {\n return selector ? ['ref', binding, selector] : ['ref', binding];\n}\n\n/**\n * Create a deref effect (snapshot read).\n *\n * @param {string} binding - Binding or entity name to read\n * @param {FetchOptions} [selector] - Optional selector for specific entity\n * @returns {DerefEffect} Deref effect array\n *\n * @example\n * deref('@entity.health'); // returns [\"deref\", \"@entity.health\"]\n * deref('User', { id: '@payload.userId' }); // returns [\"deref\", \"User\", { id: \"@payload.userId\" }]\n */\nexport function deref(binding: string): DerefEffect;\nexport function deref(binding: string, selector: FetchOptions): DerefEffect;\nexport function deref(binding: string, selector?: FetchOptions): DerefEffect {\n return selector ? ['deref', binding, selector] : ['deref', binding];\n}\n\n/**\n * Create a swap! effect (atomic compare-and-swap).\n *\n * @param {string} binding - Binding to atomically update\n * @param {SExpr} transform - Transformation expression applied to the current value\n * @returns {SwapEffect} Swap effect array\n *\n * @example\n * swap('@entity.counter', ['+', '@entity.counter', 1]);\n * // returns [\"swap!\", \"@entity.counter\", [\"+\", \"@entity.counter\", 1]]\n */\nexport function swap(binding: string, transform: SExpr): SwapEffect {\n return ['swap!', binding, transform];\n}\n\n/**\n * Create a watch effect (entity change callback).\n *\n * @example\n * watch('@entity.health', 'HEALTH_CHANGED');\n * watch('@entity.status', 'STATUS_UPDATED', { debounce: 100 });\n */\nexport function watch(binding: string, event: string): WatchEffect;\nexport function watch(binding: string, event: string, options: WatchOptions): WatchEffect;\nexport function watch(binding: string, event: string, options?: WatchOptions): WatchEffect {\n return options\n ? ['watch', binding, event, options]\n : ['watch', binding, event];\n}\n\n/**\n * Create an atomic effect (transaction group).\n *\n * @param {...SExpr[]} effects - Effects to execute atomically\n * @returns {AtomicEffect} Atomic effect array\n *\n * @example\n * atomic(['set', '@entity.x', 10], ['set', '@entity.y', 20]);\n * // returns [\"atomic\", [\"set\", \"@entity.x\", 10], [\"set\", \"@entity.y\", 20]]\n */\nexport function atomic(...effects: SExpr[]): AtomicEffect {\n return ['atomic', ...effects];\n}\n\n// ============================================================================\n// Runtime Pattern Types\n// ============================================================================\n\n/** Resolved pattern props for render-ui effects at runtime. Recursive for nested pattern configs. */\nexport interface ResolvedPatternProps {\n [prop: string]: string | number | boolean | null | undefined | ResolvedPatternProps | ResolvedPatternProps[];\n}\n\n/** A node in a render-ui effect tree. */\nexport interface RenderUINode {\n type: string;\n props?: ResolvedPatternProps;\n children?: RenderUINode[];\n content?: string;\n entity?: string;\n renderItem?: RenderUINode;\n}\n\n","/**\n * S-Expression Types\n *\n * Defines the S-Expression type system for guards, effects, and computed values.\n * S-expressions are JSON arrays where the first element is an operator string.\n *\n * @example\n * // Guard: health > 0\n * [\">\", \"@entity.health\", 0]\n *\n * // Effect: set x to x + vx\n * [\"set\", \"@entity.x\", [\"+\", \"@entity.x\", \"@entity.vx\"]]\n *\n * @packageDocumentation\n */\n\nimport { z } from 'zod';\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// eslint-disable-next-line almadar/no-record-string-unknown -- SExprAtom defines the base type for object literals in S-expressions\nexport type SExprAtom = string | number | boolean | null | Record<string, unknown>;\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 * 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.unknown()), // Objects for payload data\n]);\n\n/**\n * Recursive schema for S-expressions.\n * Validates that arrays have at least one element and first element is a string (operator).\n */\nexport const SExprSchema: z.ZodType<SExpr> = z.lazy(() =>\n z.union([\n SExprAtomSchema,\n z\n .array(z.lazy(() => SExprSchema))\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// ============================================================================\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: unknown): 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 {unknown} 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: unknown): 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 {unknown} 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: unknown): 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 {unknown} 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: unknown): 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 */\nexport const CORE_BINDINGS = ['entity', 'payload', 'state', 'now', 'config', 'computed', 'trait', 'user'] 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/**\n * Get the arguments from an S-expression call.\n *\n * @param expr - S-expression array\n * @returns Array of arguments (empty if not a valid call)\n */\nexport function getArgs(expr: SExpr): SExpr[] {\n if (!isSExpr(expr)) return [];\n return expr.slice(1);\n}\n\n/**\n * Create an S-expression call.\n *\n * @param operator - The operator string\n * @param args - Arguments to the operator\n * @returns S-expression array\n */\nexport function sexpr(operator: string, ...args: SExpr[]): SExpr[] {\n return [operator, ...args];\n}\n\n/**\n * Walk an S-expression tree and apply a visitor function to each node.\n *\n * @param expr - S-expression to walk\n * @param visitor - Function to call on each node\n */\nexport function walkSExpr(\n expr: SExpr,\n visitor: (node: SExpr, parent: SExpr[] | null, index: number) => void,\n parent: SExpr[] | null = null,\n index: number = 0\n): void {\n visitor(expr, parent, index);\n\n if (isSExpr(expr)) {\n for (let i = 0; i < expr.length; i++) {\n walkSExpr(expr[i], visitor, expr, i);\n }\n }\n}\n\n/**\n * Collect all bindings referenced in an S-expression.\n *\n * @param expr - S-expression to analyze\n * @returns Array of binding strings found\n */\nexport function collectBindings(expr: SExpr): string[] {\n const bindings: string[] = [];\n\n walkSExpr(expr, (node) => {\n if (isBinding(node)) {\n bindings.push(node);\n }\n });\n\n return bindings;\n}\n\n// ============================================================================\n// Type Exports\n// ============================================================================\n\nexport type SExprInput = z.input<typeof SExprSchema>;\nexport type ExpressionInput = z.input<typeof ExpressionSchema>;\n\n// ============================================================================\n// Runtime Evaluation Types\n// ============================================================================\n\n/** Evaluation context for guards and s-expressions. Recursive. */\nexport interface EvalContext {\n [key: string]: string | number | boolean | Date | null | string[] | EvalContext | undefined;\n}\n\n/**\n * A single value carried by an event payload field. The top-level payload\n * is always an object; the VALUES in that object can be primitives, nested\n * objects, or arrays of the same. Arrays are allowed so real-world emits\n * like `{ files: [{ name, size, type }, ...] }` or `{ selected: string[] }`\n * are typed natively instead of forcing consumers to wrap at every call.\n *\n * `Date` is included so `EntityRow` (whose values are `FieldValue`, which\n * includes `Date`) is assignable to a payload field without a cast —\n * emitted entity rows flow through the bus without boundary widening.\n */\nexport type EventPayloadValue =\n | string\n | number\n | boolean\n | Date\n | null\n | undefined\n | EventPayload\n | readonly EventPayloadValue[];\n\n/**\n * Typed event payload. Object-shaped so it's assignable to the bus's\n * `EventPayload` parameter without casts.\n */\nexport interface EventPayload {\n [key: string]: EventPayloadValue;\n}\n\n/**\n * 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 * State Machine Types (Self-Contained)\n *\n * Defines state machine types for traits.\n * Copied from schema/state-machine.ts to make orbitals/ self-contained.\n *\n * @packageDocumentation\n */\n\nimport { z } from \"zod\";\nimport type { Effect } from \"./effect.js\";\nimport { EffectSchema } from \"./effect.js\";\nimport type { Expression } from \"./expression.js\";\nimport { ExpressionSchema } from \"./expression.js\";\n\n// ============================================================================\n// State\n// ============================================================================\n\n/**\n * Represents a state in the state machine\n */\nexport interface State {\n /** State name (unique identifier) */\n name: string;\n /** Whether this is the initial state */\n isInitial?: boolean;\n /** Whether this is a terminal state (no outgoing transitions expected) */\n isTerminal?: boolean;\n /** Whether this is a final state (legacy alias for isTerminal) */\n isFinal?: boolean;\n /** Human-readable description */\n description?: string;\n /** Effect names to run on entry */\n onEntry?: string[];\n /** Effect names to run on exit */\n onExit?: string[];\n}\n\nexport const StateSchema = z.object({\n name: z.string().min(1, \"State name is required\"),\n isInitial: z.boolean().optional(),\n isTerminal: z.boolean().optional(),\n isFinal: z.boolean().optional(),\n description: z.string().optional(),\n onEntry: z.array(z.string()).optional(),\n onExit: z.array(z.string()).optional(),\n});\n\n// ============================================================================\n// Event\n// ============================================================================\n\n/**\n * Payload field definition for events\n */\nexport interface PayloadField {\n name: string;\n /**\n * Field type. Mirrors the Rust validator's acceptance: any non-empty\n * string. Primitives ('string' | 'number' | 'boolean' | 'object' |\n * 'array') are the canonical values; entity-name references like\n * 'CartItem' and array-of-entity references like '[CartItem]' are also\n * valid because the Rust IR's PayloadField.field_type is just a String.\n */\n type: string;\n required?: boolean;\n}\n\nexport const PayloadFieldSchema = z.object({\n name: z.string().min(1),\n type: z.string().min(1),\n required: z.boolean().optional(),\n});\n\n/**\n * Represents an event that can trigger transitions\n */\nexport interface Event {\n /** Event key (UPPER_SNAKE_CASE) */\n key: string;\n /** Human-readable name */\n name: string;\n /** Description (authored `@description` on the emit/listen). */\n description?: string;\n /** User-vocabulary synonyms (comma-separated) — per-event analogue of a\n * field/config `@synonyms`. Feeds the curation event matcher. */\n synonyms?: string;\n /** Authoring tier (`essential`/`customization`/`advanced`/`internal`). */\n tier?: string;\n /** Expected payload structure */\n payloadSchema?: PayloadField[];\n /** Domain vs System classification (optional, for analysis) */\n classification?: \"domain\" | \"system\";\n /** Semantic role of this event (optional, for analysis) */\n semanticRole?: string;\n}\n\nexport const EventSchema = z.object({\n key: z.string().min(1, \"Event key is required\"),\n name: z.string().min(1, \"Event name is required\"),\n description: z.string().optional(),\n synonyms: z.string().optional(),\n tier: z.string().optional(),\n payloadSchema: z.array(PayloadFieldSchema).optional(),\n classification: z.enum([\"domain\", \"system\"]).optional(),\n semanticRole: z.string().optional(),\n});\n\n// ============================================================================\n// Guard\n// ============================================================================\n\n/**\n * Represents a named guard condition.\n * Expression must be an S-expression.\n *\n * @example\n * {\n * name: \"hasHealth\",\n * expression: [\">\", \"@entity.health\", 0],\n * description: \"Check if entity has health remaining\"\n * }\n */\nexport interface Guard {\n name: string;\n /** Guard expression - S-expression array only */\n expression: Expression;\n description?: string;\n}\n\nexport const GuardSchema = z.object({\n name: z.string().min(1, \"Guard name is required\"),\n expression: ExpressionSchema,\n description: z.string().optional(),\n});\n\n// ============================================================================\n// Transition (Effect imported separately to avoid circular deps)\n// ============================================================================\n\n/**\n * Represents a transition between states.\n * Guards and effects must be S-expressions.\n *\n * @example\n * {\n * from: \"idle\",\n * to: \"running\",\n * event: \"START\",\n * guard: [\">\", \"@entity.fuel\", 0],\n * effects: [\n * [\"set\", \"@entity.status\", \"running\"],\n * [\"emit\", \"ENGINE_STARTED\"]\n * ]\n * }\n */\nexport interface Transition {\n /** Source state name */\n from: string;\n /** Target state name */\n to: string;\n /** Event key that triggers this transition */\n event: string;\n /** Guard expression - S-expression array */\n guard?: Expression | null;\n /** Effects to execute - S-expression arrays */\n effects?: Effect[];\n /** Description */\n description?: string | null;\n}\n\nexport const TransitionSchema = z.object({\n from: z.string().min(1, \"Transition source state is required\"),\n to: z.string().min(1, \"Transition target state is required\"),\n event: z.string().min(1, \"Transition event is required\"),\n guard: ExpressionSchema.nullish(),\n effects: z.array(EffectSchema).optional(),\n description: z.string().nullish(),\n});\n\n// ============================================================================\n// State Machine\n// ============================================================================\n\n/**\n * Complete state machine definition\n */\nexport interface StateMachine {\n /** All states in the machine */\n states: State[];\n /** All events that can be triggered */\n events: Event[];\n /** All transitions between states */\n transitions: Transition[];\n /** Named guard definitions */\n guards?: Guard[];\n}\n\nexport const StateMachineSchema = z.object({\n states: z.array(StateSchema).min(1, \"At least one state is required\"),\n events: z.array(EventSchema),\n transitions: z.array(TransitionSchema),\n guards: z.array(GuardSchema).optional(),\n});\n\n// ============================================================================\n// Type exports\n// ============================================================================\n\nexport type StateInput = z.input<typeof StateSchema>;\nexport type EventInput = z.input<typeof EventSchema>;\nexport type GuardInput = z.input<typeof GuardSchema>;\nexport type TransitionInput = z.input<typeof TransitionSchema>;\nexport type StateMachineInput = z.input<typeof StateMachineSchema>;\n\n// ============================================================================\n// Event Utilities\n// ============================================================================\n\n/**\n * Check if an event is a circuit event (not internal/system event).\n * Circuit events are user-defined events that participate in the closed circuit pattern.\n * Internal/system events start with underscore (e.g., _INIT, _TICK, _TIMER).\n *\n * @param {string} event - Event name to check\n * @returns {boolean} true if event is a circuit event (doesn't start with underscore)\n *\n * @example\n * isCircuitEvent('CREATE') // true\n * isCircuitEvent('SAVE') // true\n * isCircuitEvent('_INIT') // false (internal)\n * isCircuitEvent('_TICK') // false (internal)\n */\nexport function isCircuitEvent(event: string): boolean {\n return !event.startsWith('_');\n}\n","/**\n * Trait Types (Self-Contained)\n *\n * Defines trait types for behavioral patterns.\n * Self-contained - imports only from local orbital types.\n *\n * @packageDocumentation\n */\n\nimport { z } from 'zod';\nimport type { StateMachine } from './state-machine.js';\nimport { StateMachineSchema } from './state-machine.js';\nimport type { Effect } from './effect.js';\nimport { EffectSchema } from './effect.js';\nimport type { Entity } from './entity.js';\nimport { EntitySchema } from './entity.js';\nimport type { AnyPatternConfig } from '@almadar/patterns';\nimport type { Expression } from './expression.js';\nimport { ExpressionSchema } from './expression.js';\n\n// ============================================================================\n// Trait Configuration\n// ============================================================================\n\n/**\n * A single value in a trait's call-site `config: { ... }` block. Supports\n * scalars (string, number, boolean, null), arrays (e.g. `fields: [\"name\",\n * \"description\"]`), and nested objects. This is the authoring surface for\n * molecules to parameterize imported atoms: the atom's render-ui reads back\n * via `@config.<key>` bindings.\n */\nexport type TraitConfigValue =\n | string\n | number\n | boolean\n | null\n | ReadonlyArray<TraitConfigValue>\n | TraitConfigObject;\n\nexport interface TraitConfigObject {\n readonly [key: string]: TraitConfigValue;\n}\n\nexport type TraitConfig = TraitConfigObject;\n\n/** Zod schema for TraitConfig. Recursive via z.lazy to allow nested structures. */\nexport const TraitConfigValueSchema: z.ZodType<TraitConfigValue> = z.lazy(() =>\n z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.null(),\n z.array(TraitConfigValueSchema),\n z.record(TraitConfigValueSchema),\n ])\n);\n\nexport const TraitConfigSchema: z.ZodType<TraitConfig> = z.record(TraitConfigValueSchema);\n\n/**\n * A single entry in a call-site `config { }` override block. Either a plain\n * wiring value (`TraitConfigValue` — string, number, bool, array, object) or\n * a fully-annotated re-declaration (`ConfigFieldDeclaration` — carries `type`,\n * optional `label`/`description`/`synonyms`/`tier`). Disambiguated at runtime\n * by `isCallSiteConfigDeclaration`: the presence of a `\"type\"` string key\n * marks the annotated form.\n *\n * The `.orb` compiler emits plain values for wiring entries and\n * `{ type, default, ... }` objects for annotated entries. Consumers that only\n * need the value (e.g. `apply-params-to-orb.ts`) read `entry` directly for\n * primitives or `entry.default` for the declaration form.\n */\nexport type CallSiteConfigEntry = TraitConfigValue | ConfigFieldDeclaration;\n\n/** Typed map of call-site config entries (one per knob). */\nexport type CallSiteConfig = Readonly<Record<string, CallSiteConfigEntry>>;\n\n/**\n * Type guard: returns `true` when `entry` is an annotated `ConfigFieldDeclaration`\n * (a config-field SCHEMA: a `\"type\"` string key AND a `\"default\"` value slot)\n * rather than a plain wiring value or a render value object.\n *\n * The `\"default\"` requirement disambiguates a declaration from a `render-ui`\n * VALUE object (e.g. `{ type: \"tabs\", items: \"@entity.items\", ... }`) that\n * coincidentally carries a UI-component `type` key — such a value has no\n * `default` slot and is a `TraitConfigValue`, not a schema declaration. Every\n * annotated config field lowered from `.lolo` carries a `default`; misreading a\n * render value as a declaration drops it straight into the `config` map where\n * Rust's `serde` rejects its inner fields (e.g. `items` is a binding string,\n * not a `FieldDefinition`).\n */\nexport function isCallSiteConfigDeclaration(\n entry: CallSiteConfigEntry,\n): entry is ConfigFieldDeclaration {\n return (\n typeof entry === 'object' &&\n entry !== null &&\n !Array.isArray(entry) &&\n 'type' in entry &&\n typeof entry.type === 'string' &&\n 'default' in entry\n );\n}\n\n/**\n * Per-field entry in a trait's DECLARED `config { }` schema as it lives\n * on the `.orb` JSON: `{ type: \"string\" | \"[string]\" | \"object\" | ...,\n * default?: <value> }`. Distinct from `TraitConfigValue` (which is the\n * resolved runtime value). The runtime reads `default` to seed the\n * `@config.X` binding context when no call-site override is supplied.\n *\n * Authored as `config { foo : string = \"bar\" }` in `.lolo`; lowered to\n * `{ foo: { type: \"string\", default: \"bar\" } }` in `.orb`. The optional\n * metadata fields below (`label`/`description`/`tier`/`values`/`synonyms`)\n * carry the `.lolo` `@label`/`@description`/`@tier`/`@synonyms` annotations and\n * the enum member list through lowering — consumed by config-driven UI\n * (e.g. the playground property inspector) to render typed controls.\n */\nexport interface ConfigFieldDeclaration {\n readonly type: string;\n readonly default?: TraitConfigValue;\n /** `@label` — human-readable control label. */\n readonly label?: string;\n /** `@description` — help/tooltip text for the field. */\n readonly description?: string;\n /** `@tier` — disclosure tier: `presentation`|`domain`|`policy`|`infra`|`internal`. */\n readonly tier?: string;\n /** Enum members when the field's type is a string union — drives a select control. */\n readonly values?: ReadonlyArray<string>;\n /** `@synonyms` — comma-separated vocabulary synonyms (metadata). */\n readonly synonyms?: string;\n}\n\nexport const ConfigFieldDeclarationSchema: z.ZodType<ConfigFieldDeclaration> = z.object({\n type: z.string(),\n default: TraitConfigValueSchema.optional(),\n label: z.string().optional(),\n description: z.string().optional(),\n tier: z.string().optional(),\n values: z.array(z.string()).optional(),\n synonyms: z.string().optional(),\n});\n\n/**\n * Map of declared config fields keyed by name. Lives on `Trait.config`\n * and `ResolvedTrait.config` for atoms/molecules that expose typed\n * configuration to consumers.\n */\nexport type DeclaredTraitConfig = Readonly<Record<string, ConfigFieldDeclaration>>;\n\nexport const DeclaredTraitConfigSchema: z.ZodType<DeclaredTraitConfig> = z.record(\n ConfigFieldDeclarationSchema,\n);\n\n// ============================================================================\n// Trait Categories\n// ============================================================================\n\n/**\n * Categories for organizing traits\n */\nexport type TraitCategory =\n | 'lifecycle'\n | 'temporal'\n | 'validation'\n | 'notification'\n | 'integration'\n | 'interaction'\n | 'agent'\n | 'game-core'\n | 'game-character'\n | 'game-ai'\n | 'game-combat'\n | 'game-items'\n | 'game-cards'\n | 'game-board'\n | 'game-puzzle';\n\nexport const TraitCategorySchema = z.enum([\n 'lifecycle',\n 'temporal',\n 'validation',\n 'notification',\n 'integration',\n 'interaction',\n 'agent',\n 'game-core',\n 'game-character',\n 'game-ai',\n 'game-combat',\n 'game-items',\n 'game-cards',\n 'game-board',\n 'game-puzzle',\n]);\n\n// ============================================================================\n// Trait Entity Field (simplified)\n// ============================================================================\n\n/**\n * Field types for trait data entities\n */\nexport type TraitFieldType = 'string' | 'number' | 'boolean' | 'date' | 'array' | 'object' | 'timestamp' | 'datetime' | 'enum';\n\n/**\n * Simplified field for trait data entities\n */\nexport interface TraitEntityField {\n name: string;\n type: TraitFieldType;\n required?: boolean;\n default?: unknown;\n values?: string[];\n}\n\nexport const TraitEntityFieldSchema = z.object({\n name: z.string().min(1),\n type: z.enum([\n 'string',\n 'number',\n 'boolean',\n 'date',\n 'array',\n 'object',\n 'timestamp',\n 'datetime',\n 'enum',\n ]),\n required: z.boolean().optional(),\n default: z.unknown().optional(),\n values: z.array(z.string()).optional(),\n});\n\n// ============================================================================\n// Trait Data Entity\n// ============================================================================\n\n/**\n * Simplified data entity for traits\n */\nexport interface TraitDataEntity {\n name: string;\n collection?: string;\n fields: TraitEntityField[];\n timestamps?: boolean;\n description?: string;\n runtime?: boolean;\n singleton?: boolean;\n pages?: string[];\n}\n\nexport const TraitDataEntitySchema = z.object({\n name: z.string().min(1),\n collection: z.string().optional(),\n fields: z.array(TraitEntityFieldSchema).min(1),\n timestamps: z.boolean().optional(),\n description: z.string().optional(),\n runtime: z.boolean().optional(),\n singleton: z.boolean().optional(),\n pages: z.array(z.string()).optional(),\n});\n\n// ============================================================================\n// Trait Tick\n// ============================================================================\n\n/**\n * Tick rule for traits.\n * Guards can be legacy strings or S-expressions.\n * Effects can be typed Effect objects or S-expressions.\n */\nexport interface TraitTick {\n name: string;\n description?: string;\n priority?: number;\n interval: string | number;\n appliesTo?: string[];\n pages?: string[];\n /** Guard expression - string (legacy) or S-expression array */\n guard?: Expression;\n /** Effects to execute (S-expressions) */\n effects: Effect[];\n /**\n * Events this tick emits.\n * Must reference events defined in trait's emits array.\n * Used for validation and documentation.\n */\n emits?: string[];\n}\n\nexport const TraitTickSchema = z.object({\n name: z.string().min(1),\n description: z.string().optional(),\n priority: z.number().optional(),\n interval: z.union([z.literal('frame'), z.number().positive()]),\n appliesTo: z.array(z.string()).optional(),\n pages: z.array(z.string()).optional(),\n guard: ExpressionSchema.optional(),\n effects: z.array(EffectSchema).min(1),\n emits: z.array(z.string()).optional(),\n});\n\n// ============================================================================\n// Event Scope\n// ============================================================================\n\n/**\n * Event scope determines visibility:\n * - 'internal': Trait-to-trait within same orbital (default)\n * - 'external': Exposed for cross-orbital communication\n */\nexport type EventScope = 'internal' | 'external';\n\nexport const EventScopeSchema = z.enum(['internal', 'external']);\n\n// ============================================================================\n// Event Payload Field\n// ============================================================================\n\n/**\n * Payload field definition for events.\n * Defines the structure of data carried by events.\n */\nexport interface EventPayloadField {\n /** Field name */\n name: string;\n /**\n * Field type. Any non-empty string, mirroring the Rust validator's\n * acceptance (Zod schema below uses `z.string().min(1)`). Well-known\n * values include the primitives (`string`, `number`, `boolean`,\n * `object`, `array`, `entity`), date variants (`date`, `datetime`,\n * `timestamp`), entity-name references (`User`), and array-of-entity\n * shorthand (`[User]`). Narrowing happens at the call sites that care\n * (e.g. `orbital-compiler/phases/validation/emit_payload.rs`), not at\n * the structural type level — this keeps `.orb`-emitted payloads\n * round-trippable through TypeScript without losing precision.\n */\n type: string;\n /** Whether field is required in payload */\n required?: boolean;\n /** Human-readable description */\n description?: string;\n /** For 'entity' type: the entity type name */\n entityType?: string;\n}\n\nexport const EventPayloadFieldSchema = z.object({\n name: z.string().min(1),\n /**\n * Field type. Mirrors the Rust validator's acceptance: any non-empty\n * string. Primitives ('string' | 'number' | 'boolean' | 'object' |\n * 'array') are the canonical values; entity-name references like\n * 'ModalRecord' and array-of-entity references like '[ModalRecord]'\n * are also valid because the Rust IR's PayloadField.field_type is\n * just a String. Only enforced narrowly at the call site (e.g.\n * emit-literal type-mismatch warnings in\n * orbital-compiler/phases/validation/emit_payload.rs) — not here.\n */\n type: z.string().min(1),\n required: z.boolean().optional(),\n description: z.string().optional(),\n entityType: z.string().optional(),\n});\n\n// ============================================================================\n// Trait Event Contract\n// ============================================================================\n\n/**\n * Event contract for events a trait emits.\n * Declares the event name, scope, and payload schema.\n */\nexport interface TraitEventContract {\n /** Event name (UPPER_SNAKE_CASE) */\n event: string;\n /** Human-readable description */\n description?: string;\n /** User-vocabulary synonyms (comma-separated) — the per-event analogue of a\n * field/config `@synonyms`. Feeds the curation event matcher. */\n synonyms?: string;\n /** Authoring tier (`essential`/`customization`/`advanced`/`internal`). */\n tier?: string;\n /** Payload schema — declarative type info for the event's payload.\n * Distinct from the runtime payload value (`@payload.X` bindings,\n * `EventPayload`) which is a separate concept. */\n payloadSchema?: EventPayloadField[];\n /**\n * Event scope:\n * - 'internal': Trait-to-trait within same orbital (default)\n * - 'external': Exposed for cross-orbital communication\n */\n scope?: EventScope;\n}\n\nexport const TraitEventContractSchema = z.object({\n /**\n * Event name. Mirrors the Rust validator's `is_valid_event_identifier`:\n * starts with a letter, then any letters / digits / underscores. Both\n * UPPER_SNAKE_CASE and PascalCase shapes are valid identifiers in the\n * post-Phase 2.5 nominal-event type system (events declared via\n * `type X = Event<T>`).\n */\n event: z.string().min(1).regex(\n /^[A-Za-z][A-Za-z0-9_]*$/,\n 'Event name must start with a letter and contain only letters, digits, and underscores'\n ),\n description: z.string().optional(),\n synonyms: z.string().optional(),\n tier: z.string().optional(),\n payloadSchema: z.array(EventPayloadFieldSchema).optional(),\n scope: EventScopeSchema.optional(),\n});\n\n// ============================================================================\n// Trait Event Listener\n// ============================================================================\n\n/**\n * Event listener for trait communication.\n * Guards can be legacy strings or S-expressions.\n * Enhanced with scope and payloadMapping for cross-orbital communication.\n */\n/**\n * Source-scoping for a `listens {}` entry. Determines which emitters the\n * listener responds to.\n *\n * - `{ kind: \"any\" }`: wildcard (`* EVENT -> TRIGGER`). Any trait, any orbital.\n * - `{ kind: \"trait\", trait: \"X\" }`: intra-orbital (`X EVENT -> TRIGGER`).\n * Only emits from the same orbital's trait `X`.\n * - `{ kind: \"orbital\", orbital: \"O\", trait: \"X\" }`: cross-orbital\n * (`O.X EVENT -> TRIGGER`). Only emits from orbital `O`'s trait `X`.\n *\n * Absent (undefined) means the listener is a local payload-declaration only\n * — pure type metadata, no bus subscription.\n */\nexport type ListenSource =\n | { kind: 'any' }\n | { kind: 'trait'; trait: string }\n | { kind: 'orbital'; orbital: string; trait: string };\n\nexport const ListenSourceSchema = z.union([\n z.object({ kind: z.literal('any') }),\n z.object({ kind: z.literal('trait'), trait: z.string().min(1) }),\n z.object({\n kind: z.literal('orbital'),\n orbital: z.string().min(1),\n trait: z.string().min(1),\n }),\n]);\n\nexport interface TraitEventListener {\n /** Event key to listen for (bare event name, no source prefix in the new shape) */\n event: string;\n /** State machine event to trigger */\n triggers: string;\n /** Human-readable description (authored `@description` on the listen). */\n description?: string;\n /** User-vocabulary synonyms (comma-separated). */\n synonyms?: string;\n /** Authoring tier (`essential`/`customization`/`advanced`/`internal`). */\n tier?: string;\n /** Guard expression - string (legacy) or S-expression array */\n guard?: Expression;\n /**\n * Listener scope:\n * - 'internal': Listen to events within same orbital (default)\n * - 'external': Listen to events from other orbitals\n */\n scope?: EventScope;\n /** Map event payload fields to transition payload */\n payloadMapping?: Record<string, string>;\n /**\n * Source scoping (see `ListenSource`). Undefined when the listen entry is\n * a local payload declaration rather than a bus subscription.\n */\n source?: ListenSource;\n}\n\nexport const TraitEventListenerSchema = z.object({\n event: z.string().min(1),\n triggers: z.string().min(1),\n description: z.string().optional(),\n synonyms: z.string().optional(),\n tier: z.string().optional(),\n guard: ExpressionSchema.optional(),\n scope: EventScopeSchema.optional(),\n payloadMapping: z.record(z.string()).optional(),\n source: ListenSourceSchema.optional(),\n});\n\n// ============================================================================\n// Required Field\n// ============================================================================\n\n/**\n * Field required by a trait from its linkedEntity\n */\nexport interface RequiredField {\n name: string;\n type: 'string' | 'number' | 'boolean' | 'date' | 'array' | 'object' | 'timestamp' | 'datetime' | 'enum';\n description?: string;\n}\n\nexport const RequiredFieldSchema = z.object({\n name: z.string().min(1),\n type: z.enum(['string', 'number', 'boolean', 'date', 'array', 'object', 'timestamp', 'datetime', 'enum']),\n description: z.string().optional(),\n});\n\n// ============================================================================\n// Trait Reference\n// ============================================================================\n\n/**\n * Reference to a trait from an entity or page.\n *\n * Phase F treats a trait reference as a function call: `ref` names the\n * imported trait and the sibling fields are arguments. The compiler's\n * identifier-substitution pass uses these arguments to rewrite the\n * inlined trait clone before lowering.\n */\nexport interface TraitReference {\n ref: string;\n /**\n * Phase 1.2: optional registry path disambiguator. Pairs with `ref` to\n * explicitly name which `uses` entry the alias was imported from\n * (e.g. \"std/behaviors/atoms/std-browse\"). Helpful for programmatic\n * descriptor construction and inline-phase disambiguation when multiple\n * registries expose the same alias prefix.\n */\n from?: string;\n linkedEntity?: string;\n /** Phase F: rename the inlined trait at the call site */\n name?: string;\n /** Phase F: rename atom event keys at the call site, e.g. {OPEN: \"ADD_ITEM\"} */\n events?: Record<string, string>;\n /**\n * Entity-field remap: rewrite the inlined trait's canonical `@entity.X` /\n * `@payload.row.X` field references to the consumer entity's field names,\n * e.g. `{ name: \"title\", folder: \"parentId\" }`. Mirrors `events` for\n * fields. Applied during inline substitution alongside `linkedEntity`.\n */\n fields?: Record<string, string>;\n /**\n * Call-site config overrides. Each entry is either a plain wiring value\n * (`TraitConfigValue`) or a fully-annotated re-declaration\n * (`ConfigFieldDeclaration` with `type`, optional `label`/`description`/\n * `synonyms`/`tier`). Use `isCallSiteConfigDeclaration` to discriminate.\n *\n * Plain wiring (existing callers): `config: { icon: \"star\", count: 5 }`.\n * Annotated (new): `config: { icon: { type: \"string\", default: \"star\",\n * label: \"Icon\", tier: \"presentation\" } }`.\n */\n config?: CallSiteConfig;\n appliesTo?: string[];\n /**\n * Phase F.7: replace the imported trait's `listens` array with the\n * caller-supplied list. Empty array clears all upstream listens. The\n * inliner applies this AFTER substitution, overwriting whatever the\n * upstream declared. Use sparingly: this drops external event wiring.\n */\n listens?: TraitEventListener[];\n /**\n * Phase F.7: set every emit's `scope` to the caller-supplied value.\n * `'internal'` confines emits to the orbital's internal bus; `'external'`\n * broadcasts them. Applied after substitution and listens replacement.\n */\n emitsScope?: 'internal' | 'external';\n /**\n * Phase F.8: per-transition effects override. The map's keys are event\n * names (the transition triggers, AFTER any rename via `events`). The\n * values are the SExpression effect lists that REPLACE the matching\n * transitions' `effects[]` arrays.\n *\n * This is the unified content + effect override mechanism. Whether the\n * override list contains `[\"render-ui\", ...]` (visual content),\n * `[\"fetch\", ...]` (data load), `[\"persist\", ...]` (mutation), or any\n * combination, the inliner just substitutes the whole list. Identifier\n * substitution (entity refs, event refs) still runs over the merged\n * trait body, so override effects can use either upstream or caller\n * identifiers and the F.3 walker will rewrite them consistently.\n *\n * Example:\n * ```json\n * \"effects\": {\n * \"ADD_ITEM\": [\n * [\"fetch\", \"CartItem\"],\n * [\"render-ui\", \"main\", { ... }]\n * ],\n * \"SAVE\": [\n * [\"persist\", \"create\", \"CartItem\", \"@payload.data\"]\n * ]\n * }\n * ```\n */\n effects?: Record<string, unknown[]>;\n}\n\nexport const TraitReferenceSchema = z\n .object({\n ref: z.string().min(1),\n // Phase 1.2: optional registry path disambiguator, pairs with `ref`.\n from: z.string().optional(),\n linkedEntity: z.string().optional(),\n name: z.string().optional(),\n events: z\n .record(\n z.string().min(1, \"events key (atom event name) must be non-empty\"),\n z.string().min(1, \"events value (caller event name) must be non-empty\"),\n )\n .optional(),\n fields: z\n .record(\n z.string().min(1, \"fields key (canonical field name) must be non-empty\"),\n z.string().min(1, \"fields value (consumer field name) must be non-empty\"),\n )\n .optional(),\n // Each value is either a plain wiring value (TraitConfigValue) or an\n // annotated ConfigFieldDeclaration. Declaration form is tried first\n // (it's more specific — has a `\"type\"` string key); plain values fall\n // through to the recursive TraitConfigValue union.\n config: z.record(z.union([ConfigFieldDeclarationSchema, TraitConfigValueSchema])).optional(),\n appliesTo: z.array(z.string()).optional(),\n // Phase F.7: zod accepts an array (the inliner validates element\n // shape). The full ListenDefinition shape isn't recursively encoded\n // here because TraitReference is the call-site form — listen entries\n // pasted in are already-resolved structured definitions, not nested\n // overrides.\n listens: z.array(z.unknown()).optional(),\n emitsScope: z.enum(['internal', 'external']).optional(),\n // Phase F.8: per-transition effects override. The keys are event\n // names (the transition triggers AFTER renames). Values are arrays\n // of SExpression-shaped data; the inliner validates the SExpression\n // shape during application, so the schema accepts loose `unknown[]`.\n effects: z\n .record(\n z.string().min(1, \"effects override key (event name) must be non-empty\"),\n z.array(z.unknown()),\n )\n .optional(),\n })\n .refine(\n (ref) => {\n if (!ref.events) return true;\n // Phase F.4: reject empty event-name strings on either side of\n // every entry. The substitution pass treats empty strings as\n // no-ops at runtime, but accepting them at the schema boundary\n // hides authoring errors. The per-entry .min(1) above already\n // rejects most cases; this refine is the belt-and-braces check\n // that survives any future relaxation of the inner validators.\n for (const [from, to] of Object.entries(ref.events)) {\n if (from.length === 0 || to.length === 0) return false;\n }\n return true;\n },\n {\n message:\n 'TraitReference \"events\" entries must have non-empty atom and caller event names',\n path: [\"events\"],\n },\n );\n\n/**\n * Simplified trait reference - supports string, reference object, or inline Trait definition\n * - string: \"TraitName\" - reference to a trait by name\n * - { ref: \"TraitName\" }: reference object with optional config / overrides\n * - { name: \"TraitName\", stateMachine: {...} }: inline trait definition\n *\n * Phase F adds `name` and `events` to the reference object form so callers\n * can rename the trait and remap atom event keys.\n */\nexport type TraitRef =\n | string\n | {\n ref: string;\n config?: CallSiteConfig;\n linkedEntity?: string;\n name?: string;\n events?: Record<string, string>;\n }\n | Trait;\n\n// TraitRefSchema is defined after TraitSchema (see below) to avoid forward reference\n\n// ============================================================================\n// Trait UI Binding\n// ============================================================================\n\nexport type PresentationType = 'modal' | 'drawer' | 'popover' | 'inline' | 'confirm-dialog';\n\nexport interface TraitUIBinding {\n [stateName: string]: {\n presentation: PresentationType;\n content: AnyPatternConfig | AnyPatternConfig[];\n props?: {\n size?: 'sm' | 'md' | 'lg' | 'xl' | 'full';\n position?: 'left' | 'right' | 'top' | 'bottom' | 'center';\n title?: string;\n closable?: boolean;\n width?: string;\n showProgress?: boolean;\n step?: number;\n totalSteps?: number;\n };\n };\n}\n\n// ============================================================================\n// Trait Definition\n// ============================================================================\n\n/**\n * A Trait is a reusable behavioral module with state machine.\n *\n * Traits declare their event contracts via `emits` and `listens`:\n * - `emits`: Events this trait can emit (with scope and payload schema)\n * - `listens`: Events this trait listens for (with optional payloadMapping)\n */\n/**\n * Instance vs collection scope for a trait.\n *\n * Mirrors the `.lolo` trait modifier list (`[interaction, instance]` /\n * `[interaction, collection]`). Instance traits own a single entity record\n * (typed by `linkedEntity`) and read/write `@entity.field`. Collection\n * traits render records of `linkedEntity` without owning any one; data flows\n * through `@payload.data` typed as `Array<linkedEntity>`.\n *\n * Optional today. A future phase (Almadar_Entity_V2_Plan.md Phase 4) makes\n * it required and adds static checks in the compiler.\n */\nexport type TraitScope = 'instance' | 'collection';\n\nexport const TraitScopeSchema = z.enum(['instance', 'collection']);\n\n/**\n * Inferred field contract for a `@rebindable` trait binding. `requires` =\n * entity fields the trait READS via `@entity.<field>`; `provides` = fields it\n * WRITES via `(set @entity.<field> ...)`. A consumer that rebinds the trait\n * (`linkedEntity`) must point at an entity whose fields ⊇ `requires`. Inferred\n * by the lolo lowerer from the trait's own SExpr usage; the orbital-rust L2\n * validator enforces it (`ORB_T_REBIND_MISSING_FIELDS`). Mirrors the Rust\n * `EntityFieldContract` serde shape exactly.\n */\nexport interface EntityFieldContract {\n requires: string[];\n provides: string[];\n}\n\nexport const EntityFieldContractSchema = z.object({\n requires: z.array(z.string()),\n provides: z.array(z.string()),\n});\n\nexport interface Trait {\n name: string;\n description?: string;\n description_visual_prompt?: string;\n category?: TraitCategory;\n /**\n * Opt-in marker authored as `-> @rebindable Entity` in `.lolo`. When\n * `true`, a consuming molecule/organism may rebind this trait's entity via\n * `linkedEntity`; otherwise the binding is fixed and the validator rejects\n * any rebind (`ORB_T_ENTITY_NOT_REBINDABLE`). Absent on traits that don't\n * bind an entity.\n */\n entityRebindable?: boolean;\n /**\n * Inferred field contract a rebind target must satisfy. Emitted only\n * alongside `entityRebindable: true`. See {@link EntityFieldContract}.\n */\n entityContract?: EntityFieldContract;\n /**\n * `@description \"...\"` authored on the `@rebindable` binding in `.lolo`.\n * Surfaced to catalog prose + knob-embeddings so the LLM can reach for the\n * binding from intent vocabulary (binding-discovery). Absent when unmarked.\n */\n entityBindingDescription?: string;\n /** `@synonyms \"...\"` authored on the `@rebindable` binding in `.lolo`. */\n entityBindingSynonyms?: string;\n /**\n * Author-supplied capability tags lifted from the `.lolo` trait header's\n * bracket list. Anything beyond the known scope tokens (`instance` /\n * `collection`) and the first category identifier accumulates here.\n * Free-form strings — the lolo parser does not validate them against a\n * known set. The Phase 4 translator overlay matches rules to traits by\n * exact set membership against this list. Empty when no capabilities\n * were declared. See `docs/Almadar_Domain_Language.md` Phase 3.\n */\n capabilities?: string[];\n /**\n * Instance or collection scope. Required in V2: every trait operates on\n * either a single record (`instance`) or a group (`collection`). Drives\n * payload-inference rules for emits declared via `type X = Event<T>` and\n * shapes the runtime's binding semantics. Authored in `.lolo` as the\n * `[instance]` / `[collection]` modifier on the trait header.\n */\n scope: TraitScope;\n /**\n * The entity this trait is linked to.\n * Required for inline trait definitions within an orbital.\n */\n linkedEntity?: string;\n requiredFields?: RequiredField[];\n dataEntities?: TraitDataEntity[];\n stateMachine?: StateMachine;\n initialEffects?: Effect[];\n ticks?: TraitTick[];\n /**\n * Events this trait emits.\n * Each event can be scoped as internal or external.\n * External events are namespaced at orbital level (TraitName.EVENT_NAME).\n */\n emits?: TraitEventContract[];\n /**\n * Events this trait listens for.\n * External listeners reference namespaced events (TraitName.EVENT_NAME).\n */\n listens?: TraitEventListener[];\n ui?: TraitUIBinding;\n /**\n * Declared `config { }` schema authored on the trait. Drives\n * `@config.X` substitution: each field's `default` seeds the\n * binding context behind any caller-supplied call-site\n * `config: { ... }` override.\n */\n config?: DeclaredTraitConfig;\n /**\n * Set by the resolve/inline phase when this trait was cloned from a\n * `uses[]` import. Absent for traits authored directly on the\n * orbital. Viewport-only metadata — runtime and codegen ignore it.\n * Drives Studio's L2 grouping (imported traits collapse under one\n * card per alias) and L3 drill (alias → that behavior's transitions).\n */\n sourceBehavior?: SourceBehaviorMetadata;\n /**\n * Set by the resolve/inline phase alongside `sourceBehavior`. Carries\n * the resolved `Entity` definition of the imported behavior so the\n * client-side mock-data generator can produce rows for the trait's\n * `linkedEntity` without re-walking the import graph at runtime.\n */\n sourceEntityDefinition?: Entity;\n}\n\n/**\n * Provenance attached to a trait that was cloned from a `uses[]` import\n * during the inline phase. The resolved schema carries this so Studio\n * can group L2 cards by source behavior and offer an L3 drill into the\n * import's own transitions.\n */\nexport interface SourceBehaviorMetadata {\n /** Behavior name (e.g. \"std-stat-card\") — the resolved `from:` value. */\n behavior: string;\n /** Alias used at the import site (e.g. \"Stat\"). Multiple imports of\n * the same atom group by alias, not by behavior. */\n alias: string;\n /** Original trait name inside the imported behavior, before any\n * call-site `name:` rename. */\n originalName: string;\n}\n\nexport const SourceBehaviorMetadataSchema = z.object({\n behavior: z.string().min(1),\n alias: z.string().min(1),\n originalName: z.string().min(1),\n});\n\nexport const TraitSchema = z.object({\n name: z.string().min(1),\n description: z.string().optional(),\n description_visual_prompt: z.string().optional(),\n category: TraitCategorySchema.optional(),\n entityRebindable: z.boolean().optional(),\n entityContract: EntityFieldContractSchema.optional(),\n entityBindingDescription: z.string().optional(),\n entityBindingSynonyms: z.string().optional(),\n capabilities: z.array(z.string()).optional(),\n scope: TraitScopeSchema,\n linkedEntity: z.string().optional(),\n requiredFields: z.array(RequiredFieldSchema).optional(),\n dataEntities: z.array(TraitDataEntitySchema).optional(),\n stateMachine: StateMachineSchema.optional(),\n initialEffects: z.array(EffectSchema).optional(),\n ticks: z.array(TraitTickSchema).optional(),\n emits: z.array(TraitEventContractSchema).optional(),\n listens: z.array(TraitEventListenerSchema).optional(),\n ui: z.record(z.unknown()).optional(),\n config: DeclaredTraitConfigSchema.optional(),\n sourceBehavior: SourceBehaviorMetadataSchema.optional(),\n sourceEntityDefinition: EntitySchema.optional(),\n});\n\n// TraitRefSchema defined here after TraitSchema to avoid forward reference\nexport const TraitRefSchema = z.union([\n z.string().min(1),\n z.object({\n ref: z.string().min(1),\n config: TraitConfigSchema.optional(),\n linkedEntity: z.string().optional(),\n name: z.string().optional(),\n // Phase F.4: same non-empty refine as TraitReferenceSchema.events.\n // Both schemas accept the same call-site argument shape, so the\n // validators should agree.\n events: z\n .record(\n z.string().min(1, \"events key (atom event name) must be non-empty\"),\n z.string().min(1, \"events value (caller event name) must be non-empty\"),\n )\n .optional(),\n }),\n TraitSchema, // Allow inline trait definitions\n]);\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Check if a trait ref is an inline Trait definition\n */\n/**\n * Checks if a trait reference is an inline trait definition.\n * \n * Type guard to determine if a TraitRef is an inline trait object\n * (with 'name' property) rather than a string reference or object reference.\n * \n * @param {TraitRef} traitRef - Trait reference to check\n * @returns {boolean} True if traitRef is an inline trait, false otherwise\n * \n * @example\n * isInlineTrait({ name: 'MyTrait' }); // returns true (inline)\n * isInlineTrait('MyTrait'); // returns false (string reference)\n * isInlineTrait({ ref: 'MyTrait' }); // returns false (object reference)\n */\nexport function isInlineTrait(traitRef: TraitRef): traitRef is Trait {\n return typeof traitRef === 'object' && 'name' in traitRef && !('ref' in traitRef);\n}\n\n/**\n * Extracts the trait name from a trait reference.\n * \n * Handles all trait reference formats (string, inline object, object reference)\n * and returns the canonical trait name.\n * \n * @param {TraitRef} traitRef - Trait reference to extract name from\n * @returns {string} Trait name\n * \n * @example\n * getTraitName('MyTrait'); // returns 'MyTrait'\n * getTraitName({ name: 'MyTrait' }); // returns 'MyTrait'\n * getTraitName({ ref: 'MyTrait' }); // returns 'MyTrait'\n */\nexport function getTraitName(traitRef: TraitRef): string {\n if (typeof traitRef === 'string') {\n return traitRef;\n }\n if (isInlineTrait(traitRef)) {\n return traitRef.name;\n }\n return traitRef.ref;\n}\n\n/**\n * Extracts the configuration from a trait reference.\n * \n * Returns the configuration object for trait references that support it\n * (object references with 'config' property). Returns undefined for\n * string references and inline traits.\n * \n * @param {TraitRef} traitRef - Trait reference to extract config from\n * @returns {TraitConfig | undefined} Trait configuration or undefined\n *\n * @example\n * getTraitConfig('MyTrait'); // returns undefined\n * getTraitConfig({ name: 'MyTrait' }); // returns undefined\n * getTraitConfig({ ref: 'MyTrait', config: { option: 'value' } }); // returns config object\n */\nexport function getTraitConfig(traitRef: TraitRef): CallSiteConfig | undefined {\n if (typeof traitRef === 'string') {\n return undefined;\n }\n if (isInlineTrait(traitRef)) {\n return undefined; // Inline traits don't have config\n }\n return traitRef.config;\n}\n\n/**\n * Normalizes a trait reference to object form.\n * \n * Converts any trait reference format (string, inline, object) to a\n * standardized object format with 'ref' and optional 'config' properties.\n * \n * @param {TraitRef} traitRef - Trait reference to normalize\n * @returns {{ ref: string; config?: TraitConfig }} Normalized trait reference\n *\n * @example\n * normalizeTraitRef('MyTrait'); // returns { ref: 'MyTrait' }\n * normalizeTraitRef({ name: 'MyTrait' }); // returns { ref: 'MyTrait' }\n * normalizeTraitRef({ ref: 'MyTrait', config: {...} }); // returns original\n */\nexport function normalizeTraitRef(traitRef: TraitRef): { ref: string; config?: CallSiteConfig } {\n if (typeof traitRef === 'string') {\n return { ref: traitRef };\n }\n if (isInlineTrait(traitRef)) {\n return { ref: traitRef.name };\n }\n return traitRef;\n}\n\n// ============================================================================\n// Type exports\n// ============================================================================\n\nexport type TraitInput = z.input<typeof TraitSchema>;\nexport type TraitReferenceInput = z.input<typeof TraitReferenceSchema>;\n\n// Backward compatibility aliases\nexport type OrbitalTraitRef = TraitRef;\nexport const OrbitalTraitRefSchema = TraitRefSchema;\n","/**\n * Page Types for Orbital Units\n *\n * Defines OrbitalPage type for pages within an Orbital Unit.\n *\n * IMPORTANT: Trait-driven UI architecture requires pages to have traits.\n * Static sections are NO LONGER SUPPORTED.\n *\n * @packageDocumentation\n */\n\nimport { z } from 'zod';\nimport { TraitConfigSchema, type TraitConfig } from './trait.js';\n\n// ============================================================================\n// View Type\n// ============================================================================\n\n/**\n * Page view types.\n * Note: viewType may be deprecated in favor of trait-driven UI.\n */\nexport type ViewType = 'list' | 'detail' | 'create' | 'edit' | 'dashboard' | 'custom';\n\nexport const ViewTypeSchema = z.enum([\n 'list',\n 'detail',\n 'create',\n 'edit',\n 'dashboard',\n 'custom',\n]);\n\n// ============================================================================\n// Trait Reference\n// ============================================================================\n\n/**\n * Trait reference on a page.\n */\nexport interface PageTraitRef {\n /** Trait name from library */\n ref: string;\n /** Entity this trait operates on */\n linkedEntity?: string;\n /** Additional trait configuration */\n config?: TraitConfig;\n}\n\nexport const PageTraitRefSchema = z.object({\n ref: z.string().min(1, 'Trait ref is required'),\n linkedEntity: z.string().optional(),\n config: TraitConfigSchema.optional(),\n});\n\n// ============================================================================\n// Orbital Page\n// ============================================================================\n\n/**\n * OrbitalPage - a page definition within an Orbital Unit.\n *\n * TRAIT-DRIVEN: Pages must have traits array. Sections are NOT supported.\n */\nexport interface OrbitalPage {\n /** Page name (PascalCase, e.g., \"TasksPage\") */\n name: string;\n\n /** URL path (e.g., \"/tasks\", \"/tasks/:id\") */\n path: string;\n\n /** View type (optional in trait-driven mode) */\n viewType?: ViewType;\n\n /** Page title (optional, defaults to derived from name) */\n title?: string;\n\n /** Primary entity for this page */\n primaryEntity?: string;\n\n /**\n * Traits that drive UI for this page.\n * REQUIRED in trait-driven architecture.\n */\n traits?: PageTraitRef[];\n\n /** Is this the initial page for navigation? */\n isInitial?: boolean;\n}\n\n/**\n * Strict Zod schema for trait-driven pages.\n * Rejects unknown properties like 'sections'.\n */\nexport const OrbitalPageStrictSchema = z.object({\n name: z.string().min(1, 'Page name is required'),\n path: z.string().min(1, 'Page path is required').startsWith('/', 'Path must start with /'),\n primaryEntity: z.string().min(1, 'Primary entity is required'),\n traits: z.array(PageTraitRefSchema).min(1, 'Page must have at least one trait'),\n title: z.string().optional(),\n}).strict(); // Reject unknown keys like 'sections'\n\n/**\n * Zod schema for OrbitalPage.\n * Trait-driven: pages have traits instead of static sections/patterns.\n * Uses .strict() to reject unknown keys like 'sections'.\n */\nexport const OrbitalPageSchema = z.object({\n name: z.string().min(1, 'Page name is required'),\n path: z.string().min(1, 'Page path is required').startsWith('/', 'Path must start with /'),\n viewType: ViewTypeSchema.optional(),\n title: z.string().optional(),\n primaryEntity: z.string().optional(),\n traits: z.array(PageTraitRefSchema).optional(),\n isInitial: z.boolean().optional(),\n}).strict(); // Reject unknown keys like 'sections' - use traits with render_ui effects\n\nexport type OrbitalPageInput = z.input<typeof OrbitalPageSchema>;\nexport type OrbitalPageStrictInput = z.input<typeof OrbitalPageStrictSchema>;\n\n// ============================================================================\n// Type Aliases (for cleaner imports)\n// ============================================================================\n\n/** Alias for OrbitalPage - preferred name */\nexport type Page = OrbitalPage;\n\n/** Alias for OrbitalPageSchema - preferred name */\nexport const PageSchema = OrbitalPageSchema;\n","/**\n * Domain Context Types (Self-Contained)\n *\n * Defines domain classification types for applications.\n * Copied from schema/domain-context.ts to make orbitals/ self-contained.\n *\n * @packageDocumentation\n */\n\nimport { z } from \"zod\";\n\n// ============================================================================\n// Domain Categories\n// ============================================================================\n\n/**\n * High-level domain categories\n */\nexport type DomainCategory =\n | \"healthcare\"\n | \"education\"\n | \"finance\"\n | \"ecommerce\"\n | \"real-estate\"\n | \"logistics\"\n | \"hospitality\"\n | \"hr-management\"\n | \"project-management\"\n | \"social\"\n | \"content-management\"\n | \"iot\"\n | \"analytics\"\n | \"game\"\n | \"custom\";\n\nexport const DomainCategorySchema = z.enum([\n \"healthcare\",\n \"education\",\n \"finance\",\n \"ecommerce\",\n \"real-estate\",\n \"logistics\",\n \"hospitality\",\n \"hr-management\",\n \"project-management\",\n \"social\",\n \"content-management\",\n \"iot\",\n \"analytics\",\n \"game\",\n \"custom\",\n]);\n\n// ============================================================================\n// Agent Domain Categories (simplified for LLM-based tools)\n// ============================================================================\n\n/**\n * Simplified domain categories used by the agent tools for application classification.\n * All agent tools and skill generators should derive from this constant.\n */\nexport const AGENT_DOMAIN_CATEGORIES = [\n \"game\",\n \"business\",\n \"dashboard\",\n \"form\",\n \"content\",\n \"social\",\n \"ecommerce\",\n \"workflow\",\n] as const;\n\nexport type AgentDomainCategory = (typeof AGENT_DOMAIN_CATEGORIES)[number];\n\nexport const AgentDomainCategorySchema = z.enum([...AGENT_DOMAIN_CATEGORIES]);\n\n// ============================================================================\n// Game Sub-Categories\n// ============================================================================\n\n/**\n * Game genre sub-categories\n */\nexport type GameSubCategory =\n | \"platformer\"\n | \"shooter\"\n | \"puzzle\"\n | \"rpg\"\n | \"board\"\n | \"racing\"\n | \"fighting\"\n | \"tower-defense\"\n | \"endless-runner\"\n | \"simulation\"\n | \"arcade\"\n | \"adventure\";\n\nexport const GameSubCategorySchema = z.enum([\n \"platformer\",\n \"shooter\",\n \"puzzle\",\n \"rpg\",\n \"board\",\n \"racing\",\n \"fighting\",\n \"tower-defense\",\n \"endless-runner\",\n \"simulation\",\n \"arcade\",\n \"adventure\",\n]);\n\n// ============================================================================\n// Node Classification\n// ============================================================================\n\n/**\n * Domain vs System classification\n */\nexport type NodeClassification = \"domain\" | \"system\";\n\nexport const NodeClassificationSchema = z.enum([\"domain\", \"system\"]);\n\n// ============================================================================\n// Semantic Roles\n// ============================================================================\n\nexport type StateSemanticRole =\n | \"pending\"\n | \"active\"\n | \"completed\"\n | \"cancelled\"\n | \"error\"\n | \"suspended\"\n | \"blocked\"\n | \"domain_workflow\"\n | \"domain_status\"\n | \"system_loading\"\n | \"system_error\"\n | \"system_idle\"\n | \"system_editing\"\n | \"system_confirming\";\n\nexport const StateSemanticRoleSchema = z.enum([\n \"pending\",\n \"active\",\n \"completed\",\n \"cancelled\",\n \"error\",\n \"suspended\",\n \"blocked\",\n \"domain_workflow\",\n \"domain_status\",\n \"system_loading\",\n \"system_error\",\n \"system_idle\",\n \"system_editing\",\n \"system_confirming\",\n]);\n\nexport type EventSemanticRole =\n | \"domain_action\"\n | \"domain_trigger\"\n | \"system_crud\"\n | \"system_navigation\"\n | \"system_form\"\n | \"system_ui\";\n\nexport const EventSemanticRoleSchema = z.enum([\n \"domain_action\",\n \"domain_trigger\",\n \"system_crud\",\n \"system_navigation\",\n \"system_form\",\n \"system_ui\",\n]);\n\nexport type EntitySemanticRole =\n | \"domain_core\"\n | \"domain_supporting\"\n | \"domain_reference\"\n | \"system_user\"\n | \"system_config\"\n | \"system_audit\";\n\nexport const EntitySemanticRoleSchema = z.enum([\n \"domain_core\",\n \"domain_supporting\",\n \"domain_reference\",\n \"system_user\",\n \"system_config\",\n \"system_audit\",\n]);\n\n// ============================================================================\n// Domain Vocabulary\n// ============================================================================\n\n/**\n * Domain-specific vocabulary for naming conventions.\n * Maps generic terms to domain-appropriate labels.\n */\nexport interface DomainVocabulary {\n /** Label for items (e.g., \"Task\", \"Cargo\", \"Patient\") */\n item?: string;\n /** Label for collections (e.g., \"Tasks\", \"Inventory\", \"Patients\") */\n collection?: string;\n /** Label for create action (e.g., \"Add\", \"Recruit\", \"Admit\") */\n create?: string;\n /** Label for delete action (e.g., \"Remove\", \"Discharge\", \"Archive\") */\n delete?: string;\n /** Label for container (e.g., \"List\", \"Hold\", \"Ward\") */\n container?: string;\n /** Additional custom vocabulary */\n [key: string]: string | undefined;\n}\n\nexport const DomainVocabularySchema = z\n .record(z.string(), z.string())\n .optional();\n\n// ============================================================================\n// Domain Context (Simplified for Design System)\n// ============================================================================\n\n/**\n * User persona for UX decisions\n */\nexport interface UserPersona {\n /** Persona name */\n name: string;\n /** Role for RBAC */\n role?: string;\n /** Primary device */\n device?: \"mobile\" | \"tablet\" | \"desktop\";\n}\n\nexport const UserPersonaSchema = z.object({\n name: z.string().min(1),\n role: z.string().optional(),\n device: z.enum([\"mobile\", \"tablet\", \"desktop\"]).optional(),\n});\n\n/**\n * Domain context - user request + classification\n */\nexport interface DomainContext {\n /** Original user request - verbatim (typically at schema level) */\n request: string;\n /**\n * The verbatim excerpt or summary of the user request that produced THIS orbital.\n *\n * Purpose: Traceability - know exactly what the user asked for that led to this orbital.\n *\n * Can be:\n * - Exact quote: \"...with a calendar that syncs with Google Calendar...\"\n * - Summarized: \"Calendar integration with Google Calendar sync\"\n *\n * Examples:\n * - Request: \"Build a project management app with tasks, team collaboration, and Gantt charts\"\n * - Task orbital: requestFragment: \"tasks\"\n * - Team orbital: requestFragment: \"team collaboration\"\n * - Timeline orbital: requestFragment: \"Gantt charts\"\n *\n * This enables:\n * - Understanding WHY this orbital exists\n * - Regenerating with original context preserved\n * - Validating the orbital matches user intent\n */\n requestFragment?: string;\n /** Domain category */\n category: AgentDomainCategory;\n /** Sub-domain for more specific classification */\n subDomain?: string;\n /** User personas */\n personas?: UserPersona[];\n /** Domain-specific vocabulary for naming */\n vocabulary?: DomainVocabulary;\n}\n\nexport const DomainContextSchema = z.object({\n request: z.string().min(1, \"Original request is required\"),\n requestFragment: z.string().optional(),\n category: AgentDomainCategorySchema,\n subDomain: z.string().optional(),\n personas: z.array(UserPersonaSchema).optional(),\n vocabulary: DomainVocabularySchema.optional(),\n});\n\n// ============================================================================\n// UX Hints\n// ============================================================================\n\n/**\n * UX hints for guiding UI generation.\n * These inform pattern selection and layout decisions.\n */\n/**\n * UX hints for guiding UI generation.\n * These inform pattern selection and layout decisions.\n *\n * Note: These are HINTS, not strict requirements. LLMs may use any string value\n * including 'dashboard-grid', 'none', etc. The subagent generator interprets these\n * flexibly to produce appropriate render-ui effects.\n */\nexport interface UXHints {\n /** Overall user flow pattern (e.g., 'hub-spoke', 'crud-cycle', 'linear') */\n flowPattern?: string;\n /** Pattern for displaying lists (e.g., 'entity-table', 'entity-cards', 'dashboard-grid', 'none') */\n listPattern?: string;\n /** Pattern for create/edit forms (e.g., 'modal', 'drawer', 'page', 'none') */\n formPattern?: string;\n /** Pattern for entity detail views (e.g., 'drawer', 'page', 'split', 'none') */\n detailPattern?: string;\n /** Cross-orbital navigation links */\n relatedLinks?: RelatedLink[];\n}\n\n// UX hints use flexible string types - they are guidance, not strict validation\nexport const UXHintsSchema = z.object({\n flowPattern: z.string().optional(),\n listPattern: z.string().optional(),\n formPattern: z.string().optional(),\n detailPattern: z.string().optional(),\n relatedLinks: z.array(z.lazy(() => RelatedLinkSchema)).optional(),\n});\n\n/**\n * Related link for cross-orbital navigation.\n */\nexport interface RelatedLink {\n /** Field name of the relation (e.g., \"customerId\") */\n relation: string;\n /** Button/link text (e.g., \"View Customer\") */\n label: string;\n /** Target view type */\n targetView?: \"list\" | \"detail\";\n}\n\nexport const RelatedLinkSchema = z.object({\n relation: z.string().min(1),\n label: z.string().min(1),\n targetView: z.enum([\"list\", \"detail\"]).optional(),\n});\n\n// ============================================================================\n// Suggested Guards (Pre-Generation)\n// ============================================================================\n\n/**\n * Suggested guard - natural language description for decomposition phase.\n * Generator converts these to S-expressions during generation.\n */\nexport interface SuggestedGuard {\n /** Unique identifier */\n id: string;\n /** Natural language description (e.g., \"Weight must be under 1000kg\") */\n description: string;\n /** Events this guard applies to (e.g., [\"Cargo.CREATE\", \"Cargo.UPDATE\"]) */\n appliesTo: string[];\n}\n\nexport const SuggestedGuardSchema = z.object({\n id: z.string().min(1),\n description: z.string().min(1),\n appliesTo: z.array(z.string().min(1)),\n});\n\n// ============================================================================\n// Design Preferences\n// ============================================================================\n\n/**\n * Design preferences for visual styling\n */\nexport interface DesignPreferences {\n /** Design style */\n style?: \"minimal\" | \"modern\" | \"playful\" | \"data-driven\" | \"immersive\";\n /** Primary color (hex) */\n primaryColor?: string;\n /** Target device */\n device?: \"mobile\" | \"tablet\" | \"desktop\" | \"all\";\n /** Dark mode */\n darkMode?: boolean;\n /** UX hints for pattern selection */\n uxHints?: UXHints;\n}\n\nexport const DesignPreferencesSchema = z.object({\n style: z\n .enum([\"minimal\", \"modern\", \"playful\", \"data-driven\", \"immersive\"])\n .optional(),\n primaryColor: z\n .string()\n .regex(/^#[0-9A-Fa-f]{6}$/, \"Must be valid hex color\")\n .optional(),\n device: z.enum([\"mobile\", \"tablet\", \"desktop\", \"all\"]).optional(),\n darkMode: z.boolean().optional(),\n uxHints: UXHintsSchema.optional(),\n});\n\n// ============================================================================\n// Theme Definition — Skin axes (Layer 1 visual variation, see docs/Almadar_Std_Variations.md)\n// ============================================================================\n\n/** Spacing scale entry — each step pairs with a CSS `--space-N` variable */\nexport interface SpacingScale {\n space0?: string;\n space1?: string;\n space2?: string;\n space3?: string;\n space4?: string;\n space5?: string;\n space6?: string;\n space7?: string;\n space8?: string;\n space9?: string;\n space10?: string;\n space11?: string;\n space12?: string;\n}\n\nexport const SpacingScaleSchema = z.object({\n space0: z.string().optional(),\n space1: z.string().optional(),\n space2: z.string().optional(),\n space3: z.string().optional(),\n space4: z.string().optional(),\n space5: z.string().optional(),\n space6: z.string().optional(),\n space7: z.string().optional(),\n space8: z.string().optional(),\n space9: z.string().optional(),\n space10: z.string().optional(),\n space11: z.string().optional(),\n space12: z.string().optional(),\n});\n\n/**\n * Density axis — spacing rhythm + per-element heights and paddings.\n * Determines whether a UI feels compact (Linear), cozy (default), or spacious (Notion).\n */\nexport interface DensityTokens {\n spacing?: SpacingScale;\n buttonHeightSm?: string;\n buttonHeightMd?: string;\n buttonHeightLg?: string;\n inputHeightSm?: string;\n inputHeightMd?: string;\n inputHeightLg?: string;\n rowHeightCompact?: string;\n rowHeightNormal?: string;\n rowHeightSpacious?: string;\n cardPaddingSm?: string;\n cardPaddingMd?: string;\n cardPaddingLg?: string;\n dialogPadding?: string;\n sectionGap?: string;\n}\n\nexport const DensityTokensSchema = z.object({\n spacing: SpacingScaleSchema.optional(),\n buttonHeightSm: z.string().optional(),\n buttonHeightMd: z.string().optional(),\n buttonHeightLg: z.string().optional(),\n inputHeightSm: z.string().optional(),\n inputHeightMd: z.string().optional(),\n inputHeightLg: z.string().optional(),\n rowHeightCompact: z.string().optional(),\n rowHeightNormal: z.string().optional(),\n rowHeightSpacious: z.string().optional(),\n cardPaddingSm: z.string().optional(),\n cardPaddingMd: z.string().optional(),\n cardPaddingLg: z.string().optional(),\n dialogPadding: z.string().optional(),\n sectionGap: z.string().optional(),\n});\n\n/** Single entry in the type scale — size + matching line-height */\nexport interface TypeScaleEntry {\n size: string;\n lineHeight: string;\n}\n\nexport const TypeScaleEntrySchema = z.object({\n size: z.string(),\n lineHeight: z.string(),\n});\n\n/** Type slot (which family the intent renders in) */\nexport type TypeSlot = \"display\" | \"body\" | \"mono\";\n\nexport const TypeSlotSchema = z.enum([\"display\", \"body\", \"mono\"]);\n\n/** Type size key from the scale */\nexport type TypeSizeKey =\n | \"xs\"\n | \"sm\"\n | \"base\"\n | \"lg\"\n | \"xl\"\n | \"2xl\"\n | \"3xl\"\n | \"4xl\"\n | \"display-1\"\n | \"display-2\";\n\nexport const TypeSizeKeySchema = z.enum([\n \"xs\",\n \"sm\",\n \"base\",\n \"lg\",\n \"xl\",\n \"2xl\",\n \"3xl\",\n \"4xl\",\n \"display-1\",\n \"display-2\",\n]);\n\n/** Type weight key */\nexport type TypeWeight = \"normal\" | \"medium\" | \"bold\";\n\nexport const TypeWeightSchema = z.enum([\"normal\", \"medium\", \"bold\"]);\n\n/** Intent → (slot, size, weight) mapping. Authors write intent in render-ui; skin resolves. */\nexport interface TypeIntent {\n slot: TypeSlot;\n size: TypeSizeKey;\n weight: TypeWeight;\n}\n\nexport const TypeIntentSchema = z.object({\n slot: TypeSlotSchema,\n size: TypeSizeKeySchema,\n weight: TypeWeightSchema,\n});\n\nexport interface TypeScale {\n xs?: TypeScaleEntry;\n sm?: TypeScaleEntry;\n base?: TypeScaleEntry;\n lg?: TypeScaleEntry;\n xl?: TypeScaleEntry;\n \"2xl\"?: TypeScaleEntry;\n \"3xl\"?: TypeScaleEntry;\n \"4xl\"?: TypeScaleEntry;\n \"display-1\"?: TypeScaleEntry;\n \"display-2\"?: TypeScaleEntry;\n}\n\nexport const TypeScaleSchema = z.object({\n xs: TypeScaleEntrySchema.optional(),\n sm: TypeScaleEntrySchema.optional(),\n base: TypeScaleEntrySchema.optional(),\n lg: TypeScaleEntrySchema.optional(),\n xl: TypeScaleEntrySchema.optional(),\n \"2xl\": TypeScaleEntrySchema.optional(),\n \"3xl\": TypeScaleEntrySchema.optional(),\n \"4xl\": TypeScaleEntrySchema.optional(),\n \"display-1\": TypeScaleEntrySchema.optional(),\n \"display-2\": TypeScaleEntrySchema.optional(),\n});\n\nexport interface TypeIntentMap {\n headingMajor?: TypeIntent;\n headingMinor?: TypeIntent;\n bodyEmphasis?: TypeIntent;\n bodyDefault?: TypeIntent;\n bodyQuiet?: TypeIntent;\n caption?: TypeIntent;\n numeric?: TypeIntent;\n}\n\nexport const TypeIntentMapSchema = z.object({\n headingMajor: TypeIntentSchema.optional(),\n headingMinor: TypeIntentSchema.optional(),\n bodyEmphasis: TypeIntentSchema.optional(),\n bodyDefault: TypeIntentSchema.optional(),\n bodyQuiet: TypeIntentSchema.optional(),\n caption: TypeIntentSchema.optional(),\n numeric: TypeIntentSchema.optional(),\n});\n\n/**\n * Type axis — family triplet, size scale, and intent mapping.\n * Determines whether a UI reads as editorial (serif display + sans body),\n * tech (sans + mono numeric), or dense (mono everywhere, tight leading).\n */\nexport interface TypeScaleTokens {\n displayFamily?: string;\n bodyFamily?: string;\n monoFamily?: string;\n scale?: TypeScale;\n intents?: TypeIntentMap;\n}\n\nexport const TypeScaleTokensSchema = z.object({\n displayFamily: z.string().optional(),\n bodyFamily: z.string().optional(),\n monoFamily: z.string().optional(),\n scale: TypeScaleSchema.optional(),\n intents: TypeIntentMapSchema.optional(),\n});\n\n/** Duration palette key */\nexport type MotionDurationKey =\n | \"instant\"\n | \"fast\"\n | \"normal\"\n | \"slow\"\n | \"dramatic\";\n\nexport const MotionDurationKeySchema = z.enum([\n \"instant\",\n \"fast\",\n \"normal\",\n \"slow\",\n \"dramatic\",\n]);\n\n/** Easing palette key */\nexport type MotionEasingKey = \"linear\" | \"standard\" | \"emphasized\" | \"spring\";\n\nexport const MotionEasingKeySchema = z.enum([\n \"linear\",\n \"standard\",\n \"emphasized\",\n \"spring\",\n]);\n\n/** Per-intent motion specification (duration + easing) */\nexport interface MotionIntent {\n duration: MotionDurationKey;\n easing: MotionEasingKey;\n}\n\nexport const MotionIntentSchema = z.object({\n duration: MotionDurationKeySchema,\n easing: MotionEasingKeySchema,\n});\n\nexport interface MotionDurationPalette {\n instant?: string;\n fast?: string;\n normal?: string;\n slow?: string;\n dramatic?: string;\n}\n\nexport const MotionDurationPaletteSchema = z.object({\n instant: z.string().optional(),\n fast: z.string().optional(),\n normal: z.string().optional(),\n slow: z.string().optional(),\n dramatic: z.string().optional(),\n});\n\nexport interface MotionEasingPalette {\n linear?: string;\n standard?: string;\n emphasized?: string;\n spring?: string;\n}\n\nexport const MotionEasingPaletteSchema = z.object({\n linear: z.string().optional(),\n standard: z.string().optional(),\n emphasized: z.string().optional(),\n spring: z.string().optional(),\n});\n\nexport interface MotionIntentMap {\n enter?: MotionIntent;\n exit?: MotionIntent;\n hover?: MotionIntent;\n press?: MotionIntent;\n expand?: MotionIntent;\n transition?: MotionIntent;\n}\n\nexport const MotionIntentMapSchema = z.object({\n enter: MotionIntentSchema.optional(),\n exit: MotionIntentSchema.optional(),\n hover: MotionIntentSchema.optional(),\n press: MotionIntentSchema.optional(),\n expand: MotionIntentSchema.optional(),\n transition: MotionIntentSchema.optional(),\n});\n\n/**\n * Motion axis — duration palette + easing palette + per-intent mapping.\n * Mechanical (linear, fast) vs organic (cubic-bezier, medium) vs dramatic (spring, slow).\n */\nexport interface MotionTokens {\n durations?: MotionDurationPalette;\n easings?: MotionEasingPalette;\n intents?: MotionIntentMap;\n}\n\nexport const MotionTokensSchema = z.object({\n durations: MotionDurationPaletteSchema.optional(),\n easings: MotionEasingPaletteSchema.optional(),\n intents: MotionIntentMapSchema.optional(),\n});\n\n/** Icon family selector */\nexport type IconFamily =\n | \"lucide\"\n | \"phosphor-outline\"\n | \"phosphor-fill\"\n | \"phosphor-duotone\"\n | \"tabler\"\n | \"fa-solid\";\n\nexport const IconFamilySchema = z.enum([\n \"lucide\",\n \"phosphor-outline\",\n \"phosphor-fill\",\n \"phosphor-duotone\",\n \"tabler\",\n \"fa-solid\",\n]);\n\n/**\n * Iconography axis — icon set + stroke + default size.\n * Outline (Lucide) vs filled (Phosphor-fill) vs duotone (Phosphor-duotone).\n */\nexport interface IconographyTokens {\n family?: IconFamily;\n strokeWidth?: string;\n defaultSize?: string;\n}\n\nexport const IconographyTokensSchema = z.object({\n family: IconFamilySchema.optional(),\n strokeWidth: z.string().optional(),\n defaultSize: z.string().optional(),\n});\n\n/**\n * Elevation axis — per-layer shadow mapping.\n * Each value references a `--shadow-*` token or a raw CSS shadow value.\n */\nexport interface ElevationTokens {\n cardElevation?: string;\n popoverElevation?: string;\n dialogElevation?: string;\n toastElevation?: string;\n}\n\nexport const ElevationTokensSchema = z.object({\n cardElevation: z.string().optional(),\n popoverElevation: z.string().optional(),\n dialogElevation: z.string().optional(),\n toastElevation: z.string().optional(),\n});\n\n/**\n * Geometry axis — radius rhythm + border-width rhythm with intent.\n * Sharp (radius 0) vs soft (radius 8/12) vs pill (radius full on interactive).\n */\nexport interface GeometryTokens {\n radiusContainer?: string;\n radiusInteractive?: string;\n radiusPill?: string;\n borderHairline?: string;\n borderStandard?: string;\n borderHeavy?: string;\n}\n\nexport const GeometryTokensSchema = z.object({\n radiusContainer: z.string().optional(),\n radiusInteractive: z.string().optional(),\n radiusPill: z.string().optional(),\n borderHairline: z.string().optional(),\n borderStandard: z.string().optional(),\n borderHeavy: z.string().optional(),\n});\n\n/**\n * Color axis — semantic + surface + feedback color tokens as a typed bundle.\n *\n * Replaces the free-form `colors: Record<string, string>` on `ThemeTokens` for\n * authors targeting the typed SkinSpec entrypoint. Every field maps 1:1 to a\n * `--color-*` CSS custom property emitted by themes. All fields are optional\n * so a partial slice can layer onto a default (light/dark mode pair, etc.).\n */\nexport interface ColorTokens {\n /* Brand / accent */\n primary?: string;\n primaryHover?: string;\n primaryForeground?: string;\n secondary?: string;\n secondaryHover?: string;\n secondaryForeground?: string;\n accent?: string;\n accentForeground?: string;\n muted?: string;\n mutedForeground?: string;\n\n /* Surface palette */\n background?: string;\n foreground?: string;\n card?: string;\n cardForeground?: string;\n surface?: string;\n border?: string;\n input?: string;\n ring?: string;\n\n /* Feedback */\n error?: string;\n errorForeground?: string;\n success?: string;\n successForeground?: string;\n warning?: string;\n warningForeground?: string;\n info?: string;\n infoForeground?: string;\n\n /* Optional table-specific (themes that ship them; default to neutrals) */\n tableHeader?: string;\n tableBorder?: string;\n tableRowHover?: string;\n surfaceHover?: string;\n borderHover?: string;\n placeholder?: string;\n}\n\nexport const ColorTokensSchema = z.object({\n primary: z.string().optional(),\n primaryHover: z.string().optional(),\n primaryForeground: z.string().optional(),\n secondary: z.string().optional(),\n secondaryHover: z.string().optional(),\n secondaryForeground: z.string().optional(),\n accent: z.string().optional(),\n accentForeground: z.string().optional(),\n muted: z.string().optional(),\n mutedForeground: z.string().optional(),\n background: z.string().optional(),\n foreground: z.string().optional(),\n card: z.string().optional(),\n cardForeground: z.string().optional(),\n surface: z.string().optional(),\n border: z.string().optional(),\n input: z.string().optional(),\n ring: z.string().optional(),\n error: z.string().optional(),\n errorForeground: z.string().optional(),\n success: z.string().optional(),\n successForeground: z.string().optional(),\n warning: z.string().optional(),\n warningForeground: z.string().optional(),\n info: z.string().optional(),\n infoForeground: z.string().optional(),\n tableHeader: z.string().optional(),\n tableBorder: z.string().optional(),\n tableRowHover: z.string().optional(),\n surfaceHover: z.string().optional(),\n borderHover: z.string().optional(),\n placeholder: z.string().optional(),\n});\n\n/**\n * Illustration style preset for empty/loading/error/onboarding states.\n *\n * - `minimal`: icon + short text, no imagery (current default)\n * - `illustrated`: svg illustration library (undraw-style)\n * - `photo`: stock photography\n * - `text-only`: clean text, no imagery\n * - `mascot`: branded character (Mailchimp-style)\n */\nexport type IllustrationStyle =\n | \"minimal\"\n | \"illustrated\"\n | \"photo\"\n | \"text-only\"\n | \"mascot\";\n\nexport const IllustrationStyleSchema = z.enum([\n \"minimal\",\n \"illustrated\",\n \"photo\",\n \"text-only\",\n \"mascot\",\n]);\n\n/**\n * Illustration axis — empty/loading/error/onboarding imagery style.\n * `style` selects the preset; the per-state `*Asset` fields are optional\n * overrides for skins that want to ship custom artwork.\n */\nexport interface IllustrationTokens {\n style?: IllustrationStyle;\n emptyAsset?: string;\n loadingAsset?: string;\n errorAsset?: string;\n onboardingAsset?: string;\n}\n\nexport const IllustrationTokensSchema = z.object({\n style: IllustrationStyleSchema.optional(),\n emptyAsset: z.string().optional(),\n loadingAsset: z.string().optional(),\n errorAsset: z.string().optional(),\n onboardingAsset: z.string().optional(),\n});\n\n/**\n * Theme tokens - CSS custom properties for design system.\n *\n * Layer 1 visual variation (see docs/Almadar_Std_Variations.md): the original\n * `colors`/`radii`/`spacing`/`typography`/`shadows` Record fields are kept for\n * backward compatibility. The new typed axes (`density`, `typeScale`, `motion`,\n * `iconography`, `elevation`, `geometry`) carry the structured token surface\n * that lets two themes feel like different products, not just different paint.\n */\nexport interface ThemeTokens {\n /**\n * Color axis — typed semantic + surface + feedback colors.\n * Replaces the free-form `colors` Record below for new authors.\n */\n color?: ColorTokens;\n /** Density axis — spacing rhythm, per-element heights and paddings */\n density?: DensityTokens;\n /** Type axis — family triplet, scale, intent mapping */\n typeScale?: TypeScaleTokens;\n /** Motion axis — duration palette, easing palette, intent mapping */\n motion?: MotionTokens;\n /** Iconography axis — icon family, stroke, default size */\n iconography?: IconographyTokens;\n /** Elevation axis — per-layer shadow mapping */\n elevation?: ElevationTokens;\n /** Geometry axis — radius rhythm, border-width rhythm with intent */\n geometry?: GeometryTokens;\n /** Illustration axis — empty/loading/error state imagery style */\n illustration?: IllustrationTokens;\n\n // ── Legacy free-form maps (pre-Layer-1). Kept for back-compat with\n // older callers that emit raw `--color-*` / `--radius-*` etc. as\n // string maps. New authors should use the typed axes above.\n /** @deprecated Use `color` (typed). */\n colors?: Record<string, string>;\n /** @deprecated Use `geometry.radius*` and theme CSS for full radius scale. */\n radii?: Record<string, string>;\n /** @deprecated Use `density.spacing` (typed scale). */\n spacing?: Record<string, string>;\n /** @deprecated Use `typeScale` (typed family + scale + intents). */\n typography?: Record<string, string>;\n /** @deprecated Use `elevation` (typed per-layer mapping). */\n shadows?: Record<string, string>;\n}\n\nexport const ThemeTokensSchema = z.object({\n color: ColorTokensSchema.optional(),\n density: DensityTokensSchema.optional(),\n typeScale: TypeScaleTokensSchema.optional(),\n motion: MotionTokensSchema.optional(),\n iconography: IconographyTokensSchema.optional(),\n elevation: ElevationTokensSchema.optional(),\n geometry: GeometryTokensSchema.optional(),\n illustration: IllustrationTokensSchema.optional(),\n // Legacy\n colors: z.record(z.string(), z.string()).optional(),\n radii: z.record(z.string(), z.string()).optional(),\n spacing: z.record(z.string(), z.string()).optional(),\n typography: z.record(z.string(), z.string()).optional(),\n shadows: z.record(z.string(), z.string()).optional(),\n});\n\n/**\n * Theme variant - overrides for a specific mode (e.g., dark mode).\n * Mirrors ThemeTokens fields with the same backward-compat + new-axis structure.\n */\nexport interface ThemeVariant {\n /** Color axis overrides */\n color?: ColorTokens;\n /** Density axis overrides */\n density?: DensityTokens;\n /** Type axis overrides */\n typeScale?: TypeScaleTokens;\n /** Motion axis overrides */\n motion?: MotionTokens;\n /** Iconography axis overrides */\n iconography?: IconographyTokens;\n /** Elevation axis overrides */\n elevation?: ElevationTokens;\n /** Geometry axis overrides */\n geometry?: GeometryTokens;\n /** Illustration axis overrides */\n illustration?: IllustrationTokens;\n\n // ── Legacy free-form maps (pre-Layer-1). See ThemeTokens for guidance.\n /** @deprecated Use `color`. */\n colors?: Record<string, string>;\n /** @deprecated */\n radii?: Record<string, string>;\n /** @deprecated */\n spacing?: Record<string, string>;\n /** @deprecated */\n typography?: Record<string, string>;\n /** @deprecated */\n shadows?: Record<string, string>;\n}\n\nexport const ThemeVariantSchema = z.object({\n color: ColorTokensSchema.optional(),\n density: DensityTokensSchema.optional(),\n typeScale: TypeScaleTokensSchema.optional(),\n motion: MotionTokensSchema.optional(),\n iconography: IconographyTokensSchema.optional(),\n elevation: ElevationTokensSchema.optional(),\n geometry: GeometryTokensSchema.optional(),\n illustration: IllustrationTokensSchema.optional(),\n colors: z.record(z.string(), z.string()).optional(),\n radii: z.record(z.string(), z.string()).optional(),\n spacing: z.record(z.string(), z.string()).optional(),\n typography: z.record(z.string(), z.string()).optional(),\n shadows: z.record(z.string(), z.string()).optional(),\n});\n\n/**\n * Theme definition - design system for an orbital.\n */\nexport interface ThemeDefinition {\n /** Theme name */\n name: string;\n /** Base tokens */\n tokens: ThemeTokens;\n /** Named variants (e.g., \"dark\", \"high-contrast\") */\n variants?: Record<string, ThemeVariant>;\n}\n\nexport const ThemeDefinitionSchema = z.object({\n name: z.string().min(1, \"Theme name is required\"),\n tokens: ThemeTokensSchema,\n variants: z.record(z.string(), ThemeVariantSchema).optional(),\n});\n\n/**\n * ThemeRef - Theme can be inline definition OR reference to imported theme.\n *\n * Reference format: \"Alias.theme\"\n */\nexport type ThemeRef = ThemeDefinition | string;\n\n/**\n * Checks if a theme reference is a string.\n * \n * Type guard to determine if a theme reference is a string reference\n * (format: \"Alias.theme\") rather than an inline theme definition.\n * \n * @param {ThemeRef} theme - Theme reference to check\n * @returns {boolean} True if theme is a string reference, false otherwise\n * \n * @example\n * isThemeReference(\"Ocean.theme\"); // returns true\n * isThemeReference({ name: \"ocean\", colors: {...} }); // returns false\n */\nexport function isThemeReference(theme: ThemeRef): theme is string {\n return typeof theme === \"string\";\n}\n\n/**\n * Validate theme reference format: \"Alias.theme\"\n */\nexport const ThemeRefStringSchema = z\n .string()\n .regex(\n /^[A-Z][a-zA-Z0-9]*\\.theme$/,\n 'Theme reference must be in format \"Alias.theme\" (e.g., \"Ocean.theme\")',\n );\n\nexport const ThemeRefSchema = z.union([\n ThemeDefinitionSchema,\n ThemeRefStringSchema,\n]);\n\n// ============================================================================\n// SkinSpec — Layer 1 visual variation vocabulary (docs/Almadar_Std_Variations.md §2.3)\n// ============================================================================\n\n/**\n * `SkinSpec` is an alias for `ThemeDefinition` — same object, doc-aligned\n * name. The doc refers to a complete eight-axis visual identity as a\n * \"SkinSpec\"; in the type system it's a `ThemeDefinition` whose `tokens`\n * field carries the eight typed slices (`color`, `density`, `typeScale`,\n * `geometry`, `elevation`, `motion`, `iconography`, `illustration`).\n *\n * There is no separate type — this alias prevents the two surfaces from\n * drifting.\n */\nexport type SkinSpec = ThemeDefinition;\nexport const SkinSpecSchema = ThemeDefinitionSchema;\n\n/**\n * Slice-name aliases — the doc and `_contract.md` refer to each axis as\n * `<Name>Slice`. The existing types use `<Name>Tokens`. These aliases let\n * skin authors write the doc's vocabulary while pointing at the single\n * canonical type definition. No forks.\n */\nexport type ColorSlice = ColorTokens;\nexport type DensitySlice = DensityTokens;\nexport type TypeSlice = TypeScaleTokens;\nexport type GeometrySlice = GeometryTokens;\nexport type ElevationSlice = ElevationTokens;\nexport type MotionSlice = MotionTokens;\nexport type IconographySlice = IconographyTokens;\nexport type IllustrationSlice = IllustrationTokens;\n\nexport const ColorSliceSchema = ColorTokensSchema;\nexport const DensitySliceSchema = DensityTokensSchema;\nexport const TypeSliceSchema = TypeScaleTokensSchema;\nexport const GeometrySliceSchema = GeometryTokensSchema;\nexport const ElevationSliceSchema = ElevationTokensSchema;\nexport const MotionSliceSchema = MotionTokensSchema;\nexport const IconographySliceSchema = IconographyTokensSchema;\nexport const IllustrationSliceSchema = IllustrationTokensSchema;\n\n// ============================================================================\n// Design Tokens (Legacy)\n// ============================================================================\n\n/**\n * Design tokens - reusable Tailwind class collections.\n * @deprecated Use ThemeDefinition instead for new code.\n *\n * Instead of repeating raw Tailwind classes everywhere, define once and reference by name.\n * Example: `token: \"surfaces.glass\"` resolves to the Tailwind classes defined here.\n */\nexport interface DesignTokens {\n /** Surface styles: backgrounds, borders, shadows */\n surfaces?: Record<string, string>;\n /** Text styles: typography, colors */\n text?: Record<string, string>;\n /** Interactive element styles: buttons, links */\n interactive?: Record<string, string>;\n /** Effect styles: shadows, animations, transitions */\n effects?: Record<string, string>;\n /** Additional custom categories */\n [category: string]: Record<string, string> | undefined;\n}\n\nexport const DesignTokensSchema = z\n .record(z.string(), z.record(z.string(), z.string()))\n .optional();\n\n// ============================================================================\n// Custom Pattern Definitions\n// ============================================================================\n\n/**\n * Allowed HTML elements for custom patterns.\n * These are safe, semantic elements for building custom UIs.\n */\nexport const ALLOWED_CUSTOM_COMPONENTS = [\n \"div\",\n \"span\",\n \"button\",\n \"a\",\n \"p\",\n \"h1\",\n \"h2\",\n \"h3\",\n \"h4\",\n \"h5\",\n \"h6\",\n \"header\",\n \"footer\",\n \"section\",\n \"article\",\n \"nav\",\n \"main\",\n \"aside\",\n \"ul\",\n \"ol\",\n \"li\",\n \"img\",\n \"label\",\n \"input\",\n \"form\",\n] as const;\n\nexport type AllowedCustomComponent = (typeof ALLOWED_CUSTOM_COMPONENTS)[number];\n\n/**\n * Custom pattern definition for app-specific reusable patterns.\n *\n * Register custom designs that can be referenced by name throughout the schema.\n */\nexport interface CustomPatternDefinition {\n /** Always 'custom' for custom patterns */\n type: \"custom\";\n /** HTML element to render */\n component: AllowedCustomComponent;\n /** Base Tailwind classes (can include {prop} placeholders) */\n className: string;\n /** Named content slots for nested content */\n slots?: string[];\n /** Configurable props that can be passed when using the pattern */\n props?: string[];\n}\n\nexport const CustomPatternDefinitionSchema = z.object({\n type: z.literal(\"custom\"),\n component: z.enum(ALLOWED_CUSTOM_COMPONENTS),\n className: z.string(),\n slots: z.array(z.string()).optional(),\n props: z.array(z.string()).optional(),\n});\n\n/**\n * Map of custom pattern names to their definitions.\n */\nexport type CustomPatternMap = Record<string, CustomPatternDefinition>;\n\nexport const CustomPatternMapSchema = z\n .record(z.string(), CustomPatternDefinitionSchema)\n .optional();\n\n// ============================================================================\n// Type exports\n// ============================================================================\n\nexport type DomainContextInput = z.input<typeof DomainContextSchema>;\nexport type DesignPreferencesInput = z.input<typeof DesignPreferencesSchema>;\nexport type UserPersonaInput = z.input<typeof UserPersonaSchema>;\nexport type DesignTokensInput = z.input<typeof DesignTokensSchema>;\nexport type CustomPatternDefinitionInput = z.input<\n typeof CustomPatternDefinitionSchema\n>;\nexport type CustomPatternMapInput = z.input<typeof CustomPatternMapSchema>;\n","/**\n * Service Types for Orbital Schema\n *\n * Defines external service integrations (REST APIs, WebSockets, MCP servers)\n * that can be used by orbital units via the `call_service` effect.\n *\n * @packageDocumentation\n */\n\nimport { z } from \"zod\";\n\n// ============================================================================\n// Service Type Enum\n// ============================================================================\n\n/**\n * Types of external services that can be integrated.\n */\nexport const SERVICE_TYPES = [\"rest\", \"socket\", \"mcp\"] as const;\n\nexport type ServiceType = (typeof SERVICE_TYPES)[number];\n\nexport const ServiceTypeSchema = z.enum(SERVICE_TYPES);\n\n// ============================================================================\n// REST Service Definition\n// ============================================================================\n\n/**\n * Configuration for a REST API service.\n *\n * @example\n * ```typescript\n * const weatherService: RestServiceDef = {\n * name: 'WeatherAPI',\n * type: 'rest',\n * baseUrl: 'https://api.openweathermap.org/data/2.5',\n * headers: {\n * 'Content-Type': 'application/json',\n * },\n * auth: {\n * type: 'api-key',\n * keyName: 'appid',\n * location: 'query',\n * },\n * };\n * ```\n */\nexport interface RestServiceDef {\n /** Unique service name (used in call_service effect) */\n name: string;\n\n /** Service type */\n type: \"rest\";\n\n /** Optional description */\n description?: string;\n\n /** Base URL for the API */\n baseUrl: string;\n\n /** Default headers to include in all requests */\n headers?: Record<string, string>;\n\n /** Authentication configuration */\n auth?: RestAuthConfig;\n\n /** Timeout in milliseconds (default: 30000) */\n timeout?: number;\n}\n\n/**\n * Authentication configuration for REST services.\n */\nexport interface RestAuthConfig {\n /** Authentication type */\n type: \"api-key\" | \"bearer\" | \"basic\" | \"oauth2\";\n\n /** For api-key: the query parameter or header name */\n keyName?: string;\n\n /** For api-key: where to place the key */\n location?: \"query\" | \"header\";\n\n /** Environment variable name containing the secret (for secure storage) */\n secretEnv?: string;\n}\n\nexport const RestAuthConfigSchema = z.object({\n type: z.enum([\"api-key\", \"bearer\", \"basic\", \"oauth2\"]),\n keyName: z.string().optional(),\n location: z.enum([\"query\", \"header\"]).optional(),\n secretEnv: z.string().optional(),\n});\n\nexport const RestServiceDefSchema = z.object({\n name: z.string().min(1, \"Service name is required\"),\n type: z.literal(\"rest\"),\n description: z.string().optional(),\n baseUrl: z.string().url(\"Base URL must be a valid URL\"),\n headers: z.record(z.string()).optional(),\n auth: RestAuthConfigSchema.optional(),\n timeout: z.number().positive().optional(),\n});\n\n// ============================================================================\n// Socket Service Definition\n// ============================================================================\n\n/**\n * Configuration for a WebSocket service.\n *\n * @example\n * ```typescript\n * const chatService: SocketServiceDef = {\n * name: 'ChatSocket',\n * type: 'socket',\n * url: 'wss://chat.example.com',\n * events: {\n * inbound: ['message_received', 'user_joined', 'user_left'],\n * outbound: ['send_message', 'join_room', 'leave_room'],\n * },\n * };\n * ```\n */\nexport interface SocketServiceDef {\n /** Unique service name */\n name: string;\n\n /** Service type */\n type: \"socket\";\n\n /** Optional description */\n description?: string;\n\n /** WebSocket URL */\n url: string;\n\n /** Event definitions */\n events: SocketEvents;\n\n /** Reconnection configuration */\n reconnect?: {\n /** Enable automatic reconnection */\n enabled: boolean;\n /** Maximum reconnection attempts */\n maxAttempts?: number;\n /** Delay between attempts in ms */\n delayMs?: number;\n };\n}\n\n/**\n * Socket event definitions.\n */\nexport interface SocketEvents {\n /** Events received from server (maps to orbital events) */\n inbound: string[];\n\n /** Events sent to server (triggered by effects) */\n outbound: string[];\n}\n\nexport const SocketEventsSchema = z.object({\n inbound: z.array(z.string()),\n outbound: z.array(z.string()),\n});\n\nexport const SocketServiceDefSchema = z.object({\n name: z.string().min(1, \"Service name is required\"),\n type: z.literal(\"socket\"),\n description: z.string().optional(),\n url: z.string().url(\"WebSocket URL must be valid\"),\n events: SocketEventsSchema,\n reconnect: z\n .object({\n enabled: z.boolean(),\n maxAttempts: z.number().positive().optional(),\n delayMs: z.number().positive().optional(),\n })\n .optional(),\n});\n\n// ============================================================================\n// MCP Service Definition\n// ============================================================================\n\n/**\n * Configuration for an MCP (Model Context Protocol) server.\n *\n * @example\n * ```typescript\n * const mcpService: McpServiceDef = {\n * name: 'DatabaseMCP',\n * type: 'mcp',\n * serverPath: './mcp-servers/database',\n * capabilities: ['query', 'insert', 'update'],\n * };\n * ```\n */\nexport interface McpServiceDef {\n /** Unique service name */\n name: string;\n\n /** Service type */\n type: \"mcp\";\n\n /** Optional description */\n description?: string;\n\n /** Path to MCP server executable or module */\n serverPath: string;\n\n /** List of capabilities/tools exposed by the MCP server */\n capabilities: string[];\n\n /** Environment variables to pass to the MCP server */\n env?: Record<string, string>;\n}\n\nexport const McpServiceDefSchema = z.object({\n name: z.string().min(1, \"Service name is required\"),\n type: z.literal(\"mcp\"),\n description: z.string().optional(),\n serverPath: z.string().min(1, \"Server path is required\"),\n capabilities: z\n .array(z.string())\n .min(1, \"At least one capability is required\"),\n env: z.record(z.string()).optional(),\n});\n\n// ============================================================================\n// Union Type: ServiceDefinition\n// ============================================================================\n\n/**\n * Union type for all service definitions.\n */\nexport type ServiceDefinition =\n | RestServiceDef\n | SocketServiceDef\n | McpServiceDef;\n\nexport const ServiceDefinitionSchema = z.discriminatedUnion(\"type\", [\n RestServiceDefSchema,\n SocketServiceDefSchema,\n McpServiceDefSchema,\n]);\n\n// ============================================================================\n// Service Reference (Inline OR Reference)\n// ============================================================================\n\n/**\n * ServiceRef - Service can be inline definition, reference object with overrides,\n * or bare string reference to an imported service.\n *\n * Reference format: \"Alias.services.ServiceName\"\n */\nexport type ServiceRef = ServiceDefinition | ServiceRefObject | string;\n\n/**\n * Phase F: Service reference object with override fields.\n *\n * Mirrors the Rust `ServiceRefObject` at\n * `orbital-rust/crates/orbital-core/src/schema/types.rs:353-375`. A caller\n * imports a service via `uses[]`, references it by `ref`, and supplies\n * any subset of these fields to override the imported service's defaults\n * during inlining.\n *\n * @example\n * ```typescript\n * const ref: ServiceRefObject = {\n * ref: \"Weather.services.openweather\",\n * baseUrl: \"https://staging.weather.example.com\",\n * headers: { \"X-Tenant\": \"acme\" },\n * };\n * ```\n */\nexport interface ServiceRefObject {\n /** Reference to imported service: \"Alias.services.ServiceName\" */\n ref: string;\n /** Override the service description */\n description?: string;\n /** Override the REST baseUrl */\n baseUrl?: string;\n /** Override or merge default headers (caller wins on key collision) */\n headers?: Record<string, string>;\n /** Override the WebSocket url */\n url?: string;\n /** Override the MCP server path */\n serverPath?: string;\n}\n\n/**\n * Checks if a service reference is a bare string reference.\n *\n * Type guard to determine if a service reference is a string reference\n * (format: \"Alias.services.ServiceName\") rather than an inline service\n * definition or a reference object.\n *\n * @param {ServiceRef} service - Service reference to check\n * @returns {boolean} True if service is a string reference, false otherwise\n *\n * @example\n * isServiceReference(\"Weather.services.openweather\"); // returns true\n * isServiceReference({ name: \"weather\", type: \"rest\" }); // returns false\n * isServiceReference({ ref: \"Weather.services.openweather\" }); // returns false\n */\nexport function isServiceReference(service: ServiceRef): service is string {\n return typeof service === \"string\";\n}\n\n/**\n * Phase F: Type guard for `ServiceRefObject` (the override-carrying form).\n *\n * @param {ServiceRef} service - Service reference to check\n * @returns {boolean} True if service is a ServiceRefObject\n */\nexport function isServiceReferenceObject(\n service: ServiceRef,\n): service is ServiceRefObject {\n return (\n typeof service === \"object\" &&\n service !== null &&\n \"ref\" in service &&\n !(\"type\" in service)\n );\n}\n\n/**\n * Validate service reference format: \"Alias.services.ServiceName\"\n */\nexport const ServiceRefStringSchema = z\n .string()\n .regex(\n /^[A-Z][a-zA-Z0-9]*\\.services\\.[a-zA-Z][a-zA-Z0-9]*$/,\n 'Service reference must be in format \"Alias.services.ServiceName\" (e.g., \"Weather.services.openweather\")',\n );\n\nexport const ServiceRefObjectSchema = z.object({\n ref: ServiceRefStringSchema,\n description: z.string().optional(),\n baseUrl: z.string().url(\"baseUrl override must be a valid URL\").optional(),\n headers: z.record(z.string()).optional(),\n url: z.string().url(\"url override must be a valid URL\").optional(),\n serverPath: z.string().optional(),\n});\n\nexport const ServiceRefSchema = z.union([\n ServiceDefinitionSchema,\n ServiceRefObjectSchema,\n ServiceRefStringSchema,\n]);\n\n/**\n * Parses a service reference into its components.\n * \n * Extracts the alias and service name from a service reference string\n * in format \"Alias.services.ServiceName\". Returns null if not a valid reference.\n * \n * @param {string} ref - Service reference string\n * @returns {{ alias: string; serviceName: string } | null} Parsed components or null\n * \n * @example\n * parseServiceRef(\"Weather.services.openweather\"); // returns { alias: \"Weather\", serviceName: \"openweather\" }\n * parseServiceRef(\"invalid\"); // returns null\n */\nexport function parseServiceRef(\n ref: string,\n): { alias: string; serviceName: string } | null {\n const match = ref.match(\n /^([A-Z][a-zA-Z0-9]*)\\.services\\.([a-zA-Z][a-zA-Z0-9]*)$/,\n );\n if (!match) return null;\n return { alias: match[1], serviceName: match[2] };\n}\n\n// ============================================================================\n// Utility Functions\n// ============================================================================\n\n/**\n * Checks if a service definition is a REST service.\n * \n * Type guard to determine if a service definition represents a REST API service.\n * Used for service type discrimination and validation.\n * \n * @param {ServiceDefinition} service - Service definition to check\n * @returns {boolean} True if service is a REST service, false otherwise\n * \n * @example\n * isRestService({ name: \"weather\", type: \"rest\", baseUrl: \"...\" }); // returns true\n * isRestService({ name: \"chat\", type: \"socket\" }); // returns false\n */\nexport function isRestService(\n service: ServiceDefinition,\n): service is RestServiceDef {\n return service.type === \"rest\";\n}\n\n/**\n * Checks if a service definition is a Socket service.\n * \n * Type guard to determine if a service definition represents a WebSocket service.\n * Used for service type discrimination and validation.\n * \n * @param {ServiceDefinition} service - Service definition to check\n * @returns {boolean} True if service is a Socket service, false otherwise\n * \n * @example\n * isSocketService({ name: \"chat\", type: \"socket\", url: \"wss://...\" }); // returns true\n * isSocketService({ name: \"weather\", type: \"rest\" }); // returns false\n */\nexport function isSocketService(\n service: ServiceDefinition,\n): service is SocketServiceDef {\n return service.type === \"socket\";\n}\n\n/**\n * Checks if a service definition is an MCP service.\n * \n * Type guard to determine if a service definition represents an MCP\n * (Multiplayer Control Protocol) service. Used for service type discrimination.\n * \n * @param {ServiceDefinition} service - Service definition to check\n * @returns {boolean} True if service is an MCP service, false otherwise\n * \n * @example\n * isMcpService({ name: \"game\", type: \"mcp\", serverUrl: \"...\" }); // returns true\n * isMcpService({ name: \"chat\", type: \"socket\" }); // returns false\n */\nexport function isMcpService(\n service: ServiceDefinition,\n): service is McpServiceDef {\n return service.type === \"mcp\";\n}\n\n/**\n * Get all service names from a list of services.\n */\nexport function getServiceNames(services: ServiceDefinition[]): string[] {\n return services.map((s) => s.name);\n}\n\n/**\n * Find a service by name.\n */\nexport function findService(\n services: ServiceDefinition[],\n name: string,\n): ServiceDefinition | undefined {\n return services.find((s) => s.name.toLowerCase() === name.toLowerCase());\n}\n\n/**\n * Check if a service name exists (case-insensitive).\n */\nexport function hasService(\n services: ServiceDefinition[],\n name: string,\n): boolean {\n return services.some((s) => s.name.toLowerCase() === name.toLowerCase());\n}\n\n/**\n * Allowed leaf value for `ServiceParams`. Mirrors `EventPayloadValue`'s\n * recursive-array shape so integration call signatures can express the\n * nested structures real services need (port mappings, volume mounts,\n * pagination cursors), and so a value satisfying `EventPayloadValue`\n * also satisfies `ServiceParamsValue` without a cast — the same data\n * flows through `call-service` and `emit` without boundary widening.\n */\nexport type ServiceParamsValue =\n | string\n | number\n | boolean\n | Date\n | null\n | undefined\n | ServiceParams\n | readonly ServiceParamsValue[];\n\n/** Parameters passed to call-service effects. Recursive for nested request shapes. */\nexport interface ServiceParams {\n [key: string]: ServiceParamsValue;\n}\n","/**\n * Orbital Type (Self-Contained)\n *\n * Defines the Orbital - the atomic building block of applications.\n * Formula: Orbital = Entity × Traits × Pages\n *\n * An Orbital is a module that exports { entity, traits, pages }.\n * Use `uses` to import other Orbitals and access their components via:\n * - Alias.entity\n * - Alias.traits.TraitName\n * - Alias.pages.PageName\n *\n * @packageDocumentation\n */\n\nimport { z } from \"zod\";\nimport type { Entity, EntityPersistence } from \"./entity.js\";\nimport { EntitySchema, EntityPersistenceSchema } from \"./entity.js\";\nimport type { EntityField } from \"./field.js\";\nimport { EntityFieldSchema } from \"./field.js\";\nimport type { Page } from \"./page.js\";\nimport { PageSchema } from \"./page.js\";\nimport type {\n TraitRef,\n EventPayloadField,\n EventScope,\n Trait,\n} from \"./trait.js\";\nimport {\n TraitRefSchema,\n EventPayloadFieldSchema,\n EventScopeSchema,\n TraitSchema,\n} from \"./trait.js\";\nimport type {\n DomainContext,\n DesignPreferences,\n SuggestedGuard,\n ThemeRef,\n} from \"./domain.js\";\nimport {\n DomainContextSchema,\n DesignPreferencesSchema,\n SuggestedGuardSchema,\n ThemeRefSchema,\n} from \"./domain.js\";\nimport type { ServiceRef } from \"./service.js\";\nimport { ServiceRefSchema } from \"./service.js\";\nimport type { Expression } from \"./expression.js\";\nimport { ExpressionSchema } from \"./expression.js\";\n\n// ============================================================================\n// Use Declaration (Import System)\n// ============================================================================\n\n/**\n * UseDeclaration - Import an external Orbital as a namespace.\n *\n * After importing, access components via:\n * - Alias.entity - The entity definition\n * - Alias.traits.TraitName - A specific trait\n * - Alias.pages.PageName - A specific page\n *\n * @example\n * ```json\n * {\n * \"uses\": [\n * { \"from\": \"./health.orb\", \"as\": \"Health\" },\n * { \"from\": \"std/behaviors/game-core\", \"as\": \"GameCore\" }\n * ]\n * }\n * ```\n */\nexport interface UseDeclaration {\n /**\n * Import source path:\n * - \"std/behaviors/game-core\" - Standard library\n * - \"./shared/health.orb\" - Local .orb file (relative path)\n * - \"../common/physics.orb\" - Parent directory .orb file\n * - \"@game-lib/enemies.orb\" - Scoped package (configured base)\n */\n from: string;\n\n /**\n * Alias for accessing imported components.\n * Used as namespace: Alias.entity, Alias.traits.X, Alias.pages.X\n */\n as: string;\n}\n\nexport const UseDeclarationSchema = z.object({\n from: z.string().min(1, \"Import source is required\"),\n as: z\n .string()\n .min(1, \"Alias is required\")\n .regex(\n /^[A-Z][a-zA-Z0-9]*$/,\n 'Alias must be PascalCase (e.g., \"Health\", \"GameCore\")',\n ),\n});\n\n// ============================================================================\n// Entity Reference (Inline OR Reference)\n// ============================================================================\n\n/**\n * EntityCall - Reference to an imported entity with optional override arguments.\n *\n * Treats the imported entity as a callable function: the atom's declared\n * fields are defaults and the caller can append extra fields, rename, or\n * override persistence/collection. The discriminator key is `extends` to\n * stay consistent with the Phase A.5 Rust schema (`EntityRef::Extends`).\n *\n * @example\n * ```json\n * // Inherit ModalRecord's fields, rename to CartItem, add pendingId\n * {\n * \"extends\": \"Modal.entity\",\n * \"name\": \"CartItem\",\n * \"fields\": [{ \"name\": \"pendingId\", \"type\": \"string\" }]\n * }\n * ```\n */\nexport interface EntityCall {\n /** Reference to the imported entity using the \"extends\" discriminator key */\n extends: string;\n /** Optional rename for the resulting entity */\n name?: string;\n /** Additional fields appended to the inherited set (caller wins on name collision) */\n fields?: EntityField[];\n /** Optional persistence override */\n persistence?: EntityPersistence;\n /** Optional collection override */\n collection?: string;\n}\n\n/**\n * EntityRef - Entity can be inline definition OR reference to imported entity.\n *\n * Reference formats:\n * - Simple string: \"Alias.entity\"\n * - Call form (with overrides): { extends: \"Alias.entity\", name?, fields?, persistence?, collection? }\n *\n * @example\n * ```json\n * // Inline\n * { \"entity\": { \"name\": \"Player\", \"fields\": [...] } }\n *\n * // Simple reference\n * { \"entity\": \"Goblin.entity\" }\n *\n * // Call form with overrides (Phase F)\n * { \"entity\": { \"extends\": \"Modal.entity\", \"name\": \"CartItem\", \"fields\": [...] } }\n * ```\n */\nexport type EntityRef = Entity | string | EntityCall;\n\n/**\n * Checks if an entity reference is a string reference.\n *\n * Type guard to determine if an EntityRef is a string reference\n * (format: \"Alias.entity\") rather than an inline entity definition or\n * an EntityCall object.\n *\n * Note: This guard intentionally narrows to `string` only. To check for\n * any non-inline form (string OR EntityCall), use `isEntityReferenceAny`.\n *\n * @param {EntityRef} entity - Entity reference to check\n * @returns {boolean} True if entity is a string reference, false otherwise\n *\n * @example\n * const ref1 = \"User.entity\"; // string reference\n * const ref2 = { name: \"User\", fields: [...] }; // inline definition\n * const ref3 = { extends: \"User.entity\" }; // EntityCall\n *\n * isEntityReference(ref1); // returns true\n * isEntityReference(ref2); // returns false\n * isEntityReference(ref3); // returns false\n */\nexport function isEntityReference(entity: EntityRef): entity is string {\n return typeof entity === \"string\";\n}\n\n/**\n * Checks if an entity reference is an EntityCall (extends form).\n *\n * Type guard for the call-form EntityRef introduced in Phase F. EntityCall\n * is identified by the presence of the \"extends\" discriminator key.\n *\n * @param {EntityRef} entity - Entity reference to check\n * @returns {boolean} True if entity is an EntityCall object\n *\n * @example\n * isEntityCall({ extends: \"Modal.entity\", name: \"CartItem\" }); // returns true\n * isEntityCall(\"Modal.entity\"); // returns false\n * isEntityCall({ name: \"Modal\", fields: [] }); // returns false\n */\nexport function isEntityCall(entity: EntityRef): entity is EntityCall {\n return typeof entity === \"object\" && entity !== null && \"extends\" in entity;\n}\n\n/**\n * Checks if an entity reference is any non-inline form (string or EntityCall).\n *\n * Broader companion to `isEntityReference` that recognizes both the bare\n * string reference and the Phase F EntityCall form.\n *\n * @param {EntityRef} entity - Entity reference to check\n * @returns {boolean} True if entity is a string reference or EntityCall\n */\nexport function isEntityReferenceAny(\n entity: EntityRef,\n): entity is string | EntityCall {\n return isEntityReference(entity) || isEntityCall(entity);\n}\n\n/**\n * Validate entity reference format: \"Alias.entity\"\n */\nexport const EntityRefStringSchema = z\n .string()\n .regex(\n /^[A-Z][a-zA-Z0-9]*\\.entity$/,\n 'Entity reference must be in format \"Alias.entity\" (e.g., \"Goblin.entity\")',\n );\n\n/**\n * Validate EntityCall (extends form) shape.\n *\n * Phase F.4 refines:\n * - The `fields` override array must not contain duplicate field names\n * (case-sensitive). Duplicates would silently shadow each other during\n * the inliner's field-merge step, so reject at the schema boundary.\n */\nexport const EntityCallSchema = z\n .object({\n extends: z\n .string()\n .regex(\n /^[A-Z][a-zA-Z0-9]*\\.entity$/,\n 'EntityCall \"extends\" must be in format \"Alias.entity\"',\n ),\n name: z.string().optional(),\n fields: z.array(EntityFieldSchema).optional(),\n persistence: EntityPersistenceSchema.optional(),\n collection: z.string().optional(),\n })\n .refine(\n (call) => {\n if (!call.fields) return true;\n const seen = new Set<string>();\n for (const field of call.fields) {\n if (field.name === undefined) continue;\n if (seen.has(field.name)) return false;\n seen.add(field.name);\n }\n return true;\n },\n {\n message:\n 'EntityCall \"fields\" override list must not contain duplicate field names',\n path: [\"fields\"],\n },\n );\n\nexport const EntityRefSchema = z.union([\n EntitySchema,\n EntityRefStringSchema,\n EntityCallSchema,\n]);\n\n// ============================================================================\n// Page Reference (Inline OR Reference)\n// ============================================================================\n\n/**\n * PageRefObject - Reference to imported page with optional override arguments.\n *\n * Phase F adds `linkedEntity` and `traits` arguments so a caller can rebind\n * the imported page's entity and trait set, treating the page as a callable\n * function.\n */\nexport interface PageRefObject {\n /**\n * Reference to imported page: \"Alias.pages.PageName\"\n */\n ref: string;\n\n /**\n * Phase 1.2: optional registry path disambiguator. Pairs with `ref` to\n * explicitly name which `uses` entry the alias was imported from\n * (e.g. \"std/behaviors/atoms/std-browse\"). Helpful for programmatic\n * descriptor construction and inline-phase disambiguation when multiple\n * registries expose the same alias prefix.\n */\n from?: string;\n\n /**\n * Optional path override.\n * If provided, overrides the original page's path.\n */\n path?: string;\n\n /**\n * Phase F: rebind the page's entity to the caller's entity.\n * Identifier-substitution pass rewrites references to the original\n * entity inside the imported page.\n */\n linkedEntity?: string;\n\n /**\n * Phase F: override the page's trait set with the caller-supplied list.\n * Each entry may be a string trait reference or an inline trait reference object.\n */\n traits?: TraitRef[];\n}\n\n/**\n * PageRef - Page can be inline definition OR reference to imported page.\n *\n * Reference formats:\n * - \"Alias.pages.PageName\" - Simple reference (keeps original path)\n * - { ref: \"Alias.pages.PageName\", path: \"/custom\" } - Reference with path override\n *\n * @example\n * ```json\n * // Inline\n * { \"name\": \"Dashboard\", \"path\": \"/\", ... }\n *\n * // Simple reference\n * \"User.pages.Profile\"\n *\n * // Reference with path override\n * { \"ref\": \"User.pages.Profile\", \"path\": \"/my-profile\" }\n * ```\n */\nexport type PageRef = Page | string | PageRefObject;\n\n/**\n * Checks if a page reference is a string reference.\n * \n * Type guard to determine if a PageRef is a simple string reference\n * (format: \"Alias.pages.PageName\") rather than an inline page definition or object reference.\n * \n * @param {PageRef} page - Page reference to check\n * @returns {boolean} True if page is a string reference, false otherwise\n * \n * @example\n * const ref1 = \"User.pages.Profile\"; // string reference\n * const ref2 = { name: \"Dashboard\", path: \"/\" }; // inline definition\n * \n * isPageReferenceString(ref1); // returns true\n * isPageReferenceString(ref2); // returns false\n */\nexport function isPageReferenceString(page: PageRef): page is string {\n return typeof page === \"string\";\n}\n\n/**\n * Checks if a page reference is a reference object.\n * \n * Type guard to determine if a PageRef is an object reference\n * with a 'ref' property rather than an inline page definition.\n * \n * @param {PageRef} page - Page reference to check\n * @returns {boolean} True if page is a reference object, false otherwise\n * \n * @example\n * const ref1 = { ref: \"User.pages.Profile\", path: \"/custom\" }; // reference object\n * const ref2 = { name: \"Dashboard\", path: \"/\" }; // inline definition\n * \n * isPageReferenceObject(ref1); // returns true\n * isPageReferenceObject(ref2); // returns false\n */\nexport function isPageReferenceObject(page: PageRef): page is PageRefObject {\n return typeof page === \"object\" && \"ref\" in page && !(\"name\" in page);\n}\n\n/**\n * Checks if a page reference is any type of reference.\n * \n * Type guard to determine if a PageRef is a reference (string or object)\n * rather than an inline page definition.\n * \n * @param {PageRef} page - Page reference to check\n * @returns {boolean} True if page is a reference, false if inline definition\n * \n * @example\n * const ref1 = \"User.pages.Profile\"; // string reference\n * const ref2 = { ref: \"User.pages.Profile\", path: \"/custom\" }; // object reference\n * const ref3 = { name: \"Dashboard\", path: \"/\" }; // inline definition\n * \n * isPageReference(ref1); // returns true\n * isPageReference(ref2); // returns true\n * isPageReference(ref3); // returns false\n */\nexport function isPageReference(page: PageRef): page is string | PageRefObject {\n return isPageReferenceString(page) || isPageReferenceObject(page);\n}\n\n/**\n * Validate page reference format: \"Alias.pages.PageName\"\n */\nexport const PageRefStringSchema = z\n .string()\n .regex(\n /^[A-Z][a-zA-Z0-9]*\\.pages\\.[A-Z][a-zA-Z0-9]*$/,\n 'Page reference must be in format \"Alias.pages.PageName\" (e.g., \"User.pages.Profile\")',\n );\n\nexport const PageRefObjectSchema = z.object({\n ref: PageRefStringSchema,\n // Phase 1.2: optional registry path disambiguator, pairs with `ref`.\n from: z.string().optional(),\n path: z.string().startsWith(\"/\").optional(),\n linkedEntity: z.string().optional(),\n traits: z.array(TraitRefSchema).optional(),\n});\n\nexport const PageRefSchema = z.union([\n PageSchema,\n PageRefStringSchema,\n PageRefObjectSchema,\n]);\n\n// ============================================================================\n// Trait Reference Extensions\n// ============================================================================\n\n/**\n * Extended trait reference format for imported traits.\n *\n * Formats:\n * - \"TraitName\" - Local trait (inline or from uses without alias)\n * - \"Alias.traits.TraitName\" - Imported trait with namespace\n *\n * The existing TraitRef type already supports these via string.\n */\n\n/**\n * Validate trait reference format for imported traits.\n */\nexport const ImportedTraitRefStringSchema = z\n .string()\n .regex(\n /^([A-Z][a-zA-Z0-9]*\\.traits\\.)?[A-Z][a-zA-Z0-9]*$/,\n 'Trait reference must be \"TraitName\" or \"Alias.traits.TraitName\"',\n );\n\n/**\n * Checks if a trait reference is an imported reference.\n * \n * Determines if a trait reference uses the imported format\n * \"Alias.traits.TraitName\" rather than a simple \"TraitName\".\n * \n * @param {string} ref - Trait reference to check\n * @returns {boolean} True if reference is imported format, false otherwise\n * \n * @example\n * isImportedTraitRef(\"User.traits.Profile\"); // returns true\n * isImportedTraitRef(\"Profile\"); // returns false\n */\nexport function isImportedTraitRef(ref: string): boolean {\n return /^[A-Z][a-zA-Z0-9]*\\.traits\\.[A-Z][a-zA-Z0-9]*$/.test(ref);\n}\n\n/**\n * Parses an imported trait reference.\n * \n * Extracts the alias and trait name from an imported trait reference\n * in format \"Alias.traits.TraitName\". Returns null if not a valid imported reference.\n * \n * @param {string} ref - Trait reference to parse\n * @returns {{ alias: string; traitName: string } | null} Parsed reference or null\n * \n * @example\n * parseImportedTraitRef(\"User.traits.Profile\"); // returns { alias: \"User\", traitName: \"Profile\" }\n * parseImportedTraitRef(\"Profile\"); // returns null\n */\nexport function parseImportedTraitRef(\n ref: string,\n): { alias: string; traitName: string } | null {\n const match = ref.match(/^([A-Z][a-zA-Z0-9]*)\\.traits\\.([A-Z][a-zA-Z0-9]*)$/);\n if (!match) return null;\n return { alias: match[1], traitName: match[2] };\n}\n\n/**\n * Parses an entity reference.\n * \n * Extracts the alias from an entity reference in format \"Alias.entity\".\n * Returns null if not a valid entity reference.\n * \n * @param {string} ref - Entity reference to parse\n * @returns {{ alias: string } | null} Parsed reference or null\n * \n * @example\n * parseEntityRef(\"User.entity\"); // returns { alias: \"User\" }\n * parseEntityRef(\"User\"); // returns null\n */\nexport function parseEntityRef(ref: string): { alias: string } | null {\n const match = ref.match(/^([A-Z][a-zA-Z0-9]*)\\.entity$/);\n if (!match) return null;\n return { alias: match[1] };\n}\n\n/**\n * Parses a page reference.\n * \n * Extracts the alias and page name from a page reference\n * in format \"Alias.pages.PageName\". Returns null if not a valid page reference.\n * \n * @param {string} ref - Page reference to parse\n * @returns {{ alias: string; pageName: string } | null} Parsed reference or null\n * \n * @example\n * parsePageRef(\"User.pages.Profile\"); // returns { alias: \"User\", pageName: \"Profile\" }\n * parsePageRef(\"Profile\"); // returns null\n */\nexport function parsePageRef(\n ref: string,\n): { alias: string; pageName: string } | null {\n const match = ref.match(/^([A-Z][a-zA-Z0-9]*)\\.pages\\.([A-Z][a-zA-Z0-9]*)$/);\n if (!match) return null;\n return { alias: match[1], pageName: match[2] };\n}\n\n// ============================================================================\n// Event Listener (Legacy)\n// ============================================================================\n\n/**\n * Event listener for cross-orbital communication (legacy format).\n * @deprecated Use trait-level listens with scope instead.\n */\nexport interface EventListener {\n /** Event key to listen for */\n event: string;\n /** Action to trigger */\n triggers: string;\n /** Optional guard condition */\n guard?: string;\n}\n\nexport const EventListenerSchema = z.object({\n event: z.string().min(1),\n triggers: z.string().min(1),\n guard: z.string().optional(),\n});\n\n// ============================================================================\n// Computed Event Contract (Trait-Centric Model)\n// ============================================================================\n\n/**\n * Source of an event - which trait/transition/tick emits it.\n */\nexport interface EventSource {\n /** Trait that emits this event */\n trait: string;\n /** Transition that emits this event (if applicable) */\n transition?: string;\n /** Tick that emits this event (if applicable) */\n tick?: string;\n}\n\nexport const EventSourceSchema = z.object({\n trait: z.string().min(1),\n transition: z.string().optional(),\n tick: z.string().optional(),\n});\n\n/**\n * Computed event contract with source tracking.\n * Generated by aggregating trait-level emits with namespacing.\n */\nexport interface ComputedEventContract {\n /** Namespaced event: \"TraitName.EVENT_NAME\" */\n event: string;\n /** Original event name without namespace */\n originalEvent: string;\n /** Source trait that emits this event */\n source: EventSource;\n /** Human-readable description */\n description?: string;\n /** Payload schema */\n payload?: EventPayloadField[];\n}\n\nexport const ComputedEventContractSchema = z.object({\n event: z.string().min(1),\n originalEvent: z.string().min(1),\n source: EventSourceSchema,\n description: z.string().optional(),\n payload: z.array(EventPayloadFieldSchema).optional(),\n});\n\n/**\n * Computed event listener with source tracking.\n * Generated by aggregating trait-level listens.\n */\nexport interface ComputedEventListener {\n /** Event to listen for (may be namespaced) */\n event: string;\n /** Source trait that defines this listener */\n source: EventSource;\n /** State machine event to trigger */\n triggers: string;\n /** Guard expression */\n guard?: Expression;\n /** Payload field mapping */\n payloadMapping?: Record<string, string>;\n}\n\nexport const ComputedEventListenerSchema = z.object({\n event: z.string().min(1),\n source: EventSourceSchema,\n triggers: z.string().min(1),\n guard: ExpressionSchema.optional(),\n payloadMapping: z.record(z.string()).optional(),\n});\n\n// ============================================================================\n// Orbital\n// ============================================================================\n\n/**\n * Orbital - The atomic building block of applications.\n *\n * Formula: Orbital = Entity × Traits × Pages\n *\n * An orbital is a self-contained feature unit that groups:\n * - One entity (the data nucleus) - inline OR referenced via \"Alias.entity\"\n * - Zero or more traits (behavioral patterns) - inline OR referenced via \"Alias.traits.X\"\n * - Zero or more pages (UI entry points) - inline OR referenced via \"Alias.pages.X\"\n *\n * Use `uses` to import other orbitals and access their components.\n */\nexport type Orbital = OrbitalDefinition;\n\nexport interface OrbitalDefinition {\n /** Human-readable name */\n name: string;\n\n /** Optional description */\n description?: string;\n\n /** Visual prompt override */\n visual_prompt?: string;\n\n // ========================================================================\n // Import System (Unified Reference)\n // ========================================================================\n\n /**\n * Import external orbitals as namespaces.\n *\n * After importing, access components via:\n * - Alias.entity - The entity definition\n * - Alias.traits.TraitName - A specific trait\n * - Alias.pages.PageName - A specific page\n * - Alias.theme - The theme definition\n * - Alias.services.ServiceName - A specific service\n *\n * @example\n * ```json\n * \"uses\": [\n * { \"from\": \"./health.orb\", \"as\": \"Health\" },\n * { \"from\": \"std/behaviors/game-core\", \"as\": \"GameCore\" }\n * ]\n * ```\n */\n uses?: UseDeclaration[];\n\n // ========================================================================\n // Theme & Services\n // ========================================================================\n\n /**\n * Theme definition (inline OR reference via \"Alias.theme\").\n *\n * @example\n * ```json\n * // Inline\n * \"theme\": { \"name\": \"ocean\", \"tokens\": { \"colors\": { \"primary\": \"#0ea5e9\" } } }\n *\n * // Reference\n * \"theme\": \"Ocean.theme\"\n * ```\n */\n theme?: ThemeRef;\n\n /**\n * Service definitions (inline OR reference via \"Alias.services.ServiceName\").\n *\n * @example\n * ```json\n * // Inline\n * \"services\": [{ \"name\": \"weather\", \"type\": \"rest\", \"baseUrl\": \"...\" }]\n *\n * // Reference\n * \"services\": [\"Weather.services.openweather\"]\n * ```\n */\n services?: ServiceRef[];\n\n // ========================================================================\n // Components (Inline OR Reference)\n // ========================================================================\n\n /**\n * Entity definition (nucleus).\n *\n * Can be:\n * - Inline: Full entity definition\n * - Reference: \"Alias.entity\" (from uses)\n *\n * Entity sharing depends on persistence type:\n * - persistent: Shared (same DB collection)\n * - runtime: Isolated (each orbital gets own instances)\n * - singleton: Shared (single global instance)\n */\n entity: EntityRef;\n\n /**\n * Imported atom entities surfaced into this orbital's resolution\n * scope WITHOUT modifying the primary `entity`. Populated by the\n * compiler's inline phase when a trait reference imports an atom\n * and OMITS the `-> Entity` linkedEntity rebind: the atom keeps its\n * own entity (e.g. `SearchResult` from std-search), and that entity\n * is registered here so validators / codegen / runtime can resolve\n * `linkedEntity = \"SearchResult\"` lookups, register persistence for\n * it, and emit its TypeScript type alongside the primary entity.\n * The orbital's per-trait entity arity stays 1:1 — this is purely a\n * NAME-RESOLUTION side channel for cross-import linkedEntity\n * references.\n */\n auxiliaryEntities?: EntityRef[];\n\n /** Trait references (local or imported via \"Alias.traits.TraitName\") */\n traits: TraitRef[];\n\n /**\n * Page definitions.\n *\n * Can be:\n * - Inline: Full page definition\n * - Reference string: \"Alias.pages.PageName\"\n * - Reference object: { ref: \"Alias.pages.PageName\", path: \"/custom\" }\n */\n pages: PageRef[];\n\n // ========================================================================\n // Event Interface (Trait-Centric Model)\n // ========================================================================\n\n /**\n * Events this orbital emits.\n *\n * COMPUTED from trait-level emits:\n * - Aggregated from all traits with `scope: 'external'`\n * - Namespaced as \"TraitName.EVENT_NAME\"\n * - Filtered by `exposes` if present\n *\n * Do not author directly - computed by resolver.\n */\n emits?: ComputedEventContract[];\n\n /**\n * Events this orbital listens for.\n *\n * COMPUTED from trait-level listens:\n * - Aggregated from all traits with `scope: 'external'`\n *\n * Do not author directly - computed by resolver.\n */\n listens?: ComputedEventListener[];\n\n /**\n * Filter which trait events are exposed externally.\n * If omitted, all external-scoped trait events are exposed.\n * Format: [\"TraitName.EVENT_NAME\", ...]\n */\n exposes?: string[];\n\n // ========================================================================\n // Context fields - persisted throughout orbital lifecycle\n // ========================================================================\n\n /** Domain context - category, vocabulary, personas */\n domainContext?: DomainContext;\n\n /** Design preferences - style, colors, UX hints */\n design?: DesignPreferences;\n\n /**\n * Suggested guards (decomposition phase only).\n * Natural language descriptions that generator converts to S-expressions.\n * Removed after generation - guards live in traits.\n */\n suggestedGuards?: SuggestedGuard[];\n}\n\nexport const OrbitalDefinitionSchema = z.object({\n name: z.string().min(1, \"Orbital name is required\"),\n description: z.string().optional(),\n visual_prompt: z.string().optional(),\n // Import system\n uses: z.array(UseDeclarationSchema).optional(),\n // Theme & Services\n theme: ThemeRefSchema.optional(),\n services: z.array(ServiceRefSchema).optional(),\n // Components (inline or reference)\n entity: EntityRefSchema,\n traits: z.array(TraitRefSchema),\n pages: z.array(PageRefSchema),\n // Event interface (trait-centric model) - computed by resolver\n emits: z.array(ComputedEventContractSchema).optional(),\n listens: z.array(ComputedEventListenerSchema).optional(),\n // Filter for exposed events (trait-centric model)\n exposes: z.array(z.string()).optional(),\n // Context fields - persisted throughout orbital lifecycle\n domainContext: DomainContextSchema.optional(),\n design: DesignPreferencesSchema.optional(),\n suggestedGuards: z.array(SuggestedGuardSchema).optional(),\n});\n\nexport const OrbitalSchema = OrbitalDefinitionSchema;\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\n/**\n * Type guard to check if an Orbital is a full definition.\n * @deprecated No longer needed since Orbital is always OrbitalDefinition now.\n */\nexport function isOrbitalDefinition(\n orbital: Orbital,\n): orbital is OrbitalDefinition {\n return \"entity\" in orbital;\n}\n\n// ============================================================================\n// Type exports\n// ============================================================================\n\nexport type OrbitalInput = z.input<typeof OrbitalSchema>;\n\n// Backward compatibility\nexport type OrbitalUnit = Orbital;\nexport const OrbitalUnitSchema = OrbitalSchema;\n","/**\n * Orbital Schema Type (Self-Contained)\n *\n * Defines the OrbitalSchema - the top-level application definition.\n * An application is a composition of orbitals: App = Σ(Orbitals)\n *\n * @packageDocumentation\n */\n\nimport { z } from \"zod\";\nimport type { Orbital } from \"./orbital.js\";\nimport { OrbitalSchema as OrbitalZodSchema } from \"./orbital.js\";\nimport type {\n DomainContext,\n DesignPreferences,\n DesignTokens,\n CustomPatternMap,\n} from \"./domain.js\";\nimport {\n DomainContextSchema,\n DesignPreferencesSchema,\n DesignTokensSchema,\n CustomPatternMapSchema,\n} from \"./domain.js\";\nimport type { ServiceDefinition } from \"./service.js\";\nimport { ServiceDefinitionSchema } from \"./service.js\";\nimport type { Trait } from \"./trait.js\";\n\n// ============================================================================\n// Orbital Config\n// ============================================================================\n\n/**\n * Global configuration for the application\n */\nexport interface OrbitalConfig {\n /** Theme configuration */\n theme?: {\n primary?: string;\n secondary?: string;\n mode?: \"light\" | \"dark\" | \"system\";\n };\n /** Feature flags */\n features?: Record<string, boolean>;\n /** API configuration */\n api?: {\n baseUrl?: string;\n timeout?: number;\n };\n}\n\nexport const OrbitalConfigSchema = z.object({\n theme: z\n .object({\n primary: z.string().optional(),\n secondary: z.string().optional(),\n mode: z.enum([\"light\", \"dark\", \"system\"]).optional(),\n })\n .optional(),\n features: z.record(z.boolean()).optional(),\n api: z\n .object({\n baseUrl: z.string().optional(),\n timeout: z.number().optional(),\n })\n .optional(),\n});\n\n// ============================================================================\n// Orbital Schema\n// ============================================================================\n\n/**\n * OrbitalSchema - The top-level application definition.\n *\n * An application is a composition of orbitals:\n * App = Σ(Orbitals)\n *\n * Custom traits can be defined at the schema level and referenced\n * by orbitals via TraitRef. This allows LLMs to generate custom\n * traits that aren't in the trait library.\n */\n/**\n * One `@config.<knob>` → render-ui prop substitution recorded by the inline\n * phase. Lets a consumer trace a resolved render-ui literal back to the config\n * knob it came from (the `@config.X` string is erased after substitution).\n * Mirrors the Rust `ConfigProvenanceRecord`.\n */\nexport interface ConfigProvenanceRecord {\n /** Resolved trait name (post call-site rename) owning the render-ui effect. */\n trait: string;\n /** Pattern path within the render-ui tree (e.g. `root.children.0`). */\n patternPath?: string;\n /** The pattern-node prop key whose value was a `@config.X` binding. */\n prop: string;\n /** The config knob name (`X` in `@config.X`). */\n knob: string;\n}\n\n/** Compiler-emitted schema metadata — the resolved `.orb` `_metadata` block. */\nexport interface SchemaMetadata {\n version?: number;\n createdAt?: number;\n source?: string;\n updatedAt?: number;\n /** Config→knob provenance keyed by orbital name. See {@link ConfigProvenanceRecord}. */\n configProvenance?: Record<string, ConfigProvenanceRecord[]>;\n}\n\nexport interface OrbitalSchema {\n /** Application name */\n name: string;\n\n /** Description */\n description?: string;\n\n /**\n * Short human-readable summary distinct from `description`. Typically an\n * AI-generated one-liner used by app list views, breadcrumbs, and the\n * `GET /graphs/:appId/domain-text` projection. Kept separate from\n * `description` (which may be longer / authored copy) so consumers can\n * present a stable short label without truncating.\n */\n summary?: string;\n\n /** Version (semver) */\n version?: string;\n\n /** Domain context - user request + classification */\n domainContext?: DomainContext;\n\n /** Design preferences */\n design?: DesignPreferences;\n\n /**\n * Design tokens - reusable Tailwind class collections.\n * Reference via `token: \"surfaces.glass\"` in patterns.\n */\n designTokens?: DesignTokens;\n\n /**\n * Custom pattern definitions for app-specific reusable patterns.\n * Register custom designs that can be referenced by name.\n */\n customPatterns?: CustomPatternMap;\n\n /** Array of orbitals */\n orbitals: Orbital[];\n\n /** External services */\n services?: ServiceDefinition[];\n\n /** Global config */\n config?: OrbitalConfig;\n\n /** Compiler-emitted metadata (resolved `.orb` `_metadata`). */\n _metadata?: SchemaMetadata;\n}\n\nexport const ConfigProvenanceRecordSchema = z.object({\n trait: z.string(),\n patternPath: z.string().optional(),\n prop: z.string(),\n knob: z.string(),\n});\n\nexport const SchemaMetadataSchema = z.object({\n version: z.number().optional(),\n createdAt: z.number().optional(),\n source: z.string().optional(),\n updatedAt: z.number().optional(),\n configProvenance: z.record(z.array(ConfigProvenanceRecordSchema)).optional(),\n});\n\nexport const OrbitalSchemaSchema = z.object({\n name: z.string().min(1, \"Schema name is required\"),\n description: z.string().optional(),\n summary: z.string().optional(),\n version: z.string().optional(),\n domainContext: DomainContextSchema.optional(),\n design: DesignPreferencesSchema.optional(),\n designTokens: DesignTokensSchema,\n customPatterns: CustomPatternMapSchema,\n orbitals: z\n .array(OrbitalZodSchema)\n .min(1, \"At least one orbital is required\"),\n services: z.array(ServiceDefinitionSchema).optional(),\n config: OrbitalConfigSchema.optional(),\n _metadata: SchemaMetadataSchema.optional(),\n});\n\n// ============================================================================\n// Persisted/Flattened View\n// ============================================================================\n\n/**\n * Flattened `OrbitalSchema` view used by the persistence/runtime layer.\n *\n * Canonical `OrbitalSchema` keeps every trait inside its owning\n * `OrbitalDefinition.traits`. Some runtime paths (e.g. the orbital-agent\n * stream, Firestore persistence) additionally roll the resolved trait set up\n * to the top level as `traits[]` so diffs and list views don't have to walk\n * every orbital.\n *\n * This is intentionally a LOSSY persisted view, NOT the canonical authoring\n * shape: it carries the rolled-up array alongside the per-orbital trait\n * lists, and consumers should prefer `OrbitalSchema` whenever the rolled-up\n * surface isn't required.\n */\nexport interface OrbitalSchemaWithTraits extends OrbitalSchema {\n /** Flattened trait set rolled up from all orbitals. Persisted-view only. */\n traits?: Trait[];\n}\n\n// ============================================================================\n// Parsing Functions\n// ============================================================================\n\n/**\n * Parses raw data into a validated OrbitalSchema.\n * \n * Uses Zod validation to ensure the data conforms to the OrbitalSchema structure.\n * Throws a ZodError if validation fails. For safe parsing that doesn't throw,\n * use `safeParseOrbitalSchema()` instead.\n * \n * @param {unknown} data - Raw data to parse (typically JSON)\n * @returns {OrbitalSchema} Validated orbital schema\n * @throws {z.ZodError} If data doesn't match OrbitalSchema structure\n * \n * @example\n * ```typescript\n * try {\n * const schema = parseOrbitalSchema(jsonData);\n * console.log('Valid schema:', schema.name);\n * } catch (error) {\n * console.error('Invalid schema:', error);\n * }\n * ```\n * \n * @see safeParseOrbitalSchema\n */\nexport function parseOrbitalSchema(data: unknown): OrbitalSchema {\n return OrbitalSchemaSchema.parse(data) as OrbitalSchema;\n}\n\n/**\n * Safely parses raw data into a validated OrbitalSchema without throwing.\n * \n * Uses Zod's safeParse method to validate data and return a result object\n * instead of throwing errors. This is useful for form validation and\n * user input handling where you want to gracefully handle invalid data.\n * \n * @param {unknown} data - Raw data to parse (typically JSON)\n * @returns {z.SafeParseReturnType<OrbitalSchema, OrbitalSchema>} Parse result with success/status\n * \n * @example\n * ```typescript\n * const result = safeParseOrbitalSchema(jsonData);\n * if (result.success) {\n * console.log('Valid schema:', result.data.name);\n * } else {\n * console.error('Validation errors:', result.error);\n * }\n * ```\n * \n * @see parseOrbitalSchema\n */\nexport function safeParseOrbitalSchema(data: unknown) {\n return OrbitalSchemaSchema.safeParse(data);\n}\n\n// ============================================================================\n// Type exports\n// ============================================================================\n\nexport type OrbitalSchemaInput = z.input<typeof OrbitalSchemaSchema>;\nexport type OrbitalConfigInput = z.input<typeof OrbitalConfigSchema>;\n","/**\n * S-Expression Bindings\n *\n * Defines binding types and utilities for S-expression context.\n * Bindings are references to values that are resolved at runtime.\n *\n * Core Bindings:\n * - @entity - The linked entity for this trait (e.g., @entity.health)\n * - @payload - Event payload data (e.g., @payload.amount)\n * - @state - Current state machine state\n * - @now - Current timestamp (Date.now())\n *\n * Entity Bindings:\n * - @EntityName.field - Reference to singleton/runtime entity (e.g., @GameConfig.gravity)\n *\n * @packageDocumentation\n */\n\nimport { z } from 'zod';\n\n// Re-export core binding utilities from expression.ts\nexport {\n isBinding,\n parseBinding,\n isValidBinding,\n CORE_BINDINGS,\n type CoreBinding,\n type ParsedBinding,\n} from './expression.js';\n\n// ============================================================================\n// Binding Schema\n// ============================================================================\n\n/**\n * Schema for a binding string.\n * Validates that the string starts with @ and has valid format.\n */\nexport const BindingSchema = z.string().refine(\n (val) => {\n if (!val.startsWith('@')) return false;\n const parts = val.slice(1).split('.');\n if (parts.length === 0 || parts[0] === '') return false;\n // All parts must be valid identifiers (letters, numbers, underscore)\n // supporting unicode characters for i18n\n return parts.every((part) => /^[\\p{L}_][\\p{L}0-9_]*$/u.test(part));\n },\n { message: 'Invalid binding format. Must be @name or @name.path.to.field' }\n);\n\n// ============================================================================\n// Binding Constants\n// ============================================================================\n\n/**\n * Binding documentation for LLM prompts and validation messages.\n * \n * IMPORTANT: Keep synchronized with CORE_BINDINGS in expression.ts\n */\nexport const BINDING_DOCS = {\n entity: {\n description: 'Reference to the linked entity for this trait',\n examples: ['@entity.health', '@entity.x', '@entity.status'],\n requiresPath: true,\n },\n payload: {\n description: 'Reference to the event payload data',\n examples: ['@payload.amount', '@payload.targetId', '@payload.action'],\n requiresPath: true,\n },\n state: {\n description: 'Current state machine state name',\n examples: ['@state'],\n requiresPath: false,\n },\n now: {\n description: 'Current timestamp in milliseconds',\n examples: ['@now'],\n requiresPath: false,\n },\n config: {\n description: 'Trait configuration values',\n examples: ['@config.apiEndpoint', '@config.theme'],\n requiresPath: true,\n },\n computed: {\n description: 'Computed/calculated values',\n examples: ['@computed.total', '@computed.isValid'],\n requiresPath: true,\n },\n trait: {\n description: 'Trait context data',\n examples: ['@trait.name', '@trait.category'],\n requiresPath: true,\n },\n user: {\n description: 'Authenticated user / agent context for ownership and role-based gating',\n examples: ['@user.id', '@user.role'],\n requiresPath: true,\n },\n} as const;\n\n/**\n * Validation rules for bindings in different contexts.\n */\nexport const BINDING_CONTEXT_RULES = {\n guard: {\n allowed: ['entity', 'payload', 'state', 'now', 'config', 'user'] as const,\n description:\n 'Guards can access entity fields, event payload, current state, time, the call-site trait config (@config.X), and the authenticated user context (@user.id, @user.role) for ownership / role gates. Config access lets atoms write mode-aware guards — e.g. std-modal\\'s OPEN can require @payload.row only when @config.mode equals \"edit\", letting create-mode legitimately fire OPEN with no row. Like effects, @config.X is substituted at molecule/organism inline time with the literal call-site value; at atom-scope validate, @config is allowed-but-unresolved.',\n },\n effect: {\n allowed: ['entity', 'payload', 'state', 'now', 'trait', 'config', 'user'] as const,\n description:\n 'Effects can access and modify entity fields, use payload data, embed another trait\\'s live frame via @trait.X inside render-ui children, read trait config values (@config.X) for atoms parameterized by their call-site, and read the authenticated user context (@user.id, @user.role). At molecule/organism inline time, @config.X is substituted with the literal value from the call-site config block; at atom-scope validate, @config is allowed-but-unresolved.',\n },\n tick: {\n allowed: ['entity', 'state', 'now', 'config', 'user'] as const,\n description: 'Ticks can access entity fields, current state, time, trait config (@config.X) for parameterized atoms, and the authenticated user context (@user.id, @user.role). Same substitution semantics as guards/effects.',\n },\n} as const;\n\nexport type BindingContext = keyof typeof BINDING_CONTEXT_RULES;\n\n// ============================================================================\n// Binding Validation Helpers\n// ============================================================================\n\n/**\n * Check if a binding is valid in a given context.\n *\n * @param binding - Parsed binding\n * @param context - Context where binding is used\n * @returns Error message if invalid, null if valid\n */\nexport function validateBindingInContext(\n binding: { type: 'core' | 'entity'; root: string },\n context: BindingContext\n): string | null {\n const rules = BINDING_CONTEXT_RULES[context];\n\n if (binding.type === 'core') {\n if (!(rules.allowed as readonly string[]).includes(binding.root)) {\n return `Binding @${binding.root} is not allowed in ${context} context. Allowed: ${rules.allowed.join(', ')}`;\n }\n }\n\n // Entity bindings are always allowed (they reference singletons/runtime entities)\n return null;\n}\n\n/**\n * Get all valid binding examples for a context.\n *\n * @param context - Context to get examples for\n * @returns Array of example binding strings\n */\nexport function getBindingExamples(context: BindingContext): string[] {\n const rules = BINDING_CONTEXT_RULES[context];\n const examples: string[] = [];\n\n for (const binding of rules.allowed) {\n const doc = BINDING_DOCS[binding];\n examples.push(...doc.examples);\n }\n\n // Add entity binding example\n examples.push('@GameConfig.gravity', '@Filter.searchTerm');\n\n return examples;\n}\n","/**\n * Binding root classification\n *\n * The prefix of an `@X.path` binding expression identifies which runtime\n * context resolves the rest of the path. This type is the TS-side mirror\n * of `OirBindingRoot` in `orbital-core`'s IR; publishing it from\n * `@almadar/core` lets the codegen, the runtime binding resolver, and\n * the verifier's schema walker all refer to the same narrow union.\n *\n * Distinct from {@link ParsedBinding.root} (which is a plain string): use\n * `BindingRoot` whenever you need exhaustiveness over the known prefixes.\n *\n * - `entity`: `@entity.field` — the trait's linked entity (first row on\n * the client, `getById` result on the server).\n * - `payload`: `@payload.x` — the last event's payload.\n * - `state`: `@state.x` — the state machine's `state` slot (rare;\n * mostly used for guard/effect contexts).\n * - `config`: `@config.x` — the trait ref's merged config from the\n * molecule call site.\n * - `user`: `@user.x` — authenticated user / agent context.\n * - `trait`: `@trait.x` — render-time reference to another trait's\n * mounted view. Resolved by `<TraitFrame>` at runtime, not by the\n * SExpression compiler.\n * - `item`: `@item.x` — iterator variable inside a `map` / repeat\n * pattern.\n * - `now`: `@now` — current timestamp (ISO string).\n * - `computed`: `@computed.x` — evaluator-computed value (Phase 4.5).\n * - `other`: catch-all for unknown prefixes or entity-reference\n * bindings (`@User.name`, `@_item`).\n *\n * @packageDocumentation\n */\n\nimport { z } from 'zod';\n\nexport type BindingRoot =\n | 'entity'\n | 'payload'\n | 'state'\n | 'config'\n | 'user'\n | 'trait'\n | 'item'\n | 'now'\n | 'computed'\n | 'other';\n\n/** Every known binding root, in a stable order — useful for exhaustiveness checks. */\nexport const BINDING_ROOTS: readonly BindingRoot[] = [\n 'entity',\n 'payload',\n 'state',\n 'config',\n 'user',\n 'trait',\n 'item',\n 'now',\n 'computed',\n 'other',\n] as const;\n\nconst KNOWN_ROOTS = new Set<string>(BINDING_ROOTS.filter((r) => r !== 'other'));\n\n/**\n * Narrow a raw binding-root string (e.g. the `root` field of\n * `ParsedBinding` from `./expression.ts`) to a `BindingRoot`. Returns\n * `'other'` for entity-reference roots like `@User.name` or unknown\n * prefixes.\n */\nexport function toBindingRoot(root: string): BindingRoot {\n return KNOWN_ROOTS.has(root) ? (root as BindingRoot) : 'other';\n}\n\n/**\n * A trait reference string of the form `@trait.<TraitName>`. Used as the\n * value type for `trait`-typed config fields. The runtime + compiled codegen\n * both substitute this with embedded trait UI at render time.\n *\n * Branded as a literal-template type so TS narrows on use; consumers should\n * call {@link isTraitFieldRef} to validate runtime values before assignment.\n */\nexport type TraitFieldRef = `@trait.${string}`;\n\nconst TRAIT_REF_PATTERN = /^@trait\\.[A-Z][a-zA-Z0-9]*$/;\n\n/** Type guard: narrow an unknown value to {@link TraitFieldRef}. */\nexport function isTraitFieldRef(value: unknown): value is TraitFieldRef {\n return typeof value === 'string' && TRAIT_REF_PATTERN.test(value);\n}\n\n/** Zod schema for {@link TraitFieldRef} values. Useful when validating analyzer\n * JSON or recipe overrides at runtime boundaries. */\nexport const TraitFieldRefSchema = z\n .string()\n .regex(TRAIT_REF_PATTERN, 'expected `@trait.<TraitName>` reference');\n","/**\n * Interaction Model Types\n *\n * Defines how users interact with entities in the application.\n * Used to drive trait selection and UI slot usage.\n *\n * @packageDocumentation\n */\n\nimport { z } from 'zod';\n\n// ============================================================================\n// Flow Types\n// ============================================================================\n\n/**\n * Create flow - how new items are created\n */\nexport type CreateFlow = 'modal' | 'page' | 'inline' | 'none';\n\n/**\n * Edit flow - how items are edited\n */\nexport type EditFlow = 'modal' | 'page' | 'inline' | 'none';\n\n/**\n * View flow - how item details are viewed\n */\nexport type ViewFlow = 'drawer' | 'page' | 'modal' | 'inline' | 'none';\n\n/**\n * Delete flow - how items are deleted\n */\nexport type DeleteFlow = 'confirm' | 'instant' | 'none';\n\n/**\n * List interaction - what happens when clicking list items\n */\nexport type ListInteraction = 'click-to-view' | 'click-to-edit' | 'inline-edit';\n\n// ============================================================================\n// Interaction Model\n// ============================================================================\n\n/**\n * InteractionModel - defines how users interact with entities.\n *\n * This drives:\n * - Which traits to attach (EntityManagement, ModalEdit, etc.)\n * - How render_ui effects target slots (modal, drawer, page)\n * - What UI patterns to use\n */\nexport interface InteractionModel {\n /** How new items are created */\n createFlow: CreateFlow;\n\n /** How items are edited */\n editFlow: EditFlow;\n\n /** How item details are viewed */\n viewFlow: ViewFlow;\n\n /** How items are deleted */\n deleteFlow: DeleteFlow;\n\n /** What happens when clicking list items */\n listInteraction?: ListInteraction;\n\n /** Enable bulk actions (select multiple, delete all) */\n bulkActions?: boolean;\n\n /** Enable real-time updates */\n realtime?: boolean;\n}\n\nexport const InteractionModelSchema = z.object({\n createFlow: z.enum(['modal', 'page', 'inline', 'none']),\n editFlow: z.enum(['modal', 'page', 'inline', 'none']),\n viewFlow: z.enum(['drawer', 'page', 'modal', 'inline', 'none']),\n deleteFlow: z.enum(['confirm', 'instant', 'none']),\n listInteraction: z.enum(['click-to-view', 'click-to-edit', 'inline-edit']).optional(),\n bulkActions: z.boolean().optional(),\n realtime: z.boolean().optional(),\n});\n\n// ============================================================================\n// Default Models per Domain\n// ============================================================================\n\n/**\n * Default interaction models for each domain type\n */\nexport const DEFAULT_INTERACTION_MODELS: Record<string, InteractionModel> = {\n business: {\n createFlow: 'modal',\n editFlow: 'modal',\n viewFlow: 'drawer',\n deleteFlow: 'confirm',\n listInteraction: 'click-to-view',\n bulkActions: true,\n },\n game: {\n createFlow: 'none',\n editFlow: 'none',\n viewFlow: 'none',\n deleteFlow: 'none',\n realtime: true,\n },\n form: {\n createFlow: 'inline',\n editFlow: 'inline',\n viewFlow: 'none',\n deleteFlow: 'none',\n },\n dashboard: {\n createFlow: 'modal',\n editFlow: 'modal',\n viewFlow: 'drawer',\n deleteFlow: 'confirm',\n listInteraction: 'click-to-view',\n },\n content: {\n createFlow: 'page',\n editFlow: 'page',\n viewFlow: 'page',\n deleteFlow: 'confirm',\n listInteraction: 'click-to-view',\n },\n};\n\n/**\n * Gets the interaction model for a domain.\n * \n * Retrieves the appropriate interaction model configuration based on the\n * specified domain. Falls back to the business model if no specific\n * domain match is found.\n * \n * @param {string} domain - Domain name (e.g., 'healthcare', 'education')\n * @returns {InteractionModel} Interaction model configuration\n * \n * @example\n * getInteractionModelForDomain('healthcare'); // returns healthcare-specific model\n * getInteractionModelForDomain('unknown'); // returns business fallback model\n */\nexport function getInteractionModelForDomain(domain: string): InteractionModel {\n return DEFAULT_INTERACTION_MODELS[domain] ?? DEFAULT_INTERACTION_MODELS.business;\n}\n\n// ============================================================================\n// Type exports\n// ============================================================================\n\nexport type InteractionModelInput = z.input<typeof InteractionModelSchema>;\n","/**\n * Pattern Type for Orbital Units\n *\n * Re-exports pattern type definitions from @almadar/patterns,\n * which is the single source of truth for all pattern types.\n *\n * @packageDocumentation\n */\n\nimport { z } from 'zod';\n\n// ============================================================================\n// Pattern Type - Re-exported from @almadar/patterns\n// ============================================================================\n\n/**\n * All valid pattern type names, imported from the almadar-patterns registry.\n * The authoritative list is auto-generated from patterns-registry.json.\n */\nexport {\n PATTERN_TYPES,\n isValidPatternType,\n} from '@almadar/patterns';\nexport type { PatternType } from '@almadar/patterns';\n\n/**\n * Zod schema for pattern types.\n * Accepts any string - validation against full registry happens at runtime.\n */\nexport const PatternTypeSchema = z.string();\n\n// Re-export for backward compatibility\nimport { PATTERN_TYPES as _PATTERN_TYPES } from '@almadar/patterns';\n\n/**\n * Get all valid pattern types from the registry.\n * \n * Returns a complete list of pattern type names from the canonical\n * @almadar/patterns registry. Use this to iterate over or validate\n * pattern types programmatically.\n * \n * @returns {string[]} Array of pattern type names\n * \n * @example\n * const types = getAllPatternTypes();\n * // Returns: ['data-table', 'detail-view', 'form-section', ...]\n */\nexport function getAllPatternTypes(): string[] {\n return [..._PATTERN_TYPES];\n}\n","/**\n * Service Contract Types\n *\n * Formalizes the two public surfaces of an Almadar service:\n * 1. Call-Service Contract — what the .orb schema can invoke on the TypeScript package\n * 2. Event Contract — what events enter/leave the service\n *\n * Plus internal-but-standardized patterns:\n * 3. StoreContract — database abstraction boundary\n * 4. LazyService — singleton lifecycle pattern\n *\n * @packageDocumentation\n */\n\nimport type { EventPayload, EventPayloadValue, LogMeta } from './types/expression.js';\nimport type { ServiceParams } from './types/service.js';\n\n// ============================================================================\n// Service Action Names (generated from services-registry.json)\n// ============================================================================\n\n/**\n * All known service action names across all contracts.\n * Kept in sync with `tools/almadar-service-sync/services-registry.json`.\n *\n * Persist operations are listed separately because they also appear\n * as `EffectResult.action` for persist effects.\n */\nexport type PersistActionName =\n | \"create\"\n | \"update\"\n | \"delete\"\n | \"list\"\n | \"query\";\n\n/**\n * Union of all service action names across all 22 service contracts.\n */\nexport type ServiceActionName =\n | PersistActionName\n // Data service\n | \"get\"\n | \"getById\"\n | \"set\"\n | \"remove\"\n | \"size\"\n // LLM\n | \"generate\"\n | \"classify\"\n | \"extract\"\n | \"summarize\"\n // Messaging\n | \"send\"\n | \"sendMessage\"\n | \"sendSMS\"\n | \"sendWhatsApp\"\n // Auth / Identity\n | \"authorize\"\n | \"revoke\"\n | \"token\"\n | \"refresh\"\n | \"userinfo\"\n | \"register\"\n // Git / VCS\n | \"cloneRepo\"\n | \"commit\"\n | \"createBranch\"\n | \"createPR\"\n | \"getPRComments\"\n | \"pull\"\n | \"push\"\n // CI / Build\n | \"build\"\n | \"compile\"\n | \"compileSchema\"\n | \"run\"\n | \"validate\"\n | \"validateSchema\"\n | \"publish\"\n // Queue / Jobs\n | \"enqueue\"\n | \"dequeue\"\n | \"cancel\"\n // Storage / Assets\n | \"upload\"\n | \"download\"\n | \"getSignedUrl\"\n // Search / Issues\n | \"search\"\n | \"getIssue\"\n | \"listIssues\"\n // Agent / Generation\n | \"generateAll\"\n | \"generateDomainLanguage\"\n | \"generateFix\"\n | \"generateOrbitals\"\n | \"cancelGeneration\"\n | \"getGenerationHistory\"\n | \"recordGeneration\"\n // Telemetry / Metrics\n | \"startSpan\"\n | \"endSpan\"\n | \"getSpan\"\n | \"recordMetric\"\n | \"getMetrics\"\n | \"increment\"\n | \"logs\"\n // Events / Channels\n | \"addEvent\"\n | \"emit\"\n | \"findEmitters\"\n | \"findListeners\"\n | \"getListenerCounts\"\n | \"getChannel\"\n | \"subscribe\"\n // User / Preferences\n | \"getUserPreferences\"\n | \"updateUserPreferences\"\n | \"getThreadHistory\"\n // Media\n | \"getVideo\"\n // Payments\n | \"createPaymentIntent\"\n | \"confirmPayment\"\n | \"refund\"\n // Lifecycle\n | \"complete\"\n | \"fail\"\n | \"expire\"\n | \"resume\"\n | \"status\"\n | \"stop\"\n | \"lock\"\n | \"unlock\"\n | \"clear\";\n\n// ============================================================================\n// Call-Service Contract\n// ============================================================================\n\n/**\n * Action definition for a service contract.\n *\n * - `params` is bus-payload-shaped (`ServiceParams`): JSON-serializable\n * key/value bag with optional nesting. Service contracts override this\n * with stricter shapes via the generic position on `ServiceContract`.\n *\n * - `result` is JSON-serializable too (`EventPayloadValue`): a primitive,\n * `null`/`undefined`, an array of values, or an `EventPayload` object.\n * This is the same recursive shape the bus accepts when an effect's\n * `success` event fires with the call-service result, so no boundary\n * widening is needed when the runtime forwards the value.\n */\nexport interface ServiceAction {\n params: ServiceParams;\n result: EventPayloadValue;\n}\n\n/**\n * What `[\"call-service\", \"name\", \"action\", {...}]` actually calls at runtime.\n * Each service defines its action map as a Record<string, ServiceAction>.\n *\n * @example\n * ```typescript\n * type LLMActions = {\n * generate: {\n * params: { userPrompt: string; model: string; maxTokens: number };\n * result: { content: string; tokensUsed: number; latencyMs: number };\n * };\n * };\n *\n * class LLMService implements ServiceContract<LLMActions> {\n * async execute(action, params) { ... }\n * }\n * ```\n */\nexport interface ServiceContract<\n Actions extends Record<string, ServiceAction>,\n> {\n execute<A extends keyof Actions & string>(\n action: A,\n params: Actions[A][\"params\"],\n ): Promise<Actions[A][\"result\"]>;\n}\n\n// ============================================================================\n// Event Contract\n// ============================================================================\n\n/**\n * Event contract — what events the service emits/listens with typed payloads.\n * Derived from the `.orb` schema's `emits` and `listens` declarations.\n *\n * @example\n * ```typescript\n * type LLMEventMap = {\n * AGENT_LLM_REQUEST: { requestId: string; prompt: string };\n * LLM_RESPONSE: { requestId: string; content: string; tokensUsed: number };\n * LLM_ERROR: { requestId: string; error: string };\n * };\n *\n * const events: ServiceEvents<LLMEventMap> = getEventBus();\n * events.emit('LLM_RESPONSE', { requestId: '1', content: '...', tokensUsed: 42 });\n * ```\n */\nexport interface ServiceEvents<\n EventMap extends Record<string, EventPayload>,\n> {\n emit<E extends keyof EventMap & string>(\n event: E,\n payload: EventMap[E],\n ): void;\n on<E extends keyof EventMap & string>(\n event: E,\n handler: (payload: EventMap[E]) => void,\n ): () => void;\n}\n\n/**\n * Create a typed view of an untyped EventBus. Wraps the raw EventBus\n * with compile-time type checking while keeping runtime behavior identical.\n *\n * @example\n * ```typescript\n * type LLMEventMap = {\n * LLM_RESPONSE: { requestId: string; content: string };\n * LLM_ERROR: { requestId: string; error: string };\n * };\n *\n * const typedBus = createTypedEventBus<LLMEventMap>(getServerEventBus());\n * typedBus.emit('LLM_RESPONSE', { requestId: '1', content: '...' }); // type-safe\n * typedBus.on('LLM_ERROR', (payload) => { payload.error; }); // payload is typed\n * ```\n */\n/**\n * Creates a typed event bus from an untyped bus implementation.\n * \n * This wrapper adds TypeScript type safety to event emission and listening.\n * The generic `EventMap` defines the shape of all events and their payloads.\n * \n * @template EventMap - Type mapping event names to their payload types\n * @param {Object} bus - Untyped event bus implementation\n * @param {Function} bus.emit - Function to emit events\n * @param {Function} bus.on - Function to listen to events\n * @returns {ServiceEvents<EventMap>} Typed event bus interface\n * \n * @example\n * interface MyEvents {\n * 'user.created': { id: string; name: string };\n * 'user.deleted': { id: string };\n * }\n * \n * const typedBus = createTypedEventBus<MyEvents>(rawBus);\n * typedBus.emit('user.created', { id: '123', name: 'Alice' });\n */\nexport function createTypedEventBus<\n EventMap extends Record<string, EventPayload>,\n>(bus: {\n emit(event: string, payload?: unknown, meta?: LogMeta): void;\n on(event: string, handler: (payload: unknown, meta?: LogMeta) => void): () => void;\n}): ServiceEvents<EventMap> {\n return {\n emit<E extends keyof EventMap & string>(event: E, payload: EventMap[E]): void {\n bus.emit(event, payload);\n },\n on<E extends keyof EventMap & string>(\n event: E,\n handler: (payload: EventMap[E]) => void,\n ): () => void {\n return bus.on(event, handler as (payload: unknown) => void);\n },\n };\n}\n\n// ============================================================================\n// Store Contract\n// ============================================================================\n\n/** Filter operator for store queries. */\nexport type StoreFilterOp =\n | \"==\"\n | \"!=\"\n | \"<\"\n | \"<=\"\n | \">\"\n | \">=\"\n | \"in\"\n | \"not-in\"\n | \"contains\";\n\n/** A single filter clause for store queries. */\nexport interface StoreFilter<T> {\n field: keyof T & string;\n op: StoreFilterOp;\n value: unknown;\n}\n\n/**\n * Database abstraction boundary. Services receive `StoreContract<T>`,\n * not raw database clients. Swappable per database engine.\n *\n * @example\n * ```typescript\n * interface LLMRequest { id: string; prompt: string; status: string }\n *\n * class FirestoreLLMRequestStore implements StoreContract<LLMRequest> {\n * async getById(id) { ... }\n * async create(data) { ... }\n * async update(id, data) { ... }\n * async delete(id) { ... }\n * async query(filters) { ... }\n * }\n * ```\n */\nexport interface StoreContract<T extends { id: string }> {\n getById(id: string): Promise<T | null>;\n create(data: Omit<T, \"id\">): Promise<T>;\n update(id: string, data: Partial<T>): Promise<T>;\n delete(id: string): Promise<void>;\n query(filters: StoreFilter<T>[]): Promise<T[]>;\n}\n\n// ============================================================================\n// Lazy Service (Singleton Pattern)\n// ============================================================================\n\n/**\n * Standardized singleton lifecycle. Replaces ad-hoc\n * `let x = null; export function getX()` patterns.\n *\n * @example\n * ```typescript\n * const llmClient = createLazyService(() => new LLMClient({ apiKey: process.env.LLM_KEY }));\n *\n * // In request handler:\n * const client = llmClient.get(); // created on first call, cached after\n *\n * // In test teardown:\n * llmClient.reset(); // next get() creates a fresh instance\n * ```\n */\nexport interface LazyService<T> {\n /** Get the singleton instance (creates on first call). */\n get(): T;\n /** Reset the singleton (next get() creates fresh). For test isolation. */\n reset(): void;\n}\n\n/**\n * Create a lazy singleton from a factory function.\n * \n * Creates a service that lazily initializes on first access and caches the instance.\n * Useful for expensive resources like database connections or API clients.\n * \n * @template T - The type of service to create\n * @param {() => T} factory - Factory function that creates the service instance\n * @returns {LazyService<T>} Lazy service with get() and reset() methods\n * \n * @example\n * const dbService = createLazyService(() => new DatabaseClient(config));\n * const db = dbService.get(); // Initializes on first call\n */\nexport function createLazyService<T>(factory: () => T): LazyService<T> {\n let instance: T | null = null;\n return {\n get(): T {\n if (instance === null) {\n instance = factory();\n }\n return instance;\n },\n reset(): void {\n instance = null;\n },\n };\n}\n","/**\n * Shared Intermediate Representation Types\n *\n * Unified IR types used by both the compiler and runtime.\n * This is the single source of truth for IR structures.\n *\n * @packageDocumentation\n */\n\nimport type { SExpr } from './expression.js';\nimport type { EntityRow, FieldValue } from './entity.js';\nimport type { AnyPatternConfig } from '@almadar/patterns';\n\n// ============================================================================\n// Transition Types\n// ============================================================================\n\n/**\n * Transition source state specification.\n * - string: Single state name (e.g., 'Idle')\n * - '*': Wildcard - matches any current state\n * - string[]: Array of states - matches any of the listed states\n */\nexport type TransitionFrom = string | '*' | string[];\n\n// ============================================================================\n// Field Types\n// ============================================================================\n\nexport interface ResolvedField {\n name: string;\n type: string;\n tsType: string;\n description?: string;\n default?: unknown;\n required: boolean;\n validation?: unknown;\n /** Enum values for enum or constrained string fields */\n values?: string[];\n /** Enum values (alias for values, for compatibility) */\n enumValues?: string[];\n /** Relation configuration for foreign key references */\n relation?: {\n entity: string;\n cardinality?: string;\n field?: string;\n };\n}\n\n// ============================================================================\n// Entity Types\n// ============================================================================\n\nexport interface ResolvedEntity {\n name: string;\n description?: string;\n icon?: string;\n collection: string;\n fields: ResolvedField[];\n\n /** Whether this entity only exists in runtime (not persisted to Firestore) */\n runtime?: boolean;\n\n /** Whether this is a singleton entity (only one instance exists) */\n singleton?: boolean;\n\n /** Whether this entity has pre-authored instances in the schema */\n hasInstances?: boolean;\n\n /** Pre-authored instances from the schema (seed data or static reference data) */\n instances?: EntityRow[];\n\n /** Default field values from schema (for spawning singletons) */\n defaults?: Record<string, FieldValue>;\n\n // Cross-references\n usedByTraits: string[];\n usedByPages: string[];\n}\n\nexport interface ResolvedEntityBinding {\n /** Binding name in code */\n name: string;\n\n /** Entity being bound */\n entity: ResolvedEntity;\n\n /** CRUD operations to generate */\n operations: ('list' | 'get' | 'create' | 'update' | 'delete')[];\n}\n\n// ============================================================================\n// Trait Types\n// ============================================================================\n\nexport interface ResolvedTraitState {\n name: string;\n isInitial: boolean;\n isFinal: boolean;\n}\n\nexport interface ResolvedTraitEvent {\n key: string;\n name: string;\n payload?: Record<string, string>;\n}\n\nexport interface ResolvedTraitTransition {\n /** Source state(s): string, '*' for wildcard, or array of states */\n from: TransitionFrom;\n to: string;\n event: string;\n guard?: SExpr;\n effects: SExpr[];\n}\n\nexport interface ResolvedTraitGuard {\n name: string;\n condition: SExpr;\n}\n\nexport interface ResolvedTraitTick {\n name: string;\n interval: number | 'frame';\n guard?: SExpr;\n effects: SExpr[];\n priority: number;\n appliesTo: string[];\n}\n\nexport interface ResolvedTraitListener {\n event: string;\n triggers: string;\n guard?: SExpr;\n}\n\nexport interface ResolvedTraitDataEntity {\n name: string;\n fields: ResolvedField[];\n runtime: boolean;\n singleton: boolean;\n}\n\n/**\n * UI binding for interaction traits - maps states to presentations\n */\nexport interface ResolvedTraitUIBinding {\n [stateName: string]: {\n /** Presentation type: modal, drawer, popover, inline, confirm-dialog */\n presentation: string;\n /** Content pattern(s) to render */\n content: AnyPatternConfig | AnyPatternConfig[];\n /** Presentation props */\n props?: {\n size?: string;\n position?: string;\n title?: string;\n closable?: boolean;\n width?: string;\n showProgress?: boolean;\n step?: number;\n totalSteps?: number;\n };\n };\n}\n\n/**\n * Fully resolved trait - expanded from schema OR library.\n * The compiler generates code from this structure universally,\n * without knowing which specific trait it is.\n */\nexport interface ResolvedTrait {\n /** Unique trait identifier */\n name: string;\n\n /** Human-readable description */\n description?: string;\n\n /** Where this trait came from */\n source: 'schema' | 'library' | 'inline';\n\n /** Category for organizing traits */\n category?: 'lifecycle' | 'temporal' | 'validation' | 'notification' | 'integration' | 'interaction' | 'agent' |\n 'game-core' | 'game-character' | 'game-ai' | 'game-combat' | 'game-items' | 'game-cards' | 'game-board' | 'game-puzzle';\n\n // State Machine (all optional - not all traits have state machines)\n states: ResolvedTraitState[];\n events: ResolvedTraitEvent[];\n transitions: ResolvedTraitTransition[];\n guards: ResolvedTraitGuard[];\n\n // Behavior\n ticks: ResolvedTraitTick[];\n\n // Communication\n listens: ResolvedTraitListener[];\n\n // Data\n dataEntities: ResolvedTraitDataEntity[];\n\n /**\n * Atom-declared linked entity. The atom (e.g. std-pagination)\n * declares which entity its `@entity.X` bindings resolve against\n * (e.g. `PagedItem`). Distinct from the call-site rebind on\n * `ResolvedTraitBinding.linkedEntity`, which a molecule may use\n * to override the atom's default. Either side may be undefined\n * for traits that don't bind any entity (pure interaction).\n */\n linkedEntity?: string;\n\n /**\n * The trait's DECLARED `config { }` schema (per-field\n * `{ type, default? }`). Drives `@config.X` substitution: each\n * field's `default` seeds the binding context behind any caller-\n * supplied call-site `config: { ... }` override on the trait\n * reference. Authored on the atom; flows through verbatim from\n * `Trait.config`.\n *\n * (Caller-supplied call-site overrides live on the page-trait\n * binding's `config: TraitConfig` — see `ResolvedTraitBinding`.)\n */\n config?: import('./trait.js').DeclaredTraitConfig;\n\n // UI Bindings for interaction traits\n ui?: ResolvedTraitUIBinding;\n}\n\n/**\n * Trait binding on a page - links a resolved trait to the page\n */\nexport interface ResolvedTraitBinding {\n /** Reference name */\n ref?: string;\n\n /** Fully resolved trait */\n trait: ResolvedTrait;\n\n /** Entity this trait operates on (if any) */\n linkedEntity?: string;\n\n /** Instance configuration */\n config?: import('./trait.js').TraitConfig;\n}\n\n// ============================================================================\n// Pattern & Section Types\n// ============================================================================\n\nexport interface ResolvedPattern {\n /** Pattern type (e.g., 'page-header', 'entity-list', 'game-canvas') */\n type: string;\n\n /** Pattern configuration */\n config: AnyPatternConfig;\n\n /** Shell component to use */\n shellComponent?: string;\n}\n\nexport interface ResolvedSectionEvent {\n event: string;\n action: string;\n target?: string;\n}\n\nexport interface ResolvedSection {\n /** Section identifier */\n id: string;\n\n /** Resolved pattern */\n pattern: ResolvedPattern;\n\n /** Events emitted by this section */\n events: ResolvedSectionEvent[];\n\n /** Position in page layout */\n position?: number;\n\n /** Entity binding for this section */\n binding?: ResolvedEntityBinding;\n}\n\n// ============================================================================\n// Page Types\n// ============================================================================\n\nexport interface ResolvedNavigation {\n event?: string;\n from?: string;\n to: string;\n trigger?: string;\n params?: Record<string, string>;\n label?: string;\n path?: string;\n icon?: string;\n}\n\nexport interface ResolvedPage {\n /** Page identifier */\n name: string;\n\n /** URL path */\n path: string;\n\n /** Feature folder name */\n featureName: string;\n\n /** Layout component */\n layout?: string;\n\n /** View type (dashboard, list, detail, create, edit) */\n viewType?: 'dashboard' | 'list' | 'detail' | 'create' | 'edit';\n\n /** Resolved sections */\n sections: ResolvedSection[];\n\n /** Resolved trait bindings */\n traits: ResolvedTraitBinding[];\n\n /** Entity data bindings */\n entityBindings: ResolvedEntityBinding[];\n\n /** Navigation wiring */\n navigation: ResolvedNavigation[];\n\n /** Singleton entities to spawn on this page (runtime singletons) */\n singletonEntities: ResolvedEntity[];\n}\n\n// ============================================================================\n// IR Types\n// ============================================================================\n\n/**\n * Complete resolved IR - all references expanded\n */\nexport interface ResolvedIR {\n /** App name */\n appName: string;\n\n /** App description */\n description?: string;\n\n /** App version */\n version?: string;\n\n /** All resolved entities (Map for lookup) */\n entities: Map<string, ResolvedEntity>;\n\n /** All resolved traits (Map for lookup) */\n traits: Map<string, ResolvedTrait>;\n\n /** All resolved pages (Map for lookup) */\n pages: Map<string, ResolvedPage>;\n\n /** Entity bindings (used for data hook generation) */\n entityBindings: ResolvedEntityBinding[];\n\n /** Raw data entities (used for instance data generation) */\n rawEntities?: unknown[];\n\n /** Generation timestamp */\n generatedAt: string;\n}\n\n// ============================================================================\n// Factory Functions\n// ============================================================================\n\n/**\n * Create an empty resolved trait with defaults\n */\nexport function createEmptyResolvedTrait(name: string, source: 'schema' | 'library' | 'inline'): ResolvedTrait {\n return {\n name,\n source,\n states: [],\n events: [],\n transitions: [],\n guards: [],\n ticks: [],\n listens: [],\n dataEntities: [],\n };\n}\n\n/**\n * Create an empty resolved page with defaults\n */\nexport function createEmptyResolvedPage(name: string): ResolvedPage {\n return {\n name,\n path: `/${name.toLowerCase()}`,\n featureName: name.toLowerCase(),\n sections: [],\n traits: [],\n entityBindings: [],\n navigation: [],\n singletonEntities: [],\n };\n}\n\n/**\n * Infer TypeScript type from schema type\n */\nexport function inferTsType(schemaType: string): string {\n const typeMap: Record<string, string> = {\n string: 'string',\n number: 'number',\n boolean: 'boolean',\n date: 'Date',\n datetime: 'Date',\n timestamp: 'number',\n array: 'unknown[]',\n object: 'Record<string, unknown>',\n any: 'unknown',\n };\n\n // Handle array types like \"string[]\"\n if (schemaType.endsWith('[]')) {\n const baseType = schemaType.slice(0, -2);\n return `${typeMap[baseType] || baseType}[]`;\n }\n\n // Handle the typed-map form `Map<K,V>` (the orbital `Map K V` type) →\n // `Record<K, V>`. Mirrors the Rust `parse_payload_field_type` map branch so\n // TS-land type derivation agrees with codegen. Key is comma-free (split on\n // the first comma; value may itself be `Map<…>`).\n if (schemaType.startsWith('Map<') && schemaType.endsWith('>')) {\n const inner = schemaType.slice(4, -1);\n const comma = inner.indexOf(',');\n if (comma !== -1) {\n const key = inferTsType(inner.slice(0, comma).trim());\n const value = inferTsType(inner.slice(comma + 1).trim());\n return `Record<${key}, ${value}>`;\n }\n }\n\n return typeMap[schemaType] || schemaType;\n}\n\n/**\n * Create a resolved field with TypeScript type inference\n */\nexport function createResolvedField(field: {\n name: string;\n type: string;\n description?: string;\n default?: unknown;\n required?: boolean;\n validation?: unknown;\n values?: string[];\n}): ResolvedField {\n return {\n name: field.name,\n type: field.type,\n tsType: inferTsType(field.type),\n description: field.description,\n default: field.default,\n required: field.required ?? false,\n validation: field.validation,\n values: field.values,\n };\n}\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\n/**\n * Type guard to check if an object is a ResolvedIR.\n * \n * Validates that an unknown value conforms to the ResolvedIR structure.\n * Checks for required properties and correct types. Used for runtime\n * type checking and validation.\n * \n * @param {unknown} ir - Value to check\n * @returns {boolean} True if value is ResolvedIR, false otherwise\n * \n * @example\n * if (isResolvedIR(schema)) {\n * // Type-safe access to ResolvedIR properties\n * console.log('Valid IR:', schema.appName);\n * }\n */\nexport function isResolvedIR(ir: unknown): ir is ResolvedIR {\n if (!ir || typeof ir !== 'object') return false;\n const r = ir as ResolvedIR;\n return typeof r.appName === 'string' && r.traits instanceof Map && r.pages instanceof Map;\n}\n","/**\n * JSON primitives — the universal \"data crossed a boundary\" type.\n *\n * Every value that arrives over the wire from an LLM (tool-call args),\n * from disk (workspace files), or from an HTTP body before\n * domain-specific validation is a `JsonValue`. Narrow with a typed\n * predicate (`is`-guard) at the boundary; don't widen back to `unknown`.\n *\n * `JsonObject` and `ToolArgs` are aliases for the common\n * `Record<string, JsonValue>` shape. `ToolArgs` is the name the\n * agent surface uses for LLM-emitted tool-call arguments; `JsonObject`\n * is the general-purpose alias. They are the same type — the alias\n * exists so call sites read at the right semantic level.\n *\n * Why not `Record<string, unknown>`? Two reasons. (1) `unknown` widens\n * back to anything, which defeats the purpose of typing the boundary.\n * (2) The `@almadar/eslint-plugin/no-record-string-unknown` rule blocks\n * the wider form — `JsonValue`-based records are the typed answer.\n *\n * @packageDocumentation\n */\n\n/**\n * Recursive JSON value union — every shape JSON can carry.\n */\nexport type JsonValue =\n | string\n | number\n | boolean\n | null\n | JsonValue[]\n | { [key: string]: JsonValue };\n\n/**\n * JSON object — keyed string→JsonValue. The wire form of arbitrary\n * structured data. Replaces `Record<string, unknown>` at typed\n * boundaries (LLM emits, file reads, HTTP bodies).\n */\nexport type JsonObject = { [key: string]: JsonValue };\n\n/**\n * LLM tool-call arguments — same shape as `JsonObject`, named for the\n * agent-surface call site. Each tool's `execute(args: ToolArgs)`\n * receives this and narrows via an `is`-guard predicate before any\n * field access.\n */\nexport type ToolArgs = JsonObject;\n\n/**\n * Type guard: is the given value a JSON primitive (non-array,\n * non-object)? Used by walkers that decide whether to recurse.\n */\nexport function isJsonPrimitive(\n value: JsonValue,\n): value is string | number | boolean | null {\n return (\n value === null\n || typeof value === 'string'\n || typeof value === 'number'\n || typeof value === 'boolean'\n );\n}\n\n/**\n * Type guard: is the given value a JSON object (non-array, non-null)?\n */\nexport function isJsonObject(value: JsonValue): value is JsonObject {\n return (\n value !== null\n && typeof value === 'object'\n && !Array.isArray(value)\n );\n}\n\n/**\n * Type guard: is the given value a JSON array?\n */\nexport function isJsonArray(value: JsonValue): value is JsonValue[] {\n return Array.isArray(value);\n}\n","/**\n * Validation error types — the shape emitted by every\n * `.orb` / `.lolo` validator pass.\n *\n * `ValidationError` is the wire shape: `{ code, path, message, suggestion? }`.\n * `code` is `ValidationErrorCode`, which is an OPEN `string` to let the\n * Rust validator emit new codes without an `@almadar/core` rev. The\n * `KNOWN_VALIDATION_ERROR_CODES` const documents the codes currently\n * emitted by the validator + lolo lower pipeline (extracted from\n * `orbital-rust/crates/orbital-compiler/src/phases/validation/` +\n * `orbital-rust/crates/orbital-lolo/src/`).\n *\n * Consumers that want to narrow a code to the closed known set use\n * `KnownValidationErrorCode`:\n *\n * ```ts\n * if (err.code in KNOWN_VALIDATION_ERROR_CODES) {\n * // err.code is now narrowable to KnownValidationErrorCode for\n * // exhaustive switch handling.\n * }\n * ```\n *\n * @packageDocumentation\n */\n\n/**\n * One validation diagnostic emitted by the validator / lolo lower pipeline.\n *\n * - `code`: machine-readable identifier (see `KNOWN_VALIDATION_ERROR_CODES`).\n * - `path`: JSON pointer-like path into the failing schema location,\n * e.g. `'orbitals[0].traits[2].stateMachine.transitions[1].effects[0]'`.\n * - `message`: human-readable description of the failure.\n * - `suggestion`: optional hint the validator may add to help the\n * author / LLM fix the issue.\n */\nexport interface ValidationError {\n code: ValidationErrorCode;\n path: string;\n message: string;\n suggestion?: string;\n}\n\n/**\n * Validation error code — open `string` for forward-compat with the\n * Rust validator's evolving code set. Narrow to the closed known set\n * via `KnownValidationErrorCode` when exhaustive handling is needed.\n */\nexport type ValidationErrorCode = string;\n\n/**\n * The result of a single validator pass: a boolean verdict plus the errors\n * and warnings (the validator wire shape, `ValidationError`).\n *\n * Distinct from `ValidationResults` (app.ts): that is the Firestore-persisted\n * app-document shape keyed on `ValidationIssue` (with `severity` + array path\n * + `validatedAt`). This `ValidationResult` is the in-process pass result keyed\n * on `ValidationError` (code + JSON-pointer string path + `suggestion`).\n * `ok === true` iff there are zero errors AND zero warnings.\n */\nexport interface ValidationResult {\n ok: boolean;\n errors: ValidationError[];\n warnings: ValidationError[];\n}\n\n/**\n * Closed set of validation codes the Rust validator + lolo lower\n * pipeline currently emit. Source-tagged: codes are extracted from\n * `orbital-rust/crates/orbital-compiler/src/phases/validation/**.rs`\n * and `orbital-rust/crates/orbital-lolo/src/**.rs`. Keep this in sync\n * with the Rust side; mismatches are caught by the Rust validator's\n * own unit tests, which assert the emitted code-set matches an\n * exported manifest.\n *\n * Categories (prefix → meaning):\n * - `ORB_BINDING_*` — binding (`@entity.X`, `@payload.Y`, ...) issues\n * - `ORB_E_*` / `ORB_EFF_*` / `ORB_EMIT_*` — entity / effect / emit\n * - `ORB_GEN_*` — generic / cross-cutting structure\n * - `ORB_O_*` / `ORB_P_*` / `ORB_S_*` / `ORB_SM_*` / `ORB_T_*` —\n * orbital / page / schema / state-machine / trait\n * - `ORB_QUERY_*` — query / search behaviors\n * - `ORB_RUI_*` — render-UI binding + prop validation\n * - `ORB_SLOT_*` — UI-slot conflict / contention\n * - `ORB_SVC_*` / `ORB_UI_*` — service / UI primitives\n * - `ORB_X_*` — cross-orbital constraints (listens, emits, IDs)\n */\nexport const KNOWN_VALIDATION_ERROR_CODES = {\n // Binding (`@entity.X`, `@payload.Y`, `@state.Z`, `@now`, ...)\n ORB_BINDING_ENTITY_FIELD_NEVER_SET: 'ORB_BINDING_ENTITY_FIELD_NEVER_SET',\n ORB_BINDING_ENTITY_FIELD_NOT_FOUND: 'ORB_BINDING_ENTITY_FIELD_NOT_FOUND',\n ORB_BINDING_INVALID_FIELD_NAME: 'ORB_BINDING_INVALID_FIELD_NAME',\n ORB_BINDING_INVALID_FORMAT: 'ORB_BINDING_INVALID_FORMAT',\n ORB_BINDING_INVALID_PATH: 'ORB_BINDING_INVALID_PATH',\n ORB_BINDING_NOW_NO_PATH: 'ORB_BINDING_NOW_NO_PATH',\n ORB_BINDING_PAYLOAD_FIELD_UNDECLARED: 'ORB_BINDING_PAYLOAD_FIELD_UNDECLARED',\n ORB_BINDING_PAYLOAD_IN_TICK: 'ORB_BINDING_PAYLOAD_IN_TICK',\n ORB_BINDING_PAYLOAD_TYPE_INCOMPATIBLE: 'ORB_BINDING_PAYLOAD_TYPE_INCOMPATIBLE',\n ORB_BINDING_SET_TARGET_MISSING_PATH: 'ORB_BINDING_SET_TARGET_MISSING_PATH',\n ORB_BINDING_STATE_NO_PATH: 'ORB_BINDING_STATE_NO_PATH',\n ORB_BINDING_TRAIT_CYCLE: 'ORB_BINDING_TRAIT_CYCLE',\n ORB_BINDING_TRAIT_INVALID_FORMAT: 'ORB_BINDING_TRAIT_INVALID_FORMAT',\n ORB_BINDING_TRAIT_INVALID_POSITION: 'ORB_BINDING_TRAIT_INVALID_POSITION',\n ORB_BINDING_TRAIT_MISSING_NAME: 'ORB_BINDING_TRAIT_MISSING_NAME',\n ORB_BINDING_TRAIT_SELF_REFERENCE: 'ORB_BINDING_TRAIT_SELF_REFERENCE',\n ORB_BINDING_TRAIT_UNKNOWN: 'ORB_BINDING_TRAIT_UNKNOWN',\n ORB_BINDING_UNKNOWN_ENTITY: 'ORB_BINDING_UNKNOWN_ENTITY',\n ORB_BINDING_UNKNOWN_ROOT: 'ORB_BINDING_UNKNOWN_ROOT',\n\n // Entity / field\n ORB_E_DUPLICATE_FIELD: 'ORB_E_DUPLICATE_FIELD',\n ORB_E_EMPTY_ENUM_VALUES: 'ORB_E_EMPTY_ENUM_VALUES',\n ORB_E_INVALID_FIELD_NAME: 'ORB_E_INVALID_FIELD_NAME',\n ORB_E_INVALID_FIELD_TYPE: 'ORB_E_INVALID_FIELD_TYPE',\n ORB_E_INVALID_RELATION: 'ORB_E_INVALID_RELATION',\n ORB_E_LITERAL_UNION_DEFAULT_MISMATCH: 'ORB_E_LITERAL_UNION_DEFAULT_MISMATCH',\n ORB_E_MISSING_COLLECTION: 'ORB_E_MISSING_COLLECTION',\n ORB_E_MISSING_NAME: 'ORB_E_MISSING_NAME',\n ORB_E_NO_FIELDS: 'ORB_E_NO_FIELDS',\n\n // Effect / emit\n ORB_EFF_CALL_SERVICE_MISSING_ACTION: 'ORB_EFF_CALL_SERVICE_MISSING_ACTION',\n ORB_EFF_CALL_SERVICE_MISSING_HANDLERS: 'ORB_EFF_CALL_SERVICE_MISSING_HANDLERS',\n ORB_EFF_CALL_SERVICE_MISSING_SERVICE: 'ORB_EFF_CALL_SERVICE_MISSING_SERVICE',\n ORB_EFF_EMIT_INVALID_NAME: 'ORB_EFF_EMIT_INVALID_NAME',\n ORB_EFF_EMIT_KEY_INVALID: 'ORB_EFF_EMIT_KEY_INVALID',\n ORB_EFF_EMIT_UNDECLARED_EVENT: 'ORB_EFF_EMIT_UNDECLARED_EVENT',\n ORB_EFF_FETCH_INVALID_ENTITY: 'ORB_EFF_FETCH_INVALID_ENTITY',\n ORB_EFF_FETCH_INVALID_INCLUDE: 'ORB_EFF_FETCH_INVALID_INCLUDE',\n ORB_EFF_MISSING_FETCH_FOR_ENTITY: 'ORB_EFF_MISSING_FETCH_FOR_ENTITY',\n ORB_EFF_MISSING_REQUIRED_EMIT: 'ORB_EFF_MISSING_REQUIRED_EMIT',\n ORB_EFF_NAVIGATE_MISSING_PAYLOAD: 'ORB_EFF_NAVIGATE_MISSING_PAYLOAD',\n ORB_EFF_NAVIGATE_TARGET_UNREACHABLE: 'ORB_EFF_NAVIGATE_TARGET_UNREACHABLE',\n ORB_EFF_SET_INVALID_BINDING: 'ORB_EFF_SET_INVALID_BINDING',\n ORB_EFF_SET_PAYLOAD_NOT_ALLOWED: 'ORB_EFF_SET_PAYLOAD_NOT_ALLOWED',\n ORB_EFF_SLOT_CONFLICT: 'ORB_EFF_SLOT_CONFLICT',\n ORB_EFF_UNKNOWN_TYPE: 'ORB_EFF_UNKNOWN_TYPE',\n ORB_EMIT_DECLARED_BUT_UNFIRED: 'ORB_EMIT_DECLARED_BUT_UNFIRED',\n ORB_EMIT_PAYLOAD_EXTRA_FIELD: 'ORB_EMIT_PAYLOAD_EXTRA_FIELD',\n ORB_EMIT_PAYLOAD_FIELD_TYPE_MISMATCH: 'ORB_EMIT_PAYLOAD_FIELD_TYPE_MISMATCH',\n ORB_EMIT_PAYLOAD_MISSING_REQUIRED: 'ORB_EMIT_PAYLOAD_MISSING_REQUIRED',\n ORB_EMIT_SUCCESS_PAYLOAD_RETURN_MISMATCH: 'ORB_EMIT_SUCCESS_PAYLOAD_RETURN_MISMATCH',\n\n // Generic / cross-cutting structure\n ORB_GEN_DUPLICATE: 'ORB_GEN_DUPLICATE',\n ORB_GEN_INVALID_REFERENCE: 'ORB_GEN_INVALID_REFERENCE',\n ORB_GEN_INVALID_VALUE: 'ORB_GEN_INVALID_VALUE',\n ORB_GEN_MISSING_FIELD: 'ORB_GEN_MISSING_FIELD',\n\n // Orbital\n ORB_O_MISSING_PAGES: 'ORB_O_MISSING_PAGES',\n\n // Page\n ORB_P_DUPLICATE_PATH: 'ORB_P_DUPLICATE_PATH',\n ORB_P_EMPTY_TRAITS: 'ORB_P_EMPTY_TRAITS',\n ORB_P_INVALID_PATH: 'ORB_P_INVALID_PATH',\n ORB_P_INVALID_TRAIT_REF: 'ORB_P_INVALID_TRAIT_REF',\n ORB_P_INVALID_VIEW_TYPE: 'ORB_P_INVALID_VIEW_TYPE',\n ORB_P_MISSING_NAME: 'ORB_P_MISSING_NAME',\n ORB_P_MISSING_PATH: 'ORB_P_MISSING_PATH',\n ORB_P_MISSING_TRAITS: 'ORB_P_MISSING_TRAITS',\n ORB_P_SECTIONS_FORBIDDEN: 'ORB_P_SECTIONS_FORBIDDEN',\n\n // Query / search behaviors\n ORB_QUERY_MISSING_RECOMMENDED: 'ORB_QUERY_MISSING_RECOMMENDED',\n ORB_QUERY_MISSING_SEARCH: 'ORB_QUERY_MISSING_SEARCH',\n ORB_QUERY_UNKNOWN_SINGLETON: 'ORB_QUERY_UNKNOWN_SINGLETON',\n ORB_QUERY_UNSUPPORTED_PATTERN: 'ORB_QUERY_UNSUPPORTED_PATTERN',\n ORB_QUERY_UNUSED_SINGLETON: 'ORB_QUERY_UNUSED_SINGLETON',\n\n // Render-UI binding + prop validation\n ORB_RUI_BINDING_TYPE_MISMATCH: 'ORB_RUI_BINDING_TYPE_MISMATCH',\n ORB_RUI_ELEMENT_SHAPE_MISMATCH: 'ORB_RUI_ELEMENT_SHAPE_MISMATCH',\n ORB_RUI_EVENT_BINDING_PAYLOAD_MISMATCH: 'ORB_RUI_EVENT_BINDING_PAYLOAD_MISMATCH',\n ORB_RUI_INVALID_FIELD_PATH: 'ORB_RUI_INVALID_FIELD_PATH',\n ORB_RUI_INVALID_ITEM_ACTION: 'ORB_RUI_INVALID_ITEM_ACTION',\n ORB_RUI_INVALID_PATTERN: 'ORB_RUI_INVALID_PATTERN',\n ORB_RUI_INVALID_PROP: 'ORB_RUI_INVALID_PROP',\n ORB_RUI_INVALID_SLOT: 'ORB_RUI_INVALID_SLOT',\n ORB_RUI_MISSING_ACTION: 'ORB_RUI_MISSING_ACTION',\n ORB_RUI_MISSING_PATTERN_TYPE: 'ORB_RUI_MISSING_PATTERN_TYPE',\n ORB_RUI_MISSING_REQUIRED_PROP: 'ORB_RUI_MISSING_REQUIRED_PROP',\n ORB_RUI_PROP_TYPE_MISMATCH: 'ORB_RUI_PROP_TYPE_MISMATCH',\n ORB_RUI_UNKNOWN_ITEM_ACTION_PROP: 'ORB_RUI_UNKNOWN_ITEM_ACTION_PROP',\n\n // Schema-level\n ORB_S_EMPTY_VERSION: 'ORB_S_EMPTY_VERSION',\n ORB_S_MISSING_NAME: 'ORB_S_MISSING_NAME',\n ORB_S_NO_ORBITALS: 'ORB_S_NO_ORBITALS',\n\n // UI slots\n ORB_SLOT_CONTENTION: 'ORB_SLOT_CONTENTION',\n ORB_SLOT_CONTENTION_RUNTIME: 'ORB_SLOT_CONTENTION_RUNTIME',\n ORB_SLOT_HUD_NON_GAME: 'ORB_SLOT_HUD_NON_GAME',\n ORB_SLOT_INVALID_NAME: 'ORB_SLOT_INVALID_NAME',\n ORB_SLOT_INVALID_NESTING: 'ORB_SLOT_INVALID_NESTING',\n ORB_SLOT_MAIN_NOT_COVERED: 'ORB_SLOT_MAIN_NOT_COVERED',\n ORB_SLOT_PRIORITY_CONFLICT: 'ORB_SLOT_PRIORITY_CONFLICT',\n\n // Service\n ORB_SVC_DUPLICATE_NAME: 'ORB_SVC_DUPLICATE_NAME',\n ORB_SVC_INVALID_INTEGRATOR: 'ORB_SVC_INVALID_INTEGRATOR',\n ORB_SVC_INVALID_URL: 'ORB_SVC_INVALID_URL',\n ORB_SVC_MISSING_BASE_URL: 'ORB_SVC_MISSING_BASE_URL',\n ORB_SVC_MISSING_CAPABILITIES: 'ORB_SVC_MISSING_CAPABILITIES',\n ORB_SVC_MISSING_EVENTS: 'ORB_SVC_MISSING_EVENTS',\n ORB_SVC_MISSING_SERVER_PATH: 'ORB_SVC_MISSING_SERVER_PATH',\n ORB_SVC_RESERVED_EVENT: 'ORB_SVC_RESERVED_EVENT',\n ORB_SVC_UNKNOWN_TYPE: 'ORB_SVC_UNKNOWN_TYPE',\n\n // Trait\n ORB_T_CONFIG_OBJECT_ARRAY_FORBIDDEN: 'ORB_T_CONFIG_OBJECT_ARRAY_FORBIDDEN',\n ORB_T_CONFIG_SHAPE_MISMATCH: 'ORB_T_CONFIG_SHAPE_MISMATCH',\n ORB_T_CONFIG_TIER_INVALID: 'ORB_T_CONFIG_TIER_INVALID',\n ORB_T_DEPRECATED_UI: 'ORB_T_DEPRECATED_UI',\n ORB_T_DUPLICATE_NAME: 'ORB_T_DUPLICATE_NAME',\n ORB_T_DUPLICATE_STATE: 'ORB_T_DUPLICATE_STATE',\n ORB_T_DUPLICATE_TRANSITION: 'ORB_T_DUPLICATE_TRANSITION',\n ORB_T_ENTITY_NAME_SHADOWS_TRAIT_UNION: 'ORB_T_ENTITY_NAME_SHADOWS_TRAIT_UNION',\n ORB_T_EVENT_TYPE_WRONG_KIND: 'ORB_T_EVENT_TYPE_WRONG_KIND',\n ORB_T_EVT_DUPLICATE: 'ORB_T_EVT_DUPLICATE',\n ORB_T_EVT_EXTERNAL_MISSING_PAYLOAD: 'ORB_T_EVT_EXTERNAL_MISSING_PAYLOAD',\n ORB_T_EVT_INVALID_NAME: 'ORB_T_EVT_INVALID_NAME',\n ORB_T_EVT_SCOPE_MISMATCH: 'ORB_T_EVT_SCOPE_MISMATCH',\n ORB_T_EVT_TICK_UNDECLARED: 'ORB_T_EVT_TICK_UNDECLARED',\n ORB_T_EVT_UNDECLARED: 'ORB_T_EVT_UNDECLARED',\n ORB_T_INIT_MISSING_FETCH: 'ORB_T_INIT_MISSING_FETCH',\n ORB_T_INVALID_CATEGORY: 'ORB_T_INVALID_CATEGORY',\n ORB_T_INVALID_FORMAT: 'ORB_T_INVALID_FORMAT',\n ORB_T_INVALID_PATTERN_DEFAULT: 'ORB_T_INVALID_PATTERN_DEFAULT',\n ORB_T_INVALID_SLOT_DEFAULT: 'ORB_T_INVALID_SLOT_DEFAULT',\n ORB_T_INVALID_TRANSITION: 'ORB_T_INVALID_TRANSITION',\n ORB_T_MISSING_INIT_TRANSITION: 'ORB_T_MISSING_INIT_TRANSITION',\n ORB_T_MISSING_RENDER_UI: 'ORB_T_MISSING_RENDER_UI',\n ORB_T_MULTIPLE_INITIAL_STATES: 'ORB_T_MULTIPLE_INITIAL_STATES',\n ORB_T_NO_INITIAL_STATE: 'ORB_T_NO_INITIAL_STATE',\n ORB_T_TYPE_ANNOTATION_MISMATCH: 'ORB_T_TYPE_ANNOTATION_MISMATCH',\n ORB_T_TYPE_COMPOSITION_CONFLICT: 'ORB_T_TYPE_COMPOSITION_CONFLICT',\n ORB_T_TYPE_CYCLE: 'ORB_T_TYPE_CYCLE',\n ORB_T_TYPE_KIND_MISMATCH: 'ORB_T_TYPE_KIND_MISMATCH',\n ORB_T_TYPE_UNKNOWN: 'ORB_T_TYPE_UNKNOWN',\n ORB_T_TYPE_UNKNOWN_PARAM: 'ORB_T_TYPE_UNKNOWN_PARAM',\n ORB_T_TYPE_WRONG_ARG_COUNT: 'ORB_T_TYPE_WRONG_ARG_COUNT',\n ORB_T_UNDEFINED_EVENT: 'ORB_T_UNDEFINED_EVENT',\n ORB_T_UNDEFINED_TRAIT: 'ORB_T_UNDEFINED_TRAIT',\n\n // UI primitives (icons, etc.)\n ORB_UI_ICON_EMPTY: 'ORB_UI_ICON_EMPTY',\n ORB_UI_ICON_INVALID_FORMAT: 'ORB_UI_ICON_INVALID_FORMAT',\n ORB_UI_ICON_NOT_FOUND: 'ORB_UI_ICON_NOT_FOUND',\n\n // Cross-orbital constraints (listens, emits, IDs, payloads)\n ORB_X_CIRCULAR_DEPENDENCY: 'ORB_X_CIRCULAR_DEPENDENCY',\n ORB_X_CROSS_EMITTER_DECLARED_PAYLOAD_MISMATCH: 'ORB_X_CROSS_EMITTER_DECLARED_PAYLOAD_MISMATCH',\n ORB_X_DUPLICATE_ENTITY: 'ORB_X_DUPLICATE_ENTITY',\n ORB_X_EVENT_COLLISION: 'ORB_X_EVENT_COLLISION',\n ORB_X_INTERNAL_EVENT_EXPOSED: 'ORB_X_INTERNAL_EVENT_EXPOSED',\n ORB_X_LISTEN_SOURCE_UNRESOLVED: 'ORB_X_LISTEN_SOURCE_UNRESOLVED',\n ORB_X_MISSING_ORBITAL_NAME: 'ORB_X_MISSING_ORBITAL_NAME',\n ORB_X_ORPHAN_LISTENER: 'ORB_X_ORPHAN_LISTENER',\n ORB_X_PAYLOAD_MISMATCH: 'ORB_X_PAYLOAD_MISMATCH',\n ORB_X_RENDER_UI_EVENT_LITERAL_STALE: 'ORB_X_RENDER_UI_EVENT_LITERAL_STALE',\n ORB_X_UNRESOLVED_PATTERN_FIELD_REF: 'ORB_X_UNRESOLVED_PATTERN_FIELD_REF',\n ORB_X_UNUSED_EMISSION: 'ORB_X_UNUSED_EMISSION',\n} as const;\n\n/**\n * Narrow union of the codes documented in `KNOWN_VALIDATION_ERROR_CODES`.\n * Use this in exhaustive `switch` handlers; use the broader\n * `ValidationErrorCode` (open `string`) anywhere a fresh validator-side\n * code could plausibly arrive.\n */\nexport type KnownValidationErrorCode =\n typeof KNOWN_VALIDATION_ERROR_CODES[keyof typeof KNOWN_VALIDATION_ERROR_CODES];\n\n/**\n * Type guard: is the given code a known one? After the guard returns\n * true, the code can be narrowed to `KnownValidationErrorCode` via a\n * separate cast, because the type system can't track `in` against\n * `as const` records without an explicit narrowing helper.\n */\nexport function isKnownValidationErrorCode(\n code: ValidationErrorCode,\n): boolean {\n return code in KNOWN_VALIDATION_ERROR_CODES;\n}\n","/**\n * Living Orbital Schema — Golden Data Structure type system.\n *\n * The Living layer treats an `OrbitalSchema` as a heterogeneous attributed\n * graph: every vertex (orbital, entity, trait, state, transition, page, field,\n * event, effect, config-knob) carries a `SemanticAnnotation` + an embedding\n * vector, and the whole object can embed / validate / compile / similarity-\n * search / evolve itself. These are the canonical TYPE definitions shared by\n * the masar (Python) implementation and any TS implementation (rabit, Phase 5);\n * the numeric implementation lives outside @almadar/core.\n *\n * See `docs/Almadar_Masar_Golden_Data_Structure.md` §II/§III/§VIII. Existing\n * core vocabulary is reused, never re-defined: `SchemaChange`/`SemanticChangeKind`\n * (changeset.ts) back the evolution delta, `ValidationError`/`ValidationResult`\n * (validation.ts) back `validate()`, and the per-vertex payloads ARE the existing\n * structural types.\n *\n * @packageDocumentation\n */\n\nimport type { OrbitalSchema } from \"./schema.js\";\nimport type { OrbitalDefinition } from \"./orbital.js\";\nimport type { Entity } from \"./entity.js\";\nimport type { EntityField } from \"./field.js\";\nimport type { Trait, TraitConfigValue, ConfigFieldDeclaration } from \"./trait.js\";\nimport type { State, Transition, Event } from \"./state-machine.js\";\nimport type { Page } from \"./page.js\";\nimport type { Effect } from \"./effect.js\";\nimport type { SExpr, EvalContext, EventPayload } from \"./expression.js\";\nimport type { SchemaChange } from \"./changeset.js\";\nimport type { ValidationError, ValidationResult } from \"./validation.js\";\n// Type-only import (erased at build): no runtime cycle even though factory/\n// imports from types/. `AnnotationTier` is the documented superset of this.\nimport type { FactoryConfigTier } from \"../factory/types.js\";\n\n// ============================================================================\n// Semantic annotation (the NL → typed bridge)\n// ============================================================================\n\n/**\n * Decision-kind tier for the annotation layer. SUPERSET of the validator-\n * enforced `FactoryConfigTier` (`domain`/`policy`/`infra`/`presentation`/\n * `internal`), adding `essential` and `customization` for non-knob (event)\n * vertices that still carry the old vocabulary. Every `FactoryConfigTier`\n * value must be a member so `widenTier` stays a valid identity widen.\n */\nexport type AnnotationTier =\n | \"essential\"\n | \"domain\"\n | \"policy\"\n | \"infra\"\n | \"presentation\"\n | \"customization\"\n | \"internal\";\n\n/** Widen a knob's `FactoryConfigTier` into the annotation-layer `AnnotationTier`. */\nexport function widenTier(tier: FactoryConfigTier): AnnotationTier {\n return tier;\n}\n\n/**\n * The natural-language metadata attached to every living vertex — the text that\n * gets embedded for `similar()`/`match_intent()`. Today these four members live\n * scattered inline across core types (`EntityField.description`/`synonyms`,\n * `Event`/`TraitEventContract`.`description`/`synonyms`/`tier`,\n * `FactoryConfigParam.label`/`description`/`synonyms`/`tier`); `SemanticAnnotation`\n * is the uniform bundle of them, generalized to every vertex.\n */\nexport interface SemanticAnnotation {\n description: string;\n synonyms: string[];\n label: string;\n tier: AnnotationTier;\n}\n\n// ============================================================================\n// ML scalar/vector aliases\n// ============================================================================\n\n/**\n * A dense semantic embedding. In-memory form is `Float32Array`; the at-rest\n * JSON form (e.g. rabit's `knob-embeddings.json`) is `number[]`.\n */\nexport type SemanticVector = Float32Array;\n\n/** A probability in `[0, 1]`. */\nexport type Probability = number;\n\n/** Whether a semantic gate's transition is open, closed, or ~0.5 ambiguous. */\nexport type GateState = \"open\" | \"closed\" | \"ambiguous\";\n\n// ============================================================================\n// Graph vertex / edge typing\n// ============================================================================\n\n/** The typed vertex kinds of the living attributed graph (§II.1 `V_*`). */\nexport type VertexType =\n | \"orbital\"\n | \"entity\"\n | \"trait\"\n | \"state\"\n | \"transition\"\n | \"page\"\n | \"field\"\n | \"event\"\n | \"effect\"\n | \"value\";\n\n/**\n * A stable, structural, embedding-independent vertex id (path style, e.g.\n * `orb:Cart/trt:AddItem/st:Open`). Re-embedding never changes it.\n */\nexport type VertexId = string;\n\n/** The typed directed edge kinds of the living attributed graph (§II.1 `E_*`). */\nexport type EdgeType =\n | \"belongs_to\"\n | \"has_trait\"\n | \"has_state\"\n | \"has_transition\"\n | \"from_state\"\n | \"to_state\"\n | \"on_event\"\n | \"emits\"\n | \"listens\"\n | \"cross_orbital\"\n | \"has_effect\"\n | \"effect_seq\"\n | \"data_flow\"\n | \"ref_in_effect\"\n | \"has_page\"\n | \"has_field\"\n | \"ref\";\n\n/**\n * An effect vertex's payload. Effects are positional S-expression tuples\n * (`Effect`), so the synthesized coordinates (operator, owning transition,\n * positional index) carry the addressing the raw tuple lacks.\n */\nexport interface EffectPayload {\n sexpr: Effect;\n operator: string;\n transitionId: VertexId;\n index: number;\n}\n\n/**\n * A config-knob vertex's payload — joins a `Trait.config` dict key with its\n * declaration (no single core type carries both).\n */\nexport interface KnobPayload {\n name: string;\n declaration: ConfigFieldDeclaration;\n traitId: VertexId;\n}\n\n/** The union of every kind of vertex payload (the existing structural types). */\nexport type VertexPayload =\n | OrbitalDefinition\n | Entity\n | Trait\n | State\n | Transition\n | Page\n | EntityField\n | Event\n | EffectPayload\n | KnobPayload;\n\n/**\n * One vertex of the living graph: a structural payload plus its annotation and\n * embedding. Identity is `id` (structural); annotation/embedding are derived.\n */\nexport interface LivingVertex<P extends VertexPayload = VertexPayload> {\n id: VertexId;\n vtype: VertexType;\n payload: P;\n annotation: SemanticAnnotation;\n /** Lazily populated — undefined until the schema's `embed()` runs. */\n embedding?: SemanticVector;\n}\n\nexport type LivingOrbital = LivingVertex<OrbitalDefinition>;\nexport type LivingEntity = LivingVertex<Entity>;\nexport type LivingTrait = LivingVertex<Trait>;\nexport type LivingState = LivingVertex<State>;\nexport type LivingTransition = LivingVertex<Transition>;\nexport type LivingPage = LivingVertex<Page>;\nexport type LivingField = LivingVertex<EntityField>;\nexport type LivingEvent = LivingVertex<Event>;\nexport type LivingEffect = LivingVertex<EffectPayload>;\nexport type LivingValue = LivingVertex<KnobPayload>;\n\n/**\n * One directed edge. `via` carries the transition vertex for the ternary\n * `has_transition(from, via, to)` decomposition; `seq` carries the ordering for\n * `effect_seq`.\n */\nexport interface LivingEdge {\n etype: EdgeType;\n src: VertexId;\n dst: VertexId;\n via?: VertexId;\n seq?: number;\n}\n\n// ============================================================================\n// Evolution + lineage (composes changeset.ts vocabulary)\n// ============================================================================\n\n/**\n * A single evolution step over the living graph. `modified` reuses the canonical\n * `SchemaChange` (changeset.ts) rather than inventing a parallel operation enum;\n * `intent` is the natural-language delta that caused the change.\n */\nexport interface EvolutionDelta {\n added: VertexId[];\n removed: VertexId[];\n modified: SchemaChange[];\n intent: string;\n}\n\n/** One immutable entry in a living schema's evolution lineage (§6.2). */\nexport interface LineageEntry {\n root: string;\n parent: string;\n delta: EvolutionDelta;\n intent: string;\n time: number;\n valid: boolean;\n}\n\n// ============================================================================\n// Effect-simulation results\n// ============================================================================\n\n/** The result of simulating one effect's S-expression (§4.6) — pure, no I/O. */\nexport interface EffectResult {\n result: SExpr;\n sideEffects: string[];\n emittedEvents: string[];\n}\n\n// ============================================================================\n// The living schema contract (§VIII) — implemented by masar (Python) + rabit (TS)\n// ============================================================================\n\n/**\n * The operation surface of a living orbital schema. This interface is the shared\n * CONTRACT; the numeric implementation (embedding, cosine, validator shelling)\n * is language-specific. `compile()` is the bridge back to the canonical\n * `OrbitalSchema` (the ML surface — annotations beyond `description`, embeddings,\n * gates — is stripped).\n */\nexport interface LivingOrbitalSchema {\n // Orbital container\n orbitals: LivingOrbital[];\n addOrbital(name: string): LivingOrbital;\n removeOrbital(name: string): void;\n getOrbital(name: string): LivingOrbital;\n\n // Semantic layer\n annotations: Map<VertexId, SemanticAnnotation>;\n embeddings: Map<VertexId, SemanticVector>;\n\n // Structural operations\n embed(): void;\n compile(): OrbitalSchema;\n validate(): ValidationResult;\n\n // Semantic retrieval\n similar(query: string | SemanticVector, k: number, type?: VertexType): LivingVertex[];\n matchIntent(intent: string, threshold?: number): { vertex: LivingVertex; score: number }[];\n\n // Predictive operations\n predictConfig(intent: string, trait: Trait): Record<string, TraitConfigValue>;\n predictPresence(intent: string): Set<string>;\n suggestOrbital(intent: string): LivingOrbital[];\n suggestEntity(intent: string): LivingEntity[];\n suggestTrait(intent: string): LivingTrait[];\n\n // Evolution\n evolve(intentDelta: string): LivingOrbitalSchema;\n compose(other: LivingOrbitalSchema): LivingOrbitalSchema;\n repair(errors: ValidationError[]): LivingOrbitalSchema;\n\n // Cross-orbital wiring\n wireEvents(source: LivingEvent, target: LivingEvent): void;\n findWiringGaps(): LivingEvent[];\n\n // Effect simulation\n simulateEffect(effect: LivingEffect, context: EvalContext): EffectResult;\n simulateInteraction(effect: LivingEffect, path: string[]): { event: LivingEvent; payload: EventPayload };\n traceDataFlow(transition: LivingTransition, inputEntity: LivingEntity): LivingEffect[];\n\n // Gates\n evaluateGates(intentEmbedding: SemanticVector): Map<VertexId, GateState[]>;\n sampleTrajectory(intentEmbedding: SemanticVector, steps: number): LivingVertex[];\n\n // Lineage\n lineage: LineageEntry[];\n checkout(hash: string): LivingOrbitalSchema;\n diff(hash1: string, hash2: string): EvolutionDelta;\n}\n","/**\n * Render-UI structural editing — the single canonical pattern-tree navigator,\n * mutators, and overlay application. Promoted out of apps/builder so the studio\n * client, rabit's contextual-edit path, and the overlay replay share ONE\n * implementation (no shadow copies).\n *\n * Operates on the SERIALIZABLE structural pattern node — the resolved `.orb`\n * render-ui shape (`{ type, children, ...props }`, props are strings/numbers/\n * booleans/bindings/arrays). It never holds function-typed props: those exist\n * only in the React-component `AnyPatternConfig`, never in resolved IR. A node\n * to insert/swap is built as a structural literal and validated against the\n * pattern registry by the caller — `AnyPatternConfig` is never assigned in.\n */\n\nimport type { OrbitalDefinition, Trait, Effect } from './types/index.js';\n\n// ----------------------------------------------------------------------------\n// Structural pattern node\n// ----------------------------------------------------------------------------\n\n/** A serializable value inside a render-ui pattern node. No functions. */\nexport type PatternValue =\n | string\n | number\n | boolean\n | Date\n | null\n | undefined\n | PatternNode\n | readonly PatternValue[];\n\n/** One node in a render-ui pattern tree as it appears in resolved `.orb`. */\nexport interface PatternNode {\n type?: string;\n children?: PatternNode[];\n [prop: string]: PatternValue | PatternNode[] | undefined;\n}\n\n// ----------------------------------------------------------------------------\n// EditFocus — a canvas selection resolved to an address in the resolved `.orb`\n// ----------------------------------------------------------------------------\n\nexport type EditFocusLevel =\n | 'node'\n | 'slot'\n | 'field'\n | 'effect'\n | 'trait'\n | 'page'\n | 'orbital';\n\n/** A pointed-at element. Plain data — constructible with or without a DOM. */\nexport interface EditFocus {\n level: EditFocusLevel;\n orbital: string;\n trait?: string;\n transition?: string;\n state?: string;\n slot?: string;\n path?: string;\n patternType?: string;\n entity?: string;\n source?: string;\n label: string;\n}\n\n// ----------------------------------------------------------------------------\n// RenderUiPatch — a structural render-ui edit, replayed after factory expansion\n// ----------------------------------------------------------------------------\n\nexport type RenderUiPatchOp = 'replace' | 'insert' | 'remove' | 'set-prop' | 'rebind';\n\nexport interface RenderUiPatchAddress {\n trait: string;\n transition: string;\n state?: string;\n slot: string;\n /** patternPath, e.g. `root.children.2`. For `insert`, the PARENT path. */\n path: string;\n}\n\nexport interface RenderUiPatch {\n op: RenderUiPatchOp;\n address: RenderUiPatchAddress;\n /** Structural fingerprint of the pre-edit node, used to re-anchor the patch\n * if a later factory rebuild shifts `address.path`. */\n fingerprint?: string;\n /** For `replace` / `insert`: the concrete node to place. */\n node?: PatternNode;\n /** For `insert`: index within the parent's children (default: append). */\n index?: number;\n /** For `set-prop` / `rebind`: the prop key. */\n prop?: string;\n /** For `set-prop`: the new value. For `rebind`: pass the binding via `value`. */\n value?: PatternValue;\n}\n\n// ----------------------------------------------------------------------------\n// Pure node primitives\n// ----------------------------------------------------------------------------\n\n/** Navigate a dot-separated path (`root`, `root.children.0`, …) to a node. */\nexport function navigatePatternPath(root: PatternNode, path: string): PatternNode | null {\n if (!path || path === 'root') return root;\n const parts = path.split('.');\n let current: PatternValue | PatternNode | readonly PatternValue[] | undefined = root;\n for (const part of parts) {\n if (current === null || current === undefined || typeof current !== 'object') return null;\n if (Array.isArray(current)) {\n const idx = Number.parseInt(part, 10);\n if (Number.isNaN(idx) || idx < 0 || idx >= current.length) return null;\n current = current[idx];\n } else {\n const record = current as PatternNode;\n if (part === 'children' && Array.isArray(record.children)) {\n current = record.children;\n } else {\n current = record[part];\n }\n }\n }\n return typeof current === 'object' && current !== null && !Array.isArray(current)\n ? (current as PatternNode)\n : null;\n}\n\nfunction splitChildPath(path: string): { parentPath: string; index: number } | null {\n const lastDot = path.lastIndexOf('.');\n if (lastDot === -1) return null;\n const index = Number.parseInt(path.slice(lastDot + 1), 10);\n if (Number.isNaN(index)) return null;\n return { parentPath: path.slice(0, lastDot), index };\n}\n\n/** Set a prop on the node at `path`. Returns false if the path misses. */\nexport function setPropAtPath(\n root: PatternNode,\n path: string,\n prop: string,\n value: PatternValue,\n): boolean {\n const node = navigatePatternPath(root, path);\n if (!node) return false;\n node[prop] = value;\n return true;\n}\n\n/** Replace the node at a child path (`<parent>.children.<i>`) with `node`. */\nexport function replaceChildAtPath(root: PatternNode, path: string, node: PatternNode): boolean {\n const split = splitChildPath(path);\n if (!split) return false;\n const parent = navigatePatternPath(root, split.parentPath);\n if (!parent || !Array.isArray(parent.children)) return false;\n if (split.index < 0 || split.index >= parent.children.length) return false;\n parent.children[split.index] = node;\n return true;\n}\n\n/** Insert `node` into the parent's `children` at `index` (clamped to end). */\nexport function insertChildAtPath(\n root: PatternNode,\n parentPath: string,\n index: number,\n node: PatternNode,\n): boolean {\n const parent = navigatePatternPath(root, parentPath);\n if (!parent) return false;\n const children = parent.children ?? [];\n const i = index < 0 || index > children.length ? children.length : index;\n children.splice(i, 0, node);\n parent.children = children;\n return true;\n}\n\n/** Remove the node at a child path. */\nexport function removeChildAtPath(root: PatternNode, path: string): boolean {\n const split = splitChildPath(path);\n if (!split) return false;\n const parent = navigatePatternPath(root, split.parentPath);\n if (!parent || !Array.isArray(parent.children)) return false;\n if (split.index < 0 || split.index >= parent.children.length) return false;\n parent.children.splice(split.index, 1);\n return true;\n}\n\n/** Replace a node's contents in place (used to swap the render-ui root). */\nfunction replaceNodeInPlace(target: PatternNode, source: PatternNode): void {\n for (const key of Object.keys(target)) {\n delete target[key];\n }\n Object.assign(target, source);\n}\n\n// ----------------------------------------------------------------------------\n// Fingerprint (re-anchor)\n// ----------------------------------------------------------------------------\n\nfunction stableValue(value: PatternValue | PatternNode[] | undefined): string {\n if (value === undefined) return 'u';\n if (value === null) return 'n';\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n return JSON.stringify(value);\n }\n if (value instanceof Date) return value.toISOString();\n if (Array.isArray(value)) return `[${value.map(stableValue).join(',')}]`;\n const nodeType = 'type' in value ? value.type : undefined;\n return `{${typeof nodeType === 'string' ? nodeType : ''}}`;\n}\n\n/** Deterministic structural fingerprint of a node (excludes child contents;\n * identifies the base node so a patch can re-anchor after a path shift). */\nexport function fingerprintNode(node: PatternNode): string {\n const props = Object.keys(node)\n .filter((k) => k !== 'children')\n .sort()\n .map((k) => `${k}=${stableValue(node[k])}`)\n .join(',');\n const childCount = Array.isArray(node.children) ? node.children.length : 0;\n return `t:${node.type ?? ''}|${props}|c:${childCount}`;\n}\n\nfunction findByFingerprint(node: PatternNode, path: string, fp: string): string | null {\n if (fingerprintNode(node) === fp) return path;\n if (Array.isArray(node.children)) {\n for (let i = 0; i < node.children.length; i++) {\n const r = findByFingerprint(node.children[i], `${path}.children.${i}`, fp);\n if (r) return r;\n }\n }\n return null;\n}\n\n// ----------------------------------------------------------------------------\n// Overlay application\n// ----------------------------------------------------------------------------\n\nexport interface RenderOverlayResult {\n applied: number;\n /** Patches whose target node could not be resolved (path gone + fingerprint\n * unmatched). Surfaced as `patch_stale` — never silently dropped. */\n stale: RenderUiPatch[];\n}\n\n/** A render-ui effect's slot + root pattern node, validated from the canonical\n * `Effect` tuple. The `['render-ui', slot, config]` form carries the structural\n * pattern node at index 2 in resolved `.orb`; we narrow `Effect` by its tag and\n * validate the payload is a concrete node (not a `@binding` string or null). */\nfunction readRenderUi(eff: Effect): { slot: string; node: PatternNode } | null {\n if (eff[0] !== 'render-ui') return null;\n const slot = eff[1];\n const config = eff[2];\n if (typeof slot !== 'string') return null;\n if (config === null || typeof config !== 'object' || Array.isArray(config)) return null;\n return { slot, node: config as PatternNode };\n}\n\n/** Narrow a trait reference to an inline `Trait` (the only `TraitRef` member\n * with a `stateMachine`). No cast — `in` narrows the union. */\nfunction asInlineTrait(ref: OrbitalDefinition['traits'][number]): Trait | null {\n if (typeof ref === 'object' && ref !== null && 'stateMachine' in ref) {\n return ref;\n }\n return null;\n}\n\n/** Find the render-ui root node for a patch address. Prefers the exact\n * transition match; falls back to the first trait+slot render-ui when the\n * transition is unknown (canvas selections at INIT carry no data-orb-transition,\n * so `address.transition` is empty and no real transition can match). */\nfunction findRenderUiRoot(\n orbital: OrbitalDefinition,\n address: RenderUiPatchAddress,\n): PatternNode | null {\n const wantTransition = address.transition !== '';\n const wantState = address.state !== undefined && address.state !== '';\n let fallback: PatternNode | null = null;\n for (const ref of orbital.traits) {\n const trait = asInlineTrait(ref);\n if (!trait || trait.name !== address.trait) continue;\n for (const t of trait.stateMachine?.transitions ?? []) {\n if (wantState && t.from !== address.state) continue;\n for (const eff of t.effects ?? []) {\n const ru = readRenderUi(eff);\n if (!ru || ru.slot !== address.slot) continue;\n if (wantTransition && t.event === address.transition) return ru.node;\n fallback ??= ru.node;\n }\n }\n }\n return fallback;\n}\n\n/** Resolve the effective path for a patch, re-anchoring by fingerprint. */\nfunction resolvePath(root: PatternNode, patch: RenderUiPatch): string | null {\n if (patch.op === 'insert') {\n return navigatePatternPath(root, patch.address.path) ? patch.address.path : null;\n }\n const atPath = navigatePatternPath(root, patch.address.path);\n if (atPath && (patch.fingerprint === undefined || fingerprintNode(atPath) === patch.fingerprint)) {\n return patch.address.path;\n }\n if (patch.fingerprint !== undefined) {\n return findByFingerprint(root, 'root', patch.fingerprint);\n }\n return null;\n}\n\nfunction applyOnePatch(orbital: OrbitalDefinition, patch: RenderUiPatch): boolean {\n const root = findRenderUiRoot(orbital, patch.address);\n if (!root) return false;\n const path = resolvePath(root, patch);\n if (path === null) return false;\n\n switch (patch.op) {\n case 'set-prop':\n case 'rebind':\n return patch.prop !== undefined && setPropAtPath(root, path, patch.prop, patch.value);\n case 'remove':\n return removeChildAtPath(root, path);\n case 'insert':\n return patch.node !== undefined\n && insertChildAtPath(root, path, patch.index ?? Number.MAX_SAFE_INTEGER, patch.node);\n case 'replace': {\n if (patch.node === undefined) return false;\n if (path === 'root') {\n const target = navigatePatternPath(root, 'root');\n if (!target) return false;\n replaceNodeInPlace(target, patch.node);\n return true;\n }\n return replaceChildAtPath(root, path, patch.node);\n }\n default:\n return false;\n }\n}\n\n/**\n * Replay render-ui patches onto a resolved orbital, in place. Deterministic:\n * given the same base + patches, produces the same tree. Patches that cannot be\n * anchored are returned in `stale` (never silently dropped or misapplied).\n */\nexport function applyRenderOverlay(\n orbital: OrbitalDefinition,\n patches: readonly RenderUiPatch[],\n): RenderOverlayResult {\n let applied = 0;\n const stale: RenderUiPatch[] = [];\n for (const patch of patches) {\n if (applyOnePatch(orbital, patch)) {\n applied += 1;\n } else {\n stale.push(patch);\n }\n }\n return { applied, stale };\n}\n","/**\n * Schema Resolver\n *\n * Converts OrbitalSchema to Intermediate Representation (IR).\n * Resolves all entity references, expands traits, and prepares schema for compilation/runtime.\n *\n * @packageDocumentation\n */\n\nimport type { OrbitalSchema } from './types/schema.js';\nimport type { Orbital, Trait, Page, PageTraitRef, Entity } from './types/index.js';\nimport type { ResolvedIR, ResolvedPage, ResolvedEntity, ResolvedTrait, ResolvedTraitEvent, ResolvedTraitTransition, ResolvedTraitTick } from './types/ir.js';\nimport type { EntityField } from './types/field.js';\nimport type { FieldValue } from './types/entity.js';\nimport type { State, Event, Transition } from './types/state-machine.js';\nimport type { TraitEventListener, TraitTick } from './types/trait.js';\n\n/**\n * Extended entity shape for schema data that may carry `defaults`.\n * The core Entity type does not include `defaults`, but parsed schemas\n * can attach it as extra data for singleton initialization.\n */\ninterface EntityWithDefaults extends Entity {\n defaults?: Record<string, FieldValue>;\n}\n\n// ============================================================================\n// Cache\n// ============================================================================\n\n/**\n * Cache for resolved schemas, keyed on the schema object reference.\n *\n * Identity-based caching (WeakMap) is the only correct shape here: two\n * versions of the same logical schema with the same `name` + `version`\n * can have different content (e.g. a palette drop adds a render-ui\n * pattern, an agent edit rewrites a trait's effects). The old\n * `${name}-${version}` key collided across content mutations and\n * returned a stale IR — fine for the compiler's one-shot path, fatal\n * for the runtime's live-editing path where downstream identity checks\n * (`traits` array refs, trait state-machine references) depend on the\n * IR being fresh when the schema's content moved.\n *\n * WeakMap also means we don't have to think about cache invalidation:\n * when the consumer drops its reference to the schema, the entry is\n * garbage-collected automatically.\n */\nlet schemaCache = new WeakMap<OrbitalSchema, ResolvedIR>();\n\n/**\n * Clear the schema resolution cache.\n *\n * With WeakMap-on-reference caching, cache entries die naturally when\n * the schema object is GC'd, so explicit clearing is rarely necessary.\n * Kept for hot-reload paths that want to force fresh resolution; since\n * WeakMap has no `clear()`, we swap in a fresh instance.\n */\nexport function clearSchemaCache(): void {\n schemaCache = new WeakMap<OrbitalSchema, ResolvedIR>();\n}\n\n/**\n * Get cache statistics (for debugging).\n *\n * WeakMap doesn't expose size or keys; the best we can do is signal\n * that the cache is identity-keyed. Kept for API parity with the old\n * Map-based cache.\n */\nexport function getSchemaCacheStats(): { size: number; keys: string[] } {\n return { size: -1, keys: [] };\n}\n\n// ============================================================================\n// Schema to IR Conversion\n// ============================================================================\n\n/**\n * Convert OrbitalSchema to Intermediate Representation (IR).\n *\n * This function:\n * 1. Resolves all entity references\n * 2. Expands trait definitions (inline or from library)\n * 3. Resolves page bindings\n * 4. Creates the IR structure used by compiler and runtime\n *\n * @param schema - OrbitalSchema to convert\n * @param useCache - Whether to use cached result (default: true)\n * @returns Fully resolved IR\n *\n * @example\n * const schema = { name: 'MyApp', orbitals: [...] };\n * const ir = schemaToIR(schema);\n * console.log(ir.entities.size); // Number of entities\n * console.log(ir.pages.size); // Number of pages\n */\nexport function schemaToIR(schema: OrbitalSchema, useCache: boolean = true): ResolvedIR {\n // Identity cache: same object reference → same IR. Caller is responsible\n // for handing us a fresh ref when content moved (e.g. immutable update).\n if (useCache) {\n const cached = schemaCache.get(schema);\n if (cached) return cached;\n }\n\n // Create empty IR structure\n const ir: ResolvedIR = {\n appName: schema.name,\n description: schema.description,\n version: schema.version || '1.0.0',\n entities: new Map<string, ResolvedEntity>(),\n traits: new Map<string, ResolvedTrait>(),\n pages: new Map<string, ResolvedPage>(),\n entityBindings: [],\n generatedAt: new Date().toISOString(),\n };\n\n // Process each orbital\n for (const orbital of schema.orbitals as Orbital[]) {\n // Resolve entity if present\n if (orbital.entity && typeof orbital.entity !== 'string') {\n const entityDef = orbital.entity as EntityWithDefaults;\n const entity: ResolvedEntity = {\n name: entityDef.name,\n description: entityDef.description,\n // eslint-disable-next-line almadar/no-record-string-unknown -- icon is an optional extension not on Entity type\n icon: (entityDef as unknown as { icon?: string }).icon,\n collection: entityDef.collection || entityDef.name.toLowerCase() + 's',\n fields: (entityDef.fields || [])\n .filter((field: EntityField): field is EntityField & { name: string } =>\n typeof field.name === 'string' && field.name.length > 0,\n )\n .map((field) => ({\n name: field.name,\n type: field.type,\n tsType: inferTsType(field.type),\n // eslint-disable-next-line almadar/no-record-string-unknown -- description is an optional extension not on EntityField type\n description: (field as unknown as { description?: string }).description,\n default: field.default,\n required: field.required ?? false,\n values: field.type === 'enum' ? field.values : undefined,\n enumValues: field.type === 'enum' ? field.values : undefined,\n relation: field.type === 'relation' ? field.relation : undefined,\n })),\n runtime: entityDef.persistence === 'runtime',\n singleton: entityDef.persistence === 'singleton',\n hasInstances: (entityDef.instances?.length ?? 0) > 0,\n instances: entityDef.instances,\n defaults: entityDef.defaults,\n usedByTraits: [],\n usedByPages: [],\n };\n ir.entities.set(entity.name, entity);\n }\n\n // Resolve traits. Preprocessed ref traits from @almadar/runtime's\n // preprocessSchema arrive as wrappers { ref, config, linkedEntity,\n // _resolved: <full trait> }. Unwrap those before projecting so the\n // page-level trait binding can find them by name in ir.traits.\n // Without this unwrap, `trait.name` on a ref wrapper is undefined,\n // and useTraitStateMachine subscribes to zero events for every ref.\n for (const rawTrait of (orbital.traits || [])) {\n const wrap = rawTrait as { _resolved?: Trait };\n const maybeResolved = wrap._resolved;\n const trait: Trait =\n maybeResolved && maybeResolved.stateMachine\n ? maybeResolved\n : (rawTrait as Trait);\n if (!trait.name) continue;\n const resolvedTrait: ResolvedTrait = {\n name: trait.name,\n description: trait.description,\n source: 'schema',\n category: trait.category,\n states: (trait.stateMachine?.states || []).map((s: State) => ({\n name: s.name,\n isInitial: s.isInitial ?? false,\n isFinal: s.isFinal ?? s.isTerminal ?? false,\n })),\n events: (trait.stateMachine?.events || []).map((e: Event) => ({\n key: e.key,\n name: e.name,\n payload: e.payloadSchema,\n })) as ResolvedTraitEvent[],\n transitions: (trait.stateMachine?.transitions || []).map((t: Transition) => ({\n from: t.from,\n to: t.to,\n event: t.event,\n guard: t.guard,\n effects: t.effects || [],\n })) as ResolvedTraitTransition[],\n guards: [],\n ticks: (trait.ticks || []).map((tk: TraitTick) => ({\n name: tk.name,\n interval: tk.interval,\n guard: tk.guard,\n effects: tk.effects,\n priority: tk.priority ?? 0,\n appliesTo: tk.appliesTo ?? [],\n })) as ResolvedTraitTick[],\n listens: (trait.listens || []).map((l: TraitEventListener) => ({\n event: l.event,\n triggers: l.triggers,\n guard: l.guard,\n })),\n dataEntities: [],\n linkedEntity: trait.linkedEntity,\n config: trait.config,\n };\n ir.traits.set(trait.name, resolvedTrait);\n }\n\n // Resolve pages\n for (const page of (orbital.pages || []) as Page[]) {\n const resolvedPage: ResolvedPage = {\n name: page.name,\n path: page.path,\n featureName: page.name.toLowerCase(),\n viewType: page.viewType && ['list', 'detail', 'create', 'edit', 'dashboard'].includes(page.viewType) ?\n page.viewType as ('list' | 'detail' | 'create' | 'edit' | 'dashboard') : undefined,\n sections: [],\n traits: (page.traits || []).map((traitRef: PageTraitRef) => {\n const resolvedTrait = resolveTraitRef(traitRef, ir.traits, orbital.traits as Trait[] || []);\n // Precedence: page-level rebind → orbital-trait-wrapper rebind →\n // atom's resolved trait linkedEntity (from `uses` import) →\n // orbital primary entity. Without walking past the wrapper to\n // the atom's _resolved, atoms imported via `uses` without an\n // explicit `-> Entity` rebind silently rebind to the orbital's\n // primary entity (gap #22 design said atoms keep their own\n // auxiliary entity).\n const orbitalTrait = (orbital.traits as Trait[] || []).find(\n (t): t is Trait => typeof t === 'object' && t !== null\n && (\n ('name' in t && (t as { name?: string }).name === traitRef.ref)\n || ('ref' in t && (t as { ref?: string }).ref === traitRef.ref)\n )\n );\n const orbitalTraitWrapped = orbitalTrait as (Trait & { _resolved?: Trait }) | undefined;\n const wrapperLinked = orbitalTraitWrapped?.linkedEntity ?? orbitalTraitWrapped?._resolved?.linkedEntity;\n const resolvedLinked = resolvedTrait?.linkedEntity;\n return {\n ref: traitRef.ref,\n trait: resolvedTrait,\n linkedEntity: traitRef.linkedEntity ?? wrapperLinked ?? resolvedLinked ??\n (orbital.entity ? (typeof orbital.entity === 'string' ? orbital.entity.replace('.entity', '') : (orbital.entity as Entity).name) : undefined),\n config: traitRef.config,\n };\n }),\n entityBindings: [],\n navigation: [],\n singletonEntities: [],\n };\n ir.pages.set(page.name, resolvedPage);\n }\n }\n\n // Cache result against the schema's object identity.\n if (useCache) {\n schemaCache.set(schema, ir);\n }\n\n return ir;\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Infers TypeScript type from schema type string\n * \n * Converts schema type strings to their TypeScript equivalents.\n * Handles primitive types, arrays, and custom types.\n * \n * @param {string} schemaType - Schema type string (e.g., 'string', 'number[]')\n * @returns {string} TypeScript type string\n * \n * @example\n * inferTsType('string') // returns 'string'\n * inferTsType('number[]') // returns 'number[]'\n * inferTsType('custom') // returns 'custom'\n */\nfunction inferTsType(schemaType: string): string {\n const typeMap: Record<string, string> = {\n string: 'string',\n number: 'number',\n boolean: 'boolean',\n date: 'Date',\n datetime: 'Date',\n timestamp: 'number',\n array: 'unknown[]',\n object: 'Record<string, unknown>',\n any: 'unknown',\n };\n\n // Handle array types like \"string[]\"\n if (schemaType.endsWith('[]')) {\n const baseType = schemaType.slice(0, -2);\n return `${typeMap[baseType] || baseType}[]`;\n }\n\n // Typed-map form `Map<K,V>` (the orbital `Map K V` type) → `Record<K, V>`.\n // Mirrors the Rust `parse_payload_field_type` map branch.\n if (schemaType.startsWith('Map<') && schemaType.endsWith('>')) {\n const inner = schemaType.slice(4, -1);\n const comma = inner.indexOf(',');\n if (comma !== -1) {\n const key = inferTsType(inner.slice(0, comma).trim());\n const value = inferTsType(inner.slice(comma + 1).trim());\n return `Record<${key}, ${value}>`;\n }\n }\n\n return typeMap[schemaType] || schemaType;\n}\n\n/**\n * Resolves a trait reference to a full trait definition\n * \n * Looks up trait references in the resolved traits map or schema traits array.\n * Creates appropriate trait structures for different reference types.\n * \n * @param {PageTraitRef} traitRef - Trait reference (string or object)\n * @param {Map<string, ResolvedTrait>} traitsMap - Map of resolved traits\n * @param {Trait[]} schemaTraits - Array of schema traits\n * @returns {ResolvedTrait} Resolved trait definition\n * \n * @example\n * const trait = resolveTraitRef('MyTrait', traitsMap, schemaTraits);\n * const trait = resolveTraitRef({ ref: 'MyTrait' }, traitsMap, schemaTraits);\n */\nfunction resolveTraitRef(\n traitRef: PageTraitRef,\n traitsMap: Map<string, ResolvedTrait>,\n schemaTraits: Trait[]\n): ResolvedTrait {\n const refName = typeof traitRef === 'string' ? traitRef : traitRef.ref || '';\n\n // Try to find in resolved traits\n if (traitsMap.has(refName)) {\n return traitsMap.get(refName)!;\n }\n\n // Try to find in schema traits\n const schemaTrait = schemaTraits.find((t: Trait) => t.name === refName);\n if (schemaTrait) {\n // This is a simplified inline trait\n return {\n name: refName,\n source: 'inline',\n states: [],\n events: [],\n transitions: [],\n guards: [],\n ticks: [],\n listens: [],\n dataEntities: [],\n };\n }\n\n // Fallback: create empty trait\n return {\n name: refName,\n source: 'schema',\n states: [],\n events: [],\n transitions: [],\n guards: [],\n ticks: [],\n listens: [],\n dataEntities: [],\n };\n}\n\n// ============================================================================\n// Page Helpers\n// ============================================================================\n\n/**\n * Get a specific page from resolved IR by name.\n * If no name is provided, returns the first page.\n *\n * @param ir - Resolved IR\n * @param pageName - Optional page name to find\n * @returns Resolved page or undefined\n *\n * @example\n * const ir = schemaToIR(schema);\n * const homePage = getPage(ir, 'HomePage');\n * const firstPage = getPage(ir); // No name = first page\n */\nexport function getPage(ir: ResolvedIR, pageName?: string): ResolvedPage | undefined {\n if (!pageName) {\n // Return first page if no name specified\n return ir.pages.values().next().value;\n }\n return ir.pages.get(pageName);\n}\n\n/**\n * Get all pages from resolved IR as an array\n *\n * @param ir - Resolved IR\n * @returns Array of resolved pages\n */\nexport function getPages(ir: ResolvedIR): ResolvedPage[] {\n return Array.from(ir.pages.values());\n}\n\n/**\n * Get a specific entity from resolved IR by name\n *\n * @param ir - Resolved IR\n * @param entityName - Entity name to find\n * @returns Resolved entity or undefined\n */\nexport function getEntity(ir: ResolvedIR, entityName: string): ResolvedEntity | undefined {\n return ir.entities.get(entityName);\n}\n\n/**\n * Get a specific trait from resolved IR by name\n *\n * @param ir - Resolved IR\n * @param traitName - Trait name to find\n * @returns Resolved trait or undefined\n */\nexport function getTrait(ir: ResolvedIR, traitName: string): ResolvedTrait | undefined {\n return ir.traits.get(traitName);\n}\n","/**\n * Schema Diffing & Protection\n *\n * Pure functions for comparing OrbitalSchema objects, detecting destructive changes,\n * and categorizing removals. No I/O — operates on in-memory schema objects.\n */\n\nimport type { OrbitalSchema } from './types/schema.js';\nimport type { OrbitalDefinition, PageRef } from './types/orbital.js';\nimport type { Trait, TraitRef } from './types/trait.js';\nimport type { Page } from './types/page.js';\n// EntityField used transitively through entity.fields\nimport type { State, Transition } from './types/state-machine.js';\nimport type { Effect } from './types/effect.js';\nimport type {\n SchemaChange,\n ChangeSetDocument,\n CategorizedRemovals,\n ChangesetValue,\n PageContentReduction,\n SemanticSchemaChange,\n} from './types/changeset.js';\nimport { isInlineTrait } from './types/trait.js';\n\n// ============================================================================\n// Schema Diffing\n// ============================================================================\n\n/**\n * Diff two OrbitalSchema objects and produce a list of changes.\n * Compares orbitals, entities, traits, pages, services, and top-level fields.\n */\nexport function diffSchemas(\n before: OrbitalSchema,\n after: OrbitalSchema,\n): { changes: SchemaChange[] } {\n const changes: SchemaChange[] = [];\n let changeId = 0;\n const nextId = () => `change-${++changeId}`;\n\n // Compare top-level fields\n if (before.name !== after.name) {\n changes.push({\n id: nextId(),\n operation: 'modify',\n target: 'schema',\n path: ['name'],\n before: before.name,\n after: after.name,\n description: `Renamed schema from \"${before.name}\" to \"${after.name}\"`,\n });\n }\n\n if (before.description !== after.description) {\n changes.push({\n id: nextId(),\n operation: 'modify',\n target: 'schema',\n path: ['description'],\n before: before.description,\n after: after.description,\n description: `Modified schema description`,\n });\n }\n\n // Compare orbitals by name\n const beforeOrbitals = new Map(\n (before.orbitals || []).map((o, i) => [o.name, { orbital: o, index: i }]),\n );\n const afterOrbitals = new Map(\n (after.orbitals || []).map((o, i) => [o.name, { orbital: o, index: i }]),\n );\n\n // Detect removed orbitals\n for (const [name, { index }] of beforeOrbitals) {\n if (!afterOrbitals.has(name)) {\n changes.push({\n id: nextId(),\n operation: 'remove',\n target: 'orbital',\n path: ['orbitals', index],\n before: name,\n description: `Removed orbital: ${name}`,\n });\n }\n }\n\n // Detect added orbitals\n for (const [name, { index }] of afterOrbitals) {\n if (!beforeOrbitals.has(name)) {\n changes.push({\n id: nextId(),\n operation: 'add',\n target: 'orbital',\n path: ['orbitals', index],\n after: name,\n description: `Added orbital: ${name}`,\n });\n }\n }\n\n // Detect modified orbitals (deep compare via JSON)\n for (const [name, { orbital: afterOrbital, index }] of afterOrbitals) {\n const beforeEntry = beforeOrbitals.get(name);\n if (beforeEntry) {\n const beforeJson = JSON.stringify(beforeEntry.orbital);\n const afterJson = JSON.stringify(afterOrbital);\n if (beforeJson !== afterJson) {\n changes.push({\n id: nextId(),\n operation: 'modify',\n target: 'orbital',\n path: ['orbitals', index],\n description: `Modified orbital: ${name}`,\n });\n\n // Drill into entity changes\n const beforeEntity = beforeEntry.orbital.entity;\n const afterEntity = afterOrbital.entity;\n if (JSON.stringify(beforeEntity) !== JSON.stringify(afterEntity)) {\n const entityName =\n typeof afterEntity === 'string'\n ? afterEntity\n : afterEntity && typeof afterEntity === 'object' && 'name' in afterEntity\n ? (afterEntity as { name: string }).name\n : 'entity';\n changes.push({\n id: nextId(),\n operation: 'modify',\n target: 'entity',\n path: ['orbitals', index, 'entity'],\n description: `Modified entity: ${entityName}`,\n });\n }\n\n // Drill into trait changes\n const beforeTraits = beforeEntry.orbital.traits || [];\n const afterTraits = afterOrbital.traits || [];\n if (JSON.stringify(beforeTraits) !== JSON.stringify(afterTraits)) {\n changes.push({\n id: nextId(),\n operation: 'modify',\n target: 'traits',\n path: ['orbitals', index, 'traits'],\n description: `Modified traits in orbital: ${name}`,\n });\n }\n\n // Drill into page changes\n const beforePages = beforeEntry.orbital.pages || [];\n const afterPages = afterOrbital.pages || [];\n if (JSON.stringify(beforePages) !== JSON.stringify(afterPages)) {\n changes.push({\n id: nextId(),\n operation: 'modify',\n target: 'pages',\n path: ['orbitals', index, 'pages'],\n description: `Modified pages in orbital: ${name}`,\n });\n }\n }\n }\n }\n\n // Compare services\n const beforeServices = JSON.stringify(before.services || []);\n const afterServices = JSON.stringify(after.services || []);\n if (beforeServices !== afterServices) {\n changes.push({\n id: nextId(),\n operation: 'modify',\n target: 'services',\n path: ['services'],\n description: 'Modified services',\n });\n }\n\n return { changes };\n}\n\n// ============================================================================\n// Destructive Change Detection\n// ============================================================================\n\n/**\n * Check if a changeset contains any removals.\n */\nexport function isDestructiveChange(changeSet: { changes: SchemaChange[] }): boolean {\n return changeSet.changes.some((c) => c.operation === 'remove');\n}\n\n/**\n * Extract all removal operations from a changeset.\n */\nexport function getRemovals(changeSet: { changes: SchemaChange[] }): SchemaChange[] {\n return changeSet.changes.filter((c) => c.operation === 'remove');\n}\n\n/**\n * Categorize removals by severity.\n *\n * - Critical: orbitals, entities, states, pages (require confirmation)\n * - Standard: fields, actions, traits (auto-snapshotted)\n * - Minor: transitions, guards (tracked)\n */\nexport function categorizeRemovals(changeSet: {\n changes: SchemaChange[];\n}): CategorizedRemovals {\n const critical: SchemaChange[] = [];\n const standard: SchemaChange[] = [];\n const minor: SchemaChange[] = [];\n\n for (const change of changeSet.changes) {\n if (change.operation !== 'remove') continue;\n\n const target = change.target.toLowerCase();\n if (\n target === 'orbital' ||\n target === 'entity' ||\n target === 'state' ||\n target === 'page'\n ) {\n critical.push(change);\n } else if (\n target === 'field' ||\n target === 'action' ||\n target === 'trait' ||\n target === 'traits'\n ) {\n standard.push(change);\n } else {\n minor.push(change);\n }\n }\n\n return { critical, standard, minor, pageContentReductions: [] };\n}\n\n/**\n * Check if critical removals require explicit confirmation.\n */\nexport function requiresConfirmation(removals: CategorizedRemovals): boolean {\n return removals.critical.length > 0;\n}\n\n// ============================================================================\n// Page Content Reduction\n// ============================================================================\n\n/**\n * Detect implicit content reduction within pages.\n * Catches cases where a page 'modify' reduces components/actions/displays\n * without an explicit 'remove' operation.\n */\nexport function detectPageContentReduction(\n beforePages: unknown[],\n afterPages: unknown[],\n): PageContentReduction[] {\n const reductions: PageContentReduction[] = [];\n\n const getPageName = (p: unknown): string | null => {\n if (p && typeof p === 'object' && 'name' in p) {\n return (p as { name: string }).name;\n }\n return null;\n };\n\n const countContent = (\n page: unknown,\n ): { sections: number; actions: number } => {\n if (!page || typeof page !== 'object') return { sections: 0, actions: 0 };\n const p = page as { traits?: unknown[] };\n const traits = Array.isArray(p.traits) ? p.traits : [];\n return { sections: traits.length, actions: 0 };\n };\n\n // Build maps by name\n const beforeMap = new Map<string, unknown>();\n for (const p of beforePages) {\n const name = getPageName(p);\n if (name) beforeMap.set(name, p);\n }\n\n for (const afterPage of afterPages) {\n const name = getPageName(afterPage);\n if (!name) continue;\n const beforePage = beforeMap.get(name);\n if (!beforePage) continue;\n\n const beforeContent = countContent(beforePage);\n const afterContent = countContent(afterPage);\n\n const sectionsRemoved = beforeContent.sections - afterContent.sections;\n const actionsRemoved = beforeContent.actions - afterContent.actions;\n\n if (sectionsRemoved > 0 || actionsRemoved > 0) {\n reductions.push({\n pageName: name,\n componentsRemoved: sectionsRemoved,\n actionsRemoved,\n displaysRemoved: 0,\n before: beforeContent,\n after: afterContent,\n isSignificant: sectionsRemoved > 0,\n });\n }\n }\n\n return reductions;\n}\n\n/**\n * Check if page content reductions are significant.\n */\nexport function hasSignificantPageReduction(\n reductions: PageContentReduction[],\n): boolean {\n return reductions.some((r) => r.isSignificant);\n}\n\n// ============================================================================\n// Semantic Schema Diffing\n// ============================================================================\n\n/** Stable JSON comparison. */\nfunction jsonEqual(a: unknown, b: unknown): boolean {\n return JSON.stringify(a) === JSON.stringify(b);\n}\n\nfunction setsEqual(a: Set<string>, b: Set<string>): boolean {\n if (a.size !== b.size) return false;\n for (const item of a) {\n if (!b.has(item)) return false;\n }\n return true;\n}\n\nfunction inlineTraitMap(refs: TraitRef[]): Map<string, Trait> {\n const map = new Map<string, Trait>();\n for (const r of refs) {\n if (isInlineTrait(r)) map.set((r as Trait).name, r as Trait);\n }\n return map;\n}\n\nfunction inlinePageMap(refs: PageRef[]): Map<string, Page> {\n const map = new Map<string, Page>();\n for (const r of refs) {\n if (typeof r === 'string') continue;\n if ('ref' in r && !('name' in r)) continue;\n const page = r as Page;\n if (page.path) map.set(page.path, page);\n }\n return map;\n}\n\nfunction isRenderUIEffect(effect: Effect): boolean {\n if (!Array.isArray(effect)) return false;\n return String(effect[0]) === 'render-ui' || String(effect[0]) === 'renderUI';\n}\n\nfunction tKey(t: Transition): string {\n return `${t.from ?? ''}+${t.event}`;\n}\n\nfunction diffSemanticTransitions(\n orbitalName: string, traitName: string,\n before: Transition[], after: Transition[],\n): SemanticSchemaChange[] {\n const changes: SemanticSchemaChange[] = [];\n const bMap = new Map(before.map(t => [tKey(t), t]));\n const aMap = new Map(after.map(t => [tKey(t), t]));\n\n for (const [key, aT] of aMap) {\n const bT = bMap.get(key);\n if (!bT) continue;\n\n if (!jsonEqual(bT.guard, aT.guard)) {\n changes.push({ kind: 'guard-changed', orbitalName, traitName, transitionEvent: aT.event });\n }\n\n if (!jsonEqual(bT.effects, aT.effects)) {\n const bEffects = bT.effects ?? [];\n const aEffects = aT.effects ?? [];\n const bRUI = bEffects.filter(isRenderUIEffect);\n const aRUI = aEffects.filter(isRenderUIEffect);\n\n if (bRUI.length !== aRUI.length || !jsonEqual(bRUI, aRUI)) {\n changes.push({ kind: 'render-ui-changed', orbitalName, traitName, transitionEvent: aT.event });\n } else {\n changes.push({ kind: 'effect-changed', orbitalName, traitName, transitionEvent: aT.event });\n }\n }\n }\n return changes;\n}\n\nfunction diffSemanticOrbital(\n name: string, before: OrbitalDefinition, after: OrbitalDefinition,\n): SemanticSchemaChange[] {\n const changes: SemanticSchemaChange[] = [];\n\n // Entity fields\n const bEntity = typeof before.entity === 'object' ? before.entity : null;\n const aEntity = typeof after.entity === 'object' ? after.entity : null;\n if (bEntity && aEntity) {\n if (!jsonEqual(bEntity.fields, aEntity.fields)) {\n changes.push({ kind: 'entity-fields-changed', orbitalName: name });\n }\n } else if (bEntity !== aEntity) {\n changes.push({ kind: 'entity-fields-changed', orbitalName: name });\n }\n\n // Traits\n const bTraits = inlineTraitMap(before.traits ?? []);\n const aTraits = inlineTraitMap(after.traits ?? []);\n\n for (const [tName] of aTraits) {\n if (!bTraits.has(tName)) changes.push({ kind: 'trait-added', orbitalName: name, traitName: tName });\n }\n for (const [tName] of bTraits) {\n if (!aTraits.has(tName)) changes.push({ kind: 'trait-removed', orbitalName: name, traitName: tName });\n }\n\n for (const [tName, aTrait] of aTraits) {\n const bTrait = bTraits.get(tName);\n if (!bTrait) continue;\n\n const bSM = bTrait.stateMachine;\n const aSM = aTrait.stateMachine;\n\n if (!bSM && !aSM) continue;\n if (!bSM || !aSM) {\n changes.push({ kind: 'state-machine-changed', orbitalName: name, traitName: tName });\n continue;\n }\n\n const bStates = new Set((bSM.states ?? []).map((s: State) => s.name));\n const aStates = new Set((aSM.states ?? []).map((s: State) => s.name));\n if (!setsEqual(bStates, aStates)) {\n changes.push({ kind: 'state-machine-changed', orbitalName: name, traitName: tName });\n }\n\n const bTKeys = new Set((bSM.transitions ?? []).map(tKey));\n const aTKeys = new Set((aSM.transitions ?? []).map(tKey));\n if (!setsEqual(bTKeys, aTKeys)) {\n if (!changes.some(c => c.kind === 'state-machine-changed' && c.traitName === tName)) {\n changes.push({ kind: 'state-machine-changed', orbitalName: name, traitName: tName });\n }\n }\n\n changes.push(...diffSemanticTransitions(name, tName, bSM.transitions ?? [], aSM.transitions ?? []));\n\n if (!jsonEqual(bTrait.emits, aTrait.emits) || !jsonEqual(bTrait.listens, aTrait.listens)) {\n changes.push({ kind: 'event-wiring-changed', orbitalName: name, traitName: tName });\n }\n }\n\n // Pages\n const bPages = inlinePageMap(before.pages ?? []);\n const aPages = inlinePageMap(after.pages ?? []);\n const bPaths = new Set(bPages.keys());\n const aPaths = new Set(aPages.keys());\n\n if (!setsEqual(bPaths, aPaths)) {\n changes.push({ kind: 'page-changed', orbitalName: name });\n } else {\n for (const [path, aPage] of aPages) {\n if (!jsonEqual(bPages.get(path), aPage)) {\n changes.push({ kind: 'page-changed', orbitalName: name });\n break;\n }\n }\n }\n\n return changes;\n}\n\n/**\n * Semantic diff: what .orb CONCEPTS changed between two schema versions.\n *\n * Unlike `diffSchemas()` which produces operational CRUD changes for persistence,\n * this produces concept-level changes (guard-changed, render-ui-changed, etc.)\n * for canvas focus derivation, CLI narration, and selective re-verification.\n */\nexport function diffSchemaSemantics(\n before: OrbitalSchema,\n after: OrbitalSchema,\n): SemanticSchemaChange[] {\n const changes: SemanticSchemaChange[] = [];\n\n const bOrbitals = new Map<string, OrbitalDefinition>();\n for (const o of before.orbitals ?? []) {\n const orb = o as OrbitalDefinition;\n bOrbitals.set(orb.name, orb);\n }\n\n const aOrbitals = new Map<string, OrbitalDefinition>();\n for (const o of after.orbitals ?? []) {\n const orb = o as OrbitalDefinition;\n aOrbitals.set(orb.name, orb);\n }\n\n const added: string[] = [];\n for (const [name] of aOrbitals) {\n if (!bOrbitals.has(name)) {\n changes.push({ kind: 'orbital-added', orbitalName: name });\n added.push(name);\n }\n }\n for (const [name] of bOrbitals) {\n if (!aOrbitals.has(name)) {\n changes.push({ kind: 'orbital-removed', orbitalName: name });\n }\n }\n if (added.length > 1) {\n changes.push({ kind: 'behavior-composed', orbitalName: added[0] });\n }\n\n for (const [name, aOrb] of aOrbitals) {\n const bOrb = bOrbitals.get(name);\n if (bOrb) changes.push(...diffSemanticOrbital(name, bOrb, aOrb));\n }\n\n return changes;\n}\n\n// ============================================================================\n// High-level Orbital Schema Diff (changeset envelope)\n// ============================================================================\n\n/**\n * Source label for a changeset. The persistence layer accepts the canonical\n * agent labels plus `skill-agent:<skill>`-style identifiers, so the type stays\n * open as a string.\n */\nexport type SchemaDiffSource =\n | 'requirements-agent'\n | 'builder-agent'\n | 'user'\n | 'auto-fix'\n | (string & {});\n\n/** Tracking granularity used when generating the diff. */\nexport type SchemaDiffMode = 'initial' | 'update';\n\n/** Author identification carried on the changeset envelope. */\nexport interface SchemaDiffAuthor {\n userId: string;\n name?: string;\n}\n\n/** Options that shape the resulting diff envelope. */\nexport interface SchemaDiffOptions {\n mode: SchemaDiffMode;\n author: SchemaDiffAuthor;\n source: SchemaDiffSource;\n}\n\n/** Per-change entry in the diff envelope. */\nexport interface SchemaDiffChange {\n operation: 'add' | 'modify' | 'remove' | 'rename' | 'merge' | 'set';\n path: string;\n value?: ChangesetValue;\n previousValue?: ChangesetValue;\n}\n\n/** Aggregate orbital/trait deltas surfaced by the diff. */\nexport interface SchemaDiffSummary {\n orbitalsAdded: string[];\n orbitalsRemoved: string[];\n orbitalsModified: string[];\n traitsAdded: string[];\n traitsModified: string[];\n traitsRemoved: string[];\n}\n\n/** Changeset envelope produced by `diffOrbitalSchemas`. */\nexport interface SchemaDiffChangeset {\n id: string;\n source: SchemaDiffSource;\n author: SchemaDiffAuthor;\n description: string;\n changes: SchemaDiffChange[];\n}\n\n/** Result of comparing two OrbitalSchema versions. */\nexport interface SchemaDiff {\n hasChanges: boolean;\n changeCount: number;\n changeset: SchemaDiffChangeset;\n summary: SchemaDiffSummary;\n}\n\n/**\n * Compare two `OrbitalSchema` versions and produce a changeset envelope.\n *\n * Higher-level companion to `diffSchemas`: where `diffSchemas` returns a flat\n * list of `SchemaChange` entries keyed by structural path, this returns the\n * envelope the persistence layer ships to Firestore (id, author, source,\n * summary buckets).\n *\n * Identifier generation: `changeset.id` is a deterministic `chg_<hex>` value\n * derived from the schema name + change count when `globalThis.crypto.randomUUID`\n * is unavailable; otherwise a UUID is used. Callers that need a stable id\n * across regenerations should supply one themselves.\n */\nexport function diffOrbitalSchemas(\n before: OrbitalSchema | null,\n after: OrbitalSchema,\n options: SchemaDiffOptions,\n): SchemaDiff {\n const summary: SchemaDiffSummary = {\n orbitalsAdded: [],\n orbitalsRemoved: [],\n orbitalsModified: [],\n traitsAdded: [],\n traitsModified: [],\n traitsRemoved: [],\n };\n const changes: SchemaDiffChange[] = [];\n\n if (!before) {\n for (const orbital of after.orbitals ?? []) {\n const orb = orbital as OrbitalDefinition;\n summary.orbitalsAdded.push(orb.name);\n changes.push({\n operation: 'add',\n path: `orbitals[${summary.orbitalsAdded.length - 1}]`,\n value: orb,\n });\n }\n } else {\n const beforeOrbitals = new Map<string, OrbitalDefinition>();\n for (const o of before.orbitals ?? []) {\n const orb = o as OrbitalDefinition;\n beforeOrbitals.set(orb.name, orb);\n }\n const afterOrbitals = new Map<string, OrbitalDefinition>();\n for (const o of after.orbitals ?? []) {\n const orb = o as OrbitalDefinition;\n afterOrbitals.set(orb.name, orb);\n }\n\n let idx = 0;\n for (const [name, orb] of afterOrbitals) {\n const prev = beforeOrbitals.get(name);\n if (!prev) {\n summary.orbitalsAdded.push(name);\n changes.push({\n operation: 'add',\n path: `orbitals[${idx}]`,\n value: orb,\n });\n } else if (JSON.stringify(prev) !== JSON.stringify(orb)) {\n summary.orbitalsModified.push(name);\n changes.push({\n operation: 'merge',\n path: `orbitals[${idx}]`,\n previousValue: prev,\n value: orb,\n });\n }\n idx++;\n }\n for (const [name, orb] of beforeOrbitals) {\n if (!afterOrbitals.has(name)) {\n summary.orbitalsRemoved.push(name);\n changes.push({\n operation: 'remove',\n path: `orbitals[${name}]`,\n previousValue: orb,\n });\n }\n }\n\n if (before.name !== after.name) {\n changes.push({\n operation: 'set',\n path: 'name',\n previousValue: before.name,\n value: after.name,\n });\n }\n if (before.version !== after.version) {\n changes.push({\n operation: 'set',\n path: 'version',\n previousValue: before.version,\n value: after.version,\n });\n }\n if (before.description !== after.description) {\n changes.push({\n operation: 'set',\n path: 'description',\n previousValue: before.description,\n value: after.description,\n });\n }\n if (before.summary !== after.summary) {\n changes.push({\n operation: 'set',\n path: 'summary',\n previousValue: before.summary,\n value: after.summary,\n });\n }\n }\n\n const hasChanges = changes.length > 0;\n const description = describeDiff(summary, options.mode, after.name);\n\n return {\n hasChanges,\n changeCount: changes.length,\n changeset: {\n id: generateChangesetId(after.name, changes.length),\n source: options.source,\n author: options.author,\n description,\n changes,\n },\n summary,\n };\n}\n\nfunction describeDiff(\n summary: SchemaDiffSummary,\n mode: SchemaDiffMode,\n schemaName: string,\n): string {\n const parts: string[] = [];\n if (summary.orbitalsAdded.length > 0) {\n parts.push(`+${summary.orbitalsAdded.length} orbital(s)`);\n }\n if (summary.orbitalsModified.length > 0) {\n parts.push(`~${summary.orbitalsModified.length} orbital(s)`);\n }\n if (summary.orbitalsRemoved.length > 0) {\n parts.push(`-${summary.orbitalsRemoved.length} orbital(s)`);\n }\n if (parts.length === 0) return 'No changes';\n return `${mode === 'initial' ? 'Initial' : 'Update'} ${schemaName}: ${parts.join(', ')}`;\n}\n\nfunction generateChangesetId(seed: string, count: number): string {\n const cryptoApi = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (cryptoApi?.randomUUID) return cryptoApi.randomUUID();\n let hash = 0;\n const source = `${seed}:${count}:${Date.now()}`;\n for (let i = 0; i < source.length; i++) {\n hash = (hash * 31 + source.charCodeAt(i)) | 0;\n }\n return `chg_${(hash >>> 0).toString(16)}_${count}`;\n}\n","/**\n * Orbital Summarization\n *\n * Deterministic orbital-to-orbital transformation:\n * full schema in → business skeleton out.\n *\n * Input: OrbitalSchema. Output: OrbitalSchema.\n * Same types — just stripped of implementation details.\n *\n * This module provides functions to extract the essential business structure\n * from a complete orbital schema, removing implementation details like\n * effects, guards, and visual styling while preserving the core entity,\n * trait, and page definitions.\n *\n * @packageDocumentation\n */\n\nimport type { OrbitalSchema } from './types/schema.js';\nimport type { OrbitalDefinition } from './types/orbital.js';\nimport { isEntityCall, isEntityReference, parseEntityRef } from './types/orbital.js';\nimport type { Entity } from './types/entity.js';\nimport type { EntityField } from './types/field.js';\nimport type { Trait } from './types/trait.js';\nimport { isInlineTrait } from './types/trait.js';\nimport type { Page } from './types/page.js';\nimport type { Transition, Event, State } from './types/state-machine.js';\n\n// ============================================================================\n// Workflow Type Detection\n// ============================================================================\n\n/**\n * Standard CRUD state names used for workflow classification.\n * @internal\n */\nconst CRUD_STATES = new Set(['browsing', 'creating', 'editing', 'viewing', 'deleting']);\n\n/**\n * Pattern for detecting wizard-style step states (step1, step2, etc).\n * @internal\n */\nconst STEP_PATTERN = /^step\\d+$/i;\n\n/**\n * Classify a workflow from its state machine states.\n *\n * - CRUD: 3+ states match {browsing, creating, editing, viewing, deleting}\n * - Wizard: 2+ states match /^step\\d+$/i, OR linear chain to terminal state\n * - Custom: everything else\n */\nexport function classifyWorkflow(states: State[]): 'crud' | 'wizard' | 'custom' {\n const names = states.map(s => s.name.toLowerCase());\n\n const crudMatch = names.filter(n => CRUD_STATES.has(n)).length;\n if (crudMatch >= 3) return 'crud';\n\n const stepCount = names.filter(n => STEP_PATTERN.test(n)).length;\n if (stepCount >= 2) return 'wizard';\n\n const hasTerminal = states.some(s => s.isTerminal || s.isFinal);\n const hasComplete = names.some(n =>\n n === 'complete' || n === 'completed' || n === 'done' || n === 'finished'\n );\n if ((hasTerminal || hasComplete) && states.length >= 4 && crudMatch <= 1) {\n return 'wizard';\n }\n\n return 'custom';\n}\n\n// ============================================================================\n// Entity Summarization\n// ============================================================================\n\n/**\n * Check if a field is a primary key.\n * @internal\n */\nfunction isPrimaryKey(field: EntityField): boolean {\n return (field as EntityField & { primaryKey?: boolean }).primaryKey === true;\n}\n\n/**\n * Check if a field is a business field (not primary key, has business meaning).\n * @internal\n */\nfunction isBusinessField(field: EntityField): boolean {\n if (isPrimaryKey(field)) return false;\n if (field.type === 'enum' || field.type === 'relation') return true;\n if (field.required) return true;\n return false;\n}\n\n/**\n * Summarize an entity to its business-relevant fields.\n * @internal\n */\nfunction summarizeEntity(entity: Entity): Entity {\n const fields: EntityField[] = entity.fields.filter(isBusinessField).map(summarizeField);\n return {\n name: entity.name,\n collection: entity.collection,\n fields,\n };\n}\n\nfunction summarizeField(f: EntityField): EntityField {\n if (f.type === 'enum') {\n return {\n ...(f.name !== undefined ? { name: f.name } : {}),\n type: 'enum',\n values: f.values,\n ...(f.required ? { required: true } : {}),\n };\n }\n if (f.type === 'relation') {\n return {\n ...(f.name !== undefined ? { name: f.name } : {}),\n type: 'relation',\n relation: f.relation,\n ...(f.required ? { required: true } : {}),\n };\n }\n if (f.type === 'array') {\n return {\n ...(f.name !== undefined ? { name: f.name } : {}),\n type: 'array',\n items: f.items,\n ...(f.required ? { required: true } : {}),\n };\n }\n return {\n ...(f.name !== undefined ? { name: f.name } : {}),\n type: f.type,\n ...(f.required ? { required: true } : {}),\n };\n}\n\n// ============================================================================\n// Transition Summarization\n// ============================================================================\n\n/**\n * Deduplicate transitions that are identical in (from, to, event).\n * Strips effects and guards.\n */\n/**\n * Deduplicate transitions that are identical in (from, to, event).\n * Strips effects and guards.\n * @internal\n */\nfunction summarizeTransitions(transitions: Transition[]): Transition[] {\n const seen = new Set<string>();\n const result: Transition[] = [];\n\n for (const t of transitions) {\n const key = `${t.from}::${t.to}::${t.event}`;\n if (!seen.has(key)) {\n seen.add(key);\n result.push({ from: t.from, to: t.to, event: t.event });\n }\n }\n\n return result;\n}\n\n// ============================================================================\n// Trait Summarization\n// ============================================================================\n\n/**\n * Summarize events to just their keys.\n * @internal\n */\nfunction summarizeEvents(events: Event[]): Event[] {\n return events.map(e => ({ key: e.key, name: e.key }));\n}\n\n/**\n * Summarize a trait to its essential structure.\n * @internal\n */\nfunction summarizeTrait(trait: Trait): Trait {\n const states = trait.stateMachine?.states ?? [];\n const events = trait.stateMachine?.events ?? [];\n const transitions = trait.stateMachine?.transitions ?? [];\n\n const result: Trait = { name: trait.name, scope: trait.scope };\n if (trait.category) result.category = trait.category;\n if (trait.linkedEntity) result.linkedEntity = trait.linkedEntity;\n\n if (trait.stateMachine) {\n result.stateMachine = {\n states: states.map(s => {\n const st: State = { name: s.name };\n if (s.isInitial) st.isInitial = true;\n if (s.isTerminal) st.isTerminal = true;\n if (s.isFinal) st.isFinal = true;\n return st;\n }),\n events: summarizeEvents(events),\n transitions: summarizeTransitions(transitions),\n };\n }\n\n if (trait.emits && trait.emits.length > 0) {\n result.emits = trait.emits.map(e => ({\n event: e.event,\n ...(e.scope ? { scope: e.scope } : {}),\n }));\n }\n\n if (trait.listens && trait.listens.length > 0) {\n result.listens = trait.listens.map(l => ({\n event: l.event,\n triggers: l.triggers,\n ...(l.scope ? { scope: l.scope } : {}),\n }));\n }\n\n return result;\n}\n\n// ============================================================================\n// Page Summarization\n// ============================================================================\n\n/**\n * Summarize a page to its essential structure.\n * @internal\n */\nfunction summarizePage(page: Page): Page {\n const result: Page = { name: page.name, path: page.path };\n if (page.traits && page.traits.length > 0) {\n result.traits = page.traits.map(t => ({ ref: t.ref }));\n }\n return result;\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Summarize a single orbital into its business skeleton.\n *\n * OrbitalDefinition in → OrbitalDefinition out.\n * Strips effects, guards, payloads, theme, optional fields.\n * Deduplicates transitions on (from, to, event).\n */\nexport function summarizeOrbital(orbital: OrbitalDefinition): OrbitalDefinition {\n let entity: Entity;\n if (isEntityReference(orbital.entity)) {\n entity = { name: orbital.entity, fields: [] };\n } else if (isEntityCall(orbital.entity)) {\n // EntityCall (Phase F): synthesize a placeholder Entity from the call shape.\n // The full inlined entity is only available after the compiler's inline phase.\n const call = orbital.entity;\n const name = call.name ?? parseEntityRef(call.extends)?.alias ?? call.extends;\n entity = {\n name,\n fields: call.fields ?? [],\n ...(call.persistence ? { persistence: call.persistence } : {}),\n ...(call.collection ? { collection: call.collection } : {}),\n };\n } else {\n entity = summarizeEntity(orbital.entity);\n }\n\n const traits = orbital.traits.map(traitRef => {\n if (isInlineTrait(traitRef)) {\n return summarizeTrait(traitRef);\n }\n return traitRef;\n });\n\n const pages = orbital.pages\n .filter((p): p is Page => typeof p === 'object' && 'name' in p && !('ref' in p))\n .map(summarizePage);\n\n return { name: orbital.name, entity, traits, pages };\n}\n\n/**\n * Summarize an entire OrbitalSchema into a business skeleton.\n *\n * OrbitalSchema in → OrbitalSchema out.\n * Strips schema-level metadata (domainContext, design, designTokens, customPatterns).\n */\nexport function summarizeSchema(schema: OrbitalSchema): OrbitalSchema {\n return {\n name: schema.name,\n description: schema.description,\n version: schema.version,\n orbitals: schema.orbitals.map(summarizeOrbital),\n };\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']);\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 (param.key.endsWith('Event')) 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 const label = param.label ?? humanizeKey(param.key);\n const question = `${label}?`;\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: `${call.orbital}.${trait.name}.${param.key}`,\n orbitalName: call.orbital,\n question,\n inputType: deriveInputType(param),\n mutationTemplate: {\n kind: 'set-trait-override-config',\n orbitalName: call.orbital,\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 */\nfunction 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 * 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: `${call.orbital}.__entityFields`,\n orbitalName: call.orbital,\n question: `Which fields should a ${entityName} have?`,\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: call.orbital,\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 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 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 ?? call.orbital;\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: `${call.orbital}.capability.${cap}`,\n orbitalName: call.orbital,\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 * `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 'singleton',\n 'instance',\n 'local',\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 { EntityPersistence } from '../types/entity.js';\nimport type { TraitReference } from '../types/trait.js';\nimport type {\n FactoryCallSite,\n FactoryCallSiteParams,\n FactoryParamValue,\n FactorySignature,\n FactoryTraitSignature,\n} from './types.js';\nimport type {\n OwnershipOverlayEntry,\n PresentationNavItem,\n PresentationOverlay,\n RuleOverlay,\n RuleOverlayEntry,\n TraitOverlay,\n TraitOverlayEntry,\n} from './overlays.js';\n\n/**\n * The per-orbital binding the agent assembles when it picks a\n * signature. Carries the user-authored overrides directly; no shared\n * domain ontology, no DomainDocument.\n */\nexport interface TranslationBinding {\n /** Entity name override. When equal to `signature.entities[0].name`,\n * no rename is emitted. */\n entityName: string;\n /** Extra fields beyond the signature's canonical entity surface. */\n entityFields?: ReadonlyArray<EntityField>;\n /** Persistence override. */\n persistence?: EntityPersistence;\n /** Collection name override. */\n collection?: string;\n /** Per-page path overrides keyed by `signature.pages[i].name`. */\n pagePaths?: Readonly<Record<string, string>>;\n}\n\nexport interface TranslationWarning {\n /** Dotted path of the binding field that couldn't be lowered. */\n field: string;\n /** Human-readable reason. */\n reason: string;\n}\n\nexport interface TranslationResult {\n callSite: FactoryCallSite;\n warnings: ReadonlyArray<TranslationWarning>;\n}\n\nexport function translateOverlaysToParams(\n binding: TranslationBinding,\n signature: FactorySignature,\n presentation?: PresentationOverlay,\n ruleOverlay?: RuleOverlay,\n traitOverlay?: TraitOverlay,\n catalog?: ReadonlyArray<FactorySignature>,\n): TranslationResult {\n const warnings: TranslationWarning[] = [];\n const params: FactoryCallSiteParams = {};\n\n applyEntityName(binding, signature, params);\n applyEntityFields(binding, signature, params);\n applyPersistence(binding, signature, params, warnings);\n applyCollection(binding, params);\n applyPagePaths(binding, signature, params, warnings);\n applyPresentation(presentation, signature, params, warnings);\n applyTraitOverlay(traitOverlay, signature, params, warnings);\n applyRuleOverlay(ruleOverlay, signature, binding, catalog, params, warnings);\n\n return {\n callSite: {\n organism: signature.organism,\n orbital: signature.orbital,\n factoryPath: signature.factoryPath,\n params,\n },\n warnings,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Per-field lowering\n// ---------------------------------------------------------------------------\n\nfunction applyEntityName(\n binding: TranslationBinding,\n signature: FactorySignature,\n params: FactoryCallSiteParams,\n): void {\n if (signature.entities.length === 0) return;\n if (binding.entityName === signature.entities[0].name) return;\n params.entityName = binding.entityName;\n}\n\nfunction applyEntityFields(\n binding: TranslationBinding,\n signature: FactorySignature,\n params: FactoryCallSiteParams,\n): void {\n if (!binding.entityFields || binding.entityFields.length === 0) return;\n if (signature.entities.length === 0) {\n params.entityFields = [...binding.entityFields];\n return;\n }\n const canonical = new Set(signature.entities[0].fields.map((f) => f.name));\n const extras: EntityField[] = [];\n for (const f of binding.entityFields) {\n if (f.name && canonical.has(f.name)) continue;\n extras.push(f);\n }\n if (extras.length > 0) params.entityFields = extras;\n}\n\nfunction applyPersistence(\n binding: TranslationBinding,\n signature: FactorySignature,\n params: FactoryCallSiteParams,\n warnings: TranslationWarning[],\n): void {\n if (!binding.persistence) return;\n if (signature.entities.length === 0) {\n warnings.push({\n field: `entity.${binding.entityName}.persistence`,\n reason: 'factory signature has no entity to apply persistence to',\n });\n return;\n }\n if (binding.persistence === signature.entities[0].persistence) return;\n params.persistence = binding.persistence;\n}\n\nfunction applyCollection(\n binding: TranslationBinding,\n params: FactoryCallSiteParams,\n): void {\n if (!binding.collection) return;\n params.collection = binding.collection;\n}\n\nfunction applyPagePaths(\n binding: TranslationBinding,\n signature: FactorySignature,\n params: FactoryCallSiteParams,\n warnings: TranslationWarning[],\n): void {\n if (!binding.pagePaths) return;\n const sigPages = new Map(signature.pages.map((p) => [p.name, p]));\n const overrides: Record<string, string> = {};\n for (const [pageName, url] of Object.entries(binding.pagePaths)) {\n const sig = sigPages.get(pageName);\n if (!sig) {\n warnings.push({\n field: `page.${pageName}.url`,\n reason: `factory signature has no page named \"${pageName}\"`,\n });\n continue;\n }\n if (sig.defaultPath !== url) overrides[pageName] = url;\n }\n if (Object.keys(overrides).length > 0) params.pagePaths = overrides;\n}\n\nfunction applyPresentation(\n overlay: PresentationOverlay | undefined,\n signature: FactorySignature,\n params: FactoryCallSiteParams,\n warnings: TranslationWarning[],\n): void {\n if (!overlay?.navAdditions || overlay.navAdditions.length === 0) return;\n const target = signature.traits.find((t) =>\n t.overridableConfigKeys.some((p) => p.key === 'navItems'),\n );\n if (!target) {\n warnings.push({\n field: 'presentation.navAdditions',\n reason:\n 'factory signature has no trait advertising a `navItems` config key',\n });\n return;\n }\n const existing = params.traitOverrides?.[target.name] ?? {};\n const existingConfig = existing.config ?? {};\n const items: ReadonlyArray<FactoryParamValue> = overlay.navAdditions.map(\n navItemToParamValue,\n );\n params.traitOverrides = {\n ...params.traitOverrides,\n [target.name]: {\n ...existing,\n config: { ...existingConfig, navItems: items },\n },\n };\n}\n\nfunction applyTraitOverlay(\n overlay: TraitOverlay | undefined,\n signature: FactorySignature,\n params: FactoryCallSiteParams,\n warnings: TranslationWarning[],\n): void {\n if (!overlay) return;\n const traitsByName = new Map(signature.traits.map((t) => [t.name, t]));\n for (const [traitName, entry] of Object.entries(overlay)) {\n const trait = traitsByName.get(traitName);\n if (!trait) {\n warnings.push({\n field: `traitOverlay.${traitName}`,\n reason: `factory signature has no trait named \"${traitName}\"`,\n });\n continue;\n }\n mergeTraitOverride(traitName, entry, trait, params, warnings);\n }\n}\n\nfunction mergeTraitOverride(\n traitName: string,\n entry: TraitOverlayEntry,\n trait: FactoryTraitSignature,\n params: FactoryCallSiteParams,\n warnings: TranslationWarning[],\n): void {\n const advertised = new Set(trait.overridableConfigKeys.map((p) => p.key));\n const existing = params.traitOverrides?.[traitName] ?? {};\n const existingConfig = existing.config ?? {};\n const mergedConfig: Record<string, FactoryParamValue> = { ...existingConfig };\n\n if (entry.config) {\n for (const [k, v] of Object.entries(entry.config)) {\n if (!advertised.has(k)) {\n const advertisedKeys = trait.overridableConfigKeys.map((p) => p.key).join(', ');\n warnings.push({\n field: `traitOverlay.${traitName}.config.${k}`,\n reason: `trait does not advertise config key \"${k}\" (overridableConfigKeys: [${advertisedKeys}])`,\n });\n continue;\n }\n mergedConfig[k] = v;\n }\n }\n\n // Thread every documented override field through verbatim — `config`\n // gets the merged + validated map; the rest pass through as the overlay\n // authored them. Pre-unification only `config` was preserved, so any\n // overlay-authored `linkedEntity` / `events` / `name` / `emitsScope` /\n // `listens` was silently dropped before reaching the factory.\n params.traitOverrides = {\n ...params.traitOverrides,\n [traitName]: {\n ...existing,\n ...(Object.keys(mergedConfig).length > 0 ? { config: mergedConfig } : {}),\n ...(entry.linkedEntity !== undefined ? { linkedEntity: entry.linkedEntity } : {}),\n ...(entry.events !== undefined ? { events: entry.events } : {}),\n ...(entry.name !== undefined ? { name: entry.name } : {}),\n ...(entry.emitsScope !== undefined ? { emitsScope: entry.emitsScope } : {}),\n ...(entry.listens !== undefined ? { listens: entry.listens } : {}),\n },\n };\n}\n\nfunction applyRuleOverlay(\n overlay: RuleOverlay | undefined,\n signature: FactorySignature,\n binding: TranslationBinding,\n catalog: ReadonlyArray<FactorySignature> | undefined,\n params: FactoryCallSiteParams,\n warnings: TranslationWarning[],\n): void {\n if (!overlay) return;\n\n // `rule.appliesTo` is frozen at the name in scope when the rule was\n // CAPTURED — typically the canonical entity name. If the caller later\n // rebinds via `params.entityName`, `binding.entityName` carries the\n // rebound name and a direct equality check fails. Match against BOTH\n // the rebound name (current binding) AND the canonical name (the\n // signature's authored entity) so cross-turn rule references survive\n // entity renames.\n const matchableNames = collectMatchableEntityNames(signature, binding);\n\n for (const rule of overlay.rules) {\n if (!ruleAppliesToAnyName(rule, matchableNames)) continue;\n if (!catalog) {\n warnings.push({\n field: `ruleOverlay.rules.${rule.id}`,\n reason: 'rule overlay supplied without a catalog — capability lookup requires one',\n });\n continue;\n }\n const match = findTraitByCapability(catalog, rule.capability);\n if (!match) {\n warnings.push({\n field: `ruleOverlay.rules.${rule.id}`,\n reason: `no trait in the catalog advertises capability \"${rule.capability}\"`,\n });\n continue;\n }\n appendRuleExtraTrait(rule, match, binding, params);\n if (rule.config) {\n threadRuleConfig(rule, match.trait, params, warnings);\n }\n }\n\n if (overlay.ownership) {\n for (const entry of overlay.ownership) {\n if (!matchableNames.includes(entry.entity)) continue;\n applyOwnership(entry, params, signature, catalog, warnings);\n }\n }\n}\n\n/**\n * Names the rule overlay may legitimately target for THIS binding.\n * Includes the rebound entity name (current `binding.entityName`) AND\n * every canonical name on `signature.entities[*]`. Deduped, empty-safe.\n */\nfunction collectMatchableEntityNames(\n signature: FactorySignature,\n binding: TranslationBinding,\n): ReadonlyArray<string> {\n const out = new Set<string>();\n if (binding.entityName.length > 0) out.add(binding.entityName);\n for (const ent of signature.entities) {\n if (typeof ent.name === 'string' && ent.name.length > 0) out.add(ent.name);\n }\n return [...out];\n}\n\nfunction ruleAppliesToAnyName(\n rule: RuleOverlayEntry,\n matchableNames: ReadonlyArray<string>,\n): boolean {\n if (rule.appliesTo.length === 0) return true;\n for (const n of rule.appliesTo) {\n if (matchableNames.includes(n)) return true;\n }\n return false;\n}\n\ninterface CapabilityMatch {\n signature: FactorySignature;\n trait: FactoryTraitSignature;\n}\n\nfunction findTraitByCapability(\n catalog: ReadonlyArray<FactorySignature>,\n capability: string,\n): CapabilityMatch | undefined {\n for (const sig of catalog) {\n for (const trait of sig.traits) {\n if (trait.capabilities.includes(capability)) {\n return { signature: sig, trait };\n }\n }\n }\n return undefined;\n}\n\nfunction appendRuleExtraTrait(\n _rule: RuleOverlayEntry,\n match: CapabilityMatch,\n binding: TranslationBinding,\n params: FactoryCallSiteParams,\n): void {\n const fromPath = `std/behaviors/${match.signature.organism}`;\n const alias = organismToAlias(match.signature.organism);\n const ref: TraitReference = {\n from: fromPath,\n ref: `${alias}.traits.${match.trait.name}`,\n linkedEntity: binding.entityName,\n };\n const existing = params.extraTraits ?? [];\n params.extraTraits = [...existing, ref];\n}\n\nfunction organismToAlias(organism: string): string {\n const trimmed = organism.startsWith('std-') ? organism.slice(4) : organism;\n return trimmed\n .split('-')\n .filter((s) => s.length > 0)\n .map((s) => s.charAt(0).toUpperCase() + s.slice(1))\n .join('');\n}\n\nfunction threadRuleConfig(\n rule: RuleOverlayEntry,\n trait: FactoryTraitSignature,\n params: FactoryCallSiteParams,\n warnings: TranslationWarning[],\n): void {\n if (!rule.config) return;\n const advertised = new Set(trait.overridableConfigKeys.map((p) => p.key));\n const existing = params.traitOverrides?.[trait.name] ?? {};\n const existingConfig = existing.config ?? {};\n const merged: Record<string, FactoryParamValue> = { ...existingConfig };\n for (const [k, v] of Object.entries(rule.config)) {\n if (!advertised.has(k)) {\n warnings.push({\n field: `ruleOverlay.rules.${rule.id}.config.${k}`,\n reason: `trait \"${trait.name}\" does not advertise config key \"${k}\"`,\n });\n continue;\n }\n merged[k] = v;\n }\n if (Object.keys(merged).length > 0) {\n params.traitOverrides = {\n ...params.traitOverrides,\n [trait.name]: { ...existing, config: merged },\n };\n }\n}\n\nfunction applyOwnership(\n entry: OwnershipOverlayEntry,\n params: FactoryCallSiteParams,\n signature: FactorySignature,\n catalog: ReadonlyArray<FactorySignature> | undefined,\n warnings: TranslationWarning[],\n): void {\n const local = signature.traits.find((t) =>\n t.overridableConfigKeys.some((p) => p.key === 'ownerField'),\n );\n if (local) {\n writeOwnerField(local.name, entry.ownerField, params);\n return;\n }\n if (catalog) {\n for (const sig of catalog) {\n const trait = sig.traits.find((t) =>\n t.overridableConfigKeys.some((p) => p.key === 'ownerField'),\n );\n if (trait) {\n writeOwnerField(trait.name, entry.ownerField, params);\n return;\n }\n }\n }\n warnings.push({\n field: `ruleOverlay.ownership.${entry.entity}`,\n reason: 'no trait in the bound signature or catalog advertises an `ownerField` config knob',\n });\n}\n\nfunction writeOwnerField(\n traitName: string,\n ownerField: string,\n params: FactoryCallSiteParams,\n): void {\n const existing = params.traitOverrides?.[traitName] ?? {};\n const existingConfig = existing.config ?? {};\n params.traitOverrides = {\n ...params.traitOverrides,\n [traitName]: {\n ...existing,\n config: { ...existingConfig, ownerField },\n },\n };\n}\n\nfunction navItemToParamValue(item: PresentationNavItem): FactoryParamValue {\n const out: Record<string, FactoryParamValue> = {\n label: item.label,\n path: item.path,\n };\n if (item.icon) out.icon = item.icon;\n return out;\n}\n","/**\n * Structural diff between two `FactoryCallSite[]` lists. Pure typed,\n * no side effects. Used by downstream consumers (agent planner, UI\n * cascade view) to turn a \"previous calls\" + \"next calls\" pair into a\n * minimal change set.\n *\n * Identity for diffing is `(organism, orbital)`. Renames are not\n * handled here — they show up as a delete + add. The agent layer is\n * expected to merge those back into a `'rename'` op if it can prove\n * the underlying domain entity was renamed.\n */\n\nimport type {\n FactoryCallSite,\n FactoryCallSiteParams,\n FactoryParamValue,\n} from './types.js';\n\nexport type CallSiteDiff =\n | { kind: 'add'; orbitalName: string; next: FactoryCallSite }\n | { kind: 'delete'; orbitalName: string; prior: FactoryCallSite }\n | {\n kind: 'edit';\n orbitalName: string;\n prior: FactoryCallSite;\n next: FactoryCallSite;\n }\n | { kind: 'keep'; orbitalName: string; call: FactoryCallSite };\n\nexport function diffFactoryCalls(\n prior: ReadonlyArray<FactoryCallSite>,\n next: ReadonlyArray<FactoryCallSite>,\n): ReadonlyArray<CallSiteDiff> {\n const out: CallSiteDiff[] = [];\n const priorByKey = new Map(prior.map((c) => [callKey(c), c]));\n const nextByKey = new Map(next.map((c) => [callKey(c), c]));\n\n for (const [key, p] of priorByKey) {\n const n = nextByKey.get(key);\n if (!n) {\n out.push({ kind: 'delete', orbitalName: p.orbital, prior: p });\n continue;\n }\n if (paramsEqual(p.params, n.params)) {\n out.push({ kind: 'keep', orbitalName: p.orbital, call: n });\n } else {\n out.push({ kind: 'edit', orbitalName: p.orbital, prior: p, next: n });\n }\n }\n for (const [key, n] of nextByKey) {\n if (!priorByKey.has(key)) {\n out.push({ kind: 'add', orbitalName: n.orbital, next: n });\n }\n }\n return out;\n}\n\nfunction callKey(c: FactoryCallSite): string {\n return `${c.organism}::${c.orbital}`;\n}\n\nfunction paramsEqual(a: FactoryCallSiteParams, b: FactoryCallSiteParams): boolean {\n return canonicalParams(a) === canonicalParams(b);\n}\n\nfunction canonicalParams(p: FactoryCallSiteParams): string {\n const keys: Array<keyof FactoryCallSiteParams> = [\n 'collection',\n 'entityFields',\n 'entityName',\n 'extraTraits',\n 'pagePaths',\n 'persistence',\n 'traitOverrides',\n ];\n const parts: string[] = [];\n for (const k of keys) {\n const v = p[k];\n if (v === undefined) continue;\n parts.push(`${k}:${canonicalNode(v)}`);\n }\n return `{${parts.join(',')}}`;\n}\n\nfunction canonicalNode(\n v:\n | string\n | FactoryCallSiteParams[keyof FactoryCallSiteParams],\n): string {\n if (v === undefined) return 'u';\n if (typeof v === 'string') return JSON.stringify(v);\n if (Array.isArray(v)) {\n return `[${v.map((x) => canonicalParamValue(x as FactoryParamValue)).join(',')}]`;\n }\n const keys = Object.keys(v).sort();\n const parts: string[] = [];\n for (const k of keys) {\n const child = (v as Readonly<Record<string, FactoryParamValue | { config?: Readonly<Record<string, FactoryParamValue>> }>>)[k];\n parts.push(`${JSON.stringify(k)}:${canonicalParamValue(child)}`);\n }\n return `{${parts.join(',')}}`;\n}\n\nfunction canonicalParamValue(\n v: FactoryParamValue | { config?: Readonly<Record<string, FactoryParamValue>> },\n): string {\n if (v === null || v === undefined) return 'u';\n if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') {\n return JSON.stringify(v);\n }\n if (Array.isArray(v)) {\n return `[${v.map(canonicalParamValue).join(',')}]`;\n }\n const keys = Object.keys(v).sort();\n const parts: string[] = [];\n for (const k of keys) {\n const child = (v as Readonly<Record<string, FactoryParamValue | undefined>>)[k];\n if (child === undefined) continue;\n parts.push(`${JSON.stringify(k)}:${canonicalParamValue(child)}`);\n }\n return `{${parts.join(',')}}`;\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 * Layout Strategy Detection\n *\n * Auto-detects the best layout strategy for a composed application\n * based on the number of orbitals and their event wiring topology.\n *\n * @packageDocumentation\n */\n\nimport type { OrbitalDefinition } from '../types/orbital.js';\nimport type { EventWiringEntry } from './event-wiring.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Layout strategy for the composed application.\n *\n * - 'single': One orbital, one page\n * - 'tabs': 2-4 orbitals with no sequential chain\n * - 'sidebar': 5+ orbitals (navigation-heavy)\n * - 'dashboard': Single page with all orbitals visible\n * - 'wizard-flow': Sequential event chain detected (A -> B -> C)\n */\nexport type LayoutStrategy =\n | 'sidebar'\n | 'tabs'\n | 'dashboard'\n | 'wizard-flow'\n | 'single';\n\n// ============================================================================\n// Chain Detection\n// ============================================================================\n\n/**\n * Detect whether the event wiring forms a sequential chain.\n *\n * A sequential chain exists when orbital A's `from` feeds into B's `to`,\n * and B's `from` feeds into C's `to`, forming A -> B -> C.\n *\n * We build a directed graph from wiring entries and look for a chain\n * that covers 3+ nodes (the minimum for a meaningful wizard flow).\n */\nfunction hasSequentialChain(wiring: EventWiringEntry[]): boolean {\n if (wiring.length < 2) {\n return false;\n }\n\n // Build adjacency: from -> Set<to>\n const adjacency = new Map<string, Set<string>>();\n const allTargets = new Set<string>();\n\n for (const entry of wiring) {\n let targets = adjacency.get(entry.from);\n if (!targets) {\n targets = new Set<string>();\n adjacency.set(entry.from, targets);\n }\n targets.add(entry.to);\n allTargets.add(entry.to);\n }\n\n // Find roots (nodes that are sources but never targets)\n const roots: string[] = [];\n for (const from of adjacency.keys()) {\n if (!allTargets.has(from)) {\n roots.push(from);\n }\n }\n\n // If no clear root, try all sources\n const starts = roots.length > 0 ? roots : [...adjacency.keys()];\n\n // Walk from each start and measure chain length\n for (const start of starts) {\n let current = start;\n let length = 1;\n const visited = new Set<string>([current]);\n\n while (true) {\n const nexts = adjacency.get(current);\n if (!nexts || nexts.size === 0) break;\n\n // Follow the first unvisited successor (linear chain)\n let advanced = false;\n for (const next of nexts) {\n if (!visited.has(next)) {\n visited.add(next);\n current = next;\n length++;\n advanced = true;\n break;\n }\n }\n\n if (!advanced) break;\n }\n\n // A chain of 3+ nodes qualifies as wizard-flow\n if (length >= 3) {\n return true;\n }\n }\n\n return false;\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Detect the best layout strategy based on orbital count and event wiring.\n *\n * Heuristic:\n * 1. Sequential event chain detected -> 'wizard-flow'\n * 2. 1 orbital -> 'single'\n * 3. 2-4 orbitals -> 'tabs'\n * 4. 5+ orbitals -> 'sidebar'\n */\nexport function detectLayoutStrategy(\n orbitals: OrbitalDefinition[],\n eventWiring?: EventWiringEntry[],\n): LayoutStrategy {\n // Check for sequential chain first (takes priority)\n if (eventWiring && eventWiring.length > 0 && hasSequentialChain(eventWiring)) {\n return 'wizard-flow';\n }\n\n const count = orbitals.length;\n\n if (count <= 1) {\n return 'single';\n }\n\n if (count <= 4) {\n return 'tabs';\n }\n\n return 'sidebar';\n}\n","/**\n * Event Wiring\n *\n * Applies cross-orbital event wiring to orbital definitions.\n * Adds emits/listens declarations to traits so they can communicate\n * across orbital boundaries.\n *\n * @packageDocumentation\n */\n\nimport type { OrbitalDefinition } from '../types/orbital.js';\nimport type { Trait, TraitEventContract, TraitEventListener } from '../types/trait.js';\nimport { isInlineTrait } from '../types/trait.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * A single event wiring entry connecting two traits across orbitals.\n */\nexport interface EventWiringEntry {\n /** Source trait name or orbital name */\n from: string;\n /** Event name (UPPER_SNAKE_CASE) */\n event: string;\n /** Target trait name or orbital name */\n to: string;\n /** Event to trigger on the listener side */\n triggers: string;\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/**\n * Find a trait by name across all orbitals.\n * Only inline traits can be mutated; string/ref traits are skipped.\n * Returns the inline Trait object if found, or null.\n */\nfunction findInlineTrait(\n orbitals: OrbitalDefinition[],\n name: string,\n): Trait | null {\n for (const orbital of orbitals) {\n for (const traitRef of orbital.traits) {\n if (isInlineTrait(traitRef) && traitRef.name === name) {\n return traitRef;\n }\n }\n }\n return null;\n}\n\n/**\n * Check if an emit already exists in the list.\n * @internal\n */\nfunction hasEmit(emits: TraitEventContract[], event: string): boolean {\n return emits.some((e) => e.event === event);\n}\n\n/**\n * Check if a listen already exists in the list.\n * @internal\n */\nfunction hasListen(\n listens: TraitEventListener[],\n event: string,\n triggers: string,\n): boolean {\n return listens.some((l) => l.event === event && l.triggers === triggers);\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Apply event wiring to orbital definitions.\n *\n * For each wiring entry:\n * 1. Find the source trait and add an external emit (if not already present)\n * 2. Find the target trait and add an external listen (if not already present)\n *\n * Returns a new array of orbitals with wiring applied (deep-cloned).\n */\nexport function applyEventWiring(\n orbitals: OrbitalDefinition[],\n wiring: EventWiringEntry[],\n): OrbitalDefinition[] {\n // Deep clone to avoid mutating input\n const cloned: OrbitalDefinition[] = JSON.parse(\n JSON.stringify(orbitals),\n ) as OrbitalDefinition[];\n\n for (const entry of wiring) {\n // Wire the source: add emit\n const sourceTrait = findInlineTrait(cloned, entry.from);\n if (sourceTrait) {\n if (!sourceTrait.emits) {\n sourceTrait.emits = [];\n }\n if (!hasEmit(sourceTrait.emits, entry.event)) {\n sourceTrait.emits.push({\n event: entry.event,\n scope: 'external',\n });\n }\n }\n\n // Wire the target: add listen\n const targetTrait = findInlineTrait(cloned, entry.to);\n if (targetTrait) {\n if (!targetTrait.listens) {\n targetTrait.listens = [];\n }\n if (!hasListen(targetTrait.listens, entry.event, entry.triggers)) {\n targetTrait.listens.push({\n event: entry.event,\n triggers: entry.triggers,\n scope: 'external',\n });\n }\n }\n }\n\n return cloned;\n}\n","/**\n * Compose Behaviors\n *\n * Main entry point for composing multiple orbital definitions into\n * a single OrbitalSchema application. Handles event wiring, layout\n * strategy detection, and page generation.\n *\n * @packageDocumentation\n */\n\nimport type { OrbitalDefinition } from '../types/orbital.js';\nimport type { OrbitalSchema } from '../types/schema.js';\n\n/** Unwrap OrbitalSchema | OrbitalDefinition inputs to a flat OrbitalDefinition[]. */\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}\nimport type { Page } from '../types/page.js';\nimport type { EventWiringEntry } from './event-wiring.js';\nimport { applyEventWiring } from './event-wiring.js';\nimport type { LayoutStrategy } from './layout-strategy.js';\nimport { detectLayoutStrategy } from './layout-strategy.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Input for composing behaviors into an application.\n */\nexport interface ComposeBehaviorsInput {\n /** Application name */\n appName: string;\n /** Orbital definitions (or schemas) to compose */\n orbitals: (OrbitalDefinition | OrbitalSchema)[];\n /** Layout strategy override, or 'auto' to detect */\n layoutStrategy?: LayoutStrategy | 'auto';\n /** Cross-orbital event wiring */\n eventWiring?: EventWiringEntry[];\n /** Optional entity name mappings (original -> renamed) */\n entityMappings?: Record<string, string>;\n}\n\n/**\n * Result of composing behaviors.\n */\nexport interface ComposeBehaviorsResult {\n /** The composed OrbitalSchema */\n schema: OrbitalSchema;\n /** Layout metadata */\n layout: { strategy: LayoutStrategy; pageCount: number };\n /** Wiring metadata */\n wiring: { connections: number };\n}\n\n// ============================================================================\n// Page Generation\n// ============================================================================\n\nfunction toKebabCase(name: string): string {\n return name\n .replace(/([a-z])([A-Z])/g, '$1-$2')\n .replace(/[\\s_]+/g, '-')\n .toLowerCase();\n}\n\n/**\n * Generate pages for each orbital based on the layout strategy.\n *\n * For strategies that produce one page per orbital (sidebar, tabs, wizard-flow),\n * each orbital gets a page at `/<kebab-name>` with `isInitial` on the first.\n *\n * For 'dashboard', all orbitals share a single page.\n * For 'single', the lone orbital gets a single root page.\n */\nfunction generatePages(\n orbitals: OrbitalDefinition[],\n strategy: LayoutStrategy,\n): Page[] {\n switch (strategy) {\n case 'single': {\n const orbital = orbitals[0];\n const name = orbital?.name ?? 'Main';\n return [\n {\n name: `${name}Page`,\n path: '/',\n isInitial: true,\n primaryEntity: getEntityName(orbital),\n },\n ];\n }\n\n case 'dashboard': {\n return [\n {\n name: 'DashboardPage',\n path: '/',\n viewType: 'dashboard',\n isInitial: true,\n },\n ];\n }\n\n case 'sidebar':\n case 'tabs':\n case 'wizard-flow': {\n return orbitals.map((orbital, index) => ({\n name: `${orbital.name}Page`,\n path: index === 0 ? '/' : `/${toKebabCase(orbital.name)}`,\n isInitial: index === 0,\n primaryEntity: getEntityName(orbital),\n }));\n }\n }\n}\n\n/**\n * Extract entity name from an orbital definition.\n * Handles both inline entities and string references.\n */\nfunction getEntityName(orbital: OrbitalDefinition | undefined): string | undefined {\n if (!orbital) return undefined;\n const entity = orbital.entity;\n if (typeof entity === 'string') {\n // Reference like \"Alias.entity\" - extract the alias as entity name\n return entity.replace('.entity', '');\n }\n return entity.name;\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Compose multiple orbital definitions into a single application schema.\n *\n * Steps:\n * 1. Apply event wiring (adds emits/listens to traits)\n * 2. Detect or use provided layout strategy\n * 3. Generate pages based on the strategy\n * 4. Build the final OrbitalSchema\n */\nexport function composeBehaviors(\n input: ComposeBehaviorsInput,\n): ComposeBehaviorsResult {\n const {\n appName,\n orbitals: rawInputs,\n layoutStrategy: strategyInput,\n eventWiring,\n } = input;\n\n // Unwrap any OrbitalSchema inputs to OrbitalDefinition[]\n const rawOrbitals = asDefinitions(rawInputs);\n\n // Step 1: Apply event wiring\n const wiredOrbitals =\n eventWiring && eventWiring.length > 0\n ? applyEventWiring(rawOrbitals, eventWiring)\n : rawOrbitals;\n\n // Step 2: Determine layout strategy\n const strategy: LayoutStrategy =\n !strategyInput || strategyInput === 'auto'\n ? detectLayoutStrategy(wiredOrbitals, eventWiring)\n : strategyInput;\n\n // Step 3: Generate pages\n const pages = generatePages(wiredOrbitals, strategy);\n\n // Step 4: Assign generated pages to orbitals (merge, don't replace existing)\n const orbitalsWithPages = wiredOrbitals.map((orbital, index) => {\n // If the orbital already has pages, keep them\n if (orbital.pages && orbital.pages.length > 0) {\n return orbital;\n }\n\n // Assign the generated page for this orbital\n const page = strategy === 'dashboard' || strategy === 'single'\n ? pages[0]\n : pages[index];\n\n return {\n ...orbital,\n pages: page ? [page] : [],\n };\n });\n\n // Step 5: Build the schema\n const schema: OrbitalSchema = {\n name: appName,\n version: '1.0.0',\n orbitals: orbitalsWithPages,\n };\n\n return {\n schema,\n layout: {\n strategy,\n pageCount: pages.length,\n },\n wiring: {\n connections: eventWiring?.length ?? 0,\n },\n };\n}\n","/**\n * State Graph Construction\n *\n * Build an adjacency list from state machine transitions.\n * Extracted from orbital-verify-unified/src/analyze.ts.\n *\n * @packageDocumentation\n */\n\nimport type { GraphTransition, StateEdge } from './types.js';\n\n/**\n * Builds an adjacency list from state machine transitions.\n * \n * Constructs a state transition graph where each state maps to an array\n * of outgoing edges (events and target states). Wildcard transitions\n * (from === '*') are excluded since they don't represent fixed edges.\n * Used as the foundation for state machine analysis, traversal, and verification.\n * \n * @param {GraphTransition[]} transitions - Array of state transitions\n * @returns {Map<string, StateEdge[]>} State transition graph\n * \n * @example\n * const graph = buildStateGraph(transitions);\n * const edgesFromInitial = graph.get('initial'); // Array of outgoing edges\n * console.log(`Initial state has ${edgesFromInitial?.length} transitions`);\n */\nexport function buildStateGraph(\n transitions: GraphTransition[]\n): Map<string, StateEdge[]> {\n const graph = new Map<string, StateEdge[]>();\n for (const t of transitions) {\n if (t.from === '*') continue;\n if (!graph.has(t.from)) graph.set(t.from, []);\n graph.get(t.from)!.push({ event: t.event, to: t.to });\n }\n return graph;\n}\n","/**\n * BFS Reachability Algorithms\n *\n * Breadth-first search over state machine graphs.\n * Extracted from orbital-verify-unified/src/analyze.ts and phase3-server.ts.\n *\n * @packageDocumentation\n */\n\nimport type { BFSNode, StateEdge } from './types.js';\nimport { buildStateGraph } from './graph.js';\nimport type { GraphTransition } from './types.js';\n\n/**\n * Collects all reachable states from an initial state using breadth-first search.\n * \n * Performs BFS traversal of the state machine to find all states reachable\n * from the initial state, up to the specified maximum depth. Used for\n * state machine analysis, verification, and test coverage assessment.\n * \n * @param {GraphTransition[]} transitions - Array of state transitions\n * @param {string} initialState - Starting state name\n * @param {number} [maxDepth=5] - Maximum search depth\n * @returns {Set<string>} Set of reachable state names\n * \n * @example\n * const reachable = collectReachableStates(transitions, 'initial', 10);\n * console.log('Reachable states:', Array.from(reachable));\n */\nexport function collectReachableStates(\n transitions: GraphTransition[],\n initialState: string,\n maxDepth = 5\n): Set<string> {\n const graph = buildStateGraph(transitions);\n const visited = new Set<string>([initialState]);\n const queue: BFSNode[] = [{ state: initialState, depth: 0 }];\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n if (current.depth >= maxDepth) continue;\n\n const edges = graph.get(current.state) ?? [];\n for (const edge of edges) {\n if (!visited.has(edge.to)) {\n visited.add(edge.to);\n queue.push({ state: edge.to, depth: current.depth + 1 });\n }\n }\n }\n\n return visited;\n}\n\n/**\n * Walks all reachable (state, event) pairs using BFS and invokes callback for each.\n * \n * Traverses the state machine using breadth-first search and calls the visitor\n * function for each (state, edge) pair encountered. Used by server verification\n * to test transitions by POSTing to endpoints and checking responses.\n * \n * @param {GraphTransition[]} transitions - Array of state transitions\n * @param {string} initialState - Starting state name\n * @param {number} maxDepth - Maximum BFS depth\n * @param {(state: string, edge: StateEdge, depth: number) => Promise<boolean>} visitor - Callback for each pair\n * @returns {Promise<{ visitedPairs: Set<string>; walkedEdges: number }>} Traversal statistics\n * \n * @example\n * const result = await walkStatePairs(transitions, 'initial', 5, async (state, edge) => {\n * console.log(`Transition: ${state} --${edge.event}--> ${edge.to}`);\n * return true; // Continue exploration\n * });\n * console.log(`Visited ${result.visitedPairs.size} state-event pairs`);\n */\nexport async function walkStatePairs(\n transitions: GraphTransition[],\n initialState: string,\n maxDepth: number,\n visitor: (state: string, edge: StateEdge, depth: number) => Promise<boolean>\n): Promise<{ visitedPairs: Set<string>; walkedEdges: number }> {\n const graph = buildStateGraph(transitions);\n const visitedPairs = new Set<string>();\n const queue: BFSNode[] = [{ state: initialState, depth: 0 }];\n let walkedEdges = 0;\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n if (current.depth >= maxDepth) continue;\n\n const edges = graph.get(current.state) ?? [];\n for (const edge of edges) {\n const pairKey = `${current.state}:${edge.event}`;\n if (visitedPairs.has(pairKey)) continue;\n visitedPairs.add(pairKey);\n\n const shouldEnqueue = await visitor(current.state, edge, current.depth);\n walkedEdges++;\n\n if (shouldEnqueue) {\n const stateVisited = [...visitedPairs].some((k) => k.startsWith(`${edge.to}:`));\n if (!stateVisited) {\n queue.push({ state: edge.to, depth: current.depth + 1 });\n }\n }\n }\n }\n\n return { visitedPairs, walkedEdges };\n}\n","/**\n * Guard Payload Builder\n *\n * Derive pass and fail payloads from guard s-expressions.\n * Extracted from orbital-verify-unified/src/analyze.ts.\n *\n * @packageDocumentation\n */\n\nimport type { GuardPayload } from './types.js';\n\n/**\n * Extracts the first segment of a payload field reference.\n * \n * Parses binding references in the format \"@payload.field\" and extracts\n * the first field name segment. Used for identifying payload fields in\n * guard conditions for test data generation.\n * \n * @param {unknown} ref - Binding reference to extract from\n * @returns {string | null} First field segment or null for non-payload references\n * \n * @example\n * extractPayloadFieldRef('@payload.item'); // returns 'item'\n * extractPayloadFieldRef('@payload.data.weight'); // returns 'data'\n * extractPayloadFieldRef('@entity.id'); // returns null\n * extractPayloadFieldRef('@user.name'); // returns null\n */\nexport function extractPayloadFieldRef(ref: unknown): string | null {\n if (typeof ref !== 'string') return null;\n const match = ref.match(/^@payload\\.([A-Za-z0-9_]+)/);\n return match ? match[1] : null;\n}\n\n/**\n * Builds test payloads that satisfy or violate guard conditions.\n * \n * Generates pass/fail test data for guard s-expressions used in state machine\n * transitions. Pass payloads satisfy the guard condition (allowing transition),\n * fail payloads violate it (blocking transition). Used for automated testing\n * and validation of state machine behavior.\n * \n * Supports operators: not-nil, nil, eq, not-eq, gt, gte, lt, lte, and, or, not\n * \n * @param {unknown} guard - Guard s-expression to analyze\n * @returns {GuardPayload} Object with pass and fail payloads\n * \n * @example\n * // Guard: ['not-nil', '@payload.completed']\n * buildGuardPayloads(['not-nil', '@payload.completed']);\n * // Returns: { pass: { completed: 'mock-test-value' }, fail: { completed: null } }\n * \n * @example\n * // Guard: ['eq', '@payload.status', 'active']\n * buildGuardPayloads(['eq', '@payload.status', 'active']);\n * // Returns: { pass: { status: 'active' }, fail: { status: 'not-active' } }\n * \n * @example\n * // Guard: ['and', ['not-nil', '@payload.id'], ['eq', '@payload.status', 'ready']]\n * buildGuardPayloads(['and', ['not-nil', '@payload.id'], ['eq', '@payload.status', 'ready']]);\n * // Returns: { pass: { id: 'mock-test-value', status: 'ready' }, fail: { id: null } }\n */\n/**\n * Evaluate a guard that is fully constant (no `@payload`/`@entity`/`@config`\n * bindings — e.g. after molecule/organism inlining folds `@config.mode` to a\n * literal). Returns the constant truth value, or `null` when the guard depends\n * on a binding (so a payload must be synthesized). This lets callers (a) emit\n * an empty payload for a constant guard (no field to satisfy) and (b) skip the\n * meaningless variant: an always-true guard has no fail case, an always-false\n * guard has no pass case. Without it, `(or (= \"create\" \"create\") @payload.row)`\n * (create-mode modal OPEN) was synthesized with a spurious `row`, which the\n * runtime read as edit-mode and rejected.\n */\nexport function constTruth(guard: unknown): boolean | null {\n if (typeof guard === 'boolean') return guard;\n if (typeof guard === 'string') {\n if (guard.startsWith('@')) return null; // a binding — not constant\n return guard.length > 0; // bare non-binding literal: truthy iff non-empty\n }\n if (!Array.isArray(guard) || guard.length === 0) return null;\n const op = String(guard[0]);\n const isLiteral = (x: unknown): boolean =>\n x === null ||\n typeof x === 'number' ||\n typeof x === 'boolean' ||\n (typeof x === 'string' && !x.startsWith('@'));\n if (op === '=' || op === '==' || op === 'eq') {\n return isLiteral(guard[1]) && isLiteral(guard[2]) ? guard[1] === guard[2] : null;\n }\n if (op === '!=' || op === 'ne' || op === 'not-eq' || op === 'neq') {\n return isLiteral(guard[1]) && isLiteral(guard[2]) ? guard[1] !== guard[2] : null;\n }\n if (op === 'not') {\n const inner = constTruth(guard[1]);\n return inner === null ? null : !inner;\n }\n if (op === 'or') {\n const subs = (guard.slice(1) as unknown[]).map(constTruth);\n if (subs.some((s) => s === true)) return true; // short-circuit\n if (subs.every((s) => s === false)) return false;\n return null;\n }\n if (op === 'and') {\n const subs = (guard.slice(1) as unknown[]).map(constTruth);\n if (subs.some((s) => s === false)) return false; // short-circuit\n if (subs.every((s) => s === true)) return true;\n return null;\n }\n return null;\n}\n\nexport function buildGuardPayloads(guard: unknown): GuardPayload {\n // A fully-constant guard (post-inline literal fold) is decided by its\n // literals, not by the payload — synthesize nothing for either case.\n if (constTruth(guard) !== null) {\n return { pass: {}, fail: {} };\n }\n // Bare-binding existence guard: e.g. `when @payload.row` lowers to\n // the string `\"@payload.row\"`. The transition fires iff that field is\n // truthy. Synthesize pass with a truthy mock and fail with null so\n // the verifier can drive both branches. Without this, std-confirmation\n // and std-modal's existence guards (REQUEST/EDIT requiring @payload.row)\n // get empty payloads in both cases — the pass case then fails the\n // server-side guard and the portal observer flags \"slot not mounted\".\n if (typeof guard === 'string') {\n const field = extractPayloadFieldRef(guard);\n if (field) return { pass: { [field]: { id: 'mock-test-id', name: 'mock-test-name' } }, fail: { [field]: null } };\n }\n\n if (!Array.isArray(guard) || guard.length === 0) {\n return { pass: {}, fail: {} };\n }\n\n const op = String(guard[0]);\n\n if (op === 'not-nil' || op === 'not_nil') {\n const field = extractPayloadFieldRef(guard[1]);\n if (field) return { pass: { [field]: 'mock-test-value' }, fail: { [field]: null } };\n }\n\n if (op === 'nil') {\n const field = extractPayloadFieldRef(guard[1]);\n if (field) return { pass: {}, fail: { [field]: 'mock-test-value' } };\n }\n\n if (op === 'eq' || op === '==' || op === '=') {\n const field = extractPayloadFieldRef(guard[1]);\n const val = guard[2];\n if (field && val !== undefined) {\n const failVal =\n typeof val === 'number' ? val + 1\n : typeof val === 'string' ? `not-${val}`\n : null;\n return { pass: { [field]: val }, fail: { [field]: failVal } };\n }\n }\n\n if (op === 'not-eq' || op === '!=' || op === 'neq') {\n const field = extractPayloadFieldRef(guard[1]);\n const val = guard[2];\n if (field && val !== undefined) {\n const passVal =\n typeof val === 'number' ? val + 1\n : typeof val === 'string' ? `not-${val}`\n : 'other';\n return { pass: { [field]: passVal }, fail: { [field]: val } };\n }\n }\n\n if (op === 'gt' || op === '>') {\n const field = extractPayloadFieldRef(guard[1]);\n const n = typeof guard[2] === 'number' ? guard[2] : 0;\n if (field) return { pass: { [field]: n + 1 }, fail: { [field]: n - 1 } };\n }\n\n if (op === 'gte' || op === '>=') {\n const field = extractPayloadFieldRef(guard[1]);\n const n = typeof guard[2] === 'number' ? guard[2] : 0;\n if (field) return { pass: { [field]: n }, fail: { [field]: n - 1 } };\n }\n\n if (op === 'lt' || op === '<') {\n const field = extractPayloadFieldRef(guard[1]);\n const n = typeof guard[2] === 'number' ? guard[2] : 0;\n if (field) return { pass: { [field]: n - 1 }, fail: { [field]: n + 1 } };\n }\n\n if (op === 'lte' || op === '<=') {\n const field = extractPayloadFieldRef(guard[1]);\n const n = typeof guard[2] === 'number' ? guard[2] : 0;\n if (field) return { pass: { [field]: n }, fail: { [field]: n + 1 } };\n }\n\n if (op === 'and') {\n // Accept BOTH array sub-guards and bare-binding string sub-guards\n // (e.g. `(and \"@payload.row\" (not-nil \"@payload.id\"))`). Dropping the\n // bare strings with filter(Array.isArray) lost their fields from the\n // pass payload. AND passes iff every sub-guard passes, so merge all\n // sub-guards' pass payloads; AND fails iff any sub-guard fails, so the\n // first sub-guard's fail payload is a sufficient violation.\n const subs = guard.slice(1) as unknown[];\n if (subs.length >= 2) {\n const built = subs.map(buildGuardPayloads);\n const pass = built.reduce<GuardPayload['pass']>((acc, b) => ({ ...acc, ...b.pass }), {});\n return { pass, fail: built[0].fail };\n }\n if (subs.length === 1) return buildGuardPayloads(subs[0]);\n }\n\n if (op === 'or') {\n // Accept BOTH array sub-guards and bare-binding string sub-guards\n // (post-substitution mode-aware guards like\n // `(or (= \"edit\" \"create\") \"@payload.row\")` mix array + string children).\n const subs = guard.slice(1) as unknown[];\n if (subs.length >= 2) {\n const s1 = buildGuardPayloads(subs[0]);\n const s2 = buildGuardPayloads(subs[1]);\n // For OR: pass if EITHER branch passes. Prefer the second branch's\n // pass payload if the first yields nothing useful — the literal-fold\n // case `(= \"edit\" \"create\") || @payload.row` has the first branch\n // return `{}` and the row-payload comes from the second.\n const combinedPass = Object.keys(s1.pass).length > 0 ? s1.pass : s2.pass;\n return { pass: combinedPass, fail: { ...s1.fail, ...s2.fail } };\n }\n if (subs.length === 1) return buildGuardPayloads(subs[0]);\n }\n\n if (op === 'not') {\n const inner = buildGuardPayloads(guard[1]);\n return { pass: inner.fail, fail: inner.pass };\n }\n\n // Agent pure operators used in guards\n if (op === 'agent/is-pinned') {\n const field = extractPayloadFieldRef(guard[1]);\n if (field) return { pass: { [field]: 'mem_test_unpinned' }, fail: { [field]: 'mem_test_pinned' } };\n }\n\n if (op === 'agent/memory-strength') {\n const field = extractPayloadFieldRef(guard[1]);\n if (field) return { pass: { [field]: 'mem_test_id' }, fail: { [field]: 'mem_nonexistent' } };\n }\n\n // Agent operators in comparison contexts (e.g., [\">=\", [\"agent/context-usage\"], 0.85])\n // These don't use @payload, they query agent state directly. Return empty payloads\n // since the guard result depends on agent context, not event payload.\n if (op.startsWith('agent/')) {\n return { pass: {}, fail: {} };\n }\n\n return { pass: {}, fail: {} };\n}\n","/**\n * Replay Path Builder\n *\n * Compute the shortest path (replay steps) from an initial state\n * to every reachable state in a state machine. Used by browser\n * verification to navigate through states before running assertions.\n *\n * Extracted from orbital-verify-unified/src/analyze.ts (collectDataMutationTests).\n *\n * @packageDocumentation\n */\n\nimport type { GraphTransition, ReplayStep, PayloadFieldSchema } from './types.js';\n\n/** Entity-data sentinel payload fields: presence means transition needs a selected row */\nconst ENTITY_PAYLOAD_FIELDS = new Set(['data', 'row', 'item', 'id']);\n\n/**\n * Extended transition with render and payload info needed for replay path building.\n * Compatible with orbital-verify's UnifiedTransition.\n */\nexport interface ReplayTransition extends GraphTransition {\n hasGuard: boolean;\n guard?: unknown[];\n payloadFields: string[];\n payloadSchema: PayloadFieldSchema[];\n renderEffects: Array<{\n slot: string;\n patternType: string | null;\n }>;\n}\n\n/**\n * Builds the shortest replay paths from initial state to all reachable states.\n * \n * Computes step-by-step navigation paths for state machine testing and verification.\n * Uses breadth-first search to find shortest paths up to specified depth limit.\n * Each path contains replay steps with event, state, and payload information\n * needed to reproduce state transitions in tests.\n * \n * @param {ReplayTransition[]} transitions - Transitions with render/payload information\n * @param {string} initialState - Starting state name\n * @param {number} [maxDepth=3] - Maximum path length (default: 3)\n * @returns {Map<string, ReplayStep[]>} Map of state names to replay step arrays\n * \n * @example\n * // Build paths from 'initial' state\n * const paths = buildReplayPaths(transitions, 'initial', 5);\n * \n * // Get steps to reach 'completed' state\n * const stepsToComplete = paths.get('completed');\n * \n * // Execute replay steps\n * for (const step of stepsToComplete) {\n * await dispatchEvent(step.event, step.payload);\n * }\n */\nexport function buildReplayPaths(\n transitions: ReplayTransition[],\n initialState: string,\n maxDepth = 3\n): Map<string, ReplayStep[]> {\n type QueueNode = { state: string; path: ReplayStep[] };\n\n const queue: QueueNode[] = [{ state: initialState, path: [] }];\n const replayPaths = new Map<string, ReplayStep[]>();\n replayPaths.set(initialState, []);\n\n while (queue.length > 0) {\n const { state, path } = queue.shift()!;\n if (path.length >= maxDepth) continue;\n\n const fromHere = transitions.filter(\n (t) => t.from === state && t.event !== 'INIT',\n );\n\n for (const transition of fromHere) {\n if (replayPaths.has(transition.to)) continue;\n\n const renderEffect = transition.renderEffects.find((re) => re.patternType !== null);\n const stepNeedsEntityData =\n transition.hasGuard ||\n transition.payloadFields.some((f) => ENTITY_PAYLOAD_FIELDS.has(f));\n\n const step: ReplayStep = {\n event: transition.event,\n fromState: state,\n toState: transition.to,\n slot: renderEffect?.slot ?? 'main',\n expectedPattern: renderEffect?.patternType ?? undefined,\n needsEntityData: stepNeedsEntityData,\n payloadSchema: transition.payloadSchema.length > 0 ? transition.payloadSchema : undefined,\n };\n\n const newPath = [...path, step];\n replayPaths.set(transition.to, newPath);\n queue.push({ state: transition.to, path: newPath });\n }\n }\n\n return replayPaths;\n}\n","/**\n * Edge-Covering Walk Algorithm\n *\n * Computes an ordered sequence of events (WalkStep[]) that attempts to cover\n * every transition (edge) in a state machine graph. This is a greedy chained\n * walk: it does NOT guarantee 100% coverage. With no reset concept it can\n * strand on absorbing states (no outgoing edges and no path back to uncovered\n * edges), and a guard-fail misprediction desyncs the chained walk so later\n * steps fire from the wrong state. Superseded by the hermetic per-frame walk\n * in @almadar-io/verify, which re-seeds each frame independently.\n *\n * Algorithm:\n * 1. Build adjacency list and edge universe (guarded transitions produce two edges)\n * 2. Precompute BFS shortest paths between all state pairs (for repositioning)\n * 3. Greedy DFS: at each state, prefer uncovered outgoing edges\n * 4. When stuck, insert repositioning steps to nearest state with uncovered edges\n * 5. Guard-fail steps don't advance state (guard blocks transition)\n *\n * Used by StateWalkEngine in @almadar-io/verify. Both orbital-verify and\n * runtime-verify share this algorithm for consistent coverage.\n *\n * @packageDocumentation\n */\n\nimport type { EdgeWalkTransition, WalkStep, StateEdge } from './types.js';\nimport type { EventPayload, EventPayloadValue } from '../types/expression.js';\nimport { buildGuardPayloads } from './guard-payloads.js';\n\n/**\n * Build an ordered walk that covers every edge in the state machine.\n *\n * @param transitions - All transitions in the state machine\n * @param initialState - Starting state\n * @returns Ordered walk steps covering every edge\n */\nexport function buildEdgeCoveringWalk(\n transitions: EdgeWalkTransition[],\n initialState: string,\n): WalkStep[] {\n // 1. Build adjacency list. Skip wildcards (pseudostates) and skip the\n // boot INIT (the runtime auto-fires INIT from the initial state on\n // mount, so the walker doesn't need to fire it). User-triggered INITs\n // from non-initial states (refresh, retry) ARE walkable edges and\n // stay in the graph so coverage can reach them.\n const filtered = transitions.filter(\n (t) => t.from !== '*' && !(t.event === 'INIT' && t.from === initialState),\n );\n\n const graph = new Map<string, Array<{ event: string; to: string; transition: EdgeWalkTransition }>>();\n const allStates = new Set<string>();\n\n for (const t of filtered) {\n allStates.add(t.from);\n allStates.add(t.to);\n if (!graph.has(t.from)) graph.set(t.from, []);\n graph.get(t.from)!.push({ event: t.event, to: t.to, transition: t });\n }\n\n // Ensure initial state is in the set\n allStates.add(initialState);\n\n // 2. Build edge universe. Guarded transitions produce pass + fail edges.\n const uncovered = new Set<string>();\n const edgeMeta = new Map<string, { transition: EdgeWalkTransition; guardCase: 'pass' | 'fail' | null }>();\n\n for (const t of filtered) {\n if (t.hasGuard) {\n const keyPass = `${t.from}+${t.event}->${t.to}[pass]`;\n const keyFail = `${t.from}+${t.event}->${t.to}[fail]`;\n uncovered.add(keyPass);\n uncovered.add(keyFail);\n edgeMeta.set(keyPass, { transition: t, guardCase: 'pass' });\n edgeMeta.set(keyFail, { transition: t, guardCase: 'fail' });\n } else {\n const key = `${t.from}+${t.event}->${t.to}`;\n uncovered.add(key);\n edgeMeta.set(key, { transition: t, guardCase: null });\n }\n }\n\n if (uncovered.size === 0) return [];\n\n // 3. Precompute BFS shortest paths between all state pairs\n const shortestPaths = new Map<string, Map<string, Array<{ event: string; to: string }>>>();\n for (const state of allStates) {\n shortestPaths.set(state, bfsShortestPaths(state, graph));\n }\n\n // 4. Greedy walk\n const walk: WalkStep[] = [];\n let currentState = initialState;\n const maxIterations = uncovered.size * allStates.size * 2; // safety bound\n let iterations = 0;\n\n while (uncovered.size > 0 && iterations < maxIterations) {\n iterations++;\n\n // Find uncovered edges from currentState\n const outgoing = findUncoveredEdges(currentState, graph, uncovered);\n\n if (outgoing.length > 0) {\n // Pick first uncovered edge\n const pick = outgoing[0];\n const payload = buildPayloadForEdge(pick.transition, pick.guardCase);\n\n walk.push({\n from: currentState,\n event: pick.transition.event,\n to: pick.transition.to,\n guardCase: pick.guardCase,\n payload,\n isRepositioning: false,\n });\n\n uncovered.delete(pick.key);\n\n // Guard-fail doesn't advance state\n if (pick.guardCase !== 'fail') {\n currentState = pick.transition.to;\n }\n } else {\n // Stuck: find nearest state with uncovered edges\n const target = findNearestUncoveredState(currentState, graph, uncovered, shortestPaths);\n\n if (!target) {\n // No reachable state with uncovered edges. Remaining edges are unreachable.\n break;\n }\n\n // Insert repositioning steps\n const repoPath = shortestPaths.get(currentState)?.get(target);\n if (!repoPath || repoPath.length === 0) break;\n\n for (const step of repoPath) {\n walk.push({\n from: currentState,\n event: step.event,\n to: step.to,\n guardCase: null,\n payload: {},\n isRepositioning: true,\n });\n currentState = step.to;\n }\n }\n }\n\n return walk;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\n/**\n * BFS from a source state, returning shortest paths to all reachable states.\n * Each path is an array of {event, to} steps.\n */\nfunction bfsShortestPaths(\n source: string,\n graph: Map<string, Array<{ event: string; to: string; transition: EdgeWalkTransition }>>,\n): Map<string, Array<{ event: string; to: string }>> {\n const paths = new Map<string, Array<{ event: string; to: string }>>();\n const visited = new Set<string>([source]);\n const queue: Array<{ state: string; path: Array<{ event: string; to: string }> }> = [\n { state: source, path: [] },\n ];\n\n while (queue.length > 0) {\n const { state, path } = queue.shift()!;\n const edges = graph.get(state) ?? [];\n\n for (const edge of edges) {\n if (visited.has(edge.to)) continue;\n visited.add(edge.to);\n const newPath = [...path, { event: edge.event, to: edge.to }];\n paths.set(edge.to, newPath);\n queue.push({ state: edge.to, path: newPath });\n }\n }\n\n return paths;\n}\n\n/**\n * Find uncovered edges from a given state.\n */\nfunction findUncoveredEdges(\n state: string,\n graph: Map<string, Array<{ event: string; to: string; transition: EdgeWalkTransition }>>,\n uncovered: Set<string>,\n): Array<{ key: string; transition: EdgeWalkTransition; guardCase: 'pass' | 'fail' | null }> {\n const edges = graph.get(state) ?? [];\n const result: Array<{ key: string; transition: EdgeWalkTransition; guardCase: 'pass' | 'fail' | null }> = [];\n\n for (const edge of edges) {\n if (edge.transition.hasGuard) {\n const keyPass = `${state}+${edge.event}->${edge.to}[pass]`;\n const keyFail = `${state}+${edge.event}->${edge.to}[fail]`;\n // Prefer pass first (advances state), then fail\n if (uncovered.has(keyPass)) {\n result.push({ key: keyPass, transition: edge.transition, guardCase: 'pass' });\n }\n if (uncovered.has(keyFail)) {\n result.push({ key: keyFail, transition: edge.transition, guardCase: 'fail' });\n }\n } else {\n const key = `${state}+${edge.event}->${edge.to}`;\n if (uncovered.has(key)) {\n result.push({ key, transition: edge.transition, guardCase: null });\n }\n }\n }\n\n return result;\n}\n\n/**\n * Find the nearest state (from currentState) that has uncovered outgoing edges.\n */\nfunction findNearestUncoveredState(\n currentState: string,\n graph: Map<string, Array<{ event: string; to: string; transition: EdgeWalkTransition }>>,\n uncovered: Set<string>,\n shortestPaths: Map<string, Map<string, Array<{ event: string; to: string }>>>,\n): string | null {\n // Collect states that have uncovered edges\n const statesWithUncovered = new Set<string>();\n for (const key of uncovered) {\n // Key format: \"state+EVENT->target\" or \"state+EVENT->target[pass]\"\n const fromState = key.split('+')[0];\n statesWithUncovered.add(fromState);\n }\n\n // If current state has uncovered edges, return it (shouldn't happen, but handle it)\n if (statesWithUncovered.has(currentState)) return currentState;\n\n // Find nearest reachable state with uncovered edges\n const paths = shortestPaths.get(currentState);\n if (!paths) return null;\n\n let nearestState: string | null = null;\n let nearestDist = Infinity;\n\n for (const target of statesWithUncovered) {\n const path = paths.get(target);\n if (path && path.length < nearestDist) {\n nearestDist = path.length;\n nearestState = target;\n }\n }\n\n return nearestState;\n}\n\n/**\n * Build a payload for a given edge based on its guard case and payload schema.\n * For guarded transitions, uses guard expressions to generate pass/fail payloads.\n * For unguarded transitions with payload schemas (e.g., EDIT/VIEW with { id }),\n * generates mock values so fetch-by-ID effects can resolve entity data.\n */\nfunction buildPayloadForEdge(\n transition: EdgeWalkTransition,\n guardCase: 'pass' | 'fail' | null,\n): EventPayload {\n // Guard-based payload generation (existing behavior)\n if (transition.hasGuard && transition.guard && guardCase) {\n const payloads = buildGuardPayloads(transition.guard);\n return guardCase === 'pass' ? payloads.pass : payloads.fail;\n }\n\n // Schema-based payload generation for events that declare required fields\n // (e.g., EDIT/VIEW declare { name: \"id\", type: \"string\", required: true })\n if (transition.payloadSchema && transition.payloadSchema.length > 0) {\n const payload: EventPayload = {};\n for (const field of transition.payloadSchema) {\n // Use caller-provided mockValue if available (set from entity context)\n if (field.mockValue !== undefined) {\n payload[field.name] = field.mockValue as EventPayloadValue;\n } else if (field.type === 'string') {\n payload[field.name] = `mock-${field.name}`;\n } else if (field.type === 'number') {\n payload[field.name] = 1;\n } else if (field.type === 'boolean') {\n payload[field.name] = true;\n } else if (field.type === 'object' || field.type === 'any') {\n // `mock-<name>` is a plain string; persisting that for an object\n // field (e.g. SAVE's `data: object` carrying a form row) spreads\n // the string's characters across numeric keys server-side and\n // the downstream grid renders blank cards. An empty object is a\n // safer default — callers that need entity-shaped mocks should\n // set `mockValue` at the call site (see orbital-verify-unified's\n // phase4-browser TraitWalkConfig builder).\n payload[field.name] = {};\n } else {\n payload[field.name] = `mock-${field.name}`;\n }\n }\n return payload;\n }\n\n return {};\n}\n"]}
|