{"version":3,"sources":["../src/index.ts","../src/core/types.ts","../src/core/tokenization/token-utils.ts","../src/core/matching/match-skeleton.ts","../src/core/matching/type-validation.ts","../src/core/matching/possessive-keywords.ts","../src/core/matching/stock-reading.ts","../src/core/matching/stock-reader.ts","../src/core/matching/stock-confidence.ts","../src/generation/schema-patterns.ts","../src/generation/pattern-render.ts","../src/grammar/types.ts","../src/grammar/transformer.ts","../src/interfaces/dictionary.ts","../src/interfaces/profile-provider.ts","../src/interfaces/value-extractor.ts","../src/ir/references.ts","../src/ir/explicit-parser.ts","../src/ir/explicit-renderer.ts","../src/ir/json-schema.ts","../src/ir/protocol-json.ts","../src/ir/from-interchange.ts","../src/ir/to-runtime-ast.ts","../src/api/reading.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","../src/api/translation-loss.ts","../src/aot/domain-scanner.ts","../src/aot/aot-orchestrator.ts","../src/aot/registry-bridge.ts","../src/schema/command-schema.ts","../src/generation/profile.ts","../src/generation/renderer.ts","../src/generation/diagnostics.ts","../src/core/tokenization/extractors.ts","../src/core/tokenization/extractors/operator.ts","../src/core/tokenization/extractors/punctuation.ts","../src/core/tokenization/default-extractors.ts","../src/core/tokenization/base-tokenizer.ts","../src/multilingual/builders.ts","../src/core/tokenization/char-classifiers.ts","../src/core/tokenization/morphology/types.ts","../src/core/tokenization/morphology/base-normalizer.ts","../src/training/jsonl-writer.ts","../src/feedback/confidence-gate.ts","../src/feedback/pattern-tracker.ts","../src/parsing/multi-statement.ts"],"sourcesContent":["/**\n * @lokascript/framework - Generic framework for building multilingual DSLs\n *\n * This framework provides the building blocks for creating domain-specific languages\n * that work across multiple human languages (English, Japanese, Spanish, etc.) with\n * semantic parsing and grammar transformation.\n *\n * @example\n * ```typescript\n * import { createMultilingualDSL } from '@lokascript/framework';\n *\n * const myDSL = createMultilingualDSL({\n *   schemas: [{ action: 'select', roles: [...] }],\n *   languages: [{ code: 'en', profile: {...}, tokenizer: {...} }],\n *   codeGenerator: (node) => generateSQL(node)\n * });\n *\n * myDSL.parse('select name from users', 'en');\n * myDSL.translate('select name from users', 'en', 'ja');\n * ```\n */\n\n// Main API\nexport * from './api';\n\n// AOT (generalized ahead-of-time compilation)\nexport * from './aot';\n\n// Interfaces (for dependency injection)\nexport * from './interfaces';\n\n// Core modules\nexport * from './schema';\nexport * from './generation';\n\n// Grammar exports - explicitly list to avoid PatternMatcher conflict with core\nexport { GrammarTransformer } from './grammar/transformer';\nexport type { TransformerConfig } from './grammar/transformer';\nexport { reorderRoles, insertMarkers, joinTokens } from './grammar/types';\nexport type {\n  LanguageProfile,\n  PatternTransform,\n  ParsedElement,\n  WordOrder,\n  GrammaticalMarker,\n  AdpositionType,\n} from './grammar/types';\n\n// Multilingual bridge — inject semantic language profiles into domain DSLs\n// (explicit list: the module also re-exports grammar types already exported above)\nexport {\n  buildPatternProfile,\n  buildDomainTokenizer,\n  buildLanguageConfig,\n  deriveRoleMarkers,\n} from './multilingual';\nexport type {\n  GrammarProfileSlice,\n  DomainVocabulary,\n  DomainKeywordTranslation,\n  DomainKeywordEntry,\n  RoleMarkerSlice,\n  TokenizationSlice,\n  VerbSlice,\n  DomainTokenizerOptions,\n  LanguageConfigMeta,\n} from './multilingual';\n// A language's grammar (the data lives in `@lokascript/framework/languages/<code>`)\nexport type { GrammarProfile } from './languages/types';\n\n// Core - export classes and utilities\nexport * from './core';\n\n// Re-export key types for convenience\nexport type {\n  ActionType,\n  SemanticRole as SemanticRoleType,\n  SemanticValue,\n  SemanticNode,\n  CommandSemanticNode,\n  EventHandlerSemanticNode,\n  ConditionalSemanticNode,\n  CompoundSemanticNode,\n  LoopSemanticNode,\n  LiteralValue,\n  SelectorValue,\n  ReferenceValue,\n  PropertyPathValue,\n  ExpressionValue,\n  SemanticMetadata,\n  SourcePosition,\n  LanguageToken,\n  TokenStream,\n  LanguageTokenizer,\n  LanguagePattern,\n  // v1.2 types\n  Annotation,\n  ProtocolDiagnostic,\n  AsyncVariant,\n  MatchArm,\n  LSEEnvelope,\n} from './core/types';\n\nexport type { CommandSchema, RoleSpec } from './schema';\n\n// Renderer\nexport type {\n  NaturalLanguageRenderer,\n  KeywordTable,\n  MarkerTable,\n  RendererConfig,\n  DomainRenderFn,\n  DomainRendererConfig,\n} from './generation/renderer';\nexport {\n  lookupKeyword,\n  lookupMarker,\n  buildPhrase,\n  buildTablesFromProfiles,\n  detectWordOrders,\n  createSchemaRenderer,\n  createDomainRenderer,\n} from './generation/renderer';\n\n// Diagnostics\nexport type {\n  DiagnosticSeverity,\n  Diagnostic,\n  DiagnosticResult,\n  DiagnosticSummary,\n  DiagnosticCollector,\n  DiagnosticOptions,\n} from './generation/diagnostics';\nexport { createDiagnosticCollector, fromError, filterBySeverity } from './generation/diagnostics';\n\nexport type {\n  LanguageConfig,\n  DSLConfig,\n  MultilingualDSL,\n  CodeGenerator,\n  DomainExtension,\n  ExtensionVocabulary,\n  ValidationResult,\n  CompileResult,\n  DomainDescriptor,\n  MCPToolDefinition,\n  MCPToolResponse,\n  DispatchResult,\n  CompositeParseResult,\n  CompositeStatement,\n  CompositeError,\n  DispatcherOptions,\n} from './api';\n\n// `createMultilingualDSL` is the package's primary entry point, so it is\n// exported by name rather than reaching consumers only through `export * from\n// './api'` above.\nexport { createMultilingualDSL, DomainRegistry, CrossDomainDispatcher } from './api';\n\n// Re-export helper functions\nexport {\n  createLiteral,\n  createSelector,\n  createReference,\n  createPropertyPath,\n  createExpression,\n  createCommandNode,\n  createEventHandlerNode,\n  createConditionalNode,\n  createCompoundNode,\n  createLoopNode,\n  extractValue,\n  extractRoleValue,\n  // v1.2 factories\n  createTryNode,\n  createAsyncNode,\n  createMatchNode,\n} from './core/types';\n\nexport { defineCommand, defineRole } from './schema';\nexport { createSimpleTokenizer } from './core/tokenization/base-tokenizer';\nexport type { SimpleTokenizerConfig } from './core/tokenization/base-tokenizer';\n\n// Morphological normalization base class and types\nexport { BaseMorphologicalNormalizer } from './core/tokenization/morphology/base-normalizer';\nexport type {\n  ConjugationEnding,\n  NormalizerConfig,\n} from './core/tokenization/morphology/base-normalizer';\n\n// IR (Intermediate Representation) — explicit syntax, JSON conversion, reference validation\nexport * from './ir';\n\n// LLM Prompt Generation — auto-generate system prompts from CommandSchema[]\nexport * from './prompts';\n\n// Training Data Generation — synthesize (natural_language, LSE) pairs from schemas\nexport * from './training';\n\n// Feedback Loop — structured errors, disambiguation, pattern tracking\nexport * from './feedback';\n\n// Multi-statement parser\nexport { createMultiStatementParser, accumulateBlocks } from './parsing/multi-statement';\nexport type {\n  MultiStatementParser,\n  MultiStatementConfig,\n  MultiStatementResult,\n  ParsedStatement,\n  StatementError,\n  StatementBlock,\n  BlockConfig,\n  BlockResult,\n  KeywordMap,\n  WordOrderHint,\n} from './parsing/multi-statement';\n","/**\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   * The pattern reads a form the renderer does not write by choosing it\n   * (hyperscript's wait `esperar evento {event}`: the renderer writes the event\n   * word itself, before a name no table knows). The renderer skips it.\n   */\n  readonly parseOnly?: boolean;\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   * Parse-only marker: the matcher still consumes this literal, but the\n   * renderer skips it. Set when a role declares `renderOverride: { <lang>: '' }`\n   * (hyperscript's fetch `from`: required to PARSE `fetch from /api`, absent from\n   * the render, since `fetch from \"/api\"` is not canonical _hyperscript).\n   */\n  readonly renderSuppress?: boolean;\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   * The words the slot reads, from the schema's `RoleSpec.words` for the pattern's language (its\n   * `'*'` list and the language's own): the stock reader reads the slot only from one of them.\n   */\n  readonly words?: readonly string[];\n  /**\n   * Mirrors the schema's `RoleSpec.valueShape`: the slot's surface form is\n   * unambiguous on its own. Carried onto the pattern token because the value\n   * reader needs it too, not just the confidence model (hyperscript's\n   * `'keyword'` slots hold a fixed keyword phrase and are exempt from the\n   * trailing-slot verb guard).\n   */\n  readonly valueShape?: 'time' | 'reference' | 'keyword' | 'object' | 'clause' | 'list';\n}\n\nexport interface GroupPatternToken {\n  readonly type: 'group';\n  readonly tokens: PatternToken[];\n  readonly optional?: boolean;\n  /**\n   * The group is optional for PARSING but belongs in canonical output: the\n   * marker-only groups a profile's optional case markers produce (Turkish case\n   * suffixes may be dropped colloquially, so the parse accepts both forms).\n   * The matcher's skeleton also requires such a group's marker after a role it\n   * captures (`MatchSkeleton`).\n   */\n  readonly renderRequired?: 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  /**\n   * The static `value` is an expression, as the English parse types the word\n   * (hyperscript's `go back` destination), not a literal.\n   */\n  readonly valueIsExpression?: true;\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   * Stream index at which each captured role's value STARTED, for callers that\n   * need to re-read a slot's own span rather than the tail after it. Populated\n   * on the same success path as `captured` (`MatchSkeleton`), so a role left\n   * behind by a rolled-back group survives in both maps or in neither.\n   */\n  readonly roleStarts?: ReadonlyMap<SemanticRole, number>;\n  /**\n   * A source phrase hyperscript's reader found in an event HEAD (`from #btn`\n   * right after the event) rather than in a pattern slot: kept out of\n   * `captured`, so a fused pattern's own source group can neither overwrite it\n   * nor be overwritten (`ValueReader.resultFields`).\n   */\n  readonly eventSource?: SemanticValue;\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 * Token Utilities\n *\n * Core token creation, stream implementation, and character classification.\n * These are the foundational building blocks used by all tokenizers.\n */\n\nimport type { LanguageToken, TokenKind, TokenStream, StreamMark, SourcePosition } from '../types';\n\n// =============================================================================\n// Time Unit Configuration\n// =============================================================================\n\n/**\n * Configuration for a native language time unit pattern.\n * Used by tryNumberWithTimeUnits() to match language-specific time units.\n */\nexport interface TimeUnitMapping {\n  /** The pattern to match (e.g., 'segundos', 'ミリ秒') */\n  readonly pattern: string;\n  /** The standard suffix to use (ms, s, m, h) */\n  readonly suffix: string;\n  /** Length of the pattern (for optimization) */\n  readonly length: number;\n  /** Whether to check for word boundary after the pattern */\n  readonly checkBoundary?: boolean;\n  /** Character that cannot follow the pattern (e.g., 's' for 'm' to avoid 'ms') */\n  readonly notFollowedBy?: string;\n  /** Whether to do case-insensitive matching */\n  readonly caseInsensitive?: boolean;\n}\n\n// =============================================================================\n// Token Stream Implementation\n// =============================================================================\n\n/**\n * Concrete implementation of TokenStream.\n */\nexport class TokenStreamImpl implements TokenStream {\n  readonly tokens: readonly LanguageToken[];\n  readonly language: string;\n  private pos: number = 0;\n\n  constructor(tokens: LanguageToken[], language: string) {\n    this.tokens = tokens;\n    this.language = language;\n  }\n\n  peek(offset: number = 0): LanguageToken | null {\n    const index = this.pos + offset;\n    if (index < 0 || index >= this.tokens.length) {\n      return null;\n    }\n    return this.tokens[index];\n  }\n\n  advance(): LanguageToken {\n    if (this.isAtEnd()) {\n      throw new Error('Unexpected end of token stream');\n    }\n    return this.tokens[this.pos++];\n  }\n\n  isAtEnd(): boolean {\n    return this.pos >= this.tokens.length;\n  }\n\n  mark(): StreamMark {\n    return { position: this.pos };\n  }\n\n  reset(mark: StreamMark): void {\n    this.pos = mark.position;\n  }\n\n  position(): number {\n    return this.pos;\n  }\n\n  /**\n   * Get remaining tokens as an array.\n   */\n  remaining(): LanguageToken[] {\n    return this.tokens.slice(this.pos);\n  }\n\n  /**\n   * Consume tokens while predicate is true.\n   */\n  takeWhile(predicate: (token: LanguageToken) => boolean): LanguageToken[] {\n    const result: LanguageToken[] = [];\n    while (!this.isAtEnd() && predicate(this.peek()!)) {\n      result.push(this.advance());\n    }\n    return result;\n  }\n\n  /**\n   * Skip tokens while predicate is true.\n   */\n  skipWhile(predicate: (token: LanguageToken) => boolean): void {\n    while (!this.isAtEnd() && predicate(this.peek()!)) {\n      this.advance();\n    }\n  }\n}\n\n// =============================================================================\n// Shared Tokenization Utilities\n// =============================================================================\n\n/**\n * Create a source position from start and end offsets.\n */\nexport function createPosition(start: number, end: number): SourcePosition {\n  return { start, end };\n}\n\n/**\n * Options for creating a token with optional morphological data.\n */\nexport interface CreateTokenOptions {\n  /** Explicitly normalized form from keyword map */\n  normalized?: string;\n  /** Morphologically normalized stem */\n  stem?: string;\n  /** Confidence in the stem (0.0-1.0) */\n  stemConfidence?: number;\n  /** Additional metadata for specific token types (e.g., event modifier data) */\n  metadata?: Record<string, unknown>;\n}\n\n/**\n * Token creation options (object style).\n */\nexport interface TokenCreationParams extends CreateTokenOptions {\n  value: string;\n  kind: TokenKind;\n  position: SourcePosition;\n}\n\n/**\n * Create a language token (object style).\n */\nexport function createToken(params: TokenCreationParams): LanguageToken;\n\n/**\n * Create a language token (separate parameters style).\n */\nexport function createToken(\n  value: string,\n  kind: TokenKind,\n  position: SourcePosition,\n  normalizedOrOptions?: string | CreateTokenOptions\n): LanguageToken;\n\n/**\n * Create a language token.\n * Supports both object style and separate parameters style.\n */\nexport function createToken(\n  valueOrParams: string | TokenCreationParams,\n  kind?: TokenKind,\n  position?: SourcePosition,\n  normalizedOrOptions?: string | CreateTokenOptions\n): LanguageToken {\n  // Handle object style\n  if (typeof valueOrParams === 'object') {\n    const { value, kind, position, normalized, stem, stemConfidence, metadata } = valueOrParams;\n    return {\n      value,\n      kind,\n      position,\n      ...(normalized !== undefined && { normalized }),\n      ...(stem !== undefined && { stem }),\n      ...(stemConfidence !== undefined && { stemConfidence }),\n      ...(metadata !== undefined && { metadata }),\n    };\n  }\n\n  // Handle separate parameters style\n  const value = valueOrParams;\n  if (!kind || !position) {\n    throw new Error('createToken requires kind and position parameters');\n  }\n  // Handle legacy string argument for backward compatibility\n  if (typeof normalizedOrOptions === 'string') {\n    return { value, kind, position, normalized: normalizedOrOptions };\n  }\n\n  // Handle options object\n  if (normalizedOrOptions) {\n    const { normalized, stem, stemConfidence, metadata } = normalizedOrOptions;\n    return {\n      value,\n      kind,\n      position,\n      ...(normalized !== undefined && { normalized }),\n      ...(stem !== undefined && { stem }),\n      ...(stemConfidence !== undefined && { stemConfidence }),\n      ...(metadata !== undefined && { metadata }),\n    };\n  }\n\n  return { value, kind, position };\n}\n\n/**\n * Check if a character is whitespace.\n */\nexport function isWhitespace(char: string): boolean {\n  return /\\s/.test(char);\n}\n\n/**\n * Check if a string starts with a CSS selector prefix.\n * Includes JSX-style element selectors: <form />, <div>\n */\nexport function isSelectorStart(char: string): boolean {\n  return (\n    char === '#' || char === '.' || char === '[' || char === '@' || char === '*' || char === '<'\n  );\n}\n\n/**\n * Check if a character is a quote (string delimiter).\n */\nexport function isQuote(char: string): boolean {\n  return char === '\"' || char === \"'\" || char === '`' || char === '「' || char === '」';\n}\n\n/**\n * Check if a character is a digit.\n */\nexport function isDigit(char: string): boolean {\n  return /\\d/.test(char);\n}\n\n/**\n * Strip diacritical marks that are OPTIONAL in their script — currently Arabic\n * harakat (U+064B–U+0652: fatha, kasra, damma, sukun, shadda…) and the\n * superscript alif (U+0670).\n *\n * `بدّل` and `بَدِّل` are the same word; Arabic prose writes either. So any place\n * that compares an Arabic surface form against a declared keyword has to compare\n * stripped, or the same word fails to match itself.\n *\n * Deliberately Arabic-only. Latin diacritics are NOT optional — `obtén`, `récupère`\n * and `vá` differ from their unaccented spellings in meaning or validity — and\n * Hebrew niqqud (U+05B0–U+05BC) is out of range too, so this is inert for every\n * other script.\n */\nexport function stripOptionalDiacritics(word: string): string {\n  return word.replace(/[\\u064b-\\u0652\\u0670]/g, '');\n}\n\n/**\n * Check if a character is an ASCII letter.\n */\nexport function isAsciiLetter(char: string): boolean {\n  return /[a-zA-Z]/.test(char);\n}\n\n/**\n * Check if a character is part of an ASCII identifier.\n */\nexport function isAsciiIdentifierChar(char: string): boolean {\n  return /[a-zA-Z0-9_-]/.test(char);\n}\n","/**\n * The pattern matcher's skeleton: the grammar-neutral half of semantic's matcher\n * (domains rethink Phase 4.2-4.3, `docs-internal/DOMAINS_RETHINK.md`).\n *\n * It walks a pattern's literals, groups and role slots against the token\n * stream: literal matching (exact, normalized, stem, case- and\n * diacritic-insensitive, shattered compounds), optional groups with exact\n * rollback and the marker discipline of a postpositional group, the\n * speculative skip of an optional slot, role spans, memoized ranking by\n * priority then confidence, the confidence model, and the extraction rules.\n * Every value is read by the grammar's `ValueReader` (`value-reader.ts`);\n * hyperscript's is `@lokascript/semantic`'s `HyperscriptValueReader`, and its\n * confidence model semantic's `DefaultConfidenceModel`.\n */\n\nimport type {\n  LanguagePattern,\n  PatternToken,\n  PatternMatchResult,\n  SemanticRole,\n  SemanticValue,\n  TokenStream,\n  LanguageToken,\n} from '../types';\nimport { stripOptionalDiacritics } from '../tokenization/token-utils';\nimport type { ConfidenceModel } from './confidence-model';\nimport type { MatchView, ValueReader } from './value-reader';\n\n/** Whether a group binds a role, at any depth. */\nfunction groupHasRole(group: PatternToken & { type: 'group' }): boolean {\n  return group.tokens.some(t => t.type === 'role' || (t.type === 'group' && groupHasRole(t)));\n}\n\nexport class MatchSkeleton {\n  /**\n   * The pattern tokens still to match after the one being matched, through\n   * every enclosing group: a value stops at any marker the pattern still owes.\n   */\n  private patternRest: PatternToken[] = [];\n\n  /**\n   * Whether the role slot being matched directly follows a literal the pattern\n   * matched: its marker (`[por {quantity}]`), or the command's verb.\n   */\n  private slotAfterLiteral = false;\n\n  /** Injectable confidence scoring model (Phase 3.3) */\n  private readonly confidenceModel: ConfidenceModel;\n\n  /**\n   * Selective memoization cache (Phase 6.1).\n   * Caches pattern match results keyed by `tokenPosition:patternId`.\n   * Cleared before each top-level matchBest() call.\n   */\n  private matchCache = new Map<string, PatternMatchResult | null>();\n\n  /**\n   * Stream index where each role's capture began, for the current\n   * `matchPattern` call. Rebuilt per call, written on the same success path as\n   * `captured` — see `PatternMatchResult.roleStarts`.\n   */\n  private roleStarts = new Map<SemanticRole, number>();\n\n  /** The grammar's value reading: every role slot, and the grammar's hooks. */\n  private readonly reader: ValueReader;\n\n  /**\n   * @param makeReader - builds the grammar's reader, handed this matcher's view\n   *   of the match in progress (one reader per matcher).\n   */\n  constructor(makeReader: (view: MatchView) => ValueReader, confidenceModel: ConfidenceModel) {\n    this.confidenceModel = confidenceModel;\n    this.reader = makeReader({\n      patternRest: () => this.patternRest,\n      slotAfterLiteral: () => this.slotAfterLiteral,\n      wouldMatch: (pt, token) => this.patternTokenWouldMatch(pt, token),\n    });\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  matchPattern(tokens: TokenStream, pattern: LanguagePattern): PatternMatchResult | null {\n    const mark = tokens.mark();\n    const captured = new Map<SemanticRole, SemanticValue>();\n\n    this.reader.beginPattern(pattern);\n\n    // Reset match counters for this pattern\n    this.stemMatchCount = 0;\n    this.totalKeywordMatches = 0;\n    this.roleStarts = new Map();\n\n    this.patternRest = [];\n    const success = this.matchTokenSequence(tokens, pattern.template.tokens, captured);\n\n    if (!success) {\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.confidenceModel.calculate({\n      pattern,\n      captured,\n      stemMatchCount: this.stemMatchCount,\n      totalKeywordMatches: this.totalKeywordMatches,\n    });\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      roleStarts: this.roleStarts,\n      ...this.reader.resultFields?.(),\n    };\n  }\n\n  /**\n   * Try to match multiple patterns, return the best match.\n   */\n  matchBest(tokens: TokenStream, patterns: LanguagePattern[]): PatternMatchResult | null {\n    // Clear memoization cache for this matching round (Phase 6.1)\n    this.matchCache.clear();\n\n    const matches: PatternMatchResult[] = [];\n    const startPos = tokens.position();\n\n    for (const pattern of patterns) {\n      const mark = tokens.mark();\n\n      // Check memoization cache (Phase 6.1)\n      const cacheKey = `${startPos}:${pattern.id}`;\n      let result: PatternMatchResult | null;\n\n      if (this.matchCache.has(cacheKey)) {\n        result = this.matchCache.get(cacheKey)!;\n      } else {\n        result = this.matchPattern(tokens, pattern);\n        this.matchCache.set(cacheKey, result);\n      }\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      return b.confidence - a.confidence;\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  private matchTokenSequence(\n    tokens: TokenStream,\n    patternTokens: PatternToken[],\n    captured: Map<SemanticRole, SemanticValue>,\n    // What follows the sequence itself — a GROUP's last inner token must see the\n    // token after the group as its `next` (the trailing-slot verb guard in\n    // matchRoleToken keys on nextPatternToken === undefined meaning \"pattern\n    // truly ends here\", and a mid-pattern single-token group is not the end).\n    nextAfterSequence?: PatternToken\n  ): boolean {\n    this.reader.skipLeading?.(tokens, patternTokens);\n\n    for (let i = 0; i < patternTokens.length; i++) {\n      const patternToken = patternTokens[i];\n\n      this.reader.beforePatternToken?.(tokens, patternTokens, i, captured);\n\n      // Marker-less optional slot about to eat a command VERB, mid-pattern.\n      //\n      // The reader's own guard (hyperscript's matchRoleToken) skips such a slot only when the pattern's\n      // very next token is a literal the verb itself satisfies. Where an\n      // OPTIONAL group sits between the slot and the verb literal\n      // (`[{method}] [using view {manner}] 交換`) that test looks at the\n      // group's first token, sees no match, and lets the slot swallow the verb\n      // — so `swap #a with #b` rendered SOV (`#a に #b を 交換`) did not parse\n      // at all in bn/hi/ja/ko/qu/tr.\n      //\n      // Widening that test to look THROUGH skippable groups was measured to\n      // work and to BREAK the ja goal-reclaim lock: the no-goal transition\n      // variant's mid-pattern slot must keep capturing 遷移 and failing, so the\n      // verb-anchoring fallback can reclaim goal+duration. Both shapes are\n      // structurally identical at the slot, so no per-slot test can separate\n      // them.\n      //\n      // What separates them is the OUTCOME. Skipping the slot lets swap's\n      // pattern consume its clause ENTIRELY (`#a に #b を 交換` → end), while\n      // the ja no-goal variant completes having eaten only `opacity を 遷移`\n      // and STRANDS `0 に 300ms` — the sloppy match the lock exists to prevent.\n      // So: speculatively skip, match the rest of THIS pattern, and adopt the\n      // skip only when it consumes the whole clause. A stranded tail falls\n      // through to the capture-and-fail below, unchanged.\n      //\n      // Bounded: fires only on an optional marker-less role slot facing a\n      // command-verb keyword the next pattern token does not want, and recurses\n      // on a strictly shorter token list — never a re-run of other patterns\n      // (the abandoned last-resort retry in matchBest, which compounded).\n      if (\n        this.reader.maySkipSlot(\n          patternToken,\n          tokens.peek(),\n          patternTokens[i + 1] ?? nextAfterSequence\n        )\n      ) {\n        const skipMark = tokens.mark();\n        const speculative = new Map(captured);\n        if (\n          this.matchTokenSequence(\n            tokens,\n            patternTokens.slice(i + 1),\n            speculative,\n            nextAfterSequence\n          ) &&\n          this.reader.atClauseEnd(tokens)\n        ) {\n          captured.clear();\n          for (const [role, value] of speculative) captured.set(role, value);\n          return true;\n        }\n        tokens.reset(skipMark);\n      }\n\n      const outerRest = this.patternRest;\n      this.patternRest = [...patternTokens.slice(i + 1), ...outerRest];\n      this.slotAfterLiteral =\n        patternToken.type === 'role' && patternTokens[i - 1]?.type === 'literal';\n      const matched = this.matchPatternToken(\n        tokens,\n        patternToken,\n        captured,\n        patternTokens[i + 1] ?? nextAfterSequence\n      );\n      this.patternRest = outerRest;\n\n      if (!matched) {\n        // If token is optional, continue\n        if (this.isOptional(patternToken)) {\n          continue;\n        }\n        return false;\n      }\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    nextPatternToken?: PatternToken\n  ): boolean {\n    switch (patternToken.type) {\n      case 'literal':\n        return this.matchLiteralToken(tokens, patternToken);\n\n      case 'role': {\n        // Record where this slot's own span begins, but only once it actually\n        // captured — an optional role that matched nothing must not claim a\n        // position. See `PatternMatchResult.roleStarts`.\n        const roleStart = tokens.position();\n        const matchedRole = this.reader.readRole(tokens, patternToken, captured, nextPatternToken);\n        if (matchedRole && captured.has(patternToken.role)) {\n          this.roleStarts.set(patternToken.role, roleStart);\n        }\n        return matchedRole;\n      }\n\n      case 'group':\n        return this.matchGroupToken(tokens, patternToken, captured, nextPatternToken);\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    if (!token) return false;\n\n    // Check main value\n    const matchType = this.getMatchType(token, patternToken.value);\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    // Hyphen/underscore-compound fold: many keyword translations are compounds\n    // (ms `titik-henti`, es `punto-interrupción`, ru `по_умолчанию`,\n    // qu `ñawpaq_kaq`) that the tokenizers shatter into word/sep/word runs —\n    // and a segment can be ANOTHER command's keyword (ms `henti` → halt,\n    // qu `ñawpaq` → first), so the run mis-anchors that command instead.\n    // Join the run and compare it to any separator-bearing expected value;\n    // only fires after every single-token match above has failed.\n    for (const value of [patternToken.value, ...(patternToken.alternatives ?? [])]) {\n      for (const sep of ['-', '_'] as const) {\n        if (value.includes(sep) && this.tryMatchShatteredCompound(tokens, value, sep)) {\n          this.totalKeywordMatches++;\n          return true;\n        }\n      }\n    }\n\n    return false;\n  }\n\n  /**\n   * Match a compound keyword (`titik-henti`, `по_умолчанию`) against a\n   * shattered token run (`titik` `-` `henti` / `по` `_` `умолчанию`): word\n   * segments must be identifier/keyword/particle tokens equal to the expected\n   * segments (case-insensitive; particle because prepositions like ru `по` /\n   * uk `за` lead some underscore compounds), separators lone `sep` tokens.\n   * Consumes the run on success, resets the stream on failure.\n   */\n  private tryMatchShatteredCompound(\n    tokens: TokenStream,\n    expected: string,\n    sep: '-' | '_'\n  ): boolean {\n    const segments = expected.split(sep);\n    if (segments.length < 2 || segments.some(s => s.length === 0)) return false;\n    const mark = tokens.mark();\n    for (let i = 0; i < segments.length; i++) {\n      if (i > 0) {\n        const sepToken = tokens.peek();\n        if (!sepToken || sepToken.value !== sep) {\n          tokens.reset(mark);\n          return false;\n        }\n        tokens.advance();\n      }\n      const word = tokens.peek();\n      if (\n        !word ||\n        (word.kind !== 'identifier' && word.kind !== 'keyword' && word.kind !== 'particle') ||\n        word.value.toLowerCase() !== segments[i]!.toLowerCase()\n      ) {\n        tokens.reset(mark);\n        return false;\n      }\n      tokens.advance();\n    }\n    return true;\n  }\n\n  /**\n   * Match a group pattern token (optional sequence).\n   */\n  private matchGroupToken(\n    tokens: TokenStream,\n    patternToken: PatternToken & { type: 'group' },\n    captured: Map<SemanticRole, SemanticValue>,\n    nextPatternToken?: PatternToken\n  ): boolean {\n    const mark = tokens.mark();\n\n    // Snapshot the captured roles' VALUES, not just their keys. Clearing only\n    // the newly-added keys leaves an OVERWRITE by a failed group in place.\n    //\n    // 90 shipped patterns bind one role in TWO optional groups — every\n    // `<cmd>-event-<lang>-sov` has a pre-verb `[{destination} <marker>]` and a\n    // post-verb one, because the transformer emits the to-phrase on either side\n    // depending on the command. When the trailing group speculatively captures\n    // the next token into that role and then fails on its marker, the token\n    // stream rolls back but the corrupted value survives: ja\n    // `クリック で #panel に .active を トグル ゴミ` returned\n    // `destination=\"ゴミ\"` with the real `#panel` captured and discarded.\n    const capturedBefore = new Map(captured);\n\n    let success = this.matchTokenSequence(tokens, patternToken.tokens, captured, nextPatternToken);\n\n    // A group that read its marker and bound no role (`take .foo from .div for\n    // #d3`: `for` matched, and the recipient slot declined `#d3`) took a word\n    // that now stands for nothing, and the clause after it lost its head.\n    if (\n      success &&\n      tokens.position() > mark.position &&\n      groupHasRole(patternToken) &&\n      [...captured].every(([role, value]) => capturedBefore.get(role) === value) &&\n      captured.size === capturedBefore.size\n    ) {\n      success = false;\n    }\n\n    // A postpositional marker group ([{destination} [e]]) can \"succeed\" by\n    // capturing ONLY the role: the role is optional-in-group, the trailing\n    // marker sub-group is optional too, so `.loading i 2s değiştir` binds\n    // `.loading` as the DESTINATION and the pattern then dies on `patient` —\n    // with no backtracking, the whole (correct) parse is lost. A role captured\n    // without its own marker is indistinguishable from the next slot's value,\n    // so require the marker: if this group added a role capture but none of\n    // the tokens it consumed matched a `renderRequired` marker sub-group's\n    // literal, fail the group and roll back — the value stays available for\n    // the slot that really owns it. Scoped to groups that carry a\n    // renderRequired literal-only sub-group (the generated postpositional\n    // shape); prepositional groups ([จาก {source}]) fail fast on their leading\n    // literal and never reach this.\n    //\n    // The marker is the group's LAST token: the sub-group follows the role. A\n    // marker word inside the role's own run is the value's, not the role's\n    // marker: tr `in` is also the operator (`2 dir in arr`), `a` the article\n    // (`id dir a Number`), `nin` the possessive (`length nin textContent nin\n    // #a < 4`). Counted anywhere, they let the unmarked destination take an\n    // `if` condition's tail, so `if 2 is in arr add .a end` read `if 2 add .a\n    // to is in arr end` (P54).\n    if (success) {\n      const markerLiterals: string[] = [];\n      for (const inner of patternToken.tokens) {\n        if (inner.type === 'group' && (inner as { renderRequired?: boolean }).renderRequired) {\n          for (const t of inner.tokens) {\n            if (t.type === 'literal') markerLiterals.push(t.value, ...(t.alternatives ?? []));\n          }\n        }\n      }\n      if (markerLiterals.length > 0) {\n        const addedRole = [...captured.keys()].some(role => !capturedBefore.has(role));\n        if (addedRole) {\n          const last = tokens.tokens[tokens.position() - 1] as LanguageToken | undefined;\n          const markerSeen =\n            last !== undefined &&\n            tokens.position() > mark.position &&\n            markerLiterals.some(lit => this.getMatchType(last, lit) !== 'none');\n          if (!markerSeen) success = false;\n        }\n      }\n    }\n\n    if (!success) {\n      tokens.reset(mark);\n      // Restore the pre-group capture state exactly: drop roles the failed group\n      // added, and put back the values it overwrote.\n      for (const role of captured.keys()) {\n        if (!capturedBefore.has(role)) {\n          captured.delete(role);\n        }\n      }\n      for (const [role, value] of capturedBefore) {\n        if (captured.get(role) !== value) {\n          captured.set(role, value);\n        }\n      }\n      return patternToken.optional || false;\n    }\n\n    return true;\n  }\n\n  /**\n   * Whether a pattern token (literal, or a group starting with a literal) would\n   * match the given stream token. Used to keep the event-head source-clause\n   * consumption from stealing a marker the pattern explicitly expects.\n   */\n  private patternTokenWouldMatch(pt: PatternToken | undefined, token: LanguageToken): boolean {\n    if (!pt) return false;\n    if (pt.type === 'literal') {\n      if (this.getMatchType(token, pt.value) !== 'none') return true;\n      return !!pt.alternatives?.some(a => this.getMatchType(token, a) !== 'none');\n    }\n    if (pt.type === 'group') {\n      return this.patternTokenWouldMatch(pt.tokens?.[0], token);\n    }\n    return false;\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' && token.value.toLowerCase() === value.toLowerCase()) {\n      return 'case-insensitive';\n    }\n\n    // Diacritic-insensitive match for keywords (medium confidence). Arabic\n    // harakat are OPTIONAL in the script — `بدّل` and `بَدِّل` are the same word,\n    // and a pattern literal carries whichever spelling the profile declared. The\n    // keyword map is queried diacritic-insensitively, so the token is correctly\n    // recognized; without this the surface still fails to match its own literal\n    // here, one layer later. Restricted to keywords, and `stripOptionalDiacritics`\n    // touches only Arabic-exclusive codepoints, so it is inert for every other\n    // script (Latin accents are meaning-bearing and must never be stripped).\n    if (token.kind === 'keyword') {\n      const strippedToken = stripOptionalDiacritics(token.value).toLowerCase();\n      if (strippedToken && strippedToken === stripOptionalDiacritics(value).toLowerCase()) {\n        return 'case-insensitive';\n      }\n    }\n\n    return 'none';\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\n  private totalKeywordMatches: number = 0;\n\n  /**\n   * Apply extraction rules to fill in static values and defaults for missing\n   * roles, and re-shape captured roles that declare a `transform` (the\n   * ExtractionRule field was documented but unwired — go-qu-url-dest is the\n   * first consumer: it re-types the marker-bound capture to the expression\n   * shape the en reference produces).\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      const existing = captured.get(role as SemanticRole);\n      if (existing) {\n        if (rule.transform) {\n          const raw =\n            existing.type === 'literal'\n              ? String(existing.value)\n              : String((existing as { raw?: unknown }).raw ?? '');\n          captured.set(role as SemanticRole, rule.transform(raw));\n        }\n      } else if (rule.value !== undefined) {\n        // Static value extraction (e.g., action: { value: \"toggle\" })\n        captured.set(\n          role as SemanticRole,\n          rule.valueIsExpression\n            ? { type: 'expression', raw: rule.value }\n            : { type: 'literal', value: rule.value }\n        );\n      } else if (rule.default) {\n        // Copied, never aliased (the rule's default object is shared across\n        // parses), and tagged implicit: materialized from the default, not\n        // captured from source text — renderers suppress implicit values only.\n        // (`implicit` is semantic's value field; intent's value type has none.)\n        const implicitDefault: SemanticValue & { readonly implicit: true } = {\n          ...rule.default,\n          implicit: true,\n        };\n        captured.set(role as SemanticRole, implicitDefault);\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 * 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 * Reading a domain value at a role slot: the value reading framework's first\n * matcher did, moved here for the stock reader on the matcher's skeleton\n * (`stock-reader.ts`, domains rethink Phase 4.7). The first matcher was\n * deleted in 5.0 (Phase 6).\n *\n * In order: an English noise word before a selector (`the`), then the\n * multi-token forms (a possessive, `my value`; a method call,\n * `#dialog.showModal()`; a possessive selector, `#el's *opacity`; a property\n * access, `user.name`; a selector and its property, `#out.innerText`), then one\n * token by its kind (a selector, a quoted string, a number, a boolean, a\n * duration, a URL, an identifier). Each is checked against the slot's\n * expected types.\n */\n\nimport type {\n  PatternToken,\n  ReferenceValue,\n  SemanticRole,\n  SemanticValue,\n  TokenStream,\n  LanguageToken,\n} from '../types';\nimport { createSelector, createLiteral, createReference, createPropertyPath } from '../types';\nimport { isTypeCompatible } from './type-validation';\nimport { getPossessiveReference } from './possessive-keywords';\n\n/** What value reading needs of a language profile: its code, and its possessive words. */\nexport interface ReadingProfile {\n  readonly code: string;\n  readonly possessive?: {\n    readonly keywords?: Record<string, string>;\n  };\n}\n\nfunction isValidReference(_value: string): boolean {\n  // In generic framework, no built-in references\n  // Identifiers should be expressions\n  return false;\n}\n\n/**\n * Safely convert a value to lowercase string.\n * Provides protection against non-string values at runtime.\n */\n/** `value` lower-cased, whatever it is (the old matcher's keyword compare uses it too). */\nexport function 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 * 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/**\n * Read a value for `patternToken`'s role at the stream's position into\n * `captured`, and advance past it. False when the slot does not match; an\n * optional slot whose value does not fit returns true and captures nothing.\n */\nexport function readRoleValue(\n  tokens: TokenStream,\n  patternToken: PatternToken & { type: 'role' },\n  captured: Map<SemanticRole, SemanticValue>,\n  profile?: ReadingProfile\n): boolean {\n  // Skip noise words like \"the\" before selectors (English idiom support)\n  skipNoiseWords(tokens);\n\n  const token = tokens.peek();\n  if (!token) {\n    return patternToken.optional || false;\n  }\n\n  // Check for possessive expression (e.g., 'my value', 'its innerHTML')\n  const possessiveValue = tryMatchPossessiveExpression(tokens, profile);\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 = 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 = 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 = 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 = 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  const value = tokenToSemanticValue(token);\n  if (!value) {\n    return patternToken.optional || false;\n  }\n\n  // Validate expected types if specified\n  if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {\n    if (!isTypeCompatible(value.type, patternToken.expectedTypes)) {\n      return patternToken.optional || false;\n    }\n  }\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 */\nfunction tryMatchPossessiveExpression(\n  tokens: TokenStream,\n  profile: ReadingProfile | undefined\n): SemanticValue | null {\n  const token = tokens.peek();\n  if (!token) return null;\n\n  // Use profile-based possessive keyword lookup\n  if (!profile) return null;\n\n  const tokenValue = token.normalized || token.value;\n  const tokenLower = safeToLowerCase(tokenValue);\n  const baseRef = getPossessiveReference(profile, 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' && !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 */\nfunction 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 */\nfunction 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 < 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 */\nfunction 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 < 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 < 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 */\nfunction 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 */\nfunction 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/** Maximum depth for nested property access (e.g., a.b.c.d...) */\nconst MAX_PROPERTY_DEPTH = 10;\n\n/** Maximum number of arguments in method calls */\nconst MAX_METHOD_ARGS = 20;\n\n/**\n * Convert a language token to a semantic value.\n */\nfunction tokenToSemanticValue(token: LanguageToken): SemanticValue | null {\n  switch (token.kind) {\n    case 'selector':\n      return createSelector(token.value);\n\n    case 'literal':\n      return parseLiteralValue(token.value);\n\n    case 'keyword': {\n      // Keywords might be references or values\n      const tokenValue = token.normalized || token.value;\n      const lower = safeToLowerCase(tokenValue);\n      if (isValidReference(lower)) {\n        return createReference(lower);\n      }\n      return createLiteral(token.normalized || token.value);\n    }\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 = 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\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 */\nfunction 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 * 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 */\nconst 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 */\nfunction skipNoiseWords(tokens: TokenStream): void {\n  const token = tokens.peek();\n  if (!token) return;\n\n  const tokenLower = safeToLowerCase(token.value);\n\n  // Check if current token is a noise word (like \"the\")\n  if (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 * The stock value reader: what a domain grammar's matcher reads at each role\n * slot, on the matcher's skeleton (domains rethink Phase 4.7,\n * `docs-internal/DOMAINS_RETHINK.md`). Hyperscript's reader is semantic's\n * `HyperscriptValueReader`; a domain takes this one.\n *\n * - A **greedy** slot (`RoleSpec.greedy`: a SQL condition, a column list) reads\n *   every token up to the next marker the pattern still owes, or the end, as\n *   one expression (`readGreedy`).\n * - A slot with a **word list** (`RoleSpec.words`: behaviorspec's interaction,\n *   voice's thing to close) reads only one of its words, compared lower-cased\n *   by value or normalized form; any other word leaves the slot unread.\n * - Any other slot reads one value (`readRoleValue`, the old matcher's reading):\n *   a selector, a quoted string, a number, a boolean, a duration, a URL, an\n *   identifier, or one of the multi-token forms it knows (`user.name`,\n *   `#dialog.showModal()`), checked against the slot's expected types.\n * - A **required** slot reads nothing where the stream is at the marker the\n *   pattern wants next (the old matcher's guard against an SOV marker taken as\n *   a value). An **optional** one reads nothing at any marker the rest of the\n *   pattern owes, through its optional groups (behaviorspec `when user types\n *   into #search`, whose typed text is optional and has no marker). Where a required slot finds nothing to read, and the optional,\n *   marker-less slot just before it read a value with nothing read since, that\n *   value is given back and the required slot reads again (the old matcher's\n *   backtrack: behaviorspec `when clicks`, where the optional actor took\n *   `clicks`; flow `orders として 取得変数`, where the optional patient took\n *   `orders`).\n * - An **optional** slot may be skipped for a token the pattern wants next, the\n *   skip kept only when the rest of the pattern then reads to the end.\n */\n\nimport type {\n  StreamMark,\n  LanguagePattern,\n  LanguageToken,\n  PatternToken,\n  SemanticRole,\n  SemanticValue,\n  TokenStream,\n} from '../types';\nimport type { MatchView, RoleSlot, ValueReader } from './value-reader';\nimport { readRoleValue, type ReadingProfile } from './stock-reading';\n\n/**\n * The markers a greedy value stops at, from the pattern tokens still owed after\n * it: the next literal (with its alternatives), and each optional group's\n * leading literal up to and including the first required token.\n */\nexport function greedyStopMarkers(rest: readonly PatternToken[]): Set<string> {\n  const markers = new Set<string>();\n  const add = (pt: PatternToken & { type: 'literal' }): void => {\n    markers.add(pt.value.toLowerCase());\n    for (const alt of pt.alternatives ?? []) markers.add(alt.toLowerCase());\n  };\n  for (const pt of rest) {\n    if (pt.type === 'literal') {\n      add(pt);\n      break;\n    }\n    if (pt.type === 'group') {\n      const lead = pt.tokens.find(t => t.type === 'literal');\n      if (lead?.type === 'literal') add(lead);\n      // For optional groups, continue scanning past them so the greedy capture\n      // also sees subsequent required literals (the SOV verb after an optional\n      // WHERE group).\n      if (!pt.optional) break;\n    }\n  }\n  return markers;\n}\n\n/** Whether `token` is one of the stop markers, by its value or its normalized form. */\nfunction isStopMarker(token: LanguageToken, stopMarkers: ReadonlySet<string>): boolean {\n  if (stopMarkers.size === 0) return false;\n  if (stopMarkers.has(token.value.toLowerCase())) return true;\n  return !!token.normalized && stopMarkers.has(token.normalized.toLowerCase());\n}\n\n/**\n * Read every token up to a stop marker (or the end) as one expression value,\n * advancing past them; null (consuming nothing) when the first token stops it.\n */\nexport function readGreedy(\n  tokens: TokenStream,\n  stopMarkers: ReadonlySet<string>\n): SemanticValue | null {\n  const values: string[] = [];\n  while (!tokens.isAtEnd()) {\n    const next = tokens.peek();\n    if (!next || isStopMarker(next, stopMarkers)) break;\n    values.push(next.value);\n    tokens.advance();\n  }\n  return values.length > 0 ? { type: 'expression', raw: values.join(' ') } : null;\n}\n\n/** The stock reader, for a matcher whose profiles it may consult (possessive words). */\n/** Whether `token` is one of a slot's `words`, by value or normalized form, lower-cased. */\nexport function isListedWord(token: LanguageToken | null, words: readonly string[]): boolean {\n  if (!token) return false;\n  const forms = [token.value, token.normalized].filter((f): f is string => typeof f === 'string');\n  return forms.some(form => words.some(word => word.toLowerCase() === form.toLowerCase()));\n}\n\nexport class StockValueReader implements ValueReader {\n  private profile: ReadingProfile | undefined;\n  /** The last optional, marker-less slot that read a value: what a failing required slot may take back. */\n  private lastOptional: { role: SemanticRole; start: StreamMark; end: number } | undefined;\n\n  constructor(\n    private readonly view: MatchView,\n    private readonly profiles: Readonly<Record<string, ReadingProfile>> = {}\n  ) {}\n\n  beginPattern(pattern: LanguagePattern): void {\n    this.profile = this.profiles[pattern.language] ?? { code: pattern.language };\n    this.lastOptional = undefined;\n  }\n\n  readRole(\n    tokens: TokenStream,\n    slot: RoleSlot,\n    captured: Map<SemanticRole, SemanticValue>,\n    next: PatternToken | undefined\n  ): boolean {\n    const start = tokens.mark();\n    if (this.readOnce(tokens, slot, captured, next, true)) {\n      if (!slot.optional) {\n        this.lastOptional = undefined;\n      } else if (\n        captured.has(slot.role) &&\n        tokens.position() > start.position &&\n        !this.view.slotAfterLiteral() &&\n        next?.type !== 'literal'\n      ) {\n        this.lastOptional = { role: slot.role, start, end: tokens.position() };\n      }\n      return true;\n    }\n    const before = this.lastOptional;\n    if (slot.optional || !before || before.end !== tokens.position()) return false;\n    // Give the optional slot's value back and read this one from there.\n    this.lastOptional = undefined;\n    tokens.reset(before.start);\n    captured.delete(before.role);\n    return this.readOnce(tokens, slot, captured, next, false);\n  }\n\n  /** One read of `slot`; `guard` refuses a required slot the marker the pattern wants next. */\n  private readOnce(\n    tokens: TokenStream,\n    slot: RoleSlot,\n    captured: Map<SemanticRole, SemanticValue>,\n    next: PatternToken | undefined,\n    guard: boolean\n  ): boolean {\n    // A required slot never takes the marker the pattern wants next as its\n    // value (`v0x を 実行`: `を` is the marker, not the patient).\n    if (guard && !slot.optional && next?.type === 'literal') {\n      const token = tokens.peek();\n      if (token && this.view.wouldMatch(next, token)) return false;\n    }\n    if (slot.words && !isListedWord(tokens.peek(), slot.words)) return slot.optional ?? false;\n    // Nor does an optional slot read a marker the rest of the pattern owes, through its optional\n    // groups (`when user types into #search`: `into` is the destination's, not the typed text).\n    if (slot.optional && !slot.greedy) {\n      const token = tokens.peek();\n      if (token && isStopMarker(token, greedyStopMarkers(this.view.patternRest()))) return true;\n    }\n    if (slot.greedy) {\n      const value = readGreedy(tokens, greedyStopMarkers(this.view.patternRest()));\n      if (value) {\n        captured.set(slot.role, value);\n        return true;\n      }\n      return slot.optional ?? false;\n    }\n    return readRoleValue(tokens, slot, captured, this.profile);\n  }\n\n  maySkipSlot(\n    patternToken: PatternToken,\n    token: LanguageToken | null,\n    next: PatternToken | undefined\n  ): boolean {\n    const slot =\n      patternToken.type === 'group' && patternToken.optional\n        ? patternToken.tokens.every(t => t.type === 'role')\n          ? patternToken.tokens[0]\n          : undefined\n        : patternToken;\n    if (!slot || slot.type !== 'role' || !slot.optional) return false;\n    return !!token && this.view.wouldMatch(next, token);\n  }\n\n  atClauseEnd(tokens: TokenStream): boolean {\n    return tokens.isAtEnd();\n  }\n}\n\n/** A reader factory for `MatchSkeleton`, reading with the given profiles. */\nexport function createStockReader(\n  profiles: Readonly<Record<string, ReadingProfile>> = {}\n): (view: MatchView) => ValueReader {\n  return view => new StockValueReader(view, profiles);\n}\n","/**\n * The stock confidence model: how framework's first matcher scored a domain\n * pattern's match, moved here as a `ConfidenceModel` for the matcher's\n * skeleton (domains rethink Phase 4.7).\n *\n * Role coverage (a required slot 1, an optional one 0.8, an absent optional one\n * with a default 60% of that), a stem-match penalty (up to 15%, floor 0.5), and\n * two Arabic adjustments: a VSO verb-first boost and the preposition each role\n * takes most naturally.\n */\n\nimport type { LanguagePattern, SemanticRole, SemanticValue } from '../types';\nimport type { ConfidenceBreakdown, ConfidenceContext, ConfidenceModel } from './confidence-model';\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 */\nfunction scoreParts(ctx: ConfidenceContext): ConfidenceBreakdown {\n  const { pattern, captured } = ctx;\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  const roleCoverage = maxScore > 0 ? score / maxScore : 1;\n  let baseConfidence = roleCoverage;\n  let stemPenalty = 0;\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 (ctx.stemMatchCount > 0 && ctx.totalKeywordMatches > 0) {\n    stemPenalty = (ctx.stemMatchCount / ctx.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 = calculateVSOConfidenceBoost(pattern);\n  baseConfidence = Math.min(1.0, baseConfidence + vsoBoost);\n\n  // Apply preposition disambiguation adjustment for Arabic\n  const prepositionAdjustment = arabicPrepositionDisambiguation(pattern, captured);\n  baseConfidence = Math.max(0.0, Math.min(1.0, baseConfidence + prepositionAdjustment));\n\n  return {\n    roleCoverage,\n    stemPenalty,\n    languageBoost: vsoBoost,\n    languageAdjustment: prepositionAdjustment,\n    final: baseConfidence,\n  };\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 */\nfunction 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 */\nfunction arabicPrepositionDisambiguation(\n  pattern: LanguagePattern,\n  captured: ReadonlyMap<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/** The stock confidence model (stateless: one instance serves every matcher). */\nexport const stockConfidenceModel: ConfidenceModel = {\n  calculate: ctx => scoreParts(ctx).final,\n  calculateWithBreakdown: ctx => scoreParts(ctx),\n};\n","/**\n * Patterns from command schemas: the generator semantic's hyperscript parser\n * runs (domains rethink Phase 4.4, `docs-internal/DOMAINS_RETHINK.md`), moved\n * here from `@lokascript/semantic`; `createMultilingualDSL` generates every\n * domain's patterns with it (the classic generator went in 5.0, Phase 6).\n *\n * Per command and language it builds the main pattern and its variants: the\n * simple variant (required roles only), the omit-role, widened-type and\n * required-role variants, an SOV language's verb-first fallback, and the\n * value-prefix-literal variants (`RoleSpec` / `CommandSchema` document each).\n * What differs between grammars is a hook (`SchemaPatternGrammar`); what a\n * grammar adds on top (hyperscript's fused event-handler patterns) stays in the\n * grammar's package.\n */\n\nimport type { ExtractionRule, LanguagePattern, PatternToken } from '../core/types';\nimport type { CommandSchema, RoleSpec } from '../schema';\n\n/** What differs between grammars in how a schema becomes patterns. */\nexport interface SchemaPatternGrammar {\n  /**\n   * How `svoPosition` / `sovPosition` sort: `'ascending'` puts the lowest first\n   * (hyperscript's schemas, 1-based), `'descending'` the highest (a domain's\n   * schemas, as `sortRolesByWordOrder` and the schema renderer read them).\n   */\n  readonly positionOrder: 'ascending' | 'descending';\n}\n\n/** A role marker in a language profile. */\nexport interface SchemaPatternMarker {\n  readonly primary: string;\n  readonly alternatives?: string[];\n  readonly position: 'before' | 'after';\n}\n\n/** What the generator reads of a language profile. */\nexport interface SchemaPatternProfile {\n  readonly code: string;\n  readonly wordOrder: string;\n  readonly keywords: Readonly<\n    Record<string, { readonly primary: string; readonly alternatives?: string[] } | undefined>\n  >;\n  readonly roleMarkers: Readonly<Partial<Record<string, SchemaPatternMarker>>>;\n  /**\n   * The language may drop its role markers colloquially (Turkish case\n   * suffixes): each marker becomes an optional group that still renders.\n   */\n  readonly markersOptional?: boolean;\n}\n\n/** The generator, bound to a grammar (`createSchemaPatternGenerator`). */\nexport interface SchemaPatternGenerator {\n  /** The main pattern for a command in a language. */\n  generatePattern(\n    schema: CommandSchema,\n    profile: SchemaPatternProfile,\n    config?: SchemaPatternConfig\n  ): LanguagePattern;\n  /** The command without its optional roles; null when it has none. */\n  generateSimplePattern(\n    schema: CommandSchema,\n    profile: SchemaPatternProfile,\n    config?: SchemaPatternConfig\n  ): LanguagePattern | null;\n  /** An SOV language's verb-first fallback; null for other word orders. */\n  generateVerbFirstPattern(\n    schema: CommandSchema,\n    profile: SchemaPatternProfile,\n    config?: SchemaPatternConfig\n  ): LanguagePattern | null;\n  /** The main pattern and every variant the schema and config ask for. */\n  generatePatternVariants(\n    schema: CommandSchema,\n    profile: SchemaPatternProfile,\n    config?: SchemaPatternConfig\n  ): LanguagePattern[];\n  /** The token(s) of one role: its value slot and marker, in the language's order. */\n  buildRoleToken(roleSpec: RoleSpec, profile: SchemaPatternProfile): PatternToken[];\n}\n\n/** A generator for the grammar's schemas. */\nexport function createSchemaPatternGenerator(\n  grammar: SchemaPatternGrammar\n): SchemaPatternGenerator {\n  return {\n    generatePattern: (schema, profile, config) => generatePattern(grammar, schema, profile, config),\n    generateSimplePattern: (schema, profile, config) =>\n      generateSimplePattern(grammar, schema, profile, config),\n    generateVerbFirstPattern: (schema, profile, config) =>\n      generateVerbFirstPattern(schema, profile, config),\n    generatePatternVariants: (schema, profile, config) =>\n      generatePatternVariants(grammar, schema, profile, config),\n    buildRoleToken,\n  };\n}\n\n/** The schema without its variant-only roles: what every pattern but a required-role variant is built from. */\nexport function withoutVariantOnlyRoles<S extends CommandSchema>(schema: S): S {\n  return schema.roles.some(r => r.variantOnly)\n    ? { ...schema, roles: schema.roles.filter(r => !r.variantOnly) }\n    : schema;\n}\n\n/**\n * Roles in the grammar's position order for the word order (a stable sort).\n * Each order keeps the rule its generator always had for a role with no\n * position: 99 ascending (semantic's `sortRolesByWordOrder`), 0 descending\n * (framework's `sortRolesByWordOrder`).\n */\nfunction sortRolesByPosition<T extends Pick<RoleSpec, 'svoPosition' | 'sovPosition'>>(\n  roles: readonly T[],\n  wordOrder: string,\n  order: SchemaPatternGrammar['positionOrder']\n): T[] {\n  const sortKey = wordOrder === 'SOV' ? 'sovPosition' : 'svoPosition';\n  return [...roles].sort((a, b) =>\n    order === 'ascending'\n      ? (a[sortKey] ?? 99) - (b[sortKey] ?? 99)\n      : (b[sortKey] ?? 0) - (a[sortKey] ?? 0)\n  );\n}\n\n/**\n * Minimum interface for role specs that can have marker resolution.\n * Compatible with the RoleSpec type from command-schemas.\n */\nexport interface RoleSpecWithMarker {\n  role: string;\n  markerOverride?: Record<string, string | undefined>;\n  markerLegacy?: Record<string, readonly string[]>;\n  markerVariants?: Record<string, readonly string[]>;\n  methodCarrier?: string;\n}\n\n/**\n * Resolved marker information for a role.\n */\nexport interface ResolvedMarker {\n  /** Primary marker string (may be empty string for no marker) */\n  primary: string;\n  /** Alternative markers */\n  alternatives?: string[];\n  /** Position relative to role value */\n  position: 'before' | 'after';\n  /** Whether this is an override marker */\n  isOverride: boolean;\n}\n\n/**\n * Resolve the marker for a role in a specific language.\n *\n * Checks for command-specific marker overrides first,\n * then falls back to the default marker from the language profile.\n *\n * @param roleSpec Role specification with optional override\n * @param profile Language profile with role markers\n * @returns Resolved marker info, or null if no marker\n */\nexport function resolveMarkerForRole(\n  roleSpec: RoleSpecWithMarker,\n  profile: SchemaPatternProfile\n): ResolvedMarker | null {\n  // Check for command-specific marker override first\n  const overrideMarker = roleSpec.markerOverride?.[profile.code];\n  const defaultMarker = profile.roleMarkers[roleSpec.role];\n\n  if (overrideMarker !== undefined) {\n    // Use override marker (can be empty string to suppress default marker).\n    // markerLegacy entries stay accepted, so correcting an override does not\n    // stop the marker a previous release rendered from parsing.\n    const alternatives = legacyMarkerAlternatives(roleSpec, profile.code, overrideMarker);\n    return {\n      primary: overrideMarker,\n      ...(alternatives && { alternatives }),\n      position: defaultMarker?.position ?? 'before',\n      isOverride: true,\n    };\n  }\n\n  if (defaultMarker && defaultMarker.primary) {\n    const result: ResolvedMarker = {\n      primary: defaultMarker.primary,\n      position: defaultMarker.position,\n      isOverride: false,\n    };\n    if (defaultMarker.alternatives) {\n      result.alternatives = defaultMarker.alternatives;\n    }\n    return result;\n  }\n\n  return null;\n}\n\n/**\n * Alternatives an OVERRIDE marker accepts: the role's {@link RoleSpecWithMarker.markerLegacy}\n * entries for this language, minus the override itself.\n *\n * Every generator that resolves a marker has its own override branch, and each\n * one used to drop alternatives entirely — so correcting a marker silently\n * stopped the previous one parsing. This is the single definition of what an\n * override still accepts; call it from each of those branches.\n *\n * Prefer {@link schemaMarkerAlternatives}, which also merges `markerVariants`.\n * This narrower entry point remains for callers that must exclude variants.\n */\nexport function legacyMarkerAlternatives(\n  roleSpec: RoleSpecWithMarker,\n  languageCode: string,\n  overrideMarker: string\n): string[] | undefined {\n  const legacy = roleSpec.markerLegacy?.[languageCode];\n  if (!legacy?.length) return undefined;\n  const alternatives = [...new Set(legacy)].filter(a => a && a !== overrideMarker);\n  return alternatives.length ? alternatives : undefined;\n}\n\n/**\n * Every schema-declared alternative a role's marker accepts in this language:\n * `markerLegacy` ∪ `markerVariants`, minus the marker itself.\n *\n * **The single definition — call it from every branch of every generator.** The\n * two fields used to sit on DIFFERENT branches: the override branch read only\n * `markerLegacy`, the profile-default branch only `markerVariants`. So giving a\n * language a `markerOverride` silently deleted its `markerVariants`, and giving\n * it `markerVariants` did nothing at all wherever an override existed. Both\n * halves were live: tr `set`'s dative allomorphs (`e|a|ye|ya`) were declared as\n * variants but dropped by the tr override, so `… doğru ya ayarla` parsed only\n * inside an event handler — the one generator that happened to merge both.\n *\n * `markerVariants` are held out for a role with a {@link RoleSpecWithMarker.methodCarrier}:\n * there they are not synonyms but distinct command shapes recorded into another\n * role (`put`'s `into|before|after` → `method`), and merging them as synonyms is\n * what broke `put-before`/`put-after` in 23 languages at once. That flag is the\n * discriminator because it is set on exactly the role whose variants carry\n * meaning — pinned by `schema-consistency.test.ts`, which fails if a new\n * `markerVariants` appears without that decision being made.\n */\nexport function schemaMarkerAlternatives(\n  roleSpec: RoleSpecWithMarker,\n  languageCode: string,\n  marker: string\n): string[] | undefined {\n  const legacy = roleSpec.markerLegacy?.[languageCode] ?? [];\n  const variants = roleSpec.methodCarrier ? [] : (roleSpec.markerVariants?.[languageCode] ?? []);\n  const alternatives = [...new Set([...legacy, ...variants])].filter(a => a && a !== marker);\n  return alternatives.length ? alternatives : undefined;\n}\n\n/**\n * Configuration for pattern generation.\n */\nexport interface SchemaPatternConfig {\n  /** Base priority for generated patterns (higher = checked first) */\n  basePriority?: number;\n  /** Whether to generate simple patterns (without optional roles) */\n  generateSimpleVariants?: boolean;\n  /** Whether to generate alternative keyword patterns */\n  generateAlternatives?: boolean;\n  /**\n   * Whether to generate verb-first fallback patterns for SOV languages\n   * (`トグル .active` alongside the canonical `.active を トグル`). Default on.\n   * These are strictly lower priority than the canonical patterns, so native\n   * SOV order always wins; this only accepts bilingual/code-switched input.\n   */\n  generateVerbFirstVariants?: boolean;\n}\n\nconst defaultConfig: SchemaPatternConfig = {\n  basePriority: 100,\n  generateSimpleVariants: true,\n  generateAlternatives: true,\n};\n\n/**\n * Generate a pattern for a command in a specific language.\n */\nfunction generatePattern(\n  grammar: SchemaPatternGrammar,\n  schema: CommandSchema,\n  profile: SchemaPatternProfile,\n  config: SchemaPatternConfig = 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(grammar, schema, profile, keyword);\n\n  // Build extraction rules with defaults for optional roles\n  // This ensures defaults are applied even when optional groups don't match\n  const extraction = buildExtractionRulesWithDefaults(schema, profile);\n\n  // Build template format string (for documentation)\n  const format = buildFormatString(grammar, schema, profile, keyword);\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 * Generate a simple variant pattern (without optional roles).\n */\nfunction generateSimplePattern(\n  grammar: SchemaPatternGrammar,\n  schema: CommandSchema,\n  profile: SchemaPatternProfile,\n  config: SchemaPatternConfig = defaultConfig\n): LanguagePattern | null {\n  // Only generate simple variant if there are optional roles\n  const optionalRoles = schema.roles.filter(r => !r.required);\n  if (optionalRoles.length === 0) {\n    return null;\n  }\n\n  const requiredRoles = schema.roles.filter(r => r.required);\n  const simpleSchema: CommandSchema = {\n    ...schema,\n    roles: requiredRoles,\n  };\n\n  const pattern = generatePattern(grammar, simpleSchema, profile, config);\n\n  // Adjust for simple variant\n  return {\n    ...pattern,\n    id: `${schema.action}-${profile.code}-generated-simple`,\n    priority: (config.basePriority ?? 100) - 5, // Lower priority than full pattern (was -10)\n    extraction: buildExtractionRulesWithDefaults(schema, profile),\n  };\n}\n\n/**\n * Generate a verb-first fallback pattern for an SOV language.\n *\n * Canonical SOV order is patient-then-verb (`.active を トグル`). Bilingual and\n * code-switching authors often write the English/loanword verb first\n * (`トグル .active`). This emits `[verb] [required role(s), UNMARKED]` at a lower\n * priority so the canonical pattern always wins for native input — the\n * verb-first form only matches when the input genuinely starts with the verb.\n *\n * Kept deliberately conservative: only commands with a single required role\n * (patient-focused: toggle/add/remove/show/hide/…) get this fallback, which\n * keeps the unmarked match unambiguous. Returns null otherwise.\n */\nfunction generateVerbFirstPattern(\n  schema: CommandSchema,\n  profile: SchemaPatternProfile,\n  config: SchemaPatternConfig = defaultConfig\n): LanguagePattern | null {\n  if (profile.wordOrder !== 'SOV') return null;\n\n  const requiredRoles = schema.roles.filter(r => r.required);\n  if (requiredRoles.length !== 1) return null;\n\n  const keyword = profile.keywords[schema.action];\n  if (!keyword) return null;\n\n  const verbToken: PatternToken = keyword.alternatives\n    ? { type: 'literal', value: keyword.primary, alternatives: keyword.alternatives }\n    : { type: 'literal', value: keyword.primary };\n\n  // Verb first, then the required role(s) with NO marker (the marker is what\n  // disambiguates roles in canonical SOV; verb-first input typically omits it).\n  // A valuePrefixLiteral (rolePrefixLiteralVariants clones only) still precedes\n  // its role's value — the SOV transformer renders `移動 url \"/page\" に`\n  // verb-first, which is exactly this shape (trailing particle tolerated).\n  const roleTokens: PatternToken[] = requiredRoles.flatMap(r => {\n    const prefix = r.valuePrefixLiteral?.[profile.code];\n    const words = wordsFor(r, profile.code);\n    const roleToken: PatternToken = {\n      type: 'role',\n      role: r.role,\n      optional: false,\n      expectedTypes: r.expectedTypes,\n      ...(words ? { words } : {}),\n    };\n    return prefix ? [{ type: 'literal', value: prefix } as PatternToken, roleToken] : [roleToken];\n  });\n\n  return {\n    id: `${schema.action}-${profile.code}-generated-verb-first`,\n    language: profile.code,\n    command: schema.action,\n    // Strictly below the canonical (basePriority) and simple (basePriority - 5)\n    // patterns so native order is always preferred.\n    priority: (config.basePriority ?? 100) - 20,\n    template: {\n      format: `${keyword.primary} <${requiredRoles[0].role}>`,\n      tokens: [verbToken, ...roleTokens],\n    },\n    extraction: buildExtractionRulesWithDefaults(schema, profile),\n  };\n}\n\n/**\n * Generate all pattern variants for a command in a language.\n */\nfunction generatePatternVariants(\n  grammar: SchemaPatternGrammar,\n  schema: CommandSchema,\n  profile: SchemaPatternProfile,\n  config: SchemaPatternConfig = defaultConfig\n): LanguagePattern[] {\n  const patterns: LanguagePattern[] = [];\n  // A variant-only role is in the required-role variants alone.\n  const full = schema;\n  schema = withoutVariantOnlyRoles(schema);\n\n  // Main pattern\n  patterns.push(generatePattern(grammar, schema, profile, config));\n\n  // Simple variant (without optional roles)\n  if (config.generateSimpleVariants) {\n    const simple = generateSimplePattern(grammar, schema, profile, config);\n    if (simple) {\n      patterns.push(simple);\n    }\n  }\n\n  // Omit-role variants: an EXTRA pattern per schema-listed role with that\n  // role (and its marker phrase) removed entirely. Covers a REQUIRED role\n  // whose phrase is legitimately absent in valid hyperscript (transition's\n  // goal: `transition *max-height over 300ms`, slide-toggle) — making the\n  // role optional inside the main pattern is the verified skippable-group\n  // re-binding regression (see the transition goal NOTE); a separate variant\n  // has no skippable group at all. Priority sits below the simple variant so\n  // any text carrying the role phrase always prefers the fuller patterns.\n  for (const omitted of schema.omitRoleVariants ?? []) {\n    const variantSchema: CommandSchema = {\n      ...schema,\n      roles: schema.roles.filter(r => r.role !== omitted),\n    };\n    const variant = generatePattern(grammar, variantSchema, profile, config);\n    patterns.push({\n      ...variant,\n      id: `${schema.action}-${profile.code}-generated-no-${omitted}`,\n      priority: (config.basePriority ?? 100) - 8,\n    });\n  }\n\n  // Widened-type variants: an EXTRA pattern per entry whose named role accepts a\n  // wider set of value types. Deliberately BELOW every command pattern, so it is\n  // inert on any span a real command can claim — see the schema field's doc for\n  // the ko `transition opacity to 0` collision that rules out widening the main\n  // pattern in place.\n  for (const widen of schema.widenTypeVariants ?? []) {\n    if (widen.excludeLanguages?.includes(profile.code)) continue;\n    const cloneSchema: CommandSchema = {\n      ...schema,\n      roles: schema.roles.map(r =>\n        r.role === widen.role ? { ...r, expectedTypes: [...widen.types] } : r\n      ),\n    };\n    const main = generatePattern(grammar, cloneSchema, profile, config);\n    patterns.push({\n      ...main,\n      id: `${schema.action}-${profile.code}-generated-${widen.idSuffix}`,\n      priority: (config.basePriority ?? 100) - (widen.priorityDelta ?? 15),\n    });\n  }\n\n  // Required-role variants: inert unless the role's marker is present, so they\n  // may outrank the command's other patterns (see the schema field).\n  for (const v of full.requiredRoleVariants ?? []) {\n    const variantSchema: CommandSchema = {\n      ...full,\n      roles: full.roles\n        .filter(r => !v.omit?.includes(r.role))\n        .map(r => {\n          const required = r.role === v.role ? { ...r, required: true } : r;\n          return r.role === v.widen?.role\n            ? { ...required, expectedTypes: [...v.widen.types] }\n            : required;\n        }),\n    };\n    const variant = generatePattern(grammar, variantSchema, profile, config);\n    patterns.push({\n      ...variant,\n      id: `${schema.action}-${profile.code}-generated-${v.idSuffix}`,\n      priority: (config.basePriority ?? 100) + (v.priorityDelta ?? 5),\n    });\n  }\n\n  // Verb-first fallback for SOV languages (lower priority than the above).\n  if (config.generateVerbFirstVariants !== false) {\n    const verbFirst = generateVerbFirstPattern(schema, profile, config);\n    if (verbFirst) {\n      patterns.push(verbFirst);\n    }\n  }\n\n  // Value-prefix-literal variants: an EXTRA pattern per entry with a REQUIRED\n  // literal keyword immediately before the named role's value (`go [to] url\n  // {destination}`). Higher priority than the counterpart pattern, but inert\n  // unless the keyword is present — base patterns above stay byte-identical,\n  // so forms riding on them (`go back`) cannot regress. The matched keyword is\n  // recorded as a fixed-value literal in the variant's methodCarrier role.\n  for (const v of schema.rolePrefixLiteralVariants ?? []) {\n    const literal = v.literal[profile.code];\n    if (!literal) continue;\n    const { rolePrefixLiteralVariants: _omitted, ...baseSchema } = schema;\n    const cloneSchema: CommandSchema = {\n      ...baseSchema,\n      roles: schema.roles.map(r =>\n        r.role === v.role ? { ...r, valuePrefixLiteral: { [profile.code]: literal } } : r\n      ),\n    };\n    const delta = v.priorityDelta ?? 5;\n    const carrier: Record<string, ExtractionRule> = v.methodCarrier\n      ? { [v.methodCarrier]: { value: literal } }\n      : {};\n    const main = generatePattern(grammar, cloneSchema, profile, config);\n    patterns.push({\n      ...main,\n      id: `${schema.action}-${profile.code}-generated-${v.idSuffix}`,\n      priority: (config.basePriority ?? 100) + delta,\n      extraction: { ...main.extraction, ...carrier },\n    });\n    if (config.generateVerbFirstVariants !== false) {\n      const verbFirstUrl = generateVerbFirstPattern(cloneSchema, profile, config);\n      if (verbFirstUrl) {\n        patterns.push({\n          ...verbFirstUrl,\n          id: `${schema.action}-${profile.code}-generated-verb-first-${v.idSuffix}`,\n          priority: (config.basePriority ?? 100) - 20 + delta,\n          extraction: { ...verbFirstUrl.extraction, ...carrier },\n        });\n      }\n    }\n  }\n\n  return patterns;\n}\n\n/**\n * Build pattern tokens based on word order.\n */\nfunction buildTokens(\n  grammar: SchemaPatternGrammar,\n  schema: CommandSchema,\n  profile: SchemaPatternProfile,\n  keyword: { primary: string; alternatives?: string[] }\n): PatternToken[] {\n  const tokens: PatternToken[] = [];\n\n  // Get verb token\n  const verbToken: PatternToken = keyword.alternatives\n    ? { type: 'literal', value: keyword.primary, alternatives: keyword.alternatives }\n    : { type: 'literal', value: keyword.primary };\n\n  // Get role tokens sorted by position. In SOV a role with `sovSlot: 'postVerb'`\n  // follows the verb (a domain's summarize format: `content 要約 として format`).\n  const postVerbRoles =\n    profile.wordOrder === 'SOV' ? schema.roles.filter(r => r.sovSlot === 'postVerb') : [];\n  const roleTokens = buildRoleTokens(\n    grammar,\n    postVerbRoles.length\n      ? { ...schema, roles: schema.roles.filter(r => r.sovSlot !== 'postVerb') }\n      : schema,\n    profile\n  );\n  const postVerbTokens = postVerbRoles.length\n    ? buildRoleTokens(grammar, { ...schema, roles: postVerbRoles }, profile)\n    : [];\n\n  // Arrange based on word order\n  switch (profile.wordOrder) {\n    case 'SVO':\n      // Verb first, then roles in order\n      tokens.push(verbToken);\n      tokens.push(...roleTokens);\n      break;\n\n    case 'SOV':\n      // Roles first (reversed for SOV), then verb\n      tokens.push(...roleTokens);\n      tokens.push(verbToken);\n      tokens.push(...postVerbTokens);\n      break;\n\n    case 'VSO':\n      // Verb first, then subject, then object\n      tokens.push(verbToken);\n      tokens.push(...roleTokens);\n      break;\n\n    default:\n      // Default to SVO\n      tokens.push(verbToken);\n      tokens.push(...roleTokens);\n  }\n\n  return collapseAdjacentLiterals(tokens);\n}\n\n/**\n * Collapse adjacent identical literal tokens into one.\n *\n * For the event-handler trigger (`on`) schema, a handful of languages use the\n * same word for the trigger keyword (the `on` verb) and the event role's marker —\n * bn `তে`, hi `पर`, th `เมื่อ`. `buildTokens` then emits it twice (`<event> তে তে`),\n * which the renderer prints verbatim; on re-parse the duplicate pairs with the\n * following token as a phantom command (e.g. `তে আমি` → a spurious `on me`). No\n * trigger pattern needs to match the same literal twice in a row, so fold the\n * duplicate, preserving any `alternatives` from either side. Verified to affect\n * only the `on` patterns of bn/hi/th — no other command/language has adjacent\n * duplicate literals. See MULTILINGUAL_BEHAVIORS_PLAN.md Phase 2.\n */\nfunction collapseAdjacentLiterals(tokens: PatternToken[]): PatternToken[] {\n  const out: PatternToken[] = [];\n  for (const tok of tokens) {\n    const prev = out[out.length - 1];\n    if (prev && prev.type === 'literal' && tok.type === 'literal' && prev.value === tok.value) {\n      const alts = [...(prev.alternatives ?? []), ...(tok.alternatives ?? [])];\n      if (alts.length) out[out.length - 1] = { ...prev, alternatives: [...new Set(alts)] };\n      continue;\n    }\n    out.push(tok);\n  }\n  return out;\n}\n\n/**\n * Build tokens for roles.\n */\nfunction buildRoleTokens(\n  grammar: SchemaPatternGrammar,\n  schema: CommandSchema,\n  profile: SchemaPatternProfile\n): PatternToken[] {\n  const tokens: PatternToken[] = [];\n\n  // Sort roles by position using shared utility\n  const sortedRoles = sortRolesByPosition(schema.roles, profile.wordOrder, grammar.positionOrder);\n\n  for (const roleSpec of sortedRoles) {\n    const roleToken = buildRoleToken(roleSpec, profile);\n\n    if (!roleSpec.required) {\n      // Wrap optional roles in a group\n      tokens.push({\n        type: 'group',\n        optional: true,\n        tokens: roleToken,\n      });\n    } else {\n      tokens.push(...roleToken);\n    }\n  }\n\n  return tokens;\n}\n\n/**\n * Build token(s) for a single role.\n *\n * Exported so the fused event-handler generators can build a wrapped command's\n * optional-role slots from the very same code the standalone command patterns\n * use — a hand-rolled copy there is what let the two drift apart in the first\n * place (see `appendRemainingOptionalRoles` in event-handlers-sov.ts).\n */\n/** The words a role reads in `language` (`RoleSpec.words`: its `'*'` list and the language's own). */\nfunction wordsFor(roleSpec: RoleSpec, language: string): readonly string[] | undefined {\n  if (!roleSpec.words) return undefined;\n  const words = [...(roleSpec.words['*'] ?? []), ...(roleSpec.words[language] ?? [])];\n  return words.length > 0 ? words : undefined;\n}\n\nfunction buildRoleToken(roleSpec: RoleSpec, profile: SchemaPatternProfile): PatternToken[] {\n  const tokens: PatternToken[] = [];\n\n  // Check for command-specific marker override first\n  const overrideMarker = roleSpec.markerOverride?.[profile.code];\n  const defaultMarker = profile.roleMarkers[roleSpec.role];\n\n  // A role whose renderOverride is the empty string parses WITH its marker but\n  // renders WITHOUT it (e.g. fetch's `from`: `fetch from /api` must parse, yet\n  // canonical _hyperscript rejects `fetch from \"/api\"` while accepting\n  // `fetch \"/api\"`). Tag the emitted marker literal so the renderer skips it;\n  // the pattern matcher ignores the flag, so parsing is unchanged.\n  const suppressMarker = roleSpec.renderOverride?.[profile.code] === '';\n  const words = wordsFor(roleSpec, profile.code);\n\n  // Role value token\n  const roleValueToken: PatternToken = {\n    type: 'role',\n    role: roleSpec.role,\n    optional: !roleSpec.required,\n    expectedTypes: roleSpec.expectedTypes,\n    // The matcher reads this too — a `'keyword'`-shaped slot holds a fixed\n    // keyword phrase (`using view transition`) and must not be skipped by the\n    // trailing-slot verb guard.\n    ...(roleSpec.valueShape !== undefined ? { valueShape: roleSpec.valueShape } : {}),\n    // A greedy role reads up to the next marker the pattern owes (a domain's\n    // SQL condition); its value reader does the reading.\n    ...(roleSpec.greedy ? { greedy: true } : {}),\n    // A role with a word list reads only one of its words.\n    ...(words ? { words } : {}),\n  };\n\n  // Required literal immediately before the role VALUE (rolePrefixLiteralVariants\n  // clones only): `[to] url {destination}`, `url {destination} に`. Deliberately\n  // NOT an optional group — the variant must only match when the keyword is\n  // present, so base patterns keep winning everywhere else.\n  const prefixLiteral = roleSpec.valuePrefixLiteral?.[profile.code];\n  const pushPrefixed = (): void => {\n    if (prefixLiteral) tokens.push({ type: 'literal', value: prefixLiteral });\n    tokens.push(roleValueToken);\n  };\n\n  // Use override marker if available, otherwise use default\n  if (overrideMarker !== undefined) {\n    // Command-specific marker override. Multi-word markers (e.g. \"partials in\",\n    // \"with title\") split into one literal token per word so the matcher\n    // consumes them sequentially. A per-command markerOptional wraps each word\n    // in an optional group (`go to /page` and `go back` both parse — the\n    // render side drops the preposition, so the parse side can't require it).\n    const markerWords = overrideMarker ? overrideMarker.split(/\\s+/).filter(Boolean) : [];\n    // Where the profile carries no RoleMarker for this role there is nothing to\n    // take a side from, and 'before' is wrong in a verb-final language: ja\n    // rendered `opacity を に 0` and bn `opacity কে তে 0`, the override marker\n    // stranded AHEAD of its own value. Default to 'after' for SOV.\n    //\n    // EXEMPT a PASSTHROUGH override — one whose marker is the same string en\n    // uses (`scope`, `manner`). Those are English words carried verbatim into\n    // every language, so they keep English's prepositional side; without the\n    // exemption ja/ko/qu lose `set`'s scope.\n    const isPassthroughOverride =\n      overrideMarker !== undefined && overrideMarker === roleSpec.markerOverride?.en;\n    const position =\n      roleSpec.markerPositionOverride?.[profile.code] ??\n      roleSpec.markerPosition ??\n      defaultMarker?.position ??\n      (profile.wordOrder === 'SOV' && !isPassthroughOverride ? 'after' : 'before');\n    const optionalMarker = roleSpec.markerOptional?.[profile.code] === true;\n    // Single-word overrides also accept every schema-declared alternative\n    // (markerLegacy ∪ markerVariants), so correcting an override's marker does\n    // not stop the previous one parsing, and declaring an override does not\n    // silently delete that language's variants. schemaMarkerAlternatives holds\n    // variants out for a methodCarrier role (`put`'s before/after) — see its doc.\n    const pushWord = (word: string): void => {\n      const alternatives =\n        markerWords.length === 1\n          ? (schemaMarkerAlternatives(roleSpec, profile.code, word) ?? [])\n          : [];\n      const literal: PatternToken = {\n        type: 'literal',\n        value: word,\n        ...(alternatives.length ? { alternatives } : {}),\n        ...(suppressMarker ? { renderSuppress: true } : {}),\n      };\n      tokens.push(optionalMarker ? { type: 'group', optional: true, tokens: [literal] } : literal);\n    };\n    if (position === 'before') {\n      for (const word of markerWords) pushWord(word);\n      pushPrefixed();\n    } else {\n      pushPrefixed();\n      for (const word of markerWords) pushWord(word);\n    }\n  } else if (defaultMarker) {\n    // When the profile allows colloquial marker-dropping, the marker becomes an\n    // optional group so `.active değiştir` parses as well as `.active i değiştir`.\n    // The marked form still matches the marker literal directly (higher\n    // confidence); the unmarked form falls back through the optional group.\n    // The schema's markerVariants/markerLegacy merge in as extra alternatives:\n    // the transformer can render a role with a particle the profile default\n    // doesn't cover (zh 把 before go's destination in `go back`).\n    const asMarker = (): PatternToken => {\n      const alternatives = [\n        ...new Set([\n          ...(defaultMarker.alternatives ?? []),\n          ...(schemaMarkerAlternatives(roleSpec, profile.code, defaultMarker.primary) ?? []),\n        ]),\n      ].filter(a => a !== defaultMarker.primary);\n      return {\n        type: 'literal',\n        value: defaultMarker.primary,\n        ...(alternatives.length ? { alternatives } : {}),\n        ...(suppressMarker ? { renderSuppress: true } : {}),\n      };\n    };\n    const pushMarker = (marker: PatternToken): void => {\n      if (!profile.markersOptional && !roleSpec.markerOptional?.[profile.code]) {\n        tokens.push(marker);\n        return;\n      }\n      // A profile-wide `markersOptional` says the marker may be DROPPED\n      // colloquially, not that it is absent from canonical output — so the group\n      // still renders. A per-role `markerOptional` is the opposite: the render\n      // side genuinely omits that marker (`go to /page` vs `go back`), so it\n      // stays render-optional too.\n      tokens.push({\n        type: 'group',\n        optional: true,\n        ...(profile.markersOptional && !roleSpec.markerOptional?.[profile.code]\n          ? { renderRequired: true }\n          : {}),\n        tokens: [marker],\n      });\n    };\n    // A schema's own side for the role (a domain's `markerPosition`) outranks the profile's.\n    if ((roleSpec.markerPosition ?? defaultMarker.position) === 'before') {\n      // Preposition: \"on #button\"\n      if (defaultMarker.primary) {\n        pushMarker(asMarker());\n      }\n      pushPrefixed();\n    } else {\n      // Postposition/particle: \"#button に\"\n      pushPrefixed();\n      pushMarker(asMarker());\n    }\n  } else {\n    // No marker, just the role value\n    pushPrefixed();\n  }\n\n  return tokens;\n}\n\n// =============================================================================\n// Extraction Rules Building\n// =============================================================================\n\n/**\n * Build extraction rules for a pattern.\n */\nfunction buildExtractionRules(\n  schema: CommandSchema,\n  profile: SchemaPatternProfile\n): Record<string, ExtractionRule> {\n  const rules: Record<string, ExtractionRule> = {};\n\n  for (const roleSpec of schema.roles) {\n    // Check for command-specific marker override first\n    const overrideMarker = roleSpec.markerOverride?.[profile.code];\n    const defaultMarker = profile.roleMarkers[roleSpec.role];\n\n    if (roleSpec.valuePrefixLiteral?.[profile.code]) {\n      // The prefix literal sits immediately before the value on every surface,\n      // so it is the extraction anchor (push/replace's proven `url` shape) —\n      // it wins over the role's own marker (`to`), which may be optional/absent.\n      rules[roleSpec.role] = { marker: roleSpec.valuePrefixLiteral[profile.code] };\n    } else if (overrideMarker !== undefined) {\n      // Use the override marker, accepting the schema's declared alternatives\n      // so a corrected marker does not stop the previous one parsing and an\n      // override does not delete that language's variants (mirrors\n      // buildRoleToken; single-word overrides only, as a multi-word marker has\n      // no single token to swap).\n      if (!overrideMarker) {\n        rules[roleSpec.role] = {};\n      } else {\n        const isSingleWord = !/\\s/.test(overrideMarker.trim());\n        const markerAlternatives = isSingleWord\n          ? (schemaMarkerAlternatives(roleSpec, profile.code, overrideMarker) ?? [])\n          : [];\n        rules[roleSpec.role] = markerAlternatives.length\n          ? { marker: overrideMarker, markerAlternatives }\n          : { marker: overrideMarker };\n      }\n    } else if (defaultMarker && defaultMarker.primary) {\n      // Merge the schema's declared alternatives (mirrors buildRoleToken)\n      const markerAlternatives = [\n        ...new Set([\n          ...(defaultMarker.alternatives ?? []),\n          ...(schemaMarkerAlternatives(roleSpec, profile.code, defaultMarker.primary) ?? []),\n        ]),\n      ].filter(a => a !== defaultMarker.primary);\n      rules[roleSpec.role] = markerAlternatives.length\n        ? { marker: defaultMarker.primary, markerAlternatives }\n        : { marker: defaultMarker.primary };\n    } else {\n      rules[roleSpec.role] = {};\n    }\n  }\n\n  return rules;\n}\n\n/**\n * Build extraction rules with defaults for optional roles.\n */\nfunction buildExtractionRulesWithDefaults(\n  schema: CommandSchema,\n  profile: SchemaPatternProfile\n): Record<string, ExtractionRule> {\n  const baseRules = buildExtractionRules(schema, profile);\n  const rules: Record<string, ExtractionRule> = {};\n\n  // Copy base rules and add defaults for optional roles\n  for (const roleSpec of schema.roles) {\n    const baseRule = baseRules[roleSpec.role] || {};\n\n    if (!roleSpec.required && roleSpec.default) {\n      rules[roleSpec.role] = { ...baseRule, default: roleSpec.default };\n    } else {\n      rules[roleSpec.role] = baseRule;\n    }\n  }\n\n  return rules;\n}\n\n// =============================================================================\n// Format String Building\n// =============================================================================\n\n/**\n * Build a human-readable format string for documentation.\n */\nfunction buildFormatString(\n  grammar: SchemaPatternGrammar,\n  schema: CommandSchema,\n  profile: SchemaPatternProfile,\n  keyword: { primary: string }\n): string {\n  const parts: string[] = [];\n\n  // Sort roles by position using shared utility\n  const sortedRoles = sortRolesByPosition(schema.roles, profile.wordOrder, grammar.positionOrder);\n\n  // Build role parts\n  const roleParts = sortedRoles.map(roleSpec => {\n    // Use shared marker resolution utility\n    const resolved = resolveMarkerForRole(roleSpec, profile);\n    let part = '';\n\n    if (resolved && resolved.primary) {\n      // Has a marker\n      if (resolved.position === 'before') {\n        part = `${resolved.primary} {${roleSpec.role}}`;\n      } else {\n        part = `{${roleSpec.role}} ${resolved.primary}`;\n      }\n    } else {\n      // No marker\n      part = `{${roleSpec.role}}`;\n    }\n\n    return roleSpec.required ? part : `[${part}]`;\n  });\n\n  // Arrange based on word order\n  switch (profile.wordOrder) {\n    case 'SVO':\n    case 'VSO':\n      parts.push(keyword.primary, ...roleParts);\n      break;\n    case 'SOV':\n      parts.push(...roleParts, keyword.primary);\n      break;\n    default:\n      parts.push(keyword.primary, ...roleParts);\n  }\n\n  return parts.join(' ');\n}\n","/**\n * Rendering a command through a language's own patterns: the renderer core\n * semantic's hyperscript renderer runs (domains rethink Phase 4.5,\n * `docs-internal/DOMAINS_RETHINK.md`), moved here from `@lokascript/semantic`.\n *\n * A node renders with the pattern its parser would read it back through:\n * `selectRenderPattern` scores a language's patterns for the node (the roles it\n * carries, the slots each pattern has, the values a pattern pins), and\n * `renderPattern` walks the chosen pattern's tokens. What a value looks like in\n * the language, and the grammar's preferences, are `PatternRenderHooks`.\n * (The domains' `renderer.ts` renders from the schema instead, for\n * `createMultilingualDSL`.)\n */\n\nimport type {\n  ExtractionRule,\n  GroupPatternToken,\n  LanguagePattern,\n  PatternToken,\n  RolePatternToken,\n  SemanticNode,\n} from '../core/types';\n\n/**\n * What the core reads of a node: its roles. A grammar's own node type (semantic's\n * `SemanticNode`) qualifies as it is; the hooks receive it unchanged.\n */\nexport interface RenderableNode {\n  readonly roles: ReadonlyMap<string, { readonly type: string }>;\n}\n\n/** A grammar's part of rendering through patterns, for its node type `N`. */\nexport interface PatternRenderHooks<N extends RenderableNode = SemanticNode> {\n  /**\n   * The patterns a node may render with, from those that are not parse-only\n   * (hyperscript: an event handler renders only with a trigger pattern, never a\n   * fused `<command>-event-*` one).\n   */\n  candidates?(node: N, patterns: readonly LanguagePattern[]): readonly LanguagePattern[];\n  /** Whether the node carries `role` as written, not as a default its parser filled in. */\n  hasRealRole(node: N, role: string): boolean;\n  /** The grammar's own preference between patterns, added to the score. */\n  adjustScore?(pattern: LanguagePattern, node: N): number;\n  /**\n   * Text for token `i` and the tokens after it it covers, when the grammar\n   * writes them as one (hyperscript: a reference in its case, es `a mí`);\n   * undefined renders the token as usual.\n   */\n  span?(\n    tokens: readonly PatternToken[],\n    i: number,\n    node: N,\n    language: string,\n    topLevel: boolean\n  ): { text: string; tokens: number } | undefined;\n  /** A role slot's text; null writes nothing. */\n  writeRole(token: RolePatternToken, node: N, language: string): string | null;\n  /**\n   * Whether an optional group whose required roles the node carries is written\n   * (hyperscript: not for the implicit `me` its parser filled in). Default yes.\n   */\n  writeGroup?(token: GroupPatternToken, node: N, language: string): boolean;\n  /**\n   * Add a token's text to `parts` (hyperscript: a marker written onto its\n   * word, ko `#out에`). Default: a part of its own.\n   */\n  pushPart?(\n    parts: string[],\n    text: string,\n    token: PatternToken,\n    previous: PatternToken | undefined,\n    node: N,\n    language: string\n  ): void;\n  /** Before top-level token `i` (hyperscript: a scroll's direction word before its amount). */\n  beforeToken?(\n    tokens: readonly PatternToken[],\n    i: number,\n    parts: string[],\n    node: N,\n    language: string\n  ): void;\n  /** After a top-level token wrote `parts[part]` (hyperscript: where the event went). */\n  afterToken?(token: PatternToken, part: number, node: N): void;\n}\n\n/**\n * Score a role slot nested inside an OPTIONAL group. Lower than the top-level\n * bonus on purpose: it must break a tie between two patterns that are otherwise\n * equal (the handcrafted `toggle-{L}-full` versus the generated pattern that\n * also carries `[{duration}]`) without ever outweighing a top-level difference.\n */\nconst NESTED_ROLE_BONUS = 5;\n\n/**\n * Score against a pattern that has no slot for a role the node carries. Larger\n * than any priority gap between a command's patterns (80–100), so rendering\n * the role always beats a more idiomatic form that drops it.\n */\nconst UNCOVERED_ROLE_PENALTY = 30;\n\n/**\n * The literal a pattern pins a role to, normalized for comparison: an\n * extraction default, or a fixed value the pattern records when it matches.\n * The second is how `go`'s url variant says what it means (`go url /page`\n * records `method: 'url'`); reading only defaults let that variant render every\n * `go`, so `go back` came out as `go url back`: a navigation to a page named\n * \"back\" in every language.\n */\nfunction pinnedLiteral(rule: ExtractionRule | undefined): string | undefined {\n  if (rule?.default?.type === 'literal') return String(rule.default.value).trim().toLowerCase();\n  if (rule?.value !== undefined) return String(rule.value).trim().toLowerCase();\n  return undefined;\n}\n\n/**\n * The pattern to render `node` with, or null when there is none.\n */\nexport function selectRenderPattern<N extends RenderableNode>(\n  node: N,\n  patterns: readonly LanguagePattern[],\n  hooks: PatternRenderHooks<N>\n): LanguagePattern | null {\n  let candidates: readonly LanguagePattern[] = patterns.filter(pattern => !pattern.parseOnly);\n  if (candidates.length === 0) candidates = patterns;\n  if (hooks.candidates) candidates = hooks.candidates(node, candidates);\n\n  // Which literal values does the candidate set pin, per role? A value that is\n  // pinned by SOME candidate is a real alternative the pattern set distinguishes\n  // (put's manner: before / after / at end of), so choosing a pattern pinned to a\n  // different one would silently change meaning. A value nothing pins is not an\n  // alternative — it is just the value that came out of the parse — and must not\n  // disqualify anything. That distinction is what keeps `repeat until event X`\n  // renderable: a zh parse yields loopType `until` while the English pattern that\n  // carries the event pins `until-event`, and nothing pins bare `until`.\n  const pinnedValues = new Map<string, Set<string>>();\n  for (const pattern of candidates) {\n    for (const [role, rule] of Object.entries(pattern.extraction ?? {})) {\n      const key = pinnedLiteral(rule);\n      if (key === undefined) continue;\n      const set = pinnedValues.get(role) ?? new Set<string>();\n      set.add(key);\n      pinnedValues.set(role, set);\n    }\n  }\n\n  // Score patterns by how well they match our roles\n  const scored = candidates.map(pattern => {\n    let score = pattern.priority;\n\n    // Check each role token in the pattern, INCLUDING the ones nested inside\n    // optional groups. Scoring only the top level made a slot the pattern\n    // really has invisible: every `[for {duration}]` / `[with {style}]` group\n    // lives one level down, so a handcrafted pattern without the slot tied\n    // with the generated one that has it and won on order — `toggle .loading\n    // for 2s` rendered as `alternar .loading` in es/it/pl/ru/uk/vi/zh, the\n    // duration dropped in silence.\n    //\n    // A role inside a group is scored as PRESENT-only: its absence is what\n    // \"optional\" means, and the group's own role tokens are not consistently\n    // flagged `optional` (a handcrafted `[en {destination}]` writes the role\n    // bare), so reading the flag there would apply the missing-role penalty to\n    // a slot that is optional by construction.\n    const hasRealRole = (role: string): boolean => hooks.hasRealRole(node, role);\n    const scoreTokens = (tokens: readonly PatternToken[], inGroup: boolean): void => {\n      for (const token of tokens) {\n        if (token.type === 'group') {\n          scoreTokens(token.tokens, true);\n        } else if (token.type === 'role') {\n          if (hasRealRole(token.role)) {\n            // Bonus for patterns that use roles we have. A nested slot scores\n            // LESS than a top-level one, so carrying an extra optional slot\n            // breaks a tie without ever outweighing a top-level difference —\n            // measured: at equal weight it also re-ordered the pl behavior\n            // handler and three qu positional rows.\n            score += inGroup ? NESTED_ROLE_BONUS : 10;\n          } else if (!inGroup && !token.optional) {\n            // Heavy penalty for patterns that require roles we DON'T have\n            // This prevents selecting \"source\" patterns when there's no source\n            score -= 50;\n          }\n        }\n      }\n    };\n    scoreTokens(pattern.template.tokens, false);\n\n    // A pattern with no slot for a role the node really carries drops it in\n    // silence, so it loses to one that renders it. The bonuses above only\n    // reward coverage, which let a slot-less pattern win on a top-level-vs-\n    // nested difference: once show's patient became optional, zh `显示\n    // {patient}` beat the generated `显示 [把 {patient}] [用 {style}]` and\n    // `show #modal with *opacity` rendered without its strategy (bn/hi/zh).\n    const slots = new Set<string>();\n    const collectSlots = (tokens: readonly PatternToken[]): void => {\n      for (const token of tokens) {\n        if (token.type === 'group') collectSlots(token.tokens);\n        else if (token.type === 'role') slots.add(token.role);\n      }\n    };\n    collectSlots(pattern.template.tokens);\n    for (const role of node.roles.keys()) {\n      if (hasRealRole(role) && !slots.has(role)) score -= UNCOVERED_ROLE_PENALTY;\n    }\n\n    // Value-pinned variants. A positional pattern (`put X before Y`, `at end\n    // of`, `after`) carries its position as a baked-in literal plus an\n    // extraction default that records which value it means:\n    //   put-es-before -> extraction.manner.default = 'before'\n    //   put-es-at-end -> extraction.manner.default = 'at end of'\n    // while the neutral `put-es-full` pins nothing. So the pattern set already\n    // says which surface each value selects; scoring just has to read it.\n    //\n    // The rule: a pattern that pins a role to a literal may be chosen ONLY when\n    // the node carries that exact value. Matching is a strong preference (the\n    // pinned form is the whole reason the value exists); mismatching — or the\n    // node not carrying the role at all — disqualifies it, so a plain\n    // `put X into Y` can never render as `poner X en fin de Y`.\n    //\n    // This replaces an id-regex that penalized every `-at-end|-before|-after`\n    // pattern unconditionally. That kept plain puts safe but made the positional\n    // forms unreachable: `put \"<p>\" before me` rendered with the into-pattern in\n    // all 23 languages, losing the distinction the source drew.\n    for (const [role, rule] of Object.entries(pattern.extraction ?? {})) {\n      const pinnedKey = pinnedLiteral(rule);\n      if (pinnedKey === undefined) continue;\n      const actual = node.roles.get(role);\n      // The value as the pattern would produce it: a literal, or an\n      // expression where the rule says so (`go back`).\n      const actualKey =\n        actual?.type === (rule.valueIsExpression ? 'expression' : 'literal')\n          ? String(\n              actual.type === 'expression'\n                ? (actual as { raw?: unknown }).raw\n                : (actual as { value?: unknown }).value\n            )\n              .trim()\n              .toLowerCase()\n          : undefined;\n\n      if (actualKey === pinnedKey) {\n        // The pinned form is the whole reason this value exists — prefer it\n        // decisively over the neutral pattern, whatever the parse priorities say.\n        score += 60;\n      } else if (actualKey === undefined || pinnedValues.get(role)?.has(actualKey)) {\n        // Either the node has no such value (so this pattern would invent one:\n        // a plain `put X into Y` must never render as `put X at end of Y`), or it\n        // has a DIFFERENT value that the pattern set treats as an alternative.\n        // Both are wrong surfaces; disqualify.\n        score -= 200;\n      }\n      // Otherwise the node's value is not one of the pinned alternatives, so this\n      // pattern is still the best available carrier for it — leave the score alone\n      // and let priority and role coverage decide.\n    }\n\n    score += hooks.adjustScore?.(pattern, node) ?? 0;\n\n    return { pattern, score };\n  });\n\n  scored.sort((a, b) => b.score - a.score);\n\n  return scored.length > 0 ? scored[0]!.pattern : null;\n}\n\n/**\n * The parts `node` renders to through `pattern`'s tokens, in order: each\n * literal (unless parse-only), each role's text, each group that is written.\n * The grammar joins them (and adds what the pattern does not model).\n */\nexport function renderPattern<N extends RenderableNode>(\n  node: N,\n  pattern: LanguagePattern,\n  hooks: PatternRenderHooks<N>\n): string[] {\n  const parts: string[] = [];\n  const language = pattern.language;\n  const tokens = pattern.template.tokens;\n  for (let i = 0; i < tokens.length; i++) {\n    hooks.beforeToken?.(tokens, i, parts, node, language);\n    const span = hooks.span?.(tokens, i, node, language, true);\n    if (span !== undefined) {\n      parts.push(span.text);\n      i += span.tokens - 1;\n      continue;\n    }\n    const token = tokens[i]!;\n    const rendered = renderPatternToken(token, node, language, hooks);\n    if (rendered !== null) {\n      pushPart(hooks, parts, rendered, token, tokens[i - 1], node, language);\n      hooks.afterToken?.(token, parts.length - 1, node);\n    }\n  }\n  return parts;\n}\n\nfunction pushPart<N extends RenderableNode>(\n  hooks: PatternRenderHooks<N>,\n  parts: string[],\n  text: string,\n  token: PatternToken,\n  previous: PatternToken | undefined,\n  node: N,\n  language: string\n): void {\n  if (hooks.pushPart) hooks.pushPart(parts, text, token, previous, node, language);\n  else parts.push(text);\n}\n\n/**\n * Render a single pattern token.\n */\nfunction renderPatternToken<N extends RenderableNode>(\n  token: PatternToken,\n  node: N,\n  language: string,\n  hooks: PatternRenderHooks<N>\n): string | null {\n  switch (token.type) {\n    case 'literal':\n      // Parse-only markers (renderSuppress) consume input but never render —\n      // e.g. fetch's `from`, which parses `fetch from /api` yet must be absent\n      // from output (`fetch from \"/api\"` is invalid canonical _hyperscript).\n      return token.renderSuppress ? null : token.value;\n\n    case 'role':\n      return hooks.writeRole(token, node, language);\n\n    case 'group': {\n      // Check if we have all required roles in the group\n      const hasRequired = token.tokens\n        .filter(t => t.type === 'role' && !t.optional)\n        .every(t => node.roles.has((t as RolePatternToken).role));\n\n      if (!hasRequired && token.optional) {\n        return null;\n      }\n\n      if (hooks.writeGroup && !hooks.writeGroup(token, node, language)) return null;\n\n      const groupParts: string[] = [];\n      let hasRoleValue = false;\n      for (let i = 0; i < token.tokens.length; i++) {\n        const span = hooks.span?.(token.tokens, i, node, language, false);\n        if (span !== undefined) {\n          groupParts.push(span.text);\n          hasRoleValue = true;\n          i += span.tokens - 1;\n          continue;\n        }\n        const subToken = token.tokens[i]!;\n        const rendered = renderPatternToken(subToken, node, language, hooks);\n        if (rendered !== null) {\n          pushPart(hooks, groupParts, rendered, subToken, token.tokens[i - 1], node, language);\n          if (subToken.type === 'role') hasRoleValue = true;\n        }\n      }\n\n      // Don't emit an optional group that DECLARES a role slot and did not\n      // fill it — e.g. don't emit a dangling \"with\" when the style role is\n      // absent from \"hide #output\".\n      //\n      // …unless the group is `renderRequired`: a MARKER wrapped on its own by\n      // `profile.markersOptional` (tr, where the case suffix may be dropped\n      // colloquially, so the parse side has to accept both forms). Dropping\n      // those cost tr every role marker in every rendered command —\n      // `add .selected to #item` came out `#item .selected ekle` where the\n      // corpus has `#item e .selected i ekle`, and the marker-less surface\n      // re-parses as a one-role `add` with the destination defaulted to `me`.\n      if (token.optional && !hasRoleValue && !token.renderRequired) return null;\n\n      return groupParts.length > 0 ? groupParts.join(' ') : null;\n    }\n\n    default:\n      return null;\n  }\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 * Value Extractor Interface - Pluggable Tokenization\n *\n * Extracts typed values from input strings.\n * DSLs can provide custom extractors for their domain-specific syntax.\n *\n * Includes the ContextAwareExtractor extension for extractors that need\n * access to tokenizer state (keyword maps, morphological normalizers, etc.).\n */\n\nimport type { MorphologicalNormalizer } from '../core/tokenization/morphology/types';\n\n// =============================================================================\n// Keyword Entry (needed by TokenizerContext)\n// =============================================================================\n\n/**\n * Keyword entry for tokenizer - maps native word to normalized English form.\n * Re-exported here so ContextAwareExtractor consumers can use it without\n * depending on the base-tokenizer module directly.\n */\nexport interface KeywordEntry {\n  readonly native: string;\n  readonly normalized: string;\n}\n\n// =============================================================================\n// Core Extractor Types\n// =============================================================================\n\n/**\n * Extraction result with value and consumed length.\n */\nexport interface ExtractionResult {\n  /** The extracted value */\n  readonly value: string;\n\n  /** Number of characters consumed */\n  readonly length: number;\n\n  /** Optional metadata about the extraction */\n  readonly metadata?: Record<string, unknown>;\n}\n\n/**\n * Value extractor - identifies and extracts typed values from input.\n */\nexport interface ValueExtractor {\n  /** Name of this extractor (for debugging) */\n  readonly name: string;\n\n  /**\n   * Check if this extractor can handle input at position.\n   *\n   * @param input - Full input string\n   * @param position - Current position\n   * @returns True if this extractor should try\n   *\n   * @example\n   * // CSS selector extractor\n   * canExtract('#button', 0) // → true (starts with #)\n   * canExtract('button', 0)  // → false\n   */\n  canExtract(input: string, position: number): boolean;\n\n  /**\n   * Extract value from input at position.\n   *\n   * @param input - Full input string\n   * @param position - Start position\n   * @returns Extraction result or null if extraction failed\n   *\n   * @example\n   * extract('#button', 0) // → { value: '#button', length: 7 }\n   * extract('button', 0)  // → null (can't extract CSS selector)\n   */\n  extract(input: string, position: number): ExtractionResult | null;\n}\n\n/**\n * String literal extractor - handles quoted strings.\n */\nexport class StringLiteralExtractor implements ValueExtractor {\n  readonly name = 'string-literal';\n\n  canExtract(input: string, position: number): boolean {\n    const char = input[position];\n    // An ASCII apostrophe glued to the END of a word is the possessive marker\n    // (`#price's value`, `my's` never occurs but `it's`/`#qty's` do), not a\n    // string opener. Reading it as a quote paired it with the NEXT possessive:\n    // `(#price's value * #qty's value)` lexed `'s value * #qty'` as one string\n    // literal, which swallowed the operator and hid the property noun from\n    // translation in every language that renders `'s`. A quote that opens a\n    // string always follows whitespace, punctuation, or the start of input.\n    // A word can end in a combining mark: bn `ঘটনা`, hi `घटना` and th\n    // `เหตุการณ์` (event) end in a vowel sign or a tone mark, and without\n    // `\\p{M}` their `'s` paired with the next one (`ঘটনা's target's id` lexed\n    // `'s target'` as a string).\n    if (char === \"'\" && position > 0 && /[\\p{L}\\p{M}\\p{N}_)\\]]/u.test(input[position - 1])) {\n      return false;\n    }\n    return (\n      char === '\"' ||\n      char === \"'\" ||\n      char === '`' ||\n      char === '\\u201C' || // Chinese double quote open \"\n      char === '\\u2018' // Chinese single quote open '\n    );\n  }\n\n  extract(input: string, position: number): ExtractionResult | null {\n    const quote = input[position];\n\n    // Chinese double quotes \" ... \"\n    if (quote === '\\u201C') {\n      let length = 1;\n      while (position + length < input.length) {\n        if (input[position + length] === '\\u201D') {\n          length++;\n          return { value: input.substring(position, position + length), length };\n        }\n        length++;\n      }\n      return null;\n    }\n\n    // Chinese single quotes ' ... '\n    if (quote === '\\u2018') {\n      let length = 1;\n      while (position + length < input.length) {\n        if (input[position + length] === '\\u2019') {\n          length++;\n          return { value: input.substring(position, position + length), length };\n        }\n        length++;\n      }\n      return null;\n    }\n\n    // ASCII quotes (same open/close, support escaping)\n    let length = 1;\n    let escaped = false;\n\n    while (position + length < input.length) {\n      const char = input[position + length];\n\n      if (escaped) {\n        escaped = false;\n        length++;\n        continue;\n      }\n\n      if (char === '\\\\') {\n        escaped = true;\n        length++;\n        continue;\n      }\n\n      if (char === quote) {\n        length++; // Include closing quote\n        return {\n          value: input.substring(position, position + length),\n          length,\n        };\n      }\n\n      length++;\n    }\n\n    // Unterminated string\n    return null;\n  }\n}\n\n/**\n * Number extractor - handles integers and floats.\n */\nexport class NumberExtractor implements ValueExtractor {\n  readonly name = 'number';\n\n  canExtract(input: string, position: number): boolean {\n    return /\\d/.test(input[position]);\n  }\n\n  extract(input: string, position: number): ExtractionResult | null {\n    let length = 0;\n    let hasDecimal = false;\n\n    while (position + length < input.length) {\n      const char = input[position + length];\n\n      if (/\\d/.test(char)) {\n        length++;\n      } else if (char === '.' && !hasDecimal) {\n        hasDecimal = true;\n        length++;\n      } else {\n        break;\n      }\n    }\n\n    if (length === 0) return null;\n\n    const numValue = input.substring(position, position + length);\n    const afterNum = position + length;\n\n    // Check for time unit suffixes\n    if (afterNum < input.length) {\n      const remaining = input.slice(afterNum);\n\n      // CJK multi-char time units (longest first)\n      const cjkMultiUnits: { pattern: string; suffix: string }[] = [\n        { pattern: '毫秒', suffix: 'ms' }, // Chinese milliseconds\n        { pattern: '分钟', suffix: 'm' }, // Chinese minutes\n        { pattern: '小时', suffix: 'h' }, // Chinese hours\n        { pattern: 'ミリ秒', suffix: 'ms' }, // Japanese milliseconds\n        { pattern: '時間', suffix: 'h' }, // Japanese hours\n      ];\n      for (const unit of cjkMultiUnits) {\n        if (remaining.startsWith(unit.pattern)) {\n          return {\n            value: numValue + unit.suffix,\n            length: length + unit.pattern.length,\n            metadata: { hasTimeUnit: true },\n          };\n        }\n      }\n\n      // ASCII 'ms' (2 chars, must check before single-char)\n      if (remaining.startsWith('ms')) {\n        return {\n          value: numValue + 'ms',\n          length: length + 2,\n          metadata: { hasTimeUnit: true },\n        };\n      }\n\n      // CJK single-char time units\n      const cjkSingleUnits: { pattern: string; suffix: string }[] = [\n        { pattern: '秒', suffix: 's' }, // CJK seconds\n        { pattern: '分', suffix: 'm' }, // CJK minutes\n      ];\n      for (const unit of cjkSingleUnits) {\n        if (remaining.startsWith(unit.pattern)) {\n          return {\n            value: numValue + unit.suffix,\n            length: length + 1,\n            metadata: { hasTimeUnit: true },\n          };\n        }\n      }\n\n      // ASCII single-char units: s, m, h (with word boundary check)\n      if (/^[smh](?![a-zA-Z])/.test(remaining)) {\n        return {\n          value: numValue + remaining[0],\n          length: length + 1,\n          metadata: { hasTimeUnit: true },\n        };\n      }\n    }\n\n    return { value: numValue, length };\n  }\n}\n\n/**\n * Identifier extractor - handles variable/property names.\n */\nexport class IdentifierExtractor implements ValueExtractor {\n  readonly name = 'identifier';\n\n  canExtract(input: string, position: number): boolean {\n    return /[a-zA-Z_]/.test(input[position]);\n  }\n\n  extract(input: string, position: number): ExtractionResult | null {\n    let length = 0;\n\n    while (position + length < input.length) {\n      const char = input[position + length];\n      if (/[a-zA-Z0-9_]/.test(char)) {\n        length++;\n      } else {\n        break;\n      }\n    }\n\n    return length > 0\n      ? {\n          value: input.substring(position, position + length),\n          length,\n        }\n      : null;\n  }\n}\n\n/**\n * Unicode identifier extractor - handles non-Latin scripts.\n *\n * Matches contiguous runs of Unicode letters, numbers, and combining marks\n * that aren't ASCII (ASCII identifiers are handled by IdentifierExtractor).\n * Essential for DSLs supporting CJK, Arabic, Cyrillic, Devanagari, etc.\n */\nexport class UnicodeIdentifierExtractor implements ValueExtractor {\n  readonly name = 'unicode-identifier';\n\n  canExtract(input: string, position: number): boolean {\n    const code = input.charCodeAt(position);\n    // Skip ASCII range (handled by IdentifierExtractor)\n    if (code < 0x80) return false;\n    // Match any Unicode letter\n    return /\\p{L}/u.test(input[position]);\n  }\n\n  extract(input: string, position: number): ExtractionResult | null {\n    let length = 0;\n\n    while (position + length < input.length) {\n      const char = input[position + length];\n      // Match Unicode letters, numbers, and combining marks (e.g., Arabic diacritics)\n      if (/[\\p{L}\\p{N}\\p{M}]/u.test(char)) {\n        length++;\n      } else {\n        break;\n      }\n    }\n\n    return length > 0 ? { value: input.substring(position, position + length), length } : null;\n  }\n}\n\n/**\n * Latin Extended identifier extractor — handles Latin-script languages with\n * diacritics (Spanish ñ/á/é/í/ó/ú; French é/à/ù/ç; Turkish ç/ş/ı/ü/ğ/ö;\n * Portuguese ã/õ; German ä/ö/ü/ß; etc).\n *\n * Use this in addition to (or instead of) the default `IdentifierExtractor`\n * for any tokenizer whose language is Latin-script and may contain diacritic\n * characters in identifiers. Without it, words like `añadir` tokenize as\n * `[\"a\", \"ñadir\"]` because the default ASCII extractor stops at `ñ` and the\n * Unicode extractor only kicks in when a token *starts* with a non-ASCII\n * character.\n *\n * Matches contiguous runs of `/[\\p{L}\\p{N}_-]/u` — any Unicode letter or\n * number, plus underscore and hyphen.\n */\nexport class LatinExtendedIdentifierExtractor implements ValueExtractor {\n  readonly name = 'latin-extended-identifier';\n\n  canExtract(input: string, position: number): boolean {\n    return /\\p{L}/u.test(input[position]);\n  }\n\n  extract(input: string, position: number): ExtractionResult | null {\n    let end = position;\n    while (end < input.length && /[\\p{L}\\p{N}_-]/u.test(input[end])) {\n      end++;\n    }\n    if (end === position) return null;\n    return { value: input.slice(position, end), length: end - position };\n  }\n}\n\n/**\n * CSS selector extractor — keeps `#id` and `.class` a SINGLE token.\n *\n * Without it the sigil is split off as its own token and the role capture keeps\n * only that sigil: `add .active to #button` parses with patient `\".\"` and\n * destination `\"#\"`, silently, in every language. Five domain DSLs each carried\n * a private copy of this class and four (learn, todo, sql, jsx) had none — this\n * is the shared one; register it via `customExtractors`.\n *\n * The character after the sigil must be a letter, `_` or `-`: a CSS identifier\n * cannot start with a digit, and refusing to claim a bare `.`/`#` leaves\n * property access and other uses of those characters to the extractors that own\n * them.\n *\n * The body is Unicode so diacritics survive (`.año`, not `.a`) but STOPS at Han,\n * kana and Hangul. Those scripts are where the SOV languages write their\n * particles, and a selector is written adjacent to them with no space:\n * `#buttonに .activeを 追加` must yield `#button` + `に`, not a `#buttonに` that\n * swallows the particle and takes the role marker with it.\n */\nconst SELECTOR_BODY_CHAR = /[\\p{L}\\p{N}_-]/u;\nconst PARTICLE_SCRIPT_CHAR = /[\\p{sc=Han}\\p{sc=Hiragana}\\p{sc=Katakana}\\p{sc=Hangul}]/u;\n\nfunction isSelectorBodyChar(char: string): boolean {\n  return SELECTOR_BODY_CHAR.test(char) && !PARTICLE_SCRIPT_CHAR.test(char);\n}\n\nexport class CssSelectorExtractor implements ValueExtractor {\n  readonly name = 'css-selector';\n\n  canExtract(input: string, position: number): boolean {\n    const char = input[position];\n    if (char !== '#' && char !== '.') return false;\n    const next = input[position + 1];\n    if (next === undefined) return false;\n    return (\n      next === '_' || next === '-' || (/\\p{L}/u.test(next) && !PARTICLE_SCRIPT_CHAR.test(next))\n    );\n  }\n\n  extract(input: string, position: number): ExtractionResult | null {\n    let end = position + 1;\n    while (end < input.length && isSelectorBodyChar(input[end])) {\n      end++;\n    }\n    if (end === position + 1) return null;\n    return { value: input.slice(position, end), length: end - position };\n  }\n}\n\n/**\n * Whitespace extractor - handles spaces, tabs, newlines.\n */\nexport class WhitespaceExtractor implements ValueExtractor {\n  readonly name = 'whitespace';\n\n  canExtract(input: string, position: number): boolean {\n    return /\\s/.test(input[position]);\n  }\n\n  extract(input: string, position: number): ExtractionResult | null {\n    let length = 0;\n\n    while (position + length < input.length && /\\s/.test(input[position + length])) {\n      length++;\n    }\n\n    return length > 0\n      ? {\n          value: input.substring(position, position + length),\n          length,\n        }\n      : null;\n  }\n}\n\n// =============================================================================\n// Context-Aware Extractor System\n// =============================================================================\n\n/**\n * Tokenizer context provided to context-aware extractors.\n * Gives extractors access to tokenizer state without tight coupling.\n */\nexport interface TokenizerContext {\n  /** ISO 639-1 language code */\n  readonly language: string;\n\n  /** Text direction */\n  readonly direction: 'ltr' | 'rtl';\n\n  /**\n   * Look up a keyword by its native form.\n   * Returns keyword entry with normalized form, or undefined if not found.\n   */\n  lookupKeyword(native: string): KeywordEntry | undefined;\n\n  /**\n   * Check if a word is a known keyword.\n   */\n  isKeyword(native: string): boolean;\n\n  /**\n   * Check if a known keyword starts at the given position.\n   * Useful for word boundary detection in non-space languages.\n   */\n  isKeywordStart(input: string, position: number): boolean;\n\n  /**\n   * Like `isKeywordStart`, but only true when the keyword match ends at a\n   * word boundary (end of input or a char rejected by `isWordChar`).\n   * Space-delimited languages must use this for word-walk break checks —\n   * the keyword table includes English canonical fallbacks (me, it, you, …),\n   * so the raw check splits native words mid-word (e.g. Quechua ñit'iy\n   * contains \"it\"). Optional for backward compatibility with hand-rolled\n   * contexts; callers should treat absence as \"no boundary keyword here\".\n   */\n  isKeywordStartAtBoundary?(\n    input: string,\n    position: number,\n    isWordChar?: (char: string) => boolean\n  ): boolean;\n\n  /**\n   * Optional morphological normalizer for this language.\n   */\n  readonly normalizer?: MorphologicalNormalizer;\n}\n\n/**\n * Context-aware extractor - has access to tokenizer state.\n *\n * Use this for extractors that need:\n * - Keyword lookup (for normalization)\n * - Morphological analysis (for conjugation handling)\n * - Language-specific rules\n *\n * For stateless extractors (strings, numbers, operators), use ValueExtractor.\n */\nexport interface ContextAwareExtractor extends ValueExtractor {\n  /**\n   * Set the tokenizer context.\n   * Called once by the tokenizer during registration.\n   */\n  setContext(context: TokenizerContext): void;\n}\n\n/**\n * Type guard to check if an extractor is context-aware.\n */\nexport function isContextAwareExtractor(\n  extractor: ValueExtractor | ContextAwareExtractor\n): extractor is ContextAwareExtractor {\n  return 'setContext' in extractor && typeof extractor.setContext === 'function';\n}\n\n/**\n * Create a TokenizerContext from a tokenizer instance.\n * Works with any object that exposes the required methods.\n */\nexport function createTokenizerContext(tokenizer: {\n  language: string;\n  direction: 'ltr' | 'rtl';\n  lookupKeyword(native: string): KeywordEntry | undefined;\n  isKeyword(native: string): boolean;\n  isKeywordStart(input: string, position: number): boolean;\n  isKeywordStartAtBoundary?(\n    input: string,\n    position: number,\n    isWordChar?: (char: string) => boolean\n  ): boolean;\n  normalizer?: MorphologicalNormalizer;\n}): TokenizerContext {\n  const ctx: TokenizerContext = {\n    language: tokenizer.language,\n    direction: tokenizer.direction,\n    lookupKeyword: tokenizer.lookupKeyword.bind(tokenizer),\n    isKeyword: tokenizer.isKeyword.bind(tokenizer),\n    isKeywordStart: tokenizer.isKeywordStart.bind(tokenizer),\n    ...(tokenizer.isKeywordStartAtBoundary\n      ? { isKeywordStartAtBoundary: tokenizer.isKeywordStartAtBoundary.bind(tokenizer) }\n      : {}),\n  };\n\n  if (tokenizer.normalizer) {\n    return { ...ctx, normalizer: tokenizer.normalizer };\n  }\n\n  return ctx;\n}\n","/**\n * Reference Validation — re-exported from @lokascript/intent\n */\n\nexport { DEFAULT_REFERENCES, isValidReference } from '@lokascript/intent';\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 * LLM JSON Schema Conversion (DEPRECATED)\n *\n * These functions are superseded by the unified protocol JSON functions in\n * protocol-json.ts. `fromProtocolJSON()` now accepts optional `kind` (defaults\n * to \"command\") and `trigger` sugar, making these wrappers unnecessary.\n *\n * Use instead:\n * - `validateProtocolJSON()` instead of `validateSemanticJSON()`\n * - `fromProtocolJSON()` instead of `jsonToSemanticNode()`\n * - `toProtocolJSON()` instead of `semanticNodeToJSON()`\n *\n * These functions are kept for backward compatibility and will be removed\n * in a future major version.\n */\n\nimport type {\n  SemanticNode,\n  SemanticValue,\n  SemanticRole,\n  EventHandlerSemanticNode,\n  CompoundSemanticNode,\n} from '../core/types';\nimport {\n  createCommandNode,\n  createEventHandlerNode,\n  createSelector,\n  createLiteral,\n  createReference,\n  createExpression,\n  createFlag,\n} from '../core/types';\nimport type { SemanticJSON, SemanticJSONValue, IRDiagnostic } from './types';\n\n// =============================================================================\n// Validation\n// =============================================================================\n\nconst VALID_VALUE_TYPES = new Set([\n  'selector',\n  'literal',\n  'reference',\n  'expression',\n  'property-path',\n  'flag',\n]);\n\n/**\n * Validate LLM JSON input structure.\n * Returns diagnostics (empty array = valid).\n * @deprecated Use `validateProtocolJSON()` from `protocol-json.ts` instead.\n */\nexport function validateSemanticJSON(input: SemanticJSON): IRDiagnostic[] {\n  const diagnostics: IRDiagnostic[] = [];\n\n  // Action is required and must be a string\n  if (!input.action || typeof input.action !== 'string') {\n    diagnostics.push({\n      severity: 'error',\n      code: 'INVALID_ACTION',\n      message: 'Field \"action\" is required and must be a string.',\n      suggestion: 'Provide a command name like \"toggle\", \"add\", \"set\", etc.',\n    });\n    return diagnostics; // Can't proceed without action\n  }\n\n  // Roles validation\n  if (input.roles && typeof input.roles === 'object') {\n    for (const [role, value] of Object.entries(input.roles)) {\n      if (!value || typeof value !== 'object') {\n        diagnostics.push({\n          severity: 'error',\n          code: 'INVALID_ROLE_VALUE',\n          message: `Role \"${role}\" must be an object with \"type\" and \"value\" fields.`,\n          suggestion: 'Use: { \"type\": \"selector\", \"value\": \".active\" }',\n        });\n        continue;\n      }\n\n      const v = value as SemanticJSONValue;\n      if (!VALID_VALUE_TYPES.has(v.type)) {\n        diagnostics.push({\n          severity: 'error',\n          code: 'INVALID_VALUE_TYPE',\n          message: `Role \"${role}\" has invalid type \"${v.type}\".`,\n          suggestion: 'Valid types: selector, literal, reference, expression, property-path.',\n        });\n      }\n\n      if (v.value === undefined || v.value === null) {\n        diagnostics.push({\n          severity: 'error',\n          code: 'MISSING_VALUE',\n          message: `Role \"${role}\" is missing the \"value\" field.`,\n        });\n      }\n    }\n  }\n\n  // Trigger validation (optional)\n  if (input.trigger) {\n    if (!input.trigger.event || typeof input.trigger.event !== 'string') {\n      diagnostics.push({\n        severity: 'error',\n        code: 'INVALID_TRIGGER',\n        message: 'Trigger \"event\" is required and must be a string.',\n        suggestion: 'Use an event name like \"click\", \"mouseover\", \"keydown\".',\n      });\n    }\n  }\n\n  return diagnostics;\n}\n\n// =============================================================================\n// JSON → SemanticNode\n// =============================================================================\n\n/**\n * Convert validated SemanticJSON to a SemanticNode.\n *\n * Returns a properly typed SemanticNode using the framework's factory functions.\n * If `trigger` is present, wraps the command in an event handler node.\n * @deprecated Use `fromProtocolJSON()` from `protocol-json.ts` instead.\n */\nexport function jsonToSemanticNode(input: SemanticJSON): SemanticNode {\n  const roles = new Map<SemanticRole, SemanticValue>();\n\n  if (input.roles) {\n    for (const [role, value] of Object.entries(input.roles)) {\n      roles.set(role as SemanticRole, convertJSONValue(value));\n    }\n  }\n\n  // Event handler wrapping\n  if (input.trigger) {\n    // Set the event role\n    roles.set('event' as SemanticRole, createLiteral(input.trigger.event, 'string'));\n\n    // Build body as a single command node\n    const bodyRoles = new Map(roles);\n    bodyRoles.delete('event' as SemanticRole);\n    const bodyNode = createCommandNode(input.action, bodyRoles);\n\n    return createEventHandlerNode(\n      'on',\n      roles,\n      [bodyNode],\n      { sourceLanguage: 'json' },\n      (input.trigger.modifiers as Record<string, unknown> | undefined) ?? {}\n    );\n  }\n\n  return createCommandNode(input.action, roles, {\n    sourceLanguage: 'json',\n  });\n}\n\n// =============================================================================\n// SemanticNode → JSON\n// =============================================================================\n\n/**\n * Convert a SemanticNode to SemanticJSON format.\n *\n * This is the inverse of jsonToSemanticNode(). For event handlers,\n * the event is extracted into the `trigger` field.\n * @deprecated Use `toProtocolJSON()` from `protocol-json.ts` instead.\n */\nexport function semanticNodeToJSON(node: SemanticNode): SemanticJSON {\n  if (node.kind === 'compound') {\n    // Compound nodes: use first statement's action, flatten roles\n    const compound = node as CompoundSemanticNode;\n    if (compound.statements.length > 0) {\n      return semanticNodeToJSON(compound.statements[0]);\n    }\n    return { action: 'compound', roles: {} };\n  }\n\n  if (node.kind === 'event-handler') {\n    const eventNode = node as EventHandlerSemanticNode;\n    const bodyAction = eventNode.body?.[0]?.action ?? node.action;\n    const roles: Record<string, SemanticJSONValue> = {};\n\n    // Convert body's roles (not the event handler's)\n    if (eventNode.body?.[0]) {\n      for (const [role, value] of eventNode.body[0].roles) {\n        roles[role] = semanticValueToJSON(value);\n      }\n    }\n\n    // Extract event from roles\n    const eventValue = node.roles.get('event');\n    const eventName = eventValue\n      ? 'value' in eventValue\n        ? String(eventValue.value)\n        : 'raw' in eventValue\n          ? eventValue.raw\n          : 'unknown'\n      : 'unknown';\n\n    const result: SemanticJSON = {\n      action: bodyAction === 'on' ? (eventNode.body?.[0]?.action ?? 'on') : bodyAction,\n      roles,\n      trigger: {\n        event: eventName,\n      },\n    };\n\n    if (eventNode.eventModifiers && Object.keys(eventNode.eventModifiers).length > 0) {\n      result.trigger!.modifiers = eventNode.eventModifiers as Record<string, unknown>;\n    }\n\n    return result;\n  }\n\n  // Regular command\n  const roles: Record<string, SemanticJSONValue> = {};\n  for (const [role, value] of node.roles) {\n    roles[role] = semanticValueToJSON(value);\n  }\n\n  return { action: node.action, roles };\n}\n\n// =============================================================================\n// Internal Helpers\n// =============================================================================\n\n/**\n * Convert a SemanticJSONValue to a SemanticValue.\n */\nfunction convertJSONValue(value: SemanticJSONValue): SemanticValue {\n  switch (value.type) {\n    case 'selector':\n      return createSelector(String(value.value), detectSelectorKind(String(value.value)));\n\n    case 'literal':\n      return createLiteral(\n        value.value,\n        typeof value.value === 'number'\n          ? 'number'\n          : typeof value.value === 'boolean'\n            ? 'boolean'\n            : 'string'\n      );\n\n    case 'reference':\n      return createReference(String(value.value));\n\n    case 'expression':\n      return createExpression(String(value.value));\n\n    case 'property-path':\n      // Property paths in JSON are represented as dot-separated strings\n      return createExpression(String(value.value));\n\n    case 'flag':\n      return createFlag(String(value.value), true);\n\n    default:\n      return createLiteral(String(value.value), 'string');\n  }\n}\n\n/**\n * Convert a SemanticValue to a SemanticJSONValue.\n */\nfunction semanticValueToJSON(value: SemanticValue): SemanticJSONValue {\n  switch (value.type) {\n    case 'selector':\n      return { type: 'selector', value: value.value };\n\n    case 'literal':\n      return { type: 'literal', value: value.value };\n\n    case 'reference':\n      return { type: 'reference', value: value.value };\n\n    case 'expression':\n      return { type: 'expression', value: value.raw };\n\n    case 'property-path':\n      return {\n        type: 'property-path',\n        value: `${semanticValueToJSON(value.object).value}.${value.property}`,\n      };\n\n    case 'flag':\n      return { type: 'flag', value: value.enabled };\n  }\n}\n\nfunction detectSelectorKind(selector: string): 'id' | 'class' | 'attribute' | 'complex' {\n  if (selector.startsWith('#')) return 'id';\n  if (selector.startsWith('.')) return 'class';\n  if (selector.startsWith('[')) return 'attribute';\n  return 'complex';\n}\n","/**\n * Protocol JSON Serialization — re-exported from @lokascript/intent\n */\n\nexport {\n  toProtocolJSON,\n  fromProtocolJSON,\n  validateProtocolJSON,\n  toEnvelopeJSON,\n  fromEnvelopeJSON,\n  isEnvelope,\n} from '@lokascript/intent';\n","/**\n * InterchangeNode → SemanticNode Converter\n *\n * Converts the expression-level InterchangeNode AST (from core/semantic parsers)\n * into the command-level SemanticNode IR used by LSE, MCP tools, and domain DSLs.\n *\n * This bridges the two IR pipelines in the monorepo:\n * - Pipeline A (InterchangeNode): full expression trees, 16 node types\n * - Pipeline B (SemanticNode): command-level semantics, opaque expression values\n *\n * Expression subtrees are intentionally collapsed to ExpressionValue { raw: string }\n * — LSE deliberately abstracts away expression-level detail.\n *\n * Uses structural typing for the input to avoid a dependency on the core package.\n */\n\nimport type {\n  SemanticNode,\n  SemanticValue,\n  SemanticRole,\n  LoopVariant,\n  EventModifiers as SemanticEventModifiers,\n} from '../core/types';\nimport {\n  createCommandNode,\n  createEventHandlerNode,\n  createConditionalNode,\n  createLoopNode,\n  createLiteral,\n  createSelector,\n  createReference,\n  createExpression,\n  createPropertyPath,\n} from '../core/types';\nimport { DEFAULT_REFERENCES } from './references';\n\n// =============================================================================\n// Structural Input Types (no core package dependency)\n// =============================================================================\n\n/**\n * Minimal interface matching InterchangeNode's structural shape.\n * Uses the `type` discriminant for dispatch. Additional fields are\n * accessed dynamically — this keeps the framework free of core imports.\n */\ninterface INode {\n  readonly type: string;\n  readonly [key: string]: unknown;\n}\n\n// =============================================================================\n// Main Converter\n// =============================================================================\n\n/**\n * Convert an InterchangeNode (expression-level AST) to a SemanticNode (command-level IR).\n *\n * Handles all 16 InterchangeNode types:\n * - Command/event nodes map to corresponding SemanticNode kinds\n * - Control flow nodes (if, repeat, foreach, while) map to conditional/loop kinds\n * - Expression nodes are wrapped as `get` commands with the value as patient role\n *\n * @param node - An InterchangeNode (or structurally compatible object)\n * @returns A SemanticNode suitable for LSE rendering, protocol JSON, or MCP tools\n */\nexport function fromInterchangeNode(node: INode): SemanticNode {\n  if (!node || typeof node !== 'object') {\n    return createCommandNode('unknown', {});\n  }\n\n  switch (node.type) {\n    case 'event':\n      return convertEvent(node);\n\n    case 'command':\n      return convertCommand(node);\n\n    case 'if':\n      return convertIf(node);\n\n    case 'repeat':\n      return convertRepeat(node);\n\n    case 'foreach':\n      return convertForEach(node);\n\n    case 'while':\n      return convertWhile(node);\n\n    // Expression nodes — wrap as `get` command with patient role\n    default:\n      return createCommandNode('get', { patient: convertValue(node) });\n  }\n}\n\n// =============================================================================\n// Node Converters\n// =============================================================================\n\nfunction convertEvent(node: INode): SemanticNode {\n  const event = String(node.event ?? 'click');\n  const bodyNodes = Array.isArray(node.body) ? (node.body as INode[]) : [];\n  const body = bodyNodes.map(fromInterchangeNode);\n\n  const roles: Record<SemanticRole, SemanticValue> = {\n    event: createLiteral(event),\n  };\n\n  // Preserve event target if present\n  if (node.target && typeof node.target === 'object') {\n    roles.source = convertValue(node.target as INode);\n  }\n\n  // Bridge event modifiers\n  const modifiers = node.modifiers as Record<string, unknown> | undefined;\n  let eventModifiers: SemanticEventModifiers | undefined;\n\n  if (modifiers) {\n    eventModifiers = bridgeEventModifiers(modifiers);\n\n    // InterchangeNode-only modifiers → encode as roles\n    if (modifiers.prevent) roles.prevent = createLiteral(true);\n    if (modifiers.stop) roles.stop = createLiteral(true);\n    if (modifiers.passive) roles.passive = createLiteral(true);\n    if (modifiers.capture) roles.capture = createLiteral(true);\n  }\n\n  return createEventHandlerNode('on', roles, body, undefined, eventModifiers);\n}\n\nfunction convertCommand(node: INode): SemanticNode {\n  const name = String(node.name ?? 'unknown');\n  const args = Array.isArray(node.args) ? (node.args as INode[]) : [];\n  const target =\n    node.target && typeof node.target === 'object' ? (node.target as INode) : undefined;\n  const existingRoles = node.roles as Record<string, INode> | undefined;\n  const modifiers = node.modifiers as Record<string, unknown> | undefined;\n\n  let roles: Record<SemanticRole, SemanticValue>;\n\n  if (existingRoles && typeof existingRoles === 'object' && Object.keys(existingRoles).length > 0) {\n    // Semantic parser path: roles already present\n    roles = {};\n    for (const [role, value] of Object.entries(existingRoles)) {\n      if (value && typeof value === 'object' && 'type' in value) {\n        roles[role] = convertValue(value as INode);\n      }\n    }\n  } else {\n    // Core parser path: infer roles from command name\n    roles = inferRoles(name, args, modifiers, target);\n  }\n\n  return createCommandNode(name, roles);\n}\n\nfunction convertIf(node: INode): SemanticNode {\n  const condition =\n    node.condition && typeof node.condition === 'object'\n      ? convertValue(node.condition as INode)\n      : createExpression('true');\n\n  const thenBody = Array.isArray(node.thenBranch) ? (node.thenBranch as INode[]) : [];\n  const thenBranch = thenBody.map(fromInterchangeNode);\n\n  // Handle else branch — may include chained else-if\n  let elseBranch: SemanticNode[] | undefined;\n\n  const elseIfBranches = node.elseIfBranches as\n    ReadonlyArray<{ condition: INode; body: INode[] }> | undefined;\n\n  if (elseIfBranches && elseIfBranches.length > 0) {\n    // Chain else-if branches as nested conditionals\n    elseBranch = [chainElseIfs(elseIfBranches, node.elseBranch as INode[] | undefined)];\n  } else if (Array.isArray(node.elseBranch) && (node.elseBranch as INode[]).length > 0) {\n    elseBranch = (node.elseBranch as INode[]).map(fromInterchangeNode);\n  }\n\n  const roles: Record<SemanticRole, SemanticValue> = { condition };\n  return createConditionalNode('if', roles, thenBranch, elseBranch);\n}\n\nfunction chainElseIfs(\n  branches: ReadonlyArray<{ condition: INode; body: INode[] }>,\n  finalElse: INode[] | undefined\n): SemanticNode {\n  const [first, ...rest] = branches;\n  const condition = convertValue(first.condition as INode);\n  const thenBranch = first.body.map(fromInterchangeNode);\n\n  let elseBranch: SemanticNode[] | undefined;\n  if (rest.length > 0) {\n    elseBranch = [chainElseIfs(rest, finalElse)];\n  } else if (finalElse && finalElse.length > 0) {\n    elseBranch = finalElse.map(fromInterchangeNode);\n  }\n\n  return createConditionalNode('if', { condition }, thenBranch, elseBranch);\n}\n\nfunction convertRepeat(node: INode): SemanticNode {\n  const bodyNodes = Array.isArray(node.body) ? (node.body as INode[]) : [];\n  const body = bodyNodes.map(fromInterchangeNode);\n  const roles: Record<SemanticRole, SemanticValue> = {};\n\n  let variant: LoopVariant;\n\n  if (node.count !== undefined && node.count !== null) {\n    variant = 'times';\n    if (typeof node.count === 'number') {\n      roles.quantity = createLiteral(node.count, 'number');\n    } else if (typeof node.count === 'object') {\n      roles.quantity = convertValue(node.count as INode);\n    }\n  } else if (node.whileCondition && typeof node.whileCondition === 'object') {\n    variant = 'while';\n    roles.condition = convertValue(node.whileCondition as INode);\n  } else if (typeof node.untilEvent === 'string') {\n    // `repeat until event e from t`: the event and where it listens, as the\n    // semantic parser holds them, plus the exact form `loopVariant` folds into\n    // `until`. The event name was the CONDITION, an `until \"e\"` loop that a\n    // truthy string ends at once.\n    variant = 'until';\n    roles.loopType = createLiteral('until-event');\n    roles.event = createLiteral(node.untilEvent);\n    if (node.untilEventTarget && typeof node.untilEventTarget === 'object') {\n      roles.source = convertValue(node.untilEventTarget as INode);\n    }\n  } else {\n    variant = 'forever';\n  }\n\n  return createLoopNode('repeat', roles, variant, body, undefined, indexNameOf(node));\n}\n\n/** `index i`, which every loop form can name. */\nfunction indexNameOf(node: INode): string | undefined {\n  return typeof node.indexName === 'string' ? node.indexName : undefined;\n}\n\nfunction convertForEach(node: INode): SemanticNode {\n  const bodyNodes = Array.isArray(node.body) ? (node.body as INode[]) : [];\n  const body = bodyNodes.map(fromInterchangeNode);\n  const roles: Record<SemanticRole, SemanticValue> = {};\n\n  if (node.collection && typeof node.collection === 'object') {\n    roles.source = convertValue(node.collection as INode);\n  }\n\n  const itemName = typeof node.itemName === 'string' ? node.itemName : undefined;\n\n  return createLoopNode('repeat', roles, 'for', body, itemName, indexNameOf(node));\n}\n\nfunction convertWhile(node: INode): SemanticNode {\n  const bodyNodes = Array.isArray(node.body) ? (node.body as INode[]) : [];\n  const body = bodyNodes.map(fromInterchangeNode);\n  const roles: Record<SemanticRole, SemanticValue> = {};\n\n  if (node.condition && typeof node.condition === 'object') {\n    roles.condition = convertValue(node.condition as INode);\n  }\n\n  return createLoopNode('repeat', roles, 'while', body, undefined, indexNameOf(node));\n}\n\n// =============================================================================\n// Value Conversion\n// =============================================================================\n\n/**\n * Convert an InterchangeNode to a SemanticValue.\n *\n * Simple nodes map directly to typed SemanticValue variants.\n * Complex expression nodes are collapsed to ExpressionValue { raw: string }.\n */\nexport function convertValue(node: INode): SemanticValue {\n  switch (node.type) {\n    case 'literal':\n      return convertLiteral(node);\n\n    case 'selector':\n      return createSelector(String(node.value ?? ''), inferSelectorKind(String(node.value ?? '')));\n\n    case 'identifier':\n      return convertIdentifier(node);\n\n    case 'variable':\n      return convertVariable(node);\n\n    case 'possessive':\n      return createPropertyPath(\n        node.object && typeof node.object === 'object'\n          ? convertValue(node.object as INode)\n          : createReference('me'),\n        String(node.property ?? '')\n      );\n\n    // Complex expressions → collapse to raw string\n    case 'binary':\n    case 'unary':\n    case 'member':\n    case 'call':\n    case 'positional':\n      return createExpression(renderExpr(node));\n\n    default:\n      // Unknown type — render as expression\n      if ('value' in node) return createLiteral(String(node.value ?? ''));\n      return createExpression(renderExpr(node));\n  }\n}\n\nfunction convertLiteral(node: INode): SemanticValue {\n  const value = node.value;\n  if (value === null || value === undefined) return createLiteral('null');\n\n  const dataType =\n    typeof value === 'number'\n      ? ('number' as const)\n      : typeof value === 'boolean'\n        ? ('boolean' as const)\n        : undefined;\n\n  return createLiteral(value as string | number | boolean, dataType);\n}\n\nfunction convertIdentifier(node: INode): SemanticValue {\n  const value = String(node.value ?? '');\n  if (DEFAULT_REFERENCES.has(value)) {\n    return createReference(value);\n  }\n  return createLiteral(value);\n}\n\nfunction convertVariable(node: INode): SemanticValue {\n  const name = String(node.name ?? '');\n  const scope = String(node.scope ?? 'local');\n\n  switch (scope) {\n    case 'element':\n      return createExpression(`:${name}`);\n    case 'global':\n      return createExpression(`$${name}`);\n    default:\n      return createExpression(name);\n  }\n}\n\n// =============================================================================\n// Expression Renderer\n// =============================================================================\n\n/**\n * Recursively render an InterchangeNode expression tree to a string.\n * Used to collapse complex expressions into ExpressionValue.raw.\n */\nexport function renderExpr(node: INode): string {\n  if (!node || typeof node !== 'object') return '';\n\n  switch (node.type) {\n    case 'literal': {\n      const v = node.value;\n      if (v === null || v === undefined) return 'null';\n      if (typeof v === 'string') return /\\s/.test(v) ? `\"${v}\"` : v;\n      return String(v);\n    }\n\n    case 'identifier':\n      return String(node.value ?? '');\n\n    case 'selector':\n      return String(node.value ?? '');\n\n    case 'variable': {\n      const name = String(node.name ?? '');\n      const scope = String(node.scope ?? 'local');\n      if (scope === 'element') return `:${name}`;\n      if (scope === 'global') return `$${name}`;\n      return name;\n    }\n\n    case 'binary': {\n      const left = node.left && typeof node.left === 'object' ? renderExpr(node.left as INode) : '';\n      const right =\n        node.right && typeof node.right === 'object' ? renderExpr(node.right as INode) : '';\n      return `${left} ${node.operator ?? ''} ${right}`;\n    }\n\n    case 'unary': {\n      const operand =\n        node.operand && typeof node.operand === 'object' ? renderExpr(node.operand as INode) : '';\n      return `${node.operator ?? ''} ${operand}`;\n    }\n\n    case 'member': {\n      const obj =\n        node.object && typeof node.object === 'object' ? renderExpr(node.object as INode) : '';\n      if (node.computed && node.property && typeof node.property === 'object') {\n        return `${obj}[${renderExpr(node.property as INode)}]`;\n      }\n      const prop =\n        typeof node.property === 'string'\n          ? node.property\n          : node.property && typeof node.property === 'object'\n            ? renderExpr(node.property as INode)\n            : '';\n      return `${obj}.${prop}`;\n    }\n\n    case 'possessive': {\n      const obj =\n        node.object && typeof node.object === 'object' ? renderExpr(node.object as INode) : '';\n      return `${obj}'s ${node.property ?? ''}`;\n    }\n\n    case 'call': {\n      const callee =\n        node.callee && typeof node.callee === 'object' ? renderExpr(node.callee as INode) : '';\n      const args = Array.isArray(node.args)\n        ? (node.args as INode[]).map(a => renderExpr(a)).join(', ')\n        : '';\n      return `${callee}(${args})`;\n    }\n\n    case 'positional': {\n      const target =\n        node.target && typeof node.target === 'object' ? renderExpr(node.target as INode) : '';\n      return target ? `${node.position ?? ''} ${target}` : String(node.position ?? '');\n    }\n\n    default:\n      if ('value' in node) return String(node.value ?? '');\n      return '';\n  }\n}\n\n// =============================================================================\n// Role Inference\n// =============================================================================\n\n/**\n * Marker-keyword sets — mirror the runtime command parsers' skip lists so the\n * inferred roles point at the real value, not the literal marker word.\n */\nconst SCROLL_MARKERS: ReadonlySet<string> = new Set([\n  'to',\n  'of',\n  'the',\n  'top',\n  'bottom',\n  'middle',\n  'center',\n  'nearest',\n  'left',\n  'right',\n  'smoothly',\n  'instantly',\n]);\nconst URL_MARKERS: ReadonlySet<string> = new Set(['url']);\nconst PARTIALS_IN_MARKERS: ReadonlySet<string> = new Set(['partials', 'in']);\n\n/**\n * Return the first arg that isn't a marker identifier from the given set.\n * Identifier args carry the marker word in `name` (or `value` as a fallback).\n */\nfunction firstNonMarkerArg(args: INode[], markers: ReadonlySet<string>): INode | undefined {\n  for (const a of args) {\n    if (a.type === 'identifier') {\n      const ident = a as { name?: unknown; value?: unknown };\n      const word = typeof ident.name === 'string' ? ident.name : ident.value;\n      if (typeof word === 'string' && markers.has(word)) continue;\n    }\n    return a;\n  }\n  return undefined;\n}\n\n/**\n * Infer semantic roles from command name, positional args, modifiers, and target.\n * Mirrors the heuristics in core's from-core.ts inferRoles() function.\n */\nfunction inferRoles(\n  name: string,\n  args: INode[],\n  modifiers: Record<string, unknown> | undefined,\n  target: INode | undefined\n): Record<SemanticRole, SemanticValue> {\n  const roles: Record<SemanticRole, SemanticValue> = {};\n\n  switch (name) {\n    case 'set': {\n      if (args[0]) roles.destination = convertValue(args[0]);\n      const toVal = modifiers?.to;\n      if (toVal && typeof toVal === 'object' && 'type' in (toVal as object)) {\n        roles.patient = convertValue(toVal as INode);\n      } else if (args[1]) {\n        roles.patient = convertValue(args[1]);\n      }\n      break;\n    }\n\n    case 'put': {\n      if (args[0]) roles.patient = convertValue(args[0]);\n      if (modifiers) {\n        for (const key of ['into', 'before', 'after'] as const) {\n          const val = modifiers[key];\n          if (val && typeof val === 'object' && 'type' in (val as object)) {\n            roles.destination = convertValue(val as INode);\n            roles.method = createLiteral(key);\n            break;\n          }\n        }\n      }\n      if (!roles.destination && target) {\n        roles.destination = convertValue(target);\n      }\n      break;\n    }\n\n    case 'increment':\n    case 'decrement': {\n      if (args[0]) roles.destination = convertValue(args[0]);\n      const byVal = modifiers?.by;\n      if (byVal && typeof byVal === 'object' && 'type' in (byVal as object)) {\n        roles.quantity = convertValue(byVal as INode);\n      } else if (args[1]) {\n        roles.quantity = convertValue(args[1]);\n      }\n      break;\n    }\n\n    case 'fetch': {\n      if (args[0]) roles.source = convertValue(args[0]);\n      const asVal = modifiers?.as;\n      if (asVal && typeof asVal === 'object' && 'type' in (asVal as object)) {\n        roles.responseType = convertValue(asVal as INode);\n      } else if (typeof asVal === 'string') {\n        roles.responseType = createLiteral(asVal);\n      }\n      break;\n    }\n\n    case 'wait':\n    case 'settle': {\n      if (args[0]) roles.duration = convertValue(args[0]);\n      break;\n    }\n\n    case 'toggle':\n    case 'add':\n    case 'show':\n    case 'hide': {\n      if (args[0]) roles.patient = convertValue(args[0]);\n      if (target) roles.destination = convertValue(target);\n      break;\n    }\n\n    case 'remove': {\n      if (args[0]) roles.patient = convertValue(args[0]);\n      if (target) roles.source = convertValue(target);\n      break;\n    }\n\n    case 'send':\n    case 'trigger': {\n      if (args[0]) roles.patient = convertValue(args[0]);\n      if (target) roles.destination = convertValue(target);\n      break;\n    }\n\n    case 'log': {\n      if (args[0]) roles.patient = convertValue(args[0]);\n      break;\n    }\n\n    // scroll [to] [position] target [smoothly|instantly]  →  destination=target\n    case 'scroll': {\n      const t = firstNonMarkerArg(args, SCROLL_MARKERS);\n      if (t) roles.destination = convertValue(t);\n      break;\n    }\n\n    // push|replace url <X>  →  patient=X\n    case 'push':\n    case 'replace': {\n      const t = firstNonMarkerArg(args, URL_MARKERS);\n      if (t) roles.patient = convertValue(t);\n      break;\n    }\n\n    // process partials in <X>  →  patient=X\n    case 'process': {\n      const t = firstNonMarkerArg(args, PARTIALS_IN_MARKERS);\n      if (t) roles.patient = convertValue(t);\n      break;\n    }\n\n    default: {\n      // Generic fallback: first arg as patient, target as destination\n      if (args[0]) roles.patient = convertValue(args[0]);\n      if (target) roles.destination = convertValue(target);\n      break;\n    }\n  }\n\n  return roles;\n}\n\n// =============================================================================\n// Helpers\n// =============================================================================\n\n/**\n * Infer selectorKind from a CSS selector string.\n */\nfunction inferSelectorKind(\n  value: string\n): 'id' | 'class' | 'attribute' | 'element' | 'complex' | undefined {\n  if (!value) return undefined;\n  if (value.startsWith('#')) return 'id';\n  if (value.startsWith('.')) return 'class';\n  if (value.startsWith('[')) return 'attribute';\n  if (value.startsWith('<') || value.startsWith('*')) return 'element';\n  // Check for combinators indicating complex selectors\n  if (/[>\\+~ ]/.test(value) && value.length > 1) return 'complex';\n  return undefined;\n}\n\n/**\n * Infer a SemanticValue from a string (for event modifier `from` bridging).\n */\nfunction inferValueFromString(value: string): SemanticValue {\n  if (DEFAULT_REFERENCES.has(value)) return createReference(value);\n  const kind = inferSelectorKind(value);\n  if (kind) return createSelector(value, kind);\n  return createLiteral(value);\n}\n\n/**\n * Bridge InterchangeNode EventModifiers to SemanticNode EventModifiers.\n */\nfunction bridgeEventModifiers(mods: Record<string, unknown>): SemanticEventModifiers | undefined {\n  const once = mods.once === true ? true : undefined;\n  const debounce = typeof mods.debounce === 'number' ? mods.debounce : undefined;\n  const throttle = typeof mods.throttle === 'number' ? mods.throttle : undefined;\n  const from = typeof mods.from === 'string' ? inferValueFromString(mods.from) : undefined;\n\n  if (\n    once === undefined &&\n    debounce === undefined &&\n    throttle === undefined &&\n    from === undefined\n  ) {\n    return undefined;\n  }\n\n  return {\n    ...(once !== undefined ? { once } : {}),\n    ...(debounce !== undefined ? { debounce } : {}),\n    ...(throttle !== undefined ? { throttle } : {}),\n    ...(from !== undefined ? { from } : {}),\n  };\n}\n","/**\n * SemanticNode → Runtime AST Converter\n *\n * Converts framework SemanticNode (LSE IR) to a structural AST format\n * that the core runtime can execute directly. Uses structural typing\n * to avoid a dependency on the core package.\n *\n * This is the canonical converter — AOT compiler delegates to it.\n *\n * The output matches the core runtime's expected node shapes:\n * - `{ type: 'command', name, args, roles }` → processCommand()\n * - `{ type: 'event', event, modifiers, body }` → adapted to executeEventHandler()\n */\n\nimport type {\n  SemanticNode,\n  SemanticValue,\n  EventHandlerSemanticNode,\n  ConditionalSemanticNode,\n  LoopSemanticNode,\n} from '../core/types';\n\n// =============================================================================\n// Structural output types (no core package dependency)\n// =============================================================================\n\n/** Minimal AST node that the core runtime can execute. */\nexport interface RuntimeASTNode {\n  readonly type: string;\n  readonly [key: string]: unknown;\n}\n\n/** Command node shape expected by runtime's processCommand(). */\nexport interface RuntimeCommandNode extends RuntimeASTNode {\n  readonly type: 'command';\n  readonly name: string;\n  readonly args: RuntimeASTNode[];\n  readonly roles?: Readonly<Record<string, RuntimeASTNode>>;\n  readonly modifiers?: Record<string, unknown>;\n}\n\n/** Event node shape expected by runtime's event adapter. */\nexport interface RuntimeEventNode extends RuntimeASTNode {\n  readonly type: 'event';\n  readonly event: string;\n  readonly modifiers: Record<string, unknown>;\n  readonly body: RuntimeASTNode[];\n}\n\n// =============================================================================\n// Converter\n// =============================================================================\n\n/**\n * Convert a SemanticNode to a RuntimeASTNode that the core runtime can execute.\n *\n * @example\n * ```typescript\n * import { parseExplicit } from '@lokascript/framework/ir';\n * import { semanticNodeToRuntimeAST } from '@lokascript/framework/ir';\n *\n * const node = parseExplicit('[toggle patient:.active]');\n * const ast = semanticNodeToRuntimeAST(node);\n * // { type: 'command', name: 'toggle', args: [{ type: 'selector', value: '.active' }], roles: { patient: ... } }\n * ```\n */\nexport function semanticNodeToRuntimeAST(node: SemanticNode): RuntimeASTNode {\n  switch (node.kind) {\n    case 'event-handler':\n      return convertEventHandler(node as EventHandlerSemanticNode);\n\n    case 'conditional':\n      return convertConditional(node as ConditionalSemanticNode);\n\n    case 'loop':\n      return convertLoop(node as LoopSemanticNode);\n\n    case 'compound': {\n      const compound = node as SemanticNode & { statements?: SemanticNode[]; chainType?: string };\n      const commands = (compound.statements ?? []).map(semanticNodeToRuntimeAST);\n      return {\n        type: 'CommandSequence',\n        commands,\n      };\n    }\n\n    case 'command':\n    default:\n      return convertCommand(node);\n  }\n}\n\nfunction convertEventHandler(eh: EventHandlerSemanticNode): RuntimeEventNode {\n  const eventValue = eh.roles.get('event');\n  const eventName = eventValue && 'value' in eventValue ? String(eventValue.value) : 'click';\n\n  const modifiers: Record<string, unknown> = {};\n  if (eh.eventModifiers) {\n    if (eh.eventModifiers.once) modifiers.once = true;\n    if (eh.eventModifiers.debounce) modifiers.debounce = eh.eventModifiers.debounce;\n    if (eh.eventModifiers.throttle) modifiers.throttle = eh.eventModifiers.throttle;\n    if (eh.eventModifiers.queue) modifiers.queue = eh.eventModifiers.queue;\n  }\n\n  return {\n    type: 'event',\n    event: eventName,\n    modifiers,\n    body: (eh.body ?? []).map(semanticNodeToRuntimeAST),\n  };\n}\n\nfunction convertCommand(node: SemanticNode): RuntimeCommandNode {\n  const roles: Record<string, RuntimeASTNode> = {};\n  const args: RuntimeASTNode[] = [];\n\n  for (const [roleName, value] of node.roles) {\n    const astValue = semanticValueToAST(value);\n    roles[roleName] = astValue;\n    args.push(astValue);\n  }\n\n  return {\n    type: 'command',\n    name: node.action,\n    args,\n    roles,\n  };\n}\n\n/** A body as core's parser holds one: a block of commands. */\nfunction block(nodes: readonly SemanticNode[] | undefined): RuntimeASTNode {\n  return { type: 'block', commands: (nodes ?? []).map(semanticNodeToRuntimeAST) };\n}\n\n/**\n * An `if` as core's parser builds it: `args: [condition, then-block,\n * else-block?]`. This wrote the branches beside `args: [condition]`, so every\n * `if` through `evalLSE` threw \"if command requires \"then\" branch with\n * commands\".\n */\nfunction convertConditional(node: ConditionalSemanticNode): RuntimeASTNode {\n  const name = node.action === 'unless' ? 'unless' : 'if';\n  const conditionValue = node.roles.get('condition');\n  // No condition is malformed: empty args make core say so.\n  if (!conditionValue) return { type: 'command', name, args: [] };\n  return {\n    type: 'command',\n    name,\n    args: [\n      semanticValueToAST(conditionValue),\n      block(node.thenBranch),\n      ...(node.elseBranch && node.elseBranch.length > 0 ? [block(node.elseBranch)] : []),\n    ],\n  };\n}\n\n/** The loop forms core's `repeat` runs: its parser's `loopType`. */\nconst LOOP_FORMS = new Set(['for', 'times', 'while', 'until', 'until-event', 'forever']);\n\n/** The text of a name-like value: a loop form, an event name. */\nfunction valueText(value: SemanticValue | undefined): string | undefined {\n  if (!value) return undefined;\n  if (value.type === 'literal') return String(value.value);\n  if (value.type === 'expression') return value.raw;\n  if (value.type === 'reference' || value.type === 'selector') return value.value;\n  return undefined;\n}\n\n/**\n * A loop as core's parser builds it (Arc 3 step 3): the form in\n * `modifiers.loopType`, the operands in `for`/`in`, `times`, `while`/`until`,\n * `event`/`from` and `index`, the body the one positional block.\n *\n * This emitted `args: [count]` with the variant and body beside it, a shape\n * `repeat` has not read since the slot migration, so every loop through\n * `evalLSE` / `compileLSE` threw \"repeat command requires a loop type\". The\n * form comes from a `loopType` role when it names one, since it keeps the\n * exact form (`until-event`) that `loopVariant` folds into `until`.\n */\nfunction convertLoop(node: LoopSemanticNode): RuntimeASTNode {\n  const text = (value: string): RuntimeASTNode => ({ type: 'string', value });\n  const operand = (role: string): RuntimeASTNode | undefined => {\n    const value = node.roles.get(role);\n    return value ? semanticValueToAST(value) : undefined;\n  };\n  const declared = valueText(node.roles.get('loopType'));\n  const form =\n    node.action === 'for'\n      ? 'for'\n      : declared && LOOP_FORMS.has(declared)\n        ? declared\n        : (node.loopVariant ?? 'forever');\n\n  const modifiers: Record<string, RuntimeASTNode> = { loopType: text(form) };\n  const slot = (name: string, value: RuntimeASTNode | undefined) => {\n    if (value) modifiers[name] = value;\n  };\n  switch (form) {\n    case 'for':\n      if (node.loopVariable) slot('for', text(node.loopVariable));\n      slot('in', operand('source'));\n      break;\n    case 'times':\n      // `patient` and `count` are what this read before the slot shape.\n      slot('times', operand('quantity') ?? operand('patient') ?? operand('count'));\n      break;\n    case 'while':\n    case 'until':\n      slot(form, operand('condition'));\n      break;\n    case 'until-event': {\n      const event = valueText(node.roles.get('event'));\n      if (event) slot('event', text(event));\n      slot('from', operand('source'));\n      break;\n    }\n  }\n  if (node.indexVariable) slot('index', text(node.indexVariable));\n\n  return { type: 'command', name: 'repeat', args: [block(node.body)], modifiers };\n}\n\n/**\n * Convert a SemanticValue to a RuntimeASTNode.\n */\nexport function semanticValueToAST(value: SemanticValue): RuntimeASTNode {\n  switch (value.type) {\n    case 'selector':\n      return { type: 'selector', value: value.value as string };\n\n    case 'reference':\n      return { type: 'identifier', value: value.value as string };\n\n    case 'literal': {\n      const lit = value as { value: unknown; dataType?: string };\n      if (lit.dataType === 'duration') {\n        const str = String(lit.value);\n        const match = /^(\\d+(?:\\.\\d+)?)(ms|s)$/.exec(str);\n        if (match) {\n          const ms = match[2] === 's' ? parseFloat(match[1]) * 1000 : parseFloat(match[1]);\n          return { type: 'literal', value: ms };\n        }\n      }\n      return { type: 'literal', value: lit.value as string | number | boolean | null };\n    }\n\n    case 'property-path': {\n      const pp = value as import('../core/types').PropertyPathValue;\n      const objectAST = semanticValueToAST(pp.object);\n      return {\n        type: 'member',\n        object: objectAST,\n        property: pp.property,\n      };\n    }\n\n    case 'expression': {\n      const expr = value as { raw: string };\n      return { type: 'expression', value: expr.raw };\n    }\n\n    case 'flag': {\n      const flag = value as { name: string; enabled: boolean };\n      return { type: 'literal', value: flag.enabled };\n    }\n\n    default:\n      return { type: 'literal', value: String((value as { value?: unknown }).value ?? '') };\n  }\n}\n","/**\n * How a read-back is compared (internal: not exported from the package). `translate` and the\n * registry's translate tool both require a rendering to read back as its source; this is their rule.\n */\nimport type { SemanticNode } from '../core/types';\n\n/** A node's role values as strings, by role: what a read-back is compared on. */\nfunction roleValues(node: SemanticNode): Map<string, string> {\n  const out = new Map<string, string>();\n  for (const [role, value] of node.roles) {\n    const v = value as { value?: unknown; raw?: unknown };\n    out.set(role, String(v?.value ?? v?.raw ?? value));\n  }\n  return out;\n}\n\n/** How `back` differs from `source`; empty when it reads the same. */\nexport function readingDifference(source: SemanticNode, back: SemanticNode): string {\n  if (back.action !== source.action) return `reads as ${back.action}`;\n  const want = roleValues(source);\n  const got = roleValues(back);\n  const parts: string[] = [];\n  for (const [role, value] of want) {\n    if (!got.has(role)) parts.push(`${role} lost`);\n    else if (got.get(role) !== value) parts.push(`${role}: ${value} → ${got.get(role)}`);\n  }\n  for (const role of got.keys()) if (!want.has(role)) parts.push(`${role} added`);\n  return parts.join(', ');\n}\n","/**\n * Main API for creating multilingual DSLs\n */\n\nimport type {\n  SemanticNode,\n  LanguageToken,\n  LanguageTokenizer,\n  LanguagePattern,\n  PatternMatchResult,\n  RolePatternToken,\n  TokenStream,\n} from '../core/types';\nimport { extractRoleValue } from '../core/types';\nimport type { CommandSchema } from '../schema';\nimport { MatchSkeleton, createStockReader, stockConfidenceModel } from '../core/matching';\nimport type { PatternGenLanguageProfile } from '../generation/profile';\nimport type { DomainRenderFn } from '../generation/renderer';\nimport {\n  createSchemaPatternGenerator,\n  type SchemaPatternProfile,\n} from '../generation/schema-patterns';\nimport { renderPattern, selectRenderPattern } from '../generation/pattern-render';\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 { readingDifference } from './reading';\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   * What reads and writes the DSL. `'core'`, the only engine (and the\n   * default): the core semantic's hyperscript parser runs — patterns from\n   * `createSchemaPatternGenerator` (positions descending, as a domain's schemas\n   * read), matched by `MatchSkeleton` with the stock reader and confidence\n   * model, and rendered through those patterns where the domain's own renderer\n   * declines. The option stays so a config written for framework 4.7–4.8\n   * (`engine: 'core'`) builds unchanged; `'classic'`, framework's first\n   * generator and matcher, was removed in 5.0 (domains rethink Phase 6) and\n   * throws.\n   */\n  readonly engine?: 'core';\n}\n\n/**\n * Validation result.\n */\nexport interface ValidationResult {\n  readonly valid: boolean;\n  readonly node?: SemanticNode;\n  readonly errors?: string[];\n  /** Set when the input was refused for a known reason: `'unread-input'` (`UnreadInputError`). */\n  readonly errorCode?: string;\n}\n\n/**\n * Compilation result.\n */\nexport interface CompileResult {\n  readonly ok: boolean;\n  readonly code?: string;\n  readonly errors?: string[];\n  /** Set when the input was refused for a known reason: `'unread-input'` (`UnreadInputError`). */\n  readonly errorCode?: string;\n  readonly node?: SemanticNode;\n  readonly metadata?: {\n    readonly parser: string;\n    readonly confidence: number;\n  };\n}\n\n/**\n * Thrown by `parse` (and so `compile`, `validate`, `translate`) when the input reads as a command\n * only by leaving some of it unread: `select name from users banana` is not `select name from users`.\n * `reading` is what the longest such match read, `unread` the text after it. `hint`, when there is\n * one, says how the input might read: where a bare word read as a value is followed by another, the\n * two may be one value written without quotes (todo `add buy milk to groceries`).\n */\nexport class UnreadInputError extends Error {\n  readonly code = 'unread-input';\n\n  constructor(\n    readonly input: string,\n    readonly language: string,\n    readonly reading: SemanticNode,\n    readonly unread: string,\n    readonly hint?: string\n  ) {\n    super(\n      `\"${input}\" (${language}) reads as ${reading.action} only by leaving \"${unread}\" unread` +\n        (hint ? `; ${hint}` : '')\n    );\n    this.name = 'UnreadInputError';\n  }\n}\n\n/** Options for `translate`. */\nexport interface TranslateOptions {\n  /**\n   * `'allow'` returns a translation that does not read back as the source instead of throwing\n   * `TranslationReadBackError`, as semantic's `translate` does with the same option.\n   */\n  readonly lossy?: 'allow' | 'refuse';\n}\n\n/**\n * Thrown by `translate` when its output, read in the target language, is not the source command:\n * it does not read at all, or reads as another command, or with a role lost or changed. `partial` is\n * what `translate` would have returned; `reading` what it reads as (null when it does not read).\n */\nexport class TranslationReadBackError extends Error {\n  readonly code = 'translation-does-not-read-back';\n\n  constructor(\n    readonly partial: string,\n    readonly from: string,\n    readonly to: string,\n    readonly source: SemanticNode,\n    readonly reading: SemanticNode | null,\n    readonly why: string\n  ) {\n    super(`translation ${from} → ${to} does not read back as the source (${why}): \"${partial}\"`);\n    this.name = 'TranslationReadBackError';\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  /**\n   * Parse in one language, render in another. The output must read back as the source command\n   * (the same action and role values, or the same compiled code); when it does not,\n   * `TranslationReadBackError`, unless `{ lossy: 'allow' }`.\n   */\n  translate(\n    input: string,\n    fromLanguage: string,\n    toLanguage: string,\n    options?: TranslateOptions\n  ): 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(\n    config: DSLConfig,\n    partiallyTranslatedActions: ReadonlySet<string>,\n    private readonly generate: DSLEngine['generate']\n  ) {\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 = this.generate(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 match: DSLEngine['match'];\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    engine: DSLEngine\n  ) {\n    this.registry = registry;\n    this.match = engine.match;\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 = engine.fallbackRenderer(config, registry);\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    // Every pattern is tried, and only a match that reads the WHOLE input counts; of those, the\n    // highest priority wins, then the highest confidence, then the earliest pattern. The first match\n    // used to win however much it read, so a trailing word was dropped without a word (the domain\n    // gate measured 1,744 of 1,744 such inputs accepted) and an earlier, shorter pattern could\n    // shadow the one that reads everything.\n    const total = tokens.tokens.length;\n    let best: PatternMatchResult | null = null;\n    let longestPartial: PatternMatchResult | null = null;\n    for (const pattern of patterns) {\n      const mark = tokens.mark();\n      const match = this.match(tokens, pattern, language);\n      tokens.reset(mark);\n      if (!match) continue;\n      if (match.consumedTokens < total) {\n        if (!longestPartial || match.consumedTokens > longestPartial.consumedTokens)\n          longestPartial = match;\n        continue;\n      }\n      if (\n        !best ||\n        match.pattern.priority > best.pattern.priority ||\n        (match.pattern.priority === best.pattern.priority &&\n          match.confidence > best.confidence + 0.001)\n      )\n        best = match;\n    }\n\n    if (best) {\n      const node = this.nodeOf(best, input, language);\n      return { node, confidence: best.confidence };\n    }\n    if (longestPartial) {\n      const unread = tokens.tokens\n        .slice(longestPartial.consumedTokens)\n        .map(t => t.value)\n        .join(' ');\n      const hint = this.quoteHint(longestPartial, tokens.tokens);\n      throw new UnreadInputError(\n        input,\n        language,\n        this.nodeOf(longestPartial, input, language),\n        unread,\n        ...(hint ? [hint] : [])\n      );\n    }\n    throw new Error(`No pattern matched for input: ${input}`);\n  }\n\n  /**\n   * `if \"buy milk\" is one value, quote it`, where the last token a match read is a bare word it took\n   * as a role's value (a role with no word list) and the first it left is a bare word too.\n   */\n  private quoteHint(\n    match: PatternMatchResult,\n    tokens: readonly LanguageToken[]\n  ): string | undefined {\n    const last = tokens[match.consumedTokens - 1];\n    const next = tokens[match.consumedTokens];\n    if (last?.kind !== 'identifier' || next?.kind !== 'identifier') return undefined;\n    const schema = this.schemaLookup.getSchema(match.pattern.command);\n    const role = [...match.captured].find(\n      ([, v]) => (v as { raw?: unknown }).raw === last.value\n    )?.[0];\n    if (!role || schema?.roles.find(r => r.role === role)?.words) return undefined;\n    return `if \"${last.value} ${next.value}\" is one value, quote it`;\n  }\n\n  private nodeOf(match: PatternMatchResult, input: string, language: string): SemanticNode {\n    return {\n      kind: 'command',\n      action: match.pattern.command,\n      roles: match.captured,\n      metadata: {\n        sourceLanguage: language,\n        sourceText: input,\n        patternId: match.pattern.id,\n        confidence: match.confidence,\n      },\n    };\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        ...(error instanceof UnreadInputError ? { errorCode: error.code } : {}),\n      };\n    }\n  }\n\n  translate(\n    input: string,\n    fromLanguage: string,\n    toLanguage: string,\n    options?: TranslateOptions\n  ): 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 this.readsBack(rendered, node, fromLanguage, toLanguage, options);\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.readsBack(\n        this.transformer.transform(input, fromLanguage, toLanguage),\n        node,\n        fromLanguage,\n        toLanguage,\n        options\n      );\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  /**\n   * `rendered`, read in `to`, must be `source`: the same action and role values, or, when the DSL\n   * compiles, the same code (a parser may keep a translated word its generator normalizes: bdd ja\n   * `表示` is `visible`). The rule is the domain gate's (lokascript-domains). A translation used to be\n   * returned whatever it read as: ja/ko bdd `select` dropped its value, and nothing said so.\n   */\n  private readsBack(\n    rendered: string,\n    source: SemanticNode,\n    from: string,\n    to: string,\n    options?: TranslateOptions\n  ): string {\n    if (options?.lossy === 'allow') return rendered;\n    let back: SemanticNode;\n    try {\n      back = this.parseWithConfidence(rendered, to).node;\n    } catch (error) {\n      const why = error instanceof Error ? error.message : String(error);\n      throw new TranslationReadBackError(rendered, from, to, source, null, why);\n    }\n    const difference = readingDifference(source, back);\n    if (!difference) return rendered;\n    if (this.codeGenerator) {\n      try {\n        if (this.codeGenerator.generate(back) === this.codeGenerator.generate(source))\n          return rendered;\n      } catch {\n        // a generator that cannot compile one of them does not vouch for either\n      }\n    }\n    throw new TranslationReadBackError(rendered, from, to, source, back, difference);\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        ...(error instanceof UnreadInputError ? { errorCode: error.code } : {}),\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 engine = engineFor(config);\n  const registry = new DSLRegistry(effectiveConfig, extensionActions, engine.generate);\n  return new MultilingualDSLImpl(effectiveConfig, registry, transformer, profileProvider, engine);\n}\n\n// =============================================================================\n// The engines: how a DSL turns its schemas into patterns and reads with them\n// =============================================================================\n\n/**\n * What reads and writes a DSL: how each command's pattern is generated, how\n * input is matched against it, and the renderer `render()` falls back to.\n * Parsing's whole-input rule, refusals, translation's read-back, compile,\n * explicit syntax and extensions sit above it.\n */\ninterface DSLEngine {\n  generate(schema: CommandSchema, profile: PatternGenLanguageProfile): LanguagePattern;\n  match(tokens: TokenStream, pattern: LanguagePattern, language: string): PatternMatchResult | null;\n  fallbackRenderer(config: DSLConfig, registry: DSLRegistry): DomainRenderFn;\n}\n\n/**\n * The engine `config.engine` names: the core, the only one since 5.0. An\n * unknown name throws rather than reading with the default, and `'classic'`\n * says what replaced it.\n */\nfunction engineFor(config: DSLConfig): DSLEngine {\n  const name: string = config.engine ?? 'core';\n  if (name === 'core') return coreEngine();\n  if (name === 'classic') {\n    throw new Error(\n      'The \"classic\" DSL engine was removed in @lokascript/framework 5.0. ' +\n        'Omit `engine` (or pass \"core\"): every domain reads on the core.'\n    );\n  }\n  throw new Error(`Unknown DSL engine \"${name}\" (expected \"core\")`);\n}\n\n/**\n * A domain profile as the schema-pattern generator reads it: every role marker\n * with a side (the word order's default where the profile names none).\n */\nfunction schemaProfileOf(profile: PatternGenLanguageProfile): SchemaPatternProfile {\n  const side = profile.wordOrder === 'SOV' ? 'after' : 'before';\n  const roleMarkers: Record<string, NonNullable<SchemaPatternProfile['roleMarkers'][string]>> = {};\n  for (const [role, marker] of Object.entries(profile.roleMarkers ?? {})) {\n    roleMarkers[role] = {\n      primary: marker.primary,\n      ...(marker.alternatives ? { alternatives: marker.alternatives } : {}),\n      position: marker.position ?? side,\n    };\n  }\n  return {\n    code: profile.code,\n    wordOrder: profile.wordOrder,\n    keywords: profile.keywords,\n    roleMarkers,\n  };\n}\n\n/**\n * The core (domains rethink Phase 4, `engine: 'core'`): the schema-pattern\n * generator, the skeleton, the stock reader.\n */\nfunction coreEngine(): DSLEngine {\n  const generator = createSchemaPatternGenerator({ positionOrder: 'descending' });\n  const matcher = new MatchSkeleton(createStockReader(), stockConfidenceModel);\n  return {\n    generate: (schema, profile) => generator.generatePattern(schema, schemaProfileOf(profile)),\n    match: (tokens, pattern) => matcher.matchPattern(tokens, pattern),\n    fallbackRenderer: (config, registry) => {\n      const schemas = new Map(config.schemas.map(s => [s.action, s]));\n      const hooks = {\n        hasRealRole: (node: SemanticNode, role: string) => {\n          const value = node.roles.get(role) as { implicit?: unknown } | undefined;\n          return value !== undefined && value.implicit !== true;\n        },\n        writeRole: (token: RolePatternToken, node: SemanticNode) => {\n          if (!node.roles.has(token.role)) return null;\n          let value = extractRoleValue(node, token.role);\n          const spec = schemas.get(node.action)?.roles.find(r => r.role === token.role);\n          if (spec?.quoteMultiword && /\\s/.test(value) && !/^([\"']).*\\1$/.test(value)) {\n            value = `\"${value}\"`;\n          }\n          return value || null;\n        },\n      };\n      return (node, language) => {\n        const patterns = registry.getPatterns(language).filter(p => p.command === node.action);\n        const pattern = selectRenderPattern(node, patterns, hooks);\n        if (!pattern) return null;\n        const text = renderPattern(node, pattern, hooks).join(' ');\n        return text || null;\n      };\n    },\n  };\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/domains/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/domains/sql').then(m => m.createSQLDSL()),\n *   getRenderer: () => import('@lokascript/domains/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 { UnreadInputError, TranslationReadBackError } from './create-dsl';\nimport { readingDifference } from './reading';\nimport type { SemanticNode } from '../core/types';\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      // A refusal is not a tool failure: say what was refused and why, as translate_code does.\n      if (error instanceof UnreadInputError) return unreadInputResponse(error);\n      if (error instanceof TranslationReadBackError) return readBackResponse(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      ...(result.errorCode === 'unread-input'\n        ? { diagnostics: [UNREAD_INPUT(result.errors)] }\n        : {}),\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      ...(result.errorCode === 'unread-input'\n        ? { diagnostics: [UNREAD_INPUT(result.errors)] }\n        : {}),\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    // The rendering must read back as the source, by the rule `translate` uses: the same action and\n    // role values, or the same compiled code. A rendering that does not is refused, with the text under\n    // `partial`, never `rendered`.\n    if (rendered != null) {\n      let back: SemanticNode | null = null;\n      let why = '';\n      try {\n        back = dsl.parse(rendered, to);\n        why = readingDifference(node, back);\n        if (why && compiled.ok) {\n          const again = dsl.compile(rendered, to);\n          if (again.ok && again.code === compiled.code) why = '';\n        }\n      } catch (error) {\n        why = error instanceof Error ? error.message : String(error);\n      }\n      if (why)\n        return readBackResponse(new TranslationReadBackError(rendered, from, to, node, back, why));\n    }\n\n    return jsonResponse({\n      ok: true,\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}. A rendering that does not read back as the source is REFUSED: ok is false, the diagnostic is TRANSLATION_DOES_NOT_READ_BACK, and its text is under \\`partial\\`, never \\`rendered\\`: do not present it as the translation. Input left unread is refused as UNREAD_INPUT.`,\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 readingOf(node: SemanticNode): { action: string; roles: Record<string, unknown> } {\n  const roles: Record<string, unknown> = {};\n  for (const [key, value] of node.roles) roles[key] = value;\n  return { action: node.action, roles };\n}\n\nconst UNREAD_INPUT = (errors?: readonly string[]) => ({\n  severity: 'error',\n  code: 'UNREAD_INPUT',\n  message: errors?.[0] ?? 'part of the input was not read',\n  suggestion:\n    'Part of the input belongs to no role of the command it reads as: remove it, or quote a value of several words.',\n});\n\n/** A parse refused because it read the command only by leaving input unread. */\nfunction unreadInputResponse(error: UnreadInputError): MCPToolResponse {\n  return jsonResponse(\n    {\n      ok: false,\n      unread: error.unread,\n      reading: readingOf(error.reading),\n      diagnostics: [UNREAD_INPUT([error.message])],\n    },\n    true\n  );\n}\n\n/** A translation refused because it does not read back as the source; its text under `partial`. */\nfunction readBackResponse(error: TranslationReadBackError): MCPToolResponse {\n  return jsonResponse(\n    {\n      ok: false,\n      partial: error.partial,\n      ...(error.reading ? { reading: readingOf(error.reading) } : {}),\n      diagnostics: [\n        {\n          severity: 'error',\n          code: 'TRANSLATION_DOES_NOT_READ_BACK',\n          message: error.message,\n          suggestion:\n            'The rendering would not mean the source in the target language: do not present `partial` as the translation.',\n        },\n      ],\n    },\n    true\n  );\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","/**\n * Fail-loud translation: what a translation checks before it returns (domains\n * rethink Phase 4.5, `docs-internal/DOMAINS_RETHINK.md`). Moved from\n * `@lokascript/semantic`'s `explicit/lossy.ts`, whose `translate` runs it with\n * hyperscript's rules; `createMultilingualDSL`'s `translate` keeps its own\n * read-back (`TranslationReadBackError`).\n *\n * A parse that matches a prefix of a script and leaves the rest unread used to\n * come back from `translate()` as though it were the whole: `toggle .a .b`\n * became `toggle .a`. A surface that cannot carry a script now says so: the\n * translation throws a {@link LossyTranslationError}, which carries the output\n * it would have returned and what it loses. Four checks, cheapest first:\n *\n *   - `truncation`  the parse of the input left input bound to no role (its\n *                   `unconsumed-input` diagnostics);\n *   - `core-only`   the input holds a form the grammar's writer has no spelling\n *                   for (hyperscript: a form only `@hyperfixi/core` ran, which\n *                   upstream reads with another meaning) — `rules.unwritable`;\n *   - `read-back`   the output, read in the target language, does not read,\n *                   leaves input unread, or differs from what was written\n *                   (`rules.differences`, in order);\n *   - `invariant`   a value the translation must write verbatim is missing\n *                   from the output (`rules.missingValues`).\n *\n * None of them can say a translation is right. Each says one way it is wrong.\n */\n\nexport type TranslationLossKind = 'truncation' | 'core-only' | 'read-back' | 'invariant';\n\n/** One way a translation loses part of its input. */\nexport interface TranslationLoss {\n  kind: TranslationLossKind;\n  /**\n   * What is lost: the input left unread (`truncation`); the forms nothing\n   * writes (`core-only`, as `swap <strategy>`); the output left unread or what\n   * it reads back without or with in excess (`read-back`, as `-cmd` / `+cmd`);\n   * or the verbatim values missing from the output (`invariant`).\n   */\n  lost: string[];\n}\n\nexport class LossyTranslationError extends Error {\n  override readonly name = 'LossyTranslationError';\n\n  constructor(\n    /** The output `translate()` would have returned: NOT the whole script. */\n    readonly partial: string,\n    readonly loss: TranslationLoss,\n    readonly from: string,\n    readonly to: string\n  ) {\n    super(\n      `translation ${from} → ${to} would lose part of the script (${loss.kind}): ` +\n        loss.lost.join(', ')\n    );\n  }\n}\n\n/** What the checks read of a parse: its diagnostics. */\nexport interface LossCheckedNode {\n  readonly diagnostics?: ReadonlyArray<{ readonly code?: string; readonly message: string }>;\n}\n\n/** The spans a parse left bound to no role (its top node carries them all). */\nexport function unconsumedSpans(node: LossCheckedNode): string[] {\n  const out: string[] = [];\n  for (const d of node.diagnostics ?? []) {\n    if (d.code !== 'unconsumed-input') continue;\n    out.push(/\"(.*)\"\\s*$/s.exec(d.message)?.[1] ?? d.message);\n  }\n  return out;\n}\n\n/** A grammar's rules for `findTranslationLoss`, for its node type `N`. */\nexport interface TranslationLossRules<N extends LossCheckedNode> {\n  /** The forms in `node` the grammar's writer has no spelling for (`core-only`). */\n  unwritable?(node: N): string[];\n  /**\n   * `node` as it was written into the target language, to compare its\n   * read-back with (hyperscript: in upstream's spelling for English). Default:\n   * `node` itself.\n   */\n  written?(node: N): N;\n  /**\n   * How the read-back differs from what was written, checked in order: the\n   * first that finds a difference is the loss (hyperscript: commands, then\n   * roles, then clauses kept as written).\n   */\n  readonly differences: ReadonlyArray<(written: N, back: N) => string[]>;\n  /** The values `input` holds that `output` must write verbatim and does not (`invariant`). */\n  missingValues?(input: string, output: string): string[];\n}\n\n/**\n * How a translation of `input` (parsed as `node`) into `output` loses part of\n * it, or undefined. `readBack` parses the output in the target language; it\n * throws when the output does not read.\n */\nexport function findTranslationLoss<N extends LossCheckedNode>(\n  input: string,\n  node: N,\n  output: string,\n  readBack: (output: string) => N,\n  rules: TranslationLossRules<N>\n): TranslationLoss | undefined {\n  const unread = unconsumedSpans(node);\n  if (unread.length) return { kind: 'truncation', lost: unread };\n  const unwritable = rules.unwritable?.(node) ?? [];\n  if (unwritable.length) return { kind: 'core-only', lost: unwritable };\n\n  let back: N;\n  try {\n    back = readBack(output);\n  } catch (e) {\n    return { kind: 'read-back', lost: [`the output does not read: ${(e as Error).message}`] };\n  }\n  const misread = unconsumedSpans(back);\n  if (misread.length) return { kind: 'read-back', lost: misread };\n  const written = rules.written ? rules.written(node) : node;\n  for (const difference of rules.differences) {\n    const lost = difference(written, back);\n    if (lost.length) return { kind: 'read-back', lost };\n  }\n\n  const values = rules.missingValues?.(input, output) ?? [];\n  if (values.length) return { kind: 'invariant', lost: values };\n  return undefined;\n}\n","/**\n * Domain-Aware Scanner\n *\n * Extracts DSL snippets from HTML/template files based on domain-declared\n * attribute patterns and script types. Unlike the hyperscript-specific\n * HTMLScanner, this scanner is configured dynamically from DomainScanConfig.\n */\n\nimport type { DomainScanConfig, ExtractedSnippet } from './types';\n\n// =============================================================================\n// Helpers\n// =============================================================================\n\n/**\n * Build regex patterns for extracting attribute values.\n * Handles double-quoted, single-quoted, and backtick-quoted values.\n */\nfunction buildAttributePatterns(attributes: readonly string[]): RegExp[] {\n  const patterns: RegExp[] = [];\n  for (const attr of attributes) {\n    const escaped = attr.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n    // Match: attr=\"value\", attr='value', attr=`value`\n    patterns.push(new RegExp(`${escaped}\\\\s*=\\\\s*\"([^\"]+)\"`, 'g'));\n    patterns.push(new RegExp(`${escaped}\\\\s*=\\\\s*'([^']+)'`, 'g'));\n    patterns.push(new RegExp(`${escaped}\\\\s*=\\\\s*\\`([^\\`]+)\\``, 'g'));\n  }\n  return patterns;\n}\n\n/**\n * Build regex patterns for extracting script tag contents.\n */\nfunction buildScriptPatterns(scriptTypes: readonly string[]): RegExp[] {\n  return scriptTypes.map(type => {\n    const escaped = type.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n    return new RegExp(`<script[^>]*type=[\"']?${escaped}[\"']?[^>]*>([\\\\s\\\\S]*?)<\\\\/script>`, 'gi');\n  });\n}\n\n/**\n * Count newlines before a position to determine line number.\n */\nfunction getLineNumber(source: string, position: number): number {\n  let line = 1;\n  for (let i = 0; i < position && i < source.length; i++) {\n    if (source[i] === '\\n') line++;\n  }\n  return line;\n}\n\n/**\n * Try to extract an element ID near the matched attribute.\n * Looks backward in the source for an id=\"...\" on the same element.\n */\nfunction extractElementId(source: string, matchIndex: number): string | undefined {\n  // Find the opening < before this attribute\n  const before = source.lastIndexOf('<', matchIndex);\n  if (before === -1) return undefined;\n\n  const tagChunk = source.slice(before, matchIndex + 200);\n  const idMatch = tagChunk.match(/\\bid=[\"']([^\"']+)[\"']/);\n  return idMatch?.[1];\n}\n\n/**\n * Try to extract a lang attribute from the element.\n */\nfunction extractLangAttribute(source: string, matchIndex: number): string | undefined {\n  const before = source.lastIndexOf('<', matchIndex);\n  if (before === -1) return undefined;\n\n  const tagChunk = source.slice(before, matchIndex + 200);\n  const langMatch = tagChunk.match(/\\blang=[\"']([^\"']+)[\"']/);\n  return langMatch?.[1];\n}\n\n// =============================================================================\n// DomainAwareScanner\n// =============================================================================\n\n/**\n * Scans HTML/template files for domain-specific snippets.\n *\n * Configured by DomainScanConfig objects, each declaring which\n * HTML attributes and script types a domain uses.\n */\nexport class DomainAwareScanner {\n  private configs: readonly DomainScanConfig[];\n\n  constructor(configs: readonly DomainScanConfig[]) {\n    this.configs = configs;\n  }\n\n  /**\n   * Extract all domain snippets from an HTML source string.\n   */\n  extract(source: string, filename: string): ExtractedSnippet[] {\n    const snippets: ExtractedSnippet[] = [];\n\n    for (const config of this.configs) {\n      const defaultLang = config.defaultLanguage ?? 'en';\n\n      // Extract from attributes\n      const attrPatterns = buildAttributePatterns(config.attributes);\n      for (const pattern of attrPatterns) {\n        pattern.lastIndex = 0;\n        let match: RegExpExecArray | null;\n        while ((match = pattern.exec(source))) {\n          const code = match[1].trim();\n          if (!code) continue;\n\n          const line = getLineNumber(source, match.index);\n          const elementId = extractElementId(source, match.index);\n          const langAttr = extractLangAttribute(source, match.index);\n\n          snippets.push({\n            domain: config.domain,\n            code,\n            language: langAttr ?? defaultLang,\n            file: filename,\n            line,\n            column: 1,\n            ...(elementId != null && { elementId }),\n          });\n        }\n      }\n\n      // Extract from script tags\n      if (config.scriptTypes) {\n        const scriptPatterns = buildScriptPatterns(config.scriptTypes);\n        for (const pattern of scriptPatterns) {\n          pattern.lastIndex = 0;\n          let match: RegExpExecArray | null;\n          while ((match = pattern.exec(source))) {\n            const code = match[1].trim();\n            if (!code) continue;\n\n            const line = getLineNumber(source, match.index);\n\n            snippets.push({\n              domain: config.domain,\n              code,\n              language: defaultLang,\n              file: filename,\n              line,\n              column: 1,\n            });\n          }\n        }\n      }\n    }\n\n    return snippets;\n  }\n\n  /**\n   * Extract snippets from multiple files.\n   */\n  async extractFromFiles(\n    files: string[],\n    readFile: (path: string) => Promise<string>\n  ): Promise<ExtractedSnippet[]> {\n    const allSnippets: ExtractedSnippet[] = [];\n\n    for (const file of files) {\n      try {\n        const source = await readFile(file);\n        const snippets = this.extract(source, file);\n        allSnippets.push(...snippets);\n      } catch {\n        // Skip files that can't be read\n      }\n    }\n\n    return allSnippets;\n  }\n}\n","/**\n * Generalized AOT Orchestrator\n *\n * Coordinates scan → parse → compile → collect for any domain.\n * Each domain provides a DomainCompilationBackend (DSL + CodeGenerator + scan config),\n * and the orchestrator handles the rest.\n *\n * @example\n * ```typescript\n * import { AOTOrchestrator } from '@lokascript/framework';\n *\n * const orchestrator = new AOTOrchestrator();\n *\n * orchestrator.registerBackend({\n *   domain: 'sql',\n *   dsl: createSQLDSL(),\n *   codeGenerator: sqlCodeGenerator,\n *   scanConfig: {\n *     domain: 'sql',\n *     attributes: ['data-sql'],\n *     scriptTypes: ['text/sql-dsl'],\n *   },\n * });\n *\n * const result = await orchestrator.compileFiles(\n *   ['index.html', 'about.html'],\n *   (path) => fs.promises.readFile(path, 'utf-8')\n * );\n * ```\n */\n\nimport type { MultilingualDSL, CodeGenerator } from '../api/create-dsl';\nimport type {\n  DomainScanConfig,\n  ExtractedSnippet,\n  CompiledSnippet,\n  AOTBatchResult,\n  GeneralizedAOTOptions,\n  OutputOptions,\n} from './types';\nimport { DomainAwareScanner } from './domain-scanner';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * Per-domain compilation backend.\n * Provides everything needed to scan, parse, and compile a domain's syntax.\n */\nexport interface DomainCompilationBackend {\n  /** Domain name (must match scanConfig.domain) */\n  readonly domain: string;\n  /** The DSL instance for parsing and compilation */\n  readonly dsl: MultilingualDSL;\n  /** Code generator for producing target code from semantic nodes */\n  readonly codeGenerator: CodeGenerator;\n  /** Scan configuration declaring HTML attribute patterns */\n  readonly scanConfig: DomainScanConfig;\n}\n\n// =============================================================================\n// AOTOrchestrator\n// =============================================================================\n\n/**\n * Generalized AOT orchestrator for any domain.\n */\nexport class AOTOrchestrator {\n  private backends = new Map<string, DomainCompilationBackend>();\n  private options: Required<GeneralizedAOTOptions>;\n\n  constructor(options?: GeneralizedAOTOptions) {\n    this.options = {\n      confidenceThreshold: options?.confidenceThreshold ?? 0.7,\n      continueOnError: options?.continueOnError ?? true,\n      debug: options?.debug ?? false,\n    };\n  }\n\n  /**\n   * Register a domain compilation backend.\n   * @throws if a backend with the same domain name is already registered\n   */\n  registerBackend(backend: DomainCompilationBackend): void {\n    if (this.backends.has(backend.domain)) {\n      throw new Error(`Backend already registered for domain: ${backend.domain}`);\n    }\n    this.backends.set(backend.domain, backend);\n  }\n\n  /**\n   * Scan source files and compile all domain snippets.\n   */\n  async compileFiles(\n    files: string[],\n    readFile: (path: string) => Promise<string>\n  ): Promise<AOTBatchResult> {\n    // Build scanner from all backends' scan configs\n    const configs = Array.from(this.backends.values()).map(b => b.scanConfig);\n    const scanner = new DomainAwareScanner(configs);\n\n    // Extract all snippets\n    const snippets = await scanner.extractFromFiles(files, readFile);\n\n    if (this.options.debug) {\n      console.log(`[aot] Extracted ${snippets.length} snippets from ${files.length} files`);\n    }\n\n    // Compile each snippet\n    const compiled: CompiledSnippet[] = [];\n    const errors: AOTBatchResult['errors'][number][] = [];\n    const domainBreakdown: Record<string, number> = {};\n\n    for (const snippet of snippets) {\n      domainBreakdown[snippet.domain] = (domainBreakdown[snippet.domain] ?? 0) + 1;\n\n      const result = this.compileSnippet(snippet);\n      if ('error' in result) {\n        errors.push({\n          domain: snippet.domain,\n          source: snippet.code,\n          file: snippet.file,\n          line: snippet.line,\n          message: result.error,\n        });\n        if (!this.options.continueOnError) break;\n      } else {\n        compiled.push(result);\n      }\n    }\n\n    return {\n      compiled,\n      errors,\n      stats: {\n        totalSnippets: snippets.length,\n        compiledCount: compiled.length,\n        errorCount: errors.length,\n        domainBreakdown,\n      },\n    };\n  }\n\n  /**\n   * Compile a single extracted snippet.\n   * Returns the compiled result or an error object.\n   */\n  compileSnippet(snippet: ExtractedSnippet): CompiledSnippet | { error: string } {\n    const backend = this.backends.get(snippet.domain);\n    if (!backend) {\n      return { error: `No backend registered for domain: ${snippet.domain}` };\n    }\n\n    try {\n      const result = backend.dsl.compile(snippet.code, snippet.language);\n      if (!result.ok || !result.code) {\n        return { error: result.errors?.join('; ') ?? 'Compilation failed' };\n      }\n\n      return {\n        domain: snippet.domain,\n        source: snippet.code,\n        compiled: result.code,\n        language: snippet.language,\n        file: snippet.file,\n        line: snippet.line,\n      };\n    } catch (err) {\n      return { error: err instanceof Error ? err.message : String(err) };\n    }\n  }\n\n  /**\n   * Generate combined output from compilation results.\n   */\n  generateOutput(result: AOTBatchResult, options?: OutputOptions): string {\n    const format = options?.format ?? 'esm';\n    const includeComments = options?.includeComments ?? true;\n    const groupByDomain = options?.groupByDomain ?? true;\n\n    const sections: string[] = [];\n\n    if (includeComments) {\n      sections.push(`// Generated by @lokascript/framework AOT compiler`);\n      sections.push(\n        `// ${result.stats.compiledCount} snippets compiled, ${result.stats.errorCount} errors`\n      );\n      sections.push('');\n    }\n\n    if (groupByDomain) {\n      // Group by domain\n      const grouped = new Map<string, CompiledSnippet[]>();\n      for (const snippet of result.compiled) {\n        const list = grouped.get(snippet.domain) ?? [];\n        list.push(snippet);\n        grouped.set(snippet.domain, list);\n      }\n\n      for (const [domain, snippets] of grouped) {\n        if (includeComments) {\n          sections.push(`// === Domain: ${domain} ===`);\n          sections.push('');\n        }\n\n        for (const snippet of snippets) {\n          if (includeComments) {\n            sections.push(`// Source: ${snippet.file}:${snippet.line}`);\n            sections.push(`// Language: ${snippet.language}`);\n          }\n          sections.push(snippet.compiled);\n          sections.push('');\n        }\n      }\n    } else {\n      for (const snippet of result.compiled) {\n        if (includeComments) {\n          sections.push(`// [${snippet.domain}] ${snippet.file}:${snippet.line}`);\n        }\n        sections.push(snippet.compiled);\n        sections.push('');\n      }\n    }\n\n    const body = sections.join('\\n').trimEnd();\n\n    switch (format) {\n      case 'cjs':\n        return `'use strict';\\n\\n${body}\\n`;\n      case 'iife':\n        return `(function() {\\n${body}\\n})();\\n`;\n      case 'esm':\n      default:\n        return `${body}\\n`;\n    }\n  }\n}\n","/**\n * Registry-to-AOT Bridge\n *\n * Converts DomainRegistry entries into DomainCompilationBackend instances\n * for use with AOTOrchestrator. Only domains that have scanConfig defined\n * are included.\n *\n * @example\n * ```typescript\n * const registry = new DomainRegistry();\n * // ... register domains with scanConfig ...\n *\n * const backends = await registryToAOTBackends(registry);\n * const orchestrator = new AOTOrchestrator();\n * for (const backend of backends) {\n *   orchestrator.registerBackend(backend);\n * }\n * ```\n */\n\nimport type { DomainCompilationBackend } from './aot-orchestrator';\nimport type { DomainScanConfig } from './types';\nimport type { DomainRegistry } from '../api/domain-registry';\nimport type { CodeGenerator } from '../api/create-dsl';\nimport type { SemanticNode } from '../core/types';\n\n/**\n * Convert all registry entries with scanConfig into AOT backends.\n * Domains without scanConfig are skipped.\n */\nexport async function registryToAOTBackends(\n  registry: DomainRegistry\n): Promise<DomainCompilationBackend[]> {\n  const backends: DomainCompilationBackend[] = [];\n\n  for (const name of registry.getDomainNames()) {\n    const descriptor = registry.getDescriptor(name);\n    if (!descriptor?.scanConfig) continue;\n\n    const dsl = await registry.getDSLForDomain(name);\n    if (!dsl) continue;\n\n    const scanConfig: DomainScanConfig = {\n      domain: name,\n      attributes: [...descriptor.scanConfig.attributes],\n      ...(descriptor.scanConfig.scriptTypes\n        ? { scriptTypes: [...descriptor.scanConfig.scriptTypes] }\n        : {}),\n      defaultLanguage: descriptor.scanConfig.defaultLanguage ?? 'en',\n    };\n\n    // The AOTOrchestrator only calls backend.dsl.compile(), not codeGenerator directly.\n    // Provide a thin adapter that parses then generates via the DSL's internal pipeline.\n    const codeGenerator: CodeGenerator = {\n      generate(node: SemanticNode): string {\n        // Fallback: compile through the DSL by reconstructing explicit syntax.\n        // In practice, AOTOrchestrator uses dsl.compile() directly.\n        return JSON.stringify({ action: node.action, roles: Object.fromEntries(node.roles) });\n      },\n    };\n\n    backends.push({ domain: name, dsl, codeGenerator, scanConfig });\n  }\n\n  return backends;\n}\n","/**\n * Command Schema Types — re-exported from @lokascript/intent\n */\n\nexport type { CommandSchema, RoleSpec } from '@lokascript/intent';\nexport { defineCommand, defineRole, getRoleSpec } from '@lokascript/intent';\n","/**\n * A domain's language profile, and the role order its sentences use.\n */\n\nimport type { RoleSpec } from '../schema';\n\n/**\n * A domain's language profile as framework reads it: word order, command\n * keywords, and role markers (with the side of the value each attaches to).\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 * Sort roles by word order: descending `svoPosition` (or `sovPosition` in an\n * SOV language) — higher values come first. The schema renderer\n * (`createSchemaRenderer`) orders roles with it, as the core's pattern\n * generator does (`createSchemaPatternGenerator` with `positionOrder:\n * 'descending'`), so a rendered surface re-parses.\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 * 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 './profile';\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 * Structured Error Diagnostics\n *\n * Re-exported from @lokascript/intent.\n * This module is the framework's re-export point for the diagnostic types\n * that live in the universal intent package.\n */\n\nexport type {\n  DiagnosticSeverity,\n  Diagnostic,\n  DiagnosticResult,\n  DiagnosticSummary,\n  DiagnosticCollector,\n  DiagnosticOptions,\n} from '@lokascript/intent';\n\nexport { createDiagnosticCollector, fromError, filterBySeverity } from '@lokascript/intent';\n","/**\n * Extraction Utilities\n *\n * Pure functions for extracting CSS selectors, string literals, URLs, and numbers\n * from input strings. These are language-independent and used by all tokenizers.\n */\n\nimport {\n  isSelectorStart,\n  isWhitespace,\n  isAsciiIdentifierChar,\n  isAsciiLetter,\n  isQuote,\n  isDigit,\n} from './token-utils';\n\n// =============================================================================\n// CSS Selector Tokenization\n// =============================================================================\n\n/**\n * Extract a CSS selector from the input string starting at pos.\n * CSS selectors are universal across languages.\n *\n * Supported formats:\n * - #id\n * - .class\n * - [attribute]\n * - [attribute=value]\n * - @attribute (shorthand)\n * - *property (CSS property shorthand)\n * - Complex selectors with combinators (limited)\n *\n * Method call handling:\n * - #dialog.showModal() → stops after #dialog (method call, not compound selector)\n * - #box.active → compound selector (no parens)\n *\n * NOTE: intentionally diverges from the semantic package's copy\n * (packages/semantic/src/tokenizers/extractors/css-selector.ts), which also\n * consumes pseudo-class/pseudo-element segments (#x:hover, .a:not(.b)). This\n * legacy version is only used by BaseTokenizer.trySelector (no semantic call\n * sites) and stays as-is.\n */\nexport function extractCssSelector(input: string, startPos: number): string | null {\n  if (startPos >= input.length) return null;\n\n  const char = input[startPos];\n  if (!isSelectorStart(char)) return null;\n\n  let pos = startPos;\n  let selector = '';\n\n  // Handle different selector types\n  if (char === '#' || char === '.') {\n    // ID or class selector: #id, .class\n    selector += input[pos++];\n    while (pos < input.length && isAsciiIdentifierChar(input[pos])) {\n      selector += input[pos++];\n    }\n    // Must have at least one character after prefix\n    if (selector.length <= 1) return null;\n\n    // Check for method call pattern: #id.method() or .class.method()\n    // If we see .identifier followed by (, don't consume it - it's a method call\n    if (pos < input.length && input[pos] === '.' && char === '#') {\n      // Look ahead to see if this is a method call\n      const methodStart = pos + 1;\n      let methodEnd = methodStart;\n      while (methodEnd < input.length && isAsciiIdentifierChar(input[methodEnd])) {\n        methodEnd++;\n      }\n      // If followed by (, it's a method call - stop here\n      if (methodEnd < input.length && input[methodEnd] === '(') {\n        return selector;\n      }\n    }\n  } else if (char === '[') {\n    // Attribute selector: [attr] or [attr=value] or [attr=\"value\"]\n    // Need to track quote state to avoid counting brackets inside quotes\n    let depth = 1;\n    let inQuote = false;\n    let quoteChar: string | null = null;\n    let escaped = false;\n\n    selector += input[pos++]; // [\n\n    while (pos < input.length && depth > 0) {\n      const c = input[pos];\n      selector += c;\n\n      if (escaped) {\n        // Skip escaped character\n        escaped = false;\n      } else if (c === '\\\\') {\n        // Next character is escaped\n        escaped = true;\n      } else if (inQuote) {\n        // Inside a quoted string\n        if (c === quoteChar) {\n          inQuote = false;\n          quoteChar = null;\n        }\n      } else {\n        // Not inside a quoted string\n        if (c === '\"' || c === \"'\" || c === '`') {\n          inQuote = true;\n          quoteChar = c;\n        } else if (c === '[') {\n          depth++;\n        } else if (c === ']') {\n          depth--;\n        }\n      }\n      pos++;\n    }\n    if (depth !== 0) return null;\n  } else if (char === '@') {\n    // Attribute shorthand: @disabled\n    selector += input[pos++];\n    while (pos < input.length && isAsciiIdentifierChar(input[pos])) {\n      selector += input[pos++];\n    }\n    if (selector.length <= 1) return null;\n  } else if (char === '*') {\n    // CSS property shorthand: *display\n    selector += input[pos++];\n    while (pos < input.length && isAsciiIdentifierChar(input[pos])) {\n      selector += input[pos++];\n    }\n    if (selector.length <= 1) return null;\n  } else if (char === '<') {\n    // HTML literal selector with optional modifiers and attributes:\n    // - <div>\n    // - <div.class>\n    // - <div#id>\n    // - <div.class#id>\n    // - <button[disabled]/>\n    // - <div.card/>\n    // - <div.class#id[attr=\"value\"]/>\n    selector += input[pos++]; // <\n\n    // Must be followed by an identifier (tag name)\n    if (pos >= input.length || !isAsciiLetter(input[pos])) return null;\n\n    // Extract tag name\n    while (pos < input.length && isAsciiIdentifierChar(input[pos])) {\n      selector += input[pos++];\n    }\n\n    // Process modifiers and attributes\n    // Can have multiple .class, one #id, and multiple [attr] in any order\n    while (pos < input.length) {\n      const modChar = input[pos];\n\n      if (modChar === '.') {\n        // Class modifier\n        selector += input[pos++]; // .\n        if (pos >= input.length || !isAsciiIdentifierChar(input[pos])) {\n          return null; // Invalid - class name required after .\n        }\n        while (pos < input.length && isAsciiIdentifierChar(input[pos])) {\n          selector += input[pos++];\n        }\n      } else if (modChar === '#') {\n        // ID modifier\n        selector += input[pos++]; // #\n        if (pos >= input.length || !isAsciiIdentifierChar(input[pos])) {\n          return null; // Invalid - ID required after #\n        }\n        while (pos < input.length && isAsciiIdentifierChar(input[pos])) {\n          selector += input[pos++];\n        }\n      } else if (modChar === '[') {\n        // Attribute modifier: [disabled] or [type=\"button\"]\n        // Need to track quote state to avoid counting brackets inside quotes\n        let depth = 1;\n        let inQuote = false;\n        let quoteChar: string | null = null;\n        let escaped = false;\n\n        selector += input[pos++]; // [\n\n        while (pos < input.length && depth > 0) {\n          const c = input[pos];\n          selector += c;\n\n          if (escaped) {\n            escaped = false;\n          } else if (c === '\\\\') {\n            escaped = true;\n          } else if (inQuote) {\n            if (c === quoteChar) {\n              inQuote = false;\n              quoteChar = null;\n            }\n          } else {\n            if (c === '\"' || c === \"'\" || c === '`') {\n              inQuote = true;\n              quoteChar = c;\n            } else if (c === '[') {\n              depth++;\n            } else if (c === ']') {\n              depth--;\n            }\n          }\n          pos++;\n        }\n        if (depth !== 0) return null; // Unclosed bracket\n      } else {\n        // No more modifiers\n        break;\n      }\n    }\n\n    // Skip whitespace before optional self-closing /\n    while (pos < input.length && isWhitespace(input[pos])) {\n      selector += input[pos++];\n    }\n\n    // Optional self-closing /\n    if (pos < input.length && input[pos] === '/') {\n      selector += input[pos++];\n      // Skip whitespace after /\n      while (pos < input.length && isWhitespace(input[pos])) {\n        selector += input[pos++];\n      }\n    }\n\n    // Must end with >\n    if (pos >= input.length || input[pos] !== '>') return null;\n    selector += input[pos++]; // >\n  }\n\n  return selector || null;\n}\n\n// =============================================================================\n// String Literal Tokenization\n// =============================================================================\n\n/**\n * Check if a single quote at pos is a possessive marker ('s).\n * Returns true if this looks like possessive, not a string start.\n *\n * Examples:\n * - #element's *opacity → possessive (returns true)\n * - 'hello' → string (returns false)\n * - it's value → possessive (returns true)\n */\nexport function isPossessiveMarker(input: string, pos: number): boolean {\n  if (pos >= input.length || input[pos] !== \"'\") return false;\n\n  // Check if followed by 's' or 'S'\n  if (pos + 1 >= input.length) return false;\n  const nextChar = input[pos + 1].toLowerCase();\n  if (nextChar !== 's') return false;\n\n  // After 's, should be end, whitespace, or special char (not alphanumeric)\n  if (pos + 2 >= input.length) return true; // end of input\n  const afterS = input[pos + 2];\n  return isWhitespace(afterS) || afterS === '*' || !isAsciiIdentifierChar(afterS);\n}\n\n/**\n * Extract a string literal from the input starting at pos.\n * Handles both ASCII quotes and Unicode quotes.\n *\n * Note: Single quotes that look like possessive markers ('s) are skipped.\n */\nexport function extractStringLiteral(input: string, startPos: number): string | null {\n  if (startPos >= input.length) return null;\n\n  const openQuote = input[startPos];\n  if (!isQuote(openQuote)) return null;\n\n  // Check for possessive marker - don't treat as string\n  if (openQuote === \"'\" && isPossessiveMarker(input, startPos)) {\n    return null;\n  }\n\n  // Map opening quotes to closing quotes\n  const closeQuoteMap: Record<string, string> = {\n    '\"': '\"',\n    \"'\": \"'\",\n    '`': '`',\n    '「': '」',\n  };\n\n  const closeQuote = closeQuoteMap[openQuote];\n  if (!closeQuote) return null;\n\n  let pos = startPos + 1;\n  let literal = openQuote;\n  let escaped = false;\n\n  while (pos < input.length) {\n    const char = input[pos];\n    literal += char;\n\n    if (escaped) {\n      escaped = false;\n    } else if (char === '\\\\') {\n      escaped = true;\n    } else if (char === closeQuote) {\n      // Found closing quote\n      return literal;\n    }\n    pos++;\n  }\n\n  // Unclosed string - return what we have\n  return literal;\n}\n\n// =============================================================================\n// URL Tokenization\n// =============================================================================\n\n/**\n * Check if the input at position starts a URL.\n * Detects: /path, ./path, ../path, //domain.com, http://, https://\n */\nexport function isUrlStart(input: string, pos: number): boolean {\n  if (pos >= input.length) return false;\n\n  const char = input[pos];\n  const next = input[pos + 1] || '';\n  const third = input[pos + 2] || '';\n\n  // Absolute path: /something (but not just /)\n  // Must be followed by alphanumeric or path char, not another / (that's protocol-relative)\n  if (char === '/' && next !== '/' && /[a-zA-Z0-9._-]/.test(next)) {\n    return true;\n  }\n\n  // Protocol-relative: //domain.com\n  if (char === '/' && next === '/' && /[a-zA-Z]/.test(third)) {\n    return true;\n  }\n\n  // Relative path: ./ or ../\n  if (char === '.' && (next === '/' || (next === '.' && third === '/'))) {\n    return true;\n  }\n\n  // Full URL: http:// or https://\n  const slice = input.slice(pos, pos + 8).toLowerCase();\n  if (slice.startsWith('http://') || slice.startsWith('https://')) {\n    return true;\n  }\n\n  return false;\n}\n\n/**\n * Extract a URL from the input starting at pos.\n * Handles paths, query strings, and fragments.\n *\n * Fragment (#) handling:\n * - /page#section → includes fragment as part of URL\n * - #id alone → not a URL (CSS selector)\n */\nexport function extractUrl(input: string, startPos: number): string | null {\n  if (!isUrlStart(input, startPos)) return null;\n\n  let pos = startPos;\n  let url = '';\n\n  // Core URL characters (RFC 3986 unreserved + sub-delims + path/query chars)\n  // Includes: letters, digits, and - . _ ~ : / ? # [ ] @ ! $ & ' ( ) * + , ; = %\n  const urlChars = /[a-zA-Z0-9/:._\\-?&=%@+~!$'()*,;[\\]]/;\n\n  while (pos < input.length) {\n    const char = input[pos];\n\n    // Special handling for #\n    if (char === '#') {\n      // Only include # if we have path content before it (it's a fragment)\n      // If # appears at URL start or after certain chars, stop (might be CSS selector)\n      if (url.length > 0 && /[a-zA-Z0-9/.]$/.test(url)) {\n        // Include fragment\n        url += char;\n        pos++;\n        // Consume fragment identifier (letters, digits, underscore, hyphen)\n        while (pos < input.length && /[a-zA-Z0-9_-]/.test(input[pos])) {\n          url += input[pos++];\n        }\n      }\n      // Stop either way - fragment consumed or # is separate token\n      break;\n    }\n\n    if (urlChars.test(char)) {\n      url += char;\n      pos++;\n    } else {\n      break;\n    }\n  }\n\n  // Minimum length validation\n  if (url.length < 2) return null;\n\n  return url;\n}\n\n// =============================================================================\n// Number Tokenization\n// =============================================================================\n\n/**\n * Extract a number from the input starting at pos.\n * Handles integers and decimals.\n */\nexport function extractNumber(input: string, startPos: number): string | null {\n  if (startPos >= input.length) return null;\n\n  const char = input[startPos];\n  if (!isDigit(char) && char !== '-' && char !== '+') return null;\n\n  let pos = startPos;\n  let number = '';\n\n  // Optional sign\n  if (input[pos] === '-' || input[pos] === '+') {\n    number += input[pos++];\n  }\n\n  // Must have at least one digit\n  if (pos >= input.length || !isDigit(input[pos])) {\n    return null;\n  }\n\n  // Integer part\n  while (pos < input.length && isDigit(input[pos])) {\n    number += input[pos++];\n  }\n\n  // Optional decimal part\n  if (pos < input.length && input[pos] === '.') {\n    number += input[pos++];\n    while (pos < input.length && isDigit(input[pos])) {\n      number += input[pos++];\n    }\n  }\n\n  // Optional duration suffix (s, ms, m, h)\n  if (pos < input.length) {\n    const suffix = input.slice(pos, pos + 2);\n    if (suffix === 'ms') {\n      number += 'ms';\n    } else if (input[pos] === 's' || input[pos] === 'm' || input[pos] === 'h') {\n      number += input[pos];\n    }\n  }\n\n  return number;\n}\n","/**\n * Operator Extractor - Handles programming language operators\n *\n * Extracts operators like +, -, *, /, =, >, <, >=, <=, !=, ===, etc.\n * Supports multi-character operators with longest-match priority.\n */\n\nimport type { ValueExtractor, ExtractionResult } from '../../../interfaces/value-extractor';\n\n/**\n * Default operators for most programming languages.\n * Sorted longest-first for greedy matching.\n */\nexport const DEFAULT_OPERATORS = [\n  // Three-character operators\n  '===',\n  '!==',\n  '->',\n  // Two-character operators\n  '==',\n  '!=',\n  '<=',\n  '>=',\n  '&&',\n  '||',\n  '**',\n  '+=',\n  '-=',\n  '*=',\n  '/=',\n  // Single-character operators\n  '+',\n  '-',\n  '*',\n  '/',\n  '=',\n  '>',\n  '<',\n  '!',\n  '&',\n  '|',\n  '%',\n  '^',\n  '~',\n];\n\n/**\n * OperatorExtractor - Extracts programming language operators.\n */\nexport class OperatorExtractor implements ValueExtractor {\n  readonly name = 'operator';\n\n  constructor(private operators: string[] = DEFAULT_OPERATORS) {\n    // Sort operators longest-first for greedy matching\n    this.operators = [...operators].sort((a, b) => b.length - a.length);\n  }\n\n  canExtract(input: string, position: number): boolean {\n    return this.operators.some(op => input.startsWith(op, position));\n  }\n\n  extract(input: string, position: number): ExtractionResult | null {\n    // Find longest matching operator\n    for (const op of this.operators) {\n      if (input.startsWith(op, position)) {\n        return {\n          value: op,\n          length: op.length,\n        };\n      }\n    }\n\n    return null;\n  }\n}\n","/**\n * Punctuation Extractor - Handles punctuation characters\n *\n * Extracts punctuation like parentheses, brackets, braces, commas, colons, semicolons.\n * Each character is extracted individually (no multi-character punctuation).\n */\n\nimport type { ValueExtractor, ExtractionResult } from '../../../interfaces/value-extractor';\n\n/**\n * Default punctuation characters for most programming languages.\n */\nexport const DEFAULT_PUNCTUATION = '()[]{},:;';\n\n/**\n * PunctuationExtractor - Extracts punctuation characters.\n */\nexport class PunctuationExtractor implements ValueExtractor {\n  readonly name = 'punctuation';\n\n  constructor(private punctuation: string = DEFAULT_PUNCTUATION) {}\n\n  canExtract(input: string, position: number): boolean {\n    return this.punctuation.includes(input[position]);\n  }\n\n  extract(input: string, position: number): ExtractionResult | null {\n    const char = input[position];\n\n    if (this.punctuation.includes(char)) {\n      return {\n        value: char,\n        length: 1,\n      };\n    }\n\n    return null;\n  }\n}\n","/**\n * Default Extractor Sets\n *\n * Provides pre-configured sets of extractors for common use cases.\n * DSLs can use these as a starting point and add domain-specific extractors.\n */\n\nimport type { ValueExtractor } from '../../interfaces/value-extractor';\nimport {\n  StringLiteralExtractor,\n  NumberExtractor,\n  IdentifierExtractor,\n  UnicodeIdentifierExtractor,\n} from '../../interfaces/value-extractor';\nimport { OperatorExtractor, PunctuationExtractor } from './extractors/index';\n\n/**\n * Get default extractors for generic programming-language-style DSLs.\n * These work for most DSLs (SQL, config files, scripts, etc.).\n *\n * Included extractors:\n * - String literals: \"double\", 'single', `backtick`\n * - Numbers: 123, 45.67\n * - Operators: +, -, *, /, =, ==, !=, >=, <=, etc.\n * - Punctuation: ( ) [ ] { } , : ;\n * - Identifiers: variable_names, functionNames\n * - Unicode identifiers: CJK, Arabic, Cyrillic, etc.\n *\n * @returns Array of default extractors\n *\n * @example\n * ```typescript\n * class MyDSLTokenizer extends BaseTokenizer {\n *   constructor() {\n *     super();\n *     this.registerExtractors(getDefaultExtractors());\n *   }\n * }\n * ```\n */\nexport function getDefaultExtractors(): ValueExtractor[] {\n  return [\n    new StringLiteralExtractor(), // \"strings\", 'strings', `strings`\n    new NumberExtractor(), // 123, 45.67\n    new OperatorExtractor(), // +, -, *, /, =, >, <, etc.\n    new PunctuationExtractor(), // ( ) [ ] { } , : ;\n    new IdentifierExtractor(), // variable_names, functionNames (ASCII)\n    new UnicodeIdentifierExtractor(), // CJK, Arabic, Cyrillic, etc.\n  ];\n}\n\n/**\n * Auto-register default extractors in a tokenizer.\n * Convenience helper for chaining.\n *\n * @param tokenizer - Tokenizer to configure\n * @returns The same tokenizer (for chaining)\n *\n * @example\n * ```typescript\n * const tokenizer = withDefaultExtractors(new MyTokenizer());\n * ```\n */\nexport function withDefaultExtractors<\n  T extends { registerExtractors(extractors: ValueExtractor[]): void },\n>(tokenizer: T): T {\n  tokenizer.registerExtractors(getDefaultExtractors());\n  return tokenizer;\n}\n","/**\n * Base Tokenizer Class\n *\n * Abstract base class for language-specific tokenizers.\n * Provides keyword management, morphological normalization,\n * and high-level token extraction methods.\n */\n\nimport type { LanguageToken, TokenKind, TokenStream, LanguageTokenizer } from '../types';\nimport type { MorphologicalNormalizer, NormalizationResult } from './morphology/types';\nimport {\n  type ValueExtractor,\n  type KeywordEntry,\n  isContextAwareExtractor,\n  createTokenizerContext,\n} from '../../interfaces/value-extractor';\nimport {\n  createToken,\n  createPosition,\n  isWhitespace,\n  isDigit,\n  isAsciiIdentifierChar,\n  stripOptionalDiacritics,\n  TokenStreamImpl,\n  type TimeUnitMapping,\n  type CreateTokenOptions,\n} from './token-utils';\nimport { extractCssSelector, extractStringLiteral, extractNumber, extractUrl } from './extractors';\nimport { DEFAULT_OPERATORS } from './extractors/operator';\nimport { getDefaultExtractors } from './default-extractors';\n\n// Module-scope operator set for O(1) lookup in createSimpleTokenizer.\n// Uses the canonical list from OperatorExtractor to avoid duplication.\nconst SIMPLE_TOKENIZER_OPERATOR_SET = new Set(DEFAULT_OPERATORS);\n\n/**\n * Normalized concepts that are matched via the pattern matcher's ROLE-MARKER\n * MECHANISM (the source/destination/event clause matchers in\n * `packages/semantic/src/parser/pattern-matcher.ts`), which peeks/advances a\n * SINGLE token and checks `.value`/`.normalized`. A multi-word phrase carrying\n * one of these must NOT be pre-matched as a single keyword token — doing so\n * shadows the single-word marker those clause matchers expect (e.g. id\n * `ke dalam`=into hides the `ke` destination marker; ko `할 때`=eventMarker\n * pre-empts SOV event extraction).\n *\n * NOTE — what is *not* here. Prepositional modifiers that the generated patterns\n * expose as ordinary pattern LITERALS (`before`/`after` in put-before/after,\n * `until` in repeat-until) are deliberately absent: those are read by\n * `matchLiteralToken`, which compares the whole token by exact value OR\n * normalized form (`getMatchType`), so a multi-word marker token (`से पहले`,\n * `cho đến khi`) matches the literal's value/alternatives directly with no\n * special handling. Keeping them out lets `tryMultiWordKeyword` emit them as one\n * token — the profile-driven replacement for the per-language hardcoded compound\n * lists (Task #10). `into` stays excluded because it IS consumed by the role\n * mechanism in some languages (id destination `ke`), and `from`/`to`/`with`/\n * `on`/`at`/`of`/`as`/`by`/`in` are genuine role markers. Command verbs /\n * control-flow / event names were always absent. See `multiWordKeywords` /\n * `tryMultiWordKeyword`.\n */\nconst MARKER_CONCEPT_NORMALIZEDS: ReadonlySet<string> = new Set([\n  // Role-marker role names (profile.roleMarkers normalizeds)\n  'patient',\n  'destination',\n  'source',\n  'style',\n  'event',\n  'eventMarker',\n  'agent',\n  'goal',\n  'manner',\n  // Prepositional / positional modifier concepts matched via the role mechanism\n  // (profile.keywords \"Modifiers\"). `before`/`after`/`until` are intentionally\n  // NOT here — they are pattern literals (see the note above).\n  'into',\n  'from',\n  'to',\n  'with',\n  'at',\n  'of',\n  'as',\n  'by',\n  'in',\n  'on',\n  'over',\n  'under',\n  'between',\n  'through',\n  'without',\n]);\n\n/**\n * A hyphen-JOINED keyword surface (`na-żywo`, `ao-vivo`): letters on both sides\n * of every hyphen. A leading/trailing hyphen (qu's `-kama` / `-manta` suffix\n * alternatives) or a bare `-` is not one — those stay with the word walk.\n */\nfunction isHyphenatedWord(native: string): boolean {\n  return native.includes('-') && /^[\\p{L}\\p{N}_]+(-[\\p{L}\\p{N}_]+)+$/u.test(native);\n}\n\n// =============================================================================\n// Types\n// =============================================================================\n\n// KeywordEntry is imported from interfaces/value-extractor and re-exported\n// for backward compatibility with code importing from this module.\nexport type { KeywordEntry };\n\n/**\n * Standard DOM event names recognized in every language as universal fallbacks.\n * The i18n grammar transformer emits these verbatim (no native dictionary form),\n * so each tokenizer must accept them or English-named event handlers won't parse.\n * Kept to genuine DOM event names (not command verbs) to minimize collisions; the\n * registration is `!has`-guarded so any native keyword of the same spelling wins.\n */\nconst ENGLISH_DOM_EVENT_NAMES: readonly string[] = [\n  'click',\n  'dblclick',\n  'input',\n  'change',\n  'submit',\n  'keydown',\n  'keyup',\n  'keypress',\n  'mousedown',\n  'mouseup',\n  'mouseover',\n  'mouseout',\n  'mouseenter',\n  'mouseleave',\n  'mousemove',\n  'pointerdown',\n  'pointerup',\n  'pointermove',\n  'focus',\n  'blur',\n  'load',\n  'resize',\n  'scroll',\n];\n\n/**\n * Profile interface for keyword derivation.\n * Matches the structure of LanguageProfile but only includes fields needed for tokenization.\n */\nexport interface TokenizerProfile {\n  readonly keywords?: Record<\n    string,\n    { primary: string; alternatives?: string[]; normalized?: string }\n  >;\n  readonly references?: Record<string, string>;\n  readonly roleMarkers?: Record<\n    string,\n    { primary: string; alternatives?: string[]; position?: string }\n  >;\n  readonly possessive?: {\n    readonly marker: string;\n    readonly markerPosition: 'after-object' | 'between' | 'before-property';\n    readonly specialForms?: Record<string, string>;\n    readonly usePossessiveAdjectives?: boolean;\n    readonly keywords?: Record<string, string>;\n  };\n}\n\n// =============================================================================\n// Base Tokenizer Class\n// =============================================================================\n\n/**\n * Abstract base class for language-specific tokenizers.\n * Provides common functionality for CSS selectors, strings, and numbers.\n */\nexport abstract class BaseTokenizer implements LanguageTokenizer {\n  abstract readonly language: string;\n  abstract readonly direction: 'ltr' | 'rtl';\n\n  /** Optional morphological normalizer for this language */\n  protected normalizer?: MorphologicalNormalizer;\n\n  /** Keywords derived from profile, sorted longest-first for greedy matching */\n  protected profileKeywords: KeywordEntry[] = [];\n\n  /**\n   * Space-containing profile keywords (multi-word phrases), longest-first.\n   * Used by `tryMultiWordKeyword` so natural spaced forms (hi `मेल खाता`,\n   * vi `chuyển đổi`, es `tecla abajo`, …) tokenize as ONE keyword — the\n   * profile-driven replacement for the per-language hardcoded compound lists.\n   * Empty for no-space (CJK) languages, so they are unaffected.\n   */\n  protected multiWordKeywords: KeywordEntry[] = [];\n\n  /** Map for O(1) keyword lookups by lowercase native word */\n  protected profileKeywordMap: Map<string, KeywordEntry> = new Map();\n\n  /**\n   * The raw EXTRAS list passed to initializeKeywordsFromProfile, kept pre-dedup.\n   * The keyword map is keyed by native word with last-wins insertion, so a\n   * duplicate native word inside the extras silently shadows the earlier entry\n   * (e.g. a `nächste→closest` entry shadowing `nächste→next` broke German\n   * positional expressions). Exposed so consistency tests can detect such\n   * intra-extras collisions, which are invisible in the deduplicated map.\n   */\n  private rawExtraEntries: KeywordEntry[] = [];\n\n  /** Raw extras as passed in, pre-dedup — for consistency tests. */\n  getExtraKeywordEntries(): readonly KeywordEntry[] {\n    return this.rawExtraEntries;\n  }\n\n  /**\n   * Pluggable value extractors for domain-specific syntax.\n   * When registered, BaseTokenizer will use extractor-based tokenization instead of legacy methods.\n   */\n  protected extractors: ValueExtractor[] = [];\n\n  /**\n   * Tokenize input string to token stream.\n   * Delegates to extractor-based tokenization if extractors are registered,\n   * otherwise subclass must override this method.\n   *\n   * @param input - Input string to tokenize\n   * @returns Token stream\n   */\n  tokenize(input: string): TokenStream {\n    if (this.isUsingExtractors()) {\n      return this.tokenizeWithExtractors(input);\n    }\n\n    // If no extractors registered, subclass must provide implementation\n    throw new Error(\n      `${this.constructor.name}: tokenize() not implemented and no extractors registered. ` +\n        'Either register extractors or override tokenize() method.'\n    );\n  }\n\n  abstract classifyToken(token: string): TokenKind;\n\n  /**\n   * Register a value extractor for domain-specific syntax.\n   * Extractors are tried in registration order during tokenization.\n   * Context-aware extractors automatically receive the tokenizer context.\n   *\n   * @param extractor - Value extractor to register\n   */\n  registerExtractor(extractor: ValueExtractor): void {\n    if (isContextAwareExtractor(extractor)) {\n      extractor.setContext(createTokenizerContext(this as any));\n    }\n    this.extractors.push(extractor);\n  }\n\n  /**\n   * Register multiple value extractors at once.\n   *\n   * @param extractors - Array of value extractors to register\n   */\n  registerExtractors(extractors: ValueExtractor[]): void {\n    for (const extractor of extractors) {\n      this.registerExtractor(extractor);\n    }\n  }\n\n  /**\n   * Clear all registered extractors.\n   * Returns tokenizer to legacy mode.\n   */\n  clearExtractors(): void {\n    this.extractors = [];\n  }\n\n  /**\n   * Check if this tokenizer is using extractor-based tokenization.\n   * Returns true if any extractors are registered.\n   */\n  protected isUsingExtractors(): boolean {\n    return this.extractors.length > 0;\n  }\n\n  /**\n   * Tokenize input using registered value extractors.\n   * This is the new path - extractors handle all syntax detection.\n   *\n   * @param input - Input string to tokenize\n   * @returns Token stream\n   */\n  protected tokenizeWithExtractors(input: string): TokenStream {\n    const tokens: LanguageToken[] = [];\n    let pos = 0;\n\n    while (pos < input.length) {\n      // Skip whitespace\n      while (pos < input.length && isWhitespace(input[pos])) {\n        pos++;\n      }\n      if (pos >= input.length) break;\n\n      // Multi-word keyword pre-match: a profile keyword containing a space\n      // (e.g. hi `मेल खाता`, vi `chuyển đổi`, es `tecla abajo`) is matched as ONE\n      // keyword token at a word boundary, longest-first. Runs before the\n      // per-language extractors so natural spaced multi-word keywords tokenize\n      // without each tokenizer hardcoding a compound list. No-op for single-word\n      // and no-space (CJK) languages (multiWordKeywords is empty).\n      const multiWord = this.tryMultiWordKeyword(input, pos);\n      if (multiWord) {\n        tokens.push(multiWord);\n        pos = multiWord.position.end;\n        continue;\n      }\n\n      // Try registered extractors in order\n      let extracted = false;\n      for (const extractor of this.extractors) {\n        if (extractor.canExtract(input, pos)) {\n          const result = extractor.extract(input, pos);\n          if (result) {\n            // Promote normalized/stem/stemConfidence from metadata to top-level token options\n            const normalized = result.metadata?.normalized as string | undefined;\n            const stem = result.metadata?.stem as string | undefined;\n            const stemConfidence = result.metadata?.stemConfidence as number | undefined;\n\n            // Build clean metadata without promoted fields\n            const cleanMetadata: Record<string, unknown> = {};\n            if (result.metadata) {\n              for (const [key, value] of Object.entries(result.metadata)) {\n                if (key !== 'normalized' && key !== 'stem' && key !== 'stemConfidence') {\n                  cleanMetadata[key] = value;\n                }\n              }\n            }\n\n            const options: CreateTokenOptions = {};\n            if (normalized) options.normalized = normalized;\n            if (stem) options.stem = stem;\n            if (stemConfidence !== undefined) options.stemConfidence = stemConfidence;\n            if (Object.keys(cleanMetadata).length > 0) options.metadata = cleanMetadata;\n\n            tokens.push(\n              createToken(\n                result.value,\n                this.classifyToken(result.value),\n                createPosition(pos, pos + result.length),\n                Object.keys(options).length > 0 ? options : undefined\n              )\n            );\n            pos += result.length;\n            extracted = true;\n            break;\n          }\n        }\n      }\n\n      // Fallback: single character as operator/punctuation\n      if (!extracted) {\n        const char = input[pos];\n        const kind = this.classifyUnknownChar(char);\n        tokens.push(createToken(char, kind, createPosition(pos, pos + 1)));\n        pos++;\n      }\n    }\n\n    return new TokenStreamImpl(this.mergeColonQualifiedNames(tokens), this.language);\n  }\n\n  /**\n   * ASCII word of the shape the English word-walker produces. Excludes `:`, so a\n   * token that already carries a qualifier never merges again — `a:b:c` yields\n   * `a:b` + `:c`, byte-matching the English extractor's single-segment merge.\n   */\n  private static readonly ASCII_WORD = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n  /** `:name` — only a variable-ref-style extractor ever emits this token shape. */\n  private static readonly COLON_QUALIFIER = /^:[A-Za-z_][A-Za-z0-9_]*$/;\n\n  /**\n   * Fuse `name` + `:qualifier` into ONE identifier (`draggable:start`).\n   *\n   * `:name` is hyperscript's local-variable sigil, but a colon IMMEDIATELY\n   * preceded by an identifier is a qualifier (custom event namespace), not a\n   * sigil. The English tokenizer already merges these inside\n   * EnglishKeywordExtractor; this post-pass gives the other 23 languages the\n   * same stream. Strict position adjacency is the discriminator: whitespace\n   * between the tokens (`trigger :start`) breaks `end === start`, so a spaced\n   * local-variable reference survives untouched.\n   *\n   * Self-gating for non-hyperscript tokenizers (domain DSLs): their extractor\n   * sets tokenize `:` as bare punctuation (length 1), which never matches\n   * COLON_QUALIFIER, so this pass is a no-op for them.\n   */\n  protected mergeColonQualifiedNames(tokens: LanguageToken[]): LanguageToken[] {\n    const out: LanguageToken[] = [];\n    for (const tok of tokens) {\n      const prev = out[out.length - 1];\n      // No kind gate: the English extractor merges before classification, so a\n      // word some language classifies as particle/keyword (es `a`, tr `i`)\n      // must fuse the same way. ASCII_WORD already excludes every non-word\n      // kind structurally (selectors, urls, numbers, strings, operators).\n      if (\n        prev &&\n        BaseTokenizer.ASCII_WORD.test(prev.value) &&\n        BaseTokenizer.COLON_QUALIFIER.test(tok.value) &&\n        prev.position.end === tok.position.start\n      ) {\n        const merged = prev.value + tok.value;\n        // Re-classify and drop normalized/stem/metadata — the merged word is no\n        // longer the keyword the pieces may have been (matches the en shape).\n        out[out.length - 1] = createToken(\n          merged,\n          this.classifyToken(merged),\n          createPosition(prev.position.start, tok.position.end)\n        );\n        continue;\n      }\n      out.push(tok);\n    }\n    return out;\n  }\n\n  /**\n   * Classify an unknown character when no extractor matches.\n   * Provides sensible defaults for common syntax.\n   *\n   * @param char - Character to classify\n   * @returns Token kind\n   */\n  protected classifyUnknownChar(char: string): TokenKind {\n    if ('()[]{},:;'.includes(char)) return 'punctuation';\n    if ('+-*/<>=!&|'.includes(char)) return 'operator';\n    return 'identifier';\n  }\n\n  /**\n   * Check if current position is a property access (obj.prop) vs CSS selector (.active).\n   * Property access: no whitespace before '.', previous token is identifier/keyword/selector.\n   * Also detects standalone method calls: .identifier( pattern.\n   *\n   * Returns true if '.' was emitted as an operator token and pos should advance by 1.\n   * Returns false if this is a CSS selector and should be handled by trySelector().\n   */\n  protected tryPropertyAccess(input: string, pos: number, tokens: LanguageToken[]): boolean {\n    if (input[pos] !== '.') return false;\n\n    const lastToken = tokens[tokens.length - 1];\n    // Property access requires NO whitespace between tokens (e.g., \"obj.prop\")\n    const hasWhitespaceBefore = lastToken && lastToken.position.end < pos;\n    const isPropertyAccess =\n      lastToken &&\n      !hasWhitespaceBefore &&\n      (lastToken.kind === 'identifier' ||\n        lastToken.kind === 'keyword' ||\n        lastToken.kind === 'selector');\n\n    if (isPropertyAccess) {\n      tokens.push(createToken('.', 'operator', createPosition(pos, pos + 1)));\n      return true;\n    }\n\n    // Check for method call pattern at start: .identifier(\n    const methodStart = pos + 1;\n    let methodEnd = methodStart;\n    while (methodEnd < input.length && isAsciiIdentifierChar(input[methodEnd])) {\n      methodEnd++;\n    }\n    if (methodEnd < input.length && input[methodEnd] === '(') {\n      tokens.push(createToken('.', 'operator', createPosition(pos, pos + 1)));\n      return true;\n    }\n\n    return false;\n  }\n\n  /**\n   * Initialize keyword mappings from a language profile.\n   * Builds a list of native→english mappings from:\n   * - profile.keywords (primary + alternatives)\n   * - profile.references (me, it, you, etc.)\n   * - profile.roleMarkers (into, from, with, etc.)\n   *\n   * Results are sorted longest-first for greedy matching (important for non-space languages).\n   * Extras take precedence over profile entries when there are duplicates.\n   *\n   * @param profile - Language profile containing keyword translations\n   * @param extras - Additional keyword entries to include (literals, positional, events)\n   */\n  protected initializeKeywordsFromProfile(\n    profile: TokenizerProfile,\n    extras: KeywordEntry[] = []\n  ): void {\n    // Use a Map to deduplicate, with extras taking precedence\n    const keywordMap = new Map<string, KeywordEntry>();\n    this.rawExtraEntries = extras;\n\n    // Extract from keywords (command translations)\n    if (profile.keywords) {\n      for (const [normalized, translation] of Object.entries(profile.keywords)) {\n        // Primary translation\n        keywordMap.set(translation.primary, {\n          native: translation.primary,\n          normalized: translation.normalized || normalized,\n        });\n\n        // Alternative forms\n        if (translation.alternatives) {\n          for (const alt of translation.alternatives) {\n            keywordMap.set(alt, {\n              native: alt,\n              normalized: translation.normalized || normalized,\n            });\n          }\n        }\n      }\n    }\n\n    // Extract from references (me, it, you, etc.)\n    if (profile.references) {\n      for (const [normalized, native] of Object.entries(profile.references)) {\n        keywordMap.set(native, { native, normalized });\n      }\n      // Also register English canonical forms as universal fallbacks.\n      // Users frequently mix English references (me, it, you) into non-English\n      // hyperscript (e.g., \"alternar .active on me\"). Without this, the English\n      // word \"me\" would be unrecognized in non-English token streams.\n      for (const canonical of Object.keys(profile.references)) {\n        if (!keywordMap.has(canonical)) {\n          keywordMap.set(canonical, { native: canonical, normalized: canonical });\n        }\n      }\n    }\n\n    // Extract from roleMarkers (into, from, with, etc.)\n    if (profile.roleMarkers) {\n      for (const [role, marker] of Object.entries(profile.roleMarkers)) {\n        if (marker.primary) {\n          keywordMap.set(marker.primary, { native: marker.primary, normalized: role });\n        }\n        if (marker.alternatives) {\n          for (const alt of marker.alternatives) {\n            keywordMap.set(alt, { native: alt, normalized: role });\n          }\n        }\n      }\n    }\n\n    // Extract from possessive keywords (e.g., ñuqapa, qampa for Quechua)\n    if (profile.possessive?.keywords) {\n      for (const [native, normalized] of Object.entries(profile.possessive.keywords)) {\n        keywordMap.set(native, { native, normalized });\n      }\n    }\n\n    // Register English DOM event names as universal fallbacks. The i18n grammar\n    // transformer has no native form for most DOM events, so it passes them\n    // through verbatim (`on keyup …` → `<on-marker> keyup …`). Without these,\n    // non-English token streams treat `keyup`/`keydown`/`resize`/… as bare\n    // identifiers, and event handlers using them (often with `[key==…]` guards)\n    // fail to parse. Guarded by `!has` so any native mapping wins (same policy\n    // as the English-reference fallbacks above). Generalizes the per-language\n    // registration introduced for Hebrew in #272.\n    for (const evt of ENGLISH_DOM_EVENT_NAMES) {\n      if (!keywordMap.has(evt)) {\n        keywordMap.set(evt, { native: evt, normalized: evt });\n      }\n    }\n\n    // Add extra entries (literals, positional, events) - these OVERRIDE profile entries\n    for (const extra of extras) {\n      keywordMap.set(extra.native, extra);\n    }\n\n    // Convert to array and sort longest-first for greedy matching\n    this.profileKeywords = Array.from(keywordMap.values()).sort(\n      (a, b) => b.native.length - a.native.length\n    );\n\n    // Multi-word keywords — space-containing (hi `मेल खाता`, vi `chuyển đổi`)\n    // or HYPHENATED (pl `na-żywo`, pt `ao-vivo`, fr `point-arrêt`) — for\n    // longest-phrase matching at a token boundary. Already longest-first\n    // (profileKeywords is sorted above). Hyphenated ones were left to the word\n    // walk, which stops at the `-` and hands the parts to whatever they happen\n    // to be: pl `na-żywo` (live) read as `na`(→destination) + `-` + `żywo`, so\n    // every pl `live … koniec` render parsed back as a handler with the `live`\n    // action gone; es `en-vivo` / pt `ao-vivo` survived only because their\n    // second half is a `live` alternative.\n    // Marker/modifier concepts are EXCLUDED: those are matched positionally by\n    // the pattern matcher (role markers), and greedily consuming a multi-word\n    // marker phrase shadows the single-word marker patterns rely on — e.g. id\n    // `ke dalam` (into) would swallow the `ke` destination marker, and ko `할 때`\n    // (eventMarker) would pre-empt the SOV event extraction. Command verbs,\n    // control-flow, and event-name keywords (vi `với mỗi`=for, es `tecla abajo`=\n    // keydown, bn `তৈরি করুন`=make) are kept — the pattern matcher treats those\n    // as keyword literals, so one-token matching is strictly better.\n    this.multiWordKeywords = this.profileKeywords.filter(\n      k =>\n        (k.native.includes(' ') || isHyphenatedWord(k.native)) &&\n        !MARKER_CONCEPT_NORMALIZEDS.has(k.normalized)\n    );\n\n    // Build Map for O(1) lookups (case-insensitive + diacritic-insensitive)\n    // This allows matching both 'بدّل' (with shadda) and 'بدل' (without) to the same entry\n    this.profileKeywordMap = new Map();\n    for (const keyword of this.profileKeywords) {\n      // Add original form (with diacritics if present)\n      this.profileKeywordMap.set(keyword.native.toLowerCase(), keyword);\n\n      // Add diacritic-normalized form (for Arabic, Turkish, etc.)\n      const normalized = this.removeDiacritics(keyword.native);\n      if (normalized !== keyword.native && !this.profileKeywordMap.has(normalized.toLowerCase())) {\n        this.profileKeywordMap.set(normalized.toLowerCase(), keyword);\n      }\n    }\n  }\n\n  /**\n   * Remove diacritical marks from a word for normalization.\n   * Primarily for Arabic (shadda, fatha, kasra, damma, sukun, etc.)\n   * but could be extended for other languages.\n   *\n   * @param word - Word to normalize\n   * @returns Word without diacritics\n   */\n  protected removeDiacritics(word: string): string {\n    return stripOptionalDiacritics(word);\n  }\n\n  /**\n   * Try to match a keyword from profile at the current position.\n   * Uses longest-first greedy matching (important for non-space languages).\n   *\n   * @param input - Input string\n   * @param pos - Current position\n   * @returns Token if matched, null otherwise\n   */\n  protected tryProfileKeyword(input: string, pos: number): LanguageToken | null {\n    for (const entry of this.profileKeywords) {\n      if (input.slice(pos).startsWith(entry.native)) {\n        return createToken(\n          entry.native,\n          'keyword',\n          createPosition(pos, pos + entry.native.length),\n          entry.normalized\n        );\n      }\n    }\n    return null;\n  }\n\n  /**\n   * Match the longest multi-word (space-containing) profile keyword at `pos`,\n   * requiring the match to end at a word boundary. The profile-driven\n   * counterpart of the per-language hardcoded compound lists (the hindi and\n   * vietnamese keyword extractors). Returns a keyword token (with the normalized\n   * form) or null. Case-sensitive against the stored native form, mirroring\n   * `tryProfileKeyword`/`isKeywordStart` (the i18n dicts emit a fixed surface\n   * case). No-op when `multiWordKeywords` is empty (no-space/CJK languages).\n   *\n   * @param input - Input string\n   * @param pos - Current position (must be a token-start boundary)\n   * @param isWordChar - End-boundary predicate (defaults to Unicode letter/digit/_)\n   */\n  protected tryMultiWordKeyword(\n    input: string,\n    pos: number,\n    isWordChar: (char: string) => boolean = ch => /[\\p{L}\\p{N}_]/u.test(ch)\n  ): LanguageToken | null {\n    if (this.multiWordKeywords.length === 0) return null;\n    const rest = input.slice(pos);\n    for (const entry of this.multiWordKeywords) {\n      if (!rest.startsWith(entry.native)) continue;\n      const after = input[pos + entry.native.length];\n      if (after !== undefined && isWordChar(after)) continue; // not a word boundary\n      return createToken(\n        entry.native,\n        'keyword',\n        createPosition(pos, pos + entry.native.length),\n        entry.normalized\n      );\n    }\n    return null;\n  }\n\n  /**\n   * Check if the remaining input starts with any known keyword.\n   * Useful for non-space languages to detect word boundaries.\n   *\n   * @param input - Input string\n   * @param pos - Current position\n   * @returns true if a keyword starts at this position\n   */\n  protected isKeywordStart(input: string, pos: number): boolean {\n    const remaining = input.slice(pos);\n    return this.profileKeywords.some(entry => remaining.startsWith(entry.native));\n  }\n\n  /**\n   * Check if a known keyword starts at the given position AND ends at a word\n   * boundary (end of input or a non-word character).\n   *\n   * Space-delimited languages must use this (not `isKeywordStart`) for\n   * word-walk break checks: the keyword table includes English canonical\n   * fallbacks (me, it, you, …), so a raw `startsWith` check splits any native\n   * word with an embedded fallback mid-word (e.g. Quechua ñit'iy contains\n   * \"it\"). CJK/no-space tokenizers rely on mid-text keyword starts and must\n   * keep using `isKeywordStart`.\n   *\n   * @param input - Input string\n   * @param pos - Current position\n   * @param isWordChar - Language-specific word-character predicate; pass the\n   *   tokenizer's letter classifier so e.g. the Quechua glottal apostrophe\n   *   counts as part of a word. Defaults to Unicode letters/digits/underscore.\n   * @returns true if a keyword starts here and is not followed by a word char\n   */\n  protected isKeywordStartAtBoundary(\n    input: string,\n    pos: number,\n    isWordChar: (char: string) => boolean = ch => /[\\p{L}\\p{N}_]/u.test(ch)\n  ): boolean {\n    const remaining = input.slice(pos);\n    return this.profileKeywords.some(entry => {\n      if (!remaining.startsWith(entry.native)) return false;\n      const after = input[pos + entry.native.length];\n      return after === undefined || !isWordChar(after);\n    });\n  }\n\n  /**\n   * Look up a keyword by native word (case-insensitive, diacritic-insensitive).\n   * O(1) lookup using the keyword map.\n   *\n   * The map is INDEXED both with and without diacritics (see\n   * `initializeKeywordsFromProfile`), so a stripped QUERY is the other half of\n   * that: it lets a surface form carrying harakat the profile does not happen to\n   * spell still find its entry. Only consulted after the exact lookup misses, so\n   * every previously-matching word resolves byte-identically.\n   *\n   * Half-implementing this — indexing stripped but querying exact — is what made\n   * diacritized `بَدِّل` (toggle) tokenize as `kind=particle normalized=with`:\n   * `isKeyword` returned false, so the guard in `ArabicProcliticExtractor` that\n   * exists to prevent exactly that handed the word on, and the single-char `ب`\n   * bi- proclitic claimed it. A wrong CONCEPT, not a failed parse.\n   *\n   * @param native - Native word to look up\n   * @returns KeywordEntry if found, undefined otherwise\n   */\n  protected lookupKeyword(native: string): KeywordEntry | undefined {\n    const exact = this.profileKeywordMap.get(native.toLowerCase());\n    if (exact) return exact;\n    const stripped = this.removeDiacritics(native);\n    if (stripped === native) return undefined;\n    return this.profileKeywordMap.get(stripped.toLowerCase());\n  }\n\n  /**\n   * Check if a word is a known keyword (case-insensitive, diacritic-insensitive).\n   * O(1) lookup using the keyword map. See {@link lookupKeyword}.\n   *\n   * @param native - Native word to check\n   * @returns true if the word is a keyword\n   */\n  protected isKeyword(native: string): boolean {\n    return this.lookupKeyword(native) !== undefined;\n  }\n\n  /**\n   * Set the morphological normalizer for this tokenizer.\n   */\n  setNormalizer(normalizer: MorphologicalNormalizer): void {\n    this.normalizer = normalizer;\n  }\n\n  /**\n   * Try to normalize a word using the morphological normalizer.\n   * Returns null if no normalizer is set or normalization fails.\n   *\n   * Note: We don't check isNormalizable() here because the individual tokenizers\n   * historically called normalize() directly without that check. The normalize()\n   * method itself handles returning noChange() for words that can't be normalized.\n   */\n  protected tryNormalize(word: string): NormalizationResult | null {\n    if (!this.normalizer) return null;\n\n    const result = this.normalizer.normalize(word);\n\n    // Only return if actually normalized (stem differs from input)\n    if (result.stem !== word && result.confidence >= 0.7) {\n      return result;\n    }\n\n    return null;\n  }\n\n  /**\n   * Try morphological normalization and keyword lookup.\n   *\n   * If the word can be normalized to a stem that matches a known keyword,\n   * returns a keyword token with morphological metadata (stem, stemConfidence).\n   *\n   * This is the common pattern for handling conjugated verbs across languages:\n   * 1. Normalize the word (e.g., \"toggled\" → \"toggle\")\n   * 2. Look up the stem in the keyword map\n   * 3. Create a token with both the original form and stem metadata\n   *\n   * @param word - The word to normalize and look up\n   * @param startPos - Start position for the token\n   * @param endPos - End position for the token\n   * @returns Token if stem matches a keyword, null otherwise\n   */\n  protected tryMorphKeywordMatch(\n    word: string,\n    startPos: number,\n    endPos: number\n  ): LanguageToken | null {\n    const result = this.tryNormalize(word);\n    if (!result) return null;\n\n    // Check if the stem is a known keyword\n    const stemEntry = this.lookupKeyword(result.stem);\n    if (!stemEntry) return null;\n\n    const tokenOptions: CreateTokenOptions = {\n      normalized: stemEntry.normalized,\n      stem: result.stem,\n      stemConfidence: result.confidence,\n    };\n    return createToken(word, 'keyword', createPosition(startPos, endPos), tokenOptions);\n  }\n\n  /**\n   * Try to extract a CSS selector at the current position.\n   */\n  protected trySelector(input: string, pos: number): LanguageToken | null {\n    const selector = extractCssSelector(input, pos);\n    if (selector) {\n      return createToken(selector, 'selector', createPosition(pos, pos + selector.length));\n    }\n    return null;\n  }\n\n  /**\n   * Try to extract an event modifier at the current position.\n   * Event modifiers are .once, .debounce(N), .throttle(N), .queue(strategy)\n   */\n  protected tryEventModifier(input: string, pos: number): LanguageToken | null {\n    // Must start with a dot\n    if (input[pos] !== '.') {\n      return null;\n    }\n\n    // Match pattern: .(once|debounce|throttle|queue) followed by optional (value)\n    const match = input\n      .slice(pos)\n      .match(/^\\.(?:once|debounce|throttle|queue)(?:\\(([^)]+)\\))?(?:\\s|$|\\.)/);\n    if (!match) {\n      return null;\n    }\n\n    const fullMatch = match[0].replace(/(\\s|\\.)$/, ''); // Remove trailing space or dot\n    const modifierName = fullMatch.slice(1).split('(')[0]; // Extract modifier name\n    const value = match[1]; // Extract value from parentheses if present\n\n    // Create token with metadata\n    const token = createToken(\n      fullMatch,\n      'event-modifier',\n      createPosition(pos, pos + fullMatch.length)\n    );\n\n    // Add metadata for the modifier\n    return {\n      ...token,\n      metadata: {\n        modifierName,\n        value: value ? (modifierName === 'queue' ? value : parseInt(value, 10)) : undefined,\n      },\n    };\n  }\n\n  /**\n   * Try to extract a string literal at the current position.\n   */\n  protected tryString(input: string, pos: number): LanguageToken | null {\n    const literal = extractStringLiteral(input, pos);\n    if (literal) {\n      return createToken(literal, 'literal', createPosition(pos, pos + literal.length));\n    }\n    return null;\n  }\n\n  /**\n   * Try to extract a number at the current position.\n   */\n  protected tryNumber(input: string, pos: number): LanguageToken | null {\n    const number = extractNumber(input, pos);\n    if (number) {\n      return createToken(number, 'literal', createPosition(pos, pos + number.length));\n    }\n    return null;\n  }\n\n  /**\n   * Configuration for native language time units.\n   * Maps patterns to their standard suffix (ms, s, m, h).\n   */\n  protected static readonly STANDARD_TIME_UNITS: readonly TimeUnitMapping[] = [\n    { pattern: 'ms', suffix: 'ms', length: 2 },\n    { pattern: 's', suffix: 's', length: 1, checkBoundary: true },\n    { pattern: 'm', suffix: 'm', length: 1, checkBoundary: true, notFollowedBy: 's' },\n    { pattern: 'h', suffix: 'h', length: 1, checkBoundary: true },\n  ];\n\n  /**\n   * Try to match a time unit from a list of patterns.\n   *\n   * @param input - Input string\n   * @param pos - Position after the number\n   * @param timeUnits - Array of time unit mappings (native pattern → standard suffix)\n   * @param skipWhitespace - Whether to skip whitespace before time unit (default: false)\n   * @returns Object with matched suffix and new position, or null if no match\n   */\n  protected tryMatchTimeUnit(\n    input: string,\n    pos: number,\n    timeUnits: readonly TimeUnitMapping[],\n    skipWhitespace = false\n  ): { suffix: string; endPos: number } | null {\n    let unitPos = pos;\n\n    // Optionally skip whitespace before time unit\n    if (skipWhitespace) {\n      while (unitPos < input.length && isWhitespace(input[unitPos])) {\n        unitPos++;\n      }\n    }\n\n    const remaining = input.slice(unitPos);\n\n    // Check each time unit pattern\n    for (const unit of timeUnits) {\n      const candidate = remaining.slice(0, unit.length);\n      const matches = unit.caseInsensitive\n        ? candidate.toLowerCase() === unit.pattern.toLowerCase()\n        : candidate === unit.pattern;\n\n      if (matches) {\n        // Check notFollowedBy constraint (e.g., 'm' should not match 'ms')\n        if (unit.notFollowedBy) {\n          const nextChar = remaining[unit.length] || '';\n          if (nextChar === unit.notFollowedBy) continue;\n        }\n\n        // Check word boundary if required\n        if (unit.checkBoundary) {\n          const nextChar = remaining[unit.length] || '';\n          if (isAsciiIdentifierChar(nextChar)) continue;\n        }\n\n        return { suffix: unit.suffix, endPos: unitPos + unit.length };\n      }\n    }\n\n    return null;\n  }\n\n  /**\n   * Parse a base number (sign, integer, decimal) without time units.\n   * Returns the number string and end position.\n   *\n   * @param input - Input string\n   * @param startPos - Start position\n   * @param allowSign - Whether to allow +/- sign (default: true)\n   * @returns Object with number string and end position, or null\n   */\n  protected parseBaseNumber(\n    input: string,\n    startPos: number,\n    allowSign = true\n  ): { number: string; endPos: number } | null {\n    let pos = startPos;\n    let number = '';\n\n    // Optional sign\n    if (allowSign && (input[pos] === '-' || input[pos] === '+')) {\n      number += input[pos++];\n    }\n\n    // Must have at least one digit\n    if (pos >= input.length || !isDigit(input[pos])) {\n      return null;\n    }\n\n    // Integer part\n    while (pos < input.length && isDigit(input[pos])) {\n      number += input[pos++];\n    }\n\n    // Optional decimal\n    if (pos < input.length && input[pos] === '.') {\n      number += input[pos++];\n      while (pos < input.length && isDigit(input[pos])) {\n        number += input[pos++];\n      }\n    }\n\n    if (!number || number === '-' || number === '+') return null;\n\n    return { number, endPos: pos };\n  }\n\n  /**\n   * Try to extract a number with native language time units.\n   *\n   * This is a template method that handles the common pattern:\n   * 1. Parse the base number (sign, integer, decimal)\n   * 2. Try to match native language time units\n   * 3. Fall back to standard time units (ms, s, m, h)\n   *\n   * @param input - Input string\n   * @param pos - Start position\n   * @param nativeTimeUnits - Language-specific time unit mappings\n   * @param options - Configuration options\n   * @returns Token if number found, null otherwise\n   */\n  protected tryNumberWithTimeUnits(\n    input: string,\n    pos: number,\n    nativeTimeUnits: readonly TimeUnitMapping[],\n    options: { allowSign?: boolean; skipWhitespace?: boolean } = {}\n  ): LanguageToken | null {\n    const { allowSign = true, skipWhitespace = false } = options;\n\n    // Parse base number\n    const baseResult = this.parseBaseNumber(input, pos, allowSign);\n    if (!baseResult) return null;\n\n    let { number, endPos } = baseResult;\n\n    // Try native time units first, then standard\n    const allUnits = [...nativeTimeUnits, ...BaseTokenizer.STANDARD_TIME_UNITS];\n    const timeMatch = this.tryMatchTimeUnit(input, endPos, allUnits, skipWhitespace);\n\n    if (timeMatch) {\n      number += timeMatch.suffix;\n      endPos = timeMatch.endPos;\n    }\n\n    return createToken(number, 'literal', createPosition(pos, endPos));\n  }\n\n  /**\n   * Try to extract a URL at the current position.\n   * Handles /path, ./path, ../path, //domain.com, http://, https://\n   */\n  protected tryUrl(input: string, pos: number): LanguageToken | null {\n    const url = extractUrl(input, pos);\n    if (url) {\n      return createToken(url, 'url', createPosition(pos, pos + url.length));\n    }\n    return null;\n  }\n\n  /**\n   * Try to extract a variable reference (:varname) at the current position.\n   * In hyperscript, :x refers to a local variable named x.\n   */\n  protected tryVariableRef(input: string, pos: number): LanguageToken | null {\n    if (input[pos] !== ':') return null;\n    if (pos + 1 >= input.length) return null;\n    if (!isAsciiIdentifierChar(input[pos + 1])) return null;\n\n    let endPos = pos + 1;\n    while (endPos < input.length && isAsciiIdentifierChar(input[endPos])) {\n      endPos++;\n    }\n\n    const varRef = input.slice(pos, endPos);\n    return createToken(varRef, 'identifier', createPosition(pos, endPos));\n  }\n\n  /**\n   * Try to extract an operator or punctuation token at the current position.\n   * Handles two-character operators (==, !=, etc.) and single-character operators.\n   */\n  protected tryOperator(input: string, pos: number): LanguageToken | null {\n    // Two-character operators\n    const twoChar = input.slice(pos, pos + 2);\n    if (['==', '!=', '<=', '>=', '&&', '||', '->'].includes(twoChar)) {\n      return createToken(twoChar, 'operator', createPosition(pos, pos + 2));\n    }\n\n    // Single-character operators\n    const oneChar = input[pos];\n    if (['<', '>', '!', '+', '-', '*', '/', '='].includes(oneChar)) {\n      return createToken(oneChar, 'operator', createPosition(pos, pos + 1));\n    }\n\n    // Punctuation\n    if (['(', ')', '{', '}', ',', ';', ':'].includes(oneChar)) {\n      return createToken(oneChar, 'punctuation', createPosition(pos, pos + 1));\n    }\n\n    return null;\n  }\n\n  /**\n   * Try to match a multi-character particle from a list.\n   *\n   * Used by languages like Japanese, Korean, and Chinese that have\n   * multi-character particles (e.g., Japanese から, まで, より).\n   *\n   * @param input - Input string\n   * @param pos - Current position\n   * @param particles - Array of multi-character particles to match\n   * @returns Token if matched, null otherwise\n   */\n  protected tryMultiCharParticle(\n    input: string,\n    pos: number,\n    particles: readonly string[]\n  ): LanguageToken | null {\n    for (const particle of particles) {\n      if (input.slice(pos, pos + particle.length) === particle) {\n        return createToken(particle, 'particle', createPosition(pos, pos + particle.length));\n      }\n    }\n    return null;\n  }\n}\n\n// =============================================================================\n// Simple Tokenizer Factory\n// =============================================================================\n\n/**\n * Configuration for createSimpleTokenizer.\n *\n * Creates a tokenizer from declarative config instead of a class definition.\n * Covers the common pattern used by domain packages (SQL, BDD, JSX).\n *\n * **Keyword resolution** uses two additive paths:\n * 1. `keywords` — explicit list, checked first. Respects `caseInsensitive`.\n * 2. `keywordProfile` — populates BaseTokenizer's profile keyword map via\n *    `initializeKeywordsFromProfile()`. Checked second via `isKeyword()`, which\n *    always lowercases (harmless for CJK/Arabic; notable for Latin scripts\n *    with `caseInsensitive: false`). Provides normalization metadata for\n *    non-Latin scripts.\n */\nexport interface SimpleTokenizerConfig {\n  /** ISO 639-1 language code */\n  language: string;\n  /** Text direction (default: 'ltr') */\n  direction?: 'ltr' | 'rtl';\n  /** Keywords to recognize (lowercased for lookup if caseInsensitive) */\n  keywords: string[];\n  /** Extra keyword entries for non-Latin normalization */\n  keywordExtras?: KeywordEntry[];\n  /** Profile for initializeKeywordsFromProfile (for non-Latin scripts) */\n  keywordProfile?: TokenizerProfile;\n  /** Include operator classification (default: false). Uses DEFAULT_OPERATORS from OperatorExtractor. */\n  includeOperators?: boolean;\n  /** Case-insensitive keyword matching (default: true) */\n  caseInsensitive?: boolean;\n  /** Custom extractors registered BEFORE default extractors */\n  customExtractors?: ValueExtractor[];\n}\n\n/**\n * Create a tokenizer from declarative configuration.\n *\n * Eliminates the boilerplate of extending BaseTokenizer for simple domain tokenizers.\n * Handles keyword classification, optional operator support, and non-Latin keyword setup.\n *\n * @example\n * ```typescript\n * const englishSQL = createSimpleTokenizer({\n *   language: 'en',\n *   keywords: ['select', 'insert', 'update', 'delete', 'from', 'into', 'where', 'set', 'values'],\n *   includeOperators: true,\n *   caseInsensitive: true,\n * });\n * ```\n */\nexport function createSimpleTokenizer(config: SimpleTokenizerConfig): LanguageTokenizer {\n  const {\n    language,\n    direction = 'ltr',\n    keywords,\n    keywordExtras,\n    keywordProfile,\n    includeOperators = false,\n    caseInsensitive = true,\n    customExtractors,\n  } = config;\n\n  const keywordSet = new Set(caseInsensitive ? keywords.map(k => k.toLowerCase()) : keywords);\n\n  class SimpleTokenizer extends BaseTokenizer {\n    readonly language = language;\n    readonly direction = direction;\n\n    constructor() {\n      super();\n      if (customExtractors) {\n        this.registerExtractors(customExtractors);\n      }\n      this.registerExtractors(getDefaultExtractors());\n      if (keywordProfile) {\n        this.initializeKeywordsFromProfile(keywordProfile, keywordExtras);\n      }\n    }\n\n    classifyToken(token: string): TokenKind {\n      // Fast path: explicit keywords from config (respects caseInsensitive)\n      const lookup = caseInsensitive ? token.toLowerCase() : token;\n      if (keywordSet.has(lookup)) return 'keyword';\n      // Profile path: non-Latin normalization (always lowercases via profileKeywordMap)\n      if (this.isKeyword(token)) return 'keyword';\n      if (/^\\d/.test(token)) return 'literal';\n      if (/^['\"]/.test(token)) return 'literal';\n      if (includeOperators && SIMPLE_TOKENIZER_OPERATOR_SET.has(token)) return 'operator';\n      return 'identifier';\n    }\n  }\n\n  return new SimpleTokenizer();\n}\n","/**\n * Framework ↔ Semantic bridge builders.\n *\n * Pure functions that combine an injected {@link GrammarProfileSlice} (the\n * per-language grammar facts, typically a `@lokascript/semantic`\n * `LanguageProfile`) with a {@link DomainVocabulary} (the only thing a domain\n * authors per language) into the shapes `createMultilingualDSL` consumes:\n * a `PatternGenLanguageProfile`, a `LanguageTokenizer`, or a complete\n * `LanguageConfig`.\n */\n\nimport type { LanguageTokenizer } from '../core/types';\nimport type { PatternGenLanguageProfile } from '../generation/profile';\nimport type { LanguageConfig } from '../api/create-dsl';\nimport type { LanguageProfile as GrammarProfile } from '../grammar';\nimport { createSimpleTokenizer, type TokenizerProfile } from '../core/tokenization/base-tokenizer';\nimport {\n  LatinExtendedIdentifierExtractor,\n  type ValueExtractor,\n} from '../interfaces/value-extractor';\nimport type { DomainVocabulary, GrammarProfileSlice, RoleMarkerSlice } from './types';\n\n/** Mutable role-marker shape shared by PatternGenLanguageProfile and TokenizerProfile. */\ntype MergedRoleMarker = { primary: string; alternatives?: string[]; position?: 'before' | 'after' };\n\n/**\n * Merge the slice's language-default role markers with the vocabulary's\n * domain-specific overrides (vocabulary wins). Empty-string primaries are\n * dropped — an empty override means \"bare positional arg, no marker\".\n */\nfunction mergeRoleMarkers(\n  slice: GrammarProfileSlice,\n  vocab: DomainVocabulary\n): Record<string, MergedRoleMarker> {\n  const merged: Record<string, MergedRoleMarker> = {};\n  const add = (role: string, marker: RoleMarkerSlice | undefined) => {\n    if (!marker?.primary) {\n      delete merged[role];\n      return;\n    }\n    merged[role] = {\n      primary: marker.primary,\n      ...(marker.alternatives?.length && { alternatives: [...marker.alternatives] }),\n      ...(marker.position && { position: marker.position }),\n    };\n  };\n  for (const [role, marker] of Object.entries(slice.roleMarkers ?? {})) add(role, marker);\n  for (const [role, marker] of Object.entries(vocab.roleMarkerOverrides ?? {})) add(role, marker);\n  return merged;\n}\n\n/**\n * Build a pattern-generation profile: domain keywords + slice grammar\n * (word order, role markers). The result feeds `LanguageConfig.patternProfile`\n * and the schema renderer.\n */\nexport function buildPatternProfile(\n  slice: GrammarProfileSlice,\n  vocab: DomainVocabulary\n): PatternGenLanguageProfile {\n  const keywords: Record<string, { primary: string; alternatives?: string[] }> = {};\n  for (const [action, translation] of Object.entries(vocab.keywords)) {\n    keywords[action] = {\n      primary: translation.primary,\n      ...(translation.alternatives?.length && { alternatives: [...translation.alternatives] }),\n    };\n  }\n\n  const roleMarkers = mergeRoleMarkers(slice, vocab);\n\n  return {\n    code: slice.code,\n    wordOrder: slice.wordOrder,\n    keywords,\n    ...(Object.keys(roleMarkers).length > 0 && { roleMarkers }),\n  };\n}\n\n/** Options for {@link buildDomainTokenizer}, overriding the slice-derived defaults. */\nexport interface DomainTokenizerOptions {\n  /**\n   * Recognize operator tokens (default: false, matching `createSimpleTokenizer`).\n   * Domains whose grammar contains operators (e.g. SQL's `WHERE age > 18`) pass\n   * `true`; most natural-language DSLs leave it off.\n   */\n  readonly includeOperators?: boolean;\n  /**\n   * Case-insensitive keyword matching. Defaults to true for bicameral scripts\n   * (`latin`, `cyrillic`, or when the slice omits `script`), false otherwise.\n   */\n  readonly caseInsensitive?: boolean;\n  /** Extra extractors, registered before the slice-derived ones */\n  readonly customExtractors?: readonly ValueExtractor[];\n}\n\nfunction defaultCaseInsensitive(script: string | undefined): boolean {\n  return script === undefined || script === 'latin' || script === 'cyrillic';\n}\n\n/**\n * Build a domain tokenizer from a grammar slice + domain vocabulary, wrapping\n * `createSimpleTokenizer`. Derived from the slice:\n *\n * - `direction` (rtl for e.g. Arabic/Hebrew slices)\n * - keyword set: vocabulary verbs (primary + alternatives), role markers\n *   (slice defaults merged with `vocab.roleMarkerOverrides`), tokenization\n *   particles, and `vocab.tokenizerKeywords`\n * - keyword-normalization profile (native verb → action name, marker → role)\n * - a `LatinExtendedIdentifierExtractor` when `slice.script === 'latin'`, so\n *   diacritics (ñ, é, ş, …) never split identifiers\n * - case-insensitivity for bicameral scripts\n */\nexport function buildDomainTokenizer(\n  slice: GrammarProfileSlice,\n  vocab: DomainVocabulary,\n  options: DomainTokenizerOptions = {}\n): LanguageTokenizer {\n  const roleMarkers = mergeRoleMarkers(slice, vocab);\n\n  // Flat keyword list for token classification.\n  const keywords = new Set<string>();\n  for (const translation of Object.values(vocab.keywords)) {\n    keywords.add(translation.primary);\n    for (const alt of translation.alternatives ?? []) keywords.add(alt);\n  }\n  for (const marker of Object.values(roleMarkers)) {\n    keywords.add(marker.primary);\n    for (const alt of marker.alternatives ?? []) keywords.add(alt);\n  }\n  for (const particle of slice.tokenization?.particles ?? []) keywords.add(particle);\n  for (const extra of vocab.tokenizerKeywords ?? []) keywords.add(extra);\n\n  // Normalization profile: native verb forms → action names, markers → roles.\n  const profileKeywords: NonNullable<TokenizerProfile['keywords']> = {};\n  for (const [action, translation] of Object.entries(vocab.keywords)) {\n    profileKeywords[action] = {\n      primary: translation.primary,\n      ...(translation.alternatives?.length && { alternatives: [...translation.alternatives] }),\n      normalized: translation.normalized ?? action,\n    };\n  }\n  const keywordProfile: TokenizerProfile = {\n    keywords: profileKeywords,\n    ...(Object.keys(roleMarkers).length > 0 && { roleMarkers }),\n  };\n\n  const customExtractors: ValueExtractor[] = [\n    ...(options.customExtractors ?? []),\n    ...(slice.script === 'latin' ? [new LatinExtendedIdentifierExtractor()] : []),\n  ];\n\n  return createSimpleTokenizer({\n    language: slice.code,\n    direction: slice.direction ?? 'ltr',\n    keywords: [...keywords],\n    ...(vocab.keywordExtras?.length && { keywordExtras: vocab.keywordExtras.map(e => ({ ...e })) }),\n    keywordProfile,\n    includeOperators: options.includeOperators ?? false,\n    caseInsensitive: options.caseInsensitive ?? defaultCaseInsensitive(slice.script),\n    ...(customExtractors.length > 0 && { customExtractors }),\n  });\n}\n\n/** Metadata / overrides for {@link buildLanguageConfig}. */\nexport interface LanguageConfigMeta {\n  /** English name (default: `slice.name`, falling back to `slice.code`) */\n  readonly name?: string;\n  /** Native name (default: `slice.nativeName`, falling back to the English name) */\n  readonly nativeName?: string;\n  /** Grammar-transformation profile to attach (optional, as on `LanguageConfig`) */\n  readonly grammarProfile?: GrammarProfile;\n  /** Use this tokenizer instead of the slice-derived one */\n  readonly tokenizer?: LanguageTokenizer;\n  /** Options for the slice-derived tokenizer (ignored when `tokenizer` is given) */\n  readonly tokenizerOptions?: DomainTokenizerOptions;\n}\n\n/**\n * The one-call path into `createMultilingualDSL`: build a complete\n * `LanguageConfig` (tokenizer + pattern profile + names) from a grammar slice\n * and a domain vocabulary.\n */\nexport function buildLanguageConfig(\n  slice: GrammarProfileSlice,\n  vocab: DomainVocabulary,\n  meta: LanguageConfigMeta = {}\n): LanguageConfig {\n  const name = meta.name ?? slice.name ?? slice.code;\n  return {\n    code: slice.code,\n    name,\n    nativeName: meta.nativeName ?? slice.nativeName ?? name,\n    tokenizer: meta.tokenizer ?? buildDomainTokenizer(slice, vocab, meta.tokenizerOptions),\n    patternProfile: buildPatternProfile(slice, vocab),\n    ...(meta.grammarProfile && { grammarProfile: meta.grammarProfile }),\n  };\n}\n\n/**\n * Derive schema `markerOverride` defaults for ONE language from the slice's\n * role markers, given a domain-role → semantic-role mapping. Returns\n * `{ domainRole: primaryMarker }` with entries only where the slice has a\n * marker for the mapped semantic role.\n *\n * ```ts\n * deriveRoleMarkers(jaSlice, { table: 'source', target: 'destination' });\n * // → { table: 'から', target: 'に' }\n * ```\n *\n * Explicitly authored `markerOverride` entries stay authoritative — when\n * assembling a per-language marker map for a schema role, spread the explicit\n * entries after the derived defaults.\n */\nexport function deriveRoleMarkers(\n  slice: GrammarProfileSlice,\n  roleMapping: Readonly<Record<string, string>>\n): Record<string, string> {\n  const derived: Record<string, string> = {};\n  for (const [domainRole, semanticRole] of Object.entries(roleMapping)) {\n    const marker = slice.roleMarkers?.[semanticRole];\n    if (marker?.primary) derived[domainRole] = marker.primary;\n  }\n  return derived;\n}\n","/**\n * Character Classifiers\n *\n * Unicode range classification and Latin character classifier factories.\n * Used by language-specific tokenizers to define character sets.\n */\n\n// =============================================================================\n// Unicode Range Classification\n// =============================================================================\n\n/**\n * Unicode range tuple: [start, end] (inclusive).\n */\nexport type UnicodeRange = readonly [number, number];\n\n/**\n * Create a character classifier for Unicode ranges.\n * Returns a function that checks if a character's code point falls within any of the ranges.\n *\n * @example\n * // Japanese Hiragana\n * const isHiragana = createUnicodeRangeClassifier([[0x3040, 0x309f]]);\n *\n * // Korean (Hangul syllables + Jamo)\n * const isKorean = createUnicodeRangeClassifier([\n *   [0xac00, 0xd7a3],  // Hangul syllables\n *   [0x1100, 0x11ff],  // Hangul Jamo\n *   [0x3130, 0x318f],  // Hangul Compatibility Jamo\n * ]);\n */\nexport function createUnicodeRangeClassifier(\n  ranges: readonly UnicodeRange[]\n): (char: string) => boolean {\n  return (char: string): boolean => {\n    const code = char.charCodeAt(0);\n    return ranges.some(([start, end]) => code >= start && code <= end);\n  };\n}\n\n/**\n * Combine multiple character classifiers into one.\n * Returns true if any of the classifiers return true.\n *\n * @example\n * const isJapanese = combineClassifiers(isHiragana, isKatakana, isKanji);\n */\nexport function combineClassifiers(\n  ...classifiers: Array<(char: string) => boolean>\n): (char: string) => boolean {\n  return (char: string): boolean => classifiers.some(fn => fn(char));\n}\n\n/**\n * Character classifiers for a Latin-based language.\n */\nexport interface LatinCharClassifiers {\n  /** Check if character is a letter in this language (including accented chars). */\n  isLetter: (char: string) => boolean;\n  /** Check if character is part of an identifier (letter, digit, underscore, hyphen). */\n  isIdentifierChar: (char: string) => boolean;\n}\n\n/**\n * Create character classifiers for a Latin-based language.\n * Returns isLetter and isIdentifierChar functions based on the provided regex.\n *\n * @example\n * // Spanish letters\n * const { isLetter, isIdentifierChar } = createLatinCharClassifiers(/[a-zA-Z\\u00e1\\u00e9\\u00ed\\u00f3\\u00fa\\u00fc\\u00f1\\u00c1\\u00c9\\u00cd\\u00d3\\u00da\\u00dc\\u00d1]/);\n *\n * // German letters\n * const { isLetter, isIdentifierChar } = createLatinCharClassifiers(/[a-zA-Z\\u00e4\\u00f6\\u00fc\\u00c4\\u00d6\\u00dc\\u00df]/);\n */\nexport function createLatinCharClassifiers(letterPattern: RegExp): LatinCharClassifiers {\n  const isLetter = (char: string): boolean => letterPattern.test(char);\n  const isIdentifierChar = (char: string): boolean => isLetter(char) || /[0-9_-]/.test(char);\n  return { isLetter, isIdentifierChar };\n}\n","/**\n * Morphological Normalizer Types\n *\n * Defines interfaces for language-specific morphological analysis.\n * Normalizers reduce conjugated/inflected forms to canonical stems\n * that can be matched against keyword dictionaries.\n */\n\n/**\n * Result of morphological normalization.\n */\nexport interface NormalizationResult {\n  /** The extracted stem/root form */\n  readonly stem: string;\n\n  /** Confidence in the normalization (0.0-1.0) */\n  readonly confidence: number;\n\n  /** Optional metadata about the transformation */\n  readonly metadata?: NormalizationMetadata;\n}\n\n/**\n * Metadata about morphological transformations applied.\n */\nexport interface NormalizationMetadata {\n  /** Prefixes that were removed */\n  readonly removedPrefixes?: readonly string[];\n\n  /** Suffixes that were removed */\n  readonly removedSuffixes?: readonly string[];\n\n  /** Type of conjugation detected */\n  readonly conjugationType?: ConjugationType;\n\n  /** Original form classification */\n  readonly originalForm?: string;\n\n  /** Applied transformation rules (for debugging) */\n  readonly appliedRules?: readonly string[];\n}\n\n/**\n * Types of verb conjugation/inflection.\n */\nexport type ConjugationType =\n  // Tense\n  | 'present'\n  | 'past'\n  | 'future'\n  | 'progressive'\n  | 'perfect'\n  // Mood\n  | 'imperative'\n  | 'subjunctive'\n  | 'conditional'\n  // Voice\n  | 'passive'\n  | 'causative'\n  // Politeness (Japanese/Korean)\n  | 'polite'\n  | 'humble'\n  | 'honorific'\n  // Form\n  | 'negative'\n  | 'potential'\n  | 'volitional'\n  // Japanese conditional forms\n  | 'conditional-tara' // たら/したら - if/when (completed action)\n  | 'conditional-to' // と/すると - when (habitual/expected)\n  | 'conditional-ba' // ば/すれば - if (hypothetical)\n  // Korean-specific\n  | 'connective' // 하고, 해서 etc.\n  | 'conditional-myeon' // -(으)면 - if/when (general conditional)\n  | 'temporal-ttae' // -(으)ㄹ 때 - when (at the time of)\n  | 'causal-nikka' // -(으)니까 - because/since\n  // Korean honorific forms (-시- infix)\n  | 'honorific-conditional' // -하시면 - if (honorific)\n  | 'honorific-temporal' // -하실 때 - when (honorific)\n  | 'honorific-causal' // -하시니까 - because (honorific)\n  | 'honorific-past' // -하셨어요 - past (honorific)\n  | 'honorific-polite' // -하십니다 - polite (honorific)\n  // Korean sequential forms\n  | 'sequential-after' // -고 나서 - after doing\n  | 'sequential-before' // -기 전에 - before doing\n  | 'immediate' // -자마자 - as soon as\n  | 'obligation' // -아야/어야 해 - must do, should do\n  // Spanish-specific\n  | 'reflexive'\n  | 'reflexive-imperative'\n  | 'gerund'\n  | 'participle'\n  // Arabic-specific\n  | 'conditional-idha' // إذا - if/when (hypothetical)\n  | 'temporal-indama' // عندما - when (temporal conjunction)\n  | 'temporal-hina' // حين - at the time of\n  | 'temporal-lamma' // لمّا - when (past emphasis)\n  | 'past-verb' // فعل ماضي - past tense verb\n  // Turkish-specific\n  | 'conditional-se' // -se/-sa - if (hypothetical)\n  | 'temporal-ince' // -ince/-ınca/-unca/-ünce - when/as\n  | 'temporal-dikce' // -dikçe/-dıkça/-dukça/-dükçe - as/while\n  | 'aorist' // -ir/-ar - habitual/general\n  | 'optative' // -eyim/-ayım/-elim/-alım - let me/us\n  | 'necessitative' // -meli/-malı - must/should\n  // Japanese request/contracted forms\n  | 'request' // てください/でください - polite request\n  | 'casual-request' // てくれ/でくれ - casual request\n  | 'contracted' // ちゃう/じゃう - contracted completion (てしまう)\n  | 'contracted-past' // ちゃった/じゃった - contracted past completion\n  // Compound\n  | 'compound' // Multi-layer suffixes (ていなかった, 하고나서였어)\n  | 'te-form' // Japanese て-form\n  | 'dictionary'; // Base/infinitive form\n\n/**\n * Interface for language-specific morphological normalizers.\n *\n * Normalizers attempt to reduce inflected word forms to their\n * canonical stems. This enables matching conjugated verbs against\n * keyword dictionaries that only contain base forms.\n *\n * Example (Japanese):\n *   切り替えた (past) → { stem: '切り替え', confidence: 0.85 }\n *   切り替えます (polite) → { stem: '切り替え', confidence: 0.85 }\n *\n * Example (Spanish):\n *   mostrarse (reflexive infinitive) → { stem: 'mostrar', confidence: 0.85 }\n *   alternando (gerund) → { stem: 'alternar', confidence: 0.85 }\n */\nexport interface MorphologicalNormalizer {\n  /** Language code this normalizer handles */\n  readonly language: string;\n\n  /**\n   * Normalize a word to its canonical stem form.\n   *\n   * @param word - The word to normalize\n   * @returns Normalization result with stem and confidence\n   */\n  normalize(word: string): NormalizationResult;\n\n  /**\n   * Check if a word appears to be a verb form that can be normalized.\n   * Optional optimization to skip normalization for non-verb tokens.\n   *\n   * @param word - The word to check\n   * @returns true if the word might be a normalizable verb form\n   */\n  isNormalizable?(word: string): boolean;\n}\n\n/**\n * Configuration for suffix-based normalization rules.\n * Used by agglutinative languages (Japanese, Korean, Turkish).\n */\nexport interface SuffixRule {\n  /** The suffix pattern to match */\n  readonly pattern: string;\n\n  /** Confidence when this suffix is stripped */\n  readonly confidence: number;\n\n  /** What to replace the suffix with (empty string for simple removal) */\n  readonly replacement?: string;\n\n  /** Conjugation type this suffix indicates */\n  readonly conjugationType?: ConjugationType;\n\n  /** Minimum stem length after stripping (to avoid over-stripping) */\n  readonly minStemLength?: number;\n}\n\n/**\n * Configuration for prefix-based normalization rules.\n * Used primarily by Arabic for article/conjunction prefixes.\n */\nexport interface PrefixRule {\n  /** The prefix pattern to match */\n  readonly pattern: string;\n\n  /** Confidence penalty when this prefix is stripped */\n  readonly confidencePenalty: number;\n\n  /** What the prefix indicates (for metadata) */\n  readonly prefixType?: 'article' | 'conjunction' | 'preposition' | 'verb-marker';\n\n  /** Minimum remaining characters after stripping (to avoid over-stripping) */\n  readonly minRemaining?: number;\n}\n\n/**\n * Helper to create a \"no change\" normalization result.\n */\nexport function noChange(word: string): NormalizationResult {\n  return { stem: word, confidence: 1.0 };\n}\n\n/**\n * Helper to create a normalization result with metadata.\n */\nexport function normalized(\n  stem: string,\n  confidence: number,\n  metadata?: NormalizationMetadata\n): NormalizationResult {\n  if (metadata) {\n    return { stem, confidence, metadata };\n  }\n  return { stem, confidence };\n}\n","/**\n * BaseMorphologicalNormalizer — Shared base class for language normalizers.\n *\n * Provides the common suffix/prefix stripping loop, reflexive verb handling,\n * and normalize() pipeline. Language-specific normalizers extend this class\n * and provide their conjugation rules.\n *\n * Phase 3.1 of parser-ecosystem-plan-v3.\n */\n\nimport type {\n  MorphologicalNormalizer,\n  NormalizationResult,\n  ConjugationType,\n  SuffixRule,\n  PrefixRule,\n} from './types';\nimport { noChange, normalized } from './types';\n\n/**\n * Conjugation ending rule for verb classes (Romance languages etc.)\n * Broader than SuffixRule — includes the replacement stem (e.g., strip -ando, add -ar).\n */\nexport interface ConjugationEnding {\n  readonly ending: string;\n  readonly stem: string;\n  readonly confidence: number;\n  readonly type: ConjugationType;\n}\n\n/**\n * Configuration for BaseMorphologicalNormalizer.\n * Subclasses provide this in their constructor.\n */\nexport interface NormalizerConfig {\n  /** Language code */\n  readonly language: string;\n\n  /** Minimum word length to attempt normalization */\n  readonly minWordLength?: number;\n\n  /** Minimum stem length after stripping (default: 2) */\n  readonly minStemLength?: number;\n\n  /** Conjugation endings sorted longest-first */\n  readonly endings?: readonly ConjugationEnding[];\n\n  /** Suffix rules (for SuffixRule-style normalizers) */\n  readonly suffixRules?: readonly SuffixRule[];\n\n  /** Prefix rules */\n  readonly prefixRules?: readonly PrefixRule[];\n\n  /** Reflexive suffixes (for Romance languages) */\n  readonly reflexiveSuffixes?: readonly string[];\n\n  /** Infinitive endings (for checking if already normalized) */\n  readonly infinitiveEndings?: readonly string[];\n}\n\n/**\n * Abstract base class for morphological normalizers.\n *\n * Subclasses must implement `isNormalizable()` and can override any\n * normalization step. The default `normalize()` pipeline is:\n *\n * 1. Check if already in dictionary form → noChange\n * 2. Try reflexive normalization (if reflexiveSuffixes configured)\n * 3. Try conjugation endings (if endings configured)\n * 4. Try suffix rules (if suffixRules configured)\n * 5. Try prefix rules (if prefixRules configured)\n * 6. Return noChange\n */\nexport abstract class BaseMorphologicalNormalizer implements MorphologicalNormalizer {\n  readonly language: string;\n  protected readonly config: NormalizerConfig;\n\n  constructor(config: NormalizerConfig) {\n    this.language = config.language;\n    this.config = {\n      minWordLength: 3,\n      minStemLength: 2,\n      ...config,\n    };\n  }\n\n  /**\n   * Check if a word can be normalized. Subclasses must implement this\n   * with language-specific script/character detection.\n   */\n  abstract isNormalizable(word: string): boolean;\n\n  /**\n   * Standard normalization pipeline. Override for custom behavior.\n   */\n  normalize(word: string): NormalizationResult {\n    const lower = word.toLowerCase();\n\n    // Check if already in dictionary form\n    if (this.isAlreadyNormalized(lower)) {\n      return noChange(word);\n    }\n\n    // Try reflexive normalization (Romance languages)\n    if (this.config.reflexiveSuffixes) {\n      const reflexive = this.tryReflexiveNormalization(lower);\n      if (reflexive) return reflexive;\n    }\n\n    // Try conjugation endings\n    if (this.config.endings) {\n      const conjugation = this.tryConjugationEndings(lower);\n      if (conjugation) return conjugation;\n    }\n\n    // Try suffix rules\n    if (this.config.suffixRules) {\n      const suffix = this.trySuffixRules(lower);\n      if (suffix) return suffix;\n    }\n\n    // Try prefix rules\n    if (this.config.prefixRules) {\n      const prefix = this.tryPrefixRules(lower);\n      if (prefix) return prefix;\n    }\n\n    return noChange(word);\n  }\n\n  /**\n   * Check if word is already in dictionary form (e.g., ends in -ar/-er/-ir).\n   * Override for language-specific checks.\n   */\n  protected isAlreadyNormalized(word: string): boolean {\n    if (this.config.infinitiveEndings) {\n      return this.config.infinitiveEndings.some(e => word.endsWith(e));\n    }\n    return false;\n  }\n\n  /**\n   * Try to strip reflexive suffixes and normalize the remainder.\n   * Common in Romance languages (Spanish, Portuguese, French).\n   */\n  protected tryReflexiveNormalization(word: string): NormalizationResult | null {\n    const suffixes = this.config.reflexiveSuffixes;\n    if (!suffixes) return null;\n\n    for (const suffix of suffixes) {\n      if (!word.endsWith(suffix)) continue;\n      const remainder = word.slice(0, -suffix.length);\n\n      // Check if remainder is already an infinitive\n      if (this.isAlreadyNormalized(remainder)) {\n        return normalized(remainder, 0.88, {\n          removedSuffixes: [suffix],\n          conjugationType: 'reflexive',\n        });\n      }\n\n      // Try to normalize the remainder\n      const inner = this.tryConjugationEndings(remainder) || this.trySuffixRules(remainder);\n      if (inner && inner.stem !== remainder) {\n        return normalized(inner.stem, inner.confidence * 0.95, {\n          removedSuffixes: [suffix, ...(inner.metadata?.removedSuffixes || [])],\n          conjugationType: 'reflexive',\n        });\n      }\n    }\n\n    return null;\n  }\n\n  /**\n   * Try conjugation endings (verb class endings like -ar/-er/-ir patterns).\n   * Endings must be pre-sorted longest-first.\n   */\n  protected tryConjugationEndings(word: string): NormalizationResult | null {\n    const endings = this.config.endings;\n    if (!endings) return null;\n\n    const minStem = this.config.minStemLength ?? 2;\n\n    for (const rule of endings) {\n      if (!word.endsWith(rule.ending)) continue;\n\n      const stemBase = word.slice(0, -rule.ending.length);\n      if (stemBase.length < minStem) continue;\n\n      const infinitive = stemBase + rule.stem;\n      return normalized(infinitive, rule.confidence, {\n        removedSuffixes: [rule.ending],\n        conjugationType: rule.type,\n      });\n    }\n\n    return null;\n  }\n\n  /**\n   * Try SuffixRule-style normalization.\n   * Rules must be pre-sorted longest-first.\n   */\n  protected trySuffixRules(word: string): NormalizationResult | null {\n    const rules = this.config.suffixRules;\n    if (!rules) return null;\n\n    const defaultMinStem = this.config.minStemLength ?? 2;\n\n    for (const rule of rules) {\n      if (!word.endsWith(rule.pattern)) continue;\n\n      const stem = word.slice(0, -rule.pattern.length);\n      const minStem = rule.minStemLength ?? defaultMinStem;\n      if (stem.length < minStem) continue;\n\n      const result = stem + (rule.replacement || '');\n      return normalized(result, rule.confidence, {\n        removedSuffixes: [rule.pattern],\n        ...(rule.conjugationType && { conjugationType: rule.conjugationType }),\n      });\n    }\n\n    return null;\n  }\n\n  /**\n   * Try PrefixRule-style normalization.\n   */\n  protected tryPrefixRules(word: string): NormalizationResult | null {\n    const rules = this.config.prefixRules;\n    if (!rules) return null;\n\n    for (const rule of rules) {\n      if (!word.startsWith(rule.pattern)) continue;\n\n      const remainder = word.slice(rule.pattern.length);\n      const minRemaining = rule.minRemaining ?? this.config.minStemLength ?? 2;\n      if (remainder.length < minRemaining) continue;\n\n      return normalized(remainder, 1.0 - rule.confidencePenalty, {\n        removedPrefixes: [rule.pattern],\n      });\n    }\n\n    return null;\n  }\n}\n","/**\n * JSONL Writer\n *\n * Exports training pairs in JSONL (JSON Lines) format,\n * compatible with standard fine-tuning pipelines.\n */\n\nimport type { TrainingPair } from './types';\n\n/**\n * Convert training pairs to JSONL format (one JSON object per line).\n *\n * Each line contains:\n * - id: unique pair identifier\n * - prompt: the natural language input\n * - completion: the LSE bracket syntax output\n * - metadata: domain, action, language, source, quality\n */\nexport function toJSONL(pairs: readonly TrainingPair[]): string {\n  return pairs.map(pair => JSON.stringify(toJSONLRow(pair))).join('\\n');\n}\n\n/**\n * Convert a single training pair to a JSONL row.\n */\nexport function toJSONLRow(pair: TrainingPair): JSONLRow {\n  return {\n    id: pair.id,\n    prompt: pair.natural,\n    completion: pair.explicit,\n    metadata: {\n      domain: pair.domain,\n      action: pair.action,\n      language: pair.language,\n      source: pair.source,\n      quality: pair.quality,\n      ...(pair.confidence !== undefined && { confidence: pair.confidence }),\n    },\n  };\n}\n\n/**\n * Parse JSONL back into rows (for validation/roundtrip testing).\n */\nexport function parseJSONL(text: string): JSONLRow[] {\n  return text\n    .split('\\n')\n    .filter(line => line.trim().length > 0)\n    .map(line => JSON.parse(line) as JSONLRow);\n}\n\n/**\n * A single row in JSONL format.\n */\nexport interface JSONLRow {\n  readonly id: string;\n  readonly prompt: string;\n  readonly completion: string;\n  readonly metadata: {\n    readonly domain: string;\n    readonly action: string;\n    readonly language: string;\n    readonly source: string;\n    readonly quality: number;\n    readonly confidence?: number;\n  };\n}\n","/**\n * Confidence-Aware Disambiguation\n *\n * When parse confidence is borderline (between low and high thresholds),\n * generates a disambiguation request with alternative interpretations\n * instead of blindly accepting or rejecting.\n */\n\nimport type { SemanticNode } from '../core/types';\nimport { renderExplicit } from '../ir/explicit-renderer';\nimport type { DisambiguationRequest, DisambiguationCandidate } from './types';\n\n// =============================================================================\n// Public API\n// =============================================================================\n\n/**\n * Check whether a confidence score falls in the disambiguation range.\n *\n * @returns true if the confidence is ambiguous (between low and high thresholds)\n */\nexport function needsDisambiguation(\n  confidence: number,\n  low: number = 0.5,\n  high: number = 0.7\n): boolean {\n  return confidence >= low && confidence < high;\n}\n\n/**\n * Build a disambiguation request from candidate interpretations.\n *\n * @param input - The original ambiguous input\n * @param candidates - Alternative interpretations with confidence scores\n */\nexport function buildDisambiguation(\n  input: string,\n  candidates: ReadonlyArray<{\n    action: string;\n    confidence: number;\n    node: SemanticNode;\n    description?: string;\n  }>\n): DisambiguationRequest {\n  const sortedCandidates = [...candidates].sort((a, b) => b.confidence - a.confidence);\n\n  const disambiguationCandidates: DisambiguationCandidate[] = sortedCandidates.map((c, i) => ({\n    action: c.action,\n    confidence: c.confidence,\n    explicit: renderExplicit(c.node),\n    description: c.description || `${c.action} (option ${String.fromCharCode(97 + i)})`,\n  }));\n\n  const optionLines = disambiguationCandidates.map(\n    (c, i) =>\n      `  (${String.fromCharCode(97 + i)}) ${c.explicit} — ${c.description} (conf: ${c.confidence.toFixed(2)})`\n  );\n\n  const question = [\n    `Your input parsed with confidence ${sortedCandidates[0]?.confidence.toFixed(2) ?? '?'}.`,\n    ...optionLines,\n    'Which did you mean?',\n  ].join('\\n');\n\n  return {\n    input,\n    candidates: disambiguationCandidates,\n    question,\n  };\n}\n","/**\n * Pattern Hit-Rate Tracker\n *\n * Records pattern events in a ring buffer and computes hit-rate\n * statistics by command, language, and diagnostic code. Patterns\n * with high rejected/attempts ratios indicate miscalibrated confidence.\n */\n\nimport type { PatternEvent, HitRate, PatternTrackerSummary, TopFailure } from './types';\n\n// =============================================================================\n// Public API\n// =============================================================================\n\nexport class PatternTracker {\n  private events: PatternEvent[] = [];\n  private readonly maxEvents: number;\n\n  constructor(maxEvents: number = 1000) {\n    this.maxEvents = maxEvents;\n  }\n\n  /**\n   * Record a pattern event.\n   */\n  record(event: PatternEvent): void {\n    this.events.push(event);\n    // Ring buffer: drop oldest when full\n    if (this.events.length > this.maxEvents) {\n      this.events = this.events.slice(this.events.length - this.maxEvents);\n    }\n  }\n\n  /**\n   * Get hit rate by command action.\n   */\n  getHitRateByCommand(): Record<string, HitRate> {\n    return this.computeHitRate(e => e.action);\n  }\n\n  /**\n   * Get hit rate by language.\n   */\n  getHitRateByLanguage(): Record<string, HitRate> {\n    return this.computeHitRate(e => e.language);\n  }\n\n  /**\n   * Get the most frequent failure diagnostic codes.\n   */\n  getTopFailures(limit: number = 10): TopFailure[] {\n    const codeMap = new Map<string, { count: number; actions: Set<string> }>();\n\n    for (const event of this.events) {\n      if (event.outcome !== 'rejected' || !event.diagnosticCodes) continue;\n      for (const code of event.diagnosticCodes) {\n        const entry = codeMap.get(code) || { count: 0, actions: new Set() };\n        entry.count++;\n        entry.actions.add(event.action);\n        codeMap.set(code, entry);\n      }\n    }\n\n    return Array.from(codeMap.entries())\n      .map(([code, { count, actions }]) => ({\n        code,\n        count,\n        actions: Array.from(actions),\n      }))\n      .sort((a, b) => b.count - a.count)\n      .slice(0, limit);\n  }\n\n  /**\n   * Get a complete summary of tracking data.\n   */\n  getSummary(): PatternTrackerSummary {\n    const byOutcome: Record<string, number> = {};\n    for (const event of this.events) {\n      byOutcome[event.outcome] = (byOutcome[event.outcome] || 0) + 1;\n    }\n\n    return {\n      totalEvents: this.events.length,\n      byOutcome,\n      byCommand: this.getHitRateByCommand(),\n      byLanguage: this.getHitRateByLanguage(),\n      topFailures: this.getTopFailures(),\n    };\n  }\n\n  /**\n   * Export all events as JSONL.\n   */\n  exportJSONL(): string {\n    return this.events.map(e => JSON.stringify(e)).join('\\n');\n  }\n\n  /**\n   * Get the number of recorded events.\n   */\n  get size(): number {\n    return this.events.length;\n  }\n\n  /**\n   * Clear all events.\n   */\n  clear(): void {\n    this.events = [];\n  }\n\n  // ---------------------------------------------------------------------------\n  // Private\n  // ---------------------------------------------------------------------------\n\n  private computeHitRate(keyFn: (e: PatternEvent) => string): Record<string, HitRate> {\n    const map = new Map<string, { attempts: number; successes: number }>();\n\n    for (const event of this.events) {\n      const key = keyFn(event);\n      const entry = map.get(key) || { attempts: 0, successes: 0 };\n      entry.attempts++;\n      if (event.outcome === 'accepted') {\n        entry.successes++;\n      }\n      map.set(key, entry);\n    }\n\n    const result: Record<string, HitRate> = {};\n    for (const [key, { attempts, successes }] of map) {\n      result[key] = {\n        attempts,\n        successes,\n        rate: attempts > 0 ? successes / attempts : 0,\n      };\n    }\n    return result;\n  }\n}\n","/**\n * Multi-statement parser for domain DSLs.\n *\n * Provides generic mechanics for parsing multi-line/multi-statement DSL input:\n * - Statement splitting (line-based or delimiter-based)\n * - Keyword classification (SVO start / SOV end detection)\n * - Block accumulation (grouping lines into blocks)\n * - Error collection with line numbers\n *\n * Domains provide the semantics (what keywords mean, preprocessing, hierarchy).\n * The framework provides the mechanics.\n */\n\nimport type { SemanticNode } from '../core/types';\nimport type { MultilingualDSL } from '../api/create-dsl';\n\n// =============================================================================\n// Configuration Types\n// =============================================================================\n\n/**\n * Word order affects keyword detection position.\n */\nexport type WordOrderHint = 'SVO' | 'SOV' | 'VSO';\n\n/**\n * How to split input into individual statements.\n */\nexport interface SplitConfig {\n  /**\n   * Split mode:\n   * - 'line': split on newlines (for indentation-based DSLs)\n   * - 'delimiter': split on language-specific delimiters\n   */\n  readonly mode: 'line' | 'delimiter';\n\n  /**\n   * Language-specific delimiter patterns (used when mode='delimiter').\n   * Key is language code, value is regex pattern.\n   * Example: { en: /,\\s*|\\n\\s*‍/, ja: /、|。|\\n\\s*‍/ }\n   */\n  readonly delimiters?: Readonly<Record<string, RegExp>>;\n\n  /**\n   * Default delimiter when language not in delimiters map.\n   */\n  readonly defaultDelimiter?: RegExp;\n\n  /**\n   * Whether to trim each statement after splitting.\n   * Default: true\n   */\n  readonly trim?: boolean;\n\n  /**\n   * Comment prefixes to strip. Lines starting with these are skipped.\n   * Default: ['--', '//']\n   */\n  readonly commentPrefixes?: readonly string[];\n}\n\n/**\n * A keyword category with its translations.\n * Maps language code to array of keyword variants.\n */\nexport type KeywordMap = Readonly<Record<string, readonly string[]>>;\n\n/**\n * Configuration for keyword classification.\n */\nexport interface KeywordConfig {\n  /**\n   * Named keyword categories with their per-language translations.\n   * Example: { test: { en: ['test'], ja: ['テスト'], es: ['prueba'] } }\n   */\n  readonly categories: Readonly<Record<string, KeywordMap>>;\n\n  /**\n   * Word order hint per language (affects where keywords are detected).\n   * Default for unlisted languages: 'SVO'\n   */\n  readonly wordOrders?: Readonly<Record<string, WordOrderHint>>;\n}\n\n/**\n * Configuration for continuation resolution (e.g., BDD's \"and\" keyword).\n */\nexport interface ContinuationConfig {\n  /**\n   * The keyword(s) that signal continuation, per language.\n   * Example: { en: ['and'], es: ['y'], ja: ['かつ'], ar: ['و'] }\n   */\n  readonly keywords: KeywordMap;\n\n  /**\n   * How to resolve continuation: re-prefix with previous step's keyword.\n   * The function receives (content after 'and', previous step's category, language)\n   * and returns the re-prefixed string for re-parsing.\n   *\n   * Default: `(content, prevCategory, language, categoryKeywords) =>\n   *   categoryKeywords[prevCategory]?.[language]?.[0] + ' ' + content`\n   */\n  readonly resolve?: (\n    content: string,\n    prevCategory: string,\n    language: string,\n    categoryKeywords: Record<string, KeywordMap>\n  ) => string;\n}\n\n/**\n * A parsed statement with its line context.\n */\nexport interface ParsedStatement {\n  /** The parsed semantic node */\n  readonly node: SemanticNode;\n  /** Original source line/text */\n  readonly source: string;\n  /** Line number (1-based) in original input */\n  readonly line: number;\n  /** Detected keyword category (e.g., 'test', 'given', 'when') */\n  readonly category?: string;\n  /** Indentation level (number of leading spaces, 0-based) */\n  readonly indent: number;\n}\n\n/**\n * A parse error with location information.\n */\nexport interface StatementError {\n  /** Error message */\n  readonly message: string;\n  /** Line number (1-based) in original input */\n  readonly line: number;\n  /** Original source line/text */\n  readonly source: string;\n  /** Error code for programmatic handling */\n  readonly code?: 'parse-error' | 'unexpected-line' | 'continuation-error';\n}\n\n/**\n * Result of multi-statement parsing.\n */\nexport interface MultiStatementResult {\n  /** Successfully parsed statements */\n  readonly statements: readonly ParsedStatement[];\n  /** Errors encountered during parsing */\n  readonly errors: readonly StatementError[];\n}\n\n/**\n * Preprocessor function called before each statement is parsed.\n * Returns the modified string to parse, or null to skip the line.\n */\nexport type StatementPreprocessor = (\n  line: string,\n  category: string | undefined,\n  language: string,\n  context: PreprocessorContext\n) => string | null;\n\n/**\n * Context available to preprocessors.\n */\nexport interface PreprocessorContext {\n  /** The previous parsed statement, if any */\n  readonly previous?: ParsedStatement;\n  /** Line number (1-based) */\n  readonly lineNumber: number;\n  /** Indentation level */\n  readonly indent: number;\n}\n\n/**\n * Full configuration for multi-statement parser.\n */\nexport interface MultiStatementConfig {\n  /** How to split input into statements */\n  readonly split: SplitConfig;\n  /** Keyword classification (optional — if omitted, no category detection) */\n  readonly keywords?: KeywordConfig;\n  /** Continuation resolution (optional — e.g., BDD 'and') */\n  readonly continuation?: ContinuationConfig;\n  /** Statement preprocessor (optional — for article stripping, expect-prepending, etc.) */\n  readonly preprocessor?: StatementPreprocessor;\n}\n\n// =============================================================================\n// Multi-Statement Parser\n// =============================================================================\n\n/**\n * A reusable multi-statement parser.\n * Created via `createMultiStatementParser()`.\n */\nexport interface MultiStatementParser {\n  /**\n   * Parse multi-statement input into an array of parsed statements.\n   */\n  parse(input: string, language: string): MultiStatementResult;\n}\n\n/**\n * Create a multi-statement parser that wraps a `MultilingualDSL` instance.\n *\n * The parser handles splitting, keyword detection, continuation resolution,\n * preprocessing, and error collection. It delegates single-statement parsing\n * to the provided DSL's `parse()` method.\n *\n * @example\n * ```typescript\n * const parser = createMultiStatementParser(myDSL, {\n *   split: { mode: 'line', commentPrefixes: ['--', '//'] },\n *   keywords: {\n *     categories: {\n *       given: { en: ['given'], ja: ['前提'], es: ['dado'] },\n *       when: { en: ['when'], ja: ['もし'], es: ['cuando'] },\n *       then: { en: ['then'], ja: ['ならば'], es: ['entonces'] },\n *     },\n *     wordOrders: { ja: 'SOV', ar: 'VSO' },\n *   },\n *   continuation: {\n *     keywords: { en: ['and'], es: ['y'], ja: ['かつ'] },\n *   },\n * });\n *\n * const result = parser.parse(`\n *   given #login is visible\n *   when click on #submit\n *   then #dashboard appears\n * `, 'en');\n * ```\n */\nexport function createMultiStatementParser(\n  dsl: MultilingualDSL,\n  config: MultiStatementConfig\n): MultiStatementParser {\n  return new MultiStatementParserImpl(dsl, config);\n}\n\n// =============================================================================\n// Implementation\n// =============================================================================\n\nclass MultiStatementParserImpl implements MultiStatementParser {\n  constructor(\n    private readonly dsl: MultilingualDSL,\n    private readonly config: MultiStatementConfig\n  ) {}\n\n  parse(input: string, language: string): MultiStatementResult {\n    const rawStatements = this.splitStatements(input, language);\n    const statements: ParsedStatement[] = [];\n    const errors: StatementError[] = [];\n    let previous: ParsedStatement | undefined;\n\n    for (const raw of rawStatements) {\n      // Detect keyword category\n      const category = this.classifyLine(raw.text, language);\n\n      // Handle continuation (e.g., 'and')\n      let textToParse = raw.text;\n      if (this.config.continuation) {\n        const resolved = this.resolveContinuation(raw.text, language, previous?.category);\n        if (resolved !== null) {\n          textToParse = resolved;\n        }\n      }\n\n      // Run preprocessor\n      if (this.config.preprocessor) {\n        const processed = this.config.preprocessor(textToParse, category, language, {\n          ...(previous != null && { previous }),\n          lineNumber: raw.line,\n          indent: raw.indent,\n        });\n        if (processed === null) continue; // skip line\n        textToParse = processed;\n      }\n\n      // Parse with DSL\n      try {\n        const node = this.dsl.parse(textToParse, language);\n        const stmt: ParsedStatement = {\n          node,\n          source: raw.text,\n          line: raw.line,\n          ...(category != null && { category }),\n          indent: raw.indent,\n        };\n        statements.push(stmt);\n        previous = stmt;\n      } catch (err) {\n        errors.push({\n          message: err instanceof Error ? err.message : String(err),\n          line: raw.line,\n          source: raw.text,\n          code: 'parse-error',\n        });\n      }\n    }\n\n    return { statements, errors };\n  }\n\n  /**\n   * Split input into raw statement lines with metadata.\n   */\n  private splitStatements(\n    input: string,\n    language: string\n  ): Array<{ text: string; line: number; indent: number }> {\n    const { mode, trim = true, commentPrefixes = ['--', '//'] } = this.config.split;\n\n    if (mode === 'delimiter') {\n      return this.splitByDelimiter(input, language, trim, commentPrefixes);\n    }\n\n    // Line-based splitting\n    const lines = input.split('\\n');\n    const result: Array<{ text: string; line: number; indent: number }> = [];\n\n    for (let i = 0; i < lines.length; i++) {\n      const raw = lines[i];\n      const indent = raw.length - raw.trimStart().length;\n      const text = trim ? raw.trim() : raw;\n\n      // Skip empty lines\n      if (!text) continue;\n\n      // Skip comments\n      if (commentPrefixes.some(p => text.startsWith(p))) continue;\n\n      result.push({ text, line: i + 1, indent });\n    }\n\n    return result;\n  }\n\n  /**\n   * Split by language-specific delimiters.\n   */\n  private splitByDelimiter(\n    input: string,\n    language: string,\n    trim: boolean,\n    commentPrefixes: readonly string[]\n  ): Array<{ text: string; line: number; indent: number }> {\n    const delimiter =\n      this.config.split.delimiters?.[language] ??\n      this.config.split.defaultDelimiter ??\n      /,\\s*|\\n\\s*/;\n\n    const parts = input.split(delimiter);\n    const result: Array<{ text: string; line: number; indent: number }> = [];\n\n    for (let i = 0; i < parts.length; i++) {\n      const raw = parts[i];\n      const text = trim ? raw.trim() : raw;\n\n      if (!text) continue;\n      if (commentPrefixes.some(p => text.startsWith(p))) continue;\n\n      result.push({ text, line: i + 1, indent: 0 });\n    }\n\n    return result;\n  }\n\n  /**\n   * Classify a line by its keyword category.\n   * Returns the category name or undefined if no match.\n   */\n  private classifyLine(line: string, language: string): string | undefined {\n    if (!this.config.keywords) return undefined;\n\n    const lower = line.toLowerCase();\n    const wordOrder = this.config.keywords.wordOrders?.[language] ?? 'SVO';\n\n    for (const [category, keywordMap] of Object.entries(this.config.keywords.categories)) {\n      const keywords = keywordMap[language] ?? keywordMap['en'] ?? [];\n      for (const kw of keywords) {\n        const kwLower = kw.toLowerCase();\n        if (wordOrder === 'SOV') {\n          // SOV: check end of line first, then start\n          if (lower.endsWith(kwLower) || lower.startsWith(kwLower)) {\n            return category;\n          }\n        } else {\n          // SVO/VSO: check start of line\n          if (lower.startsWith(kwLower)) {\n            return category;\n          }\n        }\n      }\n    }\n\n    return undefined;\n  }\n\n  /**\n   * Resolve continuation keywords (e.g., 'and' → re-prefix with previous step type).\n   * Returns the resolved string, or null if not a continuation.\n   */\n  private resolveContinuation(\n    text: string,\n    language: string,\n    prevCategory: string | undefined\n  ): string | null {\n    if (!this.config.continuation || !prevCategory) return null;\n\n    const contKeywords =\n      this.config.continuation.keywords[language] ?? this.config.continuation.keywords['en'] ?? [];\n\n    const lower = text.toLowerCase();\n    for (const kw of contKeywords) {\n      const kwLower = kw.toLowerCase();\n      if (lower.startsWith(kwLower)) {\n        const content = text.slice(kw.length).trim();\n        if (!content) return null;\n\n        if (this.config.continuation.resolve) {\n          return this.config.continuation.resolve(\n            content,\n            prevCategory,\n            language,\n            this.config.keywords?.categories ?? {}\n          );\n        }\n\n        // Default: prepend previous category's keyword\n        const prevKeywords =\n          this.config.keywords?.categories[prevCategory]?.[language] ??\n          this.config.keywords?.categories[prevCategory]?.['en'];\n        if (prevKeywords?.[0]) {\n          return prevKeywords[0] + ' ' + content;\n        }\n\n        return null;\n      }\n    }\n\n    return null;\n  }\n}\n\n// =============================================================================\n// Block Accumulator (for grouped/nested structures)\n// =============================================================================\n\n/**\n * A block of accumulated statements, grouped by a block-opening keyword.\n */\nexport interface StatementBlock<TMeta = unknown> {\n  /** Block type (e.g., 'test', 'feature', 'scenario') */\n  readonly type: string;\n  /** Block name, if any (e.g., test name from quotes) */\n  readonly name?: string;\n  /** Statements within this block */\n  readonly statements: readonly ParsedStatement[];\n  /** Child blocks (for nested structures) */\n  readonly children: readonly StatementBlock<TMeta>[];\n  /** Starting line number */\n  readonly line: number;\n  /** Indentation level of the block opener */\n  readonly indent: number;\n  /** Domain-specific metadata */\n  readonly meta?: TMeta;\n}\n\n/**\n * Configuration for block accumulation.\n */\nexport interface BlockConfig {\n  /**\n   * Block-opening keyword categories.\n   * Statements classified in these categories start new blocks.\n   */\n  readonly blockTypes: readonly string[];\n\n  /**\n   * How to determine block nesting:\n   * - 'indent': indentation-based (deeper indent = child block)\n   * - 'flat': all blocks at same level (no nesting)\n   */\n  readonly nesting: 'indent' | 'flat';\n\n  /**\n   * Extract block name from statement text.\n   * Default: extracts quoted string after keyword (e.g., test \"Login\" → \"Login\")\n   */\n  readonly extractName?: (text: string, category: string) => string | undefined;\n}\n\n/**\n * Result of block accumulation.\n */\nexport interface BlockResult<TMeta = unknown> {\n  /** Top-level blocks */\n  readonly blocks: readonly StatementBlock<TMeta>[];\n  /** Statements not inside any block */\n  readonly orphans: readonly ParsedStatement[];\n}\n\n/**\n * Accumulate parsed statements into blocks based on keyword categories.\n *\n * This groups statements into hierarchical blocks based on block-opening keywords\n * and indentation levels. Useful for test/feature/scenario structures.\n *\n * @example\n * ```typescript\n * const result = accumulateBlocks(statements, {\n *   blockTypes: ['test', 'feature', 'setup'],\n *   nesting: 'indent',\n *   extractName: (text, category) => {\n *     const match = text.match(/\"([^\"]+)\"/);\n *     return match?.[1];\n *   },\n * });\n * ```\n */\nexport function accumulateBlocks<TMeta = unknown>(\n  statements: readonly ParsedStatement[],\n  config: BlockConfig\n): BlockResult<TMeta> {\n  if (config.nesting === 'flat') {\n    return accumulateFlat(statements, config);\n  }\n  return accumulateIndented(statements, config);\n}\n\nfunction accumulateFlat<TMeta>(\n  statements: readonly ParsedStatement[],\n  config: BlockConfig\n): BlockResult<TMeta> {\n  const blocks: StatementBlock<TMeta>[] = [];\n  const orphans: ParsedStatement[] = [];\n  let current: {\n    type: string;\n    name?: string;\n    stmts: ParsedStatement[];\n    line: number;\n    indent: number;\n  } | null = null;\n\n  const flush = () => {\n    if (current) {\n      blocks.push({\n        type: current.type,\n        ...(current.name != null && { name: current.name }),\n        statements: current.stmts,\n        children: [],\n        line: current.line,\n        indent: current.indent,\n      });\n      current = null;\n    }\n  };\n\n  for (const stmt of statements) {\n    if (stmt.category && config.blockTypes.includes(stmt.category)) {\n      flush();\n      const name = config.extractName?.(stmt.source, stmt.category);\n      current = {\n        type: stmt.category,\n        ...(name != null && { name }),\n        stmts: [stmt],\n        line: stmt.line,\n        indent: stmt.indent,\n      };\n    } else if (current) {\n      current.stmts.push(stmt);\n    } else {\n      orphans.push(stmt);\n    }\n  }\n\n  flush();\n  return { blocks, orphans };\n}\n\nfunction accumulateIndented<TMeta>(\n  statements: readonly ParsedStatement[],\n  config: BlockConfig\n): BlockResult<TMeta> {\n  const rootBlocks: StatementBlock<TMeta>[] = [];\n  const orphans: ParsedStatement[] = [];\n\n  // Stack of open blocks with their indent level\n  const stack: Array<{\n    type: string;\n    name?: string;\n    stmts: ParsedStatement[];\n    children: StatementBlock<TMeta>[];\n    line: number;\n    indent: number;\n  }> = [];\n\n  const flushTo = (targetIndent: number) => {\n    while (stack.length > 0) {\n      const top = stack[stack.length - 1];\n      if (top.indent >= targetIndent) {\n        stack.pop();\n        const block: StatementBlock<TMeta> = {\n          type: top.type,\n          ...(top.name != null && { name: top.name }),\n          statements: top.stmts,\n          children: top.children,\n          line: top.line,\n          indent: top.indent,\n        };\n        if (stack.length > 0) {\n          stack[stack.length - 1].children.push(block);\n        } else {\n          rootBlocks.push(block);\n        }\n      } else {\n        break;\n      }\n    }\n  };\n\n  for (const stmt of statements) {\n    if (stmt.category && config.blockTypes.includes(stmt.category)) {\n      // Flush blocks at same or deeper indent\n      flushTo(stmt.indent);\n      const name = config.extractName?.(stmt.source, stmt.category);\n      stack.push({\n        type: stmt.category,\n        ...(name != null && { name }),\n        stmts: [stmt],\n        children: [],\n        line: stmt.line,\n        indent: stmt.indent,\n      });\n    } else if (stack.length > 0) {\n      stack[stack.length - 1].stmts.push(stmt);\n    } else {\n      orphans.push(stmt);\n    }\n  }\n\n  // Flush remaining\n  flushTo(-1);\n\n  return { blocks: rootBlocks, orphans };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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AI;AAAA,IACzC,OAAO;AACL,cAAQ,KAAK,IAAI;AAAA,IACnB;AAAA,EACF;AAGA,UAAQ,EAAE;AAEV,SAAO,EAAE,QAAQ,YAAY,QAAQ;AACvC;","names":["value","kind","position","normalized","num","length","import_intent","import_intent","import_intent","roles","import_intent","convertCommand","detectSelectorKind","generateRoleCombinations","sampleValue","toSemanticValue","sampleSelector","sampleLiteral","sampleExpression","detectSelectorKind","toSemanticValue","import_intent","import_intent","normalized","block"]}