@lokascript/framework 2.3.1 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/api/index.js +29 -516
  2. package/dist/api/index.js.map +1 -1
  3. package/dist/core/index.js +20 -128
  4. package/dist/core/index.js.map +1 -1
  5. package/dist/core/pattern-matching/index.js +19 -12
  6. package/dist/core/pattern-matching/index.js.map +1 -1
  7. package/dist/core/tokenization/index.js.map +1 -1
  8. package/dist/core/types.d.ts +7 -354
  9. package/dist/core/types.d.ts.map +1 -1
  10. package/dist/core/types.js +21 -129
  11. package/dist/core/types.js.map +1 -1
  12. package/dist/generation/diagnostics.d.ts +5 -115
  13. package/dist/generation/diagnostics.d.ts.map +1 -1
  14. package/dist/generation/index.js +20 -77
  15. package/dist/generation/index.js.map +1 -1
  16. package/dist/index.cjs +189 -1458
  17. package/dist/index.cjs.map +1 -1
  18. package/dist/index.js +108 -1347
  19. package/dist/index.js.map +1 -1
  20. package/dist/interfaces/value-extractor.d.ts +20 -0
  21. package/dist/interfaces/value-extractor.d.ts.map +1 -1
  22. package/dist/ir/explicit-parser.d.ts +2 -83
  23. package/dist/ir/explicit-parser.d.ts.map +1 -1
  24. package/dist/ir/explicit-renderer.d.ts +2 -31
  25. package/dist/ir/explicit-renderer.d.ts.map +1 -1
  26. package/dist/ir/index.js +89 -1260
  27. package/dist/ir/index.js.map +1 -1
  28. package/dist/ir/protocol-json.d.ts +2 -70
  29. package/dist/ir/protocol-json.d.ts.map +1 -1
  30. package/dist/ir/references.d.ts +2 -16
  31. package/dist/ir/references.d.ts.map +1 -1
  32. package/dist/ir/types.d.ts +2 -148
  33. package/dist/ir/types.d.ts.map +1 -1
  34. package/dist/parsing/index.js +19 -12
  35. package/dist/parsing/index.js.map +1 -1
  36. package/dist/schema/command-schema.d.ts +3 -92
  37. package/dist/schema/command-schema.d.ts.map +1 -1
  38. package/dist/schema/index.js +3 -20
  39. package/dist/schema/index.js.map +1 -1
  40. package/dist/testing/index.js +1066 -712
  41. package/dist/testing/index.js.map +1 -1
  42. package/package.json +6 -2
  43. package/src/core/types.ts +71 -600
  44. package/src/generation/diagnostics.ts +12 -233
  45. package/src/interfaces/value-extractor.ts +32 -0
  46. package/src/ir/explicit-parser.ts +12 -792
  47. package/src/ir/explicit-renderer.ts +2 -195
  48. package/src/ir/from-interchange.test.ts +91 -4
  49. package/src/ir/from-interchange.ts +59 -0
  50. package/src/ir/protocol-json.test.ts +16 -7
  51. package/src/ir/protocol-json.ts +9 -748
  52. package/src/ir/references.ts +2 -30
  53. package/src/ir/types.ts +18 -190
  54. package/src/schema/command-schema.ts +3 -134
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/core/types.ts","../../src/core/logger.ts","../../src/core/pattern-matching/utils/type-validation.ts","../../src/core/pattern-matching/utils/possessive-keywords.ts","../../src/core/pattern-matching/pattern-matcher.ts","../../src/generation/pattern-generator.ts","../../src/grammar/types.ts","../../src/grammar/transformer.ts","../../src/interfaces/dictionary.ts","../../src/interfaces/profile-provider.ts","../../src/ir/references.ts","../../src/ir/explicit-parser.ts","../../src/ir/explicit-renderer.ts","../../src/api/create-dsl.ts","../../src/prompts/prompt-generator.ts","../../src/training/schema-synthesizer.ts","../../src/feedback/feedback-formatter.ts","../../src/api/domain-registry.ts","../../src/api/dispatcher.ts"],"sourcesContent":["/**\n * Generic Semantic Types for Multilingual DSLs\n *\n * This module defines the canonical semantic representation that all languages\n * parse to and render from. The semantic layer is language-neutral - it captures\n * the MEANING of DSL commands independent of surface syntax.\n *\n * These types are domain-agnostic - they work for any DSL (SQL, animations, etc.)\n */\n\nimport type { Diagnostic } from '../generation/diagnostics';\n\n// =============================================================================\n// Action Types (Generic)\n// =============================================================================\n\n/**\n * Action type represents the command/operation in a DSL.\n * This is generic - each DSL defines its own set of actions.\n *\n * Examples:\n * - Hyperscript: 'toggle', 'add', 'remove', 'fetch'\n * - SQL: 'select', 'insert', 'update', 'delete'\n * - Animation: 'animate', 'fade', 'slide', 'rotate'\n */\nexport type ActionType = string;\n\n/**\n * Semantic role represents the grammatical function of a part of a command.\n * This is generic - each DSL can define its own roles, though common ones include:\n *\n * Common roles across DSLs:\n * - action: The verb/command\n * - patient: What is being acted upon\n * - destination: Where something goes\n * - source: Where something comes from\n * - condition: Boolean expressions\n * - quantity: Numeric amounts\n * - duration: Time spans\n *\n * Examples:\n * - Hyperscript: 'patient', 'destination', 'source', 'event', 'style'\n * - SQL: 'columns', 'table', 'condition', 'orderBy', 'limit'\n * - Animation: 'target', 'duration', 'easing', 'delay'\n */\nexport type SemanticRole = string;\n\n// =============================================================================\n// Semantic Values\n// =============================================================================\n\n/**\n * A semantic value represents a typed piece of data in a semantic node.\n * Values are language-neutral - they capture what something IS, not how it's written.\n */\nexport type SemanticValue =\n | LiteralValue\n | SelectorValue\n | ReferenceValue\n | PropertyPathValue\n | ExpressionValue\n | FlagValue;\n\n/**\n * Expected value types for role tokens.\n * Shared between RoleSpec (command-schemas) and RolePatternToken.\n */\nexport type ExpectedType = SemanticValue['type'];\n\nexport interface LiteralValue {\n readonly type: 'literal';\n readonly value: string | number | boolean;\n readonly dataType?: 'string' | 'number' | 'boolean' | 'duration';\n}\n\nexport interface SelectorValue {\n readonly type: 'selector';\n readonly value: string; // The selector: #id, .class, [attr], table-name, etc.\n readonly selectorKind?: 'id' | 'class' | 'attribute' | 'element' | 'complex' | 'identifier';\n}\n\nexport interface ReferenceValue {\n readonly type: 'reference';\n readonly value: string; // Generic reference name (DSL-specific)\n}\n\nexport interface PropertyPathValue {\n readonly type: 'property-path';\n readonly object: SemanticValue;\n readonly property: string;\n}\n\nexport interface ExpressionValue {\n readonly type: 'expression';\n /** Raw expression string for complex expressions that need further parsing */\n readonly raw: string;\n}\n\n/**\n * A boolean flag value — present (+flag) or negated (~flag).\n * Used in declarative domains for no-value attributes like primary-key, not-null.\n */\nexport interface FlagValue {\n readonly type: 'flag';\n readonly name: string;\n readonly enabled: boolean;\n}\n\n// =============================================================================\n// Annotations & Diagnostics (v1.2)\n// =============================================================================\n\n/** A metadata annotation on a node (v1.2). */\nexport interface Annotation {\n readonly name: string;\n readonly value?: string;\n}\n\n/**\n * A type constraint diagnostic attached to a node (v1.2).\n *\n * Named `ProtocolDiagnostic` to avoid collision with the framework's own\n * `Diagnostic` type (which has `severity: 'error' | 'warning' | 'info'`\n * and `suggestion?: string`).\n */\nexport interface ProtocolDiagnostic {\n readonly level: 'error' | 'warning';\n readonly role: string;\n readonly message: string;\n readonly code: string;\n}\n\n/** Async coordination variant (v1.2). */\nexport type AsyncVariant = 'all' | 'race';\n\n/** A single arm in a match command (v1.2). */\nexport interface MatchArm {\n readonly pattern: SemanticValue;\n readonly body: SemanticNode[];\n}\n\n// =============================================================================\n// Semantic Nodes\n// =============================================================================\n\n/**\n * Base interface for all semantic nodes.\n * Semantic nodes capture the MEANING of DSL constructs.\n */\nexport interface SemanticNode {\n readonly kind: 'command' | 'event-handler' | 'conditional' | 'compound' | 'loop';\n readonly action: ActionType;\n readonly roles: ReadonlyMap<SemanticRole, SemanticValue>;\n readonly metadata?: SemanticMetadata;\n /** Metadata annotations (v1.2). */\n readonly annotations?: readonly Annotation[];\n /** Diagnostics from parsing, validation, and schema checks (v1.2, extended v1.2.1). */\n readonly diagnostics?: readonly Diagnostic[];\n}\n\n/**\n * Metadata about the source of a semantic node.\n * Useful for debugging, error messages, and round-trip conversion.\n */\nexport interface SemanticMetadata {\n readonly sourceLanguage?: string;\n readonly sourceText?: string;\n readonly sourcePosition?: SourcePosition;\n readonly patternId?: string;\n /**\n * Confidence score for the parse (0-1).\n * Higher values indicate more certain matches.\n * - 1.0: Exact match with all roles captured\n * - 0.8-0.99: High confidence with minor uncertainty\n * - 0.6-0.8: Medium confidence (normalization, defaults applied)\n * - <0.6: Low confidence (may need fallback)\n */\n readonly confidence?: number;\n}\n\nexport interface SourcePosition {\n readonly start: number;\n readonly end: number;\n readonly line?: number;\n readonly column?: number;\n}\n\n/**\n * A command semantic node - represents a single DSL command.\n *\n * v1.2 adds optional fields for try/catch/finally, async coordination (all/race),\n * and pattern matching (match/arms). These are encoded as fields on command nodes\n * (matching the protocol wire format) rather than new node kinds.\n */\nexport interface CommandSemanticNode extends SemanticNode {\n readonly kind: 'command';\n /** try body — commands to execute in the try block (v1.2). */\n readonly body?: readonly SemanticNode[];\n /** catch branch — commands to execute on error (v1.2). */\n readonly catchBranch?: readonly SemanticNode[];\n /** finally branch — cleanup commands that always execute (v1.2). */\n readonly finallyBranch?: readonly SemanticNode[];\n /** Async coordination variant: all (wait for all) or race (first wins) (v1.2). */\n readonly asyncVariant?: AsyncVariant;\n /** Async body — concurrent commands for all/race (v1.2). */\n readonly asyncBody?: readonly SemanticNode[];\n /** Match arms — pattern/body pairs for match command (v1.2). */\n readonly arms?: readonly MatchArm[];\n /** Default arm — executed when no match arm matches (v1.2). */\n readonly defaultArm?: readonly SemanticNode[];\n}\n\n/**\n * An event handler semantic node - represents trigger-based commands.\n * E.g., \"on click [commands]\" in hyperscript, or \"when condition [commands]\" in other DSLs.\n */\nexport interface EventHandlerSemanticNode extends SemanticNode {\n readonly kind: 'event-handler';\n readonly body: SemanticNode[];\n readonly eventModifiers?: EventModifiers;\n readonly additionalEvents?: readonly SemanticValue[];\n readonly parameterNames?: readonly string[];\n}\n\nexport interface EventModifiers {\n readonly once?: boolean;\n readonly debounce?: number;\n readonly throttle?: number;\n readonly queue?: 'first' | 'last' | 'all' | 'none';\n readonly from?: SemanticValue;\n}\n\n/**\n * A conditional semantic node - represents \"if [condition] then [body] else [body]\".\n */\nexport interface ConditionalSemanticNode extends SemanticNode {\n readonly kind: 'conditional';\n readonly thenBranch: SemanticNode[];\n readonly elseBranch?: SemanticNode[];\n}\n\n/**\n * A compound semantic node - represents multiple chained statements.\n */\nexport interface CompoundSemanticNode extends SemanticNode {\n readonly kind: 'compound';\n readonly statements: SemanticNode[];\n readonly chainType: 'then' | 'and' | 'async' | 'sequential' | 'pipe';\n}\n\n/**\n * Loop variant discriminant for different loop types.\n */\nexport type LoopVariant = 'forever' | 'times' | 'for' | 'while' | 'until';\n\n/**\n * A loop semantic node - represents repeat/for/while loops.\n */\nexport interface LoopSemanticNode extends SemanticNode {\n readonly kind: 'loop';\n readonly loopVariant: LoopVariant;\n readonly body: SemanticNode[];\n readonly loopVariable?: string;\n readonly indexVariable?: string;\n}\n\n// =============================================================================\n// Tokenization Types\n// =============================================================================\n\n/**\n * Token kind - categorizes what type of token this is.\n */\nexport type TokenKind =\n | 'keyword' // Command or modifier keyword\n | 'selector' // CSS selector or identifier (#id, .class, table-name)\n | 'literal' // String or number literal\n | 'particle' // Grammatical particle (を, に, من)\n | 'conjunction' // Grammatical conjunction\n | 'event-modifier' // Event modifier (.once, .debounce(300))\n | 'identifier' // Generic identifier\n | 'operator' // Operators (., +, -, etc.)\n | 'punctuation' // Punctuation (parentheses, etc.)\n | 'url'; // URL or path\n\n/**\n * A language token - the result of tokenization.\n */\nexport interface LanguageToken {\n readonly value: string;\n readonly kind: TokenKind;\n readonly position: SourcePosition;\n /** Normalized form from explicit keyword map */\n readonly normalized?: string;\n /** Morphologically normalized stem */\n readonly stem?: string;\n /** Confidence in the morphological stem (0.0-1.0) */\n readonly stemConfidence?: number;\n /** Additional metadata for specific token types */\n readonly metadata?: Record<string, unknown>;\n}\n\n/**\n * Token stream - provides sequential access to tokens with backtracking.\n */\nexport interface TokenStream {\n readonly tokens: readonly LanguageToken[];\n readonly language: string;\n\n /** Look at token at current position + offset without consuming */\n peek(offset?: number): LanguageToken | null;\n\n /** Consume and return current token, advance position */\n advance(): LanguageToken;\n\n /** Check if we've consumed all tokens */\n isAtEnd(): boolean;\n\n /** Save current position for backtracking */\n mark(): StreamMark;\n\n /** Restore to a saved position */\n reset(mark: StreamMark): void;\n\n /** Get current position */\n position(): number;\n}\n\n/**\n * Stream mark for backtracking during parsing.\n */\nexport interface StreamMark {\n readonly position: number;\n}\n\n/**\n * Language tokenizer interface - converts text to tokens.\n */\nexport interface LanguageTokenizer {\n readonly language: string;\n readonly direction: 'ltr' | 'rtl';\n\n /** Convert input string to token stream */\n tokenize(input: string): TokenStream;\n\n /** Classify a single token */\n classifyToken(token: string): TokenKind;\n}\n\n// =============================================================================\n// Pattern Matching Types\n// =============================================================================\n\n/**\n * A language pattern defines how a semantic structure appears in a specific language.\n */\nexport interface LanguagePattern {\n /** Unique identifier for this pattern */\n readonly id: string;\n /** ISO 639-1 language code */\n readonly language: string;\n /** Which command this pattern matches */\n readonly command: ActionType;\n /** Priority for disambiguation (higher = checked first) */\n readonly priority: number;\n /** The pattern template with role placeholders */\n readonly template: PatternTemplate;\n /** Rules for extracting semantic roles from matched tokens */\n readonly extraction: ExtractionRules;\n /** Optional constraints on when this pattern applies */\n readonly constraints?: PatternConstraints;\n}\n\n/**\n * Pattern template - defines expected token sequence.\n */\nexport interface PatternTemplate {\n /** Human-readable template string */\n readonly format: string;\n /** Parsed token sequence for matching */\n readonly tokens: PatternToken[];\n}\n\n/**\n * Pattern token - literal, role placeholder, or group.\n */\nexport type PatternToken = LiteralPatternToken | RolePatternToken | GroupPatternToken;\n\nexport interface LiteralPatternToken {\n readonly type: 'literal';\n readonly value: string;\n /** Alternative spellings/forms that also match */\n readonly alternatives?: string[];\n}\n\nexport interface RolePatternToken {\n readonly type: 'role';\n readonly role: SemanticRole;\n readonly optional?: boolean;\n /** Expected value types (for validation) */\n readonly expectedTypes?: Array<ExpectedType>;\n /** When true, captures all remaining tokens until next marker or end */\n readonly greedy?: boolean;\n}\n\nexport interface GroupPatternToken {\n readonly type: 'group';\n readonly tokens: PatternToken[];\n readonly optional?: boolean;\n}\n\n/**\n * Rules for extracting semantic values from matched tokens.\n */\nexport interface ExtractionRules {\n readonly [role: string]: ExtractionRule;\n}\n\nexport interface ExtractionRule {\n /** Position-based extraction (0-indexed from pattern start) */\n readonly position?: number;\n /** Marker-based extraction (find value after this marker) */\n readonly marker?: string;\n /** Alternative markers that also work */\n readonly markerAlternatives?: string[];\n /** Transform the extracted value */\n readonly transform?: (raw: string) => SemanticValue;\n /** Default value if not found (for optional roles) */\n readonly default?: SemanticValue;\n /** Static value extraction */\n readonly value?: string;\n /** Extract value from a pattern role by name */\n readonly fromRole?: string;\n}\n\n/**\n * Additional constraints on pattern applicability.\n */\nexport interface PatternConstraints {\n /** Required roles that must be present */\n readonly requiredRoles?: SemanticRole[];\n /** Roles that must NOT be present */\n readonly forbiddenRoles?: SemanticRole[];\n /** Valid selector types for the patient role */\n readonly validPatientTypes?: Array<SelectorValue['selectorKind']>;\n /** Pattern IDs this conflicts with */\n readonly conflictsWith?: string[];\n}\n\n/**\n * Result of matching a pattern against tokens.\n */\nexport interface PatternMatchResult {\n readonly pattern: LanguagePattern;\n readonly captured: ReadonlyMap<SemanticRole, SemanticValue>;\n readonly consumedTokens: number;\n readonly confidence: number; // 0-1, how well the pattern matched\n}\n\n/**\n * Error when pattern matching fails.\n */\nexport interface PatternMatchError {\n readonly message: string;\n readonly position: SourcePosition;\n readonly expectedPatterns?: string[];\n readonly partialMatch?: Partial<PatternMatchResult>;\n}\n\n// =============================================================================\n// Helper Functions\n// =============================================================================\n\n/**\n * Create a literal value\n */\nexport function createLiteral(\n value: string | number | boolean,\n dataType?: 'string' | 'number' | 'boolean' | 'duration'\n): LiteralValue {\n return dataType ? { type: 'literal', value, dataType } : { type: 'literal', value };\n}\n\n/**\n * Create a selector value\n */\nexport function createSelector(\n value: string,\n selectorKind?: SelectorValue['selectorKind']\n): SelectorValue {\n return selectorKind ? { type: 'selector', value, selectorKind } : { type: 'selector', value };\n}\n\n/**\n * Create a reference value\n */\nexport function createReference(value: string): ReferenceValue {\n return { type: 'reference', value };\n}\n\n/**\n * Create a property path value\n */\nexport function createPropertyPath(object: SemanticValue, property: string): PropertyPathValue {\n return { type: 'property-path', object, property };\n}\n\n/**\n * Create an expression value\n */\nexport function createExpression(raw: string): ExpressionValue {\n return { type: 'expression', raw };\n}\n\n/**\n * Create a boolean flag value (+flag or ~flag)\n */\nexport function createFlag(name: string, enabled: boolean = true): FlagValue {\n return { type: 'flag', name, enabled };\n}\n\n/**\n * Create a command semantic node\n */\nexport function createCommandNode(\n action: ActionType,\n roles: Record<SemanticRole, SemanticValue> | Map<SemanticRole, SemanticValue>,\n metadata?: SemanticMetadata\n): CommandSemanticNode {\n const rolesMap = roles instanceof Map ? roles : new Map(Object.entries(roles));\n const node: CommandSemanticNode = {\n kind: 'command',\n action,\n roles: rolesMap,\n };\n if (metadata) {\n return { ...node, metadata };\n }\n return node;\n}\n\n/**\n * Create an event handler semantic node\n */\nexport function createEventHandlerNode(\n action: ActionType,\n roles: Record<SemanticRole, SemanticValue> | Map<SemanticRole, SemanticValue>,\n body: SemanticNode[],\n metadata?: SemanticMetadata,\n eventModifiers?: EventModifiers\n): EventHandlerSemanticNode {\n const rolesMap = roles instanceof Map ? roles : new Map(Object.entries(roles));\n const base = {\n kind: 'event-handler' as const,\n action,\n roles: rolesMap,\n body,\n };\n return {\n ...base,\n ...(eventModifiers && { eventModifiers }),\n ...(metadata && { metadata }),\n };\n}\n\n/**\n * Create a conditional semantic node\n */\nexport function createConditionalNode(\n action: ActionType,\n roles: Record<SemanticRole, SemanticValue> | Map<SemanticRole, SemanticValue>,\n thenBranch: SemanticNode[],\n elseBranch?: SemanticNode[],\n metadata?: SemanticMetadata\n): ConditionalSemanticNode {\n const rolesMap = roles instanceof Map ? roles : new Map(Object.entries(roles));\n const base = {\n kind: 'conditional' as const,\n action,\n roles: rolesMap,\n thenBranch,\n };\n return {\n ...base,\n ...(elseBranch && { elseBranch }),\n ...(metadata && { metadata }),\n };\n}\n\n/**\n * Create a compound semantic node\n */\nexport function createCompoundNode(\n statements: SemanticNode[],\n chainType: CompoundSemanticNode['chainType'] = 'sequential',\n metadata?: SemanticMetadata\n): CompoundSemanticNode {\n const base = {\n kind: 'compound' as const,\n action: 'compound' as const,\n roles: new Map(),\n statements,\n chainType,\n };\n return metadata ? { ...base, metadata } : base;\n}\n\n/**\n * Extract a string value from a SemanticValue.\n *\n * Handles all value types in the SemanticValue union:\n * - ExpressionValue: returns `raw`\n * - LiteralValue/SelectorValue/ReferenceValue: returns `value` as string\n * - PropertyPathValue: returns `object.property` path\n *\n * This is the standard way to get a display string from any semantic value,\n * eliminating the need for `as any` casts in domain code generators.\n */\nexport function extractValue(value: SemanticValue): string {\n if (value.type === 'flag') return value.name;\n if ('raw' in value && value.raw !== undefined) return String(value.raw);\n if ('value' in value && value.value !== undefined) return String(value.value);\n if (value.type === 'property-path') return `${extractValue(value.object)}.${value.property}`;\n return '';\n}\n\n/**\n * Extract a string value from a named role on a SemanticNode.\n *\n * Convenience wrapper: looks up the role, returns empty string if missing.\n * Eliminates the common `const x = node.roles.get('role'); const val = x ? extractValue(x as any) : '';` pattern.\n */\nexport function extractRoleValue(node: SemanticNode, role: string): string {\n const value = node.roles.get(role);\n if (!value) return '';\n return extractValue(value);\n}\n\n/**\n * Create a loop semantic node\n */\nexport function createLoopNode(\n action: ActionType,\n roles: Record<SemanticRole, SemanticValue> | Map<SemanticRole, SemanticValue>,\n loopVariant: LoopVariant,\n body: SemanticNode[],\n loopVariable?: string,\n indexVariable?: string,\n metadata?: SemanticMetadata\n): LoopSemanticNode {\n const rolesMap = roles instanceof Map ? roles : new Map(Object.entries(roles));\n const base = {\n kind: 'loop' as const,\n action,\n roles: rolesMap,\n loopVariant,\n body,\n };\n return {\n ...base,\n ...(loopVariable && { loopVariable }),\n ...(indexVariable && { indexVariable }),\n ...(metadata && { metadata }),\n };\n}\n\n// =============================================================================\n// v1.2 Factory Helpers\n// =============================================================================\n\n/**\n * Create a try/catch/finally command node (v1.2).\n */\nexport function createTryNode(\n body: SemanticNode[],\n catchBranch?: SemanticNode[],\n finallyBranch?: SemanticNode[],\n metadata?: SemanticMetadata\n): CommandSemanticNode {\n return {\n kind: 'command',\n action: 'try',\n roles: new Map(),\n body,\n ...(catchBranch && catchBranch.length > 0 ? { catchBranch } : {}),\n ...(finallyBranch && finallyBranch.length > 0 ? { finallyBranch } : {}),\n ...(metadata ? { metadata } : {}),\n };\n}\n\n/**\n * Create an async coordination (all/race) command node (v1.2).\n */\nexport function createAsyncNode(\n variant: AsyncVariant,\n asyncBody: SemanticNode[],\n metadata?: SemanticMetadata\n): CommandSemanticNode {\n return {\n kind: 'command',\n action: variant,\n roles: new Map(),\n asyncVariant: variant,\n asyncBody,\n ...(metadata ? { metadata } : {}),\n };\n}\n\n/**\n * Create a match command node with pattern arms (v1.2).\n */\nexport function createMatchNode(\n roles: Record<SemanticRole, SemanticValue> | Map<SemanticRole, SemanticValue>,\n arms: MatchArm[],\n defaultArm?: SemanticNode[],\n metadata?: SemanticMetadata\n): CommandSemanticNode {\n const rolesMap = roles instanceof Map ? roles : new Map(Object.entries(roles));\n return {\n kind: 'command',\n action: 'match',\n roles: rolesMap,\n arms,\n ...(defaultArm && defaultArm.length > 0 ? { defaultArm } : {}),\n ...(metadata ? { metadata } : {}),\n };\n}\n\n/** Wire format envelope with version metadata (v1.2). */\nexport interface LSEEnvelope {\n readonly lseVersion: string;\n readonly features?: readonly string[];\n readonly nodes: readonly SemanticNode[];\n}\n","/**\n * Debug Logging System\n *\n * Provides environment-aware debug logging for the framework.\n * Enable via DEBUG environment variable or programmatically.\n */\n\ntype LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\ninterface Logger {\n debug(message: string, ...args: any[]): void;\n info(message: string, ...args: any[]): void;\n warn(message: string, ...args: any[]): void;\n error(message: string, ...args: any[]): void;\n isEnabled(): boolean;\n}\n\nclass DebugLogger {\n private enabled: boolean;\n private namespace: string;\n\n constructor(namespace: string) {\n this.namespace = namespace;\n this.enabled = this.checkEnabled();\n }\n\n private checkEnabled(): boolean {\n // Check if running in Node.js\n if (typeof process !== 'undefined' && process.env) {\n const DEBUG = process.env.DEBUG || '';\n // Enable if DEBUG=* or DEBUG=framework:* or DEBUG=framework:namespace\n return (\n DEBUG === '*' ||\n DEBUG.includes('framework:*') ||\n DEBUG.includes(`framework:${this.namespace}`)\n );\n }\n return false;\n }\n\n private log(level: LogLevel, message: string, ...args: any[]): void {\n if (!this.enabled) return;\n\n const prefix = `[framework:${this.namespace}]`;\n const timestamp = new Date().toISOString();\n\n switch (level) {\n case 'debug':\n // eslint-disable-next-line no-console\n console.debug(`${timestamp} ${prefix} DEBUG:`, message, ...args);\n break;\n case 'info':\n // eslint-disable-next-line no-console\n console.info(`${timestamp} ${prefix} INFO:`, message, ...args);\n break;\n case 'warn':\n // eslint-disable-next-line no-console\n console.warn(`${timestamp} ${prefix} WARN:`, message, ...args);\n break;\n case 'error':\n // eslint-disable-next-line no-console\n console.error(`${timestamp} ${prefix} ERROR:`, message, ...args);\n break;\n }\n }\n\n debug(message: string, ...args: any[]): void {\n this.log('debug', message, ...args);\n }\n\n info(message: string, ...args: any[]): void {\n this.log('info', message, ...args);\n }\n\n warn(message: string, ...args: any[]): void {\n this.log('warn', message, ...args);\n }\n\n error(message: string, ...args: any[]): void {\n this.log('error', message, ...args);\n }\n\n /**\n * Check if logging is enabled for this namespace.\n */\n isEnabled(): boolean {\n return this.enabled;\n }\n\n /**\n * Programmatically enable logging for this namespace.\n */\n enable(): void {\n this.enabled = true;\n }\n\n /**\n * Programmatically disable logging for this namespace.\n */\n disable(): void {\n this.enabled = false;\n }\n}\n\n/**\n * Create a logger for a specific namespace.\n *\n * @param namespace - Logger namespace (e.g., 'pattern-matcher', 'tokenizer')\n * @returns Logger instance\n *\n * @example\n * const logger = createLogger('pattern-matcher');\n * logger.debug('Matching pattern:', pattern.id);\n * logger.warn('Low confidence match:', confidence);\n */\nexport function createLogger(namespace: string): Logger {\n return new DebugLogger(namespace);\n}\n\n/**\n * No-op logger that does nothing.\n * Useful for disabling logging in production builds.\n */\nexport const noopLogger: Logger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n isEnabled: () => false,\n};\n","/**\n * Type Validation Utility\n *\n * Shared utilities for validating semantic value types against expected types.\n * Used by pattern-matcher to validate captured role values.\n */\n\nimport type { SemanticValue } from '../../types';\n\n/**\n * Semantic value type strings.\n */\nexport type SemanticValueType = SemanticValue['type'];\n\n/**\n * Check if a value type matches any of the expected types.\n *\n * The 'expression' type is treated as a wildcard that matches any value.\n * The 'property-path' type is compatible with selector, reference, and expression.\n *\n * @param actualType The actual type of the value\n * @param expectedTypes Array of expected types\n * @returns True if the type is compatible\n */\nexport function isTypeCompatible(\n actualType: SemanticValueType | string,\n expectedTypes: (SemanticValueType | string)[]\n): boolean {\n // Empty expected types means any type is valid\n if (!expectedTypes || expectedTypes.length === 0) {\n return true;\n }\n\n // Direct match\n if (expectedTypes.includes(actualType)) {\n return true;\n }\n\n // 'expression' is always compatible (wildcard)\n if (expectedTypes.includes('expression')) {\n return true;\n }\n\n // 'property-path' is compatible with selector, reference, and expression\n if (actualType === 'property-path') {\n return expectedTypes.some(t => ['selector', 'reference', 'expression'].includes(t));\n }\n\n return false;\n}\n\n/**\n * Validate a semantic value against expected types.\n *\n * @param value The semantic value to validate\n * @param expectedTypes Array of expected types (empty means any type is valid)\n * @returns True if the value type is valid\n */\nexport function validateValueType(\n value: SemanticValue,\n expectedTypes?: (SemanticValueType | string)[]\n): boolean {\n if (!expectedTypes || expectedTypes.length === 0) {\n return true;\n }\n\n return isTypeCompatible(value.type, expectedTypes);\n}\n\n/**\n * Check if a value is a CSS selector.\n */\nexport function isCSSSelector(value: string): boolean {\n return value.startsWith('.') || value.startsWith('#') || value.startsWith('<');\n}\n\n/**\n * Check if a value is a class name (starts with .).\n */\nexport function isClassName(value: string): boolean {\n return value.startsWith('.');\n}\n\n/**\n * Check if a value is an ID selector (starts with #).\n */\nexport function isIdSelector(value: string): boolean {\n return value.startsWith('#');\n}\n\n/**\n * Check if a value is a CSS property reference (starts with *).\n */\nexport function isCSSPropertyRef(value: string): boolean {\n return value.startsWith('*');\n}\n\n/**\n * Check if a value is a numeric value.\n */\nexport function isNumericValue(value: string): boolean {\n // Handle duration values (e.g., \"100ms\", \"2s\")\n const durationMatch = value.match(/^(\\d+(?:\\.\\d+)?)(ms|s|m|h)?$/);\n if (durationMatch) {\n return true;\n }\n\n // Plain number\n const num = parseFloat(value);\n return !isNaN(num) && isFinite(num);\n}\n\n/**\n * Check if a value is a property name (identifier-like).\n */\nexport function isPropertyName(value: string): boolean {\n // Property names are identifiers (start with letter or _, contain alphanumeric)\n return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(value);\n}\n\n/**\n * Check if a value is a variable reference (starts with :).\n */\nexport function isVariableRef(value: string): boolean {\n return value.startsWith(':');\n}\n\n/**\n * Check if a value is a built-in reference (me, you, it, etc.).\n */\nexport function isBuiltInReference(value: string): boolean {\n const builtIns = new Set(['me', 'you', 'it', 'result', 'event', 'target', 'body']);\n return builtIns.has(value.toLowerCase());\n}\n","/**\n * Possessive Keywords Utility\n *\n * Provides functions to look up possessive keywords from language profiles.\n * Used by pattern-matcher to recognize possessive expressions like \"my value\".\n */\n\n/**\n * Minimal profile interface for possessive keyword lookup.\n */\nexport interface PossessiveProfile {\n readonly possessive?: {\n readonly keywords?: Record<string, string>;\n };\n}\n\n/**\n * Get the reference for a possessive keyword from a profile.\n *\n * @param profile Language profile\n * @param keyword Possessive keyword (e.g., 'my', 'your', 'its')\n * @returns The reference (e.g., 'me', 'you', 'it') or undefined if not found\n */\nexport function getPossessiveReference(\n profile: PossessiveProfile | undefined,\n keyword: string\n): string | undefined {\n return profile?.possessive?.keywords?.[keyword];\n}\n\n/**\n * Check if a keyword is a possessive keyword in the given profile.\n *\n * @param profile Language profile\n * @param keyword Keyword to check\n * @returns True if the keyword is a possessive keyword\n */\nexport function isPossessiveKeyword(\n profile: PossessiveProfile | undefined,\n keyword: string\n): boolean {\n return profile?.possessive?.keywords?.[keyword] !== undefined;\n}\n\n/**\n * Get all possessive keywords from a profile.\n *\n * @param profile Language profile\n * @returns Record of possessive keywords to references, or empty object\n */\nexport function getAllPossessiveKeywords(\n profile: PossessiveProfile | undefined\n): Record<string, string> {\n return profile?.possessive?.keywords ?? {};\n}\n","/**\n * Pattern Matcher\n *\n * Matches tokenized input against language patterns to extract semantic roles.\n * This is the core algorithm for multilingual parsing.\n */\n\nimport type {\n LanguagePattern,\n PatternToken,\n PatternMatchResult,\n ReferenceValue,\n SemanticRole,\n SemanticValue,\n TokenStream,\n LanguageToken,\n} from '../types';\nimport { createSelector, createLiteral, createReference, createPropertyPath } from '../types';\nimport { createLogger } from '../logger';\n\n/**\n * Helper to check if a value is a built-in reference.\n * In the generic framework, we don't assume any built-in references.\n * DSLs that need references (like hyperscript's 'me', 'it', 'you') should\n * handle them in their tokenizer or provide a custom reference validator.\n *\n * For generic DSLs, identifiers are treated as expressions by default.\n */\nfunction isValidReference(_value: string): boolean {\n // In generic framework, no built-in references\n // Identifiers should be expressions\n return false;\n}\nimport { isTypeCompatible } from './utils/type-validation';\nimport { getPossessiveReference } from './utils/possessive-keywords';\n\n/**\n * Minimal profile interface needed by PatternMatcher.\n * DSLs can provide this to enable possessive handling and language-specific features.\n */\nexport interface PatternMatcherProfile {\n readonly code: string;\n readonly possessive?: {\n readonly keywords?: Record<string, string>;\n };\n}\n\n// =============================================================================\n// Pattern Matcher\n// =============================================================================\n\nexport class PatternMatcher {\n /** Maximum tokens to scan ahead when looking for a group's leading marker */\n private static readonly MAX_MARKER_SCAN = 3;\n\n /** Debug logger */\n private logger = createLogger('pattern-matcher');\n\n /** Current language profile for the pattern being matched */\n private currentProfile: PatternMatcherProfile | undefined;\n\n /**\n * Safely convert a value to lowercase string.\n * Provides protection against non-string values at runtime.\n */\n private safeToLowerCase(value: unknown): string {\n if (typeof value === 'string') {\n return value.toLowerCase();\n }\n if (value === null || value === undefined) {\n return '';\n }\n return String(value).toLowerCase();\n }\n\n /**\n * Try to match a single pattern against the token stream.\n * Returns the match result or null if no match.\n *\n * @param tokens - Token stream to match against\n * @param pattern - Pattern to match\n * @param profile - Optional language profile for possessive handling\n */\n matchPattern(\n tokens: TokenStream,\n pattern: LanguagePattern,\n profile?: PatternMatcherProfile\n ): PatternMatchResult | null {\n const mark = tokens.mark();\n const captured = new Map<SemanticRole, SemanticValue>();\n\n // Debug logging\n this.logger.debug('========================================');\n this.logger.debug('matchPattern ENTRY');\n this.logger.debug('Pattern ID:', pattern.id);\n this.logger.debug('Pattern command:', pattern.command);\n this.logger.debug('Pattern language:', pattern.language);\n this.logger.debug('Pattern template:', JSON.stringify(pattern.template, null, 2));\n\n if (this.logger.isEnabled()) {\n const firstTokens = [];\n for (let i = 0; i < 10; i++) {\n const t = tokens.peek(i);\n if (t)\n firstTokens.push({\n type: (t as any).type,\n value: (t as any).value,\n kind: (t as any).kind,\n });\n else break;\n }\n this.logger.debug('Input tokens (first 10):', firstTokens);\n this.logger.debug('Profile code:', profile?.code);\n }\n\n // Use provided profile for possessive keyword lookup\n this.currentProfile = profile;\n\n // Reset match counters for this pattern\n this.stemMatchCount = 0;\n this.totalKeywordMatches = 0;\n\n this.logger.debug('--- Calling matchTokenSequence ---');\n this.logger.debug('Pattern tokens to match:', JSON.stringify(pattern.template.tokens, null, 2));\n const success = this.matchTokenSequence(tokens, pattern.template.tokens, captured);\n this.logger.debug('matchTokenSequence returned:', success);\n this.logger.debug(\n 'Captured roles:',\n Array.from(captured.entries()).map(([k, v]) => [k, JSON.stringify(v)])\n );\n\n if (!success) {\n this.logger.debug('>>> MATCH FAILED - resetting token position');\n tokens.reset(mark);\n return null;\n }\n\n // Calculate confidence BEFORE applying defaults\n // This ensures defaulted roles don't artificially inflate confidence\n const confidence = this.calculateConfidence(pattern, captured);\n\n // Apply extraction rules to fill in any missing roles with defaults\n this.applyExtractionRules(pattern, captured);\n\n return {\n pattern,\n captured,\n consumedTokens: tokens.position() - mark.position,\n confidence,\n };\n }\n\n /**\n * Try to match multiple patterns, return the best match.\n *\n * @param tokens - Token stream to match against\n * @param patterns - Candidate patterns to try\n * @param profile - Optional language profile for possessive handling\n */\n matchBest(\n tokens: TokenStream,\n patterns: LanguagePattern[],\n profile?: PatternMatcherProfile\n ): PatternMatchResult | null {\n const matches: PatternMatchResult[] = [];\n\n for (const pattern of patterns) {\n const mark = tokens.mark();\n const result = this.matchPattern(tokens, pattern, profile);\n\n if (result) {\n matches.push(result);\n }\n\n tokens.reset(mark);\n }\n\n if (matches.length === 0) {\n return null;\n }\n\n // Sort by confidence and priority\n matches.sort((a, b) => {\n // First by priority\n const priorityDiff = b.pattern.priority - a.pattern.priority;\n if (priorityDiff !== 0) return priorityDiff;\n\n // Then by confidence\n const confidenceDiff = b.confidence - a.confidence;\n if (Math.abs(confidenceDiff) > 0.001) return confidenceDiff;\n\n // Then by tokens consumed (prefer more complete matches)\n return b.consumedTokens - a.consumedTokens;\n });\n\n // Re-consume tokens for the best match\n const best = matches[0];\n this.matchPattern(tokens, best.pattern);\n\n return best;\n }\n\n /**\n * Match a sequence of pattern tokens against the token stream.\n *\n * Supports bounded single-step backtracking: if an optional role consumes\n * a token and the immediately following pattern token fails, the matcher\n * resets to before the optional role and retries the failed token.\n */\n private matchTokenSequence(\n tokens: TokenStream,\n patternTokens: PatternToken[],\n captured: Map<SemanticRole, SemanticValue>,\n parentStopMarkers?: Set<string>\n ): boolean {\n // Skip leading conjunctions for Arabic (proclitics: و, ف, ول, وب, etc.)\n // BUT NOT if the pattern explicitly expects a conjunction (proclitic patterns)\n const firstPatternToken = patternTokens[0];\n const patternExpectsConjunction =\n firstPatternToken?.type === 'literal' &&\n (firstPatternToken.value === 'and' ||\n firstPatternToken.value === 'then' ||\n firstPatternToken.alternatives?.includes('and') ||\n firstPatternToken.alternatives?.includes('then'));\n\n if (this.currentProfile?.code === 'ar' && !patternExpectsConjunction) {\n while (tokens.peek()?.kind === 'conjunction') {\n tokens.advance();\n }\n }\n\n // Backtracking state: track the most recent optional role that consumed a token\n let prevOptionalMark: ReturnType<TokenStream['mark']> | null = null;\n let prevOptionalRole: SemanticRole | null = null;\n\n for (let i = 0; i < patternTokens.length; i++) {\n const patternToken = patternTokens[i];\n this.logger.debug(' >> Matching pattern token:', JSON.stringify(patternToken, null, 2));\n const currTok = tokens.peek();\n this.logger.debug(\n ' >> Current input token:',\n currTok\n ? JSON.stringify({\n type: (currTok as any).type,\n value: (currTok as any).value,\n kind: (currTok as any).kind,\n })\n : 'EOF'\n );\n\n // Greedy role capture: consume all remaining tokens until the next\n // recognized marker keyword or end of input\n if (patternToken.type === 'role' && patternToken.greedy) {\n const stopMarkers = this.collectStopMarkers(patternTokens, i + 1);\n // Merge parent-level stop markers so greedy roles inside groups\n // know when to stop for tokens outside the group (e.g., SOV verb keywords)\n if (parentStopMarkers) {\n for (const m of parentStopMarkers) stopMarkers.add(m);\n }\n const values: string[] = [];\n while (!tokens.isAtEnd()) {\n const nextToken = tokens.peek();\n if (!nextToken) break;\n if (this.isStopMarker(nextToken, stopMarkers)) break;\n values.push(nextToken.value);\n tokens.advance();\n }\n if (values.length > 0) {\n captured.set(patternToken.role, { type: 'expression', raw: values.join(' ') });\n prevOptionalMark = null;\n prevOptionalRole = null;\n continue;\n } else if (patternToken.optional) {\n continue;\n } else {\n return false;\n }\n }\n\n // Group tokens: compute sibling stop markers and forward to inner matching\n if (patternToken.type === 'group') {\n const siblingStopMarkers = this.collectStopMarkers(patternTokens, i + 1);\n if (parentStopMarkers) {\n for (const m of parentStopMarkers) siblingStopMarkers.add(m);\n }\n const groupMatched = this.matchGroupToken(\n tokens,\n patternToken as PatternToken & { type: 'group' },\n captured,\n siblingStopMarkers\n );\n if (groupMatched) {\n prevOptionalMark = null;\n prevOptionalRole = null;\n continue;\n }\n if (this.isOptional(patternToken)) {\n continue;\n }\n return false;\n }\n\n // Save stream position before attempting optional roles\n const isOptionalRole = patternToken.type === 'role' && patternToken.optional === true;\n const markBefore = isOptionalRole ? tokens.mark() : null;\n\n // SOV marker-stealing guard: before matching a required role, check if\n // the current input token would match the immediately-following pattern\n // literal (the role's own postpositional marker). If so, skip consuming\n // this token as a role value — it should be matched as the literal instead.\n const isRoleToken = patternToken.type === 'role';\n if (isRoleToken && !isOptionalRole) {\n const nextPT = i + 1 < patternTokens.length ? patternTokens[i + 1] : null;\n if (nextPT?.type === 'literal') {\n const currentToken = tokens.peek();\n if (currentToken && this.getMatchType(currentToken, nextPT.value) !== 'none') {\n // Current token is the marker literal, not a role value — treat role as failed\n this.logger.debug(\n ' >> MARKER-STEAL GUARD: current token matches next literal, skipping role'\n );\n // Fall through to failure handling below\n // (which will trigger backtracking of previous optional role)\n\n // Match failed\n this.logger.debug(' >> Token match FAILED');\n\n if (this.isOptional(patternToken)) {\n continue;\n }\n\n // Required token failed — try backtracking over the previous optional role\n if (prevOptionalMark && prevOptionalRole) {\n this.logger.debug(' >> BACKTRACKING: undoing optional role', prevOptionalRole);\n tokens.reset(prevOptionalMark);\n captured.delete(prevOptionalRole);\n prevOptionalMark = null;\n prevOptionalRole = null;\n\n // Retry the current (failed) pattern token from the restored position\n const retryMatched = this.matchPatternToken(tokens, patternToken, captured);\n this.logger.debug(' >> Backtrack retry result:', retryMatched);\n if (retryMatched) {\n continue;\n }\n }\n\n return false;\n }\n }\n }\n\n const matched = this.matchPatternToken(tokens, patternToken, captured);\n this.logger.debug(' >> Match result:', matched);\n\n if (matched) {\n if (isOptionalRole) {\n // Track this consumption so we can undo it if the next token fails\n prevOptionalMark = markBefore;\n prevOptionalRole = patternToken.role;\n } else {\n // Non-optional succeeded — clear backtrack state\n prevOptionalMark = null;\n prevOptionalRole = null;\n }\n continue;\n }\n\n // Match failed\n this.logger.debug(' >> Token match FAILED');\n\n if (this.isOptional(patternToken)) {\n continue;\n }\n\n // Required token failed — try backtracking over the previous optional role\n if (prevOptionalMark && prevOptionalRole) {\n this.logger.debug(' >> BACKTRACKING: undoing optional role', prevOptionalRole);\n tokens.reset(prevOptionalMark);\n captured.delete(prevOptionalRole);\n prevOptionalMark = null;\n prevOptionalRole = null;\n\n // Retry the current (failed) pattern token from the restored position\n const retryMatched = this.matchPatternToken(tokens, patternToken, captured);\n this.logger.debug(' >> Backtrack retry result:', retryMatched);\n if (retryMatched) {\n continue;\n }\n }\n\n return false;\n }\n\n return true;\n }\n\n /**\n * Match a single pattern token against the current position in the stream.\n */\n private matchPatternToken(\n tokens: TokenStream,\n patternToken: PatternToken,\n captured: Map<SemanticRole, SemanticValue>\n ): boolean {\n switch (patternToken.type) {\n case 'literal':\n return this.matchLiteralToken(tokens, patternToken);\n\n case 'role':\n return this.matchRoleToken(tokens, patternToken, captured);\n\n case 'group':\n return this.matchGroupToken(tokens, patternToken, captured);\n\n default:\n return false;\n }\n }\n\n /**\n * Match a literal pattern token (keyword or particle).\n */\n private matchLiteralToken(\n tokens: TokenStream,\n patternToken: PatternToken & { type: 'literal' }\n ): boolean {\n const token = tokens.peek();\n this.logger.debug(' >>> matchLiteralToken: expecting', patternToken.value);\n this.logger.debug(\n ' >>> matchLiteralToken: got token',\n token\n ? JSON.stringify({\n type: (token as any).type,\n value: (token as any).value,\n kind: (token as any).kind,\n })\n : 'null'\n );\n if (!token) {\n this.logger.debug(' >>> matchLiteralToken: FAIL - no token');\n return false;\n }\n\n // Check main value\n const matchType = this.getMatchType(token, patternToken.value);\n this.logger.debug(\n ' >>> matchType for',\n token.value,\n 'vs',\n patternToken.value,\n ':',\n matchType\n );\n if (matchType !== 'none') {\n this.totalKeywordMatches++;\n if (matchType === 'stem') {\n this.stemMatchCount++;\n }\n tokens.advance();\n return true;\n }\n\n // Check alternatives\n if (patternToken.alternatives) {\n for (const alt of patternToken.alternatives) {\n const altMatchType = this.getMatchType(token, alt);\n if (altMatchType !== 'none') {\n this.totalKeywordMatches++;\n if (altMatchType === 'stem') {\n this.stemMatchCount++;\n }\n tokens.advance();\n return true;\n }\n }\n }\n\n return false;\n }\n\n /**\n * Match a role pattern token (captures a semantic value).\n * Handles multi-token expressions like:\n * - 'my value' (possessive keyword + property)\n * - '#dialog.showModal()' (method call)\n * - \"#element's *opacity\" (possessive selector + property)\n */\n private matchRoleToken(\n tokens: TokenStream,\n patternToken: PatternToken & { type: 'role' },\n captured: Map<SemanticRole, SemanticValue>\n ): boolean {\n this.logger.debug(' >>> matchRoleToken ENTRY: capturing role', patternToken.role);\n this.logger.debug(' >>> matchRoleToken: expected types', patternToken.expectedTypes);\n this.logger.debug(' >>> matchRoleToken: optional?', patternToken.optional);\n // Skip noise words like \"the\" before selectors (English idiom support)\n this.skipNoiseWords(tokens);\n\n const token = tokens.peek();\n this.logger.debug(\n ' >>> After skipNoiseWords, current token:',\n token ? JSON.stringify({ value: (token as any).value, kind: (token as any).kind }) : 'null'\n );\n if (!token) {\n return patternToken.optional || false;\n }\n\n // Check for possessive expression (e.g., 'my value', 'its innerHTML')\n const possessiveValue = this.tryMatchPossessiveExpression(tokens);\n if (possessiveValue) {\n // Validate expected types if specified\n if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {\n if (!isTypeCompatible(possessiveValue.type, patternToken.expectedTypes)) {\n return patternToken.optional || false;\n }\n }\n captured.set(patternToken.role, possessiveValue);\n return true;\n }\n\n // Check for method call expression (e.g., '#dialog.showModal()')\n const methodCallValue = this.tryMatchMethodCallExpression(tokens);\n if (methodCallValue) {\n if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {\n if (!isTypeCompatible(methodCallValue.type, patternToken.expectedTypes)) {\n return patternToken.optional || false;\n }\n }\n captured.set(patternToken.role, methodCallValue);\n return true;\n }\n\n // Check for possessive selector expression (e.g., \"#element's *opacity\")\n const possessiveSelectorValue = this.tryMatchPossessiveSelectorExpression(tokens);\n if (possessiveSelectorValue) {\n if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {\n // property-path is compatible with selector, reference, and expression\n if (!isTypeCompatible(possessiveSelectorValue.type, patternToken.expectedTypes)) {\n return patternToken.optional || false;\n }\n }\n captured.set(patternToken.role, possessiveSelectorValue);\n return true;\n }\n\n // Check for property access expression (e.g., 'userData.name', 'it.data')\n const propertyAccessValue = this.tryMatchPropertyAccessExpression(tokens);\n if (propertyAccessValue) {\n if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {\n if (!isTypeCompatible(propertyAccessValue.type, patternToken.expectedTypes)) {\n return patternToken.optional || false;\n }\n }\n captured.set(patternToken.role, propertyAccessValue);\n return true;\n }\n\n // Check for selector + property expression (e.g., '#output.innerText')\n // This handles cases where the tokenizer produces two selector tokens\n const selectorPropertyValue = this.tryMatchSelectorPropertyExpression(tokens);\n if (selectorPropertyValue) {\n if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {\n if (!isTypeCompatible(selectorPropertyValue.type, patternToken.expectedTypes)) {\n return patternToken.optional || false;\n }\n }\n captured.set(patternToken.role, selectorPropertyValue);\n return true;\n }\n\n // Try to extract a semantic value from the token\n this.logger.debug(\n ' >>> Trying tokenToSemanticValue for token:',\n token ? JSON.stringify({ value: (token as any).value, kind: (token as any).kind }) : 'null'\n );\n const value = this.tokenToSemanticValue(token);\n this.logger.debug(\n ' >>> tokenToSemanticValue returned:',\n value ? JSON.stringify(value) : 'null'\n );\n if (!value) {\n return patternToken.optional || false;\n }\n\n // Validate expected types if specified\n this.logger.debug(\n ' >>> Validating type:',\n value.type,\n 'against expected:',\n patternToken.expectedTypes\n );\n if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {\n if (!isTypeCompatible(value.type, patternToken.expectedTypes)) {\n this.logger.debug(' >>> TYPE MISMATCH - returning', patternToken.optional || false);\n return patternToken.optional || false;\n }\n }\n this.logger.debug(' >>> Type validation PASSED');\n\n captured.set(patternToken.role, value);\n tokens.advance();\n return true;\n }\n\n /**\n * Try to match a possessive expression like 'my value' or 'its innerHTML'.\n * Returns the PropertyPathValue if matched, or null if not.\n */\n private tryMatchPossessiveExpression(tokens: TokenStream): SemanticValue | null {\n const token = tokens.peek();\n if (!token) return null;\n\n // Use profile-based possessive keyword lookup\n if (!this.currentProfile) return null;\n\n const tokenValue = token.normalized || token.value;\n const tokenLower = this.safeToLowerCase(tokenValue);\n const baseRef = getPossessiveReference(this.currentProfile, tokenLower);\n\n if (!baseRef) return null;\n\n // We have a possessive keyword, look ahead for property name\n const mark = tokens.mark();\n tokens.advance();\n\n const propertyToken = tokens.peek();\n if (!propertyToken) {\n // Just the possessive keyword, no property - revert\n tokens.reset(mark);\n return null;\n }\n\n // Property should be an identifier, keyword (not structural), or selector (for style/dot/attr)\n // Examples: \"my value\", \"my innerHTML\", \"my *background\", \"my *opacity\", \"my @data-count\"\n // Also handles dot-property access: \"my.textContent\" tokenized as \"my\" + \".textContent\"\n if (\n propertyToken.kind === 'identifier' ||\n (propertyToken.kind === 'keyword' && !this.isStructuralKeyword(propertyToken.value)) ||\n (propertyToken.kind === 'selector' && propertyToken.value.startsWith('*')) ||\n (propertyToken.kind === 'selector' && propertyToken.value.startsWith('@')) ||\n (propertyToken.kind === 'selector' &&\n propertyToken.value.startsWith('.') &&\n /^\\.[a-zA-Z_]\\w*/.test(propertyToken.value))\n ) {\n tokens.advance();\n\n // For dot-property selectors (.textContent), strip the leading dot\n let propertyName = propertyToken.value;\n if (\n propertyToken.kind === 'selector' &&\n propertyName.startsWith('.') &&\n /^\\.[a-zA-Z_]\\w*/.test(propertyName)\n ) {\n propertyName = propertyName.substring(1);\n }\n\n // Consume chained dot-property access (.parentElement.style.display)\n let chainedProps = propertyName;\n while (\n tokens.peek()?.kind === 'selector' &&\n tokens.peek()!.value.startsWith('.') &&\n /^\\.[a-zA-Z_]\\w*/.test(tokens.peek()!.value)\n ) {\n chainedProps += tokens.peek()!.value; // keep the dots for chaining\n tokens.advance();\n }\n\n // Check for method call — next token is '(' in the value (e.g., .getAttribute(\"data-id\"))\n const nextPeek = tokens.peek();\n if (nextPeek?.kind === 'literal' && nextPeek.value.startsWith('(')) {\n // Consume method args\n chainedProps += nextPeek.value;\n tokens.advance();\n }\n\n // Create property-path: my value -> { object: me, property: 'value' }\n // baseRef from getPossessiveReference is always a valid reference ('me', 'you', 'it', etc.)\n return createPropertyPath(createReference(baseRef as ReferenceValue['value']), chainedProps);\n }\n\n // Not a valid property, revert\n tokens.reset(mark);\n return null;\n }\n\n /**\n * Check if a keyword is a structural keyword (preposition, control flow, etc.)\n * that shouldn't be consumed as a property name.\n */\n private isStructuralKeyword(value: string): boolean {\n const structural = new Set([\n // Prepositions\n 'into',\n 'in',\n 'to',\n 'from',\n 'at',\n 'by',\n 'with',\n 'without',\n 'before',\n 'after',\n 'of',\n 'as',\n 'on',\n // Control flow\n 'then',\n 'end',\n 'else',\n 'if',\n 'repeat',\n 'while',\n 'for',\n // Commands (shouldn't be property names)\n 'toggle',\n 'add',\n 'remove',\n 'put',\n 'set',\n 'show',\n 'hide',\n 'increment',\n 'decrement',\n 'send',\n 'trigger',\n 'call',\n ]);\n return structural.has(value.toLowerCase());\n }\n\n /**\n * Try to match a method call expression like '#dialog.showModal()'.\n * Pattern: selector + '.' + identifier + '(' + [args] + ')'\n * Returns an expression value if matched, or null if not.\n */\n private tryMatchMethodCallExpression(tokens: TokenStream): SemanticValue | null {\n const token = tokens.peek();\n if (!token || token.kind !== 'selector') return null;\n\n // Look ahead for: . identifier (\n const mark = tokens.mark();\n tokens.advance(); // consume selector\n\n const dotToken = tokens.peek();\n if (!dotToken || dotToken.kind !== 'operator' || dotToken.value !== '.') {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume .\n\n const methodToken = tokens.peek();\n if (!methodToken || methodToken.kind !== 'identifier') {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume method name\n\n const openParen = tokens.peek();\n if (!openParen || openParen.kind !== 'punctuation' || openParen.value !== '(') {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume (\n\n // Consume arguments until we find ) (with depth limit for security)\n const args: string[] = [];\n while (!tokens.isAtEnd() && args.length < PatternMatcher.MAX_METHOD_ARGS) {\n const argToken = tokens.peek();\n if (!argToken) break;\n if (argToken.kind === 'punctuation' && argToken.value === ')') {\n tokens.advance(); // consume )\n break;\n }\n // Skip commas\n if (argToken.kind === 'punctuation' && argToken.value === ',') {\n tokens.advance();\n continue;\n }\n // Collect arg value\n args.push(argToken.value);\n tokens.advance();\n }\n\n // Create expression value: #dialog.showModal()\n const methodCall = `${token.value}.${methodToken.value}(${args.join(', ')})`;\n return {\n type: 'expression',\n raw: methodCall,\n } as SemanticValue;\n }\n\n /**\n * Try to match a property access expression like 'userData.name' or 'it.data'.\n * Pattern: (identifier | keyword) + '.' + identifier [+ '.' + identifier ...]\n * Returns an expression value if matched, or null if not.\n */\n private tryMatchPropertyAccessExpression(tokens: TokenStream): SemanticValue | null {\n const token = tokens.peek();\n if (!token) return null;\n\n // Must start with an identifier or keyword reference\n if (token.kind !== 'identifier' && token.kind !== 'keyword') return null;\n\n // Look ahead for: . identifier\n const mark = tokens.mark();\n tokens.advance(); // consume first token\n\n const dotToken = tokens.peek();\n if (!dotToken || dotToken.kind !== 'operator' || dotToken.value !== '.') {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume .\n\n const propertyToken = tokens.peek();\n if (!propertyToken || propertyToken.kind !== 'identifier') {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume property name\n\n // Build the property chain\n let chain = `${token.value}.${propertyToken.value}`;\n let depth = 1; // Already have one property access\n\n // Continue for nested property access (e.g., userData.address.city)\n // With depth limit for security\n while (!tokens.isAtEnd() && depth < PatternMatcher.MAX_PROPERTY_DEPTH) {\n const nextDot = tokens.peek();\n if (!nextDot || nextDot.kind !== 'operator' || nextDot.value !== '.') {\n break;\n }\n tokens.advance(); // consume .\n\n const nextProp = tokens.peek();\n if (!nextProp || nextProp.kind !== 'identifier') {\n // Dot without property - put the dot back and stop\n // Can't easily put a single token back, so we'll include it\n break;\n }\n tokens.advance(); // consume property\n chain += `.${nextProp.value}`;\n depth++;\n }\n\n // Check for method call: chain + '(' + args + ')'\n // e.g., me.insertBefore(draggedItem, dropTarget)\n const openParen = tokens.peek();\n if (openParen && openParen.kind === 'punctuation' && openParen.value === '(') {\n tokens.advance(); // consume (\n\n // Collect arguments (comma-separated values)\n const args: string[] = [];\n let argDepth = 0; // Track nested parentheses\n while (!tokens.isAtEnd() && args.length < PatternMatcher.MAX_METHOD_ARGS) {\n const argToken = tokens.peek();\n if (!argToken) break;\n\n // Handle close paren - respecting nesting\n if (argToken.kind === 'punctuation' && argToken.value === ')') {\n if (argDepth === 0) {\n tokens.advance(); // consume )\n break;\n }\n argDepth--;\n }\n // Track nested open parens\n if (argToken.kind === 'punctuation' && argToken.value === '(') {\n argDepth++;\n }\n // Skip commas between arguments\n if (argToken.kind === 'punctuation' && argToken.value === ',') {\n tokens.advance();\n continue;\n }\n // Collect arg value\n args.push(argToken.value);\n tokens.advance();\n }\n\n // Create expression value with method call: me.insertBefore(a, b)\n const methodCall = `${chain}(${args.join(', ')})`;\n return {\n type: 'expression',\n raw: methodCall,\n } as SemanticValue;\n }\n\n // Create expression value: userData.name\n return {\n type: 'expression',\n raw: chain,\n } as SemanticValue;\n }\n\n /**\n * Try to match a possessive selector expression like \"#element's *opacity\".\n * Pattern: selector + \"'s\" + (selector | identifier)\n * Returns a property-path value if matched, or null if not.\n */\n private tryMatchPossessiveSelectorExpression(tokens: TokenStream): SemanticValue | null {\n const token = tokens.peek();\n if (!token || token.kind !== 'selector') return null;\n\n // Look ahead for: 's (possessive marker)\n const mark = tokens.mark();\n tokens.advance(); // consume selector\n\n const possessiveToken = tokens.peek();\n if (\n !possessiveToken ||\n possessiveToken.kind !== 'punctuation' ||\n possessiveToken.value !== \"'s\"\n ) {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume 's\n\n const propertyToken = tokens.peek();\n if (!propertyToken) {\n tokens.reset(mark);\n return null;\n }\n\n // Property can be a selector (*opacity) or identifier\n if (propertyToken.kind !== 'selector' && propertyToken.kind !== 'identifier') {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume property\n\n // Create property-path: #element's *opacity\n return createPropertyPath(createSelector(token.value), propertyToken.value);\n }\n\n /**\n * Try to match a selector + property expression like \"#output.innerText\".\n * This handles cases where the tokenizer produces two selector tokens:\n * - #output (id selector)\n * - .innerText (looks like class selector, but is actually property)\n *\n * Pattern: id-selector + class-selector-that-is-actually-property\n * Returns a property-path value if matched, or null if not.\n */\n private tryMatchSelectorPropertyExpression(tokens: TokenStream): SemanticValue | null {\n const token = tokens.peek();\n if (!token || token.kind !== 'selector') return null;\n\n // Must be an ID selector (starts with #)\n if (typeof token.value !== 'string' || !token.value.startsWith('#')) return null;\n\n // Look ahead for: selector that looks like a property (.something)\n const mark = tokens.mark();\n tokens.advance(); // consume first selector\n\n const propertyToken = tokens.peek();\n if (!propertyToken || propertyToken.kind !== 'selector') {\n tokens.reset(mark);\n return null;\n }\n\n // Second token must look like a class selector (starts with .)\n // but we interpret it as a property access\n if (!propertyToken.value.startsWith('.')) {\n tokens.reset(mark);\n return null;\n }\n\n // Verify the next token is not a selector (to avoid consuming too many)\n // This helps distinguish \"#output.innerText\" from \"#box .child\"\n const peek2 = tokens.peek(1);\n if (peek2 && peek2.kind === 'selector') {\n // Could be a compound selector chain - only take first two\n }\n\n tokens.advance(); // consume property selector\n\n // Create property-path: #output.innerText\n // Extract property name without the leading dot\n const propertyName = propertyToken.value.slice(1);\n\n return createPropertyPath(createSelector(token.value), propertyName);\n }\n\n /**\n * Match a group pattern token (optional sequence).\n * When the group's leading marker isn't at the current position, scans ahead\n * up to MAX_MARKER_SCAN tokens to find it. This allows unmarked tokens\n * (e.g., a value like 'hello') to sit between groups without blocking later\n * marker matches.\n */\n private matchGroupToken(\n tokens: TokenStream,\n patternToken: PatternToken & { type: 'group' },\n captured: Map<SemanticRole, SemanticValue>,\n parentStopMarkers?: Set<string>\n ): boolean {\n const mark = tokens.mark();\n const capturedBefore = new Set(captured.keys());\n\n const success = this.matchTokenSequence(\n tokens,\n patternToken.tokens,\n captured,\n parentStopMarkers\n );\n if (success) return true;\n\n // Reset from failed attempt\n tokens.reset(mark);\n for (const role of captured.keys()) {\n if (!capturedBefore.has(role)) captured.delete(role);\n }\n\n if (!patternToken.optional) return false;\n\n // Marker scan: look ahead for the group's leading marker past intervening tokens.\n // This handles cases like \"types 'hello' into #search\" where 'hello' blocks the\n // 'into' marker from being found at the current position.\n const leadingMarker = this.getGroupLeadingMarker(patternToken);\n if (leadingMarker) {\n for (let offset = 1; offset <= PatternMatcher.MAX_MARKER_SCAN; offset++) {\n const ahead = tokens.peek(offset);\n if (!ahead) break;\n const aheadValue = (ahead.normalized || ahead.value).toLowerCase();\n if (aheadValue === leadingMarker) {\n this.logger.debug(\n ' >> MARKER SCAN: found',\n leadingMarker,\n 'at offset',\n offset,\n '- skipping intervening tokens'\n );\n // Advance past intervening tokens to reach the marker\n for (let s = 0; s < offset; s++) tokens.advance();\n\n // Retry group match from marker position\n const retrySuccess = this.matchTokenSequence(\n tokens,\n patternToken.tokens,\n captured,\n parentStopMarkers\n );\n if (retrySuccess) return true;\n\n // Retry failed — full reset\n tokens.reset(mark);\n for (const role of captured.keys()) {\n if (!capturedBefore.has(role)) captured.delete(role);\n }\n break;\n }\n }\n }\n\n return true; // Optional group, just skip\n }\n\n /**\n * Get the leading marker literal from an optional group.\n * Returns the lowercase marker value, or null if the group\n * doesn't start with a literal token (e.g., SOV groups where\n * the role comes before the marker).\n */\n private getGroupLeadingMarker(group: PatternToken & { type: 'group' }): string | null {\n const first = group.tokens[0];\n if (first?.type === 'literal') return first.value.toLowerCase();\n return null;\n }\n\n /**\n * Get the type of match for a token against a value.\n * Used for confidence calculation.\n */\n private getMatchType(\n token: LanguageToken,\n value: string\n ): 'exact' | 'normalized' | 'stem' | 'case-insensitive' | 'none' {\n // Exact match (highest confidence)\n if (token.value === value) return 'exact';\n\n // Explicit keyword map normalized match (high confidence)\n if (token.normalized === value) return 'normalized';\n\n // Morphologically normalized stem match (medium-high confidence)\n // Only accept if stem confidence is reasonable\n if (token.stem === value && token.stemConfidence !== undefined && token.stemConfidence >= 0.7) {\n return 'stem';\n }\n\n // Case-insensitive match for keywords (medium confidence)\n if (token.kind === 'keyword' && this.safeToLowerCase(token.value) === value.toLowerCase()) {\n return 'case-insensitive';\n }\n\n return 'none';\n }\n\n /**\n * Collect literal values from upcoming pattern tokens that act as stop markers\n * for greedy role capture. Returns the set of lowercase values.\n */\n private collectStopMarkers(patternTokens: PatternToken[], startIndex: number): Set<string> {\n const markers = new Set<string>();\n for (let j = startIndex; j < patternTokens.length; j++) {\n const pt = patternTokens[j];\n if (pt.type === 'literal') {\n markers.add(pt.value.toLowerCase());\n if (pt.alternatives) {\n for (const alt of pt.alternatives) {\n markers.add(alt.toLowerCase());\n }\n }\n break;\n }\n if (pt.type === 'group') {\n for (const gt of pt.tokens) {\n if (gt.type === 'literal') {\n markers.add(gt.value.toLowerCase());\n if (gt.alternatives) {\n for (const alt of gt.alternatives) {\n markers.add(alt.toLowerCase());\n }\n }\n break;\n }\n }\n // For optional groups, continue scanning past them so the greedy\n // capture also sees subsequent required literals (e.g., the SOV verb\n // keyword after an optional WHERE group).\n if (!pt.optional) break;\n }\n }\n return markers;\n }\n\n /**\n * Check if a token matches any stop marker for greedy capture.\n */\n private isStopMarker(token: LanguageToken, stopMarkers: Set<string>): boolean {\n if (stopMarkers.size === 0) return false;\n // Check both raw value and normalized form against stop markers.\n // Pattern literals use native keywords (e.g., '選択') while tokenizers may\n // set normalized to the English equivalent (e.g., 'select'). Both must match.\n if (stopMarkers.has(token.value.toLowerCase())) return true;\n if (token.normalized && stopMarkers.has(token.normalized.toLowerCase())) return true;\n return false;\n }\n\n /**\n * Track stem matches for confidence calculation.\n * This is set during matching and read during confidence calculation.\n */\n private stemMatchCount: number = 0;\n private totalKeywordMatches: number = 0;\n\n // ==========================================================================\n // Depth Limits for Expression Parsing (security hardening)\n // ==========================================================================\n\n /** Maximum depth for nested property access (e.g., a.b.c.d...) */\n private static readonly MAX_PROPERTY_DEPTH = 10;\n\n /** Maximum number of arguments in method calls */\n private static readonly MAX_METHOD_ARGS = 20;\n\n /**\n * Convert a language token to a semantic value.\n */\n private tokenToSemanticValue(token: LanguageToken): SemanticValue | null {\n switch (token.kind) {\n case 'selector':\n return createSelector(token.value);\n\n case 'literal':\n return this.parseLiteralValue(token.value);\n\n case 'keyword':\n // Keywords might be references or values\n const tokenValue = token.normalized || token.value;\n const lower = this.safeToLowerCase(tokenValue);\n if (isValidReference(lower)) {\n return createReference(lower);\n }\n return createLiteral(token.normalized || token.value);\n\n case 'identifier':\n // Check if it's a variable reference (:varname)\n // Note: :varname doesn't match the ReferenceValue union but is used as a\n // reference token downstream — this cast preserves existing behavior\n if (typeof token.value === 'string' && token.value.startsWith(':')) {\n return createReference(token.value as ReferenceValue['value']);\n }\n // Check if it's a built-in reference\n const identLower = this.safeToLowerCase(token.value);\n if (isValidReference(identLower)) {\n return createReference(identLower);\n }\n // Regular identifiers are variable references - use 'expression' type\n // which gets converted to 'identifier' AST nodes by semantic-integration.ts\n return { type: 'expression', raw: token.value } as const;\n\n case 'url':\n // URLs are treated as string literals (paths/URLs for navigation/fetch)\n return createLiteral(token.value, 'string');\n\n default:\n return null;\n }\n }\n\n /**\n * Parse a literal value (string, number, boolean).\n */\n private parseLiteralValue(value: string): SemanticValue {\n // String literal\n if (\n value.startsWith('\"') ||\n value.startsWith(\"'\") ||\n value.startsWith('`') ||\n value.startsWith('「')\n ) {\n const inner = value.slice(1, -1);\n return createLiteral(inner, 'string');\n }\n\n // Boolean\n if (value === 'true') return createLiteral(true, 'boolean');\n if (value === 'false') return createLiteral(false, 'boolean');\n\n // Duration (number with suffix)\n const durationMatch = value.match(/^(\\d+(?:\\.\\d+)?)(ms|s|m|h)?$/);\n if (durationMatch) {\n const num = parseFloat(durationMatch[1]);\n const unit = durationMatch[2];\n if (unit) {\n return createLiteral(value, 'duration');\n }\n return createLiteral(num, 'number');\n }\n\n // Plain number\n const num = parseFloat(value);\n if (!isNaN(num)) {\n return createLiteral(num, 'number');\n }\n\n // Default to string\n return createLiteral(value, 'string');\n }\n\n /**\n * Apply extraction rules to fill in static values and defaults for missing roles.\n */\n private applyExtractionRules(\n pattern: LanguagePattern,\n captured: Map<SemanticRole, SemanticValue>\n ): void {\n for (const [role, rule] of Object.entries(pattern.extraction)) {\n if (!captured.has(role as SemanticRole)) {\n if (rule.value !== undefined) {\n // Static value extraction (e.g., action: { value: \"toggle\" })\n captured.set(role as SemanticRole, { type: 'literal', value: rule.value });\n } else if (rule.default) {\n captured.set(role as SemanticRole, rule.default);\n }\n }\n }\n }\n\n /**\n * Check if a pattern token is optional.\n */\n private isOptional(patternToken: PatternToken): boolean {\n return patternToken.type !== 'literal' && patternToken.optional === true;\n }\n\n /**\n * Calculate confidence score for a match (0-1).\n *\n * Confidence is reduced for:\n * - Stem matches (morphological normalization has inherent uncertainty)\n * - Missing optional roles (but less penalty if role has a default value)\n *\n * Confidence is increased for:\n * - VSO languages (Arabic) when pattern starts with a verb\n */\n private calculateConfidence(\n pattern: LanguagePattern,\n captured: Map<SemanticRole, SemanticValue>\n ): number {\n let score = 0;\n let maxScore = 0;\n\n // Helper to check if a role has a default value in extraction rules\n const hasDefault = (role: SemanticRole): boolean => {\n return pattern.extraction?.[role]?.default !== undefined;\n };\n\n // Score based on captured roles\n for (const token of pattern.template.tokens) {\n if (token.type === 'role') {\n maxScore += 1;\n if (captured.has(token.role)) {\n score += 1;\n }\n } else if (token.type === 'group') {\n // Group tokens are optional - weight depends on whether they have defaults\n for (const subToken of token.tokens) {\n if (subToken.type === 'role') {\n const roleHasDefault = hasDefault(subToken.role);\n const weight = 0.8; // Optional roles: 80% weight\n maxScore += weight;\n\n if (captured.has(subToken.role)) {\n // Role was explicitly provided by user\n score += weight;\n } else if (roleHasDefault) {\n // Role has a default - give 60% partial credit since command is semantically complete\n // This prevents penalizing common patterns like \"toggle .active\" (default: me)\n score += weight * 0.6;\n }\n // If no default and not captured, score += 0 (true penalty for missing info)\n }\n }\n }\n }\n\n let baseConfidence = maxScore > 0 ? score / maxScore : 1;\n\n // Apply penalty for stem matches\n // Each stem match reduces confidence slightly (e.g., 5% per stem match)\n // This ensures exact matches are preferred over morphological matches\n if (this.stemMatchCount > 0 && this.totalKeywordMatches > 0) {\n const stemPenalty = (this.stemMatchCount / this.totalKeywordMatches) * 0.15;\n baseConfidence = Math.max(0.5, baseConfidence - stemPenalty);\n }\n\n // Apply VSO confidence boost for Arabic verb-first patterns\n const vsoBoost = this.calculateVSOConfidenceBoost(pattern);\n baseConfidence = Math.min(1.0, baseConfidence + vsoBoost);\n\n // Apply preposition disambiguation adjustment for Arabic\n const prepositionAdjustment = this.arabicPrepositionDisambiguation(pattern, captured);\n baseConfidence = Math.max(0.0, Math.min(1.0, baseConfidence + prepositionAdjustment));\n\n return baseConfidence;\n }\n\n /**\n * Calculate confidence boost for VSO (Verb-Subject-Object) language patterns.\n * Arabic naturally uses VSO word order, so patterns that start with a verb\n * should receive a confidence boost.\n *\n * Returns +0.15 confidence boost if:\n * - Language is Arabic ('ar')\n * - Pattern's first token is a verb keyword\n *\n * @param pattern The language pattern being matched\n * @returns Confidence boost (0 or 0.15)\n */\n private calculateVSOConfidenceBoost(pattern: LanguagePattern): number {\n // Only apply to Arabic\n if (pattern.language !== 'ar') {\n return 0;\n }\n\n // Check if first token in pattern is a literal (keyword)\n const firstToken = pattern.template.tokens[0];\n if (!firstToken || firstToken.type !== 'literal') {\n return 0;\n }\n\n // List of Arabic verb keywords (command verbs)\n const ARABIC_VERBS = new Set([\n 'بدل',\n 'غير',\n 'أضف',\n 'أزل',\n 'ضع',\n 'اجعل',\n 'عين',\n 'زد',\n 'انقص',\n 'سجل',\n 'أظهر',\n 'أخف',\n 'شغل',\n 'أرسل',\n 'ركز',\n 'شوش',\n 'توقف',\n 'انسخ',\n 'احذف',\n 'اصنع',\n 'انتظر',\n 'انتقال',\n 'أو',\n ]);\n\n // Check if first token value is a verb\n if (ARABIC_VERBS.has(firstToken.value)) {\n return 0.15;\n }\n\n // Check alternatives\n if (firstToken.alternatives) {\n for (const alt of firstToken.alternatives) {\n if (ARABIC_VERBS.has(alt)) {\n return 0.15;\n }\n }\n }\n\n return 0;\n }\n\n /**\n * Arabic preposition disambiguation for confidence adjustment.\n *\n * Different Arabic prepositions are more or less natural for different semantic roles:\n * - على (on/upon) is preferred for patient/target roles (element selectors)\n * - إلى (to) is preferred for destination roles\n * - من (from) is preferred for source roles\n * - في (in) is preferred for location roles\n *\n * This method analyzes the prepositions used with captured semantic roles and\n * adjusts confidence based on idiomaticity:\n * - +0.10 for highly idiomatic preposition choices\n * - -0.10 for less natural preposition choices\n *\n * @param pattern The language pattern being matched\n * @param captured The captured semantic values\n * @returns Confidence adjustment (-0.10 to +0.10)\n */\n private arabicPrepositionDisambiguation(\n pattern: LanguagePattern,\n captured: Map<SemanticRole, SemanticValue>\n ): number {\n // Only apply to Arabic\n if (pattern.language !== 'ar') {\n return 0;\n }\n\n let adjustment = 0;\n\n // Preferred prepositions for each semantic role\n // Only including roles that commonly use prepositions in Arabic\n const PREFERRED_PREPOSITIONS: Partial<Record<SemanticRole, string[]>> = {\n patient: ['على'], // element selectors prefer على (on/upon)\n destination: ['إلى', 'الى'], // destination prefers إلى (to)\n source: ['من'], // source prefers من (from)\n agent: ['من'], // agent/by prefers من (from/by)\n manner: ['ب'], // manner prefers ب (with/by)\n style: ['ب'], // style prefers ب (with)\n goal: ['إلى', 'الى'], // target state prefers إلى (to)\n method: ['ب'], // method prefers ب (with/by)\n };\n\n // Check each captured role for preposition metadata\n for (const [role, value] of captured.entries()) {\n // Skip if no preferred prepositions defined for this role\n const preferred = PREFERRED_PREPOSITIONS[role];\n if (!preferred || preferred.length === 0) {\n continue;\n }\n\n // Check if the value has preposition metadata (from Arabic tokenizer)\n // This metadata is attached when a preposition particle token is consumed\n const metadata =\n 'metadata' in value ? (value as { metadata: Record<string, unknown> }).metadata : undefined;\n if (metadata && typeof metadata.prepositionValue === 'string') {\n const usedPreposition = metadata.prepositionValue;\n\n // Check if the used preposition is in the preferred list\n if (preferred.includes(usedPreposition)) {\n // Idiomatic choice - boost confidence\n adjustment += 0.1;\n } else {\n // Less natural choice - reduce confidence\n adjustment -= 0.1;\n }\n }\n }\n\n // Cap total adjustment at ±0.10 (even if multiple roles analyzed)\n return Math.max(-0.1, Math.min(0.1, adjustment));\n }\n\n // ===========================================================================\n // English Idiom Support - Noise Word Handling\n // ===========================================================================\n\n /**\n * Noise words that can be skipped in English for more natural syntax.\n * - \"the\" before selectors: \"toggle the .active\" → \"toggle .active\"\n * - \"class\" after class selectors: \"add the .visible class\" → \"add .visible\"\n */\n private static readonly ENGLISH_NOISE_WORDS = new Set(['the', 'a', 'an']);\n\n /**\n * Skip noise words like \"the\" before selectors.\n * This enables more natural English syntax like \"toggle the .active\".\n */\n private skipNoiseWords(tokens: TokenStream): void {\n const token = tokens.peek();\n if (!token) return;\n\n const tokenLower = this.safeToLowerCase(token.value);\n\n // Check if current token is a noise word (like \"the\")\n if (PatternMatcher.ENGLISH_NOISE_WORDS.has(tokenLower)) {\n // Look ahead to see if the next token is a selector\n const mark = tokens.mark();\n tokens.advance();\n const nextToken = tokens.peek();\n\n if (nextToken && nextToken.kind === 'selector') {\n // Keep the position after \"the\" - effectively skipping it\n return;\n }\n\n // Not followed by a selector, revert\n tokens.reset(mark);\n }\n\n // Also handle \"class\" after class selectors: \".visible class\" → \".visible\"\n // This is handled when the selector has already been consumed,\n // so we check if current token is \"class\" and skip it\n if (tokenLower === 'class') {\n // Skip \"class\" as it's just noise after a class selector\n tokens.advance();\n }\n }\n\n /**\n * Extract event modifiers from the token stream.\n * Event modifiers are .once, .debounce(N), .throttle(N), .queue(strategy)\n * that can appear after event names.\n *\n * Returns EventModifiers object or undefined if no modifiers found.\n */\n extractEventModifiers(tokens: TokenStream): import('../types').EventModifiers | undefined {\n const modifiers: {\n once?: boolean;\n debounce?: number;\n throttle?: number;\n queue?: 'first' | 'last' | 'all' | 'none';\n from?: SemanticValue;\n } = {};\n\n let foundModifier = false;\n\n // Consume all consecutive event modifier tokens\n while (!tokens.isAtEnd()) {\n const token = tokens.peek();\n if (!token || token.kind !== 'event-modifier') {\n break;\n }\n\n const metadata = token.metadata as\n | { modifierName: string; value?: number | string }\n | undefined;\n if (!metadata) {\n break;\n }\n\n foundModifier = true;\n\n switch (metadata.modifierName) {\n case 'once':\n modifiers.once = true;\n break;\n case 'debounce':\n if (typeof metadata.value === 'number') {\n modifiers.debounce = metadata.value;\n }\n break;\n case 'throttle':\n if (typeof metadata.value === 'number') {\n modifiers.throttle = metadata.value;\n }\n break;\n case 'queue':\n if (\n metadata.value === 'first' ||\n metadata.value === 'last' ||\n metadata.value === 'all' ||\n metadata.value === 'none'\n ) {\n modifiers.queue = metadata.value;\n }\n break;\n }\n\n tokens.advance();\n }\n\n return foundModifier ? modifiers : undefined;\n }\n}\n\n// =============================================================================\n// Convenience Functions\n// =============================================================================\n\n/**\n * Singleton pattern matcher instance.\n */\nexport const patternMatcher = new PatternMatcher();\n\n/**\n * Match tokens against a pattern.\n */\nexport function matchPattern(\n tokens: TokenStream,\n pattern: LanguagePattern\n): PatternMatchResult | null {\n return patternMatcher.matchPattern(tokens, pattern);\n}\n\n/**\n * Match tokens against multiple patterns, return best match.\n */\nexport function matchBest(\n tokens: TokenStream,\n patterns: LanguagePattern[]\n): PatternMatchResult | null {\n return patternMatcher.matchBest(tokens, patterns);\n}\n","/**\n * Pattern Generator\n *\n * Generates LanguagePattern objects from CommandSchema + LanguageProfile.\n * This solves the pattern explosion problem by deriving patterns from\n * high-level schema definitions rather than hand-writing each one.\n */\n\nimport type { LanguagePattern, PatternToken, ExtractionRule } from '../core/types';\nimport type { CommandSchema, RoleSpec } from '../schema';\n\n/**\n * Minimal language profile interface for pattern generation.\n */\nexport interface PatternGenLanguageProfile {\n readonly code: string;\n readonly wordOrder: 'SVO' | 'SOV' | 'VSO' | 'VOS' | 'OSV' | 'OVS' | 'free';\n readonly keywords: Record<string, { primary: string; alternatives?: string[] }>;\n readonly roleMarkers?: Record<\n string,\n { primary: string; alternatives?: string[]; position?: 'before' | 'after' }\n >;\n}\n\n/**\n * Configuration for pattern generation.\n */\nexport interface GeneratorConfig {\n /** Base priority for generated patterns (default: 100) */\n readonly basePriority?: number;\n /** Include optional role variants (default: true) */\n readonly includeOptionalVariants?: boolean;\n}\n\nconst defaultConfig: GeneratorConfig = {\n basePriority: 100,\n includeOptionalVariants: true,\n};\n\n/**\n * Generate a language pattern from a command schema and language profile.\n *\n * @param schema - Command schema defining the command structure\n * @param profile - Language profile with word order and keywords\n * @param config - Optional configuration\n * @returns Generated language pattern\n */\nexport function generatePattern(\n schema: CommandSchema,\n profile: PatternGenLanguageProfile,\n config: GeneratorConfig = defaultConfig\n): LanguagePattern {\n const id = `${schema.action}-${profile.code}-generated`;\n const priority = config.basePriority ?? 100;\n\n // Get keyword translation\n const keyword = profile.keywords[schema.action];\n if (!keyword) {\n throw new Error(`No keyword translation for '${schema.action}' in ${profile.code}`);\n }\n\n // Build tokens based on word order\n const tokens = buildTokens(schema, profile, keyword.primary, keyword.alternatives);\n\n // Build extraction rules\n const extraction = buildExtractionRules(schema, profile);\n\n // Build format string for documentation\n const format = buildFormatString(schema, profile, keyword.primary);\n\n return {\n id,\n language: profile.code,\n command: schema.action,\n priority,\n template: {\n format,\n tokens,\n },\n extraction,\n };\n}\n\n/**\n * Build pattern tokens based on word order and role markers.\n */\nfunction buildTokens(\n schema: CommandSchema,\n profile: PatternGenLanguageProfile,\n keyword: string,\n alternatives?: string[]\n): PatternToken[] {\n const tokens: PatternToken[] = [];\n const keywordToken: PatternToken = {\n type: 'literal',\n value: keyword,\n ...(alternatives?.length && { alternatives }),\n };\n\n // Sort roles by word order\n const sortedRoles = sortRolesByWordOrder(schema.roles, profile.wordOrder);\n\n // For SVO: [action, patient, destination, source, ...]\n if (profile.wordOrder === 'SVO') {\n // Add keyword first\n tokens.push(keywordToken);\n\n // Add roles with markers\n for (const role of sortedRoles) {\n addRoleWithMarker(tokens, role, profile);\n }\n }\n // For SOV: [patient, destination, source, ..., action]\n else if (profile.wordOrder === 'SOV') {\n // Add roles with markers first\n for (const role of sortedRoles) {\n addRoleWithMarker(tokens, role, profile);\n }\n\n // Add keyword last\n tokens.push(keywordToken);\n }\n // For VSO: [action, destination, patient, source, ...]\n else if (profile.wordOrder === 'VSO') {\n // Add keyword first\n tokens.push(keywordToken);\n\n // Add roles with markers\n for (const role of sortedRoles) {\n addRoleWithMarker(tokens, role, profile);\n }\n }\n // Other word orders can be added as needed\n else {\n // Fallback to SVO-style ordering\n tokens.push(keywordToken);\n for (const role of sortedRoles) {\n addRoleWithMarker(tokens, role, profile);\n }\n }\n\n return tokens;\n}\n\n/**\n * Add a role token with its grammatical marker if needed.\n * For optional roles, wraps the role + marker in a group.\n */\nfunction addRoleWithMarker(\n tokens: PatternToken[],\n roleSpec: RoleSpec,\n profile: PatternGenLanguageProfile\n): void {\n const marker = getMarkerForRole(roleSpec, profile);\n const isOptional = !roleSpec.required;\n\n // Build the role token\n const roleToken: PatternToken = {\n type: 'role',\n role: roleSpec.role,\n optional: isOptional,\n expectedTypes: roleSpec.expectedTypes,\n ...(roleSpec.greedy && { greedy: true }),\n };\n\n if (marker) {\n const markerInfo = profile.roleMarkers?.[roleSpec.role];\n // Priority: schema markerPosition → profile roleMarkers position → word-order default\n const defaultPosition = profile.wordOrder === 'SOV' ? 'after' : 'before';\n const position = roleSpec.markerPosition ?? markerInfo?.position ?? defaultPosition;\n\n if (isOptional) {\n // Optional role: wrap marker + role in optional group\n if (position === 'before') {\n tokens.push({\n type: 'group',\n optional: true,\n tokens: [{ type: 'literal', value: marker }, roleToken],\n });\n } else {\n tokens.push({\n type: 'group',\n optional: true,\n tokens: [roleToken, { type: 'literal', value: marker }],\n });\n }\n } else {\n // Required role: add marker + role separately\n if (position === 'before') {\n tokens.push({ type: 'literal', value: marker });\n tokens.push(roleToken);\n } else {\n tokens.push(roleToken);\n tokens.push({ type: 'literal', value: marker });\n }\n }\n } else {\n // No marker - just add the role\n tokens.push(roleToken);\n }\n}\n\n/**\n * Get the grammatical marker for a role from the profile.\n */\nfunction getMarkerForRole(\n roleSpec: RoleSpec,\n profile: PatternGenLanguageProfile\n): string | undefined {\n // Check for role-specific override first\n if (roleSpec.markerOverride?.[profile.code]) {\n return roleSpec.markerOverride[profile.code];\n }\n\n // Use profile's default marker for this role\n return profile.roleMarkers?.[roleSpec.role]?.primary;\n}\n\n/**\n * Sort roles by word order for pattern building.\n */\nfunction sortRolesByWordOrder(roles: RoleSpec[], wordOrder: string): RoleSpec[] {\n const sorted = [...roles];\n\n if (wordOrder === 'SVO') {\n // Sort by svoPosition (higher = earlier)\n sorted.sort((a, b) => (b.svoPosition ?? 0) - (a.svoPosition ?? 0));\n } else if (wordOrder === 'SOV') {\n // Sort by sovPosition (higher = earlier)\n sorted.sort((a, b) => (b.sovPosition ?? 0) - (a.sovPosition ?? 0));\n }\n // VSO and others use SVO-style ordering\n\n return sorted;\n}\n\n/**\n * Build extraction rules for capturing role values during parsing.\n */\nfunction buildExtractionRules(\n schema: CommandSchema,\n profile: PatternGenLanguageProfile\n): Record<string, ExtractionRule> {\n const rules: Record<string, ExtractionRule> = {};\n\n for (const roleSpec of schema.roles) {\n // Build the rule object correctly with readonly properties\n const marker = getMarkerForRole(roleSpec, profile);\n\n const rule: ExtractionRule = {\n ...(roleSpec.default !== undefined && { default: roleSpec.default }),\n ...(marker && { marker }),\n };\n\n rules[roleSpec.role] = rule;\n }\n\n return rules;\n}\n\n/**\n * Build a human-readable format string for the pattern.\n */\nfunction buildFormatString(\n schema: CommandSchema,\n profile: PatternGenLanguageProfile,\n keyword: string\n): string {\n const parts: string[] = [];\n\n if (profile.wordOrder === 'SVO' || profile.wordOrder === 'VSO') {\n parts.push(keyword);\n }\n\n for (const role of schema.roles) {\n const marker = getMarkerForRole(role, profile);\n const roleName = `{${role.role}}`;\n\n if (marker) {\n const markerInfo = profile.roleMarkers?.[role.role];\n if (markerInfo?.position === 'after') {\n parts.push(`${roleName} ${marker}`);\n } else {\n parts.push(`${marker} ${roleName}`);\n }\n } else {\n parts.push(roleName);\n }\n }\n\n if (profile.wordOrder === 'SOV') {\n parts.push(keyword);\n }\n\n return parts.join(' ');\n}\n\n/**\n * Generate multiple pattern variants (with and without optional roles).\n */\nexport function generatePatternVariants(\n schema: CommandSchema,\n profile: PatternGenLanguageProfile,\n config: GeneratorConfig = defaultConfig\n): LanguagePattern[] {\n const patterns: LanguagePattern[] = [];\n\n // Main pattern (all roles)\n patterns.push(generatePattern(schema, profile, config));\n\n // TODO: Generate variants with optional roles omitted\n // This can be added later when needed\n\n return patterns;\n}\n","/**\n * Generalized Grammar System for Multilingual Hyperscript\n *\n * This system abstracts grammatical patterns across language families,\n * enabling deep multilingual support without per-language hardcoding.\n *\n * Key Linguistic Concepts:\n * - Word Order: SVO, SOV, VSO (and variations)\n * - Adposition Type: Preposition (English) vs Postposition (Japanese/Korean)\n * - Morphology: Isolating (Chinese) vs Agglutinative (Turkish) vs Fusional (Arabic)\n * - Text Direction: LTR vs RTL\n */\n\n// =============================================================================\n// Core Types\n// =============================================================================\n\n/**\n * Semantic roles in hyperscript commands.\n * These are universal across all 13 supported languages - only the surface form changes.\n *\n * ## Core Thematic Roles (from linguistic theory)\n * | Role | Usage | Purpose | Example |\n * |-------------|-------|-----------------------------|---------------------------|\n * | action | 100% | Command verb | toggle, put, fetch |\n * | patient | 90% | What is acted upon | .active, #count |\n * | destination | 40% | Where something goes | into #output, to .class |\n * | source | 13% | Where something comes from | from #input, from URL |\n * | event | 106% | Trigger events | click, keydown, submit |\n * | condition | 8% | Boolean expressions | if x > 5, when visible |\n * | agent | 0% | Who performs action | Reserved for future use |\n * | goal | 1% | Target value/state | to 'red' (in transition) |\n *\n * ## Quantitative Roles (answer \"how much/long\")\n * | Role | Usage | Purpose | Example |\n * |----------|-------|----------------|----------------------|\n * | quantity | 7% | Numeric amount | by 5, 3 times |\n * | duration | 1% | Time span | for 5 seconds, 500ms |\n *\n * ## Adverbial/Modifier Roles (answer \"how/by what means\")\n * | Role | Usage | Purpose | Example |\n * |--------------|-------|---------------------------|-------------------|\n * | style | 2% | Animation/behavior | with fade |\n * | manner | 2% | Insertion position | before, after |\n * | method | 1% | HTTP method/technique | via POST, as GET |\n * | responseType | 1% | Response format | as json, as html |\n *\n * ## Control Flow Roles\n * | Role | Usage | Purpose | Example |\n * |----------|-------|--------------|-----------------------|\n * | loopType | 6% | Loop variant | forever, until, times |\n *\n * ## Design Notes\n * - Low-usage roles (agent, goal, method, responseType) are intentionally kept for:\n * - Linguistic completeness across all 13 languages\n * - Future extensibility (AI agents, server-side execution)\n * - Command-specific semantics (fetch, transition)\n * - Each role has distinct grammatical markers per language (see profiles/index.ts)\n * - Usage percentages based on pattern database analysis\n */\nexport type SemanticRole =\n // Core thematic roles\n | 'action' // The command/verb (increment, put, toggle)\n | 'agent' // Who/what performs action (reserved for future: AI agents, server-side)\n | 'patient' // What is acted upon (the counter, .active)\n | 'source' // Origin (from #input, from URL)\n | 'destination' // Target location (into #output, to .class)\n | 'goal' // Target value/state (to 'red', to 100)\n | 'event' // Trigger (click, input, keydown)\n | 'condition' // Boolean expression (if x > 5)\n // Quantitative roles\n | 'quantity' // Numeric amount (by 5, 3 times)\n | 'duration' // Time span (for 5 seconds, over 500ms)\n // Adverbial roles\n | 'responseType' // Response format (as json, as text, as html)\n | 'method' // HTTP method/technique (via POST, using GET)\n | 'style' // Visual/behavioral manner (with fade, smoothly)\n | 'manner' // Insertion position (before, after)\n // Control flow roles\n | 'loopType' // Loop variant: forever, times, for, while, until, until-event\n // Structural roles (for parser control)\n | 'continues'; // Continuation marker (then-chains)\n\n/**\n * Word order patterns\n * These represent the major typological categories\n */\nexport type WordOrder = 'SVO' | 'SOV' | 'VSO' | 'VOS' | 'OVS' | 'OSV' | 'free';\n\n/**\n * Where grammatical markers appear relative to their noun/verb\n */\nexport type AdpositionType = 'preposition' | 'postposition' | 'circumposition' | 'none';\n\n/**\n * Morphological typology - how words are constructed\n */\nexport type MorphologyType =\n | 'isolating' // Chinese - no inflection, word order matters\n | 'agglutinative' // Turkish, Japanese - morphemes stack predictably\n | 'fusional' // Arabic, Spanish - morphemes blend together\n | 'polysynthetic'; // Quechua - complex words encode full sentences\n\n/**\n * A grammatical marker (particle, case ending, preposition)\n */\nexport interface GrammaticalMarker {\n form: string; // The actual text (を, に, to, 的)\n role: SemanticRole; // What semantic role it marks\n position: AdpositionType; // Where it appears\n required: boolean; // Is it mandatory?\n alternatives?: string[]; // Alternative forms (e.g., 을/를 in Korean)\n}\n\n/**\n * Metadata for preserving line structure during translation.\n * Tracks indentation and blank lines so output maintains the same format.\n */\nexport interface LineMetadata {\n /** Trimmed line content (empty string for blank lines) */\n content: string;\n /** Leading whitespace (tabs/spaces) from original line */\n originalIndent: string;\n /** True if the line was empty or whitespace-only */\n isBlank: boolean;\n}\n\n// =============================================================================\n// Language Profile\n// =============================================================================\n\n/**\n * Complete grammatical profile for a language\n * This captures the essential typological features needed for transformation\n */\nexport interface LanguageProfile {\n code: string; // ISO 639-1 code\n name: string; // Native name\n\n // Typological features\n wordOrder: WordOrder;\n adpositionType: AdpositionType;\n morphology: MorphologyType;\n direction: 'ltr' | 'rtl';\n\n // Grammatical markers for each semantic role\n markers: GrammaticalMarker[];\n\n // Role ordering - which semantic roles come in what order\n // E.g., Japanese: ['patient', 'source', 'destination', 'action']\n // E.g., English: ['action', 'patient', 'source', 'destination']\n canonicalOrder: SemanticRole[];\n\n // Special rules\n rules?: GrammarRule[];\n}\n\n/**\n * Pattern for transforming hyperscript structures\n */\nexport interface GrammarRule {\n name: string;\n description: string;\n\n // Pattern matching (in canonical English form)\n match: PatternMatcher;\n\n // How to transform for this language\n transform: PatternTransform;\n\n // Priority (higher = checked first)\n priority: number;\n}\n\n/**\n * Matches a hyperscript pattern\n */\nexport interface PatternMatcher {\n // Command type(s) this matches\n commands?: string[];\n\n // Required semantic roles\n requiredRoles: SemanticRole[];\n\n // Optional roles\n optionalRoles?: SemanticRole[];\n\n // Custom predicate for complex matching\n predicate?: (parsed: ParsedStatement) => boolean;\n}\n\n/**\n * Defines how to transform a matched pattern\n */\nexport interface PatternTransform {\n // Reorder roles for target language\n roleOrder: SemanticRole[];\n\n // Insert markers between roles\n insertMarkers?: boolean;\n\n // Custom transformation function\n custom?: (parsed: ParsedStatement, profile: LanguageProfile) => string;\n}\n\n// =============================================================================\n// Parsed Structures\n// =============================================================================\n\n/**\n * A parsed hyperscript statement broken into semantic components\n */\nexport interface ParsedStatement {\n type: 'event-handler' | 'command' | 'conditional' | 'loop';\n roles: Map<SemanticRole, ParsedElement>;\n original: string;\n}\n\n/**\n * A single element with its semantic role\n */\nexport interface ParsedElement {\n role: SemanticRole;\n value: string; // Original English value\n translated?: string; // Translated value\n isSelector?: boolean; // CSS selector (don't translate)\n isLiteral?: boolean; // Literal value (don't translate)\n}\n\n// =============================================================================\n// Universal Pattern Templates\n// =============================================================================\n\n/**\n * Universal templates for common hyperscript patterns\n * These define the semantic structure independent of surface form\n */\nexport const UNIVERSAL_PATTERNS = {\n // on click increment #count\n eventIncrement: {\n name: 'event-increment',\n roles: ['event', 'action', 'patient'] as SemanticRole[],\n english: 'on {event} {action} {patient}',\n },\n\n // put X into Y\n putInto: {\n name: 'put-into',\n roles: ['action', 'patient', 'destination'] as SemanticRole[],\n english: '{action} {patient} into {destination}',\n },\n\n // add .class to element\n addTo: {\n name: 'add-to',\n roles: ['action', 'patient', 'destination'] as SemanticRole[],\n english: '{action} {patient} to {destination}',\n },\n\n // toggle .class on element\n toggleOn: {\n name: 'toggle-on',\n roles: ['action', 'patient', 'destination'] as SemanticRole[],\n english: '{action} {patient} on {destination}',\n },\n\n // wait 2 seconds\n waitDuration: {\n name: 'wait-duration',\n roles: ['action', 'quantity'] as SemanticRole[],\n english: '{action} {quantity}',\n },\n\n // if condition then ... end\n conditional: {\n name: 'conditional',\n roles: ['action', 'condition'] as SemanticRole[],\n english: '{action} {condition} then ... end',\n },\n\n // fetch URL as type\n fetchAs: {\n name: 'fetch-as',\n roles: ['action', 'source', 'method'] as SemanticRole[],\n english: '{action} {source} as {method}',\n },\n\n // show element with animation\n showWith: {\n name: 'show-with',\n roles: ['action', 'patient', 'style'] as SemanticRole[],\n english: '{action} {patient} with {style}',\n },\n\n // transition property over duration\n transitionOver: {\n name: 'transition-over',\n roles: ['action', 'patient', 'duration'] as SemanticRole[],\n english: '{action} {patient} over {duration}',\n },\n} as const;\n\n// =============================================================================\n// Language Family Defaults\n// =============================================================================\n\n/**\n * Default profiles for major language families\n * Individual languages inherit and override these\n */\nexport const LANGUAGE_FAMILY_DEFAULTS: Record<string, Partial<LanguageProfile>> = {\n // Germanic (English, German, Dutch)\n germanic: {\n wordOrder: 'SVO',\n adpositionType: 'preposition',\n morphology: 'fusional',\n direction: 'ltr',\n canonicalOrder: [\n 'action',\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n ],\n },\n\n // Romance (Spanish, French, Italian, Portuguese)\n romance: {\n wordOrder: 'SVO',\n adpositionType: 'preposition',\n morphology: 'fusional',\n direction: 'ltr',\n canonicalOrder: [\n 'action',\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n ],\n },\n\n // Japonic (Japanese)\n japonic: {\n wordOrder: 'SOV',\n adpositionType: 'postposition',\n morphology: 'agglutinative',\n direction: 'ltr',\n canonicalOrder: [\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n 'action',\n ],\n },\n\n // Koreanic (Korean)\n koreanic: {\n wordOrder: 'SOV',\n adpositionType: 'postposition',\n morphology: 'agglutinative',\n direction: 'ltr',\n canonicalOrder: [\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n 'action',\n ],\n },\n\n // Turkic (Turkish, Azerbaijani)\n turkic: {\n wordOrder: 'SOV',\n adpositionType: 'postposition',\n morphology: 'agglutinative',\n direction: 'ltr',\n canonicalOrder: [\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n 'action',\n ],\n },\n\n // Sinitic (Chinese, Cantonese)\n sinitic: {\n wordOrder: 'SVO', // Topic-prominent, flexible\n adpositionType: 'preposition',\n morphology: 'isolating',\n direction: 'ltr',\n canonicalOrder: [\n 'action',\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n ],\n },\n\n // Semitic (Arabic, Hebrew)\n semitic: {\n wordOrder: 'VSO',\n adpositionType: 'preposition',\n morphology: 'fusional', // Root-pattern system\n direction: 'rtl',\n canonicalOrder: [\n 'action',\n 'agent',\n 'patient',\n 'destination',\n 'source',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n ],\n },\n\n // Austronesian (Indonesian, Tagalog)\n austronesian: {\n wordOrder: 'SVO',\n adpositionType: 'preposition',\n morphology: 'agglutinative',\n direction: 'ltr',\n canonicalOrder: [\n 'action',\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n ],\n },\n\n // Quechuan (Quechua)\n quechuan: {\n wordOrder: 'SOV',\n adpositionType: 'postposition',\n morphology: 'agglutinative', // Actually polysynthetic but simplified\n direction: 'ltr',\n canonicalOrder: [\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n 'action',\n ],\n },\n\n // Bantu (Swahili)\n bantu: {\n wordOrder: 'SVO',\n adpositionType: 'preposition',\n morphology: 'agglutinative',\n direction: 'ltr',\n canonicalOrder: [\n 'action',\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n ],\n },\n};\n\n// =============================================================================\n// Transformation Utilities\n// =============================================================================\n\n/**\n * Reorder semantic roles according to target language.\n * Includes a safety net to append any roles present in input\n * but missing from the target order, preventing data loss.\n */\nexport function reorderRoles(\n roles: Map<SemanticRole, ParsedElement>,\n targetOrder: SemanticRole[]\n): ParsedElement[] {\n const result: ParsedElement[] = [];\n const usedRoles = new Set<SemanticRole>();\n\n // 1. Add roles that are explicitly in the canonical order\n for (const role of targetOrder) {\n const element = roles.get(role);\n if (element) {\n result.push(element);\n usedRoles.add(role);\n }\n }\n\n // 2. Safety Net: Append any roles present in input but missing from target order\n // This prevents data loss (e.g., if 'manner' or 'instrument' isn't in the profile)\n for (const [role, element] of roles) {\n if (!usedRoles.has(role)) {\n result.push(element);\n }\n }\n\n return result;\n}\n\n/**\n * Insert grammatical markers between elements\n */\nexport function insertMarkers(\n elements: ParsedElement[],\n markers: GrammaticalMarker[],\n adpositionType: AdpositionType\n): string[] {\n const result: string[] = [];\n\n for (const element of elements) {\n const marker = markers.find(m => m.role === element.role);\n\n if (marker) {\n if (adpositionType === 'preposition') {\n // Marker before element: \"to element\"\n if (marker.form) result.push(marker.form);\n result.push(element.translated || element.value);\n } else if (adpositionType === 'postposition') {\n // Marker after element: \"element を\"\n result.push(element.translated || element.value);\n if (marker.form) result.push(marker.form);\n } else {\n result.push(element.translated || element.value);\n }\n } else {\n result.push(element.translated || element.value);\n }\n }\n\n return result;\n}\n\n/**\n * Intelligently joins tokens, handling agglutinative suffixes and prefixes.\n *\n * Rules:\n * 1. If a token ends with '-' (prefix marker), no space after it\n * 2. If a token starts with '-' (suffix marker), no space before it\n * 3. Removes the hyphen indicators from the final output\n *\n * Examples:\n * - ['#count', '-ta'] → '#countta' (Quechua accusative suffix)\n * - ['بـ-', 'الماوس'] → 'بـالماوس' (Arabic prefix attachment)\n * - ['value', 'を'] → 'value を' (Japanese particle, normal spacing)\n */\nexport function joinTokens(tokens: string[]): string {\n if (tokens.length === 0) return '';\n\n let result = '';\n\n for (let i = 0; i < tokens.length; i++) {\n const token = tokens[i];\n const nextToken = tokens[i + 1];\n\n // Check if current token is a prefix (ends with -)\n const isPrefix = token.endsWith('-');\n // Check if current token is a suffix (starts with -)\n const isSuffix = token.startsWith('-');\n\n // Get the display form (strip hyphen markers)\n let displayToken = token;\n if (isPrefix) displayToken = token.slice(0, -1);\n if (isSuffix) displayToken = token.substring(1);\n\n result += displayToken;\n\n // Determine if we need a space before the next token\n if (nextToken) {\n const nextIsSuffix = nextToken.startsWith('-');\n\n // Don't add space if:\n // - Current token is a prefix (ends with -)\n // - Next token is a suffix (starts with -)\n if (!isPrefix && !nextIsSuffix) {\n result += ' ';\n }\n }\n }\n\n return result;\n}\n\n/**\n * Transform a parsed statement to target language\n */\nexport function transformStatement(\n parsed: ParsedStatement,\n _sourceProfile: LanguageProfile,\n targetProfile: LanguageProfile\n): string {\n // 1. Reorder roles for target language\n const reordered = reorderRoles(parsed.roles, targetProfile.canonicalOrder);\n\n // 2. Insert grammatical markers\n const withMarkers = insertMarkers(reordered, targetProfile.markers, targetProfile.adpositionType);\n\n // 3. Join with intelligent spacing for agglutinative languages\n // (handles suffixes like -ta, prefixes like بـ-, etc.)\n return joinTokens(withMarkers);\n}\n","/**\n * Grammar Transformer - Dependency Injection Architecture\n *\n * Transforms statements between languages using injected dependencies.\n * This makes the transformer completely domain-agnostic.\n */\n\nimport type { LanguageProfile, ParsedElement, SemanticRole } from './types';\nimport { reorderRoles, insertMarkers, joinTokens } from './types';\nimport type { Dictionary } from '../interfaces/dictionary';\nimport type { ProfileProvider } from '../interfaces/profile-provider';\n\n/**\n * Configuration for grammar transformer.\n */\nexport interface TransformerConfig {\n /** Dictionary for keyword translation */\n readonly dictionary: Dictionary;\n\n /** Profile provider for grammar rules */\n readonly profileProvider: ProfileProvider;\n}\n\n/**\n * Generic grammar transformer using dependency injection.\n *\n * @example\n * const transformer = new GrammarTransformer({\n * dictionary: new InMemoryDictionary(translations),\n * profileProvider: new InMemoryProfileProvider(profiles)\n * });\n *\n * const japanese = transformer.transform('select name from users', 'en', 'ja');\n * // → \"users から name を 選択\"\n */\nexport class GrammarTransformer {\n private dictionary: Dictionary;\n private profileProvider: ProfileProvider;\n\n constructor(config: TransformerConfig) {\n this.dictionary = config.dictionary;\n this.profileProvider = config.profileProvider;\n }\n\n /**\n * Transform a statement from one language to another.\n *\n * @param input - Statement in source language\n * @param fromLanguage - Source language code\n * @param toLanguage - Target language code\n * @returns Transformed statement in target language\n *\n * @throws Error if profiles not found or translation fails\n */\n transform(input: string, fromLanguage: string, toLanguage: string): string {\n // Get language profiles\n const fromProfile = this.profileProvider.getProfile(fromLanguage);\n const toProfile = this.profileProvider.getProfile(toLanguage);\n\n if (!fromProfile) {\n throw new Error(`No profile found for language: ${fromLanguage}`);\n }\n if (!toProfile) {\n throw new Error(`No profile found for language: ${toLanguage}`);\n }\n\n // Parse statement to semantic roles\n const parsed = this.parseStatement(input, fromLanguage, fromProfile);\n\n // Translate each word\n const translated = this.translateRoles(parsed, fromLanguage, toLanguage);\n\n // Reorder and insert markers\n const reordered = reorderRoles(translated, toProfile.canonicalOrder);\n\n const withMarkers = insertMarkers(reordered, toProfile.markers, toProfile.adpositionType);\n\n return joinTokens(withMarkers);\n }\n\n /**\n * Parse statement into semantic roles.\n * This is a simplified generic parser - DSLs can provide custom parsers.\n */\n private parseStatement(\n input: string,\n language: string,\n profile: LanguageProfile\n ): Map<SemanticRole, string> {\n const roles = new Map<SemanticRole, string>();\n const tokens = input.split(/\\s+/);\n\n // Simple parsing: extract roles based on markers\n let i = 0;\n while (i < tokens.length) {\n const token = tokens[i];\n\n // Check if token is a marker\n const marker = profile.markers.find(m => m.form === token);\n\n if (marker) {\n // Next token is the value for this role\n if (i + 1 < tokens.length) {\n roles.set(marker.role, tokens[i + 1]);\n i += 2;\n } else {\n i++;\n }\n } else {\n // Look up token in dictionary to find its role\n const canonical = this.dictionary.lookup(token, language);\n\n if (canonical) {\n // Assume it's the action (command keyword)\n roles.set('action', canonical);\n } else {\n // Assume it's a value (selector, identifier, etc.)\n // Try to guess the role based on syntax\n if (token.startsWith('#') || token.startsWith('.')) {\n roles.set('patient', token);\n } else {\n // Default to patient for unknown values\n roles.set('patient', token);\n }\n }\n\n i++;\n }\n }\n\n return roles;\n }\n\n /**\n * Translate roles using injected dictionary.\n * Returns a Map of ParsedElement objects expected by reorderRoles.\n */\n private translateRoles(\n roles: Map<SemanticRole, string>,\n _fromLanguage: string,\n toLanguage: string\n ): Map<SemanticRole, ParsedElement> {\n const result = new Map<SemanticRole, ParsedElement>();\n\n for (const [role, value] of roles) {\n // Translate using dictionary\n const translated = this.dictionary.translate(value, toLanguage);\n\n // Create ParsedElement with role, value, and translated\n result.set(role, {\n role,\n value, // Original value\n translated: translated ?? value, // Translated value or original if no translation\n });\n }\n\n return result;\n }\n}\n","/**\n * Dictionary Interface - Keyword Translation\n *\n * Provides keyword translations between languages.\n * DSLs implement this to provide their domain-specific translations.\n */\n\n/**\n * Dictionary provides keyword translations between languages.\n */\nexport interface Dictionary {\n /**\n * Look up canonical form from localized keyword.\n *\n * @param localizedWord - Word in target language (e.g., 'トグル', 'alternar')\n * @param language - Language code\n * @returns Canonical form (e.g., 'toggle') or undefined\n *\n * @example\n * dictionary.lookup('トグル', 'ja') // → 'toggle'\n * dictionary.lookup('alternar', 'es') // → 'toggle'\n */\n lookup(localizedWord: string, language: string): string | undefined;\n\n /**\n * Translate canonical keyword to target language.\n *\n * @param canonical - Canonical form (e.g., 'toggle')\n * @param targetLanguage - Target language code\n * @returns Localized form or undefined\n *\n * @example\n * dictionary.translate('toggle', 'ja') // → 'トグル'\n * dictionary.translate('toggle', 'es') // → 'alternar'\n */\n translate(canonical: string, targetLanguage: string): string | undefined;\n\n /**\n * Get all translations of a word across all supported languages.\n *\n * @param word - Word to translate\n * @param sourceLanguage - Source language\n * @returns Map of language code to translation\n *\n * @example\n * dictionary.getAllTranslations('toggle', 'en')\n * // → { ja: 'トグル', es: 'alternar', ko: '토글', ... }\n */\n getAllTranslations(word: string, sourceLanguage: string): Record<string, string>;\n\n /**\n * Optional: Find what category a word belongs to.\n * Useful for organizing translations by domain (commands, modifiers, events, etc.).\n */\n getCategory?(word: string, language: string): string | undefined;\n}\n\n/**\n * Simple in-memory dictionary implementation.\n * Suitable for small DSLs or prototyping.\n */\nexport class InMemoryDictionary implements Dictionary {\n /**\n * @param translations - Map of language code to canonical→localized mappings\n *\n * @example\n * new InMemoryDictionary({\n * en: { select: 'select', insert: 'insert' },\n * es: { select: 'seleccionar', insert: 'insertar' },\n * ja: { select: '選択', insert: '挿入' }\n * })\n */\n constructor(private translations: Record<string, Record<string, string>>) {}\n\n lookup(word: string, language: string): string | undefined {\n const langDict = this.translations[language];\n if (!langDict) return undefined;\n\n // Reverse lookup: find key where value = word\n const wordLower = word.toLowerCase();\n for (const [canonical, localized] of Object.entries(langDict)) {\n if (localized.toLowerCase() === wordLower) {\n return canonical;\n }\n }\n return undefined;\n }\n\n translate(canonical: string, targetLanguage: string): string | undefined {\n return this.translations[targetLanguage]?.[canonical];\n }\n\n getAllTranslations(word: string, sourceLanguage: string): Record<string, string> {\n const canonical = this.lookup(word, sourceLanguage);\n if (!canonical) return {};\n\n const result: Record<string, string> = {};\n for (const [lang, dict] of Object.entries(this.translations)) {\n const translation = dict[canonical];\n if (translation) {\n result[lang] = translation;\n }\n }\n return result;\n }\n}\n\n/**\n * Null dictionary - no translations (useful for single-language DSLs).\n */\nexport class NullDictionary implements Dictionary {\n lookup(word: string, _language: string): string | undefined {\n return word; // Identity: word is its own canonical form\n }\n\n translate(canonical: string, _targetLanguage: string): string | undefined {\n return canonical; // Identity: no translation\n }\n\n getAllTranslations(word: string, _sourceLanguage: string): Record<string, string> {\n return { en: word }; // Only source language\n }\n}\n","/**\n * Profile Provider Interface - Language Profile Access\n *\n * Provides language profiles for grammar transformation.\n * DSLs implement this to provide their domain-specific profiles.\n */\n\nimport type { LanguageProfile } from '../grammar';\n\n/**\n * Provides language profiles for transformation.\n */\nexport interface ProfileProvider {\n /**\n * Get language profile by code.\n *\n * @param language - ISO 639-1 code (e.g., 'en', 'ja', 'es')\n * @returns Language profile or undefined if not supported\n *\n * @example\n * const profile = provider.getProfile('ja');\n * console.log(profile.wordOrder); // 'SOV'\n */\n getProfile(language: string): LanguageProfile | undefined;\n\n /**\n * Get all supported language codes.\n *\n * @returns Array of ISO 639-1 codes\n *\n * @example\n * provider.getSupportedLanguages() // → ['en', 'ja', 'es', 'ko']\n */\n getSupportedLanguages(): string[];\n\n /**\n * Check if a language is supported.\n *\n * @param language - Language code to check\n * @returns True if language is supported\n */\n hasLanguage(language: string): boolean;\n}\n\n/**\n * Simple in-memory profile provider.\n */\nexport class InMemoryProfileProvider implements ProfileProvider {\n /**\n * @param profiles - Map of language code to profile\n *\n * @example\n * new InMemoryProfileProvider({\n * en: { code: 'en', wordOrder: 'SVO', ... },\n * ja: { code: 'ja', wordOrder: 'SOV', ... }\n * })\n */\n constructor(private profiles: Record<string, LanguageProfile>) {}\n\n getProfile(language: string): LanguageProfile | undefined {\n return this.profiles[language];\n }\n\n getSupportedLanguages(): string[] {\n return Object.keys(this.profiles);\n }\n\n hasLanguage(language: string): boolean {\n return language in this.profiles;\n }\n}\n\n/**\n * Null profile provider - for DSLs that don't need grammar transformation.\n */\nexport class NullProfileProvider implements ProfileProvider {\n getProfile(_language: string): LanguageProfile | undefined {\n return undefined;\n }\n\n getSupportedLanguages(): string[] {\n return [];\n }\n\n hasLanguage(_language: string): boolean {\n return false;\n }\n}\n","/**\n * Reference Validation\n *\n * Configurable validation for reference values (me, you, it, result, etc.).\n * Domain DSLs can provide custom reference sets.\n */\n\n/**\n * Default set of valid references.\n * Covers the common hyperscript references; domain DSLs can extend or replace.\n */\nexport const DEFAULT_REFERENCES: ReadonlySet<string> = new Set([\n 'me',\n 'you',\n 'it',\n 'result',\n 'event',\n 'target',\n 'body',\n]);\n\n/**\n * Check if a value is a valid reference name.\n *\n * @param value - The string to check\n * @param referenceSet - Custom reference set (defaults to DEFAULT_REFERENCES)\n */\nexport function isValidReference(\n value: string,\n referenceSet: ReadonlySet<string> = DEFAULT_REFERENCES\n): boolean {\n return referenceSet.has(value);\n}\n","/**\n * Explicit Syntax Parser\n *\n * Parses the universal [command role:value ...] bracket syntax.\n * Domain-agnostic — schema validation is injectable via ParseExplicitOptions.\n *\n * Three parsing levels matching the ABNF grammar:\n * parseDocument() → parseCompound() → parseExplicit()\n * (multi-line) (chain ops) (single bracket)\n *\n * Syntax:\n * [command role1:value1 role2:value2 ...]\n * [cmd1 ...] then [cmd2 ...]\n * @annotation(value) [command ...]\n * #!lse 1.2\\n[cmd1 ...]\\n[cmd2 ...]\n */\n\nimport type {\n SemanticNode,\n SemanticValue,\n SemanticRole,\n ActionType,\n LoopVariant,\n Annotation,\n LSEEnvelope,\n CompoundSemanticNode,\n} from '../core/types';\nimport {\n createCommandNode,\n createEventHandlerNode,\n createConditionalNode,\n createLoopNode,\n createCompoundNode,\n createSelector,\n createLiteral,\n createReference,\n createFlag,\n} from '../core/types';\nimport type { Diagnostic } from '../generation/diagnostics';\nimport type { ParseExplicitOptions } from './types';\nimport { isValidReference, DEFAULT_REFERENCES } from './references';\n\n/** Structural role names whose bracket-enclosed values may be nested commands. */\nexport const STRUCTURAL_ROLES = new Set([\n 'body',\n 'then',\n 'else',\n 'condition',\n 'loop-body',\n 'variable',\n 'catch', // v1.2: try/catch/finally\n 'finally', // v1.2: try/catch/finally\n]);\n\n/**\n * Checks whether a bracket-enclosed value is a nested command (vs. an attribute selector).\n * A value starting with `[` is a nested command if the inner content (after stripping\n * outer `[]`) contains at least one ASCII space or `:` at bracket-depth 0.\n */\nfunction isNestedCommand(value: string): boolean {\n const inner = value.slice(1, -1);\n let depth = 0;\n for (const ch of inner) {\n if (ch === '[') depth++;\n else if (ch === ']') depth--;\n else if (depth === 0 && (ch === ' ' || ch === ':')) return true;\n }\n return false;\n}\n\n// =============================================================================\n// Explicit Syntax Parser\n// =============================================================================\n\n/**\n * Parse explicit bracket syntax into a semantic node.\n *\n * When `options.schemaLookup` is provided, validates roles against the\n * command's schema. When omitted, accepts any role names.\n */\nexport function parseExplicit(input: string, options: ParseExplicitOptions = {}): SemanticNode {\n const trimmed = input.trim();\n const collect = options.collectDiagnostics === true;\n const diagnostics: Diagnostic[] = [];\n\n if (!trimmed.startsWith('[') || !trimmed.endsWith(']')) {\n throw new Error('Explicit syntax must be wrapped in brackets: [command role:value ...]');\n }\n\n const content = trimmed.slice(1, -1).trim();\n if (!content) {\n throw new Error('Empty explicit statement');\n }\n\n const tokens = tokenizeExplicit(content);\n if (tokens.length === 0) {\n throw new Error('No command specified in explicit statement');\n }\n\n const command = tokens[0].toLowerCase() as ActionType;\n const roles = new Map<SemanticRole, SemanticValue>();\n const refSet = options.referenceSet ?? DEFAULT_REFERENCES;\n\n // Look up schema for role validation (undefined = skip validation)\n const schema = options.schemaLookup?.getSchema(command);\n const validRoleNames = schema ? new Set(schema.roles.map(r => r.role)) : null;\n\n // Parse role:value pairs and flags\n for (let i = 1; i < tokens.length; i++) {\n const token = tokens[i];\n\n // Boolean flag: +flag-name or ~flag-name\n if (token.startsWith('+') || token.startsWith('~')) {\n const enabled = token.startsWith('+');\n const flagName = token.slice(1);\n if (!flagName) {\n if (collect) {\n diagnostics.push({\n severity: 'error',\n code: 'EMPTY_FLAG',\n message: `Empty flag name: \"${token}\"`,\n source: 'schema',\n });\n continue;\n }\n throw new Error(`Empty flag name: \"${token}\"`);\n }\n if (validRoleNames && !validRoleNames.has(flagName as SemanticRole)) {\n const roleList = [...validRoleNames].join(', ');\n if (collect) {\n diagnostics.push({\n severity: 'error',\n code: 'UNKNOWN_FLAG',\n message: `Unknown flag \"${flagName}\" for command \"${command}\"`,\n source: 'schema',\n suggestions: [...validRoleNames].map(r => `+${r}`),\n });\n // Still add the flag so the node is usable\n roles.set(flagName as SemanticRole, createFlag(flagName, enabled));\n continue;\n }\n throw new Error(\n `Unknown flag \"${flagName}\" for command \"${command}\". Valid roles: ${roleList}`\n );\n }\n roles.set(flagName as SemanticRole, createFlag(flagName, enabled));\n continue;\n }\n\n const colonIndex = token.indexOf(':');\n\n if (colonIndex === -1) {\n if (collect) {\n diagnostics.push({\n severity: 'error',\n code: 'INVALID_ROLE_FORMAT',\n message: `Invalid role format: \"${token}\". Expected role:value or +flag`,\n source: 'schema',\n });\n continue;\n }\n throw new Error(`Invalid role format: \"${token}\". Expected role:value or +flag`);\n }\n\n const roleName = token.slice(0, colonIndex);\n\n // Validate role name against schema (skip for structural roles)\n if (\n validRoleNames &&\n !STRUCTURAL_ROLES.has(roleName) &&\n !validRoleNames.has(roleName as SemanticRole)\n ) {\n const roleList = [...validRoleNames].join(', ');\n if (collect) {\n diagnostics.push({\n severity: 'error',\n code: 'UNKNOWN_ROLE',\n message: `Unknown role \"${roleName}\" for command \"${command}\"`,\n source: 'schema',\n suggestions: [...validRoleNames],\n });\n // Still parse and add the role so the node is usable\n } else {\n throw new Error(\n `Unknown role \"${roleName}\" for command \"${command}\". Valid roles: ${roleList}`\n );\n }\n }\n\n const role = roleName as SemanticRole;\n const valueStr = token.slice(colonIndex + 1);\n\n // Handle nested explicit syntax for structural roles (body, then, else, condition, loop-body, variable)\n if (STRUCTURAL_ROLES.has(roleName) && valueStr.startsWith('[') && isNestedCommand(valueStr)) {\n const nestedEnd = findMatchingBracket(token, colonIndex + 1);\n const nestedSyntax = token.slice(colonIndex + 1, nestedEnd + 1);\n roles.set(role, { type: 'expression', raw: nestedSyntax });\n continue;\n }\n\n const value = parseExplicitValue(valueStr, refSet);\n roles.set(role, value);\n }\n\n // Validate required roles are present (skip for event handlers — handled below)\n if (schema && command !== 'on') {\n for (const roleSpec of schema.roles) {\n if (roleSpec.required && !roles.has(roleSpec.role as SemanticRole) && !roleSpec.default) {\n if (collect) {\n diagnostics.push({\n severity: 'error',\n code: 'MISSING_REQUIRED_ROLE',\n message: `Missing required role \"${roleSpec.role}\" for command \"${command}\": ${roleSpec.description}`,\n source: 'schema',\n });\n } else {\n throw new Error(\n `Missing required role \"${roleSpec.role}\" for command \"${command}\": ${roleSpec.description}`\n );\n }\n }\n }\n }\n\n // Helper: attach diagnostics to a node if any were collected\n const attachDiagnostics = (node: SemanticNode): SemanticNode => {\n if (diagnostics.length === 0) return node;\n return { ...node, diagnostics };\n };\n\n // Build appropriate node type based on action name\n switch (command) {\n case 'on': {\n const eventValue = roles.get('event');\n if (!eventValue) {\n if (collect) {\n diagnostics.push({\n severity: 'error',\n code: 'MISSING_EVENT_ROLE',\n message: 'Event handler requires event role: [on event:click ...]',\n source: 'schema',\n });\n // Return a stub event handler with diagnostics\n return attachDiagnostics(\n createEventHandlerNode('on', roles, [], {\n sourceLanguage: 'explicit',\n })\n );\n }\n throw new Error('Event handler requires event role: [on event:click ...]');\n }\n\n // Parse body if present\n const body = extractStructuralBody(roles, 'body', options);\n roles.delete('body' as SemanticRole);\n\n return attachDiagnostics(\n createEventHandlerNode('on', roles, body, {\n sourceLanguage: 'explicit',\n })\n );\n }\n\n case 'if': {\n // Extract structural roles for conditional\n const thenBranch = extractStructuralBody(roles, 'then', options);\n const elseBranch = extractStructuralBody(roles, 'else', options);\n roles.delete('then' as SemanticRole);\n roles.delete('else' as SemanticRole);\n\n return attachDiagnostics(\n createConditionalNode(\n command,\n roles,\n thenBranch,\n elseBranch.length > 0 ? elseBranch : undefined,\n {\n sourceLanguage: 'explicit',\n }\n )\n );\n }\n\n case 'repeat': {\n // Extract loop structural roles\n const loopBody = extractStructuralBody(roles, 'loop-body', options);\n const loopVariantValue = roles.get('loop-variant' as SemanticRole);\n const variableValue = roles.get('variable' as SemanticRole);\n const indexVariableValue = roles.get('index-variable' as SemanticRole);\n\n roles.delete('loop-body' as SemanticRole);\n roles.delete('loop-variant' as SemanticRole);\n roles.delete('variable' as SemanticRole);\n roles.delete('index-variable' as SemanticRole);\n\n // Determine loop variant: explicit > inferred from roles\n let variant: LoopVariant;\n if (\n loopVariantValue &&\n loopVariantValue.type === 'literal' &&\n typeof loopVariantValue.value === 'string'\n ) {\n variant = loopVariantValue.value as LoopVariant;\n } else if (roles.has('quantity' as SemanticRole)) {\n variant = 'times';\n } else if (roles.has('source' as SemanticRole)) {\n variant = 'for';\n } else if (roles.has('condition' as SemanticRole)) {\n variant = 'while';\n } else {\n variant = 'forever';\n }\n\n const loopVariable =\n variableValue?.type === 'literal' && typeof variableValue.value === 'string'\n ? variableValue.value\n : variableValue?.type === 'expression'\n ? variableValue.raw\n : undefined;\n const indexVariable =\n indexVariableValue?.type === 'literal' && typeof indexVariableValue.value === 'string'\n ? indexVariableValue.value\n : undefined;\n\n return attachDiagnostics(\n createLoopNode(command, roles, variant, loopBody, loopVariable, indexVariable, {\n sourceLanguage: 'explicit',\n })\n );\n }\n\n default:\n return attachDiagnostics(\n createCommandNode(command, roles, {\n sourceLanguage: 'explicit',\n })\n );\n }\n}\n\n/**\n * Check if input is explicit bracket syntax.\n */\nexport function isExplicitSyntax(input: string): boolean {\n const trimmed = input.trim();\n return trimmed.startsWith('[') && trimmed.endsWith(']');\n}\n\n// =============================================================================\n// Compound Statement Parsing\n// =============================================================================\n\n/** Chain operators per ABNF: \"then\" / \"and\" / \"async\" / \"sequential\" / \"|>\" */\nconst CHAIN_KEYWORDS = new Set(['then', 'and', 'async', 'sequential']);\n\n/**\n * Split input into bracket-command segments separated by chain operators.\n * Returns segments and the chain operator found (first one wins for mixed).\n */\nfunction splitCompoundSegments(input: string): {\n segments: string[];\n chainType: CompoundSemanticNode['chainType'] | null;\n} {\n const segments: string[] = [];\n let chainType: CompoundSemanticNode['chainType'] | null = null;\n let current = '';\n let bracketDepth = 0;\n let inString = false;\n let stringChar = '';\n\n for (let i = 0; i < input.length; i++) {\n const char = input[i];\n\n if (inString) {\n current += char;\n if (char === stringChar && input[i - 1] !== '\\\\') {\n inString = false;\n }\n continue;\n }\n\n if (char === '\"' || char === \"'\") {\n inString = true;\n stringChar = char;\n current += char;\n continue;\n }\n\n if (char === '[') {\n bracketDepth++;\n current += char;\n continue;\n }\n\n if (char === ']') {\n bracketDepth--;\n current += char;\n\n // At depth 0 after closing bracket, check for chain operator\n if (bracketDepth === 0) {\n const rest = input.slice(i + 1);\n // Check for |> pipe operator\n const pipeMatch = rest.match(/^\\s*\\|>\\s*/);\n if (pipeMatch) {\n segments.push(current.trim());\n current = '';\n chainType ??= 'pipe';\n i += pipeMatch[0].length;\n continue;\n }\n // Check for keyword chain operators\n const keywordMatch = rest.match(/^\\s+(then|and|async|sequential)\\s+/);\n if (keywordMatch && CHAIN_KEYWORDS.has(keywordMatch[1])) {\n segments.push(current.trim());\n current = '';\n chainType ??= keywordMatch[1] as CompoundSemanticNode['chainType'];\n i += keywordMatch[0].length;\n continue;\n }\n }\n continue;\n }\n\n current += char;\n }\n\n if (current.trim()) {\n segments.push(current.trim());\n }\n\n return { segments, chainType };\n}\n\n/**\n * Parse a compound statement (one or more bracket commands chained with operators).\n *\n * ABNF: compound-stmt = bracket-cmd *( chain-op bracket-cmd )\n *\n * Single commands pass through to parseExplicit(). Multiple commands produce\n * a CompoundSemanticNode.\n *\n * Also handles annotations (@name or @name(value)) before the first bracket.\n *\n * @example\n * ```typescript\n * // Single command — passthrough\n * parseCompound('[toggle patient:.active]')\n *\n * // Compound statement\n * parseCompound('[add patient:.loading] then [fetch source:/api/data]')\n *\n * // With annotation\n * parseCompound('@timeout(5s) [fetch source:/api/users]')\n * ```\n */\nexport function parseCompound(input: string, options?: ParseExplicitOptions): SemanticNode {\n const trimmed = input.trim();\n\n // Extract annotations before the first bracket\n const { annotations, remainder } = extractAnnotations(trimmed);\n\n const { segments, chainType } = splitCompoundSegments(remainder);\n\n let node: SemanticNode;\n if (segments.length <= 1) {\n // Single command — delegate to parseExplicit\n node = parseExplicit(segments[0] || remainder, options);\n } else {\n // Multiple commands — create compound node\n const statements = segments.map(seg => parseExplicit(seg, options));\n node = createCompoundNode(statements, chainType ?? 'sequential');\n }\n\n // Attach annotations if any\n if (annotations.length > 0) {\n return { ...node, annotations };\n }\n return node;\n}\n\n// =============================================================================\n// Annotation Parsing\n// =============================================================================\n\n/**\n * Extract @name and @name(value) annotations from before the first bracket.\n * Per ABNF, annotations precede the compound statement on the same line.\n */\nfunction extractAnnotations(input: string): { annotations: Annotation[]; remainder: string } {\n const annotations: Annotation[] = [];\n let pos = 0;\n\n while (pos < input.length) {\n // Skip whitespace\n while (pos < input.length && (input[pos] === ' ' || input[pos] === '\\t')) {\n pos++;\n }\n\n // If we hit '[' or end of string, we're done with annotations\n if (pos >= input.length || input[pos] !== '@') {\n break;\n }\n\n // Parse @name\n pos++; // skip @\n const nameStart = pos;\n while (pos < input.length && /[A-Za-z0-9\\-_]/.test(input[pos])) {\n pos++;\n }\n const name = input.slice(nameStart, pos);\n if (!name) break;\n\n // Check for (value)\n let value: string | undefined;\n if (pos < input.length && input[pos] === '(') {\n pos++; // skip (\n const valueStart = pos;\n // Handle quoted strings inside annotation values\n if (pos < input.length && (input[pos] === '\"' || input[pos] === \"'\")) {\n const quote = input[pos];\n pos++; // skip opening quote\n while (pos < input.length && input[pos] !== quote) {\n if (input[pos] === '\\\\') pos++; // skip escape\n pos++;\n }\n pos++; // skip closing quote\n value = input.slice(valueStart + 1, pos - 1); // strip quotes\n } else {\n // Plain value chars: ALPHA / DIGIT / \"-\" / \"_\" / \".\" / \"/\" / \":\"\n while (pos < input.length && input[pos] !== ')') {\n pos++;\n }\n value = input.slice(valueStart, pos);\n }\n if (pos < input.length && input[pos] === ')') {\n pos++; // skip )\n }\n }\n\n annotations.push(value !== undefined ? { name, value } : { name });\n }\n\n return { annotations, remainder: input.slice(pos).trim() };\n}\n\n// =============================================================================\n// Document Parsing\n// =============================================================================\n\n/** Version header regex: #!lse <version> */\nconst VERSION_HEADER_RE = /^#!lse\\s+(\\d+\\.\\d+(?:\\.\\d+)?)\\s*$/;\n\n/**\n * Parse a multi-line LSE document into an LSEEnvelope.\n *\n * ABNF: document = [ version-header LF ] *( line LF ) [ line ]\n *\n * Handles version headers (#!lse 1.2), comments (// or #), blank lines,\n * and statement lines (one compound statement per line).\n *\n * @example\n * ```typescript\n * const envelope = parseDocument(`\n * #!lse 1.2\n * // Toggle active state\n * [toggle patient:.active]\n * [add patient:.highlight]\n * `);\n * // envelope.lseVersion === '1.2'\n * // envelope.nodes.length === 2\n * ```\n */\nexport function parseDocument(input: string, options?: ParseExplicitOptions): LSEEnvelope {\n const lines = input.split('\\n');\n let lseVersion = '1.0';\n const nodes: SemanticNode[] = [];\n let startLine = 0;\n\n // Check for version header on first non-blank line\n for (let i = 0; i < lines.length; i++) {\n const trimmed = lines[i].trim();\n if (!trimmed) continue; // skip leading blank lines\n const versionMatch = trimmed.match(VERSION_HEADER_RE);\n if (versionMatch) {\n lseVersion = versionMatch[1];\n startLine = i + 1;\n }\n break;\n }\n\n // Parse remaining lines\n for (let i = startLine; i < lines.length; i++) {\n const trimmed = lines[i].trim();\n\n // Skip blank lines\n if (!trimmed) continue;\n\n // Skip comments (// or #, but NOT #! which is version header)\n if (trimmed.startsWith('//') || (trimmed.startsWith('#') && !trimmed.startsWith('#!'))) {\n continue;\n }\n\n // Parse statement line\n nodes.push(parseCompound(trimmed, options));\n }\n\n return { lseVersion, nodes };\n}\n\n// =============================================================================\n// Detection Helpers\n// =============================================================================\n\n/**\n * Check if input contains compound chaining (multiple bracket commands\n * with chain operators at bracket-depth 0).\n */\nexport function isCompoundSyntax(input: string): boolean {\n const { segments } = splitCompoundSegments(input.trim());\n return segments.length > 1;\n}\n\n/**\n * Check if input is a multi-line LSE document (contains newlines,\n * version header, or comment lines).\n */\nexport function isDocumentSyntax(input: string): boolean {\n const trimmed = input.trim();\n if (trimmed.includes('\\n')) return true;\n if (VERSION_HEADER_RE.test(trimmed)) return true;\n if (trimmed.startsWith('//') || (trimmed.startsWith('#') && !trimmed.startsWith('#!'))) {\n return true;\n }\n return false;\n}\n\n// =============================================================================\n// Internal Helpers\n// =============================================================================\n\n/**\n * Extract and parse a structural role (body, then, else, loop-body) into SemanticNode[].\n * Returns an empty array if the role is not present.\n */\nfunction extractStructuralBody(\n roles: Map<SemanticRole, SemanticValue>,\n roleName: string,\n options: ParseExplicitOptions\n): SemanticNode[] {\n const value = roles.get(roleName as SemanticRole);\n if (!value) return [];\n if (value.type === 'expression') {\n return [parseExplicit(value.raw, options)];\n }\n return [];\n}\n\n/**\n * Infer selectorKind from a CSS selector string.\n */\nfunction inferSelectorKind(\n value: string\n): 'id' | 'class' | 'attribute' | 'element' | 'complex' | undefined {\n if (!value) return undefined;\n if (value.startsWith('#')) return 'id';\n if (value.startsWith('.')) return 'class';\n if (value.startsWith('[')) return 'attribute';\n if (value.startsWith('<') || value.startsWith('*')) return 'element';\n if (/[>+~ ]/.test(value) && value.length > 1) return 'complex';\n return undefined;\n}\n\n/**\n * Tokenize explicit syntax content (space-separated, respecting quotes and brackets).\n */\nfunction tokenizeExplicit(content: string): string[] {\n const tokens: string[] = [];\n let current = '';\n let inString = false;\n let stringChar = '';\n let bracketDepth = 0;\n\n for (let i = 0; i < content.length; i++) {\n const char = content[i];\n\n if (inString) {\n current += char;\n if (char === stringChar && content[i - 1] !== '\\\\') {\n inString = false;\n }\n continue;\n }\n\n if (char === '\"' || char === \"'\") {\n inString = true;\n stringChar = char;\n current += char;\n continue;\n }\n\n if (char === '[') {\n bracketDepth++;\n current += char;\n continue;\n }\n\n if (char === ']') {\n bracketDepth--;\n current += char;\n continue;\n }\n\n if (char === ' ' && bracketDepth === 0) {\n if (current) {\n tokens.push(current);\n current = '';\n }\n continue;\n }\n\n current += char;\n }\n\n if (current) {\n tokens.push(current);\n }\n\n return tokens;\n}\n\n/**\n * Parse a value string into a SemanticValue.\n */\nfunction parseExplicitValue(valueStr: string, referenceSet: ReadonlySet<string>): SemanticValue {\n // CSS selector\n if (\n valueStr.startsWith('#') ||\n valueStr.startsWith('.') ||\n valueStr.startsWith('[') ||\n valueStr.startsWith('@') ||\n valueStr.startsWith('*')\n ) {\n return createSelector(valueStr, inferSelectorKind(valueStr));\n }\n\n // String literal\n if (valueStr.startsWith('\"') || valueStr.startsWith(\"'\")) {\n const inner = valueStr.slice(1, -1);\n return createLiteral(inner, 'string');\n }\n\n // Boolean\n if (valueStr === 'true') return createLiteral(true, 'boolean');\n if (valueStr === 'false') return createLiteral(false, 'boolean');\n\n // Reference\n const lowerRef = valueStr.toLowerCase();\n if (isValidReference(lowerRef, referenceSet)) {\n return createReference(lowerRef);\n }\n\n // Number (possibly with duration suffix)\n const numMatch = valueStr.match(/^(-?\\d+(?:\\.\\d+)?)(ms|s|m|h)?$/);\n if (numMatch) {\n const num = parseFloat(numMatch[1]);\n const suffix = numMatch[2];\n if (suffix) {\n return createLiteral(valueStr, 'duration');\n }\n return createLiteral(num, 'number');\n }\n\n // Default to untyped string literal (no dataType — avoids spurious quoting on round-trip).\n // Only explicitly-quoted values (handled above) get dataType: 'string'.\n return createLiteral(valueStr);\n}\n\n/**\n * Find the matching closing bracket.\n */\nfunction findMatchingBracket(str: string, start: number): number {\n let depth = 0;\n\n for (let i = start; i < str.length; i++) {\n if (str[i] === '[') depth++;\n else if (str[i] === ']') {\n depth--;\n if (depth === 0) return i;\n }\n }\n\n return str.length - 1;\n}\n","/**\n * Explicit Syntax Renderer\n *\n * Serializes SemanticNode to the universal [command role:value ...] bracket syntax.\n * Zero dependencies beyond core types — no language-specific logic.\n *\n * Also renders annotations (@name(value)) and multi-line documents.\n */\n\nimport type {\n SemanticNode,\n SemanticValue,\n CommandSemanticNode,\n CompoundSemanticNode,\n EventHandlerSemanticNode,\n ConditionalSemanticNode,\n LoopSemanticNode,\n LSEEnvelope,\n} from '../core/types';\n\n/**\n * Render a semantic node as explicit bracket syntax.\n *\n * Handles annotations (v1.2) — if the node has annotations, they are\n * prepended as @name or @name(value) before the bracket output.\n *\n * @example\n * ```typescript\n * renderExplicit(node) // \"[toggle patient:.active destination:#button]\"\n * // With annotations:\n * renderExplicit(annotatedNode) // \"@timeout(5s) [fetch source:\\\"/api/users\\\"]\"\n * ```\n */\nexport function renderExplicit(node: SemanticNode): string {\n let result: string;\n\n // Handle compound nodes\n if (node.kind === 'compound') {\n const compoundNode = node as CompoundSemanticNode;\n const renderedStatements = compoundNode.statements.map(stmt => renderExplicit(stmt));\n result = renderedStatements.join(` ${compoundNode.chainType} `);\n } else {\n result = renderBracketCommand(node);\n }\n\n // Prepend annotations if present\n if (node.annotations && node.annotations.length > 0) {\n const annParts = node.annotations.map(ann =>\n ann.value !== undefined ? `@${ann.name}(${ann.value})` : `@${ann.name}`\n );\n return annParts.join(' ') + ' ' + result;\n }\n\n return result;\n}\n\n/**\n * Render an LSEEnvelope as a multi-line document string.\n *\n * @example\n * ```typescript\n * renderDocument(envelope)\n * // \"#!lse 1.2\\n[toggle patient:.active]\\n[add patient:.highlight]\"\n * ```\n */\nexport function renderDocument(envelope: LSEEnvelope): string {\n const lines: string[] = [];\n\n // Emit version header if not the default\n if (envelope.lseVersion && envelope.lseVersion !== '1.0') {\n lines.push(`#!lse ${envelope.lseVersion}`);\n }\n\n // Emit each node on its own line\n for (const node of envelope.nodes) {\n lines.push(renderExplicit(node));\n }\n\n return lines.join('\\n');\n}\n\n// =============================================================================\n// Internal Helpers\n// =============================================================================\n\n/**\n * Render a single bracket command (non-compound node).\n */\nfunction renderBracketCommand(node: SemanticNode): string {\n const parts: string[] = [node.action];\n\n // Add roles\n for (const [role, value] of node.roles) {\n if (value.type === 'flag') {\n parts.push(value.enabled ? `+${value.name}` : `~${value.name}`);\n } else {\n parts.push(`${role}:${valueToString(value)}`);\n }\n }\n\n // Handle event handler body\n if (node.kind === 'event-handler') {\n const eventNode = node as EventHandlerSemanticNode;\n if (eventNode.body && eventNode.body.length > 0) {\n const bodyParts = eventNode.body.map(n => renderExplicit(n));\n parts.push(`body:${bodyParts.join(' ')}`);\n }\n }\n\n // Handle conditional branches (v1.1)\n if (node.kind === 'conditional') {\n const condNode = node as ConditionalSemanticNode;\n if (condNode.thenBranch && condNode.thenBranch.length > 0) {\n const thenParts = condNode.thenBranch.map(n => renderExplicit(n));\n parts.push(`then:${thenParts.join(' ')}`);\n }\n if (condNode.elseBranch && condNode.elseBranch.length > 0) {\n const elseParts = condNode.elseBranch.map(n => renderExplicit(n));\n parts.push(`else:${elseParts.join(' ')}`);\n }\n }\n\n // Handle loop body and metadata (v1.1)\n if (node.kind === 'loop') {\n const loopNode = node as LoopSemanticNode;\n if (loopNode.loopVariant) {\n parts.push(`loop-variant:${loopNode.loopVariant}`);\n }\n if (loopNode.loopVariable) {\n parts.push(`variable:${loopNode.loopVariable}`);\n }\n if (loopNode.indexVariable) {\n parts.push(`index-variable:${loopNode.indexVariable}`);\n }\n if (loopNode.body && loopNode.body.length > 0) {\n const bodyParts = loopNode.body.map(n => renderExplicit(n));\n parts.push(`loop-body:${bodyParts.join(' ')}`);\n }\n }\n\n // Handle v1.2 command fields (try/catch/finally, async, match)\n if (node.kind === 'command') {\n const cmd = node as CommandSemanticNode;\n if (cmd.body && cmd.body.length > 0) {\n const bodyParts = cmd.body.map(n => renderExplicit(n));\n parts.push(`body:${bodyParts.join(' ')}`);\n }\n if (cmd.catchBranch && cmd.catchBranch.length > 0) {\n const catchParts = cmd.catchBranch.map(n => renderExplicit(n));\n parts.push(`catch:${catchParts.join(' ')}`);\n }\n if (cmd.finallyBranch && cmd.finallyBranch.length > 0) {\n const finallyParts = cmd.finallyBranch.map(n => renderExplicit(n));\n parts.push(`finally:${finallyParts.join(' ')}`);\n }\n if (cmd.asyncVariant) {\n parts.push(`async-variant:${cmd.asyncVariant}`);\n }\n if (cmd.asyncBody && cmd.asyncBody.length > 0) {\n const asyncParts = cmd.asyncBody.map(n => renderExplicit(n));\n parts.push(`async-body:${asyncParts.join(' ')}`);\n }\n }\n\n return `[${parts.join(' ')}]`;\n}\n\n/**\n * Convert a semantic value to its explicit syntax string form.\n */\nfunction valueToString(value: SemanticValue): string {\n switch (value.type) {\n case 'literal':\n if (typeof value.value === 'string') {\n // Quote strings that contain spaces or are explicitly typed as strings\n if (value.dataType === 'string' || /\\s/.test(value.value)) {\n return `\"${value.value}\"`;\n }\n return value.value;\n }\n return String(value.value);\n\n case 'selector':\n return value.value;\n\n case 'reference':\n return value.value;\n\n case 'property-path':\n return `${valueToString(value.object)}'s ${value.property}`;\n\n case 'expression':\n return value.raw;\n\n case 'flag':\n return value.name;\n }\n}\n","/**\n * Main API for creating multilingual DSLs\n */\n\nimport type { SemanticNode, LanguageTokenizer, LanguagePattern } from '../core/types';\nimport type { CommandSchema } from '../schema';\nimport { PatternMatcher, type PatternMatcherProfile } from '../core/pattern-matching';\nimport { generatePattern, type PatternGenLanguageProfile } from '../generation/pattern-generator';\nimport { GrammarTransformer, type LanguageProfile as GrammarProfile } from '../grammar';\nimport {\n type Dictionary,\n type ProfileProvider,\n type ValueExtractor,\n InMemoryDictionary,\n InMemoryProfileProvider,\n} from '../interfaces';\nimport { isExplicitSyntax, parseExplicit } from '../ir';\nimport type { SchemaLookup } from '../ir';\n\n/**\n * Language configuration for a DSL.\n */\nexport interface LanguageConfig {\n /** ISO 639-1 language code */\n readonly code: string;\n /** English name of the language */\n readonly name: string;\n /** Native name of the language */\n readonly nativeName: string;\n /** Language tokenizer */\n readonly tokenizer: LanguageTokenizer;\n /** Language profile for pattern generation */\n readonly patternProfile: PatternGenLanguageProfile;\n /** Language profile for grammar transformation (optional) */\n readonly grammarProfile?: GrammarProfile;\n}\n\n/**\n * Code generator function that transforms semantic AST to target code.\n */\nexport interface CodeGenerator {\n generate(node: SemanticNode): string;\n}\n\n/**\n * DSL configuration with dependency injection support.\n */\nexport interface DSLConfig {\n /** DSL name (for debugging/documentation) */\n readonly name?: string;\n\n /** Command schemas defining the DSL grammar */\n readonly schemas: readonly CommandSchema[];\n\n /** Language configurations */\n readonly languages: readonly LanguageConfig[];\n\n // === Dependency Injection (Optional) ===\n\n /** Dictionary for keyword translation (default: built from language configs) */\n readonly dictionary?: Dictionary;\n\n /** Profile provider for grammar transformation (default: built from language configs) */\n readonly profileProvider?: ProfileProvider;\n\n /** Value extractors for tokenization (default: generic extractors) */\n readonly valueExtractors?: ValueExtractor[];\n\n /** Code generator for compilation (default: none) */\n readonly codeGenerator?: CodeGenerator;\n\n // === Options ===\n\n /** Auto-generate patterns from schemas (default: true) */\n readonly generatePatterns?: boolean;\n\n /** Custom patterns to supplement generated ones */\n readonly customPatterns?: LanguagePattern[];\n}\n\n/**\n * Validation result.\n */\nexport interface ValidationResult {\n readonly valid: boolean;\n readonly node?: SemanticNode;\n readonly errors?: string[];\n}\n\n/**\n * Compilation result.\n */\nexport interface CompileResult {\n readonly ok: boolean;\n readonly code?: string;\n readonly errors?: string[];\n readonly node?: SemanticNode;\n readonly metadata?: {\n readonly parser: string;\n readonly confidence: number;\n };\n}\n\n/**\n * Main multilingual DSL interface.\n */\nexport interface MultilingualDSL {\n // Parsing\n parse(input: string, language: string): SemanticNode;\n parseWithConfidence(input: string, language: string): { node: SemanticNode; confidence: number };\n\n // Validation\n validate(input: string, language: string): ValidationResult;\n\n // Compilation\n compile(input: string, language: string): CompileResult;\n\n // Translation\n translate(input: string, fromLanguage: string, toLanguage: string): string;\n\n // Language support\n getSupportedLanguages(): string[];\n}\n\n/**\n * Internal registry for DSL configuration.\n */\nclass DSLRegistry {\n private patterns = new Map<string, LanguagePattern[]>();\n private tokenizers = new Map<string, LanguageTokenizer>();\n private schemas: readonly CommandSchema[];\n\n constructor(config: DSLConfig) {\n this.schemas = config.schemas;\n\n // Register each language\n for (const lang of config.languages) {\n this.registerLanguage(lang);\n }\n }\n\n private registerLanguage(lang: LanguageConfig): void {\n // Register tokenizer\n this.tokenizers.set(lang.code, lang.tokenizer);\n\n // Generate patterns for this language\n const patterns: LanguagePattern[] = [];\n for (const schema of this.schemas) {\n const pattern = generatePattern(schema, lang.patternProfile);\n patterns.push(pattern);\n }\n\n this.patterns.set(lang.code, patterns);\n }\n\n getPatterns(language: string): LanguagePattern[] {\n return this.patterns.get(language) || [];\n }\n\n getTokenizer(language: string): LanguageTokenizer | undefined {\n return this.tokenizers.get(language);\n }\n\n getSupportedLanguages(): string[] {\n return Array.from(this.patterns.keys());\n }\n}\n\n/**\n * Implementation of MultilingualDSL.\n */\nclass MultilingualDSLImpl implements MultilingualDSL {\n private registry: DSLRegistry;\n private matcher: PatternMatcher;\n private transformer: GrammarTransformer;\n private codeGenerator?: CodeGenerator;\n private schemaLookup: SchemaLookup;\n\n constructor(config: DSLConfig, registry: DSLRegistry, transformer: GrammarTransformer) {\n this.registry = registry;\n this.matcher = new PatternMatcher();\n this.transformer = transformer;\n if (config.codeGenerator) {\n this.codeGenerator = config.codeGenerator;\n }\n\n // Build SchemaLookup from config schemas for explicit syntax validation\n const schemaMap = new Map(config.schemas.map(s => [s.action, s]));\n this.schemaLookup = {\n getSchema: (action: string) => schemaMap.get(action),\n };\n }\n\n parse(input: string, language: string): SemanticNode {\n const result = this.parseWithConfidence(input, language);\n return result.node;\n }\n\n parseWithConfidence(input: string, language: string): { node: SemanticNode; confidence: number } {\n // Try explicit bracket syntax first (language-agnostic)\n if (isExplicitSyntax(input)) {\n const node = parseExplicit(input, { schemaLookup: this.schemaLookup });\n // Only match if this DSL has a schema for the action\n if (!this.schemaLookup.getSchema(node.action)) {\n throw new Error(`No schema for action \"${node.action}\" in this DSL`);\n }\n return { node, confidence: 1.0 };\n }\n\n // Get tokenizer for language\n const tokenizer = this.registry.getTokenizer(language);\n if (!tokenizer) {\n throw new Error(`No tokenizer registered for language: ${language}`);\n }\n\n // Tokenize input\n const tokens = tokenizer.tokenize(input);\n\n // Get patterns for language\n const patterns = this.registry.getPatterns(language);\n\n // Create profile for matcher\n const profile: PatternMatcherProfile = {\n code: language,\n };\n\n // Try to match each pattern\n for (const pattern of patterns) {\n const match = this.matcher.matchPattern(tokens, pattern, profile);\n if (match) {\n // Build semantic node\n const node: SemanticNode = {\n kind: 'command',\n action: pattern.command,\n roles: match.captured,\n metadata: {\n sourceLanguage: language,\n sourceText: input,\n patternId: pattern.id,\n confidence: match.confidence,\n },\n };\n\n return { node, confidence: match.confidence };\n }\n }\n\n throw new Error(`No pattern matched for input: ${input}`);\n }\n\n validate(input: string, language: string): ValidationResult {\n try {\n const result = this.parseWithConfidence(input, language);\n return {\n valid: true,\n node: result.node,\n };\n } catch (error) {\n return {\n valid: false,\n errors: [error instanceof Error ? error.message : String(error)],\n };\n }\n }\n\n translate(input: string, fromLanguage: string, toLanguage: string): string {\n // Explicit syntax is language-agnostic — return unchanged\n if (isExplicitSyntax(input)) return input;\n // Use injected grammar transformer\n return this.transformer.transform(input, fromLanguage, toLanguage);\n }\n\n compile(input: string, language: string): CompileResult {\n if (!this.codeGenerator) {\n return {\n ok: false,\n errors: ['No code generator configured for this DSL'],\n };\n }\n\n try {\n const result = this.parseWithConfidence(input, language);\n const code = this.codeGenerator.generate(result.node);\n\n return {\n ok: true,\n code,\n node: result.node,\n metadata: {\n parser: 'semantic',\n confidence: result.confidence,\n },\n };\n } catch (error) {\n return {\n ok: false,\n errors: [error instanceof Error ? error.message : String(error)],\n };\n }\n }\n\n getSupportedLanguages(): string[] {\n return this.registry.getSupportedLanguages();\n }\n}\n\n/**\n * Create a new multilingual DSL instance.\n *\n * @param config - DSL configuration\n * @returns MultilingualDSL instance\n *\n * @example\n * ```typescript\n * const myDSL = createMultilingualDSL({\n * schemas: [\n * defineCommand('select', [\n * defineRole('field', 'identifier', true),\n * defineRole('source', 'identifier', true),\n * ]),\n * ],\n * languages: [\n * {\n * code: 'en',\n * name: 'English',\n * nativeName: 'English',\n * tokenizer: englishTokenizer,\n * patternProfile: englishProfile,\n * },\n * ],\n * codeGenerator: {\n * generate: (node) => generateSQL(node),\n * },\n * });\n *\n * const result = myDSL.compile('select name from users', 'en');\n * ```\n */\n/**\n * Create default dictionary from language configurations.\n */\nfunction createDefaultDictionary(config: DSLConfig): Dictionary {\n const translations: Record<string, Record<string, string>> = {};\n\n for (const lang of config.languages) {\n // Convert keyword objects to simple string mappings\n const keywords: Record<string, string> = {};\n for (const [canonical, keywordDef] of Object.entries(lang.patternProfile.keywords)) {\n keywords[canonical] = keywordDef.primary;\n }\n translations[lang.code] = keywords;\n }\n\n return new InMemoryDictionary(translations);\n}\n\n/**\n * Create default profile provider from language configurations.\n */\nfunction createDefaultProfileProvider(config: DSLConfig): ProfileProvider {\n const profiles: Record<string, GrammarProfile> = {};\n\n for (const lang of config.languages) {\n if (lang.grammarProfile) {\n profiles[lang.code] = lang.grammarProfile;\n }\n }\n\n return new InMemoryProfileProvider(profiles);\n}\n\nexport function createMultilingualDSL(config: DSLConfig): MultilingualDSL {\n // Create or use provided dictionary\n const dictionary = config.dictionary ?? createDefaultDictionary(config);\n\n // Create or use provided profile provider\n const profileProvider = config.profileProvider ?? createDefaultProfileProvider(config);\n\n // Create grammar transformer with injected dependencies\n const transformer = new GrammarTransformer({\n dictionary,\n profileProvider,\n });\n\n // Create registry and implementation\n const registry = new DSLRegistry(config);\n return new MultilingualDSLImpl(config, registry, transformer);\n}\n","/**\n * LLM Prompt Generator\n *\n * Auto-generates LLM system prompts from CommandSchema[]. Given a set of\n * domain schemas, produces a structured markdown prompt that teaches LLMs\n * to output valid LSE bracket syntax and/or LLM-simplified JSON.\n *\n * The generated prompt includes:\n * - Protocol overview (LSE syntax summary)\n * - Value type reference\n * - Per-command documentation with role descriptions\n * - Synthetic examples in both formats\n * - Output format specification\n * - Error recovery instructions\n */\n\nimport type { CommandSchema, RoleSpec } from '../schema/command-schema';\nimport type { SemanticJSON, SemanticJSONValue } from '../ir/types';\nimport { renderExplicit } from '../ir/explicit-renderer';\nimport { createCommandNode } from '../core/types';\nimport type {\n PromptGeneratorConfig,\n GeneratedPrompt,\n PromptSection,\n PromptMetadata,\n} from './types';\n\n// =============================================================================\n// Public API\n// =============================================================================\n\n/**\n * Generate an LLM system prompt from domain command schemas.\n *\n * @example\n * ```typescript\n * import { generatePrompt } from '@lokascript/framework';\n * import { allSchemas } from '@lokascript/domain-flow';\n *\n * const prompt = generatePrompt({\n * domain: 'flow',\n * description: 'Reactive data flow pipelines',\n * schemas: allSchemas,\n * });\n *\n * console.log(prompt.text); // Full markdown system prompt\n * ```\n */\nexport function generatePrompt(config: PromptGeneratorConfig): GeneratedPrompt {\n const outputFormat = config.outputFormat ?? 'both';\n const examplesPerCommand = config.examplesPerCommand ?? 2;\n\n const sections: PromptSection[] = [\n buildProtocolSection(),\n buildValueTypeSection(),\n buildCommandsSection(config.schemas, outputFormat, examplesPerCommand),\n buildOutputFormatSection(outputFormat),\n buildErrorRecoverySection(),\n ];\n\n // Apply token budget if specified\n let finalSections = sections;\n if (config.maxTokens && config.maxTokens > 0) {\n finalSections = truncateToTokenBudget(sections, config.maxTokens);\n }\n\n const text = finalSections.map(s => `## ${s.title}\\n\\n${s.content}`).join('\\n\\n---\\n\\n');\n\n const totalRoles = config.schemas.reduce((sum, s) => sum + s.roles.length, 0);\n const approximateTokens = estimateTokens(text);\n\n const metadata: PromptMetadata = {\n domain: config.domain,\n commandCount: config.schemas.length,\n roleCount: totalRoles,\n approximateTokens,\n };\n\n return { text, sections: finalSections, metadata };\n}\n\n/**\n * Generate synthetic LSE examples from a single command schema.\n * Used by both the prompt generator and training data synthesizer.\n */\nexport function generateExamples(\n schema: CommandSchema,\n count: number = 2\n): Array<{ explicit: string; json: SemanticJSON }> {\n const combos = generateRoleCombinations(schema);\n const examples: Array<{ explicit: string; json: SemanticJSON }> = [];\n\n for (let i = 0; i < Math.min(count, combos.length); i++) {\n const combo = combos[i];\n const roles = new Map<string, { type: string; value: string | number | boolean }>();\n\n for (const role of combo) {\n const sample = sampleValue(role);\n roles.set(role.role, sample);\n }\n\n // Build SemanticNode for rendering to bracket syntax\n const nodeRoles = new Map<\n string,\n {\n type: string;\n value: string | number | boolean;\n raw?: string;\n dataType?: string;\n selectorKind?: string;\n }\n >();\n for (const [roleName, sample] of roles) {\n nodeRoles.set(roleName, toSemanticValue(sample));\n }\n\n const node = createCommandNode(schema.action, nodeRoles as never);\n const explicit = renderExplicit(node);\n\n // Build JSON format\n const jsonRoles: Record<string, SemanticJSONValue> = {};\n for (const [roleName, sample] of roles) {\n jsonRoles[roleName] = sample as SemanticJSONValue;\n }\n const json: SemanticJSON = { action: schema.action, roles: jsonRoles };\n\n examples.push({ explicit, json });\n }\n\n return examples;\n}\n\n/**\n * Generate a condensed LSE protocol reference (for MCP resources).\n */\nexport function generateProtocolReference(): string {\n const protocol = buildProtocolSection();\n const valueTypes = buildValueTypeSection();\n return `# LokaScript Explicit Syntax (LSE) Quick Reference\\n\\n${protocol.content}\\n\\n${valueTypes.content}`;\n}\n\n// =============================================================================\n// Section Builders\n// =============================================================================\n\nfunction buildProtocolSection(): PromptSection {\n const content = `LokaScript Explicit Syntax (LSE) is a bracket-based format for imperative commands.\n\n### Syntax\n\n\\`\\`\\`\n[command role1:value1 role2:value2 +flag1 ~flag2]\n\\`\\`\\`\n\n- **Command**: The first token inside brackets (lowercased)\n- **Role pair**: \\`name:value\\` — a named semantic role with a typed value (no space around colon)\n- **Enabled flag**: \\`+name\\` — boolean attribute present\n- **Disabled flag**: \\`~name\\` — boolean attribute negated\n- **Nested body**: \\`body:[command ...]\\` — a bracket command inside a role value\n\n### Rules\n\n1. Commands are always lowercased\n2. Role names preserve their original case\n3. No spaces around the colon in role:value pairs\n4. Strings with spaces must be quoted: \\`patient:\"hello world\"\\`\n5. Selectors start with \\`#\\`, \\`.\\`, \\`[\\`, \\`@\\`, or \\`*\\`\n6. Output must be valid bracket syntax: \\`[action role:value ...]\\``;\n\n return {\n id: 'protocol',\n title: 'LSE Protocol',\n content,\n approximateTokens: estimateTokens(content),\n };\n}\n\nfunction buildValueTypeSection(): PromptSection {\n const content = `Values in LSE are classified by their syntactic form (first match wins):\n\n| Type | Syntax | Example |\n|------|--------|---------|\n| Selector | Starts with \\`#\\` \\`.\\` \\`[\\` \\`@\\` \\`*\\` | \\`#button\\`, \\`.active\\`, \\`[data-id]\\` |\n| String | Quoted with \\`\"\\` or \\`'\\` | \\`\"hello world\"\\`, \\`'json'\\` |\n| Boolean | Exact: \\`true\\` / \\`false\\` | \\`visible:true\\` |\n| Reference | Built-in name | \\`me\\`, \\`you\\`, \\`it\\`, \\`result\\`, \\`event\\`, \\`target\\`, \\`body\\` |\n| Duration | Number + suffix | \\`500ms\\`, \\`2s\\`, \\`1m\\`, \\`1h\\` |\n| Number | Digits with optional decimal | \\`5\\`, \\`3.14\\`, \\`-1\\` |\n| Plain | Fallback (any non-whitespace) | \\`/api/users\\`, \\`json\\`, \\`production\\` |\n\n**Important**: Classification is by prefix, not by intent. \\`#true\\` is a selector (not boolean). \\`event\\` as a value is a reference (not plain text).`;\n\n return {\n id: 'value-types',\n title: 'Value Types',\n content,\n approximateTokens: estimateTokens(content),\n };\n}\n\nfunction buildCommandsSection(\n schemas: readonly CommandSchema[],\n outputFormat: 'explicit' | 'json' | 'both',\n examplesPerCommand: number\n): PromptSection {\n const parts: string[] = [];\n\n for (const schema of schemas) {\n parts.push(formatCommandDoc(schema, outputFormat, examplesPerCommand));\n }\n\n const content = parts.join('\\n\\n');\n\n return {\n id: 'commands',\n title: 'Available Commands',\n content,\n approximateTokens: estimateTokens(content),\n };\n}\n\nfunction buildOutputFormatSection(outputFormat: 'explicit' | 'json' | 'both'): PromptSection {\n let content: string;\n\n if (outputFormat === 'explicit') {\n content = `Output valid LSE bracket syntax. Each command must be wrapped in brackets:\n\n\\`\\`\\`\n[command role:value ...]\n\\`\\`\\`\n\nDo NOT output JSON. Only use bracket syntax.`;\n } else if (outputFormat === 'json') {\n content = `Output valid JSON in the LLM-simplified format:\n\n\\`\\`\\`json\n{\n \"action\": \"command-name\",\n \"roles\": {\n \"roleName\": { \"type\": \"valueType\", \"value\": \"theValue\" }\n }\n}\n\\`\\`\\`\n\nValid value types: \\`selector\\`, \\`literal\\`, \\`reference\\`, \\`expression\\`.\nDo NOT output bracket syntax. Only use JSON.`;\n } else {\n content = `You may output EITHER format:\n\n**Bracket syntax** (preferred for single commands):\n\\`\\`\\`\n[command role:value ...]\n\\`\\`\\`\n\n**JSON format** (preferred when structured data is needed):\n\\`\\`\\`json\n{\n \"action\": \"command-name\",\n \"roles\": {\n \"roleName\": { \"type\": \"valueType\", \"value\": \"theValue\" }\n }\n}\n\\`\\`\\`\n\nBoth formats are equally valid. Use whichever is more natural for the context.`;\n }\n\n return {\n id: 'output-format',\n title: 'Output Format',\n content,\n approximateTokens: estimateTokens(content),\n };\n}\n\nfunction buildErrorRecoverySection(): PromptSection {\n const content = `If you're unsure about a command or role:\n\n1. **Unknown command**: Use the closest matching command from the Available Commands section. Do not invent commands.\n2. **Unknown role**: Use only the roles listed for each command. Do not add roles not in the schema.\n3. **Ambiguous value type**: When in doubt, use \\`expression\\` type (it's the most permissive).\n4. **Missing required role**: Always include all required roles. Check the Required/Optional labels.\n5. **Selector vs plain value**: If a value starts with \\`#\\`, \\`.\\`, \\`[\\`, \\`@\\`, or \\`*\\`, it's a selector. URLs like \\`/api/data\\` are plain values.\n\nWhen generating LSE, prefer explicit role labeling over positional guessing. Every value should have a role name.`;\n\n return {\n id: 'error-recovery',\n title: 'Error Recovery',\n content,\n approximateTokens: estimateTokens(content),\n };\n}\n\n// =============================================================================\n// Command Documentation\n// =============================================================================\n\nfunction formatCommandDoc(\n schema: CommandSchema,\n outputFormat: 'explicit' | 'json' | 'both',\n examplesPerCommand: number\n): string {\n const lines: string[] = [];\n\n // Header\n lines.push(`### \\`${schema.action}\\` — ${schema.description}`);\n lines.push('');\n\n // Roles\n const required = schema.roles.filter(r => r.required);\n const optional = schema.roles.filter(r => !r.required);\n\n if (required.length > 0) {\n lines.push('**Required roles:**');\n for (const role of required) {\n lines.push(`- \\`${role.role}\\`: ${role.description} (type: ${formatExpectedTypes(role)})`);\n }\n }\n\n if (optional.length > 0) {\n lines.push('**Optional roles:**');\n for (const role of optional) {\n lines.push(`- \\`${role.role}\\`: ${role.description} (type: ${formatExpectedTypes(role)})`);\n }\n }\n\n // Examples\n const examples = generateExamples(schema, examplesPerCommand);\n if (examples.length > 0) {\n lines.push('');\n if (outputFormat === 'explicit' || outputFormat === 'both') {\n lines.push('**Bracket syntax:**');\n for (const ex of examples) {\n lines.push(`\\`\\`\\`\\n${ex.explicit}\\n\\`\\`\\``);\n }\n }\n if (outputFormat === 'json' || outputFormat === 'both') {\n lines.push('**JSON format:**');\n for (const ex of examples) {\n lines.push(`\\`\\`\\`json\\n${JSON.stringify(ex.json, null, 2)}\\n\\`\\`\\``);\n }\n }\n }\n\n return lines.join('\\n');\n}\n\nfunction formatExpectedTypes(role: RoleSpec): string {\n return role.expectedTypes.join(' | ');\n}\n\n// =============================================================================\n// Example Generation Helpers\n// =============================================================================\n\n/**\n * Generate role combinations for example synthesis.\n * Returns arrays of RoleSpec[] representing different valid input combinations:\n * 1. Required roles only\n * 2. Required + each optional role individually\n * 3. Required + all optional roles (if different from #1 and #2)\n */\nfunction generateRoleCombinations(schema: CommandSchema): RoleSpec[][] {\n const required = schema.roles.filter(r => r.required);\n const optional = schema.roles.filter(r => !r.required);\n\n const combos: RoleSpec[][] = [];\n\n // 1. Required only\n if (required.length > 0) {\n combos.push(required);\n }\n\n // 2. Required + each optional individually\n for (const opt of optional) {\n combos.push([...required, opt]);\n }\n\n // 3. Required + all optional (if there are 2+ optional roles)\n if (optional.length >= 2) {\n combos.push([...required, ...optional]);\n }\n\n // Fallback: if schema has no required roles, use all roles\n if (combos.length === 0) {\n combos.push(schema.roles.slice());\n }\n\n return combos;\n}\n\n/**\n * Sample a value for a role based on its expected types and name.\n */\nfunction sampleValue(role: RoleSpec): { type: string; value: string | number | boolean } {\n const primaryType = role.expectedTypes[0] || 'expression';\n\n // Use role name as a heuristic for realistic values\n switch (primaryType) {\n case 'selector':\n return sampleSelector(role.role);\n case 'literal':\n return sampleLiteral(role.role);\n case 'reference':\n return { type: 'reference', value: 'me' };\n case 'expression':\n return sampleExpression(role.role);\n case 'flag':\n return { type: 'flag', value: true };\n default:\n return { type: 'literal', value: 'example' };\n }\n}\n\nfunction sampleSelector(roleName: string): { type: string; value: string } {\n const selectors: Record<string, string> = {\n patient: '.active',\n destination: '#output',\n source: '#input',\n target: '#target',\n };\n return { type: 'selector', value: selectors[roleName] || `#${roleName}` };\n}\n\nfunction sampleLiteral(roleName: string): { type: string; value: string | number } {\n const literals: Record<string, string | number> = {\n duration: '30s',\n interval: '5s',\n delay: '500ms',\n timeout: '10s',\n quantity: 5,\n limit: 10,\n style: 'json',\n manner: 'rolling',\n format: 'html',\n };\n return { type: 'literal', value: literals[roleName] || roleName };\n}\n\nfunction sampleExpression(roleName: string): { type: string; value: string } {\n const expressions: Record<string, string> = {\n source: '/api/data',\n destination: '#output',\n patient: '.active',\n instrument: 'toUpperCase',\n condition: 'age > 18',\n style: 'json',\n duration: '5s',\n url: '/api/users',\n };\n return { type: 'expression', value: expressions[roleName] || `/api/${roleName}` };\n}\n\n/**\n * Convert a sampled value into a SemanticValue for renderExplicit().\n */\nfunction toSemanticValue(sample: { type: string; value: string | number | boolean }): {\n type: string;\n value: string | number | boolean;\n raw?: string;\n dataType?: string;\n selectorKind?: string;\n} {\n switch (sample.type) {\n case 'selector':\n return {\n type: 'selector',\n value: String(sample.value),\n selectorKind: detectSelectorKind(String(sample.value)),\n };\n case 'literal':\n return {\n type: 'literal',\n value: sample.value,\n dataType:\n typeof sample.value === 'number'\n ? 'number'\n : typeof sample.value === 'boolean'\n ? 'boolean'\n : 'string',\n };\n case 'reference':\n return { type: 'reference', value: String(sample.value) };\n case 'expression':\n return { type: 'expression', value: String(sample.value), raw: String(sample.value) };\n case 'flag':\n return { type: 'flag', value: sample.value };\n default:\n return { type: 'literal', value: String(sample.value), dataType: 'string' };\n }\n}\n\nfunction detectSelectorKind(selector: string): string {\n if (selector.startsWith('#')) return 'id';\n if (selector.startsWith('.')) return 'class';\n if (selector.startsWith('[')) return 'attribute';\n return 'complex';\n}\n\n// =============================================================================\n// Token Budget\n// =============================================================================\n\nfunction estimateTokens(text: string): number {\n return Math.ceil(text.length / 4);\n}\n\nfunction truncateToTokenBudget(sections: PromptSection[], maxTokens: number): PromptSection[] {\n const result: PromptSection[] = [];\n let budget = maxTokens;\n\n for (const section of sections) {\n if (section.approximateTokens <= budget) {\n result.push(section);\n budget -= section.approximateTokens;\n } else {\n // Truncate the section to fit remaining budget (always include at least something)\n const charBudget = Math.max(budget * 4, 40);\n const truncatedContent = section.content.slice(0, charBudget) + '\\n\\n*(truncated)*';\n result.push({\n ...section,\n content: truncatedContent,\n approximateTokens: estimateTokens(truncatedContent),\n });\n break;\n }\n }\n\n return result;\n}\n","/**\n * Schema Synthesizer\n *\n * Generates synthetic (natural_language, LSE) training pairs from\n * CommandSchema[]. Enumerates valid role combinations and produces\n * examples in both bracket syntax and JSON wire format.\n */\n\nimport type { CommandSchema, RoleSpec } from '../schema/command-schema';\nimport type { SemanticJSON, SemanticJSONValue } from '../ir/types';\nimport { renderExplicit } from '../ir/explicit-renderer';\nimport { createCommandNode } from '../core/types';\nimport type { TrainingPair, SynthesisConfig, SynthesisResult, SynthesisMetadata } from './types';\n\n// =============================================================================\n// Public API\n// =============================================================================\n\n/**\n * Synthesize training pairs from command schemas.\n *\n * Generates multiple examples per command by enumerating role combinations:\n * 1. Required roles only (minimum viable)\n * 2. Required + each optional role individually\n * 3. Required + all optional roles (maximum)\n * 4. Shuffled role order variants (teaches role-label independence)\n */\nexport function synthesizeFromSchemas(\n schemas: readonly CommandSchema[],\n config: SynthesisConfig\n): SynthesisResult {\n const maxPerCommand = config.maxPairsPerCommand ?? 5;\n const minQuality = config.minQuality ?? 0.5;\n const shuffleRoles = config.shuffleRoles ?? true;\n const languages = config.languages ?? ['en'];\n\n const pairs: TrainingPair[] = [];\n let idCounter = 0;\n\n for (const schema of schemas) {\n const combos = generateRoleCombinations(schema);\n\n for (const language of languages) {\n let commandPairCount = 0;\n\n for (const combo of combos) {\n if (commandPairCount >= maxPerCommand) break;\n\n const pair = buildTrainingPair(\n schema,\n combo,\n language,\n config.domain,\n `${config.domain}-synth-${idCounter++}`\n );\n\n if (pair.quality >= minQuality) {\n pairs.push(pair);\n commandPairCount++;\n }\n\n // Generate shuffled variant\n if (shuffleRoles && combo.length >= 2 && commandPairCount < maxPerCommand) {\n const shuffled = [...combo].reverse();\n const shuffledPair = buildTrainingPair(\n schema,\n shuffled,\n language,\n config.domain,\n `${config.domain}-synth-${idCounter++}`\n );\n if (shuffledPair.quality >= minQuality) {\n pairs.push(shuffledPair);\n commandPairCount++;\n }\n }\n }\n }\n }\n\n const metadata: SynthesisMetadata = {\n domain: config.domain,\n commandCount: schemas.length,\n pairCount: pairs.length,\n bySource: { synthetic: pairs.length },\n languages,\n };\n\n return { pairs, metadata };\n}\n\n// =============================================================================\n// Role Combination Generation\n// =============================================================================\n\nfunction generateRoleCombinations(schema: CommandSchema): RoleSpec[][] {\n const required = schema.roles.filter(r => r.required);\n const optional = schema.roles.filter(r => !r.required);\n\n const combos: RoleSpec[][] = [];\n\n // 1. Required only\n if (required.length > 0) {\n combos.push(required);\n }\n\n // 2. Required + each optional individually\n for (const opt of optional) {\n combos.push([...required, opt]);\n }\n\n // 3. Required + all optional (if 2+ optional)\n if (optional.length >= 2) {\n combos.push([...required, ...optional]);\n }\n\n // Fallback: if no required roles, use all roles\n if (combos.length === 0) {\n combos.push(schema.roles.slice());\n }\n\n return combos;\n}\n\n// =============================================================================\n// Pair Building\n// =============================================================================\n\nfunction buildTrainingPair(\n schema: CommandSchema,\n roles: RoleSpec[],\n language: string,\n domain: string,\n id: string\n): TrainingPair {\n const sampledRoles = new Map<string, { type: string; value: string | number | boolean }>();\n\n for (const role of roles) {\n sampledRoles.set(role.role, sampleValue(role));\n }\n\n // Build SemanticNode for bracket syntax\n const nodeRoles = new Map<string, unknown>();\n for (const [name, sample] of sampledRoles) {\n nodeRoles.set(name, toSemanticValue(sample));\n }\n const node = createCommandNode(schema.action, nodeRoles as never);\n const explicit = renderExplicit(node);\n\n // Build JSON format\n const jsonRoles: Record<string, SemanticJSONValue> = {};\n for (const [name, sample] of sampledRoles) {\n jsonRoles[name] = sample as SemanticJSONValue;\n }\n const json: SemanticJSON = { action: schema.action, roles: jsonRoles };\n\n // Build natural language form\n const natural = buildNaturalForm(schema, sampledRoles, language);\n\n // Quality: synthetic pairs get a base quality, higher if more roles are filled\n const requiredCount = schema.roles.filter(r => r.required).length;\n const filledRequired = roles.filter(r => r.required).length;\n const quality = requiredCount > 0 ? filledRequired / requiredCount : 0.8;\n\n return {\n id,\n natural,\n language,\n explicit,\n json,\n domain,\n action: schema.action,\n source: 'synthetic',\n quality,\n };\n}\n\n/**\n * Build a natural language form from sampled roles.\n * Uses marker overrides for the given language when available.\n */\nfunction buildNaturalForm(\n schema: CommandSchema,\n roles: Map<string, { type: string; value: string | number | boolean }>,\n language: string\n): string {\n const parts: string[] = [schema.action];\n\n for (const roleSpec of schema.roles) {\n const sample = roles.get(roleSpec.role);\n if (!sample) continue;\n\n const marker = roleSpec.markerOverride?.[language];\n if (marker) {\n parts.push(marker);\n }\n parts.push(String(sample.value));\n }\n\n return parts.join(' ');\n}\n\n// =============================================================================\n// Value Sampling\n// =============================================================================\n\nfunction sampleValue(role: RoleSpec): { type: string; value: string | number | boolean } {\n const primaryType = role.expectedTypes[0] || 'expression';\n\n switch (primaryType) {\n case 'selector':\n return sampleSelector(role.role);\n case 'literal':\n return sampleLiteral(role.role);\n case 'reference':\n return { type: 'reference', value: 'me' };\n case 'expression':\n return sampleExpression(role.role);\n case 'flag':\n return { type: 'flag', value: true };\n default:\n return { type: 'literal', value: 'example' };\n }\n}\n\nfunction sampleSelector(roleName: string): { type: string; value: string } {\n const selectors: Record<string, string> = {\n patient: '.active',\n destination: '#output',\n source: '#input',\n target: '#target',\n };\n return { type: 'selector', value: selectors[roleName] || `#${roleName}` };\n}\n\nfunction sampleLiteral(roleName: string): { type: string; value: string | number } {\n const literals: Record<string, string | number> = {\n duration: '30s',\n interval: '5s',\n delay: '500ms',\n timeout: '10s',\n quantity: 5,\n limit: 10,\n style: 'json',\n manner: 'rolling',\n format: 'html',\n };\n return { type: 'literal', value: literals[roleName] || roleName };\n}\n\nfunction sampleExpression(roleName: string): { type: string; value: string } {\n const expressions: Record<string, string> = {\n source: '/api/data',\n destination: '#output',\n patient: '.active',\n instrument: 'toUpperCase',\n condition: 'age > 18',\n style: 'json',\n duration: '5s',\n url: '/api/users',\n };\n return { type: 'expression', value: expressions[roleName] || `/api/${roleName}` };\n}\n\nfunction toSemanticValue(sample: { type: string; value: string | number | boolean }): {\n type: string;\n value: string | number | boolean;\n raw?: string;\n dataType?: string;\n selectorKind?: string;\n} {\n switch (sample.type) {\n case 'selector':\n return {\n type: 'selector',\n value: String(sample.value),\n selectorKind: detectSelectorKind(String(sample.value)),\n };\n case 'literal':\n return {\n type: 'literal',\n value: sample.value,\n dataType:\n typeof sample.value === 'number'\n ? 'number'\n : typeof sample.value === 'boolean'\n ? 'boolean'\n : 'string',\n };\n case 'reference':\n return { type: 'reference', value: String(sample.value) };\n case 'expression':\n return { type: 'expression', value: String(sample.value), raw: String(sample.value) };\n case 'flag':\n return { type: 'flag', value: sample.value };\n default:\n return { type: 'literal', value: String(sample.value), dataType: 'string' };\n }\n}\n\nfunction detectSelectorKind(selector: string): string {\n if (selector.startsWith('#')) return 'id';\n if (selector.startsWith('.')) return 'class';\n if (selector.startsWith('[')) return 'attribute';\n return 'complex';\n}\n","/**\n * Feedback Formatter\n *\n * Maps diagnostics to machine-actionable LSEFeedback with hints,\n * corrected examples, and schema context. Enables LLMs to self-correct\n * based on structured error information.\n */\n\nimport type { Diagnostic } from '../generation/diagnostics';\nimport type { CommandSchema } from '../schema/command-schema';\nimport type { SchemaLookup, SemanticJSON, SemanticJSONValue } from '../ir/types';\nimport { renderExplicit } from '../ir/explicit-renderer';\nimport { createCommandNode } from '../core/types';\nimport type { LSEFeedback, FeedbackDiagnostic, FixType } from './types';\n\n// =============================================================================\n// Public API\n// =============================================================================\n\n/**\n * Build structured feedback from diagnostics and optional schema context.\n *\n * @param input - The original input text\n * @param inputFormat - Format of the input\n * @param diagnostics - Error diagnostics from validation/parsing\n * @param schemaLookup - Optional schema lookup for generating hints and corrections\n * @param action - The attempted command action (if identifiable)\n */\nexport function buildFeedback(\n input: string,\n inputFormat: 'explicit' | 'json' | 'natural',\n diagnostics: readonly Diagnostic[],\n schemaLookup?: SchemaLookup,\n action?: string\n): LSEFeedback {\n const hasErrors = diagnostics.some(d => d.severity === 'error');\n const feedbackDiagnostics = diagnostics.map(d => toFeedbackDiagnostic(d));\n const hints = generateHints(feedbackDiagnostics, schemaLookup, action);\n\n let schemaInfo: LSEFeedback['schema'] | undefined;\n let correctedExample: LSEFeedback['correctedExample'] | undefined;\n\n if (action && schemaLookup) {\n const schema = schemaLookup.getSchema(action);\n if (schema) {\n schemaInfo = extractSchemaInfo(schema);\n if (hasErrors) {\n correctedExample = generateCorrectedExample(schema);\n }\n }\n }\n\n return {\n accepted: !hasErrors,\n input: { format: inputFormat, text: input },\n diagnostics: feedbackDiagnostics,\n hints,\n ...(schemaInfo && { schema: schemaInfo }),\n ...(correctedExample && { correctedExample }),\n };\n}\n\n// =============================================================================\n// Diagnostic Classification\n// =============================================================================\n\n/**\n * Map a framework Diagnostic to a FeedbackDiagnostic with fix type.\n */\nfunction toFeedbackDiagnostic(d: Diagnostic): FeedbackDiagnostic {\n const fixType = classifyFixType(d);\n return {\n severity: d.severity,\n code: d.code || 'unknown',\n message: d.message,\n ...(d.suggestions?.[0] && { suggestion: d.suggestions[0] }),\n ...(fixType && { fixType }),\n };\n}\n\n/**\n * Classify a diagnostic into a machine-actionable fix type.\n */\nfunction classifyFixType(d: Diagnostic): FixType | undefined {\n const code = (d.code || '').toLowerCase();\n const msg = d.message.toLowerCase();\n\n // Missing required role\n if (\n code.includes('missing-role') ||\n code.includes('missing_role') ||\n msg.includes('required role') ||\n msg.includes('missing role')\n ) {\n return 'missing_role';\n }\n\n // Invalid value type\n if (\n code.includes('invalid-type') ||\n code.includes('invalid_type') ||\n code.includes('type-mismatch') ||\n msg.includes('invalid type') ||\n msg.includes('expected type')\n ) {\n return 'invalid_type';\n }\n\n // Unknown command\n if (\n code.includes('unknown-command') ||\n code.includes('unknown_command') ||\n msg.includes('unknown command') ||\n (msg.includes('not recognized') && msg.includes('command'))\n ) {\n return 'unknown_command';\n }\n\n // Unknown role\n if (\n code.includes('unknown-role') ||\n code.includes('unknown_role') ||\n msg.includes('unknown role') ||\n (msg.includes('not recognized') && msg.includes('role'))\n ) {\n return 'unknown_role';\n }\n\n // Syntax error (catch-all for parse errors)\n if (\n code.includes('parse') ||\n code.includes('syntax') ||\n msg.includes('syntax error') ||\n msg.includes('parse error') ||\n msg.includes('unexpected')\n ) {\n return 'syntax_error';\n }\n\n return undefined;\n}\n\n// =============================================================================\n// Hint Generation\n// =============================================================================\n\nfunction generateHints(\n diagnostics: readonly FeedbackDiagnostic[],\n schemaLookup?: SchemaLookup,\n action?: string\n): string[] {\n const hints: string[] = [];\n const schema = action && schemaLookup ? schemaLookup.getSchema(action) : undefined;\n\n for (const d of diagnostics) {\n if (d.severity !== 'error') continue;\n\n switch (d.fixType) {\n case 'missing_role': {\n if (schema) {\n const required = schema.roles\n .filter(r => r.required)\n .map(r => `'${r.role}' (${r.description}, type: ${r.expectedTypes.join('|')})`)\n .join(', ');\n hints.push(`Required roles for '${action}': ${required}`);\n } else {\n hints.push('Check that all required roles are present.');\n }\n break;\n }\n\n case 'unknown_command': {\n hints.push(\n `Command not recognized. Ensure you're using a valid command from the domain schema.`\n );\n break;\n }\n\n case 'unknown_role': {\n if (schema) {\n const validRoles = schema.roles.map(r => `'${r.role}'`).join(', ');\n hints.push(`Valid roles for '${action}': ${validRoles}`);\n } else {\n hints.push('Use only roles defined in the command schema.');\n }\n break;\n }\n\n case 'invalid_type': {\n hints.push(\n 'Check value types: selectors start with #.[@*, strings use quotes, numbers are plain digits.'\n );\n break;\n }\n\n case 'syntax_error': {\n hints.push('Ensure bracket syntax: [command role:value ...]. No spaces around the colon.');\n break;\n }\n\n default: {\n if (d.suggestion) {\n hints.push(d.suggestion);\n }\n }\n }\n }\n\n // Deduplicate\n return [...new Set(hints)];\n}\n\n// =============================================================================\n// Schema Info Extraction\n// =============================================================================\n\nfunction extractSchemaInfo(schema: CommandSchema): LSEFeedback['schema'] {\n const requiredRoles: string[] = [];\n const optionalRoles: string[] = [];\n const roleDescriptions: Record<string, string> = {};\n\n for (const role of schema.roles) {\n if (role.required) {\n requiredRoles.push(role.role);\n } else {\n optionalRoles.push(role.role);\n }\n roleDescriptions[role.role] = role.description;\n }\n\n return {\n action: schema.action,\n requiredRoles,\n optionalRoles,\n roleDescriptions,\n };\n}\n\n// =============================================================================\n// Corrected Example Generation\n// =============================================================================\n\nfunction generateCorrectedExample(schema: CommandSchema): { explicit: string; json: SemanticJSON } {\n const roles = new Map<string, unknown>();\n const jsonRoles: Record<string, SemanticJSONValue> = {};\n\n for (const role of schema.roles) {\n if (!role.required) continue;\n const sample = sampleDefaultValue(role.role, role.expectedTypes[0] || 'expression');\n roles.set(role.role, toSemanticValue(sample));\n jsonRoles[role.role] = sample as SemanticJSONValue;\n }\n\n const node = createCommandNode(schema.action, roles as never);\n const explicit = renderExplicit(node);\n const json: SemanticJSON = { action: schema.action, roles: jsonRoles };\n\n return { explicit, json };\n}\n\nfunction sampleDefaultValue(\n roleName: string,\n expectedType: string\n): { type: string; value: string } {\n switch (expectedType) {\n case 'selector':\n return { type: 'selector', value: `#${roleName}` };\n case 'expression':\n return { type: 'expression', value: `<${roleName}-value>` };\n case 'literal':\n return { type: 'literal', value: `<${roleName}-value>` };\n case 'reference':\n return { type: 'reference', value: 'me' };\n default:\n return { type: 'expression', value: `<${roleName}-value>` };\n }\n}\n\nfunction toSemanticValue(sample: { type: string; value: string }): {\n type: string;\n value: string;\n raw?: string;\n selectorKind?: string;\n dataType?: string;\n} {\n switch (sample.type) {\n case 'selector':\n return { type: 'selector', value: sample.value, selectorKind: 'id' };\n case 'expression':\n return { type: 'expression', value: sample.value, raw: sample.value };\n case 'literal':\n return { type: 'literal', value: sample.value, dataType: 'string' };\n case 'reference':\n return { type: 'reference', value: sample.value };\n default:\n return { type: 'literal', value: sample.value, dataType: 'string' };\n }\n}\n","/**\n * Domain Registry\n *\n * Provides auto-discovery and registration of framework domains for MCP servers.\n * Instead of hardcoding tool definitions and dispatch logic per domain, domains\n * export a `DomainDescriptor` and the registry generates everything automatically.\n *\n * @example\n * ```typescript\n * import { DomainRegistry } from '@lokascript/framework';\n *\n * const registry = new DomainRegistry();\n *\n * // Register domains (each provides a descriptor)\n * registry.register({\n * name: 'sql',\n * description: 'Natural language SQL',\n * languages: ['en', 'es', 'ja', 'ar'],\n * inputLabel: 'query',\n * inputDescription: 'SQL query in natural language',\n * getDSL: () => import('@lokascript/domain-sql').then(m => m.createSQLDSL()),\n * getRenderer: () => import('@lokascript/domain-sql').then(m => m.renderSQL),\n * });\n *\n * // Auto-generate MCP tool definitions\n * const tools = registry.getToolDefinitions();\n *\n * // Dispatch a tool call\n * const result = await registry.handleToolCall('parse_sql', { query: 'select name from users' });\n * ```\n */\n\nimport type { SemanticNode } from '../core/types';\nimport type { MultilingualDSL, CompileResult, ValidationResult } from './create-dsl';\nimport type { NaturalLanguageRenderer } from '../generation/renderer';\nimport type { CommandSchema } from '../schema/command-schema';\nimport type { SchemaLookup } from '../ir/types';\nimport type { Diagnostic } from '../generation/diagnostics';\nimport type { GeneratedPrompt, PromptGeneratorConfig } from '../prompts/types';\nimport type { SynthesisConfig, SynthesisResult } from '../training/types';\nimport type { LSEFeedback } from '../feedback/types';\nimport { generatePrompt as _generatePrompt } from '../prompts/prompt-generator';\nimport { synthesizeFromSchemas as _synthesizeFromSchemas } from '../training/schema-synthesizer';\nimport { buildFeedback as _buildFeedback } from '../feedback/feedback-formatter';\nimport { parseExplicit as _parseExplicit } from '../ir/explicit-parser';\n\n// =============================================================================\n// Descriptor Interface\n// =============================================================================\n\n/**\n * Describes a domain for auto-registration in MCP servers.\n *\n * Domains provide this descriptor to the registry, which generates\n * tool definitions and handles dispatch automatically.\n */\nexport interface DomainDescriptor {\n /** Short identifier (used in tool names: parse_{name}, compile_{name}, etc.) */\n readonly name: string;\n\n /** Human-readable description */\n readonly description: string;\n\n /** Supported language codes */\n readonly languages: readonly string[];\n\n /** Label for the primary input parameter (e.g., 'query', 'scenario', 'code') */\n readonly inputLabel: string;\n\n /** Description of the primary input parameter */\n readonly inputDescription: string;\n\n /** What compile_{name} produces (e.g., \"a SQL query string\"). Used in tool description. */\n readonly outputDescription?: string;\n\n /**\n * Factory to lazily create the DSL instance.\n * Called once on first tool use. The result is cached.\n */\n readonly getDSL: () => MultilingualDSL | Promise<MultilingualDSL>;\n\n /**\n * Factory to lazily create the renderer.\n * Required for translate_{name} tool. Called once on first use.\n */\n readonly getRenderer?: () =>\n | NaturalLanguageRenderer\n | ((node: SemanticNode, language: string) => string)\n | Promise<NaturalLanguageRenderer | ((node: SemanticNode, language: string) => string)>;\n\n /**\n * Which standard tools to generate. Default: all four.\n */\n readonly tools?: readonly ('parse' | 'compile' | 'validate' | 'translate')[];\n\n /**\n * Optional command schemas for this domain.\n * When provided, enables system prompt generation, training data synthesis,\n * and structured feedback via the registry's convenience methods.\n */\n readonly schemas?: readonly CommandSchema[];\n\n /**\n * Optional scan configuration for AOT compilation and Vite plugin.\n * Declares which HTML attributes/script types this domain uses.\n */\n readonly scanConfig?: {\n /** Attribute names to scan for (e.g., ['data-sql', '_sql']) */\n readonly attributes: readonly string[];\n /** Script tag types to scan for (e.g., ['text/sql-dsl']) */\n readonly scriptTypes?: readonly string[];\n /** Default language when not specified on element */\n readonly defaultLanguage?: string;\n /** Keywords for detection, keyed by language code */\n readonly keywords?: Readonly<Record<string, readonly string[]>>;\n };\n}\n\n// =============================================================================\n// MCP Tool Types (minimal — compatible with @modelcontextprotocol/sdk)\n// =============================================================================\n\n/**\n * MCP tool definition. Compatible with the MCP SDK's tool schema.\n */\nexport interface MCPToolDefinition {\n readonly name: string;\n readonly description: string;\n readonly inputSchema: {\n readonly type: 'object';\n readonly properties: Record<string, unknown>;\n readonly required: readonly string[];\n };\n}\n\n/**\n * MCP tool response. Compatible with the MCP SDK's response format.\n */\nexport interface MCPToolResponse {\n readonly content: ReadonlyArray<{ readonly type: string; readonly text: string }>;\n readonly isError?: boolean;\n}\n\n// =============================================================================\n// Domain Registry\n// =============================================================================\n\n/**\n * Registry for framework domains.\n *\n * Manages domain descriptors, generates MCP tool definitions,\n * and dispatches tool calls to the appropriate domain.\n */\nexport class DomainRegistry {\n private descriptors = new Map<string, DomainDescriptor>();\n private dslCache = new Map<string, MultilingualDSL>();\n private rendererCache = new Map<\n string,\n NaturalLanguageRenderer | ((node: SemanticNode, language: string) => string)\n >();\n\n /**\n * Register a domain.\n * @throws if a domain with the same name is already registered\n */\n register(descriptor: DomainDescriptor): void {\n if (this.descriptors.has(descriptor.name)) {\n throw new Error(`Domain already registered: ${descriptor.name}`);\n }\n this.descriptors.set(descriptor.name, descriptor);\n }\n\n /**\n * Attach schemas to an already-registered domain.\n * Useful for lazy loading schemas after initial registration.\n */\n setSchemas(name: string, schemas: readonly CommandSchema[]): void {\n const existing = this.descriptors.get(name);\n if (!existing) {\n throw new Error(`Domain not registered: ${name}`);\n }\n // Create a new descriptor with schemas attached\n this.descriptors.set(name, { ...existing, schemas });\n }\n\n /**\n * Get all registered domain names.\n */\n getDomainNames(): string[] {\n return Array.from(this.descriptors.keys());\n }\n\n /**\n * Get a specific domain descriptor.\n */\n getDescriptor(name: string): DomainDescriptor | undefined {\n return this.descriptors.get(name);\n }\n\n /**\n * Generate MCP tool definitions for all registered domains.\n */\n getToolDefinitions(): MCPToolDefinition[] {\n const tools: MCPToolDefinition[] = [];\n for (const desc of this.descriptors.values()) {\n tools.push(...generateToolDefinitions(desc));\n }\n return tools;\n }\n\n /**\n * Check if a tool name belongs to a registered domain.\n */\n canHandle(toolName: string): boolean {\n const parsed = parseToolName(toolName);\n if (!parsed) return false;\n return this.descriptors.has(parsed.domain);\n }\n\n /**\n * Handle a tool call by dispatching to the appropriate domain.\n * Returns null if the tool name doesn't match any registered domain.\n */\n async handleToolCall(\n toolName: string,\n args: Record<string, unknown>\n ): Promise<MCPToolResponse | null> {\n const parsed = parseToolName(toolName);\n if (!parsed) return null;\n\n const descriptor = this.descriptors.get(parsed.domain);\n if (!descriptor) return null;\n\n try {\n const dsl = await this.getDSL(descriptor);\n\n switch (parsed.operation) {\n case 'parse':\n return await this.handleParse(descriptor, dsl, args);\n case 'compile':\n return await this.handleCompile(descriptor, dsl, args);\n case 'validate':\n return await this.handleValidate(descriptor, dsl, args);\n case 'translate':\n return await this.handleTranslate(descriptor, dsl, args);\n default:\n return jsonResponse({ error: `Unknown operation: ${parsed.operation}` }, true);\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return jsonResponse({ error: `${descriptor.name} tool error: ${message}` }, true);\n }\n }\n\n /**\n * Get the DSL instance for a named domain.\n * Returns null if the domain is not registered.\n * The DSL is lazily created and cached.\n */\n async getDSLForDomain(name: string): Promise<MultilingualDSL | null> {\n const descriptor = this.descriptors.get(name);\n if (!descriptor) return null;\n return this.getDSL(descriptor);\n }\n\n // ---------------------------------------------------------------------------\n // LLM ↔ LSE Convenience Methods\n // ---------------------------------------------------------------------------\n\n /**\n * Generate an LLM system prompt for a domain from its schemas.\n * Returns null if the domain is not registered or has no schemas.\n */\n generatePrompt(domain: string, config?: Partial<PromptGeneratorConfig>): GeneratedPrompt | null {\n const descriptor = this.descriptors.get(domain);\n if (!descriptor?.schemas || descriptor.schemas.length === 0) return null;\n\n return _generatePrompt({\n domain,\n description: descriptor.description,\n schemas: descriptor.schemas,\n ...config,\n });\n }\n\n /**\n * Synthesize training data for a domain from its schemas.\n * Returns null if the domain is not registered or has no schemas.\n */\n generateTrainingData(domain: string, config?: Partial<SynthesisConfig>): SynthesisResult | null {\n const descriptor = this.descriptors.get(domain);\n if (!descriptor?.schemas || descriptor.schemas.length === 0) return null;\n\n return _synthesizeFromSchemas(descriptor.schemas, {\n domain,\n ...config,\n });\n }\n\n /**\n * Build structured feedback for a failed LSE input in a domain.\n * Returns null if the domain is not registered or has no schemas.\n */\n buildFeedback(\n domain: string,\n input: string,\n inputFormat: 'explicit' | 'json' | 'natural',\n diagnostics: readonly Diagnostic[]\n ): LSEFeedback | null {\n const descriptor = this.descriptors.get(domain);\n if (!descriptor?.schemas || descriptor.schemas.length === 0) return null;\n\n const schemaLookup = this.createSchemaLookup(descriptor.schemas);\n\n // Try to extract the action from the input\n let action: string | undefined;\n try {\n if (inputFormat === 'explicit') {\n const node = _parseExplicit(input, { schemaLookup });\n action = node.action;\n }\n } catch {\n // Action detection failed — still build feedback without it\n }\n\n return _buildFeedback(input, inputFormat, diagnostics, schemaLookup, action);\n }\n\n /**\n * Get schemas for a domain (if available).\n */\n getSchemas(domain: string): readonly CommandSchema[] | null {\n const descriptor = this.descriptors.get(domain);\n if (!descriptor?.schemas) return null;\n return descriptor.schemas;\n }\n\n /**\n * Create a SchemaLookup from a domain's schemas.\n */\n private createSchemaLookup(schemas: readonly CommandSchema[]): SchemaLookup {\n const map = new Map<string, CommandSchema>();\n for (const s of schemas) {\n map.set(s.action, s);\n }\n return { getSchema: (action: string) => map.get(action) };\n }\n\n // ---------------------------------------------------------------------------\n // Private: DSL/renderer lifecycle\n // ---------------------------------------------------------------------------\n\n private async getDSL(descriptor: DomainDescriptor): Promise<MultilingualDSL> {\n const cached = this.dslCache.get(descriptor.name);\n if (cached) return cached;\n\n const dsl = await descriptor.getDSL();\n this.dslCache.set(descriptor.name, dsl);\n return dsl;\n }\n\n private async getRenderer(\n descriptor: DomainDescriptor\n ): Promise<NaturalLanguageRenderer | ((node: SemanticNode, language: string) => string) | null> {\n if (!descriptor.getRenderer) return null;\n\n const cached = this.rendererCache.get(descriptor.name);\n if (cached) return cached;\n\n const renderer = await descriptor.getRenderer();\n this.rendererCache.set(descriptor.name, renderer);\n return renderer;\n }\n\n // ---------------------------------------------------------------------------\n // Private: Tool handlers\n // ---------------------------------------------------------------------------\n\n private async handleParse(\n descriptor: DomainDescriptor,\n dsl: MultilingualDSL,\n args: Record<string, unknown>\n ): Promise<MCPToolResponse> {\n const input = getString(args, descriptor.inputLabel);\n if (!input) return missingParam(descriptor.inputLabel);\n const language = getString(args, 'language', 'en');\n\n const node = dsl.parse(input, language);\n\n const roles: Record<string, unknown> = {};\n for (const [key, value] of node.roles) {\n roles[key] = value;\n }\n\n return jsonResponse({\n action: node.action,\n roles,\n language,\n [descriptor.inputLabel]: input,\n });\n }\n\n private async handleCompile(\n descriptor: DomainDescriptor,\n dsl: MultilingualDSL,\n args: Record<string, unknown>\n ): Promise<MCPToolResponse> {\n const input = getString(args, descriptor.inputLabel);\n if (!input) return missingParam(descriptor.inputLabel);\n const language = getString(args, 'language', 'en');\n\n const result: CompileResult = dsl.compile(input, language);\n\n return jsonResponse({\n ok: result.ok,\n code: result.code,\n errors: result.errors,\n language,\n input,\n });\n }\n\n private async handleValidate(\n descriptor: DomainDescriptor,\n dsl: MultilingualDSL,\n args: Record<string, unknown>\n ): Promise<MCPToolResponse> {\n const input = getString(args, descriptor.inputLabel);\n if (!input) return missingParam(descriptor.inputLabel);\n const language = getString(args, 'language', 'en');\n\n const result: ValidationResult = dsl.validate(input, language);\n\n return jsonResponse({\n valid: result.valid,\n errors: result.errors,\n language,\n [descriptor.inputLabel]: input,\n });\n }\n\n private async handleTranslate(\n descriptor: DomainDescriptor,\n dsl: MultilingualDSL,\n args: Record<string, unknown>\n ): Promise<MCPToolResponse> {\n const input = getString(args, descriptor.inputLabel);\n if (!input) return missingParam(descriptor.inputLabel);\n const from = getString(args, 'from');\n if (!from) return missingParam('from');\n const to = getString(args, 'to');\n if (!to) return missingParam('to');\n\n // Parse in source language\n const node = dsl.parse(input, from);\n\n // Compile (language-neutral output)\n const compiled = dsl.compile(input, from);\n\n // Render to target language\n let rendered: string | null = null;\n const renderer = await this.getRenderer(descriptor);\n if (renderer) {\n try {\n rendered = typeof renderer === 'function' ? renderer(node, to) : renderer.render(node, to);\n } catch {\n // Fall through with rendered = null\n }\n }\n\n const roles: Record<string, unknown> = {};\n for (const [key, value] of node.roles) {\n roles[key] = value;\n }\n\n return jsonResponse({\n input: { [descriptor.inputLabel]: input, language: from },\n ...(rendered != null && { rendered: { text: rendered, language: to } }),\n semantic: { action: node.action, roles },\n ...(compiled.ok && compiled.code != null && { compiled: compiled.code }),\n });\n }\n}\n\n// =============================================================================\n// Tool Definition Generator\n// =============================================================================\n\nfunction generateToolDefinitions(desc: DomainDescriptor): MCPToolDefinition[] {\n const tools: MCPToolDefinition[] = [];\n const ops = desc.tools ?? (['parse', 'compile', 'validate', 'translate'] as const);\n const langList = desc.languages.join(', ');\n\n for (const op of ops) {\n switch (op) {\n case 'parse':\n tools.push({\n name: `parse_${desc.name}`,\n description: `Parse a ${desc.description} input into a semantic representation (action, roles, confidence). Supports: ${langList}.`,\n inputSchema: {\n type: 'object',\n properties: {\n [desc.inputLabel]: {\n type: 'string',\n description: desc.inputDescription,\n },\n language: {\n type: 'string',\n description: `Language code: ${langList}`,\n default: 'en',\n },\n },\n required: [desc.inputLabel],\n },\n });\n break;\n\n case 'compile':\n tools.push({\n name: `compile_${desc.name}`,\n description: `Compile a ${desc.description} input to ${desc.outputDescription ?? 'target code'}. Supports: ${langList}.`,\n inputSchema: {\n type: 'object',\n properties: {\n [desc.inputLabel]: {\n type: 'string',\n description: desc.inputDescription,\n },\n language: {\n type: 'string',\n description: `Language code: ${langList}`,\n default: 'en',\n },\n },\n required: [desc.inputLabel],\n },\n });\n break;\n\n case 'validate':\n tools.push({\n name: `validate_${desc.name}`,\n description: `Check ${desc.description} syntax for errors. Returns {valid, errors[]}. Supports: ${langList}.`,\n inputSchema: {\n type: 'object',\n properties: {\n [desc.inputLabel]: {\n type: 'string',\n description: `${desc.inputDescription} to validate`,\n },\n language: {\n type: 'string',\n description: `Language code: ${langList}`,\n default: 'en',\n },\n },\n required: [desc.inputLabel],\n },\n });\n break;\n\n case 'translate':\n tools.push({\n name: `translate_${desc.name}`,\n description: `Translate ${desc.description} input between natural languages (requires 'from' and 'to' codes). Supports: ${langList}.`,\n inputSchema: {\n type: 'object',\n properties: {\n [desc.inputLabel]: {\n type: 'string',\n description: `${desc.inputDescription} to translate`,\n },\n from: {\n type: 'string',\n description: `Source language code: ${langList}`,\n },\n to: {\n type: 'string',\n description: `Target language code: ${langList}`,\n },\n },\n required: [desc.inputLabel, 'from', 'to'],\n },\n });\n break;\n }\n }\n\n return tools;\n}\n\n// =============================================================================\n// Helpers\n// =============================================================================\n\nfunction parseToolName(name: string): { operation: string; domain: string } | null {\n const match = name.match(/^(parse|compile|validate|translate)_(.+)$/);\n if (!match) return null;\n return { operation: match[1], domain: match[2] };\n}\n\nfunction getString(args: Record<string, unknown>, name: string, defaultValue = ''): string {\n const value = args[name];\n return typeof value === 'string' ? value : defaultValue;\n}\n\nfunction jsonResponse(data: unknown, isError?: boolean): MCPToolResponse {\n return {\n content: [{ type: 'text', text: JSON.stringify(data, null, 2) }],\n ...(isError && { isError: true }),\n };\n}\n\nfunction missingParam(param: string): MCPToolResponse {\n return jsonResponse({ error: `Missing required parameter: ${param}` }, true);\n}\n","/**\n * Cross-Domain Dispatcher\n *\n * Routes natural-language input to the correct domain by trying all registered\n * domains and picking the highest-confidence match. Supports auto-detection,\n * composite multi-line parsing, and confidence-based routing.\n *\n * @example\n * ```typescript\n * import { DomainRegistry, CrossDomainDispatcher } from '@lokascript/framework';\n *\n * const registry = new DomainRegistry();\n * registry.register(sqlDescriptor);\n * registry.register(bddDescriptor);\n *\n * const dispatcher = new CrossDomainDispatcher(registry);\n *\n * // Auto-detect which domain handles the input\n * const result = await dispatcher.detect('select name from users', 'en');\n * // → { domain: 'sql', node: ..., confidence: 0.95, dsl: ... }\n *\n * // Parse multi-line input across domains\n * const composite = await dispatcher.parseComposite(`\n * select name from users\n * given page http://localhost\n * `, 'en');\n * ```\n */\n\nimport type { SemanticNode } from '../core/types';\nimport type { MultilingualDSL, CompileResult, ValidationResult } from './create-dsl';\nimport { DomainRegistry } from './domain-registry';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/** Result of domain auto-detection */\nexport interface DispatchResult {\n /** The domain that matched */\n readonly domain: string;\n /** Parsed semantic node */\n readonly node: SemanticNode;\n /** Confidence score (0-1) */\n readonly confidence: number;\n /** The DSL instance that parsed it */\n readonly dsl: MultilingualDSL;\n}\n\n/** A single statement in a composite parse result */\nexport interface CompositeStatement {\n readonly line: number;\n readonly input: string;\n readonly domain: string;\n readonly node: SemanticNode;\n readonly confidence: number;\n}\n\n/** An error from a composite parse */\nexport interface CompositeError {\n readonly line: number;\n readonly input: string;\n readonly message: string;\n}\n\n/** Result of multi-domain composite parsing */\nexport interface CompositeParseResult {\n /** Successfully parsed statements */\n readonly statements: readonly CompositeStatement[];\n /** Lines that could not be matched to any domain */\n readonly errors: readonly CompositeError[];\n}\n\n/** A single compiled statement in a composite compile result */\nexport interface CompositeCompileStatement {\n readonly line: number;\n readonly input: string;\n readonly domain: string;\n readonly ok: boolean;\n readonly code?: string | undefined;\n readonly errors?: string[] | undefined;\n}\n\n/** Result of multi-domain composite compilation */\nexport interface CompositeCompileResult {\n /** Successfully detected and compiled statements */\n readonly statements: readonly CompositeCompileStatement[];\n /** Lines that could not be matched to any domain */\n readonly errors: readonly CompositeError[];\n}\n\n/** Dispatcher configuration options */\nexport interface DispatcherOptions {\n /** Minimum confidence to accept a match (default: 0.5) */\n readonly minConfidence?: number;\n /** Domain priority order — earlier domains win on confidence ties */\n readonly priority?: readonly string[];\n}\n\n// =============================================================================\n// Comment line detection\n// =============================================================================\n\nconst COMMENT_PATTERN = /^\\s*(\\/\\/|--|#)/;\n\nfunction isSkippableLine(line: string): boolean {\n const trimmed = line.trim();\n return trimmed === '' || COMMENT_PATTERN.test(trimmed);\n}\n\n// =============================================================================\n// CrossDomainDispatcher\n// =============================================================================\n\n/**\n * Dispatcher that routes input to the correct domain by confidence scoring.\n *\n * Built on top of DomainRegistry — uses registered domains' DSL instances\n * to try parsing input and picks the highest-confidence match.\n */\nexport class CrossDomainDispatcher {\n private registry: DomainRegistry;\n private minConfidence: number;\n private priority: readonly string[];\n\n constructor(registry: DomainRegistry, options?: DispatcherOptions) {\n this.registry = registry;\n this.minConfidence = options?.minConfidence ?? 0.5;\n this.priority = options?.priority ?? [];\n }\n\n /**\n * Auto-detect which domain handles the input.\n * Tries all registered domains and returns the highest-confidence match.\n * Returns null if no domain matches above minConfidence.\n */\n async detect(input: string, language = 'en'): Promise<DispatchResult | null> {\n const domainNames = this.registry.getDomainNames();\n if (domainNames.length === 0) return null;\n\n const candidates: DispatchResult[] = [];\n\n for (const name of domainNames) {\n try {\n const dsl = await this.registry.getDSLForDomain(name);\n if (!dsl) continue;\n\n const { node, confidence } = dsl.parseWithConfidence(input, language);\n if (confidence >= this.minConfidence) {\n candidates.push({ domain: name, node, confidence, dsl });\n }\n } catch {\n // Domain could not be loaded or parse this input — skip\n }\n }\n\n if (candidates.length === 0) return null;\n\n // Sort by priority first, then confidence within each priority tier.\n // Simpler schemas (fewer roles) often score higher confidence than more\n // specific ones — e.g., voice's \"select [patient:greedy]\" gets 1.0 while\n // sql's \"select [columns] from [source]\" gets 0.71 for the same input.\n // Priority ordering ensures domain specificity wins when both match.\n if (this.priority.length > 0) {\n candidates.sort((a, b) => {\n const pa = this.getPriorityIndex(a.domain);\n const pb = this.getPriorityIndex(b.domain);\n if (pa !== pb) return pa - pb;\n return b.confidence - a.confidence;\n });\n } else {\n // No priority configured: pure confidence ordering\n candidates.sort((a, b) => b.confidence - a.confidence);\n }\n\n return candidates[0];\n }\n\n /**\n * Parse multi-line input where each line may belong to a different domain.\n * Empty lines and comment lines (starting with //, --, or #) are skipped.\n */\n async parseComposite(input: string, language = 'en'): Promise<CompositeParseResult> {\n const lines = input.split('\\n');\n const statements: CompositeStatement[] = [];\n const errors: CompositeError[] = [];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n if (isSkippableLine(line)) continue;\n\n const trimmed = line.trim();\n const result = await this.detect(trimmed, language);\n\n if (result) {\n statements.push({\n line: i + 1,\n input: trimmed,\n domain: result.domain,\n node: result.node,\n confidence: result.confidence,\n });\n } else {\n errors.push({\n line: i + 1,\n input: trimmed,\n message: 'No domain matched this input',\n });\n }\n }\n\n return { statements, errors };\n }\n\n /**\n * Compile input using auto-detected domain.\n * Returns the compilation result with the domain name.\n */\n async compile(\n input: string,\n language = 'en'\n ): Promise<(CompileResult & { domain: string }) | null> {\n const detected = await this.detect(input, language);\n if (!detected) return null;\n\n const result = detected.dsl.compile(input, language);\n return { ...result, domain: detected.domain };\n }\n\n /**\n * Compile multi-line input where each line may belong to a different domain.\n * Detects the domain for each line and compiles it, returning per-line results.\n * Empty lines and comment lines are skipped.\n */\n async compileComposite(input: string, language = 'en'): Promise<CompositeCompileResult> {\n const lines = input.split('\\n');\n const statements: CompositeCompileStatement[] = [];\n const errors: CompositeError[] = [];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n if (isSkippableLine(line)) continue;\n\n const trimmed = line.trim();\n const detected = await this.detect(trimmed, language);\n\n if (detected) {\n const result = detected.dsl.compile(trimmed, language);\n statements.push({\n line: i + 1,\n input: trimmed,\n domain: detected.domain,\n ok: result.ok,\n code: result.code,\n errors: result.errors,\n });\n } else {\n errors.push({\n line: i + 1,\n input: trimmed,\n message: 'No domain matched this input',\n });\n }\n }\n\n return { statements, errors };\n }\n\n /**\n * Validate input against all domains, returning the best match.\n */\n async validate(input: string, language = 'en'): Promise<ValidationResult & { domain?: string }> {\n const detected = await this.detect(input, language);\n if (!detected) {\n return { valid: false, errors: ['No domain matched this input'] };\n }\n\n const result = detected.dsl.validate(input, language);\n return { ...result, domain: detected.domain };\n }\n\n // ---------------------------------------------------------------------------\n // Private\n // ---------------------------------------------------------------------------\n\n private getPriorityIndex(domain: string): number {\n const idx = this.priority.indexOf(domain);\n return idx === -1 ? this.priority.length : idx;\n }\n}\n"],"mappings":";AA4dO,SAAS,cACd,OACA,UACc;AACd,SAAO,WAAW,EAAE,MAAM,WAAW,OAAO,SAAS,IAAI,EAAE,MAAM,WAAW,MAAM;AACpF;AAKO,SAAS,eACd,OACA,cACe;AACf,SAAO,eAAe,EAAE,MAAM,YAAY,OAAO,aAAa,IAAI,EAAE,MAAM,YAAY,MAAM;AAC9F;AAKO,SAAS,gBAAgB,OAA+B;AAC7D,SAAO,EAAE,MAAM,aAAa,MAAM;AACpC;AAKO,SAAS,mBAAmB,QAAuB,UAAqC;AAC7F,SAAO,EAAE,MAAM,iBAAiB,QAAQ,SAAS;AACnD;AAYO,SAAS,WAAW,MAAc,UAAmB,MAAiB;AAC3E,SAAO,EAAE,MAAM,QAAQ,MAAM,QAAQ;AACvC;AAKO,SAAS,kBACd,QACA,OACA,UACqB;AACrB,QAAM,WAAW,iBAAiB,MAAM,QAAQ,IAAI,IAAI,OAAO,QAAQ,KAAK,CAAC;AAC7E,QAAM,OAA4B;AAAA,I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Q;AACrD,mBAAW,KAAK;AAAA,UACd,MAAM,IAAI;AAAA,UACV,OAAO;AAAA,UACP,QAAQ,SAAS;AAAA,UACjB,IAAI,OAAO;AAAA,UACX,MAAM,OAAO;AAAA,UACb,QAAQ,OAAO;AAAA,QACjB,CAAC;AAAA,MACH,OAAO;AACL,eAAO,KAAK;AAAA,UACV,MAAM,IAAI;AAAA,UACV,OAAO;AAAA,UACP,SAAS;AAAA,QACX,CAAC;AAAA,MACH;AAAA,IACF;AAEA,WAAO,EAAE,YAAY,OAAO;AAAA,EAC9B;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,SAAS,OAAe,WAAW,MAAuD;AAC9F,UAAM,WAAW,MAAM,KAAK,OAAO,OAAO,QAAQ;AAClD,QAAI,CAAC,UAAU;AACb,aAAO,EAAE,OAAO,OAAO,QAAQ,CAAC,8BAA8B,EAAE;AAAA,IAClE;AAEA,UAAM,SAAS,SAAS,IAAI,SAAS,OAAO,QAAQ;AACpD,WAAO,EAAE,GAAG,QAAQ,QAAQ,SAAS,OAAO;AAAA,EAC9C;AAAA;AAAA;AAAA;AAAA,EAMQ,iBAAiB,QAAwB;AAC/C,UAAM,MAAM,KAAK,SAAS,QAAQ,MAAM;AACxC,WAAO,QAAQ,KAAK,KAAK,SAAS,SAAS;AAAA,EAC7C;AACF;","names":["num","isValidReference","isValidReference","generateRoleCombinations","sampleValue","toSemanticValue","sampleSelector","sampleLiteral","sampleExpression","detectSelectorKind","toSemanticValue"]}
1
+ {"version":3,"sources":["../../src/core/types.ts","../../src/core/logger.ts","../../src/core/pattern-matching/utils/type-validation.ts","../../src/core/pattern-matching/utils/possessive-keywords.ts","../../src/core/pattern-matching/pattern-matcher.ts","../../src/generation/pattern-generator.ts","../../src/grammar/types.ts","../../src/grammar/transformer.ts","../../src/interfaces/dictionary.ts","../../src/interfaces/profile-provider.ts","../../src/ir/explicit-parser.ts","../../src/ir/explicit-renderer.ts","../../src/api/create-dsl.ts","../../src/prompts/prompt-generator.ts","../../src/training/schema-synthesizer.ts","../../src/feedback/feedback-formatter.ts","../../src/api/domain-registry.ts","../../src/api/dispatcher.ts"],"sourcesContent":["/**\n * Core Types — re-exported from @lokascript/intent + framework-specific extensions\n *\n * The universal semantic types (SemanticNode, SemanticValue, etc.) now live in\n * @lokascript/intent and are re-exported here for backward compatibility.\n *\n * Framework-specific types (tokenization, pattern matching) are defined below.\n */\n\n// =============================================================================\n// Re-export everything from @lokascript/intent\n// =============================================================================\n\nexport type {\n ActionType,\n SemanticRole,\n SemanticValue,\n ExpectedType,\n LiteralValue,\n SelectorValue,\n ReferenceValue,\n PropertyPathValue,\n ExpressionValue,\n FlagValue,\n Annotation,\n ProtocolDiagnostic,\n AsyncVariant,\n MatchArm,\n SemanticNode,\n SemanticMetadata,\n SourcePosition,\n CommandSemanticNode,\n EventHandlerSemanticNode,\n EventModifiers,\n ConditionalSemanticNode,\n CompoundSemanticNode,\n LoopVariant,\n LoopSemanticNode,\n LSEEnvelope,\n} from '@lokascript/intent';\n\nexport {\n createLiteral,\n createSelector,\n createReference,\n createPropertyPath,\n createExpression,\n createFlag,\n createCommandNode,\n createEventHandlerNode,\n createConditionalNode,\n createCompoundNode,\n createLoopNode,\n createTryNode,\n createAsyncNode,\n createMatchNode,\n extractValue,\n extractRoleValue,\n getRoleValue,\n} from '@lokascript/intent';\n\n// =============================================================================\n// Framework-specific types (multilingual DSL infrastructure)\n// =============================================================================\n\nimport type {\n ActionType,\n SemanticRole,\n SemanticValue,\n SelectorValue,\n ExpectedType,\n SourcePosition,\n} from '@lokascript/intent';\n\n/**\n * Token kind - categorizes what type of token this is.\n */\nexport type TokenKind =\n | 'keyword' // Command or modifier keyword\n | 'selector' // CSS selector or identifier (#id, .class, table-name)\n | 'literal' // String or number literal\n | 'particle' // Grammatical particle (を, に, من)\n | 'conjunction' // Grammatical conjunction\n | 'event-modifier' // Event modifier (.once, .debounce(300))\n | 'identifier' // Generic identifier\n | 'operator' // Operators (., +, -, etc.)\n | 'punctuation' // Punctuation (parentheses, etc.)\n | 'url'; // URL or path\n\n/**\n * A language token - the result of tokenization.\n */\nexport interface LanguageToken {\n readonly value: string;\n readonly kind: TokenKind;\n readonly position: SourcePosition;\n readonly normalized?: string;\n readonly stem?: string;\n readonly stemConfidence?: number;\n readonly metadata?: Record<string, unknown>;\n}\n\n/**\n * Token stream - provides sequential access to tokens with backtracking.\n */\nexport interface TokenStream {\n readonly tokens: readonly LanguageToken[];\n readonly language: string;\n peek(offset?: number): LanguageToken | null;\n advance(): LanguageToken;\n isAtEnd(): boolean;\n mark(): StreamMark;\n reset(mark: StreamMark): void;\n position(): number;\n}\n\nexport interface StreamMark {\n readonly position: number;\n}\n\n/**\n * Language tokenizer interface - converts text to tokens.\n */\nexport interface LanguageTokenizer {\n readonly language: string;\n readonly direction: 'ltr' | 'rtl';\n tokenize(input: string): TokenStream;\n classifyToken(token: string): TokenKind;\n}\n\n// =============================================================================\n// Pattern Matching Types\n// =============================================================================\n\nexport interface LanguagePattern {\n readonly id: string;\n readonly language: string;\n readonly command: ActionType;\n readonly priority: number;\n readonly template: PatternTemplate;\n readonly extraction: ExtractionRules;\n readonly constraints?: PatternConstraints;\n}\n\nexport interface PatternTemplate {\n readonly format: string;\n readonly tokens: PatternToken[];\n}\n\nexport type PatternToken = LiteralPatternToken | RolePatternToken | GroupPatternToken;\n\nexport interface LiteralPatternToken {\n readonly type: 'literal';\n readonly value: string;\n readonly alternatives?: string[];\n}\n\nexport interface RolePatternToken {\n readonly type: 'role';\n readonly role: SemanticRole;\n readonly optional?: boolean;\n readonly expectedTypes?: Array<ExpectedType>;\n readonly greedy?: boolean;\n}\n\nexport interface GroupPatternToken {\n readonly type: 'group';\n readonly tokens: PatternToken[];\n readonly optional?: boolean;\n}\n\nexport interface ExtractionRules {\n readonly [role: string]: ExtractionRule;\n}\n\nexport interface ExtractionRule {\n readonly position?: number;\n readonly marker?: string;\n readonly markerAlternatives?: string[];\n readonly transform?: (raw: string) => SemanticValue;\n readonly default?: SemanticValue;\n readonly value?: string;\n readonly fromRole?: string;\n}\n\nexport interface PatternConstraints {\n readonly requiredRoles?: SemanticRole[];\n readonly forbiddenRoles?: SemanticRole[];\n readonly validPatientTypes?: Array<SelectorValue['selectorKind']>;\n readonly conflictsWith?: string[];\n}\n\nexport interface PatternMatchResult {\n readonly pattern: LanguagePattern;\n readonly captured: ReadonlyMap<SemanticRole, SemanticValue>;\n readonly consumedTokens: number;\n readonly confidence: number;\n}\n\nexport interface PatternMatchError {\n readonly message: string;\n readonly position: SourcePosition;\n readonly expectedPatterns?: string[];\n readonly partialMatch?: Partial<PatternMatchResult>;\n}\n","/**\n * Debug Logging System\n *\n * Provides environment-aware debug logging for the framework.\n * Enable via DEBUG environment variable or programmatically.\n */\n\ntype LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\ninterface Logger {\n debug(message: string, ...args: any[]): void;\n info(message: string, ...args: any[]): void;\n warn(message: string, ...args: any[]): void;\n error(message: string, ...args: any[]): void;\n isEnabled(): boolean;\n}\n\nclass DebugLogger {\n private enabled: boolean;\n private namespace: string;\n\n constructor(namespace: string) {\n this.namespace = namespace;\n this.enabled = this.checkEnabled();\n }\n\n private checkEnabled(): boolean {\n // Check if running in Node.js\n if (typeof process !== 'undefined' && process.env) {\n const DEBUG = process.env.DEBUG || '';\n // Enable if DEBUG=* or DEBUG=framework:* or DEBUG=framework:namespace\n return (\n DEBUG === '*' ||\n DEBUG.includes('framework:*') ||\n DEBUG.includes(`framework:${this.namespace}`)\n );\n }\n return false;\n }\n\n private log(level: LogLevel, message: string, ...args: any[]): void {\n if (!this.enabled) return;\n\n const prefix = `[framework:${this.namespace}]`;\n const timestamp = new Date().toISOString();\n\n switch (level) {\n case 'debug':\n // eslint-disable-next-line no-console\n console.debug(`${timestamp} ${prefix} DEBUG:`, message, ...args);\n break;\n case 'info':\n // eslint-disable-next-line no-console\n console.info(`${timestamp} ${prefix} INFO:`, message, ...args);\n break;\n case 'warn':\n // eslint-disable-next-line no-console\n console.warn(`${timestamp} ${prefix} WARN:`, message, ...args);\n break;\n case 'error':\n // eslint-disable-next-line no-console\n console.error(`${timestamp} ${prefix} ERROR:`, message, ...args);\n break;\n }\n }\n\n debug(message: string, ...args: any[]): void {\n this.log('debug', message, ...args);\n }\n\n info(message: string, ...args: any[]): void {\n this.log('info', message, ...args);\n }\n\n warn(message: string, ...args: any[]): void {\n this.log('warn', message, ...args);\n }\n\n error(message: string, ...args: any[]): void {\n this.log('error', message, ...args);\n }\n\n /**\n * Check if logging is enabled for this namespace.\n */\n isEnabled(): boolean {\n return this.enabled;\n }\n\n /**\n * Programmatically enable logging for this namespace.\n */\n enable(): void {\n this.enabled = true;\n }\n\n /**\n * Programmatically disable logging for this namespace.\n */\n disable(): void {\n this.enabled = false;\n }\n}\n\n/**\n * Create a logger for a specific namespace.\n *\n * @param namespace - Logger namespace (e.g., 'pattern-matcher', 'tokenizer')\n * @returns Logger instance\n *\n * @example\n * const logger = createLogger('pattern-matcher');\n * logger.debug('Matching pattern:', pattern.id);\n * logger.warn('Low confidence match:', confidence);\n */\nexport function createLogger(namespace: string): Logger {\n return new DebugLogger(namespace);\n}\n\n/**\n * No-op logger that does nothing.\n * Useful for disabling logging in production builds.\n */\nexport const noopLogger: Logger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n isEnabled: () => false,\n};\n","/**\n * Type Validation Utility\n *\n * Shared utilities for validating semantic value types against expected types.\n * Used by pattern-matcher to validate captured role values.\n */\n\nimport type { SemanticValue } from '../../types';\n\n/**\n * Semantic value type strings.\n */\nexport type SemanticValueType = SemanticValue['type'];\n\n/**\n * Check if a value type matches any of the expected types.\n *\n * The 'expression' type is treated as a wildcard that matches any value.\n * The 'property-path' type is compatible with selector, reference, and expression.\n *\n * @param actualType The actual type of the value\n * @param expectedTypes Array of expected types\n * @returns True if the type is compatible\n */\nexport function isTypeCompatible(\n actualType: SemanticValueType | string,\n expectedTypes: (SemanticValueType | string)[]\n): boolean {\n // Empty expected types means any type is valid\n if (!expectedTypes || expectedTypes.length === 0) {\n return true;\n }\n\n // Direct match\n if (expectedTypes.includes(actualType)) {\n return true;\n }\n\n // 'expression' is always compatible (wildcard)\n if (expectedTypes.includes('expression')) {\n return true;\n }\n\n // 'property-path' is compatible with selector, reference, and expression\n if (actualType === 'property-path') {\n return expectedTypes.some(t => ['selector', 'reference', 'expression'].includes(t));\n }\n\n return false;\n}\n\n/**\n * Validate a semantic value against expected types.\n *\n * @param value The semantic value to validate\n * @param expectedTypes Array of expected types (empty means any type is valid)\n * @returns True if the value type is valid\n */\nexport function validateValueType(\n value: SemanticValue,\n expectedTypes?: (SemanticValueType | string)[]\n): boolean {\n if (!expectedTypes || expectedTypes.length === 0) {\n return true;\n }\n\n return isTypeCompatible(value.type, expectedTypes);\n}\n\n/**\n * Check if a value is a CSS selector.\n */\nexport function isCSSSelector(value: string): boolean {\n return value.startsWith('.') || value.startsWith('#') || value.startsWith('<');\n}\n\n/**\n * Check if a value is a class name (starts with .).\n */\nexport function isClassName(value: string): boolean {\n return value.startsWith('.');\n}\n\n/**\n * Check if a value is an ID selector (starts with #).\n */\nexport function isIdSelector(value: string): boolean {\n return value.startsWith('#');\n}\n\n/**\n * Check if a value is a CSS property reference (starts with *).\n */\nexport function isCSSPropertyRef(value: string): boolean {\n return value.startsWith('*');\n}\n\n/**\n * Check if a value is a numeric value.\n */\nexport function isNumericValue(value: string): boolean {\n // Handle duration values (e.g., \"100ms\", \"2s\")\n const durationMatch = value.match(/^(\\d+(?:\\.\\d+)?)(ms|s|m|h)?$/);\n if (durationMatch) {\n return true;\n }\n\n // Plain number\n const num = parseFloat(value);\n return !isNaN(num) && isFinite(num);\n}\n\n/**\n * Check if a value is a property name (identifier-like).\n */\nexport function isPropertyName(value: string): boolean {\n // Property names are identifiers (start with letter or _, contain alphanumeric)\n return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(value);\n}\n\n/**\n * Check if a value is a variable reference (starts with :).\n */\nexport function isVariableRef(value: string): boolean {\n return value.startsWith(':');\n}\n\n/**\n * Check if a value is a built-in reference (me, you, it, etc.).\n */\nexport function isBuiltInReference(value: string): boolean {\n const builtIns = new Set(['me', 'you', 'it', 'result', 'event', 'target', 'body']);\n return builtIns.has(value.toLowerCase());\n}\n","/**\n * Possessive Keywords Utility\n *\n * Provides functions to look up possessive keywords from language profiles.\n * Used by pattern-matcher to recognize possessive expressions like \"my value\".\n */\n\n/**\n * Minimal profile interface for possessive keyword lookup.\n */\nexport interface PossessiveProfile {\n readonly possessive?: {\n readonly keywords?: Record<string, string>;\n };\n}\n\n/**\n * Get the reference for a possessive keyword from a profile.\n *\n * @param profile Language profile\n * @param keyword Possessive keyword (e.g., 'my', 'your', 'its')\n * @returns The reference (e.g., 'me', 'you', 'it') or undefined if not found\n */\nexport function getPossessiveReference(\n profile: PossessiveProfile | undefined,\n keyword: string\n): string | undefined {\n return profile?.possessive?.keywords?.[keyword];\n}\n\n/**\n * Check if a keyword is a possessive keyword in the given profile.\n *\n * @param profile Language profile\n * @param keyword Keyword to check\n * @returns True if the keyword is a possessive keyword\n */\nexport function isPossessiveKeyword(\n profile: PossessiveProfile | undefined,\n keyword: string\n): boolean {\n return profile?.possessive?.keywords?.[keyword] !== undefined;\n}\n\n/**\n * Get all possessive keywords from a profile.\n *\n * @param profile Language profile\n * @returns Record of possessive keywords to references, or empty object\n */\nexport function getAllPossessiveKeywords(\n profile: PossessiveProfile | undefined\n): Record<string, string> {\n return profile?.possessive?.keywords ?? {};\n}\n","/**\n * Pattern Matcher\n *\n * Matches tokenized input against language patterns to extract semantic roles.\n * This is the core algorithm for multilingual parsing.\n */\n\nimport type {\n LanguagePattern,\n PatternToken,\n PatternMatchResult,\n ReferenceValue,\n SemanticRole,\n SemanticValue,\n TokenStream,\n LanguageToken,\n} from '../types';\nimport { createSelector, createLiteral, createReference, createPropertyPath } from '../types';\nimport { createLogger } from '../logger';\n\n/**\n * Helper to check if a value is a built-in reference.\n * In the generic framework, we don't assume any built-in references.\n * DSLs that need references (like hyperscript's 'me', 'it', 'you') should\n * handle them in their tokenizer or provide a custom reference validator.\n *\n * For generic DSLs, identifiers are treated as expressions by default.\n */\nfunction isValidReference(_value: string): boolean {\n // In generic framework, no built-in references\n // Identifiers should be expressions\n return false;\n}\nimport { isTypeCompatible } from './utils/type-validation';\nimport { getPossessiveReference } from './utils/possessive-keywords';\n\n/**\n * Minimal profile interface needed by PatternMatcher.\n * DSLs can provide this to enable possessive handling and language-specific features.\n */\nexport interface PatternMatcherProfile {\n readonly code: string;\n readonly possessive?: {\n readonly keywords?: Record<string, string>;\n };\n}\n\n// =============================================================================\n// Pattern Matcher\n// =============================================================================\n\nexport class PatternMatcher {\n /** Maximum tokens to scan ahead when looking for a group's leading marker */\n private static readonly MAX_MARKER_SCAN = 3;\n\n /** Debug logger */\n private logger = createLogger('pattern-matcher');\n\n /** Current language profile for the pattern being matched */\n private currentProfile: PatternMatcherProfile | undefined;\n\n /**\n * Safely convert a value to lowercase string.\n * Provides protection against non-string values at runtime.\n */\n private safeToLowerCase(value: unknown): string {\n if (typeof value === 'string') {\n return value.toLowerCase();\n }\n if (value === null || value === undefined) {\n return '';\n }\n return String(value).toLowerCase();\n }\n\n /**\n * Try to match a single pattern against the token stream.\n * Returns the match result or null if no match.\n *\n * @param tokens - Token stream to match against\n * @param pattern - Pattern to match\n * @param profile - Optional language profile for possessive handling\n */\n matchPattern(\n tokens: TokenStream,\n pattern: LanguagePattern,\n profile?: PatternMatcherProfile\n ): PatternMatchResult | null {\n const mark = tokens.mark();\n const captured = new Map<SemanticRole, SemanticValue>();\n\n // Debug logging\n this.logger.debug('========================================');\n this.logger.debug('matchPattern ENTRY');\n this.logger.debug('Pattern ID:', pattern.id);\n this.logger.debug('Pattern command:', pattern.command);\n this.logger.debug('Pattern language:', pattern.language);\n this.logger.debug('Pattern template:', JSON.stringify(pattern.template, null, 2));\n\n if (this.logger.isEnabled()) {\n const firstTokens = [];\n for (let i = 0; i < 10; i++) {\n const t = tokens.peek(i);\n if (t)\n firstTokens.push({\n type: (t as any).type,\n value: (t as any).value,\n kind: (t as any).kind,\n });\n else break;\n }\n this.logger.debug('Input tokens (first 10):', firstTokens);\n this.logger.debug('Profile code:', profile?.code);\n }\n\n // Use provided profile for possessive keyword lookup\n this.currentProfile = profile;\n\n // Reset match counters for this pattern\n this.stemMatchCount = 0;\n this.totalKeywordMatches = 0;\n\n this.logger.debug('--- Calling matchTokenSequence ---');\n this.logger.debug('Pattern tokens to match:', JSON.stringify(pattern.template.tokens, null, 2));\n const success = this.matchTokenSequence(tokens, pattern.template.tokens, captured);\n this.logger.debug('matchTokenSequence returned:', success);\n this.logger.debug(\n 'Captured roles:',\n Array.from(captured.entries()).map(([k, v]) => [k, JSON.stringify(v)])\n );\n\n if (!success) {\n this.logger.debug('>>> MATCH FAILED - resetting token position');\n tokens.reset(mark);\n return null;\n }\n\n // Calculate confidence BEFORE applying defaults\n // This ensures defaulted roles don't artificially inflate confidence\n const confidence = this.calculateConfidence(pattern, captured);\n\n // Apply extraction rules to fill in any missing roles with defaults\n this.applyExtractionRules(pattern, captured);\n\n return {\n pattern,\n captured,\n consumedTokens: tokens.position() - mark.position,\n confidence,\n };\n }\n\n /**\n * Try to match multiple patterns, return the best match.\n *\n * @param tokens - Token stream to match against\n * @param patterns - Candidate patterns to try\n * @param profile - Optional language profile for possessive handling\n */\n matchBest(\n tokens: TokenStream,\n patterns: LanguagePattern[],\n profile?: PatternMatcherProfile\n ): PatternMatchResult | null {\n const matches: PatternMatchResult[] = [];\n\n for (const pattern of patterns) {\n const mark = tokens.mark();\n const result = this.matchPattern(tokens, pattern, profile);\n\n if (result) {\n matches.push(result);\n }\n\n tokens.reset(mark);\n }\n\n if (matches.length === 0) {\n return null;\n }\n\n // Sort by confidence and priority\n matches.sort((a, b) => {\n // First by priority\n const priorityDiff = b.pattern.priority - a.pattern.priority;\n if (priorityDiff !== 0) return priorityDiff;\n\n // Then by confidence\n const confidenceDiff = b.confidence - a.confidence;\n if (Math.abs(confidenceDiff) > 0.001) return confidenceDiff;\n\n // Then by tokens consumed (prefer more complete matches)\n return b.consumedTokens - a.consumedTokens;\n });\n\n // Re-consume tokens for the best match\n const best = matches[0];\n this.matchPattern(tokens, best.pattern);\n\n return best;\n }\n\n /**\n * Match a sequence of pattern tokens against the token stream.\n *\n * Supports bounded single-step backtracking: if an optional role consumes\n * a token and the immediately following pattern token fails, the matcher\n * resets to before the optional role and retries the failed token.\n */\n private matchTokenSequence(\n tokens: TokenStream,\n patternTokens: PatternToken[],\n captured: Map<SemanticRole, SemanticValue>,\n parentStopMarkers?: Set<string>\n ): boolean {\n // Skip leading conjunctions for Arabic (proclitics: و, ف, ول, وب, etc.)\n // BUT NOT if the pattern explicitly expects a conjunction (proclitic patterns)\n const firstPatternToken = patternTokens[0];\n const patternExpectsConjunction =\n firstPatternToken?.type === 'literal' &&\n (firstPatternToken.value === 'and' ||\n firstPatternToken.value === 'then' ||\n firstPatternToken.alternatives?.includes('and') ||\n firstPatternToken.alternatives?.includes('then'));\n\n if (this.currentProfile?.code === 'ar' && !patternExpectsConjunction) {\n while (tokens.peek()?.kind === 'conjunction') {\n tokens.advance();\n }\n }\n\n // Backtracking state: track the most recent optional role that consumed a token\n let prevOptionalMark: ReturnType<TokenStream['mark']> | null = null;\n let prevOptionalRole: SemanticRole | null = null;\n\n for (let i = 0; i < patternTokens.length; i++) {\n const patternToken = patternTokens[i];\n this.logger.debug(' >> Matching pattern token:', JSON.stringify(patternToken, null, 2));\n const currTok = tokens.peek();\n this.logger.debug(\n ' >> Current input token:',\n currTok\n ? JSON.stringify({\n type: (currTok as any).type,\n value: (currTok as any).value,\n kind: (currTok as any).kind,\n })\n : 'EOF'\n );\n\n // Greedy role capture: consume all remaining tokens until the next\n // recognized marker keyword or end of input\n if (patternToken.type === 'role' && patternToken.greedy) {\n const stopMarkers = this.collectStopMarkers(patternTokens, i + 1);\n // Merge parent-level stop markers so greedy roles inside groups\n // know when to stop for tokens outside the group (e.g., SOV verb keywords)\n if (parentStopMarkers) {\n for (const m of parentStopMarkers) stopMarkers.add(m);\n }\n const values: string[] = [];\n while (!tokens.isAtEnd()) {\n const nextToken = tokens.peek();\n if (!nextToken) break;\n if (this.isStopMarker(nextToken, stopMarkers)) break;\n values.push(nextToken.value);\n tokens.advance();\n }\n if (values.length > 0) {\n captured.set(patternToken.role, { type: 'expression', raw: values.join(' ') });\n prevOptionalMark = null;\n prevOptionalRole = null;\n continue;\n } else if (patternToken.optional) {\n continue;\n } else {\n return false;\n }\n }\n\n // Group tokens: compute sibling stop markers and forward to inner matching\n if (patternToken.type === 'group') {\n const siblingStopMarkers = this.collectStopMarkers(patternTokens, i + 1);\n if (parentStopMarkers) {\n for (const m of parentStopMarkers) siblingStopMarkers.add(m);\n }\n const groupMatched = this.matchGroupToken(\n tokens,\n patternToken as PatternToken & { type: 'group' },\n captured,\n siblingStopMarkers\n );\n if (groupMatched) {\n prevOptionalMark = null;\n prevOptionalRole = null;\n continue;\n }\n if (this.isOptional(patternToken)) {\n continue;\n }\n return false;\n }\n\n // Save stream position before attempting optional roles\n const isOptionalRole = patternToken.type === 'role' && patternToken.optional === true;\n const markBefore = isOptionalRole ? tokens.mark() : null;\n\n // SOV marker-stealing guard: before matching a required role, check if\n // the current input token would match the immediately-following pattern\n // literal (the role's own postpositional marker). If so, skip consuming\n // this token as a role value — it should be matched as the literal instead.\n const isRoleToken = patternToken.type === 'role';\n if (isRoleToken && !isOptionalRole) {\n const nextPT = i + 1 < patternTokens.length ? patternTokens[i + 1] : null;\n if (nextPT?.type === 'literal') {\n const currentToken = tokens.peek();\n if (currentToken && this.getMatchType(currentToken, nextPT.value) !== 'none') {\n // Current token is the marker literal, not a role value — treat role as failed\n this.logger.debug(\n ' >> MARKER-STEAL GUARD: current token matches next literal, skipping role'\n );\n // Fall through to failure handling below\n // (which will trigger backtracking of previous optional role)\n\n // Match failed\n this.logger.debug(' >> Token match FAILED');\n\n if (this.isOptional(patternToken)) {\n continue;\n }\n\n // Required token failed — try backtracking over the previous optional role\n if (prevOptionalMark && prevOptionalRole) {\n this.logger.debug(' >> BACKTRACKING: undoing optional role', prevOptionalRole);\n tokens.reset(prevOptionalMark);\n captured.delete(prevOptionalRole);\n prevOptionalMark = null;\n prevOptionalRole = null;\n\n // Retry the current (failed) pattern token from the restored position\n const retryMatched = this.matchPatternToken(tokens, patternToken, captured);\n this.logger.debug(' >> Backtrack retry result:', retryMatched);\n if (retryMatched) {\n continue;\n }\n }\n\n return false;\n }\n }\n }\n\n const matched = this.matchPatternToken(tokens, patternToken, captured);\n this.logger.debug(' >> Match result:', matched);\n\n if (matched) {\n if (isOptionalRole) {\n // Track this consumption so we can undo it if the next token fails\n prevOptionalMark = markBefore;\n prevOptionalRole = patternToken.role;\n } else {\n // Non-optional succeeded — clear backtrack state\n prevOptionalMark = null;\n prevOptionalRole = null;\n }\n continue;\n }\n\n // Match failed\n this.logger.debug(' >> Token match FAILED');\n\n if (this.isOptional(patternToken)) {\n continue;\n }\n\n // Required token failed — try backtracking over the previous optional role\n if (prevOptionalMark && prevOptionalRole) {\n this.logger.debug(' >> BACKTRACKING: undoing optional role', prevOptionalRole);\n tokens.reset(prevOptionalMark);\n captured.delete(prevOptionalRole);\n prevOptionalMark = null;\n prevOptionalRole = null;\n\n // Retry the current (failed) pattern token from the restored position\n const retryMatched = this.matchPatternToken(tokens, patternToken, captured);\n this.logger.debug(' >> Backtrack retry result:', retryMatched);\n if (retryMatched) {\n continue;\n }\n }\n\n return false;\n }\n\n return true;\n }\n\n /**\n * Match a single pattern token against the current position in the stream.\n */\n private matchPatternToken(\n tokens: TokenStream,\n patternToken: PatternToken,\n captured: Map<SemanticRole, SemanticValue>\n ): boolean {\n switch (patternToken.type) {\n case 'literal':\n return this.matchLiteralToken(tokens, patternToken);\n\n case 'role':\n return this.matchRoleToken(tokens, patternToken, captured);\n\n case 'group':\n return this.matchGroupToken(tokens, patternToken, captured);\n\n default:\n return false;\n }\n }\n\n /**\n * Match a literal pattern token (keyword or particle).\n */\n private matchLiteralToken(\n tokens: TokenStream,\n patternToken: PatternToken & { type: 'literal' }\n ): boolean {\n const token = tokens.peek();\n this.logger.debug(' >>> matchLiteralToken: expecting', patternToken.value);\n this.logger.debug(\n ' >>> matchLiteralToken: got token',\n token\n ? JSON.stringify({\n type: (token as any).type,\n value: (token as any).value,\n kind: (token as any).kind,\n })\n : 'null'\n );\n if (!token) {\n this.logger.debug(' >>> matchLiteralToken: FAIL - no token');\n return false;\n }\n\n // Check main value\n const matchType = this.getMatchType(token, patternToken.value);\n this.logger.debug(\n ' >>> matchType for',\n token.value,\n 'vs',\n patternToken.value,\n ':',\n matchType\n );\n if (matchType !== 'none') {\n this.totalKeywordMatches++;\n if (matchType === 'stem') {\n this.stemMatchCount++;\n }\n tokens.advance();\n return true;\n }\n\n // Check alternatives\n if (patternToken.alternatives) {\n for (const alt of patternToken.alternatives) {\n const altMatchType = this.getMatchType(token, alt);\n if (altMatchType !== 'none') {\n this.totalKeywordMatches++;\n if (altMatchType === 'stem') {\n this.stemMatchCount++;\n }\n tokens.advance();\n return true;\n }\n }\n }\n\n return false;\n }\n\n /**\n * Match a role pattern token (captures a semantic value).\n * Handles multi-token expressions like:\n * - 'my value' (possessive keyword + property)\n * - '#dialog.showModal()' (method call)\n * - \"#element's *opacity\" (possessive selector + property)\n */\n private matchRoleToken(\n tokens: TokenStream,\n patternToken: PatternToken & { type: 'role' },\n captured: Map<SemanticRole, SemanticValue>\n ): boolean {\n this.logger.debug(' >>> matchRoleToken ENTRY: capturing role', patternToken.role);\n this.logger.debug(' >>> matchRoleToken: expected types', patternToken.expectedTypes);\n this.logger.debug(' >>> matchRoleToken: optional?', patternToken.optional);\n // Skip noise words like \"the\" before selectors (English idiom support)\n this.skipNoiseWords(tokens);\n\n const token = tokens.peek();\n this.logger.debug(\n ' >>> After skipNoiseWords, current token:',\n token ? JSON.stringify({ value: (token as any).value, kind: (token as any).kind }) : 'null'\n );\n if (!token) {\n return patternToken.optional || false;\n }\n\n // Check for possessive expression (e.g., 'my value', 'its innerHTML')\n const possessiveValue = this.tryMatchPossessiveExpression(tokens);\n if (possessiveValue) {\n // Validate expected types if specified\n if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {\n if (!isTypeCompatible(possessiveValue.type, patternToken.expectedTypes)) {\n return patternToken.optional || false;\n }\n }\n captured.set(patternToken.role, possessiveValue);\n return true;\n }\n\n // Check for method call expression (e.g., '#dialog.showModal()')\n const methodCallValue = this.tryMatchMethodCallExpression(tokens);\n if (methodCallValue) {\n if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {\n if (!isTypeCompatible(methodCallValue.type, patternToken.expectedTypes)) {\n return patternToken.optional || false;\n }\n }\n captured.set(patternToken.role, methodCallValue);\n return true;\n }\n\n // Check for possessive selector expression (e.g., \"#element's *opacity\")\n const possessiveSelectorValue = this.tryMatchPossessiveSelectorExpression(tokens);\n if (possessiveSelectorValue) {\n if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {\n // property-path is compatible with selector, reference, and expression\n if (!isTypeCompatible(possessiveSelectorValue.type, patternToken.expectedTypes)) {\n return patternToken.optional || false;\n }\n }\n captured.set(patternToken.role, possessiveSelectorValue);\n return true;\n }\n\n // Check for property access expression (e.g., 'userData.name', 'it.data')\n const propertyAccessValue = this.tryMatchPropertyAccessExpression(tokens);\n if (propertyAccessValue) {\n if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {\n if (!isTypeCompatible(propertyAccessValue.type, patternToken.expectedTypes)) {\n return patternToken.optional || false;\n }\n }\n captured.set(patternToken.role, propertyAccessValue);\n return true;\n }\n\n // Check for selector + property expression (e.g., '#output.innerText')\n // This handles cases where the tokenizer produces two selector tokens\n const selectorPropertyValue = this.tryMatchSelectorPropertyExpression(tokens);\n if (selectorPropertyValue) {\n if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {\n if (!isTypeCompatible(selectorPropertyValue.type, patternToken.expectedTypes)) {\n return patternToken.optional || false;\n }\n }\n captured.set(patternToken.role, selectorPropertyValue);\n return true;\n }\n\n // Try to extract a semantic value from the token\n this.logger.debug(\n ' >>> Trying tokenToSemanticValue for token:',\n token ? JSON.stringify({ value: (token as any).value, kind: (token as any).kind }) : 'null'\n );\n const value = this.tokenToSemanticValue(token);\n this.logger.debug(\n ' >>> tokenToSemanticValue returned:',\n value ? JSON.stringify(value) : 'null'\n );\n if (!value) {\n return patternToken.optional || false;\n }\n\n // Validate expected types if specified\n this.logger.debug(\n ' >>> Validating type:',\n value.type,\n 'against expected:',\n patternToken.expectedTypes\n );\n if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {\n if (!isTypeCompatible(value.type, patternToken.expectedTypes)) {\n this.logger.debug(' >>> TYPE MISMATCH - returning', patternToken.optional || false);\n return patternToken.optional || false;\n }\n }\n this.logger.debug(' >>> Type validation PASSED');\n\n captured.set(patternToken.role, value);\n tokens.advance();\n return true;\n }\n\n /**\n * Try to match a possessive expression like 'my value' or 'its innerHTML'.\n * Returns the PropertyPathValue if matched, or null if not.\n */\n private tryMatchPossessiveExpression(tokens: TokenStream): SemanticValue | null {\n const token = tokens.peek();\n if (!token) return null;\n\n // Use profile-based possessive keyword lookup\n if (!this.currentProfile) return null;\n\n const tokenValue = token.normalized || token.value;\n const tokenLower = this.safeToLowerCase(tokenValue);\n const baseRef = getPossessiveReference(this.currentProfile, tokenLower);\n\n if (!baseRef) return null;\n\n // We have a possessive keyword, look ahead for property name\n const mark = tokens.mark();\n tokens.advance();\n\n const propertyToken = tokens.peek();\n if (!propertyToken) {\n // Just the possessive keyword, no property - revert\n tokens.reset(mark);\n return null;\n }\n\n // Property should be an identifier, keyword (not structural), or selector (for style/dot/attr)\n // Examples: \"my value\", \"my innerHTML\", \"my *background\", \"my *opacity\", \"my @data-count\"\n // Also handles dot-property access: \"my.textContent\" tokenized as \"my\" + \".textContent\"\n if (\n propertyToken.kind === 'identifier' ||\n (propertyToken.kind === 'keyword' && !this.isStructuralKeyword(propertyToken.value)) ||\n (propertyToken.kind === 'selector' && propertyToken.value.startsWith('*')) ||\n (propertyToken.kind === 'selector' && propertyToken.value.startsWith('@')) ||\n (propertyToken.kind === 'selector' &&\n propertyToken.value.startsWith('.') &&\n /^\\.[a-zA-Z_]\\w*/.test(propertyToken.value))\n ) {\n tokens.advance();\n\n // For dot-property selectors (.textContent), strip the leading dot\n let propertyName = propertyToken.value;\n if (\n propertyToken.kind === 'selector' &&\n propertyName.startsWith('.') &&\n /^\\.[a-zA-Z_]\\w*/.test(propertyName)\n ) {\n propertyName = propertyName.substring(1);\n }\n\n // Consume chained dot-property access (.parentElement.style.display)\n let chainedProps = propertyName;\n while (\n tokens.peek()?.kind === 'selector' &&\n tokens.peek()!.value.startsWith('.') &&\n /^\\.[a-zA-Z_]\\w*/.test(tokens.peek()!.value)\n ) {\n chainedProps += tokens.peek()!.value; // keep the dots for chaining\n tokens.advance();\n }\n\n // Check for method call — next token is '(' in the value (e.g., .getAttribute(\"data-id\"))\n const nextPeek = tokens.peek();\n if (nextPeek?.kind === 'literal' && nextPeek.value.startsWith('(')) {\n // Consume method args\n chainedProps += nextPeek.value;\n tokens.advance();\n }\n\n // Create property-path: my value -> { object: me, property: 'value' }\n // baseRef from getPossessiveReference is always a valid reference ('me', 'you', 'it', etc.)\n return createPropertyPath(createReference(baseRef as ReferenceValue['value']), chainedProps);\n }\n\n // Not a valid property, revert\n tokens.reset(mark);\n return null;\n }\n\n /**\n * Check if a keyword is a structural keyword (preposition, control flow, etc.)\n * that shouldn't be consumed as a property name.\n */\n private isStructuralKeyword(value: string): boolean {\n const structural = new Set([\n // Prepositions\n 'into',\n 'in',\n 'to',\n 'from',\n 'at',\n 'by',\n 'with',\n 'without',\n 'before',\n 'after',\n 'of',\n 'as',\n 'on',\n // Control flow\n 'then',\n 'end',\n 'else',\n 'if',\n 'repeat',\n 'while',\n 'for',\n // Commands (shouldn't be property names)\n 'toggle',\n 'add',\n 'remove',\n 'put',\n 'set',\n 'show',\n 'hide',\n 'increment',\n 'decrement',\n 'send',\n 'trigger',\n 'call',\n ]);\n return structural.has(value.toLowerCase());\n }\n\n /**\n * Try to match a method call expression like '#dialog.showModal()'.\n * Pattern: selector + '.' + identifier + '(' + [args] + ')'\n * Returns an expression value if matched, or null if not.\n */\n private tryMatchMethodCallExpression(tokens: TokenStream): SemanticValue | null {\n const token = tokens.peek();\n if (!token || token.kind !== 'selector') return null;\n\n // Look ahead for: . identifier (\n const mark = tokens.mark();\n tokens.advance(); // consume selector\n\n const dotToken = tokens.peek();\n if (!dotToken || dotToken.kind !== 'operator' || dotToken.value !== '.') {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume .\n\n const methodToken = tokens.peek();\n if (!methodToken || methodToken.kind !== 'identifier') {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume method name\n\n const openParen = tokens.peek();\n if (!openParen || openParen.kind !== 'punctuation' || openParen.value !== '(') {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume (\n\n // Consume arguments until we find ) (with depth limit for security)\n const args: string[] = [];\n while (!tokens.isAtEnd() && args.length < PatternMatcher.MAX_METHOD_ARGS) {\n const argToken = tokens.peek();\n if (!argToken) break;\n if (argToken.kind === 'punctuation' && argToken.value === ')') {\n tokens.advance(); // consume )\n break;\n }\n // Skip commas\n if (argToken.kind === 'punctuation' && argToken.value === ',') {\n tokens.advance();\n continue;\n }\n // Collect arg value\n args.push(argToken.value);\n tokens.advance();\n }\n\n // Create expression value: #dialog.showModal()\n const methodCall = `${token.value}.${methodToken.value}(${args.join(', ')})`;\n return {\n type: 'expression',\n raw: methodCall,\n } as SemanticValue;\n }\n\n /**\n * Try to match a property access expression like 'userData.name' or 'it.data'.\n * Pattern: (identifier | keyword) + '.' + identifier [+ '.' + identifier ...]\n * Returns an expression value if matched, or null if not.\n */\n private tryMatchPropertyAccessExpression(tokens: TokenStream): SemanticValue | null {\n const token = tokens.peek();\n if (!token) return null;\n\n // Must start with an identifier or keyword reference\n if (token.kind !== 'identifier' && token.kind !== 'keyword') return null;\n\n // Look ahead for: . identifier\n const mark = tokens.mark();\n tokens.advance(); // consume first token\n\n const dotToken = tokens.peek();\n if (!dotToken || dotToken.kind !== 'operator' || dotToken.value !== '.') {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume .\n\n const propertyToken = tokens.peek();\n if (!propertyToken || propertyToken.kind !== 'identifier') {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume property name\n\n // Build the property chain\n let chain = `${token.value}.${propertyToken.value}`;\n let depth = 1; // Already have one property access\n\n // Continue for nested property access (e.g., userData.address.city)\n // With depth limit for security\n while (!tokens.isAtEnd() && depth < PatternMatcher.MAX_PROPERTY_DEPTH) {\n const nextDot = tokens.peek();\n if (!nextDot || nextDot.kind !== 'operator' || nextDot.value !== '.') {\n break;\n }\n tokens.advance(); // consume .\n\n const nextProp = tokens.peek();\n if (!nextProp || nextProp.kind !== 'identifier') {\n // Dot without property - put the dot back and stop\n // Can't easily put a single token back, so we'll include it\n break;\n }\n tokens.advance(); // consume property\n chain += `.${nextProp.value}`;\n depth++;\n }\n\n // Check for method call: chain + '(' + args + ')'\n // e.g., me.insertBefore(draggedItem, dropTarget)\n const openParen = tokens.peek();\n if (openParen && openParen.kind === 'punctuation' && openParen.value === '(') {\n tokens.advance(); // consume (\n\n // Collect arguments (comma-separated values)\n const args: string[] = [];\n let argDepth = 0; // Track nested parentheses\n while (!tokens.isAtEnd() && args.length < PatternMatcher.MAX_METHOD_ARGS) {\n const argToken = tokens.peek();\n if (!argToken) break;\n\n // Handle close paren - respecting nesting\n if (argToken.kind === 'punctuation' && argToken.value === ')') {\n if (argDepth === 0) {\n tokens.advance(); // consume )\n break;\n }\n argDepth--;\n }\n // Track nested open parens\n if (argToken.kind === 'punctuation' && argToken.value === '(') {\n argDepth++;\n }\n // Skip commas between arguments\n if (argToken.kind === 'punctuation' && argToken.value === ',') {\n tokens.advance();\n continue;\n }\n // Collect arg value\n args.push(argToken.value);\n tokens.advance();\n }\n\n // Create expression value with method call: me.insertBefore(a, b)\n const methodCall = `${chain}(${args.join(', ')})`;\n return {\n type: 'expression',\n raw: methodCall,\n } as SemanticValue;\n }\n\n // Create expression value: userData.name\n return {\n type: 'expression',\n raw: chain,\n } as SemanticValue;\n }\n\n /**\n * Try to match a possessive selector expression like \"#element's *opacity\".\n * Pattern: selector + \"'s\" + (selector | identifier)\n * Returns a property-path value if matched, or null if not.\n */\n private tryMatchPossessiveSelectorExpression(tokens: TokenStream): SemanticValue | null {\n const token = tokens.peek();\n if (!token || token.kind !== 'selector') return null;\n\n // Look ahead for: 's (possessive marker)\n const mark = tokens.mark();\n tokens.advance(); // consume selector\n\n const possessiveToken = tokens.peek();\n if (\n !possessiveToken ||\n possessiveToken.kind !== 'punctuation' ||\n possessiveToken.value !== \"'s\"\n ) {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume 's\n\n const propertyToken = tokens.peek();\n if (!propertyToken) {\n tokens.reset(mark);\n return null;\n }\n\n // Property can be a selector (*opacity) or identifier\n if (propertyToken.kind !== 'selector' && propertyToken.kind !== 'identifier') {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume property\n\n // Create property-path: #element's *opacity\n return createPropertyPath(createSelector(token.value), propertyToken.value);\n }\n\n /**\n * Try to match a selector + property expression like \"#output.innerText\".\n * This handles cases where the tokenizer produces two selector tokens:\n * - #output (id selector)\n * - .innerText (looks like class selector, but is actually property)\n *\n * Pattern: id-selector + class-selector-that-is-actually-property\n * Returns a property-path value if matched, or null if not.\n */\n private tryMatchSelectorPropertyExpression(tokens: TokenStream): SemanticValue | null {\n const token = tokens.peek();\n if (!token || token.kind !== 'selector') return null;\n\n // Must be an ID selector (starts with #)\n if (typeof token.value !== 'string' || !token.value.startsWith('#')) return null;\n\n // Look ahead for: selector that looks like a property (.something)\n const mark = tokens.mark();\n tokens.advance(); // consume first selector\n\n const propertyToken = tokens.peek();\n if (!propertyToken || propertyToken.kind !== 'selector') {\n tokens.reset(mark);\n return null;\n }\n\n // Second token must look like a class selector (starts with .)\n // but we interpret it as a property access\n if (!propertyToken.value.startsWith('.')) {\n tokens.reset(mark);\n return null;\n }\n\n // Verify the next token is not a selector (to avoid consuming too many)\n // This helps distinguish \"#output.innerText\" from \"#box .child\"\n const peek2 = tokens.peek(1);\n if (peek2 && peek2.kind === 'selector') {\n // Could be a compound selector chain - only take first two\n }\n\n tokens.advance(); // consume property selector\n\n // Create property-path: #output.innerText\n // Extract property name without the leading dot\n const propertyName = propertyToken.value.slice(1);\n\n return createPropertyPath(createSelector(token.value), propertyName);\n }\n\n /**\n * Match a group pattern token (optional sequence).\n * When the group's leading marker isn't at the current position, scans ahead\n * up to MAX_MARKER_SCAN tokens to find it. This allows unmarked tokens\n * (e.g., a value like 'hello') to sit between groups without blocking later\n * marker matches.\n */\n private matchGroupToken(\n tokens: TokenStream,\n patternToken: PatternToken & { type: 'group' },\n captured: Map<SemanticRole, SemanticValue>,\n parentStopMarkers?: Set<string>\n ): boolean {\n const mark = tokens.mark();\n const capturedBefore = new Set(captured.keys());\n\n const success = this.matchTokenSequence(\n tokens,\n patternToken.tokens,\n captured,\n parentStopMarkers\n );\n if (success) return true;\n\n // Reset from failed attempt\n tokens.reset(mark);\n for (const role of captured.keys()) {\n if (!capturedBefore.has(role)) captured.delete(role);\n }\n\n if (!patternToken.optional) return false;\n\n // Marker scan: look ahead for the group's leading marker past intervening tokens.\n // This handles cases like \"types 'hello' into #search\" where 'hello' blocks the\n // 'into' marker from being found at the current position.\n const leadingMarker = this.getGroupLeadingMarker(patternToken);\n if (leadingMarker) {\n for (let offset = 1; offset <= PatternMatcher.MAX_MARKER_SCAN; offset++) {\n const ahead = tokens.peek(offset);\n if (!ahead) break;\n const aheadValue = (ahead.normalized || ahead.value).toLowerCase();\n if (aheadValue === leadingMarker) {\n this.logger.debug(\n ' >> MARKER SCAN: found',\n leadingMarker,\n 'at offset',\n offset,\n '- skipping intervening tokens'\n );\n // Advance past intervening tokens to reach the marker\n for (let s = 0; s < offset; s++) tokens.advance();\n\n // Retry group match from marker position\n const retrySuccess = this.matchTokenSequence(\n tokens,\n patternToken.tokens,\n captured,\n parentStopMarkers\n );\n if (retrySuccess) return true;\n\n // Retry failed — full reset\n tokens.reset(mark);\n for (const role of captured.keys()) {\n if (!capturedBefore.has(role)) captured.delete(role);\n }\n break;\n }\n }\n }\n\n return true; // Optional group, just skip\n }\n\n /**\n * Get the leading marker literal from an optional group.\n * Returns the lowercase marker value, or null if the group\n * doesn't start with a literal token (e.g., SOV groups where\n * the role comes before the marker).\n */\n private getGroupLeadingMarker(group: PatternToken & { type: 'group' }): string | null {\n const first = group.tokens[0];\n if (first?.type === 'literal') return first.value.toLowerCase();\n return null;\n }\n\n /**\n * Get the type of match for a token against a value.\n * Used for confidence calculation.\n */\n private getMatchType(\n token: LanguageToken,\n value: string\n ): 'exact' | 'normalized' | 'stem' | 'case-insensitive' | 'none' {\n // Exact match (highest confidence)\n if (token.value === value) return 'exact';\n\n // Explicit keyword map normalized match (high confidence)\n if (token.normalized === value) return 'normalized';\n\n // Morphologically normalized stem match (medium-high confidence)\n // Only accept if stem confidence is reasonable\n if (token.stem === value && token.stemConfidence !== undefined && token.stemConfidence >= 0.7) {\n return 'stem';\n }\n\n // Case-insensitive match for keywords (medium confidence)\n if (token.kind === 'keyword' && this.safeToLowerCase(token.value) === value.toLowerCase()) {\n return 'case-insensitive';\n }\n\n return 'none';\n }\n\n /**\n * Collect literal values from upcoming pattern tokens that act as stop markers\n * for greedy role capture. Returns the set of lowercase values.\n */\n private collectStopMarkers(patternTokens: PatternToken[], startIndex: number): Set<string> {\n const markers = new Set<string>();\n for (let j = startIndex; j < patternTokens.length; j++) {\n const pt = patternTokens[j];\n if (pt.type === 'literal') {\n markers.add(pt.value.toLowerCase());\n if (pt.alternatives) {\n for (const alt of pt.alternatives) {\n markers.add(alt.toLowerCase());\n }\n }\n break;\n }\n if (pt.type === 'group') {\n for (const gt of pt.tokens) {\n if (gt.type === 'literal') {\n markers.add(gt.value.toLowerCase());\n if (gt.alternatives) {\n for (const alt of gt.alternatives) {\n markers.add(alt.toLowerCase());\n }\n }\n break;\n }\n }\n // For optional groups, continue scanning past them so the greedy\n // capture also sees subsequent required literals (e.g., the SOV verb\n // keyword after an optional WHERE group).\n if (!pt.optional) break;\n }\n }\n return markers;\n }\n\n /**\n * Check if a token matches any stop marker for greedy capture.\n */\n private isStopMarker(token: LanguageToken, stopMarkers: Set<string>): boolean {\n if (stopMarkers.size === 0) return false;\n // Check both raw value and normalized form against stop markers.\n // Pattern literals use native keywords (e.g., '選択') while tokenizers may\n // set normalized to the English equivalent (e.g., 'select'). Both must match.\n if (stopMarkers.has(token.value.toLowerCase())) return true;\n if (token.normalized && stopMarkers.has(token.normalized.toLowerCase())) return true;\n return false;\n }\n\n /**\n * Track stem matches for confidence calculation.\n * This is set during matching and read during confidence calculation.\n */\n private stemMatchCount: number = 0;\n private totalKeywordMatches: number = 0;\n\n // ==========================================================================\n // Depth Limits for Expression Parsing (security hardening)\n // ==========================================================================\n\n /** Maximum depth for nested property access (e.g., a.b.c.d...) */\n private static readonly MAX_PROPERTY_DEPTH = 10;\n\n /** Maximum number of arguments in method calls */\n private static readonly MAX_METHOD_ARGS = 20;\n\n /**\n * Convert a language token to a semantic value.\n */\n private tokenToSemanticValue(token: LanguageToken): SemanticValue | null {\n switch (token.kind) {\n case 'selector':\n return createSelector(token.value);\n\n case 'literal':\n return this.parseLiteralValue(token.value);\n\n case 'keyword':\n // Keywords might be references or values\n const tokenValue = token.normalized || token.value;\n const lower = this.safeToLowerCase(tokenValue);\n if (isValidReference(lower)) {\n return createReference(lower);\n }\n return createLiteral(token.normalized || token.value);\n\n case 'identifier':\n // Check if it's a variable reference (:varname)\n // Note: :varname doesn't match the ReferenceValue union but is used as a\n // reference token downstream — this cast preserves existing behavior\n if (typeof token.value === 'string' && token.value.startsWith(':')) {\n return createReference(token.value as ReferenceValue['value']);\n }\n // Check if it's a built-in reference\n const identLower = this.safeToLowerCase(token.value);\n if (isValidReference(identLower)) {\n return createReference(identLower);\n }\n // Regular identifiers are variable references - use 'expression' type\n // which gets converted to 'identifier' AST nodes by semantic-integration.ts\n return { type: 'expression', raw: token.value } as const;\n\n case 'url':\n // URLs are treated as string literals (paths/URLs for navigation/fetch)\n return createLiteral(token.value, 'string');\n\n default:\n return null;\n }\n }\n\n /**\n * Parse a literal value (string, number, boolean).\n */\n private parseLiteralValue(value: string): SemanticValue {\n // String literal\n if (\n value.startsWith('\"') ||\n value.startsWith(\"'\") ||\n value.startsWith('`') ||\n value.startsWith('「')\n ) {\n const inner = value.slice(1, -1);\n return createLiteral(inner, 'string');\n }\n\n // Boolean\n if (value === 'true') return createLiteral(true, 'boolean');\n if (value === 'false') return createLiteral(false, 'boolean');\n\n // Duration (number with suffix)\n const durationMatch = value.match(/^(\\d+(?:\\.\\d+)?)(ms|s|m|h)?$/);\n if (durationMatch) {\n const num = parseFloat(durationMatch[1]);\n const unit = durationMatch[2];\n if (unit) {\n return createLiteral(value, 'duration');\n }\n return createLiteral(num, 'number');\n }\n\n // Plain number\n const num = parseFloat(value);\n if (!isNaN(num)) {\n return createLiteral(num, 'number');\n }\n\n // Default to string\n return createLiteral(value, 'string');\n }\n\n /**\n * Apply extraction rules to fill in static values and defaults for missing roles.\n */\n private applyExtractionRules(\n pattern: LanguagePattern,\n captured: Map<SemanticRole, SemanticValue>\n ): void {\n for (const [role, rule] of Object.entries(pattern.extraction)) {\n if (!captured.has(role as SemanticRole)) {\n if (rule.value !== undefined) {\n // Static value extraction (e.g., action: { value: \"toggle\" })\n captured.set(role as SemanticRole, { type: 'literal', value: rule.value });\n } else if (rule.default) {\n captured.set(role as SemanticRole, rule.default);\n }\n }\n }\n }\n\n /**\n * Check if a pattern token is optional.\n */\n private isOptional(patternToken: PatternToken): boolean {\n return patternToken.type !== 'literal' && patternToken.optional === true;\n }\n\n /**\n * Calculate confidence score for a match (0-1).\n *\n * Confidence is reduced for:\n * - Stem matches (morphological normalization has inherent uncertainty)\n * - Missing optional roles (but less penalty if role has a default value)\n *\n * Confidence is increased for:\n * - VSO languages (Arabic) when pattern starts with a verb\n */\n private calculateConfidence(\n pattern: LanguagePattern,\n captured: Map<SemanticRole, SemanticValue>\n ): number {\n let score = 0;\n let maxScore = 0;\n\n // Helper to check if a role has a default value in extraction rules\n const hasDefault = (role: SemanticRole): boolean => {\n return pattern.extraction?.[role]?.default !== undefined;\n };\n\n // Score based on captured roles\n for (const token of pattern.template.tokens) {\n if (token.type === 'role') {\n maxScore += 1;\n if (captured.has(token.role)) {\n score += 1;\n }\n } else if (token.type === 'group') {\n // Group tokens are optional - weight depends on whether they have defaults\n for (const subToken of token.tokens) {\n if (subToken.type === 'role') {\n const roleHasDefault = hasDefault(subToken.role);\n const weight = 0.8; // Optional roles: 80% weight\n maxScore += weight;\n\n if (captured.has(subToken.role)) {\n // Role was explicitly provided by user\n score += weight;\n } else if (roleHasDefault) {\n // Role has a default - give 60% partial credit since command is semantically complete\n // This prevents penalizing common patterns like \"toggle .active\" (default: me)\n score += weight * 0.6;\n }\n // If no default and not captured, score += 0 (true penalty for missing info)\n }\n }\n }\n }\n\n let baseConfidence = maxScore > 0 ? score / maxScore : 1;\n\n // Apply penalty for stem matches\n // Each stem match reduces confidence slightly (e.g., 5% per stem match)\n // This ensures exact matches are preferred over morphological matches\n if (this.stemMatchCount > 0 && this.totalKeywordMatches > 0) {\n const stemPenalty = (this.stemMatchCount / this.totalKeywordMatches) * 0.15;\n baseConfidence = Math.max(0.5, baseConfidence - stemPenalty);\n }\n\n // Apply VSO confidence boost for Arabic verb-first patterns\n const vsoBoost = this.calculateVSOConfidenceBoost(pattern);\n baseConfidence = Math.min(1.0, baseConfidence + vsoBoost);\n\n // Apply preposition disambiguation adjustment for Arabic\n const prepositionAdjustment = this.arabicPrepositionDisambiguation(pattern, captured);\n baseConfidence = Math.max(0.0, Math.min(1.0, baseConfidence + prepositionAdjustment));\n\n return baseConfidence;\n }\n\n /**\n * Calculate confidence boost for VSO (Verb-Subject-Object) language patterns.\n * Arabic naturally uses VSO word order, so patterns that start with a verb\n * should receive a confidence boost.\n *\n * Returns +0.15 confidence boost if:\n * - Language is Arabic ('ar')\n * - Pattern's first token is a verb keyword\n *\n * @param pattern The language pattern being matched\n * @returns Confidence boost (0 or 0.15)\n */\n private calculateVSOConfidenceBoost(pattern: LanguagePattern): number {\n // Only apply to Arabic\n if (pattern.language !== 'ar') {\n return 0;\n }\n\n // Check if first token in pattern is a literal (keyword)\n const firstToken = pattern.template.tokens[0];\n if (!firstToken || firstToken.type !== 'literal') {\n return 0;\n }\n\n // List of Arabic verb keywords (command verbs)\n const ARABIC_VERBS = new Set([\n 'بدل',\n 'غير',\n 'أضف',\n 'أزل',\n 'ضع',\n 'اجعل',\n 'عين',\n 'زد',\n 'انقص',\n 'سجل',\n 'أظهر',\n 'أخف',\n 'شغل',\n 'أرسل',\n 'ركز',\n 'شوش',\n 'توقف',\n 'انسخ',\n 'احذف',\n 'اصنع',\n 'انتظر',\n 'انتقال',\n 'أو',\n ]);\n\n // Check if first token value is a verb\n if (ARABIC_VERBS.has(firstToken.value)) {\n return 0.15;\n }\n\n // Check alternatives\n if (firstToken.alternatives) {\n for (const alt of firstToken.alternatives) {\n if (ARABIC_VERBS.has(alt)) {\n return 0.15;\n }\n }\n }\n\n return 0;\n }\n\n /**\n * Arabic preposition disambiguation for confidence adjustment.\n *\n * Different Arabic prepositions are more or less natural for different semantic roles:\n * - على (on/upon) is preferred for patient/target roles (element selectors)\n * - إلى (to) is preferred for destination roles\n * - من (from) is preferred for source roles\n * - في (in) is preferred for location roles\n *\n * This method analyzes the prepositions used with captured semantic roles and\n * adjusts confidence based on idiomaticity:\n * - +0.10 for highly idiomatic preposition choices\n * - -0.10 for less natural preposition choices\n *\n * @param pattern The language pattern being matched\n * @param captured The captured semantic values\n * @returns Confidence adjustment (-0.10 to +0.10)\n */\n private arabicPrepositionDisambiguation(\n pattern: LanguagePattern,\n captured: Map<SemanticRole, SemanticValue>\n ): number {\n // Only apply to Arabic\n if (pattern.language !== 'ar') {\n return 0;\n }\n\n let adjustment = 0;\n\n // Preferred prepositions for each semantic role\n // Only including roles that commonly use prepositions in Arabic\n const PREFERRED_PREPOSITIONS: Partial<Record<SemanticRole, string[]>> = {\n patient: ['على'], // element selectors prefer على (on/upon)\n destination: ['إلى', 'الى'], // destination prefers إلى (to)\n source: ['من'], // source prefers من (from)\n agent: ['من'], // agent/by prefers من (from/by)\n manner: ['ب'], // manner prefers ب (with/by)\n style: ['ب'], // style prefers ب (with)\n goal: ['إلى', 'الى'], // target state prefers إلى (to)\n method: ['ب'], // method prefers ب (with/by)\n };\n\n // Check each captured role for preposition metadata\n for (const [role, value] of captured.entries()) {\n // Skip if no preferred prepositions defined for this role\n const preferred = PREFERRED_PREPOSITIONS[role];\n if (!preferred || preferred.length === 0) {\n continue;\n }\n\n // Check if the value has preposition metadata (from Arabic tokenizer)\n // This metadata is attached when a preposition particle token is consumed\n const metadata =\n 'metadata' in value ? (value as { metadata: Record<string, unknown> }).metadata : undefined;\n if (metadata && typeof metadata.prepositionValue === 'string') {\n const usedPreposition = metadata.prepositionValue;\n\n // Check if the used preposition is in the preferred list\n if (preferred.includes(usedPreposition)) {\n // Idiomatic choice - boost confidence\n adjustment += 0.1;\n } else {\n // Less natural choice - reduce confidence\n adjustment -= 0.1;\n }\n }\n }\n\n // Cap total adjustment at ±0.10 (even if multiple roles analyzed)\n return Math.max(-0.1, Math.min(0.1, adjustment));\n }\n\n // ===========================================================================\n // English Idiom Support - Noise Word Handling\n // ===========================================================================\n\n /**\n * Noise words that can be skipped in English for more natural syntax.\n * - \"the\" before selectors: \"toggle the .active\" → \"toggle .active\"\n * - \"class\" after class selectors: \"add the .visible class\" → \"add .visible\"\n */\n private static readonly ENGLISH_NOISE_WORDS = new Set(['the', 'a', 'an']);\n\n /**\n * Skip noise words like \"the\" before selectors.\n * This enables more natural English syntax like \"toggle the .active\".\n */\n private skipNoiseWords(tokens: TokenStream): void {\n const token = tokens.peek();\n if (!token) return;\n\n const tokenLower = this.safeToLowerCase(token.value);\n\n // Check if current token is a noise word (like \"the\")\n if (PatternMatcher.ENGLISH_NOISE_WORDS.has(tokenLower)) {\n // Look ahead to see if the next token is a selector\n const mark = tokens.mark();\n tokens.advance();\n const nextToken = tokens.peek();\n\n if (nextToken && nextToken.kind === 'selector') {\n // Keep the position after \"the\" - effectively skipping it\n return;\n }\n\n // Not followed by a selector, revert\n tokens.reset(mark);\n }\n\n // Also handle \"class\" after class selectors: \".visible class\" → \".visible\"\n // This is handled when the selector has already been consumed,\n // so we check if current token is \"class\" and skip it\n if (tokenLower === 'class') {\n // Skip \"class\" as it's just noise after a class selector\n tokens.advance();\n }\n }\n\n /**\n * Extract event modifiers from the token stream.\n * Event modifiers are .once, .debounce(N), .throttle(N), .queue(strategy)\n * that can appear after event names.\n *\n * Returns EventModifiers object or undefined if no modifiers found.\n */\n extractEventModifiers(tokens: TokenStream): import('../types').EventModifiers | undefined {\n const modifiers: {\n once?: boolean;\n debounce?: number;\n throttle?: number;\n queue?: 'first' | 'last' | 'all' | 'none';\n from?: SemanticValue;\n } = {};\n\n let foundModifier = false;\n\n // Consume all consecutive event modifier tokens\n while (!tokens.isAtEnd()) {\n const token = tokens.peek();\n if (!token || token.kind !== 'event-modifier') {\n break;\n }\n\n const metadata = token.metadata as\n | { modifierName: string; value?: number | string }\n | undefined;\n if (!metadata) {\n break;\n }\n\n foundModifier = true;\n\n switch (metadata.modifierName) {\n case 'once':\n modifiers.once = true;\n break;\n case 'debounce':\n if (typeof metadata.value === 'number') {\n modifiers.debounce = metadata.value;\n }\n break;\n case 'throttle':\n if (typeof metadata.value === 'number') {\n modifiers.throttle = metadata.value;\n }\n break;\n case 'queue':\n if (\n metadata.value === 'first' ||\n metadata.value === 'last' ||\n metadata.value === 'all' ||\n metadata.value === 'none'\n ) {\n modifiers.queue = metadata.value;\n }\n break;\n }\n\n tokens.advance();\n }\n\n return foundModifier ? modifiers : undefined;\n }\n}\n\n// =============================================================================\n// Convenience Functions\n// =============================================================================\n\n/**\n * Singleton pattern matcher instance.\n */\nexport const patternMatcher = new PatternMatcher();\n\n/**\n * Match tokens against a pattern.\n */\nexport function matchPattern(\n tokens: TokenStream,\n pattern: LanguagePattern\n): PatternMatchResult | null {\n return patternMatcher.matchPattern(tokens, pattern);\n}\n\n/**\n * Match tokens against multiple patterns, return best match.\n */\nexport function matchBest(\n tokens: TokenStream,\n patterns: LanguagePattern[]\n): PatternMatchResult | null {\n return patternMatcher.matchBest(tokens, patterns);\n}\n","/**\n * Pattern Generator\n *\n * Generates LanguagePattern objects from CommandSchema + LanguageProfile.\n * This solves the pattern explosion problem by deriving patterns from\n * high-level schema definitions rather than hand-writing each one.\n */\n\nimport type { LanguagePattern, PatternToken, ExtractionRule } from '../core/types';\nimport type { CommandSchema, RoleSpec } from '../schema';\n\n/**\n * Minimal language profile interface for pattern generation.\n */\nexport interface PatternGenLanguageProfile {\n readonly code: string;\n readonly wordOrder: 'SVO' | 'SOV' | 'VSO' | 'VOS' | 'OSV' | 'OVS' | 'free';\n readonly keywords: Record<string, { primary: string; alternatives?: string[] }>;\n readonly roleMarkers?: Record<\n string,\n { primary: string; alternatives?: string[]; position?: 'before' | 'after' }\n >;\n}\n\n/**\n * Configuration for pattern generation.\n */\nexport interface GeneratorConfig {\n /** Base priority for generated patterns (default: 100) */\n readonly basePriority?: number;\n /** Include optional role variants (default: true) */\n readonly includeOptionalVariants?: boolean;\n}\n\nconst defaultConfig: GeneratorConfig = {\n basePriority: 100,\n includeOptionalVariants: true,\n};\n\n/**\n * Generate a language pattern from a command schema and language profile.\n *\n * @param schema - Command schema defining the command structure\n * @param profile - Language profile with word order and keywords\n * @param config - Optional configuration\n * @returns Generated language pattern\n */\nexport function generatePattern(\n schema: CommandSchema,\n profile: PatternGenLanguageProfile,\n config: GeneratorConfig = defaultConfig\n): LanguagePattern {\n const id = `${schema.action}-${profile.code}-generated`;\n const priority = config.basePriority ?? 100;\n\n // Get keyword translation\n const keyword = profile.keywords[schema.action];\n if (!keyword) {\n throw new Error(`No keyword translation for '${schema.action}' in ${profile.code}`);\n }\n\n // Build tokens based on word order\n const tokens = buildTokens(schema, profile, keyword.primary, keyword.alternatives);\n\n // Build extraction rules\n const extraction = buildExtractionRules(schema, profile);\n\n // Build format string for documentation\n const format = buildFormatString(schema, profile, keyword.primary);\n\n return {\n id,\n language: profile.code,\n command: schema.action,\n priority,\n template: {\n format,\n tokens,\n },\n extraction,\n };\n}\n\n/**\n * Build pattern tokens based on word order and role markers.\n */\nfunction buildTokens(\n schema: CommandSchema,\n profile: PatternGenLanguageProfile,\n keyword: string,\n alternatives?: string[]\n): PatternToken[] {\n const tokens: PatternToken[] = [];\n const keywordToken: PatternToken = {\n type: 'literal',\n value: keyword,\n ...(alternatives?.length && { alternatives }),\n };\n\n // Sort roles by word order\n const sortedRoles = sortRolesByWordOrder(schema.roles, profile.wordOrder);\n\n // For SVO: [action, patient, destination, source, ...]\n if (profile.wordOrder === 'SVO') {\n // Add keyword first\n tokens.push(keywordToken);\n\n // Add roles with markers\n for (const role of sortedRoles) {\n addRoleWithMarker(tokens, role, profile);\n }\n }\n // For SOV: [patient, destination, source, ..., action]\n else if (profile.wordOrder === 'SOV') {\n // Add roles with markers first\n for (const role of sortedRoles) {\n addRoleWithMarker(tokens, role, profile);\n }\n\n // Add keyword last\n tokens.push(keywordToken);\n }\n // For VSO: [action, destination, patient, source, ...]\n else if (profile.wordOrder === 'VSO') {\n // Add keyword first\n tokens.push(keywordToken);\n\n // Add roles with markers\n for (const role of sortedRoles) {\n addRoleWithMarker(tokens, role, profile);\n }\n }\n // Other word orders can be added as needed\n else {\n // Fallback to SVO-style ordering\n tokens.push(keywordToken);\n for (const role of sortedRoles) {\n addRoleWithMarker(tokens, role, profile);\n }\n }\n\n return tokens;\n}\n\n/**\n * Add a role token with its grammatical marker if needed.\n * For optional roles, wraps the role + marker in a group.\n */\nfunction addRoleWithMarker(\n tokens: PatternToken[],\n roleSpec: RoleSpec,\n profile: PatternGenLanguageProfile\n): void {\n const marker = getMarkerForRole(roleSpec, profile);\n const isOptional = !roleSpec.required;\n\n // Build the role token\n const roleToken: PatternToken = {\n type: 'role',\n role: roleSpec.role,\n optional: isOptional,\n expectedTypes: roleSpec.expectedTypes,\n ...(roleSpec.greedy && { greedy: true }),\n };\n\n if (marker) {\n const markerInfo = profile.roleMarkers?.[roleSpec.role];\n // Priority: schema markerPosition → profile roleMarkers position → word-order default\n const defaultPosition = profile.wordOrder === 'SOV' ? 'after' : 'before';\n const position = roleSpec.markerPosition ?? markerInfo?.position ?? defaultPosition;\n\n if (isOptional) {\n // Optional role: wrap marker + role in optional group\n if (position === 'before') {\n tokens.push({\n type: 'group',\n optional: true,\n tokens: [{ type: 'literal', value: marker }, roleToken],\n });\n } else {\n tokens.push({\n type: 'group',\n optional: true,\n tokens: [roleToken, { type: 'literal', value: marker }],\n });\n }\n } else {\n // Required role: add marker + role separately\n if (position === 'before') {\n tokens.push({ type: 'literal', value: marker });\n tokens.push(roleToken);\n } else {\n tokens.push(roleToken);\n tokens.push({ type: 'literal', value: marker });\n }\n }\n } else {\n // No marker - just add the role\n tokens.push(roleToken);\n }\n}\n\n/**\n * Get the grammatical marker for a role from the profile.\n */\nfunction getMarkerForRole(\n roleSpec: RoleSpec,\n profile: PatternGenLanguageProfile\n): string | undefined {\n // Check for role-specific override first\n if (roleSpec.markerOverride?.[profile.code]) {\n return roleSpec.markerOverride[profile.code];\n }\n\n // Use profile's default marker for this role\n return profile.roleMarkers?.[roleSpec.role]?.primary;\n}\n\n/**\n * Sort roles by word order for pattern building.\n */\nfunction sortRolesByWordOrder(roles: RoleSpec[], wordOrder: string): RoleSpec[] {\n const sorted = [...roles];\n\n if (wordOrder === 'SVO') {\n // Sort by svoPosition (higher = earlier)\n sorted.sort((a, b) => (b.svoPosition ?? 0) - (a.svoPosition ?? 0));\n } else if (wordOrder === 'SOV') {\n // Sort by sovPosition (higher = earlier)\n sorted.sort((a, b) => (b.sovPosition ?? 0) - (a.sovPosition ?? 0));\n }\n // VSO and others use SVO-style ordering\n\n return sorted;\n}\n\n/**\n * Build extraction rules for capturing role values during parsing.\n */\nfunction buildExtractionRules(\n schema: CommandSchema,\n profile: PatternGenLanguageProfile\n): Record<string, ExtractionRule> {\n const rules: Record<string, ExtractionRule> = {};\n\n for (const roleSpec of schema.roles) {\n // Build the rule object correctly with readonly properties\n const marker = getMarkerForRole(roleSpec, profile);\n\n const rule: ExtractionRule = {\n ...(roleSpec.default !== undefined && { default: roleSpec.default }),\n ...(marker && { marker }),\n };\n\n rules[roleSpec.role] = rule;\n }\n\n return rules;\n}\n\n/**\n * Build a human-readable format string for the pattern.\n */\nfunction buildFormatString(\n schema: CommandSchema,\n profile: PatternGenLanguageProfile,\n keyword: string\n): string {\n const parts: string[] = [];\n\n if (profile.wordOrder === 'SVO' || profile.wordOrder === 'VSO') {\n parts.push(keyword);\n }\n\n for (const role of schema.roles) {\n const marker = getMarkerForRole(role, profile);\n const roleName = `{${role.role}}`;\n\n if (marker) {\n const markerInfo = profile.roleMarkers?.[role.role];\n if (markerInfo?.position === 'after') {\n parts.push(`${roleName} ${marker}`);\n } else {\n parts.push(`${marker} ${roleName}`);\n }\n } else {\n parts.push(roleName);\n }\n }\n\n if (profile.wordOrder === 'SOV') {\n parts.push(keyword);\n }\n\n return parts.join(' ');\n}\n\n/**\n * Generate multiple pattern variants (with and without optional roles).\n */\nexport function generatePatternVariants(\n schema: CommandSchema,\n profile: PatternGenLanguageProfile,\n config: GeneratorConfig = defaultConfig\n): LanguagePattern[] {\n const patterns: LanguagePattern[] = [];\n\n // Main pattern (all roles)\n patterns.push(generatePattern(schema, profile, config));\n\n // TODO: Generate variants with optional roles omitted\n // This can be added later when needed\n\n return patterns;\n}\n","/**\n * Generalized Grammar System for Multilingual Hyperscript\n *\n * This system abstracts grammatical patterns across language families,\n * enabling deep multilingual support without per-language hardcoding.\n *\n * Key Linguistic Concepts:\n * - Word Order: SVO, SOV, VSO (and variations)\n * - Adposition Type: Preposition (English) vs Postposition (Japanese/Korean)\n * - Morphology: Isolating (Chinese) vs Agglutinative (Turkish) vs Fusional (Arabic)\n * - Text Direction: LTR vs RTL\n */\n\n// =============================================================================\n// Core Types\n// =============================================================================\n\n/**\n * Semantic roles in hyperscript commands.\n * These are universal across all 13 supported languages - only the surface form changes.\n *\n * ## Core Thematic Roles (from linguistic theory)\n * | Role | Usage | Purpose | Example |\n * |-------------|-------|-----------------------------|---------------------------|\n * | action | 100% | Command verb | toggle, put, fetch |\n * | patient | 90% | What is acted upon | .active, #count |\n * | destination | 40% | Where something goes | into #output, to .class |\n * | source | 13% | Where something comes from | from #input, from URL |\n * | event | 106% | Trigger events | click, keydown, submit |\n * | condition | 8% | Boolean expressions | if x > 5, when visible |\n * | agent | 0% | Who performs action | Reserved for future use |\n * | goal | 1% | Target value/state | to 'red' (in transition) |\n *\n * ## Quantitative Roles (answer \"how much/long\")\n * | Role | Usage | Purpose | Example |\n * |----------|-------|----------------|----------------------|\n * | quantity | 7% | Numeric amount | by 5, 3 times |\n * | duration | 1% | Time span | for 5 seconds, 500ms |\n *\n * ## Adverbial/Modifier Roles (answer \"how/by what means\")\n * | Role | Usage | Purpose | Example |\n * |--------------|-------|---------------------------|-------------------|\n * | style | 2% | Animation/behavior | with fade |\n * | manner | 2% | Insertion position | before, after |\n * | method | 1% | HTTP method/technique | via POST, as GET |\n * | responseType | 1% | Response format | as json, as html |\n *\n * ## Control Flow Roles\n * | Role | Usage | Purpose | Example |\n * |----------|-------|--------------|-----------------------|\n * | loopType | 6% | Loop variant | forever, until, times |\n *\n * ## Design Notes\n * - Low-usage roles (agent, goal, method, responseType) are intentionally kept for:\n * - Linguistic completeness across all 13 languages\n * - Future extensibility (AI agents, server-side execution)\n * - Command-specific semantics (fetch, transition)\n * - Each role has distinct grammatical markers per language (see profiles/index.ts)\n * - Usage percentages based on pattern database analysis\n */\nexport type SemanticRole =\n // Core thematic roles\n | 'action' // The command/verb (increment, put, toggle)\n | 'agent' // Who/what performs action (reserved for future: AI agents, server-side)\n | 'patient' // What is acted upon (the counter, .active)\n | 'source' // Origin (from #input, from URL)\n | 'destination' // Target location (into #output, to .class)\n | 'goal' // Target value/state (to 'red', to 100)\n | 'event' // Trigger (click, input, keydown)\n | 'condition' // Boolean expression (if x > 5)\n // Quantitative roles\n | 'quantity' // Numeric amount (by 5, 3 times)\n | 'duration' // Time span (for 5 seconds, over 500ms)\n // Adverbial roles\n | 'responseType' // Response format (as json, as text, as html)\n | 'method' // HTTP method/technique (via POST, using GET)\n | 'style' // Visual/behavioral manner (with fade, smoothly)\n | 'manner' // Insertion position (before, after)\n // Control flow roles\n | 'loopType' // Loop variant: forever, times, for, while, until, until-event\n // Structural roles (for parser control)\n | 'continues'; // Continuation marker (then-chains)\n\n/**\n * Word order patterns\n * These represent the major typological categories\n */\nexport type WordOrder = 'SVO' | 'SOV' | 'VSO' | 'VOS' | 'OVS' | 'OSV' | 'free';\n\n/**\n * Where grammatical markers appear relative to their noun/verb\n */\nexport type AdpositionType = 'preposition' | 'postposition' | 'circumposition' | 'none';\n\n/**\n * Morphological typology - how words are constructed\n */\nexport type MorphologyType =\n | 'isolating' // Chinese - no inflection, word order matters\n | 'agglutinative' // Turkish, Japanese - morphemes stack predictably\n | 'fusional' // Arabic, Spanish - morphemes blend together\n | 'polysynthetic'; // Quechua - complex words encode full sentences\n\n/**\n * A grammatical marker (particle, case ending, preposition)\n */\nexport interface GrammaticalMarker {\n form: string; // The actual text (を, に, to, 的)\n role: SemanticRole; // What semantic role it marks\n position: AdpositionType; // Where it appears\n required: boolean; // Is it mandatory?\n alternatives?: string[]; // Alternative forms (e.g., 을/를 in Korean)\n}\n\n/**\n * Metadata for preserving line structure during translation.\n * Tracks indentation and blank lines so output maintains the same format.\n */\nexport interface LineMetadata {\n /** Trimmed line content (empty string for blank lines) */\n content: string;\n /** Leading whitespace (tabs/spaces) from original line */\n originalIndent: string;\n /** True if the line was empty or whitespace-only */\n isBlank: boolean;\n}\n\n// =============================================================================\n// Language Profile\n// =============================================================================\n\n/**\n * Complete grammatical profile for a language\n * This captures the essential typological features needed for transformation\n */\nexport interface LanguageProfile {\n code: string; // ISO 639-1 code\n name: string; // Native name\n\n // Typological features\n wordOrder: WordOrder;\n adpositionType: AdpositionType;\n morphology: MorphologyType;\n direction: 'ltr' | 'rtl';\n\n // Grammatical markers for each semantic role\n markers: GrammaticalMarker[];\n\n // Role ordering - which semantic roles come in what order\n // E.g., Japanese: ['patient', 'source', 'destination', 'action']\n // E.g., English: ['action', 'patient', 'source', 'destination']\n canonicalOrder: SemanticRole[];\n\n // Special rules\n rules?: GrammarRule[];\n}\n\n/**\n * Pattern for transforming hyperscript structures\n */\nexport interface GrammarRule {\n name: string;\n description: string;\n\n // Pattern matching (in canonical English form)\n match: PatternMatcher;\n\n // How to transform for this language\n transform: PatternTransform;\n\n // Priority (higher = checked first)\n priority: number;\n}\n\n/**\n * Matches a hyperscript pattern\n */\nexport interface PatternMatcher {\n // Command type(s) this matches\n commands?: string[];\n\n // Required semantic roles\n requiredRoles: SemanticRole[];\n\n // Optional roles\n optionalRoles?: SemanticRole[];\n\n // Custom predicate for complex matching\n predicate?: (parsed: ParsedStatement) => boolean;\n}\n\n/**\n * Defines how to transform a matched pattern\n */\nexport interface PatternTransform {\n // Reorder roles for target language\n roleOrder: SemanticRole[];\n\n // Insert markers between roles\n insertMarkers?: boolean;\n\n // Custom transformation function\n custom?: (parsed: ParsedStatement, profile: LanguageProfile) => string;\n}\n\n// =============================================================================\n// Parsed Structures\n// =============================================================================\n\n/**\n * A parsed hyperscript statement broken into semantic components\n */\nexport interface ParsedStatement {\n type: 'event-handler' | 'command' | 'conditional' | 'loop';\n roles: Map<SemanticRole, ParsedElement>;\n original: string;\n}\n\n/**\n * A single element with its semantic role\n */\nexport interface ParsedElement {\n role: SemanticRole;\n value: string; // Original English value\n translated?: string; // Translated value\n isSelector?: boolean; // CSS selector (don't translate)\n isLiteral?: boolean; // Literal value (don't translate)\n}\n\n// =============================================================================\n// Universal Pattern Templates\n// =============================================================================\n\n/**\n * Universal templates for common hyperscript patterns\n * These define the semantic structure independent of surface form\n */\nexport const UNIVERSAL_PATTERNS = {\n // on click increment #count\n eventIncrement: {\n name: 'event-increment',\n roles: ['event', 'action', 'patient'] as SemanticRole[],\n english: 'on {event} {action} {patient}',\n },\n\n // put X into Y\n putInto: {\n name: 'put-into',\n roles: ['action', 'patient', 'destination'] as SemanticRole[],\n english: '{action} {patient} into {destination}',\n },\n\n // add .class to element\n addTo: {\n name: 'add-to',\n roles: ['action', 'patient', 'destination'] as SemanticRole[],\n english: '{action} {patient} to {destination}',\n },\n\n // toggle .class on element\n toggleOn: {\n name: 'toggle-on',\n roles: ['action', 'patient', 'destination'] as SemanticRole[],\n english: '{action} {patient} on {destination}',\n },\n\n // wait 2 seconds\n waitDuration: {\n name: 'wait-duration',\n roles: ['action', 'quantity'] as SemanticRole[],\n english: '{action} {quantity}',\n },\n\n // if condition then ... end\n conditional: {\n name: 'conditional',\n roles: ['action', 'condition'] as SemanticRole[],\n english: '{action} {condition} then ... end',\n },\n\n // fetch URL as type\n fetchAs: {\n name: 'fetch-as',\n roles: ['action', 'source', 'method'] as SemanticRole[],\n english: '{action} {source} as {method}',\n },\n\n // show element with animation\n showWith: {\n name: 'show-with',\n roles: ['action', 'patient', 'style'] as SemanticRole[],\n english: '{action} {patient} with {style}',\n },\n\n // transition property over duration\n transitionOver: {\n name: 'transition-over',\n roles: ['action', 'patient', 'duration'] as SemanticRole[],\n english: '{action} {patient} over {duration}',\n },\n} as const;\n\n// =============================================================================\n// Language Family Defaults\n// =============================================================================\n\n/**\n * Default profiles for major language families\n * Individual languages inherit and override these\n */\nexport const LANGUAGE_FAMILY_DEFAULTS: Record<string, Partial<LanguageProfile>> = {\n // Germanic (English, German, Dutch)\n germanic: {\n wordOrder: 'SVO',\n adpositionType: 'preposition',\n morphology: 'fusional',\n direction: 'ltr',\n canonicalOrder: [\n 'action',\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n ],\n },\n\n // Romance (Spanish, French, Italian, Portuguese)\n romance: {\n wordOrder: 'SVO',\n adpositionType: 'preposition',\n morphology: 'fusional',\n direction: 'ltr',\n canonicalOrder: [\n 'action',\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n ],\n },\n\n // Japonic (Japanese)\n japonic: {\n wordOrder: 'SOV',\n adpositionType: 'postposition',\n morphology: 'agglutinative',\n direction: 'ltr',\n canonicalOrder: [\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n 'action',\n ],\n },\n\n // Koreanic (Korean)\n koreanic: {\n wordOrder: 'SOV',\n adpositionType: 'postposition',\n morphology: 'agglutinative',\n direction: 'ltr',\n canonicalOrder: [\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n 'action',\n ],\n },\n\n // Turkic (Turkish, Azerbaijani)\n turkic: {\n wordOrder: 'SOV',\n adpositionType: 'postposition',\n morphology: 'agglutinative',\n direction: 'ltr',\n canonicalOrder: [\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n 'action',\n ],\n },\n\n // Sinitic (Chinese, Cantonese)\n sinitic: {\n wordOrder: 'SVO', // Topic-prominent, flexible\n adpositionType: 'preposition',\n morphology: 'isolating',\n direction: 'ltr',\n canonicalOrder: [\n 'action',\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n ],\n },\n\n // Semitic (Arabic, Hebrew)\n semitic: {\n wordOrder: 'VSO',\n adpositionType: 'preposition',\n morphology: 'fusional', // Root-pattern system\n direction: 'rtl',\n canonicalOrder: [\n 'action',\n 'agent',\n 'patient',\n 'destination',\n 'source',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n ],\n },\n\n // Austronesian (Indonesian, Tagalog)\n austronesian: {\n wordOrder: 'SVO',\n adpositionType: 'preposition',\n morphology: 'agglutinative',\n direction: 'ltr',\n canonicalOrder: [\n 'action',\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n ],\n },\n\n // Quechuan (Quechua)\n quechuan: {\n wordOrder: 'SOV',\n adpositionType: 'postposition',\n morphology: 'agglutinative', // Actually polysynthetic but simplified\n direction: 'ltr',\n canonicalOrder: [\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n 'action',\n ],\n },\n\n // Bantu (Swahili)\n bantu: {\n wordOrder: 'SVO',\n adpositionType: 'preposition',\n morphology: 'agglutinative',\n direction: 'ltr',\n canonicalOrder: [\n 'action',\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n ],\n },\n};\n\n// =============================================================================\n// Transformation Utilities\n// =============================================================================\n\n/**\n * Reorder semantic roles according to target language.\n * Includes a safety net to append any roles present in input\n * but missing from the target order, preventing data loss.\n */\nexport function reorderRoles(\n roles: Map<SemanticRole, ParsedElement>,\n targetOrder: SemanticRole[]\n): ParsedElement[] {\n const result: ParsedElement[] = [];\n const usedRoles = new Set<SemanticRole>();\n\n // 1. Add roles that are explicitly in the canonical order\n for (const role of targetOrder) {\n const element = roles.get(role);\n if (element) {\n result.push(element);\n usedRoles.add(role);\n }\n }\n\n // 2. Safety Net: Append any roles present in input but missing from target order\n // This prevents data loss (e.g., if 'manner' or 'instrument' isn't in the profile)\n for (const [role, element] of roles) {\n if (!usedRoles.has(role)) {\n result.push(element);\n }\n }\n\n return result;\n}\n\n/**\n * Insert grammatical markers between elements\n */\nexport function insertMarkers(\n elements: ParsedElement[],\n markers: GrammaticalMarker[],\n adpositionType: AdpositionType\n): string[] {\n const result: string[] = [];\n\n for (const element of elements) {\n const marker = markers.find(m => m.role === element.role);\n\n if (marker) {\n if (adpositionType === 'preposition') {\n // Marker before element: \"to element\"\n if (marker.form) result.push(marker.form);\n result.push(element.translated || element.value);\n } else if (adpositionType === 'postposition') {\n // Marker after element: \"element を\"\n result.push(element.translated || element.value);\n if (marker.form) result.push(marker.form);\n } else {\n result.push(element.translated || element.value);\n }\n } else {\n result.push(element.translated || element.value);\n }\n }\n\n return result;\n}\n\n/**\n * Intelligently joins tokens, handling agglutinative suffixes and prefixes.\n *\n * Rules:\n * 1. If a token ends with '-' (prefix marker), no space after it\n * 2. If a token starts with '-' (suffix marker), no space before it\n * 3. Removes the hyphen indicators from the final output\n *\n * Examples:\n * - ['#count', '-ta'] → '#countta' (Quechua accusative suffix)\n * - ['بـ-', 'الماوس'] → 'بـالماوس' (Arabic prefix attachment)\n * - ['value', 'を'] → 'value を' (Japanese particle, normal spacing)\n */\nexport function joinTokens(tokens: string[]): string {\n if (tokens.length === 0) return '';\n\n let result = '';\n\n for (let i = 0; i < tokens.length; i++) {\n const token = tokens[i];\n const nextToken = tokens[i + 1];\n\n // Check if current token is a prefix (ends with -)\n const isPrefix = token.endsWith('-');\n // Check if current token is a suffix (starts with -)\n const isSuffix = token.startsWith('-');\n\n // Get the display form (strip hyphen markers)\n let displayToken = token;\n if (isPrefix) displayToken = token.slice(0, -1);\n if (isSuffix) displayToken = token.substring(1);\n\n result += displayToken;\n\n // Determine if we need a space before the next token\n if (nextToken) {\n const nextIsSuffix = nextToken.startsWith('-');\n\n // Don't add space if:\n // - Current token is a prefix (ends with -)\n // - Next token is a suffix (starts with -)\n if (!isPrefix && !nextIsSuffix) {\n result += ' ';\n }\n }\n }\n\n return result;\n}\n\n/**\n * Transform a parsed statement to target language\n */\nexport function transformStatement(\n parsed: ParsedStatement,\n _sourceProfile: LanguageProfile,\n targetProfile: LanguageProfile\n): string {\n // 1. Reorder roles for target language\n const reordered = reorderRoles(parsed.roles, targetProfile.canonicalOrder);\n\n // 2. Insert grammatical markers\n const withMarkers = insertMarkers(reordered, targetProfile.markers, targetProfile.adpositionType);\n\n // 3. Join with intelligent spacing for agglutinative languages\n // (handles suffixes like -ta, prefixes like بـ-, etc.)\n return joinTokens(withMarkers);\n}\n","/**\n * Grammar Transformer - Dependency Injection Architecture\n *\n * Transforms statements between languages using injected dependencies.\n * This makes the transformer completely domain-agnostic.\n */\n\nimport type { LanguageProfile, ParsedElement, SemanticRole } from './types';\nimport { reorderRoles, insertMarkers, joinTokens } from './types';\nimport type { Dictionary } from '../interfaces/dictionary';\nimport type { ProfileProvider } from '../interfaces/profile-provider';\n\n/**\n * Configuration for grammar transformer.\n */\nexport interface TransformerConfig {\n /** Dictionary for keyword translation */\n readonly dictionary: Dictionary;\n\n /** Profile provider for grammar rules */\n readonly profileProvider: ProfileProvider;\n}\n\n/**\n * Generic grammar transformer using dependency injection.\n *\n * @example\n * const transformer = new GrammarTransformer({\n * dictionary: new InMemoryDictionary(translations),\n * profileProvider: new InMemoryProfileProvider(profiles)\n * });\n *\n * const japanese = transformer.transform('select name from users', 'en', 'ja');\n * // → \"users から name を 選択\"\n */\nexport class GrammarTransformer {\n private dictionary: Dictionary;\n private profileProvider: ProfileProvider;\n\n constructor(config: TransformerConfig) {\n this.dictionary = config.dictionary;\n this.profileProvider = config.profileProvider;\n }\n\n /**\n * Transform a statement from one language to another.\n *\n * @param input - Statement in source language\n * @param fromLanguage - Source language code\n * @param toLanguage - Target language code\n * @returns Transformed statement in target language\n *\n * @throws Error if profiles not found or translation fails\n */\n transform(input: string, fromLanguage: string, toLanguage: string): string {\n // Get language profiles\n const fromProfile = this.profileProvider.getProfile(fromLanguage);\n const toProfile = this.profileProvider.getProfile(toLanguage);\n\n if (!fromProfile) {\n throw new Error(`No profile found for language: ${fromLanguage}`);\n }\n if (!toProfile) {\n throw new Error(`No profile found for language: ${toLanguage}`);\n }\n\n // Parse statement to semantic roles\n const parsed = this.parseStatement(input, fromLanguage, fromProfile);\n\n // Translate each word\n const translated = this.translateRoles(parsed, fromLanguage, toLanguage);\n\n // Reorder and insert markers\n const reordered = reorderRoles(translated, toProfile.canonicalOrder);\n\n const withMarkers = insertMarkers(reordered, toProfile.markers, toProfile.adpositionType);\n\n return joinTokens(withMarkers);\n }\n\n /**\n * Parse statement into semantic roles.\n * This is a simplified generic parser - DSLs can provide custom parsers.\n */\n private parseStatement(\n input: string,\n language: string,\n profile: LanguageProfile\n ): Map<SemanticRole, string> {\n const roles = new Map<SemanticRole, string>();\n const tokens = input.split(/\\s+/);\n\n // Simple parsing: extract roles based on markers\n let i = 0;\n while (i < tokens.length) {\n const token = tokens[i];\n\n // Check if token is a marker\n const marker = profile.markers.find(m => m.form === token);\n\n if (marker) {\n // Next token is the value for this role\n if (i + 1 < tokens.length) {\n roles.set(marker.role, tokens[i + 1]);\n i += 2;\n } else {\n i++;\n }\n } else {\n // Look up token in dictionary to find its role\n const canonical = this.dictionary.lookup(token, language);\n\n if (canonical) {\n // Assume it's the action (command keyword)\n roles.set('action', canonical);\n } else {\n // Assume it's a value (selector, identifier, etc.)\n // Try to guess the role based on syntax\n if (token.startsWith('#') || token.startsWith('.')) {\n roles.set('patient', token);\n } else {\n // Default to patient for unknown values\n roles.set('patient', token);\n }\n }\n\n i++;\n }\n }\n\n return roles;\n }\n\n /**\n * Translate roles using injected dictionary.\n * Returns a Map of ParsedElement objects expected by reorderRoles.\n */\n private translateRoles(\n roles: Map<SemanticRole, string>,\n _fromLanguage: string,\n toLanguage: string\n ): Map<SemanticRole, ParsedElement> {\n const result = new Map<SemanticRole, ParsedElement>();\n\n for (const [role, value] of roles) {\n // Translate using dictionary\n const translated = this.dictionary.translate(value, toLanguage);\n\n // Create ParsedElement with role, value, and translated\n result.set(role, {\n role,\n value, // Original value\n translated: translated ?? value, // Translated value or original if no translation\n });\n }\n\n return result;\n }\n}\n","/**\n * Dictionary Interface - Keyword Translation\n *\n * Provides keyword translations between languages.\n * DSLs implement this to provide their domain-specific translations.\n */\n\n/**\n * Dictionary provides keyword translations between languages.\n */\nexport interface Dictionary {\n /**\n * Look up canonical form from localized keyword.\n *\n * @param localizedWord - Word in target language (e.g., 'トグル', 'alternar')\n * @param language - Language code\n * @returns Canonical form (e.g., 'toggle') or undefined\n *\n * @example\n * dictionary.lookup('トグル', 'ja') // → 'toggle'\n * dictionary.lookup('alternar', 'es') // → 'toggle'\n */\n lookup(localizedWord: string, language: string): string | undefined;\n\n /**\n * Translate canonical keyword to target language.\n *\n * @param canonical - Canonical form (e.g., 'toggle')\n * @param targetLanguage - Target language code\n * @returns Localized form or undefined\n *\n * @example\n * dictionary.translate('toggle', 'ja') // → 'トグル'\n * dictionary.translate('toggle', 'es') // → 'alternar'\n */\n translate(canonical: string, targetLanguage: string): string | undefined;\n\n /**\n * Get all translations of a word across all supported languages.\n *\n * @param word - Word to translate\n * @param sourceLanguage - Source language\n * @returns Map of language code to translation\n *\n * @example\n * dictionary.getAllTranslations('toggle', 'en')\n * // → { ja: 'トグル', es: 'alternar', ko: '토글', ... }\n */\n getAllTranslations(word: string, sourceLanguage: string): Record<string, string>;\n\n /**\n * Optional: Find what category a word belongs to.\n * Useful for organizing translations by domain (commands, modifiers, events, etc.).\n */\n getCategory?(word: string, language: string): string | undefined;\n}\n\n/**\n * Simple in-memory dictionary implementation.\n * Suitable for small DSLs or prototyping.\n */\nexport class InMemoryDictionary implements Dictionary {\n /**\n * @param translations - Map of language code to canonical→localized mappings\n *\n * @example\n * new InMemoryDictionary({\n * en: { select: 'select', insert: 'insert' },\n * es: { select: 'seleccionar', insert: 'insertar' },\n * ja: { select: '選択', insert: '挿入' }\n * })\n */\n constructor(private translations: Record<string, Record<string, string>>) {}\n\n lookup(word: string, language: string): string | undefined {\n const langDict = this.translations[language];\n if (!langDict) return undefined;\n\n // Reverse lookup: find key where value = word\n const wordLower = word.toLowerCase();\n for (const [canonical, localized] of Object.entries(langDict)) {\n if (localized.toLowerCase() === wordLower) {\n return canonical;\n }\n }\n return undefined;\n }\n\n translate(canonical: string, targetLanguage: string): string | undefined {\n return this.translations[targetLanguage]?.[canonical];\n }\n\n getAllTranslations(word: string, sourceLanguage: string): Record<string, string> {\n const canonical = this.lookup(word, sourceLanguage);\n if (!canonical) return {};\n\n const result: Record<string, string> = {};\n for (const [lang, dict] of Object.entries(this.translations)) {\n const translation = dict[canonical];\n if (translation) {\n result[lang] = translation;\n }\n }\n return result;\n }\n}\n\n/**\n * Null dictionary - no translations (useful for single-language DSLs).\n */\nexport class NullDictionary implements Dictionary {\n lookup(word: string, _language: string): string | undefined {\n return word; // Identity: word is its own canonical form\n }\n\n translate(canonical: string, _targetLanguage: string): string | undefined {\n return canonical; // Identity: no translation\n }\n\n getAllTranslations(word: string, _sourceLanguage: string): Record<string, string> {\n return { en: word }; // Only source language\n }\n}\n","/**\n * Profile Provider Interface - Language Profile Access\n *\n * Provides language profiles for grammar transformation.\n * DSLs implement this to provide their domain-specific profiles.\n */\n\nimport type { LanguageProfile } from '../grammar';\n\n/**\n * Provides language profiles for transformation.\n */\nexport interface ProfileProvider {\n /**\n * Get language profile by code.\n *\n * @param language - ISO 639-1 code (e.g., 'en', 'ja', 'es')\n * @returns Language profile or undefined if not supported\n *\n * @example\n * const profile = provider.getProfile('ja');\n * console.log(profile.wordOrder); // 'SOV'\n */\n getProfile(language: string): LanguageProfile | undefined;\n\n /**\n * Get all supported language codes.\n *\n * @returns Array of ISO 639-1 codes\n *\n * @example\n * provider.getSupportedLanguages() // → ['en', 'ja', 'es', 'ko']\n */\n getSupportedLanguages(): string[];\n\n /**\n * Check if a language is supported.\n *\n * @param language - Language code to check\n * @returns True if language is supported\n */\n hasLanguage(language: string): boolean;\n}\n\n/**\n * Simple in-memory profile provider.\n */\nexport class InMemoryProfileProvider implements ProfileProvider {\n /**\n * @param profiles - Map of language code to profile\n *\n * @example\n * new InMemoryProfileProvider({\n * en: { code: 'en', wordOrder: 'SVO', ... },\n * ja: { code: 'ja', wordOrder: 'SOV', ... }\n * })\n */\n constructor(private profiles: Record<string, LanguageProfile>) {}\n\n getProfile(language: string): LanguageProfile | undefined {\n return this.profiles[language];\n }\n\n getSupportedLanguages(): string[] {\n return Object.keys(this.profiles);\n }\n\n hasLanguage(language: string): boolean {\n return language in this.profiles;\n }\n}\n\n/**\n * Null profile provider - for DSLs that don't need grammar transformation.\n */\nexport class NullProfileProvider implements ProfileProvider {\n getProfile(_language: string): LanguageProfile | undefined {\n return undefined;\n }\n\n getSupportedLanguages(): string[] {\n return [];\n }\n\n hasLanguage(_language: string): boolean {\n return false;\n }\n}\n","/**\n * Explicit Syntax Parser — re-exported from @lokascript/intent\n */\n\nexport {\n STRUCTURAL_ROLES,\n parseExplicit,\n isExplicitSyntax,\n parseCompound,\n parseDocument,\n isCompoundSyntax,\n isDocumentSyntax,\n} from '@lokascript/intent';\n","/**\n * Explicit Syntax Renderer — re-exported from @lokascript/intent\n */\n\nexport { renderExplicit, renderDocument } from '@lokascript/intent';\n","/**\n * Main API for creating multilingual DSLs\n */\n\nimport type { SemanticNode, LanguageTokenizer, LanguagePattern } from '../core/types';\nimport type { CommandSchema } from '../schema';\nimport { PatternMatcher, type PatternMatcherProfile } from '../core/pattern-matching';\nimport { generatePattern, type PatternGenLanguageProfile } from '../generation/pattern-generator';\nimport { GrammarTransformer, type LanguageProfile as GrammarProfile } from '../grammar';\nimport {\n type Dictionary,\n type ProfileProvider,\n type ValueExtractor,\n InMemoryDictionary,\n InMemoryProfileProvider,\n} from '../interfaces';\nimport { isExplicitSyntax, parseExplicit } from '../ir';\nimport type { SchemaLookup } from '../ir';\n\n/**\n * Language configuration for a DSL.\n */\nexport interface LanguageConfig {\n /** ISO 639-1 language code */\n readonly code: string;\n /** English name of the language */\n readonly name: string;\n /** Native name of the language */\n readonly nativeName: string;\n /** Language tokenizer */\n readonly tokenizer: LanguageTokenizer;\n /** Language profile for pattern generation */\n readonly patternProfile: PatternGenLanguageProfile;\n /** Language profile for grammar transformation (optional) */\n readonly grammarProfile?: GrammarProfile;\n}\n\n/**\n * Code generator function that transforms semantic AST to target code.\n */\nexport interface CodeGenerator {\n generate(node: SemanticNode): string;\n}\n\n/**\n * DSL configuration with dependency injection support.\n */\nexport interface DSLConfig {\n /** DSL name (for debugging/documentation) */\n readonly name?: string;\n\n /** Command schemas defining the DSL grammar */\n readonly schemas: readonly CommandSchema[];\n\n /** Language configurations */\n readonly languages: readonly LanguageConfig[];\n\n // === Dependency Injection (Optional) ===\n\n /** Dictionary for keyword translation (default: built from language configs) */\n readonly dictionary?: Dictionary;\n\n /** Profile provider for grammar transformation (default: built from language configs) */\n readonly profileProvider?: ProfileProvider;\n\n /** Value extractors for tokenization (default: generic extractors) */\n readonly valueExtractors?: ValueExtractor[];\n\n /** Code generator for compilation (default: none) */\n readonly codeGenerator?: CodeGenerator;\n\n // === Options ===\n\n /** Auto-generate patterns from schemas (default: true) */\n readonly generatePatterns?: boolean;\n\n /** Custom patterns to supplement generated ones */\n readonly customPatterns?: LanguagePattern[];\n}\n\n/**\n * Validation result.\n */\nexport interface ValidationResult {\n readonly valid: boolean;\n readonly node?: SemanticNode;\n readonly errors?: string[];\n}\n\n/**\n * Compilation result.\n */\nexport interface CompileResult {\n readonly ok: boolean;\n readonly code?: string;\n readonly errors?: string[];\n readonly node?: SemanticNode;\n readonly metadata?: {\n readonly parser: string;\n readonly confidence: number;\n };\n}\n\n/**\n * Main multilingual DSL interface.\n */\nexport interface MultilingualDSL {\n // Parsing\n parse(input: string, language: string): SemanticNode;\n parseWithConfidence(input: string, language: string): { node: SemanticNode; confidence: number };\n\n // Validation\n validate(input: string, language: string): ValidationResult;\n\n // Compilation\n compile(input: string, language: string): CompileResult;\n\n // Translation\n translate(input: string, fromLanguage: string, toLanguage: string): string;\n\n // Language support\n getSupportedLanguages(): string[];\n}\n\n/**\n * Internal registry for DSL configuration.\n */\nclass DSLRegistry {\n private patterns = new Map<string, LanguagePattern[]>();\n private tokenizers = new Map<string, LanguageTokenizer>();\n private schemas: readonly CommandSchema[];\n\n constructor(config: DSLConfig) {\n this.schemas = config.schemas;\n\n // Register each language\n for (const lang of config.languages) {\n this.registerLanguage(lang);\n }\n }\n\n private registerLanguage(lang: LanguageConfig): void {\n // Register tokenizer\n this.tokenizers.set(lang.code, lang.tokenizer);\n\n // Generate patterns for this language\n const patterns: LanguagePattern[] = [];\n for (const schema of this.schemas) {\n const pattern = generatePattern(schema, lang.patternProfile);\n patterns.push(pattern);\n }\n\n this.patterns.set(lang.code, patterns);\n }\n\n getPatterns(language: string): LanguagePattern[] {\n return this.patterns.get(language) || [];\n }\n\n getTokenizer(language: string): LanguageTokenizer | undefined {\n return this.tokenizers.get(language);\n }\n\n getSupportedLanguages(): string[] {\n return Array.from(this.patterns.keys());\n }\n}\n\n/**\n * Implementation of MultilingualDSL.\n */\nclass MultilingualDSLImpl implements MultilingualDSL {\n private registry: DSLRegistry;\n private matcher: PatternMatcher;\n private transformer: GrammarTransformer;\n private codeGenerator?: CodeGenerator;\n private schemaLookup: SchemaLookup;\n\n constructor(config: DSLConfig, registry: DSLRegistry, transformer: GrammarTransformer) {\n this.registry = registry;\n this.matcher = new PatternMatcher();\n this.transformer = transformer;\n if (config.codeGenerator) {\n this.codeGenerator = config.codeGenerator;\n }\n\n // Build SchemaLookup from config schemas for explicit syntax validation\n const schemaMap = new Map(config.schemas.map(s => [s.action, s]));\n this.schemaLookup = {\n getSchema: (action: string) => schemaMap.get(action),\n };\n }\n\n parse(input: string, language: string): SemanticNode {\n const result = this.parseWithConfidence(input, language);\n return result.node;\n }\n\n parseWithConfidence(input: string, language: string): { node: SemanticNode; confidence: number } {\n // Try explicit bracket syntax first (language-agnostic)\n if (isExplicitSyntax(input)) {\n const node = parseExplicit(input, { schemaLookup: this.schemaLookup });\n // Only match if this DSL has a schema for the action\n if (!this.schemaLookup.getSchema(node.action)) {\n throw new Error(`No schema for action \"${node.action}\" in this DSL`);\n }\n return { node, confidence: 1.0 };\n }\n\n // Get tokenizer for language\n const tokenizer = this.registry.getTokenizer(language);\n if (!tokenizer) {\n throw new Error(`No tokenizer registered for language: ${language}`);\n }\n\n // Tokenize input\n const tokens = tokenizer.tokenize(input);\n\n // Get patterns for language\n const patterns = this.registry.getPatterns(language);\n\n // Create profile for matcher\n const profile: PatternMatcherProfile = {\n code: language,\n };\n\n // Try to match each pattern\n for (const pattern of patterns) {\n const match = this.matcher.matchPattern(tokens, pattern, profile);\n if (match) {\n // Build semantic node\n const node: SemanticNode = {\n kind: 'command',\n action: pattern.command,\n roles: match.captured,\n metadata: {\n sourceLanguage: language,\n sourceText: input,\n patternId: pattern.id,\n confidence: match.confidence,\n },\n };\n\n return { node, confidence: match.confidence };\n }\n }\n\n throw new Error(`No pattern matched for input: ${input}`);\n }\n\n validate(input: string, language: string): ValidationResult {\n try {\n const result = this.parseWithConfidence(input, language);\n return {\n valid: true,\n node: result.node,\n };\n } catch (error) {\n return {\n valid: false,\n errors: [error instanceof Error ? error.message : String(error)],\n };\n }\n }\n\n translate(input: string, fromLanguage: string, toLanguage: string): string {\n // Explicit syntax is language-agnostic — return unchanged\n if (isExplicitSyntax(input)) return input;\n // Use injected grammar transformer\n return this.transformer.transform(input, fromLanguage, toLanguage);\n }\n\n compile(input: string, language: string): CompileResult {\n if (!this.codeGenerator) {\n return {\n ok: false,\n errors: ['No code generator configured for this DSL'],\n };\n }\n\n try {\n const result = this.parseWithConfidence(input, language);\n const code = this.codeGenerator.generate(result.node);\n\n return {\n ok: true,\n code,\n node: result.node,\n metadata: {\n parser: 'semantic',\n confidence: result.confidence,\n },\n };\n } catch (error) {\n return {\n ok: false,\n errors: [error instanceof Error ? error.message : String(error)],\n };\n }\n }\n\n getSupportedLanguages(): string[] {\n return this.registry.getSupportedLanguages();\n }\n}\n\n/**\n * Create a new multilingual DSL instance.\n *\n * @param config - DSL configuration\n * @returns MultilingualDSL instance\n *\n * @example\n * ```typescript\n * const myDSL = createMultilingualDSL({\n * schemas: [\n * defineCommand('select', [\n * defineRole('field', 'identifier', true),\n * defineRole('source', 'identifier', true),\n * ]),\n * ],\n * languages: [\n * {\n * code: 'en',\n * name: 'English',\n * nativeName: 'English',\n * tokenizer: englishTokenizer,\n * patternProfile: englishProfile,\n * },\n * ],\n * codeGenerator: {\n * generate: (node) => generateSQL(node),\n * },\n * });\n *\n * const result = myDSL.compile('select name from users', 'en');\n * ```\n */\n/**\n * Create default dictionary from language configurations.\n */\nfunction createDefaultDictionary(config: DSLConfig): Dictionary {\n const translations: Record<string, Record<string, string>> = {};\n\n for (const lang of config.languages) {\n // Convert keyword objects to simple string mappings\n const keywords: Record<string, string> = {};\n for (const [canonical, keywordDef] of Object.entries(lang.patternProfile.keywords)) {\n keywords[canonical] = keywordDef.primary;\n }\n translations[lang.code] = keywords;\n }\n\n return new InMemoryDictionary(translations);\n}\n\n/**\n * Create default profile provider from language configurations.\n */\nfunction createDefaultProfileProvider(config: DSLConfig): ProfileProvider {\n const profiles: Record<string, GrammarProfile> = {};\n\n for (const lang of config.languages) {\n if (lang.grammarProfile) {\n profiles[lang.code] = lang.grammarProfile;\n }\n }\n\n return new InMemoryProfileProvider(profiles);\n}\n\nexport function createMultilingualDSL(config: DSLConfig): MultilingualDSL {\n // Create or use provided dictionary\n const dictionary = config.dictionary ?? createDefaultDictionary(config);\n\n // Create or use provided profile provider\n const profileProvider = config.profileProvider ?? createDefaultProfileProvider(config);\n\n // Create grammar transformer with injected dependencies\n const transformer = new GrammarTransformer({\n dictionary,\n profileProvider,\n });\n\n // Create registry and implementation\n const registry = new DSLRegistry(config);\n return new MultilingualDSLImpl(config, registry, transformer);\n}\n","/**\n * LLM Prompt Generator\n *\n * Auto-generates LLM system prompts from CommandSchema[]. Given a set of\n * domain schemas, produces a structured markdown prompt that teaches LLMs\n * to output valid LSE bracket syntax and/or LLM-simplified JSON.\n *\n * The generated prompt includes:\n * - Protocol overview (LSE syntax summary)\n * - Value type reference\n * - Per-command documentation with role descriptions\n * - Synthetic examples in both formats\n * - Output format specification\n * - Error recovery instructions\n */\n\nimport type { CommandSchema, RoleSpec } from '../schema/command-schema';\nimport type { SemanticJSON, SemanticJSONValue } from '../ir/types';\nimport { renderExplicit } from '../ir/explicit-renderer';\nimport { createCommandNode } from '../core/types';\nimport type {\n PromptGeneratorConfig,\n GeneratedPrompt,\n PromptSection,\n PromptMetadata,\n} from './types';\n\n// =============================================================================\n// Public API\n// =============================================================================\n\n/**\n * Generate an LLM system prompt from domain command schemas.\n *\n * @example\n * ```typescript\n * import { generatePrompt } from '@lokascript/framework';\n * import { allSchemas } from '@lokascript/domain-flow';\n *\n * const prompt = generatePrompt({\n * domain: 'flow',\n * description: 'Reactive data flow pipelines',\n * schemas: allSchemas,\n * });\n *\n * console.log(prompt.text); // Full markdown system prompt\n * ```\n */\nexport function generatePrompt(config: PromptGeneratorConfig): GeneratedPrompt {\n const outputFormat = config.outputFormat ?? 'both';\n const examplesPerCommand = config.examplesPerCommand ?? 2;\n\n const sections: PromptSection[] = [\n buildProtocolSection(),\n buildValueTypeSection(),\n buildCommandsSection(config.schemas, outputFormat, examplesPerCommand),\n buildOutputFormatSection(outputFormat),\n buildErrorRecoverySection(),\n ];\n\n // Apply token budget if specified\n let finalSections = sections;\n if (config.maxTokens && config.maxTokens > 0) {\n finalSections = truncateToTokenBudget(sections, config.maxTokens);\n }\n\n const text = finalSections.map(s => `## ${s.title}\\n\\n${s.content}`).join('\\n\\n---\\n\\n');\n\n const totalRoles = config.schemas.reduce((sum, s) => sum + s.roles.length, 0);\n const approximateTokens = estimateTokens(text);\n\n const metadata: PromptMetadata = {\n domain: config.domain,\n commandCount: config.schemas.length,\n roleCount: totalRoles,\n approximateTokens,\n };\n\n return { text, sections: finalSections, metadata };\n}\n\n/**\n * Generate synthetic LSE examples from a single command schema.\n * Used by both the prompt generator and training data synthesizer.\n */\nexport function generateExamples(\n schema: CommandSchema,\n count: number = 2\n): Array<{ explicit: string; json: SemanticJSON }> {\n const combos = generateRoleCombinations(schema);\n const examples: Array<{ explicit: string; json: SemanticJSON }> = [];\n\n for (let i = 0; i < Math.min(count, combos.length); i++) {\n const combo = combos[i];\n const roles = new Map<string, { type: string; value: string | number | boolean }>();\n\n for (const role of combo) {\n const sample = sampleValue(role);\n roles.set(role.role, sample);\n }\n\n // Build SemanticNode for rendering to bracket syntax\n const nodeRoles = new Map<\n string,\n {\n type: string;\n value: string | number | boolean;\n raw?: string;\n dataType?: string;\n selectorKind?: string;\n }\n >();\n for (const [roleName, sample] of roles) {\n nodeRoles.set(roleName, toSemanticValue(sample));\n }\n\n const node = createCommandNode(schema.action, nodeRoles as never);\n const explicit = renderExplicit(node);\n\n // Build JSON format\n const jsonRoles: Record<string, SemanticJSONValue> = {};\n for (const [roleName, sample] of roles) {\n jsonRoles[roleName] = sample as SemanticJSONValue;\n }\n const json: SemanticJSON = { action: schema.action, roles: jsonRoles };\n\n examples.push({ explicit, json });\n }\n\n return examples;\n}\n\n/**\n * Generate a condensed LSE protocol reference (for MCP resources).\n */\nexport function generateProtocolReference(): string {\n const protocol = buildProtocolSection();\n const valueTypes = buildValueTypeSection();\n return `# LokaScript Explicit Syntax (LSE) Quick Reference\\n\\n${protocol.content}\\n\\n${valueTypes.content}`;\n}\n\n// =============================================================================\n// Section Builders\n// =============================================================================\n\nfunction buildProtocolSection(): PromptSection {\n const content = `LokaScript Explicit Syntax (LSE) is a bracket-based format for imperative commands.\n\n### Syntax\n\n\\`\\`\\`\n[command role1:value1 role2:value2 +flag1 ~flag2]\n\\`\\`\\`\n\n- **Command**: The first token inside brackets (lowercased)\n- **Role pair**: \\`name:value\\` — a named semantic role with a typed value (no space around colon)\n- **Enabled flag**: \\`+name\\` — boolean attribute present\n- **Disabled flag**: \\`~name\\` — boolean attribute negated\n- **Nested body**: \\`body:[command ...]\\` — a bracket command inside a role value\n\n### Rules\n\n1. Commands are always lowercased\n2. Role names preserve their original case\n3. No spaces around the colon in role:value pairs\n4. Strings with spaces must be quoted: \\`patient:\"hello world\"\\`\n5. Selectors start with \\`#\\`, \\`.\\`, \\`[\\`, \\`@\\`, or \\`*\\`\n6. Output must be valid bracket syntax: \\`[action role:value ...]\\``;\n\n return {\n id: 'protocol',\n title: 'LSE Protocol',\n content,\n approximateTokens: estimateTokens(content),\n };\n}\n\nfunction buildValueTypeSection(): PromptSection {\n const content = `Values in LSE are classified by their syntactic form (first match wins):\n\n| Type | Syntax | Example |\n|------|--------|---------|\n| Selector | Starts with \\`#\\` \\`.\\` \\`[\\` \\`@\\` \\`*\\` | \\`#button\\`, \\`.active\\`, \\`[data-id]\\` |\n| String | Quoted with \\`\"\\` or \\`'\\` | \\`\"hello world\"\\`, \\`'json'\\` |\n| Boolean | Exact: \\`true\\` / \\`false\\` | \\`visible:true\\` |\n| Reference | Built-in name | \\`me\\`, \\`you\\`, \\`it\\`, \\`result\\`, \\`event\\`, \\`target\\`, \\`body\\` |\n| Duration | Number + suffix | \\`500ms\\`, \\`2s\\`, \\`1m\\`, \\`1h\\` |\n| Number | Digits with optional decimal | \\`5\\`, \\`3.14\\`, \\`-1\\` |\n| Plain | Fallback (any non-whitespace) | \\`/api/users\\`, \\`json\\`, \\`production\\` |\n\n**Important**: Classification is by prefix, not by intent. \\`#true\\` is a selector (not boolean). \\`event\\` as a value is a reference (not plain text).`;\n\n return {\n id: 'value-types',\n title: 'Value Types',\n content,\n approximateTokens: estimateTokens(content),\n };\n}\n\nfunction buildCommandsSection(\n schemas: readonly CommandSchema[],\n outputFormat: 'explicit' | 'json' | 'both',\n examplesPerCommand: number\n): PromptSection {\n const parts: string[] = [];\n\n for (const schema of schemas) {\n parts.push(formatCommandDoc(schema, outputFormat, examplesPerCommand));\n }\n\n const content = parts.join('\\n\\n');\n\n return {\n id: 'commands',\n title: 'Available Commands',\n content,\n approximateTokens: estimateTokens(content),\n };\n}\n\nfunction buildOutputFormatSection(outputFormat: 'explicit' | 'json' | 'both'): PromptSection {\n let content: string;\n\n if (outputFormat === 'explicit') {\n content = `Output valid LSE bracket syntax. Each command must be wrapped in brackets:\n\n\\`\\`\\`\n[command role:value ...]\n\\`\\`\\`\n\nDo NOT output JSON. Only use bracket syntax.`;\n } else if (outputFormat === 'json') {\n content = `Output valid JSON in the LLM-simplified format:\n\n\\`\\`\\`json\n{\n \"action\": \"command-name\",\n \"roles\": {\n \"roleName\": { \"type\": \"valueType\", \"value\": \"theValue\" }\n }\n}\n\\`\\`\\`\n\nValid value types: \\`selector\\`, \\`literal\\`, \\`reference\\`, \\`expression\\`.\nDo NOT output bracket syntax. Only use JSON.`;\n } else {\n content = `You may output EITHER format:\n\n**Bracket syntax** (preferred for single commands):\n\\`\\`\\`\n[command role:value ...]\n\\`\\`\\`\n\n**JSON format** (preferred when structured data is needed):\n\\`\\`\\`json\n{\n \"action\": \"command-name\",\n \"roles\": {\n \"roleName\": { \"type\": \"valueType\", \"value\": \"theValue\" }\n }\n}\n\\`\\`\\`\n\nBoth formats are equally valid. Use whichever is more natural for the context.`;\n }\n\n return {\n id: 'output-format',\n title: 'Output Format',\n content,\n approximateTokens: estimateTokens(content),\n };\n}\n\nfunction buildErrorRecoverySection(): PromptSection {\n const content = `If you're unsure about a command or role:\n\n1. **Unknown command**: Use the closest matching command from the Available Commands section. Do not invent commands.\n2. **Unknown role**: Use only the roles listed for each command. Do not add roles not in the schema.\n3. **Ambiguous value type**: When in doubt, use \\`expression\\` type (it's the most permissive).\n4. **Missing required role**: Always include all required roles. Check the Required/Optional labels.\n5. **Selector vs plain value**: If a value starts with \\`#\\`, \\`.\\`, \\`[\\`, \\`@\\`, or \\`*\\`, it's a selector. URLs like \\`/api/data\\` are plain values.\n\nWhen generating LSE, prefer explicit role labeling over positional guessing. Every value should have a role name.`;\n\n return {\n id: 'error-recovery',\n title: 'Error Recovery',\n content,\n approximateTokens: estimateTokens(content),\n };\n}\n\n// =============================================================================\n// Command Documentation\n// =============================================================================\n\nfunction formatCommandDoc(\n schema: CommandSchema,\n outputFormat: 'explicit' | 'json' | 'both',\n examplesPerCommand: number\n): string {\n const lines: string[] = [];\n\n // Header\n lines.push(`### \\`${schema.action}\\` — ${schema.description}`);\n lines.push('');\n\n // Roles\n const required = schema.roles.filter(r => r.required);\n const optional = schema.roles.filter(r => !r.required);\n\n if (required.length > 0) {\n lines.push('**Required roles:**');\n for (const role of required) {\n lines.push(`- \\`${role.role}\\`: ${role.description} (type: ${formatExpectedTypes(role)})`);\n }\n }\n\n if (optional.length > 0) {\n lines.push('**Optional roles:**');\n for (const role of optional) {\n lines.push(`- \\`${role.role}\\`: ${role.description} (type: ${formatExpectedTypes(role)})`);\n }\n }\n\n // Examples\n const examples = generateExamples(schema, examplesPerCommand);\n if (examples.length > 0) {\n lines.push('');\n if (outputFormat === 'explicit' || outputFormat === 'both') {\n lines.push('**Bracket syntax:**');\n for (const ex of examples) {\n lines.push(`\\`\\`\\`\\n${ex.explicit}\\n\\`\\`\\``);\n }\n }\n if (outputFormat === 'json' || outputFormat === 'both') {\n lines.push('**JSON format:**');\n for (const ex of examples) {\n lines.push(`\\`\\`\\`json\\n${JSON.stringify(ex.json, null, 2)}\\n\\`\\`\\``);\n }\n }\n }\n\n return lines.join('\\n');\n}\n\nfunction formatExpectedTypes(role: RoleSpec): string {\n return role.expectedTypes.join(' | ');\n}\n\n// =============================================================================\n// Example Generation Helpers\n// =============================================================================\n\n/**\n * Generate role combinations for example synthesis.\n * Returns arrays of RoleSpec[] representing different valid input combinations:\n * 1. Required roles only\n * 2. Required + each optional role individually\n * 3. Required + all optional roles (if different from #1 and #2)\n */\nfunction generateRoleCombinations(schema: CommandSchema): RoleSpec[][] {\n const required = schema.roles.filter(r => r.required);\n const optional = schema.roles.filter(r => !r.required);\n\n const combos: RoleSpec[][] = [];\n\n // 1. Required only\n if (required.length > 0) {\n combos.push(required);\n }\n\n // 2. Required + each optional individually\n for (const opt of optional) {\n combos.push([...required, opt]);\n }\n\n // 3. Required + all optional (if there are 2+ optional roles)\n if (optional.length >= 2) {\n combos.push([...required, ...optional]);\n }\n\n // Fallback: if schema has no required roles, use all roles\n if (combos.length === 0) {\n combos.push(schema.roles.slice());\n }\n\n return combos;\n}\n\n/**\n * Sample a value for a role based on its expected types and name.\n */\nfunction sampleValue(role: RoleSpec): { type: string; value: string | number | boolean } {\n const primaryType = role.expectedTypes[0] || 'expression';\n\n // Use role name as a heuristic for realistic values\n switch (primaryType) {\n case 'selector':\n return sampleSelector(role.role);\n case 'literal':\n return sampleLiteral(role.role);\n case 'reference':\n return { type: 'reference', value: 'me' };\n case 'expression':\n return sampleExpression(role.role);\n case 'flag':\n return { type: 'flag', value: true };\n default:\n return { type: 'literal', value: 'example' };\n }\n}\n\nfunction sampleSelector(roleName: string): { type: string; value: string } {\n const selectors: Record<string, string> = {\n patient: '.active',\n destination: '#output',\n source: '#input',\n target: '#target',\n };\n return { type: 'selector', value: selectors[roleName] || `#${roleName}` };\n}\n\nfunction sampleLiteral(roleName: string): { type: string; value: string | number } {\n const literals: Record<string, string | number> = {\n duration: '30s',\n interval: '5s',\n delay: '500ms',\n timeout: '10s',\n quantity: 5,\n limit: 10,\n style: 'json',\n manner: 'rolling',\n format: 'html',\n };\n return { type: 'literal', value: literals[roleName] || roleName };\n}\n\nfunction sampleExpression(roleName: string): { type: string; value: string } {\n const expressions: Record<string, string> = {\n source: '/api/data',\n destination: '#output',\n patient: '.active',\n instrument: 'toUpperCase',\n condition: 'age > 18',\n style: 'json',\n duration: '5s',\n url: '/api/users',\n };\n return { type: 'expression', value: expressions[roleName] || `/api/${roleName}` };\n}\n\n/**\n * Convert a sampled value into a SemanticValue for renderExplicit().\n */\nfunction toSemanticValue(sample: { type: string; value: string | number | boolean }): {\n type: string;\n value: string | number | boolean;\n raw?: string;\n dataType?: string;\n selectorKind?: string;\n} {\n switch (sample.type) {\n case 'selector':\n return {\n type: 'selector',\n value: String(sample.value),\n selectorKind: detectSelectorKind(String(sample.value)),\n };\n case 'literal':\n return {\n type: 'literal',\n value: sample.value,\n dataType:\n typeof sample.value === 'number'\n ? 'number'\n : typeof sample.value === 'boolean'\n ? 'boolean'\n : 'string',\n };\n case 'reference':\n return { type: 'reference', value: String(sample.value) };\n case 'expression':\n return { type: 'expression', value: String(sample.value), raw: String(sample.value) };\n case 'flag':\n return { type: 'flag', value: sample.value };\n default:\n return { type: 'literal', value: String(sample.value), dataType: 'string' };\n }\n}\n\nfunction detectSelectorKind(selector: string): string {\n if (selector.startsWith('#')) return 'id';\n if (selector.startsWith('.')) return 'class';\n if (selector.startsWith('[')) return 'attribute';\n return 'complex';\n}\n\n// =============================================================================\n// Token Budget\n// =============================================================================\n\nfunction estimateTokens(text: string): number {\n return Math.ceil(text.length / 4);\n}\n\nfunction truncateToTokenBudget(sections: PromptSection[], maxTokens: number): PromptSection[] {\n const result: PromptSection[] = [];\n let budget = maxTokens;\n\n for (const section of sections) {\n if (section.approximateTokens <= budget) {\n result.push(section);\n budget -= section.approximateTokens;\n } else {\n // Truncate the section to fit remaining budget (always include at least something)\n const charBudget = Math.max(budget * 4, 40);\n const truncatedContent = section.content.slice(0, charBudget) + '\\n\\n*(truncated)*';\n result.push({\n ...section,\n content: truncatedContent,\n approximateTokens: estimateTokens(truncatedContent),\n });\n break;\n }\n }\n\n return result;\n}\n","/**\n * Schema Synthesizer\n *\n * Generates synthetic (natural_language, LSE) training pairs from\n * CommandSchema[]. Enumerates valid role combinations and produces\n * examples in both bracket syntax and JSON wire format.\n */\n\nimport type { CommandSchema, RoleSpec } from '../schema/command-schema';\nimport type { SemanticJSON, SemanticJSONValue } from '../ir/types';\nimport { renderExplicit } from '../ir/explicit-renderer';\nimport { createCommandNode } from '../core/types';\nimport type { TrainingPair, SynthesisConfig, SynthesisResult, SynthesisMetadata } from './types';\n\n// =============================================================================\n// Public API\n// =============================================================================\n\n/**\n * Synthesize training pairs from command schemas.\n *\n * Generates multiple examples per command by enumerating role combinations:\n * 1. Required roles only (minimum viable)\n * 2. Required + each optional role individually\n * 3. Required + all optional roles (maximum)\n * 4. Shuffled role order variants (teaches role-label independence)\n */\nexport function synthesizeFromSchemas(\n schemas: readonly CommandSchema[],\n config: SynthesisConfig\n): SynthesisResult {\n const maxPerCommand = config.maxPairsPerCommand ?? 5;\n const minQuality = config.minQuality ?? 0.5;\n const shuffleRoles = config.shuffleRoles ?? true;\n const languages = config.languages ?? ['en'];\n\n const pairs: TrainingPair[] = [];\n let idCounter = 0;\n\n for (const schema of schemas) {\n const combos = generateRoleCombinations(schema);\n\n for (const language of languages) {\n let commandPairCount = 0;\n\n for (const combo of combos) {\n if (commandPairCount >= maxPerCommand) break;\n\n const pair = buildTrainingPair(\n schema,\n combo,\n language,\n config.domain,\n `${config.domain}-synth-${idCounter++}`\n );\n\n if (pair.quality >= minQuality) {\n pairs.push(pair);\n commandPairCount++;\n }\n\n // Generate shuffled variant\n if (shuffleRoles && combo.length >= 2 && commandPairCount < maxPerCommand) {\n const shuffled = [...combo].reverse();\n const shuffledPair = buildTrainingPair(\n schema,\n shuffled,\n language,\n config.domain,\n `${config.domain}-synth-${idCounter++}`\n );\n if (shuffledPair.quality >= minQuality) {\n pairs.push(shuffledPair);\n commandPairCount++;\n }\n }\n }\n }\n }\n\n const metadata: SynthesisMetadata = {\n domain: config.domain,\n commandCount: schemas.length,\n pairCount: pairs.length,\n bySource: { synthetic: pairs.length },\n languages,\n };\n\n return { pairs, metadata };\n}\n\n// =============================================================================\n// Role Combination Generation\n// =============================================================================\n\nfunction generateRoleCombinations(schema: CommandSchema): RoleSpec[][] {\n const required = schema.roles.filter(r => r.required);\n const optional = schema.roles.filter(r => !r.required);\n\n const combos: RoleSpec[][] = [];\n\n // 1. Required only\n if (required.length > 0) {\n combos.push(required);\n }\n\n // 2. Required + each optional individually\n for (const opt of optional) {\n combos.push([...required, opt]);\n }\n\n // 3. Required + all optional (if 2+ optional)\n if (optional.length >= 2) {\n combos.push([...required, ...optional]);\n }\n\n // Fallback: if no required roles, use all roles\n if (combos.length === 0) {\n combos.push(schema.roles.slice());\n }\n\n return combos;\n}\n\n// =============================================================================\n// Pair Building\n// =============================================================================\n\nfunction buildTrainingPair(\n schema: CommandSchema,\n roles: RoleSpec[],\n language: string,\n domain: string,\n id: string\n): TrainingPair {\n const sampledRoles = new Map<string, { type: string; value: string | number | boolean }>();\n\n for (const role of roles) {\n sampledRoles.set(role.role, sampleValue(role));\n }\n\n // Build SemanticNode for bracket syntax\n const nodeRoles = new Map<string, unknown>();\n for (const [name, sample] of sampledRoles) {\n nodeRoles.set(name, toSemanticValue(sample));\n }\n const node = createCommandNode(schema.action, nodeRoles as never);\n const explicit = renderExplicit(node);\n\n // Build JSON format\n const jsonRoles: Record<string, SemanticJSONValue> = {};\n for (const [name, sample] of sampledRoles) {\n jsonRoles[name] = sample as SemanticJSONValue;\n }\n const json: SemanticJSON = { action: schema.action, roles: jsonRoles };\n\n // Build natural language form\n const natural = buildNaturalForm(schema, sampledRoles, language);\n\n // Quality: synthetic pairs get a base quality, higher if more roles are filled\n const requiredCount = schema.roles.filter(r => r.required).length;\n const filledRequired = roles.filter(r => r.required).length;\n const quality = requiredCount > 0 ? filledRequired / requiredCount : 0.8;\n\n return {\n id,\n natural,\n language,\n explicit,\n json,\n domain,\n action: schema.action,\n source: 'synthetic',\n quality,\n };\n}\n\n/**\n * Build a natural language form from sampled roles.\n * Uses marker overrides for the given language when available.\n */\nfunction buildNaturalForm(\n schema: CommandSchema,\n roles: Map<string, { type: string; value: string | number | boolean }>,\n language: string\n): string {\n const parts: string[] = [schema.action];\n\n for (const roleSpec of schema.roles) {\n const sample = roles.get(roleSpec.role);\n if (!sample) continue;\n\n const marker = roleSpec.markerOverride?.[language];\n if (marker) {\n parts.push(marker);\n }\n parts.push(String(sample.value));\n }\n\n return parts.join(' ');\n}\n\n// =============================================================================\n// Value Sampling\n// =============================================================================\n\nfunction sampleValue(role: RoleSpec): { type: string; value: string | number | boolean } {\n const primaryType = role.expectedTypes[0] || 'expression';\n\n switch (primaryType) {\n case 'selector':\n return sampleSelector(role.role);\n case 'literal':\n return sampleLiteral(role.role);\n case 'reference':\n return { type: 'reference', value: 'me' };\n case 'expression':\n return sampleExpression(role.role);\n case 'flag':\n return { type: 'flag', value: true };\n default:\n return { type: 'literal', value: 'example' };\n }\n}\n\nfunction sampleSelector(roleName: string): { type: string; value: string } {\n const selectors: Record<string, string> = {\n patient: '.active',\n destination: '#output',\n source: '#input',\n target: '#target',\n };\n return { type: 'selector', value: selectors[roleName] || `#${roleName}` };\n}\n\nfunction sampleLiteral(roleName: string): { type: string; value: string | number } {\n const literals: Record<string, string | number> = {\n duration: '30s',\n interval: '5s',\n delay: '500ms',\n timeout: '10s',\n quantity: 5,\n limit: 10,\n style: 'json',\n manner: 'rolling',\n format: 'html',\n };\n return { type: 'literal', value: literals[roleName] || roleName };\n}\n\nfunction sampleExpression(roleName: string): { type: string; value: string } {\n const expressions: Record<string, string> = {\n source: '/api/data',\n destination: '#output',\n patient: '.active',\n instrument: 'toUpperCase',\n condition: 'age > 18',\n style: 'json',\n duration: '5s',\n url: '/api/users',\n };\n return { type: 'expression', value: expressions[roleName] || `/api/${roleName}` };\n}\n\nfunction toSemanticValue(sample: { type: string; value: string | number | boolean }): {\n type: string;\n value: string | number | boolean;\n raw?: string;\n dataType?: string;\n selectorKind?: string;\n} {\n switch (sample.type) {\n case 'selector':\n return {\n type: 'selector',\n value: String(sample.value),\n selectorKind: detectSelectorKind(String(sample.value)),\n };\n case 'literal':\n return {\n type: 'literal',\n value: sample.value,\n dataType:\n typeof sample.value === 'number'\n ? 'number'\n : typeof sample.value === 'boolean'\n ? 'boolean'\n : 'string',\n };\n case 'reference':\n return { type: 'reference', value: String(sample.value) };\n case 'expression':\n return { type: 'expression', value: String(sample.value), raw: String(sample.value) };\n case 'flag':\n return { type: 'flag', value: sample.value };\n default:\n return { type: 'literal', value: String(sample.value), dataType: 'string' };\n }\n}\n\nfunction detectSelectorKind(selector: string): string {\n if (selector.startsWith('#')) return 'id';\n if (selector.startsWith('.')) return 'class';\n if (selector.startsWith('[')) return 'attribute';\n return 'complex';\n}\n","/**\n * Feedback Formatter\n *\n * Maps diagnostics to machine-actionable LSEFeedback with hints,\n * corrected examples, and schema context. Enables LLMs to self-correct\n * based on structured error information.\n */\n\nimport type { Diagnostic } from '../generation/diagnostics';\nimport type { CommandSchema } from '../schema/command-schema';\nimport type { SchemaLookup, SemanticJSON, SemanticJSONValue } from '../ir/types';\nimport { renderExplicit } from '../ir/explicit-renderer';\nimport { createCommandNode } from '../core/types';\nimport type { LSEFeedback, FeedbackDiagnostic, FixType } from './types';\n\n// =============================================================================\n// Public API\n// =============================================================================\n\n/**\n * Build structured feedback from diagnostics and optional schema context.\n *\n * @param input - The original input text\n * @param inputFormat - Format of the input\n * @param diagnostics - Error diagnostics from validation/parsing\n * @param schemaLookup - Optional schema lookup for generating hints and corrections\n * @param action - The attempted command action (if identifiable)\n */\nexport function buildFeedback(\n input: string,\n inputFormat: 'explicit' | 'json' | 'natural',\n diagnostics: readonly Diagnostic[],\n schemaLookup?: SchemaLookup,\n action?: string\n): LSEFeedback {\n const hasErrors = diagnostics.some(d => d.severity === 'error');\n const feedbackDiagnostics = diagnostics.map(d => toFeedbackDiagnostic(d));\n const hints = generateHints(feedbackDiagnostics, schemaLookup, action);\n\n let schemaInfo: LSEFeedback['schema'] | undefined;\n let correctedExample: LSEFeedback['correctedExample'] | undefined;\n\n if (action && schemaLookup) {\n const schema = schemaLookup.getSchema(action);\n if (schema) {\n schemaInfo = extractSchemaInfo(schema);\n if (hasErrors) {\n correctedExample = generateCorrectedExample(schema);\n }\n }\n }\n\n return {\n accepted: !hasErrors,\n input: { format: inputFormat, text: input },\n diagnostics: feedbackDiagnostics,\n hints,\n ...(schemaInfo && { schema: schemaInfo }),\n ...(correctedExample && { correctedExample }),\n };\n}\n\n// =============================================================================\n// Diagnostic Classification\n// =============================================================================\n\n/**\n * Map a framework Diagnostic to a FeedbackDiagnostic with fix type.\n */\nfunction toFeedbackDiagnostic(d: Diagnostic): FeedbackDiagnostic {\n const fixType = classifyFixType(d);\n return {\n severity: d.severity,\n code: d.code || 'unknown',\n message: d.message,\n ...(d.suggestions?.[0] && { suggestion: d.suggestions[0] }),\n ...(fixType && { fixType }),\n };\n}\n\n/**\n * Classify a diagnostic into a machine-actionable fix type.\n */\nfunction classifyFixType(d: Diagnostic): FixType | undefined {\n const code = (d.code || '').toLowerCase();\n const msg = d.message.toLowerCase();\n\n // Missing required role\n if (\n code.includes('missing-role') ||\n code.includes('missing_role') ||\n msg.includes('required role') ||\n msg.includes('missing role')\n ) {\n return 'missing_role';\n }\n\n // Invalid value type\n if (\n code.includes('invalid-type') ||\n code.includes('invalid_type') ||\n code.includes('type-mismatch') ||\n msg.includes('invalid type') ||\n msg.includes('expected type')\n ) {\n return 'invalid_type';\n }\n\n // Unknown command\n if (\n code.includes('unknown-command') ||\n code.includes('unknown_command') ||\n msg.includes('unknown command') ||\n (msg.includes('not recognized') && msg.includes('command'))\n ) {\n return 'unknown_command';\n }\n\n // Unknown role\n if (\n code.includes('unknown-role') ||\n code.includes('unknown_role') ||\n msg.includes('unknown role') ||\n (msg.includes('not recognized') && msg.includes('role'))\n ) {\n return 'unknown_role';\n }\n\n // Syntax error (catch-all for parse errors)\n if (\n code.includes('parse') ||\n code.includes('syntax') ||\n msg.includes('syntax error') ||\n msg.includes('parse error') ||\n msg.includes('unexpected')\n ) {\n return 'syntax_error';\n }\n\n return undefined;\n}\n\n// =============================================================================\n// Hint Generation\n// =============================================================================\n\nfunction generateHints(\n diagnostics: readonly FeedbackDiagnostic[],\n schemaLookup?: SchemaLookup,\n action?: string\n): string[] {\n const hints: string[] = [];\n const schema = action && schemaLookup ? schemaLookup.getSchema(action) : undefined;\n\n for (const d of diagnostics) {\n if (d.severity !== 'error') continue;\n\n switch (d.fixType) {\n case 'missing_role': {\n if (schema) {\n const required = schema.roles\n .filter(r => r.required)\n .map(r => `'${r.role}' (${r.description}, type: ${r.expectedTypes.join('|')})`)\n .join(', ');\n hints.push(`Required roles for '${action}': ${required}`);\n } else {\n hints.push('Check that all required roles are present.');\n }\n break;\n }\n\n case 'unknown_command': {\n hints.push(\n `Command not recognized. Ensure you're using a valid command from the domain schema.`\n );\n break;\n }\n\n case 'unknown_role': {\n if (schema) {\n const validRoles = schema.roles.map(r => `'${r.role}'`).join(', ');\n hints.push(`Valid roles for '${action}': ${validRoles}`);\n } else {\n hints.push('Use only roles defined in the command schema.');\n }\n break;\n }\n\n case 'invalid_type': {\n hints.push(\n 'Check value types: selectors start with #.[@*, strings use quotes, numbers are plain digits.'\n );\n break;\n }\n\n case 'syntax_error': {\n hints.push('Ensure bracket syntax: [command role:value ...]. No spaces around the colon.');\n break;\n }\n\n default: {\n if (d.suggestion) {\n hints.push(d.suggestion);\n }\n }\n }\n }\n\n // Deduplicate\n return [...new Set(hints)];\n}\n\n// =============================================================================\n// Schema Info Extraction\n// =============================================================================\n\nfunction extractSchemaInfo(schema: CommandSchema): LSEFeedback['schema'] {\n const requiredRoles: string[] = [];\n const optionalRoles: string[] = [];\n const roleDescriptions: Record<string, string> = {};\n\n for (const role of schema.roles) {\n if (role.required) {\n requiredRoles.push(role.role);\n } else {\n optionalRoles.push(role.role);\n }\n roleDescriptions[role.role] = role.description;\n }\n\n return {\n action: schema.action,\n requiredRoles,\n optionalRoles,\n roleDescriptions,\n };\n}\n\n// =============================================================================\n// Corrected Example Generation\n// =============================================================================\n\nfunction generateCorrectedExample(schema: CommandSchema): { explicit: string; json: SemanticJSON } {\n const roles = new Map<string, unknown>();\n const jsonRoles: Record<string, SemanticJSONValue> = {};\n\n for (const role of schema.roles) {\n if (!role.required) continue;\n const sample = sampleDefaultValue(role.role, role.expectedTypes[0] || 'expression');\n roles.set(role.role, toSemanticValue(sample));\n jsonRoles[role.role] = sample as SemanticJSONValue;\n }\n\n const node = createCommandNode(schema.action, roles as never);\n const explicit = renderExplicit(node);\n const json: SemanticJSON = { action: schema.action, roles: jsonRoles };\n\n return { explicit, json };\n}\n\nfunction sampleDefaultValue(\n roleName: string,\n expectedType: string\n): { type: string; value: string } {\n switch (expectedType) {\n case 'selector':\n return { type: 'selector', value: `#${roleName}` };\n case 'expression':\n return { type: 'expression', value: `<${roleName}-value>` };\n case 'literal':\n return { type: 'literal', value: `<${roleName}-value>` };\n case 'reference':\n return { type: 'reference', value: 'me' };\n default:\n return { type: 'expression', value: `<${roleName}-value>` };\n }\n}\n\nfunction toSemanticValue(sample: { type: string; value: string }): {\n type: string;\n value: string;\n raw?: string;\n selectorKind?: string;\n dataType?: string;\n} {\n switch (sample.type) {\n case 'selector':\n return { type: 'selector', value: sample.value, selectorKind: 'id' };\n case 'expression':\n return { type: 'expression', value: sample.value, raw: sample.value };\n case 'literal':\n return { type: 'literal', value: sample.value, dataType: 'string' };\n case 'reference':\n return { type: 'reference', value: sample.value };\n default:\n return { type: 'literal', value: sample.value, dataType: 'string' };\n }\n}\n","/**\n * Domain Registry\n *\n * Provides auto-discovery and registration of framework domains for MCP servers.\n * Instead of hardcoding tool definitions and dispatch logic per domain, domains\n * export a `DomainDescriptor` and the registry generates everything automatically.\n *\n * @example\n * ```typescript\n * import { DomainRegistry } from '@lokascript/framework';\n *\n * const registry = new DomainRegistry();\n *\n * // Register domains (each provides a descriptor)\n * registry.register({\n * name: 'sql',\n * description: 'Natural language SQL',\n * languages: ['en', 'es', 'ja', 'ar'],\n * inputLabel: 'query',\n * inputDescription: 'SQL query in natural language',\n * getDSL: () => import('@lokascript/domain-sql').then(m => m.createSQLDSL()),\n * getRenderer: () => import('@lokascript/domain-sql').then(m => m.renderSQL),\n * });\n *\n * // Auto-generate MCP tool definitions\n * const tools = registry.getToolDefinitions();\n *\n * // Dispatch a tool call\n * const result = await registry.handleToolCall('parse_sql', { query: 'select name from users' });\n * ```\n */\n\nimport type { SemanticNode } from '../core/types';\nimport type { MultilingualDSL, CompileResult, ValidationResult } from './create-dsl';\nimport type { NaturalLanguageRenderer } from '../generation/renderer';\nimport type { CommandSchema } from '../schema/command-schema';\nimport type { SchemaLookup } from '../ir/types';\nimport type { Diagnostic } from '../generation/diagnostics';\nimport type { GeneratedPrompt, PromptGeneratorConfig } from '../prompts/types';\nimport type { SynthesisConfig, SynthesisResult } from '../training/types';\nimport type { LSEFeedback } from '../feedback/types';\nimport { generatePrompt as _generatePrompt } from '../prompts/prompt-generator';\nimport { synthesizeFromSchemas as _synthesizeFromSchemas } from '../training/schema-synthesizer';\nimport { buildFeedback as _buildFeedback } from '../feedback/feedback-formatter';\nimport { parseExplicit as _parseExplicit } from '../ir/explicit-parser';\n\n// =============================================================================\n// Descriptor Interface\n// =============================================================================\n\n/**\n * Describes a domain for auto-registration in MCP servers.\n *\n * Domains provide this descriptor to the registry, which generates\n * tool definitions and handles dispatch automatically.\n */\nexport interface DomainDescriptor {\n /** Short identifier (used in tool names: parse_{name}, compile_{name}, etc.) */\n readonly name: string;\n\n /** Human-readable description */\n readonly description: string;\n\n /** Supported language codes */\n readonly languages: readonly string[];\n\n /** Label for the primary input parameter (e.g., 'query', 'scenario', 'code') */\n readonly inputLabel: string;\n\n /** Description of the primary input parameter */\n readonly inputDescription: string;\n\n /** What compile_{name} produces (e.g., \"a SQL query string\"). Used in tool description. */\n readonly outputDescription?: string;\n\n /**\n * Factory to lazily create the DSL instance.\n * Called once on first tool use. The result is cached.\n */\n readonly getDSL: () => MultilingualDSL | Promise<MultilingualDSL>;\n\n /**\n * Factory to lazily create the renderer.\n * Required for translate_{name} tool. Called once on first use.\n */\n readonly getRenderer?: () =>\n | NaturalLanguageRenderer\n | ((node: SemanticNode, language: string) => string)\n | Promise<NaturalLanguageRenderer | ((node: SemanticNode, language: string) => string)>;\n\n /**\n * Which standard tools to generate. Default: all four.\n */\n readonly tools?: readonly ('parse' | 'compile' | 'validate' | 'translate')[];\n\n /**\n * Optional command schemas for this domain.\n * When provided, enables system prompt generation, training data synthesis,\n * and structured feedback via the registry's convenience methods.\n */\n readonly schemas?: readonly CommandSchema[];\n\n /**\n * Optional scan configuration for AOT compilation and Vite plugin.\n * Declares which HTML attributes/script types this domain uses.\n */\n readonly scanConfig?: {\n /** Attribute names to scan for (e.g., ['data-sql', '_sql']) */\n readonly attributes: readonly string[];\n /** Script tag types to scan for (e.g., ['text/sql-dsl']) */\n readonly scriptTypes?: readonly string[];\n /** Default language when not specified on element */\n readonly defaultLanguage?: string;\n /** Keywords for detection, keyed by language code */\n readonly keywords?: Readonly<Record<string, readonly string[]>>;\n };\n}\n\n// =============================================================================\n// MCP Tool Types (minimal — compatible with @modelcontextprotocol/sdk)\n// =============================================================================\n\n/**\n * MCP tool definition. Compatible with the MCP SDK's tool schema.\n */\nexport interface MCPToolDefinition {\n readonly name: string;\n readonly description: string;\n readonly inputSchema: {\n readonly type: 'object';\n readonly properties: Record<string, unknown>;\n readonly required: readonly string[];\n };\n}\n\n/**\n * MCP tool response. Compatible with the MCP SDK's response format.\n */\nexport interface MCPToolResponse {\n readonly content: ReadonlyArray<{ readonly type: string; readonly text: string }>;\n readonly isError?: boolean;\n}\n\n// =============================================================================\n// Domain Registry\n// =============================================================================\n\n/**\n * Registry for framework domains.\n *\n * Manages domain descriptors, generates MCP tool definitions,\n * and dispatches tool calls to the appropriate domain.\n */\nexport class DomainRegistry {\n private descriptors = new Map<string, DomainDescriptor>();\n private dslCache = new Map<string, MultilingualDSL>();\n private rendererCache = new Map<\n string,\n NaturalLanguageRenderer | ((node: SemanticNode, language: string) => string)\n >();\n\n /**\n * Register a domain.\n * @throws if a domain with the same name is already registered\n */\n register(descriptor: DomainDescriptor): void {\n if (this.descriptors.has(descriptor.name)) {\n throw new Error(`Domain already registered: ${descriptor.name}`);\n }\n this.descriptors.set(descriptor.name, descriptor);\n }\n\n /**\n * Attach schemas to an already-registered domain.\n * Useful for lazy loading schemas after initial registration.\n */\n setSchemas(name: string, schemas: readonly CommandSchema[]): void {\n const existing = this.descriptors.get(name);\n if (!existing) {\n throw new Error(`Domain not registered: ${name}`);\n }\n // Create a new descriptor with schemas attached\n this.descriptors.set(name, { ...existing, schemas });\n }\n\n /**\n * Get all registered domain names.\n */\n getDomainNames(): string[] {\n return Array.from(this.descriptors.keys());\n }\n\n /**\n * Get a specific domain descriptor.\n */\n getDescriptor(name: string): DomainDescriptor | undefined {\n return this.descriptors.get(name);\n }\n\n /**\n * Generate MCP tool definitions for all registered domains.\n */\n getToolDefinitions(): MCPToolDefinition[] {\n const tools: MCPToolDefinition[] = [];\n for (const desc of this.descriptors.values()) {\n tools.push(...generateToolDefinitions(desc));\n }\n return tools;\n }\n\n /**\n * Check if a tool name belongs to a registered domain.\n */\n canHandle(toolName: string): boolean {\n const parsed = parseToolName(toolName);\n if (!parsed) return false;\n return this.descriptors.has(parsed.domain);\n }\n\n /**\n * Handle a tool call by dispatching to the appropriate domain.\n * Returns null if the tool name doesn't match any registered domain.\n */\n async handleToolCall(\n toolName: string,\n args: Record<string, unknown>\n ): Promise<MCPToolResponse | null> {\n const parsed = parseToolName(toolName);\n if (!parsed) return null;\n\n const descriptor = this.descriptors.get(parsed.domain);\n if (!descriptor) return null;\n\n try {\n const dsl = await this.getDSL(descriptor);\n\n switch (parsed.operation) {\n case 'parse':\n return await this.handleParse(descriptor, dsl, args);\n case 'compile':\n return await this.handleCompile(descriptor, dsl, args);\n case 'validate':\n return await this.handleValidate(descriptor, dsl, args);\n case 'translate':\n return await this.handleTranslate(descriptor, dsl, args);\n default:\n return jsonResponse({ error: `Unknown operation: ${parsed.operation}` }, true);\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return jsonResponse({ error: `${descriptor.name} tool error: ${message}` }, true);\n }\n }\n\n /**\n * Get the DSL instance for a named domain.\n * Returns null if the domain is not registered.\n * The DSL is lazily created and cached.\n */\n async getDSLForDomain(name: string): Promise<MultilingualDSL | null> {\n const descriptor = this.descriptors.get(name);\n if (!descriptor) return null;\n return this.getDSL(descriptor);\n }\n\n // ---------------------------------------------------------------------------\n // LLM ↔ LSE Convenience Methods\n // ---------------------------------------------------------------------------\n\n /**\n * Generate an LLM system prompt for a domain from its schemas.\n * Returns null if the domain is not registered or has no schemas.\n */\n generatePrompt(domain: string, config?: Partial<PromptGeneratorConfig>): GeneratedPrompt | null {\n const descriptor = this.descriptors.get(domain);\n if (!descriptor?.schemas || descriptor.schemas.length === 0) return null;\n\n return _generatePrompt({\n domain,\n description: descriptor.description,\n schemas: descriptor.schemas,\n ...config,\n });\n }\n\n /**\n * Synthesize training data for a domain from its schemas.\n * Returns null if the domain is not registered or has no schemas.\n */\n generateTrainingData(domain: string, config?: Partial<SynthesisConfig>): SynthesisResult | null {\n const descriptor = this.descriptors.get(domain);\n if (!descriptor?.schemas || descriptor.schemas.length === 0) return null;\n\n return _synthesizeFromSchemas(descriptor.schemas, {\n domain,\n ...config,\n });\n }\n\n /**\n * Build structured feedback for a failed LSE input in a domain.\n * Returns null if the domain is not registered or has no schemas.\n */\n buildFeedback(\n domain: string,\n input: string,\n inputFormat: 'explicit' | 'json' | 'natural',\n diagnostics: readonly Diagnostic[]\n ): LSEFeedback | null {\n const descriptor = this.descriptors.get(domain);\n if (!descriptor?.schemas || descriptor.schemas.length === 0) return null;\n\n const schemaLookup = this.createSchemaLookup(descriptor.schemas);\n\n // Try to extract the action from the input\n let action: string | undefined;\n try {\n if (inputFormat === 'explicit') {\n const node = _parseExplicit(input, { schemaLookup });\n action = node.action;\n }\n } catch {\n // Action detection failed — still build feedback without it\n }\n\n return _buildFeedback(input, inputFormat, diagnostics, schemaLookup, action);\n }\n\n /**\n * Get schemas for a domain (if available).\n */\n getSchemas(domain: string): readonly CommandSchema[] | null {\n const descriptor = this.descriptors.get(domain);\n if (!descriptor?.schemas) return null;\n return descriptor.schemas;\n }\n\n /**\n * Create a SchemaLookup from a domain's schemas.\n */\n private createSchemaLookup(schemas: readonly CommandSchema[]): SchemaLookup {\n const map = new Map<string, CommandSchema>();\n for (const s of schemas) {\n map.set(s.action, s);\n }\n return { getSchema: (action: string) => map.get(action) };\n }\n\n // ---------------------------------------------------------------------------\n // Private: DSL/renderer lifecycle\n // ---------------------------------------------------------------------------\n\n private async getDSL(descriptor: DomainDescriptor): Promise<MultilingualDSL> {\n const cached = this.dslCache.get(descriptor.name);\n if (cached) return cached;\n\n const dsl = await descriptor.getDSL();\n this.dslCache.set(descriptor.name, dsl);\n return dsl;\n }\n\n private async getRenderer(\n descriptor: DomainDescriptor\n ): Promise<NaturalLanguageRenderer | ((node: SemanticNode, language: string) => string) | null> {\n if (!descriptor.getRenderer) return null;\n\n const cached = this.rendererCache.get(descriptor.name);\n if (cached) return cached;\n\n const renderer = await descriptor.getRenderer();\n this.rendererCache.set(descriptor.name, renderer);\n return renderer;\n }\n\n // ---------------------------------------------------------------------------\n // Private: Tool handlers\n // ---------------------------------------------------------------------------\n\n private async handleParse(\n descriptor: DomainDescriptor,\n dsl: MultilingualDSL,\n args: Record<string, unknown>\n ): Promise<MCPToolResponse> {\n const input = getString(args, descriptor.inputLabel);\n if (!input) return missingParam(descriptor.inputLabel);\n const language = getString(args, 'language', 'en');\n\n const node = dsl.parse(input, language);\n\n const roles: Record<string, unknown> = {};\n for (const [key, value] of node.roles) {\n roles[key] = value;\n }\n\n return jsonResponse({\n action: node.action,\n roles,\n language,\n [descriptor.inputLabel]: input,\n });\n }\n\n private async handleCompile(\n descriptor: DomainDescriptor,\n dsl: MultilingualDSL,\n args: Record<string, unknown>\n ): Promise<MCPToolResponse> {\n const input = getString(args, descriptor.inputLabel);\n if (!input) return missingParam(descriptor.inputLabel);\n const language = getString(args, 'language', 'en');\n\n const result: CompileResult = dsl.compile(input, language);\n\n return jsonResponse({\n ok: result.ok,\n code: result.code,\n errors: result.errors,\n language,\n input,\n });\n }\n\n private async handleValidate(\n descriptor: DomainDescriptor,\n dsl: MultilingualDSL,\n args: Record<string, unknown>\n ): Promise<MCPToolResponse> {\n const input = getString(args, descriptor.inputLabel);\n if (!input) return missingParam(descriptor.inputLabel);\n const language = getString(args, 'language', 'en');\n\n const result: ValidationResult = dsl.validate(input, language);\n\n return jsonResponse({\n valid: result.valid,\n errors: result.errors,\n language,\n [descriptor.inputLabel]: input,\n });\n }\n\n private async handleTranslate(\n descriptor: DomainDescriptor,\n dsl: MultilingualDSL,\n args: Record<string, unknown>\n ): Promise<MCPToolResponse> {\n const input = getString(args, descriptor.inputLabel);\n if (!input) return missingParam(descriptor.inputLabel);\n const from = getString(args, 'from');\n if (!from) return missingParam('from');\n const to = getString(args, 'to');\n if (!to) return missingParam('to');\n\n // Parse in source language\n const node = dsl.parse(input, from);\n\n // Compile (language-neutral output)\n const compiled = dsl.compile(input, from);\n\n // Render to target language\n let rendered: string | null = null;\n const renderer = await this.getRenderer(descriptor);\n if (renderer) {\n try {\n rendered = typeof renderer === 'function' ? renderer(node, to) : renderer.render(node, to);\n } catch {\n // Fall through with rendered = null\n }\n }\n\n const roles: Record<string, unknown> = {};\n for (const [key, value] of node.roles) {\n roles[key] = value;\n }\n\n return jsonResponse({\n input: { [descriptor.inputLabel]: input, language: from },\n ...(rendered != null && { rendered: { text: rendered, language: to } }),\n semantic: { action: node.action, roles },\n ...(compiled.ok && compiled.code != null && { compiled: compiled.code }),\n });\n }\n}\n\n// =============================================================================\n// Tool Definition Generator\n// =============================================================================\n\nfunction generateToolDefinitions(desc: DomainDescriptor): MCPToolDefinition[] {\n const tools: MCPToolDefinition[] = [];\n const ops = desc.tools ?? (['parse', 'compile', 'validate', 'translate'] as const);\n const langList = desc.languages.join(', ');\n\n for (const op of ops) {\n switch (op) {\n case 'parse':\n tools.push({\n name: `parse_${desc.name}`,\n description: `Parse a ${desc.description} input into a semantic representation (action, roles, confidence). Supports: ${langList}.`,\n inputSchema: {\n type: 'object',\n properties: {\n [desc.inputLabel]: {\n type: 'string',\n description: desc.inputDescription,\n },\n language: {\n type: 'string',\n description: `Language code: ${langList}`,\n default: 'en',\n },\n },\n required: [desc.inputLabel],\n },\n });\n break;\n\n case 'compile':\n tools.push({\n name: `compile_${desc.name}`,\n description: `Compile a ${desc.description} input to ${desc.outputDescription ?? 'target code'}. Supports: ${langList}.`,\n inputSchema: {\n type: 'object',\n properties: {\n [desc.inputLabel]: {\n type: 'string',\n description: desc.inputDescription,\n },\n language: {\n type: 'string',\n description: `Language code: ${langList}`,\n default: 'en',\n },\n },\n required: [desc.inputLabel],\n },\n });\n break;\n\n case 'validate':\n tools.push({\n name: `validate_${desc.name}`,\n description: `Check ${desc.description} syntax for errors. Returns {valid, errors[]}. Supports: ${langList}.`,\n inputSchema: {\n type: 'object',\n properties: {\n [desc.inputLabel]: {\n type: 'string',\n description: `${desc.inputDescription} to validate`,\n },\n language: {\n type: 'string',\n description: `Language code: ${langList}`,\n default: 'en',\n },\n },\n required: [desc.inputLabel],\n },\n });\n break;\n\n case 'translate':\n tools.push({\n name: `translate_${desc.name}`,\n description: `Translate ${desc.description} input between natural languages (requires 'from' and 'to' codes). Supports: ${langList}.`,\n inputSchema: {\n type: 'object',\n properties: {\n [desc.inputLabel]: {\n type: 'string',\n description: `${desc.inputDescription} to translate`,\n },\n from: {\n type: 'string',\n description: `Source language code: ${langList}`,\n },\n to: {\n type: 'string',\n description: `Target language code: ${langList}`,\n },\n },\n required: [desc.inputLabel, 'from', 'to'],\n },\n });\n break;\n }\n }\n\n return tools;\n}\n\n// =============================================================================\n// Helpers\n// =============================================================================\n\nfunction parseToolName(name: string): { operation: string; domain: string } | null {\n const match = name.match(/^(parse|compile|validate|translate)_(.+)$/);\n if (!match) return null;\n return { operation: match[1], domain: match[2] };\n}\n\nfunction getString(args: Record<string, unknown>, name: string, defaultValue = ''): string {\n const value = args[name];\n return typeof value === 'string' ? value : defaultValue;\n}\n\nfunction jsonResponse(data: unknown, isError?: boolean): MCPToolResponse {\n return {\n content: [{ type: 'text', text: JSON.stringify(data, null, 2) }],\n ...(isError && { isError: true }),\n };\n}\n\nfunction missingParam(param: string): MCPToolResponse {\n return jsonResponse({ error: `Missing required parameter: ${param}` }, true);\n}\n","/**\n * Cross-Domain Dispatcher\n *\n * Routes natural-language input to the correct domain by trying all registered\n * domains and picking the highest-confidence match. Supports auto-detection,\n * composite multi-line parsing, and confidence-based routing.\n *\n * @example\n * ```typescript\n * import { DomainRegistry, CrossDomainDispatcher } from '@lokascript/framework';\n *\n * const registry = new DomainRegistry();\n * registry.register(sqlDescriptor);\n * registry.register(bddDescriptor);\n *\n * const dispatcher = new CrossDomainDispatcher(registry);\n *\n * // Auto-detect which domain handles the input\n * const result = await dispatcher.detect('select name from users', 'en');\n * // → { domain: 'sql', node: ..., confidence: 0.95, dsl: ... }\n *\n * // Parse multi-line input across domains\n * const composite = await dispatcher.parseComposite(`\n * select name from users\n * given page http://localhost\n * `, 'en');\n * ```\n */\n\nimport type { SemanticNode } from '../core/types';\nimport type { MultilingualDSL, CompileResult, ValidationResult } from './create-dsl';\nimport { DomainRegistry } from './domain-registry';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/** Result of domain auto-detection */\nexport interface DispatchResult {\n /** The domain that matched */\n readonly domain: string;\n /** Parsed semantic node */\n readonly node: SemanticNode;\n /** Confidence score (0-1) */\n readonly confidence: number;\n /** The DSL instance that parsed it */\n readonly dsl: MultilingualDSL;\n}\n\n/** A single statement in a composite parse result */\nexport interface CompositeStatement {\n readonly line: number;\n readonly input: string;\n readonly domain: string;\n readonly node: SemanticNode;\n readonly confidence: number;\n}\n\n/** An error from a composite parse */\nexport interface CompositeError {\n readonly line: number;\n readonly input: string;\n readonly message: string;\n}\n\n/** Result of multi-domain composite parsing */\nexport interface CompositeParseResult {\n /** Successfully parsed statements */\n readonly statements: readonly CompositeStatement[];\n /** Lines that could not be matched to any domain */\n readonly errors: readonly CompositeError[];\n}\n\n/** A single compiled statement in a composite compile result */\nexport interface CompositeCompileStatement {\n readonly line: number;\n readonly input: string;\n readonly domain: string;\n readonly ok: boolean;\n readonly code?: string | undefined;\n readonly errors?: string[] | undefined;\n}\n\n/** Result of multi-domain composite compilation */\nexport interface CompositeCompileResult {\n /** Successfully detected and compiled statements */\n readonly statements: readonly CompositeCompileStatement[];\n /** Lines that could not be matched to any domain */\n readonly errors: readonly CompositeError[];\n}\n\n/** Dispatcher configuration options */\nexport interface DispatcherOptions {\n /** Minimum confidence to accept a match (default: 0.5) */\n readonly minConfidence?: number;\n /** Domain priority order — earlier domains win on confidence ties */\n readonly priority?: readonly string[];\n}\n\n// =============================================================================\n// Comment line detection\n// =============================================================================\n\nconst COMMENT_PATTERN = /^\\s*(\\/\\/|--|#)/;\n\nfunction isSkippableLine(line: string): boolean {\n const trimmed = line.trim();\n return trimmed === '' || COMMENT_PATTERN.test(trimmed);\n}\n\n// =============================================================================\n// CrossDomainDispatcher\n// =============================================================================\n\n/**\n * Dispatcher that routes input to the correct domain by confidence scoring.\n *\n * Built on top of DomainRegistry — uses registered domains' DSL instances\n * to try parsing input and picks the highest-confidence match.\n */\nexport class CrossDomainDispatcher {\n private registry: DomainRegistry;\n private minConfidence: number;\n private priority: readonly string[];\n\n constructor(registry: DomainRegistry, options?: DispatcherOptions) {\n this.registry = registry;\n this.minConfidence = options?.minConfidence ?? 0.5;\n this.priority = options?.priority ?? [];\n }\n\n /**\n * Auto-detect which domain handles the input.\n * Tries all registered domains and returns the highest-confidence match.\n * Returns null if no domain matches above minConfidence.\n */\n async detect(input: string, language = 'en'): Promise<DispatchResult | null> {\n const domainNames = this.registry.getDomainNames();\n if (domainNames.length === 0) return null;\n\n const candidates: DispatchResult[] = [];\n\n for (const name of domainNames) {\n try {\n const dsl = await this.registry.getDSLForDomain(name);\n if (!dsl) continue;\n\n const { node, confidence } = dsl.parseWithConfidence(input, language);\n if (confidence >= this.minConfidence) {\n candidates.push({ domain: name, node, confidence, dsl });\n }\n } catch {\n // Domain could not be loaded or parse this input — skip\n }\n }\n\n if (candidates.length === 0) return null;\n\n // Sort by priority first, then confidence within each priority tier.\n // Simpler schemas (fewer roles) often score higher confidence than more\n // specific ones — e.g., voice's \"select [patient:greedy]\" gets 1.0 while\n // sql's \"select [columns] from [source]\" gets 0.71 for the same input.\n // Priority ordering ensures domain specificity wins when both match.\n if (this.priority.length > 0) {\n candidates.sort((a, b) => {\n const pa = this.getPriorityIndex(a.domain);\n const pb = this.getPriorityIndex(b.domain);\n if (pa !== pb) return pa - pb;\n return b.confidence - a.confidence;\n });\n } else {\n // No priority configured: pure confidence ordering\n candidates.sort((a, b) => b.confidence - a.confidence);\n }\n\n return candidates[0];\n }\n\n /**\n * Parse multi-line input where each line may belong to a different domain.\n * Empty lines and comment lines (starting with //, --, or #) are skipped.\n */\n async parseComposite(input: string, language = 'en'): Promise<CompositeParseResult> {\n const lines = input.split('\\n');\n const statements: CompositeStatement[] = [];\n const errors: CompositeError[] = [];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n if (isSkippableLine(line)) continue;\n\n const trimmed = line.trim();\n const result = await this.detect(trimmed, language);\n\n if (result) {\n statements.push({\n line: i + 1,\n input: trimmed,\n domain: result.domain,\n node: result.node,\n confidence: result.confidence,\n });\n } else {\n errors.push({\n line: i + 1,\n input: trimmed,\n message: 'No domain matched this input',\n });\n }\n }\n\n return { statements, errors };\n }\n\n /**\n * Compile input using auto-detected domain.\n * Returns the compilation result with the domain name.\n */\n async compile(\n input: string,\n language = 'en'\n ): Promise<(CompileResult & { domain: string }) | null> {\n const detected = await this.detect(input, language);\n if (!detected) return null;\n\n const result = detected.dsl.compile(input, language);\n return { ...result, domain: detected.domain };\n }\n\n /**\n * Compile multi-line input where each line may belong to a different domain.\n * Detects the domain for each line and compiles it, returning per-line results.\n * Empty lines and comment lines are skipped.\n */\n async compileComposite(input: string, language = 'en'): Promise<CompositeCompileResult> {\n const lines = input.split('\\n');\n const statements: CompositeCompileStatement[] = [];\n const errors: CompositeError[] = [];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n if (isSkippableLine(line)) continue;\n\n const trimmed = line.trim();\n const detected = await this.detect(trimmed, language);\n\n if (detected) {\n const result = detected.dsl.compile(trimmed, language);\n statements.push({\n line: i + 1,\n input: trimmed,\n domain: detected.domain,\n ok: result.ok,\n code: result.code,\n errors: result.errors,\n });\n } else {\n errors.push({\n line: i + 1,\n input: trimmed,\n message: 'No domain matched this input',\n });\n }\n }\n\n return { statements, errors };\n }\n\n /**\n * Validate input against all domains, returning the best match.\n */\n async validate(input: string, language = 'en'): Promise<ValidationResult & { domain?: string }> {\n const detected = await this.detect(input, language);\n if (!detected) {\n return { valid: false, errors: ['No domain matched this input'] };\n }\n\n const result = detected.dsl.validate(input, language);\n return { ...result, domain: detected.domain };\n }\n\n // ---------------------------------------------------------------------------\n // Private\n // ---------------------------------------------------------------------------\n\n private getPriorityIndex(domain: string): number {\n const idx = this.priority.indexOf(domain);\n return idx === -1 ? this.priority.length : idx;\n }\n}\n"],"mappings":";AAyCA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;AC1CP,IAAM,cAAN,MAAkB;AAAA,EAIhB,YAAY,WAAmB;AAC7B,SAAK,YAAY;AACjB,SAAK,UAAU,KAAK,aAAa;AAAA,EACnC;AAAA,EAEQ,eAAwB;AAE9B,QAAI,OAAO,YAAY,eAAe,QAAQ,KAAK;AACjD,YAAM,QAAQ,QAAQ,IAAI,SAAS;AAEnC,aACE,UAAU,OACV,MAAM,SAAS,aAAa,KAC5B,MAAM,SAAS,aAAa,KAAK,SAAS,EAAE;AAAA,IAEhD;AACA,WAAO;AAAA,EACT;AAAA,EAEQ,IAAI,OAAiB,YAAoB,MAAmB;AAClE,QAAI,CAAC,KAAK,QAAS;AAEnB,UAAM,SAAS,cAAc,KAAK,SAAS;AAC3C,UAAM,aAAY,oBAAI,KAAK,GAAE,YAAY;AAEzC,YAAQ,OAAO;AAAA,MACb,KAAK;AAEH,gBAAQ,MAAM,GAAG,SAAS,IAAI,MAAM,WAAW,SAAS,GAAG,IAAI;AAC/D;AAAA,MACF,KAAK;AAEH,gBAAQ,KAAK,GAAG,SAAS,IAAI,MAAM,UAAU,SAAS,GAAG,IAAI;AAC7D;AAAA,MACF,KAAK;AAEH,gBAAQ,KAAK,GAAG,SAAS,IAAI,MAAM,UAAU,SAAS,GAAG,IAAI;AAC7D;AAAA,MACF,KAAK;AAEH,gBAAQ,MAAM,GAAG,SAAS,IAAI,MAAM,WAAW,SAAS,GAAG,IAAI;AAC/D;AAAA,IACJ;AAAA,EACF;AAAA,EAEA,MA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AAA;AAAA;AAAA;AAAA,EAKA,MAAM,SAAS,OAAe,WAAW,MAAuD;AAC9F,UAAM,WAAW,MAAM,KAAK,OAAO,OAAO,QAAQ;AAClD,QAAI,CAAC,UAAU;AACb,aAAO,EAAE,OAAO,OAAO,QAAQ,CAAC,8BAA8B,EAAE;AAAA,IAClE;AAEA,UAAM,SAAS,SAAS,IAAI,SAAS,OAAO,QAAQ;AACpD,WAAO,EAAE,GAAG,QAAQ,QAAQ,SAAS,OAAO;AAAA,EAC9C;AAAA;AAAA;AAAA;AAAA,EAMQ,iBAAiB,QAAwB;AAC/C,UAAM,MAAM,KAAK,SAAS,QAAQ,MAAM;AACxC,WAAO,QAAQ,KAAK,KAAK,SAAS,SAAS;AAAA,EAC7C;AACF;","names":["num","generateRoleCombinations","sampleValue","toSemanticValue","sampleSelector","sampleLiteral","sampleExpression","detectSelectorKind","toSemanticValue"]}