/** * Ruby language adapter backed by ruby-lsp + ruby-lsp-rails (ADR-21). * * Wraps `ruby-lsp` spawned as a subprocess (via `bundle exec` when * Rails detected; via direct gem-install binary otherwise), speaking * LSP over stdio. Implements the `LanguageAdapter` interface from * src/types.ts per ADR-03 (adapters are plugins) and ADR-07 * (getTypeInfo is a required capability). * * Phase 3 implementation complete across 8 substeps: * - 3.1: skeleton — constructor, handler stubs, spawn pattern, * initialize handshake, Rails detection, shutdown * - 3.2: listSymbols — hierarchical-tree walk + parentId * back-pointer + URL-encoding dedup utility foundation * - 3.3: getSymbolDetails — hover-based signature enrichment + * parseRubyHoverContent + findSymbolByName * - 3.4: findReferences — first empirical reuse of dedup * utility; includeDeclaration: false per actual precedent * - 3.5: getDiagnostics — LSP 3.17 pull-model * (textDocument/diagnostic REQUEST; net-new substrate) * - 3.6: getTypeInfo — declaration-parse fallback per Pyright * precedent; parseRubyClassExtends + parseRubyMixins * - 3.7: getDocstring — hover-with-comments per gopls precedent; * forward-composition consumer of parseRubyHoverContent prose * - 3.8: adapter close — final cleanup + Phase 3 substrate-record * * Divergences from ADR-13 (Pyright) + ADR-14 (gopls) documented in * ADR-21: * - Pull-model diagnostics (LSP 3.17 `textDocument/diagnostic` * REQUEST), NOT publishDiagnostics notification. * - URL-encoding result duplication on Windows (`c%3A` + `c:` * forms). Adapter dedupes via `normalizePath` + (path, line) * tuple per dedupLocationsByNormalizedPath utility. * - Dual-pattern install (bundler vs direct gem) detected per- * workspace via Gemfile + bin/rails heuristic. * - Windows .bat-spawn wrap in `cmd.exe /c` per CVE-2024-27980. * - No cold-start `$/progress` readiness gate — ruby-lsp follows * Pyright pattern; per-call ceiling absorbs cold-start variance. * - ruby-lsp-rails add-on is best-effort enhancement, NOT baseline * assumption. Adapter logs add-on load failure but continues * with baseline LSP functionality. * - getSymbolDetails uses hover for signature enrichment (Pyright/ * gopls don't); ruby-lsp's documentSymbol typically omits the * detail field, hover provides rich RDoc + rbs-derived signatures. * - getTypeInfo uses local declaration-parse from documentSymbol * range (Pyright pass-1/pass-2 cache architecture not replicated * since Ruby's class hierarchy is locally-parseable); * usedByTypes always [] at v1.0 per simpler-adapter-private-scope. * - getDocstring uses hover-with-comments (gopls precedent; * substantively different from ADR-13 Pyright omits-docstrings). * - self.method class-method names preserve `self.` prefix verbatim * in Symbol-ID per Φ-γ-variant lock (ADR-21 §Rationale; gopls * receiver-prefix-verbatim precedent applied to Ruby). * * See `docs/adr/ruby-lsp-probe/findings-baseline.md` for the * empirical probe substrate motivating these design choices * (archived at v0.9 Substep 4.2 from the original flat path * `docs/adr/ruby-lsp-probe-findings-baseline.md`). */ import { LANG_CODES, type Diagnostic, type LanguageAdapter, type LanguageCode, type Reference, type ReferenceId, type Symbol as AtlasSymbol, type SymbolId, type SymbolKind, type TypeInfo } from "../types.js"; interface LspPosition { line: number; character: number; } interface LspRange { start: LspPosition; end: LspPosition; } interface LspDiagnostic { range: LspRange; severity?: number; message: string; } interface LspDocumentSymbol { name: string; detail?: string; kind: number; range: LspRange; selectionRange: LspRange; children?: LspDocumentSymbol[]; } export declare function mapRubyKind(lspKind: number): SymbolKind; export declare function mapDiagnosticSeverity(n: number | undefined): Diagnostic["severity"]; export interface RubyAdapterOptions { /** * Override the ruby-lsp binary path. When set, bypasses dual-pattern * detection and spawns the binary directly (gem-install pattern). * Defaults to `process.env.CONTEXTATLAS_RUBY_LSP_BIN` when unset. */ cliPath?: string; /** Upper bound on a single LSP request. Defaults to 30s. */ requestTimeoutMs?: number; /** * Skip the `ruby --version` preflight. Reserved for tests that stub * the LSP transport — production code should leave at default * `false` so the adapter fails fast when `ruby` is missing from PATH. */ skipRubyPreflight?: boolean; /** * Override the `ruby` binary used by the preflight. Defaults to * `"ruby"` (resolved via PATH). Test-only; production users should * put `ruby` on PATH per ADR-21. */ rubyBin?: string; /** * Override the bundler binary. Defaults to platform-appropriate * (`bundle.bat` on win32, `bundle` elsewhere). Honors * `process.env.CONTEXTATLAS_BUNDLE_BIN` env override. */ bundleBin?: string; } /** Extensions indexed in v0.9 per ADR-21 "File extensions" decision (`.rb` only). */ export declare const RUBY_EXTENSIONS: readonly string[]; export declare class RubyAdapter implements LanguageAdapter { readonly language: LanguageCode; readonly extensions: readonly string[]; private readonly client; private readonly options; private rootPath; private readonly openFiles; private readonly diagnosticsByUri; private readonly diagnosticsListeners; /** * Rails-detected flag set at initialize-time per ADR-21 §"Rails * DSL handling". Informs downstream consumers (doctor checks, * extraction pipeline) whether the add-on path is expected. * Adapter degrades gracefully regardless — the add-on either loads * or doesn't; baseline ruby-lsp continues working either way. */ private railsDetected; constructor(options?: RubyAdapterOptions); initialize(rootPath: string): Promise; shutdown(): Promise; /** * Resolve a filePath argument to absolute + workspace-relative * forms. Accepts either absolute paths or workspace-relative * paths; returns both for use by callers (LSP requests need * absolute paths via toFileUri; Symbol-IDs need workspace- * relative paths per ADR-01). */ private resolveFile; /** * Send `textDocument/didOpen` for `absPath` if not already opened * in this session. ruby-lsp (like Pyright + gopls) requires files * to be opened before symbol queries return results. Matches * gopls/pyright `ensureOpen` precedent. */ private ensureOpen; /** * Construct a Ruby Symbol-ID per ADR-01 format: `sym:rb::`. * Path is workspace-relative forward-slash-separated; name is the * symbol identifier as ruby-lsp emits it (including verbatim `self.` * prefix for class methods per Φ-γ-variant lock, and verbatim * `"macro :argument"` form for Rails DSL macros). */ private symbolId; listSymbols(filePath: string): Promise; getSymbolDetails(id: SymbolId): Promise; findReferences(id: SymbolId): Promise; getDiagnostics(filePath: string): Promise; getTypeInfo(id: SymbolId): Promise; getDocstring(id: SymbolId): Promise; } /** * Detect whether `rootPath` is a Rails application per the heuristic * ruby-lsp uses: Gemfile presence + bin/rails presence. Probe-empirical * substrate at boot section "Detected test library: rails (bin/rails * present)" confirms this is what ruby-lsp triggers add-on auto-load * on. Adapter mirrors the heuristic for observational purposes (doctor * substrate; downstream consumers may key off this flag). */ export declare function detectRails(rootPath: string): boolean; /** * Resolve the spawn command + args for the ruby-lsp subprocess per * ADR-21 §"Dual-pattern install" + §"Windows .bat-spawn handling". * * Precedence: * 1. `cliPathOverride` (env var CONTEXTATLAS_RUBY_LSP_BIN or * options.cliPath): direct gem-install pattern — spawn the * binary directly. On Windows, wrap in cmd.exe /c because * gem-installed ruby-lsp.bat is a .bat shim. * 2. Rails-detected: bundler pattern — spawn `bundle exec * ruby-lsp`. On Windows, wrap in cmd.exe /c because bundle.bat * is a .bat shim. * 3. No-Rails fallback: assume gem-install pattern — spawn * `ruby-lsp` resolved via PATH. Windows wrap applies. */ export declare function resolveSpawnPattern(opts: { cliPathOverride?: string; bundleBinOverride?: string; railsDetected: boolean; }): { command: string; args: string[]; pattern: "direct" | "bundler"; }; /** * Spawn `ruby --version` as a preflight per ADR-21 §"Install pattern" * + parallel to ADR-14 gopls's `go version` preflight. Resolves on * exit code 0; rejects with actionable error otherwise. * * The error message references ADR-21 install pattern + the doctor * recommendation surface (Windows + RubyInstaller users may need * `ridk install` if `ruby` is missing entirely). */ export declare function runRubyVersionPreflight(rubyBin: string): Promise; /** * Extract docstring prose from a ruby-lsp hover response per ADR-21 * §LSP primitive mappings. Forward-composition consumer of * parseRubyHoverContent's `prose` field (3.3 substrate; 3.7 reuses). * * Exported for unit-test access to the response-handling pipeline * without requiring live LSP integration. Defensive null-fallthrough * for response variants: * - null response → null * - missing contents → null * - string contents (LSP older shape) → null at v1.0 (only * handle markdown content envelope) * - object contents without value field → null * - empty value → null * - value with no code block AND no prose → null * - value with code block only (no RDoc body; e.g., User class * hover from probe #4) → null prose * - value with code block + RDoc body → prose returned (HTML * comments stripped, definition-links stripped, per * parseRubyHoverContent's existing logic) */ export declare function extractDocstringFromHoverResponse(response: { contents?: { kind?: string; value?: string; } | string; } | null): string | null; /** * Parse Ruby class extends (superclass) from source line. Ruby * syntax: `class Name < Super` (with optional namespacing on * either side: `class Foo::Bar < Baz::Qux`). * * Returns array (not single value) for symmetry with TypeInfo.extends * shape — Ruby supports only single inheritance, so the array is * always 0 or 1 element. Modules return [] (no superclass syntax). * * Edge cases handled: * - `class Name` (no superclass) → [] * - `class << self` (singleton class syntax) → [] (not standard * inheritance; the regex requires `<` followed by identifier, * not `<<`) * - `module Name` → [] (modules have no superclass syntax) * - Out-of-bounds line index → [] * - Empty/missing line → [] * * Reopened class scope: this parser only sees the line at * `classLine0Indexed`. If a class is reopened in multiple files, * the inheritance is parseable only at the FIRST occurrence (the * declaration line). Reopened-class mixins are still surfaced via * parseRubyMixins per the line-range-scan it performs. */ export declare function parseRubyClassExtends(sourceText: string, classLine0Indexed: number): string[]; /** * Parse Ruby mixin statements (include/extend/prepend) from class * body. Scans lines from `startLine0Indexed + 1` (after class * header) to `endLine0Indexed - 1` (before closing `end`). * * All three mixin keywords (include, extend, prepend) treated * uniformly per ADR-21 §getTypeInfo §Decision — collected into a * single array. Order preserved per source position. * * Edge cases handled: * - Multiple includes: all surfaced * - Namespaced mixins (`include Foo::Bar`): preserved verbatim * - Mixins at top of class body (common): scanned * - Mixins inside method bodies: NOT matched (regex requires * line to start with whitespace + keyword + identifier; method * body content typically has deeper indentation but the * keyword pattern still fires — this is a v1.0 known * limitation; v1.1 candidate for proper scope-aware parsing) * - Reopened class bodies: scanned via line-range * - ActiveSupport::Concern's `included do` block contents NOT * scanned for mixins (Concern bubble-up is v1.1 candidate per * ADR-21 §getTypeInfo) */ export declare function parseRubyMixins(sourceText: string, startLine0Indexed: number, endLine0Indexed: number): string[]; /** * LSP 3.17 pull-model diagnostic response shape per ADR-21 * §LSP primitive mappings. Two variants: * - full: items array contains diagnostics for the document * - unchanged: no items; resultId only (diagnostics haven't * changed since previousResultId in request — adapter doesn't * send previousResultId at v1.0, but defensive handling here) * * relatedDocuments key (diagnostics for OTHER files affected by * errors in this file) is part of the LSP 3.17 spec but ignored * at v1.0 — adapter contract is per-file scope. */ export type DocumentDiagnosticReport = { kind: "full"; items?: LspDiagnostic[]; resultId?: string; relatedDocuments?: unknown; } | { kind: "unchanged"; resultId: string; relatedDocuments?: unknown; }; /** * Build ContextAtlas Diagnostic[] from a ruby-lsp pull-model * DocumentDiagnosticReport response. Exported for unit-test access * to variant handling without requiring live LSP integration. * * Variant handling per ADR-21 §LSP primitive mappings: * - null response → empty array (defensive; per-call timeout * fallback case) * - kind: "unchanged" → empty array (ruby-lsp shouldn't emit * this when no previousResultId is sent, but defensive * handling at v1.0; future enhancement could track resultId * state for "diagnostics-haven't-changed" optimization) * - kind: "full" → items mapped to ContextAtlas Diagnostic[] * with severity remap via mapDiagnosticSeverity + 1-indexed * line conversion */ export declare function buildDiagnosticsFromResponse(response: DocumentDiagnosticReport | null, relPath: string): Diagnostic[]; /** * Construct a Ruby Reference-ID per ADR-01 format: * `ref:rb::`. Path is workspace-relative forward-slash- * separated; line is 1-indexed (human-readable). Exported for * testability of ID format separate from full findReferences flow. */ export declare function buildReferenceId(relPath: string, line: number): ReferenceId; /** * Recursive walker over LspDocumentSymbol[] looking for a symbol by * name. Walks children depth-first; first match wins. Returns null * if no match. * * Match shape: ruby-lsp's documentSymbol may emit DSL macros with * "macro :argument" naming (e.g., "has_many :posts"), class methods * with "self." prefix (e.g., "self.find_by_email"), and standard * names. Caller passes the verbatim name as parsed from Symbol-ID. */ export declare function findSymbolByName(symbols: readonly LspDocumentSymbol[], name: string): LspDocumentSymbol | null; /** * Parse ruby-lsp hover response markdown envelope into structured * `{ signature, prose }` shape per ADR-21 §LSP primitive mappings * (Probe #4 baseline empirical substrate). * * ruby-lsp hover envelope structure (probe-empirical): * ```ruby * * ``` * * **Definitions**: [link1](file:///...) | [link2](file:///...) * * * * * Parser strips: * - Definition-links section (the `**Definitions**: ...` paragraph) * - HTML comments (rdoc-file metadata, not user-facing) * * Parser preserves: * - First fenced ```ruby code block content (signature; multi-line * when ruby-lsp emits overload counts or expanded signatures) * - RDoc body prose (consumed by getDocstring at Substep 3.7) * * Edge cases: * - Empty/null value → both fields null * - Code block only (no prose) → signature populated, prose null * - No code block → signature null, prose = stripped value * * Returns: `{ signature, prose }` — both string-or-null. * Forward-composition design: Substep 3.3 consumes `signature`; * Substep 3.7 consumes `prose`. Single hover request, single * markdown parse, two field consumers. */ export declare function parseRubyHoverContent(value: string): { signature: string | null; prose: string | null; }; /** * URL-encoding dedup utility per ADR-21 §"URL-encoding result * duplication (Windows-specific)". ruby-lsp returns each cross-file * location TWICE under different URI encodings (`c%3A` and `c:` * forms) on Windows; the adapter dedupes via `normalizePath`-driven * tuple-keyed deduplication. * * Generic over the response item type — caller provides an extractor * function returning the URI + position to dedup on. listSymbols * (Substep 3.2) doesn't actually need dedup (single-file response, * no cross-file collisions), but this utility ships now as foundation * for Substeps 3.4 (findReferences), 3.6 (getTypeInfo → * declaration-parse may reuse references), and any cross-file * resolution that surfaces in Substep 3.7. Validates the path-line- * tuple-key shape generalizes across LSP response types. * * Edge cases handled: * - URL-encoded `%3A` vs literal `:` drive-letter forms (probe- * empirical) * - Forward-slash vs backslash separators (normalizePath converts) * - Optional column-component for cases needing finer dedup * granularity than (path, line) */ export declare function dedupLocationsByNormalizedPath(items: readonly T[], extractKey: (item: T) => { uri: string; line: number; col?: number; }): T[]; /** * Parse a Ruby SymbolId (`sym:rb::`) into its components. * Returns null for IDs that don't match the expected shape — callers * treat that as "no such symbol" rather than throwing. * * Ruby symbol names can contain `:`, ` `, `.`, `!`, `?` from DSL macros * (`has_many :posts`), Module::Constant qualification, `self.method` * class-method prefix, and predicate/bang method conventions. Path * component is the first colon-delimited segment after `sym:rb:`. * * Symbol-ID DSL-macro format question raised in Phase 3 plan watch #3 * — empirical resolution comes at Substep 3.2 documentSymbol mapping. */ export declare function parseSymbolId(id: SymbolId): { path: string; name: string; } | null; export { LANG_CODES }; //# sourceMappingURL=ruby.d.ts.map