# Local QA entrypoints - keep recipes identical to .github/workflows.
# Usage: make qa-fast | make qa | make qa-security | make qa-standalone | make qa-deep
#
# Defaults to .venv when present. Override on the CLI, e.g.:
#   make qa PYTHON=python

PYTHON := $(shell if test -x .venv/bin/python; then echo .venv/bin/python; else echo python3; fi)
RUFF = $(PYTHON) -m ruff
PYTEST = $(PYTHON) -m pytest
UV = $(PYTHON) -m uv
# Prefer .tools/bin from scripts/install_security_cli.sh, else PATH.
# Resolve inside recipes (not $(shell) at parse time) so
# `make install-security-cli qa-gitleaks` works in one invocation.
TOOLS_BIN := $(abspath .tools/bin)
COV_FAIL_UNDER ?= 93
# Worker count of the parallel pass of make qa (pytest-xdist -n).
PYTEST_WORKERS ?= auto
# Whitespace/conflict check against this commit (CI: PR base). Empty = bare
# working-tree check. Override: make qa-fast BASE_SHA=<sha>
BASE_SHA ?= $(shell git merge-base HEAD origin/main 2>/dev/null)
# 1 = gitleaks scans every commit in the history (manual security runs).
GITLEAKS_FULL_HISTORY ?= 0
# The interpreter version make qa-standalone installs and runs.
STANDALONE_PYTHON ?= 3.13
# A directory holding one sdist and one wheel for make package-smoke to check;
# empty, the recipe builds them itself with the hash-pinned build backend.
DIST ?=

.PHONY: qa-fast qa qa-types qa-security qa-deep qa-integrity package-smoke requirements \
	build-constraints \
	qa-gitleaks qa-actionlint qa-semgrep install-security-cli qa-standalone \
	load-baseline load-test

qa-fast:
	git diff --check $(BASE_SHA)
	$(RUFF) check .
	$(RUFF) format --check .

# pyright (standard mode) on fairlib/ and tests/ against scripts/pyright-baseline.txt;
# the baseline holds no tests/ entry, so tests/ stays at 0.
# Needs the [all,test] install: missing optional packages change inferred types.
qa-types:
	$(PYTHON) scripts/pyright_baseline.py

# The suite runs in two passes: the parallel workers (pytest-xdist) first, then
# the tests marked serial, which bound wall-clock waits and need an idle CPU.
# The serial pass appends to the parallel pass's coverage and checks the floor.
qa: qa-fast qa-types
	$(PYTHON) -m pip check
	$(PYTEST) tests/ -q -n $(PYTEST_WORKERS) -m "not serial" \
		--cov=fairlib \
		--cov-report=
	$(PYTEST) tests/ -q -m serial \
		--cov=fairlib \
		--cov-append \
		--cov-report=term-missing \
		--cov-fail-under=$(COV_FAIL_UNDER)

install-security-cli:
	bash scripts/install_security_cli.sh "$(TOOLS_BIN)"

qa-gitleaks:
	@GITLEAKS="$(TOOLS_BIN)/gitleaks"; \
	if ! test -x "$$GITLEAKS"; then GITLEAKS=$$(command -v gitleaks || true); fi; \
	if [ -z "$$GITLEAKS" ]; then \
		echo "gitleaks not found; run: make install-security-cli"; exit 1; \
	fi; \
	if [ "$(GITLEAKS_FULL_HISTORY)" = "1" ]; then \
		"$$GITLEAKS" detect --no-banner --redact --config .gitleaks.toml; \
	elif [ -n "$(BASE_SHA)" ]; then \
		"$$GITLEAKS" detect --no-banner --redact --config .gitleaks.toml \
			--log-opts="$(BASE_SHA)..HEAD"; \
	else \
		ec=0; \
		for src in fairlib tests demos scripts docs .github \
			Makefile pyproject.toml requirements.txt uv.lock README.md \
			.gitleaks.toml .semgrep.yml SECURITY.md; do \
			test -e "$$src" || continue; \
			"$$GITLEAKS" detect --no-banner --redact --no-git --source "$$src" \
				--config .gitleaks.toml || ec=$$?; \
		done; \
		exit $$ec; \
	fi

qa-actionlint:
	@ACTIONLINT="$(TOOLS_BIN)/actionlint"; \
	if ! test -x "$$ACTIONLINT"; then ACTIONLINT=$$(command -v actionlint || true); fi; \
	if [ -z "$$ACTIONLINT" ]; then \
		echo "actionlint not found; run: make install-security-cli"; exit 1; \
	fi; \
	"$$ACTIONLINT" .github/workflows/*.yml

qa-semgrep:
	@SEMGREP=""; \
	if test -x .tools/semgrep-venv/bin/semgrep; then SEMGREP=.tools/semgrep-venv/bin/semgrep; \
	elif command -v semgrep >/dev/null 2>&1; then SEMGREP=$$(command -v semgrep); fi; \
	if [ -z "$$SEMGREP" ]; then \
		echo "semgrep not found; CI: pip install 'setuptools<81' semgrep==1.110.0; local: python -m venv .tools/semgrep-venv && .tools/semgrep-venv/bin/pip install 'setuptools<81' semgrep==1.110.0"; \
		exit 1; \
	fi; \
	"$$SEMGREP" scan --config .semgrep.yml --error --metrics=off

# Compensating dependency gate (GHAS Dependency Review may be UNAVAILABLE).
# Audits the uv.lock-resolved [all,test] set (not the ambient environment).
# Also runs gitleaks + actionlint (install via make install-security-cli).
qa-security: qa-gitleaks qa-actionlint
	$(PYTHON) scripts/pip_audit_baseline.py

requirements:
	$(UV) export --locked --extra all --extra test --no-emit-project \
		--no-hashes --no-annotate -o requirements.txt

# The build backend ([build-system] requires) pinned to its uv.lock version with
# every lock hash, for uv build --build-constraints --require-hashes.
build-constraints:
	$(PYTHON) scripts/release_checks.py build-constraints -o build-constraints.txt

# The drift rows compare the generated files (requirements.txt and
# build-constraints.txt) with uv.lock; set -e makes either row's diff fail it.
qa-integrity:
	$(UV) lock --check
	@set -e; \
	tmpdir=$$(mktemp -d); \
	trap 'rm -rf "$$tmpdir"' EXIT; \
	$(UV) export --locked --extra all --extra test --no-emit-project \
		--no-hashes --no-annotate -o "$$tmpdir/requirements.txt"; \
	diff -u -I '^#' requirements.txt "$$tmpdir/requirements.txt"; \
	$(PYTHON) scripts/release_checks.py build-constraints \
		-o "$$tmpdir/build-constraints.txt"; \
	diff -u build-constraints.txt "$$tmpdir/build-constraints.txt"

# The interpreter is resolved to an absolute path before any cd, so both the
# relative .venv/bin/python and a bare PYTHON=python (CI) keep working.
# The files checked are the ones in DIST (the release workflow passes the
# sdist and the wheel it built and uploads), or, with DIST empty, an sdist and
# a wheel built here with the hash-pinned backend. twine check --strict reads
# both, and each is installed into a clean venv of its own.
# pyright --verifytypes exits 1 below 100% completeness with or without the
# marker, so its exit is ignored and its JSON report is checked instead.
# The isolation escape suite then runs against the installed wheel, from a
# directory outside the repository holding the suite and the test modules it
# imports at their own relative paths, so no import is rewritten;
# tests/test_ci_policy.py holds the list to what the suite imports.
package-smoke:
	@set -e; \
	py=$$($(PYTHON) -c 'import sys; print(sys.executable)'); \
	root="$(CURDIR)"; \
	tmpdir=$$(mktemp -d); \
	trap 'rm -rf "$$tmpdir"' EXIT; \
	if [ -n "$(DIST)" ]; then \
		dist=$$(CDPATH= cd -- "$(DIST)" && pwd); \
	else \
		dist="$$tmpdir/dist"; \
		$(UV) build --build-constraints build-constraints.txt --require-hashes \
			--out-dir "$$dist"; \
	fi; \
	set -- "$$dist"/*.whl; \
	if [ $$# -ne 1 ] || [ ! -f "$$1" ]; then echo "expected one wheel in $$dist"; exit 1; fi; \
	whl="$$1"; \
	set -- "$$dist"/*.tar.gz; \
	if [ $$# -ne 1 ] || [ ! -f "$$1" ]; then echo "expected one sdist in $$dist"; exit 1; fi; \
	sdist="$$1"; \
	"$$py" -m twine check --strict "$$whl" "$$sdist"; \
	"$$py" -m venv "$$tmpdir/venv"; \
	"$$tmpdir/venv/bin/pip" install -q "$$whl"; \
	"$$tmpdir/venv/bin/python" -I -c "import fairlib; print('fairlib import ok', getattr(fairlib, '__version__', 'unknown'))"; \
	"$$py" -c "import sys, zipfile; sys.exit(0 if 'fairlib/py.typed' in zipfile.ZipFile(sys.argv[1]).namelist() else 'the wheel does not contain fairlib/py.typed')" "$$whl"; \
	"$$py" -c "import sys, zipfile; names = set(zipfile.ZipFile(sys.argv[1]).namelist()); missing = sorted({'fairlib/evaluation/routes.yml', 'fairlib/evaluation/fixtures/data/prices.csv', 'fairlib/evaluation/fixtures/logs/app.log'} - names); sys.exit(0 if not missing else f'the wheel does not contain the evaluation data: {missing}')" "$$whl"; \
	"$$py" -m venv "$$tmpdir/venv-sdist"; \
	"$$tmpdir/venv-sdist/bin/pip" install -q "$$sdist"; \
	"$$tmpdir/venv-sdist/bin/python" -I -c "import sys, fairlib; from pathlib import Path; package = Path(fairlib.__file__).resolve().parent; where = package.is_relative_to(Path(sys.prefix).resolve()); missing = [name for name in ('py.typed', 'evaluation/routes.yml', 'evaluation/fixtures/data/prices.csv', 'evaluation/fixtures/logs/app.log') if not (package / name).is_file()]; problem = f'fairlib imported from {package}, not the sdist install' if not where else f'the sdist install does not contain {missing}' if missing else ''; sys.exit(problem) if problem else print('sdist install ok')"; \
	( cd "$$tmpdir" && VIRTUAL_ENV="$$tmpdir/venv" PATH="$$tmpdir/venv/bin:$$PATH" \
		PYRIGHT_PYTHON_IGNORE_WARNINGS=1 "$$py" -m pyright --verifytypes fairlib \
		--ignoreexternal --outputjson > "$$tmpdir/verifytypes.json" ) || true; \
	"$$py" "$$root/scripts/pyright_baseline.py" check-verifytypes \
		"$$tmpdir/verifytypes.json" "$$tmpdir/venv" \
		--floor "$$root/scripts/pyright-floor.txt"; \
	"$$tmpdir/venv/bin/pip" install -q \
		"pytest==$$("$$py" -c 'import pytest; print(pytest.__version__)')"; \
	escape="$$tmpdir/escape"; \
	for copied in tests/__init__.py tests/dispatching.py tests/tool_context.py \
		tests/modules/__init__.py tests/modules/conftest.py \
		tests/modules/security/test_isolation_escape.py; do \
		mkdir -p "$$escape/$$(dirname "$$copied")"; \
		cp "$$root/$$copied" "$$escape/$$copied"; \
	done; \
	( cd "$$escape" && "$$tmpdir/venv/bin/python" -c "import sys, fairlib; from pathlib import Path; where = Path(fairlib.__file__).resolve(); sys.exit(0 if where.is_relative_to(Path(sys.prefix).resolve()) else f'fairlib imported from {where}, not from the wheel in {sys.prefix}')" ); \
	( cd "$$escape" && "$$tmpdir/venv/bin/python" -m pytest \
		"$$escape/tests/modules/security/test_isolation_escape.py" \
		--rootdir "$$escape" -p no:cacheprovider -q -rs )

# The security tests under a uv-managed CPython (python-build-standalone, never
# a system interpreter) with the base, the openai extra (the secure-configuration
# tests drive a real OpenAIAdapter) and the test tools, each pinned from uv.lock
# by the export of exactly the extras installed, whose hashes uv checks on
# install. They run from a
# copy of the working tree (tracked and untracked files, ignored ones left out),
# so an uncommitted change is what runs, and the copy keeps docs/ and demos/,
# which some security tests read. uv keeps the interpreter in its own managed
# directory, outside the repository, so no tool scans its standard library. The
# interpreter is named by its absolute path: the isolation rows compare it
# against resolved capability-bag prefixes.
qa-standalone:
	@set -e; \
	tmpdir=$$(mktemp -d); \
	trap 'rm -rf "$$tmpdir"' EXIT; \
	mkdir "$$tmpdir/src"; \
	git ls-files -co --exclude-standard -z \
		| tar --null --ignore-failed-read -T - -cf - \
		| tar -xf - -C "$$tmpdir/src"; \
	$(UV) python install $(STANDALONE_PYTHON); \
	$(UV) venv -q --python $(STANDALONE_PYTHON) --python-preference only-managed \
		"$$tmpdir/venv"; \
	$(UV) export --locked --extra openai --extra test --no-emit-project \
		--no-annotate -q -o "$$tmpdir/constraints.txt"; \
	$(UV) pip install -q --python "$$tmpdir/venv/bin/python" \
		-c "$$tmpdir/constraints.txt" "$$tmpdir/src[openai,test]"; \
	cd "$$tmpdir/src"; \
	"$$tmpdir/venv/bin/python" -m pytest tests/modules/security \
		tests/core/test_sandbox_worker.py tests/core/test_sandbox_protocol.py \
		-q -p no:cacheprovider

qa-deep: qa qa-security qa-semgrep qa-integrity package-smoke qa-standalone

# The live load test of LoadBalancerAdapter, outside qa: two Ollama servers of
# the rig's own on GPU2/GPU3 behind the reference load manager, all stopped on
# exit (scripts/lb_load_rig.sh). load-baseline records 3 repetitions of every
# cell plus the fault cells in docs/evaluation/load/; load-test runs every cell
# once against that baseline (exit 1 timing, 3 invariant, 2 refused, 4 rig).
load-baseline:
	scripts/lb_load_rig.sh baseline

load-test:
	scripts/lb_load_rig.sh check
