diff --git a/scripts/check_import_contracts.py b/scripts/check_import_contracts.py new file mode 100644 index 000000000..4d6303295 --- /dev/null +++ b/scripts/check_import_contracts.py @@ -0,0 +1,440 @@ +#!/usr/bin/env python3 +"""Ratchet for the package dependency contracts in ``.importlinter``. + +The contracts state where the code must end up (modular packaging, see +``plans/designs/modular-endstate.md`` section 3). Today's tree breaks them, so +this script does not require zero violations; it requires that the set of +violations matches the committed baseline exactly: + +* a violation not in the baseline (a new forbidden import, or one more line + for an import that is already there) fails; +* a baseline entry that no longer occurs, or occurs on fewer lines, fails + too, until the baseline is lowered -- otherwise the freed headroom would let + a new import in unnoticed. + +Violations are counted by import-linter itself (same engine, same contract +semantics as ``lint-imports``): one per import statement LINE, keyed +``importer -> imported``. import-linter parses every import statement in a +module, including those inside functions and under ``TYPE_CHECKING``. What it +cannot see is a dynamic import by string, ``importlib.import_module("x.y")`` or +``__import__("x.y")``; those are found here by AST and counted under +``importer -> imported (dynamic)``. + +Usage:: + + python3 scripts/check_import_contracts.py # check (CI, lint.sh) + python3 scripts/check_import_contracts.py --write # rewrite the baseline + +Rewrite the baseline only to LOWER it after removing imports. Adding an entry +to make a new import pass defeats the contract. +""" + +from __future__ import annotations + +import argparse +import ast +import importlib +import json +import sys +from dataclasses import dataclass, field +from pathlib import Path +from typing import Dict, Iterator, List, Optional, Sequence, Tuple + +REPO_ROOT = Path(__file__).resolve().parents[1] +CONFIG_PATH = REPO_ROOT / ".importlinter" +BASELINE_PATH = REPO_ROOT / "scripts" / "import_contracts_ratchet.json" +#: Directories put on sys.path so import-linter can find every root package. +SEARCH_PATHS: Tuple[Path, ...] = ( + REPO_ROOT / "src", + REPO_ROOT / "plugins" / "cidx_git_backend", + REPO_ROOT / "plugins" / "cidx_orchestrator_invoker", + REPO_ROOT / "packages" / "backends" / "cidx-backend-workspace" / "src", + REPO_ROOT / "packages" / "backends" / "cidx-backend-git" / "src", + REPO_ROOT / "packages" / "cidx-testkit" / "src", + REPO_ROOT / "packages" / "cidx-sdk" / "src", + REPO_ROOT / "packages" / "features" / "cidx-xray" / "src", + REPO_ROOT / "packages" / "features" / "cidx-wiki" / "src", + REPO_ROOT / "packages" / "features" / "cidx-memory" / "src", + REPO_ROOT / "packages" / "features" / "cidx-depmap" / "src", + REPO_ROOT / "packages" / "features" / "cidx-scip" / "src", +) + +#: Top-level modules of ``code_indexer`` that are shells (CLI, daemon, server) +#: rather than libraries: they may import the server. Every other top-level +#: module must be a source of a "no server" contract; see +#: ``unclassified_top_level_modules``. +SHELL_MODULES = frozenset( + { + "server", + "daemon", + "cli_utils", + "disabled_commands", + "mode_specific_handlers", + "remote_status", + "remote_uninstall", + "teach_ai_templates", + } +) +#: Any top-level module whose name starts with this is a CLI shell module. +SHELL_PREFIX = "cli" + +DYNAMIC_SUFFIX = " (dynamic)" +_DYNAMIC_IMPORT_FUNCTIONS = frozenset({"import_module", "__import__"}) + +Violations = Dict[str, Dict[str, int]] + + +class ContractConfigError(Exception): + """The contract file uses something this ratchet cannot count.""" + + +class ImportLinterMissing(Exception): + """import-linter is not installed.""" + + +@dataclass(frozen=True) +class Contract: + """One ``forbidden`` contract, as the ratchet needs it.""" + + contract_id: str + name: str + source_modules: Tuple[str, ...] + forbidden_modules: Tuple[str, ...] + + +@dataclass +class Comparison: + grew: List[str] = field(default_factory=list) + shrank: List[str] = field(default_factory=list) + + @property + def ok(self) -> bool: + return not self.grew and not self.shrank + + +# -- reading the contracts ------------------------------------------------------ + + +def _as_tuple(value: object) -> Tuple[str, ...]: + if isinstance(value, str): + return tuple(v for v in (p.strip() for p in value.splitlines()) if v) + if isinstance(value, (list, tuple, set, frozenset)): + return tuple(sorted(str(v) for v in value)) + raise ContractConfigError(f"unexpected option value {value!r}") + + +def _read_options(config_path: Path) -> Tuple[dict, List[dict]]: + try: + from importlinter import api + except ImportError as exc: # pragma: no cover - exercised only without the tool + raise ImportLinterMissing( + "import-linter is not installed; install the version pinned in " + "pyproject.toml's dev extra" + ) from exc + options = api.read_configuration(str(config_path)) + return options["session_options"], options["contracts_options"] + + +def read_contracts(config_path: Path) -> List[Contract]: + """The contracts in ``config_path``; refuses any this ratchet cannot count. + + Only ``forbidden`` contracts with ``allow_indirect_imports = True`` are + supported: each of their violations is one direct import, which is what + the baseline counts. Anything else would be reported as chains the + baseline has no key for. + """ + _, contract_options = _read_options(config_path) + contracts = [] + for options in contract_options: + contract_id = options.get("id") or options["name"] + if options.get("type") != "forbidden": + raise ContractConfigError( + f"contract {contract_id!r}: only 'forbidden' contracts are ratcheted" + ) + if str(options.get("allow_indirect_imports", "")).lower() != "true": + raise ContractConfigError( + f"contract {contract_id!r}: set allow_indirect_imports = True " + "(the ratchet counts direct imports)" + ) + if options.get("ignore_imports"): + raise ContractConfigError( + f"contract {contract_id!r}: no ignore_imports; known violations " + f"belong in {BASELINE_PATH.name}" + ) + contracts.append( + Contract( + contract_id=contract_id, + name=options["name"], + source_modules=_as_tuple(options["source_modules"]), + forbidden_modules=_as_tuple(options["forbidden_modules"]), + ) + ) + return contracts + + +# -- counting ------------------------------------------------------------------- + + +def _key(importer: str, imported: str) -> str: + return f"{importer} -> {imported}" + + +def _within(module: str, package: str) -> bool: + return module == package or module.startswith(package + ".") + + +def _static_violations(config_path: Path) -> Violations: + """Direct imports breaking each contract, counted by import-linter.""" + from importlinter.application import use_cases + + user_options = use_cases.read_user_options(str(config_path)) + # create_report needs the contract types registered, as lint_imports does. + use_cases._register_contract_types(user_options) + ids_by_name = { + o["name"]: o.get("id") or o["name"] for o in user_options.contracts_options + } + report = use_cases.create_report(user_options, cache_dir=None) + if report.could_not_run: + raise ContractConfigError( + f"import-linter could not run: {report.invalid_contract_options}" + ) + found: Violations = {} + for contract, check in report.get_contracts_and_checks(): + counts = found.setdefault(ids_by_name[contract.name], {}) + for chain_group in check.metadata.get("invalid_chains", []): + for chain in chain_group["chains"]: + for link in chain: + key = _key(link["importer"], link["imported"]) + counts[key] = counts.get(key, 0) + len(link["line_numbers"]) + return found + + +def _literal_dynamic_targets(source: str) -> Iterator[str]: + """Module names imported by string literal through import_module/__import__.""" + tree = ast.parse(source) + for node in ast.walk(tree): + if not isinstance(node, ast.Call) or not node.args: + continue + func = node.func + name = ( + func.attr + if isinstance(func, ast.Attribute) + else func.id + if isinstance(func, ast.Name) + else None + ) + first = node.args[0] + if ( + name in _DYNAMIC_IMPORT_FUNCTIONS + and isinstance(first, ast.Constant) + and isinstance(first.value, str) + and not first.value.startswith(".") + ): + yield first.value + + +def _module_files( + package: str, search_paths: Sequence[Path] +) -> Iterator[Tuple[str, Path]]: + """(module name, file) for ``package`` and everything under it.""" + parts = package.split(".") + for root in search_paths: + base = root.joinpath(*parts) + if base.is_dir(): + for path in sorted(base.rglob("*.py")): + rel = path.relative_to(root).with_suffix("") + names = list(rel.parts) + if names[-1] == "__init__": + names.pop() + yield ".".join(names), path + return + single = base.with_suffix(".py") + if single.is_file(): + yield package, single + return + + +def _expand(expression: str, search_paths: Sequence[Path]) -> List[str]: + """Expand a trailing ``.*`` wildcard into the package's direct children.""" + if not expression.endswith(".*"): + return [expression] + parent = expression[:-2] + children = [] + for root in search_paths: + base = root.joinpath(*parent.split(".")) + if base.is_dir(): + for entry in sorted(base.iterdir()): + if entry.is_dir() and (entry / "__init__.py").is_file(): + children.append(f"{parent}.{entry.name}") + elif entry.suffix == ".py" and entry.stem != "__init__": + children.append(f"{parent}.{entry.stem}") + if not children: + raise ContractConfigError(f"wildcard {expression!r} matches nothing") + return children + + +def _dynamic_violations( + contracts: Sequence[Contract], search_paths: Sequence[Path] +) -> Violations: + found: Violations = {} + for contract in contracts: + if any("*" in m for m in contract.forbidden_modules): + raise ContractConfigError( + f"contract {contract.contract_id!r}: no wildcards in forbidden_modules" + ) + counts = found.setdefault(contract.contract_id, {}) + for expression in contract.source_modules: + for source in _expand(expression, search_paths): + for module, path in _module_files(source, search_paths): + text = path.read_text(encoding="utf-8") + for target in _literal_dynamic_targets(text): + for forbidden in contract.forbidden_modules: + # Same overlap rule as import-linter: a package + # importing itself is not a violation. + if _within(source, forbidden) or _within(forbidden, source): + continue + if _within(target, forbidden): + key = _key(module, target) + DYNAMIC_SUFFIX + counts[key] = counts.get(key, 0) + 1 + return found + + +def collect_violations( + config_path: Path = CONFIG_PATH, + search_paths: Sequence[Path] = SEARCH_PATHS, +) -> Violations: + """Every contract's violations: ``{contract id: {edge: line count}}``.""" + added = [str(p) for p in search_paths if str(p) not in sys.path] + sys.path[:0] = added + importlib.invalidate_caches() + try: + contracts = read_contracts(config_path) + found = _static_violations(config_path) + for contract_id, counts in _dynamic_violations(contracts, search_paths).items(): + merged = found.setdefault(contract_id, {}) + for key, n in counts.items(): + merged[key] = merged.get(key, 0) + n + for contract in contracts: + found.setdefault(contract.contract_id, {}) + return { + cid: dict(sorted(edges.items())) for cid, edges in sorted(found.items()) + } + finally: + for entry in added: + sys.path.remove(entry) + + +# -- the ratchet ---------------------------------------------------------------- + + +def compare(baseline: Violations, found: Violations) -> Comparison: + """What grew (fails: new imports) and what shrank (fails: stale baseline).""" + result = Comparison() + for contract_id in sorted(set(baseline) | set(found)): + if contract_id not in found: + result.shrank.append( + f"{contract_id}: contract no longer exists; drop it from the baseline" + ) + continue + before = baseline.get(contract_id, {}) + after = found[contract_id] + for key in sorted(set(before) | set(after)): + was, now = before.get(key, 0), after.get(key, 0) + if now > was: + result.grew.append(f"{contract_id}: {key} ({was} -> {now} lines)") + elif now < was: + result.shrank.append(f"{contract_id}: {key} ({was} -> {now} lines)") + return result + + +def load_baseline(path: Path = BASELINE_PATH) -> Violations: + data = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(data, dict): + raise ContractConfigError(f"{path} must hold a JSON object") + return {str(k): {str(e): int(n) for e, n in v.items()} for k, v in data.items()} + + +def write_baseline(found: Violations, path: Path = BASELINE_PATH) -> None: + path.write_text( + json.dumps(found, indent=1, sort_keys=True) + "\n", encoding="utf-8" + ) + + +def unclassified_top_level_modules( + contracts: Sequence[Contract], src: Path = REPO_ROOT / "src" +) -> List[str]: + """Top-level ``code_indexer`` modules in no "no server" contract and not a shell. + + Keeps a new top-level package from escaping the server rule by not being + listed: it has to be put in a contract or declared a shell here. + """ + covered: set = set() + for contract in contracts: + if "code_indexer.server" in contract.forbidden_modules: + covered.update(contract.source_modules) + missing = [] + for module in _expand("code_indexer.*", [src]): + short = module.split(".", 1)[1] + if short in SHELL_MODULES or short.startswith(SHELL_PREFIX): + continue + if module not in covered: + missing.append(module) + return missing + + +def _summary(found: Violations) -> str: + return "\n".join( + f" {cid}: {sum(edges.values())} import lines in {len(edges)} edges" + for cid, edges in found.items() + ) + + +def main(argv: Optional[Sequence[str]] = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument( + "--write", action="store_true", help="rewrite the baseline from the tree" + ) + args = parser.parse_args(argv) + try: + contracts = read_contracts(CONFIG_PATH) + found = collect_violations() + except (ContractConfigError, ImportLinterMissing) as exc: + print(f"import contracts: {exc}", file=sys.stderr) + return 2 + unclassified = unclassified_top_level_modules(contracts) + if unclassified: + print( + "import contracts: top-level modules in no server contract and not a " + f"shell (add them to .importlinter or SHELL_MODULES): {unclassified}", + file=sys.stderr, + ) + return 1 + if args.write: + write_baseline(found) + print(f"wrote {BASELINE_PATH.relative_to(REPO_ROOT)}\n{_summary(found)}") + return 0 + result = compare(load_baseline(), found) + if result.grew: + print( + "import contracts: NEW forbidden imports (see " + "docs/architecture/invariants/import-contracts.md):", + *result.grew, + sep="\n ", + file=sys.stderr, + ) + if result.shrank: + print( + "import contracts: violations removed -- lower the baseline with " + "`python3 scripts/check_import_contracts.py --write`:", + *result.shrank, + sep="\n ", + file=sys.stderr, + ) + if not result.ok: + return 1 + print(f"import contracts: baseline matches\n{_summary(found)}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/import_contracts_ratchet.json b/scripts/import_contracts_ratchet.json new file mode 100644 index 000000000..10407aad2 --- /dev/null +++ b/scripts/import_contracts_ratchet.json @@ -0,0 +1,270 @@ +{ + "backends-no-kernel": {}, + "core-does-not-import-backends": { + "code_indexer.server.storage.shared.clone_backend -> cidx_backend_workspace.clone": 1, + "code_indexer.server.storage.shared.content_backend -> cidx_backend_workspace.content": 1, + "code_indexer.server.storage.shared.git_backend -> cidx_backend_git.local": 1, + "code_indexer.server.storage.shared.ontap_flexclone_client -> cidx_backend_workspace.ontap_flexclone_client": 1, + "code_indexer.server.storage.shared.ripgrep_backend -> cidx_backend_workspace.ripgrep": 1, + "code_indexer.utils.index_store -> cidx_backend_workspace.index_store": 1 + }, + "core-does-not-import-depmap-feature": {}, + "core-does-not-import-memory-feature": {}, + "core-does-not-import-scip-feature": {}, + "core-does-not-import-wiki-feature": {}, + "core-does-not-import-xray-feature": {}, + "core-libraries-no-server": { + "code_indexer.api_clients.remote_query_client -> code_indexer.server.models.api_models": 1, + "code_indexer.api_clients.repos_client -> code_indexer.server.git.git_subprocess_env": 1, + "code_indexer.api_clients.repository_linking_client -> code_indexer.server.git.git_subprocess_env": 1, + "code_indexer.api_clients.repository_linking_client -> code_indexer.server.models.repository_discovery": 1, + "code_indexer.backends.filesystem_backend -> code_indexer.server.cache.id_index_cache": 1, + "code_indexer.backends.filesystem_backend -> code_indexer.server.services.query_path_cache": 1, + "code_indexer.backends.filesystem_backend -> code_indexer.server.utils.registry_factory": 1, + "code_indexer.indexing.content_prefetcher -> code_indexer.server.storage.shared.content_backend": 1, + "code_indexer.indexing.file_texts -> code_indexer.server.storage.shared.content_backend": 1, + "code_indexer.services.cohere_embedding -> code_indexer.server.fault_injection.null_factory": 1, + "code_indexer.services.cohere_embedding -> code_indexer.server.services.embedding_call_instrumentation": 1, + "code_indexer.services.cohere_multimodal -> code_indexer.server.services.embedding_call_instrumentation": 1, + "code_indexer.services.embedding_metrics_telemetry -> code_indexer.server.telemetry.manager": 1, + "code_indexer.services.embedding_metrics_telemetry -> code_indexer.server.telemetry.metrics_instrumentation": 1, + "code_indexer.services.git_head -> code_indexer.server.storage.shared.git_backend": 1, + "code_indexer.services.progress_subprocess_runner -> code_indexer.server.startup.content_backend_wiring": 2, + "code_indexer.services.progress_subprocess_runner -> code_indexer.server.startup.git_backend_wiring": 1, + "code_indexer.services.progress_subprocess_runner -> code_indexer.server.utils.cancellable_subprocess": 1, + "code_indexer.services.provider_health_monitor -> code_indexer.server.services.config_service": 1, + "code_indexer.services.provider_health_monitor -> code_indexer.server.utils.config_manager": 2, + "code_indexer.services.temporal.temporal_fusion_dispatch -> code_indexer.server.services.governed_call": 1, + "code_indexer.services.temporal.temporal_fusion_dispatch -> code_indexer.server.services.memory_governor": 1, + "code_indexer.services.temporal.temporal_fusion_dispatch -> code_indexer.server.services.search_embed_event_emit": 1, + "code_indexer.services.temporal.temporal_fusion_limit -> code_indexer.server.mcp.reranking": 1, + "code_indexer.services.temporal.temporal_git_seam -> code_indexer.server.startup.content_backend_wiring": 1, + "code_indexer.services.temporal.temporal_git_seam -> code_indexer.server.startup.git_backend_wiring": 1, + "code_indexer.services.temporal.temporal_git_seam -> code_indexer.server.storage.shared.git_backend": 1, + "code_indexer.services.temporal.temporal_indexer -> code_indexer.server.telemetry.spans": 1, + "code_indexer.services.temporal.temporal_search_service -> code_indexer.server.services.governed_call": 1, + "code_indexer.services.temporal.temporal_search_service -> code_indexer.server.services.search_event_context": 1, + "code_indexer.services.temporal.temporal_search_service -> code_indexer.server.startup.content_backend_wiring": 1, + "code_indexer.services.temporal.temporal_status -> code_indexer.server.services.served_index_cache": 1, + "code_indexer.services.temporal.temporal_status -> code_indexer.server.services.temporal_index_store": 1, + "code_indexer.services.voyage_ai -> code_indexer.server.fault_injection.null_factory": 1, + "code_indexer.services.voyage_ai -> code_indexer.server.services.embedding_call_instrumentation": 2, + "code_indexer.services.voyage_multimodal -> code_indexer.server.fault_injection.null_factory": 1, + "code_indexer.services.voyage_multimodal -> code_indexer.server.services.embedding_call_instrumentation": 2, + "code_indexer.utils.git_runner -> code_indexer.server.git.git_subprocess_env": 3, + "code_indexer.utils.git_runner -> code_indexer.server.utils.cancellable_subprocess": 2, + "code_indexer.utils.worker_budget -> code_indexer.server.services.applied_worker_count": 1 + }, + "depmap-feature-no-core": { + "cidx_depmap._platform -> code_indexer.global_repos.lifecycle_batch_runner": 1, + "cidx_depmap._platform -> code_indexer.global_repos.meta_description_hook": 1, + "cidx_depmap._platform -> code_indexer.global_repos.prompts": 1, + "cidx_depmap._platform -> code_indexer.global_repos.write_lock_manager": 1, + "cidx_depmap._platform -> code_indexer.global_repos.yaml_emitter_utils": 1, + "cidx_depmap._platform -> code_indexer.kernel.capabilities": 1, + "cidx_depmap._platform -> code_indexer.server (dynamic)": 1, + "cidx_depmap._platform -> code_indexer.server.app": 1, + "cidx_depmap._platform -> code_indexer.server.auth.dependencies": 1, + "cidx_depmap._platform -> code_indexer.server.mcp.handlers._utils": 1, + "cidx_depmap._platform -> code_indexer.server.services.activity_journal_service": 1, + "cidx_depmap._platform -> code_indexer.server.services.agent_cli_isolation": 1, + "cidx_depmap._platform -> code_indexer.server.services.backfill_journal_service": 1, + "cidx_depmap._platform -> code_indexer.server.services.cidx_meta_read_mirror": 1, + "cidx_depmap._platform -> code_indexer.server.services.claude_invoker": 1, + "cidx_depmap._platform -> code_indexer.server.services.cli_dispatcher": 1, + "cidx_depmap._platform -> code_indexer.server.services.codex_invoker": 1, + "cidx_depmap._platform -> code_indexer.server.services.codex_mcp_auth_header_provider": 1, + "cidx_depmap._platform -> code_indexer.server.services.config_service": 1, + "cidx_depmap._platform -> code_indexer.server.services.constants": 1, + "cidx_depmap._platform -> code_indexer.server.services.dep_map_dispatcher_factory": 1, + "cidx_depmap._platform -> code_indexer.server.services.dep_map_file_utils": 1, + "cidx_depmap._platform -> code_indexer.server.services.dep_map_parser_hygiene": 1, + "cidx_depmap._platform -> code_indexer.server.services.dep_map_parser_tables": 1, + "cidx_depmap._platform -> code_indexer.server.services.dep_map_source": 1, + "cidx_depmap._platform -> code_indexer.server.services.file_service": 1, + "cidx_depmap._platform -> code_indexer.server.services.jittered_dispatcher": 1, + "cidx_depmap._platform -> code_indexer.server.services.job_tracker": 1, + "cidx_depmap._platform -> code_indexer.server.services.metadata_reader": 1, + "cidx_depmap._platform -> code_indexer.server.services.query_admission_gate": 1, + "cidx_depmap._platform -> code_indexer.server.services.shared_job_sentinel": 1, + "cidx_depmap._platform -> code_indexer.server.startup.content_backend_wiring": 1, + "cidx_depmap._platform -> code_indexer.server.storage.database_manager": 1, + "cidx_depmap._platform -> code_indexer.server.storage.filesystem_backends": 1, + "cidx_depmap._platform -> code_indexer.server.storage.json_column": 1, + "cidx_depmap._platform -> code_indexer.server.storage.sqlite_backends": 1, + "cidx_depmap._platform -> code_indexer.server.telemetry.spans": 1, + "cidx_depmap._platform -> code_indexer.server.utils.cluster_node_id": 1, + "cidx_depmap._platform -> code_indexer.server.web.auth": 1, + "cidx_depmap._platform -> code_indexer.server.web.pages._shared": 1, + "cidx_depmap._platform -> code_indexer.utils.file_locking": 1, + "cidx_depmap._platform -> code_indexer.utils.subprocess_diagnostics": 1, + "cidx_depmap.server.dep_map_index_regenerator -> code_indexer.global_repos.catalog_staged_write": 1, + "cidx_depmap.server.web.routes -> code_indexer.server.services.dep_map_repair_admission": 1 + }, + "depmap-feature-no-other-feature": {}, + "features-not-imported": {}, + "library-packages-no-server": { + "code_indexer.global_repos.alias_lock_coordinator -> code_indexer.server.services.alias_lock_store.base": 6, + "code_indexer.global_repos.alias_manager -> code_indexer.server.services.index_materializer": 1, + "code_indexer.global_repos.alias_manager -> code_indexer.server.startup.index_store_wiring": 2, + "code_indexer.global_repos.cidx_meta_refresh_debouncer -> code_indexer.server.repositories.background_jobs": 1, + "code_indexer.global_repos.control_plane_metadata -> code_indexer.server.storage.protocols.control_plane_metadata_backend": 1, + "code_indexer.global_repos.git_operations -> code_indexer.server.services.delegated_refusal": 1, + "code_indexer.global_repos.git_operations -> code_indexer.server.services.git_argv_safety": 1, + "code_indexer.global_repos.git_operations -> code_indexer.server.services.git_tools_seam": 1, + "code_indexer.global_repos.git_operations -> code_indexer.server.startup.content_backend_wiring": 1, + "code_indexer.global_repos.git_operations -> code_indexer.server.startup.git_backend_wiring": 1, + "code_indexer.global_repos.git_operations -> code_indexer.server.storage.shared.git_backend": 1, + "code_indexer.global_repos.git_pull_updater -> code_indexer.server.git.remote_credentials": 1, + "code_indexer.global_repos.git_pull_updater -> code_indexer.server.startup.content_backend_wiring": 1, + "code_indexer.global_repos.git_pull_updater -> code_indexer.server.startup.content_writer_wiring": 1, + "code_indexer.global_repos.git_pull_updater -> code_indexer.server.storage.shared.git_backend": 1, + "code_indexer.global_repos.git_pull_updater -> code_indexer.server.utils.cancellable_subprocess": 1, + "code_indexer.global_repos.global_activation -> code_indexer.server.utils.registry_factory": 1, + "code_indexer.global_repos.global_registry -> code_indexer.server.storage.sqlite_backends": 1, + "code_indexer.global_repos.lifecycle_batch_runner -> code_indexer.server.services.cidx_meta_content": 1, + "code_indexer.global_repos.lifecycle_batch_runner -> code_indexer.server.services.jittered_dispatcher": 1, + "code_indexer.global_repos.lifecycle_batch_runner -> code_indexer.server.startup.content_backend_wiring": 1, + "code_indexer.global_repos.lifecycle_claude_cli_invoker -> code_indexer.server.services.cli_invoker_plugin": 1, + "code_indexer.global_repos.lifecycle_claude_cli_invoker -> code_indexer.server.services.config_service": 1, + "code_indexer.global_repos.lifecycle_claude_cli_invoker -> code_indexer.server.services.delegated_refusal": 1, + "code_indexer.global_repos.lifecycle_claude_cli_invoker -> code_indexer.server.services.dep_map_dispatcher_factory": 1, + "code_indexer.global_repos.lifecycle_claude_cli_invoker -> code_indexer.server.startup.content_backend_wiring": 2, + "code_indexer.global_repos.meta_description_hook -> code_indexer.server.repositories.background_jobs": 1, + "code_indexer.global_repos.meta_description_hook -> code_indexer.server.services.cidx_meta_content": 1, + "code_indexer.global_repos.meta_description_hook -> code_indexer.server.services.claude_cli_manager": 1, + "code_indexer.global_repos.meta_description_hook -> code_indexer.server.services.cli_invoker_plugin": 1, + "code_indexer.global_repos.meta_description_hook -> code_indexer.server.services.job_tracker": 1, + "code_indexer.global_repos.meta_directory_updater -> code_indexer.server.services.cidx_meta_content": 1, + "code_indexer.global_repos.refresh_failure_recovery -> code_indexer.server.repositories.background_jobs": 1, + "code_indexer.global_repos.refresh_failure_recovery -> code_indexer.server.services.metadata_reader": 1, + "code_indexer.global_repos.refresh_failure_recovery -> code_indexer.server.storage.protocols.golden_repo_metadata_backend": 1, + "code_indexer.global_repos.refresh_fence -> code_indexer.server.services.alias_lock_store.base": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.cache.snapshot_cache_invalidation": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.git.git_subprocess_env": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.logging_utils": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.repositories.background_jobs": 2, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.repositories.golden_repo_manager": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.services.alias_lock_store.base": 2, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.services.cidx_meta_backup": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.services.cidx_meta_content": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.services.config_seeding": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.services.config_service": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.services.constants": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.services.db_outage_throttle": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.services.embedding_stats_attribution": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.services.fts_index_builder": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.services.git_operations_service": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.services.hnsw_orphan_sweep.discovery": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.services.index_freshness": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.services.index_materializer": 4, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.services.index_spend_alarm": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.services.job_tracker": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.services.metadata_reader": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.services.query_admission_gate": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.services.served_index_cache": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.services.temporal_floor_date": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.services.temporal_index_store": 2, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.startup.content_backend_wiring": 4, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.startup.git_backend_wiring": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.storage.postgres.embedding_stats_child_wiring": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.storage.postgres.temporal_child_wiring": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.storage.shared.content_backend": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.storage.shared.git_backend": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.storage.shared.nfs_visibility": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.storage.shared.snapshot_manager": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.storage.shared.snapshot_paths": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.telemetry.job_metrics": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.telemetry.manager": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.utils.cancellable_subprocess": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.utils.config_manager": 1, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.utils.index_command_layout": 3, + "code_indexer.global_repos.refresh_scheduler -> code_indexer.server.utils.registry_factory": 3, + "code_indexer.global_repos.regex_search -> code_indexer.server.services.subprocess_executor": 1, + "code_indexer.global_repos.regex_search -> code_indexer.server.startup.content_backend_wiring": 1, + "code_indexer.global_repos.regex_search -> code_indexer.server.storage.shared.ripgrep_backend": 1, + "code_indexer.global_repos.repo_analyzer -> code_indexer.server.services.agent_cli_isolation": 1, + "code_indexer.global_repos.repo_analyzer -> code_indexer.server.services.claude_cli_manager": 1, + "code_indexer.global_repos.repo_analyzer -> code_indexer.server.services.config_service": 1, + "code_indexer.global_repos.repo_analyzer -> code_indexer.server.services.delegated_refusal": 1, + "code_indexer.global_repos.repo_analyzer -> code_indexer.server.services.mcp_self_registration_service": 1, + "code_indexer.global_repos.repointed_origin -> code_indexer.server.storage.shared.git_backend": 1, + "code_indexer.global_repos.shared_operations -> code_indexer.server.services.config_service": 2, + "code_indexer.global_repos.shared_operations -> code_indexer.server.utils.registry_factory": 2, + "code_indexer.global_repos.snapshot_retention -> code_indexer.server.services.config_service": 1, + "code_indexer.global_repos.snapshot_retention -> code_indexer.server.storage.shared.snapshot_manager": 1, + "code_indexer.global_repos.stale_index_signal -> code_indexer.server.services.metadata_reader": 1, + "code_indexer.global_repos.trigram_index_manager -> code_indexer.server.startup.content_backend_wiring": 2, + "code_indexer.global_repos.trigram_index_manager -> code_indexer.server.startup.ripgrep_backend_wiring": 1, + "code_indexer.global_repos.trigram_index_manager -> code_indexer.server.storage.shared.content_backend": 1, + "code_indexer.storage.filesystem_vector_store -> code_indexer.server.services.embedding_cache_audit": 1, + "code_indexer.storage.filesystem_vector_store -> code_indexer.server.services.file_service": 2, + "code_indexer.storage.filesystem_vector_store -> code_indexer.server.services.governed_call": 1, + "code_indexer.storage.filesystem_vector_store -> code_indexer.server.services.search_embed_event_emit": 1, + "code_indexer.storage.filesystem_vector_store -> code_indexer.server.services.search_event_context": 1, + "code_indexer.storage.filesystem_vector_store -> code_indexer.server.services.served_index_cache": 1, + "code_indexer.storage.hnsw_index_manager -> code_indexer.server.telemetry.spans": 1, + "code_indexer.storage.id_index_manager -> code_indexer.server.services.query_path_cache": 1, + "code_indexer.storage.shared.chunk_store_cache -> code_indexer.server.storage.shared.snapshot_paths": 1, + "code_indexer.storage.shared.chunk_store_cache_cross_process -> code_indexer.server.cache.payload_cache": 2, + "code_indexer.storage.shared.collection_dedup_repair -> code_indexer.server.services.deactivation_query_drain": 1, + "code_indexer.storage.shared.collection_dedup_repair -> code_indexer.server.services.query_path_cache": 1, + "code_indexer.storage.shared.collection_meta_cache -> code_indexer.server.services.query_path_cache": 1, + "code_indexer.storage.shared.hnsw_sync_state -> code_indexer.server.services.config_service": 1, + "code_indexer.storage.shared.id_mapping_cache -> code_indexer.server.services.query_path_cache": 1, + "code_indexer.storage.sqlite_chunk_store -> code_indexer.server.services.query_path_cache": 1 + }, + "memory-feature-no-core": { + "cidx_memory._platform -> code_indexer.global_repos.meta_description_hook": 1, + "cidx_memory._platform -> code_indexer.kernel.capabilities": 1, + "cidx_memory._platform -> code_indexer.server.services.cidx_meta_content": 1, + "cidx_memory._platform -> code_indexer.server.services.memory_io": 1, + "cidx_memory._platform -> code_indexer.storage.filesystem_vector_store": 1, + "cidx_memory.server.memory_store_service -> code_indexer.global_repos.catalog_lock_holder": 1 + }, + "memory-feature-no-other-feature": {}, + "plugins-no-kernel": {}, + "scip-feature-no-core": { + "cidx_scip._platform -> code_indexer.api_clients.base_client": 1, + "cidx_scip._platform -> code_indexer.config": 1, + "cidx_scip._platform -> code_indexer.disabled_commands": 1, + "cidx_scip._platform -> code_indexer.global_repos.alias_manager": 1, + "cidx_scip._platform -> code_indexer.indexing.repo_manifest": 1, + "cidx_scip._platform -> code_indexer.kernel.capabilities": 1, + "cidx_scip._platform -> code_indexer.mode_detection.command_mode_detector": 1, + "cidx_scip._platform -> code_indexer.services.git_head": 1, + "cidx_scip._platform -> code_indexer.utils.index_store": 1, + "cidx_scip._platform -> code_indexer.utils.path_confinement": 1, + "cidx_scip._platform -> code_indexer.utils.sandbox_mcp_client": 1, + "cidx_scip._platform -> code_indexer.utils.snapshot_paths": 1 + }, + "scip-feature-no-other-feature": {}, + "wiki-feature-no-core": { + "cidx_wiki._platform -> code_indexer.indexing.fetch_planner": 1, + "cidx_wiki._platform -> code_indexer.kernel.capabilities": 1, + "cidx_wiki._platform -> code_indexer.utils.path_confinement": 1 + }, + "wiki-feature-no-other-feature": {}, + "xray-feature-no-core": { + "cidx_xray._platform -> code_indexer.global_repos.regex_search": 1, + "cidx_xray._platform -> code_indexer.kernel.capabilities": 1, + "cidx_xray._platform -> code_indexer.services.path_pattern_matcher": 1, + "cidx_xray._platform -> code_indexer.utils.bounded_regex": 1, + "cidx_xray._platform -> code_indexer.utils.path_confinement": 1, + "cidx_xray._platform -> code_indexer.utils.process_group": 1, + "cidx_xray._platform -> code_indexer.utils.worker_budget": 1, + "cidx_xray.phase1_limits -> code_indexer.global_repos.regex_search": 1, + "cidx_xray.phase1_limits -> code_indexer.services.path_pattern_matcher": 1, + "cidx_xray.server.mcp.xray._explore -> code_indexer.server.services.api_metrics_service": 1, + "cidx_xray.server.mcp.xray._explore -> code_indexer.server.services.search_event_xray": 1, + "cidx_xray.server.mcp.xray._search -> code_indexer.server.services.api_metrics_service": 1, + "cidx_xray.server.mcp.xray._search -> code_indexer.server.services.search_event_recording": 1, + "cidx_xray.server.mcp.xray_batch -> code_indexer.server.mcp.handlers._utils": 1, + "cidx_xray.server.mcp.xray_batch -> code_indexer.server.services.api_metrics_service": 1, + "cidx_xray.server.pattern_service -> code_indexer.global_repos.catalog_lock_holder": 1, + "cidx_xray.server.pattern_service -> code_indexer.server.services.xray_pattern_names": 1, + "cidx_xray.server.routes -> code_indexer.server.services.api_metrics_service": 1, + "cidx_xray.server.routes -> code_indexer.server.services.search_event_recording": 1 + }, + "xray-feature-no-other-feature": {} +} diff --git a/src/code_indexer/cli.py b/src/code_indexer/cli.py index c637f1fc6..a1a095cd2 100644 --- a/src/code_indexer/cli.py +++ b/src/code_indexer/cli.py @@ -21,6 +21,7 @@ Any, List, Literal, + Tuple, cast, ) @@ -45,14 +46,12 @@ from .mode_detection.command_mode_detector import CommandModeDetector, find_project_root from .disabled_commands import require_mode from . import __version__ -from .cli_scip import scip_group from .cli_git import git_group from .cli_files import files_group from .cli_cicd import cicd_group from .cli_help import help_group from .cli_keys import keys_group from .cli_index import index_remote_group -from .cli_xray import xray_group # Module-level imports for test mocking (noqa: F401 = intentionally unused for test patching) from .api_clients.admin_client import AdminAPIClient # noqa: F401 @@ -1157,6 +1156,8 @@ def _execute_semantic_search( config_manager, console: Console, file_extensions: Optional[str] = None, + content_backend: str = "local", + git_backend: str = "local", ) -> List[Dict[str, Any]]: """Execute semantic search - extracted for parallel execution in hybrid mode. @@ -1322,11 +1323,19 @@ def _execute_semantic_search( # Check if project uses git-aware indexing from .services.git_topology_service import GitTopologyService - git_topology_service = GitTopologyService(config.codebase_dir) + # The server stamps --git-backend=delegated on a query it spawns in a + # directory that holds index state only: the branch filter then asks + # the git-backend plugin, never local git in an empty directory. + query_git_backend = _query_git_backend(git_backend) + git_topology_service = GitTopologyService( + config.codebase_dir, git_backend=query_git_backend + ) is_git_aware = git_topology_service.is_git_available() # Initialize query service for git-aware filtering - query_service = GenericQueryService(config.codebase_dir, config) + query_service = GenericQueryService( + config.codebase_dir, config, git_backend=query_git_backend + ) # Determine if we should use branch-aware querying if is_git_aware: @@ -1449,58 +1458,27 @@ def _execute_semantic_search( # Limit to requested number after filtering results = git_results[:limit] - # Apply staleness detection to local query results + # Apply staleness detection to local query results -- only where the + # files are on this machine. With --content-backend=delegated they are + # not, and asking the content backend would page the whole repository's + # manifest per query: results carry no staleness instead of a wrong one. if results: try: staleness_start = time.time() - from .api_clients.remote_query_client import QueryResultItem - from .remote.staleness_detector import StalenessDetector - - query_result_items = [] - for result in results: - payload = result["payload"] - - # Extract file metadata for staleness comparison - file_last_modified = payload.get("file_last_modified") - indexed_at = payload.get("indexed_at") - - # Convert indexed_at ISO timestamp to Unix timestamp float - indexed_timestamp = None - if indexed_at: - try: - from datetime import datetime - - dt = datetime.fromisoformat(indexed_at.rstrip("Z")) - indexed_timestamp = dt.timestamp() - except (ValueError, AttributeError): - indexed_timestamp = None - - query_item = QueryResultItem( - similarity_score=result["score"], - file_path=payload.get("path", "unknown"), - line_number=payload.get("line_start", 1), - code_snippet=payload.get("content", ""), - repository_alias=project_root.name, - file_last_modified=file_last_modified, - indexed_timestamp=indexed_timestamp, - ) - query_result_items.append(query_item) - - # Apply staleness detection in local mode - staleness_detector = StalenessDetector() - enhanced_results = staleness_detector.apply_staleness_detection( - query_result_items, project_root, mode="local" - ) - timing_info["staleness_detection_ms"] = ( - time.time() - staleness_start - ) * 1000 - - # Annotate results with staleness detection metadata. - # No reranker in this function — use preserve_order=False so - # fresh results sort before stale ones (staleness-first ordering). - results = _annotate_staleness( - results, enhanced_results, preserve_order=False + enhanced_results = _query_staleness( + results, project_root, content_backend ) + if enhanced_results is not None: + timing_info["staleness_detection_ms"] = ( + time.time() - staleness_start + ) * 1000 + + # Annotate results with staleness detection metadata. + # No reranker in this function — use preserve_order=False so + # fresh results sort before stale ones (staleness-first ordering). + results = _annotate_staleness( + results, enhanced_results, preserve_order=False + ) except Exception as _staleness_exc: # Staleness detection is best-effort; continue with original results. @@ -1722,7 +1700,28 @@ def create_auth_client(server_url: str, project_root: Path): class ModeAwareGroup(click.Group): - """Custom Click Group that adds mode compatibility icons to command help.""" + """Custom Click Group that adds mode compatibility icons to command help. + + Also serves feature add-on commands (``cli_commands()``): consulted only + for a name that is not built in, and when listing commands, so built-in + commands import nothing for features (cli_features.py). + """ + + def get_command(self, ctx, cmd_name): + command = super().get_command(ctx, cmd_name) + if command is not None or self is not cli: + return command + from code_indexer.cli_features import feature_command + + return feature_command(cmd_name) + + def list_commands(self, ctx): + builtin = super().list_commands(ctx) + if self is not cli: + return builtin + from code_indexer.cli_features import listed_feature_commands + + return sorted(builtin + listed_feature_commands(builtin)) def format_commands(self, ctx, formatter): """Format commands with mode compatibility icons.""" @@ -1944,9 +1943,6 @@ def cli( console.print(f"📁 Project root: {project_root}", style="dim") -# Register SCIP commands -cli.add_command(scip_group) - # Register Git commands (Story #737) cli.add_command(git_group) @@ -1966,8 +1962,10 @@ def cli( # Story #656: Register Remote index management commands (implemented in cli_index.py) cli.add_command(index_remote_group) -# Story #975: Register X-Ray CLI commands (implemented in cli_xray.py) -cli.add_command(xray_group) +# Story #975: `cidx xray` is the cidx-xray feature's cli_commands() +# contribution, and (modular phase 4d) `cidx scip` the cidx-scip feature's, +# found by entry point whenever the distribution is installed +# (cli_features.py; ModeAwareGroup asks it for names that are not built in). @cli.group("groups") @@ -2842,6 +2840,32 @@ def _install_embedding_stats_writer_for_index() -> None: ) EmbeddingStatsWriter.set_active(NoOpWriter()) + + # read per-job correlation tags from the env vars + # threaded by the parent and install them as process-level + # fallbacks so every EmbeddingCallRecord produced by this child + # carries the repo alias, job id, and cluster node id. + try: + from .server.storage.postgres.embedding_stats_child_wiring import ( + EMBEDDING_STATS_GOLDEN_REPO_ALIAS_ENV, + EMBEDDING_STATS_JOB_ID_ENV, + EMBEDDING_STATS_NODE_ID_ENV, + ) + from .server.services.embedding_call_instrumentation import ( + set_process_embed_stats_tags, + ) + + set_process_embed_stats_tags( + golden_repo_alias=os.environ.get(EMBEDDING_STATS_GOLDEN_REPO_ALIAS_ENV), + job_id=os.environ.get(EMBEDDING_STATS_JOB_ID_ENV), + node_id=os.environ.get(EMBEDDING_STATS_NODE_ID_ENV), + ) + except Exception as exc: + logger.debug( + "_install_embedding_stats_writer_for_index: failed to set " + "embed stats tags (non-fatal): %s", + exc, + ) else: from .server.services.embedding_stats_writer import ( EmbeddingStatsWriter, @@ -3132,6 +3156,28 @@ def _resolve_hnsw_sync_epoch_enabled_for_cli() -> bool: "indexing delegates to a daemon. Every other provider setting (model, " "timeout, retries, ...) is left untouched.", ) +@click.option( + "--content-backend", + type=click.Choice(["local", "delegated"]), + default="local", + hidden=True, + help="Internal: where repository bytes are read from. 'local' (default) " + "reads this machine's disk. 'delegated' reads through the content-backend " + "plugin the server is configured with (CIDX_CONTENT_BACKEND or the " + "code_indexer.content_backend entry point), and fails rather than falling " + "back to the disk. Stamped by the server on the commands it spawns.", +) +@click.option( + "--git-backend", + type=click.Choice(["local", "delegated"]), + default="local", + hidden=True, + help="Internal: who answers git questions about the repository (HEAD's " + "commit and branch, recorded in the index). 'local' (default) runs git " + "here. 'delegated' asks the git-backend plugin the server is configured " + "with (the git-backend plugin), for a repository this machine does not hold. Stamped by " + "the server on the commands it spawns.", +) @click.option( "--stats-attribution", default=None, @@ -3180,6 +3226,8 @@ def index( migrate_chunks_to_sqlite: bool = False, ignore_resume_state: bool = False, server_managed_provider_settings: bool = False, + content_backend: str = "local", + git_backend: str = "local", stats_attribution=None, exit_with_parent: Optional[int] = None, ): @@ -3382,6 +3430,21 @@ def _load_config_for_index() -> Config: console.print(f"❌ {exc}", style="red") sys.exit(1) + # Temporal indexing reads only history, and with --git-backend delegated it + # reads it through the git seam (the git-backend plugin). Delegated CONTENT with LOCAL git + # means the repository is not on this machine and nothing can read its + # history: refused here, before --clear can wipe anything, rather than index + # an empty history. + if index_commits and content_backend == "delegated" and git_backend == "local": + console.print( + "❌ Temporal indexing (--index-commits) with --content-backend " + "delegated needs --git-backend delegated: the repository's history " + "is not on this machine. Refusing instead of indexing an empty " + "history.", + style="red", + ) + sys.exit(1) + # Validate --diff-context flag (must happen before daemon delegation) if diff_context is not None and not index_commits: console.print( @@ -3923,8 +3986,19 @@ def _load_config_for_index() -> Config: _temporal_coll_name = resolve_temporal_collection_name( cast(str, config.temporal.active_embedder) ) + # None keeps local git; delegated reads the history through + # the git seam, and fails here, before any work, if the plugin + # is missing. + temporal_git_backend = ( + None + if git_backend == "local" + else _build_index_git_backend(git_backend) + ) temporal_indexer = TemporalIndexer( - config_manager, vector_store, collection_name=_temporal_coll_name + config_manager, + vector_store, + collection_name=_temporal_coll_name, + git_backend=temporal_git_backend, ) # Cost estimation warning for all-branches (no confirmation prompt) @@ -3933,20 +4007,32 @@ def _load_config_for_index() -> Config: try: import subprocess - result = subprocess.run( - ["git", "branch", "-a"], - cwd=config.codebase_dir, - capture_output=True, - text=True, - check=True, - ) - branch_count = len( - [ - line - for line in result.stdout.split("\n") - if line.strip() and not line.strip().startswith("*") - ] - ) + if temporal_git_backend is not None: + # `git branch -a` less the current branch's line. + branch_count = max( + len( + temporal_git_backend.list_branches( + str(config.codebase_dir), all_refs=True + ) + ) + - 1, + 0, + ) + else: + result = subprocess.run( + ["git", "branch", "-a"], + cwd=config.codebase_dir, + capture_output=True, + text=True, + check=True, + ) + branch_count = len( + [ + line + for line in result.stdout.split("\n") + if line.strip() and not line.strip().startswith("*") + ] + ) if branch_count > 50: console.print( @@ -4236,15 +4322,15 @@ def progress_callback( # type: ignore[misc] try: config = _load_config_for_index() - # Check if indexing progress file exists - progress_file = config_manager.config_path.parent / "indexing_progress.json" - if not progress_file.exists(): - console.print("❌ No indexing progress found", style="red") - console.print( - "💡 Run 'cidx index' first to create the semantic index", - style="yellow", - ) - sys.exit(1) + # the FTS index is (re)built ENTIRELY from files discovered on + # disk via FileFinder below — it never reads the semantic index or + # indexing_progress.json. Requiring that progress file here was a spurious + # precondition that made `cidx index --rebuild-fts-index` exit 1 on any + # repo indexed OUT-OF-BAND (e.g. cidx server / seeder-registered golden + # repos, whose semantic index lives server-side, not as a local progress + # file) — which is exactly the fleet the on-by-default FTS backfill sweep + # targets. The genuine "nothing to index" case is still handled by the + # `no discovered_files` check below. # Lazy import FTS components from .services.fts_lifecycle import ( @@ -4257,6 +4343,12 @@ def progress_callback( # type: ignore[misc] # Use FileFinder to discover files from disk (respects gitignore, base + override config) # This is 60-180x faster than scanning vector JSONs for large codebases file_finder = FileFinder(config) + # The server's FTS backfill spawns exactly this command. Under a + # delegated backend there is no SmartIndexer pass, so the manifest + # is built here: discovery and text both come from it, not the disk. + fts_backend, fts_manifest = _delegated_fts_source( + content_backend, file_finder + ) discovered_files = list(file_finder.find_files()) if not discovered_files: @@ -4299,7 +4391,11 @@ def _on_file(file_path: Path, error: Optional[str]) -> None: progress.advance(task) fts_rebuild_result = rebuild_fts_index_from_disk( - config, discovered_files, _on_file + config, + discovered_files, + _on_file, + backend=fts_backend, + manifest=fts_manifest, ) # Files missing from FTS (fts_lifecycle's per-file rule): the @@ -4421,8 +4517,26 @@ def _on_file(file_path: Path, error: Optional[str]) -> None: metadata_path = _get_provider_metadata_path( config_manager.config_path.parent, _primary_provider ) + # One backend for every indexer this run builds. None keeps the + # local default untouched; delegated fails here, before any work, + # if the plugin is missing -- never a silent read of the disk. + repo_content_backend = ( + None + if content_backend == "local" + else _build_index_content_backend(content_backend) + ) + # Same rule for git: None keeps local git; delegated fails here, before + # any work, if the plugin is missing. + repo_git_backend = ( + None if git_backend == "local" else _build_index_git_backend(git_backend) + ) smart_indexer = SmartIndexer( - config, embedding_provider, vector_store_client, metadata_path + config, + embedding_provider, + vector_store_client, + metadata_path, + content_backend=repo_content_backend, + git_backend=repo_git_backend, ) # Get git status and display @@ -4890,7 +5004,12 @@ def progress_callback( # type: ignore[misc] config_manager.config_path.parent, _extra_provider ) _extra_indexer = SmartIndexer( - config, _extra_embedding, _extra_client, _extra_metadata + config, + _extra_embedding, + _extra_client, + _extra_metadata, + content_backend=repo_content_backend, + git_backend=repo_git_backend, ) _extra_stats = _extra_indexer.smart_index( force_full=clear, @@ -4970,6 +5089,92 @@ def progress_callback( # type: ignore[misc] _index_mutation_lock_ctx.__exit__(None, None, None) +def _build_index_git_backend(backend_type: str) -> Any: + """Build the git backend ``cidx index --git-backend`` selected.""" + from .server.startup.git_backend_wiring import build_named_git_backend + + return build_named_git_backend(backend_type) + + +def _query_git_backend(backend_type: str) -> Any: + """The git backend ``cidx query --git-backend`` selected; None for local.""" + if backend_type == "local": + return None + return _build_index_git_backend(backend_type) + + +def _query_staleness( + results: List[Dict[str, Any]], project_root: Path, content_backend: str +) -> Optional[List[Any]]: + """Staleness of *results* against this machine's files, or None when it is + not checked: with ``--content-backend=delegated`` the files are not here + (``_query_reads_local_files``) and nothing is stat'ed.""" + if not _query_reads_local_files(content_backend): + return None + from .api_clients.remote_query_client import QueryResultItem + from .remote.staleness_detector import StalenessDetector + + query_result_items = [] + for result in results: + payload = result["payload"] + # Convert indexed_at ISO timestamp to Unix timestamp float + indexed_timestamp = None + indexed_at = payload.get("indexed_at") + if indexed_at: + try: + from datetime import datetime + + indexed_timestamp = datetime.fromisoformat( + indexed_at.rstrip("Z") + ).timestamp() + except (ValueError, AttributeError): + indexed_timestamp = None + query_result_items.append( + QueryResultItem( + similarity_score=result["score"], + file_path=payload.get("path", "unknown"), + line_number=payload.get("line_start", 1), + code_snippet=payload.get("content", ""), + repository_alias=project_root.name, + file_last_modified=payload.get("file_last_modified"), + indexed_timestamp=indexed_timestamp, + ) + ) + enhanced: List[Any] = StalenessDetector().apply_staleness_detection( + query_result_items, project_root, mode="local" + ) + return enhanced + + +def _query_reads_local_files(backend_type: str) -> bool: + """Whether ``cidx query`` may stat result files on this machine for + staleness: only with the local content backend. Delegated, the files are + not here (a stat would call every result deleted), and the content backend + has no per-file lookup -- staleness is skipped, never guessed.""" + return backend_type == "local" + + +def _build_index_content_backend(backend_type: str) -> Any: + """Build the content backend ``cidx index --content-backend`` selected.""" + from .server.startup.content_backend_wiring import build_named_content_backend + + return build_named_content_backend(backend_type) + + +def _delegated_fts_source(backend_type: str, file_finder: Any) -> Tuple[Any, Any]: + """(backend, manifest) for a delegated FTS rebuild, or (None, None) for local. + + The manifest is attached to ``file_finder`` (discovery reads from it), built + the same way the indexing pass builds it. + """ + if backend_type == "local": + return None, None + from .indexing.file_finder import attach_delegated_manifest + + backend = _build_index_content_backend(backend_type) + return backend, attach_delegated_manifest(file_finder, backend) + + @cli.command() @click.option( "--debounce", default=2.0, help="Seconds to wait before processing changes" @@ -5802,6 +6007,29 @@ def _annotate_staleness( "Only meaningful when --rerank-query is also provided." ), ) +@click.option( + "--content-backend", + "content_backend", + type=click.Choice(["local", "delegated"]), + default="local", + hidden=True, + help="Internal: where the repository's files are. 'local' (default): on " + "this machine, and results are checked for staleness against them. " + "'delegated': not here (the content-backend plugin holds them), so results " + "carry no staleness instead of calling every file deleted. Stamped by the " + "server on the queries it spawns.", +) +@click.option( + "--git-backend", + "git_backend", + type=click.Choice(["local", "delegated"]), + default="local", + hidden=True, + help="Internal: who answers the branch filter's git questions (HEAD's " + "branch, commit and tree, commit reachability). 'local' (default) runs git " + "here; 'delegated' asks the git-backend plugin (the git-backend plugin). Stamped by the " + "server on the queries it spawns.", +) @click.pass_context @require_mode("local", "remote", "proxy") def query( @@ -5834,6 +6062,8 @@ def query( rerank_query: Optional[str], rerank_instruction: Optional[str], file_extensions: Optional[str] = None, + content_backend: str = "local", + git_backend: str = "local", ): """Search the indexed codebase using semantic similarity. @@ -6753,6 +6983,8 @@ def execute_fts(): config_manager=ctx.obj["config_manager"], console=console, file_extensions=file_extensions, + content_backend=content_backend, + git_backend=git_backend, ) # Wait for BOTH to complete (parallel execution) @@ -7344,11 +7576,19 @@ def execute_fts(): # BranchAwareIndexer removed - using HighThroughputProcessor git-aware methods - git_topology_service = GitTopologyService(config.codebase_dir) + # The server stamps --git-backend=delegated on a query it spawns in a + # directory that holds index state only: the branch filter then asks + # the git-backend plugin, never local git in an empty directory. + query_git_backend = _query_git_backend(git_backend) + git_topology_service = GitTopologyService( + config.codebase_dir, git_backend=query_git_backend + ) is_git_aware = git_topology_service.is_git_available() # Initialize query service for git-aware filtering - query_service = GenericQueryService(config.codebase_dir, config) + query_service = GenericQueryService( + config.codebase_dir, config, git_backend=query_git_backend + ) # Determine if we should use branch-aware querying if is_git_aware: @@ -7668,64 +7908,32 @@ def execute_fts(): health_monitor=health_monitor, ) - # Apply staleness detection to local query results + # Apply staleness detection to local query results -- only where the + # files are on this machine. With --content-backend=delegated they are + # not, and asking the content backend would page the whole repository's + # manifest per query: results carry no staleness instead of a wrong one. if results: try: staleness_start = time.time() - # Convert local results to QueryResultItem format for staleness detection - from .api_clients.remote_query_client import QueryResultItem - from .remote.staleness_detector import StalenessDetector - - query_result_items = [] - for result in results: - payload = result["payload"] - - # Extract file metadata for staleness comparison - file_last_modified = payload.get("file_last_modified") - indexed_at = payload.get("indexed_at") - - # Convert indexed_at ISO timestamp to Unix timestamp float - indexed_timestamp = None - if indexed_at: - try: - from datetime import datetime - - dt = datetime.fromisoformat(indexed_at.rstrip("Z")) - indexed_timestamp = dt.timestamp() - except (ValueError, AttributeError): - indexed_timestamp = None - - query_item = QueryResultItem( - similarity_score=result["score"], - file_path=payload.get("path", "unknown"), - line_number=payload.get("line_start", 1), - code_snippet=payload.get("content", ""), - repository_alias=project_root.name, - file_last_modified=file_last_modified, - indexed_timestamp=indexed_timestamp, - ) - query_result_items.append(query_item) - - # Apply staleness detection in local mode - staleness_detector = StalenessDetector() - enhanced_results = staleness_detector.apply_staleness_detection( - query_result_items, project_root, mode="local" - ) - timing_info["staleness_detection_ms"] = ( - time.time() - staleness_start - ) * 1000 - - # Annotate results with staleness detection metadata. - # When a reranker was applied (effective_rerank_query is set), - # pass preserve_order=True so _annotate_staleness iterates - # `results` (reranked order) and does not clobber it with the - # staleness-sort that apply_staleness_detection uses internally - # (bug #965). Without a reranker, fresh results sort first. - results = _annotate_staleness( - results, - enhanced_results, - preserve_order=bool(effective_rerank_query), + enhanced_results = _query_staleness( + results, project_root, content_backend ) + if enhanced_results is not None: + timing_info["staleness_detection_ms"] = ( + time.time() - staleness_start + ) * 1000 + + # Annotate results with staleness detection metadata. + # When a reranker was applied (effective_rerank_query is set), + # pass preserve_order=True so _annotate_staleness iterates + # `results` (reranked order) and does not clobber it with the + # staleness-sort that apply_staleness_detection uses internally + # (bug #965). Without a reranker, fresh results sort first. + results = _annotate_staleness( + results, + enhanced_results, + preserve_order=bool(effective_rerank_query), + ) except Exception as e: # Graceful fallback - continue with original results if staleness detection fails @@ -10013,9 +10221,35 @@ def uninstall(ctx, wipe_all: bool, confirm: bool): ) @click.option("--verbose", is_flag=True, help="Show detailed information about fixes") @click.option("--force", is_flag=True, help="Apply fixes without confirmation prompts") +@click.option( + "--content-backend", + type=click.Choice(["local", "delegated"]), + default="local", + hidden=True, + help="Internal: where the repository's files are. 'delegated' means they " + "are not on this machine, so the project id and git state the index run " + "recorded are kept instead of being re-derived here. Stamped by the server.", +) +@click.option( + "--git-backend", + type=click.Choice(["local", "delegated"]), + default="local", + hidden=True, + help="Internal: who answers git questions about the repository. " + "'delegated' keeps the git state the index run recorded through the " + "server's git backend instead of asking this machine's git. Stamped by " + "the server.", +) @click.pass_context @require_mode("local", "remote", "proxy") -def fix_config(ctx, dry_run: bool, verbose: bool, force: bool): +def fix_config( + ctx, + dry_run: bool, + verbose: bool, + force: bool, + content_backend: str = "local", + git_backend: str = "local", +): """Fix corrupted configuration files. \b @@ -10097,7 +10331,11 @@ def fix_config(ctx, dry_run: bool, verbose: bool, force: bool): console.print(f" 📄 Metadata file: {config_dir / 'metadata.json'}") # Initialize repairer - repairer = ConfigurationRepairer(config_dir, dry_run=dry_run) + repairer = ConfigurationRepairer( + config_dir, + dry_run=dry_run, + repository_backend_delegated="delegated" in (content_backend, git_backend), + ) # Run the fix process result = repairer.fix_configuration() @@ -19676,6 +19914,40 @@ def global_group(ctx): pass +def _global_activate_delegated_refusal() -> Optional[str]: + """Why ``cidx global activate`` must not run on this host, or None. + + It registers an alias pointing at ``/repos//.code-indexer/index`` + on THIS host's disk. Under the server's ``content_backend: delegated`` the + repositories live on the configured content backend content-backend plugin and each pod's index state is its own, + so that alias -- written to the registry every pod shares -- would name a + path no other pod has. The selection is read from the server config + (``CIDX_SERVER_DATA_DIR``, default ``~/.cidx-server``): this command runs + outside the server process. No server config means a plain CLI host: + nothing to refuse. An unreadable one is refused too -- the backend cannot + be known. + """ + from .server.startup.content_backend_wiring import content_backend_name + from .server.utils.config_manager import ServerConfigManager + + try: + server_config = ServerConfigManager().load_config() + except ValueError as exc: + return ( + f"cannot read the server config to tell whether repositories are " + f"on this host ({exc}); refusing to register an alias" + ) + if server_config is None or content_backend_name(server_config) != "delegated": + return None + return ( + "'cidx global activate' is not available when the server's " + "content_backend is 'delegated': repositories live on the configured content backend content-backend plugin and " + "an alias to this host's index would be unreadable on every other pod. " + "Add or refresh the golden repository through the server " + "(POST /api/admin/golden-repos or the refresh endpoint) instead." + ) + + @global_group.command("activate") @click.argument("repo_name") @click.pass_context @@ -19704,6 +19976,11 @@ def global_activate(ctx, repo_name: str): console = Console() + refusal = _global_activate_delegated_refusal() + if refusal is not None: + console.print(f"[red]Error: {refusal}[/red]") + sys.exit(1) + # Get golden repos directory golden_repos_dir = os.environ.get("CIDX_GOLDEN_REPOS_DIR") if not golden_repos_dir: @@ -20249,6 +20526,3 @@ def watch_stop_command(ctx): if __name__ == "__main__": main() - - -# SCIP commands registered via cli_scip import diff --git a/src/code_indexer/cli_features.py b/src/code_indexer/cli_features.py new file mode 100644 index 000000000..90a643f3c --- /dev/null +++ b/src/code_indexer/cli_features.py @@ -0,0 +1,137 @@ +"""Feature add-on CLI commands (``cli_commands()``), found only when needed. + +The ``cidx`` group (``cli.ModeAwareGroup``) asks this module ONLY when a +command name is not a built-in one, and when listing commands for help, so +no built-in command pays anything for features: nothing here is imported on +the normal path (the CLI startup import budget). + +Which features: every INSTALLED one (entry points in ``code_indexer.features``), +independent of the server's ``enabled_features``. A feature's CLI commands work +on the user's own machine and need no server, so a CLI-only user keeps +``cidx xray`` as long as the cidx-xray distribution is installed, and +uninstalling it removes the command. (The SERVER side of a feature -- tools, +routes, pages, migrations -- still requires the name in ``enabled_features``.) +Each feature is loaded and validated on its own by the server's loader +(``load_cli_commands``: the manifest and ``cli_commands()`` only, the same +refusals), so one refused add-on hides nothing else; a feature's +``on_startup`` never runs -- a command gets no ``FeatureContext``. Loading imports +``code_indexer.server``, whose import installs the kernel capabilities a +command reaches (runtime config, telemetry, the content seam). +""" + +from __future__ import annotations + +import sys +from typing import Dict, List, Optional + +import click + +#: ``cidx_sdk.FEATURES_ENTRY_POINT_GROUP``, spelled here so the no-feature +#: path imports neither the SDK nor the server (the CLI startup budget); a +#: test pins the two equal. +FEATURES_GROUP = "code_indexer.features" + +_commands: Optional[Dict[str, click.Command]] = None +#: Installed features refused for the CLI: feature name -> why. +_refusals: Dict[str, str] = {} + + +def feature_commands() -> Dict[str, click.Command]: + """Subcommand name -> click command, for every installed feature that + loads. Loaded once per process; refusals are kept in :data:`_refusals`. + + Raises: + click.ClickException: a contribution is not a click command, or two + features register the same command name. + """ + global _commands + if _commands is not None: + return _commands + if not _any_feature_installed(): + _commands = {} + return _commands + from cidx_sdk import KNOWN_CAPABILITIES + + from code_indexer.server.features.loader import ( + discover_installed_features, + load_cli_commands, + ) + + try: + candidates = discover_installed_features() + except Exception as exc: # two distributions claim one name + raise click.ClickException(f"feature add-ons: {exc}") from exc + by_feature, refusals = load_cli_commands( + candidates, + # The server provides every capability; a command never gets one. + provided_capabilities=KNOWN_CAPABILITIES, + ) + found: Dict[str, click.Command] = {} + for feature, contributions in by_feature.items(): + for contribution in contributions: + command = contribution.command + if not isinstance(command, click.Command): + raise click.ClickException( + f"feature {feature!r} command {contribution.name!r} " + f"is a {type(command).__name__}, not a click command" + ) + if contribution.name in found: + raise click.ClickException( + f"feature command {contribution.name!r} is registered twice" + ) + found[contribution.name] = command + _refusals.clear() + _refusals.update(refusals) + _commands = found + return _commands + + +def _any_feature_installed() -> bool: + """Whether any feature entry point exists, read from distribution + metadata (and a source-tree run's SDK registrations, which exist only if + the SDK resolver is already loaded) without importing the SDK or the + server.""" + from importlib.metadata import entry_points + + if list(entry_points(group=FEATURES_GROUP)): + return True + resolver = sys.modules.get("cidx_sdk.seams.resolver") + extras = getattr(resolver, "extra_entry_points", None) + return bool(extras is not None and extras().get(FEATURES_GROUP)) + + +def _refusal_message() -> str: + return "feature add-ons refused: " + "; ".join( + f"{name}: {why}" for name, why in sorted(_refusals.items()) + ) + + +def feature_command(name: str) -> Optional[click.Command]: + """The installed feature's command *name*, or None. A name no feature + provides while an installed add-on was refused fails loud (the command + may be that add-on's).""" + command = feature_commands().get(name) + if command is None and _refusals: + raise click.ClickException(_refusal_message()) + return command + + +def listed_feature_commands(builtin: List[str]) -> List[str]: + """Feature command names for help output, minus any shadowed by a + built-in. A refused feature is reported on stderr, not raised: help + must stay usable.""" + try: + names = sorted(feature_commands()) + except click.ClickException as exc: + print(f"Warning: {exc.message}", file=sys.stderr) + return [] + if _refusals: + print(f"Warning: {_refusal_message()}", file=sys.stderr) + return [name for name in names if name not in builtin] + + +def reset_feature_commands() -> None: + """Forget the loaded commands (tests).""" + global _commands + _commands = None + _refusals.clear() diff --git a/src/code_indexer/config.py b/src/code_indexer/config.py index bef22dce4..4be9ff19b 100644 --- a/src/code_indexer/config.py +++ b/src/code_indexer/config.py @@ -1,5 +1,6 @@ """Configuration management for Code Indexer.""" +from .utils.index_store import INDEX_DIRNAME, index_root import json import logging import os @@ -7,7 +8,7 @@ import threading as _threading import yaml # type: ignore from pathlib import Path -from typing import List, Optional, Any, Literal, Tuple, Dict +from typing import IO, List, Optional, Any, Literal, Tuple, Dict, Union from pydantic import ( BaseModel, @@ -765,7 +766,7 @@ class Config(BaseModel): ".next", ".nuxt", "dist-*", - ".code-indexer", + INDEX_DIRNAME, ], description="Directories to exclude from indexing", ) @@ -959,7 +960,7 @@ class ConfigCorruptionError(ValueError): class ConfigManager: """Manages configuration loading, saving, and validation.""" - DEFAULT_CONFIG_PATH = Path(".code-indexer/config.json") + DEFAULT_CONFIG_PATH = index_root(Path(".")) / "config.json" # Daemon configuration defaults DAEMON_DEFAULTS = { @@ -971,10 +972,30 @@ class ConfigManager: "eviction_check_interval_seconds": 60, } - def __init__(self, config_path: Optional[Path] = None): + def __init__( + self, config_path: Optional[Path] = None, project_root: Optional[Path] = None + ): self.config_path = config_path or self.DEFAULT_CONFIG_PATH + # The repository this config belongs to, when the caller knows it -- + # discovery does: it found the config by asking the IndexStore about + # that very directory. See the project_root property. + self._project_root = project_root self._config: Optional[Config] = None + @property + def project_root(self) -> Path: + """The repository this config describes. + + Recorded at discovery when known. Otherwise derived from the config's + own location -- ``/.code-indexer/config.json`` -- which is true + only while the IndexStore keeps the index inside the repository (the + local backend). A store that relocates it (content seam step 2) must + record the root instead; this is the ONE place that derivation lives. + """ + if self._project_root is not None: + return self._project_root + return self.config_path.parent.parent + def load(self) -> Config: """Load configuration from file or create default with dynamic path resolution.""" if self.config_path.exists(): @@ -1011,12 +1032,11 @@ def load(self) -> Config: path = Path(data["codebase_dir"]) if not path.is_absolute(): # If relative, resolve relative to config directory - config_dir = self.config_path.parent.parent - path = (config_dir / path).resolve() + path = (self.project_root / path).resolve() data["codebase_dir"] = str(path) # Bug #1033: reconcile against actual config file location. # On NFS clusters, nodes may mount the same share at different paths. - actual_dir = self.config_path.resolve().parent.parent + actual_dir = self.project_root.resolve() if path.is_absolute() and actual_dir != path.resolve(): # Story #1082: the reconciliation (override) below is # LOAD-BEARING and runs every load; only the WARNING is @@ -1046,9 +1066,8 @@ def load(self) -> Config: # Config() defaults codebase_dir to Path(".") which is relative. # Resolve it against the project root (parent of .code-indexer/). if not self._config.codebase_dir.is_absolute(): - config_dir = self.config_path.parent.parent self._config.codebase_dir = ( - config_dir / self._config.codebase_dir + self.project_root / self._config.codebase_dir ).resolve() else: self._config = Config() @@ -1244,28 +1263,36 @@ def find_config_path(start_dir: Optional[Path] = None) -> Optional[Path]: Returns: Path to config.json if found, None otherwise """ - # Safely get current working directory with fallback + found = ConfigManager._discover(start_dir) + return found[0] if found else None + + @staticmethod + def _search_start(start_dir: Optional[Path] = None) -> Path: + """Where discovery starts: ``start_dir``, else the cwd, else the temp dir.""" if start_dir: - current = start_dir - else: - try: - current = Path.cwd() - except (FileNotFoundError, OSError): - # Working directory deleted - use temp directory as fallback - import tempfile + return Path(start_dir) + try: + return Path.cwd() + except (FileNotFoundError, OSError): + # Working directory deleted - use temp directory as fallback + import tempfile - current = Path(tempfile.gettempdir()) + return Path(tempfile.gettempdir()) - # Walk up the directory tree looking for .code-indexer/config.json + @staticmethod + def _discover(start_dir: Optional[Path] = None) -> Optional[Tuple[Path, Path]]: + """``(config_path, project_root)`` of the nearest project, from ONE walk. + + The root is the ancestor whose index root held the config -- taken from + the same iteration that matched, never re-derived from the config path, + which with a relocated store would name the store, not the repository. + """ + current = ConfigManager._search_start(start_dir) # CRITICAL: Must stop at first match to support nested projects - search_paths = [current] + list(current.parents) - for path in search_paths: - config_path = path / ".code-indexer" / "config.json" + for path in [current] + list(current.parents): + config_path = index_root(path) / "config.json" if config_path.exists(): - # DEFENSIVE: Ensure we return immediately at first match - # This prevents any issues with continued searching - return config_path - + return config_path, path return None @classmethod @@ -1293,17 +1320,11 @@ def detect_mode( if start_path: current = Path(start_path).resolve() else: - try: - current = Path.cwd() - except (FileNotFoundError, OSError): - # Working directory deleted - use temp directory as fallback - import tempfile - - current = Path(tempfile.gettempdir()) + current = cls._search_start() # Walk up the directory tree looking for .code-indexer/config.json while current != current.parent: - config_dir = current / ".code-indexer" + config_dir = index_root(current) config_file = config_dir / "config.json" if config_file.exists(): @@ -1366,27 +1387,17 @@ def create_with_backtrack(cls, start_dir: Optional[Path] = None) -> "ConfigManag logger.debug( f"Using CODEBASE_DIR environment variable override: {override_dir}" ) - override_config_path = override_dir / ".code-indexer" / "config.json" - return cls(override_config_path) + override_config_path = index_root(override_dir) / "config.json" + return cls(override_config_path, project_root=override_dir) - # CRITICAL: Use find_config_path which stops at first match - config_path = cls.find_config_path(start_dir) - if config_path is None: + # CRITICAL: the first match, as find_config_path; the root comes with it + found = cls._discover(start_dir) + if found is None: # If no config found, use default path from the start directory - if start_dir: - start = start_dir - else: - try: - start = Path.cwd() - except (FileNotFoundError, OSError): - # Working directory deleted - use temp directory as fallback - import tempfile - - start = Path(tempfile.gettempdir()) - config_path = start / ".code-indexer" / "config.json" - - # DEFENSIVE: Ensure we always return a ConfigManager with the first found config - return cls(config_path) + start = cls._search_start(start_dir) + found = (index_root(start) / "config.json", start) + config_path, project_root = found + return cls(config_path, project_root=project_root) @classmethod def load_verified_config(cls, target_dir: "Path") -> "Config": @@ -1605,20 +1616,22 @@ def get_socket_path(self) -> Path: if daemon_config.get("socket_base"): socket_base = Path(daemon_config["socket_base"]) ensure_socket_directory(socket_base, socket_mode) - repo_hash = generate_repo_hash(self.config_path.parent.parent) + repo_hash = generate_repo_hash(self.project_root) socket_path = socket_base / f"{repo_hash}.sock" else: # Use standard location - socket_path = generate_socket_path( - self.config_path.parent.parent, socket_mode - ) + socket_path = generate_socket_path(self.project_root, socket_mode) # Create mapping file for debugging - create_mapping_file(self.config_path.parent.parent, socket_path) + create_mapping_file(self.project_root, socket_path) return socket_path +#: The repository-root file a project uses to adjust what cidx indexes. +OVERRIDE_FILENAME = ".code-indexer-override.yaml" + + def _load_override_config(override_path: Path) -> OverrideConfig: """Load override configuration from YAML file. @@ -1633,42 +1646,63 @@ def _load_override_config(override_path: Path) -> OverrideConfig: """ try: with open(override_path, "r") as f: - data = yaml.safe_load(f) - - if not isinstance(data, dict): - raise ValueError("Override config must be a YAML dictionary") - - # Validate required fields exist - required_fields = [ - "add_extensions", - "remove_extensions", - "add_exclude_dirs", - "add_include_dirs", - "force_include_patterns", - "force_exclude_patterns", - ] - - missing_fields = [field for field in required_fields if field not in data] - if missing_fields: - raise ValueError( - f"Missing required fields in override config: {missing_fields}" - ) - - return OverrideConfig( - add_extensions=data["add_extensions"] or [], - remove_extensions=data["remove_extensions"] or [], - add_exclude_dirs=data["add_exclude_dirs"] or [], - add_include_dirs=data["add_include_dirs"] or [], - force_include_patterns=data["force_include_patterns"] or [], - force_exclude_patterns=data["force_exclude_patterns"] or [], - ) - + return _override_config_from_yaml(f) except yaml.YAMLError as e: raise Exception(f"Failed to parse override YAML file {override_path}: {e}") except Exception as e: raise Exception(f"Failed to load override config from {override_path}: {e}") +def override_config_from_bytes(data: bytes, origin: str) -> OverrideConfig: + """Parse an override file's bytes -- the same rules and errors as + ``_load_override_config``, with ``origin`` naming the file in the message. + + For a repository that is not on this machine: a delegated indexing pass + fetches the repository's own override file through the content backend + (``FileFinder.set_manifest``) instead of the local probe in + ``ConfigManager.load``, which on such a pod never finds it. + """ + try: + return _override_config_from_yaml(data) + except yaml.YAMLError as e: + raise Exception(f"Failed to parse override YAML file {origin}: {e}") + except Exception as e: + raise Exception(f"Failed to load override config from {origin}: {e}") + + +def _override_config_from_yaml(stream: Union[bytes, IO[str]]) -> OverrideConfig: + """Parse and validate override YAML. Raises the raw YAML/ValueError.""" + data = yaml.safe_load(stream) + + if not isinstance(data, dict): + raise ValueError("Override config must be a YAML dictionary") + + # Validate required fields exist + required_fields = [ + "add_extensions", + "remove_extensions", + "add_exclude_dirs", + "add_include_dirs", + "force_include_patterns", + "force_exclude_patterns", + ] + + missing_fields = [field for field in required_fields if field not in data] + if missing_fields: + raise ValueError( + f"Missing required fields in override config: {missing_fields}" + ) + + return OverrideConfig( + add_extensions=data["add_extensions"] or [], + remove_extensions=data["remove_extensions"] or [], + add_exclude_dirs=data["add_exclude_dirs"] or [], + add_include_dirs=data["add_include_dirs"] or [], + force_include_patterns=data["force_include_patterns"] or [], + force_exclude_patterns=data["force_exclude_patterns"] or [], + ) + + def _find_override_file(start_dir: Path) -> Optional[Path]: """Find .code-indexer-override.yaml by walking up the directory tree. @@ -1683,7 +1717,7 @@ def _find_override_file(start_dir: Path) -> Optional[Path]: # Walk up the directory tree looking for .code-indexer-override.yaml search_paths = [current] + list(current.parents) for path in search_paths: - override_path = path / ".code-indexer-override.yaml" + override_path = path / OVERRIDE_FILENAME if override_path.exists(): return override_path