orchestrata_ultimate.verification.review.checks_correctness

Reference › orchestrata_ultimate › verification › review › checks_correctness

The correctness checks of the deterministic review: does the code import what exists, run as an entry point, and declare what it needs. It is called by the review engine, by the junior volk and by the refactor codemod's review checks. Each function takes a file path and its parsed AST and returns a list of issue tuples.

Shared parsing helpers come from helpers and the issue alias from types.

At a glance

Source src/orchestrata_ultimate/verification/review/checks_correctness.py
Lines of code 196
Classes 0
Functions 5
Imports (internal) orchestrata_ultimate.core.base.traces, orchestrata_ultimate.verification.review.helpers, orchestrata_ultimate.verification.review.types
Imported by orchestrata_ultimate.agents.volks.junior.volk, orchestrata_ultimate.refactor.codemod.review_checks, orchestrata_ultimate.verification.review.engine
Tests that import it tests/verification/review/test_checks_correctness.py, tests/verification/test_checks_correctness.py, tests/verification/test_review_checks.py, tests/verification/test_review_checks_expanded.py

Class diagram

No classes; see Functions.

Dependency diagram

Dependency diagram orchestrata_ultimate.verification.review.checks_correctness

API

Functions

Function Signature Summary
check_imports check_imports(filepath: str, tree: ast.Module, project_modules: set[str]) -> list[Issue] Check 1: IMPORTS -- ordering and relative imports.
check_file_completeness check_file_completeness(filepath: str, tree: ast.Module, workspace_files: set[str], project_modules: set[str]) -> list[Issue] Check 4: FILE_COMPLETENESS -- imported local modules exist.
_build_module_candidates _build_module_candidates(top: str, full_path: str) -> list[str] Build candidate file paths for a module import.
check_entry_point check_entry_point(filepath: str, lines: list[str], is_main_file: bool) -> list[Issue] Check 5: ENTRY_POINT -- main guard present.
check_dependency_declaration traces check_dependency_declaration(filepath: str, tree: ast.Module, declared_deps: set[str], project_modules: set[str]) -> list[Issue] Check 6: DEPENDENCY_DECLARATION -- third-party declared.

Source

Permalink: https://gitlab.com/MSamy/orchestrata-ultimate-architecture/-/blob/a4cbc2bdf/src/orchestrata_ultimate/verification/review/checks_correctness.py

"""Correctness checks: imports, file completeness, entry points, deps.

Covers checklist items 1, 4, 5, 6 from the CODE_REVIEW_PROMPT.
"""

import ast
import os

from orchestrata_ultimate.core.base.traces import traces
from orchestrata_ultimate.verification.review.helpers import (
    _STDLIB_MODULES,
    _collect_imported_modules,
)
from orchestrata_ultimate.verification.review.types import Issue


def check_imports(
    filepath: str,
    tree: ast.Module,
    project_modules: set[str],
) -> list[Issue]:
    """Check 1: IMPORTS -- ordering and relative imports.

    Args:
        filepath: Absolute path to the file.
        tree: Parsed AST module.
        project_modules: Set of known project module names.

    Returns:
        List of import ordering/relative import issues.
    """
    issues: list[Issue] = []
    rel_name = os.path.basename(filepath)
    for node in ast.walk(tree):
        if isinstance(node, ast.ImportFrom) and node.level > 0:
            issues.append(
                (
                    "IMPORTS",
                    rel_name,
                    f"L{node.lineno}: Relative import "
                    f"(level={node.level}). Use absolute imports.",
                )
            )
    imported = _collect_imported_modules(tree)
    prev_group = 0  # 1=stdlib, 2=third-party, 3=local
    for top, lineno, full in imported:
        if top in _STDLIB_MODULES:
            group = 1
        elif top in project_modules:
            group = 3
        else:
            group = 2
        if group < prev_group:
            issues.append(
                (
                    "IMPORTS",
                    rel_name,
                    f"L{lineno}: Import '{full}' is out of order "
                    f"(stdlib < third-party < local).",
                )
            )
        prev_group = group
    return issues


def check_file_completeness(
    filepath: str,
    tree: ast.Module,
    workspace_files: set[str],
    project_modules: set[str],
) -> list[Issue]:
    """Check 4: FILE_COMPLETENESS -- imported local modules exist.

    Args:
        filepath: Absolute path to the file.
        tree: Parsed AST module.
        workspace_files: Set of relative paths in the workspace.
        project_modules: Set of known project module names.

    Returns:
        List of missing module file issues.
    """
    issues: list[Issue] = []
    rel_name = os.path.basename(filepath)
    imported = _collect_imported_modules(tree)
    for top, _lineno, full_path in imported:
        if top in _STDLIB_MODULES or top not in project_modules:
            continue
        candidates = _build_module_candidates(top, full_path)
        if not any(c in workspace_files for c in candidates):
            issues.append(
                (
                    "FILE_COMPLETE",
                    rel_name,
                    f"L{_lineno}: Import '{full_path}' -- "
                    f"module file not found in workspace.",
                )
            )
    return issues


def _build_module_candidates(
    top: str,
    full_path: str,
) -> list[str]:
    """Build candidate file paths for a module import."""
    candidates = [
        f"{top}.py",
        os.path.join(top, "__init__.py"),
        os.path.join("src", top, "__init__.py"),
    ]
    parts = full_path.split(".")
    if len(parts) > 1:
        candidates.append(os.path.join(*parts[:-1], f"{parts[-1]}.py"))
        candidates.append(os.path.join("src", *parts[:-1], f"{parts[-1]}.py"))
        candidates.append(os.path.join("src", *parts) + ".py")
        candidates.append(os.path.join("src", *parts, "__init__.py"))
    return candidates


def check_entry_point(
    filepath: str,
    lines: list[str],
    is_main_file: bool,
) -> list[Issue]:
    """Check 5: ENTRY_POINT -- main guard present.

    Args:
        filepath: Absolute path to the file.
        lines: File lines.
        is_main_file: Whether this is a main/cli entry file.

    Returns:
        List of missing main guard issues.
    """
    if not is_main_file:
        return []
    rel_name = os.path.basename(filepath)
    has_guard = any("__name__" in line and "__main__" in line for line in lines)
    if not has_guard:
        return [
            (
                "ENTRY_POINT",
                rel_name,
                "Main file missing `if __name__ == '__main__':` guard.",
            )
        ]
    return []


@traces(spec="027", story="validate_dependencies", reqs=["REQ-027-068"])
def check_dependency_declaration(
    filepath: str,
    tree: ast.Module,
    declared_deps: set[str],
    project_modules: set[str],
) -> list[Issue]:
    """Check 6: DEPENDENCY_DECLARATION -- third-party declared.

    Args:
        filepath: Absolute path to the file.
        tree: Parsed AST module.
        declared_deps: Normalized dep names from pyproject.toml.
        project_modules: Set of known project module names.

    Returns:
        List of undeclared dependency issues.
    """
    if not declared_deps:
        return []
    issues: list[Issue] = []
    rel_name = os.path.basename(filepath)
    aliases = {
        "pil": "pillow",
        "cv2": "opencv_python",
        "sklearn": "scikit_learn",
        "yaml": "pyyaml",
        "attr": "attrs",
        "bs4": "beautifulsoup4",
    }
    imported = _collect_imported_modules(tree)
    for top, lineno, _ in imported:
        if top in _STDLIB_MODULES or top in project_modules:
            continue
        normalized = top.lower().replace("-", "_")
        check_name = aliases.get(normalized, normalized)
        if check_name not in declared_deps:
            issues.append(
                (
                    "DEPS",
                    rel_name,
                    f"L{lineno}: '{top}' imported but not in "
                    f"pyproject.toml dependencies.",
                )
            )
    return issues