oct
Loading...
Searching...
No Matches
oct.health.oct_health Namespace Reference

Classes

class  _HealthLineMap

Functions

Dict[str, Any] check_lint_health (Path project_root, LinterContext ctx, bool verbose=False, Optional[set] exclude_dirs=None, Optional[list] wildcard_exclude=None, Optional[dict] active_rules=None, Optional[Dict[Path, Dict[str, Any]]] analysis_cache=None)
Dict[str, Any] check_fixable_health (Path project_root, LinterContext ctx, Optional[set] exclude_dirs=None, Optional[list] wildcard_exclude=None, Optional[dict] active_rules=None, bool verbose=False, Optional[Dict[Path, Dict[str, Any]]] analysis_cache=None)
Dict[str, Any] check_docs_health (Path project_root, *, bool production_mode=False)
Dict[str, Any] check_test_health (Path project_root, int timeout=300, *, Optional[float] coverage_threshold=None, bool production_mode=False, Optional[str] coverage_target=None)
Dict[str, Any] check_compat_health ()
Dict[str, Any] check_venv_health (Path project_root)
Dict[str, Any] check_git_health (Path project_root)
Optional[dict] _load_octrc_for_health (Path project_root)
tuple _build_health_template (str project_name, List[str] excluded_dirs, List[str] disabled_rules, List[str] active_checks, List[str] fixable_names, bool use_color)
str _pct_str (int count, int total)
None _print_terminal_report (Dict[str, Any] report, bool verbose)
None _print_json_report (Dict[str, Any] report)
None run_health (Path project_root, bool json_mode=False, bool verbose=False, int|None test_timeout=None, bool|None run_tests=None, bool log_output=False, bool timing=False, int timing_last=20, bool write_baseline=False, bool force_host=False, Path|None session=None)

Variables

 _AST_DEPENDENT_HEALTH_CHECKS
 _UNWAIVABLE_HEALTH_CHECKS = frozenset({"syntax_error"})
 _COVERAGE_TOTAL_RE = re.compile(r"^TOTAL\s+\d+\s+\d+\s+(\d+(?:\.\d+)?)%", re.MULTILINE)
list _HEALTH_CHECKS
dict _FIX_LABELS
list _DOC_FILES
dict _GIT_LABELS

Detailed Description

Option C project health dashboard implementation.

Purpose
-------
Provide a single-command compliance dashboard that aggregates lint results,
fixable violations, documentation status, test status, and oc_diagnostics
compatibility into one report.

Responsibilities
----------------
- Run linter checks on all Python files and aggregate statistics.
- Run formatter checks in dry-run mode to count fixable violations.
- Validate presence of required documentation files.
- Run project tests and capture pass/fail status.
- Check oc_diagnostics version compatibility.
- Output results as terminal report or JSON.

Diagnostics
-----------
Domain: OCT.HEALTH
Levels:
    L2 - health check lifecycle and command routing
    L3 - individual check categories (lint, docs, tests, compat)
    L4 - per-file analysis and detailed aggregation

Contracts
---------
- Health checks are read-only; no files are modified.
- All checks are independent; failure of one does not prevent others.
- JSON output is always valid JSON with a stable schema.
- Terminal output uses ASCII-safe characters for Windows compatibility.

Dependencies
------------
- oct (package version)
- oct.core.progress (terminal dashboard renderer)
- oct.core.parsing (safe AST parsing helper)
- oct.core.paths (project-relative path helper)
- oct.linter.oct_lint (reused validation checks and profile defaults)
- oct.core.exclusions (directory and wildcard exclusion lists)
- oct.core.project_root (project root detection)
- oct.core.compat (oc_diagnostics version compatibility check)
- oct.core.octrc (.octrc.json loader)
- oct.core.terminal (ANSI colour helpers)
- oct.core.waivers (inline waiver semantics, shared with the linter and
  the quality gate)
- oct.core.option_c_dir (lint cache, debug_config.json and octrc path resolution)
- oct.linter.lint_cache (LintCache, content hashes and current_linter_identity - reuse results for unchanged files, in the store oct lint shares)
- oct.timing.ledger (timed_stage - per-check timing records)
- oct.core.diagnostics (_dbg structured logger)
- oct.core.git (lazy; repository, branch, worktree and last-commit state for the git checks)
- oct.core.log_writer (lazy; write_command_log for the health log file)
- oct.formatter.oct_format (lazy; fixers and FormatterContext to count fixable violations)
- oct.git.conventional (lazy; Conventional Commits check of the last commit)
- oct.git.policy (lazy; branch naming validation)
- oct.timing.report (lazy; timing report, baseline and session views)
- click (lazy; ClickException for timing report errors)
- pytest (not imported; found by name and run as python -m pytest for the test check)
- pytest_cov (not imported; pytest plugin found by name, for the --cov coverage measurement)
- xdist (not imported; pytest plugin behind -n auto for the parallel test run)

Function Documentation

◆ _build_health_template()

tuple oct.health.oct_health._build_health_template ( str project_name,
List[str] excluded_dirs,
List[str] disabled_rules,
List[str] active_checks,
List[str] fixable_names,
bool use_color )
protected
Build the dashboard template lines and line-index map.

Returns ``(lines, line_map)`` where *lines* is a list of strings and
*line_map* is a :class:`_HealthLineMap` with indices into that list.

Definition at line 1137 of file oct_health.py.

Here is the caller graph for this function:

◆ _load_octrc_for_health()

Optional[dict] oct.health.oct_health._load_octrc_for_health ( Path project_root)
protected
Load ``.octrc.json`` for health checks (best-effort).

OI-519: thin wrapper around :func:`oct.core.octrc.load_octrc_safe`;
retains the historical ``None`` return on missing/invalid so existing
callers keep their truthy-check semantics.

Definition at line 1055 of file oct_health.py.

Here is the caller graph for this function:

◆ _pct_str()

str oct.health.oct_health._pct_str ( int count,
int total )
protected
Format count/total with percentage.

Definition at line 1220 of file oct_health.py.

Here is the caller graph for this function:

◆ _print_json_report()

None oct.health.oct_health._print_json_report ( Dict[str, Any] report)
protected
Print JSON health report.

Definition at line 1374 of file oct_health.py.

Here is the caller graph for this function:

◆ _print_terminal_report()

None oct.health.oct_health._print_terminal_report ( Dict[str, Any] report,
bool verbose )
protected
Print human-readable terminal health report.

Definition at line 1228 of file oct_health.py.

Here is the call graph for this function:

◆ check_compat_health()

Dict[str, Any] oct.health.oct_health.check_compat_health ( )
Check oc_diagnostics version compatibility.

Definition at line 814 of file oct_health.py.

Here is the caller graph for this function:

◆ check_docs_health()

Dict[str, Any] oct.health.oct_health.check_docs_health ( Path project_root,
* ,
bool production_mode = False )
Validate presence of required documentation files.

Standard required set: ARCHITECTURE.md, CHANGELOG.md, Tests_README.md,
run_tests.py, debug_config.json. When ``production_mode=True`` (Appendix H
Level 2), SECURITY.md is also required; otherwise it is reported as
optional alongside the required count.

Definition at line 561 of file oct_health.py.

Here is the caller graph for this function:

◆ check_fixable_health()

Dict[str, Any] oct.health.oct_health.check_fixable_health ( Path project_root,
LinterContext ctx,
Optional[set] exclude_dirs = None,
Optional[list] wildcard_exclude = None,
Optional[dict] active_rules = None,
bool verbose = False,
Optional[Dict[Path, Dict[str, Any]]] analysis_cache = None )
Count violations that oct format could fix automatically.

Runs formatter checks in dry-run mode (no modifications).
Only counts fixes for rules that are active.

Plan 269 - "active" is a PER-FILE question wherever the project uses
``linter.path_rules``. *active_rules* is the run's set; each file's
own set is resolved from it with
:func:`~oct.linter.oct_lint.effective_rules` over ``ctx.path_rules``,
which ``run_health`` has already parsed for :func:`check_lint_health`,
so the panel counts a fix only where the fixer's rule applies to that
file. Without it a module a ``tests/`` entry excused from
``dbg_import`` was still offered the fix - the panel disagreeing with
``oct lint`` on exactly the files the operator asked to treat
differently. The counter set is widened the same way: a rule a path
entry switches ON somewhere gets a counter even where the run
disables it, or the files it applies to could never be counted at
all. A project with no path rules produces byte-identical output.

Plan 277 - the file's own inline ``# OCT-LINT: disable[-file]=<rule>``
waivers are the third thing that can excuse a fixer, and the panel
now reads them too, through
:func:`~oct.core.waivers.inline_disabled_rules`: the linter's set,
written once and shared with the gate's format pass. Before, the
panel offered a ``dbg_import`` fix on every one of the nineteen
modules the operator had ruled exempt - a fix the gate would have
refused, and which on ``oct/core/diagnostics.py`` writes the
module-level self-import that file's own waiver reason says raises
``ImportError``.

When *verbose* is True the result includes a ``"files"`` key mapping
to a list of ``{"path": <rel_path>, "fixes": [<fix_name>, ...]}``
entries so the caller can show which files have fixable violations.

Definition at line 390 of file oct_health.py.

Here is the caller graph for this function:

◆ check_git_health()

Dict[str, Any] oct.health.oct_health.check_git_health ( Path project_root)
Run git-related health checks.

Returns a dict of checks, each with ``status`` (OK / WARN / SKIP)
and ``detail``.  If git is not installed or the project is not a
repo, all items return SKIP with an explanatory message.

Definition at line 914 of file oct_health.py.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ check_lint_health()

Dict[str, Any] oct.health.oct_health.check_lint_health ( Path project_root,
LinterContext ctx,
bool verbose = False,
Optional[set] exclude_dirs = None,
Optional[list] wildcard_exclude = None,
Optional[dict] active_rules = None,
Optional[Dict[Path, Dict[str, Any]]] analysis_cache = None )
Run linter checks on all Python files and aggregate pass/fail statistics.

Returns a dict with total_files, fully_compliant count, per-check pass
counts, and compliance percentage.

Definition at line 141 of file oct_health.py.

Here is the caller graph for this function:

◆ check_test_health()

Dict[str, Any] oct.health.oct_health.check_test_health ( Path project_root,
int timeout = 300,
* ,
Optional[float] coverage_threshold = None,
bool production_mode = False,
Optional[str] coverage_target = None )
Run project tests and capture pass/fail status.

Uses pytest subprocess to run tests and captures the exit code
and summary line.

Parameters
----------
project_root:
    Path to the project root containing a ``tests/`` directory.
timeout:
    Maximum seconds to wait for pytest to complete. Default 300 (OI-413).
coverage_threshold:
    FS-C3 / Drift item C3 - when set, run pytest with ``--cov`` and
    compare the resulting TOTAL coverage percentage against this
    threshold. ``None`` (default) skips the coverage measurement
    entirely so existing CI keeps its prior behaviour.
production_mode:
    When ``True`` together with a ``coverage_threshold``, a coverage
    result below the threshold flips ``status`` to ``"fail"``.
    Outside production mode, below-threshold coverage is reported
    but never blocks the dashboard.
coverage_target:
    Module / package name to measure (passed as ``--cov=<target>``).
    Defaults to the project root directory name when ``None``.

Definition at line 617 of file oct_health.py.

Here is the caller graph for this function:

◆ check_venv_health()

Dict[str, Any] oct.health.oct_health.check_venv_health ( Path project_root)
Check virtual environment status for the project.

Performs three layered checks:
1. Whether the current process is running inside *any* venv.
2. Whether a canonical ``.venv`` directory exists at the project root or its
   immediate parent (monorepo pattern: shared venv one level above subproject).
3. Whether the active venv is the project's own ``.venv`` (not a foreign env).

Returns a dict with ``status`` (OK / WARN / FAIL), ``active`` (bool),
``venv_found`` (bool), ``active_path`` (str | None), and ``message`` (str).

Definition at line 839 of file oct_health.py.

Here is the caller graph for this function:

◆ run_health()

None oct.health.oct_health.run_health ( Path project_root,
bool json_mode = False,
bool verbose = False,
int | None test_timeout = None,
bool | None run_tests = None,
bool log_output = False,
bool timing = False,
int timing_last = 20,
bool write_baseline = False,
bool force_host = False,
Path | None session = None )
Run the project health dashboard.

Parameters
----------
project_root : Path
    The detected Option C project root directory.
json_mode : bool
    Output machine-readable JSON instead of terminal report.
verbose : bool
    Show per-file details in addition to summary.
test_timeout : int | None
    Maximum seconds to wait for pytest. Overrides ``health.test_timeout``
    in ``.octrc.json``. Defaults to 300 when neither is set (OI-413).
run_tests : bool | None
    Run the project test suite. The CLI always passes a boolean and skips
    tests by default; ``None`` preserves legacy direct-call behaviour.

Definition at line 1384 of file oct_health.py.

Here is the call graph for this function:

Variable Documentation

◆ _AST_DEPENDENT_HEALTH_CHECKS

oct.health.oct_health._AST_DEPENDENT_HEALTH_CHECKS
protected
Initial value:
1= frozenset(
2 {"dbg_usage", "dbg_import", "func_pattern", "syntax_warnings"}
3)

Definition at line 128 of file oct_health.py.

◆ _COVERAGE_TOTAL_RE

oct.health.oct_health._COVERAGE_TOTAL_RE = re.compile(r"^TOTAL\s+\d+\s+\d+\s+(\d+(?:\.\d+)?)%", re.MULTILINE)
protected

Definition at line 614 of file oct_health.py.

◆ _DOC_FILES

list oct.health.oct_health._DOC_FILES
protected
Initial value:
1= [
2 "ARCHITECTURE.md",
3 "CHANGELOG.md",
4 "Tests_README.md",
5 "run_tests.py",
6 "debug_config.json",
7 "SECURITY.md",
8]

Definition at line 1099 of file oct_health.py.

◆ _FIX_LABELS

dict oct.health.oct_health._FIX_LABELS
protected
Initial value:
1= {
2 "header": "Header blocks",
3 "docstring": "Docstrings",
4 "dbg_import": "_dbg imports",
5 "func_pattern": "func patterns",
6}

Definition at line 1089 of file oct_health.py.

◆ _GIT_LABELS

dict oct.health.oct_health._GIT_LABELS
protected
Initial value:
1= {
2 "is_repo": "Repository",
3 "branch": "Branch",
4 "naming_conformant": "Branch naming",
5 "clean_worktree": "Working tree",
6 "ahead_behind": "Remote sync",
7 "hooks_installed": "Hooks",
8 "last_commit_conventional": "Last commit",
9}

Definition at line 1109 of file oct_health.py.

◆ _HEALTH_CHECKS

list oct.health.oct_health._HEALTH_CHECKS
protected
Initial value:
1= [
2 "syntax_error",
3 "header", "docstring", "diagnostics_profile",
4 "dbg_usage", "dbg_import", "func_pattern", "syntax_warnings",
5]

Definition at line 1082 of file oct_health.py.

◆ _UNWAIVABLE_HEALTH_CHECKS

oct.health.oct_health._UNWAIVABLE_HEALTH_CHECKS = frozenset({"syntax_error"})
protected

Definition at line 138 of file oct_health.py.