@lokascript/framework 2.10.0 → 2.11.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.
@@ -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/generation/renderer.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 } | 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, postVerb roles...]\n else if (profile.wordOrder === 'SOV') {\n // `sovSlot: 'postVerb'` moves a role AFTER the verb, which is what the\n // renderer does (`renderer.ts` buckets by the same field). Generation has\n // to mirror it: a role the renderer writes post-verb but the pattern\n // expects pre-verb produces a faithful surface its own parser drops the\n // argument from — voice's `戻る 2` re-parsing as a bare `back`.\n const preVerb: PatternToken[] = [];\n const postVerb: PatternToken[] = [];\n\n for (const role of sortedRoles) {\n addRoleWithMarker(role.sovSlot === 'postVerb' ? postVerb : preVerb, role, profile);\n }\n\n tokens.push(...preVerb, keywordToken, ...postVerb);\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 *\n * Exported so the renderer sorts with exactly this comparator — a rendered\n * surface whose role order differs from the generated pattern would not re-parse.\n */\nexport function 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 isSOV = profile.wordOrder === 'SOV';\n const preVerb: string[] = [];\n const postVerb: string[] = [];\n\n // Order roles the same way buildTokens does (descending position). Iterating\n // declaration order here would disagree with the token order whenever a\n // schema's roles are declared in a different order than their positions imply.\n const sortedRoles = sortRolesByWordOrder(schema.roles, profile.wordOrder);\n for (const role of sortedRoles) {\n const marker = getMarkerForRole(role, profile);\n const roleName = `{${role.role}}`;\n // Same pre/post-verb split buildTokens applies, so the documented format\n // string keeps describing the tokens it is generated alongside.\n const bucket = isSOV && role.sovSlot === 'postVerb' ? postVerb : preVerb;\n\n if (marker) {\n const markerInfo = profile.roleMarkers?.[role.role];\n if (markerInfo?.position === 'after') {\n bucket.push(`${roleName} ${marker}`);\n } else {\n bucket.push(`${marker} ${roleName}`);\n }\n } else {\n bucket.push(roleName);\n }\n }\n\n return (isSOV ? [...preVerb, keyword, ...postVerb] : [keyword, ...preVerb, ...postVerb]).join(\n ' '\n );\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 * Natural Language Renderer\n *\n * Interface and utilities for rendering SemanticNode → human-readable text\n * in any supported language. This is the inverse of parsing: it converts\n * a language-neutral semantic representation back to natural-language syntax.\n *\n * Every domain that supports `translate()` needs a renderer.\n */\n\nimport type { SemanticNode } from '../core/types';\nimport { extractRoleValue, extractValue } from '../core/types';\nimport type { CommandSchema } from '../schema';\nimport { sortRolesByWordOrder, type PatternGenLanguageProfile } from './pattern-generator';\n\n// =============================================================================\n// Renderer Interface\n// =============================================================================\n\n/**\n * Renders a SemanticNode to human-readable text in a target language.\n */\nexport interface NaturalLanguageRenderer {\n render(node: SemanticNode, language: string): string;\n}\n\n// =============================================================================\n// Renderer Helpers\n// =============================================================================\n\n/**\n * Keyword table: action → language → translated keyword.\n *\n * @example\n * ```typescript\n * const KEYWORDS: KeywordTable = {\n * select: { en: 'select', ja: '選択', es: 'seleccionar' },\n * insert: { en: 'insert', ja: '挿入', es: 'insertar' },\n * };\n * ```\n */\nexport type KeywordTable = Record<string, Record<string, string>>;\n\n/**\n * Marker table: marker name → language → translated marker.\n *\n * @example\n * ```typescript\n * const MARKERS: MarkerTable = {\n * from: { en: 'from', ja: 'から', es: 'de' },\n * into: { en: 'into', ja: 'に', es: 'en' },\n * };\n * ```\n */\nexport type MarkerTable = Record<string, Record<string, string>>;\n\n/**\n * Configuration for building a renderer from schemas and profiles.\n */\nexport interface RendererConfig {\n /** Command keyword translations per language */\n readonly keywords: KeywordTable;\n\n /** Role marker translations per language (prepositions/particles) */\n readonly markers: MarkerTable;\n\n /** Languages that use SOV word order */\n readonly sovLanguages: ReadonlySet<string>;\n\n /** Languages that use VSO word order (optional, defaults to empty) */\n readonly vsoLanguages?: ReadonlySet<string>;\n}\n\n/**\n * Look up a command keyword in the target language.\n * Falls back to the key itself if no translation found.\n */\nexport function lookupKeyword(keywords: KeywordTable, action: string, language: string): string {\n return keywords[action]?.[language] ?? action;\n}\n\n/**\n * Look up a role marker in the target language.\n * Falls back to the key itself if no translation found.\n */\nexport function lookupMarker(markers: MarkerTable, marker: string, language: string): string {\n return markers[marker]?.[language] ?? marker;\n}\n\n/**\n * Build a phrase from parts, filtering empty strings and joining with space.\n *\n * @example\n * ```typescript\n * buildPhrase('select', '', 'name', 'from', 'users')\n * // → 'select name from users'\n * ```\n */\nexport function buildPhrase(...parts: string[]): string {\n return parts.filter(Boolean).join(' ');\n}\n\n/**\n * Build keyword and marker tables from schemas and language profiles.\n * Extracts translations from the profile's keyword definitions and\n * role marker overrides.\n *\n * @example\n * ```typescript\n * const { keywords, markers } = buildTablesFromProfiles(schemas, profiles);\n * ```\n */\nexport function buildTablesFromProfiles(\n schemas: readonly CommandSchema[],\n profiles: readonly PatternGenLanguageProfile[]\n): { keywords: KeywordTable; markers: MarkerTable } {\n const keywords: KeywordTable = {};\n const markers: MarkerTable = {};\n\n // Build keyword table from profiles\n for (const profile of profiles) {\n for (const [action, kw] of Object.entries(profile.keywords)) {\n if (!keywords[action]) keywords[action] = {};\n keywords[action][profile.code] = kw.primary;\n }\n }\n\n // Build marker table from schema markerOverrides\n for (const schema of schemas) {\n for (const role of schema.roles) {\n if (role.markerOverride) {\n // Use role name as marker key\n const markerKey = role.role;\n if (!markers[markerKey]) markers[markerKey] = {};\n for (const [lang, markerText] of Object.entries(role.markerOverride)) {\n markers[markerKey][lang] = markerText;\n }\n }\n }\n }\n\n // Also extract role markers from profiles\n for (const profile of profiles) {\n if (profile.roleMarkers) {\n for (const [markerKey, markerDef] of Object.entries(profile.roleMarkers)) {\n if (!markers[markerKey]) markers[markerKey] = {};\n markers[markerKey][profile.code] = markerDef.primary;\n }\n }\n }\n\n return { keywords, markers };\n}\n\n/**\n * Detect word order from language profiles.\n * Returns sets of SOV and VSO language codes.\n */\nexport function detectWordOrders(profiles: readonly PatternGenLanguageProfile[]): {\n sovLanguages: Set<string>;\n vsoLanguages: Set<string>;\n} {\n const sovLanguages = new Set<string>();\n const vsoLanguages = new Set<string>();\n\n for (const profile of profiles) {\n if (profile.wordOrder === 'SOV') sovLanguages.add(profile.code);\n if (profile.wordOrder === 'VSO') vsoLanguages.add(profile.code);\n }\n\n return { sovLanguages, vsoLanguages };\n}\n\n/**\n * Create a basic renderer from schemas and profiles.\n *\n * This generates a renderer that handles word-order reordering automatically.\n * For each command, it constructs the output by placing the keyword and\n * role values in the correct order for the target language.\n *\n * For complex domain-specific rendering, implement `NaturalLanguageRenderer`\n * directly instead.\n *\n * @example\n * ```typescript\n * const renderer = createSchemaRenderer(schemas, profiles);\n * renderer.render(node, 'ja'); // → \"users から name 選択\"\n * ```\n */\nexport function createSchemaRenderer(\n schemas: readonly CommandSchema[],\n profiles: readonly PatternGenLanguageProfile[]\n): NaturalLanguageRenderer {\n const tables = buildRenderTables(schemas, profiles);\n\n return {\n render(node: SemanticNode, language: string): string {\n // An action with no schema still has a name — render that rather than\n // nothing. `createDomainRenderer` returns null for this case instead.\n return renderFromSchema(node, language, tables) ?? node.action;\n },\n };\n}\n\n// =============================================================================\n// Domain renderer (hand-written cases + schema fallthrough)\n// =============================================================================\n\n/**\n * Renders a SemanticNode, or returns `null` when the action cannot be rendered.\n *\n * The nullable counterpart to {@link NaturalLanguageRenderer}: `null` means \"I\n * do not know this action\", which callers can act on. A domain that signals the\n * same condition with a sentinel string forces consumers into string matching.\n */\nexport type DomainRenderFn = (node: SemanticNode, language: string) => string | null;\n\n/**\n * Configuration for {@link createDomainRenderer}.\n */\nexport interface DomainRendererConfig {\n /** Schemas for this domain's commands, including any extensions. */\n readonly schemas: readonly CommandSchema[];\n\n /** Language profiles supplying keywords and role markers. */\n readonly profiles: readonly PatternGenLanguageProfile[];\n\n /**\n * Hand-written renderers per action. These take absolute precedence over the\n * schema-driven path, so a domain's existing output is preserved byte for byte.\n *\n * An override returning `null` means \"this action cannot be rendered\" and is\n * passed straight through — it does not fall through to the schema path,\n * since a hand-written renderer knows more about its action than the schema does.\n */\n readonly overrides?: Readonly<Record<string, DomainRenderFn>>;\n}\n\n/**\n * Create a renderer that composes a domain's hand-written per-action renderers\n * with the schema-driven fallback.\n *\n * Resolution order:\n * 1. `overrides[node.action]` — the domain's own rendering, unchanged\n * 2. schema-driven rendering — any action with a schema but no hand-written case\n * 3. `null` — no override and no schema\n *\n * Step 2 is what makes a domain extensible: a consumer that adds a command\n * schema (with per-language keywords in the profiles) gets correct word order,\n * markers and keywords for free, without the domain package having to know\n * about that command.\n *\n * @example\n * ```typescript\n * const render = createDomainRenderer({\n * schemas: allSchemas,\n * profiles: allProfiles,\n * overrides: { select: renderSelect, insert: renderInsert },\n * });\n * render(node, 'ja'); // hand-written for `select`, schema-driven otherwise\n * render(bogusNode, 'en'); // → null\n * ```\n */\nexport function createDomainRenderer(config: DomainRendererConfig): DomainRenderFn {\n const { schemas, profiles, overrides } = config;\n\n // Built on first render — a domain module can construct its renderer at import\n // time without paying for table construction it may never use.\n let tables: RenderTables | undefined;\n\n return (node: SemanticNode, language: string): string | null => {\n const override = overrides?.[node.action];\n if (override) return override(node, language);\n\n tables ??= buildRenderTables(schemas, profiles);\n return renderFromSchema(node, language, tables);\n };\n}\n\n// =============================================================================\n// Shared schema-driven rendering\n// =============================================================================\n\ninterface RenderTables {\n readonly keywords: KeywordTable;\n readonly markers: MarkerTable;\n /** Marker side per role per language, from each profile's roleMarkers. */\n readonly markerPositions: Record<string, Record<string, 'before' | 'after'>>;\n readonly sovLanguages: ReadonlySet<string>;\n readonly schemaMap: ReadonlyMap<string, CommandSchema>;\n}\n\nfunction buildRenderTables(\n schemas: readonly CommandSchema[],\n profiles: readonly PatternGenLanguageProfile[]\n): RenderTables {\n const { keywords, markers } = buildTablesFromProfiles(schemas, profiles);\n const { sovLanguages } = detectWordOrders(profiles);\n\n const markerPositions: Record<string, Record<string, 'before' | 'after'>> = {};\n for (const profile of profiles) {\n for (const [role, markerDef] of Object.entries(profile.roleMarkers ?? {})) {\n if (!markerDef.position) continue;\n markerPositions[role] ??= {};\n markerPositions[role][profile.code] = markerDef.position;\n }\n }\n\n const schemaMap = new Map<string, CommandSchema>();\n for (const s of schemas) schemaMap.set(s.action, s);\n return { keywords, markers, markerPositions, sovLanguages, schemaMap };\n}\n\n/**\n * The one schema-driven rendering algorithm, shared by `createSchemaRenderer`\n * and `createDomainRenderer` so the two can never drift.\n *\n * Returns `null` when the action has no schema.\n */\nfunction renderFromSchema(\n node: SemanticNode,\n language: string,\n tables: RenderTables\n): string | null {\n const schema = tables.schemaMap.get(node.action);\n if (!schema) return null;\n\n const keyword = lookupKeyword(tables.keywords, node.action, language);\n const isSOV = tables.sovLanguages.has(language);\n\n // Order roles by their declared positions, using the SAME comparator pattern\n // generation uses. Rendering in declaration order instead would produce a\n // surface the generated pattern cannot re-parse whenever the two disagree.\n const ordered = sortRolesByWordOrder([...schema.roles], isSOV ? 'SOV' : 'SVO');\n\n // Roles rendered before the verb, and (SOV only) after it.\n const preVerb: string[] = [];\n const postVerb: string[] = [];\n\n for (const role of ordered) {\n let value = extractRoleValue(node, role.role);\n if (!value && role.default !== undefined) {\n value = String(extractValue(role.default));\n }\n // A role with no value is skipped entirely — including its marker. Emitting\n // the marker of an absent role produces dangling text (\"analyze #content as\",\n // \"#content として 分析\"), which is never valid surface syntax. This applies to\n // required roles too: a required role with no value is a malformed node, and\n // a dangling marker is a worse rendering of it than simply leaving it out.\n if (!value) continue;\n\n if (role.quoteMultiword && /\\s/.test(value) && !/^([\"']).*\\1$/.test(value)) {\n value = `\"${value}\"`;\n }\n\n // Marker resolution, most specific first. `renderOverride` for this exact\n // language is the most specific statement; `''` means \"render this role\n // bare\" (a marker that exists only to help the parser). The `'*'` key is a\n // blanket statement about the PROFILE default, so it ranks below a\n // per-language markerOverride — which is how SQL's `get` renders bare in\n // SVO languages while keeping its SOV source particles.\n const markerText =\n role.renderOverride?.[language] ??\n role.markerOverride?.[language] ??\n role.renderOverride?.['*'] ??\n tables.markers[role.role]?.[language];\n\n const markerPosition =\n role.markerPositionOverride?.[language] ??\n role.markerPosition ??\n tables.markerPositions[role.role]?.[language] ??\n (isSOV ? 'after' : 'before');\n\n const bucket = isSOV && role.sovSlot === 'postVerb' ? postVerb : preVerb;\n if (markerText && markerPosition === 'before') {\n bucket.push(markerText, value);\n } else if (markerText) {\n bucket.push(value, markerText);\n } else {\n bucket.push(value);\n }\n }\n\n return isSOV\n ? buildPhrase(...preVerb, keyword, ...postVerb)\n : buildPhrase(keyword, ...preVerb, ...postVerb);\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 { createDomainRenderer, type DomainRenderFn } from '../generation/renderer';\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 /**\n * Language profile for grammar transformation.\n *\n * Optional for `parse()`, `validate()` and `compile()`, but **required for\n * `translate()`** — omitting it makes `translate()` throw for this language.\n */\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 * Per-language vocabulary for a command added via {@link DomainExtension}.\n *\n * This is the same shape a language profile uses, narrowed to the parts a\n * single new command needs.\n */\nexport interface ExtensionVocabulary {\n /** The command's verb in this language. */\n readonly keyword: PatternGenLanguageProfile['keywords'][string];\n /**\n * Markers for roles this language does not already cover in its profile.\n * Usually unnecessary: role markers are shared across a domain's commands.\n */\n readonly roleMarkers?: PatternGenLanguageProfile['roleMarkers'];\n}\n\n/**\n * A command added to a DSL from outside the package that defines it.\n *\n * Supplying a schema plus one vocabulary entry per language is enough to parse,\n * render and translate the command in every one of them — word order, role\n * markers and keyword placement all follow from the schema and the language\n * profiles. `render` and `generate` are only needed when the command's surface\n * form or output cannot be derived.\n *\n * @example\n * ```typescript\n * const research: DomainExtension = {\n * schema: defineCommand({\n * action: 'research',\n * roles: [\n * defineRole({ role: 'patient', required: true, expectedTypes: ['expression'] }),\n * defineRole({\n * role: 'source', required: true, expectedTypes: ['expression'],\n * markerOverride: { en: 'from', ja: 'から', ar: 'من' },\n * }),\n * ],\n * }),\n * vocabulary: {\n * en: { keyword: { primary: 'research' } },\n * ja: { keyword: { primary: '調査' } },\n * ar: { keyword: { primary: 'ابحث' } },\n * },\n * };\n *\n * const llm = createLLMDSL({ extensions: [research] });\n * llm.parse('research \"climate\" from #wiki', 'en');\n * llm.render(node, 'ja'); // → '\"climate\" #wiki から 調査'\n * ```\n */\nexport interface DomainExtension {\n /** Schema for the new command. Its action must not collide with an existing one. */\n readonly schema: CommandSchema;\n\n /**\n * Vocabulary per language code. Codes must be configured on the DSL; an\n * unknown code is a configuration error, not a silent no-op.\n *\n * A subset is allowed — a command can be added in six of a DSL's eleven\n * languages. The languages left out simply do not parse it, so vocabulary\n * can be filled in over time rather than all at once.\n */\n readonly vocabulary: Readonly<Record<string, ExtensionVocabulary>>;\n\n /** Custom rendering for this action; takes precedence over the schema-driven path. */\n readonly render?: DomainRenderFn;\n\n /** Custom code generation for this action; takes precedence over the DSL's generator. */\n readonly 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 /**\n * The domain's natural-language renderer, consulted by {@link MultilingualDSL.render}.\n * Actions it returns `null` for fall through to the schema-driven renderer.\n */\n readonly renderer?: DomainRenderFn;\n\n /**\n * Commands added from outside this package. Their schemas and vocabulary are\n * merged into the DSL before pattern generation, so they parse, render and\n * compile like built-in commands.\n */\n readonly extensions?: readonly DomainExtension[];\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 /**\n * Render a parsed node back to natural language.\n *\n * Returns `null` when the action cannot be rendered — no custom renderer, no\n * domain renderer, and no schema. Optional so that third-party implementers\n * of this interface are not broken by its addition; `createMultilingualDSL`\n * always provides it.\n */\n render?(node: SemanticNode, language: string): string | null;\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 private partiallyTranslatedActions: ReadonlySet<string>;\n\n /**\n * @param partiallyTranslatedActions Actions permitted to lack a keyword in\n * some configured languages — extension commands, which may be added for a\n * subset of the DSL's languages. A built-in command missing a keyword stays\n * an error, since that is a domain-authoring mistake.\n */\n constructor(config: DSLConfig, partiallyTranslatedActions: ReadonlySet<string> = new Set()) {\n this.schemas = config.schemas;\n this.partiallyTranslatedActions = partiallyTranslatedActions;\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 if (\n this.partiallyTranslatedActions.has(schema.action) &&\n !lang.patternProfile.keywords[schema.action]\n ) {\n continue; // this extension command was not translated into this language\n }\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 profileProvider: ProfileProvider;\n private codeGenerator?: CodeGenerator;\n private schemaLookup: SchemaLookup;\n private domainRenderer?: DomainRenderFn;\n private extensionRenderers: Map<string, DomainRenderFn>;\n private schemaFallbackRenderer: DomainRenderFn;\n\n constructor(\n config: DSLConfig,\n registry: DSLRegistry,\n transformer: GrammarTransformer,\n profileProvider: ProfileProvider\n ) {\n this.registry = registry;\n this.matcher = new PatternMatcher();\n this.transformer = transformer;\n this.profileProvider = profileProvider;\n if (config.codeGenerator) {\n this.codeGenerator = config.codeGenerator;\n }\n if (config.renderer) {\n this.domainRenderer = config.renderer;\n }\n\n this.extensionRenderers = new Map();\n for (const extension of config.extensions ?? []) {\n if (extension.render) this.extensionRenderers.set(extension.schema.action, extension.render);\n }\n\n // Last resort for render(): covers extension commands with no custom\n // renderer, and any built-in action the domain renderer declines. Lazy, so\n // a DSL that never renders pays nothing.\n this.schemaFallbackRenderer = createDomainRenderer({\n schemas: config.schemas,\n profiles: config.languages.map(l => l.patternProfile),\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\n // translate() is the only path that needs grammar profiles; parse/validate/\n // compile work without them. `grammarProfile` is optional on LanguageConfig,\n // so omitting it fails here rather than at construction — name the missing\n // field instead of leaving the transformer's bare \"No profile found\".\n for (const language of [fromLanguage, toLanguage]) {\n if (!this.profileProvider.getProfile(language)) {\n throw new Error(\n `translate() requires a grammar profile for language \"${language}\", but none is ` +\n `configured. Set 'grammarProfile' on the LanguageConfig for \"${language}\" in ` +\n `createMultilingualDSL() (parse/validate/compile do not need it), or inject a ` +\n `custom 'profileProvider'.`\n );\n }\n }\n\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 render(node: SemanticNode, language: string): string | null {\n // 1. An extension's own renderer, if it supplied one\n const extensionRenderer = this.extensionRenderers.get(node.action);\n if (extensionRenderer) {\n const rendered = extensionRenderer(node, language);\n if (rendered != null) return rendered;\n }\n\n // 2. The domain's renderer — its hand-written cases are authoritative\n if (this.domainRenderer) {\n const rendered = this.domainRenderer(node, language);\n if (rendered != null) return rendered;\n }\n\n // 3. Schema-driven, which is how extension commands render by default\n return this.schemaFallbackRenderer(node, language);\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\n/**\n * Fold extensions into the config so that everything downstream — pattern\n * generation, the dictionary, explicit-syntax lookup, rendering — sees\n * extension commands exactly as it sees built-in ones.\n *\n * Done up front rather than by mutating a live DSL: `DSLRegistry` generates\n * every language's patterns in its constructor, so a command registered later\n * would compile and render but silently fail to parse.\n */\nfunction applyExtensions(config: DSLConfig): DSLConfig {\n const extensions = config.extensions;\n if (!extensions || extensions.length === 0) return config;\n\n const configuredLanguages = new Set(config.languages.map(l => l.code));\n const actions = new Set(config.schemas.map(s => s.action));\n\n for (const extension of extensions) {\n const { action } = extension.schema;\n if (actions.has(action)) {\n throw new Error(\n `Extension command \"${action}\" collides with a command this DSL already defines. ` +\n `Pick a different action name.`\n );\n }\n actions.add(action);\n\n for (const code of Object.keys(extension.vocabulary)) {\n if (!configuredLanguages.has(code)) {\n throw new Error(\n `Extension command \"${action}\" supplies vocabulary for language \"${code}\", which is ` +\n `not configured on this DSL. Configured languages: ` +\n `${[...configuredLanguages].join(', ')}.`\n );\n }\n }\n }\n\n const schemas = [...config.schemas, ...extensions.map(e => e.schema)];\n\n const languages = config.languages.map(lang => {\n const keywords = { ...lang.patternProfile.keywords };\n let roleMarkers = lang.patternProfile.roleMarkers;\n\n for (const extension of extensions) {\n const vocabulary = extension.vocabulary[lang.code];\n if (!vocabulary) continue;\n keywords[extension.schema.action] = { ...vocabulary.keyword };\n if (vocabulary.roleMarkers) {\n roleMarkers = { ...roleMarkers, ...vocabulary.roleMarkers };\n }\n }\n\n return {\n ...lang,\n patternProfile: {\n ...lang.patternProfile,\n keywords,\n ...(roleMarkers !== undefined && { roleMarkers }),\n },\n };\n });\n\n // Extension code generators dispatch ahead of the domain's own generator,\n // whose `default` branch would otherwise throw on an action it never knew.\n const extensionGenerators = new Map(\n extensions.filter(e => e.generate).map(e => [e.schema.action, e.generate!])\n );\n const baseGenerator = config.codeGenerator;\n const codeGenerator: CodeGenerator | undefined =\n extensionGenerators.size > 0\n ? {\n generate(node: SemanticNode): string {\n const generate = extensionGenerators.get(node.action);\n if (generate) return generate(node);\n if (!baseGenerator) {\n throw new Error(`No code generator for action \"${node.action}\"`);\n }\n return baseGenerator.generate(node);\n },\n }\n : baseGenerator;\n\n return {\n ...config,\n schemas,\n languages,\n ...(codeGenerator !== undefined && { codeGenerator }),\n };\n}\n\nexport function createMultilingualDSL(config: DSLConfig): MultilingualDSL {\n // Extensions must be folded in before anything reads the config\n const effectiveConfig = applyExtensions(config);\n const extensionActions = new Set((config.extensions ?? []).map(e => e.schema.action));\n\n // Create or use provided dictionary\n const dictionary = effectiveConfig.dictionary ?? createDefaultDictionary(effectiveConfig);\n\n // Create or use provided profile provider\n const profileProvider =\n effectiveConfig.profileProvider ?? createDefaultProfileProvider(effectiveConfig);\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(effectiveConfig, extensionActions);\n return new MultilingualDSLImpl(effectiveConfig, registry, transformer, profileProvider);\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. A selector containing a space, a combinator (\\`>\\` \\`+\\` \\`~\\`), or a comma must use a selector literal: \\`patient:<ul > li/>\\`, \\`patient:<.a, .b/>\\`\n7. Inside a structural role (\\`body\\`, \\`then\\`, \\`else\\`, \\`condition\\`, \\`loop-body\\`, \\`variable\\`, \\`catch\\`, \\`finally\\`) a \\`[...]\\` value is always a nested command. Write an attribute selector there as \\`condition:<[data-active]/>\\`\n8. 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 literal | Delimited by \\`<\\` and \\`/>\\` | \\`<ul > li/>\\`, \\`<.a, .b/>\\`, \\`<[data-id]/>\\` |\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 { MultilingualDSL, CompileResult, ValidationResult } from './create-dsl';\nimport type { NaturalLanguageRenderer, DomainRenderFn } 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 * The function form may return `null` for an action it cannot render; the\n * translate tool reports that as an unsuccessful translation.\n */\n readonly getRenderer?: () =>\n NaturalLanguageRenderer | DomainRenderFn | Promise<NaturalLanguageRenderer | DomainRenderFn>;\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<string, NaturalLanguageRenderer | DomainRenderFn>();\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 | DomainRenderFn | 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 } else if (dsl.render) {\n // A descriptor without an explicit renderer can still render: the DSL\n // knows its own domain renderer and its schema fallback.\n try {\n rendered = dsl.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,KA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AS,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"]}
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/generation/renderer.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 } | 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, postVerb roles...]\n else if (profile.wordOrder === 'SOV') {\n // `sovSlot: 'postVerb'` moves a role AFTER the verb, which is what the\n // renderer does (`renderer.ts` buckets by the same field). Generation has\n // to mirror it: a role the renderer writes post-verb but the pattern\n // expects pre-verb produces a faithful surface its own parser drops the\n // argument from — voice's `戻る 2` re-parsing as a bare `back`.\n const preVerb: PatternToken[] = [];\n const postVerb: PatternToken[] = [];\n\n for (const role of sortedRoles) {\n addRoleWithMarker(role.sovSlot === 'postVerb' ? postVerb : preVerb, role, profile);\n }\n\n tokens.push(...preVerb, keywordToken, ...postVerb);\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 *\n * Exported so the renderer sorts with exactly this comparator — a rendered\n * surface whose role order differs from the generated pattern would not re-parse.\n */\nexport function 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 isSOV = profile.wordOrder === 'SOV';\n const preVerb: string[] = [];\n const postVerb: string[] = [];\n\n // Order roles the same way buildTokens does (descending position). Iterating\n // declaration order here would disagree with the token order whenever a\n // schema's roles are declared in a different order than their positions imply.\n const sortedRoles = sortRolesByWordOrder(schema.roles, profile.wordOrder);\n for (const role of sortedRoles) {\n const marker = getMarkerForRole(role, profile);\n const roleName = `{${role.role}}`;\n // Same pre/post-verb split buildTokens applies, so the documented format\n // string keeps describing the tokens it is generated alongside.\n const bucket = isSOV && role.sovSlot === 'postVerb' ? postVerb : preVerb;\n\n if (marker) {\n const markerInfo = profile.roleMarkers?.[role.role];\n if (markerInfo?.position === 'after') {\n bucket.push(`${roleName} ${marker}`);\n } else {\n bucket.push(`${marker} ${roleName}`);\n }\n } else {\n bucket.push(roleName);\n }\n }\n\n return (isSOV ? [...preVerb, keyword, ...postVerb] : [keyword, ...preVerb, ...postVerb]).join(\n ' '\n );\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 * Natural Language Renderer\n *\n * Interface and utilities for rendering SemanticNode → human-readable text\n * in any supported language. This is the inverse of parsing: it converts\n * a language-neutral semantic representation back to natural-language syntax.\n *\n * Every domain that supports `translate()` needs a renderer.\n */\n\nimport type { SemanticNode } from '../core/types';\nimport { extractRoleValue, extractValue } from '../core/types';\nimport type { CommandSchema } from '../schema';\nimport { sortRolesByWordOrder, type PatternGenLanguageProfile } from './pattern-generator';\n\n// =============================================================================\n// Renderer Interface\n// =============================================================================\n\n/**\n * Renders a SemanticNode to human-readable text in a target language.\n */\nexport interface NaturalLanguageRenderer {\n render(node: SemanticNode, language: string): string;\n}\n\n// =============================================================================\n// Renderer Helpers\n// =============================================================================\n\n/**\n * Keyword table: action → language → translated keyword.\n *\n * @example\n * ```typescript\n * const KEYWORDS: KeywordTable = {\n * select: { en: 'select', ja: '選択', es: 'seleccionar' },\n * insert: { en: 'insert', ja: '挿入', es: 'insertar' },\n * };\n * ```\n */\nexport type KeywordTable = Record<string, Record<string, string>>;\n\n/**\n * Marker table: marker name → language → translated marker.\n *\n * @example\n * ```typescript\n * const MARKERS: MarkerTable = {\n * from: { en: 'from', ja: 'から', es: 'de' },\n * into: { en: 'into', ja: 'に', es: 'en' },\n * };\n * ```\n */\nexport type MarkerTable = Record<string, Record<string, string>>;\n\n/**\n * Configuration for building a renderer from schemas and profiles.\n */\nexport interface RendererConfig {\n /** Command keyword translations per language */\n readonly keywords: KeywordTable;\n\n /** Role marker translations per language (prepositions/particles) */\n readonly markers: MarkerTable;\n\n /** Languages that use SOV word order */\n readonly sovLanguages: ReadonlySet<string>;\n\n /** Languages that use VSO word order (optional, defaults to empty) */\n readonly vsoLanguages?: ReadonlySet<string>;\n}\n\n/**\n * Look up a command keyword in the target language.\n * Falls back to the key itself if no translation found.\n */\nexport function lookupKeyword(keywords: KeywordTable, action: string, language: string): string {\n return keywords[action]?.[language] ?? action;\n}\n\n/**\n * Look up a role marker in the target language.\n * Falls back to the key itself if no translation found.\n */\nexport function lookupMarker(markers: MarkerTable, marker: string, language: string): string {\n return markers[marker]?.[language] ?? marker;\n}\n\n/**\n * Build a phrase from parts, filtering empty strings and joining with space.\n *\n * @example\n * ```typescript\n * buildPhrase('select', '', 'name', 'from', 'users')\n * // → 'select name from users'\n * ```\n */\nexport function buildPhrase(...parts: string[]): string {\n return parts.filter(Boolean).join(' ');\n}\n\n/**\n * Build keyword and marker tables from schemas and language profiles.\n * Extracts translations from the profile's keyword definitions and\n * role marker overrides.\n *\n * @example\n * ```typescript\n * const { keywords, markers } = buildTablesFromProfiles(schemas, profiles);\n * ```\n */\nexport function buildTablesFromProfiles(\n schemas: readonly CommandSchema[],\n profiles: readonly PatternGenLanguageProfile[]\n): { keywords: KeywordTable; markers: MarkerTable } {\n const keywords: KeywordTable = {};\n const markers: MarkerTable = {};\n\n // Build keyword table from profiles\n for (const profile of profiles) {\n for (const [action, kw] of Object.entries(profile.keywords)) {\n if (!keywords[action]) keywords[action] = {};\n keywords[action][profile.code] = kw.primary;\n }\n }\n\n // Build marker table from schema markerOverrides\n for (const schema of schemas) {\n for (const role of schema.roles) {\n if (role.markerOverride) {\n // Use role name as marker key\n const markerKey = role.role;\n if (!markers[markerKey]) markers[markerKey] = {};\n for (const [lang, markerText] of Object.entries(role.markerOverride)) {\n markers[markerKey][lang] = markerText;\n }\n }\n }\n }\n\n // Also extract role markers from profiles\n for (const profile of profiles) {\n if (profile.roleMarkers) {\n for (const [markerKey, markerDef] of Object.entries(profile.roleMarkers)) {\n if (!markers[markerKey]) markers[markerKey] = {};\n markers[markerKey][profile.code] = markerDef.primary;\n }\n }\n }\n\n return { keywords, markers };\n}\n\n/**\n * Detect word order from language profiles.\n * Returns sets of SOV and VSO language codes.\n */\nexport function detectWordOrders(profiles: readonly PatternGenLanguageProfile[]): {\n sovLanguages: Set<string>;\n vsoLanguages: Set<string>;\n} {\n const sovLanguages = new Set<string>();\n const vsoLanguages = new Set<string>();\n\n for (const profile of profiles) {\n if (profile.wordOrder === 'SOV') sovLanguages.add(profile.code);\n if (profile.wordOrder === 'VSO') vsoLanguages.add(profile.code);\n }\n\n return { sovLanguages, vsoLanguages };\n}\n\n/**\n * Create a basic renderer from schemas and profiles.\n *\n * This generates a renderer that handles word-order reordering automatically.\n * For each command, it constructs the output by placing the keyword and\n * role values in the correct order for the target language.\n *\n * For complex domain-specific rendering, implement `NaturalLanguageRenderer`\n * directly instead.\n *\n * @example\n * ```typescript\n * const renderer = createSchemaRenderer(schemas, profiles);\n * renderer.render(node, 'ja'); // → \"users から name 選択\"\n * ```\n */\nexport function createSchemaRenderer(\n schemas: readonly CommandSchema[],\n profiles: readonly PatternGenLanguageProfile[]\n): NaturalLanguageRenderer {\n const tables = buildRenderTables(schemas, profiles);\n\n return {\n render(node: SemanticNode, language: string): string {\n // An action with no schema still has a name — render that rather than\n // nothing. `createDomainRenderer` returns null for this case instead.\n return renderFromSchema(node, language, tables) ?? node.action;\n },\n };\n}\n\n// =============================================================================\n// Domain renderer (hand-written cases + schema fallthrough)\n// =============================================================================\n\n/**\n * Renders a SemanticNode, or returns `null` when the action cannot be rendered.\n *\n * The nullable counterpart to {@link NaturalLanguageRenderer}: `null` means \"I\n * do not know this action\", which callers can act on. A domain that signals the\n * same condition with a sentinel string forces consumers into string matching.\n */\nexport type DomainRenderFn = (node: SemanticNode, language: string) => string | null;\n\n/**\n * Configuration for {@link createDomainRenderer}.\n */\nexport interface DomainRendererConfig {\n /** Schemas for this domain's commands, including any extensions. */\n readonly schemas: readonly CommandSchema[];\n\n /** Language profiles supplying keywords and role markers. */\n readonly profiles: readonly PatternGenLanguageProfile[];\n\n /**\n * Hand-written renderers per action. These take absolute precedence over the\n * schema-driven path, so a domain's existing output is preserved byte for byte.\n *\n * An override returning `null` means \"this action cannot be rendered\" and is\n * passed straight through — it does not fall through to the schema path,\n * since a hand-written renderer knows more about its action than the schema does.\n */\n readonly overrides?: Readonly<Record<string, DomainRenderFn>>;\n}\n\n/**\n * Create a renderer that composes a domain's hand-written per-action renderers\n * with the schema-driven fallback.\n *\n * Resolution order:\n * 1. `overrides[node.action]` — the domain's own rendering, unchanged\n * 2. schema-driven rendering — any action with a schema but no hand-written case\n * 3. `null` — no override and no schema\n *\n * Step 2 is what makes a domain extensible: a consumer that adds a command\n * schema (with per-language keywords in the profiles) gets correct word order,\n * markers and keywords for free, without the domain package having to know\n * about that command.\n *\n * @example\n * ```typescript\n * const render = createDomainRenderer({\n * schemas: allSchemas,\n * profiles: allProfiles,\n * overrides: { select: renderSelect, insert: renderInsert },\n * });\n * render(node, 'ja'); // hand-written for `select`, schema-driven otherwise\n * render(bogusNode, 'en'); // → null\n * ```\n */\nexport function createDomainRenderer(config: DomainRendererConfig): DomainRenderFn {\n const { schemas, profiles, overrides } = config;\n\n // Built on first render — a domain module can construct its renderer at import\n // time without paying for table construction it may never use.\n let tables: RenderTables | undefined;\n\n return (node: SemanticNode, language: string): string | null => {\n const override = overrides?.[node.action];\n if (override) return override(node, language);\n\n tables ??= buildRenderTables(schemas, profiles);\n return renderFromSchema(node, language, tables);\n };\n}\n\n// =============================================================================\n// Shared schema-driven rendering\n// =============================================================================\n\ninterface RenderTables {\n readonly keywords: KeywordTable;\n readonly markers: MarkerTable;\n /** Marker side per role per language, from each profile's roleMarkers. */\n readonly markerPositions: Record<string, Record<string, 'before' | 'after'>>;\n readonly sovLanguages: ReadonlySet<string>;\n readonly schemaMap: ReadonlyMap<string, CommandSchema>;\n}\n\nfunction buildRenderTables(\n schemas: readonly CommandSchema[],\n profiles: readonly PatternGenLanguageProfile[]\n): RenderTables {\n const { keywords, markers } = buildTablesFromProfiles(schemas, profiles);\n const { sovLanguages } = detectWordOrders(profiles);\n\n const markerPositions: Record<string, Record<string, 'before' | 'after'>> = {};\n for (const profile of profiles) {\n for (const [role, markerDef] of Object.entries(profile.roleMarkers ?? {})) {\n if (!markerDef.position) continue;\n markerPositions[role] ??= {};\n markerPositions[role][profile.code] = markerDef.position;\n }\n }\n\n const schemaMap = new Map<string, CommandSchema>();\n for (const s of schemas) schemaMap.set(s.action, s);\n return { keywords, markers, markerPositions, sovLanguages, schemaMap };\n}\n\n/**\n * The one schema-driven rendering algorithm, shared by `createSchemaRenderer`\n * and `createDomainRenderer` so the two can never drift.\n *\n * Returns `null` when the action has no schema.\n */\nfunction renderFromSchema(\n node: SemanticNode,\n language: string,\n tables: RenderTables\n): string | null {\n const schema = tables.schemaMap.get(node.action);\n if (!schema) return null;\n\n const keyword = lookupKeyword(tables.keywords, node.action, language);\n const isSOV = tables.sovLanguages.has(language);\n\n // Order roles by their declared positions, using the SAME comparator pattern\n // generation uses. Rendering in declaration order instead would produce a\n // surface the generated pattern cannot re-parse whenever the two disagree.\n const ordered = sortRolesByWordOrder([...schema.roles], isSOV ? 'SOV' : 'SVO');\n\n // Roles rendered before the verb, and (SOV only) after it.\n const preVerb: string[] = [];\n const postVerb: string[] = [];\n\n for (const role of ordered) {\n let value = extractRoleValue(node, role.role);\n if (!value && role.default !== undefined) {\n value = String(extractValue(role.default));\n }\n // A role with no value is skipped entirely — including its marker. Emitting\n // the marker of an absent role produces dangling text (\"analyze #content as\",\n // \"#content として 分析\"), which is never valid surface syntax. This applies to\n // required roles too: a required role with no value is a malformed node, and\n // a dangling marker is a worse rendering of it than simply leaving it out.\n if (!value) continue;\n\n if (role.quoteMultiword && /\\s/.test(value) && !/^([\"']).*\\1$/.test(value)) {\n value = `\"${value}\"`;\n }\n\n // Marker resolution, most specific first. `renderOverride` for this exact\n // language is the most specific statement; `''` means \"render this role\n // bare\" (a marker that exists only to help the parser). The `'*'` key is a\n // blanket statement about the PROFILE default, so it ranks below a\n // per-language markerOverride — which is how SQL's `get` renders bare in\n // SVO languages while keeping its SOV source particles.\n const markerText =\n role.renderOverride?.[language] ??\n role.markerOverride?.[language] ??\n role.renderOverride?.['*'] ??\n tables.markers[role.role]?.[language];\n\n const markerPosition =\n role.markerPositionOverride?.[language] ??\n role.markerPosition ??\n tables.markerPositions[role.role]?.[language] ??\n (isSOV ? 'after' : 'before');\n\n const bucket = isSOV && role.sovSlot === 'postVerb' ? postVerb : preVerb;\n if (markerText && markerPosition === 'before') {\n bucket.push(markerText, value);\n } else if (markerText) {\n bucket.push(value, markerText);\n } else {\n bucket.push(value);\n }\n }\n\n return isSOV\n ? buildPhrase(...preVerb, keyword, ...postVerb)\n : buildPhrase(keyword, ...preVerb, ...postVerb);\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 { createDomainRenderer, type DomainRenderFn } from '../generation/renderer';\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 /**\n * Language profile for grammar transformation.\n *\n * Optional everywhere: `translate()` primarily works parse→render through\n * the schema-driven renderer, which needs no grammar profile. Configure this\n * only to enable the whole-string GrammarTransformer FALLBACK for input the\n * pattern matcher cannot parse (or actions render() cannot cover).\n */\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 * Per-language vocabulary for a command added via {@link DomainExtension}.\n *\n * This is the same shape a language profile uses, narrowed to the parts a\n * single new command needs.\n */\nexport interface ExtensionVocabulary {\n /** The command's verb in this language. */\n readonly keyword: PatternGenLanguageProfile['keywords'][string];\n /**\n * Markers for roles this language does not already cover in its profile.\n * Usually unnecessary: role markers are shared across a domain's commands.\n */\n readonly roleMarkers?: PatternGenLanguageProfile['roleMarkers'];\n}\n\n/**\n * A command added to a DSL from outside the package that defines it.\n *\n * Supplying a schema plus one vocabulary entry per language is enough to parse,\n * render and translate the command in every one of them — word order, role\n * markers and keyword placement all follow from the schema and the language\n * profiles. `render` and `generate` are only needed when the command's surface\n * form or output cannot be derived.\n *\n * @example\n * ```typescript\n * const research: DomainExtension = {\n * schema: defineCommand({\n * action: 'research',\n * roles: [\n * defineRole({ role: 'patient', required: true, expectedTypes: ['expression'] }),\n * defineRole({\n * role: 'source', required: true, expectedTypes: ['expression'],\n * markerOverride: { en: 'from', ja: 'から', ar: 'من' },\n * }),\n * ],\n * }),\n * vocabulary: {\n * en: { keyword: { primary: 'research' } },\n * ja: { keyword: { primary: '調査' } },\n * ar: { keyword: { primary: 'ابحث' } },\n * },\n * };\n *\n * const llm = createLLMDSL({ extensions: [research] });\n * llm.parse('research \"climate\" from #wiki', 'en');\n * llm.render(node, 'ja'); // → '\"climate\" #wiki から 調査'\n * ```\n */\nexport interface DomainExtension {\n /** Schema for the new command. Its action must not collide with an existing one. */\n readonly schema: CommandSchema;\n\n /**\n * Vocabulary per language code. Codes must be configured on the DSL; an\n * unknown code is a configuration error, not a silent no-op.\n *\n * A subset is allowed — a command can be added in six of a DSL's eleven\n * languages. The languages left out simply do not parse it, so vocabulary\n * can be filled in over time rather than all at once.\n */\n readonly vocabulary: Readonly<Record<string, ExtensionVocabulary>>;\n\n /** Custom rendering for this action; takes precedence over the schema-driven path. */\n readonly render?: DomainRenderFn;\n\n /** Custom code generation for this action; takes precedence over the DSL's generator. */\n readonly 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 /**\n * The domain's natural-language renderer, consulted by {@link MultilingualDSL.render}.\n * Actions it returns `null` for fall through to the schema-driven renderer.\n */\n readonly renderer?: DomainRenderFn;\n\n /**\n * Commands added from outside this package. Their schemas and vocabulary are\n * merged into the DSL before pattern generation, so they parse, render and\n * compile like built-in commands.\n */\n readonly extensions?: readonly DomainExtension[];\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 /**\n * Render a parsed node back to natural language.\n *\n * Returns `null` when the action cannot be rendered — no custom renderer, no\n * domain renderer, and no schema. Optional so that third-party implementers\n * of this interface are not broken by its addition; `createMultilingualDSL`\n * always provides it.\n */\n render?(node: SemanticNode, language: string): string | null;\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 private partiallyTranslatedActions: ReadonlySet<string>;\n\n /**\n * @param partiallyTranslatedActions Actions permitted to lack a keyword in\n * some configured languages — extension commands, which may be added for a\n * subset of the DSL's languages. A built-in command missing a keyword stays\n * an error, since that is a domain-authoring mistake.\n */\n constructor(config: DSLConfig, partiallyTranslatedActions: ReadonlySet<string> = new Set()) {\n this.schemas = config.schemas;\n this.partiallyTranslatedActions = partiallyTranslatedActions;\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 if (\n this.partiallyTranslatedActions.has(schema.action) &&\n !lang.patternProfile.keywords[schema.action]\n ) {\n continue; // this extension command was not translated into this language\n }\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 profileProvider: ProfileProvider;\n private codeGenerator?: CodeGenerator;\n private schemaLookup: SchemaLookup;\n private domainRenderer?: DomainRenderFn;\n private extensionRenderers: Map<string, DomainRenderFn>;\n private schemaFallbackRenderer: DomainRenderFn;\n\n constructor(\n config: DSLConfig,\n registry: DSLRegistry,\n transformer: GrammarTransformer,\n profileProvider: ProfileProvider\n ) {\n this.registry = registry;\n this.matcher = new PatternMatcher();\n this.transformer = transformer;\n this.profileProvider = profileProvider;\n if (config.codeGenerator) {\n this.codeGenerator = config.codeGenerator;\n }\n if (config.renderer) {\n this.domainRenderer = config.renderer;\n }\n\n this.extensionRenderers = new Map();\n for (const extension of config.extensions ?? []) {\n if (extension.render) this.extensionRenderers.set(extension.schema.action, extension.render);\n }\n\n // Last resort for render(): covers extension commands with no custom\n // renderer, and any built-in action the domain renderer declines. Lazy, so\n // a DSL that never renders pays nothing.\n this.schemaFallbackRenderer = createDomainRenderer({\n schemas: config.schemas,\n profiles: config.languages.map(l => l.patternProfile),\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\n // Primary route: parse in the source language, render in the target — the\n // same parse→render path DomainRegistry.translate uses. The schema-driven\n // renderer covers every configured language, so this needs NO grammar\n // profiles (before 2026-08 translate() required them and therefore threw\n // for every domain in the family — none configures one).\n let node: SemanticNode;\n try {\n node = this.parseWithConfidence(input, fromLanguage).node;\n } catch (parseError) {\n // Whole-string grammar transformation can sometimes translate input the\n // pattern matcher cannot parse — but only when profiles are configured.\n if (this.hasGrammarProfile(fromLanguage) && this.hasGrammarProfile(toLanguage)) {\n return this.transformer.transform(input, fromLanguage, toLanguage);\n }\n throw parseError;\n }\n\n // Only consult render() for a CONFIGURED target language — the schema\n // renderer's lookup tables fall back to raw action/marker names for\n // unknown languages, which would silently return wrong-language output.\n const rendered = this.registry.getSupportedLanguages().includes(toLanguage)\n ? this.render(node, toLanguage)\n : null;\n if (rendered != null) return rendered;\n\n // render() covered nothing for this action/language pair; fall back to the\n // grammar transformer when profiles exist, otherwise name both remedies.\n if (this.hasGrammarProfile(fromLanguage) && this.hasGrammarProfile(toLanguage)) {\n return this.transformer.transform(input, fromLanguage, toLanguage);\n }\n throw new Error(\n `translate() could not render action \"${node.action}\" in language \"${toLanguage}\": no ` +\n `custom renderer, domain renderer, or schema pattern covers it, and no grammar ` +\n `profile is configured for the transformer fallback. Either add \"${toLanguage}\" to ` +\n `the DSL's languages/renderer, or set 'grammarProfile' on its LanguageConfig in ` +\n `createMultilingualDSL() (parse/validate/compile do not need it).`\n );\n }\n\n private hasGrammarProfile(language: string): boolean {\n return this.profileProvider.getProfile(language) != null;\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 render(node: SemanticNode, language: string): string | null {\n // 1. An extension's own renderer, if it supplied one\n const extensionRenderer = this.extensionRenderers.get(node.action);\n if (extensionRenderer) {\n const rendered = extensionRenderer(node, language);\n if (rendered != null) return rendered;\n }\n\n // 2. The domain's renderer — its hand-written cases are authoritative\n if (this.domainRenderer) {\n const rendered = this.domainRenderer(node, language);\n if (rendered != null) return rendered;\n }\n\n // 3. Schema-driven, which is how extension commands render by default\n return this.schemaFallbackRenderer(node, language);\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\n/**\n * Fold extensions into the config so that everything downstream — pattern\n * generation, the dictionary, explicit-syntax lookup, rendering — sees\n * extension commands exactly as it sees built-in ones.\n *\n * Done up front rather than by mutating a live DSL: `DSLRegistry` generates\n * every language's patterns in its constructor, so a command registered later\n * would compile and render but silently fail to parse.\n */\nfunction applyExtensions(config: DSLConfig): DSLConfig {\n const extensions = config.extensions;\n if (!extensions || extensions.length === 0) return config;\n\n const configuredLanguages = new Set(config.languages.map(l => l.code));\n const actions = new Set(config.schemas.map(s => s.action));\n\n for (const extension of extensions) {\n const { action } = extension.schema;\n if (actions.has(action)) {\n throw new Error(\n `Extension command \"${action}\" collides with a command this DSL already defines. ` +\n `Pick a different action name.`\n );\n }\n actions.add(action);\n\n for (const code of Object.keys(extension.vocabulary)) {\n if (!configuredLanguages.has(code)) {\n throw new Error(\n `Extension command \"${action}\" supplies vocabulary for language \"${code}\", which is ` +\n `not configured on this DSL. Configured languages: ` +\n `${[...configuredLanguages].join(', ')}.`\n );\n }\n }\n }\n\n const schemas = [...config.schemas, ...extensions.map(e => e.schema)];\n\n const languages = config.languages.map(lang => {\n const keywords = { ...lang.patternProfile.keywords };\n let roleMarkers = lang.patternProfile.roleMarkers;\n\n for (const extension of extensions) {\n const vocabulary = extension.vocabulary[lang.code];\n if (!vocabulary) continue;\n keywords[extension.schema.action] = { ...vocabulary.keyword };\n if (vocabulary.roleMarkers) {\n roleMarkers = { ...roleMarkers, ...vocabulary.roleMarkers };\n }\n }\n\n return {\n ...lang,\n patternProfile: {\n ...lang.patternProfile,\n keywords,\n ...(roleMarkers !== undefined && { roleMarkers }),\n },\n };\n });\n\n // Extension code generators dispatch ahead of the domain's own generator,\n // whose `default` branch would otherwise throw on an action it never knew.\n const extensionGenerators = new Map(\n extensions.filter(e => e.generate).map(e => [e.schema.action, e.generate!])\n );\n const baseGenerator = config.codeGenerator;\n const codeGenerator: CodeGenerator | undefined =\n extensionGenerators.size > 0\n ? {\n generate(node: SemanticNode): string {\n const generate = extensionGenerators.get(node.action);\n if (generate) return generate(node);\n if (!baseGenerator) {\n throw new Error(`No code generator for action \"${node.action}\"`);\n }\n return baseGenerator.generate(node);\n },\n }\n : baseGenerator;\n\n return {\n ...config,\n schemas,\n languages,\n ...(codeGenerator !== undefined && { codeGenerator }),\n };\n}\n\nexport function createMultilingualDSL(config: DSLConfig): MultilingualDSL {\n // Extensions must be folded in before anything reads the config\n const effectiveConfig = applyExtensions(config);\n const extensionActions = new Set((config.extensions ?? []).map(e => e.schema.action));\n\n // Create or use provided dictionary\n const dictionary = effectiveConfig.dictionary ?? createDefaultDictionary(effectiveConfig);\n\n // Create or use provided profile provider\n const profileProvider =\n effectiveConfig.profileProvider ?? createDefaultProfileProvider(effectiveConfig);\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(effectiveConfig, extensionActions);\n return new MultilingualDSLImpl(effectiveConfig, registry, transformer, profileProvider);\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. A selector containing a space, a combinator (\\`>\\` \\`+\\` \\`~\\`), or a comma must use a selector literal: \\`patient:<ul > li/>\\`, \\`patient:<.a, .b/>\\`\n7. Inside a structural role (\\`body\\`, \\`then\\`, \\`else\\`, \\`condition\\`, \\`loop-body\\`, \\`variable\\`, \\`catch\\`, \\`finally\\`) a \\`[...]\\` value is always a nested command. Write an attribute selector there as \\`condition:<[data-active]/>\\`\n8. 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 literal | Delimited by \\`<\\` and \\`/>\\` | \\`<ul > li/>\\`, \\`<.a, .b/>\\`, \\`<[data-id]/>\\` |\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 { MultilingualDSL, CompileResult, ValidationResult } from './create-dsl';\nimport type { NaturalLanguageRenderer, DomainRenderFn } 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 * The function form may return `null` for an action it cannot render; the\n * translate tool reports that as an unsuccessful translation.\n */\n readonly getRenderer?: () =>\n NaturalLanguageRenderer | DomainRenderFn | Promise<NaturalLanguageRenderer | DomainRenderFn>;\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/server)\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<string, NaturalLanguageRenderer | DomainRenderFn>();\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 | DomainRenderFn | 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 } else if (dsl.render) {\n // A descriptor without an explicit renderer can still render: the DSL\n // knows its own domain renderer and its schema fallback.\n try {\n rendered = dsl.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;A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AS,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"]}