Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(core): Ansible playbook/role dependency edges for YAML (#4397) (#4399)
tahodev5959e96b38ee
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/yaml.py b/packages/core/src/repowise/core/ingestion/languages/specs/yaml.pyindex 19271b836..9d33b9f1a 100644--- a/packages/core/src/repowise/core/ingestion/languages/specs/yaml.py+++ b/packages/core/src/repowise/core/ingestion/languages/specs/yaml.py@@ -9,4 +9,7 @@ SPEC = LanguageSpec(is_code=False,is_passthrough=True,color_hex="#CB171E",+ # Ansible playbook/role wiring via the lightweight tier: real edges+ # inside Ansible projects, nothing claimed for plain YAML configs.+ import_support="partial",)diff --git a/packages/core/src/repowise/core/ingestion/lightweight_imports/__init__.py b/packages/core/src/repowise/core/ingestion/lightweight_imports/__init__.pyindex cb31b2161..c7771eb60 100644--- a/packages/core/src/repowise/core/ingestion/lightweight_imports/__init__.py+++ b/packages/core/src/repowise/core/ingestion/lightweight_imports/__init__.py@@ -27,6 +27,7 @@ from __future__ import annotationsfrom collections.abc import Callablefrom ..models import FileInfo, Import+from .ansible import extract_ansible_importsfrom .clojure import extract_clojure_importsfrom .dart import extract_dart_importsfrom .elixir import extract_elixir_imports@@ -55,6 +56,10 @@ _EXTRACTORS: dict[str, ExtractorFn] = {# dbt {{ ref() }} / {{ source() }}, the only import system .sql files# have; plain SQL contains neither form, so this is a no-op outside dbt."sql": extract_dbt_imports,+ # Ansible playbook/task/role wiring, the only dependency system .yml+ # files have that we can resolve statically; byte-gated + shape-gated,+ # so plain YAML config is untouched. See ansible.py.+ "yaml": extract_ansible_imports,# <script src> / <link href>. AST-backed rather than regex — see above."html": extract_html_imports,# [ext_resource path=...] in .tscn/.tres/.escn, plus project.godot'sdiff --git a/packages/core/src/repowise/core/ingestion/lightweight_imports/ansible.py b/packages/core/src/repowise/core/ingestion/lightweight_imports/ansible.pynew file mode 100644index 000000000..351ca378d--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/lightweight_imports/ansible.py@@ -0,0 +1,184 @@+"""Dependency extraction for Ansible YAML: playbooks, task files, role meta.++Ansible repositories declare their wiring in YAML, which the registry classifies+as generic passthrough config, so the playbook/role layer produced no edges at+all (#4397). The constructs that carry a dependency are a small, closed set of+keys::++ - import_playbook: site.yml # playbook -> playbook+ - ansible.builtin.import_playbook: site.yml # FQCN spelling+ - import_tasks: tasks/foo.yml # play/task-file -> task file+ - include_tasks: { file: tasks/foo.yml } # dict form+ - import_role: { name: common } # play/task -> role+ - include_role: common # plain-string form+ - roles: [common, { role: db }] # play -> role+ # roles/<name>/meta/main.yml:+ dependencies: [base, { role: users }] # role -> role++``import_*`` is static and ``include_*`` dynamic in Ansible's execution, but+both spell a dependency on a literal target, so both yield edges. Targets with+Jinja interpolation (``{{ x }}`` / ``{% x %}``) are skipped, not guessed: a+template can expand to anything, and an edge to a guessed file is worse than a+documented absence.++Ansible YAML has no file-level marker that distinguishes it from CI configs or+Kubernetes manifests, so this extractor gates twice: a byte-level substring+check before PyYAML is invoked on a file at all, then the document's own shape+(a top-level list of plays/tasks, or a role ``meta/main.yml`` carrying+``galaxy_info``). Plain YAML walks away with zero imports, the same contract+``sql`` keeps for non-dbt files.++Role references resolve by *name*, not path, so the extractor stamps them+``role:<name>`` in ``module_path`` for the resolver (``resolvers/ansible.py``);+file references stay plain relative paths. A role edge targets the role's+conventional entry file (``roles/<name>/tasks/main.yml``) -- the graph's nodes+are files, so that entry file is what stands for the role.++Known ceilings, recorded as absent edges rather than guesses:++* ``import_tasks`` with a loop or ``apply:`` is still a single literal file,+ so it is covered.+* Role ``dependencies`` count only alongside ``galaxy_info``: a bare top-level+ ``dependencies:`` list without ``galaxy_info`` is not claimed as role wiring,+ because generic config files use that key freely.+* Galaxy/collection roles and custom ``roles_path`` directories are not visible+ to a repo-local resolver; the resolver returns ``None`` for them (deferred,+ per the issue) rather than fabricating an external node.+"""++from __future__ import annotations++from ..models import Import++_FQCN = "ansible.builtin."++# Byte-level pre-gate, checked before PyYAML runs on the file at all.+_GATE_TOKENS = (+ "import_playbook",+ "import_tasks",+ "include_tasks",+ "import_role",+ "include_role",+ "roles:",+ "galaxy_info",+)++# Keys whose presence marks a top-level list item as a play, not a task.+_PLAY_KEYS = frozenset({"hosts", "roles", "tasks", "handlers", "pre_tasks", "post_tasks"})+# Play sections that hold task lists.+_TASK_LIST_KEYS = ("tasks", "handlers", "pre_tasks", "post_tasks")+# Task keys that nest further task lists.+_BLOCK_KEYS = ("block", "rescue", "always")++_ROLE_PREFIX = "role:"+++def extract_ansible_imports(text: str) -> list[Import]:+ """Extract Ansible dependency references from a YAML document's text."""+ if not any(token in text for token in _GATE_TOKENS):+ return []+ try:+ import yaml # pyyaml, already a dependency (see special_handlers)+ except ImportError:+ return []+ try:+ data = yaml.safe_load(text)+ except Exception:+ return []++ imports: list[Import] = []+ if isinstance(data, list):+ # Playbook (list of plays) or task file (list of tasks).+ for item in data:+ if not isinstance(item, dict):+ continue+ playbook = _key(item, "import_playbook")+ if isinstance(playbook, str):+ _add(imports, playbook, kind="file", raw=f"import_playbook: {playbook}")+ elif _PLAY_KEYS & item.keys():+ _walk_play(item, imports)+ else:+ _walk_task(item, imports)+ elif isinstance(data, dict):+ # Role meta/main.yml: role -> role dependencies. ``galaxy_info`` is the+ # marker that keeps a generic ``dependencies:`` list out of scope.+ dependencies = data.get("dependencies")+ if "galaxy_info" in data and isinstance(dependencies, list):+ for dep in dependencies:+ name = _role_name(dep)+ if name is not None:+ _add(imports, name, kind="role", raw=f"dependencies: {name}")+ return imports+++def _key(mapping: dict, name: str) -> object:+ """Value of *name* or its ``ansible.builtin.`` FQCN spelling, if present."""+ if name in mapping:+ return mapping[name]+ return mapping.get(_FQCN + name)+++def _role_name(entry: object) -> str | None:+ """Role name from a ``roles:``/``dependencies:`` entry, or None."""+ if isinstance(entry, str):+ return entry+ if isinstance(entry, dict):+ name = entry.get("role") or entry.get("name")+ if isinstance(name, str):+ return name+ return None+++def _walk_play(play: dict, imports: list[Import]) -> None:+ roles = play.get("roles")+ if isinstance(roles, list):+ for entry in roles:+ name = _role_name(entry)+ if name is not None:+ _add(imports, name, kind="role", raw=f"roles: {name}")+ for key in _TASK_LIST_KEYS:+ section = play.get(key)+ if isinstance(section, list):+ for task in section:+ if isinstance(task, dict):+ _walk_task(task, imports)+++def _walk_task(task: dict, imports: list[Import]) -> None:+ for key in ("import_tasks", "include_tasks"):+ value = _key(task, key)+ target: object = value+ if isinstance(value, dict):+ target = value.get("file")+ if isinstance(target, str):+ _add(imports, target, kind="file", raw=f"{key}: {target}")+ for key in ("import_role", "include_role"):+ value = _key(task, key)+ name: object = value+ if isinstance(value, dict):+ name = value.get("name")+ if isinstance(name, str):+ _add(imports, name, kind="role", raw=f"{key}: {name}")+ for key in _BLOCK_KEYS:+ section = task.get(key)+ if isinstance(section, list):+ for sub in section:+ if isinstance(sub, dict):+ _walk_task(sub, imports)+++def _add(imports: list[Import], target: str, *, kind: str, raw: str) -> None:+ target = target.strip()+ # Jinja-interpolated targets expand at run time; skipping is documented+ # behaviour, not a miss (see module docstring).+ if not target or "{{" in target or "{%" in target:+ return+ imports.append(+ Import(+ raw_statement=raw,+ module_path=_ROLE_PREFIX + target if kind == "role" else target,+ imported_names=[],+ is_relative=True,+ resolved_file=None,+ )+ )diff --git a/packages/core/src/repowise/core/ingestion/resolvers/__init__.py b/packages/core/src/repowise/core/ingestion/resolvers/__init__.pyindex 4fc36ca9e..b6bb780de 100644--- a/packages/core/src/repowise/core/ingestion/resolvers/__init__.py+++ b/packages/core/src/repowise/core/ingestion/resolvers/__init__.py@@ -4,6 +4,7 @@ from __future__ import annotationsfrom collections.abc import Callable+from .ansible import resolve_ansible_importfrom .clojure import resolve_clojure_importfrom .cobol import resolve_cobol_importfrom .context import ResolverContext@@ -77,6 +78,8 @@ _RESOLVERS: dict[str, ResolverFn] = {"fsharp": resolve_fsharp_import,# dbt ref()/source(), gated on dbt_project.yml via the model index."sql": resolve_dbt_import,+ # Ansible file paths + `role:<name>` stamps from the yaml extractor.+ "yaml": resolve_ansible_import,# <script src>/<link href> are asset paths, not module specifiers — they# get their own document-/root-relative resolution, never the TS/JS one."html": resolve_html_asset,diff --git a/packages/core/src/repowise/core/ingestion/resolvers/ansible.py b/packages/core/src/repowise/core/ingestion/resolvers/ansible.pynew file mode 100644index 000000000..3054553ba--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/ansible.py@@ -0,0 +1,75 @@+"""Resolver for Ansible dependency references (lightweight tier, ``yaml``).++Two reference shapes arrive from ``lightweight_imports.ansible``:++* plain file paths (``import_playbook`` / ``import_tasks`` / ``include_tasks``),+ resolved relative to the importing file only (Ansible's own rule; the repo+ root is never a fallback, so a same-named root file cannot steal the edge),+ with ``.yml`` / ``.yaml`` probing when the target omits the extension;+* ``role:<name>`` stamps (``roles:`` entries, ``import_role`` / ``include_role``,+ role ``meta/main.yml`` dependencies), resolved to the role's conventional+ entry file ``roles/<name>/tasks/main.yml`` -- the graph's nodes are files,+ so the entry file is what stands for the role. Looked up from the importer's+ directory upward to the repo root, so a playbook in a subdirectory finds a+ sibling ``roles/`` tree the way Ansible's own search path does.++A miss returns ``None``: Galaxy/collection roles and custom ``roles_path``+layouts are repo-external, and the issue scopes them as deferred rather than+claimed.+"""++from __future__ import annotations++from pathlib import PurePosixPath++from .context import ResolverContext+from .gdscript import _join_relative++_ROLE_PREFIX = "role:"+_YAML_EXTENSIONS = (".yml", ".yaml")+++def resolve_ansible_import(+ module_path: str, importer_path: str, ctx: ResolverContext+) -> str | None:+ """Resolve an Ansible file or role reference to a repo-relative path."""+ raw = module_path.strip()+ if not raw:+ return None+ if raw.startswith(_ROLE_PREFIX):+ return _resolve_role(raw[len(_ROLE_PREFIX) :], importer_path, ctx)+ return _resolve_file(raw, importer_path, ctx)+++def _resolve_file(target: str, importer_path: str, ctx: ResolverContext) -> str | None:+ names = (+ [target]+ if target.endswith(_YAML_EXTENSIONS)+ else [target + ext for ext in _YAML_EXTENSIONS] + [target]+ )+ importer_dir = PurePosixPath(importer_path).parent+ for name in names:+ candidate = _join_relative(importer_dir, name)+ if candidate is not None and candidate in ctx.path_set:+ return candidate+ return None+++def _resolve_role(name: str, importer_path: str, ctx: ResolverContext) -> str | None:+ # Galaxy/collection names (``geerlingguy.nginx``, ``namespace.collection.role``)+ # and path-like names are repo-external by definition; resolving them to a+ # vendored directory that happens to match would be a wrong edge, which is+ # worse than the documented absence.+ if "." in name or "/" in name:+ return None+ # Importer's directory first, walking up to the repo root, so playbooks in+ # a subdirectory resolve a sibling ``roles/`` tree (Ansible's search path+ # covers both the playbook directory and the current directory).+ parts = [p for p in PurePosixPath(importer_path).parent.parts if p not in ("", ".")]+ for i in range(len(parts), -1, -1):+ prefix = "/".join(parts[:i])+ for ext in _YAML_EXTENSIONS:+ candidate = f"{prefix + '/' if prefix else ''}roles/{name}/tasks/main{ext}"+ if candidate in ctx.path_set:+ return candidate+ return Nonediff --git a/tests/unit/ingestion/test_ansible_imports.py b/tests/unit/ingestion/test_ansible_imports.pynew file mode 100644index 000000000..dfd1ac721--- /dev/null+++ b/tests/unit/ingestion/test_ansible_imports.py@@ -0,0 +1,241 @@+"""Unit tests for Ansible YAML dependency extraction + resolution (#4397).++Covers every construct the extractor claims (import_playbook, roles:,+import/include_tasks, import/include_role, role meta dependencies), the+FQCN spelling, block nesting, the Jinja-skip rule, and the guards that+keep plain YAML configs import-free.+"""++from __future__ import annotations++from datetime import datetime+from pathlib import Path++import networkx as nx++from repowise.core.ingestion.lightweight_imports import extract_lightweight_imports+from repowise.core.ingestion.lightweight_imports.ansible import extract_ansible_imports+from repowise.core.ingestion.models import FileInfo+from repowise.core.ingestion.resolvers import resolve_import+from repowise.core.ingestion.resolvers.ansible import resolve_ansible_import+from repowise.core.ingestion.resolvers.context import ResolverContext+++def _ctx(repo: Path | None, files: dict[str, str]) -> ResolverContext:+ """ResolverContext over *files* ({path: content}); writes them under *repo*."""+ if repo is not None:+ for rel, content in files.items():+ target = repo / rel+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_text(content, encoding="utf-8")+ stem_map: dict[str, list[str]] = {}+ for p in files:+ stem = p.rsplit("/", 1)[-1].rsplit(".", 1)[0].lower()+ stem_map.setdefault(stem, []).append(p)+ return ResolverContext(+ path_set=set(files),+ stem_map=stem_map,+ graph=nx.DiGraph(),+ repo_path=repo,+ )+++def _file_info(rel: str, lang: str) -> FileInfo:+ return FileInfo(+ path=rel,+ abs_path=f"/tmp/{rel}",+ language=lang, # type: ignore[arg-type]+ size_bytes=0,+ git_hash="",+ last_modified=datetime.now(),+ is_test=False,+ is_config=False,+ is_api_contract=False,+ is_entry_point=False,+ )+++def _modules(imports) -> list[str]:+ return [imp.module_path for imp in imports]+++def _extract(path: str, text: str, lang: str = "yaml"):+ return extract_lightweight_imports(_file_info(path, lang), text.encode())+++PLAYBOOK = """\+- import_playbook: base.yml+- name: web+ hosts: webservers+ roles:+ - common+ - role: app+ tags: [deploy]+ tasks:+ - import_tasks: tasks/setup.yml+ - name: deploy+ block:+ - include_tasks:+ file: tasks/deploy.yml+ - ansible.builtin.include_role:+ name: monitoring+ rescue:+ - import_role:+ name: rollback+"""++ROLE_META = """\+galaxy_info:+ author: someone+dependencies:+ - base+ - role: users+"""+++class TestAnsibleExtraction:+ def test_import_playbook(self) -> None:+ assert _modules(extract_ansible_imports("- import_playbook: base.yml\n")) == ["base.yml"]++ def test_fqcn_playbook_import(self) -> None:+ src = "- ansible.builtin.import_playbook: base.yml\n"+ assert _modules(extract_ansible_imports(src)) == ["base.yml"]++ def test_full_playbook(self) -> None:+ assert _modules(extract_ansible_imports(PLAYBOOK)) == [+ "base.yml",+ "role:common",+ "role:app",+ "tasks/setup.yml",+ "tasks/deploy.yml",+ "role:monitoring",+ "role:rollback",+ ]++ def test_task_file_top_level(self) -> None:+ src = "- import_tasks: sub.yml\n- include_role: cleanup\n"+ assert _modules(extract_ansible_imports(src)) == ["sub.yml", "role:cleanup"]++ def test_meta_main_dependencies(self) -> None:+ assert _modules(extract_ansible_imports(ROLE_META)) == ["role:base", "role:users"]++ def test_meta_without_galaxy_info_is_ignored(self) -> None:+ src = "dependencies:\n - base\n"+ assert extract_ansible_imports(src) == []++ def test_jinja_targets_skipped(self) -> None:+ src = "- import_tasks: '{{ item }}.yml'\n- include_role: '{{ role_name }}'\n"+ assert extract_ansible_imports(src) == []++ def test_plain_yaml_untouched(self) -> None:+ src = "apiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: web\n"+ assert extract_ansible_imports(src) == []++ def test_byte_gate(self) -> None:+ assert extract_ansible_imports("key: value\nlist: [1, 2]\n") == []++ def test_invalid_yaml_returns_nothing(self) -> None:+ src = "- roles: [{{{\n unbalanced\n"+ assert extract_ansible_imports(src) == []++ def test_dispatch_through_language(self) -> None:+ assert _modules(_extract("site.yml", PLAYBOOK)) == _modules(+ extract_ansible_imports(PLAYBOOK)+ )++ def test_non_yaml_language_untouched(self) -> None:+ assert _extract("models/stg.sql", PLAYBOOK, "sql") == []+++FILES = {+ "site.yml": PLAYBOOK,+ "base.yml": "- name: base\n hosts: all\n",+ "tasks/setup.yml": "- name: setup\n debug: msg=x\n",+ "tasks/deploy.yml": "- name: deploy\n debug: msg=x\n",+ "roles/common/tasks/main.yml": "- name: common\n debug: msg=x\n",+ "roles/app/tasks/main.yaml": "- name: app\n debug: msg=x\n",+ "roles/base/tasks/main.yml": "- name: base\n debug: msg=x\n",+ "roles/users/tasks/main.yml": "- name: users\n debug: msg=x\n",+ "setup.yml": "- name: root\n debug: msg=x\n",+ "sub/play.yml": "- name: sub\n hosts: all\n tasks:\n - import_tasks: setup.yml\n",+ "sub/setup.yml": "- name: nested\n debug: msg=x\n",+ "playbooks/web.yml": "- name: web\n hosts: all\n roles: [common]\n",+}+++class TestAnsibleResolution:+ def test_playbook_import_relative(self) -> None:+ ctx = _ctx(None, FILES)+ assert resolve_import("base.yml", "site.yml", "yaml", ctx) == "base.yml"++ def test_task_file_relative(self) -> None:+ ctx = _ctx(None, FILES)+ assert resolve_import("tasks/setup.yml", "site.yml", "yaml", ctx) == "tasks/setup.yml"++ def test_importer_dir_first(self) -> None:+ ctx = _ctx(None, FILES)+ # sub/play.yml's own setup.yml wins over the repo-root one.+ assert resolve_import("setup.yml", "sub/play.yml", "yaml", ctx) == "sub/setup.yml"++ def test_repo_root_is_not_a_fallback(self) -> None:+ # Ansible resolves import_playbook from the including file; a root+ # other.yml must not stand in for a missing sub/other.yml.+ files = dict(FILES)+ files["other.yml"] = "- name: other\n hosts: all\n"+ ctx = _ctx(None, files)+ assert resolve_import("other.yml", "sub/play.yml", "yaml", ctx) is None+ assert resolve_ansible_import("other", "sub/play.yml", ctx) is None++ def test_extension_probing(self) -> None:+ ctx = _ctx(None, FILES)+ assert resolve_ansible_import("tasks/setup", "site.yml", ctx) == "tasks/setup.yml"++ def test_role_from_root_playbook(self) -> None:+ ctx = _ctx(None, FILES)+ assert (+ resolve_import("role:common", "site.yml", "yaml", ctx) == "roles/common/tasks/main.yml"+ )++ def test_role_yaml_extension(self) -> None:+ ctx = _ctx(None, FILES)+ assert resolve_import("role:app", "site.yml", "yaml", ctx) == "roles/app/tasks/main.yaml"++ def test_role_from_subdirectory_playbook(self) -> None:+ ctx = _ctx(None, FILES)+ # playbooks/web.yml finds the repo-root roles/ tree by walking up.+ assert (+ resolve_import("role:common", "playbooks/web.yml", "yaml", ctx)+ == "roles/common/tasks/main.yml"+ )++ def test_missing_file_returns_none(self) -> None:+ ctx = _ctx(None, FILES)+ assert resolve_import("nope/missing.yml", "site.yml", "yaml", ctx) is None++ def test_galaxy_role_returns_none(self) -> None:+ ctx = _ctx(None, FILES)+ assert resolve_import("role:geerlingguy.nginx", "site.yml", "yaml", ctx) is None++ def test_galaxy_role_rejected_even_when_directory_exists(self) -> None:+ # A vendored roles/geerlingguy.nginx/ directory must not lure the+ # resolver into a wrong edge: dotted names are Galaxy-scoped.+ files = dict(FILES)+ files["roles/geerlingguy.nginx/tasks/main.yml"] = "- debug: msg=x\n"+ ctx = _ctx(None, files)+ assert resolve_import("role:geerlingguy.nginx", "site.yml", "yaml", ctx) is None++ def test_collection_role_rejected(self) -> None:+ files = dict(FILES)+ files["roles/ns.coll.role/tasks/main.yml"] = "- debug: msg=x\n"+ ctx = _ctx(None, files)+ assert resolve_import("role:ns.coll.role", "site.yml", "yaml", ctx) is None++ def test_path_like_role_rejected(self) -> None:+ files = dict(FILES)+ files["roles/vendor/common/tasks/main.yml"] = "- debug: msg=x\n"+ ctx = _ctx(None, files)+ assert resolve_import("role:vendor/common", "site.yml", "yaml", ctx) is None++ def test_empty_target_returns_none(self) -> None:+ ctx = _ctx(None, FILES)+ assert resolve_ansible_import(" ", "site.yml", ctx) is Nonediff --git a/tests/unit/ingestion/test_language_capabilities.py b/tests/unit/ingestion/test_language_capabilities.pyindex cad68cb07..6aa63b6e8 100644--- a/tests/unit/ingestion/test_language_capabilities.py+++ b/tests/unit/ingestion/test_language_capabilities.py@@ -216,6 +216,9 @@ _PARTIAL = {# import QtQuick / import "components": module specs via the qmldir# index, quoted references relative to the importing file (#727)."qml",+ # Ansible playbook/role wiring via the lightweight tier: real edges+ # inside Ansible projects, nothing claimed for plain YAML config (#4397).+ "yaml",}diff --git a/tests/unit/ingestion/test_lightweight_resolvers.py b/tests/unit/ingestion/test_lightweight_resolvers.pyindex 63de91fd3..e5bd3c620 100644--- a/tests/unit/ingestion/test_lightweight_resolvers.py+++ b/tests/unit/ingestion/test_lightweight_resolvers.py@@ -98,6 +98,9 @@ class TestDispatch:# Godot .tscn/.tres/.escn + project.godot + plugin.cfg. The only# member at import_support="full" -- see the package docstring."godot_resource",+ # Ansible playbook/role wiring in .yml files; byte- and shape-gated+ # so plain YAML config is untouched (#4397).+ "yaml",} == LIGHTWEIGHT_IMPORT_LANGUAGESdef test_other_language_returns_empty(self) -> None: