Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,9 @@ jobs:
- name: Lint
if: matrix.cov_args
run: uv run ruff check src tests
- name: Type check the core (mypy strict)
if: matrix.cov_args
run: uv run mypy
- run: uv run protocolith doctor
- run: uv run protocolith validate-all
- name: Run pytest
Expand Down
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@

## Unreleased

### Added

- `mypy --strict` runs in CI over `protocolith.core` (`uv run mypy`); `mypy` joins the `dev` extra.
- README badges for status, package, repository and project facts; a ledger and core issue form; a ledger demo GIF generated from a real run (`scripts/build_demo_gif.py`).

### Fixed

- The command line no longer fails at import or at parser build when the home directory cannot be determined: it falls back to the temporary directory (`protocolith._paths.home_dir`).

### Changed

- Citation metadata: Zenodo DOI of 0.6.0 (`10.5281/zenodo.24291830`), a DOI badge (concept DOI `10.5281/zenodo.24021995`) and an abstract that describes the ledger core.
Expand Down
6 changes: 6 additions & 0 deletions docs/development/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
```bash
uv sync --extra dev
uv run ruff check src tests
uv run mypy # strict type check of protocolith.core
uv run --extra dev pytest -q -n auto
uv run pytest -q tests/core # the core only
uv run pytest -q tests/test_readme_examples.py # README commands
Expand Down Expand Up @@ -53,3 +54,8 @@ enforced in CI; each platform-specific lock module is excluded on the other plat
Tests that depend on the outcome of an evidence run must not change a blocked or insufficient result into a pass.
`BLOCKED_SOURCE`, `INSUFFICIENT_COVERAGE`, `NEGATIVE_RESULT_UNDER_PROTOCOL` and source drift are first-class
outcomes; see [AGENTS.md](../../AGENTS.md).

## Mutation score

Measured on 2026-11-16 with `scripts/mutation_core.sh` (mutmut 3.8.1) over `canonical.py`, `ledger.py` and `rules.py`: 826 of 911 mutants
killed (90.7 percent), 85 survived (mostly error-message text and equivalent mutants). The target for the core is at least 90 percent.
6 changes: 6 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ dev = [
"pytest-xdist>=3.5",
"hypothesis>=6",
"ruff>=0.15",
"mypy>=1.13",
]
docs = [
"mkdocs>=1.6,<2",
Expand Down Expand Up @@ -134,6 +135,11 @@ markers = [
"perf: CPU-time performance measurements (run with -m 'slow or perf')",
]

[tool.mypy]
files = ["src/protocolith/core"]
python_version = "3.11"
strict = true

[tool.ruff]
target-version = "py312"
line-length = 120
Expand Down
10 changes: 6 additions & 4 deletions scripts/mutation_core.sh
Original file line number Diff line number Diff line change
@@ -1,22 +1,24 @@
#!/usr/bin/env bash
# Mutation testing of the PCJ-1 core with mutmut. Time-boxed and resumable: rerun to continue.
# Mutation testing of the PCJ-1 core with mutmut. Time-boxed. Every run starts fresh unless MUTATION_RESUME=1.
# Usage: scripts/mutation_core.sh [max_seconds] (default 1200)
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
WORK="${MUTATION_WORKDIR:-${TMPDIR:-/tmp}/protocolith-mutation}"
LIMIT="${1:-1200}"
if [ "${MUTATION_RESUME:-0}" != "1" ]; then rm -rf "$WORK"; fi
mkdir -p "$WORK"
if [ ! -d "$WORK/src" ]; then
cp -R "$ROOT/src" "$WORK/src"
mkdir -p "$WORK/spec" "$WORK/scripts" && cp -R "$ROOT/spec/vectors" "$WORK/spec/" && cp "$ROOT/scripts/build_core_vectors.py" "$WORK/scripts/"
mkdir -p "$WORK/examples" && cp -R "$ROOT/examples/atlas" "$WORK/examples/"
mkdir -p "$WORK/tests" && cp -R "$ROOT/tests/core" "$WORK/tests/core"
cp "$ROOT/tests/core_hardening/test_core_regressions.py" "$ROOT/tests/core_hardening/hardening_support.py" "$WORK/tests/core/"
cat > "$WORK/pyproject.toml" <<'EOF'
[tool.mutmut]
paths_to_mutate = ["src/protocolith/core/canonical.py", "src/protocolith/core/ledger.py", "src/protocolith/core/rules.py"]
source_paths = ["src/protocolith/core/canonical.py", "src/protocolith/core/ledger.py", "src/protocolith/core/rules.py"]
tests_dir = ["tests/core/"]
pytest_add_cli_args = ["-k", "not subprocess and not process and not mcp_command"]
also_copy = ["src/protocolith/", "spec/", "scripts/"]
pytest_add_cli_args = ["-k", "not subprocess and not process and not mcp_command and not example_translation and not template_script"]
also_copy = ["src/protocolith/", "spec/", "scripts/", "examples/"]

[tool.pytest.ini_options]
addopts = "-q -p no:cacheprovider"
Expand Down
15 changes: 15 additions & 0 deletions src/protocolith/_paths.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# SPDX-License-Identifier: Apache-2.0
"""Small path helpers shared by the command line modules."""

from __future__ import annotations

import tempfile
from pathlib import Path


def home_dir() -> Path:
"""The user's home directory, or the temporary directory when none can be determined (for example in a bare CI step)."""
try:
return Path.home()
except (RuntimeError, KeyError):
return Path(tempfile.gettempdir())
7 changes: 4 additions & 3 deletions src/protocolith/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from pathlib import Path

from protocolith.core.commands import add_core_commands
from protocolith._paths import home_dir
from protocolith.doctor import format_doctor_report, run_doctor
from protocolith.inspect import (
format_hash_lines,
Expand Down Expand Up @@ -47,7 +48,7 @@


REPO_ROOT = Path(__file__).resolve().parents[2]
DEFAULT_DEMO_ROOT = Path.home() / "protocolith_runs" / "protocolith_demo"
DEFAULT_DEMO_ROOT = home_dir() / "protocolith_runs" / "protocolith_demo"
CLONE_URL = "https://github.com/protocolith/protocolith.git"
CHECKOUT_COMMANDS = frozenset({"demo", "validate-all", "rerun", "drift", "verify"})
DEFAULT_CARD_KEYS = (
Expand Down Expand Up @@ -205,7 +206,7 @@ def build_parser() -> argparse.ArgumentParser:
run_root_parser.add_argument(
"--root",
type=Path,
default=Path.home() / "protocolith_runs",
default=home_dir() / "protocolith_runs",
help="Local-only parent directory. Defaults to ~/protocolith_runs.",
)
run_root_parser.set_defaults(func=_cmd_run_root)
Expand Down Expand Up @@ -292,7 +293,7 @@ def build_parser() -> argparse.ArgumentParser:
):
sub = rerun_sub.add_parser(name)
sub.add_argument("--operator", default="local operator")
sub.add_argument("--root", type=Path, default=Path.home() / "protocolith_runs")
sub.add_argument("--root", type=Path, default=home_dir() / "protocolith_runs")
sub.add_argument("--run-dir", type=Path)
sub.add_argument("--baseline", type=Path)
sub.set_defaults(func=handler)
Expand Down
6 changes: 3 additions & 3 deletions src/protocolith/core/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

from . import rules
from .errors import InputError
from .ledger import _HASH_RE, _TS_RE, CARD_FORMAT, ENTRY_TYPES, FORMAT_VERSION, RESULT_STATUSES
from .ledger import _HASH_RE, _TS_RE, CARD_FORMAT, ENTRY_TYPES, FORMAT_VERSION, RESULT_STATUSES, is_hash, is_ts

DIALECT = "https://json-schema.org/draft/2020-12/schema"
NAMES = ("freeze", "record", "deviation", "issue", "entry")
Expand All @@ -33,12 +33,12 @@
rules._uint: _UINT,
rules._uint_list: {"type": "array", "items": _UINT},
rules._sources: {"type": "array", "items": _SOURCE},
rules.is_hash: _HASH,
is_hash: _HASH,
rules._hash_or_null: {"anyOf": [_HASH, {"type": "null"}]},
rules._protocol_id: {"type": "string", "pattern": "^" + rules._ID_RE.pattern + "$"},
rules._version: {"type": "string", "pattern": "^" + rules._VERSION_RE.pattern + "$"},
rules._is_format: {"const": CARD_FORMAT},
rules.is_ts: {"type": "string", "pattern": "^" + _TS_RE.pattern + "$"},
is_ts: {"type": "string", "pattern": "^" + _TS_RE.pattern + "$"},
rules._any: {},
}
# Fields whose predicate is a closed-set check living outside the predicate itself.
Expand Down
4 changes: 3 additions & 1 deletion src/protocolith/doctor.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

from __future__ import annotations

from protocolith._paths import home_dir

import platform
import shutil
import sys
Expand Down Expand Up @@ -113,7 +115,7 @@ def run_doctor(repo_root: Path) -> DoctorReport:
platform_release=platform.release(),
python_version=f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
repo_root=repo_root.resolve(),
runs_root=Path.home() / "protocolith_runs",
runs_root=home_dir() / "protocolith_runs",
today_iso=date.today().isoformat(),
mode="installed-package" if installed else "checkout",
)
Expand Down
5 changes: 3 additions & 2 deletions src/protocolith/workflows.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from pathlib import Path
from typing import Any

from protocolith._paths import home_dir
from protocolith.inspect import format_hash_lines, format_json_subset, hash_files, load_json, pick_fields
from protocolith.nasa_power_fetch import download_nasa_power_d103_points
from protocolith.nasa_power_prereg_runner import evaluate_nasa_power_prereg
Expand Down Expand Up @@ -105,7 +106,7 @@ def rerun_nasa_d103(
run_dir: Path | None = None,
baseline_path: Path | None = None,
) -> int:
runs_root = root or Path.home() / "protocolith_runs"
runs_root = root or home_dir() / "protocolith_runs"
resolved_run_dir = resolve_or_create_run_dir(
protocol_id="NASA_POWER_D103",
source_url="https://power.larc.nasa.gov/docs/services/api/temporal/daily/",
Expand Down Expand Up @@ -150,7 +151,7 @@ def rerun_noaa_d131(
run_dir: Path | None = None,
baseline_path: Path | None = None,
) -> int:
runs_root = root or Path.home() / "protocolith_runs"
runs_root = root or home_dir() / "protocolith_runs"
resolved_run_dir = resolve_or_create_run_dir(
protocol_id="NOAA_COOPS_D131",
source_url="https://api.tidesandcurrents.noaa.gov/api/prod/datagetter",
Expand Down
35 changes: 35 additions & 0 deletions tests/test_paths.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"""Tests for the home directory helper."""

from __future__ import annotations

from pathlib import Path

import pytest

from protocolith._paths import home_dir


def test_home_dir_uses_the_home_directory(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))
assert home_dir() == tmp_path


def test_home_dir_falls_back_to_the_temporary_directory(monkeypatch: pytest.MonkeyPatch) -> None:
def boom(cls: type[Path]) -> Path:
raise RuntimeError("Could not determine home directory.")

monkeypatch.setattr(Path, "home", classmethod(boom))
assert home_dir() == Path(__import__("tempfile").gettempdir())


def test_cli_imports_without_a_home_directory() -> None:
import os
import subprocess
import sys

root = Path(__file__).resolve().parent.parent
env = {"PYTHONPATH": str(root / "src"), **{k: v for k, v in os.environ.items() if k in ("SYSTEMROOT", "TEMP", "TMP", "TMPDIR")}}
proc = subprocess.run(
[sys.executable, "-I", "-c", "import protocolith.cli as c; c.build_parser()"], capture_output=True, text=True, env=env, check=False
)
assert proc.returncode == 0, proc.stderr
Loading
Loading