Searching Codebases Find code in any codebase by pattern or concept. One entry point, two search strategies, automatic routing. When NOT to use this skill Python callers and definitions only. Every other code question is cheaper elsewhere, and the measurement below is why this skill is edge-case-only. | Situation | Use | |---|---| | What symbols does this file contain? | tree-sitting | | Where is X defined, so I can read it? | tree-sitting | | Any structure question, any language | tree-sitting | | A literal string or regex | plain ripgrep | | Which files are most about a concept? | bm25 | |…

, '\\\\', '.'}\n# Only flag as regex if the \"exotic\" ones appear (not just . or parens)\n_STRONG_REGEX_META = {'*', '+', '?', '[', ']', '{', '}', '^', '

Searching Codebases Find code in any codebase by pattern or concept. One entry point, two search strategies, automatic routing. When NOT to use this skill Python callers and definitions only. Every other code question is cheaper elsewhere, and the measurement below is why this skill is edge-case-only. | Situation | Use | |---|---| | What symbols does this file contain? | tree-sitting | | Where is X defined, so I can read it? | tree-sitting | | Any structure question, any language | tree-sitting | | A literal string or regex | plain ripgrep | | Which files are most about a concept? | bm25 | |…

, '\\\\', '|'}\n\n\n# @lat: [[code-intelligence#Multi-Modal Search]]\ndef detect_mode(query: str) -> str:\n \"\"\"\n Heuristic: is this query a regex/literal or a conceptual search?\n\n Returns \"regex\" or \"semantic\".\n \"\"\"\n # Explicit regex markers\n if any(c in query for c in _STRONG_REGEX_META):\n return \"regex\"\n\n # Short queries with code-like tokens → regex (literal search)\n words = query.split()\n if len(words) \u003c= 3:\n # Looks like code: contains underscores, dots, camelCase, parens\n if any(c in query for c in \"_.()\"):\n return \"regex\"\n # Single identifier\n if len(words) == 1:\n return \"regex\"\n\n # Multi-word queries without code markers → semantic\n if len(words) >= 3:\n return \"semantic\"\n\n return \"regex\"\n\n\ndef search_regex(root: str, queries: list, expand: bool = False,\n benchmark: bool = False, verbose: bool = False,\n skip_dirs: set = None) -> dict:\n \"\"\"\n Regex/literal search using sparse n-gram index.\n\n Returns {query: [matches]} where each match has file, line, text,\n and optionally context (expanded function).\n \"\"\"\n from ngram_index import NgramIndex, _brute_force_search\n\n # Build index\n index = NgramIndex()\n file_count = count_files(root, skip_dirs)\n\n # Skip indexing for tiny codebases — just use ripgrep directly\n if file_count \u003c 20 and not benchmark:\n if verbose:\n print(f\"Small codebase ({file_count} files), using direct search\", file=sys.stderr)\n results = {}\n for q in queries:\n from ngram_index import DEFAULT_SKIP_DIRS, _brute_force_search\n matches = _brute_force_search(q, root, skip_dirs or DEFAULT_SKIP_DIRS)\n results[q] = _maybe_expand(matches, root, expand)\n return results\n\n index.build(root, skip_dirs=skip_dirs,\n use_frequency_weights=True, verbose=verbose)\n\n if verbose:\n s = index.stats\n print(f\"Index: {s['files_indexed']} files, {s['unique_ngrams']:,} n-grams, \"\n f\"{s['index_time_ms']:.0f}ms\", file=sys.stderr)\n\n results = {}\n for q in queries:\n if benchmark:\n _run_benchmark(index, q, root, skip_dirs or set())\n else:\n matches = index.search(q, root, max_results=500, verbose=verbose)\n results[q] = _maybe_expand(matches, root, expand)\n\n return results\n\n\ndef search_semantic(root: str, queries: list, expand: bool = False,\n verbose: bool = False, skip_dirs: set = None) -> dict:\n \"\"\"\n Semantic search using TF-IDF over code chunks.\n\n Returns {query: [matches]} with file, line, text, score.\n \"\"\"\n # Ensure sklearn is available\n try:\n from code_rag import Index\n except ImportError:\n subprocess.run(\n [\"uv\", \"pip\", \"install\", \"scikit-learn\", \"--system\"],\n capture_output=True,\n )\n from code_rag import Index\n\n index = Index()\n index.build(root, skip_dirs=skip_dirs)\n\n if verbose:\n s = index.stats()\n print(f\"TF-IDF index: {s.get('chunks', 0)} chunks, {s.get('vocabulary', 0)} terms, \"\n f\"{s.get('build_ms', 0)}ms\", file=sys.stderr)\n\n results = {}\n for q in queries:\n hits = index.search(q, top_k=20)\n matches = []\n for chunk, score in hits:\n matches.append({\n \"file\": os.path.join(root, chunk.file) if not os.path.isabs(chunk.file) else chunk.file,\n \"line\": chunk.line,\n \"text\": chunk.text[:200],\n \"score\": round(score, 4),\n \"kind\": chunk.kind,\n \"name\": chunk.name,\n })\n results[q] = matches\n\n return results\n\n\ndef _maybe_expand(matches: list, root: str, expand: bool) -> list:\n \"\"\"Optionally expand matches to full function context.\"\"\"\n if not expand:\n return matches\n\n from context import expand_match\n\n contexts = []\n for m in matches:\n ctx = expand_match(m[\"file\"], m[\"line\"], root, signatures_only=False)\n if ctx:\n m[\"context\"] = {\n \"name\": ctx.name,\n \"type\": ctx.node_type,\n \"start_line\": ctx.start_line,\n \"end_line\": ctx.end_line,\n \"source\": ctx.source,\n }\n return matches\n\n\ndef _run_benchmark(index, pattern, root, skip_dirs):\n \"\"\"Compare indexed search vs brute-force ripgrep.\"\"\"\n from ngram_index import _brute_force_search\n\n t0 = time.monotonic()\n indexed = index.search(pattern, root, max_results=5000, verbose=False)\n t_idx = (time.monotonic() - t0) * 1000\n\n t0 = time.monotonic()\n brute = _brute_force_search(pattern, root, skip_dirs, max_results=5000)\n t_brute = (time.monotonic() - t0) * 1000\n\n idx_files = {m[\"file\"] for m in indexed}\n brute_files = {m[\"file\"] for m in brute}\n missed = brute_files - idx_files\n\n print(f\"\\n{'='*60}\")\n print(f\"BENCHMARK: '{pattern}'\")\n print(f\"{'='*60}\")\n print(f\" Indexed: {t_idx:8.1f}ms ({len(indexed)} matches, {len(idx_files)} files)\")\n print(f\" Brute rg: {t_brute:8.1f}ms ({len(brute)} matches, {len(brute_files)} files)\")\n if t_brute > 0:\n print(f\" Speedup: {t_brute / max(t_idx, 0.1):.1f}x\")\n if missed:\n print(f\" ⚠ Missed: {len(missed)} files\")\n elif not (idx_files - brute_files):\n print(\" ✓ Results match\")\n\n\ndef format_results(results: dict, root: str, output_json: bool = False) -> str:\n \"\"\"Format search results for display.\"\"\"\n if output_json:\n # Make paths relative\n for q, matches in results.items():\n for m in matches:\n try:\n m[\"file\"] = os.path.relpath(m[\"file\"], root)\n except ValueError:\n pass\n return json.dumps(results, indent=2)\n\n lines = []\n for query, matches in results.items():\n if len(results) > 1:\n lines.append(f\"\\n--- {query} ---\")\n\n if not matches:\n lines.append(\"No matches found.\")\n continue\n\n lines.append(f\"{len(matches)} match{'es' if len(matches) != 1 else ''}\")\n\n for m in matches[:30]:\n try:\n rel = os.path.relpath(m[\"file\"], root)\n except ValueError:\n rel = m[\"file\"]\n\n if \"score\" in m:\n lines.append(f\" {rel}:{m['line']} [{m['score']:.3f}] {m.get('name', '')}\")\n else:\n text = m[\"text\"][:150].rstrip()\n lines.append(f\" {rel}:{m['line']}: {text}\")\n\n if \"context\" in m:\n ctx = m[\"context\"]\n lines.append(f\" → {ctx['type']} {ctx['name']} \"\n f\"(lines {ctx['start_line']}-{ctx['end_line']})\")\n\n if len(matches) > 30:\n lines.append(f\" ... and {len(matches) - 30} more\")\n\n return \"\\n\".join(lines)\n\n\ndef run_lsp_query(root: str, symbol: str, op: str, json_out: bool,\n verbose: bool) -> None:\n \"\"\"Binding-resolved (pyright) tier for Python symbols, with soft fallback.\n\n On any condition where the binding-resolved answer can't be produced\n (non-Python target, pyright/node absent, client unimportable), emit a\n one-line degradation note and fall back to the regex text path so the user\n still gets results.\n \"\"\"\n from lsp_refs import LspUnavailable, format_lsp, lsp_query\n\n try:\n result = lsp_query(root, symbol, op=op, verbose=verbose)\n except LspUnavailable as e:\n print(f\"[python-lsp unavailable: {e}] falling back to regex text search\",\n file=sys.stderr)\n results = search_regex(root, [symbol], verbose=verbose)\n print(format_results(results, root, json_out))\n return\n print(format_lsp(result, root, json_out))\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Unified code search\")\n parser.add_argument(\"source\", help=\"Path, GitHub URL, 'uploads', or 'project'\")\n parser.add_argument(\"queries\", nargs=\"*\", help=\"Search queries\")\n parser.add_argument(\"--regex\", action=\"store_true\", help=\"Force regex mode\")\n parser.add_argument(\"--semantic\", action=\"store_true\", help=\"Force semantic mode\")\n parser.add_argument(\"--expand\", action=\"store_true\", help=\"Expand to full function bodies\")\n parser.add_argument(\"--benchmark\", action=\"store_true\", help=\"Benchmark indexed vs brute-force\")\n parser.add_argument(\"--refs\", metavar=\"SYMBOL\", default=None,\n help=\"Binding-resolved references for a Python SYMBOL (pyright; \"\n \"excludes same-named unrelated symbols)\")\n parser.add_argument(\"--def\", dest=\"defn\", metavar=\"SYMBOL\", default=None,\n help=\"Binding-resolved go-to-definition for a Python SYMBOL \"\n \"(follows imports across files)\")\n parser.add_argument(\"--hover\", metavar=\"SYMBOL\", default=None,\n help=\"Inferred type/signature for a Python SYMBOL (pyright)\")\n parser.add_argument(\"--branch\", default=\"main\", help=\"Git branch for GitHub URLs\")\n parser.add_argument(\"--skip\", default=None, help=\"Comma-separated directories to skip\")\n parser.add_argument(\"--json\", action=\"store_true\", help=\"JSON output\")\n parser.add_argument(\"-v\", \"--verbose\", action=\"store_true\")\n\n args = parser.parse_args()\n\n # Resolve source\n root = resolve(args.source, args.branch)\n if args.verbose:\n print(f\"Resolved: {root} ({count_files(root)} files)\", file=sys.stderr)\n\n # Binding-resolved tier (Python only, engaged lazily). Mutually exclusive\n # with the text-search queries — these answer a single symbol query.\n lsp_ops = [(\"references\", args.refs), (\"definition\", args.defn), (\"hover\", args.hover)]\n active = [(op, sym) for op, sym in lsp_ops if sym]\n if active:\n if len(active) > 1:\n parser.error(\"--refs / --def / --hover are mutually exclusive\")\n op, symbol = active[0]\n run_lsp_query(root, symbol, op, args.json, args.verbose)\n return\n\n if not args.queries:\n parser.error(\"no queries given (provide search terms, or use --refs/--def/--hover)\")\n\n skip_dirs = None\n if args.skip:\n skip_dirs = set(args.skip.split(\",\"))\n\n # Route queries\n all_results = {}\n for query in args.queries:\n if args.regex:\n mode = \"regex\"\n elif args.semantic:\n mode = \"semantic\"\n else:\n mode = detect_mode(query)\n\n if args.verbose:\n print(f\"Query: '{query}' → {mode} mode\", file=sys.stderr)\n\n # Batch by mode for efficiency (one index build per mode)\n regex_queries = []\n semantic_queries = []\n for query in args.queries:\n if args.regex:\n regex_queries.append(query)\n elif args.semantic:\n semantic_queries.append(query)\n else:\n mode = detect_mode(query)\n if mode == \"regex\":\n regex_queries.append(query)\n else:\n semantic_queries.append(query)\n\n if regex_queries:\n results = search_regex(root, regex_queries, expand=args.expand,\n benchmark=args.benchmark, verbose=args.verbose,\n skip_dirs=skip_dirs)\n all_results.update(results)\n\n if semantic_queries:\n results = search_semantic(root, semantic_queries, expand=args.expand,\n verbose=args.verbose, skip_dirs=skip_dirs)\n all_results.update(results)\n\n if not args.benchmark:\n print(format_results(all_results, root, args.json))\n\n\nif __name__ == \"__main__\":\n main()\n","content_type":"text/x-python; charset=utf-8","language":"python","size":13106,"content_sha256":"aaf71b7e0f11db922c6713004dc74a13fd6f764de64fc23160d6cdcc84270b71"},{"filename":"scripts/sparse_ngrams.py","content":"\"\"\"\nSparse N-gram extraction for fast regex search indexing.\n\nBased on the approach described by Cursor (2026): variable-length n-grams\nselected deterministically via a weight function over character pairs.\n\nTwo modes:\n- build_all: Extract ALL valid sparse n-grams (used at index time)\n- build_covering: Extract MINIMAL covering set (used at query time)\n\nA sparse n-gram is a substring where the character-pair weights at both\nboundary positions are strictly greater than all interior weights.\n\"\"\"\n\nimport zlib\n\n\ndef weight_crc32(a: int, b: int) -> int:\n \"\"\"CRC32-based weight for a character pair. Deterministic, uniform.\"\"\"\n return zlib.crc32(bytes([a, b])) & 0xFFFFFFFF\n\n\nclass FrequencyWeights:\n \"\"\"\n Frequency-based weight function: rare character pairs get HIGH weights,\n common pairs get LOW weights. This produces longer n-grams at rare\n boundaries (more selective posting lists) and shorter n-grams at common\n boundaries (acceptable since they appear everywhere anyway).\n \"\"\"\n\n def __init__(self):\n self._freq: dict[tuple[int, int], int] = {}\n self._max_freq: int = 1\n self._frozen = False\n\n def train(self, data: bytes):\n \"\"\"Accumulate character pair frequencies from training data.\"\"\"\n if self._frozen:\n raise RuntimeError(\"Cannot train after freezing\")\n for i in range(len(data) - 1):\n pair = (data[i], data[i + 1])\n self._freq[pair] = self._freq.get(pair, 0) + 1\n\n def freeze(self):\n \"\"\"Finalize the frequency table. Converts frequencies to weights.\"\"\"\n if self._freq:\n self._max_freq = max(self._freq.values())\n self._frozen = True\n\n def weight(self, a: int, b: int) -> int:\n \"\"\"\n Weight for a character pair. Higher = rarer.\n Uses inverted frequency: rare pairs get high weights.\n Falls back to CRC32 for unseen pairs (treated as very rare).\n \"\"\"\n if not self._frozen:\n raise RuntimeError(\"Must freeze() before computing weights\")\n freq = self._freq.get((a, b), 0)\n if freq == 0:\n # Unseen pair = very rare = high weight\n return self._max_freq + weight_crc32(a, b) % (self._max_freq // 2 + 1)\n # Invert: rare = high weight\n return self._max_freq - freq + 1\n\n def save(self) -> bytes:\n \"\"\"Serialize frequency table.\"\"\"\n import json\n data = {\n \"freq\": {f\"{a},{b}\": c for (a, b), c in self._freq.items()},\n \"max_freq\": self._max_freq,\n }\n return json.dumps(data).encode()\n\n @classmethod\n def load(cls, raw: bytes) -> \"FrequencyWeights\":\n \"\"\"Deserialize frequency table.\"\"\"\n import json\n data = json.loads(raw)\n w = cls()\n w._freq = {\n (int(k.split(\",\")[0]), int(k.split(\",\")[1])): v\n for k, v in data[\"freq\"].items()\n }\n w._max_freq = data[\"max_freq\"]\n w._frozen = True\n return w\n\n\ndef compute_weights(\n text: bytes, weight_fn=weight_crc32\n) -> list[int]:\n \"\"\"Compute weights for all consecutive character pairs in text.\"\"\"\n if len(text) \u003c 2:\n return []\n return [weight_fn(text[i], text[i + 1]) for i in range(len(text) - 1)]\n\n\ndef build_all(weights: list[int]) -> list[tuple[int, int]]:\n \"\"\"\n Extract ALL valid sparse n-grams from a weight sequence.\n\n Uses a monotone stack algorithm (O(n) amortized).\n\n Returns list of (start_pair_pos, end_pair_pos) where each n-gram\n spans characters [start_pair_pos, end_pair_pos + 2) in the original text.\n\n A sparse n-gram from pair position a to pair position b is valid iff\n w[a] > w[k] and w[b] > w[k] for all a \u003c k \u003c b.\n \"\"\"\n n = len(weights)\n if n == 0:\n return []\n if n == 1:\n return [(0, 0)]\n\n ngrams = []\n # Monotone decreasing stack of pair positions\n stack: list[int] = []\n\n for i in range(n):\n # Pop positions dominated by current weight\n while stack and weights[i] >= weights[stack[-1]]:\n j = stack.pop()\n # (j, i) is valid: j and i are both >= weights[j],\n # and everything between j and i on the stack was already\n # popped (so had weight \u003c w[j] \u003c w[i])\n ngrams.append((j, i))\n\n # Adjacent stack entry to current position forms valid n-gram\n if stack:\n ngrams.append((stack[-1], i))\n\n stack.append(i)\n\n return ngrams\n\n\ndef build_covering(weights: list[int]) -> list[tuple[int, int]]:\n \"\"\"\n Extract the MINIMAL covering set of sparse n-grams.\n\n Used at query time: produces the fewest, longest n-grams needed\n to look up in the index. Any document containing the query text\n must contain all of these n-grams.\n\n Greedy: from each position, jump to the farthest valid endpoint\n (the first position with weight >= current).\n \"\"\"\n n = len(weights)\n if n == 0:\n return []\n if n == 1:\n return [(0, 0)]\n\n ngrams = []\n i = 0\n\n while i \u003c n:\n # Find the first position j > i where w[j] >= w[i]\n j = i + 1\n while j \u003c n and weights[j] \u003c weights[i]:\n j += 1\n\n if j >= n:\n # No higher weight found — take the highest remaining position\n # as the endpoint (best available boundary)\n if i \u003c n - 1:\n best = i + 1\n for k in range(i + 2, n):\n if weights[k] > weights[best]:\n best = k\n ngrams.append((i, best))\n i = best\n else:\n # At the last position, nothing more to cover\n break\n else:\n ngrams.append((i, j))\n i = j\n\n return ngrams\n\n\ndef ngram_text(text: bytes, start: int, end: int) -> bytes:\n \"\"\"\n Extract the n-gram substring from text given pair positions.\n Pair position p corresponds to characters text[p:p+2].\n N-gram from pair a to pair b spans text[a:b+2].\n \"\"\"\n return text[start : end + 2]\n\n\ndef ngram_hash(text: bytes, start: int, end: int) -> int:\n \"\"\"Hash an n-gram for use as index key. Uses CRC32 for speed.\"\"\"\n return zlib.crc32(text[start : end + 2]) & 0xFFFFFFFF\n","content_type":"text/x-python; charset=utf-8","language":"python","size":6239,"content_sha256":"381aed2335fbac3c046e3203de30ae94c93904c58324893a7ed5f6d2eaf3ddcd"},{"filename":"tests/fixture/pkg/__init__.py","content":"","content_type":"text/x-python; charset=utf-8","language":"python","size":0,"content_sha256":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"},{"filename":"tests/fixture/pkg/models.py","content":"class User:\n def __init__(self, name: str) -> None:\n self.name = name\n\n def greet(self) -> str:\n return f\"hi {self.name}\"\n\n\ndef helper(x: int) -> int:\n return x + 1\n","content_type":"text/x-python; charset=utf-8","language":"python","size":188,"content_sha256":"e59db23e6956322ad8bde482e5deb6eb827af7aed482f033a681871d91e4ae8d"},{"filename":"tests/fixture/pkg/other.py","content":"def helper() -> str:\n return \"unrelated\"\n\n\nprint(helper())\n","content_type":"text/x-python; charset=utf-8","language":"python","size":62,"content_sha256":"e443e8e3e9e40cd9424dc61c2eb6f3c7b3c4cc7abe6bb6e445f30427e540060c"},{"filename":"tests/fixture/pkg/service.py","content":"from pkg.models import User, helper\n\n\ndef make_user(name: str) -> User:\n u = User(name)\n print(helper(3))\n return u\n","content_type":"text/x-python; charset=utf-8","language":"python","size":125,"content_sha256":"7dc5d6779274c3dc5d91f9461e628df109ff2be8b8148defe6b57913a9167d8e"},{"filename":"tests/test_lsp_refs.py","content":"\"\"\"Tests for the binding-resolved (python-lsp) tier of searching-codebases.\n\nRound-trips against a small multi-file fixture driving a real\n``pyright-langserver``, and exercises the mandatory soft-fallback contract.\n\nRun: python -m pytest searching-codebases/tests/test_lsp_refs.py -v\nOr: python searching-codebases/tests/test_lsp_refs.py (standalone)\n\nThe semantic tests require pyright (and system node); they are skipped if the\nbootstrap can't make pyright available. The fallback tests have no such\ndependency — they assert the degradation path.\n\"\"\"\n\nimport subprocess\nimport sys\nfrom pathlib import Path\n\nimport pytest\n\nSCRIPTS = Path(__file__).resolve().parent.parent / \"scripts\"\nsys.path.insert(0, str(SCRIPTS))\n\nimport lsp_refs\nfrom lsp_refs import (\n LspUnavailable,\n definition_sites,\n lsp_query,\n occurrence_sites,\n)\n\nFIXTURE = str(Path(__file__).parent / \"fixture\")\n\n\ndef _pyright_available() -> bool:\n try:\n lsp = lsp_refs._import_lsp_client()\n lsp.ensure_pyright(install=True)\n return True\n except Exception:\n return False\n\n\npyright = pytest.mark.skipif(not _pyright_available(),\n reason=\"pyright/node unavailable\")\n\n\ndef _pyright_proc_count() -> int:\n out = subprocess.run([\"pgrep\", \"-f\", \"pyright-langserver\"],\n capture_output=True, text=True).stdout\n return len([ln for ln in out.splitlines() if ln.strip()])\n\n\n# ── symbol → position resolution (no server) ─────────────────────────────────\n\ndef test_definition_sites_finds_both_helpers():\n sites = definition_sites(FIXTURE, \"helper\")\n by_file = {s.file: s for s in sites}\n assert \"pkg/models.py\" in by_file and \"pkg/other.py\" in by_file\n # Column lands on the symbol token, not the `def` keyword (1-based).\n assert by_file[\"pkg/models.py\"].col == 5 # \"def helper\" -> h at col 5\n assert by_file[\"pkg/models.py\"].line == 9\n\n\ndef test_occurrence_sites_are_a_superset():\n occ = occurrence_sites(FIXTURE, \"helper\")\n files = {s.file for s in occ}\n # Text matching catches all three files (including the unrelated other.py).\n assert {\"pkg/models.py\", \"pkg/other.py\", \"pkg/service.py\"} \u003c= files\n\n\n# ── binding-resolved queries (the win over regex) ────────────────────────────\n\n@pyright\ndef test_references_exclude_unrelated_same_named_symbol():\n result = lsp_query(FIXTURE, \"helper\", op=\"references\")\n groups = {g[\"anchor\"].file: g for g in result[\"results\"]}\n # The models.py binding's references include its def and the use in\n # service.py, but EXCLUDE the unrelated helper in other.py.\n models = {Path(loc.path).name for loc in groups[\"pkg/models.py\"][\"locations\"]}\n models_files = {str(Path(loc.path).relative_to(Path(FIXTURE)))\n for loc in groups[\"pkg/models.py\"][\"locations\"]}\n assert \"pkg/models.py\" in models_files\n assert \"pkg/service.py\" in models_files\n assert \"pkg/other.py\" not in models_files, (\n \"binding-resolved references must exclude the same-named unrelated symbol\"\n )\n assert \"models.py\" in models # sanity on the name extraction\n\n\n@pyright\ndef test_definition_follows_import_across_files():\n result = lsp_query(FIXTURE, \"User\", op=\"definition\")\n locs = result[\"results\"][0][\"locations\"]\n files = {str(Path(loc.path).relative_to(Path(FIXTURE))) for loc in locs}\n # Anchored at every occurrence (incl. the import + use in service.py),\n # definition resolves across the import to the class in models.py.\n assert \"pkg/models.py\" in files\n\n\n@pyright\ndef test_hover_returns_inferred_signature():\n result = lsp_query(FIXTURE, \"helper\", op=\"hover\")\n hovers = \" \".join(g[\"hover\"] or \"\" for g in result[\"results\"])\n assert \"helper\" in hovers and \"int\" in hovers\n\n\n@pyright\ndef test_indexing_wait_makes_queries_deterministic():\n # Without wait_for_index this would flake to empty. Repeat must be stable.\n for _ in range(2):\n result = lsp_query(FIXTURE, \"User\", op=\"references\")\n total = sum(len(g[\"locations\"]) for g in result[\"results\"])\n assert total >= 3\n\n\n@pyright\ndef test_no_orphaned_subprocess():\n before = _pyright_proc_count()\n lsp_query(FIXTURE, \"User\", op=\"references\")\n # Context manager in lsp_query must reap the server.\n assert _pyright_proc_count() == before, \"pyright-langserver leaked\"\n\n\n# ── soft-fallback contract (no pyright dependency) ───────────────────────────\n\ndef test_missing_symbol_raises_lsp_unavailable():\n with pytest.raises(LspUnavailable):\n lsp_query(FIXTURE, \"NoSuchSymbolAnywhere\", op=\"references\")\n\n\ndef test_bootstrap_failure_raises_lsp_unavailable(monkeypatch):\n # Simulate node/pyright absence: ensure_pyright fails loud, the tier must\n # degrade (raise LspUnavailable) rather than hang.\n lsp = lsp_refs._import_lsp_client()\n\n def boom(*a, **k):\n raise lsp.BootstrapError(\"pyright requires system 'node' but none found\")\n\n monkeypatch.setattr(lsp, \"ensure_pyright\", boom)\n with pytest.raises(LspUnavailable) as exc:\n lsp_query(FIXTURE, \"helper\", op=\"references\")\n assert \"node\" in str(exc.value).lower()\n\n\n# ── standalone runner ────────────────────────────────────────────────────────\n\nif __name__ == \"__main__\":\n raise SystemExit(pytest.main([__file__, \"-v\"]))\n","content_type":"text/x-python; charset=utf-8","language":"python","size":5595,"content_sha256":"1d44fb04e5b917db02b805af132b52e4224e31969df84ecafbc4ea95666db13f"}],"content_json":{"type":"doc","content":[{"type":"heading","attrs":{"level":1},"content":[{"text":"Searching Codebases","type":"text"}]},{"type":"paragraph","content":[{"text":"Find code in any codebase by pattern or concept. One entry point, two search strategies, automatic routing.","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"When NOT to use this skill","type":"text"}]},{"type":"paragraph","content":[{"text":"Python callers and definitions only. Every other code question is cheaper elsewhere, and the measurement below is why this skill is edge-case-only.","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"Situation","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"Use","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"What symbols does this file contain?","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"tree-sitting","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"Where is X defined, so I can read it?","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"tree-sitting","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"Any structure question, any language","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"tree-sitting","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"A literal string or regex","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"plain ripgrep","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"Which files are most about a concept?","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"bm25","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"First look at an unfamiliar repo","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"exploring-codebases","type":"text"}]}]}]}]},{"type":"paragraph","content":[{"text":"Non-Python code has no pyright binding resolution to offer, so there is no version of this skill that applies to it.","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Prerequisites","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"bash"},"content":[{"text":"uv tool install ripgrep","type":"text"}]},{"type":"paragraph","content":[{"text":"tree-sitting installs automatically when needed — for ","type":"text"},{"text":"--expand","type":"text","marks":[{"type":"code_inline"}]},{"text":" context expansion and for the binding-resolved ","type":"text"},{"text":"--refs","type":"text","marks":[{"type":"code_inline"}]},{"text":"/","type":"text"},{"text":"--def","type":"text","marks":[{"type":"code_inline"}]},{"text":"/","type":"text"},{"text":"--hover","type":"text","marks":[{"type":"code_inline"}]},{"text":" tier, which uses it to resolve symbol positions. Only the bare ","type":"text"},{"text":"tree-sitter","type":"text","marks":[{"type":"code_inline"}]},{"text":" package is fetched; the language grammars ship bundled.","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Primary Command","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"bash"},"content":[{"text":"SKILL_DIR=/mnt/skills/user/searching-codebases\n\npython3 $SKILL_DIR/scripts/search.py SOURCE \"query1\" [\"query2\" ...] [OPTIONS]","type":"text"}]},{"type":"paragraph","content":[{"text":"SOURCE is any of:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Local directory path","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"GitHub URL (downloads tarball automatically)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"uploads","type":"text","marks":[{"type":"code_inline"}]},{"text":" (uses ","type":"text"},{"text":"/mnt/user-data/uploads/","type":"text","marks":[{"type":"code_inline"}]},{"text":")","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"project","type":"text","marks":[{"type":"code_inline"}]},{"text":" (uses ","type":"text"},{"text":"/mnt/project/","type":"text","marks":[{"type":"code_inline"}]},{"text":")","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Path to a ","type":"text"},{"text":".zip","type":"text","marks":[{"type":"code_inline"}]},{"text":" or ","type":"text"},{"text":".tar.gz","type":"text","marks":[{"type":"code_inline"}]},{"text":" archive","type":"text"}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Search Modes","type":"text"}]},{"type":"paragraph","content":[{"text":"Regex mode","type":"text","marks":[{"type":"strong"}]},{"text":" (patterns, identifiers, literal text):","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"bash"},"content":[{"text":"python3 $SKILL_DIR/scripts/search.py ./repo \"def handle_error\"\npython3 $SKILL_DIR/scripts/search.py ./repo \"class.*Exception\" --regex\npython3 $SKILL_DIR/scripts/search.py ./repo \"TODO|FIXME|HACK\"","type":"text"}]},{"type":"paragraph","content":[{"text":"Semantic mode","type":"text","marks":[{"type":"strong"}]},{"text":" (concepts, natural language):","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"bash"},"content":[{"text":"python3 $SKILL_DIR/scripts/search.py ./repo \"retry logic with backoff\" --semantic\npython3 $SKILL_DIR/scripts/search.py ./repo \"authentication flow\"\npython3 $SKILL_DIR/scripts/search.py ./repo \"error handling strategy\"","type":"text"}]},{"type":"paragraph","content":[{"text":"Auto-detection: short queries and code-like tokens → regex. Multi-word natural language → semantic. Override with ","type":"text"},{"text":"--regex","type":"text","marks":[{"type":"code_inline"}]},{"text":" or ","type":"text"},{"text":"--semantic","type":"text","marks":[{"type":"code_inline"}]},{"text":".","type":"text"}]},{"type":"paragraph","content":[{"text":"Binding-resolved mode","type":"text","marks":[{"type":"strong"}]},{"text":" (Python only — pyright via the ","type":"text"},{"text":"python-lsp","type":"text","marks":[{"type":"code_inline"}]},{"text":" skill):","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"bash"},"content":[{"text":"python3 $SKILL_DIR/scripts/search.py ./repo --refs SYMBOL # find all real uses\npython3 $SKILL_DIR/scripts/search.py ./repo --def SYMBOL # go-to-definition\npython3 $SKILL_DIR/scripts/search.py ./repo --hover SYMBOL # inferred type/signature","type":"text"}]},{"type":"paragraph","content":[{"text":"Regex mode matches ","type":"text"},{"text":"text","type":"text","marks":[{"type":"em"}]},{"text":", so a cross-reference for a function false-positives on shadowed and same-named-but-unrelated symbols. ","type":"text"},{"text":"--refs","type":"text","marks":[{"type":"code_inline"}]},{"text":" is ","type":"text"},{"text":"binding-resolved","type":"text","marks":[{"type":"strong"}]},{"text":": pyright excludes the unrelated same-named symbol and follows imports. Use it when you need a true \"find all callers/users\" for a ","type":"text"},{"text":".py","type":"text","marks":[{"type":"code_inline"}]},{"text":" symbol, not a text grep.","type":"text"}]},{"type":"paragraph","content":[{"text":"The tier is engaged ","type":"text"},{"text":"lazily","type":"text","marks":[{"type":"strong"}]},{"text":" — pyright's index cost is paid only when you ask for ","type":"text"},{"text":"--refs","type":"text","marks":[{"type":"code_inline"}]},{"text":"/","type":"text"},{"text":"--def","type":"text","marks":[{"type":"code_inline"}]},{"text":"/","type":"text"},{"text":"--hover","type":"text","marks":[{"type":"code_inline"}]},{"text":", never on ordinary searches. It is ","type":"text"},{"text":"Python-only","type":"text","marks":[{"type":"strong"}]},{"text":"; for non-","type":"text"},{"text":".py","type":"text","marks":[{"type":"code_inline"}]},{"text":" sources, or when pyright/node is unavailable, it prints a one-line degradation note and falls back to the regex text path. Each takes a single bare symbol name and is mutually exclusive with the other two and with text queries.","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Options","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"--regex","type":"text","marks":[{"type":"code_inline"}]},{"text":" / ","type":"text"},{"text":"--semantic","type":"text","marks":[{"type":"code_inline"}]},{"text":": Force search mode","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"--refs SYMBOL","type":"text","marks":[{"type":"code_inline"}]},{"text":" / ","type":"text"},{"text":"--def SYMBOL","type":"text","marks":[{"type":"code_inline"}]},{"text":" / ","type":"text"},{"text":"--hover SYMBOL","type":"text","marks":[{"type":"code_inline"}]},{"text":": Binding-resolved Python queries via pyright (see Binding-resolved mode above)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"--expand","type":"text","marks":[{"type":"code_inline"}]},{"text":": Return full function bodies via tree-sitting AST context","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"--benchmark","type":"text","marks":[{"type":"code_inline"}]},{"text":": Compare indexed regex vs brute-force ripgrep","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"--branch NAME","type":"text","marks":[{"type":"code_inline"}]},{"text":": Git branch for GitHub URLs (default: main)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"--skip DIRS","type":"text","marks":[{"type":"code_inline"}]},{"text":": Comma-separated directories to skip","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"--json","type":"text","marks":[{"type":"code_inline"}]},{"text":": Machine-readable output","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"-v","type":"text","marks":[{"type":"code_inline"}]},{"text":": Show index stats and query routing decisions","type":"text"}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"How It Works","type":"text"}]},{"type":"paragraph","content":[{"text":"Regex search","type":"text","marks":[{"type":"strong"}]},{"text":" builds a sparse n-gram inverted index over all files. Queries are decomposed into literal fragments, looked up in the index to identify candidate files (typically 90-99% reduction), then verified with ripgrep. Frequency-weighted n-grams make rare character sequences more selective.","type":"text"}]},{"type":"paragraph","content":[{"text":"Semantic search","type":"text","marks":[{"type":"strong"}]},{"text":" builds a TF-IDF index over code chunks (functions, classes, structural entries). Queries are ranked by cosine similarity.","type":"text"}]},{"type":"paragraph","content":[{"text":"Context expansion","type":"text","marks":[{"type":"strong"}]},{"text":" (","type":"text"},{"text":"--expand","type":"text","marks":[{"type":"code_inline"}]},{"text":") uses tree-sitting's AST cache to identify function/class boundaries, returning complete structural units rather than line fragments. On first use, tree-sitting scans the repo (~700ms for 250 files); subsequent expansions are sub-millisecond.","type":"text"}]},{"type":"paragraph","content":[{"text":"Small codebases","type":"text","marks":[{"type":"strong"}]},{"text":" (\u003c 20 files) skip indexing entirely — direct ripgrep is faster when there's nothing to narrow.","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Mixed Queries","type":"text"}]},{"type":"paragraph","content":[{"text":"Multiple queries can use different modes in a single invocation. Each query is auto-routed independently, and indexes are built once per mode:","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"bash"},"content":[{"text":"python3 $SKILL_DIR/scripts/search.py ./repo \\\n \"class.*Error\" \\\n \"error recovery strategy\" \\\n \"def retry\"","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Dependencies","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"tree-sitting","type":"text","marks":[{"type":"strong"}]},{"text":": Provides AST context expansion for ","type":"text"},{"text":"--expand","type":"text","marks":[{"type":"code_inline"}]},{"text":" ","type":"text"},{"text":"and","type":"text","marks":[{"type":"em"}]},{"text":" the symbol→position resolution that seeds the binding-resolved tier (","type":"text"},{"text":"--refs","type":"text","marks":[{"type":"code_inline"}]},{"text":"/","type":"text"},{"text":"--def","type":"text","marks":[{"type":"code_inline"}]},{"text":"/","type":"text"},{"text":"--hover","type":"text","marks":[{"type":"code_inline"}]},{"text":"). Auto-installs the bare ","type":"text"},{"text":"tree-sitter","type":"text","marks":[{"type":"code_inline"}]},{"text":" package when either is used (grammars are bundled). Regex and semantic search work without it.","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"ripgrep","type":"text","marks":[{"type":"strong"}]},{"text":": Required for regex verification. Install via ","type":"text"},{"text":"uv tool install ripgrep","type":"text","marks":[{"type":"code_inline"}]},{"text":".","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"scikit-learn","type":"text","marks":[{"type":"strong"}]},{"text":": Required for semantic mode. Installs automatically.","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"python-lsp","type":"text","marks":[{"type":"strong"}]},{"text":": Provides the binding-resolved tier (","type":"text"},{"text":"--refs","type":"text","marks":[{"type":"code_inline"}]},{"text":"/","type":"text"},{"text":"--def","type":"text","marks":[{"type":"code_inline"}]},{"text":"/","type":"text"},{"text":"--hover","type":"text","marks":[{"type":"code_inline"}]},{"text":"). Self-bootstraps pyright on first use and requires system ","type":"text"},{"text":"node","type":"text","marks":[{"type":"code_inline"}]},{"text":" (v18+). Not required — without it those flags degrade to the regex text path.","type":"text"}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"When to Use — narrow, by design","type":"text"}]},{"type":"paragraph","content":[{"text":"The ONE recommended use: ","type":"text"},{"text":"binding-resolved Python symbol queries","type":"text","marks":[{"type":"strong"}]},{"text":".","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"\"find all callers of ","type":"text"},{"text":"X","type":"text","marks":[{"type":"code_inline"}]},{"text":"\" / \"where is ","type":"text"},{"text":"X","type":"text","marks":[{"type":"code_inline"}]},{"text":" really defined\" for a ","type":"text"},{"text":".py","type":"text","marks":[{"type":"code_inline"}]},{"text":" symbol, when same-named-but-unrelated symbols would pollute a text grep. Empirical basis: ","type":"text"},{"text":"rg get","type":"text","marks":[{"type":"code_inline"}]},{"text":" on psf/requests returned 232 hits, 224 of them false; ","type":"text"},{"text":"--refs get","type":"text","marks":[{"type":"code_inline"}]},{"text":" excluded all 224 (2026-06-15).","type":"text"}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"When NOT to Use — which is most of the time","type":"text"}]},{"type":"paragraph","content":[{"text":"Everything else. Measured head-to-head on real issue-localization tasks (7 scikit-learn issues with merged fix-PRs, gold = PR diff files, 2026-07-04, replicating the file-discovery metric of arXiv:2602.11988):","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Literal tokens / identifiers","type":"text","marks":[{"type":"strong"}]},{"text":": naive ","type":"text"},{"text":"rg -l","type":"text","marks":[{"type":"code_inline"}]},{"text":" tied or beat the indexed tier on recall@10 in every instance, at 0.4s vs 25s.","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Concept / natural-language search","type":"text","marks":[{"type":"strong"}]},{"text":": the TF-IDF semantic tier never beat identifier grep — not even on identifier-poor issues, which are themselves rare (~0.3% of merged-PR traffic in the sample).","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"First encounter / \"what is this repo\"","type":"text","marks":[{"type":"strong"}]},{"text":": use exploring-codebases.","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Repos under ~20 files","type":"text","marks":[{"type":"strong"}]},{"text":": read them.","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"The self-test before invoking: would plain ","type":"text"},{"text":"rg","type":"text","marks":[{"type":"code_inline"}]},{"text":" return the same answer? If yes, use rg. The indexed-regex and semantic tiers are retained for completeness and for corpora where they may yet earn their cost (very large repos, non-code document collections), but they carry the burden of proof.","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Files","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"scripts/search.py","type":"text","marks":[{"type":"code_inline"}]},{"text":" — Entry point, query routing, output formatting","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"scripts/resolve.py","type":"text","marks":[{"type":"code_inline"}]},{"text":" — Input source resolution (GitHub, uploads, archives)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"scripts/context.py","type":"text","marks":[{"type":"code_inline"}]},{"text":" — tree-sitting-based AST context expansion","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"scripts/ngram_index.py","type":"text","marks":[{"type":"code_inline"}]},{"text":" — Sparse n-gram inverted index, regex decomposition","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"scripts/sparse_ngrams.py","type":"text","marks":[{"type":"code_inline"}]},{"text":" — Core n-gram algorithms, frequency weights","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"scripts/code_rag.py","type":"text","marks":[{"type":"code_inline"}]},{"text":" — TF-IDF semantic search over code chunks","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"scripts/lsp_refs.py","type":"text","marks":[{"type":"code_inline"}]},{"text":" — Binding-resolved Python tier: symbol→position resolution (tree-sitting), pyright queries (python-lsp), soft fallback","type":"text"}]}]}]}]},"metadata":{"date":"2026-06-05","name":"searching-codebases","author":"@skillopedia","source":{"stars":124,"repo_name":"claude-skills","origin_url":"https://github.com/oaustegard/claude-skills/blob/HEAD/searching-codebases/SKILL.md","repo_owner":"oaustegard","body_sha256":"3658c49c783396e93c7c977195e312bfa59085a17a7ecf7d5094216fc5b41517","cluster_key":"2d33203d10273d6bc936eb1dd3938297ce55f26b6d551be12373458a68e24558","refresh_tag":"upstream-refresh-2026-11","clean_bundle":{"format":"clean-skill-bundle-v1","source":"oaustegard/claude-skills/searching-codebases/SKILL.md","bundle_sha256":"3eb531e6e845a629348855e951df2aa739f6dbee6bb63dba567fc2f25dca5b65","attachment_count":14,"text_attachments":14,"attachment_storage":"skill_attachments","binary_attachments":0},"cluster_size":1,"refreshed_at":"2026-11-02T23:15:34.200Z","skill_md_path":"searching-codebases/SKILL.md","import_metadata":{"date":"2026-06-05","author":"@skillopedia","version":"v1","category":"data-analytics","category_label":"Data"},"upstream_commit":"654594f4c728d12b7d3b2bfcc8c916b263ced4ab","exact_dupes_collapsed_into_this":0},"version":"v1","category":"data-analytics","metadata":{"version":"2.5.0"},"import_tag":"clean-skills-v1","description":"Binding-resolved Python symbol queries via pyright — every true caller (--refs), the real definition (--def), or an inferred signature (--hover) of a .py symbol, excluding the same-named false positives text search cannot tell apart. Use when a task needs ALL callers or users of a named Python symbol and grep would over-match. Python only, and only for the caller/definition question: measured 2026-07-04 on real issue-localization tasks, plain ripgrep tied or beat the semantic and indexed-regex tiers at 4-60x less wall-clock, so those tiers survive below without being a default."}},"renderedAt":1794102144783}

Searching Codebases Find code in any codebase by pattern or concept. One entry point, two search strategies, automatic routing. When NOT to use this skill Python callers and definitions only. Every other code question is cheaper elsewhere, and the measurement below is why this skill is edge-case-only. | Situation | Use | |---|---| | What symbols does this file contain? | tree-sitting | | Where is X defined, so I can read it? | tree-sitting | | Any structure question, any language | tree-sitting | | A literal string or regex | plain ripgrep | | Which files are most about a concept? | bm25 | |…