@almadar/core 7.20.0 → 7.22.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 +4 -1
- package/dist/builders.js.map +1 -1
- package/dist/{compose-behaviors-DWMFJEz3.d.ts → compose-behaviors-CHAMivlZ.d.ts} +1 -1
- package/dist/domain-language/index.d.ts +7 -1
- package/dist/domain-language/index.js +4 -1
- package/dist/domain-language/index.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +4 -1
- package/dist/index.js.map +1 -1
- package/dist/{schema-WX5fN1Ra.d.ts → schema-BVni4uNf.d.ts} +87 -2
- package/dist/types/index.d.ts +2 -2
- package/dist/types/index.js +4 -1
- package/dist/types/index.js.map +1 -1
- package/package.json +1 -1
package/dist/builders.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/builders/layout-strategy.ts","../src/builders/event-wiring.ts","../src/builders/compose-behaviors.ts","../src/builders/layout-trait.ts","../src/builders.ts"],"names":["z","asDefinitions"],"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,CAAA;AAiBM,IAAM,yBAAA,GAA4B,EAAE,IAAA,CAAK;AAAA,EAC5C,KAAA;AAAA,EACA,MAAA;AAAA,EACA,aAAA;AAAA,EACA,aAAA;AAAA,EACA;AACJ,CAAC,CAAA;A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;AAAA,KACzC;AAAA,EACF,CAAC,CAAA;AAGD,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,MAAA,CAAO,QAAQ,CAAA,EAAA,EAAK;AACtC,IAAA,MAAA,CAAO,CAAC,CAAA,CAAE,KAAA,GAAQ,CAAC,KAAA,CAAM,CAAC,CAAC,CAAA;AAAA,EAC7B;AAEA,EAAA,OAAO;AAAA,IACL,MAAM,OAAA,IAAW,aAAA;AAAA,IACjB,OAAA,EAAS,OAAA;AAAA,IACT,QAAA,EAAU;AAAA,GACZ;AACF","file":"builders.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 * Layout Strategy Detection\n *\n * Auto-detects the best layout strategy for a composed application\n * based on the number of orbitals and their event wiring topology.\n *\n * @packageDocumentation\n */\n\nimport type { OrbitalDefinition } from '../types/orbital.js';\nimport type { EventWiringEntry } from './event-wiring.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Layout strategy for the composed application.\n *\n * - 'single': One orbital, one page\n * - 'tabs': 2-4 orbitals with no sequential chain\n * - 'sidebar': 5+ orbitals (navigation-heavy)\n * - 'dashboard': Single page with all orbitals visible\n * - 'wizard-flow': Sequential event chain detected (A -> B -> C)\n */\nexport type LayoutStrategy =\n | 'sidebar'\n | 'tabs'\n | 'dashboard'\n | 'wizard-flow'\n | 'single';\n\n// ============================================================================\n// Chain Detection\n// ============================================================================\n\n/**\n * Detect whether the event wiring forms a sequential chain.\n *\n * A sequential chain exists when orbital A's `from` feeds into B's `to`,\n * and B's `from` feeds into C's `to`, forming A -> B -> C.\n *\n * We build a directed graph from wiring entries and look for a chain\n * that covers 3+ nodes (the minimum for a meaningful wizard flow).\n */\nfunction hasSequentialChain(wiring: EventWiringEntry[]): boolean {\n if (wiring.length < 2) {\n return false;\n }\n\n // Build adjacency: from -> Set<to>\n const adjacency = new Map<string, Set<string>>();\n const allTargets = new Set<string>();\n\n for (const entry of wiring) {\n let targets = adjacency.get(entry.from);\n if (!targets) {\n targets = new Set<string>();\n adjacency.set(entry.from, targets);\n }\n targets.add(entry.to);\n allTargets.add(entry.to);\n }\n\n // Find roots (nodes that are sources but never targets)\n const roots: string[] = [];\n for (const from of adjacency.keys()) {\n if (!allTargets.has(from)) {\n roots.push(from);\n }\n }\n\n // If no clear root, try all sources\n const starts = roots.length > 0 ? roots : [...adjacency.keys()];\n\n // Walk from each start and measure chain length\n for (const start of starts) {\n let current = start;\n let length = 1;\n const visited = new Set<string>([current]);\n\n while (true) {\n const nexts = adjacency.get(current);\n if (!nexts || nexts.size === 0) break;\n\n // Follow the first unvisited successor (linear chain)\n let advanced = false;\n for (const next of nexts) {\n if (!visited.has(next)) {\n visited.add(next);\n current = next;\n length++;\n advanced = true;\n break;\n }\n }\n\n if (!advanced) break;\n }\n\n // A chain of 3+ nodes qualifies as wizard-flow\n if (length >= 3) {\n return true;\n }\n }\n\n return false;\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Detect the best layout strategy based on orbital count and event wiring.\n *\n * Heuristic:\n * 1. Sequential event chain detected -> 'wizard-flow'\n * 2. 1 orbital -> 'single'\n * 3. 2-4 orbitals -> 'tabs'\n * 4. 5+ orbitals -> 'sidebar'\n */\nexport function detectLayoutStrategy(\n orbitals: OrbitalDefinition[],\n eventWiring?: EventWiringEntry[],\n): LayoutStrategy {\n // Check for sequential chain first (takes priority)\n if (eventWiring && eventWiring.length > 0 && hasSequentialChain(eventWiring)) {\n return 'wizard-flow';\n }\n\n const count = orbitals.length;\n\n if (count <= 1) {\n return 'single';\n }\n\n if (count <= 4) {\n return 'tabs';\n }\n\n return 'sidebar';\n}\n","/**\n * Event Wiring\n *\n * Applies cross-orbital event wiring to orbital definitions.\n * Adds emits/listens declarations to traits so they can communicate\n * across orbital boundaries.\n *\n * @packageDocumentation\n */\n\nimport type { OrbitalDefinition } from '../types/orbital.js';\nimport type { Trait, TraitEventContract, TraitEventListener } from '../types/trait.js';\nimport { isInlineTrait } from '../types/trait.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * A single event wiring entry connecting two traits across orbitals.\n */\nexport interface EventWiringEntry {\n /** Source trait name or orbital name */\n from: string;\n /** Event name (UPPER_SNAKE_CASE) */\n event: string;\n /** Target trait name or orbital name */\n to: string;\n /** Event to trigger on the listener side */\n triggers: string;\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/**\n * Find a trait by name across all orbitals.\n * Only inline traits can be mutated; string/ref traits are skipped.\n * Returns the inline Trait object if found, or null.\n */\nfunction findInlineTrait(\n orbitals: OrbitalDefinition[],\n name: string,\n): Trait | null {\n for (const orbital of orbitals) {\n for (const traitRef of orbital.traits) {\n if (isInlineTrait(traitRef) && traitRef.name === name) {\n return traitRef;\n }\n }\n }\n return null;\n}\n\n/**\n * Check if an emit already exists in the list.\n * @internal\n */\nfunction hasEmit(emits: TraitEventContract[], event: string): boolean {\n return emits.some((e) => e.event === event);\n}\n\n/**\n * Check if a listen already exists in the list.\n * @internal\n */\nfunction hasListen(\n listens: TraitEventListener[],\n event: string,\n triggers: string,\n): boolean {\n return listens.some((l) => l.event === event && l.triggers === triggers);\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Apply event wiring to orbital definitions.\n *\n * For each wiring entry:\n * 1. Find the source trait and add an external emit (if not already present)\n * 2. Find the target trait and add an external listen (if not already present)\n *\n * Returns a new array of orbitals with wiring applied (deep-cloned).\n */\nexport function applyEventWiring(\n orbitals: OrbitalDefinition[],\n wiring: EventWiringEntry[],\n): OrbitalDefinition[] {\n // Deep clone to avoid mutating input\n const cloned: OrbitalDefinition[] = JSON.parse(\n JSON.stringify(orbitals),\n ) as OrbitalDefinition[];\n\n for (const entry of wiring) {\n // Wire the source: add emit\n const sourceTrait = findInlineTrait(cloned, entry.from);\n if (sourceTrait) {\n if (!sourceTrait.emits) {\n sourceTrait.emits = [];\n }\n if (!hasEmit(sourceTrait.emits, entry.event)) {\n sourceTrait.emits.push({\n event: entry.event,\n scope: 'external',\n });\n }\n }\n\n // Wire the target: add listen\n const targetTrait = findInlineTrait(cloned, entry.to);\n if (targetTrait) {\n if (!targetTrait.listens) {\n targetTrait.listens = [];\n }\n if (!hasListen(targetTrait.listens, entry.event, entry.triggers)) {\n targetTrait.listens.push({\n event: entry.event,\n triggers: entry.triggers,\n scope: 'external',\n });\n }\n }\n }\n\n return cloned;\n}\n","/**\n * Compose Behaviors\n *\n * Main entry point for composing multiple orbital definitions into\n * a single OrbitalSchema application. Handles event wiring, layout\n * strategy detection, and page generation.\n *\n * @packageDocumentation\n */\n\nimport type { OrbitalDefinition } from '../types/orbital.js';\nimport type { OrbitalSchema } from '../types/schema.js';\n\n/** Unwrap OrbitalSchema | OrbitalDefinition inputs to a flat OrbitalDefinition[]. */\nfunction asDefinitions(inputs: (OrbitalDefinition | OrbitalSchema)[]): OrbitalDefinition[] {\n return inputs.flatMap(input => {\n if ('orbitals' in input && Array.isArray((input as OrbitalSchema).orbitals)) {\n return (input as OrbitalSchema).orbitals as OrbitalDefinition[];\n }\n return [input as OrbitalDefinition];\n });\n}\nimport type { Page } from '../types/page.js';\nimport type { EventWiringEntry } from './event-wiring.js';\nimport { applyEventWiring } from './event-wiring.js';\nimport type { LayoutStrategy } from './layout-strategy.js';\nimport { detectLayoutStrategy } from './layout-strategy.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Input for composing behaviors into an application.\n */\nexport interface ComposeBehaviorsInput {\n /** Application name */\n appName: string;\n /** Orbital definitions (or schemas) to compose */\n orbitals: (OrbitalDefinition | OrbitalSchema)[];\n /** Layout strategy override, or 'auto' to detect */\n layoutStrategy?: LayoutStrategy | 'auto';\n /** Cross-orbital event wiring */\n eventWiring?: EventWiringEntry[];\n /** Optional entity name mappings (original -> renamed) */\n entityMappings?: Record<string, string>;\n}\n\n/**\n * Result of composing behaviors.\n */\nexport interface ComposeBehaviorsResult {\n /** The composed OrbitalSchema */\n schema: OrbitalSchema;\n /** Layout metadata */\n layout: { strategy: LayoutStrategy; pageCount: number };\n /** Wiring metadata */\n wiring: { connections: number };\n}\n\n// ============================================================================\n// Page Generation\n// ============================================================================\n\nfunction toKebabCase(name: string): string {\n return name\n .replace(/([a-z])([A-Z])/g, '$1-$2')\n .replace(/[\\s_]+/g, '-')\n .toLowerCase();\n}\n\n/**\n * Generate pages for each orbital based on the layout strategy.\n *\n * For strategies that produce one page per orbital (sidebar, tabs, wizard-flow),\n * each orbital gets a page at `/<kebab-name>` with `isInitial` on the first.\n *\n * For 'dashboard', all orbitals share a single page.\n * For 'single', the lone orbital gets a single root page.\n */\nfunction generatePages(\n orbitals: OrbitalDefinition[],\n strategy: LayoutStrategy,\n): Page[] {\n switch (strategy) {\n case 'single': {\n const orbital = orbitals[0];\n const name = orbital?.name ?? 'Main';\n return [\n {\n name: `${name}Page`,\n path: '/',\n isInitial: true,\n primaryEntity: getEntityName(orbital),\n },\n ];\n }\n\n case 'dashboard': {\n return [\n {\n name: 'DashboardPage',\n path: '/',\n viewType: 'dashboard',\n isInitial: true,\n },\n ];\n }\n\n case 'sidebar':\n case 'tabs':\n case 'wizard-flow': {\n return orbitals.map((orbital, index) => ({\n name: `${orbital.name}Page`,\n path: index === 0 ? '/' : `/${toKebabCase(orbital.name)}`,\n isInitial: index === 0,\n primaryEntity: getEntityName(orbital),\n }));\n }\n }\n}\n\n/**\n * Extract entity name from an orbital definition.\n * Handles both inline entities and string references.\n */\nfunction getEntityName(orbital: OrbitalDefinition | undefined): string | undefined {\n if (!orbital) return undefined;\n const entity = orbital.entity;\n if (typeof entity === 'string') {\n // Reference like \"Alias.entity\" - extract the alias as entity name\n return entity.replace('.entity', '');\n }\n return entity.name;\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Compose multiple orbital definitions into a single application schema.\n *\n * Steps:\n * 1. Apply event wiring (adds emits/listens to traits)\n * 2. Detect or use provided layout strategy\n * 3. Generate pages based on the strategy\n * 4. Build the final OrbitalSchema\n */\nexport function composeBehaviors(\n input: ComposeBehaviorsInput,\n): ComposeBehaviorsResult {\n const {\n appName,\n orbitals: rawInputs,\n layoutStrategy: strategyInput,\n eventWiring,\n } = input;\n\n // Unwrap any OrbitalSchema inputs to OrbitalDefinition[]\n const rawOrbitals = asDefinitions(rawInputs);\n\n // Step 1: Apply event wiring\n const wiredOrbitals =\n eventWiring && eventWiring.length > 0\n ? applyEventWiring(rawOrbitals, eventWiring)\n : rawOrbitals;\n\n // Step 2: Determine layout strategy\n const strategy: LayoutStrategy =\n !strategyInput || strategyInput === 'auto'\n ? detectLayoutStrategy(wiredOrbitals, eventWiring)\n : strategyInput;\n\n // Step 3: Generate pages\n const pages = generatePages(wiredOrbitals, strategy);\n\n // Step 4: Assign generated pages to orbitals (merge, don't replace existing)\n const orbitalsWithPages = wiredOrbitals.map((orbital, index) => {\n // If the orbital already has pages, keep them\n if (orbital.pages && orbital.pages.length > 0) {\n return orbital;\n }\n\n // Assign the generated page for this orbital\n const page = strategy === 'dashboard' || strategy === 'single'\n ? pages[0]\n : pages[index];\n\n return {\n ...orbital,\n pages: page ? [page] : [],\n };\n });\n\n // Step 5: Build the schema\n const schema: OrbitalSchema = {\n name: appName,\n version: '1.0.0',\n orbitals: orbitalsWithPages,\n };\n\n return {\n schema,\n layout: {\n strategy,\n pageCount: pages.length,\n },\n wiring: {\n connections: eventWiring?.length ?? 0,\n },\n };\n}\n","/**\n * Layout-Trait Builders\n *\n * Helpers for constructing the canonical inline LayoutTrait pattern that\n * std layout-shell molecules (`std-filtered-list`, `std-master-detail-layout`,\n * etc.) use to wrap a set of atom trait references in a `(render-ui main)`\n * effect with `@trait.X` slot embeds.\n *\n * The canonical LayoutTrait is stateless: ONE state (`composing`, initial),\n * ONE transition (`INIT` self-loop) carrying two effects — `(fetch Entity\n * {emit: {success, failure}})` and `(render-ui \"main\" <pattern-tree>)`. Atoms\n * embedded via `@trait.X` slot references react to the bus events the fetch\n * emits; the LayoutTrait owns no further state.\n *\n * Usage from a std layout-shell molecule:\n *\n * ```ts\n * import { makeSlot, makeLayoutTrait } from '@almadar/core/builders';\n *\n * const layout = makeLayoutTrait({\n * name: 'DashboardLayout',\n * linkedEntity: 'Metric',\n * fetchEntity: 'Metric',\n * loadedEvent: 'MetricLoaded',\n * loadFailedEvent: 'MetricLoadFailed',\n * renderUI: {\n * type: 'stack',\n * direction: 'vertical',\n * children: [\n * makeSlot('StatsRow'),\n * makeSlot('ChartsRow'),\n * makeSlot('FeedRow'),\n * ],\n * },\n * });\n * ```\n *\n * @packageDocumentation\n */\n\nimport type { AnyPatternConfig } from '@almadar/patterns';\nimport type { Trait } from '../types/trait.js';\nimport type { Effect, FetchEffect, RenderUIEffect, UISlot } from '../types/effect.js';\n\n/**\n * Build a `@trait.<name>` slot reference string. Used as a child entry in a\n * pattern tree to embed another trait's render-ui at that position. The\n * runtime resolves `@trait.X` to the matching trait's render-ui inline.\n *\n * @example makeSlot('FilteredItemSearch') // \"@trait.FilteredItemSearch\"\n */\nexport function makeSlot(traitName: string): string {\n return `@trait.${traitName}`;\n}\n\n/**\n * Build a `(render-ui <slot> <root>)` effect tuple. Pattern-typed sugar over\n * the raw `RenderUIEffect` literal so callers don't have to spell out the\n * three-element tuple form.\n *\n * @param slot - Canonical UI slot name (`'main'`, `'header'`, etc. — see UI_SLOTS).\n * @param root - The pattern config for this slot's content. Pass `null` to clear.\n */\nexport function makeRenderUI(slot: UISlot, root: AnyPatternConfig | null): RenderUIEffect {\n // Branch the return so TS can narrow into the correct tuple variant of\n // the RenderUIEffect union (the null arm is a separate tuple shape).\n return root === null ? ['render-ui', slot, null] : ['render-ui', slot, root];\n}\n\n/**\n * Options for {@link makeLayoutTrait}.\n */\nexport interface MakeLayoutTraitOpts {\n /** Trait name, e.g. `\"DashboardGridLayout\"`. */\n name: string;\n /** Entity this layout's emits/listens bind to. */\n linkedEntity: string;\n /** Optional human-readable description (carried through to `Trait.description`). */\n description?: string;\n /**\n * Entity name to fetch on INIT. When set, a `(fetch <Entity> {emit:\n * {success, failure}})` effect is prepended to the INIT transition. Omit\n * for purely-presentational layouts that don't load data themselves.\n */\n fetchEntity?: string;\n /**\n * Event name emitted on successful fetch. Required when `fetchEntity` is\n * set; the LayoutTrait declares this event in its `emits` and uses it as\n * the `success` emit-name in the fetch effect.\n * Convention: `\"<Entity>Loaded\"`.\n */\n loadedEvent?: string;\n /**\n * Event name emitted on fetch failure. Required when `fetchEntity` is\n * set. Convention: `\"<Entity>LoadFailed\"`.\n */\n loadFailedEvent?: string;\n /**\n * Payload schema for the loaded event. Defaults to `[{ name: \"data\", type:\n * \"[<Entity>]\" }]` when `fetchEntity` is set. Provide explicitly when the\n * payload should carry additional fields.\n */\n loadedPayloadSchema?: Array<{ name: string; type: string; required?: boolean }>;\n /**\n * The pattern tree for the layout's main slot. Children may include\n * `@trait.X` slot strings (built via {@link makeSlot}) interleaved with\n * inline pattern configs (`{ type: 'stack', ... }`). The shape conforms to\n * `AnyPatternConfig` from `@almadar/patterns`.\n */\n renderUI: AnyPatternConfig;\n /**\n * Override the slot the render-ui effect targets. Defaults to `'main'`.\n * Specify when the layout shell should render into a sub-slot (rare).\n */\n slot?: UISlot;\n /**\n * Additional effects appended to the INIT transition AFTER the fetch +\n * render-ui pair. Most layouts don't need this; provided for advanced\n * cases (analytics emit, persistence seed, etc.).\n */\n extraEffects?: Effect[];\n}\n\n/**\n * Build the canonical stateless LayoutTrait used by std layout-shell molecules.\n *\n * Result shape:\n * - `category: 'interaction'`, `scope: 'instance'`\n * - `linkedEntity` set per the option\n * - `emits` declares the loaded + loadFailed events when `fetchEntity` is set\n * - One state: `'composing'` (`isInitial: true`)\n * - One transition: `composing → composing` on `INIT`, with effects:\n * - (when `fetchEntity` set) `['fetch', '<Entity>', { emit: { success, failure } }]`\n * - `['render-ui', slot, renderUI]`\n * - …`extraEffects` if provided\n *\n * Atoms whose trait names appear as `@trait.<name>` strings inside `renderUI`\n * get embedded by the runtime when the orbital instantiates. The LayoutTrait\n * itself stays stateless — all reactive behaviour lives in the embedded atoms.\n */\nexport function makeLayoutTrait(opts: MakeLayoutTraitOpts): Trait {\n const slot: UISlot = opts.slot ?? 'main';\n const effects: Effect[] = [];\n\n // Build emits list based on fetch configuration.\n const emits: Trait['emits'] = [];\n const eventDefs: NonNullable<Trait['stateMachine']>['events'] = [\n { key: 'INIT', name: 'Initialize' },\n ];\n\n if (opts.fetchEntity) {\n if (!opts.loadedEvent || !opts.loadFailedEvent) {\n throw new Error(\n `makeLayoutTrait: fetchEntity '${opts.fetchEntity}' set but loadedEvent / loadFailedEvent are required`,\n );\n }\n const payloadSchema =\n opts.loadedPayloadSchema ?? [{ name: 'data', type: `[${opts.fetchEntity}]` }];\n emits.push(\n { event: opts.loadedEvent, scope: 'internal', payloadSchema },\n {\n event: opts.loadFailedEvent,\n scope: 'internal',\n payloadSchema: [\n { name: 'error', type: 'string' },\n { name: 'code', type: 'string' },\n ],\n },\n );\n eventDefs.push(\n { key: opts.loadedEvent, name: `${opts.fetchEntity} loaded`, payloadSchema },\n {\n key: opts.loadFailedEvent,\n name: `${opts.fetchEntity} load failed`,\n payloadSchema: [\n { name: 'error', type: 'string' },\n { name: 'code', type: 'string' },\n ],\n },\n );\n // (fetch <Entity> { emit: { success, failure } })\n const fetchFx: FetchEffect = [\n 'fetch',\n opts.fetchEntity,\n { emit: { success: opts.loadedEvent, failure: opts.loadFailedEvent } },\n ];\n effects.push(fetchFx);\n }\n\n effects.push(makeRenderUI(slot, opts.renderUI));\n if (opts.extraEffects && opts.extraEffects.length > 0) {\n effects.push(...opts.extraEffects);\n }\n\n const trait: Trait = {\n name: opts.name,\n ...(opts.description ? { description: opts.description } : {}),\n category: 'interaction',\n linkedEntity: opts.linkedEntity,\n scope: 'instance',\n ...(emits.length > 0 ? { emits } : {}),\n stateMachine: {\n states: [{ name: 'composing', isInitial: true }],\n events: eventDefs,\n transitions: [\n {\n from: 'composing',\n to: 'composing',\n event: 'INIT',\n effects,\n },\n ],\n },\n };\n\n return trait;\n}\n","/**\n * Orbital Builders\n *\n * Pure functions for constructing and composing Orbitals.\n * No new types. Everything uses existing core types:\n * Entity, Trait, Page, OrbitalDefinition, OrbitalSchema.\n *\n * Three categories:\n * 1. Builders: construct Entity, Page from common params\n * 2. Utilities: ensureIdField, resolveDefaults\n * 3. Composition: connect, compose, pipe\n *\n * @packageDocumentation\n */\n\nimport type { Entity, EntityPersistence, EntityRow } from './types/entity.js';\nimport type { EntityField } from './types/field.js';\nimport type { Page } from './types/page.js';\nimport type { EntityRef, OrbitalDefinition, PageRef, PageRefObject, UseDeclaration } from './types/orbital.js';\nimport { isEntityCall, isEntityReference, parseEntityRef } from './types/orbital.js';\nimport type { OrbitalSchema } from './types/schema.js';\nimport type { TraitEventContract, TraitEventListener, Trait, TraitRef, TraitReference, TraitConfig } from './types/trait.js';\nimport type { SExpr } from './types/expression.js';\n\n// Re-export compose-behaviors module\nexport { type LayoutStrategy, detectLayoutStrategy } from './builders/layout-strategy.js';\nexport { type EventWiringEntry, applyEventWiring } from './builders/event-wiring.js';\nexport {\n type ComposeBehaviorsInput,\n type ComposeBehaviorsResult,\n composeBehaviors,\n} from './builders/compose-behaviors.js';\n// LayoutTrait + slot-embedding helpers (Phase 7.6 — atom-composition recipe path).\nexport {\n type MakeLayoutTraitOpts,\n makeSlot,\n makeRenderUI,\n makeLayoutTrait,\n} from './builders/layout-trait.js';\n\n// ============================================================================\n// Utilities\n// ============================================================================\n\n/**\n * Ensure the fields array has an `id` field. Prepends one if missing.\n */\nexport function ensureIdField(fields?: EntityField[]): EntityField[] {\n if (!fields || fields.length === 0) return [{ name: 'id', type: 'string', required: true }];\n if (fields.some(f => f.name === 'id')) return fields;\n return [{ name: 'id', type: 'string', required: true }, ...fields];\n}\n\n/**\n * Simple pluralization: append 's'.\n */\nexport function plural(name: string): string {\n return name + 's';\n}\n\n/**\n * Resolve a printable entity name from any EntityRef shape.\n *\n * Handles:\n * - inline Entity object (uses `name`)\n * - bare string reference like \"Modal.entity\" (uses the alias)\n * - EntityCall { extends: \"Modal.entity\", name? } (uses `name` if set, else the alias)\n */\nfunction resolveEntityNameForBuilder(ref: EntityRef): string {\n if (isEntityReference(ref)) {\n return parseEntityRef(ref)?.alias ?? ref;\n }\n if (isEntityCall(ref)) {\n if (ref.name) return ref.name;\n return parseEntityRef(ref.extends)?.alias ?? ref.extends;\n }\n return ref.name;\n}\n\n// ============================================================================\n// Entity Builder\n// ============================================================================\n\nexport interface MakeEntityOpts {\n name: string;\n fields: EntityField[];\n persistence?: EntityPersistence;\n collection?: string;\n /** Pre-authored seed data instances */\n instances?: EntityRow[];\n}\n\n/**\n * Build an Entity from options. Auto-adds id field, auto-derives collection.\n */\nexport function makeEntity(opts: MakeEntityOpts): Entity {\n const fields = ensureIdField(opts.fields);\n const persistence = opts.persistence ?? 'runtime';\n return {\n name: opts.name,\n persistence,\n ...(persistence === 'persistent'\n ? { collection: opts.collection ?? plural(opts.name).toLowerCase() }\n : {}),\n fields,\n ...(opts.instances && opts.instances.length > 0 ? { instances: opts.instances } : {}),\n };\n}\n\n// ============================================================================\n// Page Builder\n// ============================================================================\n\nexport interface MakePageOpts {\n name: string;\n path: string;\n traitName: string;\n isInitial?: boolean;\n}\n\n/**\n * Build a Page that binds to a single trait.\n */\nexport function makePage(opts: MakePageOpts): Page {\n return {\n name: opts.name,\n path: opts.path,\n ...(opts.isInitial ? { isInitial: true } : {}),\n traits: [{ ref: opts.traitName }],\n };\n}\n\n// ============================================================================\n// Orbital Builder\n// ============================================================================\n\n/**\n * Build an OrbitalDefinition from its three components.\n */\nexport function makeOrbital(\n name: string,\n entity: Entity,\n traits: Trait[],\n pages: Page[],\n): OrbitalDefinition {\n return { name, entity, traits, pages } as OrbitalDefinition;\n}\n\n// ============================================================================\n// Reference-form Builders (Phase 4.2)\n// ============================================================================\n//\n// The atom/molecule/organism composition model (see CLAUDE.md \"Std Behaviors\")\n// treats every imported orbital as a callable unit: a reference site is a call\n// site whose sibling fields are call arguments. The compiler's inline pass\n// applies overrides from the reference to a cloned copy of the imported unit.\n//\n// These four helpers are convenience factories for constructing the reference\n// payloads (TraitReference, PageRefObject) and the orbital skeleton that\n// holds them. They exist to compress the otherwise ~200-line-per-behavior TS\n// rewrite down to ~30 lines. They purely pass-through fields: undefined\n// optionals are omitted (the emitted object never contains `key: undefined`),\n// so the result stays compatible with the inliner's \"present-means-override\"\n// semantics.\n\n/**\n * Options for {@link makeTraitRef}.\n */\nexport interface MakeTraitRefOpts {\n /**\n * Optional registry path disambiguator that pairs with {@link ref}\n * (see {@link TraitReference.from}).\n */\n from?: string;\n /** Trait reference string, e.g. \"Browse.traits.BrowseItemBrowse\". */\n ref: string;\n /** Rename the inlined trait at the call site. */\n name?: string;\n /** Rebind the trait to a different linkedEntity. */\n linkedEntity?: string;\n /** Per-key rename map, e.g. `{ OPEN: \"ADD_ITEM\" }`. */\n events?: Record<string, string>;\n /**\n * Per-event SExpression effect replacement. Keys are POST-rename event\n * names. See {@link TraitReference.effects} for the full contract.\n */\n effects?: Record<string, SExpr[]>;\n /** Replace the imported trait's `listens` array entirely. */\n listens?: TraitEventListener[];\n /** Set every emit's scope. */\n emitsScope?: 'internal' | 'external';\n /** Call-site config overrides. Matches {@link TraitReference.config}. */\n config?: TraitConfig;\n}\n\n/**\n * Typed-narrowing variant of {@link MakeTraitRefOpts} for callers that know\n * the imported atom's overridable surfaces — its event-key set, listen-key\n * set, and config shape. Generated std factories use this variant so an LLM\n * tool consumer (orbital-agent) sees the closed event-name set and the\n * config field schema instead of the un-narrowed `Record<string, string>` /\n * `TraitConfig` defaults.\n *\n * Type parameters:\n * - `EventKey` — string union of the atom's emit event names. Narrows the\n * `events` rename map's keys to legal originals only.\n * - `ConfigShape` — typed shape of the trait's `config { ... }` block (literal\n * unions intact). Narrows the `config` override to the atom's actual fields.\n * - `ListenKey` — string union of the atom's listen-key contract. Narrows\n * each listens entry's `event` against the atom's real subscription set.\n *\n * Runtime behavior is unchanged — {@link makeTraitRef} accepts both the\n * narrow and wide forms via the standard structural-typing rules. This is\n * a type-level narrowing only; widening at the call boundary is intentional.\n */\nexport interface MakeTraitRefOptsTyped<\n EventKey extends string = string,\n ConfigShape extends TraitConfig = Record<string, never>,\n ListenKey extends string = string,\n> extends Omit<\n MakeTraitRefOpts,\n 'events' | 'effects' | 'listens' | 'config'\n > {\n /** Per-key rename map, narrowed to the atom's actual event keys. */\n events?: Partial<Record<EventKey, string>>;\n /**\n * Per-event SExpression effect replacement. Keys are POST-rename event\n * names so they're caller-defined (no narrowing here); values stay typed\n * as `SExpr[]`.\n */\n effects?: Partial<Record<string, SExpr[]>>;\n /**\n * Replace the imported trait's `listens` array entirely. Each entry's\n * `event` field is narrowed to {@link ListenKey} where the atom's\n * subscription set is fixed; otherwise this widens to plain string.\n */\n listens?: Array<TraitEventListener & { event?: ListenKey }>;\n /** Typed call-site config overrides — narrowed to {@link ConfigShape}. */\n config?: ConfigShape;\n}\n\n/**\n * Build a {@link TraitReference} from options.\n *\n * Pass-through factory: copies only the fields that are actually provided,\n * so optionals stay absent (no `key: undefined` slots) and the emitted\n * object matches the inliner's expectation that \"present = override\".\n */\nexport function makeTraitRef(opts: MakeTraitRefOpts): TraitReference {\n const ref: TraitReference = { ref: opts.ref };\n if (opts.from !== undefined) ref.from = opts.from;\n if (opts.name !== undefined) ref.name = opts.name;\n if (opts.linkedEntity !== undefined) ref.linkedEntity = opts.linkedEntity;\n if (opts.events !== undefined) ref.events = opts.events;\n if (opts.effects !== undefined) ref.effects = opts.effects;\n if (opts.listens !== undefined) ref.listens = opts.listens;\n if (opts.emitsScope !== undefined) ref.emitsScope = opts.emitsScope;\n if (opts.config !== undefined) ref.config = opts.config;\n return ref;\n}\n\n/**\n * Options for {@link makePageRef}.\n */\nexport interface MakePageRefOpts {\n /**\n * Optional registry path disambiguator that pairs with {@link ref}\n * (see {@link PageRefObject.from}).\n */\n from?: string;\n /** Page reference string, e.g. \"Browse.pages.BrowseItemPage\". */\n ref: string;\n /** URL path override. */\n path?: string;\n /** Rebind the page's primary entity. */\n linkedEntity?: string;\n /** Replace the page's trait list. */\n traits?: TraitRef[];\n}\n\n/**\n * Typed-narrowing variant of {@link MakePageRefOpts}. Narrows the `traits`\n * override array's entries to the orbital's known trait-name union — so the\n * agent can't pass a trait name that doesn't exist on the page's owning\n * orbital. Generated std page-helpers use this variant to surface the\n * trait set in the tool schema; un-narrowed call sites stay compatible.\n *\n * Type parameter:\n * - `TraitName` — string union of trait names the page may reference.\n */\nexport interface MakePageRefOptsTyped<TraitName extends string = string>\n extends Omit<MakePageRefOpts, 'traits'> {\n traits?: Array<{ ref: TraitName } | TraitRef>;\n}\n\n/**\n * Build a {@link PageRefObject} from options. Pass-through factory — omits\n * optional keys that are `undefined`.\n */\nexport function makePageRef(opts: MakePageRefOpts): PageRefObject {\n const ref: PageRefObject = { ref: opts.ref };\n if (opts.from !== undefined) ref.from = opts.from;\n if (opts.path !== undefined) ref.path = opts.path;\n if (opts.linkedEntity !== undefined) ref.linkedEntity = opts.linkedEntity;\n if (opts.traits !== undefined) ref.traits = opts.traits;\n return ref;\n}\n\n/**\n * Options for {@link makeOrbitalWithUses}.\n */\nexport interface MakeOrbitalWithUsesOpts {\n /** Orbital name. */\n name: string;\n /**\n * Per-orbital `uses:` header entries (see CLAUDE.md \"uses: lives inside\n * the orbital\").\n */\n uses: UseDeclaration[];\n /** Entity (inline or reference form). */\n entity: EntityRef;\n /** Trait references. */\n traits: TraitRef[];\n /** Optional page references (omitted entirely when not provided). */\n pages?: PageRef[];\n}\n\n/**\n * Build an {@link OrbitalDefinition} with the `uses:` header set. Follows\n * the convention that `uses:` lives on the orbital (not the schema).\n *\n * When `pages` is omitted, the result has no `pages` property (matches the\n * existing {@link OrbitalDefinition.pages} optionality in descriptors that\n * carry trait-only atoms).\n */\nexport function makeOrbitalWithUses(opts: MakeOrbitalWithUsesOpts): OrbitalDefinition {\n const orbital: OrbitalDefinition = {\n name: opts.name,\n uses: opts.uses,\n entity: opts.entity,\n traits: opts.traits,\n pages: opts.pages ?? [],\n };\n return orbital;\n}\n\n/**\n * Options for {@link makeAtomOrbital}.\n *\n * Overrides for the single trait reference. Mirrors the {@link MakeTraitRefOpts}\n * subset that is meaningful at the atom-wrapping call site.\n */\nexport interface MakeAtomOrbitalTraitOverrides {\n name?: string;\n events?: Record<string, string>;\n effects?: Record<string, SExpr[]>;\n listens?: TraitEventListener[];\n emitsScope?: 'internal' | 'external';\n config?: TraitConfig;\n}\n\n/**\n * Options for {@link makeAtomOrbital}.\n */\nexport interface MakeAtomOrbitalOpts {\n /** Orbital name, e.g. `${entityName}Orbital`. */\n name: string;\n /** Atom registry path, e.g. `std/behaviors/atoms/std-browse`. */\n atomPath: string;\n /** Import alias (PascalCase), e.g. `Browse`. */\n alias: string;\n /** Entity definition to attach to the orbital. */\n entity: Entity;\n /** Trait reference string, e.g. `Browse.traits.BrowseItemBrowse`. */\n traitRef: string;\n /** Optional trait-level overrides applied at the call site. */\n traitOverrides?: MakeAtomOrbitalTraitOverrides;\n /** Optional page reference string, e.g. `Browse.pages.BrowseItemPage`. */\n pageRef?: string;\n /** Optional page-level overrides applied at the call site. */\n pageOverrides?: { path?: string };\n}\n\n/**\n * Build a single-atom {@link OrbitalDefinition}.\n *\n * The common atom shape: one entity + one trait reference + (optionally) one\n * page reference, all under a single `uses:` import. Wraps\n * {@link makeTraitRef}, {@link makePageRef}, and {@link makeOrbitalWithUses}.\n *\n * The trait reference is linkedEntity-bound to `entity.name` by default so\n * that the inliner's entity-substitution pass rewrites every `[\"ref\", X]`\n * and `@X.path` reference inside the atom.\n */\nexport function makeAtomOrbital(opts: MakeAtomOrbitalOpts): OrbitalDefinition {\n const traitRef = makeTraitRef({\n from: opts.atomPath,\n ref: opts.traitRef,\n linkedEntity: opts.entity.name,\n ...(opts.traitOverrides?.name !== undefined ? { name: opts.traitOverrides.name } : {}),\n ...(opts.traitOverrides?.events !== undefined ? { events: opts.traitOverrides.events } : {}),\n ...(opts.traitOverrides?.effects !== undefined ? { effects: opts.traitOverrides.effects } : {}),\n ...(opts.traitOverrides?.listens !== undefined ? { listens: opts.traitOverrides.listens } : {}),\n ...(opts.traitOverrides?.emitsScope !== undefined\n ? { emitsScope: opts.traitOverrides.emitsScope }\n : {}),\n ...(opts.traitOverrides?.config !== undefined ? { config: opts.traitOverrides.config } : {}),\n });\n\n const pages: PageRef[] | undefined = opts.pageRef\n ? [\n makePageRef({\n from: opts.atomPath,\n ref: opts.pageRef,\n linkedEntity: opts.entity.name,\n ...(opts.pageOverrides?.path !== undefined ? { path: opts.pageOverrides.path } : {}),\n }),\n ]\n : undefined;\n\n return makeOrbitalWithUses({\n name: opts.name,\n uses: [{ from: opts.atomPath, as: opts.alias }],\n entity: opts.entity,\n traits: [traitRef],\n ...(pages !== undefined ? { pages } : {}),\n });\n}\n\n/**\n * Wrap one or more OrbitalDefinitions into an OrbitalSchema.\n * Every .orb file should be a full OrbitalSchema — this is the builder for that.\n */\nexport function makeSchema(name: string, ...definitions: OrbitalDefinition[]): OrbitalSchema {\n return { name, version: '1.0.0', orbitals: definitions };\n}\n\n/**\n * Unwrap inputs that may be OrbitalSchema or OrbitalDefinition into a flat\n * array of OrbitalDefinitions. Used internally by compose/pipe/connect/extractTrait\n * so they accept both types.\n */\nfunction asDefinitions(inputs: (OrbitalDefinition | OrbitalSchema)[]): OrbitalDefinition[] {\n return inputs.flatMap(input => {\n if ('orbitals' in input && Array.isArray((input as OrbitalSchema).orbitals)) {\n return (input as OrbitalSchema).orbitals as OrbitalDefinition[];\n }\n return [input as OrbitalDefinition];\n });\n}\n\n/** Unwrap a single OrbitalSchema | OrbitalDefinition to OrbitalDefinition. */\nfunction asDefinition(input: OrbitalDefinition | OrbitalSchema): OrbitalDefinition {\n if ('orbitals' in input && Array.isArray((input as OrbitalSchema).orbitals)) {\n return (input as OrbitalSchema).orbitals[0] as OrbitalDefinition;\n }\n return input as OrbitalDefinition;\n}\n\n// ============================================================================\n// Intra-Orbital Composition\n// ============================================================================\n\n/**\n * Merge multiple OrbitalDefinitions into one.\n * Collects all traits from all sources into a single orbital with a shared entity.\n * Pure: clones all traits, no mutation.\n */\nexport function mergeOrbitals(\n name: string,\n entity: Entity,\n sources: OrbitalDefinition[],\n pages: Page[],\n): OrbitalDefinition {\n const allTraits = sources.flatMap(s =>\n (s.traits as Trait[]).map(t => structuredClone(t)),\n );\n return { name, entity, traits: allTraits, pages } as OrbitalDefinition;\n}\n\n/**\n * Wire an intra-orbital event between two traits.\n * Adds emits to the source trait, listens to the target trait.\n * Pure: returns cloned traits, no mutation.\n */\nexport function wire(\n source: Trait,\n target: Trait,\n event: TraitEventContract,\n triggers: string,\n): [Trait, Trait] {\n const s = structuredClone(source);\n const t = structuredClone(target);\n\n s.emits = [...(s.emits ?? []), { ...event, scope: event.scope ?? ('internal' as const) }];\n t.listens = [...(t.listens ?? []), {\n event: event.event,\n triggers,\n scope: 'internal' as const,\n }];\n\n return [s, t];\n}\n\n/**\n * Extract the first trait from an OrbitalDefinition or OrbitalSchema.\n * If given an OrbitalSchema, unwraps to the first orbital inside it.\n */\nexport function extractTrait(input: OrbitalDefinition | OrbitalSchema): Trait {\n const orbital = asDefinition(input);\n return structuredClone((orbital.traits as Trait[])[0]);\n}\n\n// ============================================================================\n// Composition: connect\n// ============================================================================\n\n/**\n * Wire a cross-orbital event between two orbitals.\n * Adds emits to a's first trait, listens to b's first trait.\n * Pure: returns new orbitals, no mutation.\n */\nexport function connect(\n a: OrbitalDefinition | OrbitalSchema,\n b: OrbitalDefinition | OrbitalSchema,\n event: TraitEventContract,\n triggers?: string,\n): [OrbitalDefinition, OrbitalDefinition] {\n const aClone = structuredClone(asDefinition(a));\n const bClone = structuredClone(asDefinition(b));\n\n // Add emit to first trait of a\n const aTrait = (aClone.traits as Trait[])[0];\n if (aTrait) {\n const emitContract: TraitEventContract = {\n ...event,\n scope: event.scope ?? 'external',\n };\n aTrait.emits = [...(aTrait.emits ?? []), emitContract];\n }\n\n // Add listen to first trait of b\n const bTrait = (bClone.traits as Trait[])[0];\n if (bTrait) {\n const listener: TraitEventListener = {\n event: event.event,\n triggers: triggers ?? 'INIT',\n scope: 'external',\n };\n bTrait.listens = [...(bTrait.listens ?? []), listener];\n }\n\n return [aClone, bClone];\n}\n\n// ============================================================================\n// Composition: compose\n// ============================================================================\n\nexport interface ComposeConnection {\n from: string;\n to: string;\n event: TraitEventContract;\n triggers?: string;\n}\n\nexport interface ComposePage {\n name: string;\n path: string;\n traits: string[];\n isInitial?: boolean;\n}\n\n/**\n * Compose multiple orbitals into a single OrbitalSchema (application).\n * Applies connections (cross-orbital event wiring) and page assignments.\n */\nexport function compose(\n orbitals: (OrbitalDefinition | OrbitalSchema)[],\n pages: ComposePage[],\n connections: ComposeConnection[],\n appName?: string,\n): OrbitalSchema {\n const cloned = structuredClone(asDefinitions(orbitals));\n\n // Apply connections\n for (const conn of connections) {\n const emitter = cloned.find(o => {\n const traits = o.traits as Trait[];\n return traits.some(t => t.name === conn.from);\n });\n const listener = cloned.find(o => {\n const traits = o.traits as Trait[];\n return traits.some(t => t.name === conn.to);\n });\n\n if (emitter && listener) {\n const eTrait = (emitter.traits as Trait[]).find(t => t.name === conn.from);\n const lTrait = (listener.traits as Trait[]).find(t => t.name === conn.to);\n\n if (eTrait) {\n const emitContract: TraitEventContract = { ...conn.event, scope: conn.event.scope ?? 'external' };\n eTrait.emits = [...(eTrait.emits ?? []), emitContract];\n }\n if (lTrait) {\n const listenContract: TraitEventListener = {\n event: conn.event.event,\n triggers: conn.triggers ?? 'INIT',\n scope: 'external',\n };\n lTrait.listens = [...(lTrait.listens ?? []), listenContract];\n }\n }\n }\n\n // Assign pages to orbitals\n for (const orbital of cloned) {\n const traitNames = (orbital.traits as Trait[]).map(t => t.name);\n const matchingPages = pages.filter(p =>\n p.traits.some(t => traitNames.includes(t)),\n );\n orbital.pages = matchingPages.map(p => ({\n name: p.name,\n path: p.path,\n ...(p.isInitial ? { isInitial: true } : {}),\n traits: p.traits\n .filter(t => traitNames.includes(t))\n .map(ref => ({ ref })),\n }));\n }\n\n return {\n name: appName ?? 'Application',\n version: '1.0.0',\n orbitals: cloned,\n };\n}\n\n// ============================================================================\n// Composition: pipe\n// ============================================================================\n\n/**\n * Chain orbitals in sequence with automatic event wiring.\n * Sugar over connect + compose: wires events[0] from orbital[0] to orbital[1], etc.\n */\nexport function pipe(\n orbitals: (OrbitalDefinition | OrbitalSchema)[],\n events: TraitEventContract[],\n appName?: string,\n): OrbitalSchema {\n if (events.length !== orbitals.length - 1) {\n throw new Error(`pipe requires exactly ${orbitals.length - 1} events for ${orbitals.length} orbitals`);\n }\n\n const cloned = structuredClone(asDefinitions(orbitals));\n\n // Wire adjacent pairs\n for (let i = 0; i < events.length; i++) {\n const aTrait = (cloned[i].traits as Trait[])[0];\n const bTrait = (cloned[i + 1].traits as Trait[])[0];\n\n if (aTrait) {\n const emitContract: TraitEventContract = { ...events[i], scope: events[i].scope ?? 'external' };\n aTrait.emits = [...(aTrait.emits ?? []), emitContract];\n }\n if (bTrait) {\n const listener: TraitEventListener = {\n event: events[i].event,\n triggers: 'INIT',\n scope: 'external',\n };\n bTrait.listens = [...(bTrait.listens ?? []), listener];\n }\n }\n\n // Auto-generate pages: one per orbital, first is initial\n const pages: Page[] = cloned.map((o, i) => {\n const entityName = resolveEntityNameForBuilder(o.entity);\n const traitNames = (o.traits as Trait[]).map(t => t.name);\n return {\n name: `${entityName}Page`,\n path: `/${plural(entityName).toLowerCase()}`,\n ...(i === 0 ? { isInitial: true } : {}),\n traits: traitNames.map(ref => ({ ref })),\n };\n });\n\n // Assign pages back to orbitals\n for (let i = 0; i < cloned.length; i++) {\n cloned[i].pages = [pages[i]];\n }\n\n return {\n name: appName ?? 'Application',\n version: '1.0.0',\n orbitals: cloned,\n };\n}\n"]}
|
|
1
|
+
{"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/builders/layout-strategy.ts","../src/builders/event-wiring.ts","../src/builders/compose-behaviors.ts","../src/builders/layout-trait.ts","../src/builders.ts"],"names":["z","asDefinitions"],"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,CAAA;AAiBM,IAAM,yBAAA,GAA4B,EAAE,IAAA,CAAK;AAAA,EAC5C,KAAA;AAAA,EACA,MAAA;AAAA,EACA,aAAA;AAAA,EACA,aAAA;AAAA,EACA;AACJ,CAAC,CAAA;AAmCM,IAAM,oBAAA,GAAuB,EAAE,MAAA,CAAO;AAAA,EACzC,QAAQ,CAAA,CAAE,MAAA,EAAO,CAAE,GAAA,CAAI,GAAG,2BAA2B,CAAA;AAAA,EACrD,KAAA,EAAO,CAAA,CAAE,MAAA,EAAO,C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AAI,MAAA,CAAO,QAAQ,CAAA,EAAA,EAAK;AACtC,IAAA,MAAA,CAAO,CAAC,CAAA,CAAE,KAAA,GAAQ,CAAC,KAAA,CAAM,CAAC,CAAC,CAAA;AAAA,EAC7B;AAEA,EAAA,OAAO;AAAA,IACL,MAAM,OAAA,IAAW,aAAA;AAAA,IACjB,OAAA,EAAS,OAAA;AAAA,IACT,QAAA,EAAU;AAAA,GACZ;AACF","file":"builders.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 * Author-supplied capability tags lifted from the `.lolo` trait header's\n * bracket list. Anything beyond the known scope tokens (`instance` /\n * `collection`) and the first category identifier accumulates here.\n * Free-form strings — the lolo parser does not validate them against a\n * known set. The Phase 4 translator overlay matches rules to traits by\n * exact set membership against this list. Empty when no capabilities\n * were declared. See `docs/Almadar_Domain_Language.md` Phase 3.\n */\n capabilities?: string[];\n /**\n * Instance or collection scope. Required in V2: every trait operates on\n * either a single record (`instance`) or a group (`collection`). Drives\n * payload-inference rules for emits declared via `type X = Event<T>` and\n * shapes the runtime's binding semantics. Authored in `.lolo` as the\n * `[instance]` / `[collection]` modifier on the trait header.\n */\n scope: TraitScope;\n /**\n * The entity this trait is linked to.\n * Required for inline trait definitions within an orbital.\n */\n linkedEntity?: string;\n requiredFields?: RequiredField[];\n dataEntities?: TraitDataEntity[];\n stateMachine?: StateMachine;\n initialEffects?: Effect[];\n ticks?: TraitTick[];\n /**\n * Events this trait emits.\n * Each event can be scoped as internal or external.\n * External events are namespaced at orbital level (TraitName.EVENT_NAME).\n */\n emits?: TraitEventContract[];\n /**\n * Events this trait listens for.\n * External listeners reference namespaced events (TraitName.EVENT_NAME).\n */\n listens?: TraitEventListener[];\n ui?: TraitUIBinding;\n /**\n * Declared `config { }` schema authored on the trait. Drives\n * `@config.X` substitution: each field's `default` seeds the\n * binding context behind any caller-supplied call-site\n * `config: { ... }` override.\n */\n config?: DeclaredTraitConfig;\n /**\n * Set by the resolve/inline phase when this trait was cloned from a\n * `uses[]` import. Absent for traits authored directly on the\n * orbital. Viewport-only metadata — runtime and codegen ignore it.\n * Drives Studio's L2 grouping (imported traits collapse under one\n * card per alias) and L3 drill (alias → that behavior's transitions).\n */\n sourceBehavior?: SourceBehaviorMetadata;\n /**\n * Set by the resolve/inline phase alongside `sourceBehavior`. Carries\n * the resolved `Entity` definition of the imported behavior so the\n * client-side mock-data generator can produce rows for the trait's\n * `linkedEntity` without re-walking the import graph at runtime.\n */\n sourceEntityDefinition?: Entity;\n}\n\n/**\n * Provenance attached to a trait that was cloned from a `uses[]` import\n * during the inline phase. The resolved schema carries this so Studio\n * can group L2 cards by source behavior and offer an L3 drill into the\n * import's own transitions.\n */\nexport interface SourceBehaviorMetadata {\n /** Behavior name (e.g. \"std-stat-card\") — the resolved `from:` value. */\n behavior: string;\n /** Alias used at the import site (e.g. \"Stat\"). Multiple imports of\n * the same atom group by alias, not by behavior. */\n alias: string;\n /** Original trait name inside the imported behavior, before any\n * call-site `name:` rename. */\n originalName: string;\n}\n\nexport const SourceBehaviorMetadataSchema = z.object({\n behavior: z.string().min(1),\n alias: z.string().min(1),\n originalName: z.string().min(1),\n});\n\nexport const TraitSchema = z.object({\n name: z.string().min(1),\n description: z.string().optional(),\n description_visual_prompt: z.string().optional(),\n category: TraitCategorySchema.optional(),\n capabilities: z.array(z.string()).optional(),\n scope: TraitScopeSchema,\n linkedEntity: z.string().optional(),\n requiredFields: z.array(RequiredFieldSchema).optional(),\n dataEntities: z.array(TraitDataEntitySchema).optional(),\n stateMachine: StateMachineSchema.optional(),\n initialEffects: z.array(EffectSchema).optional(),\n ticks: z.array(TraitTickSchema).optional(),\n emits: z.array(TraitEventContractSchema).optional(),\n listens: z.array(TraitEventListenerSchema).optional(),\n ui: z.record(z.unknown()).optional(),\n config: DeclaredTraitConfigSchema.optional(),\n sourceBehavior: SourceBehaviorMetadataSchema.optional(),\n sourceEntityDefinition: EntitySchema.optional(),\n});\n\n// TraitRefSchema defined here after TraitSchema to avoid forward reference\nexport const TraitRefSchema = z.union([\n z.string().min(1),\n z.object({\n ref: z.string().min(1),\n config: TraitConfigSchema.optional(),\n linkedEntity: z.string().optional(),\n name: z.string().optional(),\n // Phase F.4: same non-empty refine as TraitReferenceSchema.events.\n // Both schemas accept the same call-site argument shape, so the\n // validators should agree.\n events: z\n .record(\n z.string().min(1, \"events key (atom event name) must be non-empty\"),\n z.string().min(1, \"events value (caller event name) must be non-empty\"),\n )\n .optional(),\n }),\n TraitSchema, // Allow inline trait definitions\n]);\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Check if a trait ref is an inline Trait definition\n */\n/**\n * Checks if a trait reference is an inline trait definition.\n * \n * Type guard to determine if a TraitRef is an inline trait object\n * (with 'name' property) rather than a string reference or object reference.\n * \n * @param {TraitRef} traitRef - Trait reference to check\n * @returns {boolean} True if traitRef is an inline trait, false otherwise\n * \n * @example\n * isInlineTrait({ name: 'MyTrait' }); // returns true (inline)\n * isInlineTrait('MyTrait'); // returns false (string reference)\n * isInlineTrait({ ref: 'MyTrait' }); // returns false (object reference)\n */\nexport function isInlineTrait(traitRef: TraitRef): traitRef is Trait {\n return typeof traitRef === 'object' && 'name' in traitRef && !('ref' in traitRef);\n}\n\n/**\n * Extracts the trait name from a trait reference.\n * \n * Handles all trait reference formats (string, inline object, object reference)\n * and returns the canonical trait name.\n * \n * @param {TraitRef} traitRef - Trait reference to extract name from\n * @returns {string} Trait name\n * \n * @example\n * getTraitName('MyTrait'); // returns 'MyTrait'\n * getTraitName({ name: 'MyTrait' }); // returns 'MyTrait'\n * getTraitName({ ref: 'MyTrait' }); // returns 'MyTrait'\n */\nexport function getTraitName(traitRef: TraitRef): string {\n if (typeof traitRef === 'string') {\n return traitRef;\n }\n if (isInlineTrait(traitRef)) {\n return traitRef.name;\n }\n return traitRef.ref;\n}\n\n/**\n * Extracts the configuration from a trait reference.\n * \n * Returns the configuration object for trait references that support it\n * (object references with 'config' property). Returns undefined for\n * string references and inline traits.\n * \n * @param {TraitRef} traitRef - Trait reference to extract config from\n * @returns {TraitConfig | undefined} Trait configuration or undefined\n *\n * @example\n * getTraitConfig('MyTrait'); // returns undefined\n * getTraitConfig({ name: 'MyTrait' }); // returns undefined\n * getTraitConfig({ ref: 'MyTrait', config: { option: 'value' } }); // returns config object\n */\nexport function getTraitConfig(traitRef: TraitRef): 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 * Layout Strategy Detection\n *\n * Auto-detects the best layout strategy for a composed application\n * based on the number of orbitals and their event wiring topology.\n *\n * @packageDocumentation\n */\n\nimport type { OrbitalDefinition } from '../types/orbital.js';\nimport type { EventWiringEntry } from './event-wiring.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Layout strategy for the composed application.\n *\n * - 'single': One orbital, one page\n * - 'tabs': 2-4 orbitals with no sequential chain\n * - 'sidebar': 5+ orbitals (navigation-heavy)\n * - 'dashboard': Single page with all orbitals visible\n * - 'wizard-flow': Sequential event chain detected (A -> B -> C)\n */\nexport type LayoutStrategy =\n | 'sidebar'\n | 'tabs'\n | 'dashboard'\n | 'wizard-flow'\n | 'single';\n\n// ============================================================================\n// Chain Detection\n// ============================================================================\n\n/**\n * Detect whether the event wiring forms a sequential chain.\n *\n * A sequential chain exists when orbital A's `from` feeds into B's `to`,\n * and B's `from` feeds into C's `to`, forming A -> B -> C.\n *\n * We build a directed graph from wiring entries and look for a chain\n * that covers 3+ nodes (the minimum for a meaningful wizard flow).\n */\nfunction hasSequentialChain(wiring: EventWiringEntry[]): boolean {\n if (wiring.length < 2) {\n return false;\n }\n\n // Build adjacency: from -> Set<to>\n const adjacency = new Map<string, Set<string>>();\n const allTargets = new Set<string>();\n\n for (const entry of wiring) {\n let targets = adjacency.get(entry.from);\n if (!targets) {\n targets = new Set<string>();\n adjacency.set(entry.from, targets);\n }\n targets.add(entry.to);\n allTargets.add(entry.to);\n }\n\n // Find roots (nodes that are sources but never targets)\n const roots: string[] = [];\n for (const from of adjacency.keys()) {\n if (!allTargets.has(from)) {\n roots.push(from);\n }\n }\n\n // If no clear root, try all sources\n const starts = roots.length > 0 ? roots : [...adjacency.keys()];\n\n // Walk from each start and measure chain length\n for (const start of starts) {\n let current = start;\n let length = 1;\n const visited = new Set<string>([current]);\n\n while (true) {\n const nexts = adjacency.get(current);\n if (!nexts || nexts.size === 0) break;\n\n // Follow the first unvisited successor (linear chain)\n let advanced = false;\n for (const next of nexts) {\n if (!visited.has(next)) {\n visited.add(next);\n current = next;\n length++;\n advanced = true;\n break;\n }\n }\n\n if (!advanced) break;\n }\n\n // A chain of 3+ nodes qualifies as wizard-flow\n if (length >= 3) {\n return true;\n }\n }\n\n return false;\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Detect the best layout strategy based on orbital count and event wiring.\n *\n * Heuristic:\n * 1. Sequential event chain detected -> 'wizard-flow'\n * 2. 1 orbital -> 'single'\n * 3. 2-4 orbitals -> 'tabs'\n * 4. 5+ orbitals -> 'sidebar'\n */\nexport function detectLayoutStrategy(\n orbitals: OrbitalDefinition[],\n eventWiring?: EventWiringEntry[],\n): LayoutStrategy {\n // Check for sequential chain first (takes priority)\n if (eventWiring && eventWiring.length > 0 && hasSequentialChain(eventWiring)) {\n return 'wizard-flow';\n }\n\n const count = orbitals.length;\n\n if (count <= 1) {\n return 'single';\n }\n\n if (count <= 4) {\n return 'tabs';\n }\n\n return 'sidebar';\n}\n","/**\n * Event Wiring\n *\n * Applies cross-orbital event wiring to orbital definitions.\n * Adds emits/listens declarations to traits so they can communicate\n * across orbital boundaries.\n *\n * @packageDocumentation\n */\n\nimport type { OrbitalDefinition } from '../types/orbital.js';\nimport type { Trait, TraitEventContract, TraitEventListener } from '../types/trait.js';\nimport { isInlineTrait } from '../types/trait.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * A single event wiring entry connecting two traits across orbitals.\n */\nexport interface EventWiringEntry {\n /** Source trait name or orbital name */\n from: string;\n /** Event name (UPPER_SNAKE_CASE) */\n event: string;\n /** Target trait name or orbital name */\n to: string;\n /** Event to trigger on the listener side */\n triggers: string;\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/**\n * Find a trait by name across all orbitals.\n * Only inline traits can be mutated; string/ref traits are skipped.\n * Returns the inline Trait object if found, or null.\n */\nfunction findInlineTrait(\n orbitals: OrbitalDefinition[],\n name: string,\n): Trait | null {\n for (const orbital of orbitals) {\n for (const traitRef of orbital.traits) {\n if (isInlineTrait(traitRef) && traitRef.name === name) {\n return traitRef;\n }\n }\n }\n return null;\n}\n\n/**\n * Check if an emit already exists in the list.\n * @internal\n */\nfunction hasEmit(emits: TraitEventContract[], event: string): boolean {\n return emits.some((e) => e.event === event);\n}\n\n/**\n * Check if a listen already exists in the list.\n * @internal\n */\nfunction hasListen(\n listens: TraitEventListener[],\n event: string,\n triggers: string,\n): boolean {\n return listens.some((l) => l.event === event && l.triggers === triggers);\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Apply event wiring to orbital definitions.\n *\n * For each wiring entry:\n * 1. Find the source trait and add an external emit (if not already present)\n * 2. Find the target trait and add an external listen (if not already present)\n *\n * Returns a new array of orbitals with wiring applied (deep-cloned).\n */\nexport function applyEventWiring(\n orbitals: OrbitalDefinition[],\n wiring: EventWiringEntry[],\n): OrbitalDefinition[] {\n // Deep clone to avoid mutating input\n const cloned: OrbitalDefinition[] = JSON.parse(\n JSON.stringify(orbitals),\n ) as OrbitalDefinition[];\n\n for (const entry of wiring) {\n // Wire the source: add emit\n const sourceTrait = findInlineTrait(cloned, entry.from);\n if (sourceTrait) {\n if (!sourceTrait.emits) {\n sourceTrait.emits = [];\n }\n if (!hasEmit(sourceTrait.emits, entry.event)) {\n sourceTrait.emits.push({\n event: entry.event,\n scope: 'external',\n });\n }\n }\n\n // Wire the target: add listen\n const targetTrait = findInlineTrait(cloned, entry.to);\n if (targetTrait) {\n if (!targetTrait.listens) {\n targetTrait.listens = [];\n }\n if (!hasListen(targetTrait.listens, entry.event, entry.triggers)) {\n targetTrait.listens.push({\n event: entry.event,\n triggers: entry.triggers,\n scope: 'external',\n });\n }\n }\n }\n\n return cloned;\n}\n","/**\n * Compose Behaviors\n *\n * Main entry point for composing multiple orbital definitions into\n * a single OrbitalSchema application. Handles event wiring, layout\n * strategy detection, and page generation.\n *\n * @packageDocumentation\n */\n\nimport type { OrbitalDefinition } from '../types/orbital.js';\nimport type { OrbitalSchema } from '../types/schema.js';\n\n/** Unwrap OrbitalSchema | OrbitalDefinition inputs to a flat OrbitalDefinition[]. */\nfunction asDefinitions(inputs: (OrbitalDefinition | OrbitalSchema)[]): OrbitalDefinition[] {\n return inputs.flatMap(input => {\n if ('orbitals' in input && Array.isArray((input as OrbitalSchema).orbitals)) {\n return (input as OrbitalSchema).orbitals as OrbitalDefinition[];\n }\n return [input as OrbitalDefinition];\n });\n}\nimport type { Page } from '../types/page.js';\nimport type { EventWiringEntry } from './event-wiring.js';\nimport { applyEventWiring } from './event-wiring.js';\nimport type { LayoutStrategy } from './layout-strategy.js';\nimport { detectLayoutStrategy } from './layout-strategy.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Input for composing behaviors into an application.\n */\nexport interface ComposeBehaviorsInput {\n /** Application name */\n appName: string;\n /** Orbital definitions (or schemas) to compose */\n orbitals: (OrbitalDefinition | OrbitalSchema)[];\n /** Layout strategy override, or 'auto' to detect */\n layoutStrategy?: LayoutStrategy | 'auto';\n /** Cross-orbital event wiring */\n eventWiring?: EventWiringEntry[];\n /** Optional entity name mappings (original -> renamed) */\n entityMappings?: Record<string, string>;\n}\n\n/**\n * Result of composing behaviors.\n */\nexport interface ComposeBehaviorsResult {\n /** The composed OrbitalSchema */\n schema: OrbitalSchema;\n /** Layout metadata */\n layout: { strategy: LayoutStrategy; pageCount: number };\n /** Wiring metadata */\n wiring: { connections: number };\n}\n\n// ============================================================================\n// Page Generation\n// ============================================================================\n\nfunction toKebabCase(name: string): string {\n return name\n .replace(/([a-z])([A-Z])/g, '$1-$2')\n .replace(/[\\s_]+/g, '-')\n .toLowerCase();\n}\n\n/**\n * Generate pages for each orbital based on the layout strategy.\n *\n * For strategies that produce one page per orbital (sidebar, tabs, wizard-flow),\n * each orbital gets a page at `/<kebab-name>` with `isInitial` on the first.\n *\n * For 'dashboard', all orbitals share a single page.\n * For 'single', the lone orbital gets a single root page.\n */\nfunction generatePages(\n orbitals: OrbitalDefinition[],\n strategy: LayoutStrategy,\n): Page[] {\n switch (strategy) {\n case 'single': {\n const orbital = orbitals[0];\n const name = orbital?.name ?? 'Main';\n return [\n {\n name: `${name}Page`,\n path: '/',\n isInitial: true,\n primaryEntity: getEntityName(orbital),\n },\n ];\n }\n\n case 'dashboard': {\n return [\n {\n name: 'DashboardPage',\n path: '/',\n viewType: 'dashboard',\n isInitial: true,\n },\n ];\n }\n\n case 'sidebar':\n case 'tabs':\n case 'wizard-flow': {\n return orbitals.map((orbital, index) => ({\n name: `${orbital.name}Page`,\n path: index === 0 ? '/' : `/${toKebabCase(orbital.name)}`,\n isInitial: index === 0,\n primaryEntity: getEntityName(orbital),\n }));\n }\n }\n}\n\n/**\n * Extract entity name from an orbital definition.\n * Handles both inline entities and string references.\n */\nfunction getEntityName(orbital: OrbitalDefinition | undefined): string | undefined {\n if (!orbital) return undefined;\n const entity = orbital.entity;\n if (typeof entity === 'string') {\n // Reference like \"Alias.entity\" - extract the alias as entity name\n return entity.replace('.entity', '');\n }\n return entity.name;\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Compose multiple orbital definitions into a single application schema.\n *\n * Steps:\n * 1. Apply event wiring (adds emits/listens to traits)\n * 2. Detect or use provided layout strategy\n * 3. Generate pages based on the strategy\n * 4. Build the final OrbitalSchema\n */\nexport function composeBehaviors(\n input: ComposeBehaviorsInput,\n): ComposeBehaviorsResult {\n const {\n appName,\n orbitals: rawInputs,\n layoutStrategy: strategyInput,\n eventWiring,\n } = input;\n\n // Unwrap any OrbitalSchema inputs to OrbitalDefinition[]\n const rawOrbitals = asDefinitions(rawInputs);\n\n // Step 1: Apply event wiring\n const wiredOrbitals =\n eventWiring && eventWiring.length > 0\n ? applyEventWiring(rawOrbitals, eventWiring)\n : rawOrbitals;\n\n // Step 2: Determine layout strategy\n const strategy: LayoutStrategy =\n !strategyInput || strategyInput === 'auto'\n ? detectLayoutStrategy(wiredOrbitals, eventWiring)\n : strategyInput;\n\n // Step 3: Generate pages\n const pages = generatePages(wiredOrbitals, strategy);\n\n // Step 4: Assign generated pages to orbitals (merge, don't replace existing)\n const orbitalsWithPages = wiredOrbitals.map((orbital, index) => {\n // If the orbital already has pages, keep them\n if (orbital.pages && orbital.pages.length > 0) {\n return orbital;\n }\n\n // Assign the generated page for this orbital\n const page = strategy === 'dashboard' || strategy === 'single'\n ? pages[0]\n : pages[index];\n\n return {\n ...orbital,\n pages: page ? [page] : [],\n };\n });\n\n // Step 5: Build the schema\n const schema: OrbitalSchema = {\n name: appName,\n version: '1.0.0',\n orbitals: orbitalsWithPages,\n };\n\n return {\n schema,\n layout: {\n strategy,\n pageCount: pages.length,\n },\n wiring: {\n connections: eventWiring?.length ?? 0,\n },\n };\n}\n","/**\n * Layout-Trait Builders\n *\n * Helpers for constructing the canonical inline LayoutTrait pattern that\n * std layout-shell molecules (`std-filtered-list`, `std-master-detail-layout`,\n * etc.) use to wrap a set of atom trait references in a `(render-ui main)`\n * effect with `@trait.X` slot embeds.\n *\n * The canonical LayoutTrait is stateless: ONE state (`composing`, initial),\n * ONE transition (`INIT` self-loop) carrying two effects — `(fetch Entity\n * {emit: {success, failure}})` and `(render-ui \"main\" <pattern-tree>)`. Atoms\n * embedded via `@trait.X` slot references react to the bus events the fetch\n * emits; the LayoutTrait owns no further state.\n *\n * Usage from a std layout-shell molecule:\n *\n * ```ts\n * import { makeSlot, makeLayoutTrait } from '@almadar/core/builders';\n *\n * const layout = makeLayoutTrait({\n * name: 'DashboardLayout',\n * linkedEntity: 'Metric',\n * fetchEntity: 'Metric',\n * loadedEvent: 'MetricLoaded',\n * loadFailedEvent: 'MetricLoadFailed',\n * renderUI: {\n * type: 'stack',\n * direction: 'vertical',\n * children: [\n * makeSlot('StatsRow'),\n * makeSlot('ChartsRow'),\n * makeSlot('FeedRow'),\n * ],\n * },\n * });\n * ```\n *\n * @packageDocumentation\n */\n\nimport type { AnyPatternConfig } from '@almadar/patterns';\nimport type { Trait } from '../types/trait.js';\nimport type { Effect, FetchEffect, RenderUIEffect, UISlot } from '../types/effect.js';\n\n/**\n * Build a `@trait.<name>` slot reference string. Used as a child entry in a\n * pattern tree to embed another trait's render-ui at that position. The\n * runtime resolves `@trait.X` to the matching trait's render-ui inline.\n *\n * @example makeSlot('FilteredItemSearch') // \"@trait.FilteredItemSearch\"\n */\nexport function makeSlot(traitName: string): string {\n return `@trait.${traitName}`;\n}\n\n/**\n * Build a `(render-ui <slot> <root>)` effect tuple. Pattern-typed sugar over\n * the raw `RenderUIEffect` literal so callers don't have to spell out the\n * three-element tuple form.\n *\n * @param slot - Canonical UI slot name (`'main'`, `'header'`, etc. — see UI_SLOTS).\n * @param root - The pattern config for this slot's content. Pass `null` to clear.\n */\nexport function makeRenderUI(slot: UISlot, root: AnyPatternConfig | null): RenderUIEffect {\n // Branch the return so TS can narrow into the correct tuple variant of\n // the RenderUIEffect union (the null arm is a separate tuple shape).\n return root === null ? ['render-ui', slot, null] : ['render-ui', slot, root];\n}\n\n/**\n * Options for {@link makeLayoutTrait}.\n */\nexport interface MakeLayoutTraitOpts {\n /** Trait name, e.g. `\"DashboardGridLayout\"`. */\n name: string;\n /** Entity this layout's emits/listens bind to. */\n linkedEntity: string;\n /** Optional human-readable description (carried through to `Trait.description`). */\n description?: string;\n /**\n * Entity name to fetch on INIT. When set, a `(fetch <Entity> {emit:\n * {success, failure}})` effect is prepended to the INIT transition. Omit\n * for purely-presentational layouts that don't load data themselves.\n */\n fetchEntity?: string;\n /**\n * Event name emitted on successful fetch. Required when `fetchEntity` is\n * set; the LayoutTrait declares this event in its `emits` and uses it as\n * the `success` emit-name in the fetch effect.\n * Convention: `\"<Entity>Loaded\"`.\n */\n loadedEvent?: string;\n /**\n * Event name emitted on fetch failure. Required when `fetchEntity` is\n * set. Convention: `\"<Entity>LoadFailed\"`.\n */\n loadFailedEvent?: string;\n /**\n * Payload schema for the loaded event. Defaults to `[{ name: \"data\", type:\n * \"[<Entity>]\" }]` when `fetchEntity` is set. Provide explicitly when the\n * payload should carry additional fields.\n */\n loadedPayloadSchema?: Array<{ name: string; type: string; required?: boolean }>;\n /**\n * The pattern tree for the layout's main slot. Children may include\n * `@trait.X` slot strings (built via {@link makeSlot}) interleaved with\n * inline pattern configs (`{ type: 'stack', ... }`). The shape conforms to\n * `AnyPatternConfig` from `@almadar/patterns`.\n */\n renderUI: AnyPatternConfig;\n /**\n * Override the slot the render-ui effect targets. Defaults to `'main'`.\n * Specify when the layout shell should render into a sub-slot (rare).\n */\n slot?: UISlot;\n /**\n * Additional effects appended to the INIT transition AFTER the fetch +\n * render-ui pair. Most layouts don't need this; provided for advanced\n * cases (analytics emit, persistence seed, etc.).\n */\n extraEffects?: Effect[];\n}\n\n/**\n * Build the canonical stateless LayoutTrait used by std layout-shell molecules.\n *\n * Result shape:\n * - `category: 'interaction'`, `scope: 'instance'`\n * - `linkedEntity` set per the option\n * - `emits` declares the loaded + loadFailed events when `fetchEntity` is set\n * - One state: `'composing'` (`isInitial: true`)\n * - One transition: `composing → composing` on `INIT`, with effects:\n * - (when `fetchEntity` set) `['fetch', '<Entity>', { emit: { success, failure } }]`\n * - `['render-ui', slot, renderUI]`\n * - …`extraEffects` if provided\n *\n * Atoms whose trait names appear as `@trait.<name>` strings inside `renderUI`\n * get embedded by the runtime when the orbital instantiates. The LayoutTrait\n * itself stays stateless — all reactive behaviour lives in the embedded atoms.\n */\nexport function makeLayoutTrait(opts: MakeLayoutTraitOpts): Trait {\n const slot: UISlot = opts.slot ?? 'main';\n const effects: Effect[] = [];\n\n // Build emits list based on fetch configuration.\n const emits: Trait['emits'] = [];\n const eventDefs: NonNullable<Trait['stateMachine']>['events'] = [\n { key: 'INIT', name: 'Initialize' },\n ];\n\n if (opts.fetchEntity) {\n if (!opts.loadedEvent || !opts.loadFailedEvent) {\n throw new Error(\n `makeLayoutTrait: fetchEntity '${opts.fetchEntity}' set but loadedEvent / loadFailedEvent are required`,\n );\n }\n const payloadSchema =\n opts.loadedPayloadSchema ?? [{ name: 'data', type: `[${opts.fetchEntity}]` }];\n emits.push(\n { event: opts.loadedEvent, scope: 'internal', payloadSchema },\n {\n event: opts.loadFailedEvent,\n scope: 'internal',\n payloadSchema: [\n { name: 'error', type: 'string' },\n { name: 'code', type: 'string' },\n ],\n },\n );\n eventDefs.push(\n { key: opts.loadedEvent, name: `${opts.fetchEntity} loaded`, payloadSchema },\n {\n key: opts.loadFailedEvent,\n name: `${opts.fetchEntity} load failed`,\n payloadSchema: [\n { name: 'error', type: 'string' },\n { name: 'code', type: 'string' },\n ],\n },\n );\n // (fetch <Entity> { emit: { success, failure } })\n const fetchFx: FetchEffect = [\n 'fetch',\n opts.fetchEntity,\n { emit: { success: opts.loadedEvent, failure: opts.loadFailedEvent } },\n ];\n effects.push(fetchFx);\n }\n\n effects.push(makeRenderUI(slot, opts.renderUI));\n if (opts.extraEffects && opts.extraEffects.length > 0) {\n effects.push(...opts.extraEffects);\n }\n\n const trait: Trait = {\n name: opts.name,\n ...(opts.description ? { description: opts.description } : {}),\n category: 'interaction',\n linkedEntity: opts.linkedEntity,\n scope: 'instance',\n ...(emits.length > 0 ? { emits } : {}),\n stateMachine: {\n states: [{ name: 'composing', isInitial: true }],\n events: eventDefs,\n transitions: [\n {\n from: 'composing',\n to: 'composing',\n event: 'INIT',\n effects,\n },\n ],\n },\n };\n\n return trait;\n}\n","/**\n * Orbital Builders\n *\n * Pure functions for constructing and composing Orbitals.\n * No new types. Everything uses existing core types:\n * Entity, Trait, Page, OrbitalDefinition, OrbitalSchema.\n *\n * Three categories:\n * 1. Builders: construct Entity, Page from common params\n * 2. Utilities: ensureIdField, resolveDefaults\n * 3. Composition: connect, compose, pipe\n *\n * @packageDocumentation\n */\n\nimport type { Entity, EntityPersistence, EntityRow } from './types/entity.js';\nimport type { EntityField } from './types/field.js';\nimport type { Page } from './types/page.js';\nimport type { EntityRef, OrbitalDefinition, PageRef, PageRefObject, UseDeclaration } from './types/orbital.js';\nimport { isEntityCall, isEntityReference, parseEntityRef } from './types/orbital.js';\nimport type { OrbitalSchema } from './types/schema.js';\nimport type { TraitEventContract, TraitEventListener, Trait, TraitRef, TraitReference, TraitConfig } from './types/trait.js';\nimport type { SExpr } from './types/expression.js';\n\n// Re-export compose-behaviors module\nexport { type LayoutStrategy, detectLayoutStrategy } from './builders/layout-strategy.js';\nexport { type EventWiringEntry, applyEventWiring } from './builders/event-wiring.js';\nexport {\n type ComposeBehaviorsInput,\n type ComposeBehaviorsResult,\n composeBehaviors,\n} from './builders/compose-behaviors.js';\n// LayoutTrait + slot-embedding helpers (Phase 7.6 — atom-composition recipe path).\nexport {\n type MakeLayoutTraitOpts,\n makeSlot,\n makeRenderUI,\n makeLayoutTrait,\n} from './builders/layout-trait.js';\n\n// ============================================================================\n// Utilities\n// ============================================================================\n\n/**\n * Ensure the fields array has an `id` field. Prepends one if missing.\n */\nexport function ensureIdField(fields?: EntityField[]): EntityField[] {\n if (!fields || fields.length === 0) return [{ name: 'id', type: 'string', required: true }];\n if (fields.some(f => f.name === 'id')) return fields;\n return [{ name: 'id', type: 'string', required: true }, ...fields];\n}\n\n/**\n * Simple pluralization: append 's'.\n */\nexport function plural(name: string): string {\n return name + 's';\n}\n\n/**\n * Resolve a printable entity name from any EntityRef shape.\n *\n * Handles:\n * - inline Entity object (uses `name`)\n * - bare string reference like \"Modal.entity\" (uses the alias)\n * - EntityCall { extends: \"Modal.entity\", name? } (uses `name` if set, else the alias)\n */\nfunction resolveEntityNameForBuilder(ref: EntityRef): string {\n if (isEntityReference(ref)) {\n return parseEntityRef(ref)?.alias ?? ref;\n }\n if (isEntityCall(ref)) {\n if (ref.name) return ref.name;\n return parseEntityRef(ref.extends)?.alias ?? ref.extends;\n }\n return ref.name;\n}\n\n// ============================================================================\n// Entity Builder\n// ============================================================================\n\nexport interface MakeEntityOpts {\n name: string;\n fields: EntityField[];\n persistence?: EntityPersistence;\n collection?: string;\n /** Pre-authored seed data instances */\n instances?: EntityRow[];\n}\n\n/**\n * Build an Entity from options. Auto-adds id field, auto-derives collection.\n */\nexport function makeEntity(opts: MakeEntityOpts): Entity {\n const fields = ensureIdField(opts.fields);\n const persistence = opts.persistence ?? 'runtime';\n return {\n name: opts.name,\n persistence,\n ...(persistence === 'persistent'\n ? { collection: opts.collection ?? plural(opts.name).toLowerCase() }\n : {}),\n fields,\n ...(opts.instances && opts.instances.length > 0 ? { instances: opts.instances } : {}),\n };\n}\n\n// ============================================================================\n// Page Builder\n// ============================================================================\n\nexport interface MakePageOpts {\n name: string;\n path: string;\n traitName: string;\n isInitial?: boolean;\n}\n\n/**\n * Build a Page that binds to a single trait.\n */\nexport function makePage(opts: MakePageOpts): Page {\n return {\n name: opts.name,\n path: opts.path,\n ...(opts.isInitial ? { isInitial: true } : {}),\n traits: [{ ref: opts.traitName }],\n };\n}\n\n// ============================================================================\n// Orbital Builder\n// ============================================================================\n\n/**\n * Build an OrbitalDefinition from its three components.\n */\nexport function makeOrbital(\n name: string,\n entity: Entity,\n traits: Trait[],\n pages: Page[],\n): OrbitalDefinition {\n return { name, entity, traits, pages } as OrbitalDefinition;\n}\n\n// ============================================================================\n// Reference-form Builders (Phase 4.2)\n// ============================================================================\n//\n// The atom/molecule/organism composition model (see CLAUDE.md \"Std Behaviors\")\n// treats every imported orbital as a callable unit: a reference site is a call\n// site whose sibling fields are call arguments. The compiler's inline pass\n// applies overrides from the reference to a cloned copy of the imported unit.\n//\n// These four helpers are convenience factories for constructing the reference\n// payloads (TraitReference, PageRefObject) and the orbital skeleton that\n// holds them. They exist to compress the otherwise ~200-line-per-behavior TS\n// rewrite down to ~30 lines. They purely pass-through fields: undefined\n// optionals are omitted (the emitted object never contains `key: undefined`),\n// so the result stays compatible with the inliner's \"present-means-override\"\n// semantics.\n\n/**\n * Options for {@link makeTraitRef}.\n */\nexport interface MakeTraitRefOpts {\n /**\n * Optional registry path disambiguator that pairs with {@link ref}\n * (see {@link TraitReference.from}).\n */\n from?: string;\n /** Trait reference string, e.g. \"Browse.traits.BrowseItemBrowse\". */\n ref: string;\n /** Rename the inlined trait at the call site. */\n name?: string;\n /** Rebind the trait to a different linkedEntity. */\n linkedEntity?: string;\n /** Per-key rename map, e.g. `{ OPEN: \"ADD_ITEM\" }`. */\n events?: Record<string, string>;\n /**\n * Per-event SExpression effect replacement. Keys are POST-rename event\n * names. See {@link TraitReference.effects} for the full contract.\n */\n effects?: Record<string, SExpr[]>;\n /** Replace the imported trait's `listens` array entirely. */\n listens?: TraitEventListener[];\n /** Set every emit's scope. */\n emitsScope?: 'internal' | 'external';\n /** Call-site config overrides. Matches {@link TraitReference.config}. */\n config?: TraitConfig;\n}\n\n/**\n * Typed-narrowing variant of {@link MakeTraitRefOpts} for callers that know\n * the imported atom's overridable surfaces — its event-key set, listen-key\n * set, and config shape. Generated std factories use this variant so an LLM\n * tool consumer (orbital-agent) sees the closed event-name set and the\n * config field schema instead of the un-narrowed `Record<string, string>` /\n * `TraitConfig` defaults.\n *\n * Type parameters:\n * - `EventKey` — string union of the atom's emit event names. Narrows the\n * `events` rename map's keys to legal originals only.\n * - `ConfigShape` — typed shape of the trait's `config { ... }` block (literal\n * unions intact). Narrows the `config` override to the atom's actual fields.\n * - `ListenKey` — string union of the atom's listen-key contract. Narrows\n * each listens entry's `event` against the atom's real subscription set.\n *\n * Runtime behavior is unchanged — {@link makeTraitRef} accepts both the\n * narrow and wide forms via the standard structural-typing rules. This is\n * a type-level narrowing only; widening at the call boundary is intentional.\n */\nexport interface MakeTraitRefOptsTyped<\n EventKey extends string = string,\n ConfigShape extends TraitConfig = Record<string, never>,\n ListenKey extends string = string,\n> extends Omit<\n MakeTraitRefOpts,\n 'events' | 'effects' | 'listens' | 'config'\n > {\n /** Per-key rename map, narrowed to the atom's actual event keys. */\n events?: Partial<Record<EventKey, string>>;\n /**\n * Per-event SExpression effect replacement. Keys are POST-rename event\n * names so they're caller-defined (no narrowing here); values stay typed\n * as `SExpr[]`.\n */\n effects?: Partial<Record<string, SExpr[]>>;\n /**\n * Replace the imported trait's `listens` array entirely. Each entry's\n * `event` field is narrowed to {@link ListenKey} where the atom's\n * subscription set is fixed; otherwise this widens to plain string.\n */\n listens?: Array<TraitEventListener & { event?: ListenKey }>;\n /** Typed call-site config overrides — narrowed to {@link ConfigShape}. */\n config?: ConfigShape;\n}\n\n/**\n * Build a {@link TraitReference} from options.\n *\n * Pass-through factory: copies only the fields that are actually provided,\n * so optionals stay absent (no `key: undefined` slots) and the emitted\n * object matches the inliner's expectation that \"present = override\".\n */\nexport function makeTraitRef(opts: MakeTraitRefOpts): TraitReference {\n const ref: TraitReference = { ref: opts.ref };\n if (opts.from !== undefined) ref.from = opts.from;\n if (opts.name !== undefined) ref.name = opts.name;\n if (opts.linkedEntity !== undefined) ref.linkedEntity = opts.linkedEntity;\n if (opts.events !== undefined) ref.events = opts.events;\n if (opts.effects !== undefined) ref.effects = opts.effects;\n if (opts.listens !== undefined) ref.listens = opts.listens;\n if (opts.emitsScope !== undefined) ref.emitsScope = opts.emitsScope;\n if (opts.config !== undefined) ref.config = opts.config;\n return ref;\n}\n\n/**\n * Options for {@link makePageRef}.\n */\nexport interface MakePageRefOpts {\n /**\n * Optional registry path disambiguator that pairs with {@link ref}\n * (see {@link PageRefObject.from}).\n */\n from?: string;\n /** Page reference string, e.g. \"Browse.pages.BrowseItemPage\". */\n ref: string;\n /** URL path override. */\n path?: string;\n /** Rebind the page's primary entity. */\n linkedEntity?: string;\n /** Replace the page's trait list. */\n traits?: TraitRef[];\n}\n\n/**\n * Typed-narrowing variant of {@link MakePageRefOpts}. Narrows the `traits`\n * override array's entries to the orbital's known trait-name union — so the\n * agent can't pass a trait name that doesn't exist on the page's owning\n * orbital. Generated std page-helpers use this variant to surface the\n * trait set in the tool schema; un-narrowed call sites stay compatible.\n *\n * Type parameter:\n * - `TraitName` — string union of trait names the page may reference.\n */\nexport interface MakePageRefOptsTyped<TraitName extends string = string>\n extends Omit<MakePageRefOpts, 'traits'> {\n traits?: Array<{ ref: TraitName } | TraitRef>;\n}\n\n/**\n * Build a {@link PageRefObject} from options. Pass-through factory — omits\n * optional keys that are `undefined`.\n */\nexport function makePageRef(opts: MakePageRefOpts): PageRefObject {\n const ref: PageRefObject = { ref: opts.ref };\n if (opts.from !== undefined) ref.from = opts.from;\n if (opts.path !== undefined) ref.path = opts.path;\n if (opts.linkedEntity !== undefined) ref.linkedEntity = opts.linkedEntity;\n if (opts.traits !== undefined) ref.traits = opts.traits;\n return ref;\n}\n\n/**\n * Options for {@link makeOrbitalWithUses}.\n */\nexport interface MakeOrbitalWithUsesOpts {\n /** Orbital name. */\n name: string;\n /**\n * Per-orbital `uses:` header entries (see CLAUDE.md \"uses: lives inside\n * the orbital\").\n */\n uses: UseDeclaration[];\n /** Entity (inline or reference form). */\n entity: EntityRef;\n /** Trait references. */\n traits: TraitRef[];\n /** Optional page references (omitted entirely when not provided). */\n pages?: PageRef[];\n}\n\n/**\n * Build an {@link OrbitalDefinition} with the `uses:` header set. Follows\n * the convention that `uses:` lives on the orbital (not the schema).\n *\n * When `pages` is omitted, the result has no `pages` property (matches the\n * existing {@link OrbitalDefinition.pages} optionality in descriptors that\n * carry trait-only atoms).\n */\nexport function makeOrbitalWithUses(opts: MakeOrbitalWithUsesOpts): OrbitalDefinition {\n const orbital: OrbitalDefinition = {\n name: opts.name,\n uses: opts.uses,\n entity: opts.entity,\n traits: opts.traits,\n pages: opts.pages ?? [],\n };\n return orbital;\n}\n\n/**\n * Options for {@link makeAtomOrbital}.\n *\n * Overrides for the single trait reference. Mirrors the {@link MakeTraitRefOpts}\n * subset that is meaningful at the atom-wrapping call site.\n */\nexport interface MakeAtomOrbitalTraitOverrides {\n name?: string;\n events?: Record<string, string>;\n effects?: Record<string, SExpr[]>;\n listens?: TraitEventListener[];\n emitsScope?: 'internal' | 'external';\n config?: TraitConfig;\n}\n\n/**\n * Options for {@link makeAtomOrbital}.\n */\nexport interface MakeAtomOrbitalOpts {\n /** Orbital name, e.g. `${entityName}Orbital`. */\n name: string;\n /** Atom registry path, e.g. `std/behaviors/atoms/std-browse`. */\n atomPath: string;\n /** Import alias (PascalCase), e.g. `Browse`. */\n alias: string;\n /** Entity definition to attach to the orbital. */\n entity: Entity;\n /** Trait reference string, e.g. `Browse.traits.BrowseItemBrowse`. */\n traitRef: string;\n /** Optional trait-level overrides applied at the call site. */\n traitOverrides?: MakeAtomOrbitalTraitOverrides;\n /** Optional page reference string, e.g. `Browse.pages.BrowseItemPage`. */\n pageRef?: string;\n /** Optional page-level overrides applied at the call site. */\n pageOverrides?: { path?: string };\n}\n\n/**\n * Build a single-atom {@link OrbitalDefinition}.\n *\n * The common atom shape: one entity + one trait reference + (optionally) one\n * page reference, all under a single `uses:` import. Wraps\n * {@link makeTraitRef}, {@link makePageRef}, and {@link makeOrbitalWithUses}.\n *\n * The trait reference is linkedEntity-bound to `entity.name` by default so\n * that the inliner's entity-substitution pass rewrites every `[\"ref\", X]`\n * and `@X.path` reference inside the atom.\n */\nexport function makeAtomOrbital(opts: MakeAtomOrbitalOpts): OrbitalDefinition {\n const traitRef = makeTraitRef({\n from: opts.atomPath,\n ref: opts.traitRef,\n linkedEntity: opts.entity.name,\n ...(opts.traitOverrides?.name !== undefined ? { name: opts.traitOverrides.name } : {}),\n ...(opts.traitOverrides?.events !== undefined ? { events: opts.traitOverrides.events } : {}),\n ...(opts.traitOverrides?.effects !== undefined ? { effects: opts.traitOverrides.effects } : {}),\n ...(opts.traitOverrides?.listens !== undefined ? { listens: opts.traitOverrides.listens } : {}),\n ...(opts.traitOverrides?.emitsScope !== undefined\n ? { emitsScope: opts.traitOverrides.emitsScope }\n : {}),\n ...(opts.traitOverrides?.config !== undefined ? { config: opts.traitOverrides.config } : {}),\n });\n\n const pages: PageRef[] | undefined = opts.pageRef\n ? [\n makePageRef({\n from: opts.atomPath,\n ref: opts.pageRef,\n linkedEntity: opts.entity.name,\n ...(opts.pageOverrides?.path !== undefined ? { path: opts.pageOverrides.path } : {}),\n }),\n ]\n : undefined;\n\n return makeOrbitalWithUses({\n name: opts.name,\n uses: [{ from: opts.atomPath, as: opts.alias }],\n entity: opts.entity,\n traits: [traitRef],\n ...(pages !== undefined ? { pages } : {}),\n });\n}\n\n/**\n * Wrap one or more OrbitalDefinitions into an OrbitalSchema.\n * Every .orb file should be a full OrbitalSchema — this is the builder for that.\n */\nexport function makeSchema(name: string, ...definitions: OrbitalDefinition[]): OrbitalSchema {\n return { name, version: '1.0.0', orbitals: definitions };\n}\n\n/**\n * Unwrap inputs that may be OrbitalSchema or OrbitalDefinition into a flat\n * array of OrbitalDefinitions. Used internally by compose/pipe/connect/extractTrait\n * so they accept both types.\n */\nfunction asDefinitions(inputs: (OrbitalDefinition | OrbitalSchema)[]): OrbitalDefinition[] {\n return inputs.flatMap(input => {\n if ('orbitals' in input && Array.isArray((input as OrbitalSchema).orbitals)) {\n return (input as OrbitalSchema).orbitals as OrbitalDefinition[];\n }\n return [input as OrbitalDefinition];\n });\n}\n\n/** Unwrap a single OrbitalSchema | OrbitalDefinition to OrbitalDefinition. */\nfunction asDefinition(input: OrbitalDefinition | OrbitalSchema): OrbitalDefinition {\n if ('orbitals' in input && Array.isArray((input as OrbitalSchema).orbitals)) {\n return (input as OrbitalSchema).orbitals[0] as OrbitalDefinition;\n }\n return input as OrbitalDefinition;\n}\n\n// ============================================================================\n// Intra-Orbital Composition\n// ============================================================================\n\n/**\n * Merge multiple OrbitalDefinitions into one.\n * Collects all traits from all sources into a single orbital with a shared entity.\n * Pure: clones all traits, no mutation.\n */\nexport function mergeOrbitals(\n name: string,\n entity: Entity,\n sources: OrbitalDefinition[],\n pages: Page[],\n): OrbitalDefinition {\n const allTraits = sources.flatMap(s =>\n (s.traits as Trait[]).map(t => structuredClone(t)),\n );\n return { name, entity, traits: allTraits, pages } as OrbitalDefinition;\n}\n\n/**\n * Wire an intra-orbital event between two traits.\n * Adds emits to the source trait, listens to the target trait.\n * Pure: returns cloned traits, no mutation.\n */\nexport function wire(\n source: Trait,\n target: Trait,\n event: TraitEventContract,\n triggers: string,\n): [Trait, Trait] {\n const s = structuredClone(source);\n const t = structuredClone(target);\n\n s.emits = [...(s.emits ?? []), { ...event, scope: event.scope ?? ('internal' as const) }];\n t.listens = [...(t.listens ?? []), {\n event: event.event,\n triggers,\n scope: 'internal' as const,\n }];\n\n return [s, t];\n}\n\n/**\n * Extract the first trait from an OrbitalDefinition or OrbitalSchema.\n * If given an OrbitalSchema, unwraps to the first orbital inside it.\n */\nexport function extractTrait(input: OrbitalDefinition | OrbitalSchema): Trait {\n const orbital = asDefinition(input);\n return structuredClone((orbital.traits as Trait[])[0]);\n}\n\n// ============================================================================\n// Composition: connect\n// ============================================================================\n\n/**\n * Wire a cross-orbital event between two orbitals.\n * Adds emits to a's first trait, listens to b's first trait.\n * Pure: returns new orbitals, no mutation.\n */\nexport function connect(\n a: OrbitalDefinition | OrbitalSchema,\n b: OrbitalDefinition | OrbitalSchema,\n event: TraitEventContract,\n triggers?: string,\n): [OrbitalDefinition, OrbitalDefinition] {\n const aClone = structuredClone(asDefinition(a));\n const bClone = structuredClone(asDefinition(b));\n\n // Add emit to first trait of a\n const aTrait = (aClone.traits as Trait[])[0];\n if (aTrait) {\n const emitContract: TraitEventContract = {\n ...event,\n scope: event.scope ?? 'external',\n };\n aTrait.emits = [...(aTrait.emits ?? []), emitContract];\n }\n\n // Add listen to first trait of b\n const bTrait = (bClone.traits as Trait[])[0];\n if (bTrait) {\n const listener: TraitEventListener = {\n event: event.event,\n triggers: triggers ?? 'INIT',\n scope: 'external',\n };\n bTrait.listens = [...(bTrait.listens ?? []), listener];\n }\n\n return [aClone, bClone];\n}\n\n// ============================================================================\n// Composition: compose\n// ============================================================================\n\nexport interface ComposeConnection {\n from: string;\n to: string;\n event: TraitEventContract;\n triggers?: string;\n}\n\nexport interface ComposePage {\n name: string;\n path: string;\n traits: string[];\n isInitial?: boolean;\n}\n\n/**\n * Compose multiple orbitals into a single OrbitalSchema (application).\n * Applies connections (cross-orbital event wiring) and page assignments.\n */\nexport function compose(\n orbitals: (OrbitalDefinition | OrbitalSchema)[],\n pages: ComposePage[],\n connections: ComposeConnection[],\n appName?: string,\n): OrbitalSchema {\n const cloned = structuredClone(asDefinitions(orbitals));\n\n // Apply connections\n for (const conn of connections) {\n const emitter = cloned.find(o => {\n const traits = o.traits as Trait[];\n return traits.some(t => t.name === conn.from);\n });\n const listener = cloned.find(o => {\n const traits = o.traits as Trait[];\n return traits.some(t => t.name === conn.to);\n });\n\n if (emitter && listener) {\n const eTrait = (emitter.traits as Trait[]).find(t => t.name === conn.from);\n const lTrait = (listener.traits as Trait[]).find(t => t.name === conn.to);\n\n if (eTrait) {\n const emitContract: TraitEventContract = { ...conn.event, scope: conn.event.scope ?? 'external' };\n eTrait.emits = [...(eTrait.emits ?? []), emitContract];\n }\n if (lTrait) {\n const listenContract: TraitEventListener = {\n event: conn.event.event,\n triggers: conn.triggers ?? 'INIT',\n scope: 'external',\n };\n lTrait.listens = [...(lTrait.listens ?? []), listenContract];\n }\n }\n }\n\n // Assign pages to orbitals\n for (const orbital of cloned) {\n const traitNames = (orbital.traits as Trait[]).map(t => t.name);\n const matchingPages = pages.filter(p =>\n p.traits.some(t => traitNames.includes(t)),\n );\n orbital.pages = matchingPages.map(p => ({\n name: p.name,\n path: p.path,\n ...(p.isInitial ? { isInitial: true } : {}),\n traits: p.traits\n .filter(t => traitNames.includes(t))\n .map(ref => ({ ref })),\n }));\n }\n\n return {\n name: appName ?? 'Application',\n version: '1.0.0',\n orbitals: cloned,\n };\n}\n\n// ============================================================================\n// Composition: pipe\n// ============================================================================\n\n/**\n * Chain orbitals in sequence with automatic event wiring.\n * Sugar over connect + compose: wires events[0] from orbital[0] to orbital[1], etc.\n */\nexport function pipe(\n orbitals: (OrbitalDefinition | OrbitalSchema)[],\n events: TraitEventContract[],\n appName?: string,\n): OrbitalSchema {\n if (events.length !== orbitals.length - 1) {\n throw new Error(`pipe requires exactly ${orbitals.length - 1} events for ${orbitals.length} orbitals`);\n }\n\n const cloned = structuredClone(asDefinitions(orbitals));\n\n // Wire adjacent pairs\n for (let i = 0; i < events.length; i++) {\n const aTrait = (cloned[i].traits as Trait[])[0];\n const bTrait = (cloned[i + 1].traits as Trait[])[0];\n\n if (aTrait) {\n const emitContract: TraitEventContract = { ...events[i], scope: events[i].scope ?? 'external' };\n aTrait.emits = [...(aTrait.emits ?? []), emitContract];\n }\n if (bTrait) {\n const listener: TraitEventListener = {\n event: events[i].event,\n triggers: 'INIT',\n scope: 'external',\n };\n bTrait.listens = [...(bTrait.listens ?? []), listener];\n }\n }\n\n // Auto-generate pages: one per orbital, first is initial\n const pages: Page[] = cloned.map((o, i) => {\n const entityName = resolveEntityNameForBuilder(o.entity);\n const traitNames = (o.traits as Trait[]).map(t => t.name);\n return {\n name: `${entityName}Page`,\n path: `/${plural(entityName).toLowerCase()}`,\n ...(i === 0 ? { isInitial: true } : {}),\n traits: traitNames.map(ref => ({ ref })),\n };\n });\n\n // Assign pages back to orbitals\n for (let i = 0; i < cloned.length; i++) {\n cloned[i].pages = [pages[i]];\n }\n\n return {\n name: appName ?? 'Application',\n version: '1.0.0',\n orbitals: cloned,\n };\n}\n"]}
|