{"version":3,"file":"registry-D6t0f2ZO.mjs","names":["extractDeclarationName","declarationKey","path","path","path"],"sources":["../src/engine/merge-adapters/url-fingerprint.ts","../src/engine/merge-adapters/dotnet.ts","../src/engine/merge-adapters/elixir.ts","../src/engine/merge-adapters/go.ts","../src/engine/merge-adapters/kotlin.ts","../src/engine/merge-adapters/node.ts","../src/engine/merge-adapters/php.ts","../src/engine/merge-adapters/python.ts","../src/engine/merge-adapters/ruby.ts","../src/engine/merge-adapters/rust.ts","../src/engine/merge-adapters/index.ts","../src/engine/merger.ts","../src/engine/json-merge.ts","../src/engine/writer.ts","../src/engine/scoped-services.ts","../src/engine/generate-files.ts","../src/engine/integrate.ts","../src/engine/formatter.ts","../src/engine/manifest.ts","../src/engine/orchestrator.ts","../src/engine/registry.ts"],"sourcesContent":["import type Parser from 'tree-sitter';\nimport type { UrlFingerprintConfig } from './types.js';\n\n/**\n * Extract a URL path fingerprint from a method body using tree-sitter AST traversal.\n *\n * Walks the AST subtree of the member node looking for the first string literal\n * that starts with '/'. Normalizes interpolation expressions to '{}' and format\n * specifiers (%s, %d, etc.) to '{}' for cross-language comparison.\n *\n * @returns A normalized URL fingerprint like \"/organizations/{}\" or undefined if none found.\n */\nexport function extractUrlFingerprint(memberNode: Parser.SyntaxNode, config: UrlFingerprintConfig): string | undefined {\n  const stringTypes = new Set(config.stringNodeTypes);\n  const contentTypes = new Set(config.contentNodeTypes);\n  const interpolationTypes = new Set(config.interpolationNodeTypes);\n  const formatFns = config.formatFunctionNames ? new Set(config.formatFunctionNames) : null;\n\n  // Iterative DFS through the method's AST subtree\n  const stack: Parser.SyntaxNode[] = [memberNode];\n\n  while (stack.length > 0) {\n    const node = stack.pop()!;\n\n    if (stringTypes.has(node.type)) {\n      const fp = resolveFingerprint(node, contentTypes, interpolationTypes);\n      if (fp?.startsWith('/')) return fp;\n    }\n\n    // For format functions (Go's Sprintf, Rust's format!): check if this call\n    // matches and extract the first string argument.\n    if (formatFns && isFormatCall(node, formatFns)) {\n      const fp = extractFromFormatCall(node, stringTypes, contentTypes, interpolationTypes);\n      if (fp?.startsWith('/')) return fp;\n    }\n\n    // Push children in reverse order so leftmost child is processed first\n    for (let i = node.childCount - 1; i >= 0; i--) {\n      const child = node.child(i);\n      if (child) stack.push(child);\n    }\n  }\n\n  return undefined;\n}\n\n/**\n * Resolve the text content of a string node, normalizing interpolations to '{}'.\n */\nfunction resolveFingerprint(\n  stringNode: Parser.SyntaxNode,\n  contentTypes: Set<string>,\n  interpolationTypes: Set<string>,\n): string | undefined {\n  // Leaf string node (no children besides quotes) — strip quotes\n  if (stringNode.namedChildCount === 0) {\n    return normalizeFormatSpecifiers(stripQuotes(stringNode.text));\n  }\n\n  // Composite string (has content fragments + interpolation children)\n  let result = '';\n  for (let i = 0; i < stringNode.childCount; i++) {\n    const child = stringNode.child(i)!;\n    if (contentTypes.has(child.type)) {\n      result += child.text;\n    } else if (interpolationTypes.has(child.type)) {\n      result += '{}';\n    }\n    // Skip quote delimiters, interpolation markers, etc.\n  }\n\n  return result ? normalizeFormatSpecifiers(result) : normalizeFormatSpecifiers(stripQuotes(stringNode.text));\n}\n\n/** Check if a node is a call to one of the format functions (e.g., fmt.Sprintf, format!). */\nfunction isFormatCall(node: Parser.SyntaxNode, formatFns: Set<string>): boolean {\n  // Rust macro: format!(...) — tree-sitter may parse as macro_invocation\n  if (node.type === 'macro_invocation') {\n    const macroName = node.childForFieldName('macro')?.text;\n    return !!(macroName && formatFns.has(macroName.replace(/!$/, '')));\n  }\n\n  if (node.type !== 'call_expression') return false;\n  const fnNode = node.childForFieldName('function');\n  if (!fnNode) return false;\n\n  // Direct call: Sprintf(...) or format!(...)\n  if (formatFns.has(fnNode.text)) return true;\n\n  // Member call: fmt.Sprintf(...)\n  if (fnNode.type === 'selector_expression' || fnNode.type === 'member_expression') {\n    const prop = fnNode.childForFieldName('field') ?? fnNode.childForFieldName('property');\n    if (prop && formatFns.has(prop.text)) return true;\n  }\n  return false;\n}\n\n/** Extract the first string argument from a format function call. */\nfunction extractFromFormatCall(\n  callNode: Parser.SyntaxNode,\n  stringTypes: Set<string>,\n  contentTypes: Set<string>,\n  interpolationTypes: Set<string>,\n): string | undefined {\n  const args = callNode.childForFieldName('arguments');\n  if (!args) return undefined;\n\n  for (let i = 0; i < args.childCount; i++) {\n    const arg = args.child(i)!;\n    if (stringTypes.has(arg.type)) {\n      return resolveFingerprint(arg, contentTypes, interpolationTypes);\n    }\n  }\n  return undefined;\n}\n\n/** Strip surrounding quote characters from a string literal. */\nfunction stripQuotes(text: string): string {\n  // Handle various quote styles: \"...\", '...', `...`, f\"...\", $\"...\", @\"...\"\n  const match = text.match(/^(?:f|r|b|@|\\$)?(?:\"\"\"([\\s\\S]*)\"\"\"|'''([\\s\\S]*)'''|\"(.*)\"|'(.*)'|`(.*)`)$/s);\n  if (match) return match[1] ?? match[2] ?? match[3] ?? match[4] ?? match[5] ?? text;\n  return text;\n}\n\n/** Replace printf-style format specifiers (%s, %d, %v, %f) with {}. */\nfunction normalizeFormatSpecifiers(s: string): string {\n  return s.replace(/%[sdvf]/g, '{}');\n}\n","import type Parser from 'tree-sitter';\nimport type {\n  MergeAdapter,\n  MergeStatement,\n  MergeImport,\n  DocstringInfo,\n  SymbolDocstrings,\n  MemberDocstrings,\n} from './types.js';\nimport { extractUrlFingerprint } from './url-fingerprint.js';\n\nconst DOTNET_URL_FINGERPRINT_CONFIG = {\n  stringNodeTypes: ['string_literal', 'interpolated_string_expression'],\n  contentNodeTypes: ['string_content', 'string_literal_content'],\n  interpolationNodeTypes: ['interpolation'],\n};\n\nconst DECLARATION_TYPES = new Set([\n  'class_declaration',\n  'struct_declaration',\n  'interface_declaration',\n  'enum_declaration',\n  'record_declaration',\n]);\n\nfunction extractDeclarationName(node: Parser.SyntaxNode): string | null {\n  if (DECLARATION_TYPES.has(node.type)) {\n    const nameNode = node.childForFieldName('name') ?? node.children.find((c) => c.type === 'identifier');\n    return nameNode?.text ?? null;\n  }\n  if (node.type === 'namespace_declaration' || node.type === 'file_scoped_namespace_declaration') {\n    const nameNode =\n      node.children.find((c) => c.type === 'qualified_name') ?? node.children.find((c) => c.type === 'identifier');\n    return nameNode ? `__namespace:${nameNode.text}` : null;\n  }\n  return null;\n}\n\nfunction collectPrecedingXmlDocComments(\n  children: Parser.SyntaxNode[],\n  index: number,\n  source: string,\n): DocstringInfo | null {\n  let lastIdx = -1;\n  let firstIdx = -1;\n  for (let k = index - 1; k >= 0; k--) {\n    const prev = children[k];\n    if (prev.type === 'comment') {\n      const text = source.slice(prev.startIndex, prev.endIndex);\n      if (text.startsWith('///')) {\n        if (lastIdx === -1) lastIdx = k;\n        firstIdx = k;\n      } else {\n        break;\n      }\n    } else {\n      break;\n    }\n  }\n  if (firstIdx === -1) return null;\n  const first = children[firstIdx];\n  const last = children[lastIdx];\n  return { text: source.slice(first.startIndex, last.endIndex), startIndex: first.startIndex, endIndex: last.endIndex };\n}\n\n/**\n * Collect declarations from a list of sibling nodes (root level or namespace body).\n */\nfunction collectDeclarations(\n  children: Parser.SyntaxNode[],\n  source: string,\n  statements: MergeStatement[],\n  imports: MergeImport[],\n  importAnchors: string[],\n  importInsertionAnchor: { value?: string },\n): void {\n  for (const child of children) {\n    if (child.type === 'comment') continue;\n\n    if (child.type === 'using_directive') {\n      const text = source.slice(child.startIndex, child.endIndex);\n      imports.push({ key: text.trim(), text });\n      importAnchors.push(text);\n      continue;\n    }\n\n    if (child.type === 'file_scoped_namespace_declaration') {\n      importInsertionAnchor.value = source.slice(child.startIndex, child.endIndex);\n      // File-scoped namespace: subsequent declarations are siblings at root\n      continue;\n    }\n\n    if (child.type === 'namespace_declaration') {\n      importInsertionAnchor.value = source.slice(child.startIndex, child.endIndex);\n      // Block namespace: recurse into declaration_list\n      const body = child.children.find((c) => c.type === 'declaration_list');\n      if (body) {\n        collectDeclarations(body.namedChildren, source, statements, imports, importAnchors, importInsertionAnchor);\n      }\n      continue;\n    }\n\n    const name = extractDeclarationName(child);\n    statements.push({\n      key: name,\n      kind: name ? 'declaration' : 'other',\n      text: source.slice(child.startIndex, child.endIndex),\n    });\n  }\n}\n\nexport const dotnetMergeAdapter: MergeAdapter = {\n  language: 'dotnet',\n  grammarModule: 'tree-sitter-c-sharp',\n  testFilePatterns: [/Tests?\\.cs$/],\n  urlFingerprintConfig: DOTNET_URL_FINGERPRINT_CONFIG,\n  parseStatements(tree, source) {\n    const imports: MergeImport[] = [];\n    const importAnchors: string[] = [];\n    const statements: MergeStatement[] = [];\n    const importInsertionAnchor: { value?: string } = {};\n\n    collectDeclarations(tree.rootNode.children, source, statements, imports, importAnchors, importInsertionAnchor);\n\n    return {\n      imports,\n      importAnchors,\n      importInsertionAnchor: importInsertionAnchor.value,\n      statements,\n    };\n  },\n  renderImports(imports) {\n    return imports.map((entry) => entry.text);\n  },\n  extractDocstrings(tree, source) {\n    const result = new Map<string, SymbolDocstrings>();\n\n    function processChildren(children: Parser.SyntaxNode[]): void {\n      for (let i = 0; i < children.length; i++) {\n        const child = children[i];\n\n        // Recurse into namespaces\n        if (child.type === 'namespace_declaration') {\n          const body = child.children.find((c) => c.type === 'declaration_list');\n          if (body) processChildren(body.children);\n          continue;\n        }\n\n        const name = extractDeclarationName(child);\n        if (!name || name.startsWith('__namespace:')) continue;\n\n        const docstring = collectPrecedingXmlDocComments(children, i, source);\n        const members = new Map<string, MemberDocstrings>();\n\n        // Extract member docstrings\n        const body = child.children.find((c) => c.type === 'declaration_list');\n        if (body) {\n          const bodyChildren = body.children;\n          for (let j = 0; j < bodyChildren.length; j++) {\n            const member = bodyChildren[j];\n            if (member.type !== 'method_declaration' && member.type !== 'property_declaration') continue;\n            // For methods, the second identifier is the name (first is return type)\n            const identifiers = member.children.filter((c) => c.type === 'identifier');\n            const memberName =\n              member.type === 'method_declaration'\n                ? identifiers.length >= 2\n                  ? identifiers[1]!.text\n                  : identifiers[0]?.text\n                : identifiers[0]?.text;\n            if (!memberName) continue;\n            const memberDoc = collectPrecedingXmlDocComments(bodyChildren, j, source);\n            members.set(memberName, {\n              docstring: memberDoc,\n              declStartIndex: member.startIndex,\n              declColumn: member.startPosition.column,\n              urlFingerprint: extractUrlFingerprint(member, DOTNET_URL_FINGERPRINT_CONFIG),\n            });\n          }\n        }\n\n        result.set(name, {\n          docstring,\n          declStartIndex: child.startIndex,\n          declColumn: child.startPosition.column,\n          members,\n        });\n      }\n    }\n\n    processChildren(tree.rootNode.children);\n    return result;\n  },\n};\n","import type Parser from 'tree-sitter';\nimport type {\n  MergeAdapter,\n  MergeStatement,\n  MergeImport,\n  DocstringInfo,\n  SymbolDocstrings,\n  MemberDocstrings,\n} from './types.js';\nimport { extractUrlFingerprint } from './url-fingerprint.js';\n\nconst ELIXIR_URL_FINGERPRINT_CONFIG = {\n  stringNodeTypes: ['string'],\n  contentNodeTypes: ['quoted_content'],\n  interpolationNodeTypes: ['interpolation'],\n};\n\nfunction isDefmodule(node: Parser.SyntaxNode): boolean {\n  return node.type === 'call' && node.children[0]?.text === 'defmodule';\n}\n\nfunction getModuleName(node: Parser.SyntaxNode): string | null {\n  if (!isDefmodule(node)) return null;\n  const args = node.children.find((c) => c.type === 'arguments');\n  if (!args) return null;\n  const alias = args.children.find((c) => c.type === 'alias');\n  return alias?.text ?? null;\n}\n\nfunction getDoBlock(node: Parser.SyntaxNode): Parser.SyntaxNode | null {\n  return node.children.find((c) => c.type === 'do_block') ?? null;\n}\n\n/** Check if a node is an @moduledoc or @doc attribute. */\nfunction isDocAttribute(node: Parser.SyntaxNode): string | null {\n  if (node.type !== 'unary_operator') return null;\n  const call = node.children.find((c) => c.type === 'call');\n  if (!call) return null;\n  const id = call.children.find((c) => c.type === 'identifier');\n  if (id?.text === 'moduledoc' || id?.text === 'doc') return id.text;\n  return null;\n}\n\n/** Check if a node is a def/defp call. */\nfunction getDefName(node: Parser.SyntaxNode): string | null {\n  if (node.type !== 'call') return null;\n  const id = node.children[0];\n  if (!id || (id.text !== 'def' && id.text !== 'defp')) return null;\n  const args = node.children.find((c) => c.type === 'arguments');\n  if (!args) return null;\n  // The function name is either a simple identifier or a call (for functions with params)\n  for (const arg of args.namedChildren) {\n    if (arg.type === 'identifier') return arg.text;\n    if (arg.type === 'call') {\n      const nameNode = arg.children.find((c) => c.type === 'identifier');\n      return nameNode?.text ?? null;\n    }\n  }\n  return null;\n}\n\n/** Check if a node is an alias/import/require/use call. */\nfunction isImportLike(node: Parser.SyntaxNode): boolean {\n  if (node.type !== 'call') return false;\n  const id = node.children[0];\n  return id?.type === 'identifier' && ['alias', 'import', 'require', 'use'].includes(id.text);\n}\n\nexport const elixirMergeAdapter: MergeAdapter = {\n  language: 'elixir',\n  grammarModule: 'tree-sitter-elixir',\n  testFilePatterns: [/_test\\.exs$/],\n  urlFingerprintConfig: ELIXIR_URL_FINGERPRINT_CONFIG,\n  parseStatements(tree, source) {\n    const imports: MergeImport[] = [];\n    const importAnchors: string[] = [];\n    const statements: MergeStatement[] = [];\n\n    for (const child of tree.rootNode.children) {\n      if (child.type === 'comment') continue;\n\n      // Top-level alias/import/require/use (rare but possible outside modules)\n      if (isImportLike(child)) {\n        const text = source.slice(child.startIndex, child.endIndex);\n        imports.push({ key: text.trim(), text });\n        importAnchors.push(text);\n        continue;\n      }\n\n      const moduleName = getModuleName(child);\n      statements.push({\n        key: moduleName,\n        kind: moduleName ? 'declaration' : 'other',\n        text: source.slice(child.startIndex, child.endIndex),\n      });\n    }\n\n    return { imports, importAnchors, statements };\n  },\n  renderImports(imports) {\n    return imports.map((entry) => entry.text);\n  },\n  extractDocstrings(tree, source) {\n    const result = new Map<string, SymbolDocstrings>();\n    const rootChildren = tree.rootNode.children;\n\n    for (let i = 0; i < rootChildren.length; i++) {\n      const child = rootChildren[i];\n      const moduleName = getModuleName(child);\n      if (!moduleName) continue;\n\n      // Look for @moduledoc inside the do_block\n      let docstring: DocstringInfo | null = null;\n      const doBlock = getDoBlock(child);\n      const members = new Map<string, MemberDocstrings>();\n\n      if (doBlock) {\n        const bodyChildren = doBlock.children;\n\n        // Find @moduledoc\n        for (const bodyChild of bodyChildren) {\n          if (isDocAttribute(bodyChild) === 'moduledoc') {\n            docstring = {\n              text: source.slice(bodyChild.startIndex, bodyChild.endIndex),\n              startIndex: bodyChild.startIndex,\n              endIndex: bodyChild.endIndex,\n            };\n            break;\n          }\n        }\n\n        // Find @doc + def pairs for member docstrings\n        for (let j = 0; j < bodyChildren.length; j++) {\n          const bodyChild = bodyChildren[j];\n          const defName = getDefName(bodyChild);\n          if (!defName) continue;\n\n          // Look for preceding @doc attribute\n          let memberDoc: DocstringInfo | null = null;\n          for (let k = j - 1; k >= 0; k--) {\n            const prev = bodyChildren[k];\n            if (isDocAttribute(prev) === 'doc') {\n              memberDoc = {\n                text: source.slice(prev.startIndex, prev.endIndex),\n                startIndex: prev.startIndex,\n                endIndex: prev.endIndex,\n              };\n              break;\n            }\n            if (prev.type === 'comment') continue;\n            break;\n          }\n\n          members.set(defName, {\n            docstring: memberDoc,\n            declStartIndex: bodyChild.startIndex,\n            declColumn: bodyChild.startPosition.column,\n            urlFingerprint: extractUrlFingerprint(bodyChild, ELIXIR_URL_FINGERPRINT_CONFIG),\n          });\n        }\n      }\n\n      result.set(moduleName, {\n        docstring,\n        declStartIndex: child.startIndex,\n        declColumn: child.startPosition.column,\n        members,\n      });\n    }\n\n    return result;\n  },\n};\n","import type Parser from 'tree-sitter';\nimport type { MergeAdapter, MergeStatement, MergeImport, DocstringInfo, SymbolDocstrings } from './types.js';\n\nconst GO_URL_FINGERPRINT_CONFIG = {\n  stringNodeTypes: ['interpreted_string_literal'],\n  contentNodeTypes: ['interpreted_string_literal_content'],\n  interpolationNodeTypes: [],\n  formatFunctionNames: ['Sprintf'],\n};\n\nfunction lastIdentifier(text: string): string | null {\n  const matches = [...text.matchAll(/[A-Za-z_][A-Za-z0-9_]*/g)];\n  return matches.length > 0 ? matches[matches.length - 1]![0] : null;\n}\n\nfunction receiverKey(node: Parser.SyntaxNode): string | null {\n  const receiver = node.childForFieldName('receiver');\n  if (!receiver) return null;\n  return lastIdentifier(receiver.text);\n}\n\nfunction declarationKey(node: Parser.SyntaxNode): string | null {\n  switch (node.type) {\n    case 'package_clause': {\n      const pkg = lastIdentifier(node.text);\n      return pkg ? `__package:${pkg}` : '__package:';\n    }\n    case 'type_declaration': {\n      const spec = node.firstNamedChild?.type === 'type_spec' ? node.firstNamedChild : node.namedChildren[0];\n      const nameNode = spec?.childForFieldName('name');\n      return nameNode?.text ?? null;\n    }\n    case 'function_declaration': {\n      return node.childForFieldName('name')?.text ?? null;\n    }\n    case 'method_declaration': {\n      const name = node.childForFieldName('name')?.text ?? null;\n      const receiver = receiverKey(node);\n      return name && receiver ? `method:${receiver}.${name}` : name;\n    }\n    case 'const_declaration':\n    case 'var_declaration': {\n      return node.text.split(/\\s+/).slice(0, 3).join(' ');\n    }\n    default:\n      return null;\n  }\n}\n\nfunction importEntries(node: Parser.SyntaxNode, source: string): MergeImport[] {\n  const entries: MergeImport[] = [];\n\n  const collect = (spec: Parser.SyntaxNode): void => {\n    const path = spec.childForFieldName('path')?.text ?? spec.text;\n    const name = spec.childForFieldName('name')?.text ?? '';\n    const text = source.slice(spec.startIndex, spec.endIndex);\n    entries.push({\n      key: `${name}:${path.replace(/^\"|\"$/g, '')}`,\n      text,\n    });\n  };\n\n  for (const child of node.namedChildren) {\n    if (child.type === 'import_spec') {\n      collect(child);\n      continue;\n    }\n    if (child.type === 'import_spec_list') {\n      for (const spec of child.namedChildren) {\n        if (spec.type === 'import_spec') collect(spec);\n      }\n    }\n  }\n\n  return entries;\n}\n\nfunction collectPrecedingGoComments(\n  children: Parser.SyntaxNode[],\n  index: number,\n  source: string,\n): DocstringInfo | null {\n  let lastIdx = -1;\n  let firstIdx = -1;\n  for (let k = index - 1; k >= 0; k--) {\n    const prev = children[k];\n    if (prev.type === 'comment') {\n      const text = source.slice(prev.startIndex, prev.endIndex);\n      if (text.startsWith('//')) {\n        if (lastIdx === -1) lastIdx = k;\n        firstIdx = k;\n      } else {\n        break;\n      }\n    } else {\n      break;\n    }\n  }\n  if (firstIdx === -1) return null;\n  const first = children[firstIdx];\n  const last = children[lastIdx];\n  return { text: source.slice(first.startIndex, last.endIndex), startIndex: first.startIndex, endIndex: last.endIndex };\n}\n\nexport const goMergeAdapter: MergeAdapter = {\n  language: 'go',\n  grammarModule: 'tree-sitter-go',\n  testFilePatterns: [/_test\\.go$/],\n  urlFingerprintConfig: GO_URL_FINGERPRINT_CONFIG,\n  parseStatements(tree, source) {\n    const imports: MergeImport[] = [];\n    const importAnchors: string[] = [];\n    let importInsertionAnchor: string | undefined;\n    const statements: MergeStatement[] = [];\n\n    for (const child of tree.rootNode.children) {\n      if (child.type === 'comment') continue;\n\n      if (child.type === 'package_clause') {\n        importInsertionAnchor = source.slice(child.startIndex, child.endIndex);\n      }\n\n      if (child.type === 'import_declaration') {\n        imports.push(...importEntries(child, source));\n        importAnchors.push(source.slice(child.startIndex, child.endIndex));\n        continue;\n      }\n\n      const key = declarationKey(child);\n      statements.push({\n        key,\n        kind: key ? 'declaration' : 'other',\n        text: source.slice(child.startIndex, child.endIndex),\n      });\n    }\n\n    return { imports, importAnchors, importInsertionAnchor, statements };\n  },\n  renderImports(imports) {\n    if (imports.length === 0) return [];\n    if (imports.length === 1) return [`import ${imports[0]!.text}`];\n    return [`import (\\n${imports.map((entry) => `  ${entry.text}`).join('\\n')}\\n)`];\n  },\n  extractDocstrings(tree, source) {\n    const result = new Map<string, SymbolDocstrings>();\n    const rootChildren = tree.rootNode.children;\n\n    for (let i = 0; i < rootChildren.length; i++) {\n      const child = rootChildren[i];\n      const key = declarationKey(child);\n      if (!key || key.startsWith('__package:')) continue;\n\n      const docstring = collectPrecedingGoComments(rootChildren, i, source);\n      result.set(key, {\n        docstring,\n        declStartIndex: child.startIndex,\n        declColumn: child.startPosition.column,\n        members: new Map(),\n      });\n    }\n\n    return result;\n  },\n};\n","import type Parser from 'tree-sitter';\nimport type {\n  MergeAdapter,\n  MergeStatement,\n  MergeImport,\n  MergeMember,\n  DeepMergeSymbol,\n  DocstringInfo,\n  SymbolDocstrings,\n  MemberDocstrings,\n} from './types.js';\nimport { extractUrlFingerprint } from './url-fingerprint.js';\n\nconst KOTLIN_URL_FINGERPRINT_CONFIG = {\n  stringNodeTypes: ['string_literal'],\n  contentNodeTypes: ['string_content'],\n  interpolationNodeTypes: ['interpolated_expression'],\n};\n\nfunction extractDeclarationName(node: Parser.SyntaxNode): string | null {\n  if (node.type === 'class_declaration') {\n    // Handles class, data class, enum class, etc.\n    const nameNode = node.children.find((c) => c.type === 'type_identifier');\n    return nameNode?.text ?? null;\n  }\n  if (node.type === 'function_declaration') {\n    const nameNode = node.children.find((c) => c.type === 'simple_identifier');\n    return nameNode?.text ?? null;\n  }\n  if (node.type === 'object_declaration') {\n    const nameNode = node.children.find((c) => c.type === 'type_identifier');\n    return nameNode?.text ?? null;\n  }\n  if (node.type === 'type_alias') {\n    const nameNode = node.children.find((c) => c.type === 'type_identifier');\n    return nameNode?.text ?? null;\n  }\n  if (node.type === 'property_declaration') {\n    const nameNode = node.children.find((c) => c.type === 'variable_declaration');\n    if (nameNode) {\n      const id = nameNode.children.find((c) => c.type === 'simple_identifier');\n      return id?.text ?? null;\n    }\n  }\n  return null;\n}\n\nfunction findPrecedingKdoc(children: Parser.SyntaxNode[], index: number, source: string): DocstringInfo | null {\n  for (let k = index - 1; k >= 0; k--) {\n    const prev = children[k];\n    if (prev.type === 'multiline_comment') {\n      const text = source.slice(prev.startIndex, prev.endIndex);\n      if (text.startsWith('/**')) {\n        return { text, startIndex: prev.startIndex, endIndex: prev.endIndex };\n      }\n      return null;\n    }\n    if (prev.type === 'line_comment') continue;\n    return null;\n  }\n  return null;\n}\n\nfunction extractKotlinClassMembers(classBody: Parser.SyntaxNode, source: string): MergeMember[] {\n  const members: MergeMember[] = [];\n  const children = classBody.namedChildren;\n\n  for (let i = 0; i < children.length; i++) {\n    const child = children[i];\n    // The getter/setter fold below advances `i` past sibling accessor nodes, so\n    // remember where the declaration itself sits — the KDoc scan walks backwards\n    // from here and would otherwise start on the declaration (or its getter) and\n    // never reach the doc comment.\n    const declIndex = i;\n    let memberName: string | null = null;\n\n    if (child.type === 'property_declaration') {\n      const varDecl = child.children.find((c) => c.type === 'variable_declaration');\n      memberName = varDecl?.children.find((c) => c.type === 'simple_identifier')?.text ?? null;\n    } else if (child.type === 'function_declaration') {\n      memberName = child.children.find((c) => c.type === 'simple_identifier')?.text ?? null;\n    } else if (child.type === 'companion_object') {\n      memberName = 'companion';\n    }\n\n    if (!memberName) continue;\n\n    // Fold trailing getter/setter into the property's text span\n    let endIdx = child.endIndex;\n    if (child.type === 'property_declaration') {\n      while (i + 1 < children.length) {\n        const next = children[i + 1];\n        if (next.type === 'getter' || next.type === 'setter') {\n          endIdx = next.endIndex;\n          i++;\n        } else {\n          break;\n        }\n      }\n    }\n\n    // Include preceding KDoc comment in the text span so deep merge\n    // inserts the member with its documentation intact.\n    let startIdx = child.startIndex;\n    for (let k = declIndex - 1; k >= 0; k--) {\n      const prev = children[k];\n      if (prev.type === 'multiline_comment') {\n        const text = source.slice(prev.startIndex, prev.endIndex);\n        if (text.startsWith('/**')) startIdx = prev.startIndex;\n        break;\n      }\n      if (prev.type === 'line_comment') continue;\n      break;\n    }\n\n    members.push({ key: memberName, text: source.slice(startIdx, endIdx), startIndex: startIdx, endIndex: endIdx });\n  }\n\n  return members;\n}\n\n/**\n * KDoc signature that identifies a generator-emitted service accessor inside\n * a Kotlin client class. The Kotlin client emitter writes every accessor with this\n * exact doc preamble — when the existing file carries a member with this doc\n * but the regenerated content omits it, the member is stale (its mount target\n * was remapped or removed) and gets pruned.\n */\nconst KOTLIN_MANAGED_ACCESSOR_DOC =\n  /\\/\\*\\*[\\s\\S]*?Lazily-constructed \\[[^\\]]+\\] accessor for this \\[[^\\]]+\\] client\\.[\\s\\S]*?\\*\\//;\n\nexport const kotlinMergeAdapter: MergeAdapter = {\n  language: 'kotlin',\n  grammarModule: 'tree-sitter-kotlin',\n  testFilePatterns: [/Test\\.kt$/],\n  urlFingerprintConfig: KOTLIN_URL_FINGERPRINT_CONFIG,\n  parseStatements(tree, source) {\n    const imports: MergeImport[] = [];\n    const importAnchors: string[] = [];\n    const statements: MergeStatement[] = [];\n\n    for (const child of tree.rootNode.children) {\n      if (child.type === 'multiline_comment' || child.type === 'line_comment') continue;\n\n      if (child.type === 'import_list') {\n        const fullText = source.slice(child.startIndex, child.endIndex);\n        importAnchors.push(fullText);\n        for (const imp of child.namedChildren) {\n          if (imp.type === 'import_header') {\n            const text = source.slice(imp.startIndex, imp.endIndex).trim();\n            // Key on the full import path\n            const idNode = imp.children.find((c) => c.type === 'identifier');\n            const key = idNode?.text ?? text;\n            imports.push({ key, text });\n          }\n        }\n        continue;\n      }\n\n      const name = extractDeclarationName(child);\n      statements.push({\n        key: name,\n        kind: name ? 'declaration' : 'other',\n        text: source.slice(child.startIndex, child.endIndex),\n      });\n    }\n\n    return { imports, importAnchors, statements };\n  },\n  renderImports(imports) {\n    return imports.map((entry) => entry.text);\n  },\n  isManagedMember(member) {\n    return KOTLIN_MANAGED_ACCESSOR_DOC.test(member.text);\n  },\n  importedNames(imp) {\n    const path = imp.text.replace(/^import\\s+/, '').trim();\n    const alias = path.match(/\\s+as\\s+([A-Za-z_][A-Za-z0-9_]*)$/);\n    if (alias) return [alias[1]];\n    const last = path.split('.').pop();\n    // Star imports bind every name in the package — nothing single to track.\n    return last && last !== '*' ? [last] : [];\n  },\n  shouldSkipDeepMerge(_symbolName, existingMemberKeys, newMembers) {\n    // Skip if new members reference instance properties that don't exist in the target\n    const newText = newMembers.map((m) => m.text).join('\\n');\n    for (const match of newText.matchAll(/this\\.(\\w+)/g)) {\n      const propName = match[1];\n      if (propName && !existingMemberKeys.has(propName)) return true;\n    }\n    return false;\n  },\n  extractMembers(tree, source) {\n    const result = new Map<string, DeepMergeSymbol>();\n\n    for (const child of tree.rootNode.children) {\n      if (child.type !== 'class_declaration') continue;\n      const nameNode = child.children.find((c) => c.type === 'type_identifier');\n      if (!nameNode) continue;\n      const body = child.children.find((c) => c.type === 'class_body');\n      if (!body) continue;\n\n      const members = extractKotlinClassMembers(body, source);\n      const firstMember = body.firstNamedChild;\n      const memberIndent = firstMember ? ' '.repeat(firstMember.startPosition.column) : undefined;\n      result.set(nameNode.text, { members, bodyEndLine: body.endPosition.row, memberIndent });\n    }\n\n    return result;\n  },\n  extractDocstrings(tree, source) {\n    const result = new Map<string, SymbolDocstrings>();\n    const rootChildren = tree.rootNode.children;\n\n    for (let i = 0; i < rootChildren.length; i++) {\n      const child = rootChildren[i];\n      const name = extractDeclarationName(child);\n      if (!name) continue;\n\n      const docstring = findPrecedingKdoc(rootChildren, i, source);\n      const members = new Map<string, MemberDocstrings>();\n\n      // Extract member docstrings for classes\n      if (child.type === 'class_declaration') {\n        const body = child.children.find((c) => c.type === 'class_body' || c.type === 'enum_class_body');\n        if (body) {\n          const bodyChildren = body.children;\n          for (let j = 0; j < bodyChildren.length; j++) {\n            const member = bodyChildren[j];\n            const memberName = extractDeclarationName(member);\n            if (!memberName) continue;\n            const memberDoc = findPrecedingKdoc(bodyChildren, j, source);\n            members.set(memberName, {\n              docstring: memberDoc,\n              declStartIndex: member.startIndex,\n              declColumn: member.startPosition.column,\n              urlFingerprint: extractUrlFingerprint(member, KOTLIN_URL_FINGERPRINT_CONFIG),\n            });\n          }\n        }\n      }\n\n      result.set(name, {\n        docstring,\n        declStartIndex: child.startIndex,\n        declColumn: child.startPosition.column,\n        members,\n      });\n    }\n\n    return result;\n  },\n};\n","import type Parser from 'tree-sitter';\nimport { normalizeJsExtension } from '../../utils/naming.js';\nimport type {\n  MergeAdapter,\n  MergeStatement,\n  MergeImport,\n  DeepMergeSymbol,\n  MergeMember,\n  DocstringInfo,\n  SymbolDocstrings,\n} from './types.js';\nimport { extractUrlFingerprint } from './url-fingerprint.js';\n\nconst REEXPORT_PREFIX = '__export:';\n\nfunction extractDeclName(node: Parser.SyntaxNode): string | null {\n  const nameNode = node.childForFieldName('name');\n  if (nameNode) return nameNode.text;\n\n  if (node.type === 'lexical_declaration') {\n    const declarator = node.firstNamedChild;\n    if (declarator?.type === 'variable_declarator') {\n      const name = declarator.childForFieldName('name');\n      if (name) return name.text;\n    }\n  }\n\n  return null;\n}\n\nfunction extractNodeKey(node: Parser.SyntaxNode): { key: string | null; kind: MergeStatement['kind'] } {\n  if (node.type === 'export_statement') {\n    const decl = node.childForFieldName('declaration');\n    if (decl) {\n      return { key: extractDeclName(decl), kind: 'declaration' };\n    }\n\n    const source = node.childForFieldName('source');\n    if (source) {\n      return { key: `${REEXPORT_PREFIX}${normalizeJsExtension(source.text)}`, kind: 'reexport' };\n    }\n\n    return { key: null, kind: 'other' };\n  }\n  return { key: extractDeclName(node), kind: extractDeclName(node) ? 'declaration' : 'other' };\n}\n\nfunction extractClassMembers(classBody: Parser.SyntaxNode, source: string): MergeMember[] {\n  const members: MergeMember[] = [];\n  for (const child of classBody.namedChildren) {\n    if (child.type === 'method_definition') {\n      const nameNode = child.childForFieldName('name');\n      if (nameNode && nameNode.text !== 'constructor') {\n        members.push({ key: nameNode.text, text: source.slice(child.startIndex, child.endIndex) });\n      }\n    } else if (child.type === 'public_field_definition') {\n      const nameNode = child.childForFieldName('name');\n      if (nameNode) {\n        // tree-sitter may exclude the trailing semicolon from\n        // public_field_definition nodes — include it if present\n        let endIdx = child.endIndex;\n        if (source[endIdx] === ';') {\n          endIdx += 1;\n        }\n        members.push({ key: nameNode.text, text: source.slice(child.startIndex, endIdx) });\n      }\n    }\n  }\n  return members;\n}\n\nfunction extractInterfaceMembers(body: Parser.SyntaxNode, source: string): MergeMember[] {\n  const members: MergeMember[] = [];\n  for (const child of body.namedChildren) {\n    if (child.type === 'property_signature' || child.type === 'method_signature') {\n      const nameNode = child.childForFieldName('name');\n      if (nameNode) {\n        members.push({ key: nameNode.text, text: source.slice(child.startIndex, child.endIndex) });\n      }\n    }\n  }\n  return members;\n}\n\nfunction extractEnumMembers(body: Parser.SyntaxNode, source: string): MergeMember[] {\n  const members: MergeMember[] = [];\n  for (const child of body.namedChildren) {\n    if (child.type === 'enum_assignment') {\n      const nameNode = child.childForFieldName('name');\n      if (nameNode) {\n        members.push({ key: nameNode.text, text: source.slice(child.startIndex, child.endIndex) });\n      }\n    } else if (child.type === 'property_identifier') {\n      members.push({ key: child.text, text: source.slice(child.startIndex, child.endIndex) });\n    }\n  }\n  return members;\n}\n\nfunction isCommentNode(node: Parser.SyntaxNode): boolean {\n  // tree-sitter extras (comments) may report the parent node's type\n  // instead of 'comment' — check grammarType as fallback\n  return node.type === 'comment' || (node as any).grammarType === 'comment';\n}\n\nfunction findPrecedingDocstring(children: Parser.SyntaxNode[], index: number, source: string): DocstringInfo | null {\n  for (let k = index - 1; k >= 0; k--) {\n    const prev = children[k];\n    if (isCommentNode(prev)) {\n      const text = source.slice(prev.startIndex, prev.endIndex);\n      if (text.startsWith('/**')) {\n        return { text, startIndex: prev.startIndex, endIndex: prev.endIndex };\n      }\n      return null;\n    }\n    if (prev.type === ',' || prev.type === ';' || prev.type === '{') continue;\n    return null;\n  }\n  return null;\n}\n\nconst CLASS_MEMBER_TYPES = new Set(['method_definition', 'public_field_definition']);\nconst INTERFACE_MEMBER_TYPES = new Set(['property_signature', 'method_signature']);\nconst ENUM_MEMBER_TYPES = new Set(['enum_assignment', 'property_identifier']);\n\nconst NODE_URL_FINGERPRINT_CONFIG = {\n  stringNodeTypes: ['string', 'template_string'],\n  contentNodeTypes: ['string_fragment'],\n  interpolationNodeTypes: ['template_substitution'],\n};\n\nfunction extractBodyMemberDocstrings(\n  body: Parser.SyntaxNode,\n  source: string,\n  memberTypes: Set<string>,\n): Map<\n  string,\n  { docstring: DocstringInfo | null; declStartIndex: number; declColumn: number; urlFingerprint?: string }\n> {\n  const result = new Map<\n    string,\n    { docstring: DocstringInfo | null; declStartIndex: number; declColumn: number; urlFingerprint?: string }\n  >();\n  const allChildren = body.children;\n  for (let i = 0; i < allChildren.length; i++) {\n    const child = allChildren[i];\n    if (!memberTypes.has(child.type)) continue;\n    let memberName: string | null = null;\n    if (child.type === 'property_identifier') {\n      memberName = child.text;\n    } else {\n      const nameNode = child.childForFieldName('name');\n      if (nameNode) memberName = nameNode.text;\n    }\n    if (!memberName || memberName === 'constructor') continue;\n    const docstring = findPrecedingDocstring(allChildren, i, source);\n    const fp = extractUrlFingerprint(child, NODE_URL_FINGERPRINT_CONFIG);\n    result.set(memberName, {\n      docstring,\n      declStartIndex: child.startIndex,\n      declColumn: child.startPosition.column,\n      urlFingerprint: fp,\n    });\n  }\n  return result;\n}\n\nexport const nodeMergeAdapter: MergeAdapter = {\n  language: 'node',\n  grammarModule: 'tree-sitter-typescript/bindings/node/typescript.js',\n  normalizeReexport: normalizeJsExtension,\n  testFilePatterns: [/\\.(spec|test)\\.[jt]sx?$/],\n  urlFingerprintConfig: NODE_URL_FINGERPRINT_CONFIG,\n  shouldSkipDeepMerge(_symbolName, existingMemberKeys, newMembers) {\n    // If new members reference instance properties (this.X) that don't exist\n    // in the target class, the merged code would be broken.\n    const newText = newMembers.map((m) => m.text).join('\\n');\n    for (const match of newText.matchAll(/this\\.(\\w+)/g)) {\n      const propName = match[1];\n      if (propName && !existingMemberKeys.has(propName)) {\n        return true;\n      }\n    }\n    return false;\n  },\n  parseStatements(tree, source) {\n    const imports: MergeImport[] = [];\n    const importAnchors: string[] = [];\n    const statements: MergeStatement[] = [];\n\n    for (const child of tree.rootNode.children) {\n      if (child.type === 'comment') continue;\n\n      if (child.type === 'import_statement') {\n        const text = source.slice(child.startIndex, child.endIndex);\n        // Key on module path so `import { X }` and `import type { X }` from\n        // the same module are treated as duplicates\n        const sourceNode = child.childForFieldName('source');\n        const modulePath = sourceNode ? normalizeJsExtension(sourceNode.text) : normalizeJsExtension(text.trim());\n        imports.push({ key: modulePath, text });\n        importAnchors.push(text);\n        continue;\n      }\n\n      const { key, kind } = extractNodeKey(child);\n      statements.push({\n        key,\n        kind,\n        text: source.slice(child.startIndex, child.endIndex),\n      });\n    }\n\n    return { imports, importAnchors, statements };\n  },\n  renderImports(imports) {\n    return imports.map((entry) => entry.text);\n  },\n  extractMembers(tree, source) {\n    const result = new Map<string, DeepMergeSymbol>();\n\n    for (const child of tree.rootNode.children) {\n      if (child.type !== 'export_statement') continue;\n      const decl = child.childForFieldName('declaration');\n      if (!decl) continue;\n\n      const nameNode = decl.childForFieldName('name');\n      if (!nameNode) continue;\n      const symbolName = nameNode.text;\n\n      if (decl.type === 'class_declaration') {\n        const body = decl.childForFieldName('body');\n        if (!body) continue;\n        const members = extractClassMembers(body, source);\n        const firstMember = body.firstNamedChild;\n        const memberIndent = firstMember ? ' '.repeat(firstMember.startPosition.column) : undefined;\n        result.set(symbolName, { members, bodyEndLine: body.endPosition.row, memberIndent });\n      } else if (decl.type === 'interface_declaration') {\n        const body = decl.childForFieldName('body');\n        if (!body) continue;\n        const members = extractInterfaceMembers(body, source);\n        const firstMember = body.firstNamedChild;\n        const memberIndent = firstMember ? ' '.repeat(firstMember.startPosition.column) : undefined;\n        result.set(symbolName, { members, bodyEndLine: body.endPosition.row, memberIndent });\n      } else if (decl.type === 'enum_declaration') {\n        const body = decl.childForFieldName('body');\n        if (!body) continue;\n        const members = extractEnumMembers(body, source);\n        const firstMember = body.firstNamedChild;\n        const memberIndent = firstMember ? ' '.repeat(firstMember.startPosition.column) : undefined;\n        result.set(symbolName, { members, bodyEndLine: body.endPosition.row, memberIndent });\n      }\n    }\n\n    return result;\n  },\n  extractDocstrings(tree, source) {\n    const result = new Map<string, SymbolDocstrings>();\n    const rootChildren = tree.rootNode.children;\n\n    for (let i = 0; i < rootChildren.length; i++) {\n      const child = rootChildren[i];\n      if (child.type !== 'export_statement') continue;\n      const decl = child.childForFieldName('declaration');\n      if (!decl) continue;\n      const nameNode = decl.childForFieldName('name');\n      if (!nameNode) continue;\n\n      // Find preceding JSDoc for this top-level symbol\n      const docstring = findPrecedingDocstring(rootChildren, i, source);\n\n      // Extract member-level docstrings\n      let members = new Map<string, { docstring: DocstringInfo | null; declStartIndex: number; declColumn: number }>();\n      const body = decl.childForFieldName('body');\n      if (body) {\n        if (decl.type === 'class_declaration') {\n          members = extractBodyMemberDocstrings(body, source, CLASS_MEMBER_TYPES);\n        } else if (decl.type === 'interface_declaration') {\n          members = extractBodyMemberDocstrings(body, source, INTERFACE_MEMBER_TYPES);\n        } else if (decl.type === 'enum_declaration') {\n          members = extractBodyMemberDocstrings(body, source, ENUM_MEMBER_TYPES);\n        }\n      }\n\n      result.set(nameNode.text, {\n        docstring,\n        declStartIndex: child.startIndex,\n        declColumn: child.startPosition.column,\n        members,\n      });\n    }\n\n    return result;\n  },\n};\n","import type Parser from 'tree-sitter';\nimport type {\n  MergeAdapter,\n  MergeStatement,\n  MergeImport,\n  DocstringInfo,\n  SymbolDocstrings,\n  MemberDocstrings,\n} from './types.js';\nimport { extractUrlFingerprint } from './url-fingerprint.js';\n\nconst PHP_URL_FINGERPRINT_CONFIG = {\n  stringNodeTypes: ['encapsed_string', 'string'],\n  contentNodeTypes: ['string_content'],\n  interpolationNodeTypes: ['variable_name'],\n};\n\nfunction extractPhpDeclarationName(node: Parser.SyntaxNode): string | null {\n  switch (node.type) {\n    case 'class_declaration':\n    case 'interface_declaration':\n    case 'trait_declaration':\n    case 'enum_declaration':\n    case 'function_definition': {\n      const nameNode = node.childForFieldName('name');\n      return nameNode?.text ?? null;\n    }\n    case 'namespace_definition': {\n      const nameNode = node.childForFieldName('name');\n      return nameNode ? `__namespace:${nameNode.text}` : '__namespace:';\n    }\n    default:\n      return null;\n  }\n}\n\nfunction findPhpDocstring(children: Parser.SyntaxNode[], index: number, source: string): DocstringInfo | null {\n  for (let k = index - 1; k >= 0; k--) {\n    const prev = children[k];\n    if (prev.type === 'comment') {\n      const text = source.slice(prev.startIndex, prev.endIndex);\n      if (text.startsWith('/**')) {\n        return { text, startIndex: prev.startIndex, endIndex: prev.endIndex };\n      }\n      return null;\n    }\n    if (prev.type === ';' || prev.type === '{') continue;\n    return null;\n  }\n  return null;\n}\n\nexport const phpMergeAdapter: MergeAdapter = {\n  language: 'php',\n  grammarModule: 'tree-sitter-php',\n  testFilePatterns: [/Test\\.php$/],\n  urlFingerprintConfig: PHP_URL_FINGERPRINT_CONFIG,\n  resolveGrammar: (mod) => {\n    // ESM import wraps in { default: { php, php_only } }\n    const m = (mod as Record<string, unknown>)?.default ?? mod;\n    if (typeof m === 'object' && m !== null && 'php' in (m as Record<string, unknown>))\n      return (m as { php: unknown }).php;\n    return m;\n  },\n  parseStatements(tree, source) {\n    const imports: MergeImport[] = [];\n    const importAnchors: string[] = [];\n    let importInsertionAnchor: string | undefined;\n    const statements: MergeStatement[] = [];\n\n    for (const child of tree.rootNode.children) {\n      if (child.type === 'comment') continue;\n\n      if (child.type === 'namespace_definition') {\n        importInsertionAnchor = source.slice(child.startIndex, child.endIndex);\n      }\n\n      if (child.type === 'namespace_use_declaration') {\n        const text = source.slice(child.startIndex, child.endIndex);\n        imports.push({ key: text.trim(), text });\n        importAnchors.push(text);\n        continue;\n      }\n\n      const declarationName = extractPhpDeclarationName(child);\n      const kind: MergeStatement['kind'] = declarationName ? 'declaration' : 'other';\n\n      statements.push({\n        key: declarationName,\n        kind,\n        text: source.slice(child.startIndex, child.endIndex),\n      });\n    }\n\n    return { imports, importAnchors, importInsertionAnchor, statements };\n  },\n  renderImports(imports) {\n    return imports.map((entry) => entry.text);\n  },\n  extractDocstrings(tree, source) {\n    const result = new Map<string, SymbolDocstrings>();\n    const rootChildren = tree.rootNode.children;\n\n    for (let i = 0; i < rootChildren.length; i++) {\n      const child = rootChildren[i];\n      const name = extractPhpDeclarationName(child);\n      if (!name || name.startsWith('__namespace:')) continue;\n\n      const docstring = findPhpDocstring(rootChildren, i, source);\n      const members = new Map<string, MemberDocstrings>();\n\n      const body = child.childForFieldName('body');\n      if (body) {\n        const bodyChildren = body.children;\n        for (let j = 0; j < bodyChildren.length; j++) {\n          const member = bodyChildren[j];\n          if (member.type !== 'method_declaration') continue;\n          const memberName = member.childForFieldName('name')?.text;\n          if (!memberName) continue;\n          const memberDoc = findPhpDocstring(bodyChildren, j, source);\n          members.set(memberName, {\n            docstring: memberDoc,\n            declStartIndex: member.startIndex,\n            declColumn: member.startPosition.column,\n            urlFingerprint: extractUrlFingerprint(member, PHP_URL_FINGERPRINT_CONFIG),\n          });\n        }\n      }\n\n      result.set(name, {\n        docstring,\n        declStartIndex: child.startIndex,\n        declColumn: child.startPosition.column,\n        members,\n      });\n    }\n\n    return result;\n  },\n};\n","import type Parser from 'tree-sitter';\nimport type {\n  MergeAdapter,\n  MergeStatement,\n  MergeImport,\n  DocstringInfo,\n  SymbolDocstrings,\n  MemberDocstrings,\n} from './types.js';\nimport { extractUrlFingerprint } from './url-fingerprint.js';\n\nconst PYTHON_URL_FINGERPRINT_CONFIG = {\n  stringNodeTypes: ['string'],\n  contentNodeTypes: ['string_content'],\n  interpolationNodeTypes: ['interpolation'],\n};\n\nfunction extractPythonDeclarationName(node: Parser.SyntaxNode): string | null {\n  if (node.type === 'class_definition' || node.type === 'function_definition') {\n    const nameNode = node.childForFieldName('name');\n    return nameNode?.text ?? null;\n  }\n\n  // Detect `__all__ = [...]` assignments so they get a key and can be deduplicated\n  if (node.type === 'expression_statement') {\n    const firstChild = node.firstNamedChild;\n    if (firstChild?.type === 'assignment') {\n      const left = firstChild.childForFieldName('left');\n      if (left?.type === 'identifier' && left.text === '__all__') {\n        return '__all__';\n      }\n    }\n  }\n\n  return null;\n}\n\nfunction extractPythonDocstring(bodyNode: Parser.SyntaxNode, source: string): DocstringInfo | null {\n  // Python docstrings are the first expression_statement in a body block\n  // where the expression is a string literal\n  for (const child of bodyNode.namedChildren) {\n    if (child.type === 'expression_statement') {\n      const expr = child.firstNamedChild;\n      if (expr?.type === 'string') {\n        const text = source.slice(child.startIndex, child.endIndex);\n        return { text, startIndex: child.startIndex, endIndex: child.endIndex };\n      }\n    }\n    // Only the FIRST statement can be a docstring\n    break;\n  }\n  return null;\n}\n\nfunction collectPrecedingPythonComments(\n  children: Parser.SyntaxNode[],\n  index: number,\n  source: string,\n): DocstringInfo | null {\n  let lastIdx = -1;\n  let firstIdx = -1;\n  for (let k = index - 1; k >= 0; k--) {\n    const prev = children[k];\n    if (prev.type === 'comment') {\n      if (lastIdx === -1) lastIdx = k;\n      firstIdx = k;\n    } else {\n      break;\n    }\n  }\n  if (firstIdx === -1) return null;\n  const first = children[firstIdx];\n  const last = children[lastIdx];\n  return { text: source.slice(first.startIndex, last.endIndex), startIndex: first.startIndex, endIndex: last.endIndex };\n}\n\nexport const pythonMergeAdapter: MergeAdapter = {\n  language: 'python',\n  grammarModule: 'tree-sitter-python',\n  testFilePatterns: [/(?:^|\\/)test_.*\\.py$/, /_test\\.py$/],\n  urlFingerprintConfig: PYTHON_URL_FINGERPRINT_CONFIG,\n  parseStatements(tree, source) {\n    const imports: MergeImport[] = [];\n    const importAnchors: string[] = [];\n    const statements: MergeStatement[] = [];\n\n    for (const child of tree.rootNode.children) {\n      if (child.type === 'comment') continue;\n\n      if (child.type === 'import_statement' || child.type === 'import_from_statement') {\n        const text = source.slice(child.startIndex, child.endIndex);\n        imports.push({ key: text.trim(), text });\n        importAnchors.push(text);\n        continue;\n      }\n\n      const declarationName = extractPythonDeclarationName(child);\n      const kind: MergeStatement['kind'] = declarationName ? 'declaration' : 'other';\n\n      statements.push({\n        key: declarationName,\n        kind,\n        text: source.slice(child.startIndex, child.endIndex),\n      });\n    }\n\n    return { imports, importAnchors, statements };\n  },\n  renderImports(imports) {\n    return imports.map((entry) => entry.text);\n  },\n  extractDocstrings(tree, source) {\n    const result = new Map<string, SymbolDocstrings>();\n    const rootChildren = tree.rootNode.children;\n\n    for (let i = 0; i < rootChildren.length; i++) {\n      const child = rootChildren[i];\n      const name = extractPythonDeclarationName(child);\n      if (!name) continue;\n\n      // Python: class/function docstrings are inside the body, OR use # comments before\n      let docstring: DocstringInfo | null = null;\n      const body = child.childForFieldName('body');\n      if (body) {\n        docstring = extractPythonDocstring(body, source);\n      }\n      // Fallback: check for # comments before the declaration\n      if (!docstring) {\n        docstring = collectPrecedingPythonComments(rootChildren, i, source);\n      }\n\n      const members = new Map<string, MemberDocstrings>();\n\n      // Extract method docstrings for classes\n      if (child.type === 'class_definition' && body) {\n        for (const member of body.namedChildren) {\n          if (member.type !== 'function_definition') continue;\n          const memberName = member.childForFieldName('name')?.text;\n          if (!memberName) continue;\n\n          let memberDoc: DocstringInfo | null = null;\n          const memberBody = member.childForFieldName('body');\n          if (memberBody) {\n            memberDoc = extractPythonDocstring(memberBody, source);\n          }\n\n          members.set(memberName, {\n            docstring: memberDoc,\n            declStartIndex: member.startIndex,\n            declColumn: member.startPosition.column,\n            urlFingerprint: extractUrlFingerprint(member, PYTHON_URL_FINGERPRINT_CONFIG),\n          });\n        }\n      }\n\n      result.set(name, {\n        docstring,\n        declStartIndex: child.startIndex,\n        declColumn: child.startPosition.column,\n        members,\n      });\n    }\n\n    return result;\n  },\n};\n","import type Parser from 'tree-sitter';\nimport type {\n  MergeAdapter,\n  MergeStatement,\n  MergeImport,\n  DocstringInfo,\n  SymbolDocstrings,\n  MemberDocstrings,\n} from './types.js';\nimport { extractUrlFingerprint } from './url-fingerprint.js';\n\nconst RUBY_URL_FINGERPRINT_CONFIG = {\n  stringNodeTypes: ['string'],\n  contentNodeTypes: ['string_content'],\n  interpolationNodeTypes: ['interpolation'],\n};\n\nfunction isRequireCall(node: Parser.SyntaxNode): boolean {\n  if (node.type !== 'call') return false;\n  const method = node.childForFieldName('method');\n  if (!method) return false;\n  return method.text === 'require' || method.text === 'require_relative';\n}\n\nfunction extractRubyDeclarationName(node: Parser.SyntaxNode): string | null {\n  if (node.type !== 'class' && node.type !== 'module') return null;\n  const nameNode = node.childForFieldName('name');\n  return nameNode?.text ?? null;\n}\n\nfunction collectPrecedingRubyComments(\n  children: Parser.SyntaxNode[],\n  index: number,\n  source: string,\n): DocstringInfo | null {\n  let lastIdx = -1;\n  let firstIdx = -1;\n  for (let k = index - 1; k >= 0; k--) {\n    const prev = children[k];\n    const nodeType = (prev as any).grammarType ?? prev.type;\n    if (nodeType === 'comment') {\n      const text = source.slice(prev.startIndex, prev.endIndex);\n      if (text.startsWith('#')) {\n        if (lastIdx === -1) lastIdx = k;\n        firstIdx = k;\n      } else {\n        break;\n      }\n    } else {\n      break;\n    }\n  }\n  if (firstIdx === -1) return null;\n  const first = children[firstIdx];\n  const last = children[lastIdx];\n  return { text: source.slice(first.startIndex, last.endIndex), startIndex: first.startIndex, endIndex: last.endIndex };\n}\n\nexport const rubyMergeAdapter: MergeAdapter = {\n  language: 'ruby',\n  grammarModule: 'tree-sitter-ruby',\n  testFilePatterns: [/_test\\.rb$/, /_spec\\.rb$/],\n  urlFingerprintConfig: RUBY_URL_FINGERPRINT_CONFIG,\n  parseStatements(tree, source) {\n    const imports: MergeImport[] = [];\n    const importAnchors: string[] = [];\n    const statements: MergeStatement[] = [];\n\n    for (const child of tree.rootNode.children) {\n      if (child.type === 'comment') continue;\n\n      const declarationName = extractRubyDeclarationName(child);\n      if (isRequireCall(child)) {\n        const text = source.slice(child.startIndex, child.endIndex);\n        imports.push({ key: text.trim(), text });\n        importAnchors.push(text);\n        continue;\n      }\n\n      const kind: MergeStatement['kind'] = declarationName ? 'declaration' : 'other';\n\n      statements.push({\n        key: declarationName,\n        kind,\n        text: source.slice(child.startIndex, child.endIndex),\n      });\n    }\n\n    return { imports, importAnchors, statements };\n  },\n  renderImports(imports) {\n    return imports.map((entry) => entry.text);\n  },\n  extractDocstrings(tree, source) {\n    const result = new Map<string, SymbolDocstrings>();\n    const rootChildren = tree.rootNode.children;\n\n    for (let i = 0; i < rootChildren.length; i++) {\n      const child = rootChildren[i];\n      const name = extractRubyDeclarationName(child);\n      if (!name) continue;\n\n      const docstring = collectPrecedingRubyComments(rootChildren, i, source);\n      const members = new Map<string, MemberDocstrings>();\n\n      // Ruby class/module bodies: comments may appear in class children\n      // (before body_statement) or in body_statement children (between methods)\n      if (child.type === 'class' || child.type === 'module') {\n        const allClassChildren = child.children;\n        const body = child.childForFieldName('body');\n\n        // Check for comment before body_statement in class children\n        // (docstring for the first method)\n        let firstMethodDocFromClass: DocstringInfo | null = null;\n        for (let j = 0; j < allClassChildren.length; j++) {\n          if (allClassChildren[j] === body || allClassChildren[j].type === 'body_statement') {\n            firstMethodDocFromClass = collectPrecedingRubyComments(allClassChildren, j, source);\n            break;\n          }\n        }\n\n        if (body) {\n          const bodyChildren = body.children;\n          let firstMethodHandled = false;\n          for (let j = 0; j < bodyChildren.length; j++) {\n            const member = bodyChildren[j];\n            if (member.type !== 'method') continue;\n            const memberName = member.childForFieldName('name')?.text;\n            if (!memberName) continue;\n\n            let memberDoc: DocstringInfo | null;\n            if (!firstMethodHandled && firstMethodDocFromClass) {\n              memberDoc = firstMethodDocFromClass;\n              firstMethodHandled = true;\n            } else {\n              memberDoc = collectPrecedingRubyComments(bodyChildren, j, source);\n              firstMethodHandled = true;\n            }\n\n            members.set(memberName, {\n              docstring: memberDoc,\n              declStartIndex: member.startIndex,\n              declColumn: member.startPosition.column,\n              urlFingerprint: extractUrlFingerprint(member, RUBY_URL_FINGERPRINT_CONFIG),\n            });\n          }\n        }\n      }\n\n      result.set(name, {\n        docstring,\n        declStartIndex: child.startIndex,\n        declColumn: child.startPosition.column,\n        members,\n      });\n    }\n\n    return result;\n  },\n};\n","import type Parser from 'tree-sitter';\nimport type { MergeAdapter, MergeStatement, MergeImport, DocstringInfo, SymbolDocstrings } from './types.js';\n\nconst RUST_URL_FINGERPRINT_CONFIG = {\n  stringNodeTypes: ['string_literal'],\n  contentNodeTypes: ['string_content'],\n  interpolationNodeTypes: [],\n};\n\nfunction declarationKey(node: Parser.SyntaxNode): string | null {\n  switch (node.type) {\n    case 'struct_item':\n    case 'enum_item':\n    case 'function_item':\n    case 'trait_item':\n    case 'type_item':\n    case 'const_item': {\n      return node.childForFieldName('name')?.text ?? null;\n    }\n    case 'impl_item': {\n      const typeName = node.childForFieldName('type')?.text ?? 'unknown';\n      const traitName = node.childForFieldName('trait')?.text;\n      return traitName ? `impl:${traitName}->${typeName}` : `impl:${typeName}`;\n    }\n    default:\n      return null;\n  }\n}\n\nfunction collectPrecedingRustDocComments(\n  children: Parser.SyntaxNode[],\n  index: number,\n  source: string,\n): DocstringInfo | null {\n  let lastIdx = -1;\n  let firstIdx = -1;\n  for (let k = index - 1; k >= 0; k--) {\n    const prev = children[k];\n    if (prev.type === 'line_comment') {\n      const text = source.slice(prev.startIndex, prev.endIndex);\n      if (text.startsWith('///')) {\n        if (lastIdx === -1) lastIdx = k;\n        firstIdx = k;\n      } else {\n        break;\n      }\n    } else {\n      break;\n    }\n  }\n  if (firstIdx === -1) return null;\n  const first = children[firstIdx];\n  const last = children[lastIdx];\n  return { text: source.slice(first.startIndex, last.endIndex), startIndex: first.startIndex, endIndex: last.endIndex };\n}\n\nexport const rustMergeAdapter: MergeAdapter = {\n  language: 'rust',\n  grammarModule: 'tree-sitter-rust',\n  testFilePatterns: [/_test\\.rs$/, /(?:^|\\/)tests\\/.*\\.rs$/],\n  urlFingerprintConfig: RUST_URL_FINGERPRINT_CONFIG,\n  parseStatements(tree, source) {\n    const imports: MergeImport[] = [];\n    const importAnchors: string[] = [];\n    const statements: MergeStatement[] = [];\n\n    for (const child of tree.rootNode.children) {\n      if (child.type === 'comment') continue;\n\n      if (child.type === 'use_declaration') {\n        const text = source.slice(child.startIndex, child.endIndex);\n        imports.push({ key: text.trim(), text });\n        importAnchors.push(text);\n        continue;\n      }\n\n      const key = declarationKey(child);\n      statements.push({\n        key,\n        kind: key ? 'declaration' : 'other',\n        text: source.slice(child.startIndex, child.endIndex),\n      });\n    }\n\n    return { imports, importAnchors, statements };\n  },\n  renderImports(imports) {\n    return imports.map((entry) => entry.text);\n  },\n  extractDocstrings(tree, source) {\n    const result = new Map<string, SymbolDocstrings>();\n    const rootChildren = tree.rootNode.children;\n\n    for (let i = 0; i < rootChildren.length; i++) {\n      const child = rootChildren[i];\n      const key = declarationKey(child);\n      if (!key) continue;\n\n      const docstring = collectPrecedingRustDocComments(rootChildren, i, source);\n      result.set(key, {\n        docstring,\n        declStartIndex: child.startIndex,\n        declColumn: child.startPosition.column,\n        members: new Map(),\n      });\n    }\n\n    return result;\n  },\n};\n","import type { MergeAdapter } from './types.js';\nimport { dotnetMergeAdapter } from './dotnet.js';\nimport { elixirMergeAdapter } from './elixir.js';\nimport { goMergeAdapter } from './go.js';\nimport { kotlinMergeAdapter } from './kotlin.js';\nimport { nodeMergeAdapter } from './node.js';\nimport { phpMergeAdapter } from './php.js';\nimport { pythonMergeAdapter } from './python.js';\nimport { rubyMergeAdapter } from './ruby.js';\nimport { rustMergeAdapter } from './rust.js';\n\nconst adapters = new Map<string, MergeAdapter>([\n  ['dotnet', dotnetMergeAdapter],\n  ['elixir', elixirMergeAdapter],\n  ['go', goMergeAdapter],\n  ['kotlin', kotlinMergeAdapter],\n  ['node', nodeMergeAdapter],\n  ['php', phpMergeAdapter],\n  ['python', pythonMergeAdapter],\n  ['ruby', rubyMergeAdapter],\n  ['rust', rustMergeAdapter],\n]);\n\nexport function getMergeAdapter(language: string): MergeAdapter | undefined {\n  return adapters.get(language);\n}\n","/**\n * AST-level file merger using tree-sitter.\n *\n * When generating into a directory that already contains files, the merger\n * parses both the existing and generated content, detects top-level symbols,\n * and only appends symbols that don't already exist. Hand-written code is\n * never modified or removed.\n *\n * Supports any language with a tree-sitter grammar package.\n */\n\nimport Parser from 'tree-sitter';\nimport { getMergeAdapter } from './merge-adapters/index.js';\nimport type { MergeImport, ParsedMergeFile, SymbolDocstrings, UrlFingerprintConfig } from './merge-adapters/types.js';\n\n// Cache parser instances per language\nconst parserCache = new Map<string, Parser>();\n\nimport { safeParse } from '../utils/tree-sitter.js';\n\n// --- @deprecated preservation ---\n\n/**\n * When replacing an existing docstring with a generated one, carry over any\n * `@deprecated` lines from the existing doc that aren't present in the\n * generated doc.  This prevents hand-written deprecation notices from being\n * silently dropped during docstring refresh.\n */\nfunction preserveDeprecatedTags(existingDoc: string, generatedDoc: string): string {\n  // Check if the existing docstring contains @deprecated anywhere\n  if (!existingDoc.includes('@deprecated')) return generatedDoc;\n\n  // If generated doc already has @deprecated, no need to merge\n  if (generatedDoc.includes('@deprecated')) return generatedDoc;\n\n  // Extract the @deprecated content from the existing doc.\n  // Handle both multi-line (`* @deprecated ...`) and one-liner (`/** @deprecated ... */`) formats.\n  const deprecatedParts: string[] = [];\n  for (const line of existingDoc.split('\\n')) {\n    if (/@deprecated\\b/.test(line)) {\n      // Normalize to JSDoc member format: `   * @deprecated ...`\n      const match = line.match(/@deprecated\\b.*/);\n      if (match) {\n        // Strip trailing */ and whitespace (from one-liner JSDoc like `/** @deprecated ... */`)\n        const cleaned = match[0].replace(/\\s*\\*\\/\\s*$/, '');\n        deprecatedParts.push(`   * ${cleaned}`);\n      }\n    }\n  }\n  if (deprecatedParts.length === 0) return generatedDoc;\n\n  // Insert @deprecated lines before the closing */ of the generated doc\n  const closingIdx = generatedDoc.lastIndexOf('*/');\n  if (closingIdx === -1) return generatedDoc;\n  const before = generatedDoc.slice(0, closingIdx);\n  const after = generatedDoc.slice(closingIdx);\n  return before + deprecatedParts.join('\\n') + '\\n ' + after;\n}\n\n// --- @oagen-ignore region helpers ---\n\ninterface IgnoredRegion {\n  startIndex: number;\n  endIndex: number;\n}\n\nfunction findIgnoredRegions(source: string): IgnoredRegion[] {\n  const regions: IgnoredRegion[] = [];\n  const startTag = '@oagen-ignore-start';\n  const endTag = '@oagen-ignore-end';\n  let searchFrom = 0;\n\n  while (true) {\n    const startIdx = source.indexOf(startTag, searchFrom);\n    if (startIdx === -1) break;\n    const endIdx = source.indexOf(endTag, startIdx + startTag.length);\n    if (endIdx === -1) break; // Unclosed — silently ignore\n    regions.push({ startIndex: startIdx, endIndex: endIdx + endTag.length });\n    searchFrom = endIdx + endTag.length;\n  }\n\n  return regions;\n}\n\nfunction buildIgnoredSymbolNames(docstrings: Map<string, SymbolDocstrings>, regions: IgnoredRegion[]): Set<string> {\n  if (regions.length === 0) return new Set();\n  const ignored = new Set<string>();\n  for (const [name, info] of docstrings) {\n    if (regions.some((r) => info.declStartIndex >= r.startIndex && info.declStartIndex <= r.endIndex)) {\n      ignored.add(name);\n    }\n  }\n  return ignored;\n}\n\nfunction clampIndex(value: number, contentLength: number): number {\n  if (!Number.isFinite(value)) return 0;\n  if (value < 0) return 0;\n  if (value > contentLength) return contentLength;\n  return value;\n}\n\n/**\n * Resolve the declaration line start for insertion using the current content,\n * instead of relying on parser column arithmetic. This avoids misplaced inserts\n * when parser columns/offsets drift.\n */\nfunction declarationLineStart(content: string, declStartIndex: number): number {\n  const idx = clampIndex(declStartIndex, content.length);\n  const prevNewline = content.lastIndexOf('\\n', Math.max(0, idx - 1));\n  return prevNewline === -1 ? 0 : prevNewline + 1;\n}\n\n// --- stale managed-member pruning helpers ---\n\n/**\n * Widen a member's byte range so deleting it removes whole lines.\n *\n * The raw range starts at the declaration (or its docstring), which sits after\n * the member's indentation — splicing it out verbatim leaves that indentation\n * glued to the following line. Extends backwards over the indentation and\n * forwards over the trailing newline, then absorbs the blank line the removal\n * would otherwise duplicate (or strand in front of the block's closing brace).\n */\nfunction expandPruneRange(source: string, rawStart: number, rawEnd: number): { start: number; end: number } {\n  let start = rawStart;\n  while (start > 0 && (source[start - 1] === ' ' || source[start - 1] === '\\t')) start--;\n\n  let end = rawEnd;\n  while (end < source.length && (source[end] === ' ' || source[end] === '\\t')) end++;\n  end = skipLineBreak(source, end);\n\n  if (precededByBlankLine(source, start)) {\n    if (startsWithLineBreak(source, end)) {\n      // Blank line on both sides — keep one.\n      end = skipLineBreak(source, end);\n    } else if (/^[ \\t]*\\}/.test(source.slice(end, end + 40))) {\n      // Last member in the block — don't leave the closing brace on its own\n      // after a blank line.\n      start = backOverLineBreak(source, start);\n    }\n  }\n\n  return { start, end };\n}\n\n// Line-break helpers below treat CRLF as one terminator: an SDK checked out with\n// `core.autocrlf` on would otherwise leave a stray `\\r` line behind every prune.\n\nfunction startsWithLineBreak(source: string, idx: number): boolean {\n  return source[idx] === '\\n' || (source[idx] === '\\r' && source[idx + 1] === '\\n');\n}\n\nfunction skipLineBreak(source: string, idx: number): number {\n  let i = idx;\n  if (source[i] === '\\r') i++;\n  return source[i] === '\\n' ? i + 1 : i;\n}\n\nfunction backOverLineBreak(source: string, idx: number): number {\n  let i = idx;\n  if (source[i - 1] === '\\n') i--;\n  if (source[i - 1] === '\\r') i--;\n  return i;\n}\n\n/** Whether the line ending immediately before `idx` (a line start) is empty. */\nfunction precededByBlankLine(source: string, idx: number): boolean {\n  if (idx === 0 || source[idx - 1] !== '\\n') return false;\n  const priorLineEnd = backOverLineBreak(source, idx);\n  return priorLineEnd > 0 && source[priorLineEnd - 1] === '\\n';\n}\n\nfunction referencesIdentifier(source: string, name: string): boolean {\n  return new RegExp(`\\\\b${name.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}\\\\b`).test(source);\n}\n\n/**\n * Blank out comments and string text, preserving offsets and line structure.\n *\n * An identifier lookup over raw source can't tell a live reference from a name\n * that merely survives in prose. That distinction decides whether an import\n * stays: keeping one whose only remaining mention is a KDoc leaves an import of\n * a class the generator no longer emits, which doesn't compile — the very\n * failure the prune exists to prevent.\n *\n * Interpolated expressions are the exception: `\"${Agents.NAME}\"` is code that\n * sits inside a string literal, and masking it would drop an import the file\n * genuinely uses. String extents are masked around those holes, not over them.\n *\n * Grammar node names come from the adapter's `urlFingerprintConfig`, which\n * already inventories exactly these three categories per language. Comments are\n * matched structurally instead — every grammar we support names them `*comment`.\n */\nfunction maskNonCode(tree: Parser.Tree, source: string, config: UrlFingerprintConfig | undefined): string {\n  const stringNodeTypes = new Set(config?.stringNodeTypes ?? []);\n  const interpolationNodeTypes = new Set(config?.interpolationNodeTypes ?? []);\n\n  const spans: [number, number][] = [];\n  const collectStringSpans = (node: Parser.SyntaxNode): void => {\n    // Everything in the literal is prose except the interpolation holes.\n    const holes: [number, number][] = [];\n    const findHoles = (n: Parser.SyntaxNode): void => {\n      if (interpolationNodeTypes.has(n.type)) {\n        holes.push([n.startIndex, n.endIndex]);\n        return;\n      }\n      for (const child of n.children) findHoles(child);\n    };\n    findHoles(node);\n\n    let cursor = node.startIndex;\n    for (const [holeStart, holeEnd] of holes) {\n      if (holeStart > cursor) spans.push([cursor, holeStart]);\n      cursor = holeEnd;\n    }\n    if (cursor < node.endIndex) spans.push([cursor, node.endIndex]);\n  };\n\n  const walk = (node: Parser.SyntaxNode): void => {\n    if (node.type.includes('comment')) {\n      spans.push([node.startIndex, node.endIndex]);\n      return;\n    }\n    if (stringNodeTypes.has(node.type)) {\n      collectStringSpans(node);\n      return;\n    }\n    for (const child of node.children) walk(child);\n  };\n  walk(tree.rootNode);\n  if (spans.length === 0) return source;\n\n  let masked = '';\n  let cursor = 0;\n  for (const [spanStart, spanEnd] of spans) {\n    if (spanStart < cursor) continue;\n    masked += source.slice(cursor, spanStart) + source.slice(spanStart, spanEnd).replace(/[^\\r\\n]/g, ' ');\n    cursor = spanEnd;\n  }\n  return masked + source.slice(cursor);\n}\n\nfunction removeLines(source: string, lines: Set<string>): string {\n  return source\n    .split('\\n')\n    .filter((line) => !lines.has(line.trim()))\n    .join('\\n');\n}\n\n/**\n * Resolve a docstring range by searching for the nearest matching text before\n * the declaration start. Falls back to parser-provided offsets when search fails.\n */\nfunction resolveDocRange(\n  content: string,\n  docText: string,\n  declStartIndex: number,\n  fallbackStart: number,\n  fallbackEnd: number,\n): { start: number; end: number } {\n  const safeDecl = clampIndex(declStartIndex, content.length);\n  const safeFallbackStart = clampIndex(fallbackStart, content.length);\n  const safeFallbackEnd = clampIndex(fallbackEnd, content.length);\n  const found = content.lastIndexOf(docText, safeDecl);\n  if (found !== -1) {\n    return { start: found, end: found + docText.length };\n  }\n  return { start: safeFallbackStart, end: safeFallbackEnd };\n}\n\n/**\n * Check if a tree-sitter grammar is configured for the given language.\n */\nexport function hasGrammar(language: string): boolean {\n  return getMergeAdapter(language) !== undefined;\n}\n\nasync function getParser(language: string): Promise<Parser> {\n  const cached = parserCache.get(language);\n  if (cached) return cached;\n\n  const adapter = getMergeAdapter(language);\n  if (!adapter) {\n    throw new Error(\n      `No tree-sitter grammar configured for language \"${language}\". ` +\n        `Add a merge adapter and install the corresponding tree-sitter grammar package.`,\n    );\n  }\n\n  const mod = await import(adapter.grammarModule);\n  const exported = adapter.resolveGrammar ? adapter.resolveGrammar(mod) : mod;\n  const grammar = (exported as { default?: unknown }).default ?? exported;\n  const parser = new Parser();\n  parser.setLanguage(grammar);\n  parserCache.set(language, parser);\n  return parser;\n}\n\ninterface ParsedSymbols {\n  names: Set<string>;\n  /** Trimmed text of unnamed top-level statements (for text-based dedup) */\n  unnamedTexts: Set<string>;\n}\n\n/**\n * Extract all top-level symbol names (and unnamed statement texts) from source code.\n */\nexport async function extractTopLevelSymbols(source: string, language: string): Promise<ParsedSymbols> {\n  const parser = await getParser(language);\n  const adapter = getMergeAdapter(language);\n  if (!adapter) {\n    throw new Error(`No merge adapter configured for language \"${language}\"`);\n  }\n  if (typeof source !== 'string') {\n    throw new Error(`extractTopLevelSymbols: expected string source, got ${typeof source}`);\n  }\n  const tree = safeParse(parser, source);\n  const names = new Set<string>();\n  const unnamedTexts = new Set<string>();\n  const parsed = adapter.parseStatements(tree, source);\n\n  for (const imp of parsed.imports) {\n    names.add(imp.key);\n  }\n  for (const statement of parsed.statements) {\n    if (statement.key) {\n      names.add(statement.key);\n    } else {\n      unnamedTexts.add(statement.text.trim());\n    }\n  }\n\n  return { names, unnamedTexts };\n}\n\n/** Convenience wrapper that returns only the name set. */\nexport async function extractTopLevelNames(source: string, language: string): Promise<Set<string>> {\n  return (await extractTopLevelSymbols(source, language)).names;\n}\n\n/**\n * Extract top-level statements from generated source with their names\n * and exact text span.\n */\nexport async function extractStatements(source: string, language: string): Promise<ParsedMergeFile> {\n  const parser = await getParser(language);\n  const adapter = getMergeAdapter(language);\n  if (!adapter) {\n    throw new Error(`No merge adapter configured for language \"${language}\"`);\n  }\n  const tree = safeParse(parser, source);\n  return adapter.parseStatements(tree, source);\n}\n\n/**\n * Return a map of top-level class name → { bodyEndLine, bodyEndCol } using\n * tree-sitter.  `bodyEndLine` is 0-based.  For brace-delimited classes the\n * end points at the closing brace line; for indentation-delimited classes\n * it points one past the last line of the class body.\n */\nexport async function extractClassEndLines(\n  source: string,\n  language: string,\n): Promise<Map<string, { bodyEndLine: number }>> {\n  const parser = await getParser(language);\n  const tree = safeParse(parser, source);\n  const map = new Map<string, { bodyEndLine: number }>();\n\n  function processClassNode(node: Parser.SyntaxNode): void {\n    const nameNode =\n      node.childForFieldName('name') ??\n      node.children.find((c) => c.type === 'type_identifier' || c.type === 'identifier');\n    if (!nameNode) return;\n    const name = nameNode.text;\n\n    const body =\n      node.childForFieldName('body') ?? node.children.find((c) => c.type === 'class_body' || c.type === 'body');\n    const endRow = body ? body.endPosition.row : node.endPosition.row;\n    const lastChar = source[body ? body.endIndex - 1 : node.endIndex - 1];\n\n    if (lastChar === '}') {\n      map.set(name, { bodyEndLine: endRow });\n    } else {\n      map.set(name, { bodyEndLine: endRow + 1 });\n    }\n  }\n\n  // Walk the tree recursively. Ruby (and Python) often nest target classes\n  // inside `module Foo` / `class Outer:` containers, so a flat iteration over\n  // root children would miss them.\n  function walk(node: Parser.SyntaxNode): void {\n    if (node.type === 'class' || node.type === 'class_definition' || node.type === 'class_declaration') {\n      processClassNode(node);\n    }\n    if (node.type === 'decorated_definition') {\n      for (const inner of node.namedChildren) {\n        if (inner.type === 'class_definition') processClassNode(inner);\n      }\n    }\n    if (node.type === 'export_statement') {\n      for (const inner of node.namedChildren) {\n        if (inner.type === 'class_declaration') processClassNode(inner);\n      }\n    }\n    for (const child of node.namedChildren) walk(child);\n  }\n  for (const child of tree.rootNode.children) {\n    walk(child);\n  }\n\n  return map;\n}\n\nexport interface MergeResult {\n  content: string;\n  added: number;\n  preserved: number;\n  changed: boolean;\n}\n\n/**\n * Merge generated content into an existing file.\n *\n * - Parses both files with tree-sitter\n * - Detects which top-level symbols already exist\n * - Appends only new symbols\n * - Never modifies or removes existing code\n * - Adds auto-generated header if not present\n */\nexport async function mergeIntoExisting(\n  existingContent: string,\n  generatedContent: string,\n  language: string,\n  header: string,\n): Promise<MergeResult> {\n  const adapter = getMergeAdapter(language);\n  if (!adapter) {\n    throw new Error(`No merge adapter configured for language \"${language}\"`);\n  }\n\n  // Parse existing file once — extract both symbols and statements from the same AST pass\n  const existingStatements = await extractStatements(existingContent, language);\n  const generatedStatements = await extractStatements(generatedContent, language);\n\n  const existingKeys = new Set<string>();\n  const existingUnnamedTexts = new Set<string>();\n  const existingImportKeys = new Set<string>();\n  const existingReexports = new Set<string>();\n  let lastImportEndIndex = -1;\n\n  // Collect import keys AND imported identifiers (to prevent adding declarations\n  // that clash with already-imported names)\n  const existingImportedNames = new Set<string>();\n  for (const imp of existingStatements.imports) {\n    existingImportKeys.add(imp.key);\n    // Extract identifiers from import text: import { Foo, Bar } from '...'\n    const braceMatch = imp.text.match(/\\{([^}]+)\\}/);\n    if (braceMatch) {\n      for (const name of braceMatch[1].split(',')) {\n        const trimmed = name.replace(/\\btype\\b/, '').trim();\n        if (trimmed) existingImportedNames.add(trimmed);\n      }\n    }\n  }\n  for (const anchor of existingStatements.importAnchors) {\n    const linesBefore = existingContent.slice(0, existingContent.indexOf(anchor)).split('\\n').length - 1;\n    const stmtLines = anchor.split('\\n').length;\n    lastImportEndIndex = linesBefore + stmtLines - 1;\n  }\n  if (lastImportEndIndex === -1 && existingStatements.importInsertionAnchor) {\n    const linesBefore =\n      existingContent.slice(0, existingContent.indexOf(existingStatements.importInsertionAnchor)).split('\\n').length -\n      1;\n    const stmtLines = existingStatements.importInsertionAnchor.split('\\n').length;\n    lastImportEndIndex = linesBefore + stmtLines - 1;\n  }\n\n  // Track all names exported by existing statements (both direct exports and\n  // re-export aliases like `export { X as Y }`).  Used to prevent the merger\n  // from appending a re-export that introduces a duplicate exported name.\n  const existingExportedNames = new Set<string>();\n\n  for (const stmt of existingStatements.statements) {\n    if (stmt.kind === 'reexport') {\n      existingReexports.add(adapter.normalizeReexport ? adapter.normalizeReexport(stmt.text.trim()) : stmt.text.trim());\n      // Collect aliased export names from re-exports\n      const braceMatch = stmt.text.match(/\\{([^}]+)\\}/);\n      if (braceMatch) {\n        for (const part of braceMatch[1].split(',')) {\n          const segments = part.trim().split(/\\s+as\\s+/);\n          const exportedName = (segments[1] ?? segments[0]).trim();\n          if (exportedName) existingExportedNames.add(exportedName);\n        }\n      }\n    }\n    if (stmt.key) {\n      existingKeys.add(stmt.key);\n      existingExportedNames.add(stmt.key);\n    } else {\n      existingUnnamedTexts.add(stmt.text.trim());\n    }\n  }\n\n  const headerLine = header.trim();\n\n  const newImports: MergeImport[] = [];\n  const toAppend: string[] = [];\n  let preserved = 0;\n\n  for (const imp of generatedStatements.imports) {\n    if (imp.text.trim() === headerLine) continue;\n    if (existingImportKeys.has(imp.key)) {\n      // The existing file already imports from this module path.\n      // Check if the generated import adds identifiers not present in\n      // the existing import — if so, create a supplemental import with\n      // only the new identifiers.  The supplemental participates in the\n      // usage-based filter (below) so unused identifiers are dropped.\n      const braceMatch = imp.text.match(/\\{([^}]+)\\}/);\n      if (braceMatch) {\n        const names = braceMatch[1]\n          .split(',')\n          .map((n) => n.replace(/\\btype\\b/, '').trim())\n          .filter(Boolean);\n        const newNames = names.filter((n) => !existingImportedNames.has(n) && !existingKeys.has(n));\n        if (newNames.length > 0) {\n          const isTypeImport = imp.text.trimStart().startsWith('import type');\n          const prefix = isTypeImport ? 'import type' : 'import';\n          const sourceMatch = imp.text.match(/from\\s+(['\"][^'\"]+['\"]);?/);\n          if (sourceMatch) {\n            newImports.push({\n              key: imp.key + '#supplemental',\n              text: `${prefix} { ${newNames.join(', ')} } from ${sourceMatch[1]};`,\n            });\n          }\n        }\n      }\n      preserved++;\n      continue;\n    }\n    // Strip out identifiers that are already imported from another path.\n    // This prevents duplicates when the generated file uses a specific path\n    // (e.g., '../interfaces/organization.interface') while the existing file\n    // imports the same names from a barrel (e.g., '../interfaces').\n    const braceMatch = imp.text.match(/\\{([^}]+)\\}/);\n    if (braceMatch) {\n      const names = braceMatch[1]\n        .split(',')\n        .map((n) => n.replace(/\\btype\\b/, '').trim())\n        .filter(Boolean);\n      // Check against both existing imports AND existing top-level declarations\n      const isAlreadyDefined = (n: string) => existingImportedNames.has(n) || existingKeys.has(n);\n      if (names.length > 0 && names.every(isAlreadyDefined)) {\n        preserved++;\n        continue;\n      }\n      // If only SOME identifiers are already defined, strip them out and keep only new ones\n      if (names.some(isAlreadyDefined)) {\n        const newNames = names.filter((n) => !isAlreadyDefined(n));\n        if (newNames.length === 0) {\n          preserved++;\n          continue;\n        }\n        // Rebuild the import with only new identifiers\n        const isTypeImport = imp.text.trimStart().startsWith('import type');\n        const prefix = isTypeImport ? 'import type' : 'import';\n        const sourceMatch = imp.text.match(/from\\s+(['\"][^'\"]+['\"]);?/);\n        if (sourceMatch) {\n          const newText = `${prefix} { ${newNames.join(', ')} } from ${sourceMatch[1]};`;\n          newImports.push({ key: imp.key, text: newText });\n          continue;\n        }\n      }\n    }\n    newImports.push(imp);\n  }\n\n  for (const stmt of generatedStatements.statements) {\n    // Skip the header comment\n    if (stmt.text.trim() === headerLine) continue;\n\n    // Skip re-export statements that duplicate existing re-exports\n    // (e.g., generated uses .js extension but existing doesn't).\n    // Allow genuinely new re-exports through.\n    if (stmt.kind === 'reexport') {\n      const normalizedText = adapter.normalizeReexport ? adapter.normalizeReexport(stmt.text.trim()) : stmt.text.trim();\n      if (existingReexports.has(normalizedText) || (stmt.key !== null && existingKeys.has(stmt.key))) {\n        preserved++;\n        continue;\n      }\n      // Also skip re-exports whose aliased names are already defined as\n      // top-level exports in the existing file (e.g., generated file has\n      // `export { X as deserializeFoo } from '...'` but existing file\n      // already has `export const deserializeFoo = ...`).\n      const braceMatch = stmt.text.match(/\\{([^}]+)\\}/);\n      if (braceMatch) {\n        const exportedNames = braceMatch[1]\n          .split(',')\n          .map((n) => {\n            const parts = n.trim().split(/\\s+as\\s+/);\n            return (parts[1] ?? parts[0]).trim();\n          })\n          .filter(Boolean);\n        if (exportedNames.length > 0 && exportedNames.every((n) => existingExportedNames.has(n))) {\n          preserved++;\n          continue;\n        }\n      }\n    }\n\n    if (stmt.key && (existingKeys.has(stmt.key) || existingImportedNames.has(stmt.key))) {\n      preserved++;\n      continue;\n    }\n\n    if (!stmt.key) {\n      if (existingUnnamedTexts.has(stmt.text.trim())) {\n        preserved++;\n        continue;\n      }\n    }\n\n    toAppend.push(stmt.text);\n  }\n\n  if (newImports.length === 0 && toAppend.length === 0) {\n    // No top-level changes — check for deep merge before returning\n    if (!adapter.extractMembers) {\n      // Still need to check docstring refresh below\n    }\n  }\n\n  let result = existingContent;\n\n  // Append new top-level symbols first (so deep merge can see them)\n  if (toAppend.length > 0) {\n    result = result.trimEnd() + '\\n\\n' + toAppend.join('\\n\\n') + '\\n';\n  }\n\n  // Deep merge pass: add new members to existing symbols\n  // Runs after import/symbol merge so line numbers are based on the updated content\n  let deepAdded = 0;\n  let deepPruned = 0;\n  const insertions: { line: number; text: string }[] = [];\n  const prunedTexts: string[] = [];\n  if (adapter.extractMembers) {\n    const parser = await getParser(language);\n    const resultTree = safeParse(parser, result);\n    const generatedTree = safeParse(parser, generatedContent);\n    const resultSymbols = adapter.extractMembers(resultTree, result);\n    const generatedSymbols = adapter.extractMembers(generatedTree, generatedContent);\n\n    // Build ignored symbol set from @oagen-ignore-start/@oagen-ignore-end regions\n    const existingTree = safeParse(parser, existingContent);\n    const existingDocs = adapter.extractDocstrings(existingTree, existingContent);\n    const deepIgnoredRegions = findIgnoredRegions(existingContent);\n    const deepIgnoredSymbols = buildIgnoredSymbolNames(existingDocs, deepIgnoredRegions);\n\n    // Pass 1: prune stale \"managed\" members (existing members the adapter\n    // recognizes as generator-owned but that no longer appear in the\n    // regenerated content — e.g. accessors whose mount target was remapped).\n    // Done as byte-range deletes before line-based insertions so insertion\n    // line numbers stay valid for the post-prune result.\n    if (adapter.isManagedMember) {\n      const pruneEdits: { start: number; end: number }[] = [];\n      for (const [symbolName, genSymbol] of generatedSymbols) {\n        if (deepIgnoredSymbols.has(symbolName)) continue;\n        const existSymbol = resultSymbols.get(symbolName);\n        if (!existSymbol) continue;\n        const genMemberKeys = new Set(genSymbol.members.map((m) => m.key));\n        for (const existMember of existSymbol.members) {\n          if (genMemberKeys.has(existMember.key)) continue;\n          if (existMember.startIndex === undefined || existMember.endIndex === undefined) continue;\n          if (!adapter.isManagedMember(existMember)) continue;\n          pruneEdits.push({ start: existMember.startIndex, end: existMember.endIndex });\n        }\n      }\n      if (pruneEdits.length > 0) {\n        pruneEdits.sort((a, b) => b.start - a.start);\n        for (const edit of pruneEdits) {\n          const { start, end } = expandPruneRange(result, edit.start, edit.end);\n          prunedTexts.push(result.slice(start, end));\n          result = result.slice(0, start) + result.slice(end);\n        }\n        deepPruned = pruneEdits.length;\n        // Re-extract since byte offsets and line numbers shifted.\n        const reTree = safeParse(parser, result);\n        resultSymbols.clear();\n        for (const [k, v] of adapter.extractMembers(reTree, result)) resultSymbols.set(k, v);\n      }\n    }\n\n    // Pass 2: append new members the regenerated content adds.\n    for (const [symbolName, genSymbol] of generatedSymbols) {\n      if (deepIgnoredSymbols.has(symbolName)) continue;\n      const existSymbol = resultSymbols.get(symbolName);\n      if (!existSymbol) continue; // New symbol — handled by top-level append\n\n      const existingMemberKeys = new Set(existSymbol.members.map((m) => m.key));\n      const newMembers = genSymbol.members.filter((m) => !existingMemberKeys.has(m.key));\n\n      if (newMembers.length > 0) {\n        // Let the adapter decide whether to skip deep merge (e.g., when new members\n        // reference dependencies the existing symbol doesn't provide)\n        if (adapter.shouldSkipDeepMerge?.(symbolName, existingMemberKeys, newMembers)) {\n          continue;\n        }\n\n        const indent = existSymbol.memberIndent ?? '  ';\n        const insertText = newMembers.map((m) => indent + m.text).join('\\n\\n');\n        // Leading blank line separates inserted members from existing ones.\n        insertions.push({ line: existSymbol.bodyEndLine, text: '\\n' + insertText });\n        deepAdded += newMembers.length;\n      }\n    }\n\n    if (insertions.length > 0) {\n      // Apply bottom-up to avoid offset shifting\n      insertions.sort((a, b) => b.line - a.line);\n      const resultLines = result.split('\\n');\n      for (const ins of insertions) {\n        resultLines.splice(ins.line, 0, ins.text);\n      }\n      result = resultLines.join('\\n');\n    }\n  }\n\n  // Insert new imports only when new symbols or members were actually added.\n  // This prevents orphaned imports for generated code that wasn't merged in.\n  // Additionally, filter imports to only include identifiers actually used in the\n  // appended/inserted code — prevents orphaned imports for generated code that\n  // referenced types used in other (non-appended) generated functions.\n  if (newImports.length > 0 && (toAppend.length > 0 || deepAdded > 0)) {\n    // Build text of all new code that was actually added (appended + deep-merged members)\n    const addedParts: string[] = [...toAppend];\n    if (insertions) {\n      for (const ins of insertions) {\n        addedParts.push(ins.text);\n      }\n    }\n    const addedCodeText = addedParts.join('\\n');\n\n    // Filter imports to only identifiers that appear in the added code.\n    // Strip individual unused identifiers from each import rather than\n    // keeping/dropping the entire import — prevents orphaned imports when\n    // a generated import line contains both used and unused identifiers\n    // (e.g., `import { deserializeFoo, serializeFoo }` where only\n    // serializeFoo is used in the appended code).\n    const filteredImports: MergeImport[] = [];\n    for (const imp of newImports) {\n      const braceMatch = imp.text.match(/\\{([^}]+)\\}/);\n      if (!braceMatch) {\n        // Non-destructured import (e.g., default import) — keep as-is\n        filteredImports.push(imp);\n        continue;\n      }\n      const names = braceMatch[1]\n        .split(',')\n        .map((n) => n.replace(/\\btype\\b/, '').trim())\n        .filter(Boolean);\n      const usedNames = names.filter((name) => addedCodeText.includes(name));\n      if (usedNames.length === 0) continue; // Drop entirely\n      if (usedNames.length === names.length) {\n        // All identifiers used — keep original import\n        filteredImports.push(imp);\n      } else {\n        // Rebuild import with only used identifiers\n        const isTypeImport = imp.text.trimStart().startsWith('import type');\n        const prefix = isTypeImport ? 'import type' : 'import';\n        const sourceMatch = imp.text.match(/from\\s+(['\"][^'\"]+['\"]);?/);\n        if (sourceMatch) {\n          filteredImports.push({\n            key: imp.key,\n            text: `${prefix} { ${usedNames.join(', ')} } from ${sourceMatch[1]};`,\n          });\n        } else {\n          filteredImports.push(imp);\n        }\n      }\n    }\n\n    if (filteredImports.length > 0) {\n      const renderedImports = adapter.renderImports\n        ? adapter.renderImports(filteredImports)\n        : filteredImports.map((entry) => entry.text);\n      const lines = result.split('\\n');\n      const insertIdx = lastImportEndIndex + 1;\n      lines.splice(insertIdx, 0, ...renderedImports);\n      result = lines.join('\\n');\n    }\n  }\n\n  // Drop imports the pruned managed members were the last users of. A managed\n  // accessor that leaves the spec takes its service class with it, so keeping\n  // the import is a compile error rather than merely dead code. Runs last so it\n  // sees every insertion — both new members and new imports — and so removing\n  // lines can't shift the line numbers those insertions were computed against.\n  if (prunedTexts.length > 0 && adapter.importedNames) {\n    const prunedText = prunedTexts.join('\\n');\n    // Survival is judged against code only — a class name left behind in a KDoc\n    // is not a use, and treating it as one keeps an unresolvable import.\n    const parser = await getParser(language);\n    const codeOnly = maskNonCode(safeParse(parser, result), result, adapter.urlFingerprintConfig);\n    const orphaned = new Set<string>();\n    for (const imp of existingStatements.imports) {\n      const names = adapter.importedNames(imp);\n      if (names.length === 0) continue;\n      if (!names.some((n) => referencesIdentifier(prunedText, n))) continue;\n      const line = imp.text.trim();\n      const withoutImport = removeLines(codeOnly, new Set([line]));\n      if (names.some((n) => referencesIdentifier(withoutImport, n))) continue;\n      orphaned.add(line);\n    }\n    if (orphaned.size > 0) result = removeLines(result, orphaned);\n  }\n\n  // Docstring refresh pass: update existing docstrings to match generated content\n  let docstringUpdates = 0;\n  {\n    const parser = await getParser(language);\n    const resultTree = safeParse(parser, result);\n    const generatedTree = safeParse(parser, generatedContent);\n    const resultDocs = adapter.extractDocstrings(resultTree, result);\n    const generatedDocs = adapter.extractDocstrings(generatedTree, generatedContent);\n    const docIgnoredRegions = findIgnoredRegions(result);\n    const docIgnoredSymbols = buildIgnoredSymbolNames(resultDocs, docIgnoredRegions);\n\n    const edits: { start: number; end: number; newText: string }[] = [];\n\n    for (const [symbolName, genInfo] of generatedDocs) {\n      const existInfo = resultDocs.get(symbolName);\n      if (!existInfo) continue;\n      if (docIgnoredSymbols.has(symbolName)) continue;\n\n      // Skip header comments being treated as docstrings\n      const genDoc = genInfo.docstring && genInfo.docstring.text.trim() !== headerLine ? genInfo.docstring : null;\n\n      // Top-level docstring\n      if (genDoc) {\n        if (existInfo.docstring) {\n          const isPreserved = existInfo.docstring.text.includes('@oagen-ignore');\n          if (!isPreserved && existInfo.docstring.text !== genDoc.text) {\n            const newText = preserveDeprecatedTags(existInfo.docstring.text, genDoc.text);\n            const range = resolveDocRange(\n              result,\n              existInfo.docstring.text,\n              existInfo.declStartIndex,\n              existInfo.docstring.startIndex,\n              existInfo.docstring.endIndex,\n            );\n            edits.push({\n              start: range.start,\n              end: range.end,\n              newText,\n            });\n            docstringUpdates++;\n          }\n        } else {\n          const lineStart = declarationLineStart(result, existInfo.declStartIndex);\n          const indent = ' '.repeat(existInfo.declColumn);\n          edits.push({\n            start: lineStart,\n            end: lineStart,\n            newText: indent + genDoc.text + '\\n',\n          });\n          docstringUpdates++;\n        }\n      }\n\n      // Member-level docstrings — first pass: match by name\n      const matchedExistMembers = new Set<string>();\n      for (const [memberName, genMember] of genInfo.members) {\n        const existMember = existInfo.members.get(memberName);\n        if (!existMember) continue;\n        matchedExistMembers.add(memberName);\n        if (!genMember.docstring) continue;\n\n        if (existMember.docstring) {\n          const isPreserved = existMember.docstring.text.includes('@oagen-ignore');\n          if (!isPreserved && existMember.docstring.text !== genMember.docstring.text) {\n            const newText = preserveDeprecatedTags(existMember.docstring.text, genMember.docstring.text);\n            const range = resolveDocRange(\n              result,\n              existMember.docstring.text,\n              existMember.declStartIndex,\n              existMember.docstring.startIndex,\n              existMember.docstring.endIndex,\n            );\n            edits.push({\n              start: range.start,\n              end: range.end,\n              newText,\n            });\n            docstringUpdates++;\n          }\n        } else {\n          const lineStart = declarationLineStart(result, existMember.declStartIndex);\n          const indent = ' '.repeat(existMember.declColumn);\n          edits.push({\n            start: lineStart,\n            end: lineStart,\n            newText: indent + genMember.docstring.text + '\\n',\n          });\n          docstringUpdates++;\n        }\n      }\n\n      // Member-level docstrings — second pass: URL fingerprint fallback\n      // Match generated members to existing members by URL pattern when\n      // name-based matching fails (e.g., generated \"find\" vs existing \"getWidget\"\n      // both call this.client.get('/widgets/${id}')).\n      //\n      // Safety: only attempt fingerprint matching when there is exactly ONE\n      // unmatched generated member and ONE unmatched existing member for a\n      // given fingerprint.  When multiple members share the same URL path\n      // (e.g., POST and GET on /authorization/roles), fingerprint matching\n      // is ambiguous and would swap docstrings between methods.\n      const unmatchedGenByFp = new Map<\n        string,\n        { name: string; member: typeof genInfo.members extends Map<string, infer V> ? V : never }[]\n      >();\n      for (const [genName, genMember] of genInfo.members) {\n        if (matchedExistMembers.has(genName)) continue; // name-matched in pass 1 (as an exist member) — skip\n        if (!genMember.docstring || !genMember.urlFingerprint) continue;\n        // Skip if this generated member was already name-matched\n        if (existInfo.members.has(genName)) continue;\n        const bucket = unmatchedGenByFp.get(genMember.urlFingerprint) ?? [];\n        bucket.push({ name: genName, member: genMember });\n        unmatchedGenByFp.set(genMember.urlFingerprint, bucket);\n      }\n      const unmatchedExistByFp = new Map<\n        string,\n        { name: string; member: typeof existInfo.members extends Map<string, infer V> ? V : never }[]\n      >();\n      for (const [existName, existMember] of existInfo.members) {\n        if (matchedExistMembers.has(existName)) continue;\n        if (!existMember.urlFingerprint) continue;\n        const bucket = unmatchedExistByFp.get(existMember.urlFingerprint) ?? [];\n        bucket.push({ name: existName, member: existMember });\n        unmatchedExistByFp.set(existMember.urlFingerprint, bucket);\n      }\n      for (const [fp, genBucket] of unmatchedGenByFp) {\n        if (genBucket.length !== 1) continue; // ambiguous — skip\n        const existBucket = unmatchedExistByFp.get(fp);\n        if (!existBucket || existBucket.length !== 1) continue; // ambiguous — skip\n        const genMember = genBucket[0].member;\n        const existEntry = existBucket[0];\n        const existMember = existEntry.member;\n        if (!genMember.docstring) continue;\n\n        if (existMember.docstring) {\n          const isPreserved = existMember.docstring.text.includes('@oagen-ignore');\n          if (isPreserved) continue;\n          if (existMember.docstring.text !== genMember.docstring.text) {\n            const newText = preserveDeprecatedTags(existMember.docstring.text, genMember.docstring.text);\n            const range = resolveDocRange(\n              result,\n              existMember.docstring.text,\n              existMember.declStartIndex,\n              existMember.docstring.startIndex,\n              existMember.docstring.endIndex,\n            );\n            edits.push({\n              start: range.start,\n              end: range.end,\n              newText,\n            });\n            docstringUpdates++;\n          }\n        } else {\n          const lineStart = declarationLineStart(result, existMember.declStartIndex);\n          const indent = ' '.repeat(existMember.declColumn);\n          edits.push({\n            start: lineStart,\n            end: lineStart,\n            newText: indent + genMember.docstring.text + '\\n',\n          });\n          docstringUpdates++;\n        }\n        matchedExistMembers.add(existEntry.name);\n      }\n    }\n\n    if (edits.length > 0) {\n      edits.sort((a, b) => b.start - a.start);\n      for (const edit of edits) {\n        result = result.slice(0, edit.start) + edit.newText + result.slice(edit.end);\n      }\n    }\n  }\n\n  const importsActuallyAdded =\n    toAppend.length > 0 || deepAdded > 0\n      ? adapter.renderImports\n        ? adapter.renderImports(newImports).length\n        : newImports.length\n      : 0;\n  const topLevelAdded = importsActuallyAdded + toAppend.length;\n  const totalAdded = topLevelAdded + deepAdded;\n\n  if (totalAdded === 0 && docstringUpdates === 0 && deepPruned === 0) {\n    return { content: existingContent, added: 0, preserved, changed: false };\n  }\n\n  return {\n    content: result,\n    added: totalAdded,\n    preserved,\n    changed: true,\n  };\n}\n","/**\n * Deep merge two parsed JSON values.\n *\n * - Objects: recursively merge, preserving existing keys not in generated\n * - Arrays: generated replaces existing entirely (generated owns array contents)\n * - Primitives: generated wins\n */\nexport function deepMergeJson(existing: unknown, generated: unknown): unknown {\n  if (\n    typeof existing === 'object' &&\n    existing !== null &&\n    !Array.isArray(existing) &&\n    typeof generated === 'object' &&\n    generated !== null &&\n    !Array.isArray(generated)\n  ) {\n    const merged: Record<string, unknown> = { ...(existing as Record<string, unknown>) };\n    for (const [key, value] of Object.entries(generated as Record<string, unknown>)) {\n      if (key in merged) {\n        merged[key] = deepMergeJson(merged[key], value);\n      } else {\n        merged[key] = value;\n      }\n    }\n    return merged;\n  }\n\n  // Arrays and primitives: generated wins\n  return generated;\n}\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type { GeneratedFile } from './types.js';\nimport { mergeIntoExisting, hasGrammar, extractClassEndLines, extractStatements } from './merger.js';\nimport { deepMergeJson } from './json-merge.js';\nimport { getMergeAdapter } from './merge-adapters/index.js';\n\nexport interface WriteOptions {\n  /** The emitter language (e.g., \"node\", \"ruby\"). Used to select the\n   *  tree-sitter grammar for AST-level merging. */\n  language?: string;\n  /** The auto-generated file header string. */\n  header?: string;\n}\n\nexport interface WriteResult {\n  written: string[];\n  merged: string[];\n  skipped: string[];\n  identical: string[];\n  ignored: string[];\n}\n\n/**\n * Write generated files to disk with AST-level merging.\n *\n * When a file already exists:\n * - skipIfExists → leave it alone entirely\n * - AST merge available → parse both, append only new symbols\n * - No grammar → skip (never clobber hand-written code)\n *\n * New files are always written in full.\n */\nexport async function writeFiles(\n  files: GeneratedFile[],\n  outputDir: string,\n  options?: WriteOptions,\n): Promise<WriteResult> {\n  const result: WriteResult = {\n    written: [],\n    merged: [],\n    skipped: [],\n    identical: [],\n    ignored: [],\n  };\n  const sorted = [...files].sort((a, b) => a.path.localeCompare(b.path));\n  const language = options?.language;\n  const header = options?.header ?? '';\n\n  for (const file of sorted) {\n    const fullPath = path.join(outputDir, file.path);\n\n    // Repair on-disk casing when an emitter renames a generated file in a\n    // case-only way (e.g. `AuthenticationMfaFailed.kt` → `AuthenticationMFAFailed.kt`\n    // after adding `MFA` to an acronym list). On case-insensitive filesystems\n    // (APFS, NTFS) `writeFile` would otherwise reuse the existing inode and\n    // preserve the stale casing — surfacing later as ktlint/eslint errors.\n    await renameMismatchedCasing(fullPath);\n\n    // Check if file already exists\n    let existingContent: string | null = null;\n    try {\n      existingContent = await fs.readFile(fullPath, 'utf-8');\n    } catch {\n      // File doesn't exist\n    }\n\n    // New file → write in full\n    if (existingContent === null) {\n      await fs.mkdir(path.dirname(fullPath), { recursive: true });\n      await fs.writeFile(fullPath, file.content, 'utf-8');\n      result.written.push(file.path);\n      continue;\n    }\n\n    // skipIfExists → hard skip, no merge (but ensure header is present).\n    // JSON files are skipped from header injection because a leading `//`\n    // comment makes the file invalid JSON.\n    if (file.skipIfExists) {\n      if (header && !existingContent.startsWith(header) && !file.path.endsWith('.json')) {\n        await fs.writeFile(fullPath, header + '\\n\\n' + existingContent, 'utf-8');\n      }\n      result.skipped.push(file.path);\n      continue;\n    }\n\n    // @oagen-ignore-file → skip entirely (existing file opts out of all generation)\n    if (existingContent.includes('@oagen-ignore-file')) {\n      result.ignored.push(file.path);\n      continue;\n    }\n\n    // Don't merge test files into hand-written test files — generated tests are\n    // designed for the standalone generated SDK and will have wrong\n    // signatures/fixtures when merged into hand-written tests.\n    // However, if the existing test file is itself auto-generated (has the oagen\n    // header), allow overwriteExisting to take effect so new methods get coverage.\n    const adapter = language ? getMergeAdapter(language) : undefined;\n    const isTestFile = adapter?.testFilePatterns\n      ? adapter.testFilePatterns.some((p) => p.test(file.path))\n      : isDefaultTestFile(file.path);\n    if (isTestFile) {\n      const isExistingAutoGenerated = header && existingContent.startsWith(header);\n      if (!isExistingAutoGenerated && !file.overwriteExisting) {\n        result.skipped.push(file.path);\n        continue;\n      }\n      // Auto-generated test file or overwriteExisting — fall through to overwriteExisting / identical checks\n    }\n\n    // Identical content → no-op\n    if (existingContent === file.content) {\n      result.identical.push(file.path);\n      continue;\n    }\n\n    // Force overwrite — but preserve any @oagen-ignore regions from existing content\n    if (file.overwriteExisting) {\n      const content =\n        existingContent.includes('@oagen-ignore-start') && language && hasGrammar(language)\n          ? await overwriteWithPreservedRegions(existingContent, file.content, language)\n          : file.content;\n      await fs.writeFile(fullPath, content, 'utf-8');\n      result.written.push(file.path);\n      continue;\n    }\n\n    // JSON files → deep merge preserving existing keys\n    if (file.path.endsWith('.json')) {\n      try {\n        const existingJson = JSON.parse(existingContent);\n        const generatedJson = JSON.parse(file.content);\n        const merged = deepMergeJson(existingJson, generatedJson);\n        const mergedContent = JSON.stringify(merged, null, 2) + '\\n';\n        if (mergedContent === existingContent) {\n          result.identical.push(file.path);\n        } else {\n          await fs.writeFile(fullPath, mergedContent, 'utf-8');\n          result.merged.push(file.path);\n        }\n      } catch {\n        // Parse failed — fall back to overwrite\n        await fs.writeFile(fullPath, file.content, 'utf-8');\n        result.written.push(file.path);\n      }\n      continue;\n    }\n\n    // Source files with grammar → AST-level merge\n    if (language && hasGrammar(language)) {\n      try {\n        const mergeResult = await mergeIntoExisting(existingContent, file.content, language, header);\n\n        // Ensure header is present on merged content\n        let finalContent = mergeResult.content;\n        if (header && !finalContent.startsWith(header)) {\n          finalContent = header + '\\n\\n' + finalContent;\n        }\n\n        if (!mergeResult.changed && finalContent === existingContent) {\n          result.identical.push(file.path);\n          continue;\n        }\n\n        await fs.writeFile(fullPath, finalContent, 'utf-8');\n        result.merged.push(file.path);\n        continue;\n      } catch (err) {\n        // AST merge failed (e.g. tree-sitter grammar ABI issue) — fall back to overwrite\n        console.warn(\n          `[oagen] AST merge failed for ${file.path}, falling back to overwrite.${err instanceof Error ? ` ${err.message}` : ''}`,\n        );\n        await fs.writeFile(fullPath, file.content, 'utf-8');\n        result.written.push(file.path);\n        continue;\n      }\n    }\n\n    // No grammar available → skip to avoid clobbering\n    result.skipped.push(file.path);\n  }\n\n  return result;\n}\n\n/**\n * If a sibling exists with the same name except for letter case, rename it to\n * the requested casing. Uses a two-step rename via a temporary unique name so\n * case-insensitive filesystems (APFS on macOS, NTFS on Windows) actually\n * update the entry — `rename('Foo', 'FOO')` is a no-op on those systems.\n */\nasync function renameMismatchedCasing(fullPath: string): Promise<void> {\n  const dir = path.dirname(fullPath);\n  const target = path.basename(fullPath);\n  let entries: string[];\n  try {\n    entries = await fs.readdir(dir);\n  } catch {\n    return;\n  }\n  if (entries.includes(target)) return;\n  const targetLower = target.toLowerCase();\n  const mismatch = entries.find((e) => e.toLowerCase() === targetLower);\n  if (!mismatch) return;\n  const oldPath = path.join(dir, mismatch);\n  const tempPath = path.join(dir, `.oagen-case-${process.pid}-${Date.now()}-${target}`);\n  await fs.rename(oldPath, tempPath);\n  await fs.rename(tempPath, fullPath);\n}\n\n/** Comprehensive fallback when no adapter is available. */\nfunction isDefaultTestFile(filePath: string): boolean {\n  return (\n    /\\.(spec|test)\\.[jt]sx?$/.test(filePath) ||\n    filePath.endsWith('_test.go') ||\n    filePath.endsWith('_test.rb') ||\n    filePath.endsWith('_spec.rb') ||\n    /(?:^|\\/)test_.*\\.py$/.test(filePath) ||\n    filePath.endsWith('_test.py') ||\n    filePath.endsWith('Test.php') ||\n    filePath.endsWith('_test.rs') ||\n    /(?:^|\\/)tests\\/.*\\.rs$/.test(filePath)\n  );\n}\n\n// --- @oagen-ignore region preservation for overwriteExisting ---\n\n/**\n * Overwrite a file with generated content while preserving\n * `@oagen-ignore-start` / `@oagen-ignore-end` regions (and their\n * required imports) from the existing file.\n *\n * Uses tree-sitter via `extractClassEndLines` to find accurate class\n * boundaries so ignore blocks are inserted at the correct position even\n * when docstrings contain unindented text.\n */\nexport async function overwriteWithPreservedRegions(\n  existingContent: string,\n  generatedContent: string,\n  language: string,\n): Promise<string> {\n  const existingLines = existingContent.split('\\n');\n  const generatedLines = generatedContent.split('\\n');\n\n  // 1. Extract ignore blocks, their containing class, and the anchor line\n  //    (first non-blank line after the block in the existing file).\n  const blocks: { containingClass: string; containingScope: string; lines: string[]; anchor: string }[] = [];\n  for (let i = 0; i < existingLines.length; i++) {\n    if (!existingLines[i].includes('@oagen-ignore-start')) continue;\n    const startIdx = i;\n    while (i < existingLines.length && !existingLines[i].includes('@oagen-ignore-end')) i++;\n    let anchor = '';\n    for (let a = i + 1; a < existingLines.length; a++) {\n      if (existingLines[a].trim()) {\n        anchor = existingLines[a].trimStart();\n        break;\n      }\n    }\n    blocks.push({\n      containingClass: findContainingClass(existingLines, startIdx),\n      containingScope: findContainingDescribeScope(existingLines, startIdx),\n      lines: existingLines.slice(startIdx, i + 1),\n      anchor,\n    });\n  }\n  if (blocks.length === 0) return generatedContent;\n\n  // 2. Splice extra imports from existing into generated.\n  // First strip any `@oagen-ignore-start`..`@oagen-ignore-end` regions the\n  // generator itself emitted: we are about to re-insert the on-disk versions,\n  // and if we left the generator's seed blocks in place we'd end up with two\n  // copies of every ignore block per regeneration (monotonically growing).\n  const result = stripIgnoreRegions(generatedLines);\n  spliceExtraImports(existingLines, result);\n\n  // 3. Build class-end map from the generated content (after import splicing)\n  //    via tree-sitter for accurate boundary detection.\n  const genSource = result.join('\\n');\n  const classEndLines = await extractClassEndLines(genSource, language);\n\n  // 4. Group ignore blocks by class and determine insertion points\n  const blocksByClass = new Map<string, Array<{ containingScope: string; lines: string[]; anchor: string }>>();\n  for (const b of blocks) {\n    if (!blocksByClass.has(b.containingClass)) blocksByClass.set(b.containingClass, []);\n    blocksByClass.get(b.containingClass)!.push({\n      containingScope: b.containingScope,\n      lines: b.lines,\n      anchor: b.anchor,\n    });\n  }\n\n  // 4a. Handle replacement blocks: ignore blocks that redefine their\n  //     containing class replace the generated class entirely.\n  //     Also handles top-level blocks (no containing class) that define\n  //     a class matching one in the generated content.\n  const replacedClasses = new Set<string>();\n  const handledBlockKeys = new Set<string>();\n  const replacements: {\n    startLine: number;\n    endLine: number;\n    content: string[];\n  }[] = [];\n  for (const [className, classBlocks] of blocksByClass) {\n    // Determine the target class for replacement.  When the block has a\n    // containing class, we check if the block redefines that class.  When\n    // there is no containing class (top-level ignore block), we look for a\n    // class definition inside the block that matches a generated class.\n    let targetClass = className;\n    if (!targetClass) {\n      for (const entry of classBlocks) {\n        for (const l of entry.lines) {\n          const m = l.match(/^(?:export\\s+)?class\\s+(\\w+)/);\n          if (m && classEndLines.has(m[1])) {\n            targetClass = m[1];\n            break;\n          }\n        }\n        if (targetClass) break;\n      }\n    }\n    if (!targetClass) continue;\n    const isReplacement = classBlocks.some((entry) =>\n      entry.lines.some((l) => {\n        const m = l.match(/^(?:export\\s+)?class\\s+(\\w+)/);\n        return m?.[1] === targetClass;\n      }),\n    );\n    if (!isReplacement) continue;\n    const info = classEndLines.get(targetClass);\n    if (!info) continue;\n    const startLine = findClassDeclarationStart(result, targetClass, info.bodyEndLine);\n    if (startLine < 0) continue;\n    const content: string[] = [];\n    for (const entry of classBlocks) {\n      content.push('');\n      content.push(...entry.lines);\n    }\n    replacements.push({ startLine, endLine: info.bodyEndLine, content });\n    replacedClasses.add(targetClass);\n    handledBlockKeys.add(className);\n  }\n  // Apply replacements bottom-up to preserve line indices\n  replacements.sort((a, b) => b.startLine - a.startLine);\n  for (const rep of replacements) {\n    result.splice(rep.startLine, rep.endLine - rep.startLine, ...rep.content);\n  }\n\n  // 4a-bis. Top-level declarations protected by ignore regions win over their\n  //         generated counterparts. For each top-level block, drop generated\n  //         declarations (interface/type/const/function/…) whose names are\n  //         declared inside the block; the block content replaces the first\n  //         such declaration in place. Without this, every regeneration\n  //         re-emits a duplicate of each region-protected declaration.\n  let regionDeclarationEdits = 0;\n  {\n    const topLevelEntries = blocksByClass.get('');\n    if (topLevelEntries) {\n      // When 4a already placed the top-level blocks (as part of a class\n      // replacement), only delete generated duplicates — never re-insert.\n      const alreadyPlaced = handledBlockKeys.has('');\n      const remaining: typeof topLevelEntries = [];\n      for (const entry of topLevelEntries) {\n        const outcome = await applyRegionDeclarationOverride(result, entry.lines, language, !alreadyPlaced);\n        if (outcome.edited) regionDeclarationEdits++;\n        if (!alreadyPlaced && !outcome.placed) remaining.push(entry);\n      }\n      if (!alreadyPlaced) {\n        if (remaining.length === 0) {\n          blocksByClass.delete('');\n        } else {\n          blocksByClass.set('', remaining);\n        }\n      }\n    }\n  }\n\n  // 4b. Standard insertions for non-replacement blocks\n  // Rebuild class end lines if replacements shifted line numbers.\n  let effectiveClassEndLines = classEndLines;\n  if (replacedClasses.size > 0 || regionDeclarationEdits > 0) {\n    effectiveClassEndLines = await extractClassEndLines(result.join('\\n'), language);\n  }\n\n  const insertions: { line: number; order: number; content: string[] }[] = [];\n  let insertionOrder = 0;\n  for (const [className, classBlocks] of blocksByClass) {\n    if (handledBlockKeys.has(className) || replacedClasses.has(className)) continue;\n    const info = className ? effectiveClassEndLines.get(className) : undefined;\n\n    // Insert each block individually so each can use its own anchor.\n    for (const entry of classBlocks) {\n      let insertLine: number | undefined;\n\n      // Try anchor-based positioning: find the first line in the generated\n      // file whose trimmed-start content matches the anchor (the first\n      // non-blank line that followed this block in the existing file).\n      // Skip anchors that are just punctuation (braces, etc.) since they\n      // match too many locations. Accept doc comment starters (/** /// #)\n      // as valid anchors since they're structurally meaningful.\n      // Also skip bare language keywords (`end`, `end;`, `end)`) that appear\n      // on many lines and would match the wrong location (e.g. nesting the\n      // block inside a Ruby method body instead of at class level).\n      const isAmbiguousAnchor = /^end[;)\\s]*$/.test(entry.anchor);\n      if (\n        entry.anchor &&\n        !entry.anchor.includes('@oagen-ignore') &&\n        !isAmbiguousAnchor &&\n        /[a-zA-Z]|^\\/\\*|^\\/\\//.test(entry.anchor)\n      ) {\n        for (let li = 0; li < result.length; li++) {\n          if (result[li].trimStart() === entry.anchor) {\n            insertLine = li;\n            break;\n          }\n        }\n      }\n\n      // Fallback: class body end, or for top-level import blocks, after the\n      // last import line (so they stay near the top of the file, not at the\n      // bottom where they'd trigger E402 lint errors).\n      if (insertLine === undefined) {\n        if (info) {\n          insertLine = info.bodyEndLine;\n        } else {\n          const scopeEndLine = entry.containingScope\n            ? findDescribeScopeEndLine(result, entry.containingScope)\n            : undefined;\n          const blockHasImportsFallback = entry.lines.some((l: string) => /^\\s*(import|from)\\s/.test(l));\n          if (scopeEndLine !== undefined) {\n            insertLine = scopeEndLine;\n          } else if (blockHasImportsFallback || hasTopLevelDeclaration(entry.lines)) {\n            let lastImportLine = 0;\n            for (let li = 0; li < result.length; li++) {\n              const trimmed = result[li].trimStart();\n              if (/^(import|from)\\s/.test(trimmed)) lastImportLine = li + 1;\n            }\n            insertLine = lastImportLine;\n          } else {\n            insertLine = result.length;\n          }\n        }\n      }\n\n      // When inserting an import-containing ignore block, move up past\n      // blank separator lines so the block sits flush with surrounding\n      // imports (e.g., Kotlin's ktlint forbids blank lines within import\n      // blocks).\n      const blockHasImports = entry.lines.some((l: string) => /^\\s*import\\s/.test(l));\n      if (blockHasImports) {\n        while (\n          insertLine >= 2 &&\n          result[insertLine - 1]?.trim() === '' &&\n          /^\\s*(import|using|from)\\s/.test(result[insertLine - 2] ?? '')\n        ) {\n          insertLine--;\n        }\n      }\n\n      // Skip the leading blank line when the block is adjacent to imports\n      // or already preceded by a blank line (avoids double-blank-line gaps).\n      // Exclude C# `using` directives — StyleCop SA1515 requires a blank\n      // line before comments, so collapsing breaks the build.\n      const prevLine = insertLine > 0 ? (result[insertLine - 1]?.trimStart() ?? '') : '';\n      const prevIsImport = /^import\\s/.test(prevLine) || /^from\\s/.test(prevLine);\n      const prevIsBlank = insertLine > 0 && prevLine === '';\n      const blockContent = prevIsImport || prevIsBlank ? [...entry.lines] : ['', ...entry.lines];\n      // Add a trailing blank line when the next line is a doc comment\n      // (C# SA1514 requires a blank line before `///` doc headers).\n      const nextLine = result[insertLine]?.trimStart() ?? '';\n      if (nextLine.startsWith('///')) {\n        blockContent.push('');\n      }\n      insertions.push({ line: insertLine, order: insertionOrder++, content: blockContent });\n    }\n  }\n\n  // Apply bottom-up to preserve line indices. Blocks with the same insertion\n  // line must be applied in reverse discovery order because each splice inserts\n  // at the same index; otherwise repeated generation flips their order.\n  insertions.sort((a, b) => b.line - a.line || b.order - a.order);\n  for (const ins of insertions) {\n    result.splice(ins.line, 0, ...ins.content);\n  }\n\n  removeDuplicateImportsCoveredByIgnoreBlocks(result);\n\n  return result.join('\\n');\n}\n\n/**\n * Remove every `@oagen-ignore-start`..`@oagen-ignore-end` region from the\n * supplied lines, collapsing stretches of blank lines that get left behind.\n * Used to drop generator-emitted seed blocks before splicing the on-disk\n * versions back in — otherwise every regen doubles up.\n */\nfunction stripIgnoreRegions(lines: string[]): string[] {\n  const out: string[] = [];\n  let skipping = false;\n  for (const line of lines) {\n    if (!skipping && line.includes('@oagen-ignore-start')) {\n      skipping = true;\n      // Drop a preceding blank line if we have one queued up — otherwise\n      // regen leaves a stray blank line above the spliced-in block.\n      while (out.length > 0 && out[out.length - 1].trim() === '') out.pop();\n      continue;\n    }\n    if (skipping) {\n      if (line.includes('@oagen-ignore-end')) skipping = false;\n      continue;\n    }\n    out.push(line);\n  }\n  return out;\n}\n\n/** Scan backwards from `lineIdx` to find the nearest class declaration name. */\nfunction findContainingClass(lines: string[], lineIdx: number): string {\n  if (/^\\S/.test(lines[lineIdx] ?? '')) return '';\n  // Allow leading whitespace and language-specific modifiers before `class`.\n  // Covers: `public class Foo` (C#/Java), `export class Foo` (TS),\n  // `class Foo` (Python/Ruby), `internal sealed class Foo` (C#), etc.\n  for (let j = lineIdx - 1; j >= 0; j--) {\n    const m = lines[j].match(\n      /^\\s*(?:(?:export|public|private|protected|internal|abstract|sealed|static|partial)\\s+)*class\\s+(\\w+)/,\n    );\n    if (m) return m[1];\n  }\n  return '';\n}\n\nfunction findContainingDescribeScope(lines: string[], lineIdx: number): string {\n  const markerLine = lines[lineIdx] ?? '';\n  if (/^\\S/.test(markerLine)) return '';\n  const markerIndent = leadingSpaces(markerLine);\n  for (let j = lineIdx - 1; j >= 0; j--) {\n    const line = lines[j];\n    const indent = leadingSpaces(line);\n    if (indent >= markerIndent) continue;\n    const match = line.match(/^\\s*describe\\((['\"`])(.+?)\\1\\s*,/);\n    if (match) return match[2];\n    if (/^\\s*(?:export\\s+)?class\\s+\\w+/.test(line)) return '';\n  }\n  return '';\n}\n\nfunction findDescribeScopeEndLine(lines: string[], scopeName: string): number | undefined {\n  for (let i = 0; i < lines.length; i++) {\n    const match = lines[i].match(/^\\s*describe\\((['\"`])(.+?)\\1\\s*,/);\n    if (!match || match[2] !== scopeName) continue;\n\n    let depth = 0;\n    for (let j = i; j < lines.length; j++) {\n      depth += countChar(lines[j], '{');\n      depth -= countChar(lines[j], '}');\n      if (j > i && depth <= 0) return j;\n    }\n  }\n  return undefined;\n}\n\nfunction leadingSpaces(line: string): number {\n  return line.match(/^\\s*/)?.[0].length ?? 0;\n}\n\nfunction countChar(line: string, char: string): number {\n  return [...line].filter((c) => c === char).length;\n}\n\nfunction hasTopLevelDeclaration(lines: string[]): boolean {\n  return lines.some((line) =>\n    /^(?:export\\s+)?(?:interface|type|class|function|const|let|var|enum)\\s+\\w+/.test(line.trim()),\n  );\n}\n\n/**\n * Find the start line of a class declaration (including decorators above it)\n * by scanning backwards from `beforeLine`.\n */\nfunction findClassDeclarationStart(lines: string[], className: string, beforeLine: number): number {\n  // Match optional indentation so Ruby/Python nested classes are found.\n  const classPattern = new RegExp(`^\\\\s*(?:export\\\\s+)?class\\\\s+${className}\\\\b`);\n  for (let i = beforeLine - 1; i >= 0; i--) {\n    if (!classPattern.test(lines[i])) continue;\n    // Scan backward past decorators\n    let start = i;\n    while (start > 0 && /^\\s*@\\w+/.test(lines[start - 1])) {\n      start--;\n    }\n    return start;\n  }\n  return -1;\n}\n\n// --- region-protected top-level declaration overrides ---\n\n/**\n * Conservative top-level declaration matcher for ignore-block content.\n * Matches column-0 declarations like `export interface X`, `type X = …`,\n * `const X = …`, `function X(…)`, `class X` (export optional). Names found\n * here are only acted on when the language's merge adapter also reports a\n * generated top-level statement with the same key, so false positives are\n * filtered by the real parser.\n */\nconst REGION_DECLARATION_PATTERN =\n  /^(?:export\\s+)?(?:declare\\s+)?(?:interface|type|enum|class|const|let|var|async\\s+function|function)\\s+([A-Za-z_$][\\w$]*)/;\n\n/** Extract top-level symbol names declared inside an ignore block's lines. */\nfunction collectRegionDeclaredNames(blockLines: string[]): Set<string> {\n  const names = new Set<string>();\n  for (const line of blockLines) {\n    if (line.includes('@oagen-ignore')) continue;\n    const m = line.match(REGION_DECLARATION_PATTERN);\n    if (m) names.add(m[1]);\n  }\n  return names;\n}\n\n/** Inclusive line ranges of `@oagen-ignore-start`..`@oagen-ignore-end` regions. */\nfunction collectIgnoreRegionLineRanges(lines: string[]): Array<{ start: number; end: number }> {\n  const ranges: Array<{ start: number; end: number }> = [];\n  let start = -1;\n  for (let i = 0; i < lines.length; i++) {\n    if (start === -1 && lines[i].includes('@oagen-ignore-start')) {\n      start = i;\n      continue;\n    }\n    if (start !== -1 && lines[i].includes('@oagen-ignore-end')) {\n      ranges.push({ start, end: i });\n      start = -1;\n    }\n  }\n  return ranges;\n}\n\n/**\n * Walk upward from a declaration's first line over its contiguous comment\n * block (doc comment), so the comment is dropped together with the\n * declaration. Stops at blank lines, region markers, and line 0 (a comment\n * on line 0 is the file header, not a docstring).\n */\nfunction extendOverPrecedingComments(lines: string[], startLine: number): number {\n  let s = startLine;\n  while (s > 1) {\n    const prev = lines[s - 1].trim();\n    if (prev === '' || prev.includes('@oagen-ignore')) break;\n    const isComment = prev.startsWith('//') || prev.startsWith('/*') || prev.startsWith('*') || prev.startsWith('#');\n    if (!isComment) break;\n    s--;\n  }\n  return s;\n}\n\n/**\n * Drop generated top-level declarations that are redeclared inside an ignore\n * block (\"region wins\"). When `placeBlock` is set and at least one generated\n * declaration matches, the block's lines replace the first match in place\n * (mirroring the class-replacement behavior above); any further matches are\n * deleted. Mutates `result` in place.\n *\n * Returns `placed` (the block content now lives in `result` and must not be\n * inserted again) and `edited` (line numbers shifted).\n */\nasync function applyRegionDeclarationOverride(\n  result: string[],\n  blockLines: string[],\n  language: string,\n  placeBlock: boolean,\n): Promise<{ placed: boolean; edited: boolean }> {\n  const names = collectRegionDeclaredNames(blockLines);\n  if (names.size === 0) return { placed: false, edited: false };\n\n  const source = result.join('\\n');\n  let parsed;\n  try {\n    parsed = await extractStatements(source, language);\n  } catch {\n    return { placed: false, edited: false };\n  }\n\n  const regionRanges = collectIgnoreRegionLineRanges(result);\n  const inRegion = (line: number) => regionRanges.some((r) => line >= r.start && line <= r.end);\n\n  const spans: Array<{ start: number; end: number }> = [];\n  for (const stmt of parsed.statements) {\n    if (stmt.kind !== 'declaration' || !stmt.key || !names.has(stmt.key)) continue;\n    // Locate the statement's line span; skip occurrences inside ignore\n    // regions (those ARE the protected content).\n    let idx = source.indexOf(stmt.text);\n    let startLine = -1;\n    while (idx !== -1) {\n      const line = source.slice(0, idx).split('\\n').length - 1;\n      if (!inRegion(line)) {\n        startLine = line;\n        break;\n      }\n      idx = source.indexOf(stmt.text, idx + 1);\n    }\n    if (startLine === -1) continue;\n    const endLine = startLine + stmt.text.split('\\n').length - 1;\n    spans.push({ start: extendOverPrecedingComments(result, startLine), end: endLine });\n  }\n  if (spans.length === 0) return { placed: false, edited: false };\n\n  spans.sort((a, b) => a.start - b.start);\n\n  // Delete all matches after the first, bottom-up to preserve indices.\n  for (let i = spans.length - 1; i >= 1; i--) {\n    const span = spans[i];\n    let deleteCount = span.end - span.start + 1;\n    // Collapse the blank separator the deletion leaves behind.\n    const prevBlank = span.start === 0 || (result[span.start - 1] ?? '').trim() === '';\n    const nextBlank = (result[span.end + 1] ?? '').trim() === '';\n    if (prevBlank && nextBlank && span.end + 1 < result.length) deleteCount++;\n    result.splice(span.start, deleteCount);\n  }\n\n  const first = spans[0];\n  if (placeBlock) {\n    result.splice(first.start, first.end - first.start + 1, ...blockLines);\n    return { placed: true, edited: true };\n  }\n\n  let deleteCount = first.end - first.start + 1;\n  const prevBlank = first.start === 0 || (result[first.start - 1] ?? '').trim() === '';\n  const nextBlank = (result[first.end + 1] ?? '').trim() === '';\n  if (prevBlank && nextBlank && first.end + 1 < result.length) deleteCount++;\n  result.splice(first.start, deleteCount);\n  return { placed: false, edited: true };\n}\n\n/**\n * Collect `from X import Y, Z` identifiers grouped by module, handling\n * both single-line and multiline (parenthesized) forms.\n */\nfunction collectFromImports(lines: string[]): Map<string, Set<string>> {\n  const byModule = new Map<string, Set<string>>();\n  for (let i = 0; i < lines.length; i++) {\n    if (!/^from\\s+/.test(lines[i])) continue;\n\n    let fullText = lines[i];\n    if (fullText.includes('(') && !fullText.includes(')')) {\n      while (i + 1 < lines.length) {\n        i++;\n        fullText += ' ' + lines[i].trim();\n        if (lines[i].includes(')')) break;\n      }\n    }\n\n    const normalized = fullText.replace(/[()]/g, '').replace(/\\s+/g, ' ').trim();\n    const match = normalized.match(/^from\\s+(\\S+)\\s+import\\s+(.+)$/);\n    if (!match) continue;\n\n    const mod = match[1];\n    if (!byModule.has(mod)) byModule.set(mod, new Set());\n    for (const id of match[2]\n      .split(',')\n      .map((s) => s.trim())\n      .filter(Boolean)) {\n      byModule.get(mod)!.add(id);\n    }\n  }\n  return byModule;\n}\n\n/**\n * Collected TypeScript imports grouped by form. Each map keys on the module\n * specifier (e.g. `./foo`, `node:fs`).\n */\ninterface TsImports {\n  /** `import { X, Y } from 'module'` — module → identifier names. */\n  named: Map<string, Set<string>>;\n  /** `import type { X } from 'module'` — module → identifier names. */\n  typeOnly: Map<string, Set<string>>;\n  /** `import X from 'module'` or `import type X from 'module'` — module → name. */\n  defaults: Map<string, string>;\n  /** `import * as X from 'module'` — module → namespace alias name. */\n  namespaces: Map<string, string>;\n  /** `import 'module'` — modules imported for side effects only. */\n  sideEffects: Set<string>;\n}\n\n/**\n * Collect TypeScript imports, grouped by form. Handles single-line and\n * multi-line `{ … }` named imports. Disjoint from Python's `from X import Y`\n * syntax so this can be called in parallel with `collectFromImports`.\n */\nfunction collectTsImports(lines: string[]): TsImports {\n  const out: TsImports = {\n    named: new Map(),\n    typeOnly: new Map(),\n    defaults: new Map(),\n    namespaces: new Map(),\n    sideEffects: new Set(),\n  };\n\n  for (let i = 0; i < lines.length; i++) {\n    const trimmed = lines[i].trim();\n    if (!/^import(\\s|$)/.test(trimmed)) continue;\n\n    // Accumulate multi-line `{ … }` imports.\n    let fullText = lines[i];\n    if (fullText.includes('{') && !fullText.includes('}')) {\n      while (i + 1 < lines.length) {\n        i++;\n        fullText += ' ' + lines[i].trim();\n        if (lines[i].includes('}')) break;\n      }\n    }\n\n    const normalized = fullText.replace(/\\s+/g, ' ').trim().replace(/;\\s*$/, '');\n\n    // `import 'module'`\n    let m = normalized.match(/^import\\s+['\"]([^'\"]+)['\"]$/);\n    if (m) {\n      out.sideEffects.add(m[1]);\n      continue;\n    }\n\n    // `import * as X from 'module'`\n    m = normalized.match(/^import\\s+\\*\\s+as\\s+(\\w+)\\s+from\\s+['\"]([^'\"]+)['\"]$/);\n    if (m) {\n      out.namespaces.set(m[2], m[1]);\n      continue;\n    }\n\n    // `import [Default,] { X, Y as Z } from 'module'` or `import type { X } from 'module'`\n    m = normalized.match(/^import\\s+(type\\s+)?(?:(\\w+)\\s*,\\s*)?\\{\\s*([^}]*)\\s*\\}\\s+from\\s+['\"]([^'\"]+)['\"]$/);\n    if (m) {\n      const isTypeOnly = !!m[1];\n      const defaultName = m[2];\n      const namesRaw = m[3];\n      const mod = m[4];\n      if (defaultName) out.defaults.set(mod, defaultName);\n      const names = namesRaw\n        .split(',')\n        .map((s) => s.trim().replace(/\\s+as\\s+\\w+$/, ''))\n        .filter(Boolean);\n      for (const rawName of names) {\n        const isInlineTypeOnly = rawName.startsWith('type ');\n        const name = rawName.replace(/^type\\s+/, '');\n        const target = isTypeOnly || isInlineTypeOnly ? out.typeOnly : out.named;\n        if (!target.has(mod)) target.set(mod, new Set());\n        target.get(mod)!.add(name);\n      }\n      continue;\n    }\n\n    // `import X from 'module'` or `import type X from 'module'`\n    m = normalized.match(/^import\\s+(?:type\\s+)?(\\w+)\\s+from\\s+['\"]([^'\"]+)['\"]$/);\n    if (m) {\n      out.defaults.set(m[2], m[1]);\n      continue;\n    }\n  }\n\n  return out;\n}\n\n/**\n * Remove the given symbols from generated `import type` bindings, in place.\n *\n * Called when an existing *value* import for the same symbol is being spliced\n * back into the file. A value import satisfies both runtime and type uses, so\n * leaving the generated `import type { X }` would re-declare `X` (TS2300\n * duplicate identifier). Callers guarantee every symbol here is absent from\n * generated *value* imports, so each occurrence is type-only and safe to drop.\n *\n * Handles whole-line `import type { … }` and inline `import { …, type X }`,\n * single- or multi-line. A statement whose bindings all get stripped is\n * removed entirely.\n */\nfunction dropGeneratedTypeOnlyBindings(resultLines: string[], symbols: Set<string>): void {\n  if (symbols.size === 0) return;\n  const out: string[] = [];\n  for (let i = 0; i < resultLines.length; i++) {\n    const line = resultLines[i];\n    const trimmed = line.trim();\n    // Only named imports (with a brace) can carry the symbols we strip.\n    if (!/^import\\b/.test(trimmed) || !trimmed.includes('{')) {\n      out.push(line);\n      continue;\n    }\n    // Gather the full (possibly multi-line) `{ … }` statement.\n    const span = [line];\n    while (!span.join(' ').includes('}') && i + 1 < resultLines.length) {\n      i++;\n      span.push(resultLines[i]);\n    }\n    const normalized = span.join(' ').replace(/\\s+/g, ' ').trim().replace(/;\\s*$/, '');\n    const m = normalized.match(/^import\\s+(type\\s+)?(?:(\\w+)\\s*,\\s*)?\\{\\s*([^}]*)\\s*\\}\\s+from\\s+(['\"][^'\"]+['\"])$/);\n    if (!m) {\n      for (const s of span) out.push(s);\n      continue;\n    }\n    const isTypeOnly = !!m[1];\n    const defaultName = m[2];\n    const items = m[3]\n      .split(',')\n      .map((s) => s.trim())\n      .filter(Boolean);\n    const modQuoted = m[4];\n    const kept = items.filter((raw) => {\n      const isTypeBinding = isTypeOnly || raw.startsWith('type ');\n      const bare = raw.replace(/^type\\s+/, '');\n      return !(isTypeBinding && symbols.has(bare));\n    });\n    if (kept.length === items.length) {\n      // Nothing stripped — preserve the original lines verbatim.\n      for (const s of span) out.push(s);\n      continue;\n    }\n    if (kept.length === 0 && !defaultName) continue; // statement fully emptied\n    const lead = line.match(/^(\\s*)/)?.[1] ?? '';\n    const prefix = isTypeOnly ? 'import type ' : 'import ';\n    const defaultPart = defaultName ? `${defaultName}, ` : '';\n    out.push(`${lead}${prefix}${defaultPart}{ ${kept.join(', ')} } from ${modQuoted};`);\n  }\n  resultLines.splice(0, resultLines.length, ...out);\n}\n\n/**\n * Add imports from the existing file that are absent from the generated\n * result. Handles:\n *\n * - Python: `import X` and `from X import Y`\n * - TypeScript: `import { X } from 'module'`, `import type { X } from 'module'`,\n *   `import X from 'module'`, `import * as X from 'module'`, `import 'module'`\n * - PHP: `use Foo\\Bar;` and `use Foo\\Bar as Baz;` (namespace-qualified only)\n * - Ruby: `require '…'` and `require_relative '…'`\n *\n * Mutates `resultLines` in place.\n */\nfunction filterOutIgnoreRegions(lines: string[]): string[] {\n  const out: string[] = [];\n  let skipping = false;\n  for (const line of lines) {\n    if (!skipping && line.includes('@oagen-ignore-start')) {\n      skipping = true;\n      continue;\n    }\n    if (skipping) {\n      if (line.includes('@oagen-ignore-end')) skipping = false;\n      continue;\n    }\n    out.push(line);\n  }\n  return out;\n}\n\nfunction collectIgnoreRegionUsageText(lines: string[]): string {\n  const out: string[] = [];\n  let skipping = false;\n  for (const line of lines) {\n    if (!skipping && line.includes('@oagen-ignore-start')) {\n      skipping = true;\n      continue;\n    }\n    if (!skipping) continue;\n    if (/^\\s*(import|from)\\s/.test(line)) continue;\n    out.push(line);\n    if (line.includes('@oagen-ignore-end')) skipping = false;\n  }\n  return out.join('\\n');\n}\n\nfunction removeDuplicateImportsCoveredByIgnoreBlocks(lines: string[]): void {\n  const ignoredImports = new Set<string>();\n  const importStatements = collectImportStatements(lines);\n  for (const stmt of importStatements) {\n    if (stmt.inIgnore) ignoredImports.add(normalizeImportStatement(stmt.lines));\n  }\n  if (ignoredImports.size === 0) return;\n\n  for (const stmt of [...importStatements].reverse()) {\n    if (stmt.inIgnore) continue;\n    if (ignoredImports.has(normalizeImportStatement(stmt.lines))) {\n      lines.splice(stmt.start, stmt.end - stmt.start + 1);\n    }\n  }\n}\n\nfunction collectImportStatements(\n  lines: string[],\n): Array<{ start: number; end: number; lines: string[]; inIgnore: boolean }> {\n  const statements: Array<{ start: number; end: number; lines: string[]; inIgnore: boolean }> = [];\n  let inIgnore = false;\n  for (let i = 0; i < lines.length; i++) {\n    const line = lines[i];\n    if (!inIgnore && line.includes('@oagen-ignore-start')) {\n      inIgnore = true;\n      continue;\n    }\n    if (inIgnore && line.includes('@oagen-ignore-end')) {\n      inIgnore = false;\n      continue;\n    }\n    if (!isImportLine(line)) continue;\n\n    const start = i;\n    let end = i;\n    const statementLines = [line];\n    const opens = (line.match(/[({]/g) ?? []).length;\n    const closes = (line.match(/[)}]/g) ?? []).length;\n    if (opens > closes) {\n      while (end + 1 < lines.length) {\n        end++;\n        statementLines.push(lines[end]);\n        if ((lines[end].match(/[)}]/g) ?? []).length > 0 && /\\bfrom\\b/.test(lines[end])) break;\n      }\n      i = end;\n    }\n    statements.push({ start, end, lines: statementLines, inIgnore });\n  }\n  return statements;\n}\n\nfunction normalizeImportStatement(lines: string[]): string {\n  return lines.join('\\n').replace(/,\\s*}/g, ' }').replace(/\\s+/g, ' ').trim();\n}\n\nfunction isImportLine(line: string): boolean {\n  const trimmed = line.trim();\n  return (\n    /^import(\\s|$)/.test(trimmed) ||\n    /^from\\s+/.test(trimmed) ||\n    /^use\\s+[\\w\\\\]/.test(trimmed) ||\n    /^require(_relative)?\\s+['\"]/.test(trimmed)\n  );\n}\n\nfunction identifierUsed(source: string, identifier: string): boolean {\n  return new RegExp(`\\\\b${identifier.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}\\\\b`).test(source);\n}\n\nfunction spliceExtraImports(existingLines: string[], resultLines: string[]): void {\n  // Imports inside @oagen-ignore regions are converted into normal imports\n  // only when non-import ignore content still references them. This prevents\n  // stale import-only ignore blocks from creating duplicate or unused imports.\n  const existingOutsideIgnore = filterOutIgnoreRegions(existingLines);\n  const ignoreRegionText = collectIgnoreRegionUsageText(existingLines);\n\n  // Python-style `import hashlib`. Excludes TS forms like `import X from '…'`\n  // (have a `from` clause) and TS multi-line type imports whose first line is\n  // `import type {` (have a brace) — both are handled by the TS collector\n  // below.\n  const isPythonSimpleImport = (l: string) => /^import\\s+\\w/.test(l) && !/\\sfrom\\s/.test(l) && !/[{}]/.test(l);\n\n  // Simple imports (import hashlib, import json, …)\n  const existingSimple = new Set(existingOutsideIgnore.filter(isPythonSimpleImport).map((l) => l.trim()));\n  const generatedSimple = new Set(resultLines.filter(isPythonSimpleImport).map((l) => l.trim()));\n  const extraSimple = [...existingSimple].filter((l) => !generatedSimple.has(l));\n\n  // From-imports — compare by module and find extra identifiers\n  const existingFrom = collectFromImports(existingOutsideIgnore);\n  const generatedFrom = collectFromImports(resultLines);\n\n  // Build a set of all identifiers imported by the generated file (across all modules)\n  // so we can detect when an existing barrel import's identifiers are covered by\n  // more-specific generated imports (e.g., `from x.y import Z` covers `from x import Z`).\n  const allGeneratedIds = new Set<string>();\n  for (const ids of generatedFrom.values()) {\n    for (const id of ids) allGeneratedIds.add(id);\n  }\n\n  const extraFromLines: string[] = [];\n  for (const [mod, existIds] of existingFrom) {\n    const genIds = generatedFrom.get(mod);\n    if (!genIds) {\n      // The exact module isn't in the generated file — but check whether every\n      // identifier is already imported from a different (e.g., more-specific) module.\n      const extra = [...existIds].filter((id) => !allGeneratedIds.has(id));\n      if (extra.length > 0) {\n        extraFromLines.push(`from ${mod} import ${extra.join(', ')}`);\n      }\n    } else {\n      const extra = [...existIds].filter((id) => !genIds.has(id) && !allGeneratedIds.has(id));\n      if (extra.length > 0) {\n        extraFromLines.push(`from ${mod} import ${extra.join(', ')}`);\n      }\n    }\n  }\n\n  // TypeScript imports.\n  const existingTs = collectTsImports(existingOutsideIgnore);\n  const generatedTs = collectTsImports(resultLines);\n  const extraTsLines: string[] = [];\n\n  // Bindings the generated file imports anywhere, split by capability.\n  //\n  // `allGeneratedTsIds` — every binding regardless of module. The generator\n  // frequently imports a symbol from a concrete file\n  // (`./interfaces/connection.interface`) while the existing hand-written file\n  // imported the same symbol from a barrel (`./interfaces`). Splicing the\n  // barrel form back in would re-declare the binding (TS2300 duplicate\n  // identifier), so a symbol already in scope satisfies a *type* use and is\n  // never re-imported as a type even from a different specifier.\n  //\n  // `generatedValueIds` — only runtime-capable bindings (named / default /\n  // namespace, never `import type`). A *value* use is satisfied only by one of\n  // these: an `import type` binding is erased at compile time and cannot back a\n  // runtime reference inside a preserved region. So a generated `import type`\n  // must NOT suppress an existing value import of the same symbol.\n  const allGeneratedTsIds = new Set<string>();\n  const generatedValueIds = new Set<string>();\n  for (const ids of generatedTs.named.values())\n    for (const id of ids) {\n      allGeneratedTsIds.add(id);\n      generatedValueIds.add(id);\n    }\n  for (const ids of generatedTs.typeOnly.values()) for (const id of ids) allGeneratedTsIds.add(id);\n  for (const name of generatedTs.defaults.values()) {\n    allGeneratedTsIds.add(name);\n    generatedValueIds.add(name);\n  }\n  for (const name of generatedTs.namespaces.values()) {\n    allGeneratedTsIds.add(name);\n    generatedValueIds.add(name);\n  }\n\n  // Symbols the generated file imports type-only that we are nonetheless\n  // re-splicing as value imports (because a preserved region needs the runtime\n  // binding). The spliced value import also covers the type use, so the\n  // generated `import type` for the symbol must be dropped or the two collide\n  // (TS2300). Collected during the loops below, applied just before splicing.\n  const reclaimedValueIds = new Set<string>();\n  const generatedHasValue = (id: string): boolean => generatedValueIds.has(id);\n  const generatedHasTypeOnly = (id: string): boolean => allGeneratedTsIds.has(id) && !generatedValueIds.has(id);\n\n  for (const mod of existingTs.sideEffects) {\n    if (!generatedTs.sideEffects.has(mod)) extraTsLines.push(`import '${mod}';`);\n  }\n  for (const [mod, name] of existingTs.defaults) {\n    if (generatedTs.defaults.has(mod)) continue;\n    if (!identifierUsed(ignoreRegionText, name)) continue;\n    if (generatedHasValue(name)) continue;\n    if (generatedHasTypeOnly(name)) reclaimedValueIds.add(name);\n    extraTsLines.push(`import ${name} from '${mod}';`);\n  }\n  for (const [mod, name] of existingTs.namespaces) {\n    if (!identifierUsed(ignoreRegionText, name)) continue;\n    if (generatedHasValue(name)) continue;\n    if (generatedTs.namespaces.has(mod)) continue;\n    if (generatedHasTypeOnly(name)) reclaimedValueIds.add(name);\n    extraTsLines.push(`import * as ${name} from '${mod}';`);\n  }\n  for (const [mod, existIds] of existingTs.named) {\n    const extra = [...existIds].filter((id) => !generatedHasValue(id) && identifierUsed(ignoreRegionText, id));\n    for (const id of extra) if (generatedHasTypeOnly(id)) reclaimedValueIds.add(id);\n    if (extra.length > 0) extraTsLines.push(`import { ${extra.join(', ')} } from '${mod}';`);\n  }\n  for (const [mod, existIds] of existingTs.typeOnly) {\n    const extra = [...existIds].filter((id) => !allGeneratedTsIds.has(id) && identifierUsed(ignoreRegionText, id));\n    if (extra.length > 0) extraTsLines.push(`import type { ${extra.join(', ')} } from '${mod}';`);\n  }\n\n  // Drop reclaimed symbols from generated `import type` lines so the value\n  // imports spliced above do not duplicate them.\n  dropGeneratedTypeOnlyBindings(resultLines, reclaimedValueIds);\n\n  // PHP `use Foo\\Bar;` and `use Foo\\Bar as Baz;` — namespace-qualified only\n  // (a backslash anywhere in the path) so this doesn't mistakenly hoist\n  // single-segment in-class trait references like `use TraitName;`.\n  const isPhpUseImport = (l: string) => /^use\\s+[\\w\\\\]+\\\\[\\w\\\\]*(\\s+as\\s+\\w+)?\\s*;?$/.test(l);\n  const existingPhpUse = new Set(existingOutsideIgnore.filter(isPhpUseImport).map((l) => l.trim()));\n  const generatedPhpUse = new Set(resultLines.filter(isPhpUseImport).map((l) => l.trim()));\n  const extraPhpUse = [...existingPhpUse].filter((l) => !generatedPhpUse.has(l));\n\n  // Ruby `require '...'` and `require_relative '...'`. Dedupe by (kind, path)\n  // so quote style differs without producing duplicates — e.g. when the\n  // emitter writes `require 'json'` but a Ruby formatter has rewritten the\n  // on-disk copy to `require \"json\"`.\n  const rubyRequireRe = /^(require(?:_relative)?)\\s+['\"]([^'\"]+)['\"]\\s*$/;\n  const rubyRequireKey = (l: string): string | undefined => {\n    const m = l.trim().match(rubyRequireRe);\n    return m ? `${m[1]}\\t${m[2]}` : undefined;\n  };\n  const generatedRubyRequireKeys = new Set<string>();\n  for (const l of resultLines) {\n    const key = rubyRequireKey(l);\n    if (key) generatedRubyRequireKeys.add(key);\n  }\n  const seenExistingKeys = new Set<string>();\n  const extraRubyRequire: string[] = [];\n  for (const l of existingOutsideIgnore) {\n    const key = rubyRequireKey(l);\n    if (!key) continue;\n    if (generatedRubyRequireKeys.has(key)) continue;\n    if (seenExistingKeys.has(key)) continue;\n    seenExistingKeys.add(key);\n    extraRubyRequire.push(l.trim());\n  }\n\n  const allExtra = [...extraSimple, ...extraFromLines, ...extraTsLines, ...extraPhpUse, ...extraRubyRequire];\n  if (allExtra.length === 0) return;\n\n  // Find last import line in resultLines (accounting for multiline imports).\n  // Recognizes Python (`from X import Y`, `import X`), TS (`import …`), PHP\n  // (`use …`), and Ruby (`require`, `require_relative`).\n  const isImportStart = (l: string) =>\n    /^\\s*import(\\s|$)/.test(l) ||\n    /^from\\s+/.test(l) ||\n    /^\\s*use\\s+[\\w\\\\]/.test(l) ||\n    /^\\s*require(_relative)?\\s+['\"]/.test(l);\n  let lastImportIdx = -1;\n  for (let i = 0; i < resultLines.length; i++) {\n    if (!isImportStart(resultLines[i])) continue;\n    lastImportIdx = i;\n    const opens = (resultLines[i].match(/[({]/g) ?? []).length;\n    const closes = (resultLines[i].match(/[)}]/g) ?? []).length;\n    if (opens > closes) {\n      while (i + 1 < resultLines.length) {\n        i++;\n        lastImportIdx = i;\n        if ((resultLines[i].match(/[)}]/g) ?? []).length > 0) break;\n      }\n    }\n  }\n\n  if (lastImportIdx >= 0) {\n    resultLines.splice(lastImportIdx + 1, 0, ...allExtra);\n    return;\n  }\n\n  // No import survived in the generated file (e.g. its only import was a\n  // type-only line reclaimed above). Insert after any leading comment header\n  // so the spliced imports still land at the top of the file.\n  let insertAt = 0;\n  let inBlockComment = false;\n  for (let i = 0; i < resultLines.length; i++) {\n    const t = resultLines[i].trim();\n    if (inBlockComment) {\n      insertAt = i + 1;\n      if (t.includes('*/')) inBlockComment = false;\n      continue;\n    }\n    if (t.startsWith('//')) {\n      insertAt = i + 1;\n      continue;\n    }\n    if (t.startsWith('/*')) {\n      insertAt = i + 1;\n      inBlockComment = !t.includes('*/');\n      continue;\n    }\n    break; // first blank or code line — stop here\n  }\n  resultLines.splice(insertAt, 0, ...allExtra);\n}\n","import { resolveMountTarget } from '../ir/operation-hints.js';\nimport type { ApiSpec } from '../ir/types.js';\n\n/**\n * Validate a `--services` selection and return it as a set of POST-MOUNT service\n * names for emitters to scope on.\n *\n * Scoped generation does NOT filter the IR: model placement, dedup/aliasing, and\n * shared-schema decisions are global computations over the full service/model set\n * (filtering them churns shared `common/` files). Instead the full spec flows to\n * the emitters unchanged and this set is passed as `ctx.scopedServices`; each\n * emitter gates only its per-service resource/test emission on it.\n *\n * Matching is on the POST-MOUNT name. Mount resolution never mutates\n * `spec.services` — the post-mount target lives on `ResolvedOperation.mountOn`\n * (`mountOn = hint?.mountOn ?? resolveMountTarget(service.name, mountRules)`) — so\n * the post-mount name of a source service is derived here with the same\n * `resolveMountTarget` (exact rules and trailing-`*` prefix rules, longest\n * prefix wins). Selecting a target (e.g.\n * `DirectorySync`) is valid because every source tag that mounts into it\n * (`DirectoryUsers`, `DirectoryGroups`, …) shares that post-mount name, and the\n * emitters group resources by mount, so all siblings emit together.\n *\n * @param spec - The parsed API spec (never mutated; never filtered).\n * @param selected - Post-mount service names from `--services` (normalized/trimmed).\n * @param mountRules - Source-service-name (exact or trailing-`*` prefix pattern)\n *   → post-mount-target mappings.\n * @returns The validated selection as a `Set` of post-mount names.\n * @throws A `ConfigError` listing valid post-mount names when a selection is\n *   unknown — scoped generation never silently emits the wrong set.\n */\n/**\n * Canonicalize a service name to a casing/separator-insensitive key so that\n * `MultiFactorAuth` (post-mount IR name), `multi_factor_auth` (snake-cased\n * manifest record), and `multiFactorAuth` (camel-cased manifest record) all\n * collapse to `multifactorauth`. Used to match a spec service against the\n * services a prior manifest recorded as already on disk, where the casing of\n * the recorded `service` field varies per emitter.\n */\nexport function canonicalServiceKey(name: string): string {\n  return name.toLowerCase().replace(/[^a-z0-9]/g, '');\n}\n\nexport function resolveScopedServices(\n  spec: ApiSpec,\n  selected: string[],\n  mountRules?: Record<string, string>,\n): Set<string> {\n  const mounts = mountRules ?? {};\n  const validPostMount = new Set(spec.services.map((s) => resolveMountTarget(s.name, mounts)));\n  const selectedSet = new Set(selected);\n\n  const unknown = [...selectedSet].filter((s) => !validPostMount.has(s));\n  if (unknown.length > 0) {\n    const err = new Error(\n      `Unknown --services: ${unknown.sort().join(', ')}. ` +\n        `Valid post-mount services: ${[...validPostMount].sort().join(', ')}`,\n    );\n    err.name = 'ConfigError';\n    throw err;\n  }\n\n  return selectedSet;\n}\n","import type { ApiSpec, Model, TypeRef, Service, Operation, Webhook } from '../ir/types.js';\nimport {\n  walkTypeRef,\n  collectResponseHeaders,\n  collectModelTypeRefs,\n  collectRequestBodyTypes,\n  collectResponseBodyTypes,\n  collectWebhookTypeRefs,\n} from '../ir/types.js';\nimport type { OperationHint, OperationNaming } from '../ir/operation-hints.js';\nimport { resolveOperations } from '../ir/operation-hints.js';\nimport type { Emitter, EmitterContext, GeneratedFile, OperationsMap } from './types.js';\nimport type { ApiSurface, OverlayLookup } from '../compat/types.js';\nimport { toSnakeCase } from '../utils/naming.js';\nimport { canonicalServiceKey } from './scoped-services.js';\n\nexport function buildEmitterContext(\n  spec: ApiSpec,\n  options: {\n    namespace: string;\n    outputDir: string;\n    apiSurface?: ApiSurface;\n    overlayLookup?: OverlayLookup;\n    operationHints?: Record<string, OperationHint>;\n    mountRules?: Record<string, string>;\n    operationNaming?: OperationNaming;\n    modelHints?: Record<string, string>;\n    emitterOptions?: Record<string, unknown>;\n    target?: string;\n    priorTargetManifestPaths?: Set<string>;\n    scopedServices?: Set<string>;\n    presentServiceKeys?: Set<string>;\n  },\n): EmitterContext {\n  const resolvedOperations = resolveOperations(\n    spec,\n    options.operationHints,\n    options.mountRules,\n    options.operationNaming,\n  );\n\n  // In a scoped run, derive the model/enum allow-lists = names reachable from the\n  // SELECTED source services only (those whose post-mount target is selected).\n  // Emitters write a model/enum FILE only when it is in these sets, so a\n  // non-selected service's models/enums are left byte-for-byte untouched — even\n  // when their spec drifted. Barrels/clients still reference every on-disk\n  // service (aggregateSurfaceServices), so those untouched files stay importable.\n  //\n  // This is the MINIMAL-scope contract: a scoped `--services X` run touches only\n  // X's own files. It relies on the emitters correspondingly NOT regenerating\n  // present services' fixtures and skipping the wholesale round-trip test in a\n  // scoped run — otherwise a fresh fixture would assert a field the (untouched)\n  // present model lacks. The three must move together; keeping the whole surface\n  // consistent instead (the prior behaviour) is the trade-off we chose against:\n  // it made every scoped run flush all on-disk drift, defeating the point of\n  // scoping. The SDK may lag on non-selected services until they're regenerated.\n  let scopedModelNames: Set<string> | undefined;\n  let scopedEnumNames: Set<string> | undefined;\n  if (options.scopedServices && options.scopedServices.size > 0) {\n    const selected = options.scopedServices;\n    // Seed reachability from ONLY the operations that mount to a selected target\n    // — not from every operation of a source service that has one op mounted\n    // there. `resolveOperations` honours per-operation `mountOn` hints, so a\n    // single source service can split across targets; collecting the whole\n    // service would pull its sibling operations' models (mounted elsewhere) into\n    // scope and regenerate non-selected model files, breaking the selected-only\n    // contract. Build temp services carrying just the selected operations.\n    const selectedOpsByService = new Map<string, Operation[]>();\n    for (const r of resolvedOperations) {\n      if (!selected.has(r.mountOn)) continue;\n      const ops = selectedOpsByService.get(r.service.name) ?? [];\n      ops.push(r.operation);\n      selectedOpsByService.set(r.service.name, ops);\n    }\n    const selectedSourceServices = spec.services\n      .filter((s) => selectedOpsByService.has(s.name))\n      .map((s) => ({ ...s, operations: selectedOpsByService.get(s.name)! }));\n    const reachable = collectReferencedNames(selectedSourceServices, spec.models, { preserveAllDiscriminated: false });\n    scopedModelNames = reachable.models;\n    scopedEnumNames = reachable.enums;\n  }\n\n  return {\n    namespace: toSnakeCase(options.namespace),\n    namespacePascal: options.namespace,\n    spec,\n    outputDir: options.outputDir,\n    apiSurface: options.apiSurface,\n    overlayLookup: options.overlayLookup,\n    resolvedOperations,\n    modelHints: options.modelHints,\n    emitterOptions: options.emitterOptions,\n    targetDir: options.target,\n    priorTargetManifestPaths: options.priorTargetManifestPaths,\n    scopedServices: options.scopedServices,\n    presentServiceKeys: options.presentServiceKeys,\n    scopedModelNames,\n    scopedEnumNames,\n  };\n}\n\n/**\n * The services an aggregate (barrel/client/test) generator may reference in a\n * scoped run: the selected services plus every service the prior manifest\n * recorded as already on disk. A service the spec just added that is neither\n * selected nor already generated is excluded — otherwise the client/barrels\n * would import a resource/model whose file this run does not emit (the orphaned\n * `agents/__init__.py → ._resource` class of build break).\n *\n * Outside a scoped run (full generation), every service is in surface.\n */\nexport function aggregateSurfaceServices(spec: ApiSpec, ctx: EmitterContext): Service[] {\n  const scope = ctx.scopedServices;\n  if (!scope || scope.size === 0) return spec.services;\n  const present = ctx.presentServiceKeys ?? new Set<string>();\n  const postMountOf = (service: Service): string =>\n    ctx.resolvedOperations?.find((r) => r.service.name === service.name)?.mountOn ?? service.name;\n  return spec.services.filter((s) => {\n    const postMount = postMountOf(s);\n    return scope.has(postMount) || present.has(canonicalServiceKey(postMount));\n  });\n}\n\n/**\n * Collect model and enum names transitively referenced by service operations.\n * Walks operation parameters, request bodies, responses, and pagination item\n * and envelope types, then chases model field references until the set stabilizes.\n */\nexport function collectReferencedNames(\n  services: Service[],\n  models: Model[],\n  opts: { preserveAllDiscriminated?: boolean; webhooks?: Webhook[] } = {},\n): { models: Set<string>; enums: Set<string> } {\n  // Default: preserve EVERY discriminated/event model as public surface (full\n  // emission). Strict mode (`preserveAllDiscriminated: false`, used to compute a\n  // scoped run's reachable set) skips that blanket and instead chases the mapping\n  // variants of discriminated models that are actually reached — so a scoped\n  // service doesn't pull in the entire unrelated event tree.\n  const preserveAllDiscriminated = opts.preserveAllDiscriminated !== false;\n  const referencedModels = new Set<string>();\n  const referencedEnums = new Set<string>();\n\n  const collectFromTypeRef = (ref: TypeRef): void => {\n    walkTypeRef(ref, {\n      model: (r) => referencedModels.add(r.name),\n      enum: (r) => referencedEnums.add(r.name),\n    });\n  };\n\n  // Seed: walk every operation's params, request body, response, errors, and pagination\n  for (const service of services) {\n    for (const op of service.operations) {\n      for (const p of [\n        ...op.pathParams,\n        ...op.queryParams,\n        ...(op.bodyOwnedQueryParams ?? []),\n        ...op.headerParams,\n        ...(op.cookieParams ?? []),\n      ]) {\n        collectFromTypeRef(p.type);\n      }\n      if (op.requestBody) collectFromTypeRef(op.requestBody);\n      for (const { type } of collectRequestBodyTypes(op)) collectFromTypeRef(type);\n      collectFromTypeRef(op.response);\n      if (op.pagination) {\n        collectFromTypeRef(op.pagination.itemType);\n        for (const field of op.pagination.envelopeFields ?? []) collectFromTypeRef(field.type);\n      }\n      for (const header of collectResponseHeaders(op)) collectFromTypeRef(header.type);\n      for (const { type } of collectResponseBodyTypes(op)) collectFromTypeRef(type);\n      for (const err of op.errors) {\n        if (err.type) collectFromTypeRef(err.type);\n      }\n      if (op.successResponses) {\n        for (const sr of op.successResponses) {\n          collectFromTypeRef(sr.type);\n        }\n      }\n      // A callback's payload or header type is public surface too, handed to\n      // the user as a webhook's is (#382); nested callbacks come with it.\n      for (const callback of op.callbacks ?? []) {\n        for (const ref of collectWebhookTypeRefs(callback)) collectFromTypeRef(ref);\n      }\n    }\n  }\n\n  // A webhook payload or header type is public surface an emitter hands the\n  // user, so it seeds reachability like an operation's types; without this a\n  // model referenced only by a webhook would be pruned as an orphan. Its\n  // callbacks' types come with it (`collectWebhookTypeRefs` reaches them).\n  for (const webhook of opts.webhooks ?? []) {\n    for (const ref of collectWebhookTypeRefs(webhook)) collectFromTypeRef(ref);\n  }\n\n  // Preserve discriminated models as public SDK types even when no operation\n  // returns them directly. This matters for event/webhook unions where the base\n  // operation references a generic envelope but the variant structs are still\n  // useful public surface.\n  //\n  // Also preserve the variants mapped from an `allOf [base, oneOf […]]` base\n  // (carried as `Model.discriminator.mapping`). The base model is reached\n  // through the operation; without explicitly chasing its mapping, the\n  // variant structs would be unreachable and the dispatcher would dangle\n  // imports.\n  if (preserveAllDiscriminated) {\n    for (const model of models) {\n      if (isDiscriminatedModel(model)) {\n        referencedModels.add(model.name);\n      }\n      const disc = model.discriminator;\n      if (disc?.mapping) {\n        for (const variantName of Object.values(disc.mapping)) {\n          referencedModels.add(variantName);\n        }\n      }\n    }\n  }\n\n  // Chase: transitively resolve model field references until stable\n  const modelsByName = new Map(models.map((m) => [m.name, m]));\n  const visited = new Set<string>();\n  const queue = [...referencedModels];\n  while (queue.length > 0) {\n    const name = queue.pop()!;\n    if (visited.has(name)) continue;\n    visited.add(name);\n    const model = modelsByName.get(name);\n    if (!model) continue;\n    // A reached discriminated base pulls in its mapping variants (the dispatcher\n    // would otherwise dangle). In full mode this is redundant with the blanket\n    // pass above; in strict mode it is the only path that includes variants.\n    const disc = model.discriminator;\n    if (disc?.mapping) {\n      for (const variantName of Object.values(disc.mapping)) {\n        if (!referencedModels.has(variantName)) {\n          referencedModels.add(variantName);\n          queue.push(variantName);\n        }\n      }\n    }\n    // Fields and, for a named union, its variants: a union alias dangles\n    // without the models it is a union of. Then the bases a composed\n    // component names (`Model.bases`): an emitter that writes the model as\n    // an extension of them needs them emitted, as a dispatcher needs its\n    // variants (#591).\n    for (const ref of [...collectModelTypeRefs(model), ...(model.bases ?? [])]) {\n      collectFromTypeRef(ref);\n      // If new models were discovered, enqueue them\n      for (const m of referencedModels) {\n        if (!visited.has(m)) queue.push(m);\n      }\n    }\n  }\n\n  return { models: referencedModels, enums: referencedEnums };\n}\n\nfunction isDiscriminatedModel(model: Model): boolean {\n  return model.fields.some(\n    (field) =>\n      (field.name === 'event' || field.name === 'type' || field.name === 'object') && field.type.kind === 'literal',\n  );\n}\n\n/**\n * Collect all generated files from an emitter (no headers, no path prefixes).\n *\n * A full run emits over the whole spec. A scoped (`--services`) run still emits\n * model placement, dedup, the root client, and aggregate/barrel files\n * byte-identically for every service ALREADY on disk (plus the brand-new\n * selected service, which is wired into the client automatically) — but it\n * narrows that surface to `selected ∪ already-on-disk` services\n * (`aggregateSurfaceServices`). A service the spec just added that is neither\n * selected nor already generated is dropped from the surface entirely, so its\n * models/discriminators are not pulled into reachability and barrels/the client\n * never import a resource this run does not emit. The emitters additionally\n * consult `ctx.scopedServices` to emit only the selected services' per-service\n * resource/test files.\n */\nexport function generateAllFiles(spec: ApiSpec, emitter: Emitter, ctx: EmitterContext): GeneratedFile[] {\n  const scoped = !!ctx.scopedServices && ctx.scopedServices.size > 0;\n  const surfaceServices = aggregateSurfaceServices(spec, ctx);\n  // In a scoped run, restrict the blanket discriminated/event preservation to\n  // models reachable from the in-surface services; otherwise an out-of-scope,\n  // never-generated service's discriminated models (e.g. AgentRegistration*)\n  // would still be force-included and emit orphaned converters/variants.\n  // Webhooks are not a service, so no scope selects or excludes them: their\n  // payload models are in surface in every run, exactly as in a full one.\n  const referenced = collectReferencedNames(surfaceServices, spec.models, {\n    preserveAllDiscriminated: !scoped,\n    webhooks: spec.webhooks,\n  });\n  const reachableModels = spec.models.filter((m) => referenced.models.has(m.name));\n  const reachableEnums = spec.enums.filter((e) => referenced.enums.has(e.name));\n  const surfaceSpec: ApiSpec = { ...spec, services: surfaceServices };\n  const reachableSpec: ApiSpec = { ...surfaceSpec, models: reachableModels, enums: reachableEnums };\n\n  return [\n    ...emitter.generateModels(reachableModels, ctx),\n    ...emitter.generateEnums(reachableEnums, ctx),\n    ...emitter.generateResources(surfaceServices, ctx),\n    ...emitter.generateClient(surfaceSpec, ctx),\n    ...emitter.generateErrors(ctx),\n    ...(emitter.generateTypeSignatures?.(reachableSpec, ctx) ?? []),\n    ...emitter.generateTests(reachableSpec, ctx),\n  ];\n}\n\n/** Apply file header to generated files, respecting headerPlacement and JSON files. */\nexport function applyFileHeaders(files: GeneratedFile[], header: string): GeneratedFile[] {\n  return files.map((f) => ({\n    ...f,\n    content:\n      !header || f.path.endsWith('.json') || f.headerPlacement === 'skip' ? f.content : header + '\\n\\n' + f.content,\n    skipIfExists: f.skipIfExists ?? false,\n  }));\n}\n\nexport function generateFiles(\n  spec: ApiSpec,\n  emitter: Emitter,\n  options: {\n    namespace: string;\n    outputDir: string;\n    apiSurface?: ApiSurface;\n    overlayLookup?: OverlayLookup;\n    operationHints?: Record<string, OperationHint>;\n    mountRules?: Record<string, string>;\n    operationNaming?: OperationNaming;\n    modelHints?: Record<string, string>;\n    emitterOptions?: Record<string, unknown>;\n    target?: string;\n    priorTargetManifestPaths?: Set<string>;\n    /** Scoped-generation signal (POST-MOUNT names); set on ctx for emitters to gate per-service emission. */\n    scopedServices?: Set<string>;\n    /** Canonical keys of services already on disk (prior manifest); narrows the scoped aggregate surface. */\n    presentServiceKeys?: Set<string>;\n  },\n): { files: GeneratedFile[]; ctx: EmitterContext; header: string; operations?: OperationsMap } {\n  const ctx = buildEmitterContext(spec, options);\n  const files = generateAllFiles(spec, emitter, ctx);\n  // Record operations for the SAME surface generateAllFiles emitted (scope ∪\n  // already-on-disk in a scoped run; the full spec otherwise). Recording a\n  // never-generated, out-of-scope service here would persist it into the merged\n  // manifest and make the next scoped run treat it as present — re-opening the\n  // orphan it was just kept out of.\n  const surfaceSpec: ApiSpec = { ...spec, services: aggregateSurfaceServices(spec, ctx) };\n  const operations = emitter.buildOperationsMap?.(surfaceSpec, ctx);\n  const header = emitter.fileHeader();\n  return { files: applyFileHeaders(files, header), ctx, header, operations };\n}\n","import * as fs from 'node:fs/promises';\nimport path from 'node:path';\nimport type { GeneratedFile } from './types.js';\nimport { writeFiles, type WriteResult } from './writer.js';\nimport { extractStatements } from './merger.js';\nimport { hasGrammar } from './merger.js';\n\n/**\n * Resolve a relative import path against a source file path to get the\n * target file path.  Handles implicit .ts extensions and /index.ts.\n */\nfunction resolveImportPath(\n  fromFilePath: string,\n  importModulePath: string,\n  knownPaths: Set<string>,\n): string | undefined {\n  // Strip quotes from module path key (tree-sitter keeps them)\n  const cleaned = importModulePath.replace(/^['\"]|['\"]$/g, '');\n  // Skip non-relative imports (node_modules, bare specifiers)\n  if (!cleaned.startsWith('.')) return undefined;\n\n  const dir = path.dirname(fromFilePath);\n  const resolved = path.normalize(path.join(dir, cleaned));\n\n  // Try exact match, .ts, /index.ts\n  for (const candidate of [resolved, `${resolved}.ts`, `${resolved}/index.ts`]) {\n    if (knownPaths.has(candidate)) return candidate;\n  }\n  return undefined;\n}\n\n/**\n * Determine whether a generated file is a \"root\" — a file that should always\n * be integrated into the target.  Roots are entry points from which we trace\n * the import graph.  Everything else must be reachable from a root.\n *\n * Roots: resource classes, client, config, errors, enums, barrel index files.\n * Non-roots: serializers, fixtures, standalone interfaces, test files.\n */\nfunction isRootFile(filePath: string): boolean {\n  // Fixtures are never roots (and should be filtered by integrateTarget already)\n  if (filePath.includes('/fixtures/')) return false;\n  // Test files are roots — they are standalone entry points that belong in the\n  // target repo even though nothing imports them.\n  if (filePath.endsWith('.spec.ts') || filePath.endsWith('.test.ts')) return true;\n  // Serializer files\n  if (filePath.includes('/serializers/')) return false;\n  // Standalone interface files (not barrel/index)\n  if (filePath.includes('/interfaces/') && !filePath.endsWith('/index.ts')) return false;\n  // Everything else is a root: resource classes, client, config, errors, enums, barrel files\n  return true;\n}\n\n/**\n * Build a file-level dependency graph from generated files and return only\n * files reachable from root entry points.  Uses tree-sitter to parse imports.\n */\nexport async function treeShakeFiles(files: GeneratedFile[], language: string): Promise<GeneratedFile[]> {\n  if (!hasGrammar(language)) return files;\n\n  const knownPaths = new Set(files.map((f) => f.path));\n\n  // Build dependency graph: file → set of files it imports\n  const deps = new Map<string, Set<string>>();\n  for (const file of files) {\n    // Only parse .ts/.js files (skip JSON, etc.)\n    if (!file.path.endsWith('.ts') && !file.path.endsWith('.js')) {\n      deps.set(file.path, new Set());\n      continue;\n    }\n    const parsed = await extractStatements(file.content, language);\n    const fileDeps = new Set<string>();\n    for (const imp of parsed.imports) {\n      const resolved = resolveImportPath(file.path, imp.key, knownPaths);\n      if (resolved) fileDeps.add(resolved);\n    }\n    // Also check re-export statements (export * from './foo')\n    for (const stmt of parsed.statements) {\n      if (stmt.kind === 'reexport') {\n        // Extract module path from \"export * from './foo'\" or \"export { X } from './foo'\"\n        const match = stmt.text.match(/from\\s+['\"]([^'\"]+)['\"]/);\n        if (match) {\n          const resolved = resolveImportPath(file.path, match[1], knownPaths);\n          if (resolved) fileDeps.add(resolved);\n        }\n      }\n    }\n    deps.set(file.path, fileDeps);\n  }\n\n  // Determine which file extensions are source code for this language\n  const codeExtensions = new Set([\n    '.ts',\n    '.js',\n    '.tsx',\n    '.jsx',\n    '.py',\n    '.rb',\n    '.go',\n    '.rs',\n    '.kt',\n    '.cs',\n    '.ex',\n    '.exs',\n    '.php',\n  ]);\n\n  // BFS from roots\n  const reachable = new Set<string>();\n  const queue: string[] = [];\n  for (const file of files) {\n    const ext = file.path.slice(file.path.lastIndexOf('.'));\n    // Non-code files (JSON, etc.) are always reachable — they can't participate\n    // in the import graph and are loaded at runtime (e.g. test fixtures).\n    if (!codeExtensions.has(ext)) {\n      reachable.add(file.path);\n      continue;\n    }\n    if (isRootFile(file.path)) {\n      reachable.add(file.path);\n      queue.push(file.path);\n    }\n  }\n  while (queue.length > 0) {\n    const current = queue.pop()!;\n    const fileDeps = deps.get(current);\n    if (!fileDeps) continue;\n    for (const dep of fileDeps) {\n      if (!reachable.has(dep)) {\n        reachable.add(dep);\n        queue.push(dep);\n      }\n    }\n  }\n\n  return files.filter((f) => reachable.has(f.path));\n}\n\nexport function mapFilesForTargetIntegration(files: GeneratedFile[], language: string): GeneratedFile[] {\n  const langPrefix = `${language}/`;\n  return files\n    .filter((f) => f.integrateTarget !== false) // integrateTarget: false files are standalone-only\n    .map((f) => {\n      const stripped = f.path.startsWith(langPrefix) ? f.path.replace(langPrefix, '') : f.path;\n      return {\n        ...f,\n        skipIfExists: false, // Always merge in target — never hard-skip\n        path: stripped,\n      };\n    });\n}\n\n/**\n * Resolve file-to-directory conflicts in the target.\n *\n * When a generated file creates a package directory (e.g., `api_keys/__init__.py`)\n * that would shadow an existing module file (e.g., `api_keys.py`), move the\n * module file's content into `_compat.py` inside the package and add a\n * re-export from `__init__.py`.  This preserves backward-compatible imports\n * (e.g., `from acme.api_keys import ApiKeysModule`) while the package directory\n * provides the generated models and resource classes.\n */\nasync function resolveFileToDirectoryConflicts(\n  files: GeneratedFile[],\n  targetDir: string,\n): Promise<{ files: GeneratedFile[]; removals: string[] }> {\n  const result = [...files];\n  const removals: string[] = [];\n\n  for (let i = 0; i < result.length; i++) {\n    const file = result[i];\n    // Match package init files: e.g., src/acme/api_keys/__init__.py\n    const match = file.path.match(/^(.+)\\/__init__\\.py$/);\n    if (!match) continue;\n\n    const dirPath = match[1]; // e.g., src/acme/api_keys\n    const moduleFilePath = `${dirPath}.py`; // e.g., src/acme/api_keys.py\n    const fullModulePath = path.join(targetDir, moduleFilePath);\n\n    let moduleContent: string;\n    try {\n      moduleContent = await fs.readFile(fullModulePath, 'utf-8');\n    } catch {\n      continue; // Module file doesn't exist — no conflict\n    }\n\n    // Create a compat shim inside the package with the old module's content\n    const compatPath = `${dirPath}/_compat.py`;\n    result.push({\n      path: compatPath,\n      content: moduleContent,\n      overwriteExisting: true,\n    });\n\n    // Append re-export from _compat to __init__.py so existing imports work.\n    // Compat must come AFTER generated models so hand-written types take\n    // precedence over generated types with the same name.\n    const compatImport = 'from ._compat import *  # noqa: F401,F403  # pyright: ignore[reportUnusedImport]';\n    const existingContent = file.content.endsWith('\\n') ? file.content : file.content + '\\n';\n    result[i] = {\n      ...file,\n      content: existingContent + compatImport + '\\n',\n    };\n\n    // Schedule the shadowed module file for removal\n    removals.push(fullModulePath);\n  }\n\n  return { files: result, removals };\n}\n\nexport interface IntegrateResult extends WriteResult {\n  /** Final set of paths this run claims ownership of in the target (post tree-shake + conflict resolution). */\n  emittedPaths: string[];\n}\n\nexport async function integrateGeneratedFiles(opts: {\n  files: GeneratedFile[];\n  language: string;\n  targetDir: string;\n  header: string;\n}): Promise<IntegrateResult> {\n  const mapped = mapFilesForTargetIntegration(opts.files, opts.language);\n  const shaken = await treeShakeFiles(mapped, opts.language);\n\n  // Handle file-to-directory conflicts before writing\n  const { files: resolved, removals } = await resolveFileToDirectoryConflicts(shaken, opts.targetDir);\n\n  const result = await writeFiles(resolved, opts.targetDir, {\n    language: opts.language,\n    header: opts.header,\n  });\n\n  // Remove shadowed module files after integration\n  for (const filePath of removals) {\n    try {\n      await fs.unlink(filePath);\n    } catch {\n      // File may already be gone\n    }\n  }\n\n  // The manifest tracks ALL files oagen owns, including tree-shaken ones.\n  // Tree-shaking decides what to write, but shaken files are still oagen-managed\n  // and must not be pruned from the target on subsequent runs.\n  return { ...result, emittedPaths: mapped.map((f) => f.path) };\n}\n","/**\n * Post-integration formatter.\n *\n * After generating and merging files into a target directory, runs the\n * emitter-provided format command on all written/merged files so that\n * generated code matches the target project's style conventions.\n */\n\nimport { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\nimport * as path from 'node:path';\nimport type { Emitter } from './types.js';\n\nconst execFileAsync = promisify(execFile);\n\n/**\n * Run the emitter's format command on the given target files.\n * Silently skips if the emitter has no formatCommand or returns null.\n */\nexport async function formatTargetFiles(emitter: Emitter, targetDir: string, filePaths: string[]): Promise<void> {\n  if (filePaths.length === 0) return;\n  if (!emitter.formatCommand) return;\n\n  const formatCmd = emitter.formatCommand(targetDir);\n  if (!formatCmd) return;\n\n  const absolutePaths = filePaths.map((f) => path.resolve(targetDir, f));\n  const batchSize = formatCmd.batchSize ?? 100;\n\n  process.stderr.write(\n    `[oagen] formatting ${absolutePaths.length} file(s) with ${formatCmd.cmd} (batch ${batchSize})\\n`,\n  );\n\n  for (let i = 0; i < absolutePaths.length; i += batchSize) {\n    const batch = absolutePaths.slice(i, i + batchSize);\n    try {\n      await execFileAsync(formatCmd.cmd, [...formatCmd.args, ...batch], {\n        cwd: targetDir,\n        maxBuffer: 10 * 1024 * 1024,\n        timeout: 120_000,\n      });\n    } catch (err) {\n      // Formatter failed on this batch — continue with remaining batches.\n      // Surface the failure on stderr so misconfigured commands don't silently\n      // leave generated code unformatted every regen.\n      const msg = err instanceof Error ? err.message : String(err);\n      process.stderr.write(`[oagen] formatter batch failed: ${msg}\\n`);\n    }\n  }\n}\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { canonicalServiceKey } from './scoped-services.js';\n\n/**\n * Prune-manifest support for `oagen generate`.\n *\n * The manifest records every auto-generated file emitted on the previous run,\n * relative to the directory it lives in (either the `--output` standalone dir\n * or the `--target` integration dir).  On the next run we diff the previous\n * list against the current emission set and delete anything that's no longer\n * produced — preventing stale-file accumulation across regens.\n *\n * Design notes:\n *  - The manifest is versioned so future format changes can be handled safely.\n *  - Paths are stored sorted for deterministic diffs in git.\n *  - Deletion is gated on a header guard when one is available: we only remove\n *    files whose contents start with the auto-generated header.  This protects\n *    a hand-maintained file that happens to share a name with a previously\n *    generated one (extremely rare, but worth catching).\n *  - On first adoption (no previous manifest), pruning is skipped and a\n *    one-line notice is printed — no surprise deletions.\n */\n\nexport const MANIFEST_FILENAME = '.oagen-manifest.json';\nconst MANIFEST_VERSION = 2;\n\nexport interface Manifest {\n  /** Schema version.  Bump when the format changes incompatibly. */\n  version: number;\n  /** Emitter language (e.g. \"python\").  Used only as a consistency hint. */\n  language: string;\n  /** Human-readable or package-level SDK identity (e.g. \"acme-php\"). */\n  sdkName?: string;\n  /** SHA-256 hash of the source OpenAPI spec used for generation. */\n  specSha?: string;\n  /** Path or reference to the source spec. */\n  specPath?: string;\n  /** Git SHA or version of the emitter code used. */\n  emitterSha?: string;\n  /** Emitter version string if available. */\n  emitterVersion?: string;\n  /** SHA-256 hash of the effective oagen.config.ts after resolution. */\n  configSha?: string;\n  /** Version of the compat snapshot/report schema expected by this generation. */\n  compatSchemaVersion?: string;\n  /** Sorted list of paths, relative to the manifest's containing directory. */\n  files: string[];\n  /** Maps \"METHOD /path\" to SDK method + service property name. */\n  operations?: Record<string, unknown>;\n}\n\nexport interface PruneResult {\n  /** Paths actually deleted. */\n  pruned: string[];\n  /** Paths skipped because the header guard didn't match (preserved). */\n  preserved: string[];\n  /** Paths already absent on disk (nothing to do). */\n  missing: string[];\n}\n\n/** Read `.oagen-manifest.json` from a directory.  Returns null if absent or malformed. */\nexport async function readManifest(dir: string): Promise<Manifest | null> {\n  const manifestPath = path.join(dir, MANIFEST_FILENAME);\n  let raw: string;\n  try {\n    raw = await fs.readFile(manifestPath, 'utf-8');\n  } catch {\n    return null;\n  }\n  try {\n    const parsed = JSON.parse(raw) as Partial<Manifest>;\n    if (\n      typeof parsed.version !== 'number' ||\n      typeof parsed.language !== 'string' ||\n      !Array.isArray(parsed.files) ||\n      !parsed.files.every((p): p is string => typeof p === 'string')\n    ) {\n      return null;\n    }\n    if (parsed.version > MANIFEST_VERSION) {\n      console.warn(\n        `[oagen] ${MANIFEST_FILENAME} schema version ${parsed.version} is newer than supported (${MANIFEST_VERSION}); ignoring for pruning.`,\n      );\n      return null;\n    }\n    // v1 manifests are forward-compatible — new fields are simply absent\n    return parsed as Manifest;\n  } catch {\n    return null;\n  }\n}\n\n/** Options for writing a manifest. */\nexport interface WriteManifestOpts {\n  language: string;\n  files: Iterable<string>;\n  sdkName?: string;\n  specSha?: string;\n  specPath?: string;\n  emitterSha?: string;\n  emitterVersion?: string;\n  configSha?: string;\n  compatSchemaVersion?: string;\n  operations?: Record<string, unknown>;\n}\n\n/** Write `.oagen-manifest.json` to a directory with sorted paths. */\nexport async function writeManifest(dir: string, opts: WriteManifestOpts): Promise<void> {\n  const manifestPath = path.join(dir, MANIFEST_FILENAME);\n  const manifest: Manifest = {\n    version: MANIFEST_VERSION,\n    language: opts.language,\n    ...(opts.sdkName !== undefined ? { sdkName: opts.sdkName } : {}),\n    ...(opts.specSha !== undefined ? { specSha: opts.specSha } : {}),\n    ...(opts.specPath !== undefined ? { specPath: opts.specPath } : {}),\n    ...(opts.emitterSha !== undefined ? { emitterSha: opts.emitterSha } : {}),\n    ...(opts.emitterVersion !== undefined ? { emitterVersion: opts.emitterVersion } : {}),\n    ...(opts.configSha !== undefined ? { configSha: opts.configSha } : {}),\n    ...(opts.compatSchemaVersion !== undefined ? { compatSchemaVersion: opts.compatSchemaVersion } : {}),\n    files: [...new Set(opts.files)].sort(),\n    ...(opts.operations !== undefined ? { operations: opts.operations } : {}),\n  };\n  await fs.mkdir(dir, { recursive: true });\n  await fs.writeFile(manifestPath, JSON.stringify(manifest, null, 2) + '\\n', 'utf-8');\n}\n\n/** Return the set of previous paths no longer present in the current emission. */\nexport function computeStalePaths(prev: Manifest, currentPaths: Iterable<string>): string[] {\n  const current = new Set(currentPaths);\n  return prev.files.filter((p) => !current.has(p)).sort();\n}\n\n/**\n * Merge a scoped run's emitted records into the prior manifest's records.\n *\n * A scoped (`--services`) run only emits files for the selected services, but it\n * must NOT discard the prior manifest's record of unselected services' files\n * records. The result unions prior + scoped file paths and shallow-merges the\n * operations maps, with scoped operations overriding prior entries for the same\n * \"METHOD /path\" key (a re-emission updates that operation's record).\n *\n * When `prev` is null (the first-ever run is scoped) there is nothing to\n * preserve, so the scoped subset is returned unchanged — matching the\n * first-adoption behavior of a full run.\n */\nexport function mergeScopedManifestRecords(\n  prev: Manifest | null,\n  scopedFiles: Iterable<string>,\n  scopedOperations?: Record<string, unknown>,\n): { files: string[]; operations?: Record<string, unknown> } {\n  const scopedFileList = [...scopedFiles];\n  if (!prev) {\n    return { files: scopedFileList, operations: scopedOperations };\n  }\n  const files = [...new Set([...prev.files, ...scopedFileList])].sort();\n  const priorOps = prev.operations;\n  const operations = priorOps || scopedOperations ? { ...priorOps, ...scopedOperations } : undefined;\n  return { files, operations };\n}\n\n/**\n * Extract the set of services a prior manifest records as already generated on\n * disk, as canonical (casing/separator-insensitive) keys.\n *\n * The manifest's `operations` map carries each operation's owning `service`\n * (snake_case for most emitters, camelCase for Kotlin). A scoped (`--services`)\n * run uses this to tell \"service in the spec that is already on disk\" apart from\n * \"service the spec just added that this SDK has never generated\" — only the\n * former may be wired into aggregate/barrel/client files alongside the\n * selection, so a brand-new out-of-scope service is never referenced by files\n * whose implementation this run does not emit.\n *\n * Returns an empty set when the manifest is null or carries no operations\n * (a legacy manifest with no operations data); callers treat that as \"present\n * set unknown\" and fall back to not narrowing the surface.\n */\nexport function manifestServiceKeys(manifest: Manifest | null): Set<string> {\n  const keys = new Set<string>();\n  const ops = manifest?.operations;\n  if (!ops) return keys;\n  for (const value of Object.values(ops)) {\n    const entries = Array.isArray(value) ? value : [value];\n    for (const entry of entries) {\n      const service = (entry as { service?: unknown } | null)?.service;\n      if (typeof service === 'string' && service.length > 0) {\n        keys.add(canonicalServiceKey(service));\n      }\n    }\n  }\n  return keys;\n}\n\n/**\n * Delete stale files from `dir`.\n *\n * When `header` is provided, a file is only deleted if its contents start with\n * that header — so hand-maintained files that somehow collide with a previously\n * generated path can't be clobbered.  When `header` is omitted, the guard is\n * skipped (useful for non-source artifacts like fixture JSON).\n *\n * Returns lists for reporting.  Empty parent directories are removed after\n * deletion, up to (but not including) `dir` itself.\n */\nexport async function pruneStaleFiles(\n  dir: string,\n  paths: string[],\n  opts: { header?: string } = {},\n): Promise<PruneResult> {\n  const pruned: string[] = [];\n  const preserved: string[] = [];\n  const missing: string[] = [];\n\n  for (const relPath of paths) {\n    const fullPath = path.join(dir, relPath);\n    let content: string;\n    try {\n      content = await fs.readFile(fullPath, 'utf-8');\n    } catch {\n      missing.push(relPath);\n      continue;\n    }\n    if (opts.header && !content.startsWith(opts.header)) {\n      preserved.push(relPath);\n      continue;\n    }\n    try {\n      await fs.unlink(fullPath);\n      pruned.push(relPath);\n    } catch {\n      // Racing deletion or permission issue — treat as missing rather than fatal.\n      missing.push(relPath);\n      continue;\n    }\n    await removeEmptyParents(path.dirname(fullPath), dir);\n  }\n\n  return { pruned, preserved, missing };\n}\n\n/**\n * Walk up from `startDir` removing empty directories until we hit `stopDir`\n * (exclusive) or a non-empty directory.  Silently ignores errors.\n */\nasync function removeEmptyParents(startDir: string, stopDir: string): Promise<void> {\n  let current = path.resolve(startDir);\n  const stop = path.resolve(stopDir);\n  while (current.startsWith(stop + path.sep) && current !== stop) {\n    let entries: string[];\n    try {\n      entries = await fs.readdir(current);\n    } catch {\n      return;\n    }\n    if (entries.length > 0) return;\n    try {\n      await fs.rmdir(current);\n    } catch {\n      return;\n    }\n    current = path.dirname(current);\n  }\n}\n","import type { ApiSpec } from '../ir/types.js';\nimport { validateModelHints } from '../ir/types.js';\nimport type { OperationHint, OperationNaming } from '../ir/operation-hints.js';\nimport type { Emitter, GeneratedFile } from './types.js';\nimport type { ApiSurface, OverlayLookup } from '../compat/types.js';\nimport { writeFiles } from './writer.js';\nimport { generateFiles } from './generate-files.js';\nimport { resolveScopedServices } from './scoped-services.js';\nimport { integrateGeneratedFiles } from './integrate.js';\nimport { formatTargetFiles } from './formatter.js';\nimport {\n  computeStalePaths,\n  manifestServiceKeys,\n  MANIFEST_FILENAME,\n  mergeScopedManifestRecords,\n  pruneStaleFiles,\n  readManifest,\n  writeManifest,\n} from './manifest.js';\n\nexport async function generate(\n  spec: ApiSpec,\n  emitter: Emitter,\n  options: {\n    namespace: string;\n    dryRun?: boolean;\n    outputDir: string;\n    target?: string;\n    apiSurface?: ApiSurface;\n    overlayLookup?: OverlayLookup;\n    operationHints?: Record<string, OperationHint>;\n    mountRules?: Record<string, string>;\n    operationNaming?: OperationNaming;\n    modelHints?: Record<string, string>;\n    emitterOptions?: Record<string, unknown>;\n    /** When true, skip deletion of files recorded in the previous manifest but not in the current emission. */\n    noPrune?: boolean;\n    /**\n     * Post-mount service names to generate (a `--services` run). When non-empty,\n     * the FULL spec is still emitted for models/enums/client/barrels (so shared\n     * files stay byte-identical and a brand-new selected service is wired into the\n     * client automatically); only per-service resource/test emission is gated to\n     * the selection (via `ctx.scopedServices`). Pruning is disabled and the\n     * manifest is merged so unselected services' records survive.\n     */\n    services?: string[];\n  },\n): Promise<GeneratedFile[]> {\n  // Fail loud on modelHints typos up front, against the FULL spec. Placement\n  // (assignModelsToServices) is intentionally lenient because it runs over\n  // partial model/service slices; this single check is where typos are caught,\n  // and it stays correct in scoped runs because the spec is not filtered.\n  if (options.modelHints) {\n    validateModelHints(spec.models, spec.services, options.modelHints);\n  }\n\n  // Scoped generation: validate + expand the selection to POST-MOUNT names. The\n  // spec is NOT filtered — placement/dedup/shared-schemas are computed over the\n  // full spec so shared files stay byte-identical; emitters gate only per-service\n  // resource/test emission on this set.\n  const scopedServices =\n    options.services && options.services.length > 0\n      ? resolveScopedServices(spec, options.services, options.mountRules)\n      : undefined;\n  const scoped = scopedServices !== undefined;\n  // Scoped mode implies no-prune so unselected services' files survive.\n  const noPrune = options.noPrune === true || scoped;\n\n  // Read previous manifests up front so emitters can mark files the prior run\n  // wrote as safe-to-overwrite (vs files a human hand-maintains), and so scoped\n  // runs can merge prior records. Skipped only when --no-prune is set on a\n  // non-scoped run (opting out of lifecycle tracking). Scoped runs always read,\n  // even though they force no-prune, because the merge needs the prior records.\n  const skipManifestRead = options.noPrune === true && !scoped;\n  const outputPrevManifestForCtx = skipManifestRead ? null : await readManifest(options.outputDir);\n  const targetManifestForCtx = options.target && !skipManifestRead ? await readManifest(options.target) : null;\n  const priorManifestForCtx = targetManifestForCtx ?? outputPrevManifestForCtx;\n  const priorTargetManifestPaths = priorManifestForCtx ? new Set(priorManifestForCtx.files) : undefined;\n  // Services already generated on disk (from the prior manifest's operations).\n  // Only consulted in a scoped run: it keeps already-present services in the\n  // aggregate/barrel/client surface (byte-identical regen) while excluding a\n  // service the spec just added that this SDK has never generated — which would\n  // otherwise be wired into the client/barrels with no implementation behind it.\n  const presentServiceKeys = scoped ? manifestServiceKeys(priorManifestForCtx) : undefined;\n\n  const {\n    files: withHeaders,\n    header,\n    operations,\n  } = generateFiles(spec, emitter, {\n    ...options,\n    priorTargetManifestPaths,\n    scopedServices,\n    presentServiceKeys,\n  });\n\n  if (options.dryRun) {\n    if (options.target) {\n      console.log(`\\nTarget integration (${options.target}):`);\n      for (const f of withHeaders) {\n        console.log(`  ${f.path}`);\n      }\n    }\n    return withHeaders;\n  }\n\n  // Reuse the manifest read before generation; nothing above writes it.\n  const outputPrevManifest = outputPrevManifestForCtx;\n\n  const writeResult = await writeFiles(withHeaders, options.outputDir, {\n    language: emitter.language,\n    header,\n  });\n\n  if (writeResult.merged.length > 0) {\n    console.log(`Merged into ${writeResult.merged.length} existing files (additive only)`);\n  }\n  if (writeResult.ignored.length > 0) {\n    console.log(`Ignored ${writeResult.ignored.length} files (@oagen-ignore-file)`);\n  }\n\n  const outputEmittedPaths = withHeaders.map((f) => f.path);\n  await applyManifestPrune({\n    dir: options.outputDir,\n    label: 'Output',\n    prevManifest: outputPrevManifest,\n    currentPaths: outputEmittedPaths,\n    language: emitter.language,\n    header,\n    noPrune,\n    operations,\n    scoped,\n  });\n\n  // Format output files so the emitter's formatter runs even without --target.\n  const allOutputFiles = [...writeResult.written, ...writeResult.merged];\n  if (allOutputFiles.length > 0) {\n    await formatTargetFiles(emitter, options.outputDir, allOutputFiles);\n  }\n\n  // Target integration pass\n  if (options.target) {\n    // Reuse the manifest we already read to build the emitter context.  This\n    // is correct because nothing between the two reads writes the manifest.\n    const targetPrevManifest = targetManifestForCtx;\n\n    const targetResult = await integrateGeneratedFiles({\n      files: withHeaders,\n      language: emitter.language,\n      targetDir: options.target,\n      header,\n    });\n\n    if (targetResult.written.length > 0) {\n      console.log(`Target: created ${targetResult.written.length} new files`);\n    }\n    if (targetResult.merged.length > 0) {\n      console.log(`Target: merged into ${targetResult.merged.length} existing files (additive only)`);\n    }\n    if (targetResult.skipped.length > 0) {\n      console.log(`Target: skipped ${targetResult.skipped.length} files (excluded or no grammar)`);\n    }\n\n    await applyManifestPrune({\n      dir: options.target,\n      label: 'Target',\n      prevManifest: targetPrevManifest,\n      currentPaths: targetResult.emittedPaths,\n      language: emitter.language,\n      header,\n      noPrune,\n      operations,\n      scoped,\n    });\n\n    // Run the emitter's formatter on all written/merged/identical files\n    const allTargetFiles = [...targetResult.written, ...targetResult.merged, ...targetResult.identical];\n    if (allTargetFiles.length > 0) {\n      await formatTargetFiles(emitter, options.target, allTargetFiles);\n    }\n  }\n\n  return withHeaders;\n}\n\n/**\n * Prune files recorded in the previous manifest but absent from the current emission,\n * then write the fresh manifest.  Safe on first adoption (no previous manifest).\n */\nasync function applyManifestPrune(opts: {\n  dir: string;\n  label: string;\n  prevManifest: Awaited<ReturnType<typeof readManifest>>;\n  currentPaths: string[];\n  language: string;\n  header: string;\n  noPrune?: boolean;\n  operations?: Record<string, unknown>;\n  /** When true, union this scoped run's records with the prior manifest. */\n  scoped?: boolean;\n}): Promise<void> {\n  // A scoped run only emits the selected services' files, so the manifest is\n  // merged with the prior records rather than replaced — otherwise unselected\n  // services would be dropped from the manifest and mis-pruned on the next run.\n  const records = opts.scoped\n    ? mergeScopedManifestRecords(opts.prevManifest, opts.currentPaths, opts.operations)\n    : { files: opts.currentPaths, operations: opts.operations };\n  const manifestOpts = { language: opts.language, files: records.files, operations: records.operations };\n  if (opts.noPrune) {\n    // Still refresh the manifest so future runs with pruning enabled have a baseline.\n    await writeManifest(opts.dir, manifestOpts);\n    return;\n  }\n\n  if (!opts.prevManifest) {\n    console.log(\n      `${opts.label}: no ${MANIFEST_FILENAME} found — skipping prune (this baseline manifest will be written now).`,\n    );\n    await writeManifest(opts.dir, manifestOpts);\n    return;\n  }\n\n  const stale = computeStalePaths(opts.prevManifest, opts.currentPaths);\n  if (stale.length > 0) {\n    const { pruned, preserved } = await pruneStaleFiles(opts.dir, stale, { header: opts.header });\n    if (pruned.length > 0) {\n      console.log(`${opts.label}: pruned ${pruned.length} stale file${pruned.length === 1 ? '' : 's'}`);\n    }\n    if (preserved.length > 0) {\n      console.log(\n        `${opts.label}: preserved ${preserved.length} file${preserved.length === 1 ? '' : 's'} in previous manifest but lacking the auto-generated header (possibly hand-edited).`,\n      );\n      for (const p of preserved) console.log(`  ${p}`);\n    }\n  }\n\n  await writeManifest(opts.dir, manifestOpts);\n}\n","import { RegistryError } from '../errors.js';\nimport type { Emitter } from './types.js';\n\nconst emitters = new Map<string, Emitter>();\n\nexport function registerEmitter(emitter: Emitter): void {\n  emitters.set(emitter.language, emitter);\n}\n\nexport function getEmitter(language: string): Emitter {\n  const emitter = emitters.get(language);\n  if (!emitter) {\n    const available = [...emitters.keys()].join(', ') || '(none)';\n    throw new RegistryError(\n      `Unknown language: ${language}. Available: ${available}`,\n      `Register an emitter for \"${language}\" via registerEmitter() or check your oagen.config.ts plugin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