@almadar/core 7.20.0 → 7.21.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 +2 -2
- package/dist/builders.js +3 -1
- package/dist/builders.js.map +1 -1
- package/dist/{compose-behaviors-DWMFJEz3.d.ts → compose-behaviors-Cvk12C0p.d.ts} +1 -1
- package/dist/domain-language/index.d.ts +1 -1
- package/dist/domain-language/index.js +3 -1
- package/dist/domain-language/index.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/{schema-WX5fN1Ra.d.ts → schema-DRDVNvPf.d.ts} +2 -2
- package/dist/types/index.d.ts +2 -2
- package/dist/types/index.js +3 -1
- package/dist/types/index.js.map +1 -1
- package/package.json +1 -1
package/dist/types/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"],"names":["z","ref","_PATTERN_TYPES"],"mappings":";;;;;AAmCO,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;AACJ,CAAC;AAiBM,IAAM,yBAAA,GAA4B,EAAE,IAAA,CAAK;AAAA,EAC5C,KAAA;AAAA,EACA,MAAA;AAAA,EACA,aAAA;AAAA,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V,SAAA,EAAW,QAAA;AAAA,IACX,KAAA,EAAO,WAAA;AAAA,IACP,MAAA,EAAQ,yBAAA;AAAA,IACR,GAAA,EAAK;AAAA,GACP;AAGA,EAAA,IAAI,UAAA,CAAW,QAAA,CAAS,IAAI,CAAA,EAAG;AAC7B,IAAA,MAAM,QAAA,GAAW,UAAA,CAAW,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA;AACvC,IAAA,OAAO,CAAA,EAAG,OAAA,CAAQ,QAAQ,CAAA,IAAK,QAAQ,CAAA,EAAA,CAAA;AAAA,EACzC;AAEA,EAAA,OAAO,OAAA,CAAQ,UAAU,CAAA,IAAK,UAAA;AAChC;AAKO,SAAS,oBAAoB,KAAA,EAQlB;AAChB,EAAA,OAAO;AAAA,IACL,MAAM,KAAA,CAAM,IAAA;AAAA,IACZ,MAAM,KAAA,CAAM,IAAA;AAAA,IACZ,MAAA,EAAQ,WAAA,CAAY,KAAA,CAAM,IAAI,CAAA;AAAA,IAC9B,aAAa,KAAA,CAAM,WAAA;AAAA,IACnB,SAAS,KAAA,CAAM,OAAA;AAAA,IACf,QAAA,EAAU,MAAM,QAAA,IAAY,KAAA;AAAA,IAC5B,YAAY,KAAA,CAAM,UAAA;AAAA,IAClB,QAAQ,KAAA,CAAM;AAAA,GAChB;AACF;AAsBO,SAAS,aAAa,EAAA,EAA+B;AAC1D,EAAA,IAAI,CAAC,EAAA,IAAM,OAAO,EAAA,KAAO,UAAU,OAAO,KAAA;AAC1C,EAAA,MAAM,CAAA,GAAI,EAAA;AACV,EAAA,OAAO,OAAO,EAAE,OAAA,KAAY,QAAA,IAAY,EAAE,MAAA,YAAkB,GAAA,IAAO,EAAE,KAAA,YAAiB,GAAA;AACxF","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\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]);\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 = 'email' | 'url' | 'phone' | 'date' | 'datetime' | 'uuid';\n\nexport const FieldFormatSchema = z.enum([\n 'email',\n 'url',\n 'phone',\n 'date',\n 'datetime',\n 'uuid',\n]);\n\n// ============================================================================\n// Entity Field\n// ============================================================================\n\n/**\n * Entity field definition.\n */\nexport interface EntityField {\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 /** Data type */\n type: FieldType;\n /** Whether the field is required */\n required?: boolean;\n /** Default value */\n default?: unknown;\n /** Allowed values for enum types */\n values?: string[];\n /** @deprecated Use 'values' instead */\n enum?: string[];\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 /** Array item schema (for array type) */\n items?: EntityField;\n /** Relation configuration (required when type is 'relation') */\n relation?: RelationConfig;\n}\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\nexport const EntityFieldSchema: z.ZodType<EntityField, z.ZodTypeDef, unknown> = z.lazy(() =>\n 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 const raw = (input as { type: string }).type;\n const canonical = FIELD_TYPE_ALIASES[raw];\n if (canonical !== undefined) {\n return { ...(input as object), type: canonical };\n }\n }\n return input;\n },\n z.object({\n name: z.string().min(1, 'Field name is required').optional(),\n type: FieldTypeSchema,\n required: z.boolean().optional(),\n default: z.unknown().optional(),\n values: z.array(z.string()).optional(),\n enum: z.array(z.string()).optional(),\n format: FieldFormatSchema.optional(),\n min: z.number().optional(),\n max: z.number().optional(),\n items: EntityFieldSchema.optional(),\n relation: RelationConfigSchema.optional(),\n }).refine(\n (field) => field.type !== 'relation' || field.relation !== undefined,\n { message: 'Relation config is required when type is \"relation\"', path: ['relation'] }\n ).refine(\n // Enum fields must carry their allowed values. Without this refine,\n // the type was lying about what's valid — bare `type: 'enum'` without\n // `values` passed zod but failed `orb validate` downstream with\n // ORB_E_EMPTY_ENUM_VALUES, stalling the agent pipeline for 20 minutes.\n // `enum` is the legacy field-name alias; accept either.\n (field) => {\n if (field.type !== 'enum') return true;\n const vals = field.values ?? field.enum;\n return Array.isArray(vals) && vals.length > 0;\n },\n { message: 'Enum field requires a non-empty `values` array', path: ['values'] }\n ).refine(\n // Array fields must describe their element shape. Bare `type: 'array'`\n // with no `items` forces downstream consumers (builders, UI renderers,\n // persistence) to guess, so reject it at the schema boundary.\n (field) => {\n if (field.type !== 'array') return true;\n return field.items !== undefined;\n },\n { message: 'Array field requires an `items` schema describing each element', path: ['items'] }\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// 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 Definition\n// ============================================================================\n\n/**\n * Animation definition for sprites\n */\nexport interface AnimationDef {\n /** Frame indices or file names */\n frames: number[] | string[];\n /** Frames per second */\n fps: number;\n /** Whether animation loops */\n loop: boolean;\n}\n\nexport const AnimationDefSchema = z.object({\n frames: z.union([z.array(z.number()), z.array(z.string())]),\n fps: z.number().positive(),\n loop: z.boolean(),\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}\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});\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// 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>;\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// 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 * 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 * Render UI effect - displays a pattern in a UI slot.\n * @example ['render-ui', 'main', { patternType: 'entity-table', columns: ['name'] }]\n */\nexport type RenderUIEffect =\n | ['render-ui', UISlot, AnyPatternConfig]\n | ['render-ui', UISlot, AnyPatternConfig, ResolvedPatternProps]\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 */\n description?: 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 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 * 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`.\n */\nexport interface ConfigFieldDeclaration {\n readonly type: string;\n readonly default?: TraitConfigValue;\n}\n\nexport const ConfigFieldDeclarationSchema: z.ZodType<ConfigFieldDeclaration> = z.object({\n type: z.string(),\n default: TraitConfigValueSchema.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 /** 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 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 /** 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 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 config?: TraitConfig;\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 config: TraitConfigSchema.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?: TraitConfig;\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\nexport interface Trait {\n name: string;\n description?: string;\n description_visual_prompt?: string;\n category?: TraitCategory;\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 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): TraitConfig | 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?: TraitConfig } {\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\n// ============================================================================\n\n/**\n * Theme tokens - CSS custom properties for design system.\n */\nexport interface ThemeTokens {\n /** Color tokens (e.g., primary, background, foreground) */\n colors?: Record<string, string>;\n /** Border radius tokens */\n radii?: Record<string, string>;\n /** Spacing tokens */\n spacing?: Record<string, string>;\n /** Typography tokens */\n typography?: Record<string, string>;\n /** Shadow tokens */\n shadows?: Record<string, string>;\n}\n\nexport const ThemeTokensSchema = z.object({\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 */\nexport interface ThemeVariant {\n /** Color overrides */\n colors?: Record<string, string>;\n /** Radius overrides */\n radii?: Record<string, string>;\n /** Spacing overrides */\n spacing?: Record<string, string>;\n /** Typography overrides */\n typography?: Record<string, string>;\n /** Shadow overrides */\n shadows?: Record<string, string>;\n}\n\nexport const ThemeVariantSchema = z.object({\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// 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 */\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\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});\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 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"]}
|
|
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"],"names":["z","ref","_PATTERN_TYPES"],"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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AAA,EAAM,MAAA;AAAA,IACN,QAAA,EAAU,MAAA;AAAA,IACV,SAAA,EAAW,QAAA;AAAA,IACX,KAAA,EAAO,WAAA;AAAA,IACP,MAAA,EAAQ,yBAAA;AAAA,IACR,GAAA,EAAK;AAAA,GACP;AAGA,EAAA,IAAI,UAAA,CAAW,QAAA,CAAS,IAAI,CAAA,EAAG;AAC7B,IAAA,MAAM,QAAA,GAAW,UAAA,CAAW,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA;AACvC,IAAA,OAAO,CAAA,EAAG,OAAA,CAAQ,QAAQ,CAAA,IAAK,QAAQ,CAAA,EAAA,CAAA;AAAA,EACzC;AAEA,EAAA,OAAO,OAAA,CAAQ,UAAU,CAAA,IAAK,UAAA;AAChC;AAKO,SAAS,oBAAoB,KAAA,EAQlB;AAChB,EAAA,OAAO;AAAA,IACL,MAAM,KAAA,CAAM,IAAA;AAAA,IACZ,MAAM,KAAA,CAAM,IAAA;AAAA,IACZ,MAAA,EAAQ,WAAA,CAAY,KAAA,CAAM,IAAI,CAAA;AAAA,IAC9B,aAAa,KAAA,CAAM,WAAA;AAAA,IACnB,SAAS,KAAA,CAAM,OAAA;AAAA,IACf,QAAA,EAAU,MAAM,QAAA,IAAY,KAAA;AAAA,IAC5B,YAAY,KAAA,CAAM,UAAA;AAAA,IAClB,QAAQ,KAAA,CAAM;AAAA,GAChB;AACF;AAsBO,SAAS,aAAa,EAAA,EAA+B;AAC1D,EAAA,IAAI,CAAC,EAAA,IAAM,OAAO,EAAA,KAAO,UAAU,OAAO,KAAA;AAC1C,EAAA,MAAM,CAAA,GAAI,EAAA;AACV,EAAA,OAAO,OAAO,EAAE,OAAA,KAAY,QAAA,IAAY,EAAE,MAAA,YAAkB,GAAA,IAAO,EAAE,KAAA,YAAiB,GAAA;AACxF","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 = 'email' | 'url' | 'phone' | 'date' | 'datetime' | 'uuid';\n\nexport const FieldFormatSchema = z.enum([\n 'email',\n 'url',\n 'phone',\n 'date',\n 'datetime',\n 'uuid',\n]);\n\n// ============================================================================\n// Entity Field\n// ============================================================================\n\n/**\n * Entity field definition.\n */\nexport interface EntityField {\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 /** Data type */\n type: FieldType;\n /** Whether the field is required */\n required?: boolean;\n /** Default value */\n default?: unknown;\n /** Allowed values for enum types */\n values?: string[];\n /** @deprecated Use 'values' instead */\n enum?: string[];\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 /** Array item schema (for array type) */\n items?: EntityField;\n /** Relation configuration (required when type is 'relation') */\n relation?: RelationConfig;\n}\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\nexport const EntityFieldSchema: z.ZodType<EntityField, z.ZodTypeDef, unknown> = z.lazy(() =>\n 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 const raw = (input as { type: string }).type;\n const canonical = FIELD_TYPE_ALIASES[raw];\n if (canonical !== undefined) {\n return { ...(input as object), type: canonical };\n }\n }\n return input;\n },\n z.object({\n name: z.string().min(1, 'Field name is required').optional(),\n type: FieldTypeSchema,\n required: z.boolean().optional(),\n default: z.unknown().optional(),\n values: z.array(z.string()).optional(),\n enum: z.array(z.string()).optional(),\n format: FieldFormatSchema.optional(),\n min: z.number().optional(),\n max: z.number().optional(),\n items: EntityFieldSchema.optional(),\n relation: RelationConfigSchema.optional(),\n }).refine(\n (field) => field.type !== 'relation' || field.relation !== undefined,\n { message: 'Relation config is required when type is \"relation\"', path: ['relation'] }\n ).refine(\n // Enum fields must carry their allowed values. Without this refine,\n // the type was lying about what's valid — bare `type: 'enum'` without\n // `values` passed zod but failed `orb validate` downstream with\n // ORB_E_EMPTY_ENUM_VALUES, stalling the agent pipeline for 20 minutes.\n // `enum` is the legacy field-name alias; accept either.\n (field) => {\n if (field.type !== 'enum') return true;\n const vals = field.values ?? field.enum;\n return Array.isArray(vals) && vals.length > 0;\n },\n { message: 'Enum field requires a non-empty `values` array', path: ['values'] }\n ).refine(\n // Array fields must describe their element shape. Bare `type: 'array'`\n // with no `items` forces downstream consumers (builders, UI renderers,\n // persistence) to guess, so reject it at the schema boundary.\n (field) => {\n if (field.type !== 'array') return true;\n return field.items !== undefined;\n },\n { message: 'Array field requires an `items` schema describing each element', path: ['items'] }\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// 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 Definition\n// ============================================================================\n\n/**\n * Animation definition for sprites\n */\nexport interface AnimationDef {\n /** Frame indices or file names */\n frames: number[] | string[];\n /** Frames per second */\n fps: number;\n /** Whether animation loops */\n loop: boolean;\n}\n\nexport const AnimationDefSchema = z.object({\n frames: z.union([z.array(z.number()), z.array(z.string())]),\n fps: z.number().positive(),\n loop: z.boolean(),\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}\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});\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// 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>;\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// 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 * 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 * Render UI effect - displays a pattern in a UI slot.\n * @example ['render-ui', 'main', { patternType: 'entity-table', columns: ['name'] }]\n */\nexport type RenderUIEffect =\n | ['render-ui', UISlot, AnyPatternConfig]\n | ['render-ui', UISlot, AnyPatternConfig, ResolvedPatternProps]\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 */\n description?: 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 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 * 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`.\n */\nexport interface ConfigFieldDeclaration {\n readonly type: string;\n readonly default?: TraitConfigValue;\n}\n\nexport const ConfigFieldDeclarationSchema: z.ZodType<ConfigFieldDeclaration> = z.object({\n type: z.string(),\n default: TraitConfigValueSchema.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 /** 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 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 /** 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 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 config?: TraitConfig;\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 config: TraitConfigSchema.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?: TraitConfig;\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\nexport interface Trait {\n name: string;\n description?: string;\n description_visual_prompt?: string;\n category?: TraitCategory;\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 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): TraitConfig | 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?: TraitConfig } {\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\n// ============================================================================\n\n/**\n * Theme tokens - CSS custom properties for design system.\n */\nexport interface ThemeTokens {\n /** Color tokens (e.g., primary, background, foreground) */\n colors?: Record<string, string>;\n /** Border radius tokens */\n radii?: Record<string, string>;\n /** Spacing tokens */\n spacing?: Record<string, string>;\n /** Typography tokens */\n typography?: Record<string, string>;\n /** Shadow tokens */\n shadows?: Record<string, string>;\n}\n\nexport const ThemeTokensSchema = z.object({\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 */\nexport interface ThemeVariant {\n /** Color overrides */\n colors?: Record<string, string>;\n /** Radius overrides */\n radii?: Record<string, string>;\n /** Spacing overrides */\n spacing?: Record<string, string>;\n /** Typography overrides */\n typography?: Record<string, string>;\n /** Shadow overrides */\n shadows?: Record<string, string>;\n}\n\nexport const ThemeVariantSchema = z.object({\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// 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 */\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\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});\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 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"]}
|