diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ed75292..e88f099 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,8 +14,38 @@ concurrency: cancel-in-progress: true jobs: + build-kernel: + name: Build verified Dafny kernel + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: "8.0.x" + - name: Install Dafny 4.11 (with bundled Z3) + shell: bash + run: | + DAFNY_DIR="${{ runner.temp }}/dafny" + curl -fsSL -o "${{ runner.temp }}/dafny.zip" "https://github.com/dafny-lang/dafny/releases/download/v4.11.0/dafny-4.11.0-x64-ubuntu-22.04.zip" + unzip -q "${{ runner.temp }}/dafny.zip" -d "$DAFNY_DIR" + rm -f "${{ runner.temp }}/dafny.zip" + chmod +x "$DAFNY_DIR/dafny/dafny" "$DAFNY_DIR/dafny/z3/bin/"* + echo "$DAFNY_DIR/dafny" >> "$GITHUB_PATH" + "$DAFNY_DIR/dafny/dafny" --version + - name: Verify and compile Dafny kernel to Python + run: python3 scripts/tools/build_kernel.py --verify + - name: Upload compiled kernel artifact + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: dafny-kernel-gen + path: src/vkit/kernel/_dafny_gen + if-no-files-found: error + retention-days: 1 + tests: name: Core tests (${{ matrix.os }}) + needs: [build-kernel] runs-on: ${{ matrix.os }} strategy: fail-fast: false @@ -23,23 +53,47 @@ jobs: os: [ubuntu-latest, windows-latest, macos-latest] steps: - uses: actions/checkout@v4 + - name: Download compiled Dafny kernel + uses: actions/download-artifact@v4 + with: + name: dafny-kernel-gen + path: src/vkit/kernel/_dafny_gen - uses: astral-sh/setup-uv@v6 - run: uv sync --python 3.11 --extra test - run: uv run pytest -ra - - run: uvx ruff@0.14.0 check --isolated --select E4,E7,E9,F src tests scripts formal + - run: uvx ruff@0.14.0 check --isolated --select E4,E7,E9,F --exclude src/vkit/kernel/_dafny_gen src tests scripts formal - run: uv build - name: Run the installed wheel CLI run: uv run python -c "from pathlib import Path; import subprocess; wheel = next(Path('dist').glob('*.whl')); subprocess.run(['uv', 'run', '--isolated', '--no-project', '--with', str(wheel.resolve()), 'vkit', '--help'], check=True)" formal: - name: Lean and TLC evidence + name: Dafny, Lean, and TLC evidence + needs: [build-kernel] runs-on: ubuntu-24.04 timeout-minutes: 20 env: VKIT_ALLOW_YES: "1" steps: - uses: actions/checkout@v4 + - name: Download compiled Dafny kernel + uses: actions/download-artifact@v4 + with: + name: dafny-kernel-gen + path: src/vkit/kernel/_dafny_gen - uses: astral-sh/setup-uv@v6 + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: "8.0.x" + - name: Install Dafny 4.11 (with bundled Z3) + shell: bash + run: | + DAFNY_DIR="${{ runner.temp }}/dafny" + curl -fsSL -o "${{ runner.temp }}/dafny.zip" "https://github.com/dafny-lang/dafny/releases/download/v4.11.0/dafny-4.11.0-x64-ubuntu-22.04.zip" + unzip -q "${{ runner.temp }}/dafny.zip" -d "$DAFNY_DIR" + rm -f "${{ runner.temp }}/dafny.zip" + chmod +x "$DAFNY_DIR/dafny/dafny" "$DAFNY_DIR/dafny/z3/bin/"* + echo "$DAFNY_DIR/dafny" >> "$GITHUB_PATH" + "$DAFNY_DIR/dafny/dafny" --version - uses: leanprover/lean-action@v1 with: lake-package-directory: examples/lean-proof @@ -85,31 +139,17 @@ jobs: with open(os.environ["GITHUB_ENV"], "a", encoding="utf-8") as output: output.write(f"VKIT_TLA2TOOLS_JAR={jar}\n") - run: uv sync --python 3.11 --extra test + - run: uv run python formal/checks/run.py --suite all --output "${{ runner.temp }}/vkit-formal-suite" - run: uv run python formal/checks/verify_formal.py --backend all --output "${{ runner.temp }}/vkit-formal-evidence" - - run: uv run pytest tests/formal/test_logical_trust.py tests/formal/test_tlc_evidence.py -q - - run: uv run python formal/checks/check_lifecycle.py - - run: uv run python formal/checks/check_authority.py --output "${{ runner.temp }}/vkit-authority-evidence" - - run: uv run python formal/checks/check_authority.py --suite differences --output "${{ runner.temp }}/vkit-difference-evidence" - - run: uv run python formal/checks/check_authority.py --suite shadow --output "${{ runner.temp }}/vkit-shadow-authority-evidence" - - run: uv run python formal/checks/check_delegated_claim_authority.py --output "${{ runner.temp }}/vkit-delegated-claim-evidence" - - run: uv run python formal/checks/check_difference_decisions.py --output "${{ runner.temp }}/vkit-difference-decisions" - - run: uv run python formal/checks/check_finite_decisions.py --output "${{ runner.temp }}/vkit-finite-decisions/report.json" - - run: uv run pytest tests/formal/test_transition_model.py -q --basetemp "${{ runner.temp }}/vkit-transition-evidence" + - run: uv run pytest tests/formal/test_logical_trust.py tests/formal/test_tlc_evidence.py tests/formal/test_protocol_trace.py -q - name: Retain formal evidence if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 with: name: formal-evidence-${{ github.sha }} path: | + ${{ runner.temp }}/vkit-formal-suite ${{ runner.temp }}/vkit-formal-evidence - .audit/lifecycle-model - ${{ runner.temp }}/vkit-authority-evidence - ${{ runner.temp }}/vkit-difference-evidence - ${{ runner.temp }}/vkit-shadow-authority-evidence - ${{ runner.temp }}/vkit-delegated-claim-evidence - ${{ runner.temp }}/vkit-difference-decisions - ${{ runner.temp }}/vkit-finite-decisions - ${{ runner.temp }}/vkit-transition-evidence include-hidden-files: true if-no-files-found: error retention-days: 14 diff --git a/.github/workflows/ledger-qualification.yml b/.github/workflows/ledger-qualification.yml deleted file mode 100644 index 57df01f..0000000 --- a/.github/workflows/ledger-qualification.yml +++ /dev/null @@ -1,127 +0,0 @@ -name: Ledger qualification - -on: - push: - branches: [main] - paths: - - .github/workflows/ledger-qualification.yml - - examples/verus-qualification/** - - formal/checks/check_ledger_container.py - - formal/checks/qualify_ledger_reuse.py - - examples/ledger-reuse/** - - examples/ledger-refinement/** - - formal/checks/check_ledger_refinement.py - - src/vkit/** - - schemas/** - - formal/checks/check_verus_ledger.py - - formal/checks/check_p2_contracts.py - pull_request: - paths: - - .github/workflows/ledger-qualification.yml - - examples/verus-qualification/** - - formal/checks/check_ledger_container.py - - formal/checks/qualify_ledger_reuse.py - - examples/ledger-reuse/** - - examples/ledger-refinement/** - - formal/checks/check_ledger_refinement.py - - src/vkit/** - - schemas/** - - formal/checks/check_verus_ledger.py - - formal/checks/check_p2_contracts.py - workflow_dispatch: - -permissions: - contents: read - -concurrency: - group: ledger-qualification-${{ github.ref }} - cancel-in-progress: true - -jobs: - verus-comparison: - runs-on: ubuntu-24.04 - timeout-minutes: 20 - steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 - - name: Require the Docker runtime - run: | - if ! docker info >/dev/null 2>&1; then - echo "BLOCKED: Docker daemon is unavailable; the qualification cannot run without isolation." >&2 - exit 1 - fi - - name: Build the qualification image before sealed execution - timeout-minutes: 10 - env: - IMAGE_TAG: vkit-ledger-qualification-${{ github.run_id }}-${{ github.run_attempt }} - run: docker build --build-arg UBUNTU_ARCHIVE=azure.archive.ubuntu.com --file examples/verus-qualification/container/Dockerfile --tag "$IMAGE_TAG" examples/verus-qualification/container - - name: Install the official pinned Verus release - shell: python - run: | - import hashlib - import json - import os - import pathlib - import shutil - import subprocess - import urllib.request - import zipfile - - pin = json.loads(pathlib.Path("src/vkit/formal/packages/resource_ledger/upstream.json").read_text()) - name = f"verus-{pin['version']}-x86-linux.zip" - archive = pathlib.Path(os.environ["RUNNER_TEMP"]) / name - urllib.request.urlretrieve(f"{pin['repository']}/releases/download/{pin['release']}/{name}", archive) - if hashlib.sha256(archive.read_bytes()).hexdigest() != pin["archives"][name]: - raise SystemExit("official archive hash mismatch") - with zipfile.ZipFile(archive) as bundle: - bundle.extractall(pathlib.Path(os.environ["RUNNER_TEMP"]) / "verus") - tool = pathlib.Path(os.environ["RUNNER_TEMP"]) / "verus/verus-x86-linux" - for entry in tool.iterdir(): - if entry.is_file() and entry.suffix == "": - entry.chmod(entry.stat().st_mode | 0o111) - rustup_home = pathlib.Path(os.environ["RUNNER_TEMP"]) / "vkit-rustup" - cargo_home = pathlib.Path(os.environ["RUNNER_TEMP"]) / "vkit-cargo" - rustup_binary = cargo_home / "bin/rustup" - rustup_binary.parent.mkdir(parents=True, exist_ok=True) - shutil.copy2(shutil.which("rustup"), rustup_binary) - rustup_binary.chmod(0o755) - env = os.environ.copy() - env["RUSTUP_HOME"] = str(rustup_home) - env["CARGO_HOME"] = str(cargo_home) - subprocess.run([str(rustup_binary), "toolchain", "install", pin["rust"], "--profile", "minimal"], check=True, env=env) - - name: Install the VKit runtime for product execution - run: | - python3 -m venv "$RUNNER_TEMP/vkit-venv" - "$RUNNER_TEMP/vkit-venv/bin/python" -m pip wheel --disable-pip-version-check --no-deps --wheel-dir "$RUNNER_TEMP/vkit-wheel" . - "$RUNNER_TEMP/vkit-venv/bin/python" -m pip install --disable-pip-version-check "$RUNNER_TEMP"/vkit-wheel/vkit-*.whl - - name: Verify and challenge the ledger - env: - IMAGE_TAG: vkit-ledger-qualification-${{ github.run_id }}-${{ github.run_attempt }} - run: | - "$RUNNER_TEMP/vkit-venv/bin/python" formal/checks/check_ledger_container.py \ - --image "$IMAGE_TAG" \ - --run-id "${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" \ - --verus-root "$RUNNER_TEMP/verus/verus-x86-linux" \ - --archive "$RUNNER_TEMP/verus-0.2026.10.18.7d82994-x86-linux.zip" \ - --rustup-home "$RUNNER_TEMP/vkit-rustup" \ - --cargo-home "$RUNNER_TEMP/vkit-cargo" \ - --output "$RUNNER_TEMP/verus-ledger-evidence" - - name: Remove only this run's containers - if: always() - env: - IMAGE_TAG: vkit-ledger-qualification-${{ github.run_id }}-${{ github.run_attempt }} - run: | - PYTHON=python3 - if [ -x "$RUNNER_TEMP/vkit-venv/bin/python" ]; then PYTHON="$RUNNER_TEMP/vkit-venv/bin/python"; fi - PYTHONPATH="$GITHUB_WORKSPACE/src" "$PYTHON" formal/checks/check_ledger_container.py \ - --image "$IMAGE_TAG" \ - --cleanup-run-id "${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" \ - --output "$RUNNER_TEMP/verus-ledger-evidence" - - name: Retain the comparison evidence - if: always() - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 - with: - name: verus-ledger-${{ github.sha }} - path: ${{ runner.temp }}/verus-ledger-evidence - if-no-files-found: error - include-hidden-files: true - retention-days: 14 diff --git a/.gitignore b/.gitignore index 4f1b32b..90fa194 100644 --- a/.gitignore +++ b/.gitignore @@ -25,3 +25,6 @@ node_modules/ /.audit/ /TASKS.md .worktrees/ +*_TTrace_*.bin +*_TTrace_*.tla +src/vkit/kernel/_dafny_gen/ diff --git a/decisions.tsv b/decisions.tsv new file mode 100644 index 0000000..30c9f2e --- /dev/null +++ b/decisions.tsv @@ -0,0 +1,7 @@ +ts phase decision why evidence result +2026-12-02T22:17:20Z Phase-A Cloned vkit at d076db42632edf1b07925214a39b3f560f45e1a8 with --depth 50 and stripped PAT from origin Establish clean baseline while enforcing VM disk-safety and PAT hygiene .vm_scratch/setup_env.py; df /=16% /tmp=1% /usr/local=66% VERIFIED +2026-12-02T22:38:00Z Phase-A Completed 6-way parallel domain audit of entire vkit repo at d076db4 Cover all 264+ files without bloating main context window 6 subagent reports; pytest 926p/2f/9s in 443.79s; ruff clean; finite_decisions 354346 tuples VERIFIED +2026-12-02T23:08:56Z Phase-C Completed Milestone 2 across 4 disjoint workers (Core/Runtime, Verifiers/Change, CLI/Console/MCP/Plugin, Formal/TLA+) Fix all P0/P1 bugs, extract pure core/acceptance.py & pure interpreter cores, decompose cli.py & console.js, add SSE /api/events, and verify StoreRunnerLifecycle.tla & AgentStopHookProtocol.tla with TLC + Python conformance Core 283p; Verifiers+Change 346p + 2304 interpreter tuples (10/10 mutants); CLI+Console 119p + node --check 6/6; Formal TLC 7 models all PASS + 8/8 coordination mutants caught VERIFIED +2026-12-02T23:24:09Z Phase-C Completed Milestone 3 test compaction across tests/core, tests/rust, and tests/change Apply lean-test-discipline 4-lever hierarchy while preserving all verification/manifest.json and state.DOUBTS nodeids tests/core+rust -36 LOC & 30% faster on touched files (422p); tests/change -354 LOC (308p/4s); test_source_hygiene 4/4 PASS VERIFIED +2026-12-02T23:48:26Z Phase-E Passed all final verification gates across entire vkit repository Confirm zero regressions before committing branch audit/formal-arch-upgrade pytest 956p/9s/0f; ruff clean; all 12 formal checks PASS; 6/6 JS ES modules PASS; comment_lint plugin 0 findings; df /=16% /tmp=1% /usr/local=69% VERIFIED +2026-12-03T02:34:41Z Phase-E Completed Option 2 Waves 1-3 (Patchwork removal, 5-module Dafny->Python kernel, unified VKitProtocol.tla + TraceVKit.tla NDJSON trace validation) Eliminate formal patchwork without Verus, prove pure kernel directly into shipped Python with zero new PyPI deps, and bind real Python limbs to TLA+ via NDJSON traces dafny verify 39/39 (3.64s) + byte-identical regen; formal/checks/run.py --suite all 8/8 PASS; pytest 953p/9s/0f; wheel 462KB pure py3-none-any; ruff & comment_lint clean VERIFIED diff --git a/examples/formal-ci/tla2tools.sha256 b/examples/formal-ci/tla2tools.sha256 index 68726ff..680bad2 100644 --- a/examples/formal-ci/tla2tools.sha256 +++ b/examples/formal-ci/tla2tools.sha256 @@ -1 +1 @@ -fdffef247f563ef6edbfd44958d2a82db79e7564e07cb673262d896353fa6713 +71c10e61d3ffe3b55549a9915142f5e2da106449d83119ee5418524ac719aae7 diff --git a/formal/checks/_tlc_env.py b/formal/checks/_tlc_env.py new file mode 100644 index 0000000..d13ec2a --- /dev/null +++ b/formal/checks/_tlc_env.py @@ -0,0 +1,119 @@ +from __future__ import annotations + +import hashlib +import os +import re +import shutil +import subprocess +import sys +from pathlib import Path +from typing import Mapping + +ROOT = Path(__file__).resolve().parents[2] +EXPECTED_JAR_DIGEST = ROOT / "examples" / "formal-ci" / "tla2tools.sha256" + +if str(ROOT / "src") not in sys.path: + sys.path.insert(0, str(ROOT / "src")) + +from vkit.runtime.nowindow import hidden_window # noqa: E402 + +_ANSI = re.compile(r"\x1b\[[0-9;]*[A-Za-z]") +_VERSION = re.compile(r"Version\s+([0-9]+(?:\.[0-9]+)+)") + +__all__ = [ + "EXPECTED_JAR_DIGEST", + "ROOT", + "ToolchainUnavailable", + "expected_tlc_sha256", + "hidden_window", + "resolve_java", + "resolve_tlc_jar", + "sha256_file", + "tlc_version", +] + + +class ToolchainUnavailable(RuntimeError): + pass + + +def sha256_file(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def expected_tlc_sha256() -> str: + return EXPECTED_JAR_DIGEST.read_text(encoding="ascii").strip() + + +def resolve_java( + java_arg: Path | None = None, + *, + env: Mapping[str, str] | None = None, +) -> Path: + env_map = os.environ if env is None else env + executable = "java.exe" if os.name == "nt" else "java" + path_env = env_map.get("PATH") + if java_arg is not None: + configured = java_arg.expanduser() + located = shutil.which(str(configured), path=path_env) + java = ( + configured.resolve() + if configured.is_file() + else (Path(located).resolve() if located else None) + ) + else: + java_home = env_map.get("JAVA_HOME") + home_candidate = Path(java_home) / "bin" / executable if java_home else None + located = shutil.which("java", path=path_env) or ( + shutil.which("java.exe", path=path_env) if os.name == "nt" else None + ) + java = ( + home_candidate.resolve() + if home_candidate and home_candidate.is_file() + else (Path(located).resolve() if located else None) + ) + if java is None or not java.is_file(): + raise ToolchainUnavailable("Java is unavailable; set JAVA_HOME or pass --java") + return java + + +def resolve_tlc_jar( + jar_arg: Path | None = None, + *, + env: Mapping[str, str] | None = None, + verify_sha256: bool = True, +) -> Path: + env_map = os.environ if env is None else env + raw_env = env_map.get("VKIT_TLA2TOOLS_JAR", "").strip() + configured = jar_arg or (Path(raw_env) if raw_env else None) + if configured is None: + raise ToolchainUnavailable( + "TLC jar is unavailable; set VKIT_TLA2TOOLS_JAR or pass --jar" + ) + jar = configured.expanduser().resolve() + if not jar.is_file(): + raise ToolchainUnavailable(f"TLC jar does not exist: {jar}") + if verify_sha256: + expected = expected_tlc_sha256() + observed = sha256_file(jar) + if observed != expected: + raise RuntimeError( + f"TLC jar SHA-256 mismatch: expected {expected}, observed {observed}" + ) + return jar + + +def tlc_version(java: Path, jar: Path) -> str: + done = subprocess.run( + [str(java), "-cp", str(jar), "tlc2.TLC", "-help"], + capture_output=True, + text=True, + timeout=30, + check=False, + **hidden_window(), + ) + text = _ANSI.sub("", (done.stdout or "") + "\n" + (done.stderr or "")) + match = _VERSION.search(text) + if match is None: + raise RuntimeError(f"could not determine TLC version from {jar}") + return match.group(1) diff --git a/formal/checks/check_authority.py b/formal/checks/check_authority.py deleted file mode 100644 index b8811e0..0000000 --- a/formal/checks/check_authority.py +++ /dev/null @@ -1,344 +0,0 @@ -from __future__ import annotations - -import argparse -import hashlib -import json -import os -from pathlib import Path -import shutil -import subprocess -import sys -import tempfile -from typing import Any - -ROOT = Path(__file__).resolve().parents[2] -AUTHORITY_CONFIGS = { - "good": ("Authority.cfg", None), - "bad_claim": ("Authority.bad-claim.cfg", "ClaimPinned"), - "candidate_target": ("Authority.candidate-target.cfg", "TargetAuthorityPinned"), - "wrong_capture": ("Authority.wrong-capture.cfg", "CandidateCapturePinned"), - "swapped_receipt": ("Authority.swapped-receipt.cfg", "ReceiptBound"), - "stale_reuse": ("Authority.stale-reuse.cfg", "ReuseDecisionBound"), - "false_reject": ("Authority.false-reject.cfg", "ReuseRejectedBound"), - "preflight_pass": ("Authority.preflight-pass.cfg", "PreflightNotProof"), -} -AUTHORITY_PROPERTIES = [ - "TypeOK", - "ClaimPinned", - "TargetAuthorityPinned", - "SnapshotPinned", - "CandidateCapturePinned", - "ReceiptBound", - "PublishedPassBound", - "PreflightNotProof", - "ReuseDecisionBound", - "ReuseRejectedBound", -] -DIFFERENCE_CONFIGS = { - "reach_empty_done": ("Differences.reach-empty-done.cfg", "NoCompletedState"), - "reach_conformance": ("Differences.reach-conformance.cfg", "NoConformance"), - "mutant_shrink_coverage": ("Differences.mutant-shrink-coverage.cfg", "SelectedCoverage"), - "mutant_ignore_shrink": ("Differences.mutant-ignore-shrink.cfg", "UnknownBlocksConformance"), - "mutant_hide_violation": ("Differences.mutant-hide-violation.cfg", "ViolationVisibility"), - "mutant_union_guards": ("Differences.mutant-union-guards.cfg", "GuardIntersection"), - "mutant_skip_standing": ("Differences.mutant-skip-standing.cfg", "StandingIntent"), - "mutant_unguarded_change": ("Differences.mutant-unguarded-change.cfg", "UnguardedRelation"), - "mutant_reject_repair": ("Differences.mutant-reject-repair.cfg", "RepairAccepted"), - "mutant_empty": ("Differences.mutant-empty.cfg", "EmptyDomainUnknown"), -} -DIFFERENCE_PROPERTIES = [ - "TypeOK", - "SelectedCoverage", - "UnknownBlocksConformance", - "StandingIntent", - "GuardIntersection", - "UnguardedRelation", - "ViolationVisibility", - "ConformanceSoundness", - "DuplicateSelectedUnknown", - "RepairAccepted", - "RepairClassification", - "EmptyDomainUnknown", - "NoCompletedState", - "NoConformance", - "AuthorityBoundary", -] -SHADOW_AUTHORITY_CONFIGS = { - "shadow": ("ShadowAuthority.cfg", None), - "mutant_verus_check_none": ("ShadowAuthority.verus.cfg", "ShadowReceiptPolicy"), - "mutant_shadow_claim_established": ("ShadowAuthority.established.cfg", "ShadowReceiptPolicy"), - "mutant_gate_requires_shadow": ("ShadowAuthority.gate-requires-shadow.cfg", "GateMatchesRequiredSubjects"), - "mutant_gate_accepts_shadow": ("ShadowAuthority.gate-accepts-shadow.cfg", "GateMatchesRequiredSubjects"), -} -SHADOW_AUTHORITY_PROPERTIES = [ - "TypeOK", - "ShadowReceiptPolicy", - "ReceiptNamespaceSeparated", - "GateMatchesRequiredSubjects", -] -SUITES = { - "authority": { - "model": Path("formal/models/certification/Authority.tla"), - "module": "Authority", - "configs": AUTHORITY_CONFIGS, - "properties": AUTHORITY_PROPERTIES, - "check_id": "authority-model", - "description": "Exhaustively checks policy, source, target, reuse, and receipt bindings.", - "scope": "bounded package authority, source capture, receipt, reuse, and preflight policy model", - "attempts": "one package request/job; no scheduler or retry state", - "bounds": "one component, two policy/package/checker/source revisions, one protected and one candidate target", - "assumptions": [ - "digest atoms are collision-free labels; Git objects and hash algorithms are abstracted", - "the host selects protected target authority; the package request has no target field", - "a valid receipt remains historically valid after current policy drift, while a reuse attempt checks current policy, checker, source, and claim pins", - "finite request preflight returns without job, receipt, PASS, or READY", - ], - "limit": "Published PASS records are historical outcomes, not a statement about current gate readiness. TLC checks only this finite abstraction; it is not source proof or an implementation-refinement proof.", - "report": "authority-report.json", - "default_output": "authority-model", - }, - "differences": { - "model": Path("formal/models/certification/Differences.tla"), - "module": "Differences", - "configs": DIFFERENCE_CONFIGS, - "properties": DIFFERENCE_PROPERTIES, - "check_id": "difference-model", - "description": "Checks finite paired-observation coverage, policy relations, and authority limits.", - "scope": "bounded finite difference assessment over selected and shrink observations", - "attempts": "one bounded evidence collection and one assessment; no source-proof or approval state", - "bounds": "two input atoms, 13 representative records, at most two raw records with multiplicity, four modeled outputs plus one out-of-model probe, two repeats per side", - "model_bounds": { - "Scenario": 1, - "Mutant": 1, - "SourceProof": 1, - "ApprovalAuthority": 1, - }, - "assumptions": [ - "output and input atoms are finite labels; no interpreter or implementation state is modeled", - "the model explores every subset and ordering up to two raw records from its compact representative pool", - "the guard overlap configuration has a nonempty intersection; parser rejection is covered by the runtime bridge", - ], - "limit": "TLC checks only this finite abstraction. Runtime bridge cases exercise selected evaluator behaviors but do not prove implementation refinement, domain exhaustiveness, source purity, or approval authority.", - "report": "difference-report.json", - "default_output": "difference-model", - }, - "shadow": { - "model": Path("formal/models/certification/ShadowAuthority.tla"), - "module": "ShadowAuthority", - "configs": SHADOW_AUTHORITY_CONFIGS, - "properties": SHADOW_AUTHORITY_PROPERTIES, - "check_id": "shadow-authority-model", - "description": "Checks typed shadow receipt authority and separation from required gate subjects.", - "scope": "bounded receipt namespace and required-subject gate projection for shadow certification", - "attempts": "one receipt slot per typed subject; no scheduler, retries, source semantics, or implementation state", - "bounds": "three subject kinds, one identical textual id per kind, two required slots, one shadow slot, three terminal outcomes, four fault mutations", - "model_bounds": {"Fault": 1}, - "assumptions": [ - "subject identity is the pair (kind, id); the same text id under different kinds denotes distinct slots", - "registered-check is an empirical bounded scenario receipt and formal-goal is a trusted-engine Verus receipt, abstracted to typed identity, PASS outcome, assurance, and established claim", - "the gate consumes only the required registered-check and formal-goal slots; shadow outcomes are observations and are not requirements", - "source bytes, Git objects, scheduler behavior, serialization, and the Python implementation are not modeled", - ], - "limit": "TLC checks only this finite projection and fault mutations. It does not prove Python refinement, source correctness, arbitrary change behavior, or the complete gate implementation.", - "report": "shadow-authority-report.json", - "default_output": "shadow-authority-model", - }, -} - - -def _environment(output: Path) -> dict[str, str]: - env = dict(os.environ) - env["PYTHONPATH"] = os.pathsep.join( - [str(ROOT / "src"), *filter(None, env.get("PYTHONPATH", "").split(os.pathsep))] - ) - env["VKIT_CONFIG"] = str(output / "settings.json") - java_home = Path(env.get("JAVA_HOME", "")) - java_bin = java_home / "bin" - if (java_bin / ("java.exe" if os.name == "nt" else "java")).is_file(): - env["PATH"] = str(java_bin) + os.pathsep + env.get("PATH", "") - if shutil.which("java", path=env.get("PATH")) is None: - raise RuntimeError("the VKit TLC runner needs Java on PATH or under JAVA_HOME") - return env - - -def _run(argv: list[str], cwd: Path, env: dict[str, str], allowed: set[int]) -> dict[str, Any]: - options: dict[str, Any] = {} - if os.name == "nt": - from vkit.runtime.nowindow import hidden_window - - options = hidden_window() - done = subprocess.run( - argv, cwd=cwd, env=env, capture_output=True, text=True, - timeout=240, check=False, **options, - ) - if done.returncode not in allowed: - raise RuntimeError( - f"command returned {done.returncode}, expected {sorted(allowed)}: {argv!r}\n" - f"stdout:\n{done.stdout}\nstderr:\n{done.stderr}" - ) - try: - body = json.loads(done.stdout) - except json.JSONDecodeError as exc: - raise RuntimeError(f"VKit returned non-JSON output: {done.stdout}\n{done.stderr}") from exc - if not isinstance(body, dict): - raise RuntimeError("VKit returned a non-object JSON response") - return {"returncode": done.returncode, "stdout": done.stdout, - "stderr": done.stderr, "body": body} - - -def _project(case_dir: Path, config_name: str, env: dict[str, str], - suite: dict[str, Any]) -> Path: - project = case_dir / "project" - cert_dir = project / "formal" / "models" / "certification" - cert_dir.mkdir(parents=True) - (project / "verification").mkdir(parents=True) - model = suite["model"] - shutil.copyfile(ROOT / model, project / model) - shutil.copyfile(ROOT / "formal/models/certification" / config_name, - cert_dir / config_name) - raw = json.loads((ROOT / "verification/manifest.json").read_text(encoding="utf-8")) - check = next(item for item in raw["checks"] if item["id"] == "lifecycle-model") - model_path = model.as_posix() - config_path = (model.parent / config_name).as_posix() - check.update( - id=suite["check_id"], - description=suite["description"], - inputs=[model_path, config_path], - subject={"paths": [model_path, config_path], "digest": None}, - claim_id=suite["check_id"], - model={"module": suite["module"], "path": model_path}, - config=config_path, - properties=suite["properties"], - bounds=suite.get("model_bounds", { - "Fault": 1, "ComponentId": 1, "TargetPolicy": 1, - "CandidatePolicy": 1, "TargetPackage": 1, "CandidatePackage": 1, - "CheckerA": 1, "CheckerB": 1, "SourceA": 1, "SourceB": 1, - "ProtectedTarget": 1, "CandidateTarget": 1, - }), - ) - raw["checks"] = [check] - (project / "verification" / "manifest.json").write_text( - json.dumps(raw, indent=2) + "\n", encoding="utf-8" - ) - git = ["git", "-c", f"user.name=VKit {suite['module']} Model", - "-c", f"user.email={suite['check_id']}@vkit.invalid"] - subprocess.run(["git", "init", "-q"], cwd=project, env=env, check=True) - subprocess.run(git + ["add", "."], cwd=project, env=env, check=True) - subprocess.run(git + ["commit", "-qm", "bounded model fixture"], - cwd=project, env=env, check=True) - return project - - -def _run_case(output: Path, name: str, config_name: str, - expected_invariant: str | None, env: dict[str, str], - suite: dict[str, Any]) -> dict[str, Any]: - case_dir = Path(tempfile.mkdtemp(prefix=f"{name}-", dir=output)) - project = _project(case_dir, config_name, env, suite) - cli = [sys.executable, "-m", "vkit.cli"] - _run(cli + ["accept", "--yes", "--project", str(project), "--json"], - project, env, {0}) - result = _run(cli + ["check", "run", "--check", suite["check_id"], - "--project", str(project), "--json"], - project, env, {0} if expected_invariant is None else {1}) - records = result["body"].get("runs") or [] - record = records[0] if records else result["body"] - actual = (record.get("outcome") or {}).get("result") - expected_result = "PASS" if expected_invariant is None else "FAIL" - if actual != expected_result: - raise RuntimeError(f"{name}: got {actual!r}, expected {expected_result!r}: {record!r}") - obligations = record.get("obligations") or {} - satisfied = obligations.get("satisfied", []) - satisfied_names = [ - item.get("obligation", {}).get("obligation") for item in satisfied - ] - counterexamples = obligations.get("counterexamples", []) - properties = suite["properties"] - if expected_invariant is None and set(satisfied_names) != set(properties): - missing = sorted(set(properties) - set(satisfied_names)) - extra = sorted(set(satisfied_names) - set(properties)) - raise RuntimeError( - f"{name}: satisfied invariant set differs from configured properties; " - f"missing={missing}, extra={extra}" - ) - if expected_invariant is not None and not any( - item.get("obligation", {}).get("obligation") == expected_invariant - for item in counterexamples - ): - raise RuntimeError(f"{name}: TLC did not report {expected_invariant}: {counterexamples!r}") - (case_dir / "vkit.stdout.json").write_text(result["stdout"], encoding="utf-8") - (case_dir / "vkit.stderr.txt").write_text(result["stderr"], encoding="utf-8") - return { - "case": name, - "result": actual, - "expected_counterexample": expected_invariant, - "satisfied_invariants": [ - item.get("obligation", {}).get("obligation") for item in satisfied - ], - "exploration": next((item.get("states") for item in satisfied if item.get("states")), None), - "counterexample_obligations": [ - item.get("obligation", {}).get("obligation") for item in counterexamples - ], - "project": str(project), - } - - -def main() -> int: - parser = argparse.ArgumentParser(description="Qualify a bounded VKit model through TLC.") - parser.add_argument("--suite", choices=SUITES, default="authority") - parser.add_argument("--output", type=Path) - args = parser.parse_args() - suite = SUITES[args.suite] - output = (args.output or ROOT / "tmp" / suite["default_output"]).resolve() - output.mkdir(parents=True, exist_ok=True) - env = _environment(output) - sys.path.insert(0, str(ROOT / "src")) - import vkit - - if Path(vkit.__file__).resolve().parent != (ROOT / "src/vkit").resolve(): - raise RuntimeError(f"model qualification imported the wrong VKit: {vkit.__file__}") - if not env.get("VKIT_TLA2TOOLS_JAR"): - raise RuntimeError("VKIT_TLA2TOOLS_JAR must name the jar pinned by examples/formal-ci/tla2tools.sha256") - observed = hashlib.sha256(Path(env["VKIT_TLA2TOOLS_JAR"]).read_bytes()).hexdigest() - expected = (ROOT / "examples/formal-ci/tla2tools.sha256").read_text(encoding="ascii").strip() - manifest = json.loads((ROOT / "verification/manifest.json").read_text(encoding="utf-8")) - lifecycle = next(item for item in manifest["checks"] if item["id"] == "lifecycle-model") - toolchain = lifecycle["toolchain"] - if toolchain["jar_sha256"] != expected: - raise RuntimeError("lifecycle check and repository TLC checksum pins disagree") - if observed != expected: - raise RuntimeError(f"TLC jar digest mismatch: expected {expected}, observed {observed}") - - results = [] - for name, (config_name, invariant) in suite["configs"].items(): - results.append(_run_case(output, name, config_name, invariant, env, suite)) - report = { - "schema_version": 1, - "suite": args.suite, - "scope": suite["scope"], - "model": str(suite["model"]), - "toolchain": {"version": toolchain["version"], "jar_sha256": observed}, - "attempts": suite["attempts"], - "bounds": suite["bounds"], - "assumptions": suite["assumptions"], - "results": results, - "limit": suite["limit"], - } - report_path = output / suite["report"] - report_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") - negative_controls = sum( - expected is not None for _, expected in suite["configs"].values() - ) - print(json.dumps({"suite": args.suite, "result": "PASS", "cases": len(results), - "negative_controls": negative_controls, - "mutants": sum(name.startswith("mutant_") for name in suite["configs"]), - "reachability_witnesses": sum(name.startswith("reach_") for name in suite["configs"]), - "report": str(report_path)}, indent=2)) - return 0 - - -if __name__ == "__main__": - try: - raise SystemExit(main()) - except (OSError, RuntimeError, subprocess.SubprocessError, ValueError, KeyError) as exc: - print(f"model qualification failed: {exc}", file=sys.stderr) - raise SystemExit(1) diff --git a/formal/checks/check_change_corpus.py b/formal/checks/check_change_corpus.py deleted file mode 100644 index 32f1535..0000000 --- a/formal/checks/check_change_corpus.py +++ /dev/null @@ -1,243 +0,0 @@ -from __future__ import annotations - -import argparse -import hashlib -import json -import os -import re -import shutil -import subprocess -import sys -from collections import Counter -from pathlib import Path - - -ROOT = Path(__file__).resolve().parents[2] -DEFAULT_MANIFEST = ROOT / "examples/change-certification/manifest.json" -FIXTURE_ROOT = ROOT / "examples/change-certification/fixtures" -ALLOWED_JUDGMENTS = { - "equivalent_on_recorded_rows", - "approved_guarded_bugfix", - "approved_guarded_feature", - "reject_unapproved_behavior_change", - "needs_contract", - "reject_observation_tampering", - "reject_authority_tampering", -} - - -class CorpusError(Exception): - pass - - -def load_manifest(path: Path) -> tuple[dict[str, object], str]: - try: - raw = path.read_bytes() - manifest = json.loads(raw.decode("utf-8")) - except (OSError, UnicodeDecodeError, json.JSONDecodeError) as error: - raise CorpusError(f"cannot read manifest: {error}") from error - if not isinstance(manifest, dict) or manifest.get("schema_version") != 1: - raise CorpusError("manifest must be an object with schema_version 1") - cases = manifest.get("cases") - if not isinstance(cases, list) or len(cases) != 12: - raise CorpusError("manifest must contain exactly twelve cases") - ids = [case.get("id") for case in cases if isinstance(case, dict)] - if len(ids) != len(cases) or not all(isinstance(case_id, str) for case_id in ids) or len(set(ids)) != 12: - raise CorpusError("case ids must be present and unique") - - for case in cases: - if not isinstance(case.get("id"), str) or not isinstance(case.get("intent"), str): - raise CorpusError("every case needs an id and intent") - if not isinstance(case.get("requirement"), str) or not isinstance(case.get("supported_domain"), str): - raise CorpusError(f"{case['id']} needs a requirement and supported_domain") - if not isinstance(case.get("guards"), list) or not all(isinstance(item, str) for item in case["guards"]): - raise CorpusError(f"{case['id']} guards must be a list of strings") - expected = case.get("expected") - if not isinstance(expected, dict) or expected.get("judgment") not in ALLOWED_JUDGMENTS: - raise CorpusError(f"{case['id']} has an unsupported expected judgment") - witness = expected.get("witness") - if witness is not None and not isinstance(witness, str): - raise CorpusError(f"{case['id']} expected witness must be a string or null") - observations = case.get("observations") - if not isinstance(observations, list): - raise CorpusError(f"{case['id']} observations must be a list") - if case.get("kind") == "runtime": - if not isinstance(case.get("source"), str) or not isinstance(case.get("test"), str): - raise CorpusError(f"{case['id']} runtime case needs source and test") - for row in observations: - if not isinstance(row, dict) or any(not isinstance(row.get(key), str) - for key in ("input", "before", "after")): - raise CorpusError(f"{case['id']} has an invalid expected observation") - elif case.get("kind") == "policy_only": - if observations or "source" in case or "test" in case: - raise CorpusError(f"{case['id']} policy-only case cannot claim runtime observations") - if not isinstance(case.get("policy_evidence"), dict) or witness is None: - raise CorpusError(f"{case['id']} policy-only case needs policy_evidence and a witness") - else: - raise CorpusError(f"{case['id']} has an unknown case kind") - - runtime_count = sum(case["kind"] == "runtime" for case in cases) - policy_count = sum(case["kind"] == "policy_only" for case in cases) - if (runtime_count, policy_count) != (8, 4): - raise CorpusError("manifest must contain eight runtime and four policy-only cases") - if manifest.get("status") != "development_only": - raise CorpusError("manifest status must remain development_only") - held_out = manifest.get("held_out") - if (not isinstance(held_out, dict) or held_out.get("status") != "reserved_empty" - or not isinstance(held_out.get("evaluation_status"), str)): - raise CorpusError("held_out must describe a reserved empty location with no evaluation results") - if not isinstance(manifest.get("scope_limit"), str): - raise CorpusError("manifest needs a finite scope_limit") - return manifest, hashlib.sha256(raw).hexdigest() - - -def expected_rows(cases: list[dict[str, object]]) -> Counter[tuple[str, str, str, str]]: - return Counter( - (case["id"], row["input"], row["before"], row["after"]) - for case in cases if case["kind"] == "runtime" - for row in case["observations"] - ) - - -def observed_rows(output: str) -> Counter[tuple[str, str, str, str]]: - rows: Counter[tuple[str, str, str, str]] = Counter() - for line in output.splitlines(): - if not line.startswith("OBS|"): - continue - parts = line.split("|") - if len(parts) != 5 or not parts[3].startswith("before=") or not parts[4].startswith("after="): - raise CorpusError(f"malformed observation line: {line}") - rows[(parts[1], parts[2], parts[3][7:], parts[4][6:])] += 1 - return rows - - -def write_report(output_dir: Path, report: dict[str, object]) -> None: - (output_dir / "report.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") - - -def run_native(rustc: str, source: Path, binary: Path, timeout: float) -> tuple[str, list[list[str]]]: - commands: list[list[str]] = [] - compile_argv = [rustc, "--test", str(source), "-o", str(binary)] - commands.append(compile_argv) - compile_result = subprocess.run(compile_argv, cwd=ROOT, capture_output=True, text=True, - timeout=timeout, check=False, - creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0) - if compile_result.returncode: - raise CorpusError(f"rustc failed for {source.name}: {compile_result.stderr.strip() or compile_result.stdout.strip()}") - run_argv = [str(binary), "--nocapture", "--test-threads=1"] - commands.append(run_argv) - run_result = subprocess.run(run_argv, cwd=ROOT, capture_output=True, text=True, - timeout=timeout, check=False, - creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0) - combined = run_result.stdout + "\n" + run_result.stderr - if run_result.returncode: - raise CorpusError(f"native tests failed for {source.name}: {combined.strip()}") - if not re.search(r"(?m)^test result: ok\. \d+ passed; 0 failed;", combined): - raise CorpusError(f"native test summary missing or failed for {source.name}: {combined.strip()}") - return combined, commands - - -def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser(description="Run the finite change-certification Rust fixture corpus.") - parser.add_argument("--output-dir", required=True, type=Path) - parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST) - parser.add_argument("--timeout-seconds", type=float, default=30) - args = parser.parse_args(argv) - output_dir = args.output_dir.resolve() - output_dir.mkdir(parents=True, exist_ok=True) - report: dict[str, object] = {"status": "FAIL", "manifest": str(args.manifest.resolve())} - - try: - manifest_path = args.manifest.resolve() - manifest, manifest_digest = load_manifest(manifest_path) - cases = manifest["cases"] - runtime_cases = [case for case in cases if case["kind"] == "runtime"] - policy_cases = [case for case in cases if case["kind"] == "policy_only"] - report.update({"case_count": len(cases), "runtime_case_count": len(runtime_cases), - "policy_only_case_count": len(policy_cases), - "finite_scope": manifest["scope_limit"]}) - rustc = shutil.which("rustc") - if rustc is None: - report.update({"status": "BLOCKED", "reason": "rustc is unavailable"}) - write_report(output_dir, report) - print("BLOCKED: rustc is unavailable; native fixture evidence was not run.") - return 2 - - version_argv = [rustc, "--version"] - version_result = subprocess.run(version_argv, cwd=ROOT, capture_output=True, text=True, - timeout=args.timeout_seconds, check=False, - creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0) - if version_result.returncode or not version_result.stdout.strip(): - raise CorpusError(f"rustc --version failed: {version_result.stderr.strip() or version_result.stdout.strip()}") - - sources = sorted({case["source"] for case in runtime_cases}) - all_actual: Counter[tuple[str, str, str, str]] = Counter() - all_expected = expected_rows(runtime_cases) - commands: list[list[str]] = [version_argv] - source_hashes: dict[str, str] = {} - native_logs: dict[str, str] = {} - report["provenance"] = {"manifest_sha256": manifest_digest, - "fixture_source_sha256": source_hashes, - "rustc_version": version_result.stdout.strip(), - "native_output_logs": native_logs} - native_tests = 0 - suffix = ".exe" if os.name == "nt" else "" - for source_name in sources: - if Path(source_name).name != source_name: - raise CorpusError(f"fixture source must be a file name: {source_name}") - source = (FIXTURE_ROOT / source_name).resolve() - if not source.is_relative_to(FIXTURE_ROOT.resolve()) or not source.is_file(): - raise CorpusError(f"fixture source is missing or outside the fixture directory: {source_name}") - source_hashes[source_name] = hashlib.sha256(source.read_bytes()).hexdigest() - suite_cases = [case for case in runtime_cases if case["source"] == source_name] - binary = output_dir / f"change-corpus-{source.stem}{suffix}" - output, run_commands = run_native(rustc, source, binary, args.timeout_seconds) - log_path = output_dir / f"{source.stem}.native.log" - log_path.write_text(output, encoding="utf-8") - native_logs[source_name] = log_path.name - commands.extend(run_commands) - test_count = int(re.search(r"(?m)^test result: ok\. (\d+) passed; 0 failed;", output).group(1)) - if test_count != len(suite_cases): - raise CorpusError(f"native test count differs for {source_name}: expected {len(suite_cases)}, got {test_count}") - native_tests += len(suite_cases) - actual = observed_rows(output) - expected = expected_rows(suite_cases) - if actual != expected: - missing = list((expected - actual).elements()) - unexpected = list((actual - expected).elements()) - raise CorpusError(f"observations differ for {source_name}; missing={missing}; unexpected={unexpected}") - all_actual.update(actual) - - if all_actual != all_expected: - raise CorpusError("combined observations differ from the frozen manifest") - policy_summary = [ - {"id": case["id"], "expected_judgment": case["expected"]["judgment"], - "witness": case["expected"]["witness"], "kind": "policy_only"} - for case in policy_cases - ] - runtime_summary = [ - {"id": case["id"], "expected_judgment": case["expected"]["judgment"], - "observations_checked": len(case["observations"]), "kind": "runtime"} - for case in runtime_cases - ] - report.update({"status": "PASS", "runtime_observation_count": sum(all_actual.values()), - "native_test_count": native_tests, "commands": commands, - "runtime_cases": runtime_summary, "policy_only_cases": policy_summary}) - write_report(output_dir, report) - for case in policy_cases: - print(f"POLICY-ONLY {case['id']} {case['expected']['judgment']}: {case['expected']['witness']}") - print(f"PASS cases=12 runtime=8 policy_only=4 observations={sum(all_actual.values())} " - f"native_tests={native_tests} scope=finite_literal_rows") - return 0 - except (CorpusError, OSError, subprocess.SubprocessError, ValueError) as error: - report.update({"status": "FAIL", "error": str(error)}) - try: - write_report(output_dir, report) - except OSError: - pass - print(f"FAIL: {error}", file=sys.stderr) - return 1 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/formal/checks/check_change_engines.py b/formal/checks/check_change_engines.py deleted file mode 100644 index 63b0a5e..0000000 --- a/formal/checks/check_change_engines.py +++ /dev/null @@ -1,260 +0,0 @@ -from __future__ import annotations - -import argparse -import hashlib -import json -import os -from pathlib import Path -import re -import shutil -import sys - - -ROOT = Path(__file__).resolve().parents[2] -sys.path.insert(0, str(ROOT / "src")) - - -CORPUS = ROOT / "examples/change-certification" -SNAPSHOTS = { - "manifest.json": CORPUS / "manifest.json", - "scalar.rs": CORPUS / "fixtures/scalar.rs", - "experiment-kani.rs": CORPUS / "proofs/experiment-kani.rs", - "experiment-verus-positive.rs": CORPUS / "proofs/experiment-verus-positive.rs", - "experiment-verus-negative.rs": CORPUS / "proofs/experiment-verus-negative.rs", -} -KANI_EXPECTATIONS = { - "refactor": (0, "proof_success", ("VERIFICATION:- SUCCESSFUL", "Complete - 1 successfully verified harnesses, 0 failures, 1 total.")), - "regression": (1, "seeded_semantic_failure", ("VERIFICATION:- FAILED", "assertion failed: scalar::cap_before(x) == scalar::cap_after(x)")), - "exhausted": (1, "unwind_exhaustion", ("VERIFICATION:- FAILED", "exhausted.unwind.0", "unwinding assertion loop 0")), - "undefined_behavior": (1, "ub_safety_failure", ( - "VERIFICATION:- FAILED", "Check for `safety_check`", "Offset result and original pointer must point to the same allocation", - "Concrete playback unit test for `undefined_behavior`")), - "observation_mismatch": (1, "observation_mismatch", ("VERIFICATION:- FAILED", "assertion failed: before == after")), -} -VERUS_EXPECTATIONS = { - "positive": (0, "proof_success", ("verification results:: 4 verified, 0 errors",)), - "negative": (1, "seeded_semantic_failure", ("assertion failed", "verification results:: 3 verified, 1 errors")), -} - - -class ProbeStop(Exception): - def __init__(self, status: str, message: str): - self.status = status - super().__init__(message) - - -def sha256(path: Path) -> str: - digest = hashlib.sha256() - with path.open("rb") as stream: - for chunk in iter(lambda: stream.read(1024 * 1024), b""): - digest.update(chunk) - return digest.hexdigest() - - -def classify_kani(name: str, returncode: int | None, output: str) -> str: - if returncode is None: - return "timeout" - expected_code, classification, markers = KANI_EXPECTATIONS[name] - if returncode == expected_code and all(marker in output for marker in markers): - return classification - return "infrastructure_failure" - - -def classify_verus(name: str, returncode: int | None, output: str) -> str: - if returncode is None: - return "timeout" - expected_code, classification, markers = VERUS_EXPECTATIONS[name] - if returncode == expected_code and all(marker in output for marker in markers): - return classification - return "infrastructure_failure" - - -def classify_playback(name: str, returncode: int | None, output: str) -> str: - if returncode is None: - return "timeout" - failures = re.findall(r"(?m)^test (kani_concrete_playback_regression_\d+) \.\.\. FAILED$", output) - summary = re.search( - r"(?m)^test result: FAILED\. 0 passed; 1 failed; 0 ignored; 0 measured; \d+ filtered out; finished in \d+(?:\.\d+)?s$", - output, - ) - if (returncode != 0 and failures == [name] and summary - and "assertion `left == right` failed" in output and "left: 10" in output and "right: 9" in output): - return "native_regression_playback" - return "infrastructure_failure" - - -def resolve_tool(value: str) -> Path | None: - found = shutil.which(value) - if found is None: - return None - path = Path(found).resolve() - return path if path.is_file() and os.access(path, os.X_OK) else None - - -def write_report(output_dir: Path, report: dict[str, object]) -> None: - (output_dir / "report.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") - - -def run_command(name: str, argv: list[str], output_dir: Path, timeout: float) -> tuple[dict[str, object], str]: - from vkit.runtime.proc import run as run_process - - stdout_name, stderr_name = f"{name}.stdout.log", f"{name}.stderr.log" - stdout_path, stderr_path = output_dir / stdout_name, output_dir / stderr_name - record: dict[str, object] = {"name": name, "argv": argv, "cwd": str(output_dir), "returncode": None, - "timed_out": False, "launch_error": None, - "classification": "infrastructure_failure", - "stdout_log": stdout_name, "stderr_log": stderr_name} - result = run_process(argv, cwd=output_dir, stdout_path=stdout_path, stderr_path=stderr_path, - timeout_seconds=timeout) - record.update({"returncode": result.code, "timed_out": result.timed_out, - "cancelled": result.cancelled, "launch_error": result.launch_error, - "output_limited": result.output_limited}) - if result.timed_out: - record["classification"] = "timeout" - elif result.code is not None and result.launch_error is None and not result.output_limited and not result.cancelled: - record["classification"] = "completed" - stdout = stdout_path.read_text(encoding="utf-8", errors="replace") - stderr = stderr_path.read_text(encoding="utf-8", errors="replace") - return record, stdout + "\n" + stderr - - -def required_run(name: str, argv: list[str], output_dir: Path, timeout: float, classifier, - report: dict[str, object]) -> tuple[dict[str, object], str]: - record, output = run_command(name, argv, output_dir, timeout) - if record["classification"] == "completed": - record["classification"] = classifier(record["returncode"], output) - report["runs"].append(record) - if record["classification"] == "timeout": - raise ProbeStop("TIMEOUT", f"{name} timed out") - if record["classification"] == "infrastructure_failure": - raise ProbeStop("INFRASTRUCTURE_FAILURE", f"{name} return code or required diagnostic did not match") - return record, output - - -def tool_identity(name: str, path: Path, output_dir: Path, timeout: float, - report: dict[str, object]) -> None: - record, output = run_command(f"{name}-version", [str(path), "--version"], output_dir, timeout) - report["runs"].append(record) - if record["classification"] == "timeout": - raise ProbeStop("TIMEOUT", f"{name} --version timed out") - version = output.strip() - if record["returncode"] != 0 or not version: - raise ProbeStop("INFRASTRUCTURE_FAILURE", f"{name} --version failed") - record["classification"] = "tool_identity_only" - identity = {"path": str(path), "sha256": sha256(path), "version": version, - "stdout_log": record["stdout_log"], "stderr_log": record["stderr_log"]} - report["tools"][name] = identity - - -def regression_playback(output: str) -> tuple[str, str]: - section = re.search(r"Concrete playback unit test for `regression`:\s*```[^\r\n]*\r?\n(.*?)```", output, re.S) - if section is None: - raise ProbeStop("INFRASTRUCTURE_FAILURE", "Kani did not emit the regression playback test") - snippet = re.search(r"(?ms)(/// Test generated for harness `regression`.*?^})", section.group(1)) - if snippet is None or snippet.group(1).count("#[test]") != 1: - raise ProbeStop("INFRASTRUCTURE_FAILURE", "Kani playback did not contain exactly one generated test") - names = re.findall(r"(?m)^fn (kani_concrete_playback_regression_\d+)\(\)", snippet.group(1)) - if (len(names) != 1 or "kani::concrete_playback_run(concrete_vals, regression);" not in snippet.group(1) - or not re.search(r"//\s*10\s*vec!\[\s*10,\s*0,\s*0,\s*0\s*\]", snippet.group(1))): - raise ProbeStop("INFRASTRUCTURE_FAILURE", "Kani regression playback did not encode the required x=10 witness") - return names[0], snippet.group(1) - - -def snapshot_inputs(output_dir: Path) -> dict[str, str]: - hashes = {} - for name, source in SNAPSHOTS.items(): - destination = output_dir / name - destination.write_bytes(source.read_bytes()) - hashes[name] = sha256(destination) - return hashes - - -def make_playback_wrapper(snapshot: Path, destination: Path, generated_test: str) -> str: - destination.write_bytes(snapshot.read_bytes() + b"\n\n" + generated_test.strip().encode("utf-8") + b"\n") - return sha256(destination) - - -def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser(description="Run bounded Kani and Verus change-certification feasibility probes.") - parser.add_argument("--kani", required=True) - parser.add_argument("--verus", required=True) - parser.add_argument("--output-dir", required=True, type=Path) - parser.add_argument("--timeout-seconds", type=float, default=120) - args = parser.parse_args(argv) - output_dir = args.output_dir.resolve() - if output_dir.exists(): - if not output_dir.is_dir() or any(output_dir.iterdir()): - print("BLOCKED: output path must be an empty directory; choose a new directory.", file=sys.stderr) - return 2 - output_dir.mkdir(parents=True, exist_ok=True) - report: dict[str, object] = {"status": "RUNNING", "scope_limit": ( - "Small finite Rust fixture probes only. Kani verifies the copied scalar function bodies. Verus proves a separate arithmetic adaptation. " - "These results do not prove the VKit ledger, arbitrary Rust, or certification effectiveness."), - "runs": [], "tools": {}, "snapshots_sha256": {}} - try: - kani = resolve_tool(args.kani) - verus = resolve_tool(args.verus) - if kani is None or verus is None: - missing = ", ".join(name for name, value in (("kani", kani), ("verus", verus)) if value is None) - raise ProbeStop("BLOCKED", f"missing executable(s): {missing}") - - report["snapshots_sha256"] = snapshot_inputs(output_dir) - report["tools"] = {} - tool_identity("kani", kani, output_dir, args.timeout_seconds, report) - tool_identity("verus", verus, output_dir, args.timeout_seconds, report) - - kani_file = output_dir / "experiment-kani.rs" - snapshot_wrapper_sha256 = report["snapshots_sha256"]["experiment-kani.rs"] - for harness in KANI_EXPECTATIONS: - if sha256(kani_file) != snapshot_wrapper_sha256: - raise ProbeStop("INFRASTRUCTURE_FAILURE", "Kani changed the frozen wrapper snapshot") - argv = [str(kani), str(kani_file), "--harness", harness, - "-Z", "concrete-playback", "--concrete-playback", "print"] - record, output = required_run(f"kani-{harness}", argv, output_dir, args.timeout_seconds, - lambda code, text, name=harness: classify_kani(name, code, text), report) - if sha256(kani_file) != snapshot_wrapper_sha256: - raise ProbeStop("INFRASTRUCTURE_FAILURE", "Kani changed the frozen wrapper snapshot") - if harness == "regression": - test_name, generated_test = regression_playback(output) - playback_file = output_dir / "playback.rs" - playback_wrapper_sha256 = make_playback_wrapper(kani_file, playback_file, generated_test) - report["generated_regression_test"] = {"name": test_name, "wrapper": playback_file.name, - "snapshot_wrapper_sha256": snapshot_wrapper_sha256, - "playback_wrapper_sha256": playback_wrapper_sha256} - required_run( - "kani-regression-playback", - [str(kani), "playback", str(playback_file), "-Z", "concrete-playback", "--", "--nocapture", test_name], - output_dir, args.timeout_seconds, - lambda code, text, name=test_name: classify_playback(name, code, text), report) - if harness == "undefined_behavior": - report["ub_safety"] = {"proof_result": record["classification"], - "playback_generation": "GENERATED", - "native_execution": "NOT_EXECUTED_UNSAFE"} - - for version in VERUS_EXPECTATIONS: - verus_file = output_dir / f"experiment-verus-{version}.rs" - argv = [str(verus), str(verus_file)] - required_run(f"verus-{version}", argv, output_dir, args.timeout_seconds, - lambda code, text, name=version: classify_verus(name, code, text), report) - - report["status"] = "PASS_WITH_UB_PLAYBACK_NOT_EXECUTED" - write_report(output_dir, report) - print("PASS_WITH_UB_PLAYBACK_NOT_EXECUTED kani=5 regression_playback=1 verus=2 " - "ub_proof=SAFETY_FAILURE playback=GENERATED native=NOT_EXECUTED_UNSAFE") - return 0 - except ProbeStop as error: - report["status"] = error.status - report["error"] = str(error) - write_report(output_dir, report) - print(f"{error.status}: {error}", file=sys.stderr) - return 2 - except (OSError, ValueError) as error: - report["status"] = "INFRASTRUCTURE_FAILURE" - report["error"] = str(error) - write_report(output_dir, report) - print(f"INFRASTRUCTURE_FAILURE: {error}", file=sys.stderr) - return 2 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/formal/checks/check_change_witness.py b/formal/checks/check_change_witness.py deleted file mode 100644 index 586f247..0000000 --- a/formal/checks/check_change_witness.py +++ /dev/null @@ -1,384 +0,0 @@ -from __future__ import annotations - -import argparse -import hashlib -import json -import os -import platform -import shutil -import sys -import tempfile -from dataclasses import dataclass -from pathlib import Path -from typing import Any - -from jsonschema import Draft202012Validator - -from vkit.change.certification import ( - ChangeCertificationRequest, - FiniteContract, - FiniteDomain, - IntentRevision, - OutputRow, - SemanticArtifact, -) -from vkit.core.evidence import _retained_path, is_link -from vkit.core.inputs import canonical_digest, capture_git_commit -from vkit.change.intent import preflight_change_request -from vkit.runtime.paths import open_project -from vkit.runtime.proc import run as run_process -from vkit.change.witness import ( - ArtifactRef, - EngineCounterexample, - PlaybackNative, - WitnessBinding, - encode_witness, - import_kani_u32_input, - parse_witness, -) - -ROOT = Path(__file__).resolve().parents[2] -FIXTURES = ROOT / "examples/change-certification/witness-fixtures" -DEFAULT_OUTPUT = ROOT / "tmp/change-witness" -MAX_PROCESS_OUTPUT = 1_000_000 - - -@dataclass(frozen=True) -class ProcessResult: - returncode: int - stdout: bytes - stderr: bytes - - -class Qualification: - def __init__(self, run_root: Path) -> None: - self.run_root = run_root - self.logs = run_root / "process" - self.logs.mkdir() - self.calls = 0 - - def run( - self, - argv: list[str], - *, - cwd: Path, - env: dict[str, str], - input_path: Path | None = None, - timeout_seconds: float = 30, - ) -> ProcessResult: - self.calls += 1 - stdout_path = self.logs / f"{self.calls:03}-stdout.bin" - stderr_path = self.logs / f"{self.calls:03}-stderr.bin" - done = run_process( - argv, - cwd=cwd, - env=env, - stdin_path=input_path, - stdout_path=stdout_path, - stderr_path=stderr_path, - timeout_seconds=timeout_seconds, - max_output_bytes=MAX_PROCESS_OUTPUT, - ) - if done.launch_error or done.timed_out or done.cancelled or done.output_limited: - raise RuntimeError( - f"process did not complete within its limits: {Path(argv[0]).name}: {done}" - ) - return ProcessResult(done.code if done.code is not None else -1, - stdout_path.read_bytes(), stderr_path.read_bytes()) - - -def sha256(raw: bytes) -> str: - return hashlib.sha256(raw).hexdigest() - - -def canonical_bytes(value: Any) -> bytes: - return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode() - - -def _write_artifact(bundle: Path, relative: str, content: bytes, - media_type: str = "application/octet-stream") -> ArtifactRef: - path = _retained_path(bundle, relative) - path.parent.mkdir(parents=True, exist_ok=True) - _retained_path(bundle, relative).write_bytes(content) - return ArtifactRef(relative, sha256(content), media_type) - - -def _git_text(qualification: Qualification, *args: str, cwd: Path, env: dict[str, str]) -> str: - done = qualification.run(["git", *args], cwd=cwd, env=env) - if done.returncode: - raise RuntimeError(done.stderr.decode("utf-8", "replace").strip() - or f"git {' '.join(args)} failed") - return done.stdout.decode("utf-8", "replace").strip() - - -def _git_commit(qualification: Qualification, repo: Path, env: dict[str, str], message: str) -> str: - done = qualification.run( - ["git", "-c", "user.name=VKit Witness Fixture", "-c", - "user.email=witness@vkit.invalid", "commit", "-qm", message], - cwd=repo, env=env, - ) - if done.returncode: - raise RuntimeError(done.stderr.decode("utf-8", "replace").strip() - or f"fixture commit failed: {message}") - return _git_text(qualification, "rev-parse", "HEAD", cwd=repo, env=env) - - -def _captured_file(capture: Any, relative: str) -> bytes: - files = [file for file in capture.files if file.path == relative] - if len(files) != 1: - raise RuntimeError(f"Git capture did not contain exactly {relative}") - return files[0].content - - -def _materialize_capture(bundle: Path, capture: Any, relative: str, name: str) -> bytes: - content = _captured_file(capture, relative) - path = _retained_path(bundle, f"source/{name}/cap.rs") - path.parent.mkdir(parents=True, exist_ok=True) - path.write_bytes(content) - if path.read_bytes() != content: - raise RuntimeError(f"materialized source bytes changed: {name}") - return content - - -def _build_fixture( - qualification: Qualification, - run_root: Path, - env: dict[str, str], - *, - source_before: bytes, - source_after: bytes, - artifacts: dict[str, bytes], - contract: FiniteContract, -) -> tuple[Path, str, str, IntentRevision]: - repo = run_root / "target" - repo.mkdir() - init = qualification.run(["git", "init", "-q"], cwd=repo, env=env) - if init.returncode: - raise RuntimeError("could not initialize disposable Git target") - environment_path = "verification/change-intents/artifacts/environment-identity.json" - artifact_paths = { - "binding": "verification/change-intents/artifacts/u32-cap-binding.json", - "codec": "verification/change-intents/artifacts/u32-le.codec.json", - "observation": "verification/change-intents/artifacts/u32-cap-observation.v1.json", - "environment": environment_path, - } - for role, path in artifact_paths.items(): - target = repo / path - target.parent.mkdir(parents=True, exist_ok=True) - target.write_bytes(artifacts[role]) - intent = IntentRevision( - "SC-03 fixture", "Return min(x, 10) for the supported u32 range.", contract, - tuple(SemanticArtifact(role, artifact_paths[role], sha256(artifacts[role])) - for role in ("binding", "codec", "observation", "environment")), - ) - revision = repo / f"verification/change-intents/{intent.digest}.v1.json" - revision.write_bytes(canonical_bytes(intent.to_json()) + b"\n") - accepted = repo / "verification/change-intents/accepted.v1.json" - accepted.write_bytes(canonical_bytes({"schema_version": 1, "accepted": [intent.digest]}) + b"\n") - candidate_path = repo / "src/cap.rs" - candidate_path.parent.mkdir(parents=True) - candidate_path.write_bytes(source_before) - add = qualification.run(["git", "add", "."], cwd=repo, env=env) - if add.returncode: - raise RuntimeError("could not stage trusted target fixture") - target_oid = _git_commit(qualification, repo, env, "trusted target fixture") - candidate_path.write_bytes(source_after) - add = qualification.run(["git", "add", "src/cap.rs"], cwd=repo, env=env) - if add.returncode: - raise RuntimeError("could not stage candidate source fixture") - candidate_oid = _git_commit(qualification, repo, env, "candidate source fixture") - return repo, target_oid, candidate_oid, intent - - -def main() -> int: - parser = argparse.ArgumentParser(description="Qualify retained native witness playback.") - parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT) - args = parser.parse_args() - output = args.output.expanduser().absolute() - if is_link(output) or (output.exists() and not output.is_dir()): - raise RuntimeError("output path must be a plain directory") - output.mkdir(parents=True, exist_ok=True) - if is_link(output) or not output.resolve().is_dir(): - raise RuntimeError("output path is not a plain directory") - run_root = Path(tempfile.mkdtemp(prefix="run-", dir=output)) - qualification = Qualification(run_root) - - env = dict(os.environ) - env["PYTHONPATH"] = os.pathsep.join( - [str(ROOT / "src"), *filter(None, env.get("PYTHONPATH", "").split(os.pathsep))] - ) - rustup = shutil.which("rustup", path=env.get("PATH")) - if rustup is None: - raise RuntimeError("rustup must be available to resolve the installed Rust compiler") - compiler_path = qualification.run([rustup, "which", "rustc"], cwd=ROOT, env=env) - if compiler_path.returncode: - raise RuntimeError("could not resolve the installed Rust compiler") - compiler_binary = Path(compiler_path.stdout.decode("utf-8").strip()).resolve() - if not compiler_binary.is_file() or is_link(compiler_binary): - raise RuntimeError("resolved Rust compiler is not a regular file") - compiler_version = qualification.run([str(compiler_binary), "-vV"], cwd=ROOT, env=env) - if compiler_version.returncode: - raise RuntimeError("resolved Rust compiler identity probe failed") - compiler_text = compiler_version.stdout.decode("utf-8", "replace").strip() - target = next((line[6:] for line in compiler_text.splitlines() - if line.startswith("host: ")), "unknown") - - fixture_files = { - "base": FIXTURES / "u32-cap-before.rs", - "candidate": FIXTURES / "u32-cap-after.rs", - "playback": FIXTURES / "u32-playback.rs", - "kani": FIXTURES / "kani-u32-regression.txt", - "binding": FIXTURES / "u32-cap-binding.json", - "codec": FIXTURES / "u32-le.codec.json", - "observation": FIXTURES / "u32-cap-observation.v1.json", - } - fixture_bytes = {name: path.read_bytes() for name, path in fixture_files.items()} - input_bytes = import_kani_u32_input(fixture_bytes["kani"]) - if len(input_bytes) != 4 or int.from_bytes(input_bytes, "little") != 10: - raise RuntimeError("retained transcript fixture did not import the known u32 input") - - source_before = fixture_bytes["base"] - source_after = fixture_bytes["candidate"].replace(b"cap_after", b"cap") - if source_before == source_after or b"pub fn cap(" not in source_after: - raise RuntimeError("candidate source fixture does not encode a distinct cap implementation") - env_sha256 = canonical_digest({"variables": sorted(env.items()), "platform": platform.platform()}) - environment_bytes = canonical_bytes({"effective_environment_sha256": env_sha256, "target": target}) - codec_sha256 = sha256(fixture_bytes["codec"]) - observation_sha256 = sha256(fixture_bytes["observation"]) - environment_sha256 = sha256(environment_bytes) - output_10 = '{"input":10,"before":10,"after":10}' - output_9 = '{"input":10,"before":10,"after":9}' - domain = FiniteDomain( - "u32-cap", ("x=10",), (output_10, output_9), - codec_sha256, observation_sha256, environment_sha256, - ) - contract = FiniteContract( - domain, ("x=10",), (OutputRow("x=10", (output_10,)),) - ) - repo, target_oid, candidate_oid, intent = _build_fixture( - qualification, run_root, env, - source_before=source_before, source_after=source_after, - artifacts={"binding": fixture_bytes["binding"], "codec": fixture_bytes["codec"], - "observation": fixture_bytes["observation"], "environment": environment_bytes}, - contract=contract, - ) - request = ChangeCertificationRequest(target_oid, candidate_oid, intent.digest, contract) - bound = preflight_change_request( - open_project(repo), request.to_json(), trusted_target_oid=target_oid - ) - if (bound.request.base_oid != target_oid or bound.request.candidate_oid != candidate_oid - or bound.candidate_capture_sha256 == bound.base_capture_sha256): - raise RuntimeError("preflight did not bind the distinct trusted target and candidate") - - base_capture = capture_git_commit(open_project(repo), target_oid) - candidate_capture = capture_git_commit(open_project(repo), candidate_oid) - if (base_capture.digest != bound.base_capture_sha256 - or candidate_capture.digest != bound.candidate_capture_sha256): - raise RuntimeError("independent Git captures differ from preflight source captures") - base_source = _materialize_capture(run_root, base_capture, "src/cap.rs", "base") - candidate_source = _materialize_capture(run_root, candidate_capture, "src/cap.rs", "candidate") - input_ref = _write_artifact(run_root, "input.u32le", input_bytes) - counterexample_ref = _write_artifact( - run_root, "kani-transcript-fixture.txt", fixture_bytes["kani"], "text/plain" - ) - playback_path = _retained_path(run_root, "native/playback.rs") - playback_path.parent.mkdir(parents=True) - playback_path.write_bytes(fixture_bytes["playback"]) - base_path = _retained_path(run_root, "source/base/cap.rs") - candidate_path = _retained_path(run_root, "source/candidate/cap.rs") - binary_path = _retained_path(run_root, "native/u32-playback.exe" if os.name == "nt" - else "native/u32-playback") - compile_result = qualification.run( - [str(compiler_binary), "--edition=2021", str(playback_path), "-o", str(binary_path)], - cwd=run_root / "native", env=env, - ) - if compile_result.returncode or not binary_path.is_file(): - raise RuntimeError("Rust native playback compilation failed: " - + compile_result.stderr.decode("utf-8", "replace")) - runtime_identity = { - "compiler_binary_path": str(compiler_binary), - "compiler_binary_sha256": sha256(compiler_binary.read_bytes()), - "compiler_version": compiler_text, - "target": target, - "environment_sha256": env_sha256, - "base_source_sha256": sha256(base_source), - "candidate_source_sha256": sha256(candidate_source), - "playback_source_sha256": sha256(fixture_bytes["playback"]), - "binary_sha256": sha256(binary_path.read_bytes()), - } - runtime_bytes = canonical_bytes(runtime_identity) - runtime_sha256 = sha256(runtime_bytes) - runtime_ref = _write_artifact(run_root, "runtime-identity.json", runtime_bytes, "application/json") - expected = WitnessBinding.from_bound_request( - bound, - runner_identity_sha256=canonical_digest({ - "script_sha256": sha256(Path(__file__).read_bytes()), - "witness_module_sha256": sha256((ROOT / "src/vkit/change/witness.py").read_bytes()), - "schema_sha256": sha256((ROOT / "schemas/witness.v1.json").read_bytes()), - "counterexample_fixture_sha256": counterexample_ref.sha256, - }), - runtime_identity_sha256=runtime_sha256, - ) - playback = qualification.run( - [str(binary_path)], cwd=run_root / "native", env=env, input_path=input_ref_path(run_root, input_ref), - ) - if playback.returncode: - raise RuntimeError("Rust native playback failed: " - + playback.stderr.decode("utf-8", "replace")) - try: - observation = json.loads(playback.stdout.decode("utf-8")) - except (UnicodeDecodeError, json.JSONDecodeError) as exc: - raise RuntimeError(f"Rust playback did not emit valid JSON: {exc}") from exc - Draft202012Validator(json.loads(fixture_bytes["observation"])).validate(observation) - observation_ref = _write_artifact(run_root, "observation.json", playback.stdout, "application/json") - if observation != {"input": 10, "before": 10, "after": 9}: - raise RuntimeError(f"native pair did not reproduce expected after-9 behavior: {observation!r}") - witness = EngineCounterexample( - expected, counterexample_ref, input_ref, - PlaybackNative(runtime_sha256, runtime_ref, observation_ref, "reproduced"), - ) - witness_bytes = encode_witness(witness) - witness_path = _retained_path(run_root, "witness.json") - witness_path.write_bytes(witness_bytes) - parsed = parse_witness(witness_path.read_bytes(), expected=expected, artifact_root=run_root) - if not isinstance(parsed, EngineCounterexample): - raise RuntimeError("native playback witness did not round-trip as an engine counterexample") - if (base_path.read_bytes() != _captured_file(base_capture, "src/cap.rs") - or candidate_path.read_bytes() != _captured_file(candidate_capture, "src/cap.rs")): - raise RuntimeError("native compilation inputs differ from exact Git source captures") - print(json.dumps({ - "result": "native_witness_reproduced", - "input_u32": int.from_bytes(input_bytes, "little"), - "observation": observation, - "witness_sha256": sha256(witness_bytes), - "binding_sha256": expected.to_json()["binding_sha256"], - "target_commit": target_oid, - "candidate_commit": candidate_oid, - "base_capture_sha256": bound.base_capture_sha256, - "candidate_capture_sha256": bound.candidate_capture_sha256, - "runner_identity_sha256": expected.runner_identity_sha256, - "runtime_identity_sha256": runtime_sha256, - "domain_observations": [output_10, output_9], - "accepted_outputs": [output_10], - "kani_executed": False, - "transcript_is_fixture": True, - "source_proof": False, - "candidate_behavior_checked_by_preflight": False, - "run_directory": str(run_root), - }, sort_keys=True)) - return 0 - - -def input_ref_path(bundle: Path, ref: ArtifactRef) -> Path: - path = _retained_path(bundle, ref.path) - if sha256(path.read_bytes()) != ref.sha256: - raise RuntimeError("retained native input bytes do not match their digest") - return path - - -if __name__ == "__main__": - try: - raise SystemExit(main()) - except (OSError, RuntimeError, ValueError) as exc: - print(f"WITNESS_GATE_BLOCKED: {exc}", file=sys.stderr) - raise SystemExit(2) diff --git a/formal/checks/check_dafny_kernel.py b/formal/checks/check_dafny_kernel.py new file mode 100644 index 0000000..f4421ba --- /dev/null +++ b/formal/checks/check_dafny_kernel.py @@ -0,0 +1,125 @@ +"""Verify Dafny kernel proofs and Python codegen freshness.""" +from __future__ import annotations + +import os +import shutil +import subprocess +import sys +import tempfile +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +DAFNY_DIR = ROOT / "formal" / "dafny" +BUILT_GEN = ROOT / "src" / "vkit" / "kernel" / "_dafny_gen" / "vkit_kernel-py" +DAFNY_MODULES = ( + "VKitGate.dfy", + "VKitBudgets.dfy", + "VKitAcceptance.dfy", + "VKitReceipt.dfy", + "VKitChange.dfy", + "VKitKernel.dfy", +) + + +def _find_dafny() -> str | None: + env_bin = os.environ.get("VKIT_DAFNY_BIN") + if env_bin and Path(env_bin).is_file(): + return env_bin + return shutil.which("dafny") + + +def _collect_tree(root: Path) -> dict[str, bytes]: + files: dict[str, bytes] = {} + if not root.is_dir(): + return files + for path in sorted(root.rglob("*")): + if not path.is_file(): + continue + if "__pycache__" in path.parts or path.suffix == ".pyc": + continue + files[path.relative_to(root).as_posix()] = path.read_bytes() + return files + + +def main() -> int: + dafny = _find_dafny() + if dafny is None: + print("FAIL: dafny binary not found on PATH or VKIT_DAFNY_BIN", file=sys.stderr) + return 2 + + dfy_paths = [str(DAFNY_DIR / name) for name in DAFNY_MODULES] + t0 = time.monotonic() + verify = subprocess.run( + [dafny, "verify", *dfy_paths], + cwd=ROOT, + capture_output=True, + text=True, + timeout=120, + ) + verify_s = time.monotonic() - t0 + if verify.returncode != 0: + if verify.stdout: + print(verify.stdout, end="", file=sys.stderr) + if verify.stderr: + print(verify.stderr, end="", file=sys.stderr) + print(f"FAIL: dafny verify failed ({verify_s:.2f}s)", file=sys.stderr) + return 1 + + with tempfile.TemporaryDirectory() as tmp: + out_prefix = Path(tmp) / "vkit_kernel" + t1 = time.monotonic() + build = subprocess.run( + [ + dafny, + "build", + "--target:py", + "--no-verify", + f"--output:{out_prefix}", + str(DAFNY_DIR / "VKitKernel.dfy"), + ], + cwd=ROOT, + capture_output=True, + text=True, + timeout=120, + ) + build_s = time.monotonic() - t1 + if build.returncode != 0: + if build.stdout: + print(build.stdout, end="", file=sys.stderr) + if build.stderr: + print(build.stderr, end="", file=sys.stderr) + print(f"FAIL: dafny build failed ({build_s:.2f}s)", file=sys.stderr) + return 1 + + fresh = _collect_tree(Path(tmp) / "vkit_kernel-py") + if not fresh: + print("FAIL: dafny build produced no Python files", file=sys.stderr) + return 1 + + built = _collect_tree(BUILT_GEN) + if built: + missing = sorted(set(fresh) - set(built)) + extra = sorted(set(built) - set(fresh)) + mismatched = sorted( + name for name in set(fresh) & set(built) if fresh[name] != built[name] + ) + if missing or extra or mismatched: + if missing: + print(f"FAIL: missing generated files: {missing}", file=sys.stderr) + if extra: + print(f"FAIL: extra generated files: {extra}", file=sys.stderr) + if mismatched: + print(f"FAIL: byte mismatch in generated files: {mismatched}", file=sys.stderr) + return 1 + sync_note = f"{len(fresh)} built files byte-identical" + else: + sync_note = f"{len(fresh)} files compiled cleanly" + + summary = verify.stdout.strip().splitlines()[-1] if verify.stdout.strip() else "verified" + print(f"PASS: {summary} ({verify_s:.2f}s), {sync_note} ({build_s:.2f}s)") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/formal/checks/check_delegated_claim_authority.py b/formal/checks/check_delegated_claim_authority.py deleted file mode 100644 index 5d00511..0000000 --- a/formal/checks/check_delegated_claim_authority.py +++ /dev/null @@ -1,150 +0,0 @@ -from __future__ import annotations - -import argparse -import hashlib -import json -import os -import re -import shutil -import subprocess -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[2] -MODEL_DIR = ROOT / "formal" / "models" -CONFIG_DIR = MODEL_DIR / "delegated-claim" -DEFAULT_OUTPUT = ROOT / "tmp" / "delegation-tlc-output" -EXPECTED_JAR_DIGEST = ROOT / "examples" / "formal-ci" / "tla2tools.sha256" - -CASES = { - "good": None, - "omit_untrusted_target": "AcceptedHasTrustedTargetBasis", - "omit_target_identity": "AcceptedHasTrustedTargetBasis", - "omit_entailment": "AcceptedHasEntailment", - "omit_strict_strengthening": "AcceptedIsStrictStrengthening", - "omit_complete_satisfaction": "AcceptedHasCompleteSatisfaction", - "omit_meaningful_near_miss": "AcceptedHasRejectedMeaningfulNearMiss", - "omit_fresh_receipt_cancel": "AcceptedHasFreshUncancelledReceipt", - "omit_model_scope": "AcceptedUsesRestrictedModel", - "allow_self_justifying_basis": "CurrentClaimCannotBeItsOwnBasis", - "claim_approves_code": "ClaimAcceptanceDoesNotApproveCode", -} - - -class ToolchainUnavailable(RuntimeError): - pass - - -def resolve_toolchain(java_arg: Path | None = None, - jar_arg: Path | None = None) -> tuple[Path, Path]: - java_name = "java.exe" if os.name == "nt" else "java" - if java_arg is not None: - configured_java = java_arg.expanduser() - located_java = shutil.which(str(configured_java)) - java = configured_java.resolve() if configured_java.is_file() else ( - Path(located_java).resolve() if located_java else None - ) - else: - java_home = os.environ.get("JAVA_HOME") - java_home_bin = Path(java_home) / "bin" / java_name if java_home else None - located_java = shutil.which("java") - java = java_home_bin.resolve() if java_home_bin and java_home_bin.is_file() else ( - Path(located_java).resolve() if located_java else None - ) - if java is None or not java.is_file(): - raise ToolchainUnavailable("Java is unavailable; set JAVA_HOME or pass --java") - - configured_jar = jar_arg or (Path(os.environ["VKIT_TLA2TOOLS_JAR"]) - if os.environ.get("VKIT_TLA2TOOLS_JAR") else None) - if configured_jar is None: - raise ToolchainUnavailable( - "TLC jar is unavailable; set VKIT_TLA2TOOLS_JAR or pass --jar" - ) - jar = configured_jar.expanduser().resolve() - if not jar.is_file(): - raise ToolchainUnavailable(f"TLC jar does not exist: {jar}") - - expected = EXPECTED_JAR_DIGEST.read_text(encoding="ascii").strip() - actual = hashlib.sha256(jar.read_bytes()).hexdigest() - if actual != expected: - raise RuntimeError(f"TLC jar SHA-256 mismatch: {actual}") - return java, jar - - -def run_case(name: str, expected: str | None, output: Path, - java: Path, jar: Path) -> dict[str, object]: - config = CONFIG_DIR / f"{name}.cfg" - model = MODEL_DIR / "DelegatedClaimAuthority.tla" - if not config.is_file(): - raise RuntimeError(f"missing TLC configuration: {config}") - states = output / f"{name}-states" - traces = output / f"{name}-traces" - states.mkdir(parents=True, exist_ok=True) - traces.mkdir(parents=True, exist_ok=True) - options = {} - if os.name == "nt": - from vkit.runtime.nowindow import hidden_window - - options = hidden_window() - done = subprocess.run( - [str(java), "-cp", str(jar), "tlc2.TLC", "-config", str(config), - "-metadir", str(states), "-teSpecOutDir", str(traces), str(model)], - cwd=output, - capture_output=True, - text=True, - timeout=240, - check=False, - **options, - ) - transcript = done.stdout + ("\n--- stderr ---\n" + done.stderr if done.stderr else "") - (output / f"{name}.tlc.txt").write_text(transcript, encoding="utf-8") - violations = re.findall(r"Invariant ([A-Za-z][A-Za-z0-9_]*) is violated", transcript) - passed = not violations and "No error has been found" in transcript - if expected is not None: - passed = expected in violations - if done.returncode not in {0, 12} or not passed: - raise RuntimeError( - f"{name}: TLC exit={done.returncode}, expected={expected!r}, " - f"violations={violations!r}\n{transcript}" - ) - states = re.search(r"([0-9,]+) distinct states found", transcript) - return { - "case": name, - "expected_counterexample": expected, - "observed_counterexamples": violations, - "result": "counterexample" if expected else "invariants_hold", - "distinct_states": int(states.group(1).replace(",", "")) if states else None, - "tlc_exit_code": done.returncode, - "transcript": f"{name}.tlc.txt", - } - - -def run_suite(output: Path, java_arg: Path | None = None, - jar_arg: Path | None = None) -> dict[str, object]: - java, jar = resolve_toolchain(java_arg, jar_arg) - output.mkdir(parents=True, exist_ok=True) - results = [run_case(name, expected, output, java, jar) - for name, expected in CASES.items()] - report = { - "tool": "TLC", - "jar_sha256": hashlib.sha256(jar.read_bytes()).hexdigest(), - "scope": "finite delegated-claim authority abstraction; restricted captured Rust Kani model", - "limit": "This finite model is not a Python refinement proof, native-code proof, or general implementation proof.", - "cases": results, - } - (output / "report.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") - return report - - -def main() -> int: - parser = argparse.ArgumentParser(description="Run finite delegated-claim authority models with pinned TLC.") - parser.add_argument("--java", type=Path) - parser.add_argument("--jar", type=Path) - parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT) - args = parser.parse_args() - report = run_suite(args.output.resolve(), args.java, args.jar) - print(json.dumps(report, indent=2)) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/formal/checks/check_difference_decisions.py b/formal/checks/check_difference_decisions.py deleted file mode 100644 index d4a7296..0000000 --- a/formal/checks/check_difference_decisions.py +++ /dev/null @@ -1,529 +0,0 @@ -from __future__ import annotations - -import hashlib -import argparse -import json -import os -from pathlib import Path -import re -import shutil -import signal -import sys -import threading -import time -from collections import Counter -from typing import Any - -ROOT = Path(__file__).resolve().parents[2] -MODEL_DIR = ROOT / "formal" / "models" / "certification" -SCENARIOS = { - "bounded": "Differences.cfg", - "invalid_shrink": "Differences.invalid-shrink.cfg", - "violation_missing": "Differences.violation-missing.cfg", - "guard_overlap": "Differences.guard-overlap.cfg", - "repair": "Differences.repair.cfg", - "empty": "Differences.empty.cfg", -} -MARKER = "VKIT_DIFF_DECISION_V1" -MAX_OUTPUT = 8 * 1024 * 1024 -CASE_TIMEOUT = 120 - - -def sha256(path: Path) -> str: - return hashlib.sha256(path.read_bytes()).hexdigest() - - -def decode_tla_tuple(raw: str) -> tuple[Any, int]: - depth = 0 - quoted = False - escaped = False - end = None - cursor = 0 - while cursor < len(raw) - 1: - char = raw[cursor] - if quoted: - if escaped: - escaped = False - elif char == "\\": - escaped = True - elif char == '"': - quoted = False - elif char == '"': - quoted = True - elif raw[cursor:cursor + 2] == "<<": - depth += 1 - cursor += 1 - elif raw[cursor:cursor + 2] == ">>": - depth -= 1 - cursor += 1 - if depth == 0: - end = cursor + 1 - break - cursor += 1 - if end is None: - raise ValueError("unterminated TLC output sequence") - raw = raw[:end] - token = re.compile(r'\s*(<<|>>|,|TRUE\b|FALSE\b|-?[0-9]+|"(?:\\.|[^"\\])*"|.)', re.DOTALL) - tokens = [] - pos = 0 - while pos < len(raw): - match = token.match(raw, pos) - if not match: - raise ValueError("invalid TLC tuple token") - value = match.group(1) - pos = match.end() - if value.isspace(): - continue - if value not in {"<<", ">>", ",", "TRUE", "FALSE"} and not ( - value.startswith('"') or re.fullmatch(r"-?[0-9]+", value) - ): - if value.strip() == "": - continue - raise ValueError(f"unsupported TLC tuple token: {value!r}") - tokens.append(value) - - index = 0 - - def parse() -> Any: - nonlocal index - if index >= len(tokens): - raise ValueError("truncated TLC tuple") - value = tokens[index] - index += 1 - if value == "<<": - result = [] - if index < len(tokens) and tokens[index] == ">>": - index += 1 - return result - while True: - result.append(parse()) - if index >= len(tokens): - raise ValueError("unterminated TLC sequence") - separator = tokens[index] - index += 1 - if separator == ">>": - return result - if separator != ",": - raise ValueError("invalid TLC sequence separator") - if value == "TRUE": - return True - if value == "FALSE": - return False - if value.startswith('"'): - return json.loads(value) - if re.fullmatch(r"-?[0-9]+", value): - return int(value) - raise ValueError("unexpected TLC tuple delimiter") - - parsed = parse() - if index != len(tokens) or not isinstance(parsed, list): - raise ValueError("extra tokens or non-sequence TLC output") - return tuple(parsed), end - - -def terminal_rows(stdout: str) -> list[tuple[Any, ...]]: - rows = [] - needle = json.dumps(MARKER) - offset = 0 - while (marker_at := stdout.find(needle, offset)) >= 0: - start = stdout.rfind("<<", 0, marker_at) - if start < 0: - raise ValueError("TLC marker is not inside a sequence") - parsed, consumed = decode_tla_tuple(stdout[start:]) - offset = start + consumed - if len(parsed) != 9 or parsed[0] != MARKER: - raise ValueError("unexpected terminal row shape") - rows.append(parsed) - return rows - - -def validate_record(record: Any) -> None: - if (not isinstance(record, list) or len(record) != 5 - or type(record[0]) is not int or type(record[1]) is not bool - or type(record[2]) is not bool - or not isinstance(record[3], list) or not isinstance(record[4], list) - or any(type(value) is not int for value in (*record[3], *record[4]))): - raise ValueError("TLC record does not match the integer/boolean witness shape") - - -def validate_terminal_row(row: tuple[Any, ...]) -> None: - if (len(row) != 9 or row[0] != MARKER or not isinstance(row[1], str) - or not isinstance(row[2], list) or row[3] not in { - "conformance", "observed_violation", "unknown" - } or type(row[4]) is not bool or not isinstance(row[5], list) - or any(type(value) is not int for value in row[5])): - raise ValueError("TLC terminal tuple has the wrong field types") - for sequence in (row[2], row[6], row[7], row[8]): - if not isinstance(sequence, list): - raise ValueError("TLC terminal record collection is not a sequence") - for record in sequence: - validate_record(record) - - -def expected_raw_count(pool_size: int) -> int: - return sum(pool_size**length for length in range(3)) - - -def make_intent(inputs: tuple[str, ...]): - from vkit.change.certification import IntentRevision - - hashes = {name: (str(index) * 64) for index, name in enumerate( - ("binding", "codec", "observation", "environment"), start=1 - )} - raw = { - "schema_version": 1, - "requirement": {"source": "model bridge", "statement": "finite u32 output relation"}, - "contract": { - "domain": { - "binding": "u32-le", - "inputs": ["1", "2"], - "observations": ["0", "1", "2", "3"], - "codec_sha256": hashes["codec"], - "observation_sha256": hashes["observation"], - "environment_sha256": hashes["environment"], - }, - "admissible_inputs": list(inputs), - "allowed_outputs": [ - {"input": token, "outputs": ["1", "2"] if token == "1" else ["2"]} - for token in inputs - ], - }, - "artifacts": { - role: {"path": f"model/{role}", "sha256": digest} - for role, digest in hashes.items() - }, - } - return IntentRevision.from_json(raw) - - -def make_policy(intent, guarded: bool): - from vkit.change.certification import DifferencePolicy - - guards = [] - if guarded: - guards = [ - {"id": "guard-a", "requirements": [{"input": "1", "outputs": ["1", "2"]}]}, - {"id": "guard-b", "requirements": [{"input": "1", "outputs": ["2"]}]}, - ] - return DifferencePolicy.from_json({ - "schema_version": 1, - "kind": "finite_differences", - "intent_sha256": intent.digest, - "guards": guards, - }, intent=intent) - - -def record_key(record: tuple[Any, ...]) -> tuple[Any, ...]: - return (record[0], record[1], record[2], tuple(record[3]), tuple(record[4])) - - -def finding_counter(findings, kind: str) -> Counter: - return Counter( - (finding.input, finding.base_output, finding.candidate_output) - for finding in findings if finding.kind == kind - ) - - -def counter_json(counts: Counter) -> list[dict[str, Any]]: - return [ - {"input": key[0], "base_output": key[1], "candidate_output": key[2], "count": count} - for key, count in sorted(counts.items(), key=lambda item: repr(item[0])) - ] - - -def status_matches(model_status: str, python_status: str) -> bool: - projected = { - "conformance": "observed_conformance", - "observed_violation": "observed_violation", - "unknown": "unknown", - }[model_status] - return projected == python_status - - -def compare_terminal(name: str, row: tuple[Any, ...], intent, policy) -> list[dict[str, Any]]: - from vkit.change.certification import PairedObservation, assess_differences - - _, _, raw_records, model_status, model_coverage, model_missing, model_violations, model_unknowns, model_repairs = row - raw_sequence = tuple(record_key(record) for record in raw_records) - observations = tuple( - PairedObservation( - str(record[0]), tuple(str(value) for value in record[3]), - tuple(str(value) for value in record[4]), - "paired_execution_failed" if record[2] else None, bool(record[1]), - ) - for record in raw_records - ) - assessment = assess_differences(intent, policy, observations, repetitions=2) - actual = assessment.to_json() - mismatches = [] - if not status_matches(model_status, actual["status"]): - mismatches.append({"records": raw_sequence, "field": "status", "model": model_status, "python": actual["status"]}) - if actual["coverage_complete"] is not model_coverage: - mismatches.append({"records": raw_sequence, "field": "coverage_complete", "model": model_coverage, "python": actual["coverage_complete"]}) - if set(actual["missing_inputs"]) != {str(value) for value in model_missing}: - mismatches.append({"records": raw_sequence, "field": "missing_inputs", "model": model_missing, "python": actual["missing_inputs"]}) - - model_unknown_inputs = {str(value[0]) for value in model_unknowns} - model_unknown_inputs.update(str(value) for value in model_missing) - python_unknown_inputs = {finding.input for finding in assessment.findings if finding.kind == "unknown"} - if model_unknown_inputs != python_unknown_inputs: - mismatches.append({"records": raw_sequence, "field": "unknown_inputs", "model": sorted(model_unknown_inputs), "python": sorted(python_unknown_inputs)}) - - model_violation_counts = Counter( - (str(value[0]), str(value[3][0]) if value[3] else None, - str(value[4][0]) if value[4] else None) - for value in model_violations - ) - python_violation_counts = finding_counter(assessment.findings, "violation") - if model_violation_counts != python_violation_counts: - mismatches.append({"records": raw_sequence, "field": "violations", "model": counter_json(model_violation_counts), "python": counter_json(python_violation_counts)}) - - selected_counts = Counter(str(value[0]) for value in raw_sequence if value[1]) - model_repair_counts = Counter( - (str(value[0]), str(value[3][0]) if value[3] else None, - str(value[4][0]) if value[4] else None) - for value in model_repairs if value[1] and selected_counts[str(value[0])] == 1 - ) - python_repair_counts = finding_counter(assessment.findings, "standing_intent_repair") - if model_repair_counts != python_repair_counts: - mismatches.append({"records": raw_sequence, "field": "repairs", "model": counter_json(model_repair_counts), "python": counter_json(python_repair_counts)}) - if actual["source_proof"] is not False or actual["approval_authority"] is not False: - mismatches.append({"records": raw_sequence, "field": "authority", "python": actual}) - return mismatches - - -def compare_case(name: str, rows: list[tuple[Any, ...]]) -> dict[str, Any]: - raw_sequences = set() - for row in rows: - _, scenario, raw_records, *_ = row - if scenario != name: - raise ValueError(f"TLC scenario mismatch: expected {name}, got {scenario}") - validate_terminal_row(row) - frozen = tuple(record_key(record) for record in raw_records) - raw_sequences.add(frozen) - pool_sizes = { - "bounded": 13, "invalid_shrink": 2, "violation_missing": 2, - "guard_overlap": 2, "repair": 1, "empty": 0, - } - expected = expected_raw_count(pool_sizes[name]) - if len(raw_sequences) != expected: - raise ValueError(f"{name}: expected {expected} unique raw sequences, got {len(raw_sequences)}") - - tokens = ("1", "2") if name in {"bounded", "violation_missing"} else ("1",) if name != "empty" else () - intent = make_intent(tokens) - policy = make_policy(intent, name == "guard_overlap") - mismatches = [] - for row in rows: - mismatches.extend(compare_terminal(name, row, intent, policy)) - - negative_control = None - if name == "bounded" and raw_sequences: - sample = next(row for row in rows if row[6]) - mutated = (*sample[:6], sample[6][1:], *sample[7:]) - negative_mismatches = compare_terminal(name, mutated, intent, policy) - changed_status = next( - status for status in ("conformance", "observed_violation", "unknown") - if status != sample[3] - ) - status_mutation = (*sample[:3], changed_status, *sample[4:]) - status_mismatches = compare_terminal(name, status_mutation, intent, policy) - status_control = { - "control": "same raw sequence with changed terminal status", - "same_raw_sequence": tuple(record_key(record) for record in status_mutation[2]) - == tuple(record_key(record) for record in sample[2]), - "mismatches": status_mismatches, - "decision_rejected": any(item["field"] == "status" for item in status_mismatches), - } - violation_control = { - "control": "remove one actual modeled violation", - "mismatches": negative_mismatches, - "decision_rejected": any(item["field"] == "violations" for item in negative_mismatches), - } - negative_control = { - "controls": [violation_control, status_control], - "decision_rejected": all(item["decision_rejected"] for item in (violation_control, status_control)), - } - return { - "scenario": name, - "terminal_rows": len(rows), - "terminal_rows_compared": len(rows), - "duplicate_rows_counted_once_for_coverage": len(rows) - len(raw_sequences), - "unique_raw_sequences": len(raw_sequences), - "expected_raw_sequences": expected, - "comparator_negative_control": negative_control, - "mismatches": mismatches, - } - - -def run_case(name: str, cfg_name: str, run_dir: Path, cancel: threading.Event, - java: Path, tla_jar: Path) -> dict[str, Any]: - from vkit.runtime.proc import run as proc_run - - module_copy = run_dir / "Differences.tla" - wrapper_copy = run_dir / "DifferenceDecisionBridge.tla" - config_copy = run_dir / cfg_name - shutil.copyfile(MODEL_DIR / "Differences.tla", module_copy) - shutil.copyfile(MODEL_DIR / "DifferenceDecisionBridge.tla", wrapper_copy) - if (sha256(module_copy) != sha256(MODEL_DIR / "Differences.tla") - or sha256(wrapper_copy) != sha256(MODEL_DIR / "DifferenceDecisionBridge.tla")): - raise ValueError("TLC input module copy does not match its reviewed source") - config = (MODEL_DIR / cfg_name).read_text(encoding="utf-8") - config_copy.write_text(config.rstrip() + "\nINVARIANT BridgeOutput\n", encoding="utf-8") - - env_names = ("PATH", "SystemRoot", "WINDIR", "TEMP", "TMP", "TMPDIR", "LANG", "LC_ALL", "TZ") - env = {key: os.environ[key] for key in env_names if key in os.environ} - java_bin = str(java.parent) - env["PATH"] = java_bin + os.pathsep + env.get("PATH", "") - stdout_path, stderr_path = run_dir / "tlc.stdout.log", run_dir / "tlc.stderr.log" - started = time.monotonic() - result = proc_run( - [str(java), "-cp", str(tla_jar), "tlc2.TLC", "-workers", "1", "-cleanup", - "-config", config_copy.stem, "DifferenceDecisionBridge"], - cwd=run_dir, stdout_path=stdout_path, stderr_path=stderr_path, - timeout_seconds=CASE_TIMEOUT, env=env, should_cancel=cancel.is_set, - max_output_bytes=MAX_OUTPUT, - ) - stdout = stdout_path.read_text(encoding="utf-8", errors="replace") - stderr = stderr_path.read_text(encoding="utf-8", errors="replace") - if result.code != 0 or result.timed_out or result.cancelled or result.output_limited or result.launch_error: - raise RuntimeError(f"TLC failed for {name}: {result}; stdout={stdout[-1000:]!r}; stderr={stderr[-1000:]!r}") - rows = terminal_rows(stdout) - comparison = compare_case(name, rows) - comparison.update({ - "elapsed_seconds": round(time.monotonic() - started, 3), - "source_config_sha256": sha256(MODEL_DIR / cfg_name), - "instrumented_config_sha256": sha256(config_copy), - "tool_output_header": stdout.splitlines()[:3], - "stdout_sha256": sha256(stdout_path), - "stderr_sha256": sha256(stderr_path), - }) - return comparison - - -def resolve_java() -> Path: - executable = "java.exe" if os.name == "nt" else "java" - java_home = os.environ.get("JAVA_HOME") - if java_home: - candidate = Path(java_home) / "bin" / executable - if candidate.is_file(): - return candidate.resolve() - discovered = shutil.which("java") or (shutil.which("java.exe") if os.name == "nt" else None) - if discovered: - return Path(discovered).resolve() - raise FileNotFoundError("Java not found; set JAVA_HOME or add java to PATH") - - -def main() -> int: - parser = argparse.ArgumentParser(description="Compare bounded TLC terminal decisions with VKit's paired evaluator.") - parser.add_argument("--output", type=Path, default=ROOT / "tmp" / "difference-decisions") - parser.add_argument("--jar", type=Path, default=os.environ.get("VKIT_TLA2TOOLS_JAR")) - args = parser.parse_args() - output_root = args.output.resolve() - output_root.mkdir(parents=True, exist_ok=True) - run_id = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime()) - output = output_root / run_id - output.mkdir() - cancel = threading.Event() - previous_handlers = {} - - def request_cancel(signum, _frame): - cancel.set() - - for sig in (signal.SIGINT, signal.SIGTERM): - previous_handlers[sig] = signal.signal(sig, request_cancel) - report: dict[str, Any] = { - "schema_version": 1, - "scope": "bounded TLC terminal-state comparison with the public finite paired-observation evaluator", - "limitations": [ - "finite model and declared record pools only", - "does not establish source proof, dependency closure, or approval authority", - "empty admissible set is evaluated within a parsed nonempty finite universe", - ], - "source_proof": False, - "approval_authority": False, - "model": str(MODEL_DIR / "Differences.tla"), - "wrapper": str(MODEL_DIR / "DifferenceDecisionBridge.tla"), - "model_sha256": sha256(MODEL_DIR / "Differences.tla"), - "wrapper_sha256": sha256(MODEL_DIR / "DifferenceDecisionBridge.tla"), - "bridge_script_sha256": sha256(Path(__file__).resolve()), - "python_evaluator": str(ROOT / "src" / "vkit" / "change" / "certification.py"), - "python_evaluator_sha256": sha256(ROOT / "src" / "vkit" / "change" / "certification.py"), - "tlc_jar": str(args.jar) if args.jar else None, - "tlc_jar_sha256": None, - "java_runtime": None, - "java_runtime_sha256": None, - "tlc_version": None, - "limits": {"per_case_timeout_seconds": CASE_TIMEOUT, "per_process_output_bytes": MAX_OUTPUT}, - "evidence_dir": str(output), - "cases": [], - "errors": [], - } - try: - sys.path.insert(0, str(ROOT / "src")) - import vkit - - expected_package = (ROOT / "src" / "vkit").resolve() - if Path(vkit.__file__).resolve().parent != expected_package: - raise RuntimeError(f"bridge imported VKit from an unexpected location: {vkit.__file__}") - if args.jar is None: - raise FileNotFoundError("set VKIT_TLA2TOOLS_JAR or pass --jar") - tla_jar = args.jar.resolve() - java = resolve_java() - if not tla_jar.is_file(): - raise FileNotFoundError(f"TLC jar does not exist: {tla_jar}") - expected_jar_hash = (ROOT / "examples" / "formal-ci" / "tla2tools.sha256").read_text(encoding="ascii").strip() - lifecycle = json.loads((ROOT / "verification" / "manifest.json").read_text(encoding="utf-8")) - toolchain = next(item for item in lifecycle["checks"] if item["id"] == "lifecycle-model")["toolchain"] - if toolchain["jar_sha256"] != expected_jar_hash: - raise ValueError("lifecycle check and repository TLC checksum pins disagree") - if sha256(tla_jar) != expected_jar_hash: - raise ValueError("TLC jar does not match examples/formal-ci/tla2tools.sha256") - report.update({ - "tlc_jar": str(tla_jar), - "tlc_jar_sha256": sha256(tla_jar), - "tlc_version": toolchain["version"], - "java_runtime": str(java), - "java_runtime_sha256": sha256(java), - }) - for name, cfg_name in SCENARIOS.items(): - case_dir = output / name - case_dir.mkdir() - try: - case = run_case(name, cfg_name, case_dir, cancel, java, tla_jar) - report["cases"].append(case) - except Exception as exc: - report["errors"].append({"scenario": name, "error": f"{type(exc).__name__}: {exc}"}) - break - except Exception as exc: - report["errors"].append({"setup": f"{type(exc).__name__}: {exc}"}) - finally: - for sig, handler in previous_handlers.items(): - signal.signal(sig, handler) - report["unique_raw_sequences"] = sum(case["unique_raw_sequences"] for case in report["cases"]) - report["expected_raw_sequences"] = sum(case["expected_raw_sequences"] for case in report["cases"]) - report["mismatch_count"] = sum(len(case["mismatches"]) for case in report["cases"]) - report["observed_tool_output_header"] = next( - (case["tool_output_header"] for case in report["cases"] if case.get("tool_output_header")), - [], - ) - report["passed"] = ( - not report["errors"] and len(report["cases"]) == len(SCENARIOS) - and report["unique_raw_sequences"] == report["expected_raw_sequences"] == 208 - and report["mismatch_count"] == 0 - and bool(report["cases"]) - and report["cases"][0].get("comparator_negative_control", {}).get("decision_rejected") is True - ) - report_path = output / "report.json" - report_path.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8") - print(json.dumps({ - "passed": report["passed"], "cases": len(report["cases"]), - "unique_raw_sequences": report["unique_raw_sequences"], - "expected_raw_sequences": report["expected_raw_sequences"], - "mismatch_count": report["mismatch_count"], "errors": report["errors"], - "report": str(report_path), - }, sort_keys=True)) - return 0 if report["passed"] else 1 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/formal/checks/check_finite_decisions.py b/formal/checks/check_finite_decisions.py index 4074683..352dc0e 100644 --- a/formal/checks/check_finite_decisions.py +++ b/formal/checks/check_finite_decisions.py @@ -507,11 +507,11 @@ def run() -> dict[str, Any]: "checker_sha256": sha256(Path(__file__).read_bytes()).hexdigest(), "evaluator": "src/vkit/change/certification.py", "evaluator_sha256": sha256((ROOT / "src" / "vkit" / "change" / "certification.py").read_bytes()).hexdigest(), - "reference_model": "formal/models/certification/Differences.tla", + "reference_model": "formal/dafny/VKitChange.dfy", "reference_model_sha256": sha256( - (ROOT / "formal" / "models" / "certification" / "Differences.tla").read_bytes() + (ROOT / "formal" / "dafny" / "VKitChange.dfy").read_bytes() ).hexdigest(), - "selected_tlc_bridge": "formal/checks/check_difference_decisions.py", + "selected_tlc_bridge": "formal/checks/check_dafny_kernel.py", "dimensions": { "inputs": list(INPUTS), "standing_output_atoms": list(OUTPUTS), diff --git a/formal/checks/check_ledger_container.py b/formal/checks/check_ledger_container.py deleted file mode 100644 index 02aa33a..0000000 --- a/formal/checks/check_ledger_container.py +++ /dev/null @@ -1,774 +0,0 @@ -"""Run the pinned Verus ledger qualification in a sealed Docker container.""" -from __future__ import annotations - -import argparse -import hashlib -import json -import os -import shutil -import signal -import subprocess -import sys -import time -import uuid -from pathlib import Path - -from vkit.runtime.nowindow import hidden_window - -ROOT = Path(__file__).resolve().parents[2] - -PROFILE = "verus-linux-x86_64-v1" -LABEL = "vkit.ledger.run_id" -FORMAL_LABEL = "vkit.formal.run_id" -SOURCE_REL = Path("src/vkit/formal/packages/resource_ledger/ledger.rs") -TRUSTED_FILES = ( - Path("formal/checks/check_verus_ledger.py"), - Path("formal/checks/check_p2_contracts.py"), - Path("src/vkit/__init__.py"), - Path("src/vkit/runtime/__init__.py"), - Path("src/vkit/runtime/nowindow.py"), - Path("src/vkit/formal/__init__.py"), - Path("src/vkit/formal/ledger.py"), - Path("src/vkit/formal/qualification.py"), - Path("src/vkit/formal/packages/resource_ledger/upstream.json"), - Path("examples/verus-qualification/smoke.rs"), - Path("examples/verus-qualification/candidate_api.rs"), - Path("examples/verus-qualification/reserve-admission.rs"), - Path("examples/verus-qualification/reserve-strict-bound.rs"), - Path("examples/verus-qualification/historical-positive-limit.rs"), - Path("examples/verus-qualification/p2-transfer.rs"), - Path("examples/verus-qualification/p2-concurrent.rs"), - Path("src/vkit/formal/packages/resource_ledger/expected.rs.in"), - Path("src/vkit/formal/packages/resource_ledger/runtime.rs.in"), -) - - -def run(command: list[str], *, timeout: float = 30, check: bool = True) -> subprocess.CompletedProcess[str]: - result = subprocess.run(command, capture_output=True, text=True, timeout=timeout, check=False, - **hidden_window()) - if check and result.returncode: - raise RuntimeError(f"command failed ({result.returncode}): {result.stderr.strip() or result.stdout.strip()}") - return result - - -def sha256(path: Path) -> str: - digest = hashlib.sha256() - with path.open("rb") as stream: - for chunk in iter(lambda: stream.read(1024 * 1024), b""): - digest.update(chunk) - return digest.hexdigest() - - -def docker_image_id(image: str) -> str: - image_id = run(["docker", "image", "inspect", "--format", "{{.Id}}", image]).stdout.strip() - if not image_id.startswith("sha256:"): - raise ValueError("Docker did not return an image content digest") - return image_id - - -def docker_base(run_id: str, cidfile: Path) -> list[str]: - return [ - "docker", "run", "--cidfile", str(cidfile), "--label", f"{LABEL}={run_id}", - "--label", f"vkit.ledger.profile={PROFILE}", "--network=none", "--read-only", - "--cap-drop=ALL", "--security-opt=no-new-privileges", "--pids-limit=256", - "--memory=4g", "--cpus=2", "--ulimit", "nofile=1024:1024", - "--ulimit", "fsize=2147483648:2147483648", - "--tmpfs", "/tmp:rw,noexec,nosuid,nodev,size=128m", "--user", "65532:65532", - "--workdir", "/work", "--env", "HOME=/tmp", "--env", "TMPDIR=/tmp", - ] - - -def inspect_label(container_id: str) -> str: - return run(["docker", "inspect", "--format", f'{{{{ index .Config.Labels "{LABEL}" }}}}', container_id]).stdout.strip() - - -def remove_owned(run_id: str) -> list[str]: - result = run(["docker", "ps", "-aq", "--no-trunc", "--filter", f"label={LABEL}={run_id}"], check=False) - container_ids = [item for item in result.stdout.splitlines() if item] - removed = [] - for container_id in container_ids: - if inspect_label(container_id) != run_id: - raise RuntimeError(f"refusing to remove container with a different run label: {container_id}") - run(["docker", "rm", "-f", container_id], check=False) - removed.append(container_id) - remaining = run(["docker", "ps", "-aq", "--no-trunc", "--filter", f"label={LABEL}={run_id}"], check=False) - if remaining.stdout.strip(): - raise RuntimeError(f"owned containers remain for run {run_id}") - return removed - - -def cleanup_run(run_id: str, output: Path | None = None) -> list[str]: - removed = [] - for suffix in ("", "-probe", "-network", "-timeout", "-crash"): - removed.extend(remove_owned(run_id + suffix)) - removed.extend(remove_formal_owned(f"{run_id}-product")) - if output is not None and output.is_dir(): - from vkit.runtime.container import recover_attempt - - descriptors = list((output / "product/durable/project/.git/vkit/runs").glob("*/container-control/descriptor.json")) - descriptors += list((output / "product/recovery/runs").glob("*/container-control/descriptor.json")) - descriptors += list((output / "product/gate").glob("*/store/runs/*/container-control/descriptor.json")) - descriptors += list((output / "product/reuse").glob("*/project/.git/vkit/runs/*/container-control/descriptor.json")) - descriptors += list((output / "product/reuse").glob("*/runtime/container-control/descriptor.json")) - descriptors += list((output / "product/reuse/overhead").glob("direct-*/container-control/descriptor.json")) - descriptors += list((output / "product/refinement").glob("*/project/.git/vkit/runs/*/container-control/descriptor.json")) - descriptors += list((output / "product/refinement/runtime").glob("container-control/descriptor.json")) - for descriptor in descriptors: - recovery = recover_attempt(descriptor.parent.parent) - if recovery["status"] == "blocked": - raise RuntimeError(f"durable container cleanup failed: {recovery}") - return removed - - -def formal_label(container_id: str) -> str: - result = run(["docker", "inspect", "--format", f'{{{{ index .Config.Labels "{FORMAL_LABEL}" }}}}', - container_id], check=False) - return result.stdout.strip() - - -def remove_formal_owned(prefix: str) -> list[str]: - listing = run(["docker", "ps", "-aq", "--no-trunc", "--filter", f"label={FORMAL_LABEL}"], - check=False) - removed = [] - for container_id in listing.stdout.splitlines(): - if container_id and formal_label(container_id).startswith(prefix + "-"): - run(["docker", "rm", "-f", container_id], check=False) - removed.append(container_id) - remaining = run(["docker", "ps", "-aq", "--no-trunc", "--filter", f"label={FORMAL_LABEL}"], - check=False) - for container_id in remaining.stdout.splitlines(): - if container_id and formal_label(container_id).startswith(prefix + "-"): - raise RuntimeError(f"product verifier container remains for {prefix}") - return removed - - -def mount(source: Path, destination: str, readonly: bool = True) -> list[str]: - spec = f"type=bind,src={source.resolve()},dst={destination}" - return ["--mount", spec + (",readonly" if readonly else "")] - - -def stage_trusted(directory: Path, source: Path) -> tuple[Path, Path, dict[str, str]]: - trusted = directory / "trusted" - for relative in TRUSTED_FILES: - target = trusted / relative - target.parent.mkdir(parents=True, exist_ok=True) - shutil.copyfile(ROOT / relative, target) - from vkit.formal.ledger import render_expected - - expected = trusted / "examples/verus-qualification/expected.rs" - expected.parent.mkdir(parents=True, exist_ok=True) - expected.write_text(render_expected(product_component(3)), encoding="utf-8", newline="\n") - source_target = trusted / SOURCE_REL - source_target.parent.mkdir(parents=True, exist_ok=True) - source_target.touch() - captured_source = directory / "source" / "ledger.rs" - captured_source.parent.mkdir(parents=True) - shutil.copyfile(source, captured_source) - hashes = {relative.as_posix(): sha256(trusted / relative) for relative in TRUSTED_FILES} - hashes["examples/verus-qualification/expected.rs"] = sha256(expected) - hashes[SOURCE_REL.as_posix()] = sha256(captured_source) - return trusted, captured_source, hashes - - -def product_component(max_records: int): - from vkit.formal import ledger - from vkit.formal.policy import FormalComponent, LedgerBindings - - return FormalComponent( - id="resource-ledger", package=ledger.load_package().identity, - contract=ledger.CONTRACT, entry="candidate_api.rs", profile=ledger.PROFILE, - max_records=max_records, - bindings=LedgerBindings("new", "reserve", "release", "reserve_batch", - "apply_command", "run_commands"), - required=True, - ) - - -def weaken_reserve_contract(source: str) -> str: - start = source.index("pub fn reserve<") - body = source.index("\n {", start) - signature = source[start:body] - ensures = signature.index(" ensures\n") - return source[:start + ensures] + " ensures true,\n" + source[body:] - - -def run_product_probe(image_id: str, run_id: str, archive: Path, verus_root: Path, - rustup_home: Path, cargo_home: Path, directory: Path) -> dict: - from vkit.formal import ledger, verus - from vkit.core.outcome import Blocked, BlockedReason, Passed - from vkit.core.inputs import canonical_digest - - os.environ.update({ - "VKIT_VERUS_IMAGE": image_id, - "VKIT_VERUS_ARCHIVE": str(archive), - "VKIT_VERUS_ROOT": str(verus_root), - "VKIT_RUSTUP_HOME": str(rustup_home), - "VKIT_CARGO_HOME": str(cargo_home), - }) - component = product_component(3) - execution_identity = verus.resolve_execution(component) - source = (ROOT / "examples/verus-qualification/candidate_api.rs").read_text(encoding="utf-8") - cases = {} - directory.mkdir(parents=True, exist_ok=False) - - def execute_case(name: str, records: int, candidate_source: str): - snapshot = directory / "snapshots" / name - snapshot.mkdir(parents=True) - (snapshot / "candidate_api.rs").write_text(candidate_source, encoding="utf-8", newline="\n") - policy = product_component(records) - outcome, metadata = verus.execute_formal( - policy, snapshot, directory / f"{run_id}-product-{name}", - canonical_digest(execution_identity["semantic"]), should_cancel=lambda: False - ) - cases[name] = {"outcome": outcome.to_json(), "metadata": metadata} - return outcome, metadata - - for name, records in (("positive_n3", 3), ("positive_n5", 5)): - outcome, metadata = execute_case(name, records, source) - expected = list(ledger.obligation_ids(product_component(records))) - outcome_ids = [scenario.scenario_id for scenario in outcome.scenarios] if isinstance(outcome, Passed) else [] - if (not isinstance(outcome, Passed) or len(outcome.scenarios) != 7 - or outcome_ids != expected or any(not scenario.passed for scenario in outcome.scenarios) - or metadata.get("obligations") != expected - or metadata.get("method") != "verus_source" - or metadata.get("assurance") != "trusted_engine" - or metadata.get("category") != "source_verification" - or metadata.get("scope") != "required_api" - or len(metadata.get("evidence", [])) != 8 - or metadata.get("container", {}).get("removed") is not True): - raise RuntimeError(f"product Verus probe failed for {name}: {outcome.to_json()}") - - weakened, _ = execute_case("weakened_reserve", 3, weaken_reserve_contract(source)) - if not isinstance(weakened, Blocked) or weakened.reason != BlockedReason.FORMAL_OBLIGATION: - raise RuntimeError(f"product Verus negative probe did not block on the obligation: {weakened.to_json()}") - durable = run_durable_probe(directory / "durable", source, execution_identity) - recovery = run_recovery_probe(directory / "recovery", image_id, run_id) - gate = run_gate_probe(directory / "gate", source, image_id) - from qualify_ledger_reuse import qualify - - reuse = qualify(directory / "reuse", source, execution_identity) - from check_ledger_refinement import qualify_product - - refinement = qualify_product(directory / "refinement") - return {"passed": True, "image_id": image_id, "cases": cases, - "durable": durable, "recovery": recovery, "gate": gate, "reuse": reuse, - "refinement": refinement} - - -def run_gate_probe(directory: Path, source: str, image_id: str) -> dict: - from vkit.formal.service import resolve_commit - from vkit.runtime.paths import open_project - - root = directory / "project" - (root / "verification").mkdir(parents=True) - source = source.replace("verus! {", "verus! {\n const ADJUST: bool = false;", 1) - source = source.rsplit("}", 1)[0] + " const DELTA: u32 = 0;\n}\n" - source = source.replace(" ledger::ledger_api::reserve(input, id, owner, amount)", - " let amount = if ADJUST && DELTA > 0 && amount > 0 { amount - 1 } else { amount };\n" - " ledger::ledger_api::reserve(input, id, owner, amount)", 1) - (root / "candidate_api.rs").write_text(source, encoding="utf-8") - driver = '''import json, os, pathlib, socket, sys -assert "VKIT_QUALIFICATION_SECRET" not in os.environ -assert not pathlib.Path("/output/../job.json").exists() -try: - pathlib.Path("candidate_api.rs").write_text("must not be writable") -except OSError: - pass -else: - raise AssertionError("candidate mount is writable") -try: - socket.create_connection(("1.1.1.1", 443), timeout=0.2) -except OSError: - pass -else: - raise AssertionError("network is available") -pathlib.Path(sys.argv[1]).write_text(json.dumps({"schema_version":1,"scenarios":[ - {"id":"isolated","result":"PASS","observation":"candidate read-only; network and host secrets absent"}]})) -''' - check = {"id": "isolation", "kind": "scenario", "timeout_seconds": 30, - "artifact": "result.json", "command": ["{{python}}", "-I", "-c", driver, "{{run_dir}}/result.json"], - "required_scenarios": ["isolated"], "inputs": ["candidate_api.rs"], - "subject": {"paths": ["candidate_api.rs"], "digest": None}, "claim_id": "isolation"} - (root / "verification/manifest.json").write_text(json.dumps({ - "schema_version": 3, "checks": [check], - "formal": {"components": [product_component(3).to_json()]}}), encoding="utf-8") - - def git(*args): - return run(["git", "-C", str(root), "-c", "user.name=VKit CI", "-c", "user.email=ci@vkit.invalid", *args]) - - git("init", "-q") - git("add", ".") - git("commit", "-qm", "target policy and feature interaction") - project = open_project(root) - target = resolve_commit(project, "HEAD") - git("checkout", "-qb", "branch-a") - (root / "candidate_api.rs").write_text(source.replace("ADJUST: bool = false", "ADJUST: bool = true"), encoding="utf-8") - (root / "verification/manifest.json").unlink() - git("add", "-u") - git("commit", "-qm", "enable adjustment and delete candidate policy") - branch_a = resolve_commit(project, "HEAD") - git("checkout", "-qb", "branch-b", target) - (root / "candidate_api.rs").write_text(source.replace("DELTA: u32 = 0", "DELTA: u32 = 1"), encoding="utf-8") - git("add", "-u") - git("commit", "-qm", "change adjustment amount") - branch_b = resolve_commit(project, "HEAD") - git("checkout", "branch-a") - git("merge", "--no-ff", "-qm", "combined candidate", "branch-b") - combined = resolve_commit(project, "HEAD") - os.environ["VKIT_CI_IMAGE"] = image_id - os.environ["VKIT_QUALIFICATION_SECRET"] = "host-only-control" - reports = {} - try: - for name, oid in (("branch_a", branch_a), ("branch_b", branch_b), ("combined", combined)): - invocation = run([sys.executable, "-m", "vkit.cli", "gate", "--project", str(project.root), - "--candidate", oid, "--target", target, "--output", str(directory / name), "--json"], - timeout=900, check=False) - report = json.loads(invocation.stdout) - expected = "BLOCKED" if name == "combined" else "READY" - if invocation.returncode != (3 if name == "combined" else 0) or report["verdict"] != expected or len(report["checks"]) != 2: - raise RuntimeError(f"gate control {name} failed: {report['checks']}") - if any(not c["receipt_valid"] for c in report["checks"]): - raise RuntimeError(f"gate control {name} has invalid receipts") - reports[name] = {"candidate": oid, "verdict": report["verdict"], "checks": report["checks"]} - formal = next(c for c in reports["combined"]["checks"] if c["kind"] == "formal_goal") - if formal["outcome"].get("reason") != "formal_obligation": - raise RuntimeError("combined candidate did not fail on its formal obligation") - finally: - os.environ.pop("VKIT_QUALIFICATION_SECRET", None) - return {"passed": True, "target": target, "candidate_policy_deleted": True, "cases": reports} - - -def run_recovery_probe(directory: Path, image_id: str, qualification_id: str) -> dict: - from vkit.runtime.container import control_path, recover_attempt - from vkit.core.store import Store - - directory.mkdir() - attempt = qualification_id + "-recovery" - store = Store(directory) - run_dir = store.run_dir(attempt) - program = """import sys -from pathlib import Path -from vkit.runtime.container import run_container -from vkit.core.store import Store -store, attempt, image = Store(Path(sys.argv[1])), sys.argv[2], sys.argv[3] -with store.hold(attempt): - store.save({'run_id': attempt, 'state': 'running'}) - run_container(image=image, run_id=attempt+'-owned', options=['--network=none', '--read-only'], - command=['sleep', '60'], run_dir=store.run_dir(attempt), - timeout_seconds=90, should_cancel=lambda: False) -""" - with (directory / "worker.log").open("wb") as log: - worker = subprocess.Popen([sys.executable, "-c", program, str(directory), attempt, image_id], - stdout=log, stderr=subprocess.STDOUT, **hidden_window()) - try: - cid_path = control_path(run_dir).parent / "container.cid" - deadline = time.monotonic() + 30 - cid = None - while time.monotonic() < deadline and worker.poll() is None: - if cid_path.is_file(): - cid = cid_path.read_text(encoding="ascii").strip() - running = run(["docker", "inspect", "--format", "{{.State.Running}}", cid], check=False) - if running.returncode == 0 and running.stdout.strip() == "true": - break - time.sleep(0.1) - else: - raise RuntimeError("recovery probe did not reach a running container") - worker.kill() - worker.wait(timeout=10) - record = store.record(attempt) - if (record["state"] != "interrupted" or record["container_cleanup"]["status"] != "removed" - or run(["docker", "inspect", cid], check=False).returncode == 0): - raise RuntimeError(f"killed-worker container recovery failed: {record}") - return {"passed": True, "container_id": cid, "state": record["state"], - "cleanup": record["container_cleanup"]} - finally: - if worker.poll() is None: - worker.kill() - worker.wait(timeout=10) - cleanup = recover_attempt(run_dir) - if cleanup["status"] == "blocked": - raise RuntimeError(f"recovery probe cleanup failed: {cleanup}") - - -def run_durable_probe(directory: Path, source: str, identity: dict) -> dict: - from vkit.core import evidence - from vkit.core import jobs - from vkit.change.requests import GitCommit, PackageVerificationRequest - from vkit.formal.service import resolve_commit - from vkit.core.inputs import canonical_digest - from vkit.core.manifest import parse_manifest - from vkit.runtime.paths import open_project - from vkit.core.query import open_context - from vkit.core.store import Store, now - - root = directory / "project" - (root / "verification").mkdir(parents=True) - (root / "candidate_api.rs").write_text(source, encoding="utf-8", newline="\n") - component = product_component(3) - (root / "verification/manifest.json").write_text(json.dumps({ - "schema_version": 3, "checks": [], "formal": {"components": [component.to_json()]}}), encoding="utf-8") - for arguments in (["init", "-q"], ["add", "."], - ["-c", "user.name=VKit qualification", "-c", "user.email=ci@vkit.invalid", "commit", "-qm", "candidate"]): - run(["git", "-C", str(root), *arguments]) - project = open_project(root) - manifest, store = parse_manifest(project), Store.of(project) - oid = resolve_commit(project, "HEAD") - store.approve({component.digest: {"kind": "formal_policy", "policy_sha256": component.digest, - "package_sha256": component.package.sha256, - "checker_sha256": canonical_digest(identity["semantic"]), "accepted_at": now()}}) - request = PackageVerificationRequest(component.claim, GitCommit(oid)) - submitted = jobs.submit_formal(project, request, component, canonical_digest(identity["semantic"]), store=store) - first = jobs.wait(store, submitted["run_id"], 900) - from vkit.formal.service import verify - - reused = verify(open_context(root), {**request.semantic_json(), "reuse": True}) - if reused["run_id"] != first["run_id"]: - raise RuntimeError("identical accepted formal evidence was not reused") - compilation = first["verification"]["compilation"] - coverage = first["verification"]["coverage"] - if (compilation["status"] != "trusted_compilation" - or compilation["translation_validation"] != "not_provided" - or compilation["observations"]["assurance"] != "empirical" - or len(coverage["claims"]) != 6): - raise RuntimeError("compiled correspondence or claim coverage was misclassified") - bundle = directory / "bundle" - evidence.export(store, first["run_id"], bundle) - portable = directory / "portable-bundle" - run([sys.executable, "-m", "vkit.cli", "evidence", "export", "--project", str(root), - "--run", first["run_id"], "--output", str(portable), "--include-assets", "--json"], timeout=900) - (root / "candidate_api.rs").write_text("deliberately broken live checkout", encoding="utf-8") - retried = jobs.wait(store, jobs.retry(project, first["run_id"], store=store)["run_id"], 900) - replayed = jobs.wait(store, jobs.replay(project, manifest, bundle, store=store)["run_id"], 900) - for record in (first, retried, replayed): - if (record["state"] != "done" or record["outcome"]["result"] != "PASS" - or record["job_id"] != first["job_id"] - or record["assurance"] != "trusted_engine" or record["method"] != "verus_source" - or not evidence.validate_record(record, store.run_dir(record["run_id"]))): - raise RuntimeError(f"durable product verification failed: {record}") - if len({record["run_id"] for record in (first, retried, replayed)}) != 3: - raise RuntimeError("retry and replay did not create distinct attempts") - unavailable = [] - try: - for original in (Path(value) for value in identity["paths"].values()): - backup = original.with_name(original.name + ".capsule-unavailable") - if backup.exists(): - raise RuntimeError(f"portable replay backup already exists: {backup}") - original.rename(backup) - unavailable.append((original, backup)) - run(["docker", "image", "rm", identity["semantic"]["image_id"]]) - if run(["docker", "image", "inspect", identity["semantic"]["image_id"]], check=False).returncode == 0: - raise RuntimeError("portable replay control did not remove its exact image") - from vkit.mcp import Server - - restored_summary, error = Server(root).call("evidence_replay", { - "bundle": str(portable), "restore_assets": True, "wait_seconds": 0, - }) - if error: - raise RuntimeError(f"MCP portable replay failed: {restored_summary}") - restored = jobs.wait(store, restored_summary["run_id"], 900) - restored_retry = jobs.wait(store, jobs.retry(project, restored["run_id"], store=store)["run_id"], 900) - for record in (restored, restored_retry): - if (record["outcome"]["result"] != "PASS" or record["job_id"] != first["job_id"] - or not evidence.validate_record(record, store.run_dir(record["run_id"]))): - raise RuntimeError("portable replay or its retry did not establish fresh intact evidence") - finally: - for original, backup in reversed(unavailable): - backup.rename(original) - image_archive = portable / "replay/assets/image.tar" - size = image_archive.stat().st_size - with image_archive.open("ab") as stream: - stream.write(b"tampered") - try: - jobs.replay(project, manifest, portable, store=store, restore_assets=True) - except ValueError: - asset_tamper_rejected = True - else: - raise RuntimeError("portable replay accepted altered image bytes") - finally: - with image_archive.open("r+b") as stream: - stream.truncate(size) - vir = bundle / "formal-output/libcandidate_api.rlib" - vir.write_bytes(vir.read_bytes() + b"tampered") - try: - jobs.replay(project, manifest, bundle, store=store) - except ValueError: - tamper_rejected = True - else: - raise RuntimeError("replay accepted changed verifier artifacts") - return {"job_id": first["job_id"], "candidate": oid, "tamper_rejected": tamper_rejected, - "same_job_reused": True, "portable_replay": True, "portable_retry": True, - "asset_tamper_rejected": asset_tamper_rejected, - "attempts": [{"run_id": record["run_id"], "receipt": record["receipt"]} - for record in (first, retried, replayed, restored, restored_retry)]} - - -def container_command(image_id: str, base: list[str], trusted: Path, source: Path, archive: Path, - verus_root: Path, rustup_home: Path, cargo_home: Path, - output: Path | None, command: list[str]) -> list[str]: - return [ - *base, - *mount(trusted, "/trusted"), - *mount(source, f"/trusted/{SOURCE_REL.as_posix()}"), - *mount(archive, f"/assets/{archive.name}"), - *mount(verus_root, "/assets/verus"), - *mount(rustup_home, "/assets/rustup"), - *mount(cargo_home, "/assets/cargo"), - *([] if output is None else mount(output, "/output", readonly=False)), - "--env", "RUSTUP_HOME=/assets/rustup", "--env", "CARGO_HOME=/assets/cargo", - "--env", "PATH=/assets/cargo/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", - image_id, *command, - ] - - -def execute(image_id: str, run_id: str, cidfile: Path, command: list[str], - log_path: Path, timeout: float, output: Path | None = None) -> dict: - process = None - container_id = None - start = time.monotonic() - timeout_started = None - owned_label = False - removed = False - output_retained = None - previous_handlers = {sig: signal.getsignal(sig) for sig in (signal.SIGINT, signal.SIGTERM)} - - def terminate(signum, frame): - if cidfile.is_file(): - cid = cidfile.read_text(encoding="utf-8").strip() - if cid and inspect_label(cid) == run_id: - run(["docker", "stop", "--time", "2", cid], check=False) - run(["docker", "kill", cid], check=False) - raise KeyboardInterrupt(f"received signal {signum}") - - for signum in previous_handlers: - signal.signal(signum, terminate) - try: - with log_path.open("w", encoding="utf-8") as log: - process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, - **hidden_window()) - try: - code = process.wait(timeout=timeout) - except subprocess.TimeoutExpired: - timeout_started = time.monotonic() - if cidfile.is_file(): - container_id = cidfile.read_text(encoding="utf-8").strip() - if container_id: - owned_label = inspect_label(container_id) == run_id - if container_id and owned_label: - run(["docker", "stop", "--time", "2", container_id], check=False) - run(["docker", "kill", container_id], check=False) - process.kill() - process.wait() - code = None - finally: - if process is not None and process.poll() is None: - process.kill() - process.wait() - for signum, handler in previous_handlers.items(): - signal.signal(signum, handler) - if cidfile.is_file(): - container_id = cidfile.read_text(encoding="utf-8").strip() - if container_id and inspect_label(container_id) == run_id: - owned_label = True - if output is not None: - output_retained = output.is_dir() and any(output.iterdir()) - run(["docker", "rm", "-f", container_id], check=False) - removed = run(["docker", "inspect", container_id], check=False).returncode != 0 - return {"returncode": code, "container_id": container_id, "label_owned": owned_label, - "seconds": round(time.monotonic() - start, 3), "log": log_path.name, - "timed_out": code is None, "container_removed": removed, - "output_retained": output_retained, - "cancel_seconds": round(time.monotonic() - timeout_started, 3) if timeout_started else None} - - -def run_controls(image_id: str, run_id: str, cid_dir: Path, trusted: Path, source: Path, - archive: Path, verus_root: Path, rustup_home: Path, cargo_home: Path, - output: Path) -> dict: - controls = {} - probe_base = docker_base(f"{run_id}-probe", cid_dir / "probe.cid") - ro_cmd = container_command(image_id, probe_base, trusted, source, archive, verus_root, - rustup_home, cargo_home, None, - ["python3", "-c", f"from pathlib import Path; Path('/trusted/{SOURCE_REL.as_posix()}').write_text('changed')"]) - ro_result = run(ro_cmd, check=False) - controls["source_read_only"] = ro_result.returncode != 0 and "Read-only file system" in ro_result.stderr + ro_result.stdout - - net_cmd = container_command(image_id, docker_base(f"{run_id}-network", cid_dir / "network.cid"), - trusted, source, archive, verus_root, rustup_home, cargo_home, None, - ["python3", "-c", "import errno,socket,sys\ntry:\n socket.create_connection(('1.1.1.1', 53), timeout=2)\nexcept OSError as error:\n if error.errno != errno.ENETUNREACH:\n raise\n print('network_denied:ENETUNREACH')\n sys.exit(0)\nsys.exit(2)"]) - net_result = run(net_cmd, timeout=10, check=False) - network_cidfile = cid_dir / "network.cid" - network_cid = network_cidfile.read_text(encoding="utf-8").strip() if network_cidfile.is_file() else "" - network_mode = run(["docker", "inspect", "--format", "{{.HostConfig.NetworkMode}}", network_cid], - check=False).stdout.strip() if network_cid else "" - controls["network_disabled"] = (net_result.returncode == 0 - and "network_denied:ENETUNREACH" in net_result.stdout - and network_mode == "none" - and inspect_label(network_cid) == f"{run_id}-network") - controls["source_probe_removed"] = bool(remove_owned(f"{run_id}-probe")) - controls["network_probe_removed"] = network_cid in remove_owned(f"{run_id}-network") - - timeout_id = f"{run_id}-timeout" - timeout_cidfile = cid_dir / "timeout.cid" - timeout_execution = execute(image_id, timeout_id, timeout_cidfile, - [*docker_base(timeout_id, timeout_cidfile), image_id, "sleep", "60"], - cid_dir / "timeout.log", 1) - controls["timeout_cid_external"] = timeout_cidfile.parent != output and bool(timeout_execution["container_id"]) - controls["timeout_label_owned"] = timeout_execution["label_owned"] - controls["timeout_observed"] = timeout_execution["timed_out"] - controls["timeout_removed"] = timeout_execution["container_removed"] - controls["cancel_seconds"] = timeout_execution["cancel_seconds"] - controls["cancel_under_five_seconds"] = bool(controls["cancel_seconds"] is not None - and controls["cancel_seconds"] <= 5) - - crash_id = f"{run_id}-crash" - crash_cidfile = cid_dir / "crash.cid" - crash_cmd = [*docker_base(crash_id, crash_cidfile), "--detach", image_id, - "python3", "-c", "raise SystemExit(23)"] - run(crash_cmd) - crash_cid = crash_cidfile.read_text(encoding="utf-8").strip() - crash_exit = run(["docker", "wait", crash_cid]).stdout.strip() - controls["crash_exit_seen"] = crash_exit == "23" - controls["crash_label_owned"] = inspect_label(crash_cid) == crash_id - controls["crash_removed"] = crash_cid in remove_owned(crash_id) - controls["all_passed"] = all(value for key, value in controls.items() - if key not in {"all_passed", "cancel_seconds"}) - return controls - - -def cleanup(args: argparse.Namespace) -> int: - removed = cleanup_run(args.cleanup_run_id, args.output) - print(json.dumps({"run_id": args.cleanup_run_id, "removed": removed})) - return 0 - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--image", required=True) - parser.add_argument("--archive", type=Path) - parser.add_argument("--verus-root", type=Path) - parser.add_argument("--rustup-home", type=Path) - parser.add_argument("--cargo-home", type=Path) - parser.add_argument("--output", type=Path) - parser.add_argument("--timeout", type=int, default=780) - parser.add_argument("--run-id", default=f"{os.environ.get('GITHUB_RUN_ID', 'local')}-{uuid.uuid4().hex[:12]}") - parser.add_argument("--cleanup-run-id") - args = parser.parse_args() - if args.cleanup_run_id: - return cleanup(args) - required = (args.archive, args.verus_root, args.rustup_home, args.cargo_home, args.output) - if any(path is None for path in required): - parser.error("archive, verus-root, rustup-home, cargo-home and output are required") - if os.name != "posix" or os.geteuid() == 0: - raise RuntimeError("sealed ledger qualification requires a non-root Linux Docker host") - if not (args.cargo_home / "bin/rustup").is_file(): - raise FileNotFoundError("the isolated Rust toolchain must include cargo/bin/rustup") - runner_temp = Path(os.environ["RUNNER_TEMP"]).resolve() - assets = (args.archive, args.verus_root, args.rustup_home, args.cargo_home) - if any(runner_temp not in path.resolve().parents for path in assets): - raise RuntimeError("container tool assets must be staged under RUNNER_TEMP, outside the host home") - args.output.mkdir(parents=True, exist_ok=False) - os.chmod(args.output, 0o700) - candidate_output = args.output / "candidate-output" - candidate_output.mkdir() - os.chmod(candidate_output, 0o777) - image_id = docker_image_id(args.image) - run_id = args.run_id - cid_dir = args.output.parent / f"{args.output.name}-control" - cid_dir.mkdir(parents=True, exist_ok=True) - trusted, source, input_hashes = stage_trusted(cid_dir, ROOT / SOURCE_REL) - report = { - "profile": PROFILE, - "image": {"reference": args.image, "id": image_id}, - "tool_assets_root": str(runner_temp), - "dockerfile_sha256": sha256(ROOT / "examples/verus-qualification/container/Dockerfile"), - "orchestrator_sha256": sha256(Path(__file__).resolve()), - "run_id": run_id, - "input_sha256": input_hashes, - "mounts": [ - {"target": "/trusted", "read_only": True}, - {"target": f"/trusted/{SOURCE_REL.as_posix()}", "read_only": True}, - {"target": f"/assets/{args.archive.name}", "read_only": True}, - {"target": "/assets/verus", "read_only": True}, - {"target": "/assets/rustup", "read_only": True}, - {"target": "/assets/cargo", "read_only": True}, - {"target": "/tmp", "kind": "tmpfs", "size": "128 MiB", "exec": False}, - {"target": "/output", "host_source": str(candidate_output), - "kind": "private runner-temp bind", "read_only": False, "exec": True}, - ], - "container_policy": {"network": "none", "user": "65532:65532", "cap_drop": "ALL", - "no_new_privileges": True, "rootfs_read_only": True, - "tmpfs": {"/tmp": {"size": "128 MiB", "exec": False}}, - "output_file_size_limit_bytes": 2147483648, - "memory": "4 GiB", "cpus": 2, "pids": 256, - "home_token_socket_mounts": []}, - "checks": {}, - } - try: - controls = run_controls(image_id, run_id, cid_dir, trusted, source, args.archive, - args.verus_root, args.rustup_home, args.cargo_home, args.output) - report["checks"].update(controls) - if not controls["all_passed"]: - raise RuntimeError("container isolation negative probe failed") - cidfile = cid_dir / "qualification.cid" - command = container_command(image_id, docker_base(run_id, cidfile), trusted, source, - args.archive, args.verus_root, args.rustup_home, - args.cargo_home, candidate_output, - ["python3", "/trusted/formal/checks/check_verus_ledger.py", - "--verus-root", "/assets/verus", - "--archive", f"/assets/{args.archive.name}", - "--output", "/output/evidence"]) - execution = execute(image_id, run_id, cidfile, command, - args.output / "container.log", args.timeout, candidate_output) - report["execution"] = execution - evidence = candidate_output / "evidence/report.json" - report["checks"]["comparison_passed"] = False - evidence_report = json.loads(evidence.read_text(encoding="utf-8")) if evidence.is_file() else {} - report["checks"]["comparison_passed"] = evidence_report.get("comparison_passed") is True - report["driver_scope"] = evidence_report.get("scope") - report["mutation_controls"] = evidence_report.get("mutation_controls", []) - report["semantic_checks"] = evidence_report.get("semantic_checks", []) - report["semantic_controls"] = evidence_report.get("semantic_controls", []) - report["package_contracts"] = evidence_report.get("package_contracts") - report["checks"]["package_contracts_passed"] = ( - evidence_report.get("package_contracts", {}).get("passed") is True) - report["package_identity"] = evidence_report.get("package_identity") - report["package_identity_sha256"] = evidence_report.get("package_identity_sha256") - report["tool_identity_sha256"] = evidence_report.get("tool_identity_sha256") - report["checks"]["mutation_controls_passed"] = ( - evidence_report.get("mutation_controls_passed") is True) - report["checks"]["semantic_checks_passed"] = ( - evidence_report.get("semantic_checks_passed") is True) - if (execution["returncode"] != 0 or execution["timed_out"] - or not execution["output_retained"] or not evidence.is_file()): - raise RuntimeError("sealed Verus qualification failed") - checks = evidence_report["checks"] - rust_log = next(item["log"] for item in checks if item["name"] == "rust_version") - z3_log = next(item["log"] for item in checks if item["name"] == "solver_version") - rust_text = (candidate_output / "evidence" / rust_log).read_text(encoding="utf-8", errors="replace") - z3_text = (candidate_output / "evidence" / z3_log).read_text(encoding="utf-8", errors="replace") - report["checks"]["rust_1_99_1"] = "rustc 1.99.1" in rust_text - report["checks"]["z3_4_16_0"] = "Z3 version 4.16.0" in z3_text - report["product"] = run_product_probe(image_id, run_id, args.archive, args.verus_root, - args.rustup_home, args.cargo_home, args.output / "product") - report["checks"]["product_passed"] = report["product"]["passed"] - report["qualification_passed"] = all(report["checks"][name] for name in - ("comparison_passed", "mutation_controls_passed", - "semantic_checks_passed", - "rust_1_99_1", "z3_4_16_0", "product_passed", "package_contracts_passed")) - except (OSError, RuntimeError, ValueError, KeyError, StopIteration, - subprocess.SubprocessError, KeyboardInterrupt) as error: - report["error"] = str(error) - report["qualification_passed"] = False - finally: - try: - report["cleanup"] = {"removed": cleanup_run(run_id, args.output), "remaining": False} - except (OSError, RuntimeError, subprocess.SubprocessError) as error: - report["cleanup"] = {"remaining": True, "error": str(error)} - report["qualification_passed"] = False - (args.output / "container-qualification.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") - print(json.dumps({"qualification_passed": report["qualification_passed"], - "image_id": image_id, "run_id": run_id}, indent=2)) - return 0 if report["qualification_passed"] else 1 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/formal/checks/check_ledger_refinement.py b/formal/checks/check_ledger_refinement.py deleted file mode 100644 index c55cf6d..0000000 --- a/formal/checks/check_ledger_refinement.py +++ /dev/null @@ -1,65 +0,0 @@ -"""Check the ledger contract across native and split-column representations.""" -from __future__ import annotations - -import json -from pathlib import Path -from vkit.formal import ledger -from vkit.formal.policy import FormalComponent, LedgerBindings -from vkit.core.inputs import canonical_digest - -ROOT = Path(__file__).resolve().parents[2] - - -def component(*, columns: bool = False) -> FormalComponent: - package = ledger.load_package() - prefix = "columns::" if columns else "" - return FormalComponent( - "refinement", package.identity, ledger.CONTRACT, "candidate_api.rs", ledger.PROFILE, 3, - LedgerBindings(**{name: prefix + name for name in - ("new", "reserve", "release", "reserve_batch", "apply_command", "run_commands")}), - True, "columns::Columns" if columns else None, - ) - - -def qualify_product(directory: Path) -> dict: - from qualify_ledger_reuse import approve, project_for, runtime_fixture - from vkit.core import evidence - from vkit.formal import verus - from vkit.change.requests import GitCommit, PackageVerificationRequest - from vkit.core.runner import execute, prepare_formal - from vkit.core.store import Store - - policy = component(columns=True) - identity = verus.resolve_execution(policy) - source = (ROOT / "examples/ledger-refinement/columns.rs").read_text(encoding="utf-8") - broken = source.replace("owner: input.values[i].0", "owner: 0", 1) - if broken == source: - raise ValueError("refinement negative control no longer matches") - cases = [] - for name, text, expected in (("columns", source, "PASS"), ("broken_conversion", broken, "BLOCKED")): - project, commit = project_for(directory / name / "project", policy, text) - store = Store.of(project) - approve(store, policy, identity) - record = prepare_formal(project, PackageVerificationRequest(policy.claim, GitCommit(commit)), policy, - canonical_digest(identity["semantic"]), store=store) - record = execute(project, record["run_id"], store=store) - valid = evidence.validate_record(record, store.run_dir(record["run_id"])) - actual = record["outcome"] - if (not valid or actual["result"] != expected - or (expected == "BLOCKED" and actual.get("reason") != "formal_obligation")): - raise RuntimeError(f"refinement qualification failed for {name}: {actual}") - item = {"name": name, "job_id": record["job_id"], "run_id": record["run_id"], - "outcome": actual, "receipt_valid": valid, "claim_outcome": record["claim_outcome"]} - if name == "columns": - fixture = json.loads((ROOT / "examples/ledger-reuse/fixtures.json").read_text())[0] - fixture["namespace"] = "columns" - fixture["id"] = "columns" - item["runtime"] = runtime_fixture(fixture, policy, store.run_dir(record["run_id"]) / "formal-output", - identity, directory / "runtime") - cases.append(item) - report = {"passed": True, "scope": "required_api", "assurance": "trusted_engine", - "representation": policy.representation, - "limitations": ["ordered slot abstraction retained", "verified conversions cost O(N)", - "resource aborts remain possible", "no concurrency guarantee"], "cases": cases} - (directory / "refinement.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") - return report diff --git a/formal/checks/check_lifecycle.py b/formal/checks/check_lifecycle.py deleted file mode 100644 index 8b7c43b..0000000 --- a/formal/checks/check_lifecycle.py +++ /dev/null @@ -1,378 +0,0 @@ -from __future__ import annotations - -import argparse -import hashlib -import json -import os -import shutil -import signal -import subprocess -import sys -import tempfile -import threading -import time -from pathlib import Path -from typing import Any - -ROOT = Path(__file__).resolve().parents[2] -CHECK_ID = "lifecycle-model" -MODEL_REL = Path("formal/models/lifecycle/Attempts.tla") -CONFIG_REL = Path("formal/models/lifecycle/Attempts.cfg") -PROPERTIES = [ - "TypeOK", - "NoFalsePass", - "TerminalHasResult", - "InterruptedHasNoResult", - "IdentityPinned", - "PublishedAttemptComplete", -] - - -def _environment() -> dict[str, str]: - env = dict(os.environ) - java_home = Path(env.get("JAVA_HOME", "")) - java_bin = java_home / "bin" - if (java_bin / ("java.exe" if os.name == "nt" else "java")).is_file(): - env["PATH"] = str(java_bin) + os.pathsep + env.get("PATH", "") - env["PYTHONPATH"] = os.pathsep.join( - [str(ROOT / "src"), *filter(None, env.get("PYTHONPATH", "").split(os.pathsep))] - ) - os.environ["PYTHONPATH"] = env["PYTHONPATH"] - os.environ["PATH"] = env["PATH"] - sys.path.insert(0, str(ROOT / "src")) - import vkit - - if Path(vkit.__file__).resolve().parent != ROOT / "src/vkit": - raise RuntimeError("lifecycle qualification requires VKit from this checkout; restart with its src on PYTHONPATH") - return env - - -def _hidden_window() -> dict[str, Any]: - if os.name != "nt": - return {} - from vkit.runtime.nowindow import hidden_window - - return hidden_window() - - -def _run(argv: list[str], cwd: Path, env: dict[str, str], *, expected: frozenset[int] = frozenset({0})) -> dict[str, Any]: - done = subprocess.run( - argv, cwd=cwd, env=env, capture_output=True, text=True, check=False, - timeout=240, **_hidden_window(), - ) - if done.returncode not in expected: - raise RuntimeError( - f"command exited {done.returncode}, expected {sorted(expected)}: {argv!r}\n" - f"stdout:\n{done.stdout}\nstderr:\n{done.stderr}" - ) - try: - body = json.loads(done.stdout) if done.stdout.strip().startswith("{") else None - except json.JSONDecodeError: - body = None - return {"returncode": done.returncode, "stdout": done.stdout, - "stderr": done.stderr, "body": body} - - -def _cli(project: Path, env: dict[str, str], *args: str, - expected: frozenset[int] = frozenset({0})) -> dict[str, Any]: - return _run( - [sys.executable, "-m", "vkit.cli", *args, "--project", str(project), "--json"], - project, env, expected=expected, - ) - - -def _manifest(config: str) -> dict[str, Any]: - raw = json.loads((ROOT / "verification/manifest.json").read_text(encoding="utf-8")) - check = next(item for item in raw["checks"] if item["id"] == CHECK_ID) - check["config"] = config - check["inputs"] = [MODEL_REL.as_posix(), config] - check["subject"]["paths"] = [MODEL_REL.as_posix(), config] - check["properties"] = PROPERTIES - raw["checks"] = [check] - return raw - - -def _new_project(directory: Path, env: dict[str, str], *, wrong_pass: bool = False) -> Path: - directory.mkdir(parents=True, exist_ok=False) - model = (ROOT / MODEL_REL).read_text(encoding="utf-8") - config = (ROOT / CONFIG_REL).read_text(encoding="utf-8") - if wrong_pass: - config = config.replace("InjectFalsePass = FALSE", "InjectFalsePass = TRUE") - model_path = directory / MODEL_REL - config_path = directory / CONFIG_REL - model_path.parent.mkdir(parents=True) - model_path.write_text(model, encoding="utf-8", newline="\n") - config_path.write_text(config, encoding="utf-8", newline="\n") - (directory / "verification").mkdir(exist_ok=True) - (directory / "verification/manifest.json").write_text( - json.dumps(_manifest(CONFIG_REL.as_posix()), indent=2) + "\n", - encoding="utf-8", - ) - _run(["git", "init", "-q"], directory, env) - _run(["git", "-c", "user.name=VKit Lifecycle", "-c", "user.email=lifecycle@vkit.invalid", - "add", "."], directory, env) - _run(["git", "-c", "user.name=VKit Lifecycle", "-c", "user.email=lifecycle@vkit.invalid", - "commit", "-qm", "lifecycle fixture"], directory, env) - accepted = _cli(directory, env, "accept", "--yes") - if accepted["returncode"] != 0: - raise RuntimeError(f"lifecycle fixture could not accept its check: {accepted['stdout']} {accepted['stderr']}") - return directory - - -def _run_model_case(directory: Path, env: dict[str, str], expected: str) -> dict[str, Any]: - result = _cli(directory, env, "check", "run", "--check", CHECK_ID, - expected=frozenset({0, 1, 3})) - body = result["body"] - if not isinstance(body, dict): - raise RuntimeError(f"lifecycle checker returned no JSON record: {result['stdout']} {result['stderr']}") - records = body.get("runs") or ([body] if body.get("run_id") else []) - record = records[0] if records else body - actual = (record.get("outcome") or {}).get("result") - if actual != expected: - raise RuntimeError(f"lifecycle model result was {actual!r}, expected {expected!r}: {record!r}") - return record - - -def _wait_state(store: Any, run_id: str, state: str, timeout: float = 20) -> dict[str, Any]: - deadline = time.monotonic() + timeout - latest = None - while time.monotonic() < deadline: - latest = store.record(run_id) - if latest and latest["state"] == state: - return latest - if latest and latest["state"] in {"done", "interrupted"} and latest["state"] != state: - break - time.sleep(0.02) - raise RuntimeError(f"attempt {run_id} did not reach {state!r}: {latest!r}") - - -def _stop_worker(run_id: str, store: Any, env: dict[str, str]) -> None: - from vkit.core.store import _process_alive, read_json - - worker = read_json(store.run_dir(run_id) / "worker.json") - if not worker or not isinstance(worker.get("pid"), int): - raise RuntimeError(f"attempt {run_id} has no observed worker process") - pid = worker["pid"] - if os.name == "nt": - done = subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"], - capture_output=True, text=True, check=False, env=env, - timeout=15, **_hidden_window()) - if done.returncode != 0 and _process_alive(pid): - raise RuntimeError(f"could not stop worker {pid}: {done.stdout} {done.stderr}") - else: - os.killpg(pid, signal.SIGKILL) - - -def _wait_started(store: Any, run_id: str, timeout: float = 20) -> None: - deadline = time.monotonic() + timeout - path = store.run_dir(run_id) / "started" - while time.monotonic() < deadline: - if path.is_file(): - return - time.sleep(0.02) - log = store.run_dir(run_id) / "worker.log" - detail = log.read_text(encoding="utf-8", errors="replace") if log.is_file() else "no worker log" - raise RuntimeError(f"job command did not reach its start barrier: {run_id}: {detail[-2000:]}") - - -def _runtime_observations(directory: Path, env: dict[str, str]) -> dict[str, Any]: - from vkit.core.jobs import retry, submit, wait - from vkit.core.manifest import parse_manifest - from vkit.runtime.paths import open_project - from vkit.core.store import Store - - directory.mkdir(parents=True, exist_ok=False) - (directory / "verification").mkdir() - (directory / "slow.py").write_text( - "import json, sys, time\n" - "from pathlib import Path\n" - "output = Path(sys.argv[1])\n" - "root = output.parent\n" - "(root / 'started').touch()\n" - "while not (root / 'release').exists():\n" - " time.sleep(0.01)\n" - "output.write_text(json.dumps({'schema_version': 1, 'scenarios': " - "[{'id': 'ok', 'result': 'PASS', 'observation': 'ok'}]}), encoding='utf-8')\n", - encoding="utf-8", - ) - check = { - "id": "lifecycle-runtime", "kind": "scenario", "cwd": ".", - "timeout_seconds": 60, "artifact": "result.json", - "command": ["{{python}}", "slow.py", "{{run_dir}}/result.json"], - "required_scenarios": ["ok"], "inputs": ["slow.py"], - "subject": {"paths": ["slow.py"], "digest": None}, - "claim_id": "lifecycle-runtime", - } - (directory / "verification/manifest.json").write_text( - json.dumps({"schema_version": 3, "description": "Lifecycle runtime trace.", - "checks": [check]}, indent=2) + "\n", - encoding="utf-8", - ) - _run(["git", "init", "-q"], directory, env) - _run(["git", "-c", "user.name=VKit Lifecycle", "-c", "user.email=lifecycle@vkit.invalid", - "add", "."], directory, env) - _run(["git", "-c", "user.name=VKit Lifecycle", "-c", "user.email=lifecycle@vkit.invalid", - "commit", "-qm", "runtime fixture"], directory, env) - accepted = _cli(directory, env, "accept", "--yes") - if accepted["returncode"] != 0: - raise RuntimeError(f"runtime fixture could not accept its check: {accepted['stdout']} {accepted['stderr']}") - - project = open_project(directory) - manifest = parse_manifest(project) - store = Store.of(project) - first = submit(project, manifest, "lifecycle-runtime", store=store) - _wait_state(store, first["run_id"], "running") - _wait_started(store, first["run_id"]) - - second = submit(project, manifest, "lifecycle-runtime", store=store) - _wait_state(store, second["run_id"], "running") - _wait_started(store, second["run_id"]) - if first["job_id"] != second["job_id"] or first["run_id"] == second["run_id"]: - raise RuntimeError("concurrent submissions did not create distinct attempts for one job") - - # Let cancellation and command completion contend at the same release barrier. - barrier = threading.Barrier(2) - - def cancel_at_release() -> None: - barrier.wait() - store.request_cancel(first["run_id"]) - - cancel_thread = threading.Thread(target=cancel_at_release) - cancel_thread.start() - barrier.wait() - (store.run_dir(first["run_id"]) / "release").touch() - cancel_thread.join(timeout=5) - if cancel_thread.is_alive(): - raise RuntimeError("the cancellation race did not finish") - if not store.cancel_requested(first["run_id"]): - raise RuntimeError("the concurrent cancel request was not recorded") - raced = wait(store, first["run_id"], 30) - if raced["state"] != "done" or raced["outcome"]["result"] not in {"PASS", "BLOCKED"}: - raise RuntimeError(f"cancel/completion contention produced an invalid result: {raced!r}") - if raced["outcome"]["result"] == "BLOCKED" and raced["outcome"].get("reason") != "cancelled": - raise RuntimeError(f"the blocked cancellation race had an unrelated reason: {raced!r}") - - pointer_before_loss = store.evidence_for("registered_check", "lifecycle-runtime", first["job_id"]) - if pointer_before_loss is None or pointer_before_loss["run_id"] != raced["run_id"]: - raise RuntimeError("completed attempt did not publish an intact evidence pointer") - - # Keep the sibling worker active while recovery observes its death. It must not publish. - _stop_worker(second["run_id"], store, env) - interrupted = _wait_state(store, second["run_id"], "interrupted") - if interrupted.get("outcome") is not None: - raise RuntimeError(f"a lost worker exposed a terminal outcome: {interrupted!r}") - interrupted_identity = {name: interrupted.get(name) for name in - ("run_id", "job_id", "inputs", "source", "state", "outcome")} - pointer_after_loss = store.evidence_for("registered_check", "lifecycle-runtime", second["job_id"]) - if pointer_after_loss != pointer_before_loss: - raise RuntimeError("worker loss replaced previously published evidence") - - third = retry(project, second["run_id"], store=store) - _wait_state(store, third["run_id"], "running") - _wait_started(store, third["run_id"]) - (store.run_dir(third["run_id"]) / "release").touch() - passed = wait(store, third["run_id"], 30) - if passed["state"] != "done" or passed["outcome"]["result"] != "PASS": - raise RuntimeError(f"the retry did not finish with a recorded pass: {passed!r}") - - raced_final = store.record(first["run_id"]) - interrupted_final = store.record(second["run_id"]) - passed_final = store.record(third["run_id"]) - if (raced_final["state"] != raced["state"] - or raced_final["outcome"] != raced["outcome"] - or any(raced_final.get(name) != raced.get(name) - for name in ("run_id", "job_id", "inputs", "source")) - or interrupted_final["state"] != "interrupted" - or interrupted_final.get("outcome") is not None - or any(interrupted_final.get(name) != value - for name, value in interrupted_identity.items()) - or passed_final["outcome"].get("result") != "PASS"): - raise RuntimeError("later retries changed an earlier attempt or exposed a false terminal result") - published = store.evidence_for("registered_check", "lifecycle-runtime", third["job_id"]) - if published is None or published["run_id"] != third["run_id"] or published["result"] != "PASS": - raise RuntimeError("the final pass was not bound to the latest completed retry") - - records = [raced_final, interrupted_final, passed_final] - job_ids = {record["job_id"] for record in records} - input_digests = {record["inputs"]["digest"] for record in records} - run_ids = {record["run_id"] for record in records} - if len(job_ids) != 1 or len(input_digests) != 1 or len(run_ids) != 3: - raise RuntimeError("retries changed the immutable job/input identity or reused an attempt ID") - return { - "job_id": next(iter(job_ids)), - "input_digest": next(iter(input_digests)), - "attempts": [{"run_id": record["run_id"], "job_id": record["job_id"], - "state": record["state"], - "outcome": record.get("outcome")} for record in records], - "concurrent_same_job": {"run_ids": [first["run_id"], second["run_id"]], - "shared_job_id": first["job_id"]}, - "cancel_completion_race": {"run_id": raced["run_id"], - "outcome": raced["outcome"]}, - "published_before_worker_loss": pointer_before_loss, - "published_after_worker_loss": pointer_after_loss, - "final_published": published, - } - - -def capture_runtime_observations(directory: Path) -> dict[str, Any]: - return _runtime_observations(directory, _environment()) - - -def main() -> int: - parser = argparse.ArgumentParser(description="Run the registered lifecycle TLC self-check.") - parser.add_argument("--output", type=Path, default=ROOT / ".audit/lifecycle-model") - args = parser.parse_args() - jar_raw = os.environ.get("VKIT_TLA2TOOLS_JAR", "").strip() - if not jar_raw or not Path(jar_raw).is_file(): - raise RuntimeError("VKIT_TLA2TOOLS_JAR must name the pinned tla2tools.jar") - expected_jar = (ROOT / "examples/formal-ci/tla2tools.sha256").read_text(encoding="ascii").strip() - observed_jar = hashlib.sha256(Path(jar_raw).read_bytes()).hexdigest() - if observed_jar != expected_jar: - raise RuntimeError(f"TLC jar digest mismatch: expected {expected_jar}, got {observed_jar}") - env = _environment() - java = shutil.which("java", path=env.get("PATH")) - if not java: - raise RuntimeError("the pinned TLC run requires Java on PATH or under JAVA_HOME") - args.output.mkdir(parents=True, exist_ok=True) - run_root = Path(tempfile.mkdtemp(prefix="run-", dir=args.output)) - - static = _new_project(run_root / "model", env) - static_record = _run_model_case(static, env, "PASS") - - observations = _runtime_observations(run_root / "runtime", env) - bad_project = _new_project(run_root / "negative", env, wrong_pass=True) - bad_record = _run_model_case(bad_project, env, "FAIL") - counterexamples = (bad_record.get("obligations") or {}).get("counterexamples", []) - if not any(item.get("obligation", {}).get("obligation") == "NoFalsePass" - for item in counterexamples): - raise RuntimeError(f"the injected false pass did not fail NoFalsePass: {counterexamples!r}") - - report = { - "schema_version": 1, - "scope": "bounded multi-attempt lifecycle model plus observed production job API behavior", - "model": {"run_id": static_record["run_id"], "result": "PASS", - "attempt_slots": 3, "max_attempt_number": 3, - "publication_model": "The pointer selects any completed attempt for this job, including an older attempt that publishes later; publication is atomic in the model and hash bytes are abstracted.", - "obligations": static_record.get("obligations")}, - "observed_execution": observations, - "negative_control": {"result": "FAIL", - "counterexamples": counterexamples}, - "limit": "TLC checks three indexed attempts with finite state domains. No parameterized induction or implementation-refinement proof is claimed. The production observations cover these OS/process schedules only; hash bytes and crashes during pointer publication are abstracted.", - } - (run_root / "lifecycle-report.json").write_text( - json.dumps(report, indent=2) + "\n", encoding="utf-8" - ) - print(json.dumps({"result": "PASS", "report": str(run_root / "lifecycle-report.json"), - "attempts": len(observations["attempts"]), - "concurrent_same_job": True, - "cancel_completion_race": observations["cancel_completion_race"]["outcome"]["result"], - "negative_control": "NoFalsePass rejected"}, indent=2)) - return 0 - - -if __name__ == "__main__": - try: - raise SystemExit(main()) - except (OSError, RuntimeError, subprocess.SubprocessError, ValueError, KeyError) as exc: - print(f"lifecycle check failed: {exc}", file=sys.stderr) - raise SystemExit(1) diff --git a/formal/checks/check_p2_contracts.py b/formal/checks/check_p2_contracts.py deleted file mode 100644 index 96de68a..0000000 --- a/formal/checks/check_p2_contracts.py +++ /dev/null @@ -1,110 +0,0 @@ -"""Run package-level P2 transfer and concurrent contract controls.""" -from __future__ import annotations - -import json -import re -from pathlib import Path - - -def qualify( - verus: Path, - archive: Path, - tool_root: Path, - output: Path, - *, - tool_identity: dict, -) -> dict: - from check_verus_ledger import PACKAGE, ROOT, digest, run - - version = tool_identity["version"] - platform = version["platform"] - if platform not in ({"os": "windows", "arch": "x86_64"}, {"os": "linux", "arch": "x86_64"}): - raise ValueError("verified tool identity has an unsupported platform") - executable = "verus.exe" if platform == {"os": "windows", "arch": "x86_64"} else "verus" - if not tool_identity["archive_sha256"]: - raise ValueError("verified tool identity has no archive digest") - if verus.resolve() != (tool_root / executable).resolve(): - raise ValueError("Verus executable path differs from the verified tool root") - - fixtures = ROOT / "examples/verus-qualification" - model = (PACKAGE / "ledger.rs").read_text(encoding="utf-8") - transfer = (fixtures / "p2-transfer.rs").read_text(encoding="utf-8") - concurrent = (fixtures / "p2-concurrent.rs").read_text(encoding="utf-8") - positive = "\n".join((model, transfer, concurrent)) - transfer_good = """Err(error) => ( - source, - destination, - TransferResult::DestinationFailed(error), - ),""" - transfer_bad = transfer_good.replace("DestinationFailed", "SourceFailed") - reserve_good = "let (updated, result) = reserve(current, id, owner, amount);" - reserve_bad = "let (updated, result) = (current, Ok(()));" - if positive.count(transfer_good) != 1 or positive.count(reserve_good) != 1: - raise ValueError("P2 mutation anchors must each occur exactly once") - - output.mkdir(parents=True, exist_ok=False) - cases = [] - mutations = ( - ("positive", positive, None), - ("broken_transfer_error_origin", positive.replace(transfer_good, transfer_bad, 1), - "out.2 == transfer_model(source.view(), destination.view(), id, owner).1"), - ("broken_concurrent_reserve_guarantee", positive.replace(reserve_good, reserve_bad, 1), - "out.1@.1.slots == slots_after_reserve("), - ) - for name, source, marker in mutations: - source_path = output / f"{name}.rs" - log_path = output / f"{name}.log" - source_path.write_text(source, encoding="utf-8", newline="\n") - result = run( - [str(verus), str(source_path), "--no-cheating", "--no-external-by-default", - "--num-threads", "2", "--triggers-mode", "silent"], - log_path, - ROOT, - ) - log = log_path.read_text(encoding="utf-8", errors="replace") if log_path.exists() else "" - verified = result["returncode"] == 0 and bool(re.search( - r"verification results:: [1-9]\d* verified, 0 errors", log, - )) - rejected = ( - result["returncode"] not in {None, 0} - and "postcondition not satisfied" in log - and marker is not None - and marker in log - and bool(re.search(r"verification results:: \d+ verified, [1-9]\d* errors", log)) - ) - cases.append({ - "name": name, - "expected": "verified" if marker is None else "postcondition_rejection", - "expected_rejection_marker": marker, - "matched": verified if marker is None else rejected, - **result, - "source_sha256": digest(source_path.read_bytes()), - "log_sha256": digest(log_path.read_bytes()) if log_path.exists() else None, - }) - - report = { - "passed": all(case["matched"] for case in cases), - "method": "pinned_verus_same_crate_package_proof", - "scope": "package-level transfer and lock-protected reserve/release contracts; completed calls only", - "limits": [ - "not a global history or universal linearizability proof", - "no lock liveness, deadlock freedom, or starvation bound", - "no abort recovery guarantee while a write handle is held", - "no source-to-binary correspondence or runtime observation claim", - "separate from six candidate API bindings and their receipts", - ], - "package": { - "ledger_rs_sha256": digest((PACKAGE / "ledger.rs").read_bytes()), - "transfer_fixture_sha256": digest((fixtures / "p2-transfer.rs").read_bytes()), - "concurrent_fixture_sha256": digest((fixtures / "p2-concurrent.rs").read_bytes()), - }, - "verus": { - "executable_sha256": digest(verus.read_bytes()), - "archive": archive.name, - "archive_sha256": tool_identity["archive_sha256"], - "version": version, - }, - "cases": cases, - } - (output / "report.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") - return report diff --git a/formal/checks/check_protocol_trace.py b/formal/checks/check_protocol_trace.py new file mode 100644 index 0000000..ee0b572 --- /dev/null +++ b/formal/checks/check_protocol_trace.py @@ -0,0 +1,661 @@ +from __future__ import annotations + +import argparse +import importlib.util +import json +import os +import re +import shutil +import signal +import subprocess +import sys +import tempfile +import time +from pathlib import Path +from typing import Any + +try: + from formal.checks._tlc_env import ( + ROOT, + ToolchainUnavailable, + hidden_window, + resolve_java, + resolve_tlc_jar, + sha256_file, + tlc_version, + ) +except ImportError: + from _tlc_env import ( # type: ignore[no-redef] + ROOT, + ToolchainUnavailable, + hidden_window, + resolve_java, + resolve_tlc_jar, + sha256_file, + tlc_version, + ) + +MODEL_DIR = ROOT / "formal" / "models" +PROTOCOL_MODEL = MODEL_DIR / "VKitProtocol.tla" +TRACE_MODEL = MODEL_DIR / "TraceVKit.tla" +DEFAULT_OUTPUT = ROOT / "tmp" / "protocol-trace" + +PROTOCOL_CASES: dict[str, tuple[str, str | None]] = { + "clean": ("VKitProtocol.cfg", None), + "mutant_start_cancelled": ( + "VKitProtocol.mutant-start-cancelled.cfg", + "CancelledQueuedNeverStarts", + ), + "mutant_orphan_container": ( + "VKitProtocol.mutant-orphan-container.cfg", + "CrashLeavesNoOrphanContainer", + ), + "mutant_stale_gate": ( + "VKitProtocol.mutant-stale-gate.cfg", + "SourceDriftInvalidatesFreshPass", + ), + "mutant_allow_stale_stop": ( + "VKitProtocol.mutant-allow-stale-stop.cfg", + "StopBlockedUnlessReadyOrBypass", + ), +} + +TRACE_INVARIANTS = ( + "TypeOK", + "CancelledQueuedNeverStarts", + "SourceDriftInvalidatesFreshPass", + "CrashLeavesNoOrphanContainer", + "GateNeverReadyWithStaleOrUnapproved", + "StopBlockedUnlessReadyOrBypass", + "BypassAlwaysRecordedInTelemetry", +) + + +def run_protocol_tlc_case( + case_name: str, + cfg_name: str, + expected_violation: str | None, + output: Path, + java: Path, + jar: Path, +) -> dict[str, Any]: + config = MODEL_DIR / cfg_name + if not config.is_file(): + raise RuntimeError(f"missing TLC configuration: {config}") + case_dir = output / f"protocol-{case_name}" + states_dir = case_dir / "states" + traces_dir = case_dir / "traces" + states_dir.mkdir(parents=True, exist_ok=True) + traces_dir.mkdir(parents=True, exist_ok=True) + started = time.monotonic() + done = subprocess.run( + [ + str(java), + "-XX:+UseParallelGC", + "-cp", + str(jar), + "tlc2.TLC", + "-workers", + "1", + "-cleanup", + "-config", + str(config), + "-metadir", + str(states_dir), + "-teSpecOutDir", + str(traces_dir), + str(PROTOCOL_MODEL), + ], + cwd=case_dir, + capture_output=True, + text=True, + timeout=120, + check=False, + **hidden_window(), + ) + elapsed = round(time.monotonic() - started, 3) + transcript = done.stdout + ("\n--- stderr ---\n" + done.stderr if done.stderr else "") + (case_dir / "tlc.txt").write_text(transcript, encoding="utf-8") + violations = re.findall(r"Invariant ([A-Za-z][A-Za-z0-9_]*) is violated", transcript) + if expected_violation is None: + passed = done.returncode == 0 and not violations and "No error has been found" in transcript + else: + passed = done.returncode == 12 and expected_violation in violations + if not passed: + raise RuntimeError( + f"protocol/{case_name}: TLC exit={done.returncode}, " + f"expected={expected_violation!r}, violations={violations!r}\n{transcript[-3000:]}" + ) + states_match = re.search(r"([0-9,]+) distinct states found", transcript) + return { + "case": case_name, + "config": cfg_name, + "expected_counterexample": expected_violation, + "observed_counterexamples": violations, + "result": "counterexample" if expected_violation else "invariants_hold", + "distinct_states": int(states_match.group(1).replace(",", "")) if states_match else None, + "elapsed_seconds": elapsed, + "tlc_exit_code": done.returncode, + } + + +def run_protocol_tlc_suite(output: Path, java: Path, jar: Path) -> list[dict[str, Any]]: + return [ + run_protocol_tlc_case(case_name, cfg_name, expected, output, java, jar) + for case_name, (cfg_name, expected) in PROTOCOL_CASES.items() + ] + + +def _tla_str(value: str) -> str: + escaped = value.replace("\\", "\\\\").replace('"', '\\"') + return f'"{escaped}"' + + +def _tla_bool(value: bool) -> str: + return "TRUE" if value else "FALSE" + + +def ndjson_to_trace_events(ndjson_path: Path) -> tuple[list[dict[str, Any]], int, int]: + run_slots: dict[str, int] = {} + run_states: dict[int, str] = {} + events: list[dict[str, Any]] = [] + source_rev = 1 + lock_held = False + + def slot_for(run_id: str) -> int: + if run_id not in run_slots: + run_slots[run_id] = len(run_slots) + 1 + return run_slots[run_id] + + for raw_line in ndjson_path.read_text(encoding="utf-8").splitlines(): + line = raw_line.strip() + if not line: + continue + item = json.loads(line) + kind = item.get("event") + if kind == "store_approve": + events.append({"action": "ClientAccept"}) + elif kind == "source_edit": + source_rev += 1 + events.append({"action": "ClientEditSource"}) + elif kind == "store_save": + run_id = item.get("run_id") + if not isinstance(run_id, str): + continue + slot = slot_for(run_id) + state = item.get("state") + outcome = item.get("outcome") + prev = run_states.get(slot, "absent") + if state == "queued" and prev == "absent": + run_states[slot] = "queued" + events.append({"action": "ClientSubmit", "run": slot}) + elif state == "running" and prev == "queued": + run_states[slot] = "running" + events.append({"action": "WorkerStart", "run": slot}) + elif state == "done": + res = outcome if outcome in {"PASS", "FAIL", "BLOCKED"} else "BLOCKED" + if prev in {"absent", "queued"} and res == "BLOCKED": + run_states[slot] = "done" + events.append({"action": "WorkerFastBlock", "run": slot}) + elif prev == "running": + run_states[slot] = "done" + events.append({"action": "WorkerComplete", "run": slot, "res": res}) + elif kind == "cancel_request": + run_id = item.get("run_id") + if isinstance(run_id, str) and run_id in run_slots: + slot = run_slots[run_id] + if run_states.get(slot) in {"queued", "running"}: + events.append({"action": "ClientCancel", "run": slot}) + elif kind == "lock_acquire": + if not lock_held: + lock_held = True + events.append({"action": "StoreAcquireLock"}) + elif kind == "lock_release": + if lock_held: + lock_held = False + events.append({"action": "StoreReleaseLock"}) + elif kind == "worker_crash_recovered": + run_id = item.get("run_id") + if isinstance(run_id, str) and run_id in run_slots: + slot = run_slots[run_id] + if run_states.get(slot) == "running": + events.append({"action": "WorkerCrash", "run": slot}) + events.append({"action": "WorkerCleanupCrash", "run": slot}) + run_states[slot] = "interrupted" + if lock_held: + lock_held = False + events.append({"action": "StoreReleaseLock"}) + elif kind == "hook_session_start": + events.append({"action": "HookSessionStart"}) + elif kind == "hook_stop": + events.append({ + "action": "HookStop", + "bypass": bool(item.get("bypass", False)), + "decision": str(item.get("decision", "block")), + "verdict": str(item.get("verdict", "BLOCKED")), + }) + elif kind == "gate_check": + events.append({ + "action": "GateObserve", + "verdict": str(item.get("verdict", "BLOCKED")), + }) + return events, max(len(run_slots), 1), max(source_rev, 1) + + +def _render_trace_data(events: list[dict[str, Any]], max_run: int, max_rev: int) -> str: + rows: list[str] = [] + for ev in events: + row = ( + f" [action |-> {_tla_str(ev['action'])}, " + f"run |-> {int(ev.get('run', 0))}, " + f"res |-> {_tla_str(str(ev.get('res', 'none')))}, " + f"bypass |-> {_tla_bool(bool(ev.get('bypass', False)))}, " + f"decision |-> {_tla_str(str(ev.get('decision', 'none')))}, " + f"verdict |-> {_tla_str(str(ev.get('verdict', 'BLOCKED')))}]" + ) + rows.append(row) + body = ",\n".join(rows) + return ( + "---- MODULE TraceData ----\n" + "EXTENDS Naturals, Sequences\n" + f"MaxRun == {max_run}\n" + f"MaxRev == {max_rev}\n" + "Trace == <<\n" + f"{body}\n" + ">>\n" + "====\n" + ) + + +def validate_ndjson_trace( + ndjson_path: Path, + work_dir: Path, + java: Path, + jar: Path, + *, + expect_valid: bool = True, +) -> dict[str, Any]: + events, max_run, max_rev = ndjson_to_trace_events(ndjson_path) + if not events: + raise RuntimeError(f"empty NDJSON trace: {ndjson_path}") + work_dir.mkdir(parents=True, exist_ok=True) + shutil.copy2(TRACE_MODEL, work_dir / "TraceVKit.tla") + (work_dir / "TraceData.tla").write_text( + _render_trace_data(events, max_run, max_rev), encoding="utf-8" + ) + cfg_lines = ["SPECIFICATION TraceSpec", *(f"INVARIANT {inv}" for inv in TRACE_INVARIANTS)] + cfg_path = work_dir / "TraceVKit.cfg" + cfg_path.write_text("\n".join(cfg_lines) + "\n", encoding="utf-8") + states_dir = work_dir / "states" + states_dir.mkdir(parents=True, exist_ok=True) + started = time.monotonic() + done = subprocess.run( + [ + str(java), + "-XX:+UseParallelGC", + "-cp", + str(jar), + "tlc2.TLC", + "-workers", + "1", + "-cleanup", + "-config", + str(cfg_path), + "-metadir", + str(states_dir), + str(work_dir / "TraceVKit.tla"), + ], + cwd=work_dir, + capture_output=True, + text=True, + timeout=60, + check=False, + **hidden_window(), + ) + elapsed = round(time.monotonic() - started, 3) + transcript = done.stdout + ("\n--- stderr ---\n" + done.stderr if done.stderr else "") + (work_dir / "tlc.txt").write_text(transcript, encoding="utf-8") + accepted = done.returncode == 0 and "No error has been found" in transcript + if expect_valid and not accepted: + raise RuntimeError( + f"TraceVKit rejected valid trace ({len(events)} steps, rc={done.returncode}):\n" + f"{transcript[-2500:]}" + ) + if not expect_valid and accepted: + raise RuntimeError( + f"TraceVKit unexpectedly accepted mutated trace ({len(events)} steps):\n" + f"{transcript[-2500:]}" + ) + reason = "accepted" + if not accepted: + if "Deadlock reached" in transcript: + reason = "deadlock_rejected" + elif "Invariant" in transcript: + reason = "invariant_violated" + else: + reason = f"tlc_exit_{done.returncode}" + return { + "accepted": accepted, + "expected_valid": expect_valid, + "steps": len(events), + "tlc_exit_code": done.returncode, + "elapsed_seconds": elapsed, + "reason": reason, + } + + +def mutate_trace_ndjson(source_ndjson: Path, target_ndjson: Path) -> Path: + lines = [ + json.loads(line) + for line in source_ndjson.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + mutated = False + for entry in lines: + if entry.get("event") == "hook_stop" and entry.get("decision") == "block": + entry["decision"] = "allow" + entry["bypass"] = False + mutated = True + break + if not mutated: + lines.append({ + "event": "hook_stop", + "hook": "Stop", + "decision": "allow", + "verdict": "BLOCKED", + "bypass": False, + "ts": round(time.time(), 6), + }) + target_ndjson.write_text( + "\n".join(json.dumps(item, sort_keys=True) for item in lines) + "\n", + encoding="utf-8", + ) + return target_ndjson + + +def load_hook_module() -> Any: + hook_path = ROOT / "plugin" / "scripts" / "vkit_hook.py" + spec = importlib.util.spec_from_file_location("vkit_hook_trace", hook_path) + if spec is None or spec.loader is None: + raise RuntimeError(f"cannot load hook script from {hook_path}") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _run_git(argv: list[str], cwd: Path) -> None: + done = subprocess.run( + argv, + cwd=cwd, + capture_output=True, + text=True, + timeout=30, + check=False, + **hidden_window(), + ) + if done.returncode != 0: + raise RuntimeError(f"git failed ({done.returncode}): {argv!r}\n{done.stderr}") + + +def init_trace_fixture_repo(directory: Path, *, slow_barrier: bool = False) -> Path: + directory.mkdir(parents=True, exist_ok=False) + (directory / "verification").mkdir() + (directory / "app.py").write_text("VALUE = 1\n", encoding="utf-8") + if slow_barrier: + checker_code = ( + "import json, sys, time\n" + "from pathlib import Path\n" + "output = Path(sys.argv[1])\n" + "root = output.parent\n" + "(root / 'started').touch()\n" + "while not (root / 'release').exists():\n" + " time.sleep(0.01)\n" + "output.write_text(json.dumps({'schema_version': 1, 'scenarios': " + "[{'id': 'ok', 'result': 'PASS', 'observation': 'ok'}]}), encoding='utf-8')\n" + ) + else: + checker_code = ( + "import json, sys\n" + "from pathlib import Path\n" + "output = Path(sys.argv[1])\n" + "output.write_text(json.dumps({'schema_version': 1, 'scenarios': " + "[{'id': 'ok', 'result': 'PASS', 'observation': 'ok'}]}), encoding='utf-8')\n" + ) + (directory / "check_app.py").write_text(checker_code, encoding="utf-8") + check = { + "id": "app-check", + "kind": "scenario", + "cwd": ".", + "timeout_seconds": 60, + "artifact": "result.json", + "command": ["{{python}}", "check_app.py", "{{run_dir}}/result.json"], + "required_scenarios": ["ok"], + "inputs": ["app.py", "check_app.py"], + "subject": {"paths": ["app.py"], "digest": None}, + "claim_id": "app-check", + } + (directory / "verification" / "manifest.json").write_text( + json.dumps({"schema_version": 3, "description": "Protocol trace fixture.", "checks": [check]}, indent=2) + + "\n", + encoding="utf-8", + ) + _run_git(["git", "init", "-q"], directory) + _run_git(["git", "-c", "user.name=VKit Trace", "-c", "user.email=trace@vkit.invalid", "add", "."], directory) + _run_git(["git", "-c", "user.name=VKit Trace", "-c", "user.email=trace@vkit.invalid", "commit", "-qm", "init"], directory) + return directory + + +def approve_check(manifest: Any, store: Any, check_id: str) -> None: + from vkit.core.evidence import backend_identity + from vkit.core.inputs import canonical_digest + from vkit.core.state import evaluator, evaluator_digests + from vkit.core.store import now + + check = manifest.require(check_id) + digest = manifest.digest(check_id) + files = evaluator_digests(check) + record: dict[str, Any] = { + "kind": "check_definition", + "check_id": check_id, + "accepted_at": now(), + "backend": backend_identity(check), + } + if files: + store.retain_evaluator(check_id, evaluator(check)) + record["oracle"] = { + "files": files, + "digest": canonical_digest(files), + "external": False, + } + store.approve({ + digest: record, + "__inventory__": { + "kind": "obligation_inventory", + "checks": {check_id: digest}, + "formal_required": {}, + "accepted_at": now(), + }, + }) + + +def gate_verdict(project: Any, manifest: Any, store: Any) -> str: + from vkit.core.inputs import Snapshot + from vkit.core.state import approved_inventory, check_states, gate + + states = check_states(manifest, store, Snapshot(project)) + return gate(states, obligations=approved_inventory(store.approved()))["verdict"] + + +def _wait_for_file(path: Path, timeout: float = 20.0) -> None: + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if path.is_file(): + return + time.sleep(0.02) + raise RuntimeError(f"timed out waiting for {path}") + + +def _wait_state(store: Any, run_id: str, expected: str, timeout: float = 20.0) -> dict[str, Any]: + deadline = time.monotonic() + timeout + latest = None + while time.monotonic() < deadline: + latest = store.record(run_id) + if latest and latest["state"] == expected: + return latest + time.sleep(0.02) + raise RuntimeError(f"run {run_id} did not reach state {expected!r}: {latest!r}") + + +def _kill_worker(store: Any, run_id: str) -> None: + from vkit.core.store import _process_alive, read_json + + worker = read_json(store.run_dir(run_id) / "worker.json") + if not worker or not isinstance(worker.get("pid"), int): + raise RuntimeError(f"run {run_id} has no worker pid") + pid = worker["pid"] + if os.name == "nt": + subprocess.run( + ["taskkill", "/PID", str(pid), "/T", "/F"], + capture_output=True, + text=True, + check=False, + timeout=15, + **hidden_window(), + ) + else: + os.killpg(pid, signal.SIGKILL) + deadline = time.monotonic() + 10.0 + while _process_alive(pid) and time.monotonic() < deadline: + time.sleep(0.02) + + +def record_lifecycle_and_hook_trace(work_dir: Path) -> Path: + from vkit.core import jobs + from vkit.core.manifest import parse_manifest + from vkit.core.store import Store + from vkit.core.trace import emit_trace + from vkit.runtime.paths import open_project + + trace_path = work_dir / "runtime-trace.ndjson" + prev_env = os.environ.get("VKIT_TRACE_LOG") + os.environ["VKIT_TRACE_LOG"] = str(trace_path) + try: + repo = init_trace_fixture_repo(work_dir / "repo", slow_barrier=True) + hook = load_hook_module() + project = open_project(repo) + manifest = parse_manifest(project) + store = Store.of(project) + + hook.handle("SessionStart", {"session_id": "trace-s1"}, str(repo)) + emit_trace("gate_check", verdict=gate_verdict(project, manifest, store)) + + blocked_stop = hook.handle("Stop", {"session_id": "trace-s1"}, str(repo)) + if blocked_stop.get("decision") != "block": + raise RuntimeError(f"expected Stop block on unapproved gate: {blocked_stop!r}") + bypass_stop = hook.handle("Stop", {"session_id": "trace-s1", "stop_hook_active": True}, str(repo)) + if bypass_stop.get("decision") == "block": + raise RuntimeError(f"expected Stop bypass allow: {bypass_stop!r}") + + approve_check(manifest, store, "app-check") + emit_trace("gate_check", verdict=gate_verdict(project, manifest, store)) + + first = jobs.submit(project, manifest, "app-check", store=store) + _wait_for_file(store.run_dir(first["run_id"]) / "started") + (store.run_dir(first["run_id"]) / "release").touch() + passed = jobs.wait(store, first["run_id"], 30) + if passed["state"] != "done" or (passed.get("outcome") or {}).get("result") != "PASS": + raise RuntimeError(f"first run did not PASS: {passed!r}") + emit_trace("gate_check", verdict=gate_verdict(project, manifest, store)) + + ready_stop = hook.handle("Stop", {"session_id": "trace-s1"}, str(repo)) + if ready_stop != {}: + raise RuntimeError(f"expected Stop release on READY gate: {ready_stop!r}") + + (repo / "app.py").write_text("VALUE = 2\n", encoding="utf-8") + emit_trace("source_edit", rev=2) + emit_trace("gate_check", verdict=gate_verdict(project, manifest, store)) + + drifted_stop = hook.handle("SubagentStop", {"session_id": "trace-s1"}, str(repo)) + if drifted_stop.get("decision") != "block": + raise RuntimeError(f"expected SubagentStop block after source drift: {drifted_stop!r}") + + crashed = jobs.submit(project, manifest, "app-check", store=store) + _wait_for_file(store.run_dir(crashed["run_id"]) / "started") + _kill_worker(store, crashed["run_id"]) + _wait_state(store, crashed["run_id"], "interrupted") + emit_trace("worker_crash_recovered", run_id=crashed["run_id"]) + + retried = jobs.retry(project, crashed["run_id"], store=store) + _wait_for_file(store.run_dir(retried["run_id"]) / "started") + (store.run_dir(retried["run_id"]) / "release").touch() + retried_done = jobs.wait(store, retried["run_id"], 30) + if retried_done["state"] != "done" or (retried_done.get("outcome") or {}).get("result") != "PASS": + raise RuntimeError(f"retried run did not PASS: {retried_done!r}") + emit_trace("gate_check", verdict=gate_verdict(project, manifest, store)) + final_stop = hook.handle("Stop", {"session_id": "trace-s1"}, str(repo)) + if final_stop != {}: + raise RuntimeError(f"expected final Stop release on READY gate: {final_stop!r}") + finally: + if prev_env is None: + os.environ.pop("VKIT_TRACE_LOG", None) + else: + os.environ["VKIT_TRACE_LOG"] = prev_env + return trace_path + + +def main() -> int: + parser = argparse.ArgumentParser( + description="Verify VKitProtocol.tla (clean + 4 mutants) and NDJSON runtime trace validation via TraceVKit.tla." + ) + parser.add_argument("--java", type=Path) + parser.add_argument("--jar", type=Path) + parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT) + args = parser.parse_args() + + java = resolve_java(args.java) + jar = resolve_tlc_jar(args.jar) + version = tlc_version(java, jar) + + output = args.output.resolve() + output.mkdir(parents=True, exist_ok=True) + run_root = Path(tempfile.mkdtemp(prefix="run-", dir=output)) + + tlc_results = run_protocol_tlc_suite(run_root / "tlc", java, jar) + trace_path = record_lifecycle_and_hook_trace(run_root / "runtime") + clean_trace = validate_ndjson_trace(trace_path, run_root / "trace-clean", java, jar, expect_valid=True) + mutated_path = mutate_trace_ndjson(trace_path, run_root / "runtime" / "mutated-trace.ndjson") + mutated_trace = validate_ndjson_trace(mutated_path, run_root / "trace-mutated", java, jar, expect_valid=False) + + report = { + "schema_version": 2, + "result": "PASS", + "toolchain": {"tool": "tlc", "version": version, "jar_sha256": sha256_file(jar)}, + "tlc_cases": tlc_results, + "trace_validation": { + "clean_trace": clean_trace, + "mutated_trace": mutated_trace, + }, + } + report_path = run_root / "protocol-trace-report.json" + report_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + summary = { + "result": "PASS", + "tlc_cases": len(tlc_results), + "clean_models": sum(item["expected_counterexample"] is None for item in tlc_results), + "mutants_caught": sum(item["expected_counterexample"] is not None for item in tlc_results), + "clean_trace_accepted": clean_trace["accepted"], + "clean_trace_steps": clean_trace["steps"], + "mutated_trace_rejected": not mutated_trace["accepted"], + "mutated_trace_reason": mutated_trace["reason"], + "report": str(report_path), + } + print(json.dumps(summary, indent=2)) + return 0 + + +if __name__ == "__main__": + try: + raise SystemExit(main()) + except (ToolchainUnavailable, OSError, RuntimeError, subprocess.SubprocessError, ValueError, KeyError) as exc: + print(f"protocol trace check failed: {exc}", file=sys.stderr) + raise SystemExit(1) diff --git a/formal/checks/check_transition_comparison.py b/formal/checks/check_transition_comparison.py index 6075c3f..3e9a548 100644 --- a/formal/checks/check_transition_comparison.py +++ b/formal/checks/check_transition_comparison.py @@ -2,7 +2,6 @@ import argparse from collections import Counter -import hashlib import json import os from pathlib import Path @@ -13,10 +12,28 @@ import time from typing import Any -ROOT = Path(__file__).resolve().parents[2] +try: + from formal.checks._tlc_env import ( + EXPECTED_JAR_DIGEST, + ROOT, + hidden_window, + resolve_java, + resolve_tlc_jar, + sha256_file, + ) +except ImportError: + from _tlc_env import ( # type: ignore[no-redef] + EXPECTED_JAR_DIGEST, + ROOT, + hidden_window, + resolve_java, + resolve_tlc_jar, + sha256_file, + ) + MODEL = ROOT / "formal" / "models" / "FiniteTransitionComparison.tla" CONFIG = ROOT / "formal" / "models" / "finite-transition" / "complete.cfg" -EXPECTED_JAR = ROOT / "examples" / "formal-ci" / "tla2tools.sha256" +EXPECTED_JAR = EXPECTED_JAR_DIGEST DEFAULT_OUTPUT = ROOT / "tmp" / "transition-comparison" MARKER = "VKIT_FINITE_TRANSITION_PAIR_V1" DELTA_KINDS = ("initial_states", "reachable_states", "assumptions", "guards", @@ -25,40 +42,12 @@ PAIR_COUNT = MODEL_COUNT * MODEL_COUNT TIMEOUT_SECONDS = 900 - -def sha256(path: Path) -> str: - return hashlib.sha256(path.read_bytes()).hexdigest() +sha256 = sha256_file +hidden_options = hidden_window def resolve_toolchain(java_arg: Path | None, jar_arg: Path | None) -> tuple[Path, Path]: - executable = "java.exe" if os.name == "nt" else "java" - if java_arg is not None: - configured = str(java_arg.expanduser()) - located = shutil.which(configured) - java = Path(configured).resolve() if Path(configured).is_file() else ( - Path(located).resolve() if located else None - ) - else: - java_home = os.environ.get("JAVA_HOME") - home_candidate = Path(java_home) / "bin" / executable if java_home else None - located = shutil.which("java") - java = home_candidate.resolve() if home_candidate and home_candidate.is_file() else ( - Path(located).resolve() if located else None - ) - if java is None or not java.is_file(): - raise RuntimeError("Java is unavailable; set JAVA_HOME or pass --java") - configured_jar = jar_arg or (Path(os.environ["VKIT_TLA2TOOLS_JAR"]) - if os.environ.get("VKIT_TLA2TOOLS_JAR") else None) - if configured_jar is None: - raise RuntimeError("TLC jar is unavailable; set VKIT_TLA2TOOLS_JAR or pass --jar") - jar = configured_jar.expanduser().resolve() - if not jar.is_file(): - raise RuntimeError(f"TLC jar does not exist: {jar}") - expected = EXPECTED_JAR.read_text(encoding="ascii").strip() - observed = sha256(jar) - if observed != expected: - raise RuntimeError(f"TLC jar SHA-256 mismatch: expected {expected}, observed {observed}") - return java, jar + return resolve_java(java_arg), resolve_tlc_jar(jar_arg) def resolve_source(source_arg: Path | None) -> Path: @@ -72,22 +61,92 @@ def resolve_source(source_arg: Path | None) -> Path: return selected.resolve() -def hidden_options() -> dict[str, Any]: - if os.name != "nt": - return {} - startup = subprocess.STARTUPINFO() - startup.dwFlags |= subprocess.STARTF_USESHOWWINDOW - startup.wShowWindow = subprocess.SW_HIDE - return {"startupinfo": startup, "creationflags": subprocess.CREATE_NO_WINDOW} - - def decode_tla_tuple(raw: str) -> tuple[Any, int]: - scripts = str(ROOT / "formal" / "checks") - if scripts not in sys.path: - sys.path.insert(0, scripts) - from check_difference_decisions import decode_tla_tuple as decode - - return decode(raw) + depth = 0 + quoted = False + escaped = False + end = None + cursor = 0 + while cursor < len(raw) - 1: + char = raw[cursor] + if quoted: + if escaped: + escaped = False + elif char == "\\": + escaped = True + elif char == '"': + quoted = False + elif char == '"': + quoted = True + elif raw[cursor:cursor + 2] == "<<": + depth += 1 + cursor += 1 + elif raw[cursor:cursor + 2] == ">>": + depth -= 1 + cursor += 1 + if depth == 0: + end = cursor + 1 + break + cursor += 1 + if end is None: + raise ValueError("unterminated TLC output sequence") + raw = raw[:end] + token = re.compile(r'\s*(<<|>>|,|TRUE\b|FALSE\b|-?[0-9]+|"(?:\\.|[^"\\])*"|.)', re.DOTALL) + tokens = [] + pos = 0 + while pos < len(raw): + match = token.match(raw, pos) + if not match: + raise ValueError("invalid TLC tuple token") + value = match.group(1) + pos = match.end() + if value.isspace(): + continue + if value not in {"<<", ">>", ",", "TRUE", "FALSE"} and not ( + value.startswith('"') or re.fullmatch(r"-?[0-9]+", value) + ): + if value.strip() == "": + continue + raise ValueError(f"unsupported TLC tuple token: {value!r}") + tokens.append(value) + + index = 0 + + def parse() -> Any: + nonlocal index + if index >= len(tokens): + raise ValueError("truncated TLC tuple") + value = tokens[index] + index += 1 + if value == "<<": + result = [] + if index < len(tokens) and tokens[index] == ">>": + index += 1 + return result + while True: + result.append(parse()) + if index >= len(tokens): + raise ValueError("unterminated TLC sequence") + separator = tokens[index] + index += 1 + if separator == ">>": + return result + if separator != ",": + raise ValueError("invalid TLC sequence separator") + if value == "TRUE": + return True + if value == "FALSE": + return False + if value.startswith('"'): + return json.loads(value) + if re.fullmatch(r"-?[0-9]+", value): + return int(value) + raise ValueError("unexpected TLC tuple delimiter") + + parsed = parse() + if index != len(tokens) or not isinstance(parsed, list): + raise ValueError("extra tokens or non-sequence TLC output") + return tuple(parsed), end def terminal_rows(stdout: str) -> list[tuple[Any, ...]]: @@ -158,7 +217,7 @@ def run_tlc(output: Path, java: Path, jar: Path) -> tuple[list[tuple[Any, ...]], started = time.monotonic() done = subprocess.run(command, cwd=case, capture_output=True, text=True, timeout=TIMEOUT_SECONDS, check=False, - **hidden_options()) + **hidden_window()) (case / "tlc.stdout.log").write_text(done.stdout, encoding="utf-8") (case / "tlc.stderr.log").write_text(done.stderr, encoding="utf-8") transcript = "--- stdout ---\n" + done.stdout + "\n--- stderr ---\n" + done.stderr diff --git a/formal/checks/check_verifier_interpreters.py b/formal/checks/check_verifier_interpreters.py index 4c8a49b..fc6e077 100644 --- a/formal/checks/check_verifier_interpreters.py +++ b/formal/checks/check_verifier_interpreters.py @@ -1,10 +1,9 @@ -"""Exhaustive real-code formal checker for Lean 4 and TLC report interpreters. +"""Exhaustive real-code formal checker for Lean 4, TLC, Property, and Node report interpreters. -Enumerates finite abstract report states and runs the real -`vkit.verifiers.lean_adapter.interpret` (plus `logical_trust_from_report`) and -`vkit.verifiers.tlc_adapter.interpret` against an independent specification -oracle and explicit safety invariants, then proves the checker catches -deliberate negative-control mutants. +Enumerates finite abstract report states and runs the real pure-core interpreters +(`lean_adapter.interpret`, `tlc_adapter.interpret`, `property_adapter.interpret`, +and `node_adapter.interpret`) against independent specification oracles and explicit +safety invariants, then proves the checker catches deliberate negative-control mutants. """ from __future__ import annotations @@ -18,14 +17,18 @@ from typing import Any, Callable from vkit.core.outcome import Blocked, BlockedReason -from vkit.verifiers import lean_adapter, tlc_adapter +from vkit.verifiers import lean_adapter, node_adapter, property_adapter, tlc_adapter from vkit.verifiers.obligation import PropertyObligation, TheoremObligation from vkit.verifiers.spec import ( DomainBounds, FingerprintSpec, + HypothesisSettings, LeanCheck, LeanProfile, ModuleRef, + NodeTestCheck, + PinnedRunner, + PropertyCheck, TlcCheck, ToolchainRef, ) @@ -47,6 +50,13 @@ TLC_BOUND_NAME = "N" TLC_BOUND_VALUE = 2 +PROP_TEST_ID = "tests/test_prop.py::test_invariant" +PROP_PINNED_EXAMPLES = 50 + +NODE_FILE = "suite.test.js" +NODE_NAME = "handles input" +NODE_TEST_ID = f"{NODE_FILE}::{NODE_NAME}" + class OutcomeKind(StrEnum): PASS = "PASS" @@ -71,6 +81,7 @@ class TheoremResolution(StrEnum): RESOLVED = "resolved" MISSING_ERROR = "missing_error" UNREPORTED = "unreported" + AUDIT_NONZERO = "audit_nonzero" class AxiomProfile(StrEnum): @@ -100,6 +111,7 @@ class TlcPropertyState(StrEnum): MISSING_IN_CONFIG = "missing_in_config" VIOLATED_VALIDATED = "violated_validated" VIOLATED_UNVALIDATED = "violated_unvalidated" + VIOLATED_INCOMPLETE_WITNESS = "violated_incomplete_witness" class TlcBoundsState(StrEnum): @@ -124,29 +136,46 @@ class LeanAbstractState: axiom_profile: AxiomProfile +@dataclass(frozen=True) +class ComparatorAbstractState: + status: ComparatorStatus + digest_state: DigestState + exit_code: int + + @dataclass(frozen=True) class TlcAbstractState: exit_code: int simulation_mode: bool summary_state: TlcSummaryState completed_banner: bool + config_digest_match: bool property_state: TlcPropertyState bounds_state: TlcBoundsState -def _blocked_token(result: Blocked) -> str: - return result.detail.partition(":")[0] +@dataclass(frozen=True) +class PropertyAbstractState: + outcome: str + generator_present: bool + measured_examples: int + pinned_steps: int + measured_steps: int -def _classify_lean_result(result: lean_adapter.AdapterResult | Blocked) -> ExpectedOutcome: - if isinstance(result, Blocked): - return ExpectedOutcome(OutcomeKind.BLOCKED, result.reason, _blocked_token(result)) - if result.observations and not result.counterexamples: - return ExpectedOutcome(OutcomeKind.PASS) - return ExpectedOutcome(OutcomeKind.FAIL_WITNESS) +@dataclass(frozen=True) +class NodeAbstractState: + required_present: bool + directive: str | None + verdict: str + code: str + + +def _blocked_token(result: Blocked) -> str: + return result.detail.partition(":")[0] -def _classify_tlc_result(result: tlc_adapter.AdapterResult | Blocked) -> ExpectedOutcome: +def _classify_result(result: Any) -> ExpectedOutcome: if isinstance(result, Blocked): return ExpectedOutcome(OutcomeKind.BLOCKED, result.reason, _blocked_token(result)) if result.observations and not result.counterexamples: @@ -180,6 +209,8 @@ def _lean_oracle(state: LeanAbstractState) -> ExpectedOutcome: return ExpectedOutcome(OutcomeKind.BLOCKED, BlockedReason.INTERNAL_ERROR, "recheck_diverged") if state.theorem_resolution is TheoremResolution.MISSING_ERROR: return ExpectedOutcome(OutcomeKind.BLOCKED, BlockedReason.SCENARIO_UNKNOWN, "theorem_absent") + if state.theorem_resolution is TheoremResolution.AUDIT_NONZERO: + return ExpectedOutcome(OutcomeKind.BLOCKED, BlockedReason.INTERNAL_ERROR, "audit_failed") if state.theorem_resolution is TheoremResolution.UNREPORTED: return ExpectedOutcome(OutcomeKind.BLOCKED, BlockedReason.FORMAL_OBLIGATION, "axioms_unreported") if state.axiom_profile in {AxiomProfile.SORRY, AxiomProfile.SORRY_AND_CUSTOM}: @@ -219,6 +250,37 @@ def _lean_safety_violations( return violations +def _comparator_oracle(state: ComparatorAbstractState) -> ExpectedOutcome: + if state.status is ComparatorStatus.CHALLENGE_CHANGED: + return ExpectedOutcome(OutcomeKind.BLOCKED, BlockedReason.NOT_APPROVED, "challenge_changed") + if state.status is ComparatorStatus.ACCEPTED: + if state.digest_state is DigestState.EMPTY: + return ExpectedOutcome(OutcomeKind.BLOCKED, BlockedReason.ARTIFACT_MALFORMED, "challenge_unknown") + if state.digest_state is DigestState.MISMATCH: + return ExpectedOutcome(OutcomeKind.BLOCKED, BlockedReason.SOURCE_CHANGED, "challenge_altered") + if state.exit_code != 0: + return ExpectedOutcome(OutcomeKind.BLOCKED, BlockedReason.ARTIFACT_MALFORMED, "report_malformed") + return ExpectedOutcome(OutcomeKind.PASS) + if state.status is ComparatorStatus.REJECTED: + return ExpectedOutcome(OutcomeKind.BLOCKED, BlockedReason.FORMAL_OBLIGATION, "proof_rejected") + return ExpectedOutcome(OutcomeKind.BLOCKED, BlockedReason.ARTIFACT_MALFORMED, "report_malformed") + + +def _comparator_safety_violations( + state: ComparatorAbstractState, + actual: ExpectedOutcome, +) -> list[str]: + violations: list[str] = [] + if actual.kind is OutcomeKind.PASS: + if state.status is not ComparatorStatus.ACCEPTED: + violations.append("comparator_passed_without_accepted_status") + if state.digest_state is not DigestState.MATCH: + violations.append("comparator_passed_with_bad_challenge_digest") + if state.exit_code != 0: + violations.append("comparator_passed_with_nonzero_exit_code") + return violations + + def _build_lean_report( state: LeanAbstractState, challenge_path: Path, @@ -283,7 +345,7 @@ def _build_lean_report( "kind": "error", "data": f"unknown identifier '{LEAN_MODULE}.{LEAN_THEOREM}'", }) - elif state.theorem_resolution is TheoremResolution.RESOLVED: + elif state.theorem_resolution in {TheoremResolution.RESOLVED, TheoremResolution.AUDIT_NONZERO}: axioms = _lean_expected_axioms(state.axiom_profile) if not axioms: line = f"'{LEAN_MODULE}.{LEAN_THEOREM}' does not depend on any axioms" @@ -295,9 +357,13 @@ def _build_lean_report( "data": line, }) + audit_exit = ( + 1 if state.theorem_resolution in {TheoremResolution.MISSING_ERROR, TheoremResolution.AUDIT_NONZERO} + else 0 + ) steps.append({ "name": "audit", - "exit_code": 1 if state.theorem_resolution is TheoremResolution.MISSING_ERROR else 0, + "exit_code": audit_exit, "messages": audit_messages, }) @@ -330,6 +396,7 @@ def _tlc_oracle(state: TlcAbstractState) -> ExpectedOutcome: stdout_violated = state.property_state in { TlcPropertyState.VIOLATED_VALIDATED, TlcPropertyState.VIOLATED_UNVALIDATED, + TlcPropertyState.VIOLATED_INCOMPLETE_WITNESS, } violated = stdout_violated or (state.exit_code in tlc_adapter.VIOLATION_STATUSES) @@ -339,6 +406,8 @@ def _tlc_oracle(state: TlcAbstractState) -> ExpectedOutcome: if not state.completed_banner: return ExpectedOutcome(OutcomeKind.BLOCKED, BlockedReason.INTERNAL_ERROR, "incomplete_exploration") + if not state.config_digest_match: + return ExpectedOutcome(OutcomeKind.BLOCKED, BlockedReason.SOURCE_CHANGED, "source_changed") if state.property_state is TlcPropertyState.MISSING_IN_CONFIG: return ExpectedOutcome(OutcomeKind.BLOCKED, BlockedReason.SCENARIO_UNKNOWN, "properties_absent") if state.bounds_state is TlcBoundsState.MISMATCH: @@ -347,6 +416,8 @@ def _tlc_oracle(state: TlcAbstractState) -> ExpectedOutcome: if violated: if state.property_state is TlcPropertyState.VIOLATED_VALIDATED: return ExpectedOutcome(OutcomeKind.FAIL_WITNESS) + if state.property_state is TlcPropertyState.VIOLATED_INCOMPLETE_WITNESS: + return ExpectedOutcome(OutcomeKind.BLOCKED, BlockedReason.ARTIFACT_MALFORMED, "report_malformed") if state.property_state is TlcPropertyState.VIOLATED_UNVALIDATED: return ExpectedOutcome(OutcomeKind.BLOCKED, BlockedReason.SCENARIO_UNKNOWN, "witness_validation_failed") return ExpectedOutcome(OutcomeKind.BLOCKED, BlockedReason.SCENARIO_UNKNOWN, "counterexample_unattributed") @@ -370,6 +441,8 @@ def _tlc_safety_violations( violations.append("tlc_passed_with_queue_nonempty_or_absent") if not state.completed_banner: violations.append("tlc_passed_without_completion_banner") + if not state.config_digest_match: + violations.append("tlc_passed_with_config_sha256_mismatch") if state.property_state is not TlcPropertyState.ALL_SATISFIED: violations.append("tlc_passed_with_missing_or_violated_property") if state.bounds_state is not TlcBoundsState.MATCH: @@ -377,6 +450,9 @@ def _tlc_safety_violations( assert isinstance(result, tlc_adapter.AdapterResult) if not result.exploration.exhaustive: violations.append("tlc_pass_exploration_not_exhaustive") + if actual.kind is OutcomeKind.FAIL_WITNESS: + if state.property_state is TlcPropertyState.VIOLATED_INCOMPLETE_WITNESS: + violations.append("tlc_accepted_incomplete_witness_validation") return violations @@ -388,6 +464,7 @@ def _build_tlc_report_and_config(state: TlcAbstractState) -> tuple[bytes, str]: if state.property_state in { TlcPropertyState.VIOLATED_VALIDATED, TlcPropertyState.VIOLATED_UNVALIDATED, + TlcPropertyState.VIOLATED_INCOMPLETE_WITNESS, }: stdout_lines.append(f"Error: Invariant {TLC_PROPERTY} is violated.") stdout_lines.append("Error: The behavior up to this state is:") @@ -419,6 +496,26 @@ def _build_tlc_report_and_config(state: TlcAbstractState) -> tuple[bytes, str]: } trace_artifact = "trace.json" validation_artifact = "validation.json" + elif state.property_state is TlcPropertyState.VIOLATED_INCOMPLETE_WITNESS: + witness_validation = { + "status": "validated", + "property": TLC_PROPERTY, + } + trace_artifact = "trace.json" + validation_artifact = "validation.json" + + bound_rhs = f"1..{TLC_BOUND_VALUE}" if state.bounds_state is TlcBoundsState.MATCH else "1..9" + config_lines = [ + "SPECIFICATION Spec", + f"CONSTANTS {TLC_BOUND_NAME} = {bound_rhs}", + ] + if state.property_state is not TlcPropertyState.MISSING_IN_CONFIG: + config_lines.append(f"INVARIANT {TLC_PROPERTY}") + config_text = "\n".join(config_lines) + "\n" + config_sha = ( + hashlib.sha256(config_text.encode("utf-8")).hexdigest() + if state.config_digest_match else "0" * 64 + ) document = { "tool": "tlc", @@ -434,6 +531,10 @@ def _build_tlc_report_and_config(state: TlcAbstractState) -> tuple[bytes, str]: "checksum_states": False, "workers": 1, }, + "source_identity": { + "model_sha256": "c" * 64, + "config_sha256": config_sha, + }, "exit_code": state.exit_code, "stdout": "\n".join(stdout_lines), "stderr": "", @@ -442,16 +543,67 @@ def _build_tlc_report_and_config(state: TlcAbstractState) -> tuple[bytes, str]: "trace_artifact": trace_artifact, "validation_artifact": validation_artifact, } + return json.dumps(document).encode("utf-8"), config_text + + +def _property_oracle(state: PropertyAbstractState) -> ExpectedOutcome: + if state.outcome == "skipped": + return ExpectedOutcome(OutcomeKind.BLOCKED, BlockedReason.SCENARIO_UNKNOWN, "required_test_skipped") + if state.outcome == "error": + return ExpectedOutcome(OutcomeKind.BLOCKED, BlockedReason.INTERNAL_ERROR, "infrastructure_error") + if state.outcome == "failed": + return ExpectedOutcome(OutcomeKind.FAIL_WITNESS) + if not state.generator_present: + return ExpectedOutcome(OutcomeKind.BLOCKED, BlockedReason.SCENARIO_UNKNOWN, "generator_absent") + if state.measured_examples < PROP_PINNED_EXAMPLES: + return ExpectedOutcome(OutcomeKind.BLOCKED, BlockedReason.SCENARIO_UNKNOWN, "generator_weakened") + if state.pinned_steps and state.measured_steps < state.pinned_steps: + return ExpectedOutcome(OutcomeKind.BLOCKED, BlockedReason.SCENARIO_UNKNOWN, "generator_weakened") + return ExpectedOutcome(OutcomeKind.PASS) + + +def _property_safety_violations( + state: PropertyAbstractState, + actual: ExpectedOutcome, +) -> list[str]: + violations: list[str] = [] + if actual.kind is OutcomeKind.PASS: + if state.outcome != "passed": + violations.append("property_passed_without_passed_outcome") + if not state.generator_present: + violations.append("property_passed_without_generator") + if state.measured_examples < PROP_PINNED_EXAMPLES: + violations.append("property_passed_below_pinned_max_examples") + if state.pinned_steps and state.measured_steps < state.pinned_steps: + violations.append("property_passed_below_pinned_stateful_step_count") + return violations + + +def _node_oracle(state: NodeAbstractState) -> ExpectedOutcome: + if not state.required_present: + return ExpectedOutcome(OutcomeKind.BLOCKED, BlockedReason.SCENARIO_UNKNOWN, "required_test_absent") + if state.directive in {"SKIP", "TODO"}: + return ExpectedOutcome(OutcomeKind.BLOCKED, BlockedReason.SCENARIO_UNKNOWN, "required_test_skipped") + if state.verdict == "ok": + return ExpectedOutcome(OutcomeKind.PASS) + if state.code == node_adapter.ASSERTION_CODE: + return ExpectedOutcome(OutcomeKind.FAIL_WITNESS) + return ExpectedOutcome(OutcomeKind.BLOCKED, BlockedReason.INTERNAL_ERROR, "infrastructure_error") - bound_rhs = f"1..{TLC_BOUND_VALUE}" if state.bounds_state is TlcBoundsState.MATCH else "1..9" - config_lines = [ - "SPECIFICATION Spec", - f"CONSTANTS {TLC_BOUND_NAME} = {bound_rhs}", - ] - if state.property_state is not TlcPropertyState.MISSING_IN_CONFIG: - config_lines.append(f"INVARIANT {TLC_PROPERTY}") - return json.dumps(document).encode("utf-8"), "\n".join(config_lines) + "\n" +def _node_safety_violations( + state: NodeAbstractState, + actual: ExpectedOutcome, +) -> list[str]: + violations: list[str] = [] + if actual.kind is OutcomeKind.PASS: + if not state.required_present: + violations.append("node_passed_without_required_case") + if state.directive in {"SKIP", "TODO"}: + violations.append("node_passed_skipped_or_todo_case") + if state.verdict != "ok": + violations.append("node_passed_non_ok_case") + return violations def _lean_states() -> list[LeanAbstractState]: @@ -482,6 +634,15 @@ def _lean_states() -> list[LeanAbstractState]: ] +def _comparator_states() -> list[ComparatorAbstractState]: + return [ + ComparatorAbstractState(status=status, digest_state=digest_state, exit_code=exit_code) + for status, digest_state, exit_code in itertools.product( + ComparatorStatus, DigestState, (0, 1) + ) + ] + + def _tlc_states() -> list[TlcAbstractState]: exit_codes = ( tlc_adapter.SUCCESS, @@ -495,6 +656,7 @@ def _tlc_states() -> list[TlcAbstractState]: simulation_mode=simulation_mode, summary_state=summary_state, completed_banner=completed_banner, + config_digest_match=config_digest_match, property_state=property_state, bounds_state=bounds_state, ) @@ -503,6 +665,7 @@ def _tlc_states() -> list[TlcAbstractState]: simulation_mode, summary_state, completed_banner, + config_digest_match, property_state, bounds_state, ) in itertools.product( @@ -510,18 +673,59 @@ def _tlc_states() -> list[TlcAbstractState]: (False, True), TlcSummaryState, (False, True), + (True, False), TlcPropertyState, TlcBoundsState, ) ] +def _property_states() -> list[PropertyAbstractState]: + return [ + PropertyAbstractState( + outcome=outcome, + generator_present=generator_present, + measured_examples=measured_examples, + pinned_steps=pinned_steps, + measured_steps=measured_steps, + ) + for ( + outcome, + generator_present, + measured_examples, + pinned_steps, + measured_steps, + ) in itertools.product( + ("passed", "failed", "skipped", "error"), + (True, False), + (10, PROP_PINNED_EXAMPLES, 100), + (0, 10), + (0, 5, 10), + ) + ] + + +def _node_states() -> list[NodeAbstractState]: + return [ + NodeAbstractState( + required_present=required_present, + directive=directive, + verdict=verdict, + code=code, + ) + for required_present, directive, verdict, code in itertools.product( + (True, False), + (None, "SKIP", "TODO"), + ("ok", "not ok"), + (node_adapter.ASSERTION_CODE, "ERR_TEST_FAILURE"), + ) + ] + + def _check_lean_space(root: Path) -> dict[str, Any]: challenge_rel = f"{LEAN_MODULE}.lean" challenge_path = root / challenge_rel - challenge_bytes = b"theorem main_theorem : True := trivial\n" - challenge_path.write_bytes(challenge_bytes) - measured_sha256 = hashlib.sha256(challenge_bytes).hexdigest() + measured_sha256 = hashlib.sha256(b"theorem main_theorem : True := trivial\n").hexdigest() check = LeanCheck( id="formal-lean-check", @@ -543,8 +747,8 @@ def _check_lean_space(root: Path) -> dict[str, Any]: for state in states: raw = _build_lean_report(state, challenge_path, measured_sha256) - result = lean_adapter.interpret(raw, check) - actual = _classify_lean_result(result) + result = lean_adapter.interpret(raw, check, measured_challenge_sha256=measured_sha256) + actual = _classify_result(result) expected = _lean_oracle(state) if actual != expected: oracle_mismatches.append({ @@ -572,7 +776,6 @@ def _check_lean_space(root: Path) -> dict[str, Any]: }) trust_checks += 1 - # Also verify logical_trust_from_report directly on an unreported theorem report. unreported_state = LeanAbstractState( digest_state=DigestState.MATCH, build1_exit=0, @@ -594,7 +797,6 @@ def _check_lean_space(root: Path) -> dict[str, Any]: }) trust_checks += 1 - # Also verify unreviewed comparator profile statuses. comparator_check = LeanCheck( id="formal-lean-comparator", cwd=root, @@ -608,40 +810,41 @@ def _check_lean_space(root: Path) -> dict[str, Any]: permitted_axioms=LEAN_PERMITTED_AXIOMS, toolchain=ToolchainRef(tool="lean", version=LEAN_VERSION, comparator="comparator"), ) - comparator_expected: dict[ComparatorStatus, ExpectedOutcome] = { - ComparatorStatus.ACCEPTED: ExpectedOutcome(OutcomeKind.PASS), - ComparatorStatus.REJECTED: ExpectedOutcome( - OutcomeKind.BLOCKED, BlockedReason.FORMAL_OBLIGATION, "proof_rejected" - ), - ComparatorStatus.CHALLENGE_CHANGED: ExpectedOutcome( - OutcomeKind.BLOCKED, BlockedReason.NOT_APPROVED, "challenge_changed" - ), - ComparatorStatus.UNKNOWN: ExpectedOutcome( - OutcomeKind.BLOCKED, BlockedReason.ARTIFACT_MALFORMED, "report_malformed" - ), - } - for status in ComparatorStatus: + comp_states = _comparator_states() + for state in comp_states: + digest = ( + measured_sha256 if state.digest_state is DigestState.MATCH + else "" if state.digest_state is DigestState.EMPTY + else LEAN_WRONG_DIGEST + ) payload = json.dumps({ - "status": status.value, - "challenge_sha256": LEAN_WRONG_DIGEST, - "exit_code": 1, - "output": "proof rejected", + "version": 1, + "status": state.status.value, + "challenge_sha256": digest, + "exit_code": state.exit_code, + "output": "proof rejected" if state.exit_code else "", "sandbox": "bubblewrap", "comparator_version": "0.1.0", }).encode("utf-8") - actual = _classify_lean_result(lean_adapter.interpret(payload, comparator_check)) - expected = comparator_expected[status] + actual = _classify_result(lean_adapter.interpret(payload, comparator_check)) + expected = _comparator_oracle(state) if actual != expected: oracle_mismatches.append({ - "state": f"comparator:{status.value}", + "state": repr(state), "expected": repr(expected), "actual": repr(actual), }) + violations = _comparator_safety_violations(state, actual) + if violations: + safety_violations.append({ + "state": repr(state), + "violations": violations, + }) return { "reviewed_tuples": len(states), - "comparator_tuples": len(ComparatorStatus), - "total_tuples": len(states) + len(ComparatorStatus), + "comparator_tuples": len(comp_states), + "total_tuples": len(states) + len(comp_states), "pass_tuples": pass_count, "logical_trust_checks": trust_checks, "oracle_mismatches": len(oracle_mismatches), @@ -652,9 +855,6 @@ def _check_lean_space(root: Path) -> dict[str, Any]: def _check_tlc_space(root: Path) -> dict[str, Any]: - (root / TLC_MODEL_PATH).write_text("---- MODULE SpecModel ----\n====\n", encoding="utf-8") - config_file = root / TLC_CONFIG_PATH - check = TlcCheck( id="formal-tlc-check", cwd=root, @@ -676,9 +876,8 @@ def _check_tlc_space(root: Path) -> dict[str, Any]: for state in states: raw, config_text = _build_tlc_report_and_config(state) - config_file.write_text(config_text, encoding="utf-8") - result = tlc_adapter.interpret(raw, check) - actual = _classify_tlc_result(result) + result = tlc_adapter.interpret(raw, check, config_text=config_text) + actual = _classify_result(result) expected = _tlc_oracle(state) if actual != expected: oracle_mismatches.append({ @@ -708,6 +907,137 @@ def _check_tlc_space(root: Path) -> dict[str, Any]: } +def _check_property_space(root: Path) -> dict[str, Any]: + states = _property_states() + oracle_mismatches: list[dict[str, Any]] = [] + safety_violations: list[dict[str, Any]] = [] + pass_count = 0 + + for state in states: + check = PropertyCheck( + id="formal-property-check", + cwd=root, + timeout_seconds=30.0, + artifact_name="pytest-report.json", + required_tests=(PROP_TEST_ID,), + runner=PinnedRunner("pytest", ()), + report_format="json", + expect_report_version=1, + generator=HypothesisSettings( + max_examples=PROP_PINNED_EXAMPLES, + stateful_step_count=state.pinned_steps, + ), + ) + generator_doc = ( + { + "max_examples": state.measured_examples, + "stateful_step_count": state.measured_steps, + "deadline": None, + "suppress_health_check": [], + "database": None, + } + if state.generator_present else None + ) + raw = json.dumps({ + "version": 1, + "complete": True, + "exit_code": 0 if state.outcome == "passed" else 1, + "tests": [{ + "nodeid": PROP_TEST_ID, + "outcome": state.outcome, + "duration": 0.1, + "message": "assertion failed" if state.outcome == "failed" else "", + "generator": generator_doc, + }], + }).encode("utf-8") + result = property_adapter.interpret(raw, check) + actual = _classify_result(result) + expected = _property_oracle(state) + if actual != expected: + oracle_mismatches.append({ + "state": repr(state), + "expected": repr(expected), + "actual": repr(actual), + }) + violations = _property_safety_violations(state, actual) + if violations: + safety_violations.append({ + "state": repr(state), + "violations": violations, + }) + if actual.kind is OutcomeKind.PASS: + pass_count += 1 + + return { + "total_tuples": len(states), + "pass_tuples": pass_count, + "oracle_mismatches": len(oracle_mismatches), + "safety_violations": len(safety_violations), + "sample_mismatch": oracle_mismatches[0] if oracle_mismatches else None, + "sample_violation": safety_violations[0] if safety_violations else None, + } + + +def _check_node_space(root: Path) -> dict[str, Any]: + check = NodeTestCheck( + id="formal-node-check", + cwd=root, + timeout_seconds=30.0, + artifact_name="tap.txt", + required_tests=(NODE_TEST_ID,), + runner=PinnedRunner("node", ("--test",)), + report_format="tap", + expect_report_version=13, + ) + states = _node_states() + oracle_mismatches: list[dict[str, Any]] = [] + safety_violations: list[dict[str, Any]] = [] + pass_count = 0 + + for state in states: + name = NODE_NAME if state.required_present else "other case" + directive = f" # {state.directive} reason" if state.directive else "" + lines = [ + "TAP version 13", + f"{state.verdict} 1 - {name}{directive}", + " ---", + " duration_ms: 1.0", + " type: 'test'", + f" location: '{NODE_FILE}'", + ] + if state.verdict == "not ok": + lines.append(f" code: {state.code}") + lines.append(' message: "failed"') + lines.extend([" ...", "1..1"]) + raw = ("\n".join(lines) + "\n").encode("utf-8") + result = node_adapter.interpret(raw, check) + actual = _classify_result(result) + expected = _node_oracle(state) + if actual != expected: + oracle_mismatches.append({ + "state": repr(state), + "expected": repr(expected), + "actual": repr(actual), + }) + violations = _node_safety_violations(state, actual) + if violations: + safety_violations.append({ + "state": repr(state), + "violations": violations, + }) + if actual.kind is OutcomeKind.PASS: + pass_count += 1 + + return { + "total_tuples": len(states), + "pass_tuples": pass_count, + "oracle_mismatches": len(oracle_mismatches), + "safety_violations": len(safety_violations), + "sample_mismatch": oracle_mismatches[0] if oracle_mismatches else None, + "sample_violation": safety_violations[0] if safety_violations else None, + } + + def _run_mutant( name: str, target_module: Any, @@ -768,6 +1098,31 @@ def mutated(raw: bytes) -> lean_adapter.LeanRun | Blocked: ) return mutated + def lean_ignore_audit_exit_code(original: Callable[[bytes], lean_adapter.LeanRun | Blocked]) -> Callable[[bytes], lean_adapter.LeanRun | Blocked]: + def mutated(raw: bytes) -> lean_adapter.LeanRun | Blocked: + parsed = original(raw) + if isinstance(parsed, Blocked): + return parsed + steps = tuple( + {**step, "exit_code": 0} if step.get("name") == "audit" else step + for step in parsed.steps + ) + return lean_adapter.LeanRun( + parsed.module, parsed.source, parsed.profile, parsed.tool_version, + parsed.challenge_sha256, parsed.theorems, steps, + ) + return mutated + + def lean_comparator_ignore_digest_and_exit(original: Callable[..., Any]) -> Callable[..., Any]: + def mutated(raw: bytes, check: LeanCheck) -> Any: + doc = json.loads(raw.decode("utf-8")) + if doc.get("status") == "accepted": + doc["challenge_sha256"] = check.challenge_sha256 + doc["exit_code"] = 0 + raw = json.dumps(doc).encode("utf-8") + return original(raw, check) + return mutated + def tlc_ignore_left_on_queue(original: Callable[[tlc_adapter.TlcRun], tlc_adapter.Exploration | None]) -> Callable[[tlc_adapter.TlcRun], tlc_adapter.Exploration | None]: def mutated(report: tlc_adapter.TlcRun) -> tlc_adapter.Exploration | None: exp = original(report) @@ -798,62 +1153,90 @@ def mutated(report: tlc_adapter.TlcRun) -> tlc_adapter.Exploration | None: ) return mutated + def tlc_ignore_config_sha256(original: Callable[[bytes], tlc_adapter.TlcRun | Blocked]) -> Callable[[bytes], tlc_adapter.TlcRun | Blocked]: + def mutated(raw: bytes) -> tlc_adapter.TlcRun | Blocked: + parsed = original(raw) + if isinstance(parsed, Blocked): + return parsed + return tlc_adapter.TlcRun( + parsed.model, parsed.model_path, parsed.config, parsed.tool_version, + parsed.jar_sha256, parsed.fingerprint, parsed.exit_code, parsed.stdout, + parsed.stderr, parsed.trace_json_supported, parsed.witness_validation, + parsed.trace_artifact, parsed.validation_artifact, config_sha256=None, + ) + return mutated + + def tlc_accept_incomplete_witness(original: Callable[[bytes], tlc_adapter.TlcRun | Blocked]) -> Callable[[bytes], tlc_adapter.TlcRun | Blocked]: + def mutated(raw: bytes) -> tlc_adapter.TlcRun | Blocked: + parsed = original(raw) + if isinstance(parsed, Blocked) or not isinstance(parsed.witness_validation, dict): + return parsed + wv = dict(parsed.witness_validation) + wv.setdefault("method", "mutated") + wv.setdefault("state_sequence_sha256", "f" * 64) + wv.setdefault("minimization", {}) + return tlc_adapter.TlcRun( + parsed.model, parsed.model_path, parsed.config, parsed.tool_version, + parsed.jar_sha256, parsed.fingerprint, parsed.exit_code, parsed.stdout, + parsed.stderr, parsed.trace_json_supported, wv, + parsed.trace_artifact, parsed.validation_artifact, config_sha256=parsed.config_sha256, + ) + return mutated + + def property_ignore_generator_bounds(original: Callable[[dict], HypothesisSettings]) -> Callable[[dict], HypothesisSettings]: + def mutated(doc: dict) -> HypothesisSettings: + measured = original(doc) + return HypothesisSettings( + max_examples=max(measured.max_examples, PROP_PINNED_EXAMPLES), + stateful_step_count=max(measured.stateful_step_count, 10), + deadline=measured.deadline, + suppress_health_check=measured.suppress_health_check, + ) + return mutated + + def node_treat_todo_as_pass(original: Callable[..., str]) -> Callable[..., str]: + def mutated(entry: Any, block: str) -> str: + if entry.group("directive") == "TODO": + return node_adapter.PASSED + return original(entry, block) + return mutated + return [ - _run_mutant( - "lean_drop_sorry_axiom", - lean_adapter, - "_audit_records", - lean_drop_sorry_axiom, - _check_lean_space, - root, - ), - _run_mutant( - "lean_skip_recheck2", - lean_adapter, - "_read", - lean_skip_recheck2, - _check_lean_space, - root, - ), - _run_mutant( - "tlc_ignore_left_on_queue", - tlc_adapter, - "_exploration", - tlc_ignore_left_on_queue, - _check_tlc_space, - root, - ), - _run_mutant( - "tlc_ignore_completion_banner", - tlc_adapter, - "_exploration", - tlc_ignore_completion_banner, - _check_tlc_space, - root, - ), + _run_mutant("lean_drop_sorry_axiom", lean_adapter, "_audit_records", lean_drop_sorry_axiom, _check_lean_space, root), + _run_mutant("lean_skip_recheck2", lean_adapter, "_read", lean_skip_recheck2, _check_lean_space, root), + _run_mutant("lean_ignore_audit_exit_code", lean_adapter, "_read", lean_ignore_audit_exit_code, _check_lean_space, root), + _run_mutant("lean_comparator_ignore_digest_and_exit", lean_adapter, "_comparator_result", lean_comparator_ignore_digest_and_exit, _check_lean_space, root), + _run_mutant("tlc_ignore_left_on_queue", tlc_adapter, "_exploration", tlc_ignore_left_on_queue, _check_tlc_space, root), + _run_mutant("tlc_ignore_completion_banner", tlc_adapter, "_exploration", tlc_ignore_completion_banner, _check_tlc_space, root), + _run_mutant("tlc_ignore_config_sha256", tlc_adapter, "_read", tlc_ignore_config_sha256, _check_tlc_space, root), + _run_mutant("tlc_accept_incomplete_witness", tlc_adapter, "_read", tlc_accept_incomplete_witness, _check_tlc_space, root), + _run_mutant("property_ignore_generator_bounds", property_adapter, "_measured", property_ignore_generator_bounds, _check_property_space, root), + _run_mutant("node_treat_todo_as_pass", node_adapter, "_outcome_of", node_treat_todo_as_pass, _check_node_space, root), ] def run() -> dict[str, Any]: - """Run exhaustive Lean and TLC interpreter checks plus negative-control mutants.""" + """Run exhaustive Lean, TLC, Property, and Node interpreter checks plus negative-control mutants.""" with tempfile.TemporaryDirectory(prefix="vkit_formal_interpreters_") as tmp: root = Path(tmp) lean_summary = _check_lean_space(root) tlc_summary = _check_tlc_space(root) + property_summary = _check_property_space(root) + node_summary = _check_node_space(root) mutants = _run_negative_controls(root) all_mutants_caught = all(item["caught"] for item in mutants) + summaries = (lean_summary, tlc_summary, property_summary, node_summary) ok = ( - lean_summary["oracle_mismatches"] == 0 - and lean_summary["safety_violations"] == 0 - and tlc_summary["oracle_mismatches"] == 0 - and tlc_summary["safety_violations"] == 0 + all(s["oracle_mismatches"] == 0 and s["safety_violations"] == 0 for s in summaries) and all_mutants_caught ) return { "ok": ok, "lean": lean_summary, "tlc": tlc_summary, + "property": property_summary, + "node": node_summary, "negative_controls": mutants, "all_mutants_caught": all_mutants_caught, } diff --git a/formal/checks/check_verus_ledger.py b/formal/checks/check_verus_ledger.py deleted file mode 100644 index 0f85fe4..0000000 --- a/formal/checks/check_verus_ledger.py +++ /dev/null @@ -1,558 +0,0 @@ -"""Compare the pinned Verus ledger proof with deliberately incorrect bodies.""" -from __future__ import annotations - -import argparse -import hashlib -import json -import os -import re -import signal -import stat -import subprocess -import sys -import time -import zipfile -from pathlib import Path, PurePosixPath - -sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "src")) -from vkit.formal.ledger import ASSETS, CONTRACT, PACKAGE_ID, PROFILE, VERSION -from vkit.formal.qualification import ( - compare_package_snapshots, - mutation_control, - normalize_package_snapshot, - package_snapshot, -) -from vkit.runtime.nowindow import hidden_window - -ROOT = Path(__file__).resolve().parents[2] - -PACKAGE = ROOT / "src/vkit/formal/packages/resource_ledger" -PIN_PATH = PACKAGE / "upstream.json" -SOURCE = PACKAGE / "ledger.rs" -SMOKE = ROOT / "examples/verus-qualification/smoke.rs" -ADEQUACY_FIXTURES = ROOT / "examples/verus-qualification" -HISTORICAL_POSITIVE_LIMIT_FIX = { - "commit": "48ea7b7260d6ac7fe77474ae2fdac72fb9fb4cc5", - "source_path": "formal/packages/resource_ledger/Model.v", - "source_sha256": "4ef80555b3834bed3e9a5bbd8b581fdb0d2315233d77d53586523ba2703c5070", - "change": "max_records and batch_bound changed from nat to positive", - "reconstruction": "Verus shared-vocabulary zero-bound control; not a replay of the Rocq proof", -} -MUTATIONS = { - "lost_accounting": ("next.used = next.used + amount;", "next.used = amount;"), - "duplicate_id": ("if entry.id == id {", "if false {"), - "wrong_owner": ("if entry.owner != owner {", "if false {"), - "capacity_bypass": ( - "if amount > ledger.capacity - ledger.used {\n return", - "if false {\n return", - ), - "rejection_changes_state": ( - "return (ledger, Err(LedgerError::ZeroAmount));", - "return (new(ledger.slots, ledger.capacity), Err(LedgerError::ZeroAmount));", - ), - "wrong_release_amount": ("return (next, Ok(entry.amount));", "return (next, Ok(0));"), - "partial_batch_commit": ( - "ledger, BatchResponse::RequestFailed { index: 1, error },", - "current, BatchResponse::RequestFailed { index: 1, error },", - ), - "wrong_batch_index": ( - "BatchResponse::RequestFailed { index: 1, error },", - "BatchResponse::RequestFailed { index: 0, error },", - ), - "batch_bound_bypass": ( - "if count > 3 {\n return (ledger, BatchResponse::TooManyRequests);", - "if false {\n return (ledger, BatchResponse::TooManyRequests);", - ), - "wrong_trace_response": ( - "responses[i] = response;", - "responses[i] = Response::Reserved(Ok(()));", - ), - "assumed_proof": ( - " let ledger = Ledger { slots, used: 0, capacity };", - " assume(false);\n let ledger = Ledger { slots, used: 0, capacity };", - ), -} - - -def digest(data: bytes) -> str: - return hashlib.sha256(data).hexdigest() - - -def archive_files(archive: Path, pin: dict) -> dict[str, str]: - with archive.open("rb") as stream: - if hashlib.file_digest(stream, "sha256").hexdigest() != pin["archives"].get(archive.name): - raise ValueError("archive does not match its official pin") - files, roots = {}, set() - with zipfile.ZipFile(archive) as bundle: - for item in bundle.infolist(): - if item.is_dir(): - continue - path = PurePosixPath(item.filename) - if path.is_absolute() or ".." in path.parts or len(path.parts) < 2: - raise ValueError("archive contains an unsafe path") - if item.external_attr >> 16 & 0o170000 not in {0, stat.S_IFREG}: - raise ValueError("archive contains a non-regular tool") - roots.add(path.parts[0]) - relative = PurePosixPath(*path.parts[1:]).as_posix() - if relative in files: - raise ValueError("archive contains duplicate paths") - with bundle.open(item) as stream: - files[relative] = hashlib.file_digest(stream, "sha256").hexdigest() - if len(roots) != 1: - raise ValueError("archive has an unexpected root layout") - return files - - -def inventory_digest(files: dict[str, str]) -> str: - return digest(json.dumps(files, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()) - - -def run(command: list[str], output: Path, cwd: Path) -> dict: - start = time.monotonic() - env = os.environ.copy() - env.pop("VERUS_Z3_PATH", None) - with output.open("w", encoding="utf-8") as log: - try: - process = subprocess.Popen(command, cwd=cwd, env=env, stdout=log, - stderr=subprocess.STDOUT, start_new_session=os.name != "nt", - **hidden_window()) - except OSError as exc: - return {"command": command, "returncode": None, - "seconds": round(time.monotonic() - start, 3), "log": output.name, - "error": f"{type(exc).__name__}: {exc}"} - with process: - try: - code = process.wait(timeout=180) - except subprocess.TimeoutExpired: - if os.name == "nt": - subprocess.run(["taskkill", "/PID", str(process.pid), "/T", "/F"], - stdout=log, stderr=subprocess.STDOUT, check=False, - **hidden_window()) - else: - os.killpg(process.pid, signal.SIGKILL) - process.wait() - code = None - return {"command": command, "returncode": code, - "seconds": round(time.monotonic() - start, 3), "log": output.name} - - -def tool_identity(archive: Path, tool_root: Path, pin: dict) -> dict: - expected = pin["archives"].get(archive.name) - if expected is None or digest(archive.read_bytes()) != expected: - raise ValueError("archive does not match the pinned official release") - version = json.loads((tool_root / "version.json").read_text())["verus"] - if version["commit"] != pin["revision"] or version["version"] != pin["version"]: - raise ValueError("tool version does not match the pinned release") - hashes = archive_files(archive, pin) - if pin.get("expanded_files", {}).get(archive.name) != inventory_digest(hashes): - raise ValueError("expanded-file pin differs from the official archive") - for relative, expected_hash in hashes.items(): - path = tool_root / relative - if not path.is_file() or path.is_symlink() or digest(path.read_bytes()) != expected_hash: - raise ValueError(f"tool file differs from the pinned archive: {relative}") - return {"archive_sha256": expected, "version": version, "files": hashes} - - -def check_binding(exe: Path, captured: Path, out: Path, report: dict, - package_identity_sha256: str, tool_identity_sha256: str) -> bool: - root = out / "binding" - root.mkdir() - fixtures = ROOT / "examples/verus-qualification" - candidate = (fixtures / "candidate_api.rs").read_text(encoding="utf-8") - template = (PACKAGE / "expected.rs.in").read_text(encoding="utf-8") - expected = (fixtures / "expected.rs").read_text(encoding="utf-8") - report["binding_template_sha256"] = digest(template.encode()) - report["binding_scope"] = "Six required_api bindings over the fixed checked ledger library; not arbitrary source or representation correspondence" - report["binding_expected_sha256"] = digest(expected.encode()) - flags = ["--no-cheating", "--no-external-by-default", "--num-threads", "2"] - - def control(name: str, mutation_path: Path, result: dict, diagnostic: str | None, - evidence_present: bool) -> dict: - row = mutation_control( - name=name, mutation_sha256=digest(mutation_path.read_bytes()), - package_identity_sha256=package_identity_sha256, - tool_identity_sha256=tool_identity_sha256, - returncode=result["returncode"], timed_out=result["returncode"] is None and - "error" not in result, diagnostic=diagnostic, evidence_present=evidence_present, - infrastructure_error="error" in result, - ) - report["mutation_controls"].append(row) - return row - - def verify(name: str, args: list[str], cwd: Path, *, missing_symbol: str | None = None) -> dict: - log_path = out / f"{name}.log" - result = run([str(exe), "--crate-type=lib", *args, *flags], log_path, cwd) - log = log_path.read_text(encoding="utf-8", errors="replace") - proof_rejection = result["returncode"] not in {None, 0} and bool(re.search( - r"verification results:: \d+ verified, [1-9]\d* errors", log)) - symbol_rejection = (missing_symbol is not None and result["returncode"] not in {None, 0} - and not proof_rejection and "candidate_api" in log - and missing_symbol.lower() in log.lower()) - verified = result["returncode"] == 0 and bool(re.search( - r"verification results:: [1-9]\d* verified, 0 errors", log)) - return {"result": result, "log": log, "verified": verified, - "proof_rejection": proof_rejection, "symbol_rejection": symbol_rejection} - - def record(name: str, outcome: dict) -> None: - report["checks"].append({"name": name, **outcome["result"], - "verified": outcome["verified"]}) - - def function_bounds(text: str, api: str) -> tuple[int, int]: - start = text.index(f" pub fn {api}<") - next_function = text.find("\n pub fn ", start + 1) - end = next_function if next_function >= 0 else text.rfind("\n}") - return start, end - - def changed_candidate(api: str, mutation: str) -> str: - text = candidate - start, end = function_bounds(text, api) - block = text[start:end] - signature_end = block.index("\n {") - contract = block[:signature_end] - if mutation == "weak_contract": - contract, count = re.subn( - r" ensures\n.*", " ensures true,", - contract, count=1, flags=re.DOTALL, - ) - elif mutation == "stronger_precondition": - contract, count = re.subn( - r" requires [^\n]+,", " requires false,", contract, count=1, - ) - elif mutation == "missing_symbol": - return text[:start] + text[end:] - else: - raise ValueError(f"unknown binding mutation: {mutation}") - if count != 1: - raise ValueError(f"could not mutate {api} for {mutation}") - return text[:start] + contract + block[signature_end:end] + text[end:] - - def export_and_claim(name: str, source: str, *, expected_diagnostic: str | None = None) -> bool: - directory = root / name - directory.mkdir() - candidate_path = directory / "candidate_api.rs" - candidate_path.write_text(source, encoding="utf-8", newline="\n") - expected_path = directory / "expected.rs" - expected_path.write_text(expected, encoding="utf-8", newline="\n") - report[f"{name}_candidate_sha256"] = digest(candidate_path.read_bytes()) - export = verify(f"{name}_export", [str(candidate_path), *imports, "--export", - str(directory / "candidate_api.vir"), "--compile"], directory) - record(f"{name}_export", export) - if not export["verified"]: - control(f"{name}_export", candidate_path, export["result"], None, - export["result"].get("returncode") is not None and bool(export["log"].strip())) - return False - client = [str(expected_path), *imports, - "--import", f"candidate_api={directory / 'candidate_api.vir'}", - "--extern", f"candidate_api={directory / 'libcandidate_api.rlib'}", "-L", str(directory)] - claim = verify(f"{name}_claim", client, directory, - missing_symbol=name[len("binding_"):-len("_missing_symbol")] - if expected_diagnostic == "compile_missing_symbol" else None) - if expected_diagnostic is None: - record(f"{name}_claim", claim) - return claim["verified"] - observed = ("proof" if claim["proof_rejection"] else - "compile_missing_symbol" if claim["symbol_rejection"] else "unexpected") - accepted = observed == expected_diagnostic - diagnostic = ("proof_rejection" if observed == "proof" else - "missing_symbol" if observed == "compile_missing_symbol" else - "verified" if claim["verified"] else None) - control(f"{name}_claim", candidate_path, claim["result"], diagnostic, - claim["result"].get("returncode") is not None and bool(claim["log"].strip())) - report["checks"].append({ - "name": f"{name}_claim", - "expected_diagnostic": expected_diagnostic, - "observed_diagnostic": diagnostic or "unclassified", - "accepted_qualification_diagnostic": accepted, - "qualification_status": report["mutation_controls"][-1]["status"], - **claim["result"], - }) - return accepted - - ledger = verify("binding_ledger_export", [str(captured), "--export", str(root / "ledger.vir"), - "--compile"], root) - record("binding_ledger_export", ledger) - if not ledger["verified"]: - return False - imports = ["--import", f"ledger={root / 'ledger.vir'}", - "--extern", f"ledger={root / 'libledger.rlib'}", "-L", str(root)] - success = export_and_claim("binding_positive", candidate) - for api in ("new", "reserve", "release", "reserve_batch", "apply_command", "run_commands"): - for mutation, rejection in (("weak_contract", "proof"), - ("stronger_precondition", "proof"), - ("missing_symbol", "compile_missing_symbol")): - name = f"binding_{api}_{mutation}" - success = export_and_claim(name, changed_candidate(api, mutation), - expected_diagnostic=rejection) and success - return success - - -def check_specification_adequacy(exe: Path, out: Path, binding_root: Path, report: dict) -> bool: - root = out / "specification-adequacy" - root.mkdir() - identities = { - "package_identity_sha256": report["package_identity_sha256"], - "tool_identity_sha256": report["tool_identity_sha256"], - } - flags = ["--no-cheating", "--no-external-by-default", "--num-threads", "2"] - fixtures = ( - { - "name": "reserve_capacity_equivalence", - "file": "reserve-admission.rs", - "status": "verified_equivalence", - "predicates": { - "current": "amount <= state.capacity - state.used", - "rewritten": "state.used as nat + amount as nat <= state.capacity as nat", - "reserve_result_view": "Ok iff amount > 0, id absent, slots not full, and rewritten capacity predicate", - }, - "scope": "reserve_result_view capacity admission and Ok branch for every valid LedgerView", - }, - { - "name": "reserve_strict_bound_control", - "file": "reserve-strict-bound.rs", - "status": "checked_counterexample", - "predicates": { - "current": "amount <= state.capacity - state.used", - "mutated": "state.used as nat + amount as nat < state.capacity as nat", - }, - "scope": "exact-capacity reserve request in the shared ledger_api model", - "witness": { - "records": 2, - "reserve_precondition": "N > 0 && valid_view(input.view())", - "precondition_inhabited": True, - "existing_entry": {"id": 1, "owner": 9, "amount": 7}, - "request": {"id": 2, "owner": 11, "amount": 3}, - "capacity": 10, - "current_result": "Ok", - "mutated_result": "rejected by strict bound", - }, - }, - { - "name": "historical_positive_limit_regression", - "file": "historical-positive-limit.rs", - "status": "checked_counterexample", - "predicates": { - "historical": "max_records : nat (zero admitted)", - "fixed": "max_records : positive (zero excluded)", - "shared_vocabulary_witness": "valid_view::<0>(LedgerView { slots: [], used: 0, capacity: 0 })", - }, - "scope": "reconstructed zero-bound regression mapped to the current ledger slot bound", - "witness": {"record_limit": 0, "valid_view": True, "historical_admits": True, "fixed_rejects": True}, - "provenance": HISTORICAL_POSITIVE_LIMIT_FIX, - }, - ) - rows = [] - all_passed = True - for fixture in fixtures: - source = ADEQUACY_FIXTURES / fixture["file"] - source_sha256 = digest(source.read_bytes()) - log_path = root / f"{fixture['name']}.log" - result = run( - [str(exe), "--crate-type=lib", str(source), - "--import", f"ledger={binding_root / 'ledger.vir'}", - "--extern", f"ledger={binding_root / 'libledger.rlib'}", "-L", str(binding_root), *flags], - log_path, root, - ) - log = log_path.read_text(encoding="utf-8", errors="replace") if log_path.is_file() else "" - verified = result["returncode"] == 0 and bool(re.search( - r"verification results:: [1-9]\d* verified, 0 errors", log)) - status = fixture["status"] if verified else "inconclusive" - row = {"name": fixture["name"], "status": status, "predicates": fixture["predicates"], - "scope": fixture["scope"], "proof_source_sha256": source_sha256, **identities} - if verified and "witness" in fixture: - row["witness"] = fixture["witness"] - if "provenance" in fixture: - row["provenance"] = fixture["provenance"] - row["verifier_log"] = log_path.name - row["verifier_log_sha256"] = digest(log_path.read_bytes()) if log_path.is_file() else None - row["verifier_returncode"] = result["returncode"] - if "error" in result: - row["verifier_error"] = result["error"] - rows.append(row) - report["checks"].append({ - "name": fixture["name"], "verified": verified, - "source_sha256": source_sha256, **result, - }) - all_passed = all_passed and verified - positive_source = (ADEQUACY_FIXTURES / "reserve-admission.rs").read_text(encoding="utf-8") - negative_source = root / "false-capacity-equivalence.rs" - marker = "<= (state.capacity as nat)" - if positive_source.count(marker) != 1: - raise ValueError("capacity-equivalence control no longer matches its checked source") - negative_source.write_text(positive_source.replace(marker, "< (state.capacity as nat)"), encoding="utf-8") - negative_log = root / "false-capacity-equivalence.log" - result = run( - [str(exe), "--crate-type=lib", str(negative_source), - "--import", f"ledger={binding_root / 'ledger.vir'}", - "--extern", f"ledger={binding_root / 'libledger.rlib'}", "-L", str(binding_root), *flags], - negative_log, root, - ) - log = negative_log.read_text(encoding="utf-8", errors="replace") if negative_log.is_file() else "" - rejected = bool(re.search(r"verification results:: \d+ verified, [1-9]\d* errors", log)) - control = mutation_control( - name="false_capacity_equivalence", mutation_sha256=digest(negative_source.read_bytes()), - **identities, returncode=result["returncode"], - timed_out=result["returncode"] is None and "error" not in result, - infrastructure_error="error" in result, - diagnostic="proof_rejection" if rejected else "verified" if result["returncode"] == 0 else None, - evidence_present=bool(log.strip()), - ) - control.update(verifier_log=negative_log.name, - verifier_log_sha256=digest(negative_log.read_bytes()) if negative_log.is_file() else None) - report["semantic_controls"] = [control] - all_passed = all_passed and control["status"] == "detected_rejection" - report["semantic_checks"] = rows - report["semantic_checks_passed"] = all_passed - return all_passed - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--verus-root", type=Path) - parser.add_argument("--archive", type=Path, required=True) - parser.add_argument("--output", type=Path) - parser.add_argument("--compare-package", type=Path, - help="compare assets, obligations, and trust identity with a prior package snapshot or report") - parser.add_argument("--pin-extracted", action="store_true", help="derive the compact expanded-file pin from the verified official archive") - args = parser.parse_args() - pin = json.loads(PIN_PATH.read_text()) - if args.pin_extracted: - pin.setdefault("expanded_files", {})[args.archive.name] = inventory_digest(archive_files(args.archive, pin)) - PIN_PATH.write_text(json.dumps(pin, indent=2) + "\n", encoding="utf-8") - return 0 - if args.verus_root is None or args.output is None: - parser.error("--verus-root and --output are required for qualification") - out = args.output.resolve() - out.mkdir(parents=True, exist_ok=False) - identity = tool_identity(args.archive.resolve(), args.verus_root.resolve(), pin) - source = SOURCE.read_text(encoding="utf-8") - forbidden = r"\b(?:assume|admit|unsafe|exec_spec_unverified)\b|verifier\s*::\s*(?:external\w*|exec_allows_no_decreases_clause)|include!" - if re.search(forbidden, source): - raise ValueError("ledger source contains a forbidden trust escape") - exe = args.verus_root.resolve() / ("verus.exe" if os.name == "nt" else "verus") - captured = out / "ledger.rs" - captured.write_text(source, encoding="utf-8", newline="\n") - smoke = out / "smoke.rs" - smoke.write_text(SMOKE.read_text(encoding="utf-8"), encoding="utf-8", newline="\n") - report = { - "scope": "Verus comparison experiment, not product qualification", - "assurance": "Verus/Rust/vstd/SMT trusted computing base; no independent kernel certificate", - "product_policy_accepted": False, - "operational_resource_bound": "not established", - "source_sha256": digest(captured.read_bytes()), - "unverified_runtime_test_sha256": digest(smoke.read_bytes()), - "driver_sha256": digest(Path(__file__).read_bytes()), - "pin_sha256": digest(PIN_PATH.read_bytes()), - "toolchain": identity, - "tool_identity_sha256": digest(json.dumps(identity, sort_keys=True, separators=(",", ":")).encode()), - "mutation_controls": [], - "semantic_checks": [], - "semantic_checks_passed": False, - "checks": [], - } - template = (PACKAGE / "expected.rs.in").read_text(encoding="utf-8") - obligations = ["resource-ledger:ledger_map_accounting"] - obligations.extend(f"resource-ledger:{name}" for name in - re.findall(r"pub fn expected_(\w+)", template)) - assets = {name: digest((PACKAGE / name).read_bytes()) for name in ASSETS} - assets.update({f"qualification/{path.name}": digest(path.read_bytes()) for path in ( - ADEQUACY_FIXTURES / "reserve-admission.rs", - ADEQUACY_FIXTURES / "reserve-strict-bound.rs", - ADEQUACY_FIXTURES / "historical-positive-limit.rs", - )}) - package = package_snapshot( - identity={"id": PACKAGE_ID, "version": VERSION, "contract": CONTRACT, "profile": PROFILE}, - assets=assets, - obligations=obligations, - trust_identity={"pin_sha256": report["pin_sha256"], - "tool_identity_sha256": report["tool_identity_sha256"]}, - ) - report["package_identity"] = package - report["package_identity_sha256"] = digest( - json.dumps(package, sort_keys=True, separators=(",", ":")).encode()) - if args.compare_package is not None: - try: - baseline_document = json.loads(args.compare_package.read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError) as exc: - raise ValueError(f"could not read package snapshot {args.compare_package}: {exc}") from exc - baseline = normalize_package_snapshot(baseline_document) - report["package_change_review"] = compare_package_snapshots(baseline, package) - for name, command in { - "verus_version": [str(exe), "--version"], - "solver_version": [str(exe.parent / ("z3.exe" if os.name == "nt" else "z3")), "--version"], - "rust_version": ["rustup", "run", identity["version"]["toolchain"].split()[0], "rustc", "--version"], - }.items(): - result = run(command, out / f"{name}.log", out) - report["checks"].append({"name": name, **result}) - if result["returncode"] != 0: - raise RuntimeError(f"could not capture {name}") - binary = out / ("ledger.exe" if exe.suffix else "ledger") - check = run([str(exe), str(captured), "--no-cheating", "--no-external-by-default", "--num-threads", "2", - "-V", "axiom-usage-info", "--log", "call-graph", "--log-dir", str(out / "call-graph")], - out / "verify.log", out) - report["checks"].append({"name": "verified_body", **check}) - log = (out / "verify.log").read_text(encoding="utf-8", errors="replace") - success = check["returncode"] == 0 and bool(re.search(r"verification results:: [1-9]\d* verified, 0 errors", log)) - if success: - for name, (before, after) in MUTATIONS.items(): - if before not in source: - raise ValueError(f"mutation no longer matches the checked implementation: {name}") - mutated = out / f"{name}.rs" - mutated.write_text(source.replace(before, after, 1), encoding="utf-8", newline="\n") - check = run([str(exe), str(mutated), "--no-cheating", "--no-external-by-default", "--num-threads", "2"], - out / f"{name}.log", out) - log = (out / f"{name}.log").read_text(encoding="utf-8", errors="replace") - diagnostic = ("trust_escape_rejection" if name == "assumed_proof" and - "assume/admit not allowed with --no-cheating" in log else - "proof_rejection" if re.search( - r"verification results:: \d+ verified, [1-9]\d* errors", log) else - "verified" if check["returncode"] == 0 and re.search( - r"verification results:: [1-9]\d* verified, 0 errors", log) else None) - control = mutation_control( - name=name, mutation_sha256=digest(mutated.read_bytes()), - package_identity_sha256=report["package_identity_sha256"], - tool_identity_sha256=report["tool_identity_sha256"], - returncode=check["returncode"], timed_out=check["returncode"] is None and - "error" not in check, diagnostic=diagnostic, evidence_present=bool(log.strip()), - infrastructure_error="error" in check, - ) - report["mutation_controls"].append(control) - rejected = control["status"] == "detected_rejection" - report["checks"].append({"name": name, - "sensitivity_detected": rejected, - "source_sha256": digest(mutated.read_bytes()), - "qualification": control, **check}) - success = success and rejected - report["binding_passed"] = check_binding( - exe, captured, out, report, report["package_identity_sha256"], - report["tool_identity_sha256"]) - success = success and report["binding_passed"] - if report["binding_passed"]: - success = check_specification_adequacy(exe, out, out / "binding", report) and success - compiled = run([str(exe), str(smoke), "--no-cheating", "--num-threads", "2", - "--compile", "-o", str(binary)], out / "compile.log", out) - report["checks"].append({"name": "compiled_verified_source", **compiled}) - success = success and compiled["returncode"] == 0 - if compiled["returncode"] == 0: - executed = run([str(binary)], out / "execution.log", out) - report["checks"].append({"name": "compiled_execution", **executed}) - success = success and executed["returncode"] == 0 and (out / "execution.log").read_text().strip() == "VKIT_LEDGER_SMOKE_OK" - report["mutation_controls_passed"] = bool(report["mutation_controls"]) and all( - control["status"] == "detected_rejection" for control in report["mutation_controls"]) - from check_p2_contracts import qualify - - report["package_contracts"] = qualify(exe, args.archive.resolve(), args.verus_root.resolve(), - out / "package-contracts", tool_identity=identity) - report["comparison_passed"] = (success and report["mutation_controls_passed"] - and report["semantic_checks_passed"] and report["package_contracts"]["passed"]) - (out / "report.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") - print(json.dumps({"comparison_passed": report["comparison_passed"], - "mutation_controls_passed": report["mutation_controls_passed"], - "semantic_checks_passed": report["semantic_checks_passed"], - "semantic_checks": report["semantic_checks"], - "mutation_controls": report["mutation_controls"], - "checks": report["checks"]}, indent=2)) - return 0 if report["comparison_passed"] else 1 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/formal/checks/qualify_ledger_reuse.py b/formal/checks/qualify_ledger_reuse.py deleted file mode 100644 index 89f98ec..0000000 --- a/formal/checks/qualify_ledger_reuse.py +++ /dev/null @@ -1,229 +0,0 @@ -"""Exercise two ledger interpretations and compare identical proof work.""" -from __future__ import annotations - -from dataclasses import replace -import json -from pathlib import Path -import statistics -import sys -import time -import uuid - -from check_ledger_container import ROOT, product_component, run -from vkit.runtime import container -from vkit.core import evidence -from vkit.core import jobs -from vkit.formal import ledger, verus -from vkit.formal.policy import OPERATIONS, LedgerBindings -from vkit.change.requests import GitCommit, PackageVerificationRequest -from vkit.formal.service import resolve_commit -from vkit.core.inputs import canonical_digest, capture_git_commit -from vkit.runtime.paths import open_project -from vkit.core.runner import execute, prepare_formal -from vkit.core.store import Store, now - - -def project_for(root, component, source): - (root / "verification").mkdir(parents=True) - (root / component.entry).write_text(source, encoding="utf-8") - (root / "verification/manifest.json").write_text(json.dumps({"schema_version": 3, "checks": [], - "formal": {"components": [component.to_json()]}}), encoding="utf-8") - for args in (("init", "-q"), ("add", "."), ("-c", "user.name=VKit CI", "-c", - "user.email=ci@vkit.invalid", "commit", "-qm", "reuse candidate")): - run(["git", "-C", str(root), *args]) - project = open_project(root) - return project, resolve_commit(project, "HEAD") - - -def approve(store, component, identity): - store.approve({component.digest: {"kind": "formal_policy", "policy_sha256": component.digest, - "package_sha256": component.package.sha256, - "checker_sha256": canonical_digest(identity["semantic"]), "accepted_at": now()}}) - - -def phase_seconds(output): - return sum(item["seconds"] for item in json.loads((output / "timings.json").read_text())) - - -def direct(component, snapshot, identity, directory): - started = time.monotonic() - current = verus.resolve_execution(component) - if current["semantic"] != identity["semantic"]: - raise RuntimeError("direct procedure execution identity changed") - package = ledger.verify_package(component) - trusted, output = directory / "trusted", directory / "output" - trusted.mkdir(parents=True) - output.mkdir() - output.chmod(0o777) - (trusted / "expected.rs").write_text(ledger.render_expected(component), encoding="utf-8") - (trusted / "runtime.rs").write_text(ledger.render_runtime(component), encoding="utf-8") - toolchain = identity["semantic"]["verus"]["version"]["toolchain"].split()[0] - phases = verus._verus_phases( - "/trusted/package", "/output/candidate_api.rs", "/trusted/rendered/expected.rs", - toolchain, identity["semantic"]["verus"]["version"]["version"], - ) - plan = {"source": "/source/" + component.entry, - "source_sha256": evidence.sha256(snapshot / component.entry), "phases": phases} - options = [*container.sealed_options(), "--workdir", "/work", - "--env", "RUSTUP_HOME=/assets/rustup", "--env", "CARGO_HOME=/assets/cargo", - "--env", "PATH=/assets/cargo/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", - *container.mount(snapshot, "/source", True), - *container.mount(package.root, "/trusted/package", True), - *container.mount(trusted, "/trusted/rendered", True), *container.mount(output, "/output", False)] - for key, target in (("verus_root", "/assets/verus"), ("rustup_home", "/assets/rustup"), ("cargo_home", "/assets/cargo")): - options += container.mount(Path(identity["paths"][key]), target, True) - result = container.run_container(image=identity["semantic"]["image_id"], - run_id=f"{directory.name}-{uuid.uuid4().hex}", options=options, - command=["python3", "-c", verus._CONTAINER_SCRIPT, json.dumps(plan)], - run_dir=directory, timeout_seconds=900, should_cancel=lambda: False) - if result.exit.code != 0 or not result.removed or not verus._expected_logs(output, phases)[0]: - raise RuntimeError(f"direct full-proof procedure failed: {result}") - return {"wall_seconds": time.monotonic() - started, "phase_seconds": phase_seconds(output)} - - -def runtime_fixture(fixture, component, proof, identity, directory): - commands, assertions = [], [] - for i, item in enumerate(fixture["commands"]): - if "reserve" in item: - id, owner, amount = item["reserve"] - commands.append(f"Command::Reserve {{ id: {id}, owner: {owner}, amount: {amount} }}") - else: - id, owner = item["release"] - commands.append(f"Command::Release {{ id: {id}, owner: {owner} }}") - assertions.append(f"assert!(matches!(responses[{i}], {item['expected']}));") - smoke = ("extern crate ledger; extern crate candidate_api;\n" - "use ledger::ledger_api::{Command, Response, LedgerError};\n" - f"use candidate_api::{fixture['namespace']} as api;\nfn main() {{\n" - f"let initial = api::new([None; {component.max_records}], {fixture['capacity']});\n" - f"let commands = [{','.join(commands)}];\n" - f"let mut responses = [Response::Reserved(Ok(())); {len(commands)}];\n" - "let _final_state = api::run_commands(initial, commands, &mut responses);\n" - + "\n".join(assertions) + '\nprintln!("VKIT_REUSE_OK");\n}\n') - directory.mkdir() - (directory / "smoke.rs").write_text(smoke, encoding="utf-8") - output = directory / "output" - output.mkdir() - output.chmod(0o777) - command = ["/assets/verus/verus", "/trusted/smoke.rs", "--no-cheating", "--compile", - "--import", "ledger=/proof/ledger.vir", "--extern", "ledger=/proof/libledger.rlib", - "--import", "candidate_api=/proof/candidate_api.vir", "--extern", "candidate_api=/proof/libcandidate_api.rlib", - "-L", "/proof", "-o", "/output/smoke"] - options = [*container.sealed_options(), "--workdir", "/output", - "--env", "RUSTUP_HOME=/assets/rustup", "--env", "CARGO_HOME=/assets/cargo", - "--env", "PATH=/assets/cargo/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", - *container.mount(directory, "/trusted", True), *container.mount(proof, "/proof", True), - *container.mount(output, "/output", False)] - for key, target in (("verus_root", "/assets/verus"), ("rustup_home", "/assets/rustup"), ("cargo_home", "/assets/cargo")): - options += container.mount(Path(identity["paths"][key]), target, True) - driver = "import subprocess,sys,json; subprocess.run(json.loads(sys.argv[1]),check=True); subprocess.run(['/output/smoke'],check=True)" - result = container.run_container(image=identity["semantic"]["image_id"], - run_id=f"{directory.name}-{uuid.uuid4().hex}", options=options, command=["python3", "-c", driver, json.dumps(command)], - run_dir=directory, timeout_seconds=180, should_cancel=lambda: False) - if result.exit.code != 0 or not result.removed or "VKIT_REUSE_OK" not in (directory / "container.stdout").read_text(): - raise RuntimeError(f"compiled API/data fixture failed: {fixture['id']}") - return {"passed": True, "driver_sha256": evidence.sha256(directory / "smoke.rs"), "commands": len(commands)} - - -def qualify(directory, source, identity): - if Path(verus.__file__).resolve().is_relative_to(ROOT / "src"): - raise RuntimeError("reuse qualification requires the installed wheel, not an editable checkout") - fixtures = json.loads((ROOT / "examples/ledger-reuse/fixtures.json").read_text()) - if len(fixtures) != 2 or {f["id"] for f in fixtures} != {"quota-admission", "worker-slot-reservations"}: - raise RuntimeError("reuse qualification requires both named application fixtures") - for fixture in fixtures: - commands = fixture["commands"] - if (len(commands) < 5 or not any("reserve" in c for c in commands) or not any("release" in c for c in commands) - or not any("CapacityExceeded" in c["expected"] for c in commands) - or not any("OwnerMismatch" in c["expected"] for c in commands)): - raise RuntimeError("reuse fixture must exercise admission, capacity rejection, release and ownership rejection") - reuse = [] - for fixture in fixtures: - namespace = fixture["namespace"] - component = replace(product_component(fixture["max_records"]), id=fixture["id"], - bindings=LedgerBindings(**{op: f"{namespace}::{op}" for op in OPERATIONS})) - candidate = source.replace("verus! {", f"pub mod {namespace} {{\nuse super::*;\nverus! {{", 1) + "\n}\n" - project, oid = project_for(directory / fixture["id"] / "project", component, candidate) - store = Store.of(project) - approve(store, component, identity) - record = prepare_formal(project, PackageVerificationRequest(component.claim, GitCommit(oid)), component, canonical_digest(identity["semantic"]), store=store) - record = execute(None, record["run_id"], store=store) - run_dir = store.run_dir(record["run_id"]) - if record["outcome"]["result"] != "PASS" or not evidence.validate_record(record, run_dir): - raise RuntimeError(f"reuse proof failed: {fixture['id']}: {record['outcome']}") - runtime = runtime_fixture(fixture, component, run_dir / "formal-output", identity, directory / fixture["id"] / "runtime") - reuse.append({"id": component.id, "candidate": oid, "package_sha256": component.package.sha256, - "receipt": record["receipt"], "runtime": runtime}) - - component = product_component(3) - project, oid = project_for(directory / "overhead/project", component, source) - store = Store.of(project) - approve(store, component, identity) - captured = capture_git_commit(project, oid) - if len(captured.files) > 100: - raise RuntimeError("overhead fixture exceeds 100 captured files") - pairs = [] - for i in range(5): - pair = {} - for mode in (("direct", "vkit") if i % 2 == 0 else ("vkit", "direct")): - if mode == "direct": - pair[mode] = direct(component, project.root, identity, directory / "overhead" / f"direct-{i}") - else: - started = time.monotonic() - checker = store.approved()[component.digest]["checker_sha256"] - record = prepare_formal(project, PackageVerificationRequest(component.claim, GitCommit(oid)), component, checker, store=store) - record = execute(None, record["run_id"], store=store) - wall = time.monotonic() - started - run_dir = store.run_dir(record["run_id"]) - if record["outcome"]["result"] != "PASS" or not evidence.validate_record(record, run_dir): - raise RuntimeError("overhead job did not establish its full proof") - pair[mode] = {"wall_seconds": wall, "phase_seconds": phase_seconds(run_dir / "formal-output"), - "run_id": record["run_id"], "receipt": record["receipt"]} - pair["overhead_seconds"] = ((pair["vkit"]["wall_seconds"] - pair["vkit"]["phase_seconds"]) - - (pair["direct"]["wall_seconds"] - pair["direct"]["phase_seconds"])) - pairs.append(pair) - median = statistics.median(p["overhead_seconds"] for p in pairs) - report = {"reuse": reuse, "package_sha256": component.package.sha256, - "installed_module": str(Path(verus.__file__).resolve()), - "overhead": {"pairs": pairs, "median_seconds": median, "target_seconds": 2.0, "passed": median <= 2.0}} - from vkit.mcp import Server - - cli = json.loads(run([sys.executable, "-m", "vkit.cli", "verify", component.id, - "--candidate", oid, "--wait", "60", "--project", str(project.root), "--json"], timeout=900).stdout) - mcp, error = Server(project.root).call( - "verify", PackageVerificationRequest(component.claim, GitCommit(oid), wait_seconds=60).to_json()) - if error: - raise RuntimeError(f"installed MCP verification failed: {mcp}") - surface_records = [jobs.wait(store, r["summary"]["run_id"], 900) for r in (cli, mcp)] - if (len({r["job_id"] for r in surface_records}) != 1 - or len({r["run_id"] for r in surface_records}) != 2 - or any(r["outcome"]["result"] != "PASS" or not evidence.validate_record(r, store.run_dir(r["run_id"])) for r in surface_records)): - raise RuntimeError("installed CLI and MCP did not establish the same job in distinct attempts") - report["surfaces"] = {"job_id": cli["summary"]["job_id"], "attempts": [r["run_id"] for r in surface_records], - "cli_and_mcp_passed": True} - cli_reused = json.loads(run([sys.executable, "-m", "vkit.cli", "verify", component.id, - "--candidate", oid, "--reuse", "--project", str(project.root), "--json"], timeout=120).stdout) - server = Server(project.root) - mcp_reused, error = server.call("verify", PackageVerificationRequest( - component.claim, GitCommit(oid), reuse=True).to_json()) - pointer = store.evidence_for("formal_goal", component.id, surface_records[0]["job_id"]) - if pointer is None: - raise RuntimeError("completed CLI/MCP proofs have no intact published evidence") - latest = pointer["run_id"] - if error or cli_reused["summary"]["run_id"] != latest or mcp_reused["summary"]["run_id"] != latest: - raise RuntimeError("CLI/MCP reuse did not return the latest intact matching proof") - details, error = server.call("run_get", {"run_id": latest, "sections": ["coverage", "compilation"]}) - cli_details = json.loads(run([sys.executable, "-m", "vkit.cli", "run", "show", "--run", latest, - "--section", "coverage", "--section", "compilation", "--project", str(project.root), "--json"]).stdout) - if (error or details != cli_details or len(details["coverage"]["claims"]) != 6 - or details["compilation"]["observations"]["passed"] is not True - or "log" in details): - raise RuntimeError("CLI/MCP selective coverage and compilation views did not match") - report["surfaces"].update(exact_proof_reused=True, selective_coverage_compilation=True) - (directory / "reuse-qualification.json").write_text(json.dumps(report, indent=2) + "\n") - if median > 2.0: - raise RuntimeError(f"median VKit orchestration overhead exceeded two seconds: {median:.3f}") - return report - - -if __name__ == "__main__": - raise SystemExit("Run through the pinned ledger qualification workflow.") diff --git a/formal/checks/run.py b/formal/checks/run.py new file mode 100644 index 0000000..9d2d24e --- /dev/null +++ b/formal/checks/run.py @@ -0,0 +1,133 @@ +"""Unified CLI entrypoint for VKit formal verification checks.""" +from __future__ import annotations + +import argparse +import json +import os +import subprocess +import sys +import time +from pathlib import Path +from typing import Any + +ROOT = Path(__file__).resolve().parents[2] +CHECKS = Path(__file__).resolve().parent + + +def _suite_specs(out_dir: Path | None) -> dict[str, list[tuple[str, list[str]]]]: + py = sys.executable + out_root = out_dir or (ROOT / "tmp" / "formal-run") + kernel: list[tuple[str, list[str]]] = [] + if (CHECKS / "check_dafny_kernel.py").is_file(): + kernel.append(("dafny_kernel", [py, str(CHECKS / "check_dafny_kernel.py")])) + kernel.extend([ + ("gate_verdicts", [py, str(CHECKS / "check_gate_verdicts.py")]), + ("delegation_algebra", [py, str(CHECKS / "check_delegation_algebra.py")]), + ("kani_classifier", [py, str(CHECKS / "check_kani_classifier.py")]), + ("verifier_interpreters", [py, str(CHECKS / "check_verifier_interpreters.py")]), + ( + "finite_decisions", + [py, str(CHECKS / "check_finite_decisions.py"), "--output", str(out_root / "finite-decisions.json")], + ), + ]) + + tlc: list[tuple[str, list[str]]] = [] + if (CHECKS / "check_protocol_trace.py").is_file(): + tlc.append(( + "protocol_trace", + [py, str(CHECKS / "check_protocol_trace.py"), "--output", str(out_root / "protocol-trace")], + )) + elif (CHECKS / "check_limb_coordination.py").is_file(): + tlc.append(( + "limb_coordination", + [py, str(CHECKS / "check_limb_coordination.py"), "--output", str(out_root / "limb-coordination")], + )) + if (CHECKS / "check_transition_comparison.py").is_file(): + tlc.append(( + "transition_comparison", + [py, str(CHECKS / "check_transition_comparison.py"), "--output", str(out_root / "transition-comparison")], + )) + + e2e: list[tuple[str, list[str]]] = [] + if (CHECKS / "verify_formal.py").is_file(): + e2e.append(( + "verify_formal", + [py, str(CHECKS / "verify_formal.py"), "--backend", "all", "--output", str(out_root / "e2e")], + )) + + return { + "kernel": kernel, + "tlc": tlc, + "e2e": e2e, + "all": [*kernel, *tlc], + } + + +def _parse_summary(stdout: str) -> Any: + text = stdout.strip() + if not text: + return None + try: + return json.loads(text) + except json.JSONDecodeError: + lines = text.splitlines() + return lines[-1] if lines else None + + +def run_suite(suite: str, output: Path | None = None) -> dict[str, Any]: + specs = _suite_specs(output) + if suite not in specs: + raise ValueError(f"unknown suite: {suite}") + out_root = output or (ROOT / "tmp" / "formal-run") + out_root.mkdir(parents=True, exist_ok=True) + env = os.environ.copy() + src_path = str(ROOT / "src") + existing_pp = env.get("PYTHONPATH", "") + if src_path not in existing_pp.split(os.pathsep): + env["PYTHONPATH"] = f"{src_path}{os.pathsep}{existing_pp}" if existing_pp else src_path + + t_all = time.monotonic() + cases = [] + all_ok = True + for name, cmd in specs[suite]: + t0 = time.monotonic() + res = subprocess.run(cmd, cwd=ROOT, env=env, text=True, capture_output=True) + dt = round(time.monotonic() - t0, 3) + ok = res.returncode == 0 + if not ok: + all_ok = False + case: dict[str, Any] = { + "name": name, + "ok": ok, + "returncode": res.returncode, + "elapsed_seconds": dt, + "summary": _parse_summary(res.stdout), + } + if not ok and res.stderr.strip(): + case["stderr"] = res.stderr.strip()[-1000:] + cases.append(case) + + report = { + "schema_version": 2, + "suite": suite, + "ok": all_ok, + "elapsed_seconds": round(time.monotonic() - t_all, 3), + "cases": cases, + } + report_path = out_root / f"report-{suite}.json" + report_path.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8") + return report + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Run VKit formal verification suites.") + parser.add_argument("--suite", choices=("all", "kernel", "tlc", "e2e"), default="all") + parser.add_argument("--output", type=Path, default=None) + args = parser.parse_args(argv) + report = run_suite(args.suite, args.output) + print(json.dumps(report, indent=2, sort_keys=True)) + return 0 if report["ok"] else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/formal/checks/verify_formal.py b/formal/checks/verify_formal.py index 0e4a350..253c62b 100644 --- a/formal/checks/verify_formal.py +++ b/formal/checks/verify_formal.py @@ -8,7 +8,6 @@ import argparse import ctypes from contextlib import nullcontext -import hashlib import json import os import re @@ -19,16 +18,31 @@ import time from pathlib import Path -ROOT = Path(__file__).resolve().parents[2] -sys.path.insert(0, str(ROOT / "src")) +try: + from formal.checks._tlc_env import ( + ROOT, + expected_tlc_sha256, + hidden_window, + resolve_java, + resolve_tlc_jar, + tlc_version, + ) +except ImportError: + from _tlc_env import ( # type: ignore[no-redef] + ROOT, + expected_tlc_sha256, + hidden_window, + resolve_java, + resolve_tlc_jar, + tlc_version, + ) -from vkit.core.evidence import validate_record # noqa: E402 -from vkit.runtime.paths import open_project # noqa: E402 -from vkit.core.store import Store # noqa: E402 +from vkit.core.evidence import validate_record +from vkit.runtime.paths import open_project +from vkit.core.store import Store FIXTURES = ROOT / "examples" / "formal-ci" LEAN_TOOLCHAIN = ROOT / "examples" / "lean-proof" / "lean-toolchain" -TLC_VERSION = "2026.11.19.180144" RESULT_EXIT = {"PASS": 0, "FAIL": 1, "BLOCKED": 3} @@ -50,17 +64,8 @@ def _lean_version() -> str: def _tlc_jar() -> tuple[Path, str]: - raw_path = os.environ.get("VKIT_TLA2TOOLS_JAR", "").strip() - if not raw_path: - raise RuntimeError("VKIT_TLA2TOOLS_JAR must name the pinned tla2tools.jar") - jar = Path(raw_path) - if not jar.is_file(): - raise RuntimeError(f"the pinned TLC jar does not exist: {jar}") - expected = (FIXTURES / "tla2tools.sha256").read_text(encoding="ascii").strip() - observed = hashlib.sha256(jar.read_bytes()).hexdigest() - if observed != expected: - raise RuntimeError(f"TLC jar digest mismatch: expected {expected}, got {observed}") - return jar.resolve(), expected + jar = resolve_tlc_jar() + return jar, expected_tlc_sha256() def _base_check(check_id: str, input_paths: list[str]) -> dict: @@ -90,7 +95,7 @@ def _lean_entry(check_id: str, module: str, source: str, theorem: str, version: return entry -def _tlc_entry(check_id: str, config: str, property_name: str, jar_sha256: str) -> dict: +def _tlc_entry(check_id: str, config: str, property_name: str, jar_sha256: str, version: str) -> dict: model = "FiniteWorkers.tla" entry = _base_check(check_id, [model, config]) entry.update({ @@ -104,7 +109,7 @@ def _tlc_entry(check_id: str, config: str, property_name: str, jar_sha256: str) "checksum_states": False, "workers": 1, }, - "toolchain": {"tool": "tlc", "version": TLC_VERSION, "jar_sha256": jar_sha256}, + "toolchain": {"tool": "tlc", "version": version, "jar_sha256": jar_sha256}, "prerequisites": [{"name": "Java", "executable": "java", "args": ["--version"]}], }) return entry @@ -118,6 +123,7 @@ def _cli(cli: str, project: Path, args: list[str], env: dict[str, str], expected capture_output=True, text=True, check=False, + **hidden_window(), ) if completed.returncode != expected_exit: raise RuntimeError( @@ -212,7 +218,12 @@ def _run_case( (verification / "manifest.json").write_text( json.dumps(manifest, indent=2) + "\n", encoding="utf-8" ) - subprocess.run(["git", "init", "--quiet", str(project)], check=True, capture_output=True) + subprocess.run( + ["git", "init", "--quiet", str(project)], + check=True, + capture_output=True, + **hidden_window(), + ) accepted = _cli(cli, project, ["accept", "--yes"], env, 0) if accepted.get("accepted") != [check["id"]]: raise RuntimeError(f"VKit did not accept the {check['id']} check: {accepted!r}") @@ -306,7 +317,7 @@ def _lean_cases(cli: str, env: dict[str, str], output: Path | None = None) -> li return results -def _tlc_cases(cli: str, env: dict[str, str], jar_sha256: str, +def _tlc_cases(cli: str, env: dict[str, str], jar_sha256: str, version: str, output: Path | None = None) -> list[dict]: model = "FiniteWorkers.tla" cases = ( @@ -315,7 +326,7 @@ def _tlc_cases(cli: str, env: dict[str, str], jar_sha256: str, ) results = [] for check_id, name, config, property_name, expected in cases: - check = _tlc_entry(check_id, config, property_name, jar_sha256) + check = _tlc_entry(check_id, config, property_name, jar_sha256, version) results.append(_run_case( cli, name, [model, config], check, expected, env, output_dir=_case_output(output, check_id), @@ -337,20 +348,22 @@ def main() -> int: cli = _required_program("vkit") env = dict(os.environ) results = [] + resolved_tlc_version = None if args.backend in ("lean", "all"): _required_program("lean") _lean_version() results.extend(_lean_cases(cli, env, args.output)) if args.backend in ("tlc", "all"): - _required_program("java") + java = resolve_java(env=env) jar, jar_sha256 = _tlc_jar() + resolved_tlc_version = tlc_version(java, jar) env["VKIT_TLA2TOOLS_JAR"] = str(jar) - results.extend(_tlc_cases(cli, env, jar_sha256, args.output)) + results.extend(_tlc_cases(cli, env, jar_sha256, resolved_tlc_version, args.output)) if args.output is not None: summary = { "schema_version": 1, "backend": args.backend, - "tlc_version": TLC_VERSION if args.backend in ("tlc", "all") else None, + "tlc_version": resolved_tlc_version, "results": results, } (args.output / "summary.json").write_text( diff --git a/formal/dafny/VKitAcceptance.dfy b/formal/dafny/VKitAcceptance.dfy new file mode 100644 index 0000000..8c6745d --- /dev/null +++ b/formal/dafny/VKitAcceptance.dfy @@ -0,0 +1,119 @@ +module VKitAcceptance { + datatype RunResult = + | ResNone + | ResPass + | ResFail + | ResBlocked + | ResOther + + datatype RunState = + | StateOther + | StateInterrupted + | StateDone + + datatype VerdictTag = + | TagReady + | TagReadyScoped + | TagRejected + | TagFailed + | TagBlocked + | TagOther + + datatype DefChangeKind = + | DefUnchanged + | DefStrengthening + | DefWeakening + | DefIncomparable + + datatype FieldDiff = + | ListFieldDiff(was: set, current: set) + | TimeoutFieldDiff(wasPresent: bool, wasVal: real, curPresent: bool, curVal: real) + | OpaqueFieldDiff + + function RunExitCode(res: RunResult, state: RunState, unfinished: int): int + ensures res == ResPass ==> RunExitCode(res, state, unfinished) == 0 + ensures res == ResFail ==> RunExitCode(res, state, unfinished) == 1 + ensures res == ResBlocked ==> RunExitCode(res, state, unfinished) == 3 + ensures res == ResOther ==> RunExitCode(res, state, unfinished) == 3 + ensures (res == ResNone && state == StateInterrupted) ==> RunExitCode(res, state, unfinished) == 3 + ensures (res == ResNone && state == StateDone) ==> RunExitCode(res, state, unfinished) == 3 + ensures (res == ResNone && state == StateOther) ==> RunExitCode(res, state, unfinished) == unfinished + { + match res + case ResPass => 0 + case ResFail => 1 + case ResBlocked => 3 + case ResOther => 3 + case ResNone => + match state + case StateInterrupted => 3 + case StateDone => 3 + case StateOther => unfinished + } + + function VerdictExitCode(tag: VerdictTag): int + ensures (tag == TagReady || tag == TagReadyScoped) ==> VerdictExitCode(tag) == 0 + ensures (tag == TagRejected || tag == TagFailed) ==> VerdictExitCode(tag) == 1 + ensures (tag == TagBlocked || tag == TagOther) ==> VerdictExitCode(tag) == 3 + { + match tag + case TagReady => 0 + case TagReadyScoped => 0 + case TagRejected => 1 + case TagFailed => 1 + case TagBlocked => 3 + case TagOther => 3 + } + + function FieldStronger(d: FieldDiff): bool { + match d + case ListFieldDiff(was, current) => !(current <= was) + case TimeoutFieldDiff(wasPresent, wasVal, curPresent, curVal) => + if !wasPresent || !curPresent then true else curVal < wasVal + case OpaqueFieldDiff => true + } + + function FieldWeaker(d: FieldDiff): bool { + match d + case ListFieldDiff(was, current) => !(was <= current) + case TimeoutFieldDiff(wasPresent, wasVal, curPresent, curVal) => + if !wasPresent || !curPresent then true else curVal > wasVal + case OpaqueFieldDiff => true + } + + function AnyStronger(diffs: seq): bool + ensures AnyStronger(diffs) <==> (exists i :: 0 <= i < |diffs| && FieldStronger(diffs[i])) + { + if |diffs| == 0 then false + else FieldStronger(diffs[0]) || AnyStronger(diffs[1..]) + } + + function AnyWeaker(diffs: seq): bool + ensures AnyWeaker(diffs) <==> (exists i :: 0 <= i < |diffs| && FieldWeaker(diffs[i])) + { + if |diffs| == 0 then false + else FieldWeaker(diffs[0]) || AnyWeaker(diffs[1..]) + } + + function DefChange(hasOldDict: bool, diffs: seq): DefChangeKind + ensures !hasOldDict ==> DefChange(hasOldDict, diffs) == DefIncomparable + ensures (hasOldDict && |diffs| == 0) ==> DefChange(hasOldDict, diffs) == DefUnchanged + ensures DefChange(hasOldDict, diffs) == DefStrengthening ==> + (hasOldDict && |diffs| > 0 && AnyStronger(diffs) && !AnyWeaker(diffs)) + ensures DefChange(hasOldDict, diffs) == DefWeakening ==> + (hasOldDict && |diffs| > 0 && AnyWeaker(diffs) && !AnyStronger(diffs)) + ensures (hasOldDict && |diffs| > 0 && AnyStronger(diffs) && AnyWeaker(diffs)) ==> + DefChange(hasOldDict, diffs) == DefIncomparable + { + if !hasOldDict then + DefIncomparable + else if |diffs| == 0 then + DefUnchanged + else + var s := AnyStronger(diffs); + var w := AnyWeaker(diffs); + if s && !w then DefStrengthening + else if w && !s then DefWeakening + else DefIncomparable + } +} diff --git a/formal/dafny/VKitBudgets.dfy b/formal/dafny/VKitBudgets.dfy new file mode 100644 index 0000000..c0d31ff --- /dev/null +++ b/formal/dafny/VKitBudgets.dfy @@ -0,0 +1,62 @@ +module VKitBudgets { + datatype Better = Lower | Higher + + function Worse(better: Better, value: real, bound: real): bool { + match better + case Lower => value > bound + case Higher => value < bound + } + + function AbsReal(x: real): real + ensures AbsReal(x) >= 0.0 + ensures x != 0.0 ==> AbsReal(x) > 0.0 + { + if x < 0.0 then -x else x + } + + function CheckLimit( + better: Better, + value: real, + valueFinite: bool, + limit: real, + limitFinite: bool + ): bool + ensures (!valueFinite || !limitFinite) ==> + !CheckLimit(better, value, valueFinite, limit, limitFinite) + ensures (valueFinite && limitFinite) ==> + (CheckLimit(better, value, valueFinite, limit, limitFinite) <==> !Worse(better, value, limit)) + { + valueFinite && limitFinite && !Worse(better, value, limit) + } + + function CheckRegression( + better: Better, + value: real, + valueFinite: bool, + base: real, + baseFinite: bool, + maxRegressionPct: real, + maxPctFinite: bool + ): bool + ensures (!valueFinite || !baseFinite || !maxPctFinite) ==> + !CheckRegression(better, value, valueFinite, base, baseFinite, maxRegressionPct, maxPctFinite) + ensures (valueFinite && baseFinite && maxPctFinite && base == 0.0 && Worse(better, value, 0.0)) ==> + !CheckRegression(better, value, valueFinite, base, baseFinite, maxRegressionPct, maxPctFinite) + ensures (valueFinite && baseFinite && maxPctFinite && !Worse(better, value, base) && maxRegressionPct >= 0.0) ==> + CheckRegression(better, value, valueFinite, base, baseFinite, maxRegressionPct, maxPctFinite) + { + if !valueFinite || !baseFinite || !maxPctFinite then + false + else if base == 0.0 then + if value == 0.0 then + 0.0 <= maxRegressionPct + else if Worse(better, value, 0.0) then + false + else + true + else + var change := ((value - base) / AbsReal(base)) * 100.0; + var regression := match better case Lower => change case Higher => -change; + regression <= maxRegressionPct + } +} diff --git a/formal/dafny/VKitChange.dfy b/formal/dafny/VKitChange.dfy new file mode 100644 index 0000000..9fe6dba --- /dev/null +++ b/formal/dafny/VKitChange.dfy @@ -0,0 +1,452 @@ +module VKitChange { + datatype Option = None | Some(val: T) + + datatype Contract = Contract( + domainDigest: string, + admissibleInputs: seq, + allowedOutputs: map> + ) + + datatype RefinementResult = RefinementResult( + preconditionIncluded: bool, + postconditionIncluded: bool, + inputWitness: Option, + outputWitness: Option<(string, string)> + ) + + datatype ComparisonKind = + | CompEquivalent + | CompStrengthens + | CompWeakens + | CompIncomparable + | CompVacuous + | CompUnknown + + datatype ComparisonResult = ComparisonResult( + kind: ComparisonKind, + oldToNew: Option, + newToOld: Option + ) + + datatype EntailmentKind = + | EntEntailed + | EntNotEntailed + | EntVacuous + | EntUnknown + + datatype EntailmentResult = EntailmentResult( + kind: EntailmentKind, + inputsIncluded: Option, + outputsIncluded: Option, + inputWitness: Option, + outputWitness: Option<(string, string)> + ) + + datatype DelegationError = + | ErrDifferentIntent + | ErrDifferentDomains + | ErrEmptyLegalInputs + | ErrDifferentLegalInputs + | ErrEmptyIntersection + | ErrNotEntailed + | ErrNotStrictStrengthening + | ErrMissingStrictnessWitness + | ErrNearMissInputIllegal + | ErrNearMissOutputOutsideDomain + | ErrNearMissOutputNotInBaseline + | ErrNearMissOutputInIntent + | ErrNearMissOutputInClaim + + datatype DelegationVerdict = + | DelegationAccepted(strictnessInput: string, strictnessOutput: string) + | DelegationRejected(error: DelegationError, detailInput: string, detailOutput: string) + + datatype DifferenceKind = + | DiffPreserved + | DiffGuardedRequirementMet + | DiffStandingIntentRepair + | DiffViolation + | DiffUnknown + + datatype DifferenceStatus = + | StatusObservedConformance + | StatusObservedViolation + | StatusUnknown + + datatype ChangeMethodStatus = + | MethodObservedViolation + | MethodProofRejected + | MethodObservedConformance + | MethodVerified + | MethodUnknown + | MethodOther + + datatype ChangeConclusion = + | ConclObservedViolation + | ConclProofRejected + | ConclUnsupported + | ConclUnknown + | ConclModelVerified + | ConclObservedConformance + + function SeqToSet(xs: seq): set + ensures forall s :: s in SeqToSet(xs) <==> s in xs + { + set i | 0 <= i < |xs| :: xs[i] + } + + function OutputsSeq(c: Contract, token: string): seq { + if token in c.allowedOutputs then c.allowedOutputs[token] else [] + } + + function OutputsSet(c: Contract, token: string): set + ensures forall o :: o in OutputsSet(c, token) <==> o in OutputsSeq(c, token) + { + SeqToSet(OutputsSeq(c, token)) + } + + function FirstMissingInput(inputs: seq, target: set): Option + ensures FirstMissingInput(inputs, target).None? <==> (forall i :: 0 <= i < |inputs| ==> inputs[i] in target) + ensures FirstMissingInput(inputs, target).Some? ==> + (FirstMissingInput(inputs, target).val in inputs && !(FirstMissingInput(inputs, target).val in target)) + { + if |inputs| == 0 then None + else if !(inputs[0] in target) then Some(inputs[0]) + else FirstMissingInput(inputs[1..], target) + } + + function FirstExtraOutput(outs: seq, allowed: set): Option + ensures FirstExtraOutput(outs, allowed).None? <==> (forall i :: 0 <= i < |outs| ==> outs[i] in allowed) + ensures FirstExtraOutput(outs, allowed).Some? ==> + (FirstExtraOutput(outs, allowed).val in outs && !(FirstExtraOutput(outs, allowed).val in allowed)) + { + if |outs| == 0 then None + else if !(outs[0] in allowed) then Some(outs[0]) + else FirstExtraOutput(outs[1..], allowed) + } + + function FirstPostWitness(inputs: seq, oldC: Contract, newC: Contract): Option<(string, string)> + ensures FirstPostWitness(inputs, oldC, newC).None? <==> + (forall i :: 0 <= i < |inputs| ==> OutputsSet(newC, inputs[i]) <= OutputsSet(oldC, inputs[i])) + { + if |inputs| == 0 then None + else + var token := inputs[0]; + var extra := FirstExtraOutput(OutputsSeq(newC, token), OutputsSet(oldC, token)); + if extra.Some? then Some((token, extra.val)) + else FirstPostWitness(inputs[1..], oldC, newC) + } + + function Refines(oldC: Contract, newC: Contract): RefinementResult + ensures Refines(oldC, newC).preconditionIncluded <==> + (SeqToSet(oldC.admissibleInputs) <= SeqToSet(newC.admissibleInputs)) + ensures Refines(oldC, newC).postconditionIncluded <==> + (forall i :: 0 <= i < |oldC.admissibleInputs| ==> + OutputsSet(newC, oldC.admissibleInputs[i]) <= OutputsSet(oldC, oldC.admissibleInputs[i])) + { + var inW := FirstMissingInput(oldC.admissibleInputs, SeqToSet(newC.admissibleInputs)); + var outW := FirstPostWitness(oldC.admissibleInputs, oldC, newC); + RefinementResult(inW.None?, outW.None?, inW, outW) + } + + function RefinesHolds(r: RefinementResult): bool { + r.preconditionIncluded && r.postconditionIncluded + } + + function CompareContracts(oldC: Contract, newC: Contract): ComparisonResult + ensures oldC.domainDigest != newC.domainDigest ==> + CompareContracts(oldC, newC) == ComparisonResult(CompUnknown, None, None) + ensures (oldC.domainDigest == newC.domainDigest && (|oldC.admissibleInputs| == 0 || |newC.admissibleInputs| == 0)) ==> + CompareContracts(oldC, newC).kind == CompVacuous + ensures CompareContracts(oldC, newC).kind == CompStrengthens ==> + (oldC.domainDigest == newC.domainDigest && |oldC.admissibleInputs| > 0 && |newC.admissibleInputs| > 0 && + RefinesHolds(Refines(oldC, newC)) && !RefinesHolds(Refines(newC, oldC))) + ensures CompareContracts(oldC, newC).kind == CompEquivalent ==> + (oldC.domainDigest == newC.domainDigest && |oldC.admissibleInputs| > 0 && |newC.admissibleInputs| > 0 && + RefinesHolds(Refines(oldC, newC)) && RefinesHolds(Refines(newC, oldC))) + { + if oldC.domainDigest != newC.domainDigest then + ComparisonResult(CompUnknown, None, None) + else + var o2n := Refines(oldC, newC); + var n2o := Refines(newC, oldC); + var kind := + if |oldC.admissibleInputs| == 0 || |newC.admissibleInputs| == 0 then CompVacuous + else if RefinesHolds(o2n) && RefinesHolds(n2o) then CompEquivalent + else if RefinesHolds(o2n) then CompStrengthens + else if RefinesHolds(n2o) then CompWeakens + else CompIncomparable; + ComparisonResult(kind, Some(o2n), Some(n2o)) + } + + function FirstEntailmentOutputWitness( + inputs: seq, + claimInputs: set, + intentC: Contract, + claimC: Contract + ): Option<(string, string)> + ensures FirstEntailmentOutputWitness(inputs, claimInputs, intentC, claimC).None? <==> + (forall i :: 0 <= i < |inputs| && inputs[i] in claimInputs ==> + OutputsSet(intentC, inputs[i]) <= OutputsSet(claimC, inputs[i])) + { + if |inputs| == 0 then None + else + var token := inputs[0]; + if token in claimInputs then + var extra := FirstExtraOutput(OutputsSeq(intentC, token), OutputsSet(claimC, token)); + if extra.Some? then Some((token, extra.val)) + else FirstEntailmentOutputWitness(inputs[1..], claimInputs, intentC, claimC) + else + FirstEntailmentOutputWitness(inputs[1..], claimInputs, intentC, claimC) + } + + function IntentEntailsClaim(intentC: Contract, claimC: Contract): EntailmentResult + ensures intentC.domainDigest != claimC.domainDigest ==> + IntentEntailsClaim(intentC, claimC) == EntailmentResult(EntUnknown, None, None, None, None) + ensures IntentEntailsClaim(intentC, claimC).kind == EntEntailed ==> + (intentC.domainDigest == claimC.domainDigest && + |intentC.admissibleInputs| > 0 && + SeqToSet(intentC.admissibleInputs) <= SeqToSet(claimC.admissibleInputs) && + (forall i :: 0 <= i < |intentC.admissibleInputs| ==> + OutputsSet(intentC, intentC.admissibleInputs[i]) <= OutputsSet(claimC, intentC.admissibleInputs[i]))) + { + if intentC.domainDigest != claimC.domainDigest then + EntailmentResult(EntUnknown, None, None, None, None) + else + var claimSet := SeqToSet(claimC.admissibleInputs); + var inW := FirstMissingInput(intentC.admissibleInputs, claimSet); + var outW := FirstEntailmentOutputWitness(intentC.admissibleInputs, claimSet, intentC, claimC); + var inOk := inW.None?; + var outOk := outW.None?; + var kind := + if |intentC.admissibleInputs| == 0 then EntVacuous + else if inOk && outOk then EntEntailed + else EntNotEntailed; + EntailmentResult(kind, Some(inOk), Some(outOk), inW, outW) + } + + function FilterInSet(xs: seq, allowed: set): seq + ensures forall s :: s in FilterInSet(xs, allowed) <==> (s in xs && s in allowed) + { + if |xs| == 0 then [] + else if xs[0] in allowed then [xs[0]] + FilterInSet(xs[1..], allowed) + else FilterInSet(xs[1..], allowed) + } + + function FirstEmptyIntersection( + inputs: seq, + intentC: Contract, + assumptionsC: Contract + ): Option + ensures FirstEmptyIntersection(inputs, intentC, assumptionsC).None? <==> + (forall i :: 0 <= i < |inputs| ==> + |FilterInSet(OutputsSeq(intentC, inputs[i]), OutputsSet(assumptionsC, inputs[i]))| > 0) + { + if |inputs| == 0 then None + else + var token := inputs[0]; + var inter := FilterInSet(OutputsSeq(intentC, token), OutputsSet(assumptionsC, token)); + if |inter| == 0 then Some(token) + else FirstEmptyIntersection(inputs[1..], intentC, assumptionsC) + } + + function BuildConstrainedOutputs( + inputs: seq, + intentC: Contract, + assumptionsC: Contract + ): map> + ensures forall k :: k in BuildConstrainedOutputs(inputs, intentC, assumptionsC) <==> k in inputs + ensures forall i :: 0 <= i < |inputs| ==> + BuildConstrainedOutputs(inputs, intentC, assumptionsC)[inputs[i]] == + FilterInSet(OutputsSeq(intentC, inputs[i]), OutputsSet(assumptionsC, inputs[i])) + { + map i | 0 <= i < |inputs| :: + inputs[i] := FilterInSet(OutputsSeq(intentC, inputs[i]), OutputsSet(assumptionsC, inputs[i])) + } + + function CheckDelegation( + intentDigest: string, + basisIntentDigest: string, + intentC: Contract, + baselineC: Contract, + assumptionsC: Contract, + claimC: Contract, + domainObservations: set, + nearMissInput: string, + nearMissOutput: string + ): DelegationVerdict + ensures (CheckDelegation( + intentDigest, basisIntentDigest, intentC, baselineC, assumptionsC, claimC, + domainObservations, nearMissInput, nearMissOutput + ).DelegationAccepted?) ==> ( + basisIntentDigest == intentDigest && + baselineC.domainDigest == intentC.domainDigest && + assumptionsC.domainDigest == intentC.domainDigest && + claimC.domainDigest == intentC.domainDigest && + |intentC.admissibleInputs| > 0 && + SeqToSet(baselineC.admissibleInputs) == SeqToSet(intentC.admissibleInputs) && + SeqToSet(assumptionsC.admissibleInputs) == SeqToSet(intentC.admissibleInputs) && + SeqToSet(claimC.admissibleInputs) == SeqToSet(intentC.admissibleInputs) && + FirstEmptyIntersection(intentC.admissibleInputs, intentC, assumptionsC).None? && + CompareContracts(baselineC, claimC).kind == CompStrengthens && + nearMissInput in SeqToSet(intentC.admissibleInputs) && + nearMissOutput in domainObservations && + nearMissOutput in OutputsSet(baselineC, nearMissInput) && + !(nearMissOutput in OutputsSet(intentC, nearMissInput)) && + !(nearMissOutput in OutputsSet(claimC, nearMissInput)) + ) + { + if basisIntentDigest != intentDigest then + DelegationRejected(ErrDifferentIntent, "", "") + else if baselineC.domainDigest != intentC.domainDigest || + assumptionsC.domainDigest != intentC.domainDigest || + claimC.domainDigest != intentC.domainDigest then + DelegationRejected(ErrDifferentDomains, "", "") + else if |intentC.admissibleInputs| == 0 then + DelegationRejected(ErrEmptyLegalInputs, "", "") + else + var legalInputs := SeqToSet(intentC.admissibleInputs); + if SeqToSet(baselineC.admissibleInputs) != legalInputs || + SeqToSet(assumptionsC.admissibleInputs) != legalInputs || + SeqToSet(claimC.admissibleInputs) != legalInputs then + DelegationRejected(ErrDifferentLegalInputs, "", "") + else + var emptyInter := FirstEmptyIntersection(intentC.admissibleInputs, intentC, assumptionsC); + if emptyInter.Some? then + DelegationRejected(ErrEmptyIntersection, emptyInter.val, "") + else + var constrained := Contract( + intentC.domainDigest, + intentC.admissibleInputs, + BuildConstrainedOutputs(intentC.admissibleInputs, intentC, assumptionsC) + ); + var entailment := IntentEntailsClaim(constrained, claimC); + if entailment.kind != EntEntailed then + match entailment.outputWitness + case Some(pair) => DelegationRejected(ErrNotEntailed, pair.0, pair.1) + case None => DelegationRejected(ErrNotEntailed, "", "") + else + var cmp := CompareContracts(baselineC, claimC); + if cmp.kind != CompStrengthens then + DelegationRejected(ErrNotStrictStrengthening, "", "") + else + match cmp.newToOld + case None => DelegationRejected(ErrMissingStrictnessWitness, "", "") + case Some(n2o) => + match n2o.outputWitness + case None => DelegationRejected(ErrMissingStrictnessWitness, "", "") + case Some(w) => + if !(nearMissInput in legalInputs) then + DelegationRejected(ErrNearMissInputIllegal, "", "") + else if !(nearMissOutput in domainObservations) then + DelegationRejected(ErrNearMissOutputOutsideDomain, "", "") + else if !(nearMissOutput in OutputsSet(baselineC, nearMissInput)) then + DelegationRejected(ErrNearMissOutputNotInBaseline, "", "") + else if nearMissOutput in OutputsSet(intentC, nearMissInput) then + DelegationRejected(ErrNearMissOutputInIntent, "", "") + else if nearMissOutput in OutputsSet(claimC, nearMissInput) then + DelegationRejected(ErrNearMissOutputInClaim, "", "") + else + DelegationAccepted(w.0, w.1) + } + + function ClassifyDifference( + baseOutput: string, + candidateOutput: string, + standingOutputs: set, + hasGuards: bool, + guardIntersection: set + ): DifferenceKind + ensures !(candidateOutput in standingOutputs) ==> + ClassifyDifference(baseOutput, candidateOutput, standingOutputs, hasGuards, guardIntersection) == DiffViolation + ensures (candidateOutput in standingOutputs && hasGuards && !(candidateOutput in guardIntersection)) ==> + ClassifyDifference(baseOutput, candidateOutput, standingOutputs, hasGuards, guardIntersection) == DiffViolation + ensures (candidateOutput in standingOutputs && hasGuards && candidateOutput in guardIntersection) ==> + ClassifyDifference(baseOutput, candidateOutput, standingOutputs, hasGuards, guardIntersection) == DiffGuardedRequirementMet + ensures (candidateOutput in standingOutputs && !hasGuards && baseOutput == candidateOutput) ==> + ClassifyDifference(baseOutput, candidateOutput, standingOutputs, hasGuards, guardIntersection) == DiffPreserved + { + if !(candidateOutput in standingOutputs) then + DiffViolation + else if hasGuards then + if !(candidateOutput in guardIntersection) then DiffViolation + else DiffGuardedRequirementMet + else if baseOutput == candidateOutput then + DiffPreserved + else if !(baseOutput in standingOutputs) then + DiffStandingIntentRepair + else + DiffViolation + } + + function HasDiffKind(kinds: seq, target: DifferenceKind): bool + ensures HasDiffKind(kinds, target) <==> (exists i :: 0 <= i < |kinds| && kinds[i] == target) + { + if |kinds| == 0 then false + else kinds[0] == target || HasDiffKind(kinds[1..], target) + } + + function AssessDifferenceStatus( + admissibleCount: nat, + missingCount: nat, + kinds: seq + ): DifferenceStatus + ensures HasDiffKind(kinds, DiffViolation) ==> + AssessDifferenceStatus(admissibleCount, missingCount, kinds) == StatusObservedViolation + ensures (HasDiffKind(kinds, DiffUnknown) || admissibleCount == 0 || missingCount > 0) ==> + AssessDifferenceStatus(admissibleCount, missingCount, kinds) != StatusObservedConformance + ensures AssessDifferenceStatus(admissibleCount, missingCount, kinds) == StatusObservedConformance ==> + (admissibleCount > 0 && missingCount == 0 && + !HasDiffKind(kinds, DiffViolation) && !HasDiffKind(kinds, DiffUnknown)) + { + var coverageComplete := admissibleCount > 0 && missingCount == 0; + if HasDiffKind(kinds, DiffViolation) then + StatusObservedViolation + else if coverageComplete && !HasDiffKind(kinds, DiffUnknown) then + StatusObservedConformance + else + StatusUnknown + } + + function HasMethodStatus(statuses: seq, target: ChangeMethodStatus): bool + ensures HasMethodStatus(statuses, target) <==> (exists i :: 0 <= i < |statuses| && statuses[i] == target) + { + if |statuses| == 0 then false + else statuses[0] == target || HasMethodStatus(statuses[1..], target) + } + + function AllConformingOrVerified(statuses: seq): bool + ensures AllConformingOrVerified(statuses) <==> + (forall i :: 0 <= i < |statuses| ==> + statuses[i] == MethodObservedConformance || statuses[i] == MethodVerified) + { + if |statuses| == 0 then true + else (statuses[0] == MethodObservedConformance || statuses[0] == MethodVerified) && + AllConformingOrVerified(statuses[1..]) + } + + function ConcludeChangeMethods(statuses: seq): ChangeConclusion + ensures HasMethodStatus(statuses, MethodObservedViolation) ==> + ConcludeChangeMethods(statuses) == ConclObservedViolation + ensures (!HasMethodStatus(statuses, MethodObservedViolation) && HasMethodStatus(statuses, MethodProofRejected)) ==> + ConcludeChangeMethods(statuses) == ConclProofRejected + ensures |statuses| == 0 ==> + ConcludeChangeMethods(statuses) == ConclUnsupported + ensures (ConcludeChangeMethods(statuses) == ConclModelVerified || + ConcludeChangeMethods(statuses) == ConclObservedConformance) ==> + (|statuses| > 0 && AllConformingOrVerified(statuses)) + { + if HasMethodStatus(statuses, MethodObservedViolation) then + ConclObservedViolation + else if HasMethodStatus(statuses, MethodProofRejected) then + ConclProofRejected + else if |statuses| == 0 then + ConclUnsupported + else if !AllConformingOrVerified(statuses) then + ConclUnknown + else if HasMethodStatus(statuses, MethodVerified) then + ConclModelVerified + else + ConclObservedConformance + } +} diff --git a/formal/dafny/VKitGate.dfy b/formal/dafny/VKitGate.dfy new file mode 100644 index 0000000..5a1684f --- /dev/null +++ b/formal/dafny/VKitGate.dfy @@ -0,0 +1,151 @@ +module VKitGate { + datatype Freshness = + | FreshPass + | FreshFail + | FreshBlocked + | Stale + | Missing + | NotApproved + | Blocked + + datatype Verdict = + | Ready + | ReadyScoped + | Rejected + | GateBlocked + + datatype GateReason = + | ReasonWeakenedCheck + | ReasonIncomparable + | ReasonNoChecks + | ReasonMissingInventory + | ReasonObligationRemoved + | ReasonFreshFail + | ReasonNotApproved + | ReasonUncoveredChange + | ReasonReady + | ReasonFreshBlocked + | ReasonBlocked + | ReasonStale + | ReasonMissing + + datatype GateDecision = GateDecision(verdict: Verdict, reason: GateReason) + + function VerdictSeverity(v: Verdict): nat { + match v + case Ready => 0 + case ReadyScoped => 1 + case GateBlocked => 2 + case Rejected => 3 + } + + lemma VerdictPrecedenceOrder() + ensures VerdictSeverity(Rejected) > VerdictSeverity(GateBlocked) + ensures VerdictSeverity(GateBlocked) > VerdictSeverity(ReadyScoped) + ensures VerdictSeverity(ReadyScoped) > VerdictSeverity(Ready) + {} + + function HasFreshness(items: seq, target: Freshness): bool + ensures HasFreshness(items, target) <==> (exists i :: 0 <= i < |items| && items[i] == target) + { + if |items| == 0 then false + else items[0] == target || HasFreshness(items[1..], target) + } + + function AllFreshPass(items: seq): bool + ensures AllFreshPass(items) <==> (forall i :: 0 <= i < |items| ==> items[i] == FreshPass) + { + if |items| == 0 then true + else items[0] == FreshPass && AllFreshPass(items[1..]) + } + + lemma AllFreshPassConcat(a: seq, b: seq) + ensures AllFreshPass(a + b) <==> (AllFreshPass(a) && AllFreshPass(b)) + { + if |a| == 0 { + assert a + b == b; + } else { + assert (a + b)[0] == a[0]; + assert (a + b)[1..] == a[1..] + b; + AllFreshPassConcat(a[1..], b); + } + } + + function FirstBlockedReason(items: seq): GateReason + requires !AllFreshPass(items) + requires !HasFreshness(items, FreshFail) + requires !HasFreshness(items, NotApproved) + ensures FirstBlockedReason(items) == ReasonFreshBlocked || + FirstBlockedReason(items) == ReasonBlocked || + FirstBlockedReason(items) == ReasonStale || + FirstBlockedReason(items) == ReasonMissing + { + if HasFreshness(items, FreshBlocked) then ReasonFreshBlocked + else if HasFreshness(items, Blocked) then ReasonBlocked + else if HasFreshness(items, Stale) then ReasonStale + else ReasonMissing + } + + function DecideGate( + checks: seq, + requiredFormal: seq, + hasInventory: bool, + hasGhosts: bool, + hasWeakened: bool, + hasIncomparable: bool, + hasUncovered: bool + ): GateDecision + ensures hasWeakened ==> + DecideGate(checks, requiredFormal, hasInventory, hasGhosts, hasWeakened, hasIncomparable, hasUncovered) + == GateDecision(Rejected, ReasonWeakenedCheck) + ensures !hasWeakened && hasIncomparable ==> + DecideGate(checks, requiredFormal, hasInventory, hasGhosts, hasWeakened, hasIncomparable, hasUncovered) + == GateDecision(GateBlocked, ReasonIncomparable) + ensures + (HasFreshness(checks + requiredFormal, FreshFail) || + HasFreshness(checks + requiredFormal, NotApproved) || + hasWeakened || + hasGhosts || + (!hasInventory && (|checks| > 0 || |requiredFormal| > 0))) + ==> + (DecideGate(checks, requiredFormal, hasInventory, hasGhosts, hasWeakened, hasIncomparable, hasUncovered).verdict != Ready && + DecideGate(checks, requiredFormal, hasInventory, hasGhosts, hasWeakened, hasIncomparable, hasUncovered).verdict != ReadyScoped) + ensures + (DecideGate(checks, requiredFormal, hasInventory, hasGhosts, hasWeakened, hasIncomparable, hasUncovered).verdict == Ready || + DecideGate(checks, requiredFormal, hasInventory, hasGhosts, hasWeakened, hasIncomparable, hasUncovered).verdict == ReadyScoped) + ==> + (!hasWeakened && !hasIncomparable && hasInventory && !hasGhosts && + (|checks| > 0 || |requiredFormal| > 0) && + AllFreshPass(checks) && AllFreshPass(requiredFormal)) + ensures + DecideGate(checks, requiredFormal, hasInventory, hasGhosts, hasWeakened, hasIncomparable, hasUncovered).verdict == Ready + ==> !hasUncovered + ensures + DecideGate(checks, requiredFormal, hasInventory, hasGhosts, hasWeakened, hasIncomparable, hasUncovered).verdict == ReadyScoped + ==> hasUncovered + { + AllFreshPassConcat(checks, requiredFormal); + var combined := checks + requiredFormal; + if hasWeakened then + GateDecision(Rejected, ReasonWeakenedCheck) + else if hasIncomparable then + GateDecision(GateBlocked, ReasonIncomparable) + else if |checks| == 0 && |requiredFormal| == 0 && !hasGhosts then + GateDecision(GateBlocked, ReasonNoChecks) + else if !hasInventory && (|checks| > 0 || |requiredFormal| > 0) then + GateDecision(Rejected, ReasonMissingInventory) + else if hasGhosts then + GateDecision(Rejected, ReasonObligationRemoved) + else if HasFreshness(combined, FreshFail) then + GateDecision(Rejected, ReasonFreshFail) + else if HasFreshness(combined, NotApproved) then + GateDecision(Rejected, ReasonNotApproved) + else if AllFreshPass(combined) then + if hasUncovered then + GateDecision(ReadyScoped, ReasonUncoveredChange) + else + GateDecision(Ready, ReasonReady) + else + GateDecision(GateBlocked, FirstBlockedReason(combined)) + } +} diff --git a/formal/dafny/VKitKernel.dfy b/formal/dafny/VKitKernel.dfy new file mode 100644 index 0000000..0b8c1b3 --- /dev/null +++ b/formal/dafny/VKitKernel.dfy @@ -0,0 +1,5 @@ +include "VKitGate.dfy" +include "VKitBudgets.dfy" +include "VKitAcceptance.dfy" +include "VKitReceipt.dfy" +include "VKitChange.dfy" diff --git a/formal/dafny/VKitReceipt.dfy b/formal/dafny/VKitReceipt.dfy new file mode 100644 index 0000000..32e61ef --- /dev/null +++ b/formal/dafny/VKitReceipt.dfy @@ -0,0 +1,129 @@ +module VKitReceipt { + datatype OutcomeResult = + | OutPass + | OutFail + | OutBlocked + + datatype ClaimOutcome = + | ClaimEstablished + | ClaimRefuted + | ClaimUnknown + + datatype CheckKindTag = + | KindLean + | KindTlc + | KindOther + + function DeriveAssurance( + hasCheck: bool, + isShadow: bool, + kind: CheckKindTag, + customAssurance: string + ): string + ensures isShadow ==> DeriveAssurance(hasCheck, isShadow, kind, customAssurance) == "empirical" + ensures (!isShadow && !hasCheck) ==> DeriveAssurance(hasCheck, isShadow, kind, customAssurance) == "trusted_engine" + ensures (!isShadow && hasCheck && kind == KindLean) ==> DeriveAssurance(hasCheck, isShadow, kind, customAssurance) == "kernel_proof" + ensures (!isShadow && hasCheck && kind == KindTlc) ==> DeriveAssurance(hasCheck, isShadow, kind, customAssurance) == "finite_model" + { + if isShadow then + "empirical" + else if !hasCheck then + "trusted_engine" + else + match kind + case KindLean => "kernel_proof" + case KindTlc => "finite_model" + case KindOther => customAssurance + } + + function DeriveClaimOutcome( + result: OutcomeResult, + isLean: bool, + isShadow: bool + ): ClaimOutcome + ensures isShadow ==> DeriveClaimOutcome(result, isLean, isShadow) == ClaimUnknown + ensures result != OutPass ==> DeriveClaimOutcome(result, isLean, isShadow) != ClaimEstablished + ensures DeriveClaimOutcome(result, isLean, isShadow) == ClaimEstablished <==> (result == OutPass && !isShadow) + ensures (isLean && result == OutFail) ==> DeriveClaimOutcome(result, isLean, isShadow) == ClaimUnknown + { + if isShadow then + ClaimUnknown + else if isLean && result == OutFail then + ClaimUnknown + else + match result + case OutPass => ClaimEstablished + case OutFail => ClaimRefuted + case OutBlocked => ClaimUnknown + } + + function VerifyReceiptCore( + receiptDigestMatches: bool, + artifactsMatch: bool, + subjectMatches: bool, + policyMatches: bool, + jobIdMatches: bool, + authorityMatches: bool, + claimOutcomeConsistent: bool, + assuranceConsistent: bool + ): bool + ensures VerifyReceiptCore( + receiptDigestMatches, artifactsMatch, subjectMatches, policyMatches, + jobIdMatches, authorityMatches, claimOutcomeConsistent, assuranceConsistent + ) <==> ( + receiptDigestMatches && artifactsMatch && subjectMatches && policyMatches && + jobIdMatches && authorityMatches && claimOutcomeConsistent && assuranceConsistent + ) + { + receiptDigestMatches && + artifactsMatch && + subjectMatches && + policyMatches && + jobIdMatches && + authorityMatches && + claimOutcomeConsistent && + assuranceConsistent + } + + function VerifyPassingReceipt( + result: OutcomeResult, + isShadow: bool, + receiptDigestMatches: bool, + artifactsMatch: bool, + subjectMatches: bool, + policyMatches: bool, + jobIdMatches: bool, + authorityMatches: bool, + claimOutcomeConsistent: bool, + assuranceConsistent: bool + ): bool + ensures result != OutPass ==> !VerifyPassingReceipt( + result, isShadow, receiptDigestMatches, artifactsMatch, subjectMatches, policyMatches, + jobIdMatches, authorityMatches, claimOutcomeConsistent, assuranceConsistent + ) + ensures (!receiptDigestMatches || !artifactsMatch || !subjectMatches || !policyMatches || + !jobIdMatches || !authorityMatches || !claimOutcomeConsistent || !assuranceConsistent || isShadow) ==> + !VerifyPassingReceipt( + result, isShadow, receiptDigestMatches, artifactsMatch, subjectMatches, policyMatches, + jobIdMatches, authorityMatches, claimOutcomeConsistent, assuranceConsistent + ) + ensures VerifyPassingReceipt( + result, isShadow, receiptDigestMatches, artifactsMatch, subjectMatches, policyMatches, + jobIdMatches, authorityMatches, claimOutcomeConsistent, assuranceConsistent + ) ==> ( + result == OutPass && !isShadow && + DeriveClaimOutcome(result, false, isShadow) == ClaimEstablished && + VerifyReceiptCore( + receiptDigestMatches, artifactsMatch, subjectMatches, policyMatches, + jobIdMatches, authorityMatches, claimOutcomeConsistent, assuranceConsistent + ) + ) + { + result == OutPass && + !isShadow && + VerifyReceiptCore( + receiptDigestMatches, artifactsMatch, subjectMatches, policyMatches, + jobIdMatches, authorityMatches, claimOutcomeConsistent, assuranceConsistent + ) + } +} diff --git a/formal/models/DelegatedClaimAuthority.tla b/formal/models/DelegatedClaimAuthority.tla deleted file mode 100644 index 6579f77..0000000 --- a/formal/models/DelegatedClaimAuthority.tla +++ /dev/null @@ -1,152 +0,0 @@ ----- MODULE DelegatedClaimAuthority ---- -EXTENDS Naturals - -CONSTANTS Mutant, Fault - -VARIABLES phase, targetTrusted, targetIdentity, entailment, strictStrengthening, - completeSatisfaction, nearMissRejected, receiptGeneration, - acceptedReceiptGeneration, cancelled, proofScope, sampled, - basisClaim, currentClaim, acceptedClaim, accepted, - codeApproved, codeApprovalAtClaimAcceptance - -vars == <> - -Init == - /\ phase = "requested" - /\ targetTrusted = (Fault # "untrusted_target") - /\ targetIdentity = (Fault # "wrong_target_identity") - /\ entailment = (Fault # "missing_entailment") - /\ strictStrengthening = (Fault # "missing_strict_strengthening") - /\ completeSatisfaction = (Fault # "sample_only_satisfaction") - /\ nearMissRejected = (Fault # "missing_near_miss_rejection") - /\ receiptGeneration = 0 - /\ acceptedReceiptGeneration = 0 - /\ cancelled = FALSE - /\ proofScope = IF Fault = "wrong_model_scope" THEN "native" ELSE "restricted_captured_rust_kani_model" - /\ sampled = FALSE - /\ basisClaim = IF Fault = "self_justifying_basis" THEN "current_claim" ELSE "trusted_prior_claim" - /\ currentClaim = "current_claim" - /\ acceptedClaim = "none" - /\ accepted = FALSE - /\ codeApproved = FALSE - /\ codeApprovalAtClaimAcceptance = FALSE - -Prepare == - /\ phase = "requested" - /\ phase' = "prepared" - /\ UNCHANGED <> - -SampleCandidate == - /\ phase = "prepared" - /\ phase' = "sampled" - /\ sampled' = TRUE - /\ UNCHANGED <> - -RunIndependentProofs == - /\ phase \in {"prepared", "sampled"} - /\ phase' = "proved" - /\ receiptGeneration' = receiptGeneration + 1 - /\ acceptedReceiptGeneration' = receiptGeneration + 1 - /\ UNCHANGED <> - -CancelProofs == - /\ phase = "proved" - /\ phase' = "cancelled" - /\ receiptGeneration' = receiptGeneration + 1 - /\ cancelled' = TRUE - /\ UNCHANGED <> - -AcceptanceGuards == - /\ (Mutant = "omit_target_basis_identity" \/ (targetTrusted /\ targetIdentity)) - /\ (Mutant = "omit_entailment" \/ entailment) - /\ (Mutant = "omit_strict_strengthening" \/ strictStrengthening) - /\ (Mutant \in {"omit_complete_satisfaction", "sample_authorizes_claim"} - \/ completeSatisfaction) - /\ (Mutant = "omit_meaningful_near_miss" \/ nearMissRejected) - /\ (Mutant = "omit_fresh_receipt_cancel" \/ - (acceptedReceiptGeneration = receiptGeneration /\ ~cancelled)) - /\ (Mutant = "omit_model_scope" \/ proofScope = "restricted_captured_rust_kani_model") - /\ (Mutant = "omit_prior_claim_identity" \/ basisClaim = "trusted_prior_claim") - -AcceptClaim == - /\ phase \in {"proved", "cancelled"} - /\ ~accepted - /\ (Mutant # "sample_authorizes_claim" \/ sampled) - /\ AcceptanceGuards - /\ accepted' = TRUE - /\ phase' = "accepted" - /\ acceptedClaim' = currentClaim - /\ codeApproved' = IF Mutant = "claim_approves_code" THEN TRUE ELSE codeApproved - /\ codeApprovalAtClaimAcceptance' = codeApproved - /\ UNCHANGED <> - -ApproveCode == - /\ phase = "proved" - /\ phase' = "proved" - /\ codeApproved' = TRUE - /\ UNCHANGED <> - -Next == Prepare \/ SampleCandidate \/ RunIndependentProofs \/ CancelProofs \/ AcceptClaim \/ ApproveCode -Spec == Init /\ [][Next]_vars - -TypeOK == - /\ phase \in {"requested", "prepared", "sampled", "proved", "cancelled", "accepted"} - /\ targetTrusted \in BOOLEAN - /\ targetIdentity \in BOOLEAN - /\ entailment \in BOOLEAN - /\ strictStrengthening \in BOOLEAN - /\ completeSatisfaction \in BOOLEAN - /\ nearMissRejected \in BOOLEAN - /\ receiptGeneration \in {0, 1, 2} - /\ acceptedReceiptGeneration \in {0, 1} - /\ cancelled \in BOOLEAN - /\ proofScope \in {"restricted_captured_rust_kani_model", "native"} - /\ sampled \in BOOLEAN - /\ basisClaim \in {"trusted_prior_claim", "current_claim"} - /\ currentClaim = "current_claim" - /\ acceptedClaim \in {"none", "current_claim"} - /\ accepted \in BOOLEAN - /\ codeApproved \in BOOLEAN - /\ codeApprovalAtClaimAcceptance \in BOOLEAN - -AcceptedHasTrustedTargetBasis == ~accepted \/ (targetTrusted /\ targetIdentity) -AcceptedHasEntailment == ~accepted \/ entailment -AcceptedIsStrictStrengthening == ~accepted \/ strictStrengthening -AcceptedHasCompleteSatisfaction == ~accepted \/ completeSatisfaction -AcceptedHasRejectedMeaningfulNearMiss == ~accepted \/ nearMissRejected -AcceptedHasFreshUncancelledReceipt == - ~accepted \/ (acceptedReceiptGeneration = receiptGeneration /\ ~cancelled) -AcceptedUsesRestrictedModel == - ~accepted \/ proofScope = "restricted_captured_rust_kani_model" -SamplesCannotAuthorize == ~(sampled /\ ~completeSatisfaction /\ accepted) -ClaimAcceptanceDoesNotApproveCode == - ~accepted \/ codeApprovalAtClaimAcceptance = codeApproved -CurrentClaimCannotBeItsOwnBasis == - ~accepted \/ (basisClaim = "trusted_prior_claim" /\ acceptedClaim # basisClaim) - -==== diff --git a/formal/models/TraceVKit.tla b/formal/models/TraceVKit.tla new file mode 100644 index 0000000..7e831d5 --- /dev/null +++ b/formal/models/TraceVKit.tla @@ -0,0 +1,268 @@ +---- MODULE TraceVKit ---- +EXTENDS Naturals, Sequences, TraceData + +RunIds == 1..MaxRun +RunStates == {"absent", "queued", "running", "done", "interrupted"} +Outcomes == {"none", "PASS", "FAIL", "BLOCKED"} +Verdicts == {"BLOCKED", "REJECTED", "READY"} +Decisions == {"none", "allow", "block"} + +VARIABLES pc, runState, runSource, runOutcome, cancelReq, cancelledWhileQueued, + workerAlive, containerAlive, lockHeld, evidencePtr, sourceRev, + approvedDigest, gateVerdict, sessionStarted, lastDecision, + lastBypass, bypassLogged + +traceVars == <> + +FreshPassWith(evPtr, rState, rOutcome, rSource, sRev) == + /\ evPtr > 0 + /\ rState[evPtr] = "done" + /\ rOutcome[evPtr] = "PASS" + /\ rSource[evPtr] = sRev + +ComputeGate(appDig, evPtr, rState, rOutcome, rSource, sRev) == + IF appDig = 0 THEN "REJECTED" + ELSE IF FreshPassWith(evPtr, rState, rOutcome, rSource, sRev) THEN "READY" + ELSE "BLOCKED" + +TraceInit == + /\ pc = 1 + /\ runState = [r \in RunIds |-> "absent"] + /\ runSource = [r \in RunIds |-> 0] + /\ runOutcome = [r \in RunIds |-> "none"] + /\ cancelReq = [r \in RunIds |-> FALSE] + /\ cancelledWhileQueued = [r \in RunIds |-> FALSE] + /\ workerAlive = [r \in RunIds |-> FALSE] + /\ containerAlive = [r \in RunIds |-> FALSE] + /\ lockHeld = FALSE + /\ evidencePtr = 0 + /\ sourceRev = 1 + /\ approvedDigest = 0 + /\ gateVerdict = "REJECTED" + /\ sessionStarted = FALSE + /\ lastDecision = "none" + /\ lastBypass = FALSE + /\ bypassLogged = FALSE + +StepClientAccept == + /\ approvedDigest' = 1 + /\ gateVerdict' = ComputeGate(1, evidencePtr, runState, runOutcome, runSource, sourceRev) + /\ lastDecision' = "none" + /\ lastBypass' = FALSE + /\ UNCHANGED <> + +StepClientEditSource == + /\ sourceRev < MaxRev + /\ sourceRev' = sourceRev + 1 + /\ gateVerdict' = ComputeGate(approvedDigest, evidencePtr, runState, runOutcome, runSource, sourceRev + 1) + /\ lastDecision' = "none" + /\ lastBypass' = FALSE + /\ UNCHANGED <> + +StepClientSubmit(r) == + /\ r \in RunIds + /\ runState[r] = "absent" + /\ runState' = [runState EXCEPT ![r] = "queued"] + /\ runSource' = [runSource EXCEPT ![r] = sourceRev] + /\ cancelReq' = [cancelReq EXCEPT ![r] = FALSE] + /\ cancelledWhileQueued' = [cancelledWhileQueued EXCEPT ![r] = FALSE] + /\ UNCHANGED <> + +StepClientCancel(r) == + /\ r \in RunIds + /\ runState[r] \in {"queued", "running"} + /\ cancelReq' = [cancelReq EXCEPT ![r] = TRUE] + /\ cancelledWhileQueued' = [cancelledWhileQueued EXCEPT ![r] = (cancelledWhileQueued[r] \/ runState[r] = "queued")] + /\ UNCHANGED <> + +StepWorkerStart(r) == + /\ r \in RunIds + /\ runState[r] = "queued" + /\ ~cancelReq[r] + /\ runState' = [runState EXCEPT ![r] = "running"] + /\ workerAlive' = [workerAlive EXCEPT ![r] = TRUE] + /\ containerAlive' = [containerAlive EXCEPT ![r] = TRUE] + /\ UNCHANGED <> + +StepWorkerFastBlock(r) == + /\ r \in RunIds + /\ runState[r] \in {"absent", "queued"} + /\ LET nextState == [runState EXCEPT ![r] = "done"] + nextOutcome == [runOutcome EXCEPT ![r] = "BLOCKED"] + IN /\ runState' = nextState + /\ runSource' = [runSource EXCEPT ![r] = IF runSource[r] = 0 THEN sourceRev ELSE runSource[r]] + /\ runOutcome' = nextOutcome + /\ workerAlive' = [workerAlive EXCEPT ![r] = FALSE] + /\ containerAlive' = [containerAlive EXCEPT ![r] = FALSE] + /\ gateVerdict' = ComputeGate(approvedDigest, evidencePtr, nextState, nextOutcome, runSource, sourceRev) + /\ lastDecision' = "none" + /\ lastBypass' = FALSE + /\ UNCHANGED <> + +StepWorkerComplete(r, res) == + /\ r \in RunIds + /\ runState[r] = "running" + /\ workerAlive[r] + /\ res \in {"PASS", "FAIL", "BLOCKED"} + /\ LET nextState == [runState EXCEPT ![r] = "done"] + nextOutcome == [runOutcome EXCEPT ![r] = res] + nextPtr == IF res = "PASS" THEN r ELSE evidencePtr + IN /\ runState' = nextState + /\ runOutcome' = nextOutcome + /\ workerAlive' = [workerAlive EXCEPT ![r] = FALSE] + /\ containerAlive' = [containerAlive EXCEPT ![r] = FALSE] + /\ evidencePtr' = nextPtr + /\ gateVerdict' = ComputeGate(approvedDigest, nextPtr, nextState, nextOutcome, runSource, sourceRev) + /\ lastDecision' = "none" + /\ lastBypass' = FALSE + /\ UNCHANGED <> + +StepWorkerCrash(r) == + /\ r \in RunIds + /\ runState[r] = "running" + /\ workerAlive[r] + /\ workerAlive' = [workerAlive EXCEPT ![r] = FALSE] + /\ UNCHANGED <> + +StepWorkerCleanupCrash(r) == + /\ r \in RunIds + /\ runState[r] = "running" + /\ ~workerAlive[r] + /\ runState' = [runState EXCEPT ![r] = "interrupted"] + /\ containerAlive' = [containerAlive EXCEPT ![r] = FALSE] + /\ UNCHANGED <> + +StepStoreAcquireLock == + /\ ~lockHeld + /\ lockHeld' = TRUE + /\ UNCHANGED <> + +StepStoreReleaseLock == + /\ lockHeld + /\ lockHeld' = FALSE + /\ UNCHANGED <> + +StepHookSessionStart == + /\ sessionStarted' = TRUE + /\ UNCHANGED <> + +StepHookStop(stopHookActive, observedDecision, observedVerdict) == + /\ observedVerdict = gateVerdict + /\ LET cleanReady == gateVerdict = "READY" + allowed == cleanReady \/ stopHookActive + expectedDecision == IF allowed THEN "allow" ELSE "block" + bypassUsed == allowed /\ stopHookActive /\ ~cleanReady + IN /\ observedDecision = expectedDecision + /\ lastDecision' = observedDecision + /\ lastBypass' = bypassUsed + /\ bypassLogged' = IF bypassUsed THEN TRUE ELSE bypassLogged + /\ UNCHANGED <> + +StepGateObserve(observedVerdict) == + /\ observedVerdict = gateVerdict + /\ UNCHANGED <> + +TraceStep == + /\ pc <= Len(Trace) + /\ LET ev == Trace[pc] + IN CASE ev.action = "ClientAccept" -> StepClientAccept + [] ev.action = "ClientEditSource" -> StepClientEditSource + [] ev.action = "ClientSubmit" -> StepClientSubmit(ev.run) + [] ev.action = "ClientCancel" -> StepClientCancel(ev.run) + [] ev.action = "WorkerStart" -> StepWorkerStart(ev.run) + [] ev.action = "WorkerFastBlock" -> StepWorkerFastBlock(ev.run) + [] ev.action = "WorkerComplete" -> StepWorkerComplete(ev.run, ev.res) + [] ev.action = "WorkerCrash" -> StepWorkerCrash(ev.run) + [] ev.action = "WorkerCleanupCrash" -> StepWorkerCleanupCrash(ev.run) + [] ev.action = "StoreAcquireLock" -> StepStoreAcquireLock + [] ev.action = "StoreReleaseLock" -> StepStoreReleaseLock + [] ev.action = "HookSessionStart" -> StepHookSessionStart + [] ev.action = "HookStop" -> StepHookStop(ev.bypass, ev.decision, ev.verdict) + [] ev.action = "GateObserve" -> StepGateObserve(ev.verdict) + [] OTHER -> FALSE + /\ pc' = pc + 1 + +TraceDone == + /\ pc = Len(Trace) + 1 + /\ UNCHANGED traceVars + +TraceNext == TraceStep \/ TraceDone + +TraceSpec == TraceInit /\ [][TraceNext]_traceVars + +TypeOK == + /\ pc \in 1..(Len(Trace) + 1) + /\ runState \in [RunIds -> RunStates] + /\ runSource \in [RunIds -> 0..MaxRev] + /\ runOutcome \in [RunIds -> Outcomes] + /\ cancelReq \in [RunIds -> BOOLEAN] + /\ cancelledWhileQueued \in [RunIds -> BOOLEAN] + /\ workerAlive \in [RunIds -> BOOLEAN] + /\ containerAlive \in [RunIds -> BOOLEAN] + /\ lockHeld \in BOOLEAN + /\ evidencePtr \in 0..MaxRun + /\ sourceRev \in 1..MaxRev + /\ approvedDigest \in {0, 1} + /\ gateVerdict \in Verdicts + /\ sessionStarted \in BOOLEAN + /\ lastDecision \in Decisions + /\ lastBypass \in BOOLEAN + /\ bypassLogged \in BOOLEAN + +CancelledQueuedNeverStarts == + \A r \in RunIds : cancelledWhileQueued[r] => + /\ runState[r] # "running" + /\ ~workerAlive[r] + +SourceDriftInvalidatesFreshPass == + (evidencePtr > 0 /\ runSource[evidencePtr] # sourceRev) => + gateVerdict # "READY" + +CrashLeavesNoOrphanContainer == + \A r \in RunIds : runState[r] = "interrupted" => ~containerAlive[r] + +GateNeverReadyWithStaleOrUnapproved == + gateVerdict = "READY" => + /\ approvedDigest = 1 + /\ evidencePtr > 0 + /\ runState[evidencePtr] = "done" + /\ runOutcome[evidencePtr] = "PASS" + /\ runSource[evidencePtr] = sourceRev + +StopBlockedUnlessReadyOrBypass == + (lastDecision = "allow" /\ gateVerdict # "READY") => lastBypass + +BypassAlwaysRecordedInTelemetry == + lastBypass => bypassLogged + +==== diff --git a/formal/models/VKitProtocol.cfg b/formal/models/VKitProtocol.cfg new file mode 100644 index 0000000..8476a43 --- /dev/null +++ b/formal/models/VKitProtocol.cfg @@ -0,0 +1,11 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + Mutant = "none" +INVARIANT TypeOK +INVARIANT CancelledQueuedNeverStarts +INVARIANT SourceDriftInvalidatesFreshPass +INVARIANT CrashLeavesNoOrphanContainer +INVARIANT GateNeverReadyWithStaleOrUnapproved +INVARIANT StopBlockedUnlessReadyOrBypass +INVARIANT BypassAlwaysRecordedInTelemetry diff --git a/formal/models/VKitProtocol.mutant-allow-stale-stop.cfg b/formal/models/VKitProtocol.mutant-allow-stale-stop.cfg new file mode 100644 index 0000000..295655c --- /dev/null +++ b/formal/models/VKitProtocol.mutant-allow-stale-stop.cfg @@ -0,0 +1,11 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + Mutant = "allow_stale_stop" +INVARIANT TypeOK +INVARIANT CancelledQueuedNeverStarts +INVARIANT SourceDriftInvalidatesFreshPass +INVARIANT CrashLeavesNoOrphanContainer +INVARIANT GateNeverReadyWithStaleOrUnapproved +INVARIANT StopBlockedUnlessReadyOrBypass +INVARIANT BypassAlwaysRecordedInTelemetry diff --git a/formal/models/VKitProtocol.mutant-orphan-container.cfg b/formal/models/VKitProtocol.mutant-orphan-container.cfg new file mode 100644 index 0000000..e7388ed --- /dev/null +++ b/formal/models/VKitProtocol.mutant-orphan-container.cfg @@ -0,0 +1,11 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + Mutant = "orphan_container" +INVARIANT TypeOK +INVARIANT CancelledQueuedNeverStarts +INVARIANT SourceDriftInvalidatesFreshPass +INVARIANT CrashLeavesNoOrphanContainer +INVARIANT GateNeverReadyWithStaleOrUnapproved +INVARIANT StopBlockedUnlessReadyOrBypass +INVARIANT BypassAlwaysRecordedInTelemetry diff --git a/formal/models/VKitProtocol.mutant-stale-gate.cfg b/formal/models/VKitProtocol.mutant-stale-gate.cfg new file mode 100644 index 0000000..65c1a49 --- /dev/null +++ b/formal/models/VKitProtocol.mutant-stale-gate.cfg @@ -0,0 +1,11 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + Mutant = "stale_gate" +INVARIANT TypeOK +INVARIANT CancelledQueuedNeverStarts +INVARIANT SourceDriftInvalidatesFreshPass +INVARIANT CrashLeavesNoOrphanContainer +INVARIANT GateNeverReadyWithStaleOrUnapproved +INVARIANT StopBlockedUnlessReadyOrBypass +INVARIANT BypassAlwaysRecordedInTelemetry diff --git a/formal/models/VKitProtocol.mutant-start-cancelled.cfg b/formal/models/VKitProtocol.mutant-start-cancelled.cfg new file mode 100644 index 0000000..2a8971e --- /dev/null +++ b/formal/models/VKitProtocol.mutant-start-cancelled.cfg @@ -0,0 +1,11 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + Mutant = "start_cancelled" +INVARIANT TypeOK +INVARIANT CancelledQueuedNeverStarts +INVARIANT SourceDriftInvalidatesFreshPass +INVARIANT CrashLeavesNoOrphanContainer +INVARIANT GateNeverReadyWithStaleOrUnapproved +INVARIANT StopBlockedUnlessReadyOrBypass +INVARIANT BypassAlwaysRecordedInTelemetry diff --git a/formal/models/VKitProtocol.tla b/formal/models/VKitProtocol.tla new file mode 100644 index 0000000..2d899b9 --- /dev/null +++ b/formal/models/VKitProtocol.tla @@ -0,0 +1,255 @@ +---- MODULE VKitProtocol ---- +EXTENDS Naturals + +CONSTANTS Mutant + +RunIds == {1, 2} +RunStates == {"absent", "queued", "running", "done", "interrupted"} +Outcomes == {"none", "PASS", "FAIL", "BLOCKED"} +Verdicts == {"BLOCKED", "REJECTED", "READY"} +Decisions == {"none", "allow", "block"} + +VARIABLES runState, runSource, runOutcome, cancelReq, cancelledWhileQueued, + workerAlive, containerAlive, lockHeld, evidencePtr, sourceRev, + approvedDigest, gateVerdict, sessionStarted, lastDecision, + lastBypass, bypassLogged + +vars == <> + +FreshPassWith(evPtr, rState, rOutcome, rSource, sRev) == + /\ evPtr > 0 + /\ rState[evPtr] = "done" + /\ rOutcome[evPtr] = "PASS" + /\ (Mutant = "stale_gate" \/ rSource[evPtr] = sRev) + +ComputeGate(appDig, evPtr, rState, rOutcome, rSource, sRev) == + IF appDig = 0 THEN "REJECTED" + ELSE IF FreshPassWith(evPtr, rState, rOutcome, rSource, sRev) THEN "READY" + ELSE "BLOCKED" + +Init == + /\ runState = [r \in RunIds |-> "absent"] + /\ runSource = [r \in RunIds |-> 0] + /\ runOutcome = [r \in RunIds |-> "none"] + /\ cancelReq = [r \in RunIds |-> FALSE] + /\ cancelledWhileQueued = [r \in RunIds |-> FALSE] + /\ workerAlive = [r \in RunIds |-> FALSE] + /\ containerAlive = [r \in RunIds |-> FALSE] + /\ lockHeld = FALSE + /\ evidencePtr = 0 + /\ sourceRev = 1 + /\ approvedDigest = 0 + /\ gateVerdict = "REJECTED" + /\ sessionStarted = FALSE + /\ lastDecision = "none" + /\ lastBypass = FALSE + /\ bypassLogged = FALSE + +ClientAccept == + /\ approvedDigest = 0 + /\ approvedDigest' = 1 + /\ gateVerdict' = ComputeGate(1, evidencePtr, runState, runOutcome, runSource, sourceRev) + /\ lastDecision' = "none" + /\ lastBypass' = FALSE + /\ UNCHANGED <> + +ClientEditSource == + /\ sourceRev = 1 + /\ sourceRev' = 2 + /\ gateVerdict' = ComputeGate(approvedDigest, evidencePtr, runState, runOutcome, runSource, 2) + /\ lastDecision' = "none" + /\ lastBypass' = FALSE + /\ UNCHANGED <> + +ClientSubmit(r) == + /\ r \in RunIds + /\ runState[r] = "absent" + /\ runState' = [runState EXCEPT ![r] = "queued"] + /\ runSource' = [runSource EXCEPT ![r] = sourceRev] + /\ cancelReq' = [cancelReq EXCEPT ![r] = FALSE] + /\ cancelledWhileQueued' = [cancelledWhileQueued EXCEPT ![r] = FALSE] + /\ UNCHANGED <> + +ClientCancel(r) == + /\ r \in RunIds + /\ runState[r] \in {"queued", "running"} + /\ ~cancelReq[r] + /\ cancelReq' = [cancelReq EXCEPT ![r] = TRUE] + /\ cancelledWhileQueued' = [cancelledWhileQueued EXCEPT ![r] = (runState[r] = "queued")] + /\ UNCHANGED <> + +ClientRetry(from, to) == + /\ from \in RunIds + /\ to \in RunIds + /\ from # to + /\ runState[from] \in {"done", "interrupted"} + /\ ~workerAlive[from] + /\ runState[to] = "absent" + /\ runState' = [runState EXCEPT ![to] = "queued"] + /\ runSource' = [runSource EXCEPT ![to] = sourceRev] + /\ runOutcome' = [runOutcome EXCEPT ![to] = "none"] + /\ cancelReq' = [cancelReq EXCEPT ![to] = FALSE] + /\ cancelledWhileQueued' = [cancelledWhileQueued EXCEPT ![to] = FALSE] + /\ UNCHANGED <> + +WorkerStart(r) == + /\ r \in RunIds + /\ runState[r] = "queued" + /\ (Mutant = "start_cancelled" \/ ~cancelReq[r]) + /\ runState' = [runState EXCEPT ![r] = "running"] + /\ workerAlive' = [workerAlive EXCEPT ![r] = TRUE] + /\ containerAlive' = [containerAlive EXCEPT ![r] = TRUE] + /\ UNCHANGED <> + +WorkerComplete(r, res) == + /\ r \in RunIds + /\ runState[r] = "running" + /\ workerAlive[r] + /\ res \in {"PASS", "BLOCKED"} + /\ LET nextState == [runState EXCEPT ![r] = "done"] + nextOutcome == [runOutcome EXCEPT ![r] = res] + nextPtr == IF res = "PASS" THEN r ELSE evidencePtr + IN /\ runState' = nextState + /\ runOutcome' = nextOutcome + /\ workerAlive' = [workerAlive EXCEPT ![r] = FALSE] + /\ containerAlive' = [containerAlive EXCEPT ![r] = FALSE] + /\ evidencePtr' = nextPtr + /\ gateVerdict' = ComputeGate(approvedDigest, nextPtr, nextState, nextOutcome, runSource, sourceRev) + /\ lastDecision' = "none" + /\ lastBypass' = FALSE + /\ UNCHANGED <> + +WorkerCrash(r) == + /\ r \in RunIds + /\ runState[r] = "running" + /\ workerAlive[r] + /\ workerAlive' = [workerAlive EXCEPT ![r] = FALSE] + /\ UNCHANGED <> + +WorkerCleanupCrash(r) == + /\ r \in RunIds + /\ runState[r] = "running" + /\ ~workerAlive[r] + /\ runState' = [runState EXCEPT ![r] = "interrupted"] + /\ containerAlive' = [containerAlive EXCEPT ![r] = IF Mutant = "orphan_container" THEN containerAlive[r] ELSE FALSE] + /\ UNCHANGED <> + +StoreAcquireLock == + /\ ~lockHeld + /\ lockHeld' = TRUE + /\ UNCHANGED <> + +StoreReleaseLock == + /\ lockHeld + /\ lockHeld' = FALSE + /\ UNCHANGED <> + +HookSessionStart == + /\ ~sessionStarted + /\ sessionStarted' = TRUE + /\ UNCHANGED <> + +HookStop(stopHookActive) == + /\ sessionStarted + /\ stopHookActive \in BOOLEAN + /\ LET cleanReady == gateVerdict = "READY" + allowed == IF Mutant = "allow_stale_stop" + THEN (gateVerdict \in {"READY", "BLOCKED"} \/ stopHookActive) + ELSE (cleanReady \/ stopHookActive) + bypassUsed == allowed /\ stopHookActive /\ ~cleanReady + IN /\ lastDecision' = IF allowed THEN "allow" ELSE "block" + /\ lastBypass' = bypassUsed + /\ bypassLogged' = IF bypassUsed THEN TRUE ELSE bypassLogged + /\ UNCHANGED <> + +Next == + \/ ClientAccept + \/ ClientEditSource + \/ \E r \in RunIds : ClientSubmit(r) + \/ \E r \in RunIds : ClientCancel(r) + \/ \E r1, r2 \in RunIds : ClientRetry(r1, r2) + \/ \E r \in RunIds : WorkerStart(r) + \/ \E r \in RunIds : WorkerComplete(r, "PASS") + \/ \E r \in RunIds : WorkerComplete(r, "BLOCKED") + \/ \E r \in RunIds : WorkerCrash(r) + \/ \E r \in RunIds : WorkerCleanupCrash(r) + \/ StoreAcquireLock + \/ StoreReleaseLock + \/ HookSessionStart + \/ \E b \in BOOLEAN : HookStop(b) + +Spec == Init /\ [][Next]_vars + +TypeOK == + /\ runState \in [RunIds -> RunStates] + /\ runSource \in [RunIds -> 0..2] + /\ runOutcome \in [RunIds -> Outcomes] + /\ cancelReq \in [RunIds -> BOOLEAN] + /\ cancelledWhileQueued \in [RunIds -> BOOLEAN] + /\ workerAlive \in [RunIds -> BOOLEAN] + /\ containerAlive \in [RunIds -> BOOLEAN] + /\ lockHeld \in BOOLEAN + /\ evidencePtr \in 0..2 + /\ sourceRev \in {1, 2} + /\ approvedDigest \in {0, 1} + /\ gateVerdict \in Verdicts + /\ sessionStarted \in BOOLEAN + /\ lastDecision \in Decisions + /\ lastBypass \in BOOLEAN + /\ bypassLogged \in BOOLEAN + +CancelledQueuedNeverStarts == + \A r \in RunIds : cancelledWhileQueued[r] => + /\ runState[r] # "running" + /\ ~workerAlive[r] + +SourceDriftInvalidatesFreshPass == + (evidencePtr > 0 /\ runSource[evidencePtr] # sourceRev) => + gateVerdict # "READY" + +CrashLeavesNoOrphanContainer == + \A r \in RunIds : runState[r] = "interrupted" => ~containerAlive[r] + +GateNeverReadyWithStaleOrUnapproved == + gateVerdict = "READY" => + /\ approvedDigest = 1 + /\ evidencePtr > 0 + /\ runState[evidencePtr] = "done" + /\ runOutcome[evidencePtr] = "PASS" + /\ runSource[evidencePtr] = sourceRev + +StopBlockedUnlessReadyOrBypass == + (lastDecision = "allow" /\ gateVerdict # "READY") => lastBypass + +BypassAlwaysRecordedInTelemetry == + lastBypass => bypassLogged + +==== diff --git a/formal/models/certification/Authority.bad-claim.cfg b/formal/models/certification/Authority.bad-claim.cfg deleted file mode 100644 index 8ce69a3..0000000 --- a/formal/models/certification/Authority.bad-claim.cfg +++ /dev/null @@ -1,25 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Fault = "bad_claim" - ComponentId = "allocation" - TargetPolicy = "policy-0" - CandidatePolicy = "policy-1" - TargetPackage = "package-0" - CandidatePackage = "package-1" - CheckerA = "checker-0" - CheckerB = "checker-1" - SourceA = "source-0" - SourceB = "source-1" - ProtectedTarget = "target-0" - CandidateTarget = "target-1" -INVARIANT TypeOK -INVARIANT ClaimPinned -INVARIANT TargetAuthorityPinned -INVARIANT SnapshotPinned -INVARIANT CandidateCapturePinned -INVARIANT ReceiptBound -INVARIANT PublishedPassBound -INVARIANT PreflightNotProof -INVARIANT ReuseDecisionBound -INVARIANT ReuseRejectedBound diff --git a/formal/models/certification/Authority.candidate-target.cfg b/formal/models/certification/Authority.candidate-target.cfg deleted file mode 100644 index aa97403..0000000 --- a/formal/models/certification/Authority.candidate-target.cfg +++ /dev/null @@ -1,25 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Fault = "candidate_target" - ComponentId = "allocation" - TargetPolicy = "policy-0" - CandidatePolicy = "policy-1" - TargetPackage = "package-0" - CandidatePackage = "package-1" - CheckerA = "checker-0" - CheckerB = "checker-1" - SourceA = "source-0" - SourceB = "source-1" - ProtectedTarget = "target-0" - CandidateTarget = "target-1" -INVARIANT TypeOK -INVARIANT ClaimPinned -INVARIANT TargetAuthorityPinned -INVARIANT SnapshotPinned -INVARIANT CandidateCapturePinned -INVARIANT ReceiptBound -INVARIANT PublishedPassBound -INVARIANT PreflightNotProof -INVARIANT ReuseDecisionBound -INVARIANT ReuseRejectedBound diff --git a/formal/models/certification/Authority.cfg b/formal/models/certification/Authority.cfg deleted file mode 100644 index c062aad..0000000 --- a/formal/models/certification/Authority.cfg +++ /dev/null @@ -1,25 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Fault = "none" - ComponentId = "allocation" - TargetPolicy = "policy-0" - CandidatePolicy = "policy-1" - TargetPackage = "package-0" - CandidatePackage = "package-1" - CheckerA = "checker-0" - CheckerB = "checker-1" - SourceA = "source-0" - SourceB = "source-1" - ProtectedTarget = "target-0" - CandidateTarget = "target-1" -INVARIANT TypeOK -INVARIANT ClaimPinned -INVARIANT TargetAuthorityPinned -INVARIANT SnapshotPinned -INVARIANT CandidateCapturePinned -INVARIANT ReceiptBound -INVARIANT PublishedPassBound -INVARIANT PreflightNotProof -INVARIANT ReuseDecisionBound -INVARIANT ReuseRejectedBound diff --git a/formal/models/certification/Authority.false-reject.cfg b/formal/models/certification/Authority.false-reject.cfg deleted file mode 100644 index 6109240..0000000 --- a/formal/models/certification/Authority.false-reject.cfg +++ /dev/null @@ -1,25 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Fault = "false_reject" - ComponentId = "allocation" - TargetPolicy = "policy-0" - CandidatePolicy = "policy-1" - TargetPackage = "package-0" - CandidatePackage = "package-1" - CheckerA = "checker-0" - CheckerB = "checker-1" - SourceA = "source-0" - SourceB = "source-1" - ProtectedTarget = "target-0" - CandidateTarget = "target-1" -INVARIANT TypeOK -INVARIANT ClaimPinned -INVARIANT TargetAuthorityPinned -INVARIANT SnapshotPinned -INVARIANT CandidateCapturePinned -INVARIANT ReceiptBound -INVARIANT PublishedPassBound -INVARIANT PreflightNotProof -INVARIANT ReuseDecisionBound -INVARIANT ReuseRejectedBound diff --git a/formal/models/certification/Authority.preflight-pass.cfg b/formal/models/certification/Authority.preflight-pass.cfg deleted file mode 100644 index 6b231a1..0000000 --- a/formal/models/certification/Authority.preflight-pass.cfg +++ /dev/null @@ -1,25 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Fault = "promote_preflight" - ComponentId = "allocation" - TargetPolicy = "policy-0" - CandidatePolicy = "policy-1" - TargetPackage = "package-0" - CandidatePackage = "package-1" - CheckerA = "checker-0" - CheckerB = "checker-1" - SourceA = "source-0" - SourceB = "source-1" - ProtectedTarget = "target-0" - CandidateTarget = "target-1" -INVARIANT TypeOK -INVARIANT ClaimPinned -INVARIANT TargetAuthorityPinned -INVARIANT SnapshotPinned -INVARIANT CandidateCapturePinned -INVARIANT ReceiptBound -INVARIANT PublishedPassBound -INVARIANT PreflightNotProof -INVARIANT ReuseDecisionBound -INVARIANT ReuseRejectedBound diff --git a/formal/models/certification/Authority.stale-reuse.cfg b/formal/models/certification/Authority.stale-reuse.cfg deleted file mode 100644 index f543332..0000000 --- a/formal/models/certification/Authority.stale-reuse.cfg +++ /dev/null @@ -1,25 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Fault = "stale_reuse" - ComponentId = "allocation" - TargetPolicy = "policy-0" - CandidatePolicy = "policy-1" - TargetPackage = "package-0" - CandidatePackage = "package-1" - CheckerA = "checker-0" - CheckerB = "checker-1" - SourceA = "source-0" - SourceB = "source-1" - ProtectedTarget = "target-0" - CandidateTarget = "target-1" -INVARIANT TypeOK -INVARIANT ClaimPinned -INVARIANT TargetAuthorityPinned -INVARIANT SnapshotPinned -INVARIANT CandidateCapturePinned -INVARIANT ReceiptBound -INVARIANT PublishedPassBound -INVARIANT PreflightNotProof -INVARIANT ReuseDecisionBound -INVARIANT ReuseRejectedBound diff --git a/formal/models/certification/Authority.swapped-receipt.cfg b/formal/models/certification/Authority.swapped-receipt.cfg deleted file mode 100644 index 4c4abab..0000000 --- a/formal/models/certification/Authority.swapped-receipt.cfg +++ /dev/null @@ -1,25 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Fault = "swapped_receipt" - ComponentId = "allocation" - TargetPolicy = "policy-0" - CandidatePolicy = "policy-1" - TargetPackage = "package-0" - CandidatePackage = "package-1" - CheckerA = "checker-0" - CheckerB = "checker-1" - SourceA = "source-0" - SourceB = "source-1" - ProtectedTarget = "target-0" - CandidateTarget = "target-1" -INVARIANT TypeOK -INVARIANT ClaimPinned -INVARIANT TargetAuthorityPinned -INVARIANT SnapshotPinned -INVARIANT CandidateCapturePinned -INVARIANT ReceiptBound -INVARIANT PublishedPassBound -INVARIANT PreflightNotProof -INVARIANT ReuseDecisionBound -INVARIANT ReuseRejectedBound diff --git a/formal/models/certification/Authority.tla b/formal/models/certification/Authority.tla deleted file mode 100644 index 578ce47..0000000 --- a/formal/models/certification/Authority.tla +++ /dev/null @@ -1,306 +0,0 @@ ----- MODULE Authority ---- -EXTENDS FiniteSets - -CONSTANTS Fault, ComponentId, - TargetPolicy, CandidatePolicy, TargetPackage, CandidatePackage, - CheckerA, CheckerB, SourceA, SourceB, - ProtectedTarget, CandidateTarget - -NoId == "none" -Policies == {TargetPolicy, CandidatePolicy} -Packages == {TargetPackage, CandidatePackage} -Checkers == {CheckerA, CheckerB} -Sources == {SourceA, SourceB} -Modes == {"none", "local", "ci", "preflight"} -Phases == {"idle", "submitted", "captured", "sealed", "executed", - "receipted", "published", "reuse_checked", "reuse_rejected", "preflight_done"} -Results == {"none", "PASS", "FAIL", "BLOCKED"} -Targets == {NoId, ProtectedTarget, CandidateTarget} -Claim(policy, package) == - [component |-> ComponentId, policy_sha256 |-> policy, - package_sha256 |-> package] -NoClaim == [component |-> NoId, policy_sha256 |-> NoId, package_sha256 |-> NoId] -Claims == {NoClaim} \cup {Claim(policy, package) : policy \in Policies, package \in Packages} - -EmptyRequest == [claim |-> NoClaim, component_claim |-> NoClaim, - policy |-> NoId, package |-> NoId, checker |-> NoId, - source |-> NoId, capture |-> NoId, host_target |-> NoId] -EmptyJob == [claim |-> NoClaim, policy |-> NoId, package |-> NoId, - checker |-> NoId, source |-> NoId, host_target |-> NoId] -EmptyReceipt == [claim |-> NoClaim, policy |-> NoId, package |-> NoId, - checker |-> NoId, source |-> NoId, host_target |-> NoId, - outcome |-> "none"] - -VARIABLES phase, mode, live, request, job, jobExists, outcome, - receipt, receiptExists, preflightReturned, published, publishedPass -vars == <> - -Init == - /\ phase = "idle" - /\ mode = "none" - /\ live = [policy |-> TargetPolicy, package |-> TargetPackage, - checker |-> CheckerA, source |-> SourceA, - candidate_policy |-> CandidatePolicy, - candidate_package |-> CandidatePackage] - /\ request = EmptyRequest - /\ job = EmptyJob - /\ jobExists = FALSE - /\ outcome = "none" - /\ receipt = EmptyReceipt - /\ receiptExists = FALSE - /\ preflightReturned = FALSE - /\ published = FALSE - /\ publishedPass = FALSE - -SubmitLocal == - /\ phase = "idle" - /\ phase' = "submitted" - /\ mode' = "local" - /\ request' = [claim |-> IF Fault = "bad_claim" - THEN Claim(live.candidate_policy, live.candidate_package) - ELSE Claim(live.policy, live.package), - component_claim |-> Claim(live.policy, live.package), - policy |-> live.policy, package |-> live.package, - checker |-> live.checker, source |-> live.source, - capture |-> NoId, host_target |-> NoId] - /\ UNCHANGED <> - -SubmitCI == - /\ phase = "idle" - /\ phase' = "submitted" - /\ mode' = "ci" - /\ request' = [claim |-> Claim( - IF Fault = "candidate_target" THEN live.candidate_policy ELSE TargetPolicy, - IF Fault = "candidate_target" THEN live.candidate_package ELSE TargetPackage), - component_claim |-> Claim( - IF Fault = "candidate_target" THEN live.candidate_policy ELSE TargetPolicy, - IF Fault = "candidate_target" THEN live.candidate_package ELSE TargetPackage), - policy |-> IF Fault = "candidate_target" THEN live.candidate_policy ELSE TargetPolicy, - package |-> IF Fault = "candidate_target" THEN live.candidate_package ELSE TargetPackage, - checker |-> live.checker, source |-> live.source, - capture |-> NoId, - host_target |-> IF Fault = "candidate_target" THEN CandidateTarget ELSE ProtectedTarget] - /\ UNCHANGED <> - -ReturnPreflight == - /\ phase = "idle" - /\ phase' = "preflight_done" - /\ mode' = "preflight" - /\ preflightReturned' = TRUE - /\ UNCHANGED <> - -DriftPolicy == - /\ phase \notin {"reuse_checked", "reuse_rejected"} - /\ live.policy = TargetPolicy - /\ live.package = TargetPackage - /\ live' = [live EXCEPT !.policy = CandidatePolicy, - !.package = CandidatePackage] - /\ UNCHANGED <> - -DriftChecker == - /\ phase \notin {"reuse_checked", "reuse_rejected"} - /\ live.checker = CheckerA - /\ live' = [live EXCEPT !.checker = CheckerB] - /\ UNCHANGED <> - -DriftSource == - /\ phase \notin {"reuse_checked", "reuse_rejected"} - /\ live.source = SourceA - /\ live' = [live EXCEPT !.source = SourceB] - /\ UNCHANGED <> - -CaptureCandidate == - /\ phase = "submitted" - /\ phase' = "captured" - /\ request' = [request EXCEPT !.capture = - IF Fault = "wrong_capture" THEN SourceB ELSE request.source] - /\ UNCHANGED <> - -SealJob == - /\ phase = "captured" - /\ (request.claim = request.component_claim \/ Fault = "bad_claim") - /\ (request.capture = request.source \/ Fault = "wrong_capture") - /\ phase' = "sealed" - /\ jobExists' = TRUE - /\ job' = [claim |-> request.component_claim, - policy |-> request.policy, package |-> request.package, - checker |-> request.checker, source |-> request.capture, - host_target |-> request.host_target] - /\ UNCHANGED <> - -Execute == - /\ phase = "sealed" - /\ jobExists - /\ phase' = "executed" - /\ outcome' \in {"PASS", "FAIL", "BLOCKED"} - /\ UNCHANGED <> - -SealReceipt == - /\ phase = "executed" - /\ phase' = "receipted" - /\ receiptExists' = TRUE - /\ receipt' = [claim |-> IF Fault = "swapped_receipt" - THEN Claim(live.candidate_policy, live.candidate_package) - ELSE job.claim, - policy |-> job.policy, package |-> job.package, - checker |-> job.checker, source |-> job.source, - host_target |-> job.host_target, outcome |-> outcome] - /\ UNCHANGED <> - -ReceiptValid == - /\ jobExists - /\ receiptExists - /\ receipt.claim = job.claim - /\ receipt.policy = job.policy - /\ receipt.package = job.package - /\ receipt.checker = job.checker - /\ receipt.source = job.source - /\ receipt.host_target = job.host_target - /\ receipt.outcome = outcome - -Publish == - /\ phase = "receipted" - /\ ReceiptValid - /\ phase' = "published" - /\ published' = TRUE - /\ publishedPass' = (outcome = "PASS") - /\ UNCHANGED <> - -PromotePreflight == - /\ Fault = "promote_preflight" - /\ phase = "preflight_done" - /\ preflightReturned - /\ phase' = "published" - /\ jobExists' = TRUE - /\ job' = EmptyJob - /\ outcome' = "PASS" - /\ receiptExists' = TRUE - /\ receipt' = [EmptyReceipt EXCEPT !.outcome = "PASS"] - /\ published' = TRUE - /\ publishedPass' = TRUE - /\ UNCHANGED <> - -LivePinsMatchJob == - /\ live.policy = job.policy - /\ live.package = job.package - /\ live.checker = job.checker - /\ live.source = job.source - /\ Claim(live.policy, live.package) = job.claim - -TryReuse == - /\ phase = "published" - /\ mode = "local" - /\ ReceiptValid - /\ phase' = IF Fault = "false_reject" THEN "reuse_rejected" ELSE IF outcome = "PASS" \land (Fault = "stale_reuse" \lor LivePinsMatchJob) - THEN "reuse_checked" ELSE "reuse_rejected" - /\ UNCHANGED <> - -Next == - \/ SubmitLocal - \/ SubmitCI - \/ ReturnPreflight - \/ DriftPolicy - \/ DriftChecker - \/ DriftSource - \/ CaptureCandidate - \/ SealJob - \/ Execute - \/ SealReceipt - \/ Publish - \/ TryReuse - \/ PromotePreflight - -Spec == Init /\ [][Next]_vars - -RequestType == [claim : Claims, component_claim : Claims, - policy : Policies \cup {NoId}, package : Packages \cup {NoId}, - checker : Checkers \cup {NoId}, source : Sources \cup {NoId}, - capture : Sources \cup {NoId}, host_target : Targets] -JobType == [claim : Claims, policy : Policies \cup {NoId}, - package : Packages \cup {NoId}, checker : Checkers \cup {NoId}, - source : Sources \cup {NoId}, host_target : Targets] -ReceiptType == [claim : Claims, policy : Policies \cup {NoId}, - package : Packages \cup {NoId}, checker : Checkers \cup {NoId}, - source : Sources \cup {NoId}, host_target : Targets, outcome : Results] - -TypeOK == - /\ phase \in Phases - /\ mode \in Modes - /\ live \in [policy : Policies, package : Packages, - checker : Checkers, source : Sources, - candidate_policy : Policies, candidate_package : Packages] - /\ request \in RequestType - /\ job \in JobType - /\ jobExists \in BOOLEAN - /\ outcome \in Results - /\ receipt \in ReceiptType - /\ receiptExists \in BOOLEAN - /\ preflightReturned \in BOOLEAN - /\ published \in BOOLEAN - /\ publishedPass \in BOOLEAN - -ClaimPinned == - mode \in {"local", "ci"} /\ phase # "idle" => - /\ request.claim = request.component_claim - /\ jobExists => job.claim = request.component_claim - /\ jobExists => job.claim = Claim(job.policy, job.package) - -TargetAuthorityPinned == - mode = "ci" /\ phase # "idle" => - /\ request.host_target = ProtectedTarget - /\ request.claim = Claim(TargetPolicy, TargetPackage) - /\ request.policy = TargetPolicy - /\ request.package = TargetPackage - /\ (jobExists => job.host_target = ProtectedTarget) - -SnapshotPinned == - jobExists => - /\ job.policy = request.policy - /\ job.package = request.package - /\ job.checker = request.checker - -CandidateCapturePinned == - mode \in {"local", "ci"} /\ phase \in {"captured", "sealed", "executed", "receipted", "published", "reuse_checked", "reuse_rejected"} => - /\ request.capture = request.source - /\ (jobExists => job.source = request.source) - -ReceiptBound == - receiptExists => ReceiptValid - -PublishedPassBound == - publishedPass => published /\ ReceiptValid /\ outcome = "PASS" - -PreflightNotProof == - preflightReturned => - /\ mode = "preflight" - /\ phase = "preflight_done" - /\ ~jobExists - /\ ~receiptExists - /\ outcome = "none" - /\ ~published - /\ ~publishedPass - -ReuseDecisionBound == - phase = "reuse_checked" => - /\ mode = "local" - /\ ReceiptValid - /\ outcome = "PASS" - /\ LivePinsMatchJob - -ReuseRejectedBound == - phase = "reuse_rejected" => outcome # "PASS" \/ ~LivePinsMatchJob - -==== diff --git a/formal/models/certification/Authority.wrong-capture.cfg b/formal/models/certification/Authority.wrong-capture.cfg deleted file mode 100644 index 4d46e06..0000000 --- a/formal/models/certification/Authority.wrong-capture.cfg +++ /dev/null @@ -1,25 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Fault = "wrong_capture" - ComponentId = "allocation" - TargetPolicy = "policy-0" - CandidatePolicy = "policy-1" - TargetPackage = "package-0" - CandidatePackage = "package-1" - CheckerA = "checker-0" - CheckerB = "checker-1" - SourceA = "source-0" - SourceB = "source-1" - ProtectedTarget = "target-0" - CandidateTarget = "target-1" -INVARIANT TypeOK -INVARIANT ClaimPinned -INVARIANT TargetAuthorityPinned -INVARIANT SnapshotPinned -INVARIANT CandidateCapturePinned -INVARIANT ReceiptBound -INVARIANT PublishedPassBound -INVARIANT PreflightNotProof -INVARIANT ReuseDecisionBound -INVARIANT ReuseRejectedBound diff --git a/formal/models/certification/DifferenceDecisionBridge.tla b/formal/models/certification/DifferenceDecisionBridge.tla deleted file mode 100644 index cdb14f2..0000000 --- a/formal/models/certification/DifferenceDecisionBridge.tla +++ /dev/null @@ -1,14 +0,0 @@ ----- MODULE DifferenceDecisionBridge ---- -EXTENDS Differences, TLC - -WireRecord(r) == <> -WireRecords(sequence) == [j \in 1..Len(sequence) |-> WireRecord(sequence[j])] -CoverageComplete == Inputs # {} /\ Len(missing) = 0 - -BridgeOutput == - phase = "done" => - PrintT(<<"VKIT_DIFF_DECISION_V1", Scenario, WireRecords(records), status, - CoverageComplete, missing, WireRecords(violations), - WireRecords(unknowns), WireRecords(repairs)>>) - -==== diff --git a/formal/models/certification/Differences.cfg b/formal/models/certification/Differences.cfg deleted file mode 100644 index c4d6897..0000000 --- a/formal/models/certification/Differences.cfg +++ /dev/null @@ -1,22 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Scenario = "bounded" - Mutant = "none" - SourceProof = FALSE - ApprovalAuthority = FALSE -INVARIANT TypeOK -INVARIANT SelectedCoverage -INVARIANT UnknownBlocksConformance -INVARIANT StandingIntent -INVARIANT GuardIntersection -INVARIANT UnguardedRelation -INVARIANT ViolationVisibility -INVARIANT ConformanceSoundness -INVARIANT DuplicateSelectedUnknown -INVARIANT RepairAccepted -INVARIANT RepairClassification -INVARIANT EmptyDomainUnknown -INVARIANT NoCompletedState -INVARIANT NoConformance -INVARIANT AuthorityBoundary diff --git a/formal/models/certification/Differences.empty.cfg b/formal/models/certification/Differences.empty.cfg deleted file mode 100644 index 60ed542..0000000 --- a/formal/models/certification/Differences.empty.cfg +++ /dev/null @@ -1,22 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Scenario = "empty" - Mutant = "none" - SourceProof = FALSE - ApprovalAuthority = FALSE -INVARIANT TypeOK -INVARIANT SelectedCoverage -INVARIANT UnknownBlocksConformance -INVARIANT StandingIntent -INVARIANT GuardIntersection -INVARIANT UnguardedRelation -INVARIANT ViolationVisibility -INVARIANT ConformanceSoundness -INVARIANT DuplicateSelectedUnknown -INVARIANT RepairAccepted -INVARIANT RepairClassification -INVARIANT EmptyDomainUnknown -INVARIANT NoCompletedState -INVARIANT NoConformance -INVARIANT AuthorityBoundary diff --git a/formal/models/certification/Differences.guard-overlap.cfg b/formal/models/certification/Differences.guard-overlap.cfg deleted file mode 100644 index 48e5cdb..0000000 --- a/formal/models/certification/Differences.guard-overlap.cfg +++ /dev/null @@ -1,22 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Scenario = "guard_overlap" - Mutant = "none" - SourceProof = FALSE - ApprovalAuthority = FALSE -INVARIANT TypeOK -INVARIANT SelectedCoverage -INVARIANT UnknownBlocksConformance -INVARIANT StandingIntent -INVARIANT GuardIntersection -INVARIANT UnguardedRelation -INVARIANT ViolationVisibility -INVARIANT ConformanceSoundness -INVARIANT DuplicateSelectedUnknown -INVARIANT RepairAccepted -INVARIANT RepairClassification -INVARIANT EmptyDomainUnknown -INVARIANT NoCompletedState -INVARIANT NoConformance -INVARIANT AuthorityBoundary diff --git a/formal/models/certification/Differences.invalid-shrink.cfg b/formal/models/certification/Differences.invalid-shrink.cfg deleted file mode 100644 index 2c44ba3..0000000 --- a/formal/models/certification/Differences.invalid-shrink.cfg +++ /dev/null @@ -1,22 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Scenario = "invalid_shrink" - Mutant = "none" - SourceProof = FALSE - ApprovalAuthority = FALSE -INVARIANT TypeOK -INVARIANT SelectedCoverage -INVARIANT UnknownBlocksConformance -INVARIANT StandingIntent -INVARIANT GuardIntersection -INVARIANT UnguardedRelation -INVARIANT ViolationVisibility -INVARIANT ConformanceSoundness -INVARIANT DuplicateSelectedUnknown -INVARIANT RepairAccepted -INVARIANT RepairClassification -INVARIANT EmptyDomainUnknown -INVARIANT NoCompletedState -INVARIANT NoConformance -INVARIANT AuthorityBoundary diff --git a/formal/models/certification/Differences.mutant-empty.cfg b/formal/models/certification/Differences.mutant-empty.cfg deleted file mode 100644 index 4bf4ff4..0000000 --- a/formal/models/certification/Differences.mutant-empty.cfg +++ /dev/null @@ -1,22 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Scenario = "empty" - Mutant = "empty_vacuous" - SourceProof = FALSE - ApprovalAuthority = FALSE -INVARIANT TypeOK -INVARIANT EmptyDomainUnknown -INVARIANT SelectedCoverage -INVARIANT UnknownBlocksConformance -INVARIANT StandingIntent -INVARIANT GuardIntersection -INVARIANT UnguardedRelation -INVARIANT ViolationVisibility -INVARIANT ConformanceSoundness -INVARIANT DuplicateSelectedUnknown -INVARIANT RepairAccepted -INVARIANT RepairClassification -INVARIANT NoCompletedState -INVARIANT NoConformance -INVARIANT AuthorityBoundary diff --git a/formal/models/certification/Differences.mutant-hide-violation.cfg b/formal/models/certification/Differences.mutant-hide-violation.cfg deleted file mode 100644 index 41404a7..0000000 --- a/formal/models/certification/Differences.mutant-hide-violation.cfg +++ /dev/null @@ -1,22 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Scenario = "violation_missing" - Mutant = "hide_violation" - SourceProof = FALSE - ApprovalAuthority = FALSE -INVARIANT TypeOK -INVARIANT SelectedCoverage -INVARIANT UnknownBlocksConformance -INVARIANT StandingIntent -INVARIANT GuardIntersection -INVARIANT UnguardedRelation -INVARIANT ViolationVisibility -INVARIANT ConformanceSoundness -INVARIANT DuplicateSelectedUnknown -INVARIANT RepairAccepted -INVARIANT RepairClassification -INVARIANT EmptyDomainUnknown -INVARIANT NoCompletedState -INVARIANT NoConformance -INVARIANT AuthorityBoundary diff --git a/formal/models/certification/Differences.mutant-ignore-shrink.cfg b/formal/models/certification/Differences.mutant-ignore-shrink.cfg deleted file mode 100644 index 8983a5e..0000000 --- a/formal/models/certification/Differences.mutant-ignore-shrink.cfg +++ /dev/null @@ -1,22 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Scenario = "invalid_shrink" - Mutant = "ignore_shrink_unknown" - SourceProof = FALSE - ApprovalAuthority = FALSE -INVARIANT TypeOK -INVARIANT SelectedCoverage -INVARIANT UnknownBlocksConformance -INVARIANT StandingIntent -INVARIANT GuardIntersection -INVARIANT UnguardedRelation -INVARIANT ViolationVisibility -INVARIANT ConformanceSoundness -INVARIANT DuplicateSelectedUnknown -INVARIANT RepairAccepted -INVARIANT RepairClassification -INVARIANT EmptyDomainUnknown -INVARIANT NoCompletedState -INVARIANT NoConformance -INVARIANT AuthorityBoundary diff --git a/formal/models/certification/Differences.mutant-reject-repair.cfg b/formal/models/certification/Differences.mutant-reject-repair.cfg deleted file mode 100644 index 76a2212..0000000 --- a/formal/models/certification/Differences.mutant-reject-repair.cfg +++ /dev/null @@ -1,22 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Scenario = "repair" - Mutant = "reject_repair" - SourceProof = FALSE - ApprovalAuthority = FALSE -INVARIANT TypeOK -INVARIANT SelectedCoverage -INVARIANT UnknownBlocksConformance -INVARIANT StandingIntent -INVARIANT GuardIntersection -INVARIANT UnguardedRelation -INVARIANT ViolationVisibility -INVARIANT ConformanceSoundness -INVARIANT DuplicateSelectedUnknown -INVARIANT RepairAccepted -INVARIANT RepairClassification -INVARIANT EmptyDomainUnknown -INVARIANT NoCompletedState -INVARIANT NoConformance -INVARIANT AuthorityBoundary diff --git a/formal/models/certification/Differences.mutant-shrink-coverage.cfg b/formal/models/certification/Differences.mutant-shrink-coverage.cfg deleted file mode 100644 index 4e6ad2f..0000000 --- a/formal/models/certification/Differences.mutant-shrink-coverage.cfg +++ /dev/null @@ -1,22 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Scenario = "selected_vs_shrink" - Mutant = "shrink_fills_coverage" - SourceProof = FALSE - ApprovalAuthority = FALSE -INVARIANT TypeOK -INVARIANT SelectedCoverage -INVARIANT UnknownBlocksConformance -INVARIANT StandingIntent -INVARIANT GuardIntersection -INVARIANT UnguardedRelation -INVARIANT ViolationVisibility -INVARIANT ConformanceSoundness -INVARIANT DuplicateSelectedUnknown -INVARIANT RepairAccepted -INVARIANT RepairClassification -INVARIANT EmptyDomainUnknown -INVARIANT NoCompletedState -INVARIANT NoConformance -INVARIANT AuthorityBoundary diff --git a/formal/models/certification/Differences.mutant-skip-standing.cfg b/formal/models/certification/Differences.mutant-skip-standing.cfg deleted file mode 100644 index 60ae3d0..0000000 --- a/formal/models/certification/Differences.mutant-skip-standing.cfg +++ /dev/null @@ -1,22 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Scenario = "standing_violation" - Mutant = "skip_standing" - SourceProof = FALSE - ApprovalAuthority = FALSE -INVARIANT TypeOK -INVARIANT SelectedCoverage -INVARIANT UnknownBlocksConformance -INVARIANT StandingIntent -INVARIANT GuardIntersection -INVARIANT UnguardedRelation -INVARIANT ViolationVisibility -INVARIANT ConformanceSoundness -INVARIANT DuplicateSelectedUnknown -INVARIANT RepairAccepted -INVARIANT RepairClassification -INVARIANT EmptyDomainUnknown -INVARIANT NoCompletedState -INVARIANT NoConformance -INVARIANT AuthorityBoundary diff --git a/formal/models/certification/Differences.mutant-unguarded-change.cfg b/formal/models/certification/Differences.mutant-unguarded-change.cfg deleted file mode 100644 index ce64b9a..0000000 --- a/formal/models/certification/Differences.mutant-unguarded-change.cfg +++ /dev/null @@ -1,22 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Scenario = "unguarded_change" - Mutant = "allow_unguarded_change" - SourceProof = FALSE - ApprovalAuthority = FALSE -INVARIANT TypeOK -INVARIANT SelectedCoverage -INVARIANT UnknownBlocksConformance -INVARIANT StandingIntent -INVARIANT GuardIntersection -INVARIANT UnguardedRelation -INVARIANT ViolationVisibility -INVARIANT ConformanceSoundness -INVARIANT DuplicateSelectedUnknown -INVARIANT RepairAccepted -INVARIANT RepairClassification -INVARIANT EmptyDomainUnknown -INVARIANT NoCompletedState -INVARIANT NoConformance -INVARIANT AuthorityBoundary diff --git a/formal/models/certification/Differences.mutant-union-guards.cfg b/formal/models/certification/Differences.mutant-union-guards.cfg deleted file mode 100644 index 7a4e4f8..0000000 --- a/formal/models/certification/Differences.mutant-union-guards.cfg +++ /dev/null @@ -1,22 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Scenario = "guard_overlap" - Mutant = "union_guards" - SourceProof = FALSE - ApprovalAuthority = FALSE -INVARIANT TypeOK -INVARIANT SelectedCoverage -INVARIANT UnknownBlocksConformance -INVARIANT StandingIntent -INVARIANT GuardIntersection -INVARIANT UnguardedRelation -INVARIANT ViolationVisibility -INVARIANT ConformanceSoundness -INVARIANT DuplicateSelectedUnknown -INVARIANT RepairAccepted -INVARIANT RepairClassification -INVARIANT EmptyDomainUnknown -INVARIANT NoCompletedState -INVARIANT NoConformance -INVARIANT AuthorityBoundary diff --git a/formal/models/certification/Differences.reach-conformance.cfg b/formal/models/certification/Differences.reach-conformance.cfg deleted file mode 100644 index c3f4c9c..0000000 --- a/formal/models/certification/Differences.reach-conformance.cfg +++ /dev/null @@ -1,22 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Scenario = "reach_conformance" - Mutant = "none" - SourceProof = FALSE - ApprovalAuthority = FALSE -INVARIANT TypeOK -INVARIANT SelectedCoverage -INVARIANT UnknownBlocksConformance -INVARIANT StandingIntent -INVARIANT GuardIntersection -INVARIANT UnguardedRelation -INVARIANT ViolationVisibility -INVARIANT ConformanceSoundness -INVARIANT DuplicateSelectedUnknown -INVARIANT RepairAccepted -INVARIANT RepairClassification -INVARIANT EmptyDomainUnknown -INVARIANT NoCompletedState -INVARIANT NoConformance -INVARIANT AuthorityBoundary diff --git a/formal/models/certification/Differences.reach-empty-done.cfg b/formal/models/certification/Differences.reach-empty-done.cfg deleted file mode 100644 index 65ff776..0000000 --- a/formal/models/certification/Differences.reach-empty-done.cfg +++ /dev/null @@ -1,22 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Scenario = "reach_empty_done" - Mutant = "none" - SourceProof = FALSE - ApprovalAuthority = FALSE -INVARIANT TypeOK -INVARIANT SelectedCoverage -INVARIANT UnknownBlocksConformance -INVARIANT StandingIntent -INVARIANT GuardIntersection -INVARIANT UnguardedRelation -INVARIANT ViolationVisibility -INVARIANT ConformanceSoundness -INVARIANT DuplicateSelectedUnknown -INVARIANT RepairAccepted -INVARIANT RepairClassification -INVARIANT EmptyDomainUnknown -INVARIANT NoCompletedState -INVARIANT NoConformance -INVARIANT AuthorityBoundary diff --git a/formal/models/certification/Differences.repair.cfg b/formal/models/certification/Differences.repair.cfg deleted file mode 100644 index 875ae4f..0000000 --- a/formal/models/certification/Differences.repair.cfg +++ /dev/null @@ -1,22 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Scenario = "repair" - Mutant = "none" - SourceProof = FALSE - ApprovalAuthority = FALSE -INVARIANT TypeOK -INVARIANT SelectedCoverage -INVARIANT UnknownBlocksConformance -INVARIANT StandingIntent -INVARIANT GuardIntersection -INVARIANT UnguardedRelation -INVARIANT ViolationVisibility -INVARIANT ConformanceSoundness -INVARIANT DuplicateSelectedUnknown -INVARIANT RepairAccepted -INVARIANT RepairClassification -INVARIANT EmptyDomainUnknown -INVARIANT NoCompletedState -INVARIANT NoConformance -INVARIANT AuthorityBoundary diff --git a/formal/models/certification/Differences.tla b/formal/models/certification/Differences.tla deleted file mode 100644 index afb6a27..0000000 --- a/formal/models/certification/Differences.tla +++ /dev/null @@ -1,311 +0,0 @@ ----- MODULE Differences ---- -EXTENDS Naturals, FiniteSets, Sequences - -CONSTANTS Scenario, Mutant, SourceProof, ApprovalAuthority - -Inputs == - CASE Scenario = "complete" -> {1, 2} - [] Scenario = "bounded" -> {1, 2} - [] Scenario = "violation_missing" -> {1, 2} - [] Scenario = "empty" -> {} - [] OTHER -> {1} - -InputOrder == - CASE Inputs = {} -> <<>> - [] Inputs = {1, 2} -> <<1, 2>> - [] OTHER -> <<1>> - -OutputModel == {0, 1, 2, 3} -Repetitions == 2 -Standing == [i \in {1, 2} |-> IF i = 1 THEN {1, 2} ELSE {2}] - -GuardRows == - IF Scenario \in {"guard_overlap", "guard_duplicate"} THEN - { [input |-> 1, outputs |-> {1, 2}], - [input |-> 1, outputs |-> {2}] } - ELSE {} - -Record(i, isSelected, failed, baseValues, candidateValues) == - [input |-> i, selected |-> isSelected, failure |-> failed, - base |-> baseValues, candidate |-> candidateValues] - -Equal1 == Record(1, TRUE, FALSE, <<1, 1>>, <<1, 1>>) -Equal2 == Record(2, TRUE, FALSE, <<2, 2>>, <<2, 2>>) -ShrinkEqual1 == Record(1, FALSE, FALSE, <<1, 1>>, <<1, 1>>) -ShrinkUnstable1 == Record(1, FALSE, FALSE, <<1, 1>>, <<1, 2>>) -ShrinkUnstable2 == Record(2, FALSE, FALSE, <<2, 2>>, <<2, 1>>) -Violation1 == Record(1, TRUE, FALSE, <<1, 1>>, <<2, 2>>) -GuardAllowed1 == Record(1, TRUE, FALSE, <<1, 1>>, <<2, 2>>) -GuardRejected1 == Record(1, TRUE, FALSE, <<1, 1>>, <<1, 1>>) -StandingViolation1 == Record(1, TRUE, FALSE, <<3, 3>>, <<3, 3>>) -UnguardedChange1 == Record(1, TRUE, FALSE, <<1, 1>>, <<2, 2>>) -Repair1 == Record(1, TRUE, FALSE, <<0, 0>>, <<1, 1>>) -BadCandidate1 == Record(1, TRUE, FALSE, <<0, 0>>, <<0, 0>>) -SelectedEqual1 == Record(1, TRUE, FALSE, <<1, 1>>, <<1, 1>>) -SelectedEqual2 == Record(2, TRUE, FALSE, <<2, 2>>, <<2, 2>>) -SelectedChange1 == Record(1, TRUE, FALSE, <<1, 1>>, <<2, 2>>) -SelectedStandingBad1 == Record(1, TRUE, FALSE, <<1, 1>>, <<3, 3>>) -SelectedRepair1 == Record(1, TRUE, FALSE, <<0, 0>>, <<1, 1>>) -SelectedFailed1 == Record(1, TRUE, TRUE, <<1>>, <<1>>) -SelectedUnstable1 == Record(1, TRUE, FALSE, <<1, 2>>, <<1, 1>>) -SelectedPartial1 == Record(1, TRUE, FALSE, <<1>>, <<1>>) -SelectedOutOfModel1 == Record(1, TRUE, FALSE, <<1, 1>>, <<4, 4>>) -ShrinkEqual2 == Record(2, FALSE, FALSE, <<2, 2>>, <<2, 2>>) -SelectedStandingBad2 == Record(2, TRUE, FALSE, <<2, 2>>, <<1, 1>>) - -Samples == - CASE Scenario = "complete" -> <> - [] Scenario = "reach_conformance" -> <> - [] Scenario = "bounded" -> - <> - [] Scenario = "selected_vs_shrink" -> <> - [] Scenario = "guard_duplicate" -> <> - [] Scenario = "invalid_shrink" -> <> - [] Scenario = "violation_missing" -> <> - [] Scenario = "guard_overlap" -> <> - [] Scenario = "standing_violation" -> <> - [] Scenario = "unguarded_change" -> <> - [] Scenario = "repair" -> <> - [] Scenario = "bad_candidate" -> <> - [] OTHER -> <<>> - -VARIABLES phase, records, pending, assessed, missing, violations, unknowns, - repairs, status - -vars == <> - -Init == - /\ phase = "collect" - /\ records = <<>> - /\ pending = InputOrder - /\ assessed = <<>> - /\ missing = <<>> - /\ violations = <<>> - /\ unknowns = <<>> - /\ repairs = <<>> - /\ status = "unset" - -SamplesSet == {Samples[j] : j \in 1..Len(Samples)} -RecordsSet == {records[j] : j \in 1..Len(records)} -PendingInputs == {pending[j] : j \in 1..Len(pending)} -MissingInputs == {missing[j] : j \in 1..Len(missing)} - -RecordAt(j) == IF j \in 1..Len(records) THEN records[j] ELSE Record(0, FALSE, TRUE, <<>>, <<>>) -KeepRecord(r, condition) == IF condition THEN <> ELSE <<>> - -Stable(values) == - \A j, k \in 1..Len(values) : values[j] = values[k] - -Valid(r) == - /\ ~r.failure - /\ Len(r.base) = Repetitions - /\ Len(r.candidate) = Repetitions - /\ Stable(r.base) - /\ Stable(r.candidate) - /\ \A j \in 1..Len(r.base) : r.base[j] \in OutputModel - /\ \A j \in 1..Len(r.candidate) : r.candidate[j] \in OutputModel - -Rows(i) == {r \in RecordsSet : r.input = i} -SelectedRows(i) == - KeepRecord(RecordAt(1), Len(records) >= 1 /\ RecordAt(1).input = i /\ - RecordAt(1).selected) - \o KeepRecord(RecordAt(2), Len(records) >= 2 /\ RecordAt(2).input = i /\ - RecordAt(2).selected) -BadRowsForInput(i) == - KeepRecord(RecordAt(1), Len(records) >= 1 /\ RecordAt(1).input = i /\ ~Valid(RecordAt(1)) - /\ (Mutant # "ignore_shrink_unknown" \/ RecordAt(1).selected)) - \o KeepRecord(RecordAt(2), Len(records) >= 2 /\ RecordAt(2).input = i /\ ~Valid(RecordAt(2)) - /\ (Mutant # "ignore_shrink_unknown" \/ RecordAt(2).selected)) - -Guarded(i) == \E g \in GuardRows : g.input = i -GuardAllows(i, output) == - \A g \in GuardRows : g.input # i \/ output \in g.outputs -GuardUnionAllows(i, output) == - \E g \in GuardRows : g.input = i /\ output \in g.outputs - -ExpectedClass(r) == - IF r.candidate[1] \notin Standing[r.input] THEN "violation" - ELSE IF Guarded(r.input) THEN - IF GuardAllows(r.input, r.candidate[1]) THEN "accepted" ELSE "violation" - ELSE IF r.base[1] = r.candidate[1] THEN "accepted" - ELSE IF r.base[1] \notin Standing[r.input] THEN "repair" - ELSE "violation" - -ActualClass(r) == - IF Mutant = "skip_standing" - THEN IF Guarded(r.input) - THEN IF GuardAllows(r.input, r.candidate[1]) THEN "accepted" ELSE "violation" - ELSE IF r.base[1] = r.candidate[1] THEN "accepted" ELSE "violation" - ELSE IF Mutant = "union_guards" /\ Guarded(r.input) - THEN IF GuardUnionAllows(r.input, r.candidate[1]) THEN "accepted" ELSE "violation" - ELSE IF Mutant = "allow_unguarded_change" /\ ~Guarded(r.input) - THEN "accepted" - ELSE IF Mutant = "reject_repair" /\ r.base[1] \notin Standing[r.input] - /\ r.candidate[1] \in Standing[r.input] - THEN "violation" - ELSE ExpectedClass(r) - -CoverageOK(i) == - /\ Len(SelectedRows(i)) = 1 - /\ \A j \in 1..Len(SelectedRows(i)) : Valid(SelectedRows(i)[j]) - -CoverageByRule(i) == - IF Mutant = "shrink_fills_coverage" - THEN \E r \in Rows(i) : Valid(r) - ELSE CoverageOK(i) - -RawViolation(r) == - Valid(r) /\ - ((r.candidate[1] \notin Standing[r.input]) \/ - (Guarded(r.input) /\ ~GuardAllows(r.input, r.candidate[1])) \/ - (~Guarded(r.input) /\ r.base[1] \in Standing[r.input] /\ - r.base[1] # r.candidate[1])) - -NoDuplicates(sequence) == - \A j, k \in 1..Len(sequence) : j < k => sequence[j] # sequence[k] - -TypeOK == - /\ phase \in {"collect", "assess", "done"} - /\ status \in {"unset", "conformance", "observed_violation", "unknown"} - /\ Len(records) <= 2 - /\ \A j \in 1..Len(records) : records[j] \in SamplesSet - /\ \A sequence \in {pending, assessed, missing} : - NoDuplicates(sequence) /\ \A j \in 1..Len(sequence) : sequence[j] \in Inputs - /\ \A sequence \in {violations, unknowns, repairs} : - \A j \in 1..Len(sequence) : sequence[j] \in RecordsSet - -AddRecord(r) == - /\ phase = "collect" - /\ r \in SamplesSet - /\ Len(records) < 2 - /\ records' = Append(records, r) - /\ UNCHANGED <> - -RemoveInput(sequence, input) == - IF sequence[1] = input THEN - IF Len(sequence) = 1 THEN <<>> ELSE <> - ELSE <> - -CloseCollection == - /\ phase = "collect" - /\ phase' = "assess" - /\ UNCHANGED <> - -AssessInput(i) == - /\ phase = "assess" - /\ i \in PendingInputs - /\ pending' = RemoveInput(pending, i) - /\ assessed' = Append(assessed, i) - /\ missing' = IF CoverageByRule(i) THEN missing ELSE Append(missing, i) - /\ unknowns' = unknowns \o BadRowsForInput(i) - /\ violations' = violations \o - KeepRecord(RecordAt(1), Len(records) >= 1 /\ RecordAt(1).input = i /\ - Valid(RecordAt(1)) /\ ActualClass(RecordAt(1)) = "violation") - \o KeepRecord(RecordAt(2), Len(records) >= 2 /\ RecordAt(2).input = i /\ - Valid(RecordAt(2)) /\ ActualClass(RecordAt(2)) = "violation") - /\ repairs' = repairs \o - KeepRecord(RecordAt(1), Len(records) >= 1 /\ RecordAt(1).input = i /\ - Valid(RecordAt(1)) /\ ActualClass(RecordAt(1)) = "repair") - \o KeepRecord(RecordAt(2), Len(records) >= 2 /\ RecordAt(2).input = i /\ - Valid(RecordAt(2)) /\ ActualClass(RecordAt(2)) = "repair") - /\ UNCHANGED <> - -Finish == - /\ phase = "assess" - /\ pending = <<>> - /\ phase' = "done" - /\ status' = - IF Mutant = "hide_violation" - THEN IF Len(missing) > 0 \/ Len(unknowns) > 0 THEN "unknown" - ELSE IF Len(violations) > 0 THEN "observed_violation" - ELSE "conformance" - ELSE IF Mutant = "empty_vacuous" /\ Inputs = {} - THEN "conformance" - ELSE IF Len(violations) > 0 THEN "observed_violation" - ELSE IF Len(missing) = 0 /\ Len(unknowns) = 0 /\ Inputs # {} - THEN "conformance" - ELSE "unknown" - /\ UNCHANGED <> - -Done == phase = "done" /\ UNCHANGED vars -Next == (\E r \in SamplesSet : AddRecord(r)) - \/ CloseCollection - \/ (\E i \in Inputs : AssessInput(i)) - \/ Finish - \/ Done -Spec == Init /\ [][Next]_vars - -SelectedCoverage == - status = "conformance" => - /\ Inputs # {} - /\ \A i \in Inputs : CoverageOK(i) - -UnknownBlocksConformance == - status = "conformance" => - /\ Len(unknowns) = 0 - /\ \A j \in 1..Len(records) : Valid(records[j]) - -StandingIntent == - phase = "done" => - \A r \in RecordsSet : Valid(r) /\ r.candidate[1] \notin Standing[r.input] - => \E j \in 1..Len(violations) : violations[j] = r - -GuardIntersection == - phase = "done" => - \A r \in RecordsSet : - Valid(r) /\ Guarded(r.input) /\ - ~GuardAllows(r.input, r.candidate[1]) => - \E j \in 1..Len(violations) : violations[j] = r - -UnguardedRelation == - phase = "done" => - \A r \in RecordsSet : - Valid(r) /\ ~Guarded(r.input) /\ - r.base[1] \in Standing[r.input] /\ - r.base[1] # r.candidate[1] => - \E j \in 1..Len(violations) : violations[j] = r - -ViolationVisibility == - (phase = "done" /\ \E r \in RecordsSet : RawViolation(r)) => - status = "observed_violation" - -ConformanceSoundness == - status = "conformance" => - /\ Len(missing) = 0 - /\ Len(violations) = 0 - /\ Len(unknowns) = 0 - /\ \A i \in Inputs : CoverageOK(i) - -DuplicateSelectedUnknown == - phase = "done" => - \A i \in Inputs : Len(SelectedRows(i)) > 1 => - i \in MissingInputs /\ status # "conformance" - -RepairAccepted == - phase = "done" /\ Scenario = "repair" /\ Len(missing) = 0 => - /\ status = "conformance" - /\ \E j \in 1..Len(repairs) : repairs[j] = Repair1 - -RepairClassification == - phase = "done" => - \A r \in RecordsSet : - Valid(r) /\ ExpectedClass(r) = "repair" => - /\ \E j \in 1..Len(repairs) : repairs[j] = r - /\ \A j \in 1..Len(violations) : violations[j] # r - -EmptyDomainUnknown == - phase = "done" /\ Inputs = {} => status = "unknown" - -NoCompletedState == Scenario = "reach_empty_done" => phase # "done" -NoConformance == Scenario = "reach_conformance" => status # "conformance" - -AuthorityBoundary == ~SourceProof /\ ~ApprovalAuthority - -==== diff --git a/formal/models/certification/Differences.violation-missing.cfg b/formal/models/certification/Differences.violation-missing.cfg deleted file mode 100644 index 603d0bb..0000000 --- a/formal/models/certification/Differences.violation-missing.cfg +++ /dev/null @@ -1,22 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Scenario = "violation_missing" - Mutant = "none" - SourceProof = FALSE - ApprovalAuthority = FALSE -INVARIANT TypeOK -INVARIANT SelectedCoverage -INVARIANT UnknownBlocksConformance -INVARIANT StandingIntent -INVARIANT GuardIntersection -INVARIANT UnguardedRelation -INVARIANT ViolationVisibility -INVARIANT ConformanceSoundness -INVARIANT DuplicateSelectedUnknown -INVARIANT RepairAccepted -INVARIANT RepairClassification -INVARIANT EmptyDomainUnknown -INVARIANT NoCompletedState -INVARIANT NoConformance -INVARIANT AuthorityBoundary diff --git a/formal/models/certification/README.md b/formal/models/certification/README.md deleted file mode 100644 index eedf756..0000000 --- a/formal/models/certification/README.md +++ /dev/null @@ -1,119 +0,0 @@ -# Certification models - -This directory contains TLA+ models and TLC configurations for VKit's verification authority, shadow-receipt separation, and finite change-difference assessment. These models are bounded developer checks of VKit's decision logic. - -```mermaid -flowchart LR - Auth[Authority.tla
1 clean + 7 fault configs] --> CheckAuth[formal/checks/check_authority.py] - Shadow[ShadowAuthority.tla
1 clean + 4 mutant configs] --> CheckAuth - Diff[Differences.tla
6 clean + 2 reachability + 8 mutant configs] --> CheckAuth - Diff --> Bridge[DifferenceDecisionBridge.tla] - Bridge --> CheckBridge[formal/checks/check_difference_decisions.py] - CheckBridge --> Assessor[src/vkit/change/certification.py] - Finite[formal/checks/check_finite_decisions.py
354,346 tuples] --> Assessor -``` - -## Model inventory - -| Module | Configurations | Runner | Purpose | -| --- | --- | --- | --- | -| `Authority.tla` | `Authority.cfg` plus 7 fault configs | `formal/checks/check_authority.py --suite authority` | Submission, receipt validation, target authority, and reuse after drift. | -| `ShadowAuthority.tla` | `ShadowAuthority.cfg` plus 4 mutant configs | `formal/checks/check_authority.py --suite shadow` | Isolation between shadow change-certification receipts and required gate slots. | -| `Differences.tla` | 6 clean configs, 2 reachability configs, 8 mutant configs | `formal/checks/check_authority.py --suite differences` | Paired observation assessment, guard intersection, violation visibility, repairs, and empty domains. | -| `DifferenceDecisionBridge.tla` | Reuses the 6 clean `Differences` configs | `formal/checks/check_difference_decisions.py` | Emits terminal TLC decisions and compares each one with the Python assessor. | - -Other repository models live outside this directory: - -- `formal/models/lifecycle/Attempts.tla` models job attempt lifecycle and publication. -- `formal/models/DelegatedClaimAuthority.tla` models delegated claim acceptance. -- `formal/models/FiniteTransitionComparison.tla` models finite transition comparison. - -## Authority - -`Authority.tla` models submission, receipt validation, and evidence reuse. A request binds its component claim, policy, package, checker, and captured source. Protected CI derives its component and target from host-selected policy, so candidate policy cannot select that authority. - -Jobs and receipts retain the submitted snapshot when policy, tools, or source change. Reuse checks current identities against that snapshot. A passing historical receipt therefore does not establish that the current checkout can pass the gate. - -`Authority.cfg` configures one job, one component, two revisions each of policy, package, checker, and source, one trusted target, and one candidate target. Qualification verifies the invariants on `Authority.cfg` and requires all seven fault configurations to produce counterexamples: - -- `Authority.bad-claim.cfg` checks `ClaimPinned`. -- `Authority.candidate-target.cfg` checks `TargetAuthorityPinned`. -- `Authority.wrong-capture.cfg` checks `CandidateCapturePinned`. -- `Authority.swapped-receipt.cfg` checks `ReceiptBound`. -- `Authority.stale-reuse.cfg` checks `ReuseDecisionBound`. -- `Authority.false-reject.cfg` checks `ReuseRejectedBound`. -- `Authority.preflight-pass.cfg` checks `PreflightNotProof`. - -Runtime tests in `tests/core/` and `tests/formal/` separately exercise claim rejection, protected target selection, source capture, receipt validation, and reuse after drift. - -## Shadow authority - -`ShadowAuthority.tla` models three receipt slots that share one identifier: `registered_check`, `formal_goal`, and `change_certification`. Only `registered_check` and `formal_goal` are required gate slots. - -Qualification verifies `ShadowAuthority.cfg` and requires four fault configurations to produce counterexamples: - -- `ShadowAuthority.verus.cfg` checks `ShadowReceiptPolicy`. -- `ShadowAuthority.established.cfg` checks `ShadowReceiptPolicy`. -- `ShadowAuthority.gate-requires-shadow.cfg` checks `GateMatchesRequiredSubjects`. -- `ShadowAuthority.gate-accepts-shadow.cfg` checks `GateMatchesRequiredSubjects`. - -## Finite difference assessment - -`Differences.tla` models the collection and assessment of paired observations. The bounded configuration explores ordered sequences of zero, one, or two records from a finite pool over two inputs. Six clean configurations cover the bounded default (`Differences.cfg`), invalid shrink handling (`Differences.invalid-shrink.cfg`), violation visibility with missing evidence (`Differences.violation-missing.cfg`), overlapping guards (`Differences.guard-overlap.cfg`), standing-intent repairs (`Differences.repair.cfg`), and an empty admissible domain (`Differences.empty.cfg`). - -The model verifies five core rules: - -- Selected inputs require evidence. -- Overlapping guards intersect rather than union. -- Violations remain visible when other evidence is missing or unknown. -- Repairs that satisfy standing intent are accepted. -- An empty admissible domain remains unknown. - -Two reachability controls (`Differences.reach-conformance.cfg` and `Differences.reach-empty-done.cfg`) establish that completion and conformance states are reachable. Eight mutant configurations (`Differences.mutant-*.cfg`) must produce counterexamples. - -Two real-code checks complement the TLA+ model: - -- `tests/change/test_differences.py` exercises the public parsers and Python assessor with concrete observations, including duplicate records, intersecting guards, repairs, and incomplete evidence. -- `formal/checks/check_finite_decisions.py` (invoked by `tests/change/test_finite_decisions.py`) exhaustively checks 354,346 finite decision tuples directly against `src/vkit/change/certification.py`. - -## TLC and Python decision comparison - -`DifferenceDecisionBridge.tla` extends `Differences.tla` and prints terminal decisions from the six clean configurations without changing their transition relation. `formal/checks/check_difference_decisions.py` runs TLC on all six configurations and compares every emitted decision with the public Python assessor in `src/vkit/change/certification.py`. Record order and multiplicity are preserved. Negative controls alter a modeled violation or terminal status to verify that the comparator detects disagreement. - -## Run qualification - -Running the TLC suites requires Java (resolved from `JAVA_HOME` or `PATH`), the repository's Python environment, and the repository-pinned `tla2tools.jar`. - -From the repository root in a POSIX shell: - -```sh -export VKIT_TLA2TOOLS_JAR=/path/to/tla2tools.jar -export PYTHONPATH=src -uv run python formal/checks/check_authority.py --suite authority -uv run python formal/checks/check_authority.py --suite shadow -uv run python formal/checks/check_authority.py --suite differences -uv run python formal/checks/check_difference_decisions.py --output tmp/difference-decisions -``` - -From the repository root in PowerShell: - -```powershell -$env:VKIT_TLA2TOOLS_JAR = 'PATH_TO_JAR_MATCHING_REPOSITORY_PIN' -$env:PYTHONPATH = (Resolve-Path '.\src').Path -.\.venv\Scripts\python.exe formal\checks\check_authority.py --suite authority -.\.venv\Scripts\python.exe formal\checks\check_authority.py --suite shadow -.\.venv\Scripts\python.exe formal\checks\check_authority.py --suite differences -.\.venv\Scripts\python.exe formal\checks\check_difference_decisions.py --output tmp\difference-decisions -``` - -Run the exhaustive Python decision checker without Java or TLC: - -```sh -uv run pytest tests/change/test_finite_decisions.py -``` - -The authority, shadow, and difference suites create isolated VKit projects and run TLC through VKit's registered-check interface. Reports, model copies, checker output, and comparison evidence are retained under `tmp/`. - -## Scope - -Results cover only the configured finite models and the runtime cases compared with them. Hashes and Git identities are opaque atoms. The authority and shadow models do not model host authorization, human acceptance, scheduler concurrency, verifier correctness, or cryptographic collision resistance. The difference models do not cover arbitrary program inputs or longer observation sequences. Agreement with the Python assessor is bounded evidence, not a general proof that the implementation refines the model. Fault and mutant configurations are qualification controls, not reports of production defects. diff --git a/formal/models/certification/ShadowAuthority.cfg b/formal/models/certification/ShadowAuthority.cfg deleted file mode 100644 index aaa6182..0000000 --- a/formal/models/certification/ShadowAuthority.cfg +++ /dev/null @@ -1,7 +0,0 @@ -SPECIFICATION Spec -CONSTANTS - Fault = "none" -INVARIANT TypeOK -INVARIANT ShadowReceiptPolicy -INVARIANT ReceiptNamespaceSeparated -INVARIANT GateMatchesRequiredSubjects diff --git a/formal/models/certification/ShadowAuthority.established.cfg b/formal/models/certification/ShadowAuthority.established.cfg deleted file mode 100644 index 5d33367..0000000 --- a/formal/models/certification/ShadowAuthority.established.cfg +++ /dev/null @@ -1,7 +0,0 @@ -SPECIFICATION Spec -CONSTANTS - Fault = "shadow_established" -INVARIANT TypeOK -INVARIANT ShadowReceiptPolicy -INVARIANT ReceiptNamespaceSeparated -INVARIANT GateMatchesRequiredSubjects diff --git a/formal/models/certification/ShadowAuthority.gate-accepts-shadow.cfg b/formal/models/certification/ShadowAuthority.gate-accepts-shadow.cfg deleted file mode 100644 index 471012b..0000000 --- a/formal/models/certification/ShadowAuthority.gate-accepts-shadow.cfg +++ /dev/null @@ -1,7 +0,0 @@ -SPECIFICATION Spec -CONSTANTS - Fault = "gate_accepts_shadow" -INVARIANT TypeOK -INVARIANT ShadowReceiptPolicy -INVARIANT ReceiptNamespaceSeparated -INVARIANT GateMatchesRequiredSubjects diff --git a/formal/models/certification/ShadowAuthority.gate-requires-shadow.cfg b/formal/models/certification/ShadowAuthority.gate-requires-shadow.cfg deleted file mode 100644 index 5cf5a85..0000000 --- a/formal/models/certification/ShadowAuthority.gate-requires-shadow.cfg +++ /dev/null @@ -1,7 +0,0 @@ -SPECIFICATION Spec -CONSTANTS - Fault = "gate_requires_shadow" -INVARIANT TypeOK -INVARIANT ShadowReceiptPolicy -INVARIANT ReceiptNamespaceSeparated -INVARIANT GateMatchesRequiredSubjects diff --git a/formal/models/certification/ShadowAuthority.tla b/formal/models/certification/ShadowAuthority.tla deleted file mode 100644 index 5a47c47..0000000 --- a/formal/models/certification/ShadowAuthority.tla +++ /dev/null @@ -1,114 +0,0 @@ ----- MODULE ShadowAuthority ---- -EXTENDS FiniteSets - -CONSTANT Fault - -Kinds == {"registered_check", "formal_goal", "change_certification"} -Ids == {"shared-id"} -Results == {"none", "PASS", "FAIL", "BLOCKED"} -Assurances == {"none", "empirical", "finite_model", "trusted_engine"} -Claims == {"none", "established", "refuted", "unknown"} -Faults == {"none", "verus_check_none", "shadow_established", "gate_requires_shadow", "gate_accepts_shadow"} - -RegisteredSlot == "registered_check:shared-id" -FormalSlot == "formal_goal:shared-id" -ShadowSlot == "change_certification:shared-id" -Slots == {RegisteredSlot, FormalSlot, ShadowSlot} -RequiredSlots == {RegisteredSlot, FormalSlot} -SlotKind(slot) == - IF slot = RegisteredSlot THEN "registered_check" - ELSE IF slot = FormalSlot THEN "formal_goal" ELSE "change_certification" -SlotId(slot) == "shared-id" - -EmptyReceipt == [kind |-> "none", id |-> "none", result |-> "none", - assurance |-> "none", claim_outcome |-> "none", - source_proof |-> FALSE, approval_authority |-> FALSE] - -VARIABLES receipts, gate_ready -vars == <> - -Init == - /\ receipts = [s \in Slots |-> EmptyReceipt] - /\ gate_ready = FALSE - -ClaimFor(result) == IF result = "PASS" THEN "established" - ELSE IF result = "FAIL" THEN "refuted" ELSE "unknown" - -RequiredReceipt(slot, result) == - [kind |-> SlotKind(slot), id |-> SlotId(slot), result |-> result, - assurance |-> IF SlotKind(slot) = "registered_check" THEN "empirical" - ELSE "trusted_engine", - claim_outcome |-> ClaimFor(result), - source_proof |-> FALSE, approval_authority |-> FALSE] - -ShadowReceipt(result) == - [kind |-> "change_certification", id |-> "shared-id", result |-> result, - assurance |-> IF Fault = "verus_check_none" THEN "trusted_engine" ELSE "empirical", - claim_outcome |-> IF Fault = "shadow_established" THEN ClaimFor(result) ELSE "unknown", - source_proof |-> FALSE, approval_authority |-> FALSE] - -RequiredPassIn(records, slot) == - /\ records[slot].kind = SlotKind(slot) - /\ records[slot].id = SlotId(slot) - /\ records[slot].result = "PASS" - /\ records[slot].assurance = IF SlotKind(slot) = "registered_check" THEN "empirical" ELSE "trusted_engine" - /\ records[slot].claim_outcome = "established" - -RequiredGateIn(records) == \A slot \in RequiredSlots : RequiredPassIn(records, slot) - -GateDecision(records) == - IF Fault = "gate_requires_shadow" /\ records[ShadowSlot] # EmptyReceipt - THEN RequiredGateIn(records) /\ records[ShadowSlot].result = "PASS" - ELSE IF Fault = "gate_accepts_shadow" /\ records[ShadowSlot] # EmptyReceipt - THEN RequiredGateIn(records) \/ records[ShadowSlot].result = "PASS" - ELSE RequiredGateIn(records) - -PublishRequired(slot, result) == - /\ slot \in RequiredSlots - /\ result \in {"PASS", "FAIL", "BLOCKED"} - /\ receipts[slot] = EmptyReceipt - /\ receipts' = [receipts EXCEPT ![slot] = RequiredReceipt(slot, result)] - /\ gate_ready' = GateDecision(receipts') - -PublishShadow(result) == - /\ result \in {"PASS", "FAIL", "BLOCKED"} - /\ receipts[ShadowSlot] = EmptyReceipt - /\ receipts' = [receipts EXCEPT ![ShadowSlot] = ShadowReceipt(result)] - /\ gate_ready' = GateDecision(receipts') - -RequiredGate == RequiredGateIn(receipts) - -Done == UNCHANGED vars -Next == - \/ \E slot \in RequiredSlots : \E result \in {"PASS", "FAIL", "BLOCKED"} : PublishRequired(slot, result) - \/ \E result \in {"PASS", "FAIL", "BLOCKED"} : PublishShadow(result) - \/ Done - -Spec == Init /\ [][Next]_vars - -ReceiptType == [kind : Kinds \cup {"none"}, id : Ids \cup {"none"}, - result : Results, assurance : Assurances, claim_outcome : Claims, - source_proof : BOOLEAN, approval_authority : BOOLEAN] - -TypeOK == - /\ Fault \in Faults - /\ receipts \in [Slots -> ReceiptType] - /\ gate_ready \in BOOLEAN - -ShadowReceiptPolicy == - receipts[ShadowSlot] # EmptyReceipt => - /\ receipts[ShadowSlot].kind = "change_certification" - /\ receipts[ShadowSlot].id = "shared-id" - /\ receipts[ShadowSlot].assurance = "empirical" - /\ receipts[ShadowSlot].claim_outcome = "unknown" - /\ receipts[ShadowSlot].source_proof = FALSE - /\ receipts[ShadowSlot].approval_authority = FALSE - -ReceiptNamespaceSeparated == - \A slot \in Slots : receipts[slot] # EmptyReceipt => - /\ receipts[slot].kind = SlotKind(slot) - /\ receipts[slot].id = SlotId(slot) - -GateMatchesRequiredSubjects == gate_ready = RequiredGate - -==== diff --git a/formal/models/certification/ShadowAuthority.verus.cfg b/formal/models/certification/ShadowAuthority.verus.cfg deleted file mode 100644 index 82b29e5..0000000 --- a/formal/models/certification/ShadowAuthority.verus.cfg +++ /dev/null @@ -1,7 +0,0 @@ -SPECIFICATION Spec -CONSTANTS - Fault = "verus_check_none" -INVARIANT TypeOK -INVARIANT ShadowReceiptPolicy -INVARIANT ReceiptNamespaceSeparated -INVARIANT GateMatchesRequiredSubjects diff --git a/formal/models/delegated-claim/allow_self_justifying_basis.cfg b/formal/models/delegated-claim/allow_self_justifying_basis.cfg deleted file mode 100644 index 069b021..0000000 --- a/formal/models/delegated-claim/allow_self_justifying_basis.cfg +++ /dev/null @@ -1,16 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Mutant = "omit_prior_claim_identity" - Fault = "self_justifying_basis" -INVARIANT TypeOK -INVARIANT AcceptedHasTrustedTargetBasis -INVARIANT AcceptedHasEntailment -INVARIANT AcceptedIsStrictStrengthening -INVARIANT AcceptedHasCompleteSatisfaction -INVARIANT AcceptedHasRejectedMeaningfulNearMiss -INVARIANT AcceptedHasFreshUncancelledReceipt -INVARIANT AcceptedUsesRestrictedModel -INVARIANT SamplesCannotAuthorize -INVARIANT ClaimAcceptanceDoesNotApproveCode -INVARIANT CurrentClaimCannotBeItsOwnBasis diff --git a/formal/models/delegated-claim/claim_approves_code.cfg b/formal/models/delegated-claim/claim_approves_code.cfg deleted file mode 100644 index bece269..0000000 --- a/formal/models/delegated-claim/claim_approves_code.cfg +++ /dev/null @@ -1,16 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Mutant = "claim_approves_code" - Fault = "none" -INVARIANT TypeOK -INVARIANT AcceptedHasTrustedTargetBasis -INVARIANT AcceptedHasEntailment -INVARIANT AcceptedIsStrictStrengthening -INVARIANT AcceptedHasCompleteSatisfaction -INVARIANT AcceptedHasRejectedMeaningfulNearMiss -INVARIANT AcceptedHasFreshUncancelledReceipt -INVARIANT AcceptedUsesRestrictedModel -INVARIANT SamplesCannotAuthorize -INVARIANT ClaimAcceptanceDoesNotApproveCode -INVARIANT CurrentClaimCannotBeItsOwnBasis diff --git a/formal/models/delegated-claim/good.cfg b/formal/models/delegated-claim/good.cfg deleted file mode 100644 index 2c9c86b..0000000 --- a/formal/models/delegated-claim/good.cfg +++ /dev/null @@ -1,16 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Mutant = "none" - Fault = "none" -INVARIANT TypeOK -INVARIANT AcceptedHasTrustedTargetBasis -INVARIANT AcceptedHasEntailment -INVARIANT AcceptedIsStrictStrengthening -INVARIANT AcceptedHasCompleteSatisfaction -INVARIANT AcceptedHasRejectedMeaningfulNearMiss -INVARIANT AcceptedHasFreshUncancelledReceipt -INVARIANT AcceptedUsesRestrictedModel -INVARIANT SamplesCannotAuthorize -INVARIANT ClaimAcceptanceDoesNotApproveCode -INVARIANT CurrentClaimCannotBeItsOwnBasis diff --git a/formal/models/delegated-claim/omit_complete_satisfaction.cfg b/formal/models/delegated-claim/omit_complete_satisfaction.cfg deleted file mode 100644 index 812a68b..0000000 --- a/formal/models/delegated-claim/omit_complete_satisfaction.cfg +++ /dev/null @@ -1,16 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Mutant = "omit_complete_satisfaction" - Fault = "sample_only_satisfaction" -INVARIANT TypeOK -INVARIANT AcceptedHasTrustedTargetBasis -INVARIANT AcceptedHasEntailment -INVARIANT AcceptedIsStrictStrengthening -INVARIANT AcceptedHasCompleteSatisfaction -INVARIANT AcceptedHasRejectedMeaningfulNearMiss -INVARIANT AcceptedHasFreshUncancelledReceipt -INVARIANT AcceptedUsesRestrictedModel -INVARIANT SamplesCannotAuthorize -INVARIANT ClaimAcceptanceDoesNotApproveCode -INVARIANT CurrentClaimCannotBeItsOwnBasis diff --git a/formal/models/delegated-claim/omit_entailment.cfg b/formal/models/delegated-claim/omit_entailment.cfg deleted file mode 100644 index aff9dd0..0000000 --- a/formal/models/delegated-claim/omit_entailment.cfg +++ /dev/null @@ -1,16 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Mutant = "omit_entailment" - Fault = "missing_entailment" -INVARIANT TypeOK -INVARIANT AcceptedHasTrustedTargetBasis -INVARIANT AcceptedHasEntailment -INVARIANT AcceptedIsStrictStrengthening -INVARIANT AcceptedHasCompleteSatisfaction -INVARIANT AcceptedHasRejectedMeaningfulNearMiss -INVARIANT AcceptedHasFreshUncancelledReceipt -INVARIANT AcceptedUsesRestrictedModel -INVARIANT SamplesCannotAuthorize -INVARIANT ClaimAcceptanceDoesNotApproveCode -INVARIANT CurrentClaimCannotBeItsOwnBasis diff --git a/formal/models/delegated-claim/omit_fresh_receipt_cancel.cfg b/formal/models/delegated-claim/omit_fresh_receipt_cancel.cfg deleted file mode 100644 index 71bf2b7..0000000 --- a/formal/models/delegated-claim/omit_fresh_receipt_cancel.cfg +++ /dev/null @@ -1,16 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Mutant = "omit_fresh_receipt_cancel" - Fault = "none" -INVARIANT TypeOK -INVARIANT AcceptedHasTrustedTargetBasis -INVARIANT AcceptedHasEntailment -INVARIANT AcceptedIsStrictStrengthening -INVARIANT AcceptedHasCompleteSatisfaction -INVARIANT AcceptedHasRejectedMeaningfulNearMiss -INVARIANT AcceptedHasFreshUncancelledReceipt -INVARIANT AcceptedUsesRestrictedModel -INVARIANT SamplesCannotAuthorize -INVARIANT ClaimAcceptanceDoesNotApproveCode -INVARIANT CurrentClaimCannotBeItsOwnBasis diff --git a/formal/models/delegated-claim/omit_meaningful_near_miss.cfg b/formal/models/delegated-claim/omit_meaningful_near_miss.cfg deleted file mode 100644 index 75d494d..0000000 --- a/formal/models/delegated-claim/omit_meaningful_near_miss.cfg +++ /dev/null @@ -1,16 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Mutant = "omit_meaningful_near_miss" - Fault = "missing_near_miss_rejection" -INVARIANT TypeOK -INVARIANT AcceptedHasTrustedTargetBasis -INVARIANT AcceptedHasEntailment -INVARIANT AcceptedIsStrictStrengthening -INVARIANT AcceptedHasCompleteSatisfaction -INVARIANT AcceptedHasRejectedMeaningfulNearMiss -INVARIANT AcceptedHasFreshUncancelledReceipt -INVARIANT AcceptedUsesRestrictedModel -INVARIANT SamplesCannotAuthorize -INVARIANT ClaimAcceptanceDoesNotApproveCode -INVARIANT CurrentClaimCannotBeItsOwnBasis diff --git a/formal/models/delegated-claim/omit_model_scope.cfg b/formal/models/delegated-claim/omit_model_scope.cfg deleted file mode 100644 index d26e1be..0000000 --- a/formal/models/delegated-claim/omit_model_scope.cfg +++ /dev/null @@ -1,16 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Mutant = "omit_model_scope" - Fault = "wrong_model_scope" -INVARIANT TypeOK -INVARIANT AcceptedHasTrustedTargetBasis -INVARIANT AcceptedHasEntailment -INVARIANT AcceptedIsStrictStrengthening -INVARIANT AcceptedHasCompleteSatisfaction -INVARIANT AcceptedHasRejectedMeaningfulNearMiss -INVARIANT AcceptedHasFreshUncancelledReceipt -INVARIANT AcceptedUsesRestrictedModel -INVARIANT SamplesCannotAuthorize -INVARIANT ClaimAcceptanceDoesNotApproveCode -INVARIANT CurrentClaimCannotBeItsOwnBasis diff --git a/formal/models/delegated-claim/omit_strict_strengthening.cfg b/formal/models/delegated-claim/omit_strict_strengthening.cfg deleted file mode 100644 index e6c81e8..0000000 --- a/formal/models/delegated-claim/omit_strict_strengthening.cfg +++ /dev/null @@ -1,16 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Mutant = "omit_strict_strengthening" - Fault = "missing_strict_strengthening" -INVARIANT TypeOK -INVARIANT AcceptedHasTrustedTargetBasis -INVARIANT AcceptedHasEntailment -INVARIANT AcceptedIsStrictStrengthening -INVARIANT AcceptedHasCompleteSatisfaction -INVARIANT AcceptedHasRejectedMeaningfulNearMiss -INVARIANT AcceptedHasFreshUncancelledReceipt -INVARIANT AcceptedUsesRestrictedModel -INVARIANT SamplesCannotAuthorize -INVARIANT ClaimAcceptanceDoesNotApproveCode -INVARIANT CurrentClaimCannotBeItsOwnBasis diff --git a/formal/models/delegated-claim/omit_target_identity.cfg b/formal/models/delegated-claim/omit_target_identity.cfg deleted file mode 100644 index c42c759..0000000 --- a/formal/models/delegated-claim/omit_target_identity.cfg +++ /dev/null @@ -1,16 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Mutant = "omit_target_basis_identity" - Fault = "wrong_target_identity" -INVARIANT TypeOK -INVARIANT AcceptedHasTrustedTargetBasis -INVARIANT AcceptedHasEntailment -INVARIANT AcceptedIsStrictStrengthening -INVARIANT AcceptedHasCompleteSatisfaction -INVARIANT AcceptedHasRejectedMeaningfulNearMiss -INVARIANT AcceptedHasFreshUncancelledReceipt -INVARIANT AcceptedUsesRestrictedModel -INVARIANT SamplesCannotAuthorize -INVARIANT ClaimAcceptanceDoesNotApproveCode -INVARIANT CurrentClaimCannotBeItsOwnBasis diff --git a/formal/models/delegated-claim/omit_untrusted_target.cfg b/formal/models/delegated-claim/omit_untrusted_target.cfg deleted file mode 100644 index 02d3907..0000000 --- a/formal/models/delegated-claim/omit_untrusted_target.cfg +++ /dev/null @@ -1,16 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - Mutant = "omit_target_basis_identity" - Fault = "untrusted_target" -INVARIANT TypeOK -INVARIANT AcceptedHasTrustedTargetBasis -INVARIANT AcceptedHasEntailment -INVARIANT AcceptedIsStrictStrengthening -INVARIANT AcceptedHasCompleteSatisfaction -INVARIANT AcceptedHasRejectedMeaningfulNearMiss -INVARIANT AcceptedHasFreshUncancelledReceipt -INVARIANT AcceptedUsesRestrictedModel -INVARIANT SamplesCannotAuthorize -INVARIANT ClaimAcceptanceDoesNotApproveCode -INVARIANT CurrentClaimCannotBeItsOwnBasis diff --git a/formal/models/lifecycle/Attempts.cfg b/formal/models/lifecycle/Attempts.cfg deleted file mode 100644 index 3866b3d..0000000 --- a/formal/models/lifecycle/Attempts.cfg +++ /dev/null @@ -1,14 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - ExpectedJob = "job-v1" - ExpectedSource = "source-v1" - ForeignJob = "job-foreign" - ForeignSource = "source-foreign" - InjectFalsePass = FALSE -INVARIANT TypeOK -INVARIANT NoFalsePass -INVARIANT TerminalHasResult -INVARIANT InterruptedHasNoResult -INVARIANT IdentityPinned -INVARIANT PublishedAttemptComplete diff --git a/formal/models/lifecycle/Attempts.tla b/formal/models/lifecycle/Attempts.tla deleted file mode 100644 index a8cbaed..0000000 --- a/formal/models/lifecycle/Attempts.tla +++ /dev/null @@ -1,185 +0,0 @@ ----- MODULE Attempts ---- -EXTENDS Naturals, FiniteSets - -CONSTANTS ExpectedJob, ExpectedSource, ForeignJob, ForeignSource, InjectFalsePass - -AttemptIds == {1, 2, 3} -States == {"absent", "queued", "running", "done", "interrupted"} -Outcomes == {"none", "PASS", "FAIL", "BLOCKED"} -Identities == {"none", ExpectedJob, ForeignJob} -Sources == {"none", ExpectedSource, ForeignSource} -MaxAttempts == 3 - -VARIABLES state, attempt, cancelRequested, workerAlive, orphaned, outcome, - job, source, resultJob, resultSource, published - -vars == <> - -Init == - /\ state = [i \in AttemptIds |-> "absent"] - /\ attempt = [i \in AttemptIds |-> 0] - /\ cancelRequested = [i \in AttemptIds |-> FALSE] - /\ workerAlive = [i \in AttemptIds |-> FALSE] - /\ orphaned = [i \in AttemptIds |-> FALSE] - /\ outcome = [i \in AttemptIds |-> "none"] - /\ job = [i \in AttemptIds |-> "none"] - /\ source = [i \in AttemptIds |-> "none"] - /\ resultJob = [i \in AttemptIds |-> "none"] - /\ resultSource = [i \in AttemptIds |-> "none"] - /\ published = 0 - -Submit(i) == - /\ i \in AttemptIds - /\ state[i] = "absent" - /\ state' = [state EXCEPT ![i] = "queued"] - /\ attempt' = [attempt EXCEPT ![i] = 1] - /\ job' = [job EXCEPT ![i] = ExpectedJob] - /\ source' = [source EXCEPT ![i] = ExpectedSource] - /\ UNCHANGED <> - -Start(i) == - /\ i \in AttemptIds - /\ state[i] = "queued" - /\ state' = [state EXCEPT ![i] = "running"] - /\ workerAlive' = [workerAlive EXCEPT ![i] = TRUE] - /\ UNCHANGED <> - -RequestCancel(i) == - /\ i \in AttemptIds - /\ state[i] \in {"queued", "running"} - /\ cancelRequested[i] = FALSE - /\ cancelRequested' = [cancelRequested EXCEPT ![i] = TRUE] - /\ UNCHANGED <> - -Complete(i, result) == - /\ i \in AttemptIds - /\ state[i] = "running" - /\ workerAlive[i] - /\ result \in {"PASS", "FAIL", "BLOCKED"} - /\ state' = [state EXCEPT ![i] = "done"] - /\ outcome' = [outcome EXCEPT ![i] = result] - /\ resultJob' = [resultJob EXCEPT ![i] = job[i]] - /\ resultSource' = [resultSource EXCEPT ![i] = source[i]] - /\ workerAlive' = [workerAlive EXCEPT ![i] = FALSE] - /\ UNCHANGED <> - -WrongIdentityPass(i) == - /\ InjectFalsePass - /\ i \in AttemptIds - /\ state[i] = "running" - /\ workerAlive[i] - /\ state' = [state EXCEPT ![i] = "done"] - /\ outcome' = [outcome EXCEPT ![i] = "PASS"] - /\ resultJob' = [resultJob EXCEPT ![i] = ForeignJob] - /\ resultSource' = [resultSource EXCEPT ![i] = ForeignSource] - /\ workerAlive' = [workerAlive EXCEPT ![i] = FALSE] - /\ UNCHANGED <> - -WorkerLost(i) == - /\ i \in AttemptIds - /\ state[i] = "running" - /\ workerAlive[i] - /\ workerAlive' = [workerAlive EXCEPT ![i] = FALSE] - /\ orphaned' = [orphaned EXCEPT ![i] = TRUE] - /\ UNCHANGED <> - -Recover(i) == - /\ i \in AttemptIds - /\ state[i] = "running" - /\ orphaned[i] - /\ ~workerAlive[i] - /\ state' = [state EXCEPT ![i] = "interrupted"] - /\ orphaned' = [orphaned EXCEPT ![i] = FALSE] - /\ UNCHANGED <> - -Retry(from, to) == - /\ from \in AttemptIds - /\ to \in AttemptIds - /\ from # to - /\ state[from] \in {"done", "interrupted"} - /\ ~workerAlive[from] - /\ state[to] = "absent" - /\ attempt[from] < MaxAttempts - /\ state' = [state EXCEPT ![to] = "queued"] - /\ attempt' = [attempt EXCEPT ![to] = attempt[from] + 1] - /\ cancelRequested' = [cancelRequested EXCEPT ![to] = FALSE] - /\ workerAlive' = [workerAlive EXCEPT ![to] = FALSE] - /\ orphaned' = [orphaned EXCEPT ![to] = FALSE] - /\ outcome' = [outcome EXCEPT ![to] = "none"] - /\ job' = [job EXCEPT ![to] = job[from]] - /\ source' = [source EXCEPT ![to] = source[from]] - /\ resultJob' = [resultJob EXCEPT ![to] = "none"] - /\ resultSource' = [resultSource EXCEPT ![to] = "none"] - /\ UNCHANGED <> - -Publish(i) == - /\ i \in AttemptIds - /\ state[i] = "done" - /\ outcome[i] \in {"PASS", "FAIL", "BLOCKED"} - /\ published' = i - /\ UNCHANGED <> - -Actions == - \/ \E i \in AttemptIds : Submit(i) - \/ \E i \in AttemptIds : Start(i) - \/ \E i \in AttemptIds : RequestCancel(i) - \/ \E i \in AttemptIds : Complete(i, "PASS") - \/ \E i \in AttemptIds : Complete(i, "FAIL") - \/ \E i \in AttemptIds : Complete(i, "BLOCKED") - \/ \E i \in AttemptIds : WrongIdentityPass(i) - \/ \E i \in AttemptIds : WorkerLost(i) - \/ \E i \in AttemptIds : Recover(i) - \/ \E i, j \in AttemptIds : Retry(i, j) - \/ \E i \in AttemptIds : Publish(i) - -Next == Actions -Spec == Init /\ [][Next]_vars - -TypeOK == - /\ state \in [AttemptIds -> States] - /\ attempt \in [AttemptIds -> 0..MaxAttempts] - /\ cancelRequested \in [AttemptIds -> BOOLEAN] - /\ workerAlive \in [AttemptIds -> BOOLEAN] - /\ orphaned \in [AttemptIds -> BOOLEAN] - /\ outcome \in [AttemptIds -> Outcomes] - /\ job \in [AttemptIds -> Identities] - /\ source \in [AttemptIds -> Sources] - /\ resultJob \in [AttemptIds -> Identities] - /\ resultSource \in [AttemptIds -> Sources] - /\ published \in 0..3 - -NoFalsePass == - \A i \in AttemptIds : outcome[i] = "PASS" => - /\ state[i] = "done" - /\ resultJob[i] = job[i] - /\ resultSource[i] = source[i] - /\ job[i] = ExpectedJob - /\ source[i] = ExpectedSource - -TerminalHasResult == - \A i \in AttemptIds : state[i] = "done" => - outcome[i] \in {"PASS", "FAIL", "BLOCKED"} - -InterruptedHasNoResult == - \A i \in AttemptIds : state[i] = "interrupted" => outcome[i] = "none" - -IdentityPinned == - \A i \in AttemptIds : state[i] # "absent" => - /\ job[i] = ExpectedJob - /\ source[i] = ExpectedSource - -PublishedAttemptComplete == - published > 0 => - /\ state[published] = "done" - /\ outcome[published] \in {"PASS", "FAIL", "BLOCKED"} - /\ job[published] = ExpectedJob - /\ source[published] = ExpectedSource - -==== diff --git a/plugin/.mcp.json b/plugin/.mcp.json index 35050d4..0e71427 100644 --- a/plugin/.mcp.json +++ b/plugin/.mcp.json @@ -1,8 +1,8 @@ { "mcpServers": { "vkit": { - "command": "vkit", - "args": ["mcp", "serve", "--project", "${user_config.project_root}"] + "command": "${user_config.python}", + "args": ["-m", "vkit.cli", "mcp", "serve", "--project", "${user_config.project_root}"] } } } diff --git a/plugin/scripts/vkit_hook.py b/plugin/scripts/vkit_hook.py index dce89ae..f344e2f 100644 --- a/plugin/scripts/vkit_hook.py +++ b/plugin/scripts/vkit_hook.py @@ -5,14 +5,16 @@ from __future__ import annotations import argparse +import hashlib import json import subprocess import sys import time +from pathlib import Path from typing import Any FIXABLE = {"stale", "missing", "fresh_fail"} -BLOCKING = FIXABLE | {"not_approved", "obligation_removed"} +BLOCKING = FIXABLE | {"not_approved", "obligation_removed", "fresh_blocked"} def _required(status: dict[str, Any]) -> list[dict[str, Any]]: @@ -36,9 +38,11 @@ def _summary(status: dict[str, Any]) -> str: def _git(project: str, *args: str) -> bytes: + from vkit.runtime.nowindow import hidden_window from vkit.runtime.paths import open_project - done = subprocess.run(["git", "-C", str(open_project(project).root), *args], capture_output=True, timeout=30) + done = subprocess.run(["git", "-C", str(open_project(project).root), *args], + capture_output=True, timeout=30, **hidden_window()) if done.returncode != 0: raise OSError(done.stderr.decode("utf-8", "replace").strip()) return done.stdout @@ -60,22 +64,31 @@ def _record_bypass(project: str) -> None: _telemetry(project, "stop_hook_bypass") -def _record_base(project: str) -> None: - try: - from vkit.runtime.paths import open_project +def _session_base_path(project: str, payload: dict[str, Any]) -> Path: + from vkit.runtime.paths import open_project + + opened = open_project(project) + raw_session = payload.get("session_id") + if isinstance(raw_session, str) and raw_session.strip(): + key = hashlib.sha256(raw_session.strip().encode("utf-8")).hexdigest()[:16] + else: + key = hashlib.sha256(str(opened.root.resolve()).encode("utf-8")).hexdigest()[:16] + return opened.git_common_dir / "vkit" / "sessions" / f"{key}.txt" + +def _record_base(project: str, payload: dict[str, Any]) -> None: + try: top = _git(project, "rev-parse", "--show-toplevel").decode("utf-8", "surrogateescape").strip() head = _git(project, "rev-parse", "HEAD").decode("utf-8", "surrogateescape").strip() - (open_project(project).git_common_dir / "vkit" / "session_base.txt").write_text( - f"{top}\n{head}\n", encoding="utf-8") + base_file = _session_base_path(project, payload) + base_file.parent.mkdir(parents=True, exist_ok=True) + base_file.write_text(f"{top}\n{head}\n", encoding="utf-8") except Exception: # noqa: BLE001 pass -def _changed_paths(project: str) -> list[str]: - from vkit.runtime.paths import open_project - - base_file = open_project(project).git_common_dir / "vkit" / "session_base.txt" +def _changed_paths(project: str, payload: dict[str, Any]) -> list[str]: + base_file = _session_base_path(project, payload) if not base_file.is_file(): _telemetry(project, "session_base_missing") return [] @@ -105,18 +118,23 @@ def handle(event: str, payload: dict[str, Any], project: str) -> dict[str, Any]: def _handle(event: str, payload: dict[str, Any], project: str) -> dict[str, Any]: from vkit.core import query + from vkit.core.trace import emit_trace if event == "SessionStart": - _record_base(project) + _record_base(project, payload) status = query.status(query.open_context(project)) + emit_trace("hook_session_start", session_id=str(payload.get("session_id") or "")) return {"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": _summary(status)}} - paths = _changed_paths(project) + paths = _changed_paths(project, payload) status = query.status(query.open_context(project), paths, session=bool(paths)) blocking = status["gate"]["verdict"] == "REJECTED" or any(c["state"] in BLOCKING for c in _required(status)) if status["gate"]["verdict"] == "READY" or payload.get("stop_hook_active") or not blocking: - if payload.get("stop_hook_active") and blocking and status["gate"]["verdict"] != "READY": + bypass = bool(payload.get("stop_hook_active") and blocking and status["gate"]["verdict"] != "READY") + if bypass: _record_bypass(project) + emit_trace("hook_stop", hook=event, decision="allow", verdict=status["gate"]["verdict"], bypass=bypass) return {} if status["gate"]["verdict"] == "READY" else {"systemMessage": _summary(status)} + emit_trace("hook_stop", hook=event, decision="block", verdict=status["gate"]["verdict"], bypass=False) return {"decision": "block", "reason": _summary(status)} diff --git a/pyproject.toml b/pyproject.toml index deec781..3bb8c1e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -38,7 +38,7 @@ packages = ["src/vkit"] [tool.pytest.ini_options] testpaths = ["tests"] -pythonpath = ["."] +pythonpath = ["src", "."] addopts = "-q -p no:cacheprovider" [tool.ruff] diff --git a/scripts/tools/build_kernel.py b/scripts/tools/build_kernel.py new file mode 100644 index 0000000..b0ca247 --- /dev/null +++ b/scripts/tools/build_kernel.py @@ -0,0 +1,64 @@ +"""Compile verified Dafny kernel modules into src/vkit/kernel/_dafny_gen/.""" +from __future__ import annotations + +import argparse +import os +import shutil +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +DAFNY_DIR = ROOT / "formal" / "dafny" +OUT_DIR = ROOT / "src" / "vkit" / "kernel" / "_dafny_gen" +DAFNY_MODULES = ( + "VKitGate.dfy", + "VKitBudgets.dfy", + "VKitAcceptance.dfy", + "VKitReceipt.dfy", + "VKitChange.dfy", + "VKitKernel.dfy", +) + + +def _find_dafny() -> str | None: + env_bin = os.environ.get("VKIT_DAFNY_BIN") + if env_bin and Path(env_bin).is_file(): + return env_bin + return shutil.which("dafny") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Build VKit's Dafny-compiled Python kernel.") + parser.add_argument("--verify", action="store_true", help="Run dafny verify before compiling.") + args = parser.parse_args(argv) + + dafny = _find_dafny() + if dafny is None: + print("FAIL: dafny binary not found on PATH or VKIT_DAFNY_BIN", file=sys.stderr) + return 2 + + if args.verify: + dfy_paths = [str(DAFNY_DIR / name) for name in DAFNY_MODULES] + verify = subprocess.run([dafny, "verify", *dfy_paths], cwd=ROOT) + if verify.returncode != 0: + return verify.returncode + + OUT_DIR.mkdir(parents=True, exist_ok=True) + out_prefix = OUT_DIR / "vkit_kernel" + build = subprocess.run( + [ + dafny, + "build", + "--target:py", + "--no-verify", + f"--output:{out_prefix}", + str(DAFNY_DIR / "VKitKernel.dfy"), + ], + cwd=ROOT, + ) + return build.returncode + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/tools/comment_lint.py b/scripts/tools/comment_lint.py index eb37a30..305cbd9 100644 --- a/scripts/tools/comment_lint.py +++ b/scripts/tools/comment_lint.py @@ -1,8 +1,8 @@ """Report every comment in vkit's Python source as a SARIF finding. A comment is where an agent justifies code instead of fixing it. vkit's own `no-comments` check runs this and -fails on any comment that is not in the baseline a human pinned. `noqa` and `type:` pragmas are tool directives, -not prose, and are not reported. +fails on any comment that is not in the baseline a human pinned. Tool directives (`noqa`, `type:`, `pragma:`, +`ruff:`, `fmt:`) and shebangs are not prose and are not reported. """ from __future__ import annotations @@ -12,14 +12,34 @@ import tokenize from pathlib import Path +_EXEMPT_PREFIXES = ("noqa", "type:", "pragma:", "ruff:", "fmt:") +_SKIPPED_DIRS = frozenset({"_dafny_gen"}) + def findings(root: Path) -> list[dict]: results = [] - for path in sorted(root.rglob("*.py")): + paths = [root] if root.is_file() else sorted( + path for path in root.rglob("*.py") + if not (_SKIPPED_DIRS & set(path.parts)) + ) + for path in paths: source = path.read_text(encoding="utf-8") - for token in tokenize.generate_tokens(io.StringIO(source).readline): + try: + tokens = list(tokenize.generate_tokens(io.StringIO(source).readline)) + except tokenize.TokenError as exc: + message, position = exc.args + line = position[0] if isinstance(position, tuple) and position else 1 + results.append({"ruleId": "no-comments", "message": {"text": f"tokenize error: {message}"}, + "locations": [{"physicalLocation": {"artifactLocation": {"uri": path.as_posix()}, + "region": {"startLine": line}}}]}) + continue + for token in tokens: + if token.type != tokenize.COMMENT: + continue + if token.start == (1, 0) and token.string.startswith("#!"): + continue text = token.string.lstrip("#").strip() - if token.type != tokenize.COMMENT or text.startswith(("noqa", "type:")): + if text.lower().startswith(_EXEMPT_PREFIXES): continue results.append({"ruleId": "no-comments", "message": {"text": text}, "locations": [{"physicalLocation": {"artifactLocation": {"uri": path.as_posix()}, @@ -27,10 +47,22 @@ def findings(root: Path) -> list[dict]: return results -def main() -> int: +def main(argv: list[str] | None = None) -> int: + args = sys.argv[1:] if argv is None else argv + if len(args) not in (1, 2): + print("usage: comment_lint.py [sarif-output]", file=sys.stderr) + return 2 + target = Path(args[0]) + if not target.exists(): + print(f"path not found: {target}", file=sys.stderr) + return 2 report = {"version": "2.1.0", "runs": [{"tool": {"driver": {"name": "vkit-comment-lint"}}, - "results": findings(Path(sys.argv[1]))}]} - Path(sys.argv[2]).write_text(json.dumps(report, indent=2), encoding="utf-8") + "results": findings(target)}]} + rendered = json.dumps(report, indent=2) + if len(args) == 2: + Path(args[1]).write_text(rendered, encoding="utf-8") + elif report["runs"][0]["results"]: + print(rendered) return 1 if report["runs"][0]["results"] else 0 diff --git a/src/vkit/change/analysis.py b/src/vkit/change/analysis.py index 02d9ea7..28fb26b 100644 --- a/src/vkit/change/analysis.py +++ b/src/vkit/change/analysis.py @@ -328,6 +328,7 @@ def _run_prepared_change_analysis( timeout_seconds=timeout_seconds, max_shrink_trials=max_shrink_trials, should_cancel=should_cancel, + shrink_domain=bound.intent.contract.admissible_inputs, ) output_root = Path(output_dir).absolute() paired_path = _retained_path(output_root, "paired-report.json") diff --git a/src/vkit/change/certification.py b/src/vkit/change/certification.py index cf7fdf2..81f67ad 100644 --- a/src/vkit/change/certification.py +++ b/src/vkit/change/certification.py @@ -6,6 +6,13 @@ from vkit.core.inputs import canonical_digest from vkit.core.schemas import validate +from vkit.kernel import ( + assess_difference_status, + check_delegation_kernel, + classify_difference, + compare_contracts_kernel, + intent_entails_claim_kernel, +) _SCHEMA = "change-certification.v1.json" _INTENT_REVISION_SCHEMA = "intent-revision.v1.json" @@ -434,17 +441,16 @@ def _finite_contract_from_validated_json(raw: dict[str, Any]) -> FiniteContract: return FiniteContract(domain, inputs, rows) -def _refines(old: FiniteContract, new: FiniteContract) -> RefinementCheck: - input_witness = next((token for token in sorted(old.admissible_inputs) - if token not in new.admissible_inputs), None) - post_witness = next( - ((token, output) - for token in sorted(old.admissible_inputs) - for output in sorted(new.outputs_for(token) - old.outputs_for(token))), - None, - ) - return RefinementCheck(input_witness is None, post_witness is None, - input_witness, post_witness) +def _outputs_map(contract: FiniteContract) -> dict[str, tuple[str, ...]]: + return {row.input: row.outputs for row in contract.rows} + + +def _to_refinement( + raw: tuple[bool, bool, str | None, tuple[str, str] | None] | None, +) -> RefinementCheck | None: + if raw is None: + return None + return RefinementCheck(raw[0], raw[1], raw[2], raw[3]) def compare_contracts(old: FiniteContract, new: FiniteContract) -> ContractComparison: @@ -452,45 +458,54 @@ def compare_contracts(old: FiniteContract, new: FiniteContract) -> ContractCompa Directional checks remain available for inspection. """ - if old.domain.digest != new.domain.digest: - return ContractComparison(ComparisonKind.UNKNOWN, None, None) - old_to_new = _refines(old, new) - new_to_old = _refines(new, old) - if not old.admissible_inputs or not new.admissible_inputs: - kind = ComparisonKind.VACUOUS - elif old_to_new.holds and new_to_old.holds: - kind = ComparisonKind.EQUIVALENT - elif old_to_new.holds: - kind = ComparisonKind.STRENGTHENS - elif new_to_old.holds: - kind = ComparisonKind.WEAKENS - else: - kind = ComparisonKind.INCOMPARABLE - return ContractComparison(kind, old_to_new, new_to_old) + kind, old_to_new, new_to_old = compare_contracts_kernel( + old.domain.digest, + old.admissible_inputs, + _outputs_map(old), + new.domain.digest, + new.admissible_inputs, + _outputs_map(new), + ) + return ContractComparison( + ComparisonKind(kind), + _to_refinement(old_to_new), + _to_refinement(new_to_old), + ) def intent_entails_claim(intent: FiniteContract, claim: FiniteContract) -> IntentEntailment: - if intent.domain.digest != claim.domain.digest: - return IntentEntailment(EntailmentKind.UNKNOWN, None, None, None, None) - input_witness = next((token for token in sorted(intent.admissible_inputs) - if token not in claim.admissible_inputs), None) - output_witness = next( - ((token, output) - for token in sorted(intent.admissible_inputs) - if token in claim.admissible_inputs - for output in sorted(intent.outputs_for(token) - claim.outputs_for(token))), - None, + kind, inputs_included, outputs_included, input_witness, output_witness = ( + intent_entails_claim_kernel( + intent.domain.digest, + intent.admissible_inputs, + _outputs_map(intent), + claim.domain.digest, + claim.admissible_inputs, + _outputs_map(claim), + ) ) - inputs_included = input_witness is None - outputs_included = output_witness is None - if not intent.admissible_inputs: - kind = EntailmentKind.VACUOUS - elif inputs_included and outputs_included: - kind = EntailmentKind.ENTAILED - else: - kind = EntailmentKind.NOT_ENTAILED - return IntentEntailment(kind, inputs_included, outputs_included, - input_witness, output_witness) + return IntentEntailment( + EntailmentKind(kind), + inputs_included, + outputs_included, + input_witness, + output_witness, + ) + + +_DELEGATION_MESSAGES = { + "different_intent": "delegation basis names a different accepted intent", + "different_domains": "delegation contracts use different finite domains", + "empty_legal_inputs": "delegation requires a nonempty legal input set", + "different_legal_inputs": "delegation contracts must preserve the same legal input set", + "not_strict_strengthening": "claim must strictly strengthen the baseline without changing legal inputs", + "missing_strictness_witness": "strict strengthening has no output witness", + "near_miss_input_illegal": "near-miss input is not legal", + "near_miss_output_outside_domain": "near-miss output is outside the observation domain", + "near_miss_output_not_in_baseline": "near-miss output is not allowed by the baseline", + "near_miss_output_in_intent": "near-miss output is allowed by the accepted intent", + "near_miss_output_in_claim": "near-miss output is allowed by the proposed claim", +} def check_delegation( @@ -500,63 +515,39 @@ def check_delegation( near_miss: NearMiss, ) -> DelegationDerivation: """Check that target-accepted assumptions authorize a strict claim refinement.""" - if basis.intent_sha256 != intent.digest: - raise ValueError("delegation basis names a different accepted intent") - - baseline = basis.baseline - assumptions = basis.assumptions - contracts = (intent.contract, baseline, assumptions, claim) - if any(contract.domain.digest != intent.contract.domain.digest - for contract in contracts[1:]): - raise ValueError("delegation contracts use different finite domains") - - legal_inputs = set(intent.contract.admissible_inputs) - if not legal_inputs: - raise ValueError("delegation requires a nonempty legal input set") - if any(set(contract.admissible_inputs) != legal_inputs - for contract in contracts[1:]): - raise ValueError("delegation contracts must preserve the same legal input set") - - derived_rows = [] - for token in sorted(legal_inputs): - outputs = intent.contract.outputs_for(token) & assumptions.outputs_for(token) - if not outputs: - raise ValueError( - f"intent and assumptions have an empty output intersection for {token!r}" - ) - derived_rows.append(OutputRow(token, tuple(sorted(outputs)))) - constrained_intent = FiniteContract( - intent.contract.domain, tuple(sorted(legal_inputs)), tuple(derived_rows) + ok, error_code, detail_input, detail_output = check_delegation_kernel( + intent_digest=intent.digest, + basis_intent_digest=basis.intent_sha256, + intent_domain_digest=intent.contract.domain.digest, + intent_inputs=intent.contract.admissible_inputs, + intent_outputs=_outputs_map(intent.contract), + baseline_domain_digest=basis.baseline.domain.digest, + baseline_inputs=basis.baseline.admissible_inputs, + baseline_outputs=_outputs_map(basis.baseline), + assumptions_domain_digest=basis.assumptions.domain.digest, + assumptions_inputs=basis.assumptions.admissible_inputs, + assumptions_outputs=_outputs_map(basis.assumptions), + claim_domain_digest=claim.domain.digest, + claim_inputs=claim.admissible_inputs, + claim_outputs=_outputs_map(claim), + domain_observations=intent.contract.domain.observations, + near_miss_input=near_miss.input, + near_miss_output=near_miss.output, ) - entailment = intent_entails_claim(constrained_intent, claim) - if entailment.kind is not EntailmentKind.ENTAILED: - if entailment.output_witness is not None: - token, output = entailment.output_witness + if not ok: + if error_code == "empty_intersection": raise ValueError( - f"accepted intent and assumptions do not entail claim: " - f"{output!r} remains allowed for {token!r}" + f"intent and assumptions have an empty output intersection for {detail_input!r}" ) - raise ValueError("accepted intent and assumptions do not entail claim") - - comparison = compare_contracts(baseline, claim) - if comparison.kind is not ComparisonKind.STRENGTHENS: - raise ValueError("claim must strictly strengthen the baseline without changing legal inputs") - witness = comparison.new_to_old.output_witness if comparison.new_to_old else None - if witness is None: - raise ValueError("strict strengthening has no output witness") - - if near_miss.input not in legal_inputs: - raise ValueError("near-miss input is not legal") - if near_miss.output not in intent.contract.domain.observations: - raise ValueError("near-miss output is outside the observation domain") - if near_miss.output not in baseline.outputs_for(near_miss.input): - raise ValueError("near-miss output is not allowed by the baseline") - if near_miss.output in intent.contract.outputs_for(near_miss.input): - raise ValueError("near-miss output is allowed by the accepted intent") - if near_miss.output in claim.outputs_for(near_miss.input): - raise ValueError("near-miss output is allowed by the proposed claim") - - return DelegationDerivation(basis, claim, near_miss, witness) + if error_code == "not_entailed": + if detail_output: + raise ValueError( + f"accepted intent and assumptions do not entail claim: " + f"{detail_output!r} remains allowed for {detail_input!r}" + ) + raise ValueError("accepted intent and assumptions do not entail claim") + raise ValueError(_DELEGATION_MESSAGES[error_code]) + return DelegationDerivation(basis, claim, near_miss, (detail_input, detail_output)) def assess_differences( @@ -646,12 +637,9 @@ def assess_differences( findings.append(finding) coverage_complete = bool(admissible) and not missing - if any(finding.kind == "violation" for finding in findings): - status: DifferenceStatus = "observed_violation" - elif coverage_complete and not any(finding.kind == "unknown" for finding in findings): - status = "observed_conformance" - else: - status = "unknown" + status: DifferenceStatus = assess_difference_status( + len(admissible), len(missing), [finding.kind for finding in findings] + ) # type: ignore[assignment] return DifferenceAssessment(status, coverage_complete, tuple(findings), tuple(missing)) @@ -663,35 +651,44 @@ def _classify_difference( guard_requirements: list[tuple[str, frozenset[str]]], guard_ids: tuple[str, ...], ) -> InputDifference: - if candidate_output not in standing_outputs: - return InputDifference( - token, "violation", guard_ids, base_output, candidate_output, - "candidate violates standing target intent", - ) - - if guard_requirements: - permitted = frozenset.intersection(*(outputs for _, outputs in guard_requirements)) - if candidate_output not in permitted: - return InputDifference( - token, "violation", guard_ids, base_output, candidate_output, - "candidate violates an overlapping guard requirement", - ) + permitted = ( + frozenset.intersection(*(outputs for _, outputs in guard_requirements)) + if guard_requirements + else frozenset() + ) + kind: DifferenceKind = classify_difference( + base_output, + candidate_output, + standing_outputs, + has_guards=bool(guard_requirements), + guard_intersection=permitted, + ) # type: ignore[assignment] + if kind == "guarded_requirement_met": return InputDifference( - token, "guarded_requirement_met", guard_ids, base_output, candidate_output, + token, kind, guard_ids, base_output, candidate_output, "candidate meets the intersected guard requirements", ) - - if base_output == candidate_output: + if kind == "preserved": return InputDifference( - token, "preserved", (), base_output, candidate_output, + token, kind, (), base_output, candidate_output, "base and candidate observations are equal", ) - if base_output not in standing_outputs: + if kind == "standing_intent_repair": return InputDifference( - token, "standing_intent_repair", (), base_output, candidate_output, + token, kind, (), base_output, candidate_output, "candidate repairs a base result that violates standing target intent", ) + if candidate_output not in standing_outputs: + return InputDifference( + token, kind, guard_ids, base_output, candidate_output, + "candidate violates standing target intent", + ) + if guard_requirements: + return InputDifference( + token, kind, guard_ids, base_output, candidate_output, + "candidate violates an overlapping guard requirement", + ) return InputDifference( - token, "violation", (), base_output, candidate_output, + token, kind, (), base_output, candidate_output, "unguarded difference is not a standing-intent repair", ) diff --git a/src/vkit/change/claim_acceptance.py b/src/vkit/change/claim_acceptance.py index 844a62b..2f444ad 100644 --- a/src/vkit/change/claim_acceptance.py +++ b/src/vkit/change/claim_acceptance.py @@ -7,7 +7,7 @@ from vkit.change.certification import ChangeCertificationRequest from vkit.change.methods import ChangeMethodPlan, KaniMethod -from vkit.core.evidence import _retained_path, is_link +from vkit.core.evidence import _retained_path, is_link, retained_files from vkit.core.inputs import CapturedSource, canonical_digest from vkit.change.intent import BoundChangeRequest, _bind_captured_policy from vkit.rust.kani_result import classify_kani_result @@ -84,6 +84,14 @@ def _check_execution( for side, capture in (("base", program.base), ("candidate", program.candidate)): if _read(root, f"captures/{side}.json") != capture.to_json(): raise ValueError("delegated proof capture differs") + side_root = _retained_path(root, f"engine/{side}") + actual_paths = { + path.relative_to(side_root).as_posix() + for path in retained_files(side_root) + } + expected_paths = {file.path for file in capture.files} + if actual_paths != expected_paths: + raise ValueError("delegated proof source file set differs") for file in capture.files: if _retained_path(root, f"engine/{side}/{file.path}").read_bytes() != file.content: raise ValueError("delegated proof source bytes differ") @@ -146,10 +154,12 @@ def validate_claim_acceptance(record: dict[str, Any], directory: Path, base: Cap root = directory / "change-output" acceptance_path = root / ACCEPTANCE_PATH if not isinstance(delegated, dict) or delegated.get("status") != "accepted": - if is_link(acceptance_path) or acceptance_path.exists(): + if is_link(root) or is_link(acceptance_path) or acceptance_path.exists(): raise ValueError("unpublished claim acceptance artifact") return - if (record["state"] != "done" or (directory / "cancel").exists() + cancel_path = directory / "cancel" + if (record["state"] != "done" or is_link(cancel_path) or cancel_path.exists() + or is_link(root) or not root.is_dir() or report["stopped"] is not None or report["status"] != "model_verified" or _read(root, "change-certification.json") != report): raise ValueError("claim acceptance is cancelled, incomplete or stale") diff --git a/src/vkit/change/intent.py b/src/vkit/change/intent.py index 13d85d1..2ec214a 100644 --- a/src/vkit/change/intent.py +++ b/src/vkit/change/intent.py @@ -181,7 +181,8 @@ def _bind_captured_policy( raise ValueError( f"target {artifact.role} artifact hash does not match accepted intent" ) - if candidate_artifact.raw_sha256 != artifact.sha256: + if (candidate_artifact.raw_sha256 != artifact.sha256 + or candidate_artifact.mode != target_artifact.mode): raise ValueError( f"candidate {artifact.role} artifact differs from accepted intent" ) diff --git a/src/vkit/change/paired.py b/src/vkit/change/paired.py index 2abd62b..3269774 100644 --- a/src/vkit/change/paired.py +++ b/src/vkit/change/paired.py @@ -2,6 +2,7 @@ import hashlib import json +import os import re import stat import time @@ -89,8 +90,11 @@ def _artifact(root: Path, path: Path, media_type: str) -> ArtifactRef: def _write_artifact(root: Path, relative: str, content: bytes, media_type: str) -> ArtifactRef: - path = root.joinpath(*relative.split("/")) + path = _retained_path(root, relative) path.parent.mkdir(parents=True, exist_ok=True) + path = _retained_path(root, relative) + if is_link(path): + raise ValueError(f"artifact path is a filesystem link: {relative}") with path.open("xb") as stream: stream.write(content) return _artifact(root, path, media_type) @@ -232,7 +236,7 @@ def _source_matches(source: CapturedSource, root: Path) -> bool: expected = {item.path: item.raw_sha256 for item in source.files} try: actual = _tree_files(root) - modes_match = all( + modes_match = True if os.name == "nt" else all( (root.joinpath(*item.path.split("/")).stat().st_mode & 0o111 != 0) == (item.mode == "100755") for item in source.files @@ -400,7 +404,8 @@ def _save_report( ) report["status"] = _final_status(report) validate("paired execution report", "paired-execution-report.v1.json", report) - with (output_dir / "paired-report.json").open("xb") as stream: + report_path = _retained_path(output_dir, "paired-report.json") + with report_path.open("xb") as stream: stream.write(_json_bytes(report)) return PairedExecution(report["status"], live_binding, report) @@ -477,6 +482,7 @@ def _run_prepared_paired_execution( timeout_seconds: float = 10, max_shrink_trials: int = 20, should_cancel: Callable[[], bool] = lambda: False, + shrink_domain: tuple[str, ...] | None = None, ) -> PairedExecution: _validate_limits(repetitions, timeout_seconds, max_shrink_trials) started = time.monotonic() @@ -758,8 +764,11 @@ def observe(token: str, purpose: str) -> dict[str, Any]: shrink = report["shrinking"] shrink["complete"] = False shrink["seed_input"] = violation + shrink_pool = ( + bound.request.claim.admissible_inputs if shrink_domain is None else shrink_domain + ) candidates = sorted( - (token for token in bound.request.claim.admissible_inputs + (token for token in shrink_pool if _u32_token(token) < _u32_token(violation)), key=int, ) @@ -841,8 +850,22 @@ def _run_process( return None, None, None, _failure( "environment", "infrastructure_failure", "tool_pin_mismatch", str(exc), ) - stdout_path.parent.mkdir(parents=True, exist_ok=True) - stderr_path.parent.mkdir(parents=True, exist_ok=True) + try: + stdout_rel = stdout_path.absolute().relative_to(output_root.absolute()).as_posix() + stderr_rel = stderr_path.absolute().relative_to(output_root.absolute()).as_posix() + stdout_path = _retained_path(output_root, stdout_rel) + stderr_path = _retained_path(output_root, stderr_rel) + stdout_path.parent.mkdir(parents=True, exist_ok=True) + stderr_path.parent.mkdir(parents=True, exist_ok=True) + stdout_path = _retained_path(output_root, stdout_rel) + stderr_path = _retained_path(output_root, stderr_rel) + if is_link(stdout_path) or is_link(stderr_path): + raise ValueError("process output path is a filesystem link") + except (OSError, ValueError) as exc: + return None, None, None, _failure( + "retained_artifacts", "infrastructure_failure", + "retained_artifact_mismatch", str(exc), + ) usage = report["resource_usage"] limits = report["resource_limits"] if usage["process_invocations"] >= limits["max_process_invocations"]: diff --git a/src/vkit/change/service.py b/src/vkit/change/service.py index 717abba..7bd1c14 100644 --- a/src/vkit/change/service.py +++ b/src/vkit/change/service.py @@ -12,19 +12,12 @@ from vkit.change.intent import BoundChangeRequest from vkit.rust.kani_execution import run_kani_relational from vkit.change.paired import _artifact, _artifact_mismatches, _fresh_directory, _json_bytes, _write_artifact +from vkit.kernel import conclude_change_methods from vkit.rust.rust_relational import _prepare_captured_rust_relational def _conclusion(results: list[dict[str, Any]]) -> str: - statuses = {item["status"] for item in results} - for failure in ("observed_violation", "proof_rejected"): - if failure in statuses: - return failure - if not statuses: - return "unsupported" - if statuses - {"observed_conformance", "verified"}: - return "unknown" - return "model_verified" if "verified" in statuses else "observed_conformance" + return conclude_change_methods([item["status"] for item in results]) def run_change_methods( @@ -133,7 +126,7 @@ def run_change_methods( report["delegated_claim"] = {"status": "accepted", "acceptance": ref.to_json()} except (OSError, ValueError, KeyError, TypeError) as exc: report["delegated_claim"] = {"status": "unknown", "reason": str(exc)} - if should_cancel() and report["delegated_claim"]["status"] != "accepted": + if should_cancel() and report["delegated_claim"]["status"] not in {"accepted", "refuted"}: report.update(status="unknown", stopped="cancelled") _write_artifact(root, "change-certification.json", _json_bytes(report), "application/json") return report diff --git a/src/vkit/cli.py b/src/vkit/cli.py index 5ccb055..664d208 100644 --- a/src/vkit/cli.py +++ b/src/vkit/cli.py @@ -13,33 +13,86 @@ from pathlib import Path from typing import Any, Sequence +from vkit.cli_accept import ( + Refused, + _accept_card, + _accept_proposal, + _definition_record, + _inventory_record, + _oracle_diff, + _pinned_or_refuse, + run_accept, +) +from vkit.cli_render import ( + _emit, + _outcome_line, + _run_view_line, + _sentinel_line, + render_doctor, + render_features, + render_gate, + render_model_compare, + render_status, +) +from vkit.console.settings import load_launcher_settings, load_settings, save_settings +from vkit.console.workspaces import remember from vkit.core import query -from vkit.core.manifest import Manifest, ManifestError -from vkit.runtime.paths import Project, ProjectError +from vkit.core.acceptance import ( + AGENT_MARKERS, + EXIT_BLOCKED, + EXIT_FAILED, + EXIT_INTERNAL, + EXIT_INVALID, + EXIT_OK, + EXIT_UNAVAILABLE, + _command_has_agent_marker, + _corpus, + _def_change, + _demonstrated_label, + _inventory_diff, + _prior_acceptances, + run_exit_code, + verdict_exit_code, +) +from vkit.core.manifest import ManifestError from vkit.core.schemas import SchemaValidationError -from vkit.console.settings import load_launcher_settings, load_settings, save_settings from vkit.core.store import Store, now -from vkit.console.workspaces import remember - -EXIT_OK = 0 -EXIT_FAILED = 1 -EXIT_INVALID = 2 -EXIT_BLOCKED = 3 -EXIT_INTERNAL = 4 -EXIT_UNAVAILABLE = 5 - -_RESULT_EXIT = {"PASS": EXIT_OK, "FAIL": EXIT_FAILED, "BLOCKED": EXIT_BLOCKED} -_VERDICT_EXIT = {"READY": EXIT_OK, "REJECTED": EXIT_FAILED, "BLOCKED": EXIT_BLOCKED} - - -class Refused(Exception): - def __init__(self, message: str, code: int) -> None: - super().__init__(message) - self.code = code - +from vkit.runtime.paths import Project, ProjectError -def _emit(payload: dict[str, Any], as_json: bool, human: str) -> None: - print(json.dumps(payload, indent=2) if as_json else human) +__all__ = [ + "AGENT_MARKERS", + "EXIT_BLOCKED", + "EXIT_FAILED", + "EXIT_INTERNAL", + "EXIT_INVALID", + "EXIT_OK", + "EXIT_UNAVAILABLE", + "Refused", + "_accept_card", + "_accept_proposal", + "_command_has_agent_marker", + "_confirm", + "_corpus", + "_def_change", + "_definition_record", + "_demonstrated_label", + "_emit", + "_inventory_diff", + "_inventory_record", + "_oracle_diff", + "_outcome_line", + "_parent_commands", + "_pinned_or_refuse", + "_prior_acceptances", + "_run_view_line", + "_sentinel_line", + "_telemetry", + "build_parser", + "cmd_accept", + "main", + "run_exit_code", + "verdict_exit_code", +] def _unique_json_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: @@ -82,24 +135,56 @@ def _remember_workspace(project: Project, source: str) -> None: print(f"warning: could not remember VKit workspace: {exc}", file=sys.stderr, flush=True) -def _outcome_line(record: dict[str, Any]) -> str: - outcome = record.get("outcome") or {} - subject_id = record.get("subject", {}).get("id", record.get("check_id")) - line = f"{subject_id}: {outcome.get('result', record['state'].upper())}" - if outcome.get("reason"): - line += f" ({outcome['reason']}) {outcome.get('detail', '')}".rstrip() - for scenario in outcome.get("scenarios", []): - line += f"\n [{scenario['result']}] {scenario['id']}: {scenario['observation']}" - return line + f"\n run {record['run_id']}" +def _telemetry(project: Any, event: str) -> None: + import time + + try: + root = Store.of(project).root + root.mkdir(parents=True, exist_ok=True) + with (root / "telemetry.jsonl").open("a", encoding="utf-8") as handle: + handle.write(json.dumps({"event": event, "project": str(getattr(project, "root", "")), + "ts": time.time()}) + "\n") + except OSError: + pass + + +def _parent_commands(depth: int = 2) -> tuple[list[str], bool]: + commands, pid, degraded = [], os.getppid(), False + for _ in range(depth): + try: + commands.append(Path(f"/proc/{pid}/cmdline").read_bytes().replace(b"\0", b" ").decode("utf-8", "replace")) + pid = int(Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()[1]) + except (OSError, IndexError, ValueError): + degraded = True + break + if pid <= 1: + break + return commands, degraded + + +def _confirm(args: argparse.Namespace, description: str, question: str, + project: Project | None = None) -> str | None: + if args.yes: + if os.environ.get("VKIT_ALLOW_YES") != "1": + raise Refused("this action needs operator confirmation; run it interactively or set " + "VKIT_ALLOW_YES in the operator environment:\n" + description, EXIT_INVALID) + commands, degraded = _parent_commands() + if degraded: + _telemetry(project, "provenance_walk_degraded") if project else None + if any(_command_has_agent_marker(command) for command in commands): + raise Refused("this acceptance was spawned by an agent hook chain, not an operator; " + "a human must accept it:\n" + description, EXIT_INVALID) + return "operator_env" if sys.stdin.isatty() else "shell_env" + if args.json or not sys.stdin.isatty(): + raise Refused("review this and confirm it interactively as the operator (or set " + "VKIT_ALLOW_YES):\n" + description, EXIT_INVALID) + print(description) + return "interactive" if input(f"{question} [y/N] ").strip().lower() == "y" else None def cmd_doctor(args: argparse.Namespace) -> int: report = query.doctor(_context(args)) - lines = [f"project : {report['project']}", f"state : {report['state_root']}"] - for f in report["findings"]: - lines.append(f" [{'ok ' if f['ok'] else 'FAIL'}] {f.get('prerequisite', f['check'])}: {f['detail']}") - lines.append("ready" if report["ok"] else "not ready") - _emit(report, args.json, "\n".join(lines)) + _emit(report, args.json, render_doctor(report)) return EXIT_OK if report["ok"] else EXIT_BLOCKED @@ -125,18 +210,7 @@ def cmd_feedback_list(args: argparse.Namespace) -> int: def cmd_status(args: argparse.Namespace) -> int: report = query.status(_context(args), args.path or ()) - lines = [f"gate: {report['gate']['verdict']} - {report['gate']['reason']}"] - for check in report["checks"]: - lines.append(f" {check['state']:<14} {check['id']} [{check['category']}] {check['inputs']['scope']}") - for component in report["formal"]: - lines.append(f" {component['state']:<14} {component['id']} [verus_source, required_api]") - if component["detail"]: - lines.append(f" {component['detail']}") - for path in report["unmapped_paths"]: - lines.append(f" no check reads {path}") - if report["needs_run"]: - lines.append("run: vkit check run --needed") - _emit(report, args.json, "\n".join(lines)) + _emit(report, args.json, render_status(report)) return EXIT_OK @@ -148,13 +222,10 @@ def cmd_gate(args: argparse.Namespace) -> int: raise Refused("the committed gate requires --candidate, --target and --output", EXIT_INVALID) report = run_gate(_context(args).project, args.candidate, args.target, Path(args.output)) _emit(report, args.json, f"{report['verdict']}: {report['reason']}") - return EXIT_OK if report["verdict"] == "READY" else EXIT_FAILED if report["verdict"] == "FAILED" else EXIT_BLOCKED + return verdict_exit_code(report["verdict"]) report = query.status(_context(args))["gate"] - lines = [f"{report['verdict']}: {report['reason']}"] - lines += [f" {c['state']:<14} {c['id']}" for c in report["checks"]] - lines += [f" {c['state']:<14} {c['id']} [formal]" for c in report.get("formal", [])] - _emit(report, args.json, "\n".join(lines)) - return _VERDICT_EXIT[report["verdict"]] + _emit(report, args.json, render_gate(report)) + return verdict_exit_code(report["verdict"]) def cmd_check_run(args: argparse.Namespace) -> int: @@ -184,13 +255,13 @@ def cmd_check_run(args: argparse.Namespace) -> int: if (record.get("outcome") or {}).get("result") == "FAIL" and check_id in manifest.checks: ctx.store.retain_fail(check_id, canonical_digest(evaluator_digests(manifest.require(check_id))), tree) - results = {(r.get("outcome") or {}).get("result", "BLOCKED" if r["state"] == "interrupted" else None) - for r in records} _emit({"command": "check run", "runs": records}, args.json, "\n".join(_outcome_line(r) for r in records) or "every check is fresh; nothing to run") - for result in ("FAIL", "BLOCKED"): - if result in results: - return _RESULT_EXIT[result] + codes = {run_exit_code(r) for r in records} + if EXIT_FAILED in codes: + return EXIT_FAILED + if EXIT_BLOCKED in codes: + return EXIT_BLOCKED return EXIT_OK @@ -220,35 +291,20 @@ def cmd_verify(args: argparse.Namespace) -> int: raise Refused(str(exc), EXIT_BLOCKED) from exc view = query.run_view(ctx, record["run_id"], sections=args.section) _emit(view, args.json, _run_view_line(view)) - return _RESULT_EXIT.get((view["summary"].get("outcome") or {}).get("result"), EXIT_OK) + return run_exit_code(view["summary"]) def cmd_model_compare(args: argparse.Namespace) -> int: from vkit.formal.transitions import compare_transition_request report = compare_transition_request(_read_json_file(args.request, "transition comparison request")) - lines = [f"model comparison: {report['kind']} ({report['scope']})"] - for delta in report["deltas"]: - witness = delta["witness"] - lines.append(f" {delta['kind']}: {delta['removed']} removed, {delta['added']} added; " - f"{witness['side']} witness from {witness['initial_state']} " - f"in {len(witness['path'])} steps") - for step in witness["path"]: - lines.append(f" {step['source']} --{step['action']}({step['input']})--> {step['target']}") - if "probe" in witness: - probe = witness["probe"] - lines.append(f" inspect {probe['state']} with {probe['action']}({probe['input']})") - lines.append(f" difference present in {witness['side']}: {', '.join(witness['difference'])}") - if "reason" in report: - lines.append(report["reason"]) - lines.append("Explicit finite models only; no source proof or code approval.") - _emit(report, args.json, "\n".join(lines)) + _emit(report, args.json, render_model_compare(report)) return {"equivalent": EXIT_OK, "different": EXIT_FAILED}.get(report["kind"], EXIT_BLOCKED) def cmd_change_certify(args: argparse.Namespace) -> int: - from vkit.core import jobs from vkit.change.methods import parse_kani_toolchain + from vkit.core import jobs ctx = _context(args) wait_seconds = query.validate_wait_seconds(args.wait) @@ -264,10 +320,7 @@ def cmd_change_certify(args: argparse.Namespace) -> int: if view is None: raise Refused(f"no run {record['run_id']!r}", EXIT_INVALID) _emit(view, args.json, _run_view_line(view)) - result = (view["summary"].get("outcome") or {}).get("result") - if result is not None: - return _RESULT_EXIT.get(result, EXIT_BLOCKED) - return EXIT_BLOCKED if view["summary"]["state"] == "interrupted" else EXIT_OK + return run_exit_code(view["summary"]) def cmd_run_show(args: argparse.Namespace) -> int: @@ -277,11 +330,8 @@ def cmd_run_show(args: argparse.Namespace) -> int: artifact_offset=args.artifact_offset, artifact_limit=args.artifact_limit) if view is None: raise Refused(f"no run {args.run!r}", EXIT_INVALID) - summary = view["summary"] _emit(view, args.json, _run_view_line(view)) - if summary["state"] == "done": - return _RESULT_EXIT[(summary.get("outcome") or {}).get("result", "BLOCKED")] - return EXIT_BLOCKED if summary["state"] == "interrupted" else EXIT_OK + return run_exit_code(view["summary"]) def cmd_run_cancel(args: argparse.Namespace) -> int: @@ -306,30 +356,7 @@ def cmd_run_wait(args: argparse.Namespace) -> int: record = wait(ctx.store, args.run, args.timeout) view = query.run_view(ctx, record["run_id"], sections=args.section) _emit(view, args.json, _run_view_line(view)) - return _RESULT_EXIT.get((view["summary"].get("outcome") or {}).get("result"), EXIT_BLOCKED) - - -def _run_view_line(view: dict[str, Any]) -> str: - summary = view["summary"] - lines = [_outcome_line(summary)] - if "change_certification" in summary: - shadow = summary["change_certification"] - lines.append(f"shadow analysis: {shadow['status']} ({summary.get('assurance') or 'empirical'}, no approval authority)") - if shadow["requirement"] is not None: - lines.append(f"requirement: {shadow['requirement']['source']}") - if "delegated_claim" in shadow: - delegated = shadow["delegated_claim"] - lines.append(f"delegated claim: {delegated['status']}") - if "acceptance" in delegated: - lines.append(f"acceptance evidence: {delegated['acceptance']['path']}") - elif "reason" in delegated: - lines.append(f"claim reason: {delegated['reason']}") - for section in ("diagnostics", "obligations", "provenance", "artifacts"): - if section in view: - lines.append(f"{section}: {json.dumps(view[section], ensure_ascii=False)}") - if "log" in view: - lines.append(view["log"]["text"]) - return "\n\n".join(line for line in lines if line) + return run_exit_code(view["summary"], unfinished=EXIT_BLOCKED) def cmd_run_retry(args: argparse.Namespace) -> int: @@ -343,7 +370,7 @@ def cmd_run_retry(args: argparse.Namespace) -> int: if not args.detach: record = jobs.wait(ctx.store, record["run_id"]) _emit(record, args.json, _outcome_line(record)) - return _RESULT_EXIT.get((record.get("outcome") or {}).get("result"), EXIT_OK) + return run_exit_code(record) def cmd_evidence_export(args: argparse.Namespace) -> int: @@ -363,69 +390,7 @@ def cmd_evidence_replay(args: argparse.Namespace) -> int: if not args.detach: record = jobs.wait(ctx.store, record["run_id"]) _emit(record, args.json, _outcome_line(record)) - return _RESULT_EXIT.get((record.get("outcome") or {}).get("result"), EXIT_OK) - - -AGENT_MARKERS = ("vkit_hook", "claude", "codex", "deepai", "aider", "mcp") - - -def _telemetry(project: Any, event: str) -> None: - import time - - try: - root = Store.of(project).root - root.mkdir(parents=True, exist_ok=True) - with (root / "telemetry.jsonl").open("a", encoding="utf-8") as handle: - handle.write(json.dumps({"event": event, "project": str(getattr(project, "root", "")), - "ts": time.time()}) + "\n") - except OSError: - pass - - -def _parent_commands(depth: int = 2) -> tuple[list[str], bool]: - commands, pid, degraded = [], os.getppid(), False - for _ in range(depth): - try: - commands.append(Path(f"/proc/{pid}/cmdline").read_bytes().replace(b"\0", b" ").decode("utf-8", "replace")) - pid = int(Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()[1]) - except (OSError, IndexError, ValueError): - degraded = True - break - if pid <= 1: - break - return commands, degraded - - -def _command_has_agent_marker(command: str) -> bool: - for raw in command.lower().split(): - token = raw.strip("\"'") - if not token: - continue - base = token.replace("\\", "/").rsplit("/", 1)[-1] - stem = os.path.splitext(base)[0] - if base in AGENT_MARKERS or stem in AGENT_MARKERS or any(base.startswith(f"{m}-") for m in AGENT_MARKERS): - return True - return False - - -def _confirm(args: argparse.Namespace, description: str, question: str, - project: Project | None = None) -> str | None: - if args.yes: - if os.environ.get("VKIT_ALLOW_YES") != "1": - raise Refused("this action needs operator confirmation; run it interactively or set " - "VKIT_ALLOW_YES in the operator environment:\n" + description, EXIT_INVALID) - commands, degraded = _parent_commands() - if degraded: - _telemetry(project, "provenance_walk_degraded") if project else None - if any(_command_has_agent_marker(command) for command in commands): - raise Refused("this acceptance was spawned by an agent hook chain, not an operator; " - "a human must accept it:\n" + description, EXIT_INVALID) - return "operator_env" if sys.stdin.isatty() else "shell_env" - if args.json or not sys.stdin.isatty(): - raise Refused("review this and confirm it interactively as the operator (or set " - "VKIT_ALLOW_YES):\n" + description, EXIT_INVALID) - print(description) - return "interactive" if input(f"{question} [y/N] ").strip().lower() == "y" else None + return run_exit_code(record) def cmd_proposals(args: argparse.Namespace) -> int: @@ -450,339 +415,8 @@ def cmd_reject(args: argparse.Namespace) -> int: return EXIT_OK -def _accept_proposal(args: argparse.Namespace, ctx: query.Context) -> int: - from vkit.core.proposals import ProposalError, apply, find - - try: - proposal = find(ctx.store, args.proposal) - via = _confirm(args, proposal.describe(), "apply this proposal to the working tree?", ctx.project) - if via is None: - print("nothing accepted") - return EXIT_BLOCKED - accepted = apply(ctx.project, ctx.store, proposal) - if accepted: - from vkit.core.evidence import backend_identity - from vkit.core.manifest import parse_manifest - from vkit.core.state import evaluator_digests, sentinel as probe - - manifest = parse_manifest(ctx.project) - _pinned_or_refuse(manifest, accepted) - from vkit.core.state import evaluator - for c in accepted: - ctx.store.retain_evaluator(c, evaluator(manifest.require(c))) - checked = {c: probe(ctx.project, manifest.require(c)) for c in accepted} - ctx.store.approve({manifest.digest(c): _definition_record( - manifest, c, backend_identity(manifest.require(c)), checked[c], via, - evaluator_digests(manifest.require(c))) for c in accepted}) - ctx.store.approve({"__inventory__": _inventory_record(ctx.store, manifest, accepted, via)}) - except ProposalError as exc: - raise Refused(str(exc), EXIT_INVALID) from exc - _emit({"proposal": proposal.digest, "accepted_checks": accepted}, args.json, - f"applied proposal {proposal.digest[:12]}; accepted checks: {', '.join(accepted) or 'none'}") - return EXIT_OK - - -_LIST_FIELDS = ("required_scenarios", "required_tests", "scenarios", "inputs") - - -def _def_change(old: Any, new: Any) -> tuple[str, list[str]]: - if not isinstance(old, dict): - return "incomparable", ["prior accepted definition not recorded"] - changes = [(key, old.get(key), new.get(key)) for key in sorted(set(old) | set(new)) - if old.get(key) != new.get(key)] - if not changes: - return "unchanged", [] - stronger = weaker = False - lines = [] - for key, was, current in changes: - lines.append(f"{key}: {was!r} -> {current!r}") - if key in _LIST_FIELDS: - was, current = was or [], current or [] - if not set(was) <= set(current): - weaker = True - if not set(current) <= set(was): - stronger = True - elif key == "timeout_seconds": - if was is None or current is None: - stronger = weaker = True - else: - stronger = stronger or current < was - weaker = weaker or current > was - else: - stronger = weaker = True - label = ("strengthening" if stronger and not weaker else - "weakening" if weaker and not stronger else "incomparable") - return label, lines - - -def _demonstrated_label(label: str, demo: dict[str, int] | None) -> str: - if label != "strengthening": - return label - if not demo or not demo["added"]: - return "strengthening (unproven: no rejection corpus)" - return f"strengthening (declared: {demo['added']} added obligation(s), not executed)" - - -def _corpus(prior_definition: Any, entry: Any) -> dict[str, int]: - prior = prior_definition if isinstance(prior_definition, dict) else {} - return {"added": sum(len(set(entry.get(key) or ()) - set(prior.get(key) or ())) for key in _LIST_FIELDS)} - - -def _prior_acceptances(approved: dict[str, Any], check_id: str) -> list[dict[str, Any]]: - records = [r for r in approved.values() - if r.get("kind") == "check_definition" and r.get("check_id") == check_id] - return sorted(records, key=lambda r: r.get("accepted_at") or "") - - -def _oracle_diff(store: Store, prior: dict[str, Any], check) -> list[str]: - import difflib - - from vkit.core.state import evaluator - from vkit.verifiers.spec import ExternalCheck - - if isinstance(getattr(check, "variant", None) or check, ExternalCheck): - return ["oracle: external check - evaluator content is not pinned"] - was = store.evaluator_bytes(check.id, (prior.get("oracle") or {}).get("digest")) - if was is None: - return ["oracle: prior evaluator bytes are not retained (pre byte-store acceptance)"] - current = evaluator(check) - changed = [name for name in sorted(set(was) | set(current)) if was.get(name) != current.get(name)] - lines = ["oracle byte diff vs last acceptance: " + ("; ".join(changed) or "unchanged")] - for name in changed: - diff = list(difflib.unified_diff( - was.get(name, b"").decode("utf-8", "replace").splitlines(), - current.get(name, b"").decode("utf-8", "replace").splitlines(), - fromfile=f"{name} (accepted)", tofile=f"{name} (candidate)", lineterm="")) - lines += [f" {line}" for line in diff[:20]] - return lines - - -def _sentinel_line(found: dict[str, Any]) -> str: - if found["verdict"] == "rejects": - return "null-subject sentinel: rejects the null subject (" + ", ".join(found["subject"]) + " emptied)" - if found["verdict"] == "vacuous": - return ("null-subject sentinel: VACUOUS - the evaluator passes with " - + ", ".join(found["subject"]) + " emptied") - if found["verdict"] == "timeout": - return "null-subject sentinel: TIMEOUT - no artifact before the probe deadline; a slow evaluator proves nothing" - if found["verdict"] == "error": - return "null-subject sentinel: ERROR - the probe produced no judgeable artifact (crash or missing report)" - return {"not_bound": "null-subject sentinel: NOT BOUND - no subject path distinct from the evaluator", - "exempt": "null-subject sentinel: exempt for this check kind", - "unavailable": "null-subject sentinel: unavailable - " + found.get("detail", "unknown")}[found["verdict"]] - - -def _accept_card(manifest, identities, pending, formal_records, approved, snapshot, store, sentinels=None) -> list[str]: - from vkit.core.state import sentinel - - sentinels = sentinels or {} - lines = [] - for check_id in pending: - entry = manifest.entries[check_id] - check = manifest.require(check_id) - priors = _prior_acceptances(approved, check_id) - prior = priors[-1] if priors else None - label, changes = _def_change((prior or {}).get("definition"), entry) - demo = _corpus((prior or {}).get("definition"), entry) - lines.append(f"{check_id} ({manifest.digest(check_id)[:12]}): " - f"{_demonstrated_label(label, demo)} vs last acceptance" - + (f" ({prior.get('accepted_at')}, {prior.get('confirmed_via') or 'unrecorded'})" - if prior else "")) - lines += [f" {change}" for change in changes] - if prior is not None: - first_label, _ = _def_change(priors[0].get("definition"), entry) - if priors[0] is not prior: - lines.append(f" {_demonstrated_label(first_label, demo)} vs first acceptance" - f" ({priors[0].get('accepted_at')}, {priors[0].get('confirmed_via') or 'unrecorded'})") - lines += [" " + line for line in _oracle_diff(store, prior, check)] - lines.append(" " + _sentinel_line(sentinels.get(check_id) or sentinel(snapshot.project, check))) - last = store.latest(check_id) - lines.append(" evidence: " + (f"last run {last['run_id']} {last['result']}" if last - else "no finished run - accept-before-run relies on this card")) - lines.append(" inputs: " + ", ".join(entry.get("inputs", ()))) - lines.append(" checker identity: " + json.dumps(identities[check_id], sort_keys=True)) - for component_id, (record, execution) in formal_records.items(): - component = manifest.require_component(component_id) - lines += [f"formal component {component_id} ({component.digest[:12]})", - json.dumps(component.to_json(), indent=2), - "coverage: required_api; assurance: trusted_engine; method: verus_source", - "checker identity: " + json.dumps(execution, sort_keys=True)] - sets = [snapshot.inputs(c.inputs) for c in manifest.checks.values()] - uncovered = [f for f in snapshot.files if not any(s.covers(f) for s in sets)] - lines.append("uncovered paths: " + (", ".join(uncovered[:20]) - + (f" (+{len(uncovered) - 20} more)" if len(uncovered) > 20 else "") if uncovered else "none")) - return lines - - -def _inventory_diff(previous: dict[str, Any] | None, inventory: dict[str, Any], - required: dict[str, bool] | None = None) -> list[str]: - if previous is None: - return [] - lines = [] - for key, prefix in (("checks", "obligation inventory: "), ("formal_required", "formal obligations: ")): - was, current = previous.get(key, {}), inventory[key] - delta = {"removed": sorted(set(was) - set(current)), "added": sorted(set(current) - set(was)), - "rebound": sorted(name for name in current if was.get(name) != current[name])} - if any(delta.values()): - lines.append(prefix + json.dumps(delta)) - lines += [f"formal obligation no longer required: {name} (still bound until --drop {name})" - for name in sorted(previous.get("formal_required", {})) - if required is not None and name not in required] - lines += [f"formal obligation demoted: {name} (still bound until --drop {name})" - for name in sorted(previous.get("formal_required", {})) - if required is not None and required.get(name) is False] - lines += [f"drop requested: {name} (last evidence run {run})" - for name, run in sorted(inventory["dropped"].items()) - if previous.get("dropped", {}).get(name) != run] - lines += [f"drop marker cleared by this acceptance revision: {name} (slot re-accepted; its obligations bind again)" - for name in sorted(previous.get("dropped", {})) if name not in inventory["dropped"]] - return lines - - -def _definition_record(manifest, check_id: str, identity: dict[str, Any], - checked: dict[str, Any], via: str, files: dict[str, str]) -> dict[str, Any]: - from vkit.core.inputs import canonical_digest - from vkit.verifiers.spec import ExternalCheck - - external = isinstance(getattr(manifest.require(check_id), "variant", None) or manifest.require(check_id), - ExternalCheck) - return {"kind": "check_definition", "check_id": check_id, "accepted_at": now(), "confirmed_via": via, - "backend": identity, "definition": manifest.entries[check_id], - "oracle": {"files": files, "digest": canonical_digest(files), "sentinel": checked, - "external": external}} - - -def _inventory_record(store: Store, manifest: Manifest, ids: list[str], via: str, - *, dropped: dict[str, str] | None = None, - formal: dict[str, str] | None = None, - drop_names: tuple[str, ...] = ()) -> dict[str, Any]: - from vkit.core.state import approved_inventory - - base = approved_inventory(store.approved()) or {} - checks = {**base.get("checks", {}), **{c: manifest.digest(c) for c in ids}} - formal_required = {**base.get("formal_required", {}), **(formal or {})} - for name in (*(dropped or {}), *drop_names): - checks.pop(name, None) - formal_required.pop(name, None) - reaccepted = {*ids, *(formal or {})} - return {"kind": "obligation_inventory", "accepted_at": now(), - "checks": checks, - "formal_required": formal_required, - "dropped": {**{n: r for n, r in base.get("dropped", {}).items() if n not in reaccepted}, - **(dropped or {})}, - "confirmed_via": via} - - -def _pinned_or_refuse(manifest, check_ids: list[str]) -> None: - from vkit.core.state import evaluator_gaps - - for check_id in check_ids: - gaps = evaluator_gaps(manifest.require(check_id)) - if gaps: - raise Refused(f"{check_id}: evaluator content is not pinned ({'; '.join(gaps)}); " - "an empty oracle would match every future edit, so acceptance is refused", EXIT_INVALID) - - def cmd_accept(args: argparse.Namespace) -> int: - ctx = _context(args) - if args.proposal: - return _accept_proposal(args, ctx) - try: - manifest = ctx.require_manifest() - explicit = bool(args.check or args.component) - wanted = args.check or ([] if explicit else sorted(manifest.checks)) - components = args.component or ([] if explicit else sorted(manifest.components)) - for check_id in wanted: - manifest.require(check_id) - for component_id in components: - manifest.require_component(component_id) - except ManifestError as exc: - raise Refused(str(exc), EXIT_INVALID) from exc - approved = ctx.store.approved() - from vkit.core.evidence import backend_identity - from vkit.core.state import evaluator_digests, oracle_matches, sentinel - - identities = {c: backend_identity(manifest.require(c)) for c in wanted} - pending = [c for c in wanted if not oracle_matches(approved, manifest.require(c), manifest.digest(c))] - _pinned_or_refuse(manifest, pending) - sentinels = {check_id: sentinel(ctx.project, manifest.require(check_id)) for check_id in pending} - oracle = {check_id: evaluator_digests(manifest.require(check_id)) for check_id in pending} - from vkit.core.state import comparison, evaluator - - comparisons = {} - for check_id in pending: - priors = _prior_acceptances(approved, check_id) - outcome = comparison(ctx.store, ctx.project, manifest.require(check_id), priors[-1] if priors else None) - comparisons[check_id] = outcome - if outcome["outcome"] == "weakened_check": - raise Refused(f"{check_id}: weakened_check - the candidate evaluator passes a retained legitimate " - "FAIL; acceptance is refused: " + json.dumps(outcome["receipts"], indent=2), - EXIT_BLOCKED) - if outcome["outcome"] == "incomparable": - raise Refused(f"{check_id}: incomparable - the accepted evaluator cannot run against the current " - f"candidate; clearing: {outcome['clearing']}", EXIT_BLOCKED) - from vkit.formal.verus import ExecutionSetupError, resolve_execution - from vkit.core.inputs import canonical_digest - - formal_records = {} - for component_id in components: - component = manifest.require_component(component_id) - try: - execution = resolve_execution(component) - except ExecutionSetupError as exc: - raise Refused(str(exc), EXIT_BLOCKED) from exc - record = {"kind": "formal_policy", "policy_sha256": component.digest, - "package_sha256": component.package.sha256, - "checker_sha256": canonical_digest(execution["semantic"])} - if any(approved.get(component.digest, {}).get(key) != value for key, value in record.items()): - formal_records[component_id] = (record, execution["semantic"]) - from vkit.core.inputs import Snapshot - from vkit.core.state import approved_inventory - - previous = approved_inventory(approved) - inventory = {"kind": "obligation_inventory", "accepted_at": now(), - "checks": dict((previous or {}).get("checks", {})), - "formal_required": dict((previous or {}).get("formal_required", {})), - "dropped": {name: run for name, run in (previous or {}).get("dropped", {}).items() - if name not in wanted and name not in components}} - inventory["checks"].update({c: manifest.digest(c) for c in wanted}) - inventory["formal_required"].update({c: manifest.require_component(c).digest for c in components - if manifest.require_component(c).required}) - for name in args.drop or (): - inventory["checks"].pop(name, None) - inventory["formal_required"].pop(name, None) - last = ctx.store.latest(name) or ctx.store.latest_for("formal_goal", name) - if last is not None and last.get("result") == "FAIL": - inventory["dropped"][name] = last["run_id"] - lines = _accept_card(manifest, identities, pending, formal_records, approved, Snapshot(ctx.project), - ctx.store, sentinels) - for check_id, outcome in comparisons.items(): - lines.append(f"{check_id} comparison: {outcome['outcome']}" - + (f" - clearing: {outcome['clearing']}" if outcome["clearing"] else "")) - lines += _inventory_diff(previous, inventory, {c: comp.required for c, comp in manifest.components.items()}) - inventory_changed = previous != {k: inventory[k] for k in ("checks", "formal_required", "dropped")} - if not pending and not formal_records and not inventory_changed: - _emit({"accepted": [], "accepted_components": [], "pending": []}, args.json, - "every named definition is already accepted") - return EXIT_OK - via = _confirm(args, "\n".join(lines), f"accept {len(pending) + len(formal_records)} definition(s)?", ctx.project) - if via is None: - print("nothing accepted") - return EXIT_BLOCKED - records = {manifest.digest(c): _definition_record(manifest, c, identities[c], sentinels[c], via, oracle[c]) - for c in pending} - records.update({manifest.require_component(c).digest: {**entry, "accepted_at": now(), "confirmed_via": via} - for c, (entry, _) in formal_records.items()}) - records["__inventory__"] = _inventory_record(ctx.store, manifest, wanted, via, - dropped=inventory["dropped"], - formal=inventory["formal_required"], - drop_names=tuple(args.drop or ())) - for check_id in pending: - ctx.store.retain_evaluator(check_id, evaluator(manifest.require(check_id))) - ctx.store.approve(records) - _emit({"accepted": pending, "accepted_components": list(formal_records), "confirmed_via": via}, args.json, - f"accepted ({via}): {', '.join(pending + list(formal_records))}") - return EXIT_OK + return run_accept(args, _context(args), _confirm) def cmd_baseline(args: argparse.Namespace) -> int: @@ -811,13 +445,7 @@ def cmd_features(args: argparse.Namespace) -> int: report = query.status(_context(args)) if report["feature_error"]: raise Refused(report["feature_error"], EXIT_INVALID) - lines = [] - for feature in report["features"]: - lines.append(f"[{'verified ' if feature['verified'] else 'UNVERIFIED'}] {feature['id']}: {feature['behavior']}") - lines += [f" reach: {step}" for step in feature["how_to_reach"]] - lines += [f" gap: {gap}" for gap in feature["gaps"]] - lines += [f" problem: {problem}" for problem in feature["problems"]] - _emit({"features": report["features"]}, args.json, "\n".join(lines) or "no feature map") + _emit({"features": report["features"]}, args.json, render_features(report["features"])) return EXIT_OK if report["features"] and all(f["verified"] for f in report["features"]) else EXIT_BLOCKED @@ -845,11 +473,10 @@ def cmd_mcp_serve(args: argparse.Namespace) -> int: def cmd_tools(args: argparse.Namespace) -> int: + from vkit.core.categories import INFRASTRUCTURE_TOOLS from vkit.mcp import BY_NAME, Server project = _context(args).project - from vkit.core.categories import INFRASTRUCTURE_TOOLS - name = args.enable or args.disable if name: if name not in BY_NAME or name in INFRASTRUCTURE_TOOLS: @@ -1076,7 +703,10 @@ def main(argv: Sequence[str] | None = None) -> int: print(str(exc), file=sys.stderr) return exc.code except (ValueError, ManifestError, SchemaValidationError) as exc: - _emit({"error": str(exc), "exit_code": EXIT_INVALID}, args.json, str(exc)) + if args.json: + print(json.dumps({"error": str(exc), "exit_code": EXIT_INVALID})) + else: + print(str(exc), file=sys.stderr) return EXIT_INVALID except Exception as exc: # noqa: BLE001 print(f"internal error: {type(exc).__name__}: {exc}", file=sys.stderr) diff --git a/src/vkit/cli_accept.py b/src/vkit/cli_accept.py new file mode 100644 index 0000000..40208ff --- /dev/null +++ b/src/vkit/cli_accept.py @@ -0,0 +1,292 @@ +"""Operator acceptance workflow for checks, formal components, and proposals.""" +from __future__ import annotations + +import argparse +import difflib +import json +from collections.abc import Callable +from pathlib import Path +from typing import Any + +from vkit.cli_render import _emit, _sentinel_line +from vkit.core import acceptance, query +from vkit.core.acceptance import ( + EXIT_BLOCKED, + EXIT_INVALID, + EXIT_OK, + _corpus, + _def_change, + _demonstrated_label, + _inventory_diff, + _prior_acceptances, +) +from vkit.core.manifest import Manifest, ManifestError +from vkit.core.store import Store, now +from vkit.runtime.paths import Project + + +class Refused(Exception): + def __init__(self, message: str, code: int) -> None: + super().__init__(message) + self.code = code + + +def _oracle_diff(store: Store, prior: dict[str, Any], check: Any) -> list[str]: + from vkit.core.state import evaluator + from vkit.verifiers.spec import ExternalCheck + + if isinstance(getattr(check, "variant", None) or check, ExternalCheck): + return ["oracle: external check - evaluator content is not pinned"] + was = store.evaluator_bytes(check.id, (prior.get("oracle") or {}).get("digest")) + if was is None: + return ["oracle: prior evaluator bytes are not retained (pre byte-store acceptance)"] + current = evaluator(check) + changed = [name for name in sorted(set(was) | set(current)) if was.get(name) != current.get(name)] + lines = ["oracle byte diff vs last acceptance: " + ("; ".join(changed) or "unchanged")] + for name in changed: + diff = list(difflib.unified_diff( + was.get(name, b"").decode("utf-8", "replace").splitlines(), + current.get(name, b"").decode("utf-8", "replace").splitlines(), + fromfile=f"{name} (accepted)", tofile=f"{name} (candidate)", lineterm="")) + lines += [f" {line}" for line in diff[:20]] + return lines + + +def _accept_card(manifest: Manifest, identities: dict[str, Any], pending: list[str], + formal_records: dict[str, Any], approved: dict[str, Any], snapshot: Any, + store: Store, sentinels: dict[str, Any] | None = None) -> list[str]: + from vkit.core.state import sentinel + + sentinels = sentinels or {} + lines = [] + for check_id in pending: + entry = manifest.entries[check_id] + check = manifest.require(check_id) + priors = _prior_acceptances(approved, check_id) + prior = priors[-1] if priors else None + label, changes = _def_change((prior or {}).get("definition"), entry) + demo = _corpus((prior or {}).get("definition"), entry) + lines.append(f"{check_id} ({manifest.digest(check_id)[:12]}): " + f"{_demonstrated_label(label, demo)} vs last acceptance" + + (f" ({prior.get('accepted_at')}, {prior.get('confirmed_via') or 'unrecorded'})" + if prior else "")) + lines += [f" {change}" for change in changes] + if prior is not None: + first_label, _ = _def_change(priors[0].get("definition"), entry) + if priors[0] is not prior: + lines.append(f" {_demonstrated_label(first_label, demo)} vs first acceptance" + f" ({priors[0].get('accepted_at')}, {priors[0].get('confirmed_via') or 'unrecorded'})") + lines += [" " + line for line in _oracle_diff(store, prior, check)] + lines.append(" " + _sentinel_line(sentinels.get(check_id) or sentinel(snapshot.project, check))) + last = store.latest(check_id) + lines.append(" evidence: " + (f"last run {last['run_id']} {last['result']}" if last + else "no finished run - accept-before-run relies on this card")) + lines.append(" inputs: " + ", ".join(entry.get("inputs", ()))) + lines.append(" checker identity: " + json.dumps(identities[check_id], sort_keys=True)) + for component_id, (record, execution) in formal_records.items(): + component = manifest.require_component(component_id) + lines += [f"formal component {component_id} ({component.digest[:12]})", + json.dumps(component.to_json(), indent=2), + "coverage: required_api; assurance: trusted_engine; method: verus_source", + "checker identity: " + json.dumps(execution, sort_keys=True)] + sets = [snapshot.inputs(c.inputs) for c in manifest.checks.values()] + uncovered = [f for f in snapshot.files if not any(s.covers(f) for s in sets)] + lines.append("uncovered paths: " + (", ".join(uncovered[:20]) + + (f" (+{len(uncovered) - 20} more)" if len(uncovered) > 20 else "") if uncovered else "none")) + return lines + + +def _definition_record(manifest: Manifest, check_id: str, identity: dict[str, Any], + checked: dict[str, Any], via: str, files: dict[str, str]) -> dict[str, Any]: + from vkit.core.inputs import canonical_digest + from vkit.verifiers.spec import ExternalCheck + + external = isinstance(getattr(manifest.require(check_id), "variant", None) or manifest.require(check_id), + ExternalCheck) + return {"kind": "check_definition", "check_id": check_id, "accepted_at": now(), "confirmed_via": via, + "backend": identity, "definition": manifest.entries[check_id], + "oracle": {"files": files, "digest": canonical_digest(files), "sentinel": checked, + "external": external}} + + +def _inventory_record(store: Store, manifest: Manifest, ids: list[str], via: str, + *, dropped: dict[str, str] | None = None, + formal: dict[str, str] | None = None, + drop_names: tuple[str, ...] = ()) -> dict[str, Any]: + from vkit.core.state import approved_inventory + + base = approved_inventory(store.approved()) + return acceptance._inventory_record( + base, + {c: manifest.digest(c) for c in ids}, + via, + now(), + dropped=dropped, + formal=formal, + drop_names=drop_names, + ) + + +def _pinned_or_refuse(manifest: Manifest, check_ids: list[str], + *, proposed_files: set[Path] | None = None) -> None: + from vkit.core.state import evaluator_gaps + + for check_id in check_ids: + check = manifest.require(check_id) + gaps = evaluator_gaps(check) + if proposed_files: + root = check.cwd.resolve() + filtered = [] + for gap in gaps: + name, _, reason = gap.rpartition(": ") + if reason == "missing" and (root / name).resolve() in proposed_files: + continue + filtered.append(gap) + gaps = filtered + if gaps: + raise Refused(f"{check_id}: evaluator content is not pinned ({'; '.join(gaps)}); " + "an empty oracle would match every future edit, so acceptance is refused", EXIT_INVALID) + + +def _accept_proposal(args: argparse.Namespace, ctx: query.Context, + confirm_fn: Callable[[argparse.Namespace, str, str, Project | None], str | None]) -> int: + from vkit.core.proposals import ProposalError, _resulting_manifest, apply, find, validate + + try: + proposal = find(ctx.store, args.proposal) + body = validate(ctx.project, proposal.body) + proposed_checks = [entry["id"] for entry in body.get("checks", ())] + if proposed_checks: + _, preview_manifest = _resulting_manifest(ctx.project, body) + proposed_files = {(ctx.project.root / rel).resolve() for rel in body.get("files", ())} + _pinned_or_refuse(preview_manifest, proposed_checks, proposed_files=proposed_files) + via = confirm_fn(args, proposal.describe(), "apply this proposal to the working tree?", ctx.project) + if via is None: + print("nothing accepted") + return EXIT_BLOCKED + accepted = apply(ctx.project, ctx.store, proposal) + has_formal = "formal" in body + if accepted or has_formal: + from vkit.core.evidence import backend_identity + from vkit.core.manifest import parse_manifest + from vkit.core.state import evaluator, evaluator_digests, sentinel as probe + + manifest = parse_manifest(ctx.project) + records: dict[str, Any] = {} + if accepted: + for c in accepted: + ctx.store.retain_evaluator(c, evaluator(manifest.require(c))) + checked = {c: probe(ctx.project, manifest.require(c)) for c in accepted} + records.update({manifest.digest(c): _definition_record( + manifest, c, backend_identity(manifest.require(c)), checked[c], via, + evaluator_digests(manifest.require(c))) for c in accepted}) + formal_required = ({c: comp.digest for c, comp in manifest.components.items() if comp.required} + if has_formal else None) + records["__inventory__"] = _inventory_record(ctx.store, manifest, accepted, via, + formal=formal_required) + ctx.store.approve(records) + except ProposalError as exc: + raise Refused(str(exc), EXIT_INVALID) from exc + _emit({"proposal": proposal.digest, "accepted_checks": accepted}, args.json, + f"applied proposal {proposal.digest[:12]}; accepted checks: {', '.join(accepted) or 'none'}") + return EXIT_OK + + +def run_accept(args: argparse.Namespace, ctx: query.Context, + confirm_fn: Callable[[argparse.Namespace, str, str, Project | None], str | None]) -> int: + if args.proposal: + return _accept_proposal(args, ctx, confirm_fn) + try: + manifest = ctx.require_manifest() + explicit = bool(args.check or args.component) + wanted = args.check or ([] if explicit else sorted(manifest.checks)) + components = args.component or ([] if explicit else sorted(manifest.components)) + for check_id in wanted: + manifest.require(check_id) + for component_id in components: + manifest.require_component(component_id) + except ManifestError as exc: + raise Refused(str(exc), EXIT_INVALID) from exc + approved = ctx.store.approved() + from vkit.core.evidence import backend_identity + from vkit.core.state import comparison, evaluator, evaluator_digests, oracle_matches, sentinel + + identities = {c: backend_identity(manifest.require(c)) for c in wanted} + pending = [c for c in wanted if not oracle_matches(approved, manifest.require(c), manifest.digest(c))] + _pinned_or_refuse(manifest, pending) + sentinels = {check_id: sentinel(ctx.project, manifest.require(check_id)) for check_id in pending} + oracle = {check_id: evaluator_digests(manifest.require(check_id)) for check_id in pending} + + comparisons = {} + for check_id in pending: + priors = _prior_acceptances(approved, check_id) + outcome = comparison(ctx.store, ctx.project, manifest.require(check_id), priors[-1] if priors else None) + comparisons[check_id] = outcome + if outcome["outcome"] == "weakened_check": + raise Refused(f"{check_id}: weakened_check - the candidate evaluator passes a retained legitimate " + "FAIL; acceptance is refused: " + json.dumps(outcome["receipts"], indent=2), + EXIT_BLOCKED) + if outcome["outcome"] == "incomparable": + raise Refused(f"{check_id}: incomparable - the accepted evaluator cannot run against the current " + f"candidate; clearing: {outcome['clearing']}", EXIT_BLOCKED) + from vkit.core.inputs import Snapshot, canonical_digest + from vkit.core.state import approved_inventory + from vkit.formal.verus import ExecutionSetupError, resolve_execution + + formal_records = {} + for component_id in components: + component = manifest.require_component(component_id) + try: + execution = resolve_execution(component) + except ExecutionSetupError as exc: + raise Refused(str(exc), EXIT_BLOCKED) from exc + record = {"kind": "formal_policy", "policy_sha256": component.digest, + "package_sha256": component.package.sha256, + "checker_sha256": canonical_digest(execution["semantic"])} + if any(approved.get(component.digest, {}).get(key) != value for key, value in record.items()): + formal_records[component_id] = (record, execution["semantic"]) + + previous = approved_inventory(approved) + inventory = {"kind": "obligation_inventory", "accepted_at": now(), + "checks": dict((previous or {}).get("checks", {})), + "formal_required": dict((previous or {}).get("formal_required", {})), + "dropped": {name: run for name, run in (previous or {}).get("dropped", {}).items() + if name not in wanted and name not in components}} + inventory["checks"].update({c: manifest.digest(c) for c in wanted}) + inventory["formal_required"].update({c: manifest.require_component(c).digest for c in components + if manifest.require_component(c).required}) + for name in args.drop or (): + inventory["checks"].pop(name, None) + inventory["formal_required"].pop(name, None) + last = ctx.store.latest(name) or ctx.store.latest_for("formal_goal", name) + if last is not None and last.get("result") == "FAIL": + inventory["dropped"][name] = last["run_id"] + lines = _accept_card(manifest, identities, pending, formal_records, approved, Snapshot(ctx.project), + ctx.store, sentinels) + for check_id, outcome in comparisons.items(): + lines.append(f"{check_id} comparison: {outcome['outcome']}" + + (f" - clearing: {outcome['clearing']}" if outcome["clearing"] else "")) + lines += _inventory_diff(previous, inventory, {c: comp.required for c, comp in manifest.components.items()}) + inventory_changed = previous != {k: inventory[k] for k in ("checks", "formal_required", "dropped")} + if not pending and not formal_records and not inventory_changed: + _emit({"accepted": [], "accepted_components": [], "pending": []}, args.json, + "every named definition is already accepted") + return EXIT_OK + via = confirm_fn(args, "\n".join(lines), f"accept {len(pending) + len(formal_records)} definition(s)?", ctx.project) + if via is None: + print("nothing accepted") + return EXIT_BLOCKED + records = {manifest.digest(c): _definition_record(manifest, c, identities[c], sentinels[c], via, oracle[c]) + for c in pending} + records.update({manifest.require_component(c).digest: {**entry, "accepted_at": now(), "confirmed_via": via} + for c, (entry, _) in formal_records.items()}) + records["__inventory__"] = _inventory_record(ctx.store, manifest, wanted, via, + dropped=inventory["dropped"], + formal=inventory["formal_required"], + drop_names=tuple(args.drop or ())) + for check_id in pending: + ctx.store.retain_evaluator(check_id, evaluator(manifest.require(check_id))) + ctx.store.approve(records) + _emit({"accepted": pending, "accepted_components": list(formal_records), "confirmed_via": via}, args.json, + f"accepted ({via}): {', '.join(pending + list(formal_records))}") + return EXIT_OK diff --git a/src/vkit/cli_render.py b/src/vkit/cli_render.py new file mode 100644 index 0000000..e5d1121 --- /dev/null +++ b/src/vkit/cli_render.py @@ -0,0 +1,117 @@ +"""Human and JSON output rendering helpers for the vkit CLI.""" +from __future__ import annotations + +import json +from typing import Any + + +def _emit(payload: dict[str, Any], as_json: bool, human: str) -> None: + print(json.dumps(payload, indent=2) if as_json else human) + + +def _outcome_line(record: dict[str, Any]) -> str: + outcome = record.get("outcome") or {} + subject_id = record.get("subject", {}).get("id", record.get("check_id")) + line = f"{subject_id}: {outcome.get('result', record['state'].upper())}" + if outcome.get("reason"): + line += f" ({outcome['reason']}) {outcome.get('detail', '')}".rstrip() + for scenario in outcome.get("scenarios", []): + line += f"\n [{scenario['result']}] {scenario['id']}: {scenario['observation']}" + return line + f"\n run {record['run_id']}" + + +def _run_view_line(view: dict[str, Any]) -> str: + summary = view["summary"] + lines = [_outcome_line(summary)] + if "change_certification" in summary: + shadow = summary["change_certification"] + lines.append(f"shadow analysis: {shadow['status']} ({summary.get('assurance') or 'empirical'}, no approval authority)") + if shadow["requirement"] is not None: + lines.append(f"requirement: {shadow['requirement']['source']}") + if "delegated_claim" in shadow: + delegated = shadow["delegated_claim"] + lines.append(f"delegated claim: {delegated['status']}") + if "acceptance" in delegated: + lines.append(f"acceptance evidence: {delegated['acceptance']['path']}") + elif "reason" in delegated: + lines.append(f"claim reason: {delegated['reason']}") + for section in ("diagnostics", "obligations", "provenance", "artifacts"): + if section in view: + lines.append(f"{section}: {json.dumps(view[section], ensure_ascii=False)}") + if "log" in view: + lines.append(view["log"]["text"]) + return "\n\n".join(line for line in lines if line) + + +def _sentinel_line(found: dict[str, Any]) -> str: + if found["verdict"] == "rejects": + return "null-subject sentinel: rejects the null subject (" + ", ".join(found["subject"]) + " emptied)" + if found["verdict"] == "vacuous": + return ("null-subject sentinel: VACUOUS - the evaluator passes with " + + ", ".join(found["subject"]) + " emptied") + if found["verdict"] == "timeout": + return "null-subject sentinel: TIMEOUT - no artifact before the probe deadline; a slow evaluator proves nothing" + if found["verdict"] == "error": + return "null-subject sentinel: ERROR - the probe produced no judgeable artifact (crash or missing report)" + return {"not_bound": "null-subject sentinel: NOT BOUND - no subject path distinct from the evaluator", + "exempt": "null-subject sentinel: exempt for this check kind", + "unavailable": "null-subject sentinel: unavailable - " + found.get("detail", "unknown")}[found["verdict"]] + + +def render_doctor(report: dict[str, Any]) -> str: + lines = [f"project : {report['project']}", f"state : {report['state_root']}"] + for finding in report["findings"]: + lines.append(f" [{'ok ' if finding['ok'] else 'FAIL'}] {finding.get('prerequisite', finding['check'])}: {finding['detail']}") + lines.append("ready" if report["ok"] else "not ready") + return "\n".join(lines) + + +def render_status(report: dict[str, Any]) -> str: + lines = [f"gate: {report['gate']['verdict']} - {report['gate']['reason']}"] + for check in report["checks"]: + lines.append(f" {check['state']:<14} {check['id']} [{check['category']}] {check['inputs']['scope']}") + for component in report["formal"]: + lines.append(f" {component['state']:<14} {component['id']} [verus_source, required_api]") + if component["detail"]: + lines.append(f" {component['detail']}") + for path in report["unmapped_paths"]: + lines.append(f" no check reads {path}") + if report["needs_run"]: + lines.append("run: vkit check run --needed") + return "\n".join(lines) + + +def render_gate(report: dict[str, Any]) -> str: + lines = [f"{report['verdict']}: {report['reason']}"] + lines += [f" {c['state']:<14} {c['id']}" for c in report["checks"]] + lines += [f" {c['state']:<14} {c['id']} [formal]" for c in report.get("formal", [])] + return "\n".join(lines) + + +def render_model_compare(report: dict[str, Any]) -> str: + lines = [f"model comparison: {report['kind']} ({report['scope']})"] + for delta in report["deltas"]: + witness = delta["witness"] + lines.append(f" {delta['kind']}: {delta['removed']} removed, {delta['added']} added; " + f"{witness['side']} witness from {witness['initial_state']} " + f"in {len(witness['path'])} steps") + for step in witness["path"]: + lines.append(f" {step['source']} --{step['action']}({step['input']})--> {step['target']}") + if "probe" in witness: + probe = witness["probe"] + lines.append(f" inspect {probe['state']} with {probe['action']}({probe['input']})") + lines.append(f" difference present in {witness['side']}: {', '.join(witness['difference'])}") + if "reason" in report: + lines.append(report["reason"]) + lines.append("Explicit finite models only; no source proof or code approval.") + return "\n".join(lines) + + +def render_features(features: list[dict[str, Any]]) -> str: + lines = [] + for feature in features: + lines.append(f"[{'verified ' if feature['verified'] else 'UNVERIFIED'}] {feature['id']}: {feature['behavior']}") + lines += [f" reach: {step}" for step in feature["how_to_reach"]] + lines += [f" gap: {gap}" for gap in feature["gaps"]] + lines += [f" problem: {problem}" for problem in feature["problems"]] + return "\n".join(lines) or "no feature map" diff --git a/src/vkit/console/server.py b/src/vkit/console/server.py index a7637db..7e6dbee 100644 --- a/src/vkit/console/server.py +++ b/src/vkit/console/server.py @@ -1,36 +1,57 @@ """The local web console for remembered repository workspaces.""" from __future__ import annotations +import hashlib import json +import os import secrets import sqlite3 import sys import threading +import time import webbrowser from http import HTTPStatus from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from importlib import resources +from pathlib import Path from socketserver import TCPServer from typing import Any from urllib.parse import parse_qs, urlparse from vkit import __version__ +from vkit.console.settings import ( + DEFAULT_SETTINGS, + SETTINGS_SCHEMA, + SettingsFileError, + launcher_settings_path, + load_launcher_settings, + load_settings, + parse_launcher_settings, + parse_settings, + save_launcher_settings, + save_settings, + settings_path, +) +from vkit.console.workspaces import known_workspaces, registry_path, remember, resolve_workspace from vkit.core import query -from vkit.console.settings import (DEFAULT_SETTINGS, SETTINGS_SCHEMA, SettingsFileError, load_settings, - parse_settings, save_settings, settings_path, launcher_settings_path, - load_launcher_settings, parse_launcher_settings, save_launcher_settings) from vkit.core.categories import CATEGORIES from vkit.runtime.paths import Project, ProjectError, open_project -from vkit.console.workspaces import known_workspaces, remember, registry_path, resolve_workspace _MAX_BODY_BYTES = 1_048_576 _INVALID_BODY = object() +_SSE_POLL_SECONDS = 0.5 +_SSE_KEEPALIVE_SECONDS = 15.0 _ASSETS = { "/": ("static/console.html", "text/html; charset=utf-8"), "/console.css": ("static/console.css", "text/css; charset=utf-8"), "/console.js": ("static/console.js", "text/javascript; charset=utf-8"), + "/js/api.js": ("static/js/api.js", "text/javascript; charset=utf-8"), + "/js/ui.js": ("static/js/ui.js", "text/javascript; charset=utf-8"), + "/js/views/overview.js": ("static/js/views/overview.js", "text/javascript; charset=utf-8"), + "/js/views/execution.js": ("static/js/views/execution.js", "text/javascript; charset=utf-8"), + "/js/views/settings.js": ("static/js/views/settings.js", "text/javascript; charset=utf-8"), "/assets/material.js": ("static/assets/material.js", "text/javascript; charset=utf-8"), "/assets/theme.css": ("static/assets/theme.css", "text/css; charset=utf-8"), "/assets/icons.svg": ("static/assets/icons.svg", "image/svg+xml"), @@ -39,6 +60,41 @@ } +def _store_token(project: Project) -> str: + root = project.git_common_dir / "vkit" + candidates = ( + root, + root / "approved.json", + root / "config.json", + root / "runs", + root / "latest", + root / "proposals", + project.manifest_path, + project.root / "verification" / "features.json", + launcher_settings_path(), + ) + parts: list[str] = [] + for path in candidates: + try: + st = path.stat() + parts.append(f"{st.st_mtime_ns}:{st.st_size}") + except OSError: + parts.append("0:0") + runs_dir = root / "runs" + if runs_dir.is_dir(): + try: + entries = sorted(os.scandir(runs_dir), key=lambda entry: entry.name)[-5:] + for entry in entries: + try: + st = (Path(entry.path) / "record.json").stat() + parts.append(f"{entry.name}:{st.st_mtime_ns}:{st.st_size}") + except OSError: + parts.append(f"{entry.name}:0:0") + except OSError: + pass + return hashlib.sha256("|".join(parts).encode("utf-8")).hexdigest()[:16] + + def _catalog() -> dict[str, Any]: from vkit.mcp import BY_NAME @@ -165,7 +221,16 @@ def _post_json(self) -> Any: if size == 0: self._reject_post("request body is required", HTTPStatus.BAD_REQUEST) return _INVALID_BODY - raw = self.rfile.read(size) + timeout = self.connection.gettimeout() + try: + self.connection.settimeout(5.0) + raw = self.rfile.read(size) + except (TimeoutError, OSError): + self.close_connection = True + self._json({"error": "request body read timed out"}, HTTPStatus.REQUEST_TIMEOUT) + return _INVALID_BODY + finally: + self.connection.settimeout(timeout) if len(raw) != size: self._json({"error": "incomplete request body"}, HTTPStatus.BAD_REQUEST) return _INVALID_BODY @@ -175,6 +240,40 @@ def _post_json(self) -> Any: self._json({"error": f"invalid JSON body: {exc}"}, HTTPStatus.BAD_REQUEST) return _INVALID_BODY + def _stream_events(self, target: Project) -> None: + self.send_response(HTTPStatus.OK) + self.send_header("Content-Type", "text/event-stream; charset=utf-8") + self.send_header("Cache-Control", "no-store") + self.send_header("Connection", "close") + self.send_header("X-Content-Type-Options", "nosniff") + self.end_headers() + self.close_connection = True + shutdown_event = getattr(self.server, "_shutdown_event", None) + last_token = _store_token(target) + last_write = time.monotonic() + try: + self.wfile.write(f"event: state\ndata: {json.dumps({'token': last_token})}\n\n".encode("utf-8")) + self.wfile.flush() + while not (shutdown_event and shutdown_event.is_set()): + if shutdown_event: + if shutdown_event.wait(_SSE_POLL_SECONDS): + break + else: + time.sleep(_SSE_POLL_SECONDS) + token = _store_token(target) + now_ts = time.monotonic() + if token != last_token: + last_token = token + last_write = now_ts + self.wfile.write(f"event: state\ndata: {json.dumps({'token': token})}\n\n".encode("utf-8")) + self.wfile.flush() + elif now_ts - last_write >= _SSE_KEEPALIVE_SECONDS: + last_write = now_ts + self.wfile.write(b": keepalive\n\n") + self.wfile.flush() + except (BrokenPipeError, ConnectionResetError, OSError): + return + def do_GET(self) -> None: if not self._host_allowed(): self._json({"error": "unexpected Host header"}, HTTPStatus.FORBIDDEN) @@ -202,23 +301,35 @@ def do_GET(self) -> None: log=params.get("log", "stdout"), offset=int(params.get("offset", 0))) self._json(view if view is not None else {"error": "no such run"}, HTTPStatus.OK if view is not None else HTTPStatus.NOT_FOUND) + elif url.path == "/api/doctor": + target = self._project(selections) + self._json(query.doctor(query.open_context(target.root))) + elif url.path == "/api/events": + target = self._project(selections) + self._stream_events(target) elif url.path == "/api/config": target = self._project(selections) ctx = query.open_context(target.root) settings = load_settings(target) - self._json({**_catalog(), "doctor": query.doctor(ctx), - "description": ctx.manifest.description if ctx.manifest else "", - "definitions": ctx.manifest.entries if ctx.manifest else {}, - "settings": settings.as_json(), "settings_path": str(settings_path(target)), - "settings_schema": SETTINGS_SCHEMA, "csrf_token": csrf_token, - "launcher_settings": load_launcher_settings().as_json(), - "launcher_settings_path": str(launcher_settings_path()), - "mcp_config": {"mcpServers": {"vkit": { - "command": sys.executable, - "args": ["-m", "vkit.cli", "mcp", "serve", "--project", str(target.root), - "--exposure", settings.mcp_exposure, "--categories", - *(["all"] if settings.mcp_categories is None else settings.mcp_categories)], - }}}}) + payload: dict[str, Any] = { + **_catalog(), + "state_root": str(ctx.store.root), + "description": ctx.manifest.description if ctx.manifest else "", + "definitions": ctx.manifest.entries if ctx.manifest else {}, + "settings": settings.as_json(), "settings_path": str(settings_path(target)), + "settings_schema": SETTINGS_SCHEMA, "csrf_token": csrf_token, + "launcher_settings": load_launcher_settings().as_json(), + "launcher_settings_path": str(launcher_settings_path()), + "mcp_config": {"mcpServers": {"vkit": { + "command": sys.executable, + "args": ["-m", "vkit.cli", "mcp", "serve", "--project", str(target.root), + "--exposure", settings.mcp_exposure, "--categories", + *(["all"] if settings.mcp_categories is None else settings.mcp_categories)], + }}}, + } + if params.get("include_doctor") != "0": + payload["doctor"] = query.doctor(ctx) + self._json(payload) else: self._json({"error": "not found"}, HTTPStatus.NOT_FOUND) except SettingsFileError as exc: @@ -272,36 +383,41 @@ def do_POST(self) -> None: self._json({"settings": settings.as_json(), "settings_path": str(settings_path(target))}) return + if not isinstance(payload, dict) or set(payload) != {"name", "arguments"}: + self._json({"error": "request must contain exactly name and arguments"}, HTTPStatus.BAD_REQUEST) + return + from vkit.mcp import BY_NAME, Server + + name, arguments = payload["name"], payload["arguments"] + if not isinstance(name, str) or name not in BY_NAME: + self._json({"error": "unknown console tool"}, HTTPStatus.BAD_REQUEST) + return + if not isinstance(arguments, dict): + self._json({"error": "arguments must be an object"}, HTTPStatus.BAD_REQUEST) + return + result, is_error = Server(target.root).call(name, arguments) + self._json({"result": result, "is_error": is_error}) except (ValueError, ProjectError) as exc: self._json({"error": str(exc)}, HTTPStatus.BAD_REQUEST) - return except (OSError, sqlite3.Error) as exc: self._json({"error": str(exc)}, HTTPStatus.INTERNAL_SERVER_ERROR) - return - - if not isinstance(payload, dict) or set(payload) != {"name", "arguments"}: - self._json({"error": "request must contain exactly name and arguments"}, HTTPStatus.BAD_REQUEST) - return - from vkit.mcp import BY_NAME, Server - - name, arguments = payload["name"], payload["arguments"] - if not isinstance(name, str) or name not in BY_NAME: - self._json({"error": "unknown console tool"}, HTTPStatus.BAD_REQUEST) - return - if not isinstance(arguments, dict): - self._json({"error": "arguments must be an object"}, HTTPStatus.BAD_REQUEST) - return - result, is_error = Server(target.root).call(name, arguments) - self._json({"result": result, "is_error": is_error}) return Handler class _LoopbackServer(ThreadingHTTPServer): + def __init__(self, server_address: tuple[str, int], RequestHandlerClass: type[BaseHTTPRequestHandler]) -> None: + self._shutdown_event = threading.Event() + super().__init__(server_address, RequestHandlerClass) + def server_bind(self) -> None: TCPServer.server_bind(self) self.server_name, self.server_port = self.server_address[:2] + def shutdown(self) -> None: + self._shutdown_event.set() + super().shutdown() + def bind(project: Project, port: int) -> ThreadingHTTPServer: workspace = remember(project, "console") diff --git a/src/vkit/console/static/assets/icons.svg b/src/vkit/console/static/assets/icons.svg index 1a7ce15..ee25b64 100644 --- a/src/vkit/console/static/assets/icons.svg +++ b/src/vkit/console/static/assets/icons.svg @@ -24,4 +24,5 @@ + diff --git a/src/vkit/console/static/console.js b/src/vkit/console/static/console.js index ac099f8..979ed7e 100644 --- a/src/vkit/console/static/console.js +++ b/src/vkit/console/static/console.js @@ -1,1749 +1,172 @@ import "/assets/material.js"; +import { apiGet, apiPost, connectEvents } from "./js/api.js"; +import { $, el, empty, icon, pages, workspaceRequired } from "./js/ui.js"; +import { checks, refreshRun, runHistory, showCheck } from "./js/views/execution.js"; +import { allProposalItems, capabilities, featureMap, overview, proposals } from "./js/views/overview.js"; +import { + applySettings, + mergeSettingsDraft, + saveSettingsDraft, + setup, + syncSettingsForm, + updatePreference, +} from "./js/views/settings.js"; -const $ = (id) => document.getElementById(id); -const pages = { - overview: [ - "Overview", - "dashboard", - "YOUR WORKSPACE", - "Verification at a glance", - "What is known about your code, and where evidence is still needed.", - ], - checks: [ - "Checks", - "checks", - "REGISTERED VERIFICATION", - "Checks", - "Inspect each check, its inputs, and the scope of its evidence.", - ], - runs: [ - "Runs", - "history", - "EXECUTION HISTORY", - "Runs", - "Recorded outcomes, observations, measurements, and logs.", - ], - capabilities: [ - "Capabilities", - "extension", - "THE TOOL", - "What vkit can verify", - "Reusable verification methods, with explicit evidence and limits.", - ], - features: [ - "Feature map", - "features", - "APPLICATION COVERAGE", - "Feature map", - "What the application does, how to reach it, and which checks cover it.", - ], - proposals: [ - "Proposals", - "proposals", - "PENDING REVIEW", - "Proposals", - "Suggested checks, feature entries, and new files. Nothing is applied here.", - ], - setup: [ - "Setup & tools", - "settings", - "PROJECT CONFIGURATION", - "Setup & tools", - "Project configuration, tool availability, and connection details.", - ], -}; -const methods = { - scenario: [ - "Scenarios", - "checks", - "Run a reusable driver against named behaviors and collect its observations and measurements.", - "Evidence covers the cases actually run. Performance budgets apply when declared.", - ], - pytest: [ - "Python tests", - "code", - "Execute the required pytest tests and record each test’s outcome.", - "Required tests must run. Missing or skipped tests cannot establish a pass.", - ], - node_test: [ - "Node tests", - "code", - "Execute named Node tests and interpret the runner’s structured report.", - "Evidence is limited to the required tests and inputs exercised.", - ], - property: [ - "Property tests", - "science", - "Search generated cases with Hypothesis for disagreement with an expected property or reference model.", - "Sampling can find counterexamples; it does not prove the property for every input.", - ], - static: [ - "Static analysis", - "rule", - "Read analyzer findings and compare them with an accepted baseline.", - "A pass means no new reported findings, not an absence of all possible defects.", - ], - lean: [ - "Lean proofs", - "security", - "Check formal statements with Lean and audit axioms. Agent-written proofs use comparator against frozen statements.", - "The result applies to the formal statements. It needs a separate connection to application behavior.", - ], - tlc: [ - "Finite model checking", - "features", - "Explore a finite TLA+ model with TLC and check the declared properties.", - "The result applies to that model and its recorded bounds. It does not verify the implementation.", - ], -}; -const labels = { - fresh_pass: ["Passed", "success"], - fresh_fail: ["Failed", "error"], - fresh_blocked: ["Blocked", "warning"], - stale: ["Stale", "warning"], - missing: ["Not run", ""], - not_approved: ["Not accepted", "warning"], - running: ["Running", "info"], - starting: ["Starting", "info"], - done: ["Finished", ""], - interrupted: ["Interrupted", "warning"], - PASS: ["Pass", "success"], - FAIL: ["Fail", "error"], - BLOCKED: ["Blocked", "warning"], - READY: ["Ready", "success"], - REJECTED: ["Rejected", "error"], - verified: ["Verified", "success"], - unverified: ["Unverified", "warning"], - UNKNOWN: ["Unknown", "warning"], - UNAVAILABLE: ["Unavailable", "warning"], - UNSUPPORTED: ["Unsupported", "warning"], - COUNTEREXAMPLE: ["Counterexample", "warning"], - BREAKING: ["Breaking", "warning"], - INFEASIBLE: ["Infeasible", "warning"], -}; -let report, - runs = [], - configuration, - workspaceRegistry, - workspaceSummary = [], - workspaceSummaryReady = false, - activeWorkspace = "", - workspaceVisited = false, - csrfToken = "", - workspaceSaving = false, - signature = "", - refreshing, - selectedRun = null, - stream = "stdout"; -let search = "", - kind = "", - activePage = "", - settingsVersion = 0, - settingsDraft = null, - settingsMessage = "", - settingsSaving = false, - execution = { +const state = { + report: null, + runs: [], + configuration: null, + doctorReport: null, + doctorLoading: false, + workspaceRegistry: null, + workspaceSummary: [], + workspaceSummaryReady: false, + activeWorkspace: "", + workspaceVisited: false, + csrfToken: "", + workspaceSaving: false, + signature: "", + refreshing: null, + selectedRun: null, + stream: "stdout", + search: "", + kind: "", + activePage: "", + settingsVersion: 0, + settingsDraft: null, + settingsMessage: "", + settingsSaving: false, + launcherDraft: null, + launcherMessage: "", + launcherSaving: false, + execution: { pending: new Set(), checksMessage: "", runsMessage: "", - }; + }, +}; -function el(tag, text, cls) { - const node = document.createElement(tag); - if (text != null) node.textContent = text; - if (cls) node.className = cls; - return node; -} -function icon(name, cls = "icon") { - const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); - svg.setAttribute("class", cls); - svg.setAttribute("aria-hidden", "true"); - svg.setAttribute("viewBox", "0 0 24 24"); - const use = document.createElementNS(svg.namespaceURI, "use"); - use.setAttribute("href", `/assets/icons.svg#${name}`); - svg.append(use); - return svg; -} -function badge(state) { - const [label, tone] = labels[state] || [state || "No result", ""]; - return el("span", label, `status-badge ${tone}`); -} -function link(text, action) { - const button = el("md-text-button", text, "text-link"); - button.type = "button"; - button.onclick = action; - return button; -} -function workspaceUrl(url, workspace = activeWorkspace) { - const target = new URL(url, window.location.origin); - if (workspace) target.searchParams.set("workspace", workspace); - else target.searchParams.delete("workspace"); - return `${target.pathname}${target.search}${target.hash}`; -} -function action(text, page, type = "md-text-button") { - const button = el(type, text); - button.onclick = () => { - location.hash = page; - }; - return button; -} -function consoleButton(text, tone = "tonal") { - const types = { - primary: "md-filled-button", - tonal: "md-filled-tonal-button", - text: "md-text-button", - outlined: "md-outlined-button", - }, - button = el(types[tone] || types.tonal, text); - button.type = "button"; - return button; -} -function selectOption(value, headline, selected = false) { - const option = el("md-select-option"), - text = el("span", headline); - option.value = value; - if (selected) option.setAttribute("selected", ""); - text.slot = "headline"; - option.append(text); - return option; -} -function selectControl(label, values, selected) { - const control = el("md-outlined-select"); - control.label = label; - control.menuPositioning = "fixed"; - for (const [value, headline] of values) - control.append(selectOption(value, headline, value === selected)); - control.value = selected; - return control; -} -function textField(label, value, type = "text", supportingText = "") { - const control = el("md-outlined-text-field"); - control.label = label; - control.type = type; - control.value = value ?? ""; - control.supportingText = supportingText; - return control; -} -function panel(title, description, children, button) { - const box = el("section", null, "panel"), - header = el("div", null, "panel-header"), - copy = el("div"); - copy.append(el("h2", title)); - if (description) copy.append(el("p", description)); - header.append(copy); - if (button) header.append(button); - box.append(header, ...children); - return box; -} -function empty(title, description, symbol = "info") { - const box = el("div", null, "empty-state"); - box.append(icon(symbol), el("h3", title), el("p", description)); - return box; -} -function note(title, text) { - const box = el("div", null, "scope-note"); - box.append(el("strong", title), el("p", text)); - return box; -} -function date(value) { - return value - ? new Date(value).toLocaleString(undefined, { - month: "short", - day: "numeric", - hour: "2-digit", - minute: "2-digit", - }) - : "Not recorded"; -} -function row(cells) { - const tr = el("tr"); - for (const value of cells) { - const td = el("td"); - td.append( - value instanceof Node ? value : document.createTextNode(value ?? ""), - ); - tr.append(td); - } - return tr; -} -function table(headers, name) { - const wrap = el("div", null, "panel table-scroll"), - grid = el("table"), - head = el("thead"), - hr = el("tr"), - body = el("tbody"); - grid.setAttribute("aria-label", name); - for (const name of headers) { - const th = el("th", name); - th.scope = "col"; - hr.append(th); - } - head.append(hr); - grid.append(head, body); - wrap.append(grid); - return { wrap, body }; -} -function toolbar(placeholder, update, withKind = false) { - const bar = el("div", null, "toolbar"), - input = textField(placeholder, search, "search"); - input.className = "view-search"; - input.id = "view-search"; - input.oninput = () => { - search = input.value; - update(); - }; - input.append(icon("search", "icon")); - input.lastChild.slot = "leading-icon"; - bar.append(input); - if (withKind) { - const select = selectControl( - "Verification method", - [["", "All methods"], ...Object.entries(methods).map(([key, value]) => [key, value[0]])], - kind, - ); - select.onchange = () => { - kind = select.value; - update(); - }; - bar.append(select); - } - return bar; -} -function matches(value) { - return JSON.stringify(value).toLowerCase().includes(search.toLowerCase()); -} -function checkState(check) { - return check.running.length ? "running" : check.state; -} -function checkRow(check) { - const box = el("div", null, "check-row"), - symbol = el("div", null, "kind-icon"), - copy = el("div", null, "row-copy"); - symbol.append(icon(methods[check.kind]?.[1] || "checks")); - copy.append( - link(check.id, () => showCheck(check.id)), - el( - "p", - `${methods[check.kind]?.[0] || check.kind} · ${check.inputs.scope}`, - ), - ); - box.append(symbol, copy, badge(checkState(check))); - return box; -} -function isManifestMissing(error) { - return typeof error === "string" && error.startsWith("no manifest at "); -} -function activityRow(run) { - const box = el("div", null, "activity-row"), - copy = el("div", null, "row-copy"); - copy.append( - link(run.subject?.id || run.check_id, () => { - location.hash = `runs/${encodeURIComponent(run.run_id)}`; - }), - el("p", date(run.ended_at || run.started_at)), - ); - box.append(copy, badge(run.result || run.state)); - return box; -} -function formalPanel() { - return panel( - "Formal components", - "Required API contracts checked by Verus under the recorded trusted engine. Each pass covers its declared component.", - report.formal.map((component) => { - const row = el("div", null, "check-row"), copy = el("div", null, "row-copy"); - copy.append(el("strong", component.id), el("p", component.detail || component.description)); - if (component.last) copy.append(action("Inspect last run", `runs/${encodeURIComponent(component.last.run_id)}`)); - row.append(copy, badge(checkState(component))); - return row; - }), - ); -} -function projectOverview() { - const fragment = document.createDocumentFragment(), - banner = el("section", null, "verdict-banner"); - banner.dataset.verdict = report.gate.verdict; - const symbol = el("div", null, "verdict-icon"); - symbol.append( - icon( - report.gate.verdict === "READY" - ? "check" - : report.gate.verdict === "REJECTED" - ? "error" - : "schedule", - ), - ); - const copy = el("div", null, "verdict-copy"); - const titles = { - READY: "Current evidence is ready", - REJECTED: "A current check failed", - BLOCKED: isManifestMissing(report.manifest_error) ? "Not set up" : "Evidence is incomplete", - }; - copy.append( - el("h2", titles[report.gate.verdict]), - el("p", report.manifest_error || report.gate.reason), - ); - banner.append( - symbol, - copy, - isManifestMissing(report.manifest_error) - ? action("Set up workspace", "setup", "md-filled-tonal-button") - : action("Inspect checks", "checks", "md-filled-tonal-button"), - ); - fragment.append(banner); - const metrics = el("div", null, "metrics"); - const passed = report.checks.filter((c) => c.state === "fresh_pass").length; - const running = new Set(report.checks.flatMap((c) => c.running)).size; - for (const [value, label, description] of [ - [report.checks.length, "Registered checks", "Defined for this workspace"], - [passed, "Current passes", "Against the current inputs"], - [running, "Active runs", "Visible in recent history"], - [ - report.features.filter((f) => f.verified).length, - "Verified features", - `${report.features.length} mapped features`, - ], - ]) { - const metric = el("div", null, "metric"); - metric.append( - el("span", value, "metric-value"), - el("span", label, "metric-label"), - el("span", description, "metric-note"), - ); - metrics.append(metric); - } - fragment.append(metrics); - if (report.formal?.length) fragment.append(formalPanel()); - const grid = el("div", null, "overview-grid"), - left = el("div", null, "stack"), - right = el("div", null, "stack"); - const attention = report.checks.filter((c) => c.state !== "fresh_pass"); - left.append( - panel( - "Evidence to review", - `${attention.length} of ${report.checks.length} checks lack a current pass`, - attention.length - ? attention.slice(0, 6).map(checkRow) - : [ - empty( - report.checks.length - ? "Every check has current evidence" - : "No checks registered", - report.checks.length - ? "Inspect individual checks to see what each pass establishes." - : "Register reusable checks in verification/manifest.json.", - "check", - ), - ], - action("All checks", "checks"), - ), - ); - left.append( - panel( - "Recent activity", - "Latest recorded executions", - runs.length - ? runs.slice(0, 4).map(activityRow) - : [ - empty( - "No recorded runs", - "Run history will show outcomes, observations, and logs once a check executes.", - "history", - ), - ], - action("Run history", "runs"), - ), - ); - const body = el("div", null, "panel-body"), - steps = el("ol", null, "steps"); - [ - [ - "Define", - "A check names its inputs, procedure, and required observations.", - ], - ["Execute", "Vkit handles the registered procedure and reads its report."], - ["Record", "Results retain their inputs, scope, measurements, and logs."], - ["Check freshness", "Relevant file changes make earlier evidence stale."], - ].forEach(([title, text], i) => { - const step = el("li"), - textBox = el("div"); - textBox.append(el("h3", title), el("p", text)); - step.append(el("span", i + 1, "step-number"), textBox); - steps.append(step); - }); - body.append( - steps, - note( - "What “ready” means", - "Every registered check passed against its current inputs. Features without checks and behavior outside those requirements remain unverified.", - ), - ); - right.append( - panel("How verification works", "Reusable procedures. Recorded evidence.", [ - body, - ]), - ); - const methodsBody = el("div", null, "panel-body"); - methodsBody.append( - el( - "p", - `${new Set(report.checks.map((c) => c.kind)).size} of ${Object.keys(methods).length} verification methods are configured in this workspace.`, - "small quiet", - ), - action("Explore capabilities", "capabilities"), - ); - right.append( - panel( - "Verification methods", - "From application scenarios to formal statements", - [methodsBody], - ), - ); - grid.append(left, right); - fragment.append(grid); - return fragment; -} -function workspaceHref(id, page) { - const target = new URL(window.location.href); - target.searchParams.set("workspace", id); - target.hash = page; - return `${target.pathname}${target.search}${target.hash}`; -} -function workspaceAnchor(text, id, page, cls = "") { - const anchor = el("a", text, cls); - anchor.href = workspaceHref(id, page); - return anchor; -} -function workspaceLabel(workspace) { - return workspace?.name || workspace?.path || "Unknown workspace"; +let eventSource = null; +let eventWorkspace = ""; + +const systemTheme = matchMedia("(prefers-color-scheme: dark)"); +let themePreference = "system"; + +function applyTheme(preference) { + themePreference = preference; + const mode = preference === "system" ? (systemTheme.matches ? "dark" : "light") : preference; + document.documentElement.dataset.theme = mode; + const next = mode === "dark" ? "light" : "dark"; + $("theme-icon").setAttribute("href", `/assets/icons.svg#${next}`); + $("theme-toggle").setAttribute("aria-label", `Switch to ${next} theme`); + $("theme-toggle").title = `Switch to ${next} theme`; } -function proposalCard(proposal, workspace) { - const entry = el("article", null, "proposal"), - changes = el("div", null, "check-chips"), - targets = workspace.workspaces || [workspace], - primary = targets[0]; - entry.append( - el("code", (proposal.digest || "").slice(0, 12), "quiet"), - el("h3", proposal.rationale || "Suggested project changes"), - el("p", targets.length > 1 - ? `Pending in ${targets.length} worktrees for this repository. Choose where to review it.` - : `${workspaceLabel(primary)} · ${primary?.path || ""}`, "small quiet"), + +function collapse(collapsed) { + document.body.classList.toggle("nav-collapsed", collapsed); + $("collapse-nav").setAttribute("aria-expanded", String(!collapsed)); + $("collapse-nav").setAttribute( + "aria-label", + collapsed ? "Expand sidebar" : "Collapse sidebar", ); - for (const [label, values] of [ - ["Checks", proposal.checks || []], - ["Features", proposal.features || []], - ["New files", proposal.files || []], - ]) - if (values.length) - changes.append(el("span", `${label}: ${values.join(", ")}`, "small quiet")); - entry.append(changes); - const links = el("div", null, "workspace-proposal-links"); - for (const target of targets) - links.append(workspaceAnchor(`Open in ${workspaceLabel(target)}`, target.id, "proposals", "workspace-open-link")); - entry.append(links); - return entry; -} -function allProposalItems() { - const items = new Map(); - for (const workspace of workspaceSummary) { - for (const proposal of workspace.pending_proposals || []) { - const key = `${workspace.repository_id || workspace.id}:${proposal.digest}`; - const item = items.get(key) || { proposal, workspace, workspaces: [] }; - item.workspaces.push(workspace); - items.set(key, item); - } - } - return [...items.values()]; } -function allProposalList(items = allProposalItems(), className = "panel") { - const list = el("section", null, className); - if (!items.length) { - list.append(empty( - "No pending proposals", - "Proposals appear here after an agent submits changes for a remembered workspace.", - "proposals", - )); - return list; - } - for (const item of items) - list.append(proposalCard(item.proposal, item)); - return list; -} -function allOverview() { - const fragment = document.createDocumentFragment(), - total = workspaceSummary.length, - available = workspaceSummary.filter((workspace) => workspace.available), - ready = available.filter((workspace) => workspace.gate?.verdict === "READY").length, - pending = allProposalItems(), - checks = workspaceSummary.reduce((count, workspace) => count + (workspace.checks?.length || 0), 0), - metrics = el("div", null, "metrics"); - for (const [value, label, description] of [ - [total, "Remembered workspaces", `${available.length} available`], - [ready, "Ready workspaces", "Current required evidence passes"], - [checks, "Registered checks", "Across remembered workspaces"], - [pending.length, "Pending proposals", "Waiting for project review"], - ]) { - const metric = el("div", null, "metric"); - metric.append(el("span", value, "metric-value"), el("span", label, "metric-label"), el("span", description, "metric-note")); - metrics.append(metric); - } - fragment.append(metrics); - const workspaceList = el("div", null, "workspace-list"); - for (const workspace of workspaceSummary) { - const row = el("article", null, "workspace-summary-row"), - copy = el("div", null, "row-copy"), - gate = workspace.available ? workspace.gate?.verdict || "BLOCKED" : "UNAVAILABLE", - seen = workspace.last_seen - ? ` · Last seen ${date(workspace.last_seen)} via ${workspace.source || "VKit"}` - : ""; - copy.append(el("h3", workspaceLabel(workspace)), el("p", `${workspace.path || ""}${seen}`, "small quiet")); - if (!workspace.available) - copy.append(el("p", workspace.error || "This path is unavailable. Add the workspace again after moving it.", "small quiet")); - else if (isManifestMissing(workspace.manifest_error)) - copy.append(el("p", "Not set up. Add verification/manifest.json to register checks.", "small quiet")); - else if (workspace.manifest_error) - copy.append(el("p", `Manifest needs attention: ${workspace.manifest_error}`, "small quiet")); - else - copy.append(el("p", `${workspace.checks?.filter((check) => check.state === "fresh_pass").length || 0} of ${workspace.checks?.length || 0} checks have current passing evidence.`, "small quiet")); - row.append(copy, badge(gate), workspaceAnchor("Open", workspace.id, "overview", "workspace-open-link")); - workspaceList.append(row); - } - if (!total) - workspaceList.append(empty("No workspaces remembered", "Add a repository path in the left panel. VKit remembers only paths you open or add; it does not scan folders.", "folder")); - fragment.append(panel("Workspaces", "Each workspace keeps its own checks, evidence, settings, and proposals.", [workspaceList])); - fragment.append(panel("Pending proposal inbox", "Review each proposal in the workspace that owns it.", [allProposalList(pending.slice(0, 5), "proposal-list"), ...(pending.length > 5 ? [workspaceAnchor("View all proposals", "all", "proposals", "workspace-open-link")] : [])])); - return fragment; -} -function overview() { - return activeWorkspace === "all" ? allOverview() : projectOverview(); -} -function checkRunMessage(response) { - if (response.is_error) - return `Check run request failed: ${response.result?.error || "vkit rejected the request."}`; - const started = response.result?.runs || []; - return started.length - ? `Returned ${started.length} run${started.length === 1 ? "" : "s"}. Check their states in Runs.` - : "No checks needed a run."; -} -async function runChecks(arguments_) { - if (execution.pending.has("check_run")) return; - execution.pending.add("check_run"); - execution.checksMessage = "Starting check run…"; - render(); - try { - execution.checksMessage = checkRunMessage( - await callTool("check_run", arguments_), - ); - } catch (error) { - execution.checksMessage = `Check run request failed: ${error.message}`; - } finally { - execution.pending.delete("check_run"); - render(); - refresh().catch(showError); - } + +function showError(error) { + $("connection-error").hidden = false; + $("connection-error").textContent = + `Unable to refresh: ${error.message}. Showing the last received evidence.`; + document.body.classList.add("disconnected"); } -function cancelRunMessage(runId, response) { - if (response.is_error) - return `Could not cancel ${runId}: ${response.result?.error || "vkit rejected the request."}`; - return response.result?.cancelled - ? `Cancellation requested for ${runId}.` - : `${runId} is ${response.result?.state || "no longer running"}.`; + +function showWorkspaceUnavailable(message) { + $("page-eyebrow").textContent = "WORKSPACE"; + $("page-title").textContent = "Workspace unavailable"; + $("page-description").textContent = "Choose a remembered workspace or add its current repository path in the left panel."; + $("view").replaceChildren(empty("Select another workspace", message)); } -async function cancelRun(runId) { - const key = `run_cancel:${runId}`; - if (execution.pending.has(key)) return; - execution.pending.add(key); - execution.runsMessage = `Cancelling ${runId}…`; - render(); + +async function loadDoctor() { + if (state.doctorLoading || !state.activeWorkspace || state.activeWorkspace === "all") return; + const workspace = state.activeWorkspace; + state.doctorLoading = true; try { - execution.runsMessage = cancelRunMessage( - runId, - await callTool("run_cancel", { run_id: runId }), - ); - } catch (error) { - execution.runsMessage = `Could not cancel ${runId}: ${error.message}`; - } finally { - execution.pending.delete(key); - render(); - refresh().catch(showError); - } -} -function checks() { - const fragment = document.createDocumentFragment(), - grid = table( - ["CHECK", "STATE", "METHOD", "INPUT SCOPE", "LAST RUN", "ACTION"], - "checks", - ); - const runNeeded = consoleButton("Run needed checks"); - runNeeded.disabled = - execution.pending.has("check_run") || !report.needs_run?.length; - const feedback = el("p", execution.checksMessage, "action-feedback"); - feedback.setAttribute("role", "status"); - feedback.setAttribute("aria-live", "polite"); - feedback.hidden = !execution.checksMessage; - const feedbackBody = el("div", null, "panel-body"); - feedbackBody.append(feedback); - const runPanel = panel( - "Run needed checks", - "Start checks with stale or missing evidence. Each run records its own scope.", - [feedbackBody], - runNeeded, - ); - runNeeded.onclick = () => runChecks({ needed: true, wait_seconds: 0 }); - function update() { - const shown = report.checks.filter( - (c) => matches(c) && (!kind || c.kind === kind), - ); - grid.body.replaceChildren( - ...shown.map((c) => { - const copy = el("div"); - copy.append( - link(c.id, () => showCheck(c.id)), - el("p", c.description), - ); - const last = c.last - ? link(`${c.last.result} · ${date(c.last.ended_at)}`, () => { - location.hash = `runs/${encodeURIComponent(c.last.run_id)}`; - }) - : "Not run"; - const run = consoleButton( - c.running.length ? "Running" : "Run", - "text", - ); - run.setAttribute("aria-label", `Run check ${c.id}`); - run.disabled = - c.running.length > 0 || execution.pending.has("check_run"); - run.onclick = () => - runChecks({ check_ids: [c.id], wait_seconds: 0 }); - return row([ - copy, - badge(checkState(c)), - methods[c.kind]?.[0] || c.kind, - c.inputs.scope, - last, - run, - ]); - }), - ); - if (!shown.length) { - const tr = el("tr"), - td = el("td"); - td.colSpan = 6; - td.append( - empty( - "No matching checks", - report.checks.length - ? "Try another search or verification method." - : "This workspace has no registered checks.", - "checks", - ), - ); - tr.append(td); - grid.body.append(tr); - } - } - fragment.append( - runPanel, - toolbar("Search checks", update, true), - grid.wrap, - ); - update(); - if (report.formal?.length) fragment.append(formalPanel()); - return fragment; -} -function runHistory() { - const fragment = document.createDocumentFragment(), - grid = table( - ["CHECK / RUN", "RESULT", "STARTED", "WORKTREE", "ACTION"], - "runs", - ); - const feedback = el("p", execution.runsMessage, "action-feedback run-feedback"); - feedback.setAttribute("role", "status"); - feedback.setAttribute("aria-live", "polite"); - feedback.hidden = !execution.runsMessage; - function update() { - const shown = runs.filter(matches); - grid.body.replaceChildren( - ...shown.map((r) => { - const copy = el("div"); - copy.append( - link(r.subject?.id || r.check_id, () => { - location.hash = `runs/${encodeURIComponent(r.run_id)}`; - }), - el("p", r.run_id), - ); - const cancel = consoleButton( - execution.pending.has(`run_cancel:${r.run_id}`) - ? "Cancelling…" - : "Cancel", - "text", - ); - cancel.setAttribute("aria-label", `Cancel run ${r.run_id}`); - cancel.disabled = - r.state !== "running" || - execution.pending.has(`run_cancel:${r.run_id}`); - cancel.onclick = () => cancelRun(r.run_id); - return row([ - copy, - badge(r.result || r.state), - date(r.started_at), - r.worktree, - cancel, - ]); - }), - ); - if (!shown.length) { - const tr = el("tr"), - td = el("td"); - td.colSpan = 5; - td.append( - empty( - "No matching runs", - runs.length - ? "Try another search." - : "Completed and active runs appear here when checks execute.", - "history", - ), - ); - tr.append(td); - grid.body.append(tr); - } - } - const detail = el("section", null, "panel run-selected"); - detail.id = "run-detail"; - detail.hidden = !selectedRun; - fragment.append( - feedback, - toolbar("Search recent runs", update), - grid.wrap, - detail, - ); - update(); - return fragment; -} -function capabilities() { - const fragment = document.createDocumentFragment(), - list = el("section", null, "panel"); - for (const [key, [title, symbol, text, limit]] of Object.entries(methods)) { - const entry = el("div", null, "capability"), - visual = el("div", null, "kind-icon"), - copy = el("div"); - visual.append(icon(symbol)); - copy.append(el("h3", title), el("p", text), el("p", limit, "limit")); - const count = activeWorkspace === "all" - ? workspaceSummary.filter((workspace) => (workspace.checks || []).some((check) => check.kind === key)).length - : report.checks.filter((c) => c.kind === key).length; - entry.append( - visual, - copy, - el( - "span", - count - ? activeWorkspace === "all" - ? `${count} workspace${count === 1 ? "" : "s"}` - : `${count} check${count === 1 ? "" : "s"} registered` - : "No checks registered", - "capability-count", - ), - ); - list.append(entry); - } - fragment.append( - list, - el("h2", "Functions available to agents", "section-label"), - ); - const tools = el("div", null, "tool-grid"), - managedTools = activeWorkspace === "all" - ? workspaceRegistry?.managed_tools || [] - : configuration?.managed_tools || []; - for (const { name, description, category } of managedTools) { - const item = el("div", null, "tool-item"); - item.append(el("code", name), el("p", description), el("p", category || "", "small quiet")); - tools.append(item); - } - if (!managedTools.length) - tools.append(el("p", "The workspace registry has no function catalog yet.", "small quiet")); - fragment.append( - panel( - `${managedTools.length} functions in this installation`, - activeWorkspace === "all" - ? "Functions come from this VKit installation. Project settings and agent exposure can change which ones are available in a workspace." - : "These functions come from this console's VKit installation. Workspace settings can limit which functions agents can use.", - [tools], - ), - ); - return fragment; -} -function featureMap() { - const fragment = document.createDocumentFragment(), - list = el("section", null, "panel"); - function update() { - const opened = new Set( - [...list.querySelectorAll("details[open]")].map((d) => d.dataset.feature), - ); - const shown = report.features.filter(matches); - list.replaceChildren( - ...shown.map((f) => { - const entry = el("details", null, "feature-row"); - entry.dataset.feature = f.id; - entry.open = opened.has(f.id); - const summary = el("summary"), - copy = el("div", null, "row-copy"); - copy.append(el("h3", f.id), el("p", f.behavior)); - summary.append( - copy, - badge(f.verified ? "verified" : "unverified"), - icon("expand"), - ); - const content = el("div", null, "feature-content"), - grid = el("div", null, "detail-grid"); - for (const [title, lines] of [ - ["How to reach it", f.how_to_reach], - ["Entry points", f.entry_points], - ]) { - const section = el("div", null, "detail-section"), - ul = el("ul"); - for (const text of lines) ul.append(el("li", text)); - section.append( - el("h3", title), - lines.length ? ul : el("p", "Not documented", "small quiet"), - ); - grid.append(section); - } - content.append(grid); - const coverage = el("div", null, "dialog-section"), - chips = el("div", null, "check-chips"); - for (const c of f.checks) { - const button = link( - `${c.id} · ${labels[c.state]?.[0] || c.state}`, - () => showCheck(c.id), - ); - chips.append(button); - } - coverage.append( - el("h3", "Covering checks"), - f.checks.length - ? chips - : el("p", "No check covers this feature.", "small quiet"), - ); - content.append(coverage); - if (f.gaps.length || f.problems.length) - content.append( - note("Known gaps", [...f.gaps, ...f.problems].join(" · ")), - ); - entry.append(summary, content); - return entry; - }), - ); - if (!shown.length) - list.append( - empty( - "No matching features", - report.feature_error || - (report.features.length - ? "Try another search." - : "The feature map is authored in verification/features.json. Add user-visible behavior, how to reach it, entry points, and the checks that cover it."), - "features", - ), - ); - } - fragment.append(toolbar("Search features", update), list); - update(); - return fragment; -} -function command(text, label = "command") { - const box = el("div", null, "command-line"), - button = el("md-icon-button"); - button.setAttribute("aria-label", "Copy " + label); - button.title = "Copy " + label; - button.append(icon("copy")); - button.onclick = async () => { - try { - await navigator.clipboard.writeText(text); - button.setAttribute("aria-label", "Copied"); - button.replaceChildren(icon("check")); - } catch { - button.setAttribute( - "aria-label", - "Copy unavailable; select the " + label + " text", - ); - button.title = "Select and copy the " + label + " text"; + const result = await apiGet("/api/doctor", workspace); + if (workspace === state.activeWorkspace) { + state.doctorReport = result; + if (state.activePage === "setup") render(); } - }; - box.append(el("code", text), button); - return box; -} -function projectProposals() { - const list = el("section", null, "panel"); - for (const p of report.proposals) { - const entry = el("article", null, "proposal"); - entry.append( - el("code", p.digest.slice(0, 12), "quiet"), - el("h3", p.rationale), - ); - const changes = el("div", null, "check-chips"); - for (const [label, values] of [ - ["Checks", p.checks], - ["Features", p.features], - ["New files", p.files], - ]) - if (values.length) - changes.append( - el("span", `${label}: ${values.join(", ")}`, "small quiet"), - ); - entry.append(changes, command(p.accept)); - list.append(entry); - } - if (!report.proposals.length) - list.append( - empty( - "No proposals waiting for review", - "Agents can suggest reusable checks and verification rules. Suggested changes appear here before they are accepted.", - "proposals", - ), - ); - return list; -} -function proposals() { - return activeWorkspace === "all" ? allProposalList() : projectProposals(); -} -function mergeSettingsDraft(draft, next, previous) { - return Object.fromEntries(Object.keys(next).map((key) => [key, - !draft || JSON.stringify(draft[key]) === JSON.stringify(previous?.[key]) - ? next[key] : draft[key], - ])); -} -function setPreferenceFeedback(message) { - const status = $("preference-feedback"); - status.hidden = !message; - status.textContent = message; -} -function enabledToolsSummary() { - const tools = configuration.managed_tools, - enabled = tools.filter(toolAvailable).length; - return `${enabled} of ${tools.length} tools enabled. Help and compact invocation remain available.`; -} -function toolAvailable(tool) { - return !settingsDraft.disabled_tools.includes(tool.name) - && !settingsDraft.disabled_categories.includes(tool.category); -} -function syncSettingsForm() { - for (const id of ["settings-message", "tools-message"]) { - const status = $(id); - if (!status) continue; - status.textContent = settingsMessage; - status.dataset.state = settingsMessage.startsWith("Could not") ? "error" : ""; - } - const summary = $("settings-tools-summary"); - if (summary && configuration && settingsDraft) - summary.textContent = enabledToolsSummary(); - for (const checkbox of document.querySelectorAll("#tools-body [data-tool]")) { - checkbox.checked = !settingsDraft.disabled_tools.includes(checkbox.dataset.tool); - checkbox.disabled = settingsSaving || settingsDraft.disabled_categories.includes(checkbox.dataset.category); - } - for (const checkbox of document.querySelectorAll("#tools-body [data-category-toggle]")) { - checkbox.checked = !settingsDraft.disabled_categories.includes(checkbox.dataset.categoryToggle); - checkbox.disabled = settingsSaving; - } - for (const checkbox of document.querySelectorAll("#tools-body [data-scope]")) { - checkbox.checked = settingsDraft.mcp_categories === null || settingsDraft.mcp_categories.includes(checkbox.dataset.scope); - checkbox.disabled = settingsSaving || settingsDraft.mcp_categories === null; - } - for (const count of document.querySelectorAll("#tools-body [data-category-count]")) { - const tools = configuration.managed_tools.filter((tool) => tool.category === count.dataset.categoryCount); - count.textContent = `${tools.filter(toolAvailable).length} of ${tools.length} tools available`; - } - const allScope = $("all-agent-categories"); - if (allScope) { - allScope.checked = settingsDraft.mcp_categories === null; - allScope.disabled = settingsSaving; - } - $("save-tools-settings").disabled = settingsSaving; - const save = $("settings-save"), - reset = $("settings-reset"); - if (save) save.disabled = settingsSaving; - if (reset) reset.disabled = settingsSaving; - if ($("theme-toggle")) $("theme-toggle").disabled = !configuration || settingsSaving; - if ($("collapse-nav")) $("collapse-nav").disabled = !configuration || settingsSaving; -} -function applySettings(settings) { - if (!settings) return; - applyTheme(settings.theme); - collapse(settings.sidebar_collapsed); -} -function validateSettingsDraft() { - if (!settingsDraft || !["system", "light", "dark"].includes(settingsDraft.theme)) - return "Choose system, light, or dark theme."; - for (const [key, label, minimum, maximum] of [ - ["refresh_seconds", "Refresh interval", 1, 60], - ["history_limit", "Run history limit", 1, 200], - ]) { - const value = settingsDraft[key]; - if (!Number.isInteger(value) || value < minimum || value > maximum) - return `${label} must be between ${minimum} and ${maximum}.`; - } - return ""; -} -async function persistSettings(candidate, source = "form") { - if (settingsSaving) return; - const previous = { ...configuration.settings }, - draftAtRequest = { ...settingsDraft }, - snapshot = { ...candidate }; - settingsSaving = true; - settingsMessage = source === "reset" ? "Resetting defaults…" : "Saving settings…"; - if (source === "preference") setPreferenceFeedback(settingsMessage); - syncSettingsForm(); - try { - const response = await post("/api/settings", snapshot); - configuration.settings = response.settings; - configuration.settings_path = response.settings_path; - settingsVersion += 1; - settingsDraft = Object.fromEntries( - Object.keys(configuration.settings_defaults).map((key) => [ - key, - JSON.stringify(settingsDraft[key]) !== JSON.stringify(draftAtRequest[key]) - ? settingsDraft[key] - : source === "preference" && JSON.stringify(draftAtRequest[key]) !== JSON.stringify(previous[key]) - ? draftAtRequest[key] - : response.settings[key], - ]), - ); - applySettings(settingsDraft); - const hasUnsavedChanges = Object.keys(response.settings).some( - (key) => JSON.stringify(settingsDraft[key]) !== JSON.stringify(response.settings[key]), - ); - settingsMessage = hasUnsavedChanges - ? "Settings saved. Unsaved changes remain." - : source === "reset" - ? "Defaults saved." - : "Settings saved."; - if (source === "preference") setPreferenceFeedback(settingsMessage); - } catch (error) { - settingsMessage = `Could not save settings: ${error.message}`; - if (source === "preference") setPreferenceFeedback(settingsMessage); } finally { - settingsSaving = false; - syncSettingsForm(); - refresh().catch(showError); - } -} -function saveSettingsDraft() { - const error = validateSettingsDraft(); - if (error) { - settingsMessage = `Could not save settings: ${error}`; - syncSettingsForm(); - return; + state.doctorLoading = false; } - persistSettings(settingsDraft); } -function resetSettings() { - settingsDraft = { ...configuration.settings_defaults }; - settingsMessage = "Resetting defaults…"; - applySettings(settingsDraft); - render(); - persistSettings(settingsDraft, "reset"); -} -function updatePreference(key, value) { - if (!configuration || settingsSaving) return; - settingsDraft = { ...settingsDraft, [key]: value }; - applySettings(settingsDraft); - persistSettings({ ...configuration.settings, [key]: value }, "preference"); -} -function showTools() { - const tools = configuration.managed_tools, - title = "Tools available to agents", - search = textField("Search tools", "", "search"), - list = el("div", null, "tools-list"), - count = el("p", null, "small quiet"), - status = el("p", settingsMessage, "settings-message"), - category = selectControl("Category", [["", "All categories"], - ...configuration.categories.filter((group) => tools.some((tool) => tool.category === group.id)) - .map((group) => [group.id, group.label])], ""); - search.id = "tools-search"; - search.setAttribute("autofocus", ""); - count.setAttribute("role", "status"); - status.id = "tools-message"; - status.setAttribute("role", "status"); - const filter = () => { - const query = search.value.trim().toLowerCase(), - matches = tools.filter((tool) => - (!category.value || tool.category === category.value) - && `${tool.name} ${tool.description}`.toLowerCase().includes(query), - ); - list.replaceChildren(); - for (const group of configuration.categories) { - const members = matches.filter((tool) => tool.category === group.id); - if (!members.length) continue; - const section = el("section", null, "tool-category"), - heading = el("h3", group.label); - section.append(heading); - const available = el("p", null, "field-help"); - available.dataset.categoryCount = group.id; - for (const [key, text] of [["categoryToggle", "Enable category"], ["scope", "Include in agent scope"]]) { - const checkbox = el("md-checkbox"), label = el("label", null, "form-checkbox"); - checkbox.dataset[key] = group.id; - checkbox.setAttribute("aria-label", `${text}: ${group.label}`); - label.append(checkbox, el("span", text)); - section.append(label); - } - section.append(available); - for (const tool of members) { - const checkbox = el("md-checkbox"), - label = el("span"), - row = el("label", null, "form-checkbox tool-option"); - checkbox.dataset.tool = tool.name; - checkbox.dataset.category = tool.category; - checkbox.setAttribute("aria-label", tool.name); - label.append(el("span", tool.name), el("span", tool.description, "field-help")); - row.append(checkbox, label); - section.append(row); - } - list.append(section); - } - if (!matches.length) list.append(el("p", "No tools match your search.", "field-help")); - count.textContent = `${matches.length} of ${tools.length} tools shown`; - syncSettingsForm(); - }; - search.addEventListener("input", filter); - category.addEventListener("input", filter); - const change = (event) => { - if (settingsSaving) return; - const data = event.target.dataset; - if (event.target.id === "all-agent-categories") { - settingsDraft.mcp_categories = event.target.checked ? null : []; - } else { - const key = data.tool ? "disabled_tools" : data.categoryToggle ? "disabled_categories" : "mcp_categories", - name = data.tool || data.categoryToggle || data.scope; - if (!name) return; - const values = new Set(settingsDraft[key]), - include = key === "mcp_categories" ? event.target.checked : !event.target.checked; - if (include) values.add(name); - else values.delete(name); - settingsDraft[key] = [...values].sort(); - } - settingsMessage = "Unsaved settings."; - syncSettingsForm(); - }; - list.addEventListener("input", change); - const scope = el("label", null, "form-checkbox"), allScope = el("md-checkbox"); - allScope.id = "all-agent-categories"; - allScope.setAttribute("aria-label", "Include all enabled categories in agent scope"); - allScope.addEventListener("input", change); - scope.append(allScope, el("span", "Include all enabled categories in agent scope")); - $("tools-title").textContent = title; - $("tools-dialog").setAttribute("aria-label", title); - $("save-tools-settings").hidden = false; - status.hidden = false; - $("tools-body").replaceChildren( - el("p", "Category switches preserve individual tool choices. Agent scope only narrows enabled tools. Save changes; reconnect agents after changing exposure or scope.", "field-help"), - search, category, scope, count, list, status, - ); - filter(); - $("tools-dialog").show(); -} -function settingsForm() { - const form = el("form", null, "settings-form"), - fields = el("div", null, "form-grid"); - form.id = "settings-form"; - const themeField = el("div", null, "form-field"), - theme = selectControl("Color theme", [ - ["system", "Use system setting"], - ["light", "Light"], - ["dark", "Dark"], - ], settingsDraft.theme); - theme.id = "settings-theme"; - theme.dataset.setting = "theme"; - theme.supportingText = "Follow the device theme or choose one."; - themeField.append(theme); - fields.append(themeField); - const exposure = selectControl("MCP exposure", [ - ["compact", "Compact: help and invoke"], ["named", "Named: individual tools"], - ], settingsDraft.mcp_exposure); - exposure.dataset.setting = "mcp_exposure"; - exposure.supportingText = "Compact loads schemas on request. Named preserves individual tool approval controls. Applies on reconnect."; - fields.append(exposure); - - const refreshField = el("div", null, "form-field"), - refresh = textField( - "Refresh interval in seconds", - settingsDraft.refresh_seconds, - "number", - "Refresh workspace status and runs every 1 to 60 seconds.", - ); - refresh.id = "settings-refresh-seconds"; - refresh.dataset.setting = "refresh_seconds"; - refresh.min = "1"; - refresh.max = "60"; - refresh.step = "1"; - refreshField.append(refresh); - fields.append(refreshField); - - const historyField = el("div", null, "form-field"), - history = textField( - "Recent runs to load", - settingsDraft.history_limit, - "number", - "Load between 1 and 200 recent runs.", - ); - history.id = "settings-history-limit"; - history.dataset.setting = "history_limit"; - history.min = "1"; - history.max = "200"; - history.step = "1"; - historyField.append(history); - fields.append(historyField); - const sidebar = el("md-switch"); - sidebar.id = "settings-sidebar-collapsed"; - sidebar.dataset.setting = "sidebar_collapsed"; - sidebar.selected = settingsDraft.sidebar_collapsed; - sidebar.setAttribute("aria-label", "Keep the sidebar collapsed"); - const toggle = el("label", null, "form-checkbox"); - toggle.append(sidebar, el("span", "Keep the sidebar collapsed")); - fields.append(toggle); - form.append(fields); - - const tools = el("div"), - show = consoleButton("Show tools", "outlined"), - summary = el("p", null, "field-help"); - show.setAttribute("aria-haspopup", "dialog"); - show.onclick = () => showTools(); - summary.id = "settings-tools-summary"; - summary.textContent = enabledToolsSummary(); - tools.append(show, summary); - form.append(tools); - - const status = el("p", settingsMessage, "settings-message"); - status.id = "settings-message"; - status.setAttribute("role", "status"); - status.setAttribute("aria-live", "polite"); - const actions = el("div", null, "form-actions"); - const save = el("md-filled-button", "Save settings"); - save.type = "submit"; - save.id = "settings-save"; - const reset = consoleButton("Reset defaults", "text"); - reset.id = "settings-reset"; - reset.onclick = resetSettings; - actions.append(save, reset); - form.append(status, actions); - const change = (event) => { - const key = event.target.dataset.setting; - if (!key) return; - if (key === "sidebar_collapsed") settingsDraft[key] = event.target.selected; - else if (key === "refresh_seconds" || key === "history_limit") - settingsDraft[key] = event.target.value === "" ? "" : Number(event.target.value); - else settingsDraft[key] = event.target.value; - settingsMessage = "Unsaved settings."; - applySettings(settingsDraft); - syncSettingsForm(); - }; - form.addEventListener("input", change); - form.addEventListener("submit", (event) => { - event.preventDefault(); - saveSettingsDraft(); - }); - return form; -} -let launcherDraft = null, - launcherMessage = "", - launcherSaving = false; - -function launcherSettingsForm() { - const form = el("form", null, "settings-form"), - fields = el("div", null, "form-grid"); - form.id = "launcher-settings-form"; - form.append(el("p", configuration.launcher_settings_path, "small quiet")); - for (const [name, labelText, type] of [ - ["project", "Default repository", "text"], - ["port", "Web console port", "number"], - ["open_browser", "Open browser with vkit console", "checkbox"], - ]) { - const field = el(type === "checkbox" ? "label" : "div", null, - type === "checkbox" ? "form-checkbox" : "form-field"), - input = type === "checkbox" - ? el("md-switch") - : textField(labelText, launcherDraft[name], type === "number" ? "number" : "text"), - label = el("span", labelText); - input.id = `launcher-${name}`; - input.disabled = launcherSaving; - if (type === "checkbox") { - input.selected = launcherDraft[name]; - input.setAttribute("aria-label", labelText); - } - if (name === "port") { - input.min = "0"; - input.max = "65535"; - input.step = "1"; - input.required = true; - } - if (type !== "checkbox") input.supportingText = name === "project" - ? "Use an absolute path. Blank uses the current directory." - : "Use 0 to choose a free port. Applies when the server next starts."; - input.addEventListener("input", () => { - launcherDraft[name] = type === "checkbox" ? input.selected - : type === "number" ? Number(input.value) : input.value.trim() || null; - }); - if (type === "checkbox") field.append(input, label); - else field.append(input); - fields.append(field); - } - const status = el("p", launcherMessage, "settings-message"), - save = el("md-filled-button", "Save launch defaults"); - status.setAttribute("role", "status"); - save.type = "submit"; - save.disabled = launcherSaving; - form.append(fields, status, save); - form.addEventListener("submit", async (event) => { - event.preventDefault(); - if (launcherSaving) return; - const candidate = { ...launcherDraft }; - launcherSaving = true; - launcherMessage = "Saving launch defaults..."; - render(); - try { - const response = await post("/api/launcher-settings", candidate); - launcherDraft = mergeSettingsDraft(launcherDraft, response.settings, candidate); - configuration.launcher_settings = response.settings; - settingsVersion += 1; - launcherMessage = "Launch defaults saved. They apply to the next command or launch."; - } catch (error) { - launcherMessage = `Could not save launch defaults: ${error.message}`; - } finally { - launcherSaving = false; - render(); - refresh().catch(showError); - } - }); - return form; -} +const ctx = { + state, + render, + refresh, + showError, + applyTheme, + collapse, + loadDoctor, + showCheck: (id) => showCheck(ctx, id), +}; -function setup() { - if (activeWorkspace === "all") - return workspaceRequired("Project setup and tool settings"); - const isSetup = isManifestMissing(report.manifest_error), - hasManifestError = Boolean(report.manifest_error); - const fragment = document.createDocumentFragment(), - grid = el("div", null, "overview-grid"), - project = el("div", null, "panel-body"), - definitions = el("dl", null, "definition-list"); - for (const [name, value] of [ - ["Repository", report.project], - ["Evidence storage", configuration.doctor.state_root], - ["Console settings", configuration.settings_path], - ["Check definitions", "verification/manifest.json"], - ["Feature map", "verification/features.json"], - ["Version", configuration.version], - ]) { - const pair = el("div"); - pair.append(el("dt", name), el("dd", value)); - definitions.append(pair); - } - project.append( - definitions, - note( - "Input identity", - "Evidence depends on check definitions, input contents, and any pinned baseline. Undeclared dependencies can leave evidence apparently fresh.", - ), - ); - const prerequisites = el("div", null, "panel-body"), - tools = new Map(); - for (const f of configuration.doctor.findings) { - const key = f.prerequisite || f.check; - if (!tools.has(key)) tools.set(key, { ...f, checks: [] }); - tools.get(key).checks.push(f.check); - } - for (const [name, item] of tools) { - const status = el("div", null, "tool-status"), - copy = el("div", null, "row-copy"); - copy.append(el("h3", name), el("p", item.detail)); - status.append( - icon(item.ok ? "check" : "error"), - copy, - el( - "span", - item.ok ? "Available" : "Missing", - `status-badge ${item.ok ? "success" : "warning"}`, - ), - ); - prerequisites.append(status); - } - if (!tools.size) - prerequisites.append( - el( - "p", - "No prerequisites are declared by the registered checks.", - "small quiet", - ), - ); - grid.append( - panel( - isSetup ? "Not set up" : "Project", - isSetup - ? "Ask your agent to define checks in verification/manifest.json and map application behavior in verification/features.json. Review the definitions with vkit accept --project , then open Checks to run them and Runs to inspect results." - : hasManifestError - ? `VKit could not load verification/manifest.json: ${report.manifest_error}` - : configuration.description, - [project], - ), - panel( - "Required tools", - "Availability in the console server’s environment", - [prerequisites], - ), - ); - const connection = el("div", null, "panel-body"); - connection.append( - command(JSON.stringify(configuration.mcp_config, null, 2), "MCP configuration"), - note( - "Selected repository", - "This configuration uses the current repository and Python environment. Paste it into your agent application's MCP settings, reconnect, and ask the agent to call help. The agent starts its own server; this web console can be closed.", - ), - ); - fragment.append( - grid, - panel( - "Launch defaults", - "Saved for this user, outside repositories. Explicit CLI options override these values.", - [launcherSettingsForm()], - ), - panel( - "Project settings", - "Preferences and tool availability are saved for this project.", - [settingsForm()], - ), - el("h2", "Connect an agent", "section-label"), - panel( - "MCP over stdio", - "Copy this JSON into your agent application's MCP configuration.", - [connection], - ), - ); - return fragment; -} -function workspaceRequired(title) { - return panel(title, "Select a workspace from the left panel to view its project-specific data and actions.", [ - el("p", "VKit keeps evidence, runs, feature coverage, and settings bound to one selected worktree.", "small quiet"), - ]); -} -function showCheck(id) { - const check = report.checks.find((c) => c.id === id); - if (!check) return; - $("detail-title").textContent = id; - $("detail-label").textContent = - methods[check.kind]?.[0].toUpperCase() || "CHECK"; - const body = $("detail-body"); - body.replaceChildren( - badge(checkState(check)), - el( - "p", - check.description || "No description provided.", - "dialog-description", - ), - ); - for (const [title, text] of [ - ["Establishes", check.establishes], - ["Does not establish", check.does_not_establish], - [ - "Inputs", - check.inputs.declared.join(", ") || "Whole eligible repository tree", - ], - ]) { - const section = el("section", null, "dialog-section"); - section.append(el("h3", title), el("p", text)); - body.append(section); - } - if (check.inputs.unmatched.length) - body.append( - note("Missing declared inputs", check.inputs.unmatched.join(", ")), - ); - if (check.last) - body.append( - action( - "Inspect last run", - `runs/${encodeURIComponent(check.last.run_id)}`, - "md-outlined-button", - ), - ); - const definition = configuration.definitions[id]; - if (definition) { - const section = el("section", null, "dialog-section"); - section.append( - el("h3", "Registered definition"), - el("pre", JSON.stringify(definition, null, 2)), - ); - body.append(section); - } - if (!$("detail-dialog").open) $("detail-dialog").show(); -} -async function refreshRun() { - if (!selectedRun || activePage !== "runs") return; - const id = selectedRun, - requestedStream = stream; - const detail = await get( - `/api/run?id=${encodeURIComponent(id)}&log=${requestedStream}&offset=-16000`, - ); - if (id !== selectedRun || requestedStream !== stream || activePage !== "runs") - return; - const box = $("run-detail"); - if (!box) return; - const detailSignature = JSON.stringify(detail); - if (box.dataset.signature === detailSignature) return; - const logWasFocused = document.activeElement?.id === "run-log"; - box.dataset.signature = detailSignature; - box.hidden = false; - box.replaceChildren(); - const header = el("div", null, "panel-header"), - title = el("div"); - title.append(el("h2", detail.subject?.id || detail.check_id), el("p", id)); - header.append(title, badge(detail.outcome?.result || detail.state)); - box.append(header); - const body = el("div", null, "panel-body"), - meta = el("div", null, "run-meta"); - meta.append( - el("span", `Started ${date(detail.started_at)}`), - el("span", `Finished ${date(detail.ended_at)}`), - el("span", `${detail.inputs?.scope || ""}`), - ); - body.append(meta); - if (detail.outcome?.detail) - body.append( - note( - detail.outcome.reason?.replaceAll("_", " ") || "Outcome", - detail.outcome.detail, - ), - ); - for (const scenario of detail.outcome?.scenarios || []) { - const entry = el("div", null, "result-row"), - copy = el("div", null, "row-copy"); - copy.append(el("h3", scenario.id), el("p", scenario.observation)); - entry.append(badge(scenario.result), copy); - body.append(entry); - } - if (detail.measurements?.length) { - const measurements = el("div", null, "measurement-grid"); - for (const m of detail.measurements) { - const item = el("div"); - item.append( - el("span", m.name, "small quiet"), - el("strong", `${m.value} ${m.unit}`), - el( - "small", - `${m.better} is better${m.baseline != null ? ` · baseline ${m.baseline}` : ""}`, - ), - ); - measurements.append(item); - } - body.append(measurements); - } - for (const finding of detail.findings || []) - body.append( - note( - `${finding.rule} · ${finding.path}${finding.line ? ":" + finding.line : ""}`, - finding.message, - ), - ); - for (const text of detail.unchecked_budgets || []) - body.append(note("Budget not checked", text)); - if (detail.obligations) { - const obligations = el("section", null, "dialog-section"); - obligations.append(el("h3", "Formal obligations")); - obligations.append(el("pre", JSON.stringify(detail.obligations, null, 2))); - body.append(obligations); - } - const provenance = el("details", null, "dialog-section"); - provenance.append(el("summary", "Recorded inputs and execution")); - provenance.append( - el( - "pre", - JSON.stringify( - { - category: detail.category, - worktree: detail.worktree, - check_digest: detail.check_digest, - evidence_key: detail.key, - inputs: detail.inputs, - command: detail.argv, - exit_code: detail.exit_code, - environment: detail.environment, - }, - null, - 2, - ), - ), - ); - body.append(provenance); - const logHeader = el("div", null, "log-header"), - select = selectControl("Log stream", [["stdout", "stdout"], ["stderr", "stderr"]], stream); - select.id = "run-log"; - select.onchange = () => { - stream = select.value; - refreshRun().catch(showError); - }; - logHeader.append(el("h3", "Execution log"), select); - const log = el("pre", detail.log?.text || "No output in this stream."); - log.id = "run-text"; - body.append(logHeader, log); - if (detail.log?.size > 16000) - body.append(el("p", "Showing the last 16,000 bytes.", "small quiet")); - box.append(body); - if (logWasFocused) select.focus(); -} function render() { - const focused = document.activeElement, - focusId = focused?.id, - start = focused?.selectionStart, - end = focused?.selectionEnd; + const focused = document.activeElement; + const focusId = focused?.id; + const start = focused?.selectionStart; + const end = focused?.selectionEnd; const openedFeatures = [...$("view").querySelectorAll("details[open]")].map( (d) => d.dataset.feature, ); - let [, , eyebrow, title, description] = pages[activePage]; - if (activeWorkspace === "all" && activePage === "overview") { + let [, , eyebrow, title, description] = pages[state.activePage]; + if (state.activeWorkspace === "all" && state.activePage === "overview") { eyebrow = "ALL WORKSPACES"; title = "Workspace overview"; - } else if (activeWorkspace === "all" && activePage === "proposals") { + } else if (state.activeWorkspace === "all" && state.activePage === "proposals") { eyebrow = "ALL WORKSPACES"; title = "Pending proposal inbox"; description = "Review suggestions across remembered workspaces, then open each one in its owning project."; } - $("breadcrumb").textContent = pages[activePage][0]; + $("breadcrumb").textContent = pages[state.activePage][0]; $("page-eyebrow").textContent = eyebrow; $("page-title").textContent = title; - $("page-description").textContent = activeWorkspace === "all" && activePage === "overview" + $("page-description").textContent = state.activeWorkspace === "all" && state.activePage === "overview" ? "Review remembered workspaces and pending proposals, then open a workspace for its evidence and actions." : description; for (const nav of $("navigation").querySelectorAll("a")) { - if (nav.dataset.page === activePage) - nav.setAttribute("aria-current", "page"); + if (nav.dataset.page === state.activePage) nav.setAttribute("aria-current", "page"); else nav.removeAttribute("aria-current"); } - const counts = activeWorkspace === "all" + const counts = state.activeWorkspace === "all" ? { - checks: workspaceSummary.reduce((n, workspace) => n + (workspace.checks?.length || 0), 0), - proposals: allProposalItems().length, + checks: state.workspaceSummary.reduce((n, workspace) => n + (workspace.checks?.length || 0), 0), + proposals: allProposalItems(state.workspaceSummary).length, } : { - checks: report?.checks.length || 0, - runs: runs.length, - features: report?.features.length || 0, - proposals: report?.proposals.length || 0, + checks: state.report?.checks.length || 0, + runs: state.runs.length, + features: state.report?.features.length || 0, + proposals: state.report?.proposals.length || 0, }; for (const node of $("navigation").querySelectorAll(".nav-count")) node.textContent = counts[node.dataset.page] || ""; const projectPages = new Set(["checks", "runs", "features", "setup"]); for (const nav of $("navigation").querySelectorAll("a[data-page]")) - nav.hidden = activeWorkspace === "all" && projectPages.has(nav.dataset.page); + nav.hidden = state.activeWorkspace === "all" && projectPages.has(nav.dataset.page); const pageViews = { - overview, - checks, - runs: runHistory, - capabilities, - features: featureMap, - proposals, - setup, + overview: () => overview(ctx), + checks: () => checks(ctx), + runs: () => runHistory(ctx), + capabilities: () => capabilities(ctx), + features: () => featureMap(ctx), + proposals: () => proposals(ctx), + setup: () => setup(ctx), }; $("view").replaceChildren( - activeWorkspace === "all" && projectPages.has(activePage) - ? workspaceRequired(pages[activePage][0]) - : pageViews[activePage](), + state.activeWorkspace === "all" && projectPages.has(state.activePage) + ? workspaceRequired(pages[state.activePage][0]) + : pageViews[state.activePage](), ); for (const details of $("view").querySelectorAll("details")) { if (details.dataset.feature) @@ -1764,62 +187,45 @@ function render() { else restore(); } } + +function closeNavigation() { + document.body.classList.remove("nav-open"); + document.querySelector(".workspace-main").inert = false; + $("scrim").hidden = true; + $("mobile-nav").setAttribute("aria-expanded", "false"); +} + function route() { const [requested, runId] = location.hash.slice(1).split("/"); const next = Object.hasOwn(pages, requested) ? requested : "overview"; - if (next !== activePage) { - search = ""; - kind = ""; + if (next !== state.activePage) { + state.search = ""; + state.kind = ""; } - activePage = next; - selectedRun = activeWorkspace !== "all" && next === "runs" && runId + state.activePage = next; + state.selectedRun = state.activeWorkspace !== "all" && next === "runs" && runId ? decodeURIComponent(runId) : null; $("detail-dialog").close(); $("tools-dialog").close(); closeNavigation(); - if (report || (activeWorkspace === "all" && workspaceSummaryReady)) { + if (state.report || (state.activeWorkspace === "all" && state.workspaceSummaryReady)) { render(); - if (activeWorkspace !== "all") refreshRun().catch(showError); + if (state.activeWorkspace !== "all") refreshRun(ctx).catch(showError); } } -async function get(url, workspace = activeWorkspace) { - const response = await fetch(workspaceUrl(url, workspace)); - const body = await response.json(); - if (!response.ok) - throw new Error(body.error || `Request failed (${response.status})`); - return body; -} -async function post(url, value, workspace = activeWorkspace) { - if (workspace === "all" && url !== "/api/workspaces") - throw new Error("Select one workspace before changing project settings or running a tool."); - const response = await fetch(workspaceUrl(url, workspace), { - method: "POST", - headers: { - "Content-Type": "application/json", - "X-Vkit-Token": csrfToken, - }, - body: JSON.stringify(value), - }); - const body = await response.json(); - if (!response.ok) - throw new Error(body.error || `Request failed (${response.status})`); - return body; -} -function callTool(name, arguments_) { - return post("/api/call", { name, arguments: arguments_ }); -} + function syncWorkspacePicker() { - if (!workspaceRegistry) return; - const select = $("workspace-select"), - selected = activeWorkspace, - rows = workspaceRegistry.workspaces || []; + if (!state.workspaceRegistry) return; + const select = $("workspace-select"); + const selected = state.activeWorkspace; + const rows = state.workspaceRegistry.workspaces || []; select.replaceChildren(new Option("All workspaces", "all")); for (const workspace of rows) { - const summary = workspaceSummary.find((item) => item.id === workspace.id), - location = workspace.path ? ` · ${workspace.path}` : "", - label = `${workspace.name || workspace.path}${location}${summary?.available === false ? " · unavailable" : ""}`, - option = new Option(label, workspace.id); + const summary = state.workspaceSummary.find((item) => item.id === workspace.id); + const locationText = workspace.path ? ` · ${workspace.path}` : ""; + const label = `${workspace.name || workspace.path}${locationText}${summary?.available === false ? " · unavailable" : ""}`; + const option = new Option(label, workspace.id); option.title = workspace.path || workspace.name || ""; select.append(option); } @@ -1833,8 +239,9 @@ function syncWorkspacePicker() { $("project-path").textContent = selected === "all" ? `${rows.length} remembered workspace${rows.length === 1 ? "" : "s"}` : rows.find((workspace) => workspace.id === selected)?.path || "Workspace unavailable"; - $("version").textContent = `v${workspaceRegistry.version || ""}`; + $("version").textContent = `v${state.workspaceRegistry.version || ""}`; } + function setInitialWorkspace(registry) { const url = new URL(window.location.href); if (!url.searchParams.has("workspace")) { @@ -1842,39 +249,53 @@ function setInitialWorkspace(registry) { url.searchParams.set("workspace", first); window.history.replaceState(null, "", `${url.pathname}${url.search}${url.hash}`); } - activeWorkspace = new URL(window.location.href).searchParams.get("workspace") || "all"; + state.activeWorkspace = new URL(window.location.href).searchParams.get("workspace") || "all"; +} + +function ensureEventsStream() { + if (state.activeWorkspace === eventWorkspace) return; + if (eventSource) { + eventSource.close(); + eventSource = null; + } + eventWorkspace = state.activeWorkspace; + eventSource = connectEvents(state.activeWorkspace, () => { + refresh().catch(showError); + }); } + function workspacePickerChanged(event) { - const next = event.target.value, - projectSettingsChanged = configuration && settingsDraft - && JSON.stringify(settingsDraft) !== JSON.stringify(configuration.settings), - launcherSettingsChanged = configuration && launcherDraft - && JSON.stringify(launcherDraft) !== JSON.stringify(configuration.launcher_settings); - if ((projectSettingsChanged || launcherSettingsChanged) - && !window.confirm("Discard unsaved settings and switch workspaces?")) { - event.target.value = activeWorkspace; + const next = event.target.value; + const projectSettingsChanged = state.configuration && state.settingsDraft && + JSON.stringify(state.settingsDraft) !== JSON.stringify(state.configuration.settings); + const launcherSettingsChanged = state.configuration && state.launcherDraft && + JSON.stringify(state.launcherDraft) !== JSON.stringify(state.configuration.launcher_settings); + if ((projectSettingsChanged || launcherSettingsChanged) && + !window.confirm("Discard unsaved settings and switch workspaces?")) { + event.target.value = state.activeWorkspace; return; } const url = new URL(window.location.href); url.searchParams.set("workspace", next); window.location.assign(`${url.pathname}${url.search}${url.hash}`); } + function addWorkspace(event) { event.preventDefault(); - if (workspaceSaving) return; - const input = $("workspace-path"), - status = $("workspace-add-status"), - submit = event.currentTarget.querySelector("button"); + if (state.workspaceSaving) return; + const input = $("workspace-path"); + const status = $("workspace-add-status"); + const submit = event.currentTarget.querySelector("button"); const path = input.value.trim(); if (!path) { status.textContent = "Enter a repository path."; return; } - workspaceSaving = true; + state.workspaceSaving = true; submit.disabled = true; status.dataset.state = ""; status.textContent = "Remembering workspace…"; - post("/api/workspaces", { path }, null) + apiPost("/api/workspaces", { path }, null, state.csrfToken) .then((response) => { const workspace = response.workspace || response; if (!workspace.id) throw new Error("The server did not return a workspace ID."); @@ -1885,45 +306,36 @@ function addWorkspace(event) { .catch((error) => { status.dataset.state = "error"; status.textContent = `Could not add workspace: ${error.message}`; - workspaceSaving = false; + state.workspaceSaving = false; submit.disabled = false; }); } -function showError(error) { - $("connection-error").hidden = false; - $("connection-error").textContent = - `Unable to refresh: ${error.message}. Showing the last received evidence.`; - document.body.classList.add("disconnected"); -} -function showWorkspaceUnavailable(message) { - $("page-eyebrow").textContent = "WORKSPACE"; - $("page-title").textContent = "Workspace unavailable"; - $("page-description").textContent = "Choose a remembered workspace or add its current repository path in the left panel."; - $("view").replaceChildren(empty("Select another workspace", message)); -} + function refresh() { - if (refreshing) return refreshing; - refreshing = (async () => { - const requestedSettingsVersion = settingsVersion; + if (state.refreshing) return state.refreshing; + state.refreshing = (async () => { + const requestedSettingsVersion = state.settingsVersion; try { - const nextRegistry = await get("/api/workspaces", null); - csrfToken = nextRegistry.csrf_token || ""; - workspaceRegistry = nextRegistry; + const nextRegistry = await apiGet("/api/workspaces", null); + state.csrfToken = nextRegistry.csrf_token || ""; + state.workspaceRegistry = nextRegistry; setInitialWorkspace(nextRegistry); syncWorkspacePicker(); - if (activeWorkspace === "all") { - const summary = await get("/api/workspaces/summary", null); - workspaceSummary = summary.workspaces || []; - workspaceSummaryReady = true; + if (state.activeWorkspace === "all") { + ensureEventsStream(); + const summary = await apiGet("/api/workspaces/summary", null); + state.workspaceSummary = summary.workspaces || []; + state.workspaceSummaryReady = true; syncWorkspacePicker(); - report = null; - runs = []; - configuration = null; - settingsDraft = null; - launcherDraft = null; - const nextSignature = JSON.stringify([workspaceRegistry, workspaceSummary]); - if (signature !== nextSignature) { - signature = nextSignature; + state.report = null; + state.runs = []; + state.configuration = null; + state.doctorReport = null; + state.settingsDraft = null; + state.launcherDraft = null; + const nextSignature = JSON.stringify([state.workspaceRegistry, state.workspaceSummary]); + if (state.signature !== nextSignature) { + state.signature = nextSignature; render(); } $("updated").textContent = `Updated ${new Date().toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" })}`; @@ -1931,85 +343,68 @@ function refresh() { document.body.classList.remove("disconnected"); return; } - if (!(nextRegistry.workspaces || []).some((workspace) => workspace.id === activeWorkspace)) { - workspaceSummary = []; - report = null; - runs = []; - configuration = null; + if (!(nextRegistry.workspaces || []).some((workspace) => workspace.id === state.activeWorkspace)) { + state.workspaceSummary = []; + state.report = null; + state.runs = []; + state.configuration = null; + state.doctorReport = null; showWorkspaceUnavailable("This workspace ID is not in the registry. Choose another workspace or add its current path."); return; } - if (!workspaceVisited) { - await post("/api/workspaces/visit", { id: activeWorkspace }, null); - workspaceVisited = true; + if (!state.workspaceVisited) { + await apiPost("/api/workspaces/visit", { id: state.activeWorkspace }, null, state.csrfToken); + state.workspaceVisited = true; } - const nextConfig = await get("/api/config"), - [nextReport, nextRuns] = await Promise.all([ - get("/api/status"), - get(`/api/runs?limit=${nextConfig.settings.history_limit}`), - ]); - if (requestedSettingsVersion !== settingsVersion && configuration) { - nextConfig.settings = configuration.settings; - nextConfig.settings_path = configuration.settings_path; - nextConfig.launcher_settings = configuration.launcher_settings; + ensureEventsStream(); + const nextConfig = await apiGet("/api/config?include_doctor=0", state.activeWorkspace); + const [nextReport, nextRuns] = await Promise.all([ + apiGet("/api/status", state.activeWorkspace), + apiGet(`/api/runs?limit=${nextConfig.settings.history_limit}`, state.activeWorkspace), + ]); + if (requestedSettingsVersion !== state.settingsVersion && state.configuration) { + nextConfig.settings = state.configuration.settings; + nextConfig.settings_path = state.configuration.settings_path; + nextConfig.launcher_settings = state.configuration.launcher_settings; } - const previousSettings = configuration?.settings; - settingsDraft = mergeSettingsDraft(settingsDraft, nextConfig.settings, previousSettings); - launcherDraft = mergeSettingsDraft(launcherDraft, nextConfig.launcher_settings, configuration?.launcher_settings); - report = nextReport; - runs = nextRuns; - configuration = nextConfig; - applySettings(settingsDraft); - syncSettingsForm(); - const nextSignature = JSON.stringify([report, runs, configuration]); + const previousSettings = state.configuration?.settings; + state.settingsDraft = mergeSettingsDraft(state.settingsDraft, nextConfig.settings, previousSettings); + state.launcherDraft = mergeSettingsDraft(state.launcherDraft, nextConfig.launcher_settings, state.configuration?.launcher_settings); + state.report = nextReport; + state.runs = nextRuns; + state.configuration = nextConfig; + applySettings(ctx, state.settingsDraft); + syncSettingsForm(ctx); + const nextSignature = JSON.stringify([state.report, state.runs, state.configuration]); syncWorkspacePicker(); - $("version").textContent = `v${configuration.version}`; - $("updated").textContent = - `Updated ${new Date().toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" })}`; - if (signature !== nextSignature) { - signature = nextSignature; + $("version").textContent = `v${state.configuration.version}`; + $("updated").textContent = `Updated ${new Date().toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" })}`; + if (state.signature !== nextSignature) { + state.signature = nextSignature; render(); } - await refreshRun(); + await refreshRun(ctx); $("connection-error").hidden = true; document.body.classList.remove("disconnected"); } catch (error) { showError(error); - if (!report) - showWorkspaceUnavailable(error.message); + if (!state.report) showWorkspaceUnavailable(error.message); } finally { $("content").setAttribute("aria-busy", "false"); - refreshing = null; + state.refreshing = null; } })(); - return refreshing; -} -const systemTheme = matchMedia("(prefers-color-scheme: dark)"); -let themePreference = "system"; -function applyTheme(preference) { - themePreference = preference; - const mode = - preference === "system" ? (systemTheme.matches ? "dark" : "light") : preference; - document.documentElement.dataset.theme = mode; - const next = mode === "dark" ? "light" : "dark"; - $("theme-icon").setAttribute("href", `/assets/icons.svg#${next}`); - $("theme-toggle").setAttribute("aria-label", `Switch to ${next} theme`); - $("theme-toggle").title = `Switch to ${next} theme`; + return state.refreshing; } + applyTheme("system"); systemTheme.addEventListener("change", () => { if (themePreference === "system") applyTheme("system"); }); $("theme-toggle").onclick = () => { const next = document.documentElement.dataset.theme === "dark" ? "light" : "dark"; - updatePreference("theme", next); + updatePreference(ctx, "theme", next); }; -function closeNavigation() { - document.body.classList.remove("nav-open"); - document.querySelector(".workspace-main").inert = false; - $("scrim").hidden = true; - $("mobile-nav").setAttribute("aria-expanded", "false"); -} $("mobile-nav").onclick = () => { document.body.classList.add("nav-open"); document.querySelector(".workspace-main").inert = true; @@ -2027,22 +422,14 @@ document.addEventListener("keydown", (event) => { $("mobile-nav").focus(); } }); -function collapse(collapsed) { - document.body.classList.toggle("nav-collapsed", collapsed); - $("collapse-nav").setAttribute("aria-expanded", String(!collapsed)); - $("collapse-nav").setAttribute( - "aria-label", - collapsed ? "Expand sidebar" : "Collapse sidebar", - ); -} collapse(false); $("collapse-nav").onclick = () => { const collapsed = !document.body.classList.contains("nav-collapsed"); - updatePreference("sidebar_collapsed", collapsed); + updatePreference(ctx, "sidebar_collapsed", collapsed); }; $("close-detail").onclick = () => $("detail-dialog").close(); $("close-tools").onclick = () => $("tools-dialog").close(); -$("save-tools-settings").onclick = saveSettingsDraft; +$("save-tools-settings").onclick = () => saveSettingsDraft(ctx); $("refresh").onclick = () => refresh(); $("workspace-select").addEventListener("change", workspacePickerChanged); $("workspace-add-form").addEventListener("submit", addWorkspace); @@ -2064,6 +451,9 @@ window.addEventListener("hashchange", route); route(); async function poll() { await refresh(); - setTimeout(poll, (configuration?.settings.refresh_seconds || workspaceRegistry?.settings_defaults?.refresh_seconds || 5) * 1000); + setTimeout( + poll, + (state.configuration?.settings.refresh_seconds || state.workspaceRegistry?.settings_defaults?.refresh_seconds || 5) * 1000, + ); } poll(); diff --git a/src/vkit/console/static/js/api.js b/src/vkit/console/static/js/api.js new file mode 100644 index 0000000..8b3d90e --- /dev/null +++ b/src/vkit/console/static/js/api.js @@ -0,0 +1,58 @@ +export function workspaceUrl(url, workspace) { + const target = new URL(url, window.location.origin); + if (workspace) target.searchParams.set("workspace", workspace); + else target.searchParams.delete("workspace"); + return `${target.pathname}${target.search}${target.hash}`; +} + +export async function apiGet(url, workspace) { + const response = await fetch(workspaceUrl(url, workspace)); + const body = await response.json(); + if (!response.ok) { + const error = new Error(body.error || `Request failed (${response.status})`); + error.status = response.status; + throw error; + } + return body; +} + +export async function apiPost(url, value, workspace, csrfToken) { + if (workspace === "all" && url !== "/api/workspaces") + throw new Error("Select one workspace before changing project settings or running a tool."); + const response = await fetch(workspaceUrl(url, workspace), { + method: "POST", + headers: { + "Content-Type": "application/json", + "X-Vkit-Token": csrfToken, + }, + body: JSON.stringify(value), + }); + const body = await response.json(); + if (!response.ok) { + const error = new Error(body.error || `Request failed (${response.status})`); + error.status = response.status; + throw error; + } + return body; +} + +export function callTool(name, arguments_, workspace, csrfToken) { + return apiPost("/api/call", { name, arguments: arguments_ }, workspace, csrfToken); +} + +export function connectEvents(workspace, onToken) { + if (!workspace || workspace === "all" || typeof EventSource === "undefined") + return null; + let lastToken = null; + const source = new EventSource(workspaceUrl("/api/events", workspace)); + source.addEventListener("state", (event) => { + try { + const payload = JSON.parse(event.data); + if (lastToken !== null && payload.token !== lastToken) { + onToken(payload.token); + } + lastToken = payload.token; + } catch {} + }); + return source; +} diff --git a/src/vkit/console/static/js/ui.js b/src/vkit/console/static/js/ui.js new file mode 100644 index 0000000..7241252 --- /dev/null +++ b/src/vkit/console/static/js/ui.js @@ -0,0 +1,385 @@ +export const $ = (id) => document.getElementById(id); + +export const pages = { + overview: [ + "Overview", + "dashboard", + "YOUR WORKSPACE", + "Verification at a glance", + "What is known about your code, and where evidence is still needed.", + ], + checks: [ + "Checks", + "checks", + "REGISTERED VERIFICATION", + "Checks", + "Inspect each check, its inputs, and the scope of its evidence.", + ], + runs: [ + "Runs", + "history", + "EXECUTION HISTORY", + "Runs", + "Recorded outcomes, observations, measurements, and logs.", + ], + capabilities: [ + "Capabilities", + "extension", + "THE TOOL", + "What vkit can verify", + "Reusable verification methods, with explicit evidence and limits.", + ], + features: [ + "Feature map", + "features", + "APPLICATION COVERAGE", + "Feature map", + "What the application does, how to reach it, and which checks cover it.", + ], + proposals: [ + "Proposals", + "proposals", + "PENDING REVIEW", + "Proposals", + "Suggested checks, feature entries, and new files. Nothing is applied here.", + ], + setup: [ + "Setup & tools", + "settings", + "PROJECT CONFIGURATION", + "Setup & tools", + "Project configuration, tool availability, and connection details.", + ], +}; + +export const methods = { + scenario: [ + "Scenarios", + "checks", + "Run a reusable driver against named behaviors and collect its observations and measurements.", + "Evidence covers the cases actually run. Performance budgets apply when declared.", + ], + pytest: [ + "Python tests", + "code", + "Execute the required pytest tests and record each test’s outcome.", + "Required tests must run. Missing or skipped tests cannot establish a pass.", + ], + node_test: [ + "Node tests", + "code", + "Execute named Node tests and interpret the runner’s structured report.", + "Evidence is limited to the required tests and inputs exercised.", + ], + property: [ + "Property tests", + "science", + "Search generated cases with Hypothesis for disagreement with an expected property or reference model.", + "Sampling can find counterexamples; it does not prove the property for every input.", + ], + static: [ + "Static analysis", + "rule", + "Read analyzer findings and compare them with an accepted baseline.", + "A pass means no new reported findings, not an absence of all possible defects.", + ], + lean: [ + "Lean proofs", + "security", + "Check formal statements with Lean and audit axioms. Agent-written proofs use comparator against frozen statements.", + "The result applies to the formal statements. It needs a separate connection to application behavior.", + ], + tlc: [ + "Finite model checking", + "features", + "Explore a finite TLA+ model with TLC and check the declared properties.", + "The result applies to that model and its recorded bounds. It does not verify the implementation.", + ], + verus: [ + "Verus proofs", + "security", + "Verify Rust specifications and required API contracts with Verus under a pinned toolchain.", + "Source verification covers the declared contract. It is not a source-to-binary theorem.", + ], + kani: [ + "Kani model checking", + "security", + "Verify Rust harnesses with Kani bounded model checking under a pinned toolchain.", + "Bounded checks apply to the declared harnesses and unwind limits.", + ], + external: [ + "External command", + "code", + "Run a registered external command and interpret its declared exit status or report.", + "Evaluator content is external to the manifest; review command inputs and scope carefully.", + ], + model_compare: [ + "Model comparison", + "features", + "Compare two explicit finite transition models on named states, guards, and observations.", + "Applies to explicit finite models only. It does not prove source code equivalence.", + ], + change_certify: [ + "Change certification", + "rule", + "Run shadow change analysis against a trusted target commit and accepted intent.", + "Shadow analysis reports behavioral deltas without granting code approval.", + ], +}; + +export const labels = { + fresh_pass: ["Passed", "success"], + fresh_fail: ["Failed", "error"], + fresh_blocked: ["Blocked", "warning"], + stale: ["Stale", "warning"], + missing: ["Not run", ""], + not_approved: ["Not accepted", "warning"], + queued: ["Queued", "info"], + running: ["Running", "info"], + starting: ["Starting", "info"], + done: ["Finished", ""], + interrupted: ["Interrupted", "warning"], + PASS: ["Pass", "success"], + FAIL: ["Fail", "error"], + BLOCKED: ["Blocked", "warning"], + READY: ["Ready", "success"], + READY_SCOPED: ["Ready (scoped)", "success"], + REJECTED: ["Rejected", "error"], + verified: ["Verified", "success"], + unverified: ["Unverified", "warning"], + UNKNOWN: ["Unknown", "warning"], + UNAVAILABLE: ["Unavailable", "warning"], + UNSUPPORTED: ["Unsupported", "warning"], + COUNTEREXAMPLE: ["Counterexample", "warning"], + BREAKING: ["Breaking", "warning"], + INFEASIBLE: ["Infeasible", "warning"], +}; + +export function el(tag, text, cls) { + const node = document.createElement(tag); + if (text != null) node.textContent = text; + if (cls) node.className = cls; + return node; +} + +export function icon(name, cls = "icon") { + const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); + svg.setAttribute("class", cls); + svg.setAttribute("aria-hidden", "true"); + svg.setAttribute("viewBox", "0 0 24 24"); + const use = document.createElementNS(svg.namespaceURI, "use"); + use.setAttribute("href", `/assets/icons.svg#${name}`); + svg.append(use); + return svg; +} + +export function badge(state) { + const [label, tone] = labels[state] || [state || "No result", ""]; + return el("span", label, `status-badge ${tone}`); +} + +export function link(text, actionFn) { + const button = el("md-text-button", text, "text-link"); + button.type = "button"; + button.onclick = actionFn; + return button; +} + +export function action(text, page, type = "md-text-button") { + const button = el(type, text); + button.onclick = () => { + location.hash = page; + }; + return button; +} + +export function consoleButton(text, tone = "tonal") { + const types = { + primary: "md-filled-button", + tonal: "md-filled-tonal-button", + text: "md-text-button", + outlined: "md-outlined-button", + }; + const button = el(types[tone] || types.tonal, text); + button.type = "button"; + return button; +} + +export function selectOption(value, headline, selected = false) { + const option = el("md-select-option"); + const text = el("span", headline); + option.value = value; + if (selected) option.setAttribute("selected", ""); + text.slot = "headline"; + option.append(text); + return option; +} + +export function selectControl(label, values, selected) { + const control = el("md-outlined-select"); + control.label = label; + control.menuPositioning = "fixed"; + for (const [value, headline] of values) + control.append(selectOption(value, headline, value === selected)); + control.value = selected; + return control; +} + +export function textField(label, value, type = "text", supportingText = "") { + const control = el("md-outlined-text-field"); + control.label = label; + control.type = type; + control.value = value ?? ""; + control.supportingText = supportingText; + return control; +} + +export function panel(title, description, children, button) { + const box = el("section", null, "panel"); + const header = el("div", null, "panel-header"); + const copy = el("div"); + copy.append(el("h2", title)); + if (description) copy.append(el("p", description)); + header.append(copy); + if (button) header.append(button); + box.append(header, ...children); + return box; +} + +export function empty(title, description, symbol = "info") { + const box = el("div", null, "empty-state"); + box.append(icon(symbol), el("h3", title), el("p", description)); + return box; +} + +export function note(title, text) { + const box = el("div", null, "scope-note"); + box.append(el("strong", title), el("p", text)); + return box; +} + +export function date(value) { + return value + ? new Date(value).toLocaleString(undefined, { + month: "short", + day: "numeric", + hour: "2-digit", + minute: "2-digit", + }) + : "Not recorded"; +} + +export function row(cells) { + const tr = el("tr"); + for (const value of cells) { + const td = el("td"); + td.append( + value instanceof Node ? value : document.createTextNode(value ?? ""), + ); + tr.append(td); + } + return tr; +} + +export function table(headers, name) { + const wrap = el("div", null, "panel table-scroll"); + const grid = el("table"); + const head = el("thead"); + const hr = el("tr"); + const body = el("tbody"); + grid.setAttribute("aria-label", name); + for (const heading of headers) { + const th = el("th", heading); + th.scope = "col"; + hr.append(th); + } + head.append(hr); + grid.append(head, body); + wrap.append(grid); + return { wrap, body }; +} + +export function toolbar(ctx, placeholder, update, withKind = false) { + const bar = el("div", null, "toolbar"); + const input = textField(placeholder, ctx.state.search, "search"); + input.className = "view-search"; + input.id = "view-search"; + input.oninput = () => { + ctx.state.search = input.value; + update(); + }; + input.append(icon("search", "icon")); + input.lastChild.slot = "leading-icon"; + bar.append(input); + if (withKind) { + const select = selectControl( + "Verification method", + [["", "All methods"], ...Object.entries(methods).map(([key, value]) => [key, value[0]])], + ctx.state.kind, + ); + select.onchange = () => { + ctx.state.kind = select.value; + update(); + }; + bar.append(select); + } + return bar; +} + +export function matches(ctx, value) { + return JSON.stringify(value).toLowerCase().includes(ctx.state.search.toLowerCase()); +} + +export function checkState(check) { + return check.running.length ? "running" : check.state; +} + +export function isManifestMissing(error) { + return typeof error === "string" && error.startsWith("no manifest at "); +} + +export function workspaceHref(id, page) { + const target = new URL(window.location.href); + target.searchParams.set("workspace", id); + target.hash = page; + return `${target.pathname}${target.search}${target.hash}`; +} + +export function workspaceAnchor(text, id, page, cls = "") { + const anchor = el("a", text, cls); + anchor.href = workspaceHref(id, page); + return anchor; +} + +export function workspaceLabel(workspace) { + return workspace?.name || workspace?.path || "Unknown workspace"; +} + +export function workspaceRequired(title) { + return panel(title, "Select a workspace from the left panel to view its project-specific data and actions.", [ + el("p", "VKit keeps evidence, runs, feature coverage, and settings bound to one selected worktree.", "small quiet"), + ]); +} + +export function command(text, label = "command") { + const box = el("div", null, "command-line"); + const button = el("md-icon-button"); + button.setAttribute("aria-label", "Copy " + label); + button.title = "Copy " + label; + button.append(icon("copy")); + button.onclick = async () => { + try { + await navigator.clipboard.writeText(text); + button.setAttribute("aria-label", "Copied"); + button.replaceChildren(icon("check")); + } catch { + button.setAttribute( + "aria-label", + "Copy unavailable; select the " + label + " text", + ); + button.title = "Select and copy the " + label + " text"; + } + }; + box.append(el("code", text), button); + return box; +} diff --git a/src/vkit/console/static/js/views/execution.js b/src/vkit/console/static/js/views/execution.js new file mode 100644 index 0000000..0dc5b22 --- /dev/null +++ b/src/vkit/console/static/js/views/execution.js @@ -0,0 +1,379 @@ +import { apiGet, callTool } from "../api.js"; +import { + $, + action, + badge, + checkState, + consoleButton, + date, + el, + empty, + link, + matches, + methods, + note, + panel, + row, + selectControl, + table, + toolbar, +} from "../ui.js"; +import { formalPanel } from "./overview.js"; + +function checkRunMessage(response) { + if (response.is_error) + return `Check run request failed: ${response.result?.error || "vkit rejected the request."}`; + const started = response.result?.runs || []; + return started.length + ? `Returned ${started.length} run${started.length === 1 ? "" : "s"}. Check their states in Runs.` + : "No checks needed a run."; +} + +export async function runChecks(ctx, arguments_) { + const { execution, activeWorkspace, csrfToken } = ctx.state; + if (execution.pending.has("check_run")) return; + execution.pending.add("check_run"); + execution.checksMessage = "Starting check run…"; + ctx.render(); + try { + execution.checksMessage = checkRunMessage( + await callTool("check_run", arguments_, activeWorkspace, csrfToken), + ); + } catch (error) { + execution.checksMessage = `Check run request failed: ${error.message}`; + } finally { + execution.pending.delete("check_run"); + ctx.render(); + ctx.refresh().catch(ctx.showError); + } +} + +function cancelRunMessage(runId, response) { + if (response.is_error) + return `Could not cancel ${runId}: ${response.result?.error || "vkit rejected the request."}`; + return response.result?.cancelled + ? `Cancellation requested for ${runId}.` + : `${runId} is ${response.result?.state || "no longer running"}.`; +} + +export async function cancelRun(ctx, runId) { + const { execution, activeWorkspace, csrfToken } = ctx.state; + const key = `run_cancel:${runId}`; + if (execution.pending.has(key)) return; + execution.pending.add(key); + execution.runsMessage = `Cancelling ${runId}…`; + ctx.render(); + try { + execution.runsMessage = cancelRunMessage( + runId, + await callTool("run_cancel", { run_id: runId }, activeWorkspace, csrfToken), + ); + } catch (error) { + execution.runsMessage = `Could not cancel ${runId}: ${error.message}`; + } finally { + execution.pending.delete(key); + ctx.render(); + ctx.refresh().catch(ctx.showError); + } +} + +export function checks(ctx) { + const { report, execution } = ctx.state; + const fragment = document.createDocumentFragment(); + const grid = table( + ["CHECK", "STATE", "METHOD", "INPUT SCOPE", "LAST RUN", "ACTION"], + "checks", + ); + const runNeeded = consoleButton("Run needed checks"); + runNeeded.disabled = + execution.pending.has("check_run") || !report.needs_run?.length; + const feedback = el("p", execution.checksMessage, "action-feedback"); + feedback.setAttribute("role", "status"); + feedback.setAttribute("aria-live", "polite"); + feedback.hidden = !execution.checksMessage; + const feedbackBody = el("div", null, "panel-body"); + feedbackBody.append(feedback); + const runPanel = panel( + "Run needed checks", + "Start checks with stale or missing evidence. Each run records its own scope.", + [feedbackBody], + runNeeded, + ); + runNeeded.onclick = () => runChecks(ctx, { needed: true, wait_seconds: 0 }); + function update() { + const shown = report.checks.filter( + (c) => matches(ctx, c) && (!ctx.state.kind || c.kind === ctx.state.kind), + ); + grid.body.replaceChildren( + ...shown.map((c) => { + const copy = el("div"); + copy.append(link(c.id, () => showCheck(ctx, c.id)), el("p", c.description)); + const last = c.last + ? link(`${c.last.result} · ${date(c.last.ended_at)}`, () => { + location.hash = `runs/${encodeURIComponent(c.last.run_id)}`; + }) + : "Not run"; + const run = consoleButton(c.running.length ? "Running" : "Run", "text"); + run.setAttribute("aria-label", `Run check ${c.id}`); + run.disabled = c.running.length > 0 || execution.pending.has("check_run"); + run.onclick = () => runChecks(ctx, { check_ids: [c.id], wait_seconds: 0 }); + return row([ + copy, + badge(checkState(c)), + methods[c.kind]?.[0] || c.kind, + c.inputs.scope, + last, + run, + ]); + }), + ); + if (!shown.length) { + const tr = el("tr"); + const td = el("td"); + td.colSpan = 6; + td.append( + empty( + "No matching checks", + report.checks.length + ? "Try another search or verification method." + : "This workspace has no registered checks.", + "checks", + ), + ); + tr.append(td); + grid.body.append(tr); + } + } + fragment.append(runPanel, toolbar(ctx, "Search checks", update, true), grid.wrap); + update(); + if (report.formal?.length) fragment.append(formalPanel(report)); + return fragment; +} + +export function runHistory(ctx) { + const { runs, execution, selectedRun } = ctx.state; + const fragment = document.createDocumentFragment(); + const grid = table( + ["CHECK / RUN", "RESULT", "STARTED", "WORKTREE", "ACTION"], + "runs", + ); + const feedback = el("p", execution.runsMessage, "action-feedback run-feedback"); + feedback.setAttribute("role", "status"); + feedback.setAttribute("aria-live", "polite"); + feedback.hidden = !execution.runsMessage; + function update() { + const shown = runs.filter((item) => matches(ctx, item)); + grid.body.replaceChildren( + ...shown.map((r) => { + const copy = el("div"); + copy.append( + link(r.subject?.id || r.check_id, () => { + location.hash = `runs/${encodeURIComponent(r.run_id)}`; + }), + el("p", r.run_id), + ); + const cancel = consoleButton( + execution.pending.has(`run_cancel:${r.run_id}`) ? "Cancelling…" : "Cancel", + "text", + ); + cancel.setAttribute("aria-label", `Cancel run ${r.run_id}`); + cancel.disabled = + (r.state !== "running" && r.state !== "queued") || + execution.pending.has(`run_cancel:${r.run_id}`); + cancel.onclick = () => cancelRun(ctx, r.run_id); + return row([ + copy, + badge(r.result || r.state), + date(r.started_at), + r.worktree, + cancel, + ]); + }), + ); + if (!shown.length) { + const tr = el("tr"); + const td = el("td"); + td.colSpan = 5; + td.append( + empty( + "No matching runs", + runs.length + ? "Try another search." + : "Completed and active runs appear here when checks execute.", + "history", + ), + ); + tr.append(td); + grid.body.append(tr); + } + } + const detail = el("section", null, "panel run-selected"); + detail.id = "run-detail"; + detail.hidden = !selectedRun; + fragment.append(feedback, toolbar(ctx, "Search recent runs", update), grid.wrap, detail); + update(); + return fragment; +} + +export function showCheck(ctx, id) { + const { report, configuration } = ctx.state; + const check = report.checks.find((c) => c.id === id); + if (!check) return; + $("detail-title").textContent = id; + $("detail-label").textContent = methods[check.kind]?.[0].toUpperCase() || "CHECK"; + const body = $("detail-body"); + body.replaceChildren( + badge(checkState(check)), + el("p", check.description || "No description provided.", "dialog-description"), + ); + for (const [title, text] of [ + ["Establishes", check.establishes], + ["Does not establish", check.does_not_establish], + ["Inputs", check.inputs.declared.join(", ") || "Whole eligible repository tree"], + ]) { + const section = el("section", null, "dialog-section"); + section.append(el("h3", title), el("p", text)); + body.append(section); + } + if (check.inputs.unmatched.length) + body.append(note("Missing declared inputs", check.inputs.unmatched.join(", "))); + if (check.last) + body.append( + action("Inspect last run", `runs/${encodeURIComponent(check.last.run_id)}`, "md-outlined-button"), + ); + const definition = configuration?.definitions?.[id]; + if (definition) { + const section = el("section", null, "dialog-section"); + section.append( + el("h3", "Registered definition"), + el("pre", JSON.stringify(definition, null, 2)), + ); + body.append(section); + } + if (!$("detail-dialog").open) $("detail-dialog").show(); +} + +export async function refreshRun(ctx) { + if (!ctx.state.selectedRun || ctx.state.activePage !== "runs") return; + const id = ctx.state.selectedRun; + const requestedStream = ctx.state.stream; + let detail; + try { + detail = await apiGet( + `/api/run?id=${encodeURIComponent(id)}&log=${requestedStream}&offset=-16000`, + ctx.state.activeWorkspace, + ); + } catch (error) { + if (error.status === 404) { + if (id !== ctx.state.selectedRun || ctx.state.activePage !== "runs") return; + const box = $("run-detail"); + if (!box) return; + box.dataset.signature = `missing:${id}`; + box.hidden = false; + box.replaceChildren( + empty( + "Run not found", + `Run ${id} is no longer available in this workspace.`, + "history", + ), + ); + return; + } + throw error; + } + if (id !== ctx.state.selectedRun || requestedStream !== ctx.state.stream || ctx.state.activePage !== "runs") + return; + const box = $("run-detail"); + if (!box) return; + const detailSignature = JSON.stringify(detail); + if (box.dataset.signature === detailSignature) return; + const logWasFocused = document.activeElement?.id === "run-log"; + box.dataset.signature = detailSignature; + box.hidden = false; + box.replaceChildren(); + const header = el("div", null, "panel-header"); + const title = el("div"); + title.append(el("h2", detail.subject?.id || detail.check_id), el("p", id)); + header.append(title, badge(detail.outcome?.result || detail.state)); + box.append(header); + const body = el("div", null, "panel-body"); + const meta = el("div", null, "run-meta"); + meta.append( + el("span", `Started ${date(detail.started_at)}`), + el("span", `Finished ${date(detail.ended_at)}`), + el("span", `${detail.inputs?.scope || ""}`), + ); + body.append(meta); + if (detail.outcome?.detail) + body.append( + note(detail.outcome.reason?.replaceAll("_", " ") || "Outcome", detail.outcome.detail), + ); + for (const scenario of detail.outcome?.scenarios || []) { + const entry = el("div", null, "result-row"); + const copy = el("div", null, "row-copy"); + copy.append(el("h3", scenario.id), el("p", scenario.observation)); + entry.append(badge(scenario.result), copy); + body.append(entry); + } + if (detail.measurements?.length) { + const measurements = el("div", null, "measurement-grid"); + for (const m of detail.measurements) { + const item = el("div"); + item.append( + el("span", m.name, "small quiet"), + el("strong", `${m.value} ${m.unit}`), + el("small", `${m.better} is better${m.baseline != null ? ` · baseline ${m.baseline}` : ""}`), + ); + measurements.append(item); + } + body.append(measurements); + } + for (const finding of detail.findings || []) + body.append( + note(`${finding.rule} · ${finding.path}${finding.line ? ":" + finding.line : ""}`, finding.message), + ); + for (const text of detail.unchecked_budgets || []) + body.append(note("Budget not checked", text)); + if (detail.obligations) { + const obligations = el("section", null, "dialog-section"); + obligations.append(el("h3", "Formal obligations"), el("pre", JSON.stringify(detail.obligations, null, 2))); + body.append(obligations); + } + const provenance = el("details", null, "dialog-section"); + provenance.append(el("summary", "Recorded inputs and execution")); + provenance.append( + el( + "pre", + JSON.stringify( + { + category: detail.category, + worktree: detail.worktree, + check_digest: detail.check_digest, + evidence_key: detail.key, + inputs: detail.inputs, + command: detail.argv, + exit_code: detail.exit_code, + environment: detail.environment, + }, + null, + 2, + ), + ), + ); + body.append(provenance); + const logHeader = el("div", null, "log-header"); + const select = selectControl("Log stream", [["stdout", "stdout"], ["stderr", "stderr"]], ctx.state.stream); + select.id = "run-log"; + select.onchange = () => { + ctx.state.stream = select.value; + refreshRun(ctx).catch(ctx.showError); + }; + logHeader.append(el("h3", "Execution log"), select); + const log = el("pre", detail.log?.text || "No output in this stream."); + log.id = "run-text"; + body.append(logHeader, log); + if (detail.log?.size > 16000) + body.append(el("p", "Showing the last 16,000 bytes.", "small quiet")); + box.append(body); + if (logWasFocused) select.focus(); +} diff --git a/src/vkit/console/static/js/views/overview.js b/src/vkit/console/static/js/views/overview.js new file mode 100644 index 0000000..09da09d --- /dev/null +++ b/src/vkit/console/static/js/views/overview.js @@ -0,0 +1,466 @@ +import { + action, + badge, + checkState, + command, + date, + el, + empty, + icon, + isManifestMissing, + labels, + link, + matches, + methods, + note, + panel, + toolbar, + workspaceAnchor, + workspaceLabel, +} from "../ui.js"; + +export function checkRow(ctx, check) { + const box = el("div", null, "check-row"); + const symbol = el("div", null, "kind-icon"); + const copy = el("div", null, "row-copy"); + symbol.append(icon(methods[check.kind]?.[1] || "checks")); + copy.append( + link(check.id, () => ctx.showCheck(check.id)), + el("p", `${methods[check.kind]?.[0] || check.kind} · ${check.inputs.scope}`), + ); + box.append(symbol, copy, badge(checkState(check))); + return box; +} + +export function activityRow(run) { + const box = el("div", null, "activity-row"); + const copy = el("div", null, "row-copy"); + copy.append( + link(run.subject?.id || run.check_id, () => { + location.hash = `runs/${encodeURIComponent(run.run_id)}`; + }), + el("p", date(run.ended_at || run.started_at)), + ); + box.append(copy, badge(run.result || run.state)); + return box; +} + +export function formalPanel(report) { + return panel( + "Formal components", + "Required API contracts checked by Verus under the recorded trusted engine. Each pass covers its declared component.", + report.formal.map((component) => { + const box = el("div", null, "check-row"); + const copy = el("div", null, "row-copy"); + copy.append(el("strong", component.id), el("p", component.detail || component.description)); + if (component.last) + copy.append(action("Inspect last run", `runs/${encodeURIComponent(component.last.run_id)}`)); + box.append(copy, badge(checkState(component))); + return box; + }), + ); +} + +export function projectOverview(ctx) { + const { report, runs } = ctx.state; + const fragment = document.createDocumentFragment(); + const banner = el("section", null, "verdict-banner"); + banner.dataset.verdict = report.gate.verdict; + const symbol = el("div", null, "verdict-icon"); + symbol.append( + icon( + report.gate.verdict === "READY" || report.gate.verdict === "READY_SCOPED" + ? "check" + : report.gate.verdict === "REJECTED" + ? "error" + : "schedule", + ), + ); + const copy = el("div", null, "verdict-copy"); + const titles = { + READY: "Current evidence is ready", + READY_SCOPED: "Scoped evidence is ready", + REJECTED: "A current check failed", + BLOCKED: isManifestMissing(report.manifest_error) ? "Not set up" : "Evidence is incomplete", + }; + copy.append( + el("h2", titles[report.gate.verdict] || "Evidence status"), + el("p", report.manifest_error || report.gate.reason), + ); + banner.append( + symbol, + copy, + isManifestMissing(report.manifest_error) + ? action("Set up workspace", "setup", "md-filled-tonal-button") + : action("Inspect checks", "checks", "md-filled-tonal-button"), + ); + fragment.append(banner); + const metrics = el("div", null, "metrics"); + const passed = report.checks.filter((c) => c.state === "fresh_pass").length; + const running = new Set(report.checks.flatMap((c) => c.running)).size; + for (const [value, label, description] of [ + [report.checks.length, "Registered checks", "Defined for this workspace"], + [passed, "Current passes", "Against the current inputs"], + [running, "Active runs", "Visible in recent history"], + [ + report.features.filter((f) => f.verified).length, + "Verified features", + `${report.features.length} mapped features`, + ], + ]) { + const metric = el("div", null, "metric"); + metric.append( + el("span", value, "metric-value"), + el("span", label, "metric-label"), + el("span", description, "metric-note"), + ); + metrics.append(metric); + } + fragment.append(metrics); + if (report.formal?.length) fragment.append(formalPanel(report)); + const grid = el("div", null, "overview-grid"); + const left = el("div", null, "stack"); + const right = el("div", null, "stack"); + const attention = report.checks.filter((c) => c.state !== "fresh_pass"); + left.append( + panel( + "Evidence to review", + `${attention.length} of ${report.checks.length} checks lack a current pass`, + attention.length + ? attention.slice(0, 6).map((c) => checkRow(ctx, c)) + : [ + empty( + report.checks.length + ? "Every check has current evidence" + : "No checks registered", + report.checks.length + ? "Inspect individual checks to see what each pass establishes." + : "Register reusable checks in verification/manifest.json.", + "check", + ), + ], + action("All checks", "checks"), + ), + ); + left.append( + panel( + "Recent activity", + "Latest recorded executions", + runs.length + ? runs.slice(0, 4).map(activityRow) + : [ + empty( + "No recorded runs", + "Run history will show outcomes, observations, and logs once a check executes.", + "history", + ), + ], + action("Run history", "runs"), + ), + ); + const body = el("div", null, "panel-body"); + const steps = el("ol", null, "steps"); + [ + ["Define", "A check names its inputs, procedure, and required observations."], + ["Execute", "Vkit handles the registered procedure and reads its report."], + ["Record", "Results retain their inputs, scope, measurements, and logs."], + ["Check freshness", "Relevant file changes make earlier evidence stale."], + ].forEach(([title, text], i) => { + const step = el("li"); + const textBox = el("div"); + textBox.append(el("h3", title), el("p", text)); + step.append(el("span", i + 1, "step-number"), textBox); + steps.append(step); + }); + body.append( + steps, + note( + "What “ready” means", + "Every registered check passed against its current inputs. Features without checks and behavior outside those requirements remain unverified.", + ), + ); + right.append( + panel("How verification works", "Reusable procedures. Recorded evidence.", [body]), + ); + const methodsBody = el("div", null, "panel-body"); + methodsBody.append( + el( + "p", + `${new Set(report.checks.map((c) => c.kind)).size} of ${Object.keys(methods).length} verification methods are configured in this workspace.`, + "small quiet", + ), + action("Explore capabilities", "capabilities"), + ); + right.append( + panel("Verification methods", "From application scenarios to formal statements", [methodsBody]), + ); + grid.append(left, right); + fragment.append(grid); + return fragment; +} + +function proposalCard(proposal, workspace) { + const entry = el("article", null, "proposal"); + const changes = el("div", null, "check-chips"); + const targets = workspace.workspaces || [workspace]; + const primary = targets[0]; + entry.append( + el("code", (proposal.digest || "").slice(0, 12), "quiet"), + el("h3", proposal.rationale || "Suggested project changes"), + el( + "p", + targets.length > 1 + ? `Pending in ${targets.length} worktrees for this repository. Choose where to review it.` + : `${workspaceLabel(primary)} · ${primary?.path || ""}`, + "small quiet", + ), + ); + for (const [label, values] of [ + ["Checks", proposal.checks || []], + ["Features", proposal.features || []], + ["New files", proposal.files || []], + ]) + if (values.length) + changes.append(el("span", `${label}: ${values.join(", ")}`, "small quiet")); + entry.append(changes); + const links = el("div", null, "workspace-proposal-links"); + for (const target of targets) + links.append(workspaceAnchor(`Open in ${workspaceLabel(target)}`, target.id, "proposals", "workspace-open-link")); + entry.append(links); + return entry; +} + +export function allProposalItems(workspaceSummary) { + const items = new Map(); + for (const workspace of workspaceSummary) { + for (const proposal of workspace.pending_proposals || []) { + const key = `${workspace.repository_id || workspace.id}:${proposal.digest}`; + const item = items.get(key) || { proposal, workspace, workspaces: [] }; + item.workspaces.push(workspace); + items.set(key, item); + } + } + return [...items.values()]; +} + +export function allProposalList(ctx, items = allProposalItems(ctx.state.workspaceSummary), className = "panel") { + const list = el("section", null, className); + if (!items.length) { + list.append(empty( + "No pending proposals", + "Proposals appear here after an agent submits changes for a remembered workspace.", + "proposals", + )); + return list; + } + for (const item of items) list.append(proposalCard(item.proposal, item)); + return list; +} + +export function allOverview(ctx) { + const { workspaceSummary } = ctx.state; + const fragment = document.createDocumentFragment(); + const total = workspaceSummary.length; + const available = workspaceSummary.filter((workspace) => workspace.available); + const ready = available.filter((workspace) => workspace.gate?.verdict === "READY").length; + const pending = allProposalItems(workspaceSummary); + const checks = workspaceSummary.reduce((count, workspace) => count + (workspace.checks?.length || 0), 0); + const metrics = el("div", null, "metrics"); + for (const [value, label, description] of [ + [total, "Remembered workspaces", `${available.length} available`], + [ready, "Ready workspaces", "Current required evidence passes"], + [checks, "Registered checks", "Across remembered workspaces"], + [pending.length, "Pending proposals", "Waiting for project review"], + ]) { + const metric = el("div", null, "metric"); + metric.append(el("span", value, "metric-value"), el("span", label, "metric-label"), el("span", description, "metric-note")); + metrics.append(metric); + } + fragment.append(metrics); + const workspaceList = el("div", null, "workspace-list"); + for (const workspace of workspaceSummary) { + const item = el("article", null, "workspace-summary-row"); + const copy = el("div", null, "row-copy"); + const gate = workspace.available ? workspace.gate?.verdict || "BLOCKED" : "UNAVAILABLE"; + const seen = workspace.last_seen + ? ` · Last seen ${date(workspace.last_seen)} via ${workspace.source || "VKit"}` + : ""; + copy.append(el("h3", workspaceLabel(workspace)), el("p", `${workspace.path || ""}${seen}`, "small quiet")); + if (!workspace.available) + copy.append(el("p", workspace.error || "This path is unavailable. Add the workspace again after moving it.", "small quiet")); + else if (isManifestMissing(workspace.manifest_error)) + copy.append(el("p", "Not set up. Add verification/manifest.json to register checks.", "small quiet")); + else if (workspace.manifest_error) + copy.append(el("p", `Manifest needs attention: ${workspace.manifest_error}`, "small quiet")); + else + copy.append(el("p", `${workspace.checks?.filter((check) => check.state === "fresh_pass").length || 0} of ${workspace.checks?.length || 0} checks have current passing evidence.`, "small quiet")); + item.append(copy, badge(gate), workspaceAnchor("Open", workspace.id, "overview", "workspace-open-link")); + workspaceList.append(item); + } + if (!total) + workspaceList.append(empty("No workspaces remembered", "Add a repository path in the left panel. VKit remembers only paths you open or add; it does not scan folders.", "folder")); + fragment.append(panel("Workspaces", "Each workspace keeps its own checks, evidence, settings, and proposals.", [workspaceList])); + fragment.append(panel("Pending proposal inbox", "Review each proposal in the workspace that owns it.", [ + allProposalList(ctx, pending.slice(0, 5), "proposal-list"), + ...(pending.length > 5 ? [workspaceAnchor("View all proposals", "all", "proposals", "workspace-open-link")] : []), + ])); + return fragment; +} + +export function overview(ctx) { + return ctx.state.activeWorkspace === "all" ? allOverview(ctx) : projectOverview(ctx); +} + +export function capabilities(ctx) { + const { activeWorkspace, workspaceSummary, workspaceRegistry, report, configuration } = ctx.state; + const fragment = document.createDocumentFragment(); + const list = el("section", null, "panel"); + for (const [key, [title, symbol, text, limit]] of Object.entries(methods)) { + const entry = el("div", null, "capability"); + const visual = el("div", null, "kind-icon"); + const copy = el("div"); + visual.append(icon(symbol)); + copy.append(el("h3", title), el("p", text), el("p", limit, "limit")); + const count = activeWorkspace === "all" + ? workspaceSummary.filter((workspace) => (workspace.checks || []).some((check) => check.kind === key)).length + : report.checks.filter((c) => c.kind === key).length; + entry.append( + visual, + copy, + el( + "span", + count + ? activeWorkspace === "all" + ? `${count} workspace${count === 1 ? "" : "s"}` + : `${count} check${count === 1 ? "" : "s"} registered` + : "No checks registered", + "capability-count", + ), + ); + list.append(entry); + } + fragment.append(list, el("h2", "Functions available to agents", "section-label")); + const tools = el("div", null, "tool-grid"); + const managedTools = activeWorkspace === "all" + ? workspaceRegistry?.managed_tools || [] + : configuration?.managed_tools || []; + for (const { name, description, category } of managedTools) { + const item = el("div", null, "tool-item"); + item.append(el("code", name), el("p", description), el("p", category || "", "small quiet")); + tools.append(item); + } + if (!managedTools.length) + tools.append(el("p", "The workspace registry has no function catalog yet.", "small quiet")); + fragment.append( + panel( + `${managedTools.length} functions in this installation`, + activeWorkspace === "all" + ? "Functions come from this VKit installation. Project settings and agent exposure can change which ones are available in a workspace." + : "These functions come from this console's VKit installation. Workspace settings can limit which functions agents can use.", + [tools], + ), + ); + return fragment; +} + +export function featureMap(ctx) { + const { report } = ctx.state; + const fragment = document.createDocumentFragment(); + const list = el("section", null, "panel"); + function update() { + const opened = new Set( + [...list.querySelectorAll("details[open]")].map((d) => d.dataset.feature), + ); + const shown = report.features.filter((item) => matches(ctx, item)); + list.replaceChildren( + ...shown.map((f) => { + const entry = el("details", null, "feature-row"); + entry.dataset.feature = f.id; + entry.open = opened.has(f.id); + const summary = el("summary"); + const copy = el("div", null, "row-copy"); + copy.append(el("h3", f.id), el("p", f.behavior)); + summary.append(copy, badge(f.verified ? "verified" : "unverified"), icon("expand")); + const content = el("div", null, "feature-content"); + const grid = el("div", null, "detail-grid"); + for (const [title, lines] of [ + ["How to reach it", f.how_to_reach], + ["Entry points", f.entry_points], + ]) { + const section = el("div", null, "detail-section"); + const ul = el("ul"); + for (const text of lines) ul.append(el("li", text)); + section.append( + el("h3", title), + lines.length ? ul : el("p", "Not documented", "small quiet"), + ); + grid.append(section); + } + content.append(grid); + const coverage = el("div", null, "dialog-section"); + const chips = el("div", null, "check-chips"); + for (const c of f.checks) { + chips.append(link( + `${c.id} · ${labels[c.state]?.[0] || c.state}`, + () => ctx.showCheck(c.id), + )); + } + coverage.append( + el("h3", "Covering checks"), + f.checks.length ? chips : el("p", "No check covers this feature.", "small quiet"), + ); + content.append(coverage); + if (f.gaps.length || f.problems.length) + content.append(note("Known gaps", [...f.gaps, ...f.problems].join(" · "))); + entry.append(summary, content); + return entry; + }), + ); + if (!shown.length) + list.append( + empty( + "No matching features", + report.feature_error || + (report.features.length + ? "Try another search." + : "The feature map is authored in verification/features.json. Add user-visible behavior, how to reach it, entry points, and the checks that cover it."), + "features", + ), + ); + } + fragment.append(toolbar(ctx, "Search features", update), list); + update(); + return fragment; +} + +function projectProposals(ctx) { + const { report } = ctx.state; + const list = el("section", null, "panel"); + for (const p of report.proposals) { + const entry = el("article", null, "proposal"); + entry.append(el("code", p.digest.slice(0, 12), "quiet"), el("h3", p.rationale)); + const changes = el("div", null, "check-chips"); + for (const [label, values] of [ + ["Checks", p.checks], + ["Features", p.features], + ["New files", p.files], + ]) + if (values.length) + changes.append(el("span", `${label}: ${values.join(", ")}`, "small quiet")); + entry.append(changes, command(p.accept)); + list.append(entry); + } + if (!report.proposals.length) + list.append( + empty( + "No proposals waiting for review", + "Agents can suggest reusable checks and verification rules. Suggested changes appear here before they are accepted.", + "proposals", + ), + ); + return list; +} + +export function proposals(ctx) { + return ctx.state.activeWorkspace === "all" ? allProposalList(ctx) : projectProposals(ctx); +} diff --git a/src/vkit/console/static/js/views/settings.js b/src/vkit/console/static/js/views/settings.js new file mode 100644 index 0000000..fa046bd --- /dev/null +++ b/src/vkit/console/static/js/views/settings.js @@ -0,0 +1,561 @@ +import { apiPost } from "../api.js"; +import { + $, + command, + consoleButton, + el, + icon, + isManifestMissing, + note, + panel, + selectControl, + textField, + workspaceRequired, +} from "../ui.js"; + +export function mergeSettingsDraft(draft, next, previous) { + return Object.fromEntries(Object.keys(next).map((key) => [ + key, + !draft || JSON.stringify(draft[key]) === JSON.stringify(previous?.[key]) + ? next[key] + : draft[key], + ])); +} + +function setPreferenceFeedback(message) { + const status = $("preference-feedback"); + status.hidden = !message; + status.textContent = message; +} + +function toolAvailable(settingsDraft, tool) { + return !settingsDraft.disabled_tools.includes(tool.name) && + !settingsDraft.disabled_categories.includes(tool.category); +} + +function enabledToolsSummary(configuration, settingsDraft) { + const tools = configuration.managed_tools; + const enabled = tools.filter((tool) => toolAvailable(settingsDraft, tool)).length; + return `${enabled} of ${tools.length} tools enabled. Help and compact invocation remain available.`; +} + +export function syncSettingsForm(ctx) { + const { configuration, settingsDraft, settingsMessage, settingsSaving } = ctx.state; + for (const id of ["settings-message", "tools-message"]) { + const status = $(id); + if (!status) continue; + status.textContent = settingsMessage; + status.dataset.state = settingsMessage.startsWith("Could not") ? "error" : ""; + } + const summary = $("settings-tools-summary"); + if (summary && configuration && settingsDraft) + summary.textContent = enabledToolsSummary(configuration, settingsDraft); + if (settingsDraft && configuration) { + for (const checkbox of document.querySelectorAll("#tools-body [data-tool]")) { + checkbox.checked = !settingsDraft.disabled_tools.includes(checkbox.dataset.tool); + checkbox.disabled = settingsSaving || settingsDraft.disabled_categories.includes(checkbox.dataset.category); + } + for (const checkbox of document.querySelectorAll("#tools-body [data-category-toggle]")) { + checkbox.checked = !settingsDraft.disabled_categories.includes(checkbox.dataset.categoryToggle); + checkbox.disabled = settingsSaving; + } + for (const checkbox of document.querySelectorAll("#tools-body [data-scope]")) { + checkbox.checked = settingsDraft.mcp_categories === null || settingsDraft.mcp_categories.includes(checkbox.dataset.scope); + checkbox.disabled = settingsSaving || settingsDraft.mcp_categories === null; + } + for (const count of document.querySelectorAll("#tools-body [data-category-count]")) { + const tools = configuration.managed_tools.filter((tool) => tool.category === count.dataset.categoryCount); + count.textContent = `${tools.filter((tool) => toolAvailable(settingsDraft, tool)).length} of ${tools.length} tools available`; + } + const allScope = $("all-agent-categories"); + if (allScope) { + allScope.checked = settingsDraft.mcp_categories === null; + allScope.disabled = settingsSaving; + } + } + $("save-tools-settings").disabled = settingsSaving; + const save = $("settings-save"); + const reset = $("settings-reset"); + if (save) save.disabled = settingsSaving; + if (reset) reset.disabled = settingsSaving; + if ($("theme-toggle")) $("theme-toggle").disabled = !configuration || settingsSaving; + if ($("collapse-nav")) $("collapse-nav").disabled = !configuration || settingsSaving; +} + +export function applySettings(ctx, settings) { + if (!settings) return; + ctx.applyTheme(settings.theme); + ctx.collapse(settings.sidebar_collapsed); +} + +export function validateSettingsDraft(settingsDraft) { + if (!settingsDraft || !["system", "light", "dark"].includes(settingsDraft.theme)) + return "Choose system, light, or dark theme."; + for (const [key, label, minimum, maximum] of [ + ["refresh_seconds", "Refresh interval", 1, 60], + ["history_limit", "Run history limit", 1, 200], + ]) { + const value = settingsDraft[key]; + if (!Number.isInteger(value) || value < minimum || value > maximum) + return `${label} must be between ${minimum} and ${maximum}.`; + } + return ""; +} + +export async function persistSettings(ctx, candidate, source = "form") { + const { state } = ctx; + if (state.settingsSaving) return; + const previous = { ...state.configuration.settings }; + const draftAtRequest = { ...state.settingsDraft }; + const snapshot = { ...candidate }; + state.settingsSaving = true; + state.settingsMessage = source === "reset" ? "Resetting defaults…" : "Saving settings…"; + if (source === "preference") setPreferenceFeedback(state.settingsMessage); + syncSettingsForm(ctx); + try { + const response = await apiPost("/api/settings", snapshot, state.activeWorkspace, state.csrfToken); + state.configuration.settings = response.settings; + state.configuration.settings_path = response.settings_path; + state.settingsVersion += 1; + state.settingsDraft = Object.fromEntries( + Object.keys(state.configuration.settings_defaults).map((key) => [ + key, + JSON.stringify(state.settingsDraft[key]) !== JSON.stringify(draftAtRequest[key]) + ? state.settingsDraft[key] + : source === "preference" && JSON.stringify(draftAtRequest[key]) !== JSON.stringify(previous[key]) + ? draftAtRequest[key] + : response.settings[key], + ]), + ); + applySettings(ctx, state.settingsDraft); + const hasUnsavedChanges = Object.keys(response.settings).some( + (key) => JSON.stringify(state.settingsDraft[key]) !== JSON.stringify(response.settings[key]), + ); + state.settingsMessage = hasUnsavedChanges + ? "Settings saved. Unsaved changes remain." + : source === "reset" + ? "Defaults saved." + : "Settings saved."; + if (source === "preference") setPreferenceFeedback(state.settingsMessage); + } catch (error) { + state.settingsMessage = `Could not save settings: ${error.message}`; + if (source === "preference") setPreferenceFeedback(state.settingsMessage); + } finally { + state.settingsSaving = false; + syncSettingsForm(ctx); + ctx.refresh().catch(ctx.showError); + } +} + +export function saveSettingsDraft(ctx) { + const error = validateSettingsDraft(ctx.state.settingsDraft); + if (error) { + ctx.state.settingsMessage = `Could not save settings: ${error}`; + syncSettingsForm(ctx); + return; + } + persistSettings(ctx, ctx.state.settingsDraft); +} + +export function resetSettings(ctx) { + ctx.state.settingsDraft = { ...ctx.state.configuration.settings_defaults }; + ctx.state.settingsMessage = "Resetting defaults…"; + applySettings(ctx, ctx.state.settingsDraft); + ctx.render(); + persistSettings(ctx, ctx.state.settingsDraft, "reset"); +} + +export function updatePreference(ctx, key, value) { + if (!ctx.state.configuration || ctx.state.settingsSaving) return; + ctx.state.settingsDraft = { ...ctx.state.settingsDraft, [key]: value }; + applySettings(ctx, ctx.state.settingsDraft); + persistSettings(ctx, { ...ctx.state.configuration.settings, [key]: value }, "preference"); +} + +export function showTools(ctx) { + const { configuration, settingsMessage } = ctx.state; + const tools = configuration.managed_tools; + const title = "Tools available to agents"; + const search = textField("Search tools", "", "search"); + const list = el("div", null, "tools-list"); + const count = el("p", null, "small quiet"); + const status = el("p", settingsMessage, "settings-message"); + const category = selectControl("Category", [ + ["", "All categories"], + ...configuration.categories + .filter((group) => tools.some((tool) => tool.category === group.id)) + .map((group) => [group.id, group.label]), + ], ""); + search.id = "tools-search"; + search.setAttribute("autofocus", ""); + count.setAttribute("role", "status"); + status.id = "tools-message"; + status.setAttribute("role", "status"); + const filter = () => { + const query = search.value.trim().toLowerCase(); + const matched = tools.filter((tool) => + (!category.value || tool.category === category.value) && + `${tool.name} ${tool.description}`.toLowerCase().includes(query), + ); + list.replaceChildren(); + for (const group of configuration.categories) { + const members = matched.filter((tool) => tool.category === group.id); + if (!members.length) continue; + const section = el("section", null, "tool-category"); + section.append(el("h3", group.label)); + const available = el("p", null, "field-help"); + available.dataset.categoryCount = group.id; + for (const [key, text] of [["categoryToggle", "Enable category"], ["scope", "Include in agent scope"]]) { + const checkbox = el("md-checkbox"); + const label = el("label", null, "form-checkbox"); + checkbox.dataset[key] = group.id; + checkbox.setAttribute("aria-label", `${text}: ${group.label}`); + label.append(checkbox, el("span", text)); + section.append(label); + } + section.append(available); + for (const tool of members) { + const checkbox = el("md-checkbox"); + const label = el("span"); + const item = el("label", null, "form-checkbox tool-option"); + checkbox.dataset.tool = tool.name; + checkbox.dataset.category = tool.category; + checkbox.setAttribute("aria-label", tool.name); + label.append(el("span", tool.name), el("span", tool.description, "field-help")); + item.append(checkbox, label); + section.append(item); + } + list.append(section); + } + if (!matched.length) list.append(el("p", "No tools match your search.", "field-help")); + count.textContent = `${matched.length} of ${tools.length} tools shown`; + syncSettingsForm(ctx); + }; + search.addEventListener("input", filter); + category.addEventListener("input", filter); + const change = (event) => { + if (ctx.state.settingsSaving) return; + const data = event.target.dataset; + if (event.target.id === "all-agent-categories") { + ctx.state.settingsDraft.mcp_categories = event.target.checked ? null : []; + } else { + const key = data.tool ? "disabled_tools" : data.categoryToggle ? "disabled_categories" : "mcp_categories"; + const name = data.tool || data.categoryToggle || data.scope; + if (!name) return; + const values = new Set(ctx.state.settingsDraft[key]); + const include = key === "mcp_categories" ? event.target.checked : !event.target.checked; + if (include) values.add(name); + else values.delete(name); + ctx.state.settingsDraft[key] = [...values].sort(); + } + ctx.state.settingsMessage = "Unsaved settings."; + syncSettingsForm(ctx); + }; + list.addEventListener("input", change); + const scope = el("label", null, "form-checkbox"); + const allScope = el("md-checkbox"); + allScope.id = "all-agent-categories"; + allScope.setAttribute("aria-label", "Include all enabled categories in agent scope"); + allScope.addEventListener("input", change); + scope.append(allScope, el("span", "Include all enabled categories in agent scope")); + $("tools-title").textContent = title; + $("tools-dialog").setAttribute("aria-label", title); + $("save-tools-settings").hidden = false; + status.hidden = false; + $("tools-body").replaceChildren( + el("p", "Category switches preserve individual tool choices. Agent scope only narrows enabled tools. Save changes; reconnect agents after changing exposure or scope.", "field-help"), + search, category, scope, count, list, status, + ); + filter(); + $("tools-dialog").show(); +} + +export function settingsForm(ctx) { + const { configuration, settingsDraft, settingsMessage } = ctx.state; + const form = el("form", null, "settings-form"); + const fields = el("div", null, "form-grid"); + form.id = "settings-form"; + const themeField = el("div", null, "form-field"); + const theme = selectControl("Color theme", [ + ["system", "Use system setting"], + ["light", "Light"], + ["dark", "Dark"], + ], settingsDraft.theme); + theme.id = "settings-theme"; + theme.dataset.setting = "theme"; + theme.supportingText = "Follow the device theme or choose one."; + themeField.append(theme); + fields.append(themeField); + const exposure = selectControl("MCP exposure", [ + ["compact", "Compact: help and invoke"], + ["named", "Named: individual tools"], + ], settingsDraft.mcp_exposure); + exposure.dataset.setting = "mcp_exposure"; + exposure.supportingText = "Compact loads schemas on request. Named preserves individual tool approval controls. Applies on reconnect."; + fields.append(exposure); + + const refreshField = el("div", null, "form-field"); + const refreshInput = textField( + "Refresh interval in seconds", + settingsDraft.refresh_seconds, + "number", + "Refresh workspace status and runs every 1 to 60 seconds.", + ); + refreshInput.id = "settings-refresh-seconds"; + refreshInput.dataset.setting = "refresh_seconds"; + refreshInput.min = "1"; + refreshInput.max = "60"; + refreshInput.step = "1"; + refreshField.append(refreshInput); + fields.append(refreshField); + + const historyField = el("div", null, "form-field"); + const historyInput = textField( + "Recent runs to load", + settingsDraft.history_limit, + "number", + "Load between 1 and 200 recent runs.", + ); + historyInput.id = "settings-history-limit"; + historyInput.dataset.setting = "history_limit"; + historyInput.min = "1"; + historyInput.max = "200"; + historyInput.step = "1"; + historyField.append(historyInput); + fields.append(historyField); + + const sidebar = el("md-switch"); + sidebar.id = "settings-sidebar-collapsed"; + sidebar.dataset.setting = "sidebar_collapsed"; + sidebar.selected = settingsDraft.sidebar_collapsed; + sidebar.setAttribute("aria-label", "Keep the sidebar collapsed"); + const toggle = el("label", null, "form-checkbox"); + toggle.append(sidebar, el("span", "Keep the sidebar collapsed")); + fields.append(toggle); + form.append(fields); + + const tools = el("div"); + const show = consoleButton("Show tools", "outlined"); + const summary = el("p", null, "field-help"); + show.setAttribute("aria-haspopup", "dialog"); + show.onclick = () => showTools(ctx); + summary.id = "settings-tools-summary"; + summary.textContent = enabledToolsSummary(configuration, settingsDraft); + tools.append(show, summary); + form.append(tools); + + const status = el("p", settingsMessage, "settings-message"); + status.id = "settings-message"; + status.setAttribute("role", "status"); + status.setAttribute("aria-live", "polite"); + const actions = el("div", null, "form-actions"); + const save = el("md-filled-button", "Save settings"); + save.type = "submit"; + save.id = "settings-save"; + const reset = consoleButton("Reset defaults", "text"); + reset.id = "settings-reset"; + reset.onclick = () => resetSettings(ctx); + actions.append(save, reset); + form.append(status, actions); + const change = (event) => { + const key = event.target.dataset.setting; + if (!key) return; + if (key === "sidebar_collapsed") ctx.state.settingsDraft[key] = event.target.selected; + else if (key === "refresh_seconds" || key === "history_limit") + ctx.state.settingsDraft[key] = event.target.value === "" ? "" : Number(event.target.value); + else ctx.state.settingsDraft[key] = event.target.value; + ctx.state.settingsMessage = "Unsaved settings."; + applySettings(ctx, ctx.state.settingsDraft); + syncSettingsForm(ctx); + }; + form.addEventListener("input", change); + form.addEventListener("submit", (event) => { + event.preventDefault(); + saveSettingsDraft(ctx); + }); + return form; +} + +export function launcherSettingsForm(ctx) { + const { configuration, launcherDraft, launcherMessage, launcherSaving } = ctx.state; + const form = el("form", null, "settings-form"); + const fields = el("div", null, "form-grid"); + form.id = "launcher-settings-form"; + form.append(el("p", configuration.launcher_settings_path, "small quiet")); + for (const [name, labelText, type] of [ + ["project", "Default repository", "text"], + ["port", "Web console port", "number"], + ["open_browser", "Open browser with vkit console", "checkbox"], + ]) { + const field = el( + type === "checkbox" ? "label" : "div", + null, + type === "checkbox" ? "form-checkbox" : "form-field", + ); + const input = type === "checkbox" + ? el("md-switch") + : textField(labelText, launcherDraft[name], type === "number" ? "number" : "text"); + const label = el("span", labelText); + input.id = `launcher-${name}`; + input.disabled = launcherSaving; + if (type === "checkbox") { + input.selected = launcherDraft[name]; + input.setAttribute("aria-label", labelText); + } + if (name === "port") { + input.min = "0"; + input.max = "65535"; + input.step = "1"; + input.required = true; + } + if (type !== "checkbox") + input.supportingText = name === "project" + ? "Use an absolute path. Blank uses the current directory." + : "Use 0 to choose a free port. Applies when the server next starts."; + input.addEventListener("input", () => { + ctx.state.launcherDraft[name] = type === "checkbox" + ? input.selected + : type === "number" + ? (input.value === "" ? "" : Number(input.value)) + : input.value.trim() || null; + }); + if (type === "checkbox") field.append(input, label); + else field.append(input); + fields.append(field); + } + const status = el("p", launcherMessage, "settings-message"); + const save = el("md-filled-button", "Save launch defaults"); + status.setAttribute("role", "status"); + save.type = "submit"; + save.disabled = launcherSaving; + form.append(fields, status, save); + form.addEventListener("submit", async (event) => { + event.preventDefault(); + if (ctx.state.launcherSaving) return; + const portValue = ctx.state.launcherDraft.port; + if (portValue === "" || !Number.isInteger(portValue) || portValue < 0 || portValue > 65535) { + ctx.state.launcherMessage = "Could not save launch defaults: Web console port must be a whole number between 0 and 65535."; + ctx.render(); + return; + } + const candidate = { ...ctx.state.launcherDraft }; + ctx.state.launcherSaving = true; + ctx.state.launcherMessage = "Saving launch defaults..."; + ctx.render(); + try { + const response = await apiPost("/api/launcher-settings", candidate, ctx.state.activeWorkspace, ctx.state.csrfToken); + ctx.state.launcherDraft = mergeSettingsDraft(ctx.state.launcherDraft, response.settings, candidate); + ctx.state.configuration.launcher_settings = response.settings; + ctx.state.settingsVersion += 1; + ctx.state.launcherMessage = "Launch defaults saved. They apply to the next command or launch."; + } catch (error) { + ctx.state.launcherMessage = `Could not save launch defaults: ${error.message}`; + } finally { + ctx.state.launcherSaving = false; + ctx.render(); + ctx.refresh().catch(ctx.showError); + } + }); + return form; +} + +export function setup(ctx) { + const { activeWorkspace, report, configuration, doctorReport } = ctx.state; + if (activeWorkspace === "all") + return workspaceRequired("Project setup and tool settings"); + const doctor = doctorReport || configuration.doctor || null; + if (!doctor && !ctx.state.doctorLoading) { + ctx.loadDoctor().catch(ctx.showError); + } + const isSetup = isManifestMissing(report.manifest_error); + const hasManifestError = Boolean(report.manifest_error); + const fragment = document.createDocumentFragment(); + const grid = el("div", null, "overview-grid"); + const project = el("div", null, "panel-body"); + const definitions = el("dl", null, "definition-list"); + for (const [name, value] of [ + ["Repository", report.project], + ["Evidence storage", doctor?.state_root || configuration.state_root || "Loading…"], + ["Console settings", configuration.settings_path], + ["Check definitions", "verification/manifest.json"], + ["Feature map", "verification/features.json"], + ["Version", configuration.version], + ]) { + const pair = el("div"); + pair.append(el("dt", name), el("dd", value)); + definitions.append(pair); + } + project.append( + definitions, + note( + "Input identity", + "Evidence depends on check definitions, input contents, and any pinned baseline. Undeclared dependencies can leave evidence apparently fresh.", + ), + ); + const prerequisites = el("div", null, "panel-body"); + if (!doctor) { + prerequisites.append(el("p", "Checking required tools…", "small quiet")); + } else { + const tools = new Map(); + for (const f of doctor.findings) { + const key = f.prerequisite || f.check; + if (!tools.has(key)) tools.set(key, { ...f, checks: [] }); + tools.get(key).checks.push(f.check); + } + for (const [name, item] of tools) { + const status = el("div", null, "tool-status"); + const copy = el("div", null, "row-copy"); + copy.append(el("h3", name), el("p", item.detail)); + status.append( + icon(item.ok ? "check" : "error"), + copy, + el("span", item.ok ? "Available" : "Missing", `status-badge ${item.ok ? "success" : "warning"}`), + ); + prerequisites.append(status); + } + if (!tools.size) + prerequisites.append( + el("p", "No prerequisites are declared by the registered checks.", "small quiet"), + ); + } + grid.append( + panel( + isSetup ? "Not set up" : "Project", + isSetup + ? "Ask your agent to define checks in verification/manifest.json and map application behavior in verification/features.json. Review the definitions with vkit accept --project , then open Checks to run them and Runs to inspect results." + : hasManifestError + ? `VKit could not load verification/manifest.json: ${report.manifest_error}` + : configuration.description, + [project], + ), + panel("Required tools", "Availability in the console server’s environment", [prerequisites]), + ); + const connection = el("div", null, "panel-body"); + connection.append( + command(JSON.stringify(configuration.mcp_config, null, 2), "MCP configuration"), + note( + "Selected repository", + "This configuration uses the current repository and Python environment. Paste it into your agent application's MCP settings, reconnect, and ask the agent to call help. The agent starts its own server; this web console can be closed.", + ), + ); + fragment.append( + grid, + panel( + "Launch defaults", + "Saved for this user, outside repositories. Explicit CLI options override these values.", + [launcherSettingsForm(ctx)], + ), + panel( + "Project settings", + "Preferences and tool availability are saved for this project.", + [settingsForm(ctx)], + ), + el("h2", "Connect an agent", "section-label"), + panel( + "MCP over stdio", + "Copy this JSON into your agent application's MCP configuration.", + [connection], + ), + ); + return fragment; +} diff --git a/src/vkit/console/workspaces.py b/src/vkit/console/workspaces.py index 214c235..1884198 100644 --- a/src/vkit/console/workspaces.py +++ b/src/vkit/console/workspaces.py @@ -10,9 +10,9 @@ from dataclasses import asdict, dataclass from pathlib import Path -from vkit.runtime.paths import Project, ProjectError, open_project from vkit.console.settings import launcher_settings_path from vkit.core.store import STATE_DIR, now, read_json +from vkit.runtime.paths import Project, ProjectError, open_project class WorkspaceError(ValueError): @@ -89,9 +89,10 @@ def _repository_token(common_path: Path, *, create: bool) -> str: def _connect() -> sqlite3.Connection: path = registry_path() path.parent.mkdir(parents=True, exist_ok=True) - connection = sqlite3.connect(path, timeout=30) + connection = sqlite3.connect(path, timeout=5) connection.row_factory = sqlite3.Row - connection.execute("PRAGMA busy_timeout = 30000") + connection.execute("PRAGMA journal_mode = WAL") + connection.execute("PRAGMA busy_timeout = 5000") return connection diff --git a/src/vkit/core/acceptance.py b/src/vkit/core/acceptance.py new file mode 100644 index 0000000..e238d9a --- /dev/null +++ b/src/vkit/core/acceptance.py @@ -0,0 +1,135 @@ +"""Pure zero-IO acceptance, inventory, provenance marker, and CLI exit-code logic.""" +from __future__ import annotations + +import json +import os +from collections.abc import Mapping +from typing import Any + +from vkit.kernel import def_change_kernel, run_exit_code_kernel, verdict_exit_code_kernel + +EXIT_OK = 0 +EXIT_FAILED = 1 +EXIT_INVALID = 2 +EXIT_BLOCKED = 3 +EXIT_INTERNAL = 4 +EXIT_UNAVAILABLE = 5 + +_RESULT_EXIT = {"PASS": EXIT_OK, "FAIL": EXIT_FAILED, "BLOCKED": EXIT_BLOCKED} +_VERDICT_EXIT = { + "READY": EXIT_OK, + "READY_SCOPED": EXIT_OK, + "REJECTED": EXIT_FAILED, + "FAILED": EXIT_FAILED, + "BLOCKED": EXIT_BLOCKED, +} + +AGENT_MARKERS = ("vkit_hook", "claude", "codex", "deepai", "aider", "mcp") +_LIST_FIELDS = ("required_scenarios", "required_tests", "scenarios", "inputs") + + +def run_exit_code(record: Mapping[str, Any], *, unfinished: int = EXIT_OK) -> int: + outcome = record.get("outcome") or {} + result = outcome.get("result") + state = record.get("state") + return run_exit_code_kernel(result, state, unfinished) + + +def verdict_exit_code(verdict: str) -> int: + return verdict_exit_code_kernel(verdict) + + +def _command_has_agent_marker(command: str) -> bool: + for raw in command.lower().split(): + token = raw.strip("\"'") + if not token: + continue + base = token.replace("\\", "/").rsplit("/", 1)[-1] + stem = os.path.splitext(base)[0] + if base in AGENT_MARKERS or stem in AGENT_MARKERS or any(base.startswith(f"{m}-") for m in AGENT_MARKERS): + return True + return False + + +def _def_change(old: Any, new: Any) -> tuple[str, list[str]]: + if not isinstance(old, dict): + return def_change_kernel(False, ()), ["prior accepted definition not recorded"] + changes = [(key, old.get(key), new.get(key)) for key in sorted(set(old) | set(new)) + if old.get(key) != new.get(key)] + if not changes: + return def_change_kernel(True, ()), [] + lines = [] + field_diffs = [] + for key, was, current in changes: + lines.append(f"{key}: {was!r} -> {current!r}") + if key in _LIST_FIELDS: + field_diffs.append(("list", was or [], current or [])) + elif key == "timeout_seconds": + field_diffs.append(("timeout", was, current)) + else: + field_diffs.append(("opaque", was, current)) + return def_change_kernel(True, field_diffs), lines + + +def _demonstrated_label(label: str, demo: dict[str, int] | None) -> str: + if label != "strengthening": + return label + if not demo or not demo["added"]: + return "strengthening (unproven: no rejection corpus)" + return f"strengthening (declared: {demo['added']} added obligation(s), not executed)" + + +def _corpus(prior_definition: Any, entry: Any) -> dict[str, int]: + prior = prior_definition if isinstance(prior_definition, dict) else {} + return {"added": sum(len(set(entry.get(key) or ()) - set(prior.get(key) or ())) for key in _LIST_FIELDS)} + + +def _prior_acceptances(approved: Mapping[str, Any], check_id: str) -> list[dict[str, Any]]: + records = [r for r in approved.values() + if r.get("kind") == "check_definition" and r.get("check_id") == check_id] + return sorted(records, key=lambda r: r.get("accepted_at") or "") + + +def _inventory_diff(previous: Mapping[str, Any] | None, inventory: Mapping[str, Any], + required: Mapping[str, bool] | None = None) -> list[str]: + if previous is None: + return [] + lines = [] + for key, prefix in (("checks", "obligation inventory: "), ("formal_required", "formal obligations: ")): + was, current = previous.get(key, {}), inventory[key] + delta = {"removed": sorted(set(was) - set(current)), "added": sorted(set(current) - set(was)), + "rebound": sorted(name for name in current if was.get(name) != current[name])} + if any(delta.values()): + lines.append(prefix + json.dumps(delta)) + lines += [f"formal obligation no longer required: {name} (still bound until --drop {name})" + for name in sorted(previous.get("formal_required", {})) + if required is not None and name not in required] + lines += [f"formal obligation demoted: {name} (still bound until --drop {name})" + for name in sorted(previous.get("formal_required", {})) + if required is not None and required.get(name) is False] + lines += [f"drop requested: {name} (last evidence run {run})" + for name, run in sorted(inventory["dropped"].items()) + if previous.get("dropped", {}).get(name) != run] + lines += [f"drop marker cleared by this acceptance revision: {name} (slot re-accepted; its obligations bind again)" + for name in sorted(previous.get("dropped", {})) if name not in inventory["dropped"]] + return lines + + +def _inventory_record(base: Mapping[str, Any] | None, check_digests: Mapping[str, str], + via: str, accepted_at: str, *, + dropped: Mapping[str, str] | None = None, + formal: Mapping[str, str] | None = None, + drop_names: tuple[str, ...] = ()) -> dict[str, Any]: + prior = base or {} + checks = {**prior.get("checks", {}), **check_digests} + formal_required = {**prior.get("formal_required", {}), **(formal or {})} + for name in (*(dropped or {}), *drop_names): + checks.pop(name, None) + formal_required.pop(name, None) + reaccepted = {*check_digests, *(formal or {})} + return {"kind": "obligation_inventory", "accepted_at": accepted_at, + "checks": checks, + "formal_required": formal_required, + "dropped": {**{n: r for n, r in prior.get("dropped", {}).items() if n not in reaccepted}, + **(dropped or {})}, + "confirmed_via": via} diff --git a/src/vkit/core/budgets.py b/src/vkit/core/budgets.py index d981722..f7ad4d4 100644 --- a/src/vkit/core/budgets.py +++ b/src/vkit/core/budgets.py @@ -1,10 +1,12 @@ """Measurements a check reported, judged against the budgets its definition declares.""" from __future__ import annotations +import math from dataclasses import dataclass from typing import Any, Literal from vkit.core.outcome import ScenarioResult +from vkit.kernel import check_limit, check_regression @dataclass(frozen=True) @@ -45,7 +47,7 @@ def evaluate(budgets: tuple[Budget, ...], measured: tuple[Measurement, ...], continue if budget.limit is not None: word = "at most" if m.better == "lower" else "at least" - ok = not _worse(m, m.value, budget.limit) + ok = check_limit(m.better, m.value, budget.limit) results.append(ScenarioResult(f"budget:{budget.name}:limit", ok, f"{m.value:g} {m.unit}, {word} {budget.limit:g} allowed")) if budget.max_regression_pct is not None: @@ -53,9 +55,22 @@ def evaluate(budgets: tuple[Budget, ...], measured: tuple[Measurement, ...], if base is None: unchecked.append(f"{budget.name}: no baseline is pinned, so regression was not checked") continue - change = 0.0 if base == 0 else (m.value - base) / abs(base) * 100 - regression = change if m.better == "lower" else -change - ok = regression <= budget.max_regression_pct + if not (math.isfinite(m.value) and math.isfinite(base) and math.isfinite(budget.max_regression_pct)): + results.append(ScenarioResult( + f"budget:{budget.name}:regression", False, + f"{m.value:g} {m.unit} vs baseline {base:g} (non-finite), " + f"at most {budget.max_regression_pct:g}% worse allowed")) + continue + if base == 0: + if m.value == 0: + change = 0.0 + elif _worse(m, m.value, 0.0): + change = math.inf if m.better == "lower" else -math.inf + else: + change = -math.inf if m.better == "lower" else math.inf + else: + change = (m.value - base) / abs(base) * 100 + ok = check_regression(m.better, m.value, base, budget.max_regression_pct) results.append(ScenarioResult( f"budget:{budget.name}:regression", ok, f"{m.value:g} {m.unit} vs baseline {base:g} ({change:+.1f}%), " diff --git a/src/vkit/core/discover.py b/src/vkit/core/discover.py index 678329b..7f3c7d7 100644 --- a/src/vkit/core/discover.py +++ b/src/vkit/core/discover.py @@ -382,7 +382,7 @@ def _read_package_json(root: Path, inspection: Inspection, test_configs: PythonT def _node_range_satisfied(declared: str, measured: str | None) -> bool | None: - """Whether this node meets a `>=X` or `X` major range; None for anything else.""" + """Whether this node meets a `>=X`/` bool | None: return None have = int(match.group(1)) floor = re.search(r">=\s*v?(\d+)", declared) - if floor is not None: - return have >= int(floor.group(1)) + ceiling_lt = re.search(r"<(?!=)\s*v?(\d+)", declared) + ceiling_le = re.search(r"<=\s*v?(\d+)", declared) + if floor is not None or ceiling_lt is not None or ceiling_le is not None: + if floor is not None and have < int(floor.group(1)): + return False + if ceiling_lt is not None and have >= int(ceiling_lt.group(1)): + return False + if ceiling_le is not None and have > int(ceiling_le.group(1)): + return False + return True major = re.fullmatch(r"[\^~]?\s*v?(\d+)(?:\.x)?", declared.strip()) if major is not None: return have == int(major.group(1)) @@ -439,6 +447,7 @@ def _read_python_config(root: Path, inspection: Inspection, test_configs: Python "tox.ini": "tox.ini", "setup.cfg": "setup.cfg [tool:pytest]", } + seen_runners: set[str] = set() for config in test_configs.declarations: name = config.file text = _read_text(root, name) @@ -449,6 +458,9 @@ def _read_python_config(root: Path, inspection: Inspection, test_configs: Python inspection.files_read.append(name) label = labels[name] inspection.test_configuration.append(label) + if config.runner in seen_runners: + continue + seen_runners.add(config.runner) if config.runner == "tox": argv = ("tox",) line = _line_of(text, "[testenv") @@ -480,14 +492,14 @@ def _read_python_config(root: Path, inspection: Inspection, test_configs: Python def _python_spec_satisfied(declared: str) -> bool | None: """Whether this interpreter meets a `>=`/`<` requires-python bound; None for anything else.""" - floor = re.search(r">=\s*(\d+)\.(\d+)", declared) - ceiling = re.search(r"<\s*(\d+)\.(\d+)", declared) + floor = re.search(r">=\s*(\d+)(?:\.(\d+))?", declared) + ceiling = re.search(r"<(?!=)\s*(\d+)(?:\.(\d+))?", declared) if floor is None and ceiling is None: return None current = (sys.version_info.major, sys.version_info.minor) - if floor is not None and current < (int(floor.group(1)), int(floor.group(2))): + if floor is not None and current < (int(floor.group(1)), int(floor.group(2) or 0)): return False - return ceiling is None or current < (int(ceiling.group(1)), int(ceiling.group(2))) + return ceiling is None or current < (int(ceiling.group(1)), int(ceiling.group(2) or 0)) _MAKE_TARGET = re.compile(r"^([A-Za-z0-9][A-Za-z0-9_.-]*)\s*:(?!=)") diff --git a/src/vkit/core/evidence.py b/src/vkit/core/evidence.py index 6daa3d5..212833a 100644 --- a/src/vkit/core/evidence.py +++ b/src/vkit/core/evidence.py @@ -17,6 +17,7 @@ from vkit.runtime.paths import ProjectError from vkit.core.schemas import SchemaValidationError from vkit.core.store import read_json, write_json +from vkit.kernel import derive_assurance, derive_claim_outcome, verify_receipt_core _UNSEALED = frozenset({"record.json", "receipt.json", "lock", "cancel", "worker.log", "worker.json"}) @@ -135,7 +136,12 @@ def _producer_modules() -> dict[str, Path]: target = f"{base}.{node.module}" if node.module else base else: target = node.module or "" - pending.append((target, target)) + if target: + pending.append((target, target)) + for alias in node.names: + if alias.name != "*": + sub = f"{target}.{alias.name}" + pending.append((sub, sub)) return found @@ -404,29 +410,33 @@ def backend_identity(check) -> dict[str, Any]: def assurance(check) -> str: - return {"lean": "kernel_proof", "tlc": "finite_model"}.get( - check.kind.value, getattr(check, "assurance", "empirical") + return derive_assurance( + has_check=True, + is_shadow=False, + kind=check.kind.value, + custom_assurance=getattr(check, "assurance", "empirical"), ) def seal(record: dict[str, Any], directory: Path, check=None) -> None: artifacts = {name: sha256(directory / name) for name in sorted(_artifact_names(directory))} result = record["outcome"]["result"] - claim_outcome = {"PASS": "established", "FAIL": "refuted", "BLOCKED": "unknown"}[ - result - ] - if check is not None and check.kind.value == "lean" and result == "FAIL": - claim_outcome = "unknown" shadow = record["subject"]["kind"] == "change_certification" - if shadow: - claim_outcome = "unknown" + is_lean = check is not None and check.kind.value == "lean" + claim_outcome = derive_claim_outcome(result, is_lean=is_lean, is_shadow=shadow) + derived_assurance = derive_assurance( + has_check=check is not None, + is_shadow=shadow, + kind=check.kind.value if check is not None else "other", + custom_assurance=getattr(check, "assurance", "empirical") if check is not None else "empirical", + ) receipt = { "schema_version": 2, "job_id": record["job_id"], "subject": record["subject"], "source": record["source"], "inputs": record["inputs"], - "assurance": "empirical" if shadow else assurance(check) if check else "trusted_engine", + "assurance": derived_assurance, "claim_outcome": claim_outcome, "outcome": record["outcome"], "obligations": record["obligations"], @@ -572,14 +582,21 @@ def validate_record(record: dict[str, Any], directory: Path) -> bool: return False else: return False - if ( - receipt["assurance"] != link["assurance"] - or receipt["claim_outcome"] != link["claim_outcome"] - ): - return False - if ( - record["assurance"] != receipt["assurance"] - or record["claim_outcome"] != receipt["claim_outcome"] + if not verify_receipt_core( + receipt_digest_matches=True, + artifacts_match=True, + subject_matches=True, + policy_matches=True, + job_id_matches=record["job_id"] == record["key"], + authority_matches=True, + claim_outcome_consistent=( + receipt["claim_outcome"] == link["claim_outcome"] + and record["claim_outcome"] == receipt["claim_outcome"] + ), + assurance_consistent=( + receipt["assurance"] == link["assurance"] + and record["assurance"] == receipt["assurance"] + ), ): return False for item in ( @@ -611,24 +628,33 @@ def export( store, run_id: str, destination: Path, *, include_assets: bool = False ) -> dict[str, Any]: record = store.record(run_id) + run_dir = store.run_dir(run_id) if ( record is None or record["state"] != "done" - or not validate_record(record, store.run_dir(run_id)) + or not validate_record(record, run_dir) ): raise ValueError("run has no complete, intact evidence bundle") + root_resolved = run_dir.resolve() + excluded = {"lock", "cancel", "worker.log", "worker.json"} + + def _ignore_root(directory: str, names: list[str]) -> set[str]: + if Path(directory).resolve() == root_resolved: + return excluded & set(names) + return set() + shutil.copytree( - store.run_dir(run_id), + run_dir, destination, symlinks=True, - ignore=shutil.ignore_patterns("lock", "cancel", "worker.log", "worker.json"), + ignore=_ignore_root, ) portable_assets = None if include_assets: from vkit.core.replay_assets import capture try: - portable_assets = capture(record, store.run_dir(run_id), destination) + portable_assets = capture(record, run_dir, destination) except BaseException: shutil.rmtree(destination, ignore_errors=True) raise diff --git a/src/vkit/core/feedback.py b/src/vkit/core/feedback.py index c83f863..c7f09c7 100644 --- a/src/vkit/core/feedback.py +++ b/src/vkit/core/feedback.py @@ -6,6 +6,7 @@ from pathlib import Path from typing import Any +from vkit.core.evidence import is_link from vkit.core.inputs import canonical_digest from vkit.core.store import Store, now @@ -52,7 +53,7 @@ def submit(store: Store, request: dict[str, Any]) -> dict[str, Any]: def _entry(path: Path) -> dict[str, Any]: - if path.is_symlink() or not path.is_file(): + if is_link(path) or not path.is_file(): raise ValueError("feedback must be a regular Markdown file") with path.open(encoding="utf-8") as source: text = source.read(500) @@ -70,7 +71,7 @@ def collect(store: Store, *, kind: str | None = None, offset: int = 0, if not 1 <= limit <= 100 or offset < 0: raise ValueError("feedback requires limit 1 to 100 and nonnegative offset") entries = [_entry(path) for path in (store.root / "feedback").glob("*.md") - if not path.is_symlink()] + if not is_link(path) and path.is_file()] entries = [entry for entry in entries if kind is None or entry["kind"] == kind] entries.sort(key=lambda entry: entry["id"]) entries.sort(key=lambda entry: (*KINDS, "unclassified").index(entry["kind"])) diff --git a/src/vkit/core/jobs.py b/src/vkit/core/jobs.py index 4673395..a5c3bab 100644 --- a/src/vkit/core/jobs.py +++ b/src/vkit/core/jobs.py @@ -22,6 +22,7 @@ from vkit.change.requests import GitCommit, PackageVerificationRequest from vkit.core.runner import _child_env, execute, prepare, prepare_change, prepare_formal, prepare_retry from vkit.core.store import Store, new_run_id, now, read_json, write_json +from vkit.core.trace import emit_trace def _failed_submission(store: Store, run_id: str, outcome: Blocked) -> None: @@ -31,6 +32,7 @@ def _failed_submission(store: Store, run_id: str, outcome: Blocked) -> None: if record is not None and record["state"] == "queued": record.update(state="done", ended_at=now(), outcome=outcome.to_json()) store.save(record) + emit_trace("job_failed_submission", run_id=run_id, reason=outcome.reason.value) except RuntimeError: # A live worker owns publication; a failed competing launcher cannot overwrite it. return @@ -91,7 +93,9 @@ def submit( project: Project, manifest: Manifest, check_id: str, *, store: Store | None = None ) -> dict[str, Any]: store = store or Store.of(project) - return _launch(project, store, prepare(project, manifest, check_id, store=store)) + record = _launch(project, store, prepare(project, manifest, check_id, store=store)) + emit_trace("job_submit", check_id=check_id, run_id=record["run_id"], state=record["state"]) + return record def submit_formal( @@ -115,8 +119,10 @@ def retry(project: Project | None, run_id: str, *, store: Store) -> dict[str, An if previous is None or previous["state"] in ("queued", "running"): raise ValueError("retry requires a finished or interrupted attempt") worker = read_json(store.run_dir(run_id) / "worker.json") - return _launch(project, store, prepare_retry(run_id, store=store), - asset_environment=worker.get("assets") if isinstance(worker, dict) else None) + record = _launch(project, store, prepare_retry(run_id, store=store), + asset_environment=worker.get("assets") if isinstance(worker, dict) else None) + emit_trace("job_retry", from_run_id=run_id, run_id=record["run_id"], state=record["state"]) + return record def submit_change( diff --git a/src/vkit/core/proposals.py b/src/vkit/core/proposals.py index 524d2b3..7bab878 100644 --- a/src/vkit/core/proposals.py +++ b/src/vkit/core/proposals.py @@ -11,6 +11,7 @@ from vkit.core.manifest import ManifestError, parse_manifest_data from vkit.runtime.paths import Project from vkit.core.store import Store, now, read_json, write_json +from vkit.core.trace import emit_trace MAX_FILE_BYTES = 200_000 @@ -92,6 +93,7 @@ def submit(project: Project, store: Store, body: Any) -> Proposal: clean = validate(project, body) digest = canonical_digest(clean) write_json(store.root / "proposals" / f"{digest}.json", {"body": clean, "proposed_at": now(), "state": "pending"}) + emit_trace("proposal_submit", digest=digest) return Proposal(digest, clean) @@ -166,7 +168,7 @@ def apply(project: Project, store: Store, proposal: Proposal) -> list[str]: document = manifest = None if body["checks"] or "formal" in body: document, manifest = _resulting_manifest(project, body) - approvals = {} + approvals: dict[str, dict[str, Any]] = {} if "formal" in body: from vkit.formal import ledger, verus @@ -183,12 +185,6 @@ def apply(project: Project, store: Store, proposal: Proposal) -> list[str]: } except (ValueError, RuntimeError) as exc: raise ProposalError(str(exc)) from exc - if body["checks"]: - from vkit.core.evidence import backend_identity - - approvals.update({manifest.digest(e["id"]): {"kind": "check_definition", "check_id": e["id"], "accepted_at": now(), - "backend": backend_identity(manifest.require(e["id"])), - "proposal": proposal.digest} for e in body["checks"]}) if body["features"]: try: features = read_document(project.root) @@ -203,6 +199,44 @@ def apply(project: Project, store: Store, proposal: Proposal) -> list[str]: assert document is not None manifest_path.parent.mkdir(parents=True, exist_ok=True) manifest_path.write_text(json.dumps(document, indent=2) + "\n", encoding="utf-8") + if body["checks"]: + from vkit.core.evidence import backend_identity + from vkit.core.state import evaluator, evaluator_digests + from vkit.verifiers.spec import ExternalCheck + + for entry in body["checks"]: + check = manifest.require(entry["id"]) + external = isinstance(getattr(check, "variant", None) or check, ExternalCheck) + files = evaluator_digests(check) + record: dict[str, Any] = { + "kind": "check_definition", + "check_id": entry["id"], + "accepted_at": now(), + "backend": backend_identity(check), + "proposal": proposal.digest, + } + if external or files: + if files: + store.retain_evaluator(entry["id"], evaluator(check)) + record["oracle"] = { + "files": files, + "digest": canonical_digest(files), + "external": external, + } + approvals[manifest.digest(entry["id"])] = record + if "formal" in body: + from vkit.core.state import approved_inventory + + base_inv = approved_inventory(store.approved()) + formal_req = {c.id: c.digest for c in manifest.components.values() if c.required} + if base_inv is not None or formal_req: + approvals["__inventory__"] = { + "kind": "obligation_inventory", + "checks": dict((base_inv or {}).get("checks", {})), + "formal_required": formal_req, + "accepted_at": now(), + "proposal": proposal.digest, + } if approvals: store.approve(approvals) if body["features"]: @@ -211,9 +245,11 @@ def apply(project: Project, store: Store, proposal: Proposal) -> list[str]: path.write_text(json.dumps(features, indent=2) + "\n", encoding="utf-8") write_json(store.root / "proposals" / f"{proposal.digest}.json", {"body": body, "state": "accepted", "accepted_at": now()}) + emit_trace("proposal_apply", digest=proposal.digest, checks=[e["id"] for e in body["checks"]]) return [e["id"] for e in body["checks"]] def reject(store: Store, proposal: Proposal) -> None: write_json(store.root / "proposals" / f"{proposal.digest}.json", {"body": proposal.body, "state": "rejected", "rejected_at": now()}) + emit_trace("proposal_reject", digest=proposal.digest) diff --git a/src/vkit/core/query.py b/src/vkit/core/query.py index 008449b..3aff0c5 100644 --- a/src/vkit/core/query.py +++ b/src/vkit/core/query.py @@ -102,6 +102,8 @@ def status(ctx: Context, paths: Iterable[str] = (), session: bool = False) -> di wanted = [p.replace("\\", "/") for p in paths] candidates = None registered: set[str] | None = None + full_ctx = ctx + full: Snapshot | None = None if session and wanted and ctx.manifest is not None: registered = set(ctx.manifest.checks) candidates = {i: c for i, c in ctx.manifest.checks.items() @@ -122,7 +124,22 @@ def status(ctx: Context, paths: Iterable[str] = (), session: bool = False) -> di all_formal = formal_states(ctx) by_id = {s.check.id: s for s in all_states} shown = [s for s in all_states if not wanted or any(s.inputs.covers(p) for p in wanted)] - features, feature_error = _features(ctx, by_id) + all_by_id = by_id + if candidates is not None and full_ctx.manifest is not None: + try: + loaded_features = load_features(ctx.project.root) + except FeatureError: + loaded_features = [] + shown_ids = {s.check.id for s in shown} + needed: set[str] = set() + for feat in loaded_features: + if shown_ids & set(feat.covered_by) or any(matches(p, e) for p in wanted for e in feat.entry_points): + needed.update(c for c in feat.covered_by if c in full_ctx.manifest.checks and c not in by_id) + if needed: + extra = {i: full_ctx.manifest.checks[i] for i in needed} + extra_states = states(replace(full_ctx, manifest=replace(full_ctx.manifest, checks=extra), snapshot=full)) + all_by_id = {**by_id, **{s.check.id: s for s in extra_states}} + features, feature_error = _features(ctx, all_by_id) if wanted: ids = {s.check.id for s in shown} features = [f for f in features if ids & set(f["covered_by"]) diff --git a/src/vkit/core/replay_assets.py b/src/vkit/core/replay_assets.py index 51ab730..8e19a85 100644 --- a/src/vkit/core/replay_assets.py +++ b/src/vkit/core/replay_assets.py @@ -282,6 +282,13 @@ def _extract_tree(archive_path: Path, destination: Path, return root +def _require_env_path(env_name: str) -> Path: + raw = os.environ.get(env_name, "").strip() + if not raw: + raise ValueError(f"{env_name} must be set to capture portable Verus assets") + return Path(raw).resolve(strict=True) + + def capture(record: dict[str, Any], directory: Path, destination: Path) -> dict[str, Any]: """Add exact image and tool assets beneath replay/ so the original receipt stays intact.""" from vkit.core.evidence import is_link, sha256 @@ -309,7 +316,7 @@ def capture(record: dict[str, Any], directory: Path, destination: Path) -> dict[ _image_preflight(image_archive, image_id) assets: dict[str, Any] = {"image": {"path": "image.tar", "sha256": _hash(image_archive), "image_id": image_id}} - archive_path = Path(os.environ.get("VKIT_VERUS_ARCHIVE", "")).resolve(strict=True) + archive_path = _require_env_path("VKIT_VERUS_ARCHIVE") if _hash(archive_path) != semantic["verus"]["archive_sha256"]: raise ValueError("Verus archive differs from the recorded execution identity") archive_name = archive_path.name @@ -318,7 +325,7 @@ def capture(record: dict[str, Any], directory: Path, destination: Path) -> dict[ raise ValueError("Verus archive exceeds the portable asset size limit") assets["verus_archive"] = {"path": archive_name, "sha256": _hash(base / archive_name)} for name, env_name in _TREE_ENV.items(): - source = Path(os.environ.get(env_name, "")).resolve(strict=True) + source = _require_env_path(env_name) expected = semantic[name] if name != "verus_root" else semantic["verus"]["files"] asset = _tree_archive(source, base / f"{name}.tar", expected) asset.update(path=f"{name}.tar", tree=expected) diff --git a/src/vkit/core/runner.py b/src/vkit/core/runner.py index 50ca7f9..4dc472c 100644 --- a/src/vkit/core/runner.py +++ b/src/vkit/core/runner.py @@ -292,13 +292,19 @@ def prepare( or source_record["receipt"]["sha256"] != replay_receipt ): raise ValueError("source receipt changed before replay capture") + replay_root = replay_source.resolve() + excluded = {"lock", "cancel", "worker.log", "worker.json", "replay"} + + def _ignore_root(directory: str, names: list[str]) -> set[str]: + if Path(directory).resolve() == replay_root: + return excluded & set(names) + return set() + shutil.copytree( replay_source, retained, symlinks=True, - ignore=shutil.ignore_patterns( - "lock", "cancel", "worker.log", "worker.json", "replay" - ), + ignore=_ignore_root, ) if not validate_record(source_record, retained): raise ValueError("evidence changed while capturing replay bundle") @@ -818,9 +824,10 @@ def _execute( ) log = _read_deps_log(log_path) opened = {entry["p"] for entry in log or () if entry["e"] in ("read", "enumerate")} + snapshot_root = run_dir / "snapshot" unused = tuple( item["path"] for item in record["inputs"]["files"] - if str((check.cwd / item["path"]).resolve()).replace(os.sep, "/") not in opened + if str((snapshot_root / item["path"]).resolve()).replace(os.sep, "/") not in opened ) drift = [name for name, pin in pinned.items() if not _pinned_intact(pin)] write_json( diff --git a/src/vkit/core/schemas.py b/src/vkit/core/schemas.py index 422f618..7e99714 100644 --- a/src/vkit/core/schemas.py +++ b/src/vkit/core/schemas.py @@ -135,9 +135,13 @@ def validate(subject: str, schema_name: str, instance: Any) -> None: raise SchemaValidationError(subject, reason) +def _reject_non_finite(token: str) -> Any: + raise ValueError(f"non-finite JSON constant: {token}") + + def parse_artifact(raw: bytes) -> Any: """Decode a check artifact's UTF-8 JSON bytes.""" try: - return json.loads(raw.decode("utf-8")) - except (UnicodeDecodeError, json.JSONDecodeError) as exc: + return json.loads(raw.decode("utf-8"), parse_constant=_reject_non_finite) + except (UnicodeDecodeError, ValueError) as exc: raise SchemaValidationError("check artifact", f"not valid UTF-8 JSON: {exc}") from exc diff --git a/src/vkit/core/state.py b/src/vkit/core/state.py index cba6de6..06b7e50 100644 --- a/src/vkit/core/state.py +++ b/src/vkit/core/state.py @@ -18,6 +18,7 @@ from vkit.runtime.paths import ProjectError from vkit.change.requests import PackageVerificationRequest, WorkingTree from vkit.core.store import Store +from vkit.kernel import decide_gate from vkit.verifiers.spec import CheckKind, CheckSpec @@ -239,7 +240,7 @@ def comparison(store: Store, project, check: CheckSpec, prior: dict[str, Any] | if candidate in ("BLOCKED", "timeout"): return {"outcome": "incomparable", "clearing": "re-accept the reference", "receipts": receipts} current = evaluator(check) - if current == accepted or not set(accepted) & set(current): + if current == accepted: return {"outcome": "unchanged", "clearing": None, "receipts": receipts} snapshot = store.fail_snapshot(check.id, identity) if snapshot: @@ -256,6 +257,8 @@ def comparison(store: Store, project, check: CheckSpec, prior: dict[str, Any] | return {"outcome": "weakened_check", "clearing": "fix the evaluator or accept the weakening with both runs displayed", "receipts": receipts} + if accepted and not set(accepted) & set(current): + return {"outcome": "incomparable", "clearing": "re-accept the reference", "receipts": receipts} return {"outcome": "unchanged", "clearing": None, "receipts": receipts} @@ -490,47 +493,43 @@ def gate( ghosts = [] weak = sorted(cid for cid, out in (comparisons or {}).items() if out["outcome"] == "weakened_check") incomp = sorted(cid for cid, out in (comparisons or {}).items() if out["outcome"] == "incomparable") - if weak: - verdict, reason = Verdict.REJECTED, "weakened_check: " + ", ".join(weak) + " passes a retained legitimate FAIL" - elif incomp: - verdict, reason = Verdict.BLOCKED, "incomparable: " + ", ".join(incomp) + " cannot be compared; re-accept the reference" - else: - if obligations is not None: - registered = {s.check.id for s in states} - removed = set(obligations.get("checks", ())) - registered - removed |= {rid for rid in obligations.get("formal_required", ()) - if not any(s.component.id == rid and s.required for s in formal)} - removed |= set(obligations.get("dropped", ())) - registered - ghosts = [{"id": rid, "state": "obligation_removed", "run_id": None} for rid in sorted(removed)] - if not states and not required and not ghosts: - verdict, reason = Verdict.BLOCKED, "no checks are registered" - elif obligations is None and (states or required): - verdict, reason = Verdict.REJECTED, "obligation_inventory: no accepted inventory binds this manifest" - elif ghosts: - verdict, reason = Verdict.REJECTED, ("obligation_removed: " + ", ".join(g["id"] for g in ghosts) - + " were accepted but are no longer registered or required") - elif any( - state.freshness is Freshness.FRESH_FAIL - for state in (*states, *required) - ): - verdict, reason = Verdict.REJECTED, "fresh_fail: a required check failed against the current inputs" - elif any(state.freshness is Freshness.NOT_APPROVED for state in (*states, *required)): - verdict, reason = Verdict.REJECTED, "not_approved: a required check definition is not accepted" - elif all(state.freshness is Freshness.FRESH_PASS for state in states) and all( - state.freshness is Freshness.FRESH_PASS for state in required - ): - gaps = list(uncovered) - if gaps: - verdict, reason = Verdict.READY_SCOPED, (f"uncovered_change: ready, but {len(gaps)} requested paths are outside " - f"every check's inputs: {', '.join(gaps)}") - else: - verdict, reason = Verdict.READY, "every required check passed against the current inputs" - else: - gap = "some required checks have no passing evidence for the current inputs" - stuck = {s.freshness for s in (*states, *required)} - reasons = {Freshness.FRESH_BLOCKED: f"fresh_blocked: {gap}", Freshness.BLOCKED: f"blocked: {gap}", - Freshness.STALE: f"stale: {gap}", Freshness.MISSING: f"missing: {gap}"} - verdict, reason = Verdict.BLOCKED, next(reasons[fresh] for fresh in reasons if fresh in stuck) + if not weak and not incomp and obligations is not None: + registered = {s.check.id for s in states} + removed = set(obligations.get("checks", ())) - registered + removed |= {rid for rid in obligations.get("formal_required", ()) + if not any(s.component.id == rid and s.required for s in formal)} + removed |= set(obligations.get("dropped", ())) - registered + ghosts = [{"id": rid, "state": "obligation_removed", "run_id": None} for rid in sorted(removed)] + gaps = list(uncovered) + verdict_name, reason_tag = decide_gate( + [s.freshness.value for s in states], + [s.freshness.value for s in required], + has_inventory=obligations is not None, + has_ghosts=bool(ghosts), + has_weakened=bool(weak), + has_incomparable=bool(incomp), + has_uncovered=bool(gaps), + ) + verdict = Verdict(verdict_name) + gap = "some required checks have no passing evidence for the current inputs" + reason_map = { + "weakened_check": "weakened_check: " + ", ".join(weak) + " passes a retained legitimate FAIL", + "incomparable": "incomparable: " + ", ".join(incomp) + " cannot be compared; re-accept the reference", + "no_checks": "no checks are registered", + "obligation_inventory": "obligation_inventory: no accepted inventory binds this manifest", + "obligation_removed": ("obligation_removed: " + ", ".join(g["id"] for g in ghosts) + + " were accepted but are no longer registered or required"), + "fresh_fail": "fresh_fail: a required check failed against the current inputs", + "not_approved": "not_approved: a required check definition is not accepted", + "uncovered_change": (f"uncovered_change: ready, but {len(gaps)} requested paths are outside " + f"every check's inputs: {', '.join(gaps)}"), + "ready": "every required check passed against the current inputs", + "fresh_blocked": f"fresh_blocked: {gap}", + "blocked": f"blocked: {gap}", + "stale": f"stale: {gap}", + "missing": f"missing: {gap}", + } + reason = reason_map[reason_tag] fields = {s.freshness.value for s in (*states, *required) if s.freshness is not Freshness.FRESH_PASS} fields.add(reason.split(":")[0]) doubts = sorted((d for d in DOUBTS if d.field in fields), key=lambda d: _EFFECT_ORDER.index(d.effect)) diff --git a/src/vkit/core/store.py b/src/vkit/core/store.py index 6421a37..803e345 100644 --- a/src/vkit/core/store.py +++ b/src/vkit/core/store.py @@ -26,6 +26,7 @@ from typing import Any from vkit.core.inputs import canonical_digest +from vkit.core.trace import emit_trace from vkit.runtime.nowindow import is_windows from vkit.runtime.paths import Project @@ -135,11 +136,20 @@ def read_json(path: Path) -> Any | None: return None -def _try_lock(handle: Any) -> bool: +def _init_lock_file(handle: Any) -> None: + handle.seek(0, os.SEEK_END) + if handle.tell() == 0: + handle.write(b"\0") + handle.flush() + handle.seek(0) + + +def _try_lock(handle: Any, *, shared: bool = False) -> bool: if is_windows: import msvcrt try: + handle.seek(0) msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1) return True except OSError: @@ -147,7 +157,8 @@ def _try_lock(handle: Any) -> bool: import fcntl try: - fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + mode = fcntl.LOCK_SH if shared else fcntl.LOCK_EX + fcntl.flock(handle.fileno(), mode | fcntl.LOCK_NB) return True except OSError: return False @@ -157,6 +168,7 @@ def _unlock(handle: Any) -> None: if is_windows: import msvcrt + handle.seek(0) msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1) else: import fcntl @@ -211,6 +223,7 @@ def record(self, run_id: str) -> dict[str, Any] | None: def save(self, record: dict[str, Any]) -> None: write_json(self.run_dir(record["run_id"]) / "record.json", record) + emit_trace("store_save", run_id=record["run_id"], state=record.get("state"), outcome=(record.get("outcome") or {}).get("result")) def publish(self, record: dict[str, Any]) -> None: """Save a finished record and publish its typed evidence and latest pointers.""" @@ -230,6 +243,7 @@ def publish(self, record: dict[str, Any]) -> None: self.root / "evidence" / subject_dir / f"{record['job_id']}.json", pointer ) write_json(self.root / "latest" / subject_dir / "latest.json", pointer) + emit_trace("store_publish", run_id=record["run_id"], job_id=record["job_id"], result=record["outcome"]["result"]) def evidence_for( self, kind: str, subject_id: str, job_id: str @@ -295,16 +309,23 @@ def hold(self, run_id: str) -> Iterator[None]: path = self.run_dir(run_id) / "lock" path.parent.mkdir(parents=True, exist_ok=True) with open(path, "a+b") as handle: + _init_lock_file(handle) if not _try_lock(handle): raise RuntimeError(f"run {run_id} is already held") - yield + emit_trace("lock_acquire", run_id=run_id) + try: + yield + finally: + _unlock(handle) + emit_trace("lock_release", run_id=run_id) def is_alive(self, run_id: str) -> bool: path = self.run_dir(run_id) / "lock" if not path.exists(): return False with open(path, "a+b") as handle: - if not _try_lock(handle): + _init_lock_file(handle) + if not _try_lock(handle, shared=True): return True _unlock(handle) return False @@ -335,12 +356,12 @@ def evaluator_bytes(self, check_id: str, identity: str | None) -> dict[str, byte def label_fail(self, check_id: str, identity: str, label: str) -> None: check_id = _safe_segment(check_id, "check_id") identity = _safe_segment(identity, "identity") - self.root.mkdir(parents=True, exist_ok=True) - write_json(self.root / "corpus" / f"{check_id}.json", - {**(read_json(self.root / "corpus" / f"{check_id}.json") or {}), identity: label}) - marker = self.root / "fails" / check_id / identity / "label" - if marker.is_file(): - marker.write_text(label, encoding="utf-8") + with self._file_lock("corpus.lock"): + corpus_path = self.root / "corpus" / f"{check_id}.json" + write_json(corpus_path, {**(read_json(corpus_path) or {}), identity: label}) + marker = self.root / "fails" / check_id / identity / "label" + if marker.is_file(): + marker.write_text(label, encoding="utf-8") def retain_fail(self, check_id: str, identity: str, files: dict[str, bytes]) -> None: check_id = _safe_segment(check_id, "check_id") @@ -378,6 +399,7 @@ def fail_snapshot(self, check_id: str, identity: str) -> dict[str, Any] | None: def request_cancel(self, run_id: str) -> None: (self.run_dir(run_id) / "cancel").touch() + emit_trace("cancel_request", run_id=run_id) def cancel_requested(self, run_id: str) -> bool: return (self.run_dir(run_id) / "cancel").exists() @@ -386,9 +408,10 @@ def baselines(self) -> dict[str, Any]: return read_json(self.root / "baselines.json") or {} def pin_baseline(self, check_id: str, baseline: dict[str, Any]) -> None: - write_json( - self.root / "baselines.json", {**self.baselines(), check_id: baseline} - ) + with self._file_lock("baselines.lock"): + write_json( + self.root / "baselines.json", {**self.baselines(), check_id: baseline} + ) def approved(self) -> dict[str, Any]: document = read_json(self.root / "approved.json") or {} @@ -439,23 +462,25 @@ def _validate_approval(record: Any) -> None: raise ValueError("obligation inventory maps must be string maps") @contextmanager - def _approval_lock(self) -> Iterator[None]: + def _file_lock(self, name: str, label: str | None = None) -> Iterator[None]: self.root.mkdir(parents=True, exist_ok=True) - with (self.root / "approval.lock").open("a+b") as handle: - if handle.tell() == 0: - handle.write(b"\0") - handle.flush() - handle.seek(0) + with (self.root / name).open("a+b") as handle: + _init_lock_file(handle) deadline = time.monotonic() + 10 while not _try_lock(handle): if time.monotonic() >= deadline: - raise RuntimeError("timed out waiting for the shared approval lock") + raise RuntimeError(f"timed out waiting for the shared {label or name}") time.sleep(0.02) try: yield finally: _unlock(handle) + @contextmanager + def _approval_lock(self) -> Iterator[None]: + with self._file_lock("approval.lock", "approval lock"): + yield + def approve(self, entries: dict[str, dict[str, Any]]) -> None: for record in entries.values(): self._validate_approval(record) @@ -464,3 +489,4 @@ def approve(self, entries: dict[str, dict[str, Any]]) -> None: write_json( self.root / "approved.json", {"schema_version": 2, "records": records} ) + emit_trace("store_approve", count=len(entries)) diff --git a/src/vkit/core/trace.py b/src/vkit/core/trace.py new file mode 100644 index 0000000..ea5b275 --- /dev/null +++ b/src/vkit/core/trace.py @@ -0,0 +1,18 @@ +from __future__ import annotations + +import json +import os +import time +from pathlib import Path +from typing import Any + + +def emit_trace(event: str, **fields: Any) -> None: + target = os.environ.get("VKIT_TRACE_LOG") + if not target: + return + record = {"event": event, "ts": round(time.time(), 6), **fields} + path = Path(target) + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("a", encoding="utf-8") as out: + out.write(json.dumps(record, sort_keys=True) + "\n") diff --git a/src/vkit/formal/service.py b/src/vkit/formal/service.py index 75a1e5d..557ffc5 100644 --- a/src/vkit/formal/service.py +++ b/src/vkit/formal/service.py @@ -6,10 +6,12 @@ from typing import Any from vkit.core import jobs +from vkit.core.inputs import canonical_digest from vkit.runtime.nowindow import hidden_window from vkit.runtime.paths import Project from vkit.core.query import Context from vkit.change.requests import PackageVerificationRequest +from . import verus def resolve_commit(project: Project, revision: str) -> str: @@ -31,14 +33,13 @@ def verify(ctx: Context, raw: Any) -> dict[str, Any]: approval = ctx.store.approved().get(component.digest, {}) if approval.get("kind") != "formal_policy": raise ValueError("formal policy is not accepted; run `vkit accept --component " + component.id + "`") - if request.reuse: - from vkit.core.inputs import canonical_digest - from .verus import resolve_execution - - current = resolve_execution(component) - if not component.is_accepted(approval, canonical_digest(current["semantic"])): + current = verus.resolve_execution(component) + checker_sha256 = canonical_digest(current["semantic"]) + if not component.is_accepted(approval, checker_sha256): + if request.reuse: raise ValueError("formal policy, package or checker changed; accept them before reuse") - record = jobs.submit_formal(ctx.project, request, component, approval["checker_sha256"], store=ctx.store) + raise ValueError("formal policy, package or checker changed; run `vkit accept --component " + component.id + "`") + record = jobs.submit_formal(ctx.project, request, component, checker_sha256, store=ctx.store) if request.wait_seconds: record = jobs.wait(ctx.store, record["run_id"], request.wait_seconds) return record diff --git a/src/vkit/kernel/__init__.py b/src/vkit/kernel/__init__.py new file mode 100644 index 0000000..517fcc4 --- /dev/null +++ b/src/vkit/kernel/__init__.py @@ -0,0 +1,40 @@ +"""Compiled pure decision kernel backed by verified Dafny modules.""" +from __future__ import annotations + +from vkit.kernel.bridge import ( + assess_difference_status, + check_delegation_kernel, + check_limit, + check_regression, + classify_difference, + compare_contracts_kernel, + conclude_change_methods, + decide_gate, + def_change_kernel, + derive_assurance, + derive_claim_outcome, + intent_entails_claim_kernel, + run_exit_code_kernel, + verdict_exit_code_kernel, + verify_passing_receipt, + verify_receipt_core, +) + +__all__ = [ + "assess_difference_status", + "check_delegation_kernel", + "check_limit", + "check_regression", + "classify_difference", + "compare_contracts_kernel", + "conclude_change_methods", + "decide_gate", + "def_change_kernel", + "derive_assurance", + "derive_claim_outcome", + "intent_entails_claim_kernel", + "run_exit_code_kernel", + "verdict_exit_code_kernel", + "verify_passing_receipt", + "verify_receipt_core", +] diff --git a/src/vkit/kernel/bridge.py b/src/vkit/kernel/bridge.py new file mode 100644 index 0000000..cdb13db --- /dev/null +++ b/src/vkit/kernel/bridge.py @@ -0,0 +1,555 @@ +"""Typed adapter between Python facades and the Dafny-compiled pure kernel.""" +from __future__ import annotations + +import functools +import importlib.util +import math +import sys +from collections.abc import Iterable, Mapping, Sequence +from fractions import Fraction +from pathlib import Path +from types import ModuleType +from typing import Any + +_GEN_ROOT = Path(__file__).resolve().parent / "_dafny_gen" / "vkit_kernel-py" + +_LOAD_ORDER: tuple[tuple[str, Path, bool], ...] = ( + ("_dafny", _GEN_ROOT / "_dafny" / "__init__.py", True), + ("System_", _GEN_ROOT / "System_" / "__init__.py", True), + ("module_", _GEN_ROOT / "module_.py", False), + ("VKitChange", _GEN_ROOT / "VKitChange.py", False), + ("VKitReceipt", _GEN_ROOT / "VKitReceipt.py", False), + ("VKitAcceptance", _GEN_ROOT / "VKitAcceptance.py", False), + ("VKitBudgets", _GEN_ROOT / "VKitBudgets.py", False), + ("VKitGate", _GEN_ROOT / "VKitGate.py", False), +) + + +def _load_generated_modules() -> dict[str, ModuleType]: + loaded: dict[str, ModuleType] = {} + pending: list[tuple[Any, ModuleType]] = [] + for name, path, is_package in _LOAD_ORDER: + existing = sys.modules.get(name) + if existing is not None and getattr(existing, "__file__", None) == str(path): + loaded[name] = existing + continue + locations = [str(path.parent)] if is_package else None + spec = importlib.util.spec_from_file_location( + name, path, submodule_search_locations=locations + ) + if spec is None or spec.loader is None: + raise ImportError(f"unable to load generated kernel module {name} from {path}") + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + loaded[name] = module + pending.append((spec, module)) + for spec, module in pending: + spec.loader.exec_module(module) + return loaded + + +_MODULES = _load_generated_modules() +_dafny = _MODULES["_dafny"] +_VKitGate = _MODULES["VKitGate"] +_VKitBudgets = _MODULES["VKitBudgets"] +_VKitAcceptance = _MODULES["VKitAcceptance"] +_VKitReceipt = _MODULES["VKitReceipt"] +_VKitChange = _MODULES["VKitChange"] + + +@functools.lru_cache(maxsize=8192) +def _dstr(value: str) -> Any: + return _dafny.SeqWithoutIsStrInference(map(_dafny.CodePoint, value)) + + +def _pystr(value: Any) -> str: + return value.VerbatimString(False) + + +def _dreal(value: float) -> tuple[Any, bool]: + if not math.isfinite(value): + return _dafny.BigRational(0, 1), False + frac = Fraction(value) + return _dafny.BigRational(frac.numerator, frac.denominator), True + + +_FRESHNESS_TO_DAFNY = { + "fresh_pass": _VKitGate.Freshness_FreshPass(), + "fresh_fail": _VKitGate.Freshness_FreshFail(), + "fresh_blocked": _VKitGate.Freshness_FreshBlocked(), + "stale": _VKitGate.Freshness_Stale(), + "missing": _VKitGate.Freshness_Missing(), + "not_approved": _VKitGate.Freshness_NotApproved(), + "blocked": _VKitGate.Freshness_Blocked(), +} + +_VERDICT_FROM_DAFNY = { + _VKitGate.Verdict_Ready(): "READY", + _VKitGate.Verdict_ReadyScoped(): "READY_SCOPED", + _VKitGate.Verdict_Rejected(): "REJECTED", + _VKitGate.Verdict_GateBlocked(): "BLOCKED", +} + +_REASON_FROM_DAFNY = { + _VKitGate.GateReason_ReasonWeakenedCheck(): "weakened_check", + _VKitGate.GateReason_ReasonIncomparable(): "incomparable", + _VKitGate.GateReason_ReasonNoChecks(): "no_checks", + _VKitGate.GateReason_ReasonMissingInventory(): "obligation_inventory", + _VKitGate.GateReason_ReasonObligationRemoved(): "obligation_removed", + _VKitGate.GateReason_ReasonFreshFail(): "fresh_fail", + _VKitGate.GateReason_ReasonNotApproved(): "not_approved", + _VKitGate.GateReason_ReasonUncoveredChange(): "uncovered_change", + _VKitGate.GateReason_ReasonReady(): "ready", + _VKitGate.GateReason_ReasonFreshBlocked(): "fresh_blocked", + _VKitGate.GateReason_ReasonBlocked(): "blocked", + _VKitGate.GateReason_ReasonStale(): "stale", + _VKitGate.GateReason_ReasonMissing(): "missing", +} + + +def decide_gate( + check_freshness: Sequence[str], + required_formal_freshness: Sequence[str], + *, + has_inventory: bool, + has_ghosts: bool, + has_weakened: bool, + has_incomparable: bool, + has_uncovered: bool, +) -> tuple[str, str]: + checks_seq = _dafny.SeqWithoutIsStrInference( + [_FRESHNESS_TO_DAFNY[item] for item in check_freshness] + ) + formal_seq = _dafny.SeqWithoutIsStrInference( + [_FRESHNESS_TO_DAFNY[item] for item in required_formal_freshness] + ) + decision = _VKitGate.default__.DecideGate( + checks_seq, + formal_seq, + has_inventory, + has_ghosts, + has_weakened, + has_incomparable, + has_uncovered, + ) + return _VERDICT_FROM_DAFNY[decision.verdict], _REASON_FROM_DAFNY[decision.reason] + + +_BETTER_TO_DAFNY = { + "lower": _VKitBudgets.Better_Lower(), + "higher": _VKitBudgets.Better_Higher(), +} + + +def check_limit(better: str, value: float, limit: float) -> bool: + d_val, val_fin = _dreal(value) + d_lim, lim_fin = _dreal(limit) + return bool( + _VKitBudgets.default__.CheckLimit( + _BETTER_TO_DAFNY[better], d_val, val_fin, d_lim, lim_fin + ) + ) + + +def check_regression( + better: str, value: float, base: float, max_regression_pct: float +) -> bool: + d_val, val_fin = _dreal(value) + d_base, base_fin = _dreal(base) + d_pct, pct_fin = _dreal(max_regression_pct) + return bool( + _VKitBudgets.default__.CheckRegression( + _BETTER_TO_DAFNY[better], + d_val, + val_fin, + d_base, + base_fin, + d_pct, + pct_fin, + ) + ) + + +_RUN_RESULT_TO_DAFNY = { + None: _VKitAcceptance.RunResult_ResNone(), + "PASS": _VKitAcceptance.RunResult_ResPass(), + "FAIL": _VKitAcceptance.RunResult_ResFail(), + "BLOCKED": _VKitAcceptance.RunResult_ResBlocked(), +} +_RUN_RESULT_OTHER = _VKitAcceptance.RunResult_ResOther() + +_RUN_STATE_TO_DAFNY = { + "interrupted": _VKitAcceptance.RunState_StateInterrupted(), + "done": _VKitAcceptance.RunState_StateDone(), +} +_RUN_STATE_OTHER = _VKitAcceptance.RunState_StateOther() + +_VERDICT_TAG_TO_DAFNY = { + "READY": _VKitAcceptance.VerdictTag_TagReady(), + "READY_SCOPED": _VKitAcceptance.VerdictTag_TagReadyScoped(), + "REJECTED": _VKitAcceptance.VerdictTag_TagRejected(), + "FAILED": _VKitAcceptance.VerdictTag_TagFailed(), + "BLOCKED": _VKitAcceptance.VerdictTag_TagBlocked(), +} +_VERDICT_TAG_OTHER = _VKitAcceptance.VerdictTag_TagOther() + +_DEF_CHANGE_FROM_DAFNY = { + _VKitAcceptance.DefChangeKind_DefUnchanged(): "unchanged", + _VKitAcceptance.DefChangeKind_DefStrengthening(): "strengthening", + _VKitAcceptance.DefChangeKind_DefWeakening(): "weakening", + _VKitAcceptance.DefChangeKind_DefIncomparable(): "incomparable", +} + + +def run_exit_code_kernel(result: str | None, state: str | None, unfinished: int) -> int: + d_res = _RUN_RESULT_TO_DAFNY.get(result, _RUN_RESULT_OTHER) + d_state = _RUN_STATE_TO_DAFNY.get(state, _RUN_STATE_OTHER) if state is not None else _RUN_STATE_OTHER + return int(_VKitAcceptance.default__.RunExitCode(d_res, d_state, unfinished)) + + +def verdict_exit_code_kernel(verdict: str) -> int: + d_tag = _VERDICT_TAG_TO_DAFNY.get(verdict, _VERDICT_TAG_OTHER) + return int(_VKitAcceptance.default__.VerdictExitCode(d_tag)) + + +def def_change_kernel( + has_old_dict: bool, + field_diffs: Sequence[tuple[str, Any, Any]], +) -> str: + d_diffs = [] + for kind, was, current in field_diffs: + if kind == "list": + d_was = _dafny.Set(_dstr(str(item)) for item in (was or ())) + d_cur = _dafny.Set(_dstr(str(item)) for item in (current or ())) + d_diffs.append(_VKitAcceptance.FieldDiff_ListFieldDiff(d_was, d_cur)) + elif kind == "timeout": + was_present = was is not None and math.isfinite(float(was)) + cur_present = current is not None and math.isfinite(float(current)) + d_was_val = _dreal(float(was))[0] if was_present else _dafny.BigRational(0, 1) + d_cur_val = _dreal(float(current))[0] if cur_present else _dafny.BigRational(0, 1) + d_diffs.append( + _VKitAcceptance.FieldDiff_TimeoutFieldDiff( + was_present, d_was_val, cur_present, d_cur_val + ) + ) + else: + d_diffs.append(_VKitAcceptance.FieldDiff_OpaqueFieldDiff()) + result = _VKitAcceptance.default__.DefChange( + has_old_dict, _dafny.SeqWithoutIsStrInference(d_diffs) + ) + return _DEF_CHANGE_FROM_DAFNY[result] + + +_OUTCOME_TO_DAFNY = { + "PASS": _VKitReceipt.OutcomeResult_OutPass(), + "FAIL": _VKitReceipt.OutcomeResult_OutFail(), + "BLOCKED": _VKitReceipt.OutcomeResult_OutBlocked(), +} + +_CLAIM_OUTCOME_FROM_DAFNY = { + _VKitReceipt.ClaimOutcome_ClaimEstablished(): "established", + _VKitReceipt.ClaimOutcome_ClaimRefuted(): "refuted", + _VKitReceipt.ClaimOutcome_ClaimUnknown(): "unknown", +} + +_CHECK_KIND_TO_DAFNY = { + "lean": _VKitReceipt.CheckKindTag_KindLean(), + "tlc": _VKitReceipt.CheckKindTag_KindTlc(), +} +_CHECK_KIND_OTHER = _VKitReceipt.CheckKindTag_KindOther() + + +def derive_assurance( + *, + has_check: bool, + is_shadow: bool, + kind: str, + custom_assurance: str = "empirical", +) -> str: + d_kind = _CHECK_KIND_TO_DAFNY.get(kind, _CHECK_KIND_OTHER) + out = _VKitReceipt.default__.DeriveAssurance( + has_check, is_shadow, d_kind, _dstr(custom_assurance) + ) + return _pystr(out) + + +def derive_claim_outcome(result: str, *, is_lean: bool, is_shadow: bool) -> str: + out = _VKitReceipt.default__.DeriveClaimOutcome( + _OUTCOME_TO_DAFNY[result], is_lean, is_shadow + ) + return _CLAIM_OUTCOME_FROM_DAFNY[out] + + +def verify_receipt_core( + *, + receipt_digest_matches: bool, + artifacts_match: bool, + subject_matches: bool, + policy_matches: bool, + job_id_matches: bool, + authority_matches: bool, + claim_outcome_consistent: bool, + assurance_consistent: bool, +) -> bool: + return bool( + _VKitReceipt.default__.VerifyReceiptCore( + receipt_digest_matches, + artifacts_match, + subject_matches, + policy_matches, + job_id_matches, + authority_matches, + claim_outcome_consistent, + assurance_consistent, + ) + ) + + +def verify_passing_receipt( + result: str, + *, + is_shadow: bool, + receipt_digest_matches: bool, + artifacts_match: bool, + subject_matches: bool, + policy_matches: bool, + job_id_matches: bool, + authority_matches: bool, + claim_outcome_consistent: bool, + assurance_consistent: bool, +) -> bool: + return bool( + _VKitReceipt.default__.VerifyPassingReceipt( + _OUTCOME_TO_DAFNY[result], + is_shadow, + receipt_digest_matches, + artifacts_match, + subject_matches, + policy_matches, + job_id_matches, + authority_matches, + claim_outcome_consistent, + assurance_consistent, + ) + ) + + +_COMP_KIND_FROM_DAFNY = { + _VKitChange.ComparisonKind_CompEquivalent(): "equivalent", + _VKitChange.ComparisonKind_CompStrengthens(): "strengthens", + _VKitChange.ComparisonKind_CompWeakens(): "weakens", + _VKitChange.ComparisonKind_CompIncomparable(): "incomparable", + _VKitChange.ComparisonKind_CompVacuous(): "vacuous", + _VKitChange.ComparisonKind_CompUnknown(): "unknown", +} + +_ENT_KIND_FROM_DAFNY = { + _VKitChange.EntailmentKind_EntEntailed(): "entailed", + _VKitChange.EntailmentKind_EntNotEntailed(): "not_entailed", + _VKitChange.EntailmentKind_EntVacuous(): "vacuous", + _VKitChange.EntailmentKind_EntUnknown(): "unknown", +} + +_DELEGATION_ERR_FROM_DAFNY = { + _VKitChange.DelegationError_ErrDifferentIntent(): "different_intent", + _VKitChange.DelegationError_ErrDifferentDomains(): "different_domains", + _VKitChange.DelegationError_ErrEmptyLegalInputs(): "empty_legal_inputs", + _VKitChange.DelegationError_ErrDifferentLegalInputs(): "different_legal_inputs", + _VKitChange.DelegationError_ErrEmptyIntersection(): "empty_intersection", + _VKitChange.DelegationError_ErrNotEntailed(): "not_entailed", + _VKitChange.DelegationError_ErrNotStrictStrengthening(): "not_strict_strengthening", + _VKitChange.DelegationError_ErrMissingStrictnessWitness(): "missing_strictness_witness", + _VKitChange.DelegationError_ErrNearMissInputIllegal(): "near_miss_input_illegal", + _VKitChange.DelegationError_ErrNearMissOutputOutsideDomain(): "near_miss_output_outside_domain", + _VKitChange.DelegationError_ErrNearMissOutputNotInBaseline(): "near_miss_output_not_in_baseline", + _VKitChange.DelegationError_ErrNearMissOutputInIntent(): "near_miss_output_in_intent", + _VKitChange.DelegationError_ErrNearMissOutputInClaim(): "near_miss_output_in_claim", +} + +_DIFF_KIND_TO_DAFNY = { + "preserved": _VKitChange.DifferenceKind_DiffPreserved(), + "guarded_requirement_met": _VKitChange.DifferenceKind_DiffGuardedRequirementMet(), + "standing_intent_repair": _VKitChange.DifferenceKind_DiffStandingIntentRepair(), + "violation": _VKitChange.DifferenceKind_DiffViolation(), + "unknown": _VKitChange.DifferenceKind_DiffUnknown(), +} + +_DIFF_KIND_FROM_DAFNY = {v: k for k, v in _DIFF_KIND_TO_DAFNY.items()} + +_DIFF_STATUS_FROM_DAFNY = { + _VKitChange.DifferenceStatus_StatusObservedConformance(): "observed_conformance", + _VKitChange.DifferenceStatus_StatusObservedViolation(): "observed_violation", + _VKitChange.DifferenceStatus_StatusUnknown(): "unknown", +} + +_METHOD_STATUS_TO_DAFNY = { + "observed_violation": _VKitChange.ChangeMethodStatus_MethodObservedViolation(), + "proof_rejected": _VKitChange.ChangeMethodStatus_MethodProofRejected(), + "observed_conformance": _VKitChange.ChangeMethodStatus_MethodObservedConformance(), + "verified": _VKitChange.ChangeMethodStatus_MethodVerified(), + "unknown": _VKitChange.ChangeMethodStatus_MethodUnknown(), +} +_METHOD_STATUS_OTHER = _VKitChange.ChangeMethodStatus_MethodOther() + +_CONCLUSION_FROM_DAFNY = { + _VKitChange.ChangeConclusion_ConclObservedViolation(): "observed_violation", + _VKitChange.ChangeConclusion_ConclProofRejected(): "proof_rejected", + _VKitChange.ChangeConclusion_ConclUnsupported(): "unsupported", + _VKitChange.ChangeConclusion_ConclUnknown(): "unknown", + _VKitChange.ChangeConclusion_ConclModelVerified(): "model_verified", + _VKitChange.ChangeConclusion_ConclObservedConformance(): "observed_conformance", +} + + +def _dcontract( + domain_digest: str, + admissible_inputs: Sequence[str], + allowed_outputs: Mapping[str, Sequence[str]], +) -> Any: + sorted_inputs = sorted(admissible_inputs) + d_inputs = _dafny.SeqWithoutIsStrInference([_dstr(token) for token in sorted_inputs]) + d_map = _dafny.Map( + { + _dstr(token): _dafny.SeqWithoutIsStrInference( + [_dstr(out) for out in sorted(outs)] + ) + for token, outs in allowed_outputs.items() + } + ) + return _VKitChange.Contract_Contract(_dstr(domain_digest), d_inputs, d_map) + + +def _unpack_refinement(ref_opt: Any) -> tuple[bool, bool, str | None, tuple[str, str] | None] | None: + if ref_opt.is_None: + return None + ref = ref_opt.val + in_w = None if ref.inputWitness.is_None else _pystr(ref.inputWitness.val) + if ref.outputWitness.is_None: + out_w = None + else: + pair = ref.outputWitness.val + out_w = (_pystr(pair[0]), _pystr(pair[1])) + return bool(ref.preconditionIncluded), bool(ref.postconditionIncluded), in_w, out_w + + +def compare_contracts_kernel( + old_domain_digest: str, + old_inputs: Sequence[str], + old_outputs: Mapping[str, Sequence[str]], + new_domain_digest: str, + new_inputs: Sequence[str], + new_outputs: Mapping[str, Sequence[str]], +) -> tuple[ + str, + tuple[bool, bool, str | None, tuple[str, str] | None] | None, + tuple[bool, bool, str | None, tuple[str, str] | None] | None, +]: + res = _VKitChange.default__.CompareContracts( + _dcontract(old_domain_digest, old_inputs, old_outputs), + _dcontract(new_domain_digest, new_inputs, new_outputs), + ) + return ( + _COMP_KIND_FROM_DAFNY[res.kind], + _unpack_refinement(res.oldToNew), + _unpack_refinement(res.newToOld), + ) + + +def intent_entails_claim_kernel( + intent_domain_digest: str, + intent_inputs: Sequence[str], + intent_outputs: Mapping[str, Sequence[str]], + claim_domain_digest: str, + claim_inputs: Sequence[str], + claim_outputs: Mapping[str, Sequence[str]], +) -> tuple[str, bool | None, bool | None, str | None, tuple[str, str] | None]: + res = _VKitChange.default__.IntentEntailsClaim( + _dcontract(intent_domain_digest, intent_inputs, intent_outputs), + _dcontract(claim_domain_digest, claim_inputs, claim_outputs), + ) + in_inc = None if res.inputsIncluded.is_None else bool(res.inputsIncluded.val) + out_inc = None if res.outputsIncluded.is_None else bool(res.outputsIncluded.val) + in_w = None if res.inputWitness.is_None else _pystr(res.inputWitness.val) + if res.outputWitness.is_None: + out_w = None + else: + pair = res.outputWitness.val + out_w = (_pystr(pair[0]), _pystr(pair[1])) + return _ENT_KIND_FROM_DAFNY[res.kind], in_inc, out_inc, in_w, out_w + + +def check_delegation_kernel( + *, + intent_digest: str, + basis_intent_digest: str, + intent_domain_digest: str, + intent_inputs: Sequence[str], + intent_outputs: Mapping[str, Sequence[str]], + baseline_domain_digest: str, + baseline_inputs: Sequence[str], + baseline_outputs: Mapping[str, Sequence[str]], + assumptions_domain_digest: str, + assumptions_inputs: Sequence[str], + assumptions_outputs: Mapping[str, Sequence[str]], + claim_domain_digest: str, + claim_inputs: Sequence[str], + claim_outputs: Mapping[str, Sequence[str]], + domain_observations: Iterable[str], + near_miss_input: str, + near_miss_output: str, +) -> tuple[bool, str, str, str]: + res = _VKitChange.default__.CheckDelegation( + _dstr(intent_digest), + _dstr(basis_intent_digest), + _dcontract(intent_domain_digest, intent_inputs, intent_outputs), + _dcontract(baseline_domain_digest, baseline_inputs, baseline_outputs), + _dcontract(assumptions_domain_digest, assumptions_inputs, assumptions_outputs), + _dcontract(claim_domain_digest, claim_inputs, claim_outputs), + _dafny.Set(_dstr(obs) for obs in domain_observations), + _dstr(near_miss_input), + _dstr(near_miss_output), + ) + if res.is_DelegationAccepted: + return True, "", _pystr(res.strictnessInput), _pystr(res.strictnessOutput) + return ( + False, + _DELEGATION_ERR_FROM_DAFNY[res.error], + _pystr(res.detailInput), + _pystr(res.detailOutput), + ) + + +def classify_difference( + base_output: str, + candidate_output: str, + standing_outputs: Iterable[str], + *, + has_guards: bool, + guard_intersection: Iterable[str], +) -> str: + res = _VKitChange.default__.ClassifyDifference( + _dstr(base_output), + _dstr(candidate_output), + _dafny.Set(_dstr(item) for item in standing_outputs), + has_guards, + _dafny.Set(_dstr(item) for item in guard_intersection), + ) + return _DIFF_KIND_FROM_DAFNY[res] + + +def assess_difference_status( + admissible_count: int, missing_count: int, kinds: Sequence[str] +) -> str: + d_kinds = _dafny.SeqWithoutIsStrInference([_DIFF_KIND_TO_DAFNY[k] for k in kinds]) + res = _VKitChange.default__.AssessDifferenceStatus( + admissible_count, missing_count, d_kinds + ) + return _DIFF_STATUS_FROM_DAFNY[res] + + +def conclude_change_methods(statuses: Sequence[str]) -> str: + d_statuses = _dafny.SeqWithoutIsStrInference( + [_METHOD_STATUS_TO_DAFNY.get(s, _METHOD_STATUS_OTHER) for s in statuses] + ) + res = _VKitChange.default__.ConcludeChangeMethods(d_statuses) + return _CONCLUSION_FROM_DAFNY[res] diff --git a/src/vkit/mcp/__init__.py b/src/vkit/mcp/__init__.py index f7ffab1..162e3df 100644 --- a/src/vkit/mcp/__init__.py +++ b/src/vkit/mcp/__init__.py @@ -14,15 +14,15 @@ from jsonschema import ValidationError, validate from .. import __version__ +from vkit.console.settings import load_settings +from vkit.console.workspaces import remember from vkit.core import evidence from vkit.core import jobs from vkit.core import query from vkit.core.categories import CATEGORIES, INFRASTRUCTURE_TOOLS from vkit.core.manifest import ManifestError -from vkit.runtime.paths import Project, open_project from vkit.core.schemas import VERIFICATION_REQUEST, SchemaValidationError, schema -from vkit.console.settings import load_settings -from vkit.console.workspaces import remember +from vkit.runtime.paths import Project, ProjectError, open_project MAX_WAIT_SECONDS = query.MAX_WAIT_SECONDS INSTRUCTIONS = ( @@ -138,7 +138,7 @@ def call(self, name: str, arguments: dict[str, Any] | None) -> tuple[Any, bool]: return {"error": "unknown or unavailable tool"}, True _check(arguments, tool.input_schema) return tool.handler(self, arguments), False - except (OSError, Refusal, ManifestError, ValueError, SchemaValidationError) as exc: + except (OSError, Refusal, ManifestError, ProjectError, sqlite3.Error, ValueError, SchemaValidationError) as exc: return {"error": str(exc)}, True @@ -301,7 +301,14 @@ def _run_wait(server: Server, args: dict[str, Any]) -> Any: def _evidence_export(server: Server, args: dict[str, Any]) -> Any: ctx = server.context() - return evidence.export(ctx.store, args["run_id"], Path(args["output"]), + raw_output = Path(args["output"]) + if evidence.is_link(raw_output): + raise Refusal("evidence export output must not be a symlink") + resolved_output = raw_output.resolve(strict=False) + project_root = ctx.project.root.resolve() + if resolved_output == project_root or resolved_output.is_relative_to(project_root): + raise Refusal("evidence export output must be outside the project working tree") + return evidence.export(ctx.store, args["run_id"], raw_output, include_assets=args.get("include_assets", False)) diff --git a/src/vkit/runtime/container.py b/src/vkit/runtime/container.py index a19feb1..b2d67c5 100644 --- a/src/vkit/runtime/container.py +++ b/src/vkit/runtime/container.py @@ -250,7 +250,7 @@ def run_container( ) except (OSError, RuntimeError) as exc: started = proc.Exit(None, launch_error=str(exc)) - removed, resolved_id, cleanup_error = _remove_owned(run_id, container_id) + removed, resolved_id, cleanup_error = _remove_owned(run_id, container_id if valid_cid else None) stored_id = resolved_id if resolved_id and _CID.fullmatch(resolved_id) else None descriptor.update(container_id=stored_id, status="removed" if removed else "blocked") if cleanup_error: diff --git a/src/vkit/runtime/paths.py b/src/vkit/runtime/paths.py index a4ebbc9..d93bd9c 100644 --- a/src/vkit/runtime/paths.py +++ b/src/vkit/runtime/paths.py @@ -31,6 +31,10 @@ def _git(args: list[str], cwd: Path) -> str: raise ProjectError("git is not installed or not on PATH") from exc except NotADirectoryError as exc: raise ProjectError(f"{cwd} is not a usable working directory: {exc}") from exc + except subprocess.TimeoutExpired as exc: + raise ProjectError(f"git {' '.join(args)} timed out") from exc + except PermissionError as exc: + raise ProjectError(f"cannot run git in {cwd}: {exc}") from exc if done.returncode != 0: detail = done.stderr.strip().splitlines() message = detail[-1] if detail else f"git {' '.join(args)} failed" diff --git a/src/vkit/runtime/proc.py b/src/vkit/runtime/proc.py index 434516c..3594106 100644 --- a/src/vkit/runtime/proc.py +++ b/src/vkit/runtime/proc.py @@ -101,7 +101,12 @@ def run(argv: Sequence[str], *, cwd: Path, stdout_path: Path, stderr_path: Path, ) except OSError as exc: return Exit(None, launch_error=f"{argv[0]}: {exc}") - tree = _Tree(proc) + try: + tree = _Tree(proc) + except BaseException: + proc.kill() + proc.wait() + raise deadline = time.monotonic() + timeout_seconds output_limited = threading.Event() output_lock = threading.Lock() @@ -152,5 +157,5 @@ def drain(pipe, destination) -> None: finally: tree.close() for reader in readers: - reader.join() + reader.join(timeout=2.0) return Exit(code, output_limited=output_limited.is_set()) diff --git a/src/vkit/verifiers/_common.py b/src/vkit/verifiers/_common.py new file mode 100644 index 0000000..ee159e0 --- /dev/null +++ b/src/vkit/verifiers/_common.py @@ -0,0 +1,30 @@ +"""Shared refusal and duplicate-outcome helpers for verifier adapters.""" +from __future__ import annotations + +from collections.abc import Callable, Iterable +from typing import TypeVar + +from vkit.core.outcome import Blocked, BlockedReason + +_T = TypeVar("_T") + + +def refuse(token: str, reason: BlockedReason, detail: str) -> Blocked: + """A BLOCKED whose detail leads with a stable token that callers and tests match on.""" + return Blocked(reason, f"{token}: {detail}") + + +def contradiction( + items: Iterable[_T], + key: Callable[[_T], str], + outcome: Callable[[_T], str], +) -> tuple[str, str, str] | None: + """One id reported twice with different outcomes, or None. Identical repeats are one result.""" + seen: dict[str, str] = {} + for item in items: + item_key = key(item) + item_outcome = outcome(item) + first = seen.setdefault(item_key, item_outcome) + if first != item_outcome: + return (item_key, first, item_outcome) + return None diff --git a/src/vkit/verifiers/dispatch.py b/src/vkit/verifiers/dispatch.py index 2e4b837..174e9cc 100644 --- a/src/vkit/verifiers/dispatch.py +++ b/src/vkit/verifiers/dispatch.py @@ -43,7 +43,6 @@ def obligation_results(self) -> tuple[list[dict], list[dict]]: return satisfied, counterexamples - def read_scenarios(raw: bytes, required: tuple[str, ...]) -> ScenarioReading: try: document = parse_artifact(raw) @@ -54,8 +53,15 @@ def read_scenarios(raw: bytes, required: tuple[str, ...]) -> ScenarioReading: return ScenarioReading((), Blocked(BlockedReason.ARTIFACT_EMPTY, "the artifact listed no scenarios")) scenarios = tuple(ScenarioResult(item["id"], item["result"] == "PASS", item["observation"]) for item in document["scenarios"]) - known = {s.scenario_id for s in scenarios} - missing = [s for s in required if s not in known] + seen_ids: set[str] = set() + for scenario in scenarios: + if scenario.scenario_id in seen_ids: + return ScenarioReading((), Blocked( + BlockedReason.ARTIFACT_MALFORMED, + f"the artifact reports duplicate scenario {scenario.scenario_id!r}", + )) + seen_ids.add(scenario.scenario_id) + missing = [s for s in required if s not in seen_ids] if missing: return ScenarioReading(scenarios, Blocked( BlockedReason.SCENARIO_UNKNOWN, f"the artifact never reported required scenario(s): {', '.join(missing)}")) @@ -64,19 +70,14 @@ def read_scenarios(raw: bytes, required: tuple[str, ...]) -> ScenarioReading: return ScenarioReading(scenarios, measurements=measurements) -def _variant(check: Any) -> Any: - return getattr(check, "variant", None) or check - - def _substituted(parts: tuple, run_dir: Path, interpreter: str) -> tuple[str, ...]: return tuple(str(p).replace("{{run_dir}}", str(run_dir)).replace("{{python}}", interpreter) for p in parts) def _runner(check: Any, run_dir: Path, python: str | None) -> tuple[str, ...]: - variant = _variant(check) interpreter = python or sys.executable - return (*_substituted((variant.runner.executable,), run_dir, interpreter), - *_substituted(variant.runner.base_argv, run_dir, interpreter)) + return (*_substituted((check.runner.executable,), run_dir, interpreter), + *_substituted(check.runner.base_argv, run_dir, interpreter)) def _scenario_argv(check: Any, run_dir: Path, python: str | None) -> tuple[str, ...]: @@ -85,19 +86,19 @@ def _scenario_argv(check: Any, run_dir: Path, python: str | None) -> tuple[str, def _pytest_argv(check: Any, run_dir: Path, python: str | None) -> tuple[str, ...]: return (*_runner(check, run_dir, python), "-p", pytest_adapter.PLUGIN_NAME, - pytest_adapter.REPORT_FLAG, str(run_dir / check.artifact_name), *_variant(check).required_tests) + pytest_adapter.REPORT_FLAG, str(run_dir / check.artifact_name), *check.required_tests) def _property_argv(check: Any, run_dir: Path, python: str | None) -> tuple[str, ...]: - variant = _variant(check) return (*_runner(check, run_dir, python), "-p", pytest_adapter.PLUGIN_NAME, "-p", PROPERTY_PLUGIN, pytest_adapter.REPORT_FLAG, str(run_dir / check.artifact_name), - property_adapter.SETTINGS_FLAG, property_adapter.settings_token(variant), *variant.required_tests) + property_adapter.SETTINGS_FLAG, property_adapter.settings_token(check), *check.required_tests) def _node_argv(check: Any, run_dir: Path, python: str | None) -> tuple[str, ...]: - variant = _variant(check) - files, pattern = node_adapter.argv_selectors(variant.required_tests) + files, pattern = node_adapter.argv_selectors(check.required_tests) + if not files and pattern: + raise ValueError(pattern) executable, *base = _runner(check, run_dir, python) return (executable, *base, node_adapter.isolation_flag(executable), "--test-reporter", node_adapter.reporter_argv_token(), @@ -109,15 +110,15 @@ def _node_argv(check: Any, run_dir: Path, python: str | None) -> tuple[str, ...] CheckKind.SCENARIO: Adapter(CheckKind.SCENARIO, _scenario_argv, lambda check, raw: read_scenarios(raw, tuple(o.test_id for o in check.required_scenarios))), CheckKind.PYTEST: Adapter(CheckKind.PYTEST, _pytest_argv, - lambda check, raw: pytest_adapter.interpret(raw, _variant(check))), + lambda check, raw: pytest_adapter.interpret(raw, check)), CheckKind.NODE_TEST: Adapter(CheckKind.NODE_TEST, _node_argv, - lambda check, raw: node_adapter.interpret(raw, _variant(check))), + lambda check, raw: node_adapter.interpret(raw, check)), CheckKind.PROPERTY: Adapter(CheckKind.PROPERTY, _property_argv, - lambda check, raw: property_adapter.interpret(raw, _variant(check))), + lambda check, raw: property_adapter.interpret(raw, check)), CheckKind.LEAN: Adapter(CheckKind.LEAN, lean_adapter.argv_for, - lambda check, raw: lean_adapter.interpret(raw, _variant(check))), + lambda check, raw: lean_adapter.interpret(raw, check)), CheckKind.TLC: Adapter(CheckKind.TLC, tlc_adapter.argv_for, - lambda check, raw: tlc_adapter.interpret(raw, _variant(check))), + lambda check, raw: tlc_adapter.interpret(raw, check)), CheckKind.STATIC: Adapter(CheckKind.STATIC, _scenario_argv, lambda check, raw: static_adapter.read(raw, check.cwd.as_posix().rstrip("/") + "/")), } diff --git a/src/vkit/verifiers/external.py b/src/vkit/verifiers/external.py index c795668..52046cf 100644 --- a/src/vkit/verifiers/external.py +++ b/src/vkit/verifiers/external.py @@ -11,13 +11,15 @@ from pathlib import Path, PurePosixPath from typing import Any, Callable -from vkit.runtime import proc from vkit.core.evidence import is_link from vkit.core.inputs import canonical_digest, file_digest from vkit.core.outcome import Blocked, BlockedReason, Outcome, Passed +from vkit.core.store import write_json +from vkit.runtime import proc from .spec import ExternalCheck, PinnedCommand, PinnedFile _SHA256 = re.compile(r"^[0-9a-f]{64}$") +_MAX_OUTPUT_BYTES = 1024 * 1024 class ExternalProtocolError(ValueError): @@ -62,7 +64,7 @@ def execute( for artifact in check.evidence_artifacts: _safe_relative(artifact, "evidence artifact") producer_request = run_dir / "producer-request.json" - _write_json(producer_request, _request(check, job, specification, evidence_dir, current_identity)) + write_json(producer_request, _request(check, job, specification, evidence_dir, current_identity)) _ensure_identity(check, current_identity) started = time.monotonic() producer_exit = _run_command( @@ -167,7 +169,7 @@ def _check_evidence( checker_request = run_dir / "checker-request.json" receipt_path = run_dir / "checker-receipt.json" _unlink_output(receipt_path) - _write_json(checker_request, _request(check, job, specification, evidence_dir, current_identity) | { + write_json(checker_request, _request(check, job, specification, evidence_dir, current_identity) | { "evidence_bundle": {"files": files, "digest": evidence_digest}, }) _ensure_identity(check, current_identity) @@ -225,7 +227,7 @@ def _check_evidence( }, "obligations": receipt["obligations"], } - _write_json(run_dir / check.artifact_name, metadata) + write_json(run_dir / check.artifact_name, metadata) return outcome, metadata @@ -452,6 +454,7 @@ def _run_command( timeout_seconds=timeout_seconds, env=env, should_cancel=should_cancel, + max_output_bytes=_MAX_OUTPUT_BYTES, ) @@ -546,10 +549,6 @@ def _unlink_output(path: Path) -> None: raise ExternalProtocolError(f"checker receipt output is not a file: {path.name}") -def _write_json(path: Path, value: dict[str, Any]) -> None: - path.write_text(json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")), encoding="utf-8") - - def _failure_metadata( check: ExternalCheck, job: dict[str, Any], diff --git a/src/vkit/verifiers/lean_adapter.py b/src/vkit/verifiers/lean_adapter.py index 3a6ecb9..7a8c1ae 100644 --- a/src/vkit/verifiers/lean_adapter.py +++ b/src/vkit/verifiers/lean_adapter.py @@ -13,6 +13,7 @@ from typing import Any from vkit.core.outcome import Blocked, BlockedReason, ScenarioResult +from ._common import refuse as _refuse from .obligation import TheoremObligation, obligation_to_json from .spec import LeanCheck, LeanProfile @@ -30,11 +31,6 @@ COMPARATOR_RUNNER_PATH = Path(__file__).resolve().parent / "comparator_runner.py" -def _refuse(token: str, reason: BlockedReason, detail: str) -> Blocked: - """A BLOCKED whose detail leads with a stable token that callers and tests match on.""" - return Blocked(reason, f"{token}: {detail}") - - @dataclass(frozen=True) class LeanRun: """A report that passed every shape check in `_read`.""" @@ -84,23 +80,53 @@ def obligation_results(self) -> tuple[list[dict], list[dict]]: return satisfied, counterexamples -def _comparator_result(raw: bytes, variant: LeanCheck) -> AdapterResult | Blocked: +def _comparator_result(raw: bytes, check: LeanCheck) -> AdapterResult | Blocked: try: report = json.loads(raw.decode("utf-8")) + if not isinstance(report, dict): + raise TypeError(f"expected object, got {type(report).__name__}") status = report["status"] except (UnicodeDecodeError, ValueError, KeyError, TypeError) as exc: return _refuse("report_malformed", BlockedReason.ARTIFACT_MALFORMED, f"comparator report unreadable: {exc}") + version = report.get("version") + if type(version) is not int or version != REPORT_VERSION: + return _refuse( + "report_version", BlockedReason.ARTIFACT_MALFORMED, + f"comparator report version is {version!r}; this vkit reads version {REPORT_VERSION} only", + ) if status == "challenge_changed": return _refuse("challenge_changed", BlockedReason.NOT_APPROVED, f"the challenge now digests to {report.get('challenge_sha256')}, not the accepted " - f"{variant.challenge_sha256}; a human must accept the new statements") + f"{check.challenge_sha256}; a human must accept the new statements") if status == "accepted": + if not check.theorems: + return _refuse( + "report_malformed", BlockedReason.ARTIFACT_MALFORMED, + "the check declares no required theorems to accept", + ) + reported_digest = report.get("challenge_sha256") + if not isinstance(reported_digest, str) or not reported_digest: + return _refuse( + "challenge_unknown", BlockedReason.ARTIFACT_MALFORMED, + "comparator report recorded no challenge_sha256 digest", + ) + if not check.challenge_sha256 or reported_digest != check.challenge_sha256: + return _refuse( + "challenge_altered", BlockedReason.SOURCE_CHANGED, + f"comparator checked challenge {reported_digest}, not the accepted {check.challenge_sha256}", + ) + exit_code = report.get("exit_code") + if type(exit_code) is not int or exit_code != 0: + return _refuse( + "report_malformed", BlockedReason.ARTIFACT_MALFORMED, + f"comparator reported status 'accepted' with exit_code {exit_code!r}", + ) prose = (f"comparator: same statement as the frozen challenge, axioms within " - f"{', '.join(variant.permitted_axioms) or 'none'}, kernel accepted; build sandbox: " + f"{', '.join(check.permitted_axioms) or 'none'}, kernel accepted; build sandbox: " f"{report.get('sandbox')}") return AdapterResult( - tuple((t, ()) for t in variant.theorems), (), prose, - _comparator_trust(report, variant), + tuple((t, ()) for t in check.theorems), (), prose, + _comparator_trust(report, check), ) if status == "rejected": lines = [line for line in str(report.get("output", "")).splitlines() if line.strip()] @@ -119,21 +145,21 @@ def _axiom_prose(axioms: tuple[str, ...]) -> str: return f"the kernel checked it against {', '.join(axioms)}" -def _comparator_trust(report: dict[str, Any], variant: LeanCheck) -> dict[str, Any]: +def _comparator_trust(report: dict[str, Any], check: LeanCheck) -> dict[str, Any]: return { "schema_version": 1, "engine": {"name": "comparator", "version": report.get("comparator_version")}, "scope": { "kind": "lean_theorems", "items": [{ - "module": variant.challenge.module, - "source": variant.challenge.path, - "source_sha256": variant.challenge_sha256, - "theorems": [item.theorem for item in variant.theorems], + "module": check.challenge.module, + "source": check.challenge.path, + "source_sha256": check.challenge_sha256, + "theorems": [item.theorem for item in check.theorems], }], "assumptions": { "status": "policy_bound", - "items": [{"permitted_axioms": sorted(variant.permitted_axioms)}], + "items": [{"permitted_axioms": sorted(check.permitted_axioms)}], }, }, "dependencies": {"status": "not_reported", "items": []}, @@ -141,19 +167,19 @@ def _comparator_trust(report: dict[str, Any], variant: LeanCheck) -> dict[str, A "status": "not_reported", "by_obligation": [ {"obligation": f"{item.module}.{item.theorem}", "status": "not_reported", "items": []} - for item in variant.theorems + for item in check.theorems ], }, "independent_check": {"status": "not_provided", "checker": None, "certificate": None}, } -def logical_trust_from_report(report: LeanRun, variant: LeanCheck) -> dict[str, Any]: +def logical_trust_from_report(report: LeanRun, check: LeanCheck) -> dict[str, Any]: """Normalize only facts present in the engine report and accepted check policy.""" audit = _audit_step(report) - records = _audit_records(audit, variant.challenge.module) if audit is not None else {} + records = _audit_records(audit, check.challenge.module) if audit is not None else {} rows = [] - for item in variant.theorems: + for item in check.theorems: axioms = records.get(item.theorem) rows.append({ "obligation": f"{item.module}.{item.theorem}", @@ -175,7 +201,7 @@ def logical_trust_from_report(report: LeanRun, variant: LeanCheck) -> dict[str, }], "assumptions": { "status": "policy_bound", - "items": [{"permitted_axioms": sorted(variant.permitted_axioms)}], + "items": [{"permitted_axioms": sorted(check.permitted_axioms)}], }, }, "dependencies": {"status": "not_reported", "items": []}, @@ -192,8 +218,7 @@ def reported_logical_trust(raw: bytes, check: LeanCheck) -> dict[str, Any] | Non report = _read(raw) if isinstance(report, Blocked): return None - variant = getattr(check, "variant", None) or check - return logical_trust_from_report(report, variant) + return logical_trust_from_report(report, check) def source_diagnostics( @@ -248,25 +273,28 @@ def argv_for(check: LeanCheck, run_dir: Path, python: str | None) -> tuple[str, The runner is the script beside this module, never a path from the environment. """ interpreter = python or sys.executable - variant = getattr(check, "variant", None) or check - if variant.profile == LeanProfile.UNREVIEWED: + if check.profile == LeanProfile.UNREVIEWED: + if check.solution is None or not check.challenge_sha256: + raise ValueError( + "the unreviewed_agent profile requires both a solution module and a challenge_sha256" + ) return ( interpreter, str(COMPARATOR_RUNNER_PATH), - "--comparator", variant.toolchain.comparator or "comparator", + "--comparator", check.toolchain.comparator or "comparator", "--project-dir", str(Path(check.cwd)), - "--challenge-path", variant.challenge.path, "--challenge-sha256", variant.challenge_sha256, - "--challenge-module", variant.challenge.module, "--solution-module", variant.solution.module, - "--theorems", ",".join(t.theorem for t in variant.theorems), - "--axioms", ",".join(variant.permitted_axioms), + "--challenge-path", check.challenge.path, "--challenge-sha256", check.challenge_sha256, + "--challenge-module", check.challenge.module, "--solution-module", check.solution.module, + "--theorems", ",".join(t.theorem for t in check.theorems), + "--axioms", ",".join(check.permitted_axioms), "--run-dir", str(run_dir), "--report", str(run_dir / check.artifact_name), ) return ( interpreter, str(RUNNER_PATH), - "--lean", variant.toolchain.tool if _is_path(variant.toolchain.tool) else "lean", - "--source", _absolute(variant.challenge.path, check), - "--module", variant.challenge.module, - AUDIT_FLAG, ",".join(t.theorem for t in variant.theorems), - "--profile", variant.profile or DEFAULT_PROFILE, + "--lean", check.toolchain.tool if _is_path(check.toolchain.tool) else "lean", + "--source", _absolute(check.challenge.path, check), + "--module", check.challenge.module, + AUDIT_FLAG, ",".join(t.theorem for t in check.theorems), + "--profile", check.profile or DEFAULT_PROFILE, "--run-dir", str(run_dir), "--report", str(run_dir / check.artifact_name), ) @@ -282,29 +310,33 @@ def _absolute(relative: str, check: Any) -> str: return str((root / relative).resolve()) -def interpret(raw: bytes, check: LeanCheck) -> AdapterResult | Blocked: +def interpret( + raw: bytes, + check: LeanCheck, + *, + measured_challenge_sha256: str | None = None, +) -> AdapterResult | Blocked: """What one Lean run established, or why it established nothing.""" - variant = getattr(check, "variant", None) or check - profile = variant.profile or DEFAULT_PROFILE + profile = check.profile or DEFAULT_PROFILE if profile == LeanProfile.UNREVIEWED: - return _comparator_result(raw, variant) + return _comparator_result(raw, check) if profile != LeanProfile.REVIEWED: return _refuse( "profile_unsupported", BlockedReason.ARTIFACT_MALFORMED, f"the check selected unsupported Lean profile {profile!r}", ) - if any(item.module != variant.challenge.module for item in variant.theorems): + if any(item.module != check.challenge.module for item in check.theorems): return _refuse( "module_mismatch", BlockedReason.ARTIFACT_MALFORMED, "every required theorem must name the same module as the declared " - f"challenge {variant.challenge.module!r}", + f"challenge {check.challenge.module!r}", ) report = _read(raw) if isinstance(report, Blocked): return report - expected_version = variant.toolchain.version + expected_version = check.toolchain.version if not isinstance(expected_version, str) or not expected_version.strip(): return _refuse( "toolchain_unpinned", BlockedReason.TOOL_MISSING, @@ -324,32 +356,35 @@ def interpret(raw: bytes, check: LeanCheck) -> AdapterResult | Blocked: f"the check pins Lean {expected_version}, but the report names " f"Lean {actual_version}", ) - expected_theorems = tuple(item.theorem for item in variant.theorems) - expected_source = Path(_absolute(variant.challenge.path, check)).resolve() + expected_theorems = tuple(item.theorem for item in check.theorems) + expected_source = Path(_absolute(check.challenge.path, check)).resolve() reported_source = Path(report.source) if not reported_source.is_absolute(): reported_source = Path(check.cwd) / reported_source - if (report.module != variant.challenge.module + if (report.module != check.challenge.module or report.profile != profile or reported_source.resolve() != expected_source or report.theorems != expected_theorems): return _refuse( "module_mismatch", BlockedReason.ARTIFACT_MALFORMED, - f"the check names module {variant.challenge.module!r}, source " + f"the check names module {check.challenge.module!r}, source " f"{str(expected_source)!r}, profile {profile!r}, and theorem list " f"{expected_theorems!r}, but the report names module {report.module!r}, " f"source {report.source!r}, profile {report.profile!r}, and theorem " f"list {report.theorems!r}", ) - challenge = Path(_absolute(variant.challenge.path, check)) - if not challenge.is_file(): - return _refuse( - "challenge_absent", BlockedReason.ARTIFACT_MISSING, - f"the approved challenge module {challenge} does not exist, so the run " - "compared nothing against anything", - ) - measured = _digest(challenge) + if measured_challenge_sha256 is not None: + measured = measured_challenge_sha256 + else: + challenge = Path(_absolute(check.challenge.path, check)) + if not challenge.is_file(): + return _refuse( + "challenge_absent", BlockedReason.ARTIFACT_MISSING, + f"the approved challenge module {challenge} does not exist, so the run " + "compared nothing against anything", + ) + measured = _digest(challenge) if not report.challenge_sha256: return _refuse( "challenge_unknown", BlockedReason.ARTIFACT_MALFORMED, @@ -420,7 +455,7 @@ def interpret(raw: bytes, check: LeanCheck) -> AdapterResult | Blocked: ) audit_errors = [m for m in audit.get("messages", ()) if m["severity"] == "error"] if audit_errors: - missing = sorted(_unresolved(audit, variant)) + missing = sorted(_unresolved(audit, check)) return _refuse( "theorem_absent", BlockedReason.SCENARIO_UNKNOWN, f"the axiom audit did not resolve " @@ -428,12 +463,23 @@ def interpret(raw: bytes, check: LeanCheck) -> AdapterResult | Blocked: f"{', '.join(missing) if missing else audit_errors[0]['data']}. A " "theorem the kernel could not name is not a theorem that holds.", ) + unparsed_audit = [m for m in audit.get("messages", ()) if m["severity"] == "unparsed"] + if unparsed_audit: + return _refuse( + "report_malformed", BlockedReason.ARTIFACT_MALFORMED, + f"the axiom audit emitted unparsed Lean output: {unparsed_audit[0]['data'][:200]}", + ) + if audit.get("exit_code") != 0: + return _refuse( + "audit_failed", BlockedReason.INTERNAL_ERROR, + f"the axiom audit exited {audit.get('exit_code')}, so its output is not a valid audit", + ) - records = _audit_records(audit, variant.challenge.module) - permitted = frozenset(variant.permitted_axioms) - logical_trust = logical_trust_from_report(report, variant) + records = _audit_records(audit, check.challenge.module) + permitted = frozenset(check.permitted_axioms) + logical_trust = logical_trust_from_report(report, check) observations: list[tuple[TheoremObligation, tuple[str, ...]]] = [] - for obligation in variant.theorems: + for obligation in check.theorems: axioms = records.get(obligation.theorem) if axioms is None: return _refuse( @@ -477,7 +523,9 @@ def _first_error(steps: list[dict]) -> str: for step in steps: for message in step.get("messages", ()): if message["severity"] == "error": - return message["data"].strip().splitlines()[0] + lines = message["data"].strip().splitlines() + if lines: + return lines[0] return f"exit {steps[0].get('exit_code')}" diff --git a/src/vkit/verifiers/lean_runner.py b/src/vkit/verifiers/lean_runner.py index 9ffce2c..22b9e02 100644 --- a/src/vkit/verifiers/lean_runner.py +++ b/src/vkit/verifiers/lean_runner.py @@ -143,12 +143,12 @@ def main(argv: list[str]) -> int: for attempt, name in ((1, "build"), (2, "recheck")): build_dir = run_dir / f"olean-{attempt}" - build_dir.mkdir(parents=True, exist_ok=True) + olean = build_dir / Path(*args.module.split(".")).with_suffix(".olean") + olean.parent.mkdir(parents=True, exist_ok=True) step = _run([ - args.lean, "-o", str(build_dir / f"{args.module}.olean"), "--json", source.name, + args.lean, "-o", str(olean), "--json", source.name, ], source.parent) step["name"] = f"{name}:{attempt}" - olean = build_dir / f"{args.module}.olean" step["olean"] = str(olean) step["olean_digest"] = ( hashlib.sha256(olean.read_bytes()).hexdigest() if olean.is_file() else "" diff --git a/src/vkit/verifiers/node_adapter.py b/src/vkit/verifiers/node_adapter.py index 4ec098a..92c4dd2 100644 --- a/src/vkit/verifiers/node_adapter.py +++ b/src/vkit/verifiers/node_adapter.py @@ -14,6 +14,7 @@ from vkit.core.outcome import Blocked, BlockedReason from vkit.runtime.nowindow import hidden_window +from ._common import contradiction as _find_contradiction, refuse as _refuse from .obligation import CaseObligation, case_results, scenario_results from .spec import NodeTestCheck @@ -86,9 +87,10 @@ cases.push({ name: data.name, location: relative(data.file), - skip: data.skip == null ? null : String(data.skip), + skip: data.skip == null || data.skip === false ? null : String(data.skip), + todo: data.todo == null || data.todo === false ? null : String(data.todo), code: failureCode(error), - message: error ? String(error.message || error) : null, + message: error ? String(error.message || error).slice(0, 4096) : null, duration: typeof details.duration_ms === "number" ? details.duration_ms : 0, }); } @@ -99,6 +101,7 @@ const verdict = failed ? "not ok" : "ok"; out += verdict + " " + (index + 1) + " - " + entry.name; if (entry.skip !== null) out += " # SKIP " + entry.skip; + else if (entry.todo !== null) out += " # TODO " + entry.todo; out += "\\n ---\\n"; out += " duration_ms: " + entry.duration + "\\n"; out += " type: 'test'\\n"; @@ -185,7 +188,7 @@ def argv_selectors(required: tuple[str, ...]) -> tuple[tuple[str, ...], str]: """The files to run and the `--test-name-pattern` selecting the required names, or `((), refusal text)` for a malformed id. - The pattern is an exact alternation, so a required name is never discharged by a longer one. + The pattern is an anchored alternation, so a required name is never discharged by a longer one. """ files: list[str] = [] names: list[str] = [] @@ -198,7 +201,9 @@ def argv_selectors(required: tuple[str, ...]) -> tuple[tuple[str, ...], str]: files.append(file) if name not in names: names.append(name) - return tuple(files), "|".join(re.escape(name) for name in names) + if not names: + return tuple(files), "" + return tuple(files), f"^(?:{'|'.join(re.escape(name) for name in names)})$" @dataclass(frozen=True) @@ -245,11 +250,6 @@ def obligation_results(self) -> tuple[list[dict], list[dict]]: return case_results(self.observations, self.counterexamples) -def _refuse(token: str, reason: BlockedReason, detail: str) -> Blocked: - """A BLOCKED whose detail leads with a stable token that callers and tests match on.""" - return Blocked(reason, f"{token}: {detail}") - - _ENTRY = re.compile( r"^(?Pnot ok|ok)\s+(?P\d+)\s+-\s+(?P.+?)" r"(?:\s+#\s+(?PSKIP|TODO)\b(?P.*))?\s*$", @@ -309,7 +309,7 @@ def _read(raw: bytes) -> RunnerReport | Blocked: "the runner collected no test cases, which is not evidence about anything", ) - contradiction = _contradiction(tests) + contradiction = _find_contradiction(tests, lambda t: t.identity, lambda t: t.outcome) if contradiction is not None: return _refuse( "report_contradiction", BlockedReason.ARTIFACT_MALFORMED, @@ -421,17 +421,6 @@ def _message(block: str) -> str: return message[:MESSAGE_LIMIT] if message else "" -def _contradiction(tests: list[CaseOutcome]) -> tuple[str, str, str] | None: - """One case reported twice with different outcomes, or None. Identical repeats are one result. - """ - seen: dict[str, str] = {} - for test in tests: - first = seen.setdefault(test.identity, test.outcome) - if first != test.outcome: - return (test.identity, first, test.outcome) - return None - - def interpret(raw: bytes, check: NodeTestCheck) -> AdapterResult | Blocked: """What the run established, or why it could not. Required ids match exactly on `(file, name)`. """ diff --git a/src/vkit/verifiers/property_adapter.py b/src/vkit/verifiers/property_adapter.py index 623922e..0a5d946 100644 --- a/src/vkit/verifiers/property_adapter.py +++ b/src/vkit/verifiers/property_adapter.py @@ -11,9 +11,11 @@ from vkit.core.outcome import Blocked, BlockedReason from . import pytest_adapter +from ._common import refuse as _refuse from .obligation import CaseObligation, case_results, scenario_results from .spec import HypothesisSettings, PropertyCheck + def _measured(document: dict) -> HypothesisSettings: """The generator settings a run reported; read from the report, not the manifest, because a decorator or profile can move them. @@ -98,14 +100,13 @@ def interpret(raw: bytes, check: PropertyCheck) -> PropertyAdapterResult | Block """What the run established, or why it could not. Refusals are the pytest adapter's, plus `generator_absent` when a passing run reported no - generator settings: without them the sampled family is unknown. A failure needs no family. + generator settings and `generator_weakened` when measured bounds fall below the pinned ones. """ if check.generator is None: - return Blocked( - BlockedReason.ARTIFACT_MALFORMED, - "generator_absent: a property check declares no generator settings, so " - "this run cannot say what family it sampled and cannot be property " - "evidence", + return _refuse( + "generator_absent", BlockedReason.ARTIFACT_MALFORMED, + "a property check declares no generator settings, so this run cannot say " + "what family it sampled and cannot be property evidence", ) reading = pytest_adapter.interpret(raw, check) if isinstance(reading, Blocked): @@ -116,27 +117,42 @@ def interpret(raw: bytes, check: PropertyCheck) -> PropertyAdapterResult | Block _measured(reported[test_id]) for test_id in check.required_tests if test_id in reported ] - measured = min( - measured_settings, key=lambda settings: settings.max_examples, - ) if measured_settings else None - - if reading.is_pass and len(measured_settings) != len(check.required_tests): - unmeasured = [ - test_id for test_id in check.required_tests if test_id not in reported - ] - return Blocked( - BlockedReason.SCENARIO_UNKNOWN, - "generator_absent: required case(s) reported no generator settings: " - f"{', '.join(unmeasured)}. The check declared a pinned generator family " - "and the run reported none, so a sampled family cannot be claimed for a " - "run that passed", - ) + min_examples = ( + min(settings.max_examples for settings in measured_settings) + if measured_settings else None + ) + min_steps = ( + min(settings.stateful_step_count for settings in measured_settings) + if measured_settings else 0 + ) + + if reading.is_pass: + if len(measured_settings) != len(check.required_tests): + unmeasured = [ + test_id for test_id in check.required_tests if test_id not in reported + ] + return _refuse( + "generator_absent", BlockedReason.SCENARIO_UNKNOWN, + f"required case(s) reported no generator settings: {', '.join(unmeasured)}. " + "The check declared a pinned generator family and the run reported none, " + "so a sampled family cannot be claimed for a run that passed", + ) + if min_examples is None or min_examples < check.generator.max_examples: + return _refuse( + "generator_weakened", BlockedReason.SCENARIO_UNKNOWN, + f"the run sampled at most {min_examples} example(s), below the pinned " + f"minimum of {check.generator.max_examples}", + ) + if (check.generator.stateful_step_count + and min_steps < check.generator.stateful_step_count): + return _refuse( + "generator_weakened", BlockedReason.SCENARIO_UNKNOWN, + f"the run used at most {min_steps} stateful step(s), below the pinned " + f"minimum of {check.generator.stateful_step_count}", + ) return PropertyAdapterResult( reading=reading, - scope=TestedScope( - None if measured is None else measured.max_examples, - 0 if measured is None else measured.stateful_step_count, - ), + scope=TestedScope(min_examples, min_steps), ) @@ -182,7 +198,8 @@ def pytest_configure(config: Any) -> None: # noqa: D103 - a pytest plugin hook """Activate the pinned generator profile before collection, since `@given` captures settings at decoration time. """ - from hypothesis import HealthCheck, settings + from hypothesis import HealthCheck, core, settings + from hypothesis.database import DirectoryBasedExampleDatabase raw = config.getoption(SETTINGS_FLAG, None) if not raw: @@ -199,18 +216,37 @@ def pytest_configure(config: Any) -> None: # noqa: D103 - a pytest plugin hook f"examples, which is the one field a property run cannot do without. " f"Got {document!r}" ) + raw_health_checks = document.get("suppress_health_check", ()) + if not isinstance(raw_health_checks, (list, tuple)): + raise SettingsRefused( + f"suppress_health_check must be a list of HealthCheck names, got {raw_health_checks!r}" + ) + health_checks = [] + for name in raw_health_checks: + if not isinstance(name, str) or not hasattr(HealthCheck, name): + raise SettingsRefused(f"unknown Hypothesis HealthCheck: {name!r}") + health_checks.append(getattr(HealthCheck, name)) deadline = document.get("deadline") - pinned: dict = { + pinned: dict[str, Any] = { "max_examples": document["max_examples"], "deadline": None if deadline is None else timedelta(seconds=float(deadline)), - "suppress_health_check": tuple( - getattr(HealthCheck, name) - for name in document.get("suppress_health_check", ()) - if hasattr(HealthCheck, name) - ), + "suppress_health_check": tuple(health_checks), } steps = document.get("stateful_step_count") if steps: pinned["stateful_step_count"] = int(steps) + if "replay_database" in document: + replay_db = document["replay_database"] + if replay_db is None or replay_db == "none": + pinned["database"] = None + elif isinstance(replay_db, str) and replay_db.strip(): + pinned["database"] = DirectoryBasedExampleDatabase(replay_db) + else: + raise SettingsRefused(f"invalid replay_database: {replay_db!r}") + if "replay_seed" in document and document["replay_seed"] is not None: + seed = document["replay_seed"] + if type(seed) is not int: + raise SettingsRefused(f"replay_seed must be an integer, got {seed!r}") + core.global_force_seed = seed settings.register_profile(VKIT_PROFILE, **pinned) settings.load_profile(VKIT_PROFILE) \ No newline at end of file diff --git a/src/vkit/verifiers/pytest_adapter.py b/src/vkit/verifiers/pytest_adapter.py index 500210a..c1cad6a 100644 --- a/src/vkit/verifiers/pytest_adapter.py +++ b/src/vkit/verifiers/pytest_adapter.py @@ -10,6 +10,7 @@ from typing import Any from vkit.core.outcome import Blocked, BlockedReason +from ._common import contradiction as _find_contradiction, refuse as _refuse from .obligation import CaseObligation, case_results, scenario_results from .spec import PytestCheck @@ -196,11 +197,6 @@ def pytest_sessionfinish(session: Any, exitstatus: int) -> None: _INTERRUPTED_EXITSTATUSES = frozenset({2, 3, 4}) -def _refuse(token: str, reason: BlockedReason, detail: str) -> Blocked: - """A BLOCKED whose detail leads with a stable token that callers and tests match on.""" - return Blocked(reason, f"{token}: {detail}") - - def _read(raw: bytes) -> RunnerReport | Blocked: """Decode and shape-check a report, refusing each unusable form with its own token.""" try: @@ -289,7 +285,7 @@ def _read(raw: bytes) -> RunnerReport | Blocked: ) parsed.append(TestOutcome(nodeid, outcome, float(duration), message, generator)) - contradiction = _contradiction(parsed) + contradiction = _find_contradiction(parsed, lambda t: t.nodeid, lambda t: t.outcome) if contradiction is not None: return _refuse( "report_contradiction", BlockedReason.ARTIFACT_MALFORMED, @@ -320,16 +316,6 @@ def _is_generator(document: Any) -> bool: return isinstance(document["suppress_health_check"], list) -def _contradiction(tests: list[TestOutcome]) -> tuple[str, str, str] | None: - """One id reported twice with different outcomes, or None. Identical repeats are one result.""" - seen: dict[str, str] = {} - for test in tests: - first = seen.setdefault(test.nodeid, test.outcome) - if first != test.outcome: - return (test.nodeid, first, test.outcome) - return None - - def interpret(raw: bytes, check: PytestCheck) -> AdapterResult | Blocked: """What the run established, or why it could not. Required test ids match exactly, since node ids carry the parameterisation. diff --git a/src/vkit/verifiers/static_adapter.py b/src/vkit/verifiers/static_adapter.py index 8492d62..f309df4 100644 --- a/src/vkit/verifiers/static_adapter.py +++ b/src/vkit/verifiers/static_adapter.py @@ -57,7 +57,9 @@ def read(raw: bytes, root_uri: str = "") -> StaticReading | Blocked: if root_uri and path.lower().startswith(root_uri.lower()): path = path[len(root_uri):] message = (result.get("message") or {}).get("text", "") - findings.append(Finding(str(result.get("ruleId", "?")), path.lstrip("/"), line, message)) + rule_id = result.get("ruleId") + rule = str(rule_id) if rule_id is not None else "?" + findings.append(Finding(rule, path.lstrip("/"), line, message)) except (UnicodeDecodeError, json.JSONDecodeError, KeyError, TypeError, AttributeError) as exc: return Blocked(BlockedReason.ARTIFACT_MALFORMED, f"not a SARIF log: {exc}") return StaticReading(tuple(findings)) diff --git a/src/vkit/verifiers/tlc_adapter.py b/src/vkit/verifiers/tlc_adapter.py index ab7cac1..4afe7be 100644 --- a/src/vkit/verifiers/tlc_adapter.py +++ b/src/vkit/verifiers/tlc_adapter.py @@ -4,6 +4,7 @@ """ from __future__ import annotations +import hashlib import json import os import re @@ -13,6 +14,7 @@ from typing import Any from vkit.core.outcome import Blocked, BlockedReason, ScenarioResult +from ._common import refuse as _refuse from .obligation import PropertyObligation, obligation_to_json from .spec import TlcCheck @@ -62,11 +64,6 @@ TRACE_LIMIT = 6000 -def _refuse(token: str, reason: BlockedReason, detail: str) -> Blocked: - """A BLOCKED whose detail leads with a stable token that callers and tests match on.""" - return Blocked(reason, f"{token}: {detail}") - - @dataclass(frozen=True) class TlcRun: """A report that passed every shape check in `_read`.""" @@ -84,6 +81,7 @@ class TlcRun: witness_validation: dict[str, Any] | None trace_artifact: str | None validation_artifact: str | None + config_sha256: str | None = None @dataclass(frozen=True) @@ -168,20 +166,19 @@ def argv_for(check: TlcCheck, run_dir: Path, python: str | None) -> tuple[str, . `java` process exists. """ interpreter = python or sys.executable - variant = getattr(check, "variant", None) or check root = Path(check.cwd) - tool = variant.toolchain.tool + tool = check.toolchain.tool java, jar = _tool_paths(tool) - fingerprint = variant.fingerprint + fingerprint = check.fingerprint return ( interpreter, str(_runner_path()), "--java", java, "--jar", jar, - "--jar-sha256", variant.toolchain.jar_sha256 or "", - "--expected-version", variant.toolchain.version or "", - "--model", variant.model.module, - "--model-path", variant.model.path, - "--config", variant.config, + "--jar-sha256", check.toolchain.jar_sha256 or "", + "--expected-version", check.toolchain.version or "", + "--model", check.model.module, + "--model-path", check.model.path, + "--config", check.config, "--root", str(root.resolve()), "--constants-from-config", str(fingerprint.constants_from_config).lower(), "--checksum-states", str(fingerprint.checksum_states).lower(), @@ -208,13 +205,17 @@ def _runner_path() -> Path: return Path(__file__).resolve().parent / "tlc_runner.py" -def interpret(raw: bytes, check: TlcCheck) -> AdapterResult | Blocked: +def interpret( + raw: bytes, + check: TlcCheck, + *, + config_text: str | None = None, +) -> AdapterResult | Blocked: """What one TLC run established, or why it established nothing.""" - variant = getattr(check, "variant", None) or check expected_fingerprint = ( - variant.fingerprint.constants_from_config, - variant.fingerprint.checksum_states, - variant.fingerprint.workers, + check.fingerprint.constants_from_config, + check.fingerprint.checksum_states, + check.fingerprint.workers, ) if expected_fingerprint != SUPPORTED_FINGERPRINT: return _refuse( @@ -222,14 +223,14 @@ def interpret(raw: bytes, check: TlcCheck) -> AdapterResult | Blocked: f"the check declares fingerprint settings {expected_fingerprint!r}; " f"this runner supports only {SUPPORTED_FINGERPRINT!r}", ) - expected_version = variant.toolchain.version + expected_version = check.toolchain.version if not isinstance(expected_version, str) or not expected_version.strip(): return _refuse( "toolchain_unpinned", BlockedReason.TOOL_MISSING, "the check declares no TLC version, so the checker that explored the " "model is unknown", ) - if not variant.toolchain.jar_sha256: + if not check.toolchain.jar_sha256: return _refuse( "jar_unpinned", BlockedReason.TOOL_MISSING, "the check declares no tla2tools jar digest, so the checker that " @@ -239,17 +240,17 @@ def interpret(raw: bytes, check: TlcCheck) -> AdapterResult | Blocked: if isinstance(report, Blocked): return report - if report.model != variant.model.module: + if report.model != check.model.module: return _refuse( "model_mismatch", BlockedReason.ARTIFACT_MALFORMED, - f"the check names model {variant.model.module!r}, but the report names " + f"the check names model {check.model.module!r}, but the report names " f"{report.model!r}", ) - if report.model_path != variant.model.path or report.config != variant.config: + if report.model_path != check.model.path or report.config != check.config: return _refuse( "source_path_mismatch", BlockedReason.ARTIFACT_MALFORMED, - f"the check names model path {variant.model.path!r} and config " - f"{variant.config!r}, but the report names model path " + f"the check names model path {check.model.path!r} and config " + f"{check.config!r}, but the report names model path " f"{report.model_path!r} and config {report.config!r}", ) if report.fingerprint != expected_fingerprint: @@ -258,11 +259,11 @@ def interpret(raw: bytes, check: TlcCheck) -> AdapterResult | Blocked: f"the check declares fingerprint settings {expected_fingerprint!r}, " f"but the report records {report.fingerprint!r}", ) - if report.jar_sha256 != variant.toolchain.jar_sha256: + if report.jar_sha256 != check.toolchain.jar_sha256: return _refuse( "jar_mismatch", BlockedReason.PREREQUISITE_MISSING, f"the check pins tla2tools.jar sha256 " - f"{variant.toolchain.jar_sha256}, but the report records " + f"{check.toolchain.jar_sha256}, but the report records " f"{report.jar_sha256}", ) actual_version = _tlc_version(report.tool_version) @@ -329,12 +330,27 @@ def interpret(raw: bytes, check: TlcCheck) -> AdapterResult | Blocked: "rather than being cut off between the two.", ) - text = _config_text(check, variant) - if isinstance(text, Blocked): - return text + if config_text is not None: + config_bytes = config_text.encode("utf-8") + text = config_text.replace("\r\n", "\n") + else: + loaded = _config_bytes(check) + if isinstance(loaded, Blocked): + return loaded + config_bytes = loaded + text = config_bytes.replace(b"\r\n", b"\n").decode("utf-8", "replace") + + if report.config_sha256 is not None: + actual_config_sha256 = hashlib.sha256(config_bytes).hexdigest() + if actual_config_sha256 != report.config_sha256: + return _refuse( + "source_changed", BlockedReason.SOURCE_CHANGED, + f"the config file measured {actual_config_sha256} and the run read " + f"{report.config_sha256}; the config changed since TLC ran", + ) checked = _checked_properties(text) - required = {obligation.property_name for obligation in variant.properties} + required = {obligation.property_name for obligation in check.properties} unchecked = sorted(required - set(checked)) if unchecked: return _refuse( @@ -344,20 +360,20 @@ def interpret(raw: bytes, check: TlcCheck) -> AdapterResult | Blocked: "A property the run never checked cannot be discharged by it.", ) - bounds = _bounds(text, variant) + bounds = _bounds(text, check) if isinstance(bounds, Blocked): return bounds if violated: - return _failed_property(variant, _violation_trace(report.stdout), report, exploration, text) + return _failed_property(check, _violation_trace(report.stdout), report, exploration, text) return AdapterResult( - tuple(variant.properties), (), variant.model.module, report.tool_version, exploration, - _logical_trust(variant, report, text), + tuple(check.properties), (), check.model.module, report.tool_version, exploration, + _logical_trust(check, report, text), ) -def _failed_property(variant: TlcCheck, trace: str, report: TlcRun, +def _failed_property(check: TlcCheck, trace: str, report: TlcRun, exploration: Exploration, config_text: str) -> AdapterResult | Blocked: """Attribute and validate one finite safety witness, or refuse to call it a refutation.""" match = re.search( @@ -377,7 +393,7 @@ def _failed_property(variant: TlcCheck, trace: str, report: TlcRun, "traces are validated by this adapter; the raw checker output remains available", ) failures = [ - obligation for obligation in variant.properties + obligation for obligation in check.properties if obligation.property_name == match.group(2) ] if len(failures) != 1: @@ -401,6 +417,13 @@ def _failed_property(variant: TlcCheck, trace: str, report: TlcRun, f"replayed as the same state sequence against the frozen model and config: {reason}; " "the raw checker output remains available", ) + required_keys = ("method", "property", "state_sequence_sha256", "minimization") + missing_keys = [key for key in required_keys if key not in validation] + if missing_keys: + return _refuse( + "report_malformed", BlockedReason.ARTIFACT_MALFORMED, + f"the validated witness record is missing required field(s): {', '.join(missing_keys)}", + ) witness = { "artifact": report.trace_artifact, "validation_artifact": report.validation_artifact, @@ -415,22 +438,22 @@ def _failed_property(variant: TlcCheck, trace: str, report: TlcRun, "source_locations_truncated": validation.get("source_locations_truncated", False), } return AdapterResult( - (), ((failures[0], trace, witness),), variant.model.module, report.tool_version, exploration, - _logical_trust(variant, report, config_text), + (), ((failures[0], trace, witness),), check.model.module, report.tool_version, exploration, + _logical_trust(check, report, config_text), ) -def _logical_trust(variant: TlcCheck, report: TlcRun, config_text: str) -> dict[str, Any]: +def _logical_trust(check: TlcCheck, report: TlcRun, config_text: str) -> dict[str, Any]: """Facts about this bounded TLC run; unreported trust facts stay explicitly unknown.""" items = [ - {"kind": "model", "module": variant.model.module, "path": variant.model.path}, - {"kind": "config", "path": variant.config}, + {"kind": "model", "module": check.model.module, "path": check.model.path}, + {"kind": "config", "path": check.config}, {"kind": "properties", "names": list(_checked_properties(config_text))}, - {"kind": "bounds", "values": dict(variant.bounds.as_pairs)}, + {"kind": "bounds", "values": dict(check.bounds.as_pairs)}, {"kind": "fingerprint", "constants_from_config": report.fingerprint[0], "checksum_states": report.fingerprint[1], "workers": report.fingerprint[2]}, ] - properties = [p.property_name for p in variant.properties] + properties = [p.property_name for p in check.properties] return { "schema_version": 1, "engine": {"name": "TLC", "version": report.tool_version}, @@ -496,17 +519,16 @@ def _tail(blob: str) -> str: return "\n".join([line for line in blob.splitlines() if line.strip()][-15:])[:2000] -def _config_text(check: Any, variant: TlcCheck) -> str | Blocked: - """The config file TLC was pointed at, read from disk rather than from the check's declaration. - """ - path = Path(check.cwd) / variant.config +def _config_bytes(check: TlcCheck) -> bytes | Blocked: + """The config file TLC was pointed at, read from disk rather than from the check's declaration.""" + path = Path(check.cwd) / check.config if not path.is_file(): return _refuse( "bounds_unresolved", BlockedReason.ARTIFACT_MISSING, f"the config {path} does not exist, so there is no recorded " "configuration for this model result", ) - return path.read_bytes().replace(b"\r\n", b"\n").decode("utf-8", "replace") + return path.read_bytes() _CONFIG_KEYWORDS = ( @@ -516,8 +538,8 @@ def _config_text(check: Any, variant: TlcCheck) -> str | Blocked: def _strip_tla_comments(config_text: str) -> str: - text = re.sub(r"\(\*.*?\*\)", "", config_text, flags=re.DOTALL) - return re.sub(r"\\\*[^\n]*", "", text) + text = re.sub(r"\\\*[^\n]*", "", config_text) + return re.sub(r"\(\*.*?\*\)", "", text, flags=re.DOTALL) def _checked_properties(config_text: str) -> tuple[str, ...]: @@ -540,12 +562,12 @@ def _checked_properties(config_text: str) -> tuple[str, ...]: return tuple(names) -def _bounds(config_text: str, variant: TlcCheck) -> dict | Blocked: +def _bounds(config_text: str, check: TlcCheck) -> dict | Blocked: """Each pinned bound checked against the config that set it; a bound the config does not assign, or contradicts, is refused. """ assigned = _constants(config_text) - unresolved = sorted(name for name, _ in variant.bounds.as_pairs if name not in assigned) + unresolved = sorted(name for name, _ in check.bounds.as_pairs if name not in assigned) if unresolved: return _refuse( "bounds_unresolved", BlockedReason.ARTIFACT_MALFORMED, @@ -556,7 +578,7 @@ def _bounds(config_text: str, variant: TlcCheck) -> dict | Blocked: ) mismatched = sorted( f"{name}={value} (config has {assigned[name]})" - for name, value in variant.bounds.as_pairs + for name, value in check.bounds.as_pairs if value != assigned[name] ) if mismatched: @@ -567,7 +589,7 @@ def _bounds(config_text: str, variant: TlcCheck) -> dict | Blocked: "claim, and reporting it under the declared one is the lie this " "reader's existence prevents.", ) - return dict(variant.bounds.as_pairs) + return dict(check.bounds.as_pairs) def _constants(config_text: str) -> dict[str, int]: @@ -597,15 +619,21 @@ def _cardinality(value: str) -> int: if ".." in text: low, _, high = text.partition("..") try: - return int(high.strip()) - int(low.strip()) + 1 + return max(0, int(high.strip()) - int(low.strip()) + 1) except ValueError: return -1 if re.fullmatch(r"-?\d+", text): return 1 - inner = text.strip().strip("{}").strip() - if not inner: - return 0 - return len([part for part in inner.split(",") if part.strip()]) + if text.startswith("{") and text.endswith("}"): + inner = text[1:-1].strip() + if not inner: + return 0 + if "{" in inner or "}" in inner: + return -1 + return len([part for part in inner.split(",") if part.strip()]) + if "{" in text or "}" in text: + return -1 + return 1 if text else 0 def _read(raw: bytes) -> TlcRun | Blocked: @@ -693,6 +721,17 @@ def _read(raw: bytes) -> TlcRun | Blocked: if value is not None and (not isinstance(value, str) or Path(value).name != value): return _refuse("report_malformed", BlockedReason.ARTIFACT_MALFORMED, f"{name} is not a safe artifact name") + source_identity = document.get("source_identity") + config_sha256: str | None = None + if source_identity is not None: + if (not isinstance(source_identity, dict) + or not isinstance(source_identity.get("config_sha256"), str) + or not source_identity.get("config_sha256")): + return _refuse( + "report_malformed", BlockedReason.ARTIFACT_MALFORMED, + "the report's source_identity does not record a valid config_sha256", + ) + config_sha256 = source_identity["config_sha256"] return TlcRun( str(document.get("model", "")), str(document.get("model_path", "")), @@ -708,6 +747,7 @@ def _read(raw: bytes) -> TlcRun | Blocked: witness_validation, trace_artifact, validation_artifact, + config_sha256=config_sha256, ) diff --git a/src/vkit/verifiers/tlc_runner.py b/src/vkit/verifiers/tlc_runner.py index d448c3f..9fff197 100644 --- a/src/vkit/verifiers/tlc_runner.py +++ b/src/vkit/verifiers/tlc_runner.py @@ -24,6 +24,8 @@ from vkit.verifiers.tlc_witness import same_state_sequence, source_locations, trace_states, without_internal_state # noqa: E402 OUTPUT_LIMIT = 40000 +HEAD_LIMIT = 8000 +TAIL_LIMIT = 32000 TRACE_REPLAY_TIMEOUT_SECONDS = 5 TRACE_MINIMIZATION_SECONDS = 12.0 TRACE_MINIMIZATION_MAX_ATTEMPTS = 12 @@ -38,6 +40,15 @@ def _digest(path: Path) -> str: return hashlib.sha256(path.read_bytes()).hexdigest() +def _truncate(text: str) -> str: + """Keep the leading version banner and the trailing completion summary or violation trace.""" + if len(text) <= OUTPUT_LIMIT: + return text + marker = "\n...[truncated]...\n" + tail_budget = max(0, TAIL_LIMIT - len(marker)) + return text[:HEAD_LIMIT] + marker + text[-tail_budget:] + + def _run(argv: list[str], cwd: Path, timeout: float = 7200) -> dict: done = subprocess.run( argv, cwd=str(cwd), capture_output=True, encoding="utf-8", errors="replace", @@ -46,8 +57,8 @@ def _run(argv: list[str], cwd: Path, timeout: float = 7200) -> dict: return { "argv": list(argv), "exit_code": int(done.returncode), - "stdout": (done.stdout or "")[:OUTPUT_LIMIT], - "stderr": (done.stderr or "")[:OUTPUT_LIMIT], + "stdout": _truncate(done.stdout or ""), + "stderr": _truncate(done.stderr or ""), } @@ -276,7 +287,7 @@ def main(argv: list[str]) -> int: report["complete"] = False report["failure"] = f"the TLC toolchain could not be launched: {exc}" return _write(report, Path(args.report)) - source_identity = ( _digest(model_source), _digest(config_source) ) + source_identity = (_digest(model_source), _digest(config_source)) report["source_identity"] = { "model_sha256": source_identity[0], "config_sha256": source_identity[1], diff --git a/tests/change/_helpers.py b/tests/change/_helpers.py new file mode 100644 index 0000000..40744ff --- /dev/null +++ b/tests/change/_helpers.py @@ -0,0 +1,308 @@ +from __future__ import annotations + +from copy import deepcopy +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys + +import pytest + +from helpers import NO_WINDOW, git +from vkit.change.certification import ChangeCertificationRequest, FiniteContract, IntentRevision +from vkit.change.paired_profiles import identify_environment +from vkit.core.store import write_json + +POLICY_PATH = "verification/change-intents/accepted.v1.json" +SEMANTIC_ROLES = ("binding", "codec", "observation", "environment") + + +def json_bytes(value: object) -> bytes: + return (json.dumps(value, sort_keys=True, separators=(",", ":")) + "\n").encode() + + +def sha256_bytes(raw: bytes) -> str: + return hashlib.sha256(raw).hexdigest() + + +def git_output(root: Path, *args: str) -> str: + result = subprocess.run( + ["git", "-c", "user.email=t@vkit", "-c", "user.name=t", *args], + cwd=root, + check=True, + capture_output=True, + text=True, + **NO_WINDOW, + ) + return result.stdout.strip() + + +def git_commit(root: Path, message: str, *paths: str) -> str: + git(root, "add", *(paths or (".",))) + git(root, "commit", "-qm", message) + return git_output(root, "rev-parse", "HEAD") + + +def resolve_language_tools(language: str) -> tuple[Path | None, Path | None]: + if language == "python": + return None, Path(sys.executable).resolve() + if language == "rust": + raw = os.environ.get("VKIT_TEST_RUSTC") + if raw is None: + rustup = shutil.which("rustup") + if rustup is not None: + result = subprocess.run( + [rustup, "which", "rustc"], + capture_output=True, + text=True, + check=False, + **NO_WINDOW, + ) + if result.returncode == 0: + raw = result.stdout.strip() + raw = raw or shutil.which("rustc") + if raw is None or not Path(raw).is_file(): + pytest.skip("Rust compiler is unavailable; set VKIT_TEST_RUSTC to its executable") + return Path(raw).resolve(), None + compiler = os.environ.get("VKIT_TEST_TSC") + runtime = shutil.which("node") + if compiler is None or not Path(compiler).is_file() or runtime is None: + pytest.skip("native TypeScript compiler or Node is unavailable; set VKIT_TEST_TSC") + return Path(compiler).resolve(), Path(runtime).resolve() + + +def binding_source(language: str, delta: int) -> tuple[str, str]: + if language == "rust": + return "candidate.rs", f"pub fn convert(value: u32) -> u32 {{ value + {delta} }}\n" + if language == "typescript": + return "candidate.ts", f"export function convert(value: number): number {{ return value + {delta}; }}\n" + return "candidate.py", f"def convert(value):\n return value + {delta}\n" + + +def domain_json( + *, + binding: str = "ledger::reserve", + inputs: tuple[str, ...] | list[str] = ("x", "y"), + observations: tuple[str, ...] | list[str] = ("zero", "one", "two"), + codec_sha256: str = "a" * 64, + observation_sha256: str = "b" * 64, + environment_sha256: str = "c" * 64, + **changes: object, +) -> dict: + value: dict[str, object] = { + "binding": binding, + "inputs": list(inputs), + "observations": list(observations), + "codec_sha256": codec_sha256, + "observation_sha256": observation_sha256, + "environment_sha256": environment_sha256, + } + value.update(changes) + return value + + +def contract_json( + outputs: dict[str, list[str]], + *, + admissible: tuple[str, ...] | list[str] | None = None, + domain_raw: dict | None = None, +) -> dict: + return { + "domain": domain_raw if domain_raw is not None else domain_json(), + "admissible_inputs": list(outputs.keys() if admissible is None else admissible), + "allowed_outputs": [ + {"input": token, "outputs": list(values)} for token, values in outputs.items() + ], + } + + +def request_json( + contract_raw: dict, + *, + base_oid: str = "1" * 40, + candidate_oid: str = "2" * 40, + intent_sha256: str = "d" * 64, +) -> dict: + return { + "schema_version": 1, + "base_oid": base_oid, + "candidate_oid": candidate_oid, + "intent_sha256": intent_sha256, + "claim": {"kind": "finite_contract", "contract": contract_raw}, + } + + +def parse_finite_contract(contract_raw: dict) -> FiniteContract: + return ChangeCertificationRequest.from_json(request_json(contract_raw)).claim + + +def intent_revision_json( + contract_raw: dict, + *, + source: str = "requirements.md#choice", + statement: str = "Return one of the listed values for each input.", + binding_sha256: str = "d" * 64, + artifact_prefix: str = "", +) -> dict: + dom = contract_raw["domain"] + hashes = { + "binding": binding_sha256, + "codec": dom["codec_sha256"], + "observation": dom["observation_sha256"], + "environment": dom["environment_sha256"], + } + return { + "schema_version": 1, + "requirement": {"source": source, "statement": statement}, + "contract": contract_raw, + "artifacts": { + role: {"path": f"{artifact_prefix}{role}.json", "sha256": hashes[role]} + for role in SEMANTIC_ROLES + }, + } + + +def make_intent_revision(contract_raw: dict, **kwargs: object) -> IntentRevision: + return IntentRevision.from_json(intent_revision_json(contract_raw, **kwargs)) + + +def build_paired_repo( + tmp_path: Path, + *, + language: str, + candidate_delta: int, + outputs: dict[str, list[str]], + semantic_changes: dict[str, object] | None = None, + candidate_source: str | None = None, + wrong_tool_pin: bool = False, + inputs: tuple[str, ...] = ("0", "1"), + observations: tuple[str, ...] = ("0", "1", "2", "3"), +) -> tuple[Path, str, dict]: + root = tmp_path / "repo" + root.mkdir(parents=True) + git(root, "init", "-q") + + compiler, runtime = resolve_language_tools(language) + environment = json.loads(json.dumps(identify_environment(language, compiler=compiler, runtime=runtime))) + if wrong_tool_pin: + role = "runtime" if language == "python" else "compiler" + environment["tools"][role]["sha256"] = "0" * 64 + source_map = {"rust": "candidate.rs", "python": "candidate.py", "typescript": "candidate.ts"} + semantic: dict[str, object] = { + "binding": { + "schema_version": 1, + "kind": "u32_function", + "language": language, + "source": source_map[language], + "symbol": "convert", + }, + "codec": {"schema_version": 1, "kind": "u32_le"}, + "observation": {"schema_version": 1, "kind": "u32_return"}, + "environment": environment, + } + if semantic_changes: + semantic.update(semantic_changes) + raw_artifacts = {role: json_bytes(value) for role, value in semantic.items()} + hashes = {role: sha256_bytes(raw) for role, raw in raw_artifacts.items()} + dom = domain_json( + binding="example::convert", + inputs=inputs, + observations=observations, + codec_sha256=hashes["codec"], + observation_sha256=hashes["observation"], + environment_sha256=hashes["environment"], + ) + ctr = contract_json(dict(sorted(outputs.items())), admissible=inputs, domain_raw=dom) + revision = make_intent_revision( + ctr, + source="requirements.md#conversion", + statement="The conversion may return any listed value for each input.", + binding_sha256=hashes["binding"], + artifact_prefix="verification/semantics/", + ) + for role, content in raw_artifacts.items(): + path = root / f"verification/semantics/{role}.json" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(content) + revision_path = root / f"verification/change-intents/{revision.digest}.v1.json" + revision_path.parent.mkdir(parents=True, exist_ok=True) + revision_path.write_bytes(json_bytes(revision.to_json())) + (root / POLICY_PATH).write_bytes(json_bytes({"schema_version": 1, "accepted": [revision.digest]})) + + source_name, base_source = binding_source(language, 0) + source = root / source_name + source.write_text(base_source, encoding="utf-8") + target_oid = git_commit(root, "accepted target") + + _, generated_candidate = binding_source(language, candidate_delta) + comment = {"rust": "// candidate revision\n", "python": "# candidate revision\n", + "typescript": "// candidate revision\n"}[language] + source.write_text( + candidate_source if candidate_source is not None else generated_candidate + comment, + encoding="utf-8", + ) + candidate_oid = git_commit(root, "candidate", source_name) + request = request_json( + revision.contract.to_json(), + base_oid=target_oid, + candidate_oid=candidate_oid, + intent_sha256=revision.digest, + ) + return root, target_oid, request + + +def build_intent_repo( + tmp_path: Path, + *, + object_format: str = "sha1", + change_revision=None, + change_target=None, +) -> tuple[Path, str, dict, dict, str]: + root = tmp_path / "repo" + root.mkdir() + git(root, "init", "-q", f"--object-format={object_format}") + hashes = {} + for role in SEMANTIC_ROLES: + content = f'{{"role":"{role}"}}\n'.encode() + target = root / f"verification/semantics/{role}.json" + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(content) + hashes[role] = sha256_bytes(content) + dom = domain_json( + binding="example::choose", + inputs=("x", "y"), + observations=("allow", "deny", "other"), + codec_sha256=hashes["codec"], + observation_sha256=hashes["observation"], + environment_sha256=hashes["environment"], + ) + ctr = contract_json({"x": ["allow", "deny"]}, admissible=("x",), domain_raw=dom) + revision_raw = intent_revision_json( + ctr, + source="requirements.md#choice", + statement="Either allow or deny is legal.", + binding_sha256=hashes["binding"], + artifact_prefix="verification/semantics/", + ) + if change_revision: + change_revision(revision_raw) + revision = IntentRevision.from_json(revision_raw) + revision_path = f"verification/change-intents/{revision.digest}.v1.json" + write_json(root / revision_path, revision.to_json()) + write_json(root / POLICY_PATH, {"schema_version": 1, "accepted": [revision.digest]}) + (root / "candidate.rs").write_text("pub fn choose() -> bool { true }\n", encoding="utf-8") + if change_target: + change_target(root, revision_path, revision_raw) + target_oid = git_commit(root, "accept intent in target") + (root / "candidate.rs").write_text("pub fn choose() -> bool { false }\n", encoding="utf-8") + candidate_oid = git_commit(root, "change application source") + request = request_json( + deepcopy(revision_raw["contract"]), + base_oid=target_oid, + candidate_oid=candidate_oid, + intent_sha256=revision.digest, + ) + return root, target_oid, request, revision_raw, revision_path diff --git a/tests/change/test_certification.py b/tests/change/test_certification.py index 40bd112..420ad9c 100644 --- a/tests/change/test_certification.py +++ b/tests/change/test_certification.py @@ -4,9 +4,15 @@ import pytest +from tests.change._helpers import ( + contract_json, + domain_json, + parse_finite_contract, + request_json, +) from vkit.change.certification import ( - ComparisonKind, ChangeCertificationRequest, + ComparisonKind, EntailmentKind, compare_contracts, intent_entails_claim, @@ -14,182 +20,68 @@ from vkit.core.schemas import SchemaValidationError -def domain(**changes): - value = { +def _domain(**changes): + return domain_json(**{ "binding": "ledger::reserve", - "inputs": ["empty", "available"], - "observations": ["rejected", "reserved", "unchanged"], - "codec_sha256": "a" * 64, - "observation_sha256": "b" * 64, - "environment_sha256": "c" * 64, - } - value.update(changes) - return value + "inputs": ("empty", "available"), + "observations": ("rejected", "reserved", "unchanged"), + **changes, + }) -def contract(admissible=("available",), outputs=None, domain_raw=None): +def _contract(admissible=("available",), outputs=None, domain_raw=None): if outputs is None: outputs = {"available": ["reserved", "unchanged"]} - return { - "domain": domain_raw or domain(), - "admissible_inputs": list(admissible), - "allowed_outputs": [ - {"input": token, "outputs": values} for token, values in outputs.items() - ], - } - - -def request(contract_raw=None): - return { - "schema_version": 1, - "base_oid": "1" * 40, - "candidate_oid": "2" * 40, - "intent_sha256": "d" * 64, - "claim": { - "kind": "finite_contract", - "contract": contract_raw or contract(), - }, - } - - -def parse_contract(raw): - return ChangeCertificationRequest.from_json(request(raw)).claim - - -def test_refinement_reports_strengthening_with_separate_pre_and_post_results(): - old = parse_contract(contract(outputs={"available": ["reserved", "unchanged"]})) - new = parse_contract(contract(outputs={"available": ["reserved"]})) + return contract_json( + outputs, + admissible=admissible, + domain_raw=domain_raw or _domain(), + ) - result = compare_contracts(old, new) - assert result.kind is ComparisonKind.STRENGTHENS - assert result.old_to_new.precondition_included is True - assert result.old_to_new.postcondition_included is True - assert result.new_to_old.precondition_included is True - assert result.new_to_old.postcondition_included is False - assert result.new_to_old.output_witness == ("available", "unchanged") +def _request(contract_raw=None): + return request_json(contract_raw or _contract()) -def test_refinement_reports_weakening_and_equivalence(): - narrow = parse_contract(contract(outputs={"available": ["reserved"]})) - broad = parse_contract(contract(outputs={"available": ["reserved", "unchanged"]})) - reordered = parse_contract(contract(outputs={"available": ["unchanged", "reserved"]})) +def test_compare_contracts_smoke(): + narrow = parse_finite_contract(_contract(outputs={"available": ["reserved"]})) + broad = parse_finite_contract(_contract(outputs={"available": ["reserved", "unchanged"]})) + reordered = parse_finite_contract(_contract(outputs={"available": ["unchanged", "reserved"]})) + strengthens = compare_contracts(broad, narrow) + assert strengthens.kind is ComparisonKind.STRENGTHENS + assert strengthens.old_to_new.precondition_included is True + assert strengthens.old_to_new.postcondition_included is True + assert strengthens.new_to_old.postcondition_included is False + assert strengthens.new_to_old.output_witness == ("available", "unchanged") assert compare_contracts(narrow, broad).kind is ComparisonKind.WEAKENS - assert compare_contracts(broad, narrow).kind is ComparisonKind.STRENGTHENS assert compare_contracts(broad, reordered).kind is ComparisonKind.EQUIVALENT - assert narrow.domain.digest == parse_contract( - contract(domain_raw=domain(inputs=["available", "empty"], - observations=["unchanged", "reserved", "rejected"])) + assert narrow.domain.digest == parse_finite_contract( + _contract(domain_raw=_domain(inputs=["available", "empty"], + observations=["unchanged", "reserved", "rejected"])) ).domain.digest + assert compare_contracts( + broad, parse_finite_contract(_contract(domain_raw=_domain(codec_sha256="e" * 64))) + ).kind is ComparisonKind.UNKNOWN -def test_refinement_reports_incomparable_pre_and_post_failures(): - old = parse_contract(contract(admissible=("available",))) - new = parse_contract(contract( - admissible=("empty",), - outputs={"empty": ["rejected"]}, - )) - - result = compare_contracts(old, new) - - assert result.kind is ComparisonKind.INCOMPARABLE - assert result.old_to_new.precondition_included is False - assert result.old_to_new.input_witness == "available" - assert result.new_to_old.precondition_included is False - assert result.new_to_old.input_witness == "empty" - - -def test_empty_legal_domain_is_vacuous(): - empty = parse_contract(contract(admissible=(), outputs={})) - inhabited = parse_contract(contract()) - - result = compare_contracts(empty, inhabited) - - assert result.kind is ComparisonKind.VACUOUS - assert result.old_to_new.precondition_included is True - assert result.new_to_old.precondition_included is False - - -@pytest.mark.parametrize("field,value", [ - ("codec_sha256", "e" * 64), - ("observation_sha256", "e" * 64), - ("environment_sha256", "e" * 64), - ("binding", "ledger::release"), - ("observations", ["rejected", "reserved", "unchanged", "extra"]), -]) -def test_changed_domain_semantics_return_unknown(field, value): - old = parse_contract(contract()) - changed = domain(**{field: value}) - new = parse_contract(contract(domain_raw=changed)) - - result = compare_contracts(old, new) - - assert result.kind is ComparisonKind.UNKNOWN - assert result.old_to_new is None - assert result.new_to_old is None - - -def test_intent_entailment_rejects_a_claim_that_excludes_a_legal_output(): - intent = parse_contract(contract(outputs={"available": ["reserved", "unchanged"]})) - overconstrained_claim = parse_contract(contract(outputs={"available": ["reserved"]})) - - result = intent_entails_claim(intent, overconstrained_claim) - - assert result.kind is EntailmentKind.NOT_ENTAILED - assert result.inputs_included is True - assert result.outputs_included is False - assert result.output_witness == ("available", "unchanged") - - -def test_intent_entailment_fails_when_claim_excludes_an_input_with_same_outputs(): - intent = parse_contract(contract(admissible=("available", "empty"), outputs={ - "available": ["reserved"], - "empty": ["rejected"], - })) - claim = parse_contract(contract(outputs={"available": ["reserved"]})) - - result = intent_entails_claim(intent, claim) - - assert result.kind is EntailmentKind.NOT_ENTAILED - assert result.inputs_included is False - assert result.outputs_included is True - assert result.input_witness == "empty" - - -def test_intent_entailment_accepts_claim_with_extra_disallowed_outputs(): - intent = parse_contract(contract(outputs={"available": ["reserved"]})) - broader_claim = parse_contract(contract(outputs={ - "available": ["reserved", "unchanged"], - })) - - result = intent_entails_claim(intent, broader_claim) - - assert result.kind is EntailmentKind.ENTAILED - assert result.inputs_included is True - assert result.outputs_included is True - - -def test_intent_entailment_is_unknown_on_domain_mismatch(): - intent = parse_contract(contract()) - claim = parse_contract(contract(domain_raw=domain(codec_sha256="e" * 64))) - - result = intent_entails_claim(intent, claim) - - assert result.kind is EntailmentKind.UNKNOWN - assert result.inputs_included is None - assert result.outputs_included is None - - -def test_empty_intent_entailment_is_vacuous(): - intent = parse_contract(contract(admissible=(), outputs={})) - claim = parse_contract(contract()) +def test_intent_entails_claim_smoke(): + narrow = parse_finite_contract(_contract(outputs={"available": ["reserved"]})) + broad = parse_finite_contract(_contract(outputs={"available": ["reserved", "unchanged"]})) - assert intent_entails_claim(intent, claim).kind is EntailmentKind.VACUOUS + assert intent_entails_claim(narrow, broad).kind is EntailmentKind.ENTAILED + rejected = intent_entails_claim(broad, narrow) + assert rejected.kind is EntailmentKind.NOT_ENTAILED + assert rejected.inputs_included is True + assert rejected.outputs_included is False + assert rejected.output_witness == ("available", "unchanged") + assert intent_entails_claim( + broad, parse_finite_contract(_contract(domain_raw=_domain(codec_sha256="e" * 64))) + ).kind is EntailmentKind.UNKNOWN def test_change_request_parser_keeps_claimed_intent_digest_untrusted(): - parsed = ChangeCertificationRequest.from_json(request()) + parsed = ChangeCertificationRequest.from_json(_request()) assert parsed.base_oid == "1" * 40 assert parsed.candidate_oid == "2" * 40 @@ -198,7 +90,7 @@ def test_change_request_parser_keeps_claimed_intent_digest_untrusted(): def test_parser_rejects_incomplete_output_rows(): - raw = request(contract_raw=contract(outputs={})) + raw = _request(contract_raw=_contract(outputs={})) with pytest.raises(ValueError, match="exactly one row"): ChangeCertificationRequest.from_json(raw) @@ -206,7 +98,7 @@ def test_parser_rejects_incomplete_output_rows(): @pytest.mark.parametrize("kind", ["verus_source", "expression", "unknown"]) def test_parser_rejects_unsupported_claim_discriminants(kind): - raw = request() + raw = _request() raw["claim"]["kind"] = kind with pytest.raises(SchemaValidationError): @@ -218,7 +110,7 @@ def test_parser_rejects_unsupported_claim_discriminants(kind): ("candidate_oid", "a" * 39), ]) def test_parser_requires_full_git_object_identities(field, value): - raw = request() + raw = _request() raw[field] = value with pytest.raises(SchemaValidationError): @@ -226,7 +118,7 @@ def test_parser_requires_full_git_object_identities(field, value): def test_parser_rejects_mixed_git_object_formats(): - raw = request() + raw = _request() raw["candidate_oid"] = "2" * 64 with pytest.raises(ValueError, match="same object format"): @@ -239,7 +131,7 @@ def test_parser_rejects_mixed_git_object_formats(): ("candidate_oid", "2" * 64 + "\n"), ]) def test_parser_rejects_trailing_newline_in_fixed_length_identity(field, value): - raw = request() + raw = _request() raw[field] = value with pytest.raises(SchemaValidationError): @@ -247,14 +139,14 @@ def test_parser_rejects_trailing_newline_in_fixed_length_identity(field, value): def test_parser_rejects_output_tokens_outside_domain_universe(): - raw = request(contract_raw=contract(outputs={"available": ["not-a-token"]})) + raw = _request(contract_raw=_contract(outputs={"available": ["not-a-token"]})) with pytest.raises(ValueError, match="outside the domain"): ChangeCertificationRequest.from_json(raw) def test_parser_rejects_duplicate_rows_and_duplicate_tokens(): - raw = request() + raw = _request() raw["claim"]["contract"]["allowed_outputs"].append( deepcopy(raw["claim"]["contract"]["allowed_outputs"][0]) ) diff --git a/tests/change/test_change_analysis.py b/tests/change/test_change_analysis.py index 49546c7..e520a60 100644 --- a/tests/change/test_change_analysis.py +++ b/tests/change/test_change_analysis.py @@ -1,22 +1,26 @@ from __future__ import annotations +import copy import hashlib import json -import copy from pathlib import Path from types import SimpleNamespace import pytest from helpers import git -from tests.change.test_paired import _git_output, _json_bytes, _repository +from tests.change._helpers import ( + build_paired_repo as _repository, + git_commit as _commit, + json_bytes as _json_bytes, +) from vkit.change import analysis as change_analysis_module from vkit.change.analysis import run_change_analysis from vkit.change.certification import IntentRevision, assess_differences from vkit.change.intent import _prepare_change_request from vkit.core.inputs import canonical_digest -from vkit.runtime.paths import open_project from vkit.core.schemas import SchemaValidationError, validate +from vkit.runtime.paths import open_project def _policy(intent_sha256: str, outputs: tuple[str, ...] = ("1",)) -> dict: @@ -40,14 +44,13 @@ def _candidate_commit( ) -> str: git(root, "checkout", "--detach", base_oid) (root / "candidate.py").write_text(source, encoding="utf-8") - git(root, "add", "candidate.py") + paths = ["candidate.py"] if policy_bytes is not None and policy_path is not None: retained_policy = root / policy_path retained_policy.parent.mkdir(parents=True, exist_ok=True) retained_policy.write_bytes(policy_bytes) - git(root, "add", policy_path) - git(root, "commit", "-qm", "candidate for analysis") - return _git_output(root, "rev-parse", "HEAD") + paths.append(policy_path) + return _commit(root, "candidate for analysis", *paths) def _with_target_policy( @@ -63,9 +66,7 @@ def _with_target_policy( path = root / "verification/change-intents/differences" / f"{request['intent_sha256']}.v1.json" path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(_json_bytes(policy_raw)) - git(root, "add", str(path.relative_to(root))) - git(root, "commit", "-qm", "target protects finite differences") - policy_target = _git_output(root, "rev-parse", "HEAD") + policy_target = _commit(root, "target protects finite differences", str(path.relative_to(root))) candidate = _candidate_commit( root, policy_target, candidate_source, policy_bytes=candidate_policy_bytes ) @@ -96,18 +97,16 @@ def _run( semantic_changes=semantic_changes, ) if policy is not None: - policy_target, request = _with_target_policy( + target_oid, request = _with_target_policy( root, target_oid, request, _policy(request["intent_sha256"], policy), candidate_source=candidate_source, ) - target_oid = policy_target else: - candidate = _candidate_commit(root, target_oid, candidate_source) request = dict(request) - request["candidate_oid"] = candidate + request["candidate_oid"] = _candidate_commit(root, target_oid, candidate_source) if claim_outputs is not None: request = json.loads(json.dumps(request)) request["claim"]["contract"]["allowed_outputs"] = [ @@ -146,9 +145,10 @@ def _weaker_claim_repository(tmp_path): raw_path = root / "verification/change-intents" / f"{revision.digest}.v1.json" raw_path.write_bytes(_json_bytes(revision.to_json())) accepted_path.write_bytes(_json_bytes({"schema_version": 1, "accepted": [revision.digest]})) - git(root, "add", str(raw_path.relative_to(root)), str(accepted_path.relative_to(root))) - git(root, "commit", "-qm", "target narrows admissible intent inputs") - trusted_target = _git_output(root, "rev-parse", "HEAD") + trusted_target = _commit( + root, "target narrows admissible intent inputs", + str(raw_path.relative_to(root)), str(accepted_path.relative_to(root)), + ) candidate = _candidate_commit(root, trusted_target, "def convert(value):\n return value\n") request["base_oid"] = trusted_target request["candidate_oid"] = candidate @@ -217,30 +217,65 @@ def test_weaker_claim_flags_do_not_hide_standing_intent_violation(tmp_path): assert result.assessment.findings[0].reason == "candidate violates standing target intent" -def test_selected_subset_and_timeout_remain_unknown(tmp_path): - _, _, _, partial = _run( - tmp_path / "partial", - candidate_source="def convert(value):\n return value\n", - input_tokens=("1",), - repetitions=1, - ) - assert partial.assessment.status == "unknown" - assert partial.assessment.missing_inputs == ("0",) - - _, _, _, timed_out = _run( - tmp_path / "timeout", - candidate_source=( - "import time\n" - "def convert(value):\n" - " time.sleep(0.1)\n" - " return value\n" +_UNKNOWN_RUN_CASES = [ + pytest.param( + {"candidate_source": "def convert(value):\n return value\n", "input_tokens": ("1",), "repetitions": 1}, + lambda r: r.assessment.missing_inputs == ("0",), + id="partial_subset", + ), + pytest.param( + { + "candidate_source": "import time\ndef convert(value):\n time.sleep(0.1)\n return value\n", + "input_tokens": ("0",), + "repetitions": 1, + "timeout_seconds": 0.001, + }, + lambda r: r.paired_execution.status in {"unknown", "infrastructure_failure"}, + id="timeout", + ), + pytest.param( + { + "candidate_source": ( + "import os\ndef convert(value):\n os.write(1, b'2\\n')\n" + " raise RuntimeError('after direct stdout write')\n" + ), + "input_tokens": ("1",), + "repetitions": 1, + }, + lambda r: r.paired_execution.status == "infrastructure_failure" and any( + f.input == "1" and f.kind == "unknown" and f.reason == "incomplete_output" + for f in r.assessment.findings ), - input_tokens=("0",), - repetitions=1, - timeout_seconds=0.001, - ) - assert timed_out.paired_execution.status in {"unknown", "infrastructure_failure"} - assert timed_out.assessment.status == "unknown" + id="failed_stdout_alone", + ), + pytest.param( + {"candidate_source": "def convert(value):\n return True\n", "input_tokens": ("0",), "repetitions": 1}, + lambda r: r.paired_execution.status == "infrastructure_failure" and r.report["status"] == "unknown", + id="infrastructure_failure", + ), + pytest.param( + { + "candidate_source": "def convert(value):\n return value\n", + "input_tokens": ("0",), + "repetitions": 1, + "semantic_changes": {"codec": {"schema_version": 1, "kind": "unsupported_codec"}}, + }, + lambda r: ( + r.paired_execution.status == "unknown" + and r.paired_execution.binding is None + and r.report["status"] == "unknown" + ), + id="unsupported_semantic", + ), +] + + +@pytest.mark.parametrize("run_kwargs,extra_check", _UNKNOWN_RUN_CASES) +def test_analysis_error_and_incomplete_statuses_remain_unknown(tmp_path, run_kwargs, extra_check): + _, _, _, result = _run(tmp_path, **run_kwargs) + + assert result.assessment.status == "unknown" + assert extra_check(result) def test_default_selection_uses_accepted_intent_domain_and_explicit_extra_fails_early(tmp_path): @@ -316,29 +351,6 @@ def test_failed_process_stdout_does_not_erase_earlier_known_violation(tmp_path): assert failed_output["stdout"] is not None -def test_failed_process_stdout_alone_remains_unknown(tmp_path): - _, _, _, result = _run( - tmp_path, - candidate_source=( - "import os\n" - "def convert(value):\n" - " os.write(1, b'2\\n')\n" - " raise RuntimeError('after direct stdout write')\n" - ), - outputs={"0": ["0", "1"], "1": ["1", "2"]}, - input_tokens=("1",), - repetitions=1, - ) - - assert result.paired_execution.status == "infrastructure_failure" - assert result.assessment.status == "unknown" - assert any( - finding.input == "1" and finding.kind == "unknown" - and finding.reason == "incomplete_output" - for finding in result.assessment.findings - ) - - @pytest.mark.parametrize("drift", ["deleted", "newline"]) def test_candidate_must_preserve_target_policy_bytes(tmp_path, drift): root, target_oid, request = _repository( @@ -352,10 +364,7 @@ def test_candidate_must_preserve_target_policy_bytes(tmp_path, drift): path.parent.mkdir(parents=True, exist_ok=True) raw = _json_bytes(target_policy) path.write_bytes(raw) - git(root, "add", str(path.relative_to(root))) - git(root, "commit", "-qm", "target policy") - target_oid = _git_output(root, "rev-parse", "HEAD") - candidate_source = "def convert(value):\n return value\n" + target_oid = _commit(root, "target policy", str(path.relative_to(root))) git(root, "checkout", "--detach", target_oid) if drift == "deleted": path.unlink() @@ -363,11 +372,9 @@ def test_candidate_must_preserve_target_policy_bytes(tmp_path, drift): else: path.write_bytes(raw + b"\n") git(root, "add", str(path.relative_to(root))) - (root / "candidate.py").write_text(candidate_source, encoding="utf-8") - git(root, "add", "candidate.py") - git(root, "commit", "-qm", "candidate drifts from target policy") + (root / "candidate.py").write_text("def convert(value):\n return value\n", encoding="utf-8") request["base_oid"] = target_oid - request["candidate_oid"] = _git_output(root, "rev-parse", "HEAD") + request["candidate_oid"] = _commit(root, "candidate drifts from target policy", "candidate.py") with pytest.raises(ValueError, match="candidate difference policy differs"): run_change_analysis( @@ -385,14 +392,13 @@ def test_candidate_cannot_add_policy_when_target_uses_default(tmp_path): outputs={"0": ["0", "1"], "1": ["1", "2"]}, ) added = _json_bytes(_policy(request["intent_sha256"])) - candidate = _candidate_commit( + request["candidate_oid"] = _candidate_commit( root, request["candidate_oid"], "def convert(value):\n return 1\n", added, f"verification/change-intents/differences/{request['intent_sha256']}.v1.json", ) - request["candidate_oid"] = candidate with pytest.raises(ValueError, match="candidate adds a difference policy"): run_change_analysis( @@ -405,10 +411,7 @@ def test_candidate_cannot_add_policy_when_target_uses_default(tmp_path): def test_partial_selected_coverage_is_not_filled_by_shrink_sample(tmp_path): _, _, _, result = _run( tmp_path, - candidate_source=( - "def convert(value):\n" - " return 3 if value == 1 else value\n" - ), + candidate_source="def convert(value):\n return 3 if value == 1 else value\n", outputs={"0": ["0"], "1": ["1", "2"]}, input_tokens=("1",), repetitions=2, @@ -423,35 +426,6 @@ def test_partial_selected_coverage_is_not_filled_by_shrink_sample(tmp_path): assert result.assessment.missing_inputs == ("0",) -def test_infrastructure_failure_blocks_conformance(tmp_path): - _, _, _, result = _run( - tmp_path, - candidate_source="def convert(value):\n return True\n", - outputs={"0": ["0", "1"], "1": ["1", "2"]}, - input_tokens=("0",), - repetitions=1, - ) - - assert result.paired_execution.status == "infrastructure_failure" - assert result.assessment.status == "unknown" - assert result.report["status"] == "unknown" - - -def test_unsupported_semantic_declaration_returns_unknown_analysis(tmp_path): - _, _, _, result = _run( - tmp_path, - candidate_source="def convert(value):\n return value\n", - input_tokens=("0",), - repetitions=1, - semantic_changes={"codec": {"schema_version": 1, "kind": "unsupported_codec"}}, - ) - - assert result.paired_execution.status == "unknown" - assert result.paired_execution.binding is None - assert result.assessment.status == "unknown" - assert result.report["status"] == "unknown" - - def test_analysis_schema_binds_status_and_policy_path(tmp_path): _, _, _, result = _run( tmp_path, @@ -463,19 +437,19 @@ def test_analysis_schema_binds_status_and_policy_path(tmp_path): mismatched_status = copy.deepcopy(result.report) mismatched_status["assessment"]["status"] = "unknown" with pytest.raises(SchemaValidationError): - validate("change analysis report", change_analysis_module._ANALYSIS_SCHEMA, - mismatched_status) + validate("change analysis report", change_analysis_module._ANALYSIS_SCHEMA, mismatched_status) escaped_policy_path = copy.deepcopy(result.report) escaped_policy_path["policy"]["path"] = "../../outside.json" with pytest.raises(SchemaValidationError): - validate("change analysis report", change_analysis_module._ANALYSIS_SCHEMA, - escaped_policy_path) + validate("change analysis report", change_analysis_module._ANALYSIS_SCHEMA, escaped_policy_path) -def test_report_import_ignores_claim_flags_and_checks_stdout_input_and_binding(tmp_path): +@pytest.fixture(scope="module") +def guarded_analysis_fixture(tmp_path_factory): + base_dir = tmp_path_factory.mktemp("guarded_analysis") root, target_oid, request, result = _run( - tmp_path, + base_dir, candidate_source="def convert(value):\n return 1 if value == 0 else value\n", policy=["1"], input_tokens=("0", "1"), @@ -483,13 +457,18 @@ def test_report_import_ignores_claim_flags_and_checks_stdout_input_and_binding(t bound, target, _ = _prepare_change_request( open_project(root), request, trusted_target_oid=target_oid ) - report_path = tmp_path / "analysis" / "paired-report.json" - report = json.loads(report_path.read_bytes()) + analysis_dir = base_dir / "analysis" + raw_report = (analysis_dir / "paired-report.json").read_bytes() + return analysis_dir, raw_report, bound, target, result + + +def test_report_import_ignores_forged_claim_flags(guarded_analysis_fixture): + analysis_dir, raw_report, bound, target, result = guarded_analysis_fixture + report = json.loads(raw_report) report["samples"][0]["candidate_within_contract"] = False - forged_flags = _json_bytes(report) observations = change_analysis_module._report_observations( - tmp_path / "analysis", - forged_flags, + analysis_dir, + _json_bytes(report), bound=bound, target=target, expected_binding=result.paired_execution.binding, @@ -500,105 +479,79 @@ def test_report_import_ignores_claim_flags_and_checks_stdout_input_and_binding(t bound.intent, result.policy, observations, repetitions=2 ).status == "observed_conformance" - swapped_identity = json.loads(report_path.read_bytes()) - swapped_identity["identities"]["runner"] = swapped_identity["identities"]["runtime"] - with pytest.raises(ValueError, match="runner identity differs"): - change_analysis_module._report_observations( - tmp_path / "analysis", - _json_bytes(swapped_identity), - bound=bound, - target=target, - expected_binding=result.paired_execution.binding, - expected_selected=("0", "1"), - repetitions=2, - ) - - wrong_binding = SimpleNamespace(to_json=lambda: {"forged": True}) - with pytest.raises((ValueError, SchemaValidationError)): - change_analysis_module._report_observations( - tmp_path / "analysis", - report_path.read_bytes(), - bound=bound, - target=target, - expected_binding=wrong_binding, - expected_selected=("0", "1"), - repetitions=2, - ) - sample = report["samples"][0] - sample["runs"][0]["base"]["value"] = 99 - forged_output = _json_bytes(report) - with pytest.raises(ValueError, match="differs from retained stdout"): - change_analysis_module._report_observations( - tmp_path / "analysis", - forged_output, - bound=bound, - target=target, - expected_binding=result.paired_execution.binding, - expected_selected=("0", "1"), - repetitions=2, - ) +def _mutate_wrong_live_binding(report, result): + valid_wrong = result.paired_execution.binding.to_json() + valid_wrong["runner_identity_sha256"] = "0" * 64 + valid_wrong["binding_sha256"] = canonical_digest( + {k: v for k, v in valid_wrong.items() if k != "binding_sha256"} + ) + report["binding"] = valid_wrong - sample["runs"][0]["base"]["value"] = 0 - forged_input = _json_bytes(report) - input_path = tmp_path / "analysis" / "inputs" / "0.u32le" - original_input = input_path.read_bytes() - input_path.write_bytes((1).to_bytes(4, "little")) - with pytest.raises(ValueError, match="retained artifacts changed"): - change_analysis_module._report_observations( - tmp_path / "analysis", - forged_input, - bound=bound, - target=target, - expected_binding=result.paired_execution.binding, - expected_selected=("0", "1"), - repetitions=2, - ) - input_path.write_bytes(original_input) - - valid_wrong_binding = result.paired_execution.binding.to_json() - valid_wrong_binding["runner_identity_sha256"] = "0" * 64 - valid_wrong_binding["binding_sha256"] = canonical_digest({ - key: value for key, value in valid_wrong_binding.items() - if key != "binding_sha256" - }) - report["binding"] = valid_wrong_binding - with pytest.raises(ValueError, match="live execution binding"): - change_analysis_module._report_observations( - tmp_path / "analysis", - _json_bytes(report), - bound=bound, - target=target, - expected_binding=result.paired_execution.binding, - expected_selected=("0", "1"), - repetitions=2, - ) - report["source"]["candidate_oid"] = "0" * 40 - with pytest.raises(ValueError, match="source identities"): - change_analysis_module._report_observations( - tmp_path / "analysis", - _json_bytes(report), - bound=bound, - target=target, - expected_binding=result.paired_execution.binding, - expected_selected=("0", "1"), - repetitions=2, - ) - extra_sample = json.loads(report_path.read_bytes()) - extra = copy.deepcopy(extra_sample["samples"][0]) +def _mutate_duplicate_sample(report, _result): + extra = copy.deepcopy(report["samples"][0]) extra["purpose"] = "shrink" - extra_sample["samples"].append(extra) - with pytest.raises(ValueError, match="repeats input"): - change_analysis_module._report_observations( - tmp_path / "analysis", - _json_bytes(extra_sample), - bound=bound, - target=target, - expected_binding=result.paired_execution.binding, - expected_selected=("0", "1"), - repetitions=2, - ) + report["samples"].append(extra) + + +_REPORT_TAMPER_CASES = [ + pytest.param( + lambda rep, _: rep["identities"].__setitem__("runner", rep["identities"]["runtime"]), + None, False, ValueError, "runner identity differs", id="swapped_runner_identity", + ), + pytest.param( + None, SimpleNamespace(to_json=lambda: {"forged": True}), False, + (ValueError, SchemaValidationError), None, id="wrong_expected_binding", + ), + pytest.param( + lambda rep, _: rep["samples"][0]["runs"][0]["base"].__setitem__("value", 99), + None, False, ValueError, "differs from retained stdout", id="forged_stdout_value", + ), + pytest.param( + None, None, True, ValueError, "retained artifacts changed", id="tampered_input_artifact", + ), + pytest.param( + _mutate_wrong_live_binding, None, False, ValueError, "live execution binding", + id="mismatched_live_binding", + ), + pytest.param( + lambda rep, _: rep["source"].__setitem__("candidate_oid", "0" * 40), + None, False, ValueError, "source identities", id="mismatched_source_oid", + ), + pytest.param( + _mutate_duplicate_sample, None, False, ValueError, "repeats input", + id="duplicate_input_sample", + ), +] + + +@pytest.mark.parametrize("mutate,override_binding,tamper_input,exc_type,match", _REPORT_TAMPER_CASES) +def test_report_import_rejects_tampering( + guarded_analysis_fixture, mutate, override_binding, tamper_input, exc_type, match +): + analysis_dir, raw_report, bound, target, result = guarded_analysis_fixture + report = json.loads(raw_report) + if mutate is not None: + mutate(report, result) + input_path = analysis_dir / "inputs" / "0.u32le" + original_input = input_path.read_bytes() if tamper_input else None + try: + if tamper_input: + input_path.write_bytes((1).to_bytes(4, "little")) + with pytest.raises(exc_type, match=match): + change_analysis_module._report_observations( + analysis_dir, + _json_bytes(report), + bound=bound, + target=target, + expected_binding=override_binding or result.paired_execution.binding, + expected_selected=("0", "1"), + repetitions=2, + ) + finally: + if original_input is not None: + input_path.write_bytes(original_input) def test_public_analysis_rejects_stale_retained_report(tmp_path, monkeypatch): @@ -608,23 +561,18 @@ def stale_report(*args, **kwargs): execution = original(*args, **kwargs) path = Path(kwargs["output_dir"]) / "paired-report.json" report = json.loads(path.read_bytes()) - extra = copy.deepcopy(report["samples"][0]) - extra["purpose"] = "shrink" - report["samples"].append(extra) + _mutate_duplicate_sample(report, None) path.write_bytes(_json_bytes(report)) return execution - monkeypatch.setattr( - change_analysis_module, "_run_prepared_paired_execution", stale_report - ) + monkeypatch.setattr(change_analysis_module, "_run_prepared_paired_execution", stale_report) root, target_oid, request = _repository( - tmp_path, - language="python", - candidate_delta=0, + tmp_path, language="python", candidate_delta=0, outputs={"0": ["0", "1"], "1": ["1", "2"]}, ) - candidate = _candidate_commit(root, request["candidate_oid"], "def convert(value):\n return value\n") - request["candidate_oid"] = candidate + request["candidate_oid"] = _candidate_commit( + root, request["candidate_oid"], "def convert(value):\n return value\n" + ) with pytest.raises(ValueError, match="differs from its live result"): run_change_analysis( @@ -637,9 +585,7 @@ def stale_report(*args, **kwargs): @pytest.mark.parametrize("artifact", ["paired-report.json", "change-analysis.json"]) def test_candidate_cannot_precreate_analysis_reports(tmp_path, artifact): root, target_oid, request = _repository( - tmp_path, - language="python", - candidate_delta=0, + tmp_path, language="python", candidate_delta=0, outputs={"0": ["0", "1"], "1": ["1", "2"]}, ) candidate_source = ( @@ -649,9 +595,7 @@ def test_candidate_cannot_precreate_analysis_reports(tmp_path, artifact): "def convert(value):\n" " return value\n" ) - request["candidate_oid"] = _candidate_commit( - root, request["candidate_oid"], candidate_source - ) + request["candidate_oid"] = _candidate_commit(root, request["candidate_oid"], candidate_source) with pytest.raises(FileExistsError): run_change_analysis( diff --git a/tests/change/test_change_corpus.py b/tests/change/test_change_corpus.py deleted file mode 100644 index 2492737..0000000 --- a/tests/change/test_change_corpus.py +++ /dev/null @@ -1,83 +0,0 @@ -from __future__ import annotations - -import hashlib -import json -import os -import shutil -import subprocess -import sys -from pathlib import Path - -import pytest -from helpers import NO_WINDOW, ROOT - - -MANIFEST = ROOT / "examples/change-certification/manifest.json" -RUNNER = ROOT / "formal/checks/check_change_corpus.py" - - -def run_corpus(output_dir: Path, manifest: Path | None = None, env: dict[str, str] | None = None): - command = [sys.executable, str(RUNNER), "--output-dir", str(output_dir), - "--timeout-seconds", "90"] - if manifest is not None: - command += ["--manifest", str(manifest)] - return subprocess.run(command, cwd=ROOT, capture_output=True, text=True, timeout=300, - env=env, **NO_WINDOW) - - -@pytest.mark.skipif(shutil.which("rustc") is None, reason="rustc is required for native fixture execution") -def test_runner_compiles_and_checks_the_frozen_runtime_observations(tmp_path: Path): - output = tmp_path / "run" - result = run_corpus(output) - assert result.returncode == 0, result.stdout + result.stderr - assert "PASS cases=12 runtime=8 policy_only=4 observations=19 native_tests=8 scope=finite_literal_rows" in result.stdout - assert result.stdout.count("POLICY-ONLY ") == 4 - report = json.loads((output / "report.json").read_text(encoding="utf-8")) - assert (report["status"], report["runtime_observation_count"], report["native_test_count"]) == ("PASS", 19, 8) - assert len(report["runtime_cases"]) == 8 - assert all(case["kind"] == "runtime" for case in report["runtime_cases"]) - assert [case["id"] for case in report["policy_only_cases"]] == ["SC-04", "PA-04", "RS-03", "RS-04"] - assert all(case["kind"] == "policy_only" for case in report["policy_only_cases"]) - assert report["finite_scope"].startswith("Finite literal Rust fixtures.") - provenance = report["provenance"] - assert provenance["manifest_sha256"] == hashlib.sha256(MANIFEST.read_bytes()).hexdigest() - assert provenance["rustc_version"].startswith("rustc ") - assert set(provenance["fixture_source_sha256"]) == set(provenance["native_output_logs"]) - for source, digest in provenance["fixture_source_sha256"].items(): - fixture = ROOT / "examples/change-certification/fixtures" / source - assert digest == hashlib.sha256(fixture.read_bytes()).hexdigest() - log = output / provenance["native_output_logs"][source] - assert "test result: ok." in log.read_text(encoding="utf-8") - - -@pytest.mark.skipif(shutil.which("rustc") is None, reason="rustc is required for native fixture execution") -def test_runner_rejects_an_invalidated_frozen_observation(tmp_path: Path): - manifest = json.loads(MANIFEST.read_text(encoding="utf-8")) - case = next(case for case in manifest["cases"] if case["id"] == "SC-03") - row = next(row for row in case["observations"] if row["input"] == "x=10") - row["after"] = "10" - altered_manifest = tmp_path / "manifest.json" - altered_manifest.write_text(json.dumps(manifest), encoding="utf-8") - - output = tmp_path / "run" - result = run_corpus(output, altered_manifest) - assert result.returncode == 1 - assert "observations differ for scalar.rs" in result.stderr - report = json.loads((output / "report.json").read_text(encoding="utf-8")) - assert report["status"] == "FAIL" - assert "missing=" in report["error"] - assert report["provenance"]["manifest_sha256"] == hashlib.sha256(altered_manifest.read_bytes()).hexdigest() - - -def test_runner_reports_missing_rustc_as_blocked(tmp_path: Path): - empty_path = tmp_path / "empty-path" - empty_path.mkdir() - environment = os.environ.copy() - environment["PATH"] = str(empty_path) - output = tmp_path / "run" - result = run_corpus(output, env=environment) - assert result.returncode == 2 - assert result.stdout == "BLOCKED: rustc is unavailable; native fixture evidence was not run.\n" - report = json.loads((output / "report.json").read_text(encoding="utf-8")) - assert report["status"] == "BLOCKED" - assert report["reason"] == "rustc is unavailable" diff --git a/tests/change/test_change_engines.py b/tests/change/test_change_engines.py deleted file mode 100644 index 754b7b1..0000000 --- a/tests/change/test_change_engines.py +++ /dev/null @@ -1,143 +0,0 @@ -from __future__ import annotations - -import hashlib -import importlib.util -import json -from pathlib import Path -import subprocess -import sys - -from helpers import NO_WINDOW, ROOT -SCRIPT = ROOT / "formal/checks/check_change_engines.py" -spec = importlib.util.spec_from_file_location("check_change_engines", SCRIPT) -assert spec and spec.loader -probe = importlib.util.module_from_spec(spec) -spec.loader.exec_module(probe) -classify_kani = probe.classify_kani -classify_playback = probe.classify_playback -classify_verus = probe.classify_verus -make_playback_wrapper = probe.make_playback_wrapper -regression_playback = probe.regression_playback -run_command = probe.run_command - -KANI_LOG_EXCERPTS = { - "refactor": (0, "VERIFICATION:- SUCCESSFUL\nComplete - 1 successfully verified harnesses, 0 failures, 1 total."), - "regression": (1, "VERIFICATION:- FAILED\nFailed Checks: assertion failed: scalar::cap_before(x) == scalar::cap_after(x)\n" - "Concrete playback unit test for `regression`:\n```\n" - "/// Test generated for harness `regression`\n/// Check for `assertion`: \"assertion failed: scalar::cap_before(x) == scalar::cap_after(x)\"\n\n" - "#[test]\nfn kani_concrete_playback_regression_2635896623606938374() {\n" - " let concrete_vals: Vec> = vec![\n // 10\n vec![10, 0, 0, 0],\n ];\n" - " kani::concrete_playback_run(concrete_vals, regression);\n}\n```"), - "exhausted": (1, "VERIFICATION:- FAILED\nFailed Checks: unwinding assertion loop 0\nexhausted.unwind.0"), - "undefined_behavior": (1, "VERIFICATION:- FAILED\nCheck for `safety_check`: \"Offset result and original pointer must point to the same allocation\"\n" - "Concrete playback unit test for `undefined_behavior`"), - "observation_mismatch": (1, "VERIFICATION:- FAILED\nFailed Checks: assertion failed: before == after"), -} -VERUS_LOG_EXCERPTS = { - "positive": (0, "verification results:: 4 verified, 0 errors"), - "negative": (1, "error: assertion failed\nverification results:: 3 verified, 1 errors"), -} -PLAYBACK_LOG_EXCERPT = """test kani_concrete_playback_regression_2635896623606938374 ... FAILED -test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 3 filtered out; finished in 0.02s -assertion `left == right` failed -left: 10 -right: 9 -""" - - -def run_probe(output_dir: Path, kani: Path, verus: Path): - return subprocess.run( - [sys.executable, str(SCRIPT), "--kani", str(kani), "--verus", str(verus), "--output-dir", str(output_dir)], - cwd=ROOT, capture_output=True, text=True, timeout=30, **NO_WINDOW, - ) - - -def test_recorded_engine_diagnostics_require_exit_codes_and_specific_markers(): - expected_kani = { - "refactor": "proof_success", - "regression": "seeded_semantic_failure", - "exhausted": "unwind_exhaustion", - "undefined_behavior": "ub_safety_failure", - "observation_mismatch": "observation_mismatch", - } - for name, (code, output) in KANI_LOG_EXCERPTS.items(): - assert classify_kani(name, code, output) == expected_kani[name] - assert classify_kani("refactor", None, "") == "timeout" - assert classify_kani("regression", 0, KANI_LOG_EXCERPTS["regression"][1]) == "infrastructure_failure" - assert classify_kani("regression", 1, "VERIFICATION:- FAILED") == "infrastructure_failure" - for name, (code, output) in VERUS_LOG_EXCERPTS.items(): - expected = "proof_success" if name == "positive" else "seeded_semantic_failure" - assert classify_verus(name, code, output) == expected - assert classify_verus("positive", None, "") == "timeout" - assert classify_verus("negative", 0, VERUS_LOG_EXCERPTS["negative"][1]) == "infrastructure_failure" - assert classify_playback("kani_concrete_playback_regression_2635896623606938374", 101, - PLAYBACK_LOG_EXCERPT) == "native_regression_playback" - assert classify_playback("kani_concrete_playback_regression_2635896623606938374", 0, - PLAYBACK_LOG_EXCERPT) == "infrastructure_failure" - assert classify_playback("kani_concrete_playback_regression_2635896623606938374", None, - "") == "timeout" - assert classify_playback("kani_concrete_playback_regression_2635896623606938374", 101, - PLAYBACK_LOG_EXCERPT.replace("test result:", "summary:")) == "infrastructure_failure" - assert classify_playback("kani_concrete_playback_regression_2635896623606938374", 101, - PLAYBACK_LOG_EXCERPT.replace("1 failed;", "0 failed;")) == "infrastructure_failure" - - -def test_regression_parser_accepts_only_the_recorded_ten_witness(): - test_name, test_source = regression_playback(KANI_LOG_EXCERPTS["regression"][1]) - assert test_name == "kani_concrete_playback_regression_2635896623606938374" - assert "vec![10, 0, 0, 0]" in test_source - - -def test_playback_wrapper_leaves_the_frozen_proof_snapshot_unchanged(tmp_path: Path): - source = ROOT / "examples/change-certification/proofs/experiment-kani.rs" - snapshot = tmp_path / "experiment-kani.rs" - snapshot.write_bytes(source.read_bytes()) - original = snapshot.read_bytes() - _, generated_test = regression_playback(KANI_LOG_EXCERPTS["regression"][1]) - playback = tmp_path / "playback.rs" - - digest = make_playback_wrapper(snapshot, playback, generated_test) - - assert snapshot.read_bytes() == original - assert playback.read_bytes().startswith(original + b"\n\n") - assert "kani_concrete_playback_regression_" in playback.read_text(encoding="utf-8") - assert digest == hashlib.sha256(playback.read_bytes()).hexdigest() - - -def test_missing_tools_are_blocked_without_download_or_engine_execution(tmp_path: Path): - output = tmp_path / "new-output" - missing_kani = tmp_path / "missing-kani" - missing_verus = tmp_path / "missing-verus" - result = run_probe(output, missing_kani, missing_verus) - assert result.returncode == 2 - assert "BLOCKED: missing executable(s): kani, verus" in result.stderr - report = json.loads((output / "report.json").read_text(encoding="utf-8")) - assert report["status"] == "BLOCKED" - assert report["runs"] == [] - assert list(path.name for path in output.iterdir()) == ["report.json"] - - -def test_nonempty_output_directory_is_refused_without_mutation(tmp_path: Path): - output = tmp_path / "existing-output" - output.mkdir() - marker = output / "keep.txt" - marker.write_text("existing result", encoding="utf-8") - result = run_probe(output, tmp_path / "missing-kani", tmp_path / "missing-verus") - assert result.returncode == 2 - assert "output path must be an empty directory" in result.stderr - assert marker.read_text(encoding="utf-8") == "existing result" - assert [path.name for path in output.iterdir()] == ["keep.txt"] - - -def test_command_timeout_uses_the_process_tree_runner(tmp_path: Path): - record, output = run_command( - "timeout-control", - [sys.executable, "-c", "import time; print('ready', flush=True); time.sleep(5)"], - tmp_path, - 0.3, - ) - assert record["classification"] == "timeout" - assert record["timed_out"] is True - assert record["returncode"] is None - assert "ready" in output - assert (tmp_path / record["stdout_log"]).read_text(encoding="utf-8").strip() == "ready" diff --git a/tests/change/test_change_regressions.py b/tests/change/test_change_regressions.py new file mode 100644 index 0000000..fd1995f --- /dev/null +++ b/tests/change/test_change_regressions.py @@ -0,0 +1,218 @@ +from __future__ import annotations + +import hashlib +import os +from copy import deepcopy +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from vkit.change import analysis, claim_acceptance, intent, paired, service +from vkit.change.certification import ChangeCertificationRequest, IntentRevision +from vkit.change.methods import ChangeMethodPlan, KaniMethod +from vkit.core.inputs import CapturedFile, CapturedSource +from vkit.rust.kani_toolchain import KaniToolchain + + +def _captured(commit: str, files: list[CapturedFile]) -> CapturedSource: + ordered = tuple(sorted(files, key=lambda item: item.path)) + return CapturedSource( + kind="git_commit", + commit=commit, + tree="b" * 40, + parents=(), + object_format="sha1", + files=ordered, + ) + + +def _file(path: str, content: bytes, mode: str = "100644") -> CapturedFile: + return CapturedFile( + path=path, + mode=mode, + blob_oid="c" * 40, + raw_sha256=hashlib.sha256(content).hexdigest(), + content=content, + ) + + +def test_intent_rejects_semantic_artifact_mode_change(): + artifacts = {} + base_files = [] + cand_files = [] + for role in ("binding", "codec", "observation", "environment"): + content = f'{{"role":"{role}"}}\n'.encode("utf-8") + path = f"verification/semantics/{role}.json" + artifacts[role] = {"path": path, "sha256": hashlib.sha256(content).hexdigest()} + base_files.append(_file(path, content, mode="100644")) + cand_files.append(_file(path, content, mode="100755" if role == "binding" else "100644")) + + revision_raw = { + "schema_version": 1, + "requirement": {"source": "req.md#1", "statement": "x -> allow"}, + "contract": { + "domain": { + "binding": "example::f", + "inputs": ["1"], + "observations": ["1"], + **{f"{role}_sha256": artifacts[role]["sha256"] for role in ("codec", "observation", "environment")}, + }, + "admissible_inputs": ["1"], + "allowed_outputs": [{"input": "1", "outputs": ["1"]}], + }, + "artifacts": artifacts, + } + revision = IntentRevision.from_json(revision_raw) + rev_path = f"verification/change-intents/{revision.digest}.v1.json" + rev_bytes = paired._json_bytes(revision.to_json()) + acc_bytes = paired._json_bytes({"schema_version": 1, "accepted": [revision.digest]}) + for container in (base_files, cand_files): + container.append(_file(rev_path, rev_bytes)) + container.append(_file("verification/change-intents/accepted.v1.json", acc_bytes)) + + base = _captured("1" * 40, base_files) + cand = _captured("2" * 40, cand_files) + request = ChangeCertificationRequest.from_json({ + "schema_version": 1, + "base_oid": "1" * 40, + "candidate_oid": "2" * 40, + "intent_sha256": revision.digest, + "claim": {"kind": "finite_contract", "contract": deepcopy(revision_raw["contract"])}, + }) + with pytest.raises(ValueError, match="candidate binding artifact differs"): + intent._bind_captured_policy(request, base, cand) + + +def test_paired_write_artifact_rejects_symlink_parent(tmp_path: Path): + if os.name == "nt": + pytest.skip("POSIX symlink test") + outside = tmp_path / "outside" + outside.mkdir() + root = tmp_path / "run" + root.mkdir() + (root / "linked").symlink_to(outside, target_is_directory=True) + with pytest.raises(ValueError, match="link"): + paired._write_artifact(root, "linked/out.txt", b"data", "text/plain") + assert not (outside / "out.txt").exists() + + +def test_paired_source_matches_skips_posix_mode_on_nt(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + f = tmp_path / "script.sh" + f.write_bytes(b"echo hi\n") + f.chmod(0o644) + src = _captured("1" * 40, [_file("script.sh", b"echo hi\n", mode="100755")]) + if os.name != "nt": + assert not paired._source_matches(src, tmp_path) + monkeypatch.setattr(paired.os, "name", "nt") + assert paired._source_matches(src, tmp_path) + + +def test_analysis_passes_intent_admissible_inputs_as_shrink_domain(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + seen: dict[str, object] = {} + + def fake_paired(*args, **kwargs): + seen["shrink_domain"] = kwargs.get("shrink_domain") + raise RuntimeError("stop-after-capture") + + monkeypatch.setattr(analysis, "_run_prepared_paired_execution", fake_paired) + monkeypatch.setattr( + analysis, "_policy_for_captures", + lambda *_a: (object(), {"default": True}, b"{}"), + ) + bound = SimpleNamespace( + intent=SimpleNamespace(contract=SimpleNamespace(admissible_inputs=("2", "4"))), + request=SimpleNamespace(claim=SimpleNamespace(admissible_inputs=("1", "2", "3", "4"))), + ) + with pytest.raises(RuntimeError, match="stop-after-capture"): + analysis._run_prepared_change_analysis( + bound, _captured("1" * 40, []), _captured("2" * 40, []), + output_dir=tmp_path / "out", + input_tokens=("4",), + ) + assert seen["shrink_domain"] == ("2", "4") + + +def test_claim_acceptance_rejects_dangling_cancel_link_and_symlink_change_output(tmp_path: Path): + if os.name == "nt": + pytest.skip("POSIX symlink test") + base = _captured("1" * 40, []) + cand = _captured("2" * 40, []) + record = { + "state": "done", + "verification": { + "change_certification": { + "status": "model_verified", + "stopped": None, + "delegated_claim": {"status": "accepted"}, + } + }, + } + (tmp_path / "change-output").mkdir() + (tmp_path / "cancel").symlink_to(tmp_path / "nonexistent-target") + with pytest.raises(ValueError, match="cancelled, incomplete or stale"): + claim_acceptance.validate_claim_acceptance(record, tmp_path, base, cand) + + other = tmp_path / "dir2" + other.mkdir() + (other / "change-output").symlink_to(tmp_path / "outside-target") + record_unpub = {"state": "done", "verification": {"change_certification": {"delegated_claim": {"status": "unknown"}}}} + with pytest.raises(ValueError, match="unpublished claim acceptance"): + claim_acceptance.validate_claim_acceptance(record_unpub, other, base, cand) + + +def test_service_preserves_refuted_delegated_claim_when_cancelled_late(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + cancel_state = {"flag": False} + bound = SimpleNamespace( + digest="a" * 64, + intent=SimpleNamespace(digest="b" * 64, requirement_source="req", requirement_statement="stmt"), + delegation=object(), + ) + base = SimpleNamespace(digest="c" * 64) + cand = SimpleNamespace(digest="d" * 64) + toolchain = KaniToolchain( + kani_root=tmp_path / "kani", + rustup_home=tmp_path / "rustup", + cargo_home=tmp_path / "cargo", + kani_manifest_sha256="1" * 64, + rust_manifest_sha256="2" * 64, + rustup_sha256="3" * 64, + ) + methods = ChangeMethodPlan(steps=(KaniMethod(toolchain=toolchain, timeout_seconds=10.0),)) + + def fake_prepare(_b, _base, _cand): + return object() + + def fake_run_kani(_prog, *, toolchain, output_dir: Path, timeout_seconds, should_cancel): + output_dir.mkdir(parents=True, exist_ok=True) + rp = output_dir / "report.json" + rp.write_bytes(b"{}") + return SimpleNamespace( + kind="verified", + reason="ok", + report_path=rp, + report_sha256=hashlib.sha256(b"{}").hexdigest(), + ) + + def fake_claim_program(_b, _base, _cand, *, purpose): + return SimpleNamespace(purpose=purpose) + + def fake_run_claim(_prog, *, toolchain, output_dir: Path, timeout_seconds, should_cancel): + cancel_state["flag"] = True + return SimpleNamespace(kind="proof_rejected", reason="claim_failed") + + import vkit.rust.kani_execution as kani_exec + import vkit.rust.rust_relational as rust_rel + + monkeypatch.setattr(service, "_prepare_captured_rust_relational", fake_prepare) + monkeypatch.setattr(service, "run_kani_relational", fake_run_kani) + monkeypatch.setattr(rust_rel, "prepare_rust_claim_program", fake_claim_program) + monkeypatch.setattr(kani_exec, "run_kani_claim", fake_run_claim) + + report = service.run_change_methods( + bound, base, cand, methods, output_dir=tmp_path / "out", + should_cancel=lambda: cancel_state["flag"], + ) + assert report["delegated_claim"]["status"] == "refuted" + assert report["status"] == "model_verified" + assert report["stopped"] is None diff --git a/tests/change/test_delegation.py b/tests/change/test_delegation.py index e2436d4..4464250 100644 --- a/tests/change/test_delegation.py +++ b/tests/change/test_delegation.py @@ -4,6 +4,12 @@ import pytest +from tests.change._helpers import ( + contract_json, + domain_json, + parse_finite_contract, + request_json, +) from vkit.change.certification import ( ChangeCertificationRequest, ComparisonKind, @@ -18,60 +24,29 @@ from vkit.core.schemas import SchemaValidationError, validate -def domain(**changes): - value = { - "binding": "ledger::reserve", - "inputs": ["x", "y"], - "observations": ["zero", "one", "two"], - "codec_sha256": "a" * 64, - "observation_sha256": "b" * 64, - "environment_sha256": "c" * 64, - } - value.update(changes) - return value - - -def contract(outputs, *, admissible=("x",), domain_raw=None): - return { - "domain": domain_raw or domain(), - "admissible_inputs": list(admissible), - "allowed_outputs": [ - {"input": token, "outputs": values} for token, values in outputs.items() - ], - } - - -def finite(raw): - request = { - "schema_version": 1, - "base_oid": "1" * 40, - "candidate_oid": "2" * 40, - "intent_sha256": "d" * 64, - "claim": {"kind": "finite_contract", "contract": raw}, - } - return ChangeCertificationRequest.from_json(request).claim +def _finite(outputs, *, admissible=("x",), domain_raw=None): + return parse_finite_contract( + contract_json(outputs, admissible=admissible, domain_raw=domain_raw) + ) -def intent(value): +def _intent(value): return IntentRevision("requirements.md#reserve", "Reserve within policy.", value, ()) -def basis_for(intent_value, baseline, assumptions): - return DelegationBasis(intent_value.digest, baseline, assumptions) - - -def accepted_case(): - accepted_intent = intent(finite(contract({"x": ["zero", "one"]}))) - baseline = finite(contract({"x": ["zero", "one", "two"]})) - assumptions = finite(contract({"x": ["zero"]})) - claim = finite(contract({"x": ["zero"]})) - basis = basis_for(accepted_intent, baseline, assumptions) +def _accepted_case(): + accepted_intent = _intent(_finite({"x": ["zero", "one"]})) + baseline = _finite({"x": ["zero", "one", "two"]}) + assumptions = _finite({"x": ["zero"]}) + claim = _finite({"x": ["zero"]}) + basis = DelegationBasis(accepted_intent.digest, baseline, assumptions) return accepted_intent, basis, claim, NearMiss("x", "two") def test_delegation_accepts_claim_entailed_by_target_assumptions_and_strict_over_baseline(): - accepted_intent, basis, claim, near_miss = accepted_case() + accepted_intent, basis, claim, near_miss = _accepted_case() + assert intent_entails_claim(accepted_intent.contract, claim).kind is EntailmentKind.NOT_ENTAILED result = check_delegation(accepted_intent, basis, claim, near_miss) assert result.basis is basis @@ -87,14 +62,16 @@ def test_delegation_accepts_claim_entailed_by_target_assumptions_and_strict_over def test_delegation_accepts_claim_when_intent_alone_already_entails_it(): - accepted_intent = intent(finite(contract({"x": ["zero"]}))) - baseline = finite(contract({"x": ["zero", "one"]})) - assumptions = finite(contract({"x": ["zero", "one"]})) - claim = finite(contract({"x": ["zero"]})) + accepted_intent = _intent(_finite({"x": ["zero"]})) + baseline = _finite({"x": ["zero", "one"]}) + assumptions = _finite({"x": ["zero", "one"]}) + claim = _finite({"x": ["zero"]}) result = check_delegation( - accepted_intent, basis_for(accepted_intent, baseline, assumptions), - claim, NearMiss("x", "one"), + accepted_intent, + DelegationBasis(accepted_intent.digest, baseline, assumptions), + claim, + NearMiss("x", "one"), ) assert result.strictness_witness == ("x", "one") @@ -102,110 +79,68 @@ def test_delegation_accepts_claim_when_intent_alone_already_entails_it(): assert compare_contracts(baseline, claim).kind is ComparisonKind.STRENGTHENS -def test_assumptions_can_narrow_intent_before_entailment_check(): - accepted_intent, basis, claim, near_miss = accepted_case() +def _case_equivalent_to_baseline(): + accepted_intent = _intent(_finite({"x": ["zero", "one"]})) + baseline = _finite({"x": ["zero", "one"]}) + return accepted_intent, DelegationBasis(accepted_intent.digest, baseline, baseline), baseline, NearMiss("x", "two") - assert intent_entails_claim(accepted_intent.contract, claim).kind is EntailmentKind.NOT_ENTAILED - assert check_delegation(accepted_intent, basis, claim, near_miss).claim == claim +def _case_excludes_legal_input(): + accepted_intent = _intent(_finite({"x": ["zero"], "y": ["zero"]}, admissible=("x", "y"))) + baseline = _finite({"x": ["zero"], "y": ["zero", "one"]}, admissible=("x", "y")) + assumptions = _finite({"x": ["zero"], "y": ["zero"]}, admissible=("x", "y")) + return accepted_intent, DelegationBasis(accepted_intent.digest, baseline, assumptions), _finite({"x": ["zero"]}), NearMiss("x", "one") -def test_delegation_rejects_a_claim_equivalent_to_the_baseline(): - accepted_intent = intent(finite(contract({"x": ["zero", "one"]}))) - baseline = finite(contract({"x": ["zero", "one"]})) - assumptions = finite(contract({"x": ["zero", "one"]})) - with pytest.raises(ValueError, match="strictly strengthen"): - check_delegation( - accepted_intent, basis_for(accepted_intent, baseline, assumptions), - baseline, NearMiss("x", "two"), - ) +def _case_empty_intersection(): + accepted_intent = _intent(_finite({"x": ["zero"]})) + baseline = _finite({"x": ["zero", "one"]}) + assumptions = _finite({"x": ["one"]}) + return accepted_intent, DelegationBasis(accepted_intent.digest, baseline, assumptions), _finite({"x": ["zero"]}), NearMiss("x", "one") -def test_delegation_rejects_claim_not_entailed_by_intent_and_assumptions(): - accepted_intent, basis, _, near_miss = accepted_case() - claim = finite(contract({"x": ["two"]})) +def _case_near_miss_not_in_baseline(): + accepted_intent = _intent(_finite({"x": ["zero"]})) + baseline = _finite({"x": ["zero", "one"]}) + assumptions = _finite({"x": ["zero"]}) + return accepted_intent, DelegationBasis(accepted_intent.digest, baseline, assumptions), _finite({"x": ["zero"]}), NearMiss("x", "two") - with pytest.raises(ValueError, match="do not entail claim"): - check_delegation(accepted_intent, basis, claim, near_miss) +def _with_override(*, basis_digest=None, claim=None, near_miss=None): + accepted_intent, basis, default_claim, default_nm = _accepted_case() + if basis_digest is not None: + basis = DelegationBasis(basis_digest, basis.baseline, basis.assumptions) + return accepted_intent, basis, claim or default_claim, near_miss or default_nm -def test_delegation_rejects_a_claim_that_excludes_a_legal_input(): - accepted_intent = intent(finite(contract( - {"x": ["zero"], "y": ["zero"]}, admissible=("x", "y") - ))) - baseline = finite(contract({"x": ["zero"], "y": ["zero", "one"]}, - admissible=("x", "y"))) - assumptions = finite(contract({"x": ["zero"], "y": ["zero"]}, - admissible=("x", "y"))) - claim = finite(contract({"x": ["zero"]})) - with pytest.raises(ValueError, match="same legal input set"): - check_delegation( - accepted_intent, basis_for(accepted_intent, baseline, assumptions), - claim, NearMiss("x", "one"), - ) +_REJECTION_CASES = [ + pytest.param(_case_equivalent_to_baseline, "strictly strengthen", id="equivalent_to_baseline"), + pytest.param(lambda: _with_override(claim=_finite({"x": ["two"]})), "do not entail claim", id="not_entailed"), + pytest.param(_case_excludes_legal_input, "same legal input set", id="excludes_legal_input"), + pytest.param( + lambda: _with_override(claim=_finite({"x": ["zero"]}, domain_raw=domain_json(codec_sha256="e" * 64))), + "different finite domains", id="different_domain", + ), + pytest.param(_case_empty_intersection, "empty output intersection", id="empty_intersection"), + pytest.param(lambda: _with_override(basis_digest="e" * 64), "different accepted intent", id="wrong_intent_digest"), + pytest.param(lambda: _with_override(near_miss=NearMiss("y", "two")), "input is not legal", id="near_miss_illegal_input"), + pytest.param(lambda: _with_override(near_miss=NearMiss("x", "unknown")), "outside the observation domain", id="near_miss_out_of_domain"), + pytest.param(lambda: _with_override(near_miss=NearMiss("x", "zero")), "allowed by the accepted intent", id="near_miss_in_intent_zero"), + pytest.param(lambda: _with_override(near_miss=NearMiss("x", "one")), "allowed by the accepted intent", id="near_miss_in_intent_one"), + pytest.param(_case_near_miss_not_in_baseline, "not allowed by the baseline", id="near_miss_not_in_baseline"), +] -def test_delegation_rejects_a_different_finite_domain(): - accepted_intent, basis, _, near_miss = accepted_case() - claim = finite(contract({"x": ["zero"]}, domain_raw=domain(codec_sha256="e" * 64))) - - with pytest.raises(ValueError, match="different finite domains"): - check_delegation(accepted_intent, basis, claim, near_miss) - - -def test_delegation_rejects_empty_intent_assumption_intersection(): - accepted_intent = intent(finite(contract({"x": ["zero"]}))) - baseline = finite(contract({"x": ["zero", "one"]})) - assumptions = finite(contract({"x": ["one"]})) - claim = finite(contract({"x": ["zero"]})) - - with pytest.raises(ValueError, match="empty output intersection"): - check_delegation( - accepted_intent, basis_for(accepted_intent, baseline, assumptions), - claim, NearMiss("x", "one"), - ) - - -def test_delegation_rejects_basis_bound_to_another_intent_digest(): - accepted_intent, basis, claim, near_miss = accepted_case() - wrong_basis = DelegationBasis("e" * 64, basis.baseline, basis.assumptions) - - with pytest.raises(ValueError, match="different accepted intent"): - check_delegation(accepted_intent, wrong_basis, claim, near_miss) - - -@pytest.mark.parametrize( - ("near_miss", "message"), - [ - (NearMiss("y", "two"), "input is not legal"), - (NearMiss("x", "unknown"), "outside the observation domain"), - (NearMiss("x", "zero"), "allowed by the accepted intent"), - (NearMiss("x", "one"), "allowed by the accepted intent"), - ], -) -def test_delegation_rejects_invalid_near_miss(near_miss, message): - accepted_intent, basis, claim, _ = accepted_case() +@pytest.mark.parametrize("build_case,message", _REJECTION_CASES) +def test_delegation_rejections(build_case, message): + accepted_intent, basis, claim, near_miss = build_case() with pytest.raises(ValueError, match=message): check_delegation(accepted_intent, basis, claim, near_miss) -def test_delegation_rejects_near_miss_output_not_allowed_by_baseline(): - accepted_intent = intent(finite(contract({"x": ["zero"]}))) - baseline = finite(contract({"x": ["zero", "one"]})) - assumptions = finite(contract({"x": ["zero"]})) - claim = finite(contract({"x": ["zero"]})) - - with pytest.raises(ValueError, match="not allowed by the baseline"): - check_delegation( - accepted_intent, basis_for(accepted_intent, baseline, assumptions), - claim, NearMiss("x", "two"), - ) - - def test_delegation_basis_schema_round_trip_is_canonical_and_closed(): - accepted_intent, basis, _, _ = accepted_case() + accepted_intent, basis, _, _ = _accepted_case() raw = basis.to_json() parsed = DelegationBasis.from_json(raw) @@ -220,14 +155,8 @@ def test_delegation_basis_schema_round_trip_is_canonical_and_closed(): def test_change_request_optional_delegation_round_trips_without_changing_legacy_identity(): - accepted_intent, basis, claim, near_miss = accepted_case() - raw = { - "schema_version": 1, - "base_oid": "1" * 40, - "candidate_oid": "2" * 40, - "intent_sha256": accepted_intent.digest, - "claim": {"kind": "finite_contract", "contract": claim.to_json()}, - } + accepted_intent, basis, claim, near_miss = _accepted_case() + raw = request_json(claim.to_json(), intent_sha256=accepted_intent.digest) legacy = ChangeCertificationRequest.from_json(raw) assert legacy.to_json() == raw diff --git a/tests/change/test_differences.py b/tests/change/test_differences.py index bf59e75..eeb97cb 100644 --- a/tests/change/test_differences.py +++ b/tests/change/test_differences.py @@ -4,10 +4,9 @@ import pytest +from tests.change._helpers import contract_json, domain_json, make_intent_revision from vkit.change.certification import ( DifferencePolicy, - InputDifference, - IntentRevision, PairedObservation, assess_differences, ) @@ -18,43 +17,17 @@ def _intent(*, admissible=("x", "y"), outputs=None, domain_inputs=None): if outputs is None: outputs = {token: ["good", "other"] for token in admissible} domain_inputs = domain_inputs or tuple(sorted(set(admissible) | {"extra"})) - domain = { - "binding": "example::convert", - "inputs": list(domain_inputs), - "observations": ["bad", "good", "other"], - "codec_sha256": "a" * 64, - "observation_sha256": "b" * 64, - "environment_sha256": "c" * 64, - } - contract = { - "domain": domain, - "admissible_inputs": list(admissible), - "allowed_outputs": [ - {"input": token, "outputs": values} - for token, values in outputs.items() - ], - } - raw = { - "schema_version": 1, - "requirement": { - "source": "requirements.md#convert", - "statement": "Return one of the listed values for each input.", - }, - "contract": contract, - "artifacts": { - "binding": {"path": "binding.json", "sha256": "d" * 64}, - "codec": {"path": "codec.json", "sha256": domain["codec_sha256"]}, - "observation": { - "path": "observation.json", - "sha256": domain["observation_sha256"], - }, - "environment": { - "path": "environment.json", - "sha256": domain["environment_sha256"], - }, - }, - } - return IntentRevision.from_json(raw) + dom = domain_json( + binding="example::convert", + inputs=domain_inputs, + observations=("bad", "good", "other"), + ) + ctr = contract_json(outputs, admissible=admissible, domain_raw=dom) + return make_intent_revision( + ctr, + source="requirements.md#convert", + statement="Return one of the listed values for each input.", + ) def _guard(guard_id, requirements): @@ -203,57 +176,6 @@ def test_compatible_overlapping_guards_intersect_their_requirements(): assert rejected.findings[0].reason == "candidate violates an overlapping guard requirement" -@pytest.mark.parametrize( - ("observation", "reason", "base_output", "candidate_output"), - [ - ( - PairedObservation("x", ("good", "good"), ("good", "other"), selected=False), - "unstable_candidate_observations", None, None, - ), - ( - PairedObservation("x", ("good", "good"), ("good", "good"), "timeout", False), - "timeout", None, None, - ), - ( - PairedObservation("x", ("good", "good"), ("unmodeled", "unmodeled"), selected=False), - "out_of_model_observation", "good", "unmodeled", - ), - ], -) -def test_inconclusive_nonselected_sample_is_unknown_without_losing_coverage( - observation, reason, base_output, candidate_output -): - intent = _intent(admissible=("x",)) - selected = PairedObservation("x", ("good", "good"), ("good", "good")) - - result = assess_differences( - intent, _policy(intent), (selected, observation), repetitions=2 - ) - - assert result.status == "unknown" - assert result.coverage_complete is True - assert result.findings == ( - InputDifference("x", "preserved", (), "good", "good", "base and candidate observations are equal"), - InputDifference("x", "unknown", (), base_output, candidate_output, reason), - ) - assert result.missing_inputs == () - - -def test_unknown_extra_input_does_not_expand_or_replace_coverage(): - intent = _intent(admissible=("x",)) - observations = ( - PairedObservation("x", ("good", "good"), ("good", "good")), - PairedObservation("extra", ("bad", "bad"), ("bad", "bad")), - ) - - result = assess_differences(intent, _policy(intent), observations, repetitions=2) - - assert result.status == "observed_conformance" - assert result.coverage_complete is True - assert [finding.input for finding in result.findings] == ["x"] - assert result.missing_inputs == () - - def test_assessment_serialization_marks_finite_observation_scope_and_no_authority(): intent = _intent(admissible=("x",)) result = assess_differences( diff --git a/tests/change/test_finite_decisions.py b/tests/change/test_finite_decisions.py index 5194df0..b44d533 100644 --- a/tests/change/test_finite_decisions.py +++ b/tests/change/test_finite_decisions.py @@ -27,7 +27,7 @@ def test_finite_decision_checker_exhausts_declared_space_and_rejects_mutants(): assert len(report["evaluator_sha256"]) == 64 assert len(report["reference_model_sha256"]) == 64 assert report["evaluator"] == "src/vkit/change/certification.py" - assert report["reference_model"] == "formal/models/certification/Differences.tla" + assert report["reference_model"] == "formal/dafny/VKitChange.dfy" assert report["expected_status_counts"] == report["observed_status_counts"] assert {key: value for key, value in report["observed_status_counts"].items() if key.startswith("aggregate:")} == { diff --git a/tests/change/test_intent_binding.py b/tests/change/test_intent_binding.py index eac2309..50310ac 100644 --- a/tests/change/test_intent_binding.py +++ b/tests/change/test_intent_binding.py @@ -1,83 +1,31 @@ from __future__ import annotations from copy import deepcopy -import hashlib -from pathlib import Path -import subprocess import pytest -from helpers import git, NO_WINDOW +from helpers import git +from tests.change._helpers import ( + POLICY_PATH as POLICY, + build_intent_repo, + git_commit as _commit, + git_output as _git_output, +) from vkit.change.certification import IntentRevision from vkit.change.intent import preflight_change_request -from vkit.runtime.paths import open_project, ProjectError from vkit.core.store import Store, write_json - - -POLICY = "verification/change-intents/accepted.v1.json" - - -def _git_output(root: Path, *args: str) -> str: - return subprocess.check_output( - ["git", "-c", "user.email=t@vkit", "-c", "user.name=t", *args], - cwd=root, text=True, **NO_WINDOW, - ).strip() - - -def _commit(root: Path, message: str) -> str: - git(root, "add", ".") - git(root, "commit", "-qm", message) - return _git_output(root, "rev-parse", "HEAD") +from vkit.runtime.paths import ProjectError, open_project @pytest.fixture def intent_repository(tmp_path): def build(*, object_format="sha1", change_revision=None, change_target=None): - root = tmp_path / "repo" - root.mkdir() - git(root, "init", "-q", f"--object-format={object_format}") - artifacts = {} - for role in ("binding", "codec", "observation", "environment"): - content = f'{{"role":"{role}"}}\n'.encode() - path = f"verification/semantics/{role}.json" - target = root / path - target.parent.mkdir(parents=True, exist_ok=True) - target.write_bytes(content) - artifacts[role] = {"path": path, "sha256": hashlib.sha256(content).hexdigest()} - revision_raw = { - "schema_version": 1, - "requirement": {"source": "requirements.md#choice", "statement": "Either allow or deny is legal."}, - "contract": { - "domain": { - "binding": "example::choose", - "inputs": ["x", "y"], - "observations": ["allow", "deny", "other"], - **{f"{role}_sha256": artifacts[role]["sha256"] - for role in ("codec", "observation", "environment")}, - }, - "admissible_inputs": ["x"], - "allowed_outputs": [{"input": "x", "outputs": ["allow", "deny"]}], - }, - "artifacts": artifacts, - } - if change_revision: - change_revision(revision_raw) - revision = IntentRevision.from_json(revision_raw) - revision_path = f"verification/change-intents/{revision.digest}.v1.json" - write_json(root / revision_path, revision.to_json()) - write_json(root / POLICY, {"schema_version": 1, "accepted": [revision.digest]}) - (root / "candidate.rs").write_text("pub fn choose() -> bool { true }\n") - if change_target: - change_target(root, revision_path, revision_raw) - target_oid = _commit(root, "accept intent in target") - (root / "candidate.rs").write_text("pub fn choose() -> bool { false }\n") - candidate_oid = _commit(root, "change application source") - request = { - "schema_version": 1, "base_oid": target_oid, "candidate_oid": candidate_oid, - "intent_sha256": revision.digest, - "claim": {"kind": "finite_contract", "contract": deepcopy(revision_raw["contract"])}, - } - return root, target_oid, request, revision_raw, revision_path + return build_intent_repo( + tmp_path, + object_format=object_format, + change_revision=change_revision, + change_target=change_target, + ) return build diff --git a/tests/change/test_intent_revision.py b/tests/change/test_intent_revision.py index 0ac8f25..a4bb465 100644 --- a/tests/change/test_intent_revision.py +++ b/tests/change/test_intent_revision.py @@ -2,97 +2,48 @@ import hashlib import json -import subprocess import pytest -from helpers import NO_WINDOW, git +from helpers import git +from tests.change._helpers import ( + SEMANTIC_ROLES, + build_intent_repo, + contract_json, + domain_json, + git_commit, + git_output, + intent_revision_json, + request_json, +) from vkit.change.certification import ChangeCertificationRequest, IntentRevision from vkit.change.intent import preflight_change_request -from vkit.runtime.paths import open_project from vkit.core.schemas import SchemaValidationError +from vkit.runtime.paths import open_project -def _revision(artifact_hashes): - return { - "schema_version": 1, - "requirement": { - "source": "requirements.md#choice", - "statement": "Either allow or deny is legal.", - }, - "contract": { - "domain": { - "binding": "example::choose", - "inputs": ["x", "y"], - "observations": ["allow", "deny", "other"], - "codec_sha256": artifact_hashes["codec"], - "observation_sha256": artifact_hashes["observation"], - "environment_sha256": artifact_hashes["environment"], - }, - "admissible_inputs": ["x"], - "allowed_outputs": [{"input": "x", "outputs": ["allow", "deny"]}], - }, - "artifacts": { - role: {"path": f"verification/semantics/{role}.json", - "sha256": artifact_hashes[role]} - for role in ("binding", "codec", "observation", "environment") - }, - } - - -def _repository(tmp_path, *, object_format="sha1"): - root = tmp_path / "repo" - root.mkdir() - git(root, "init", "-q", f"--object-format={object_format}") - artifact_hashes = {} - for role in ("binding", "codec", "observation", "environment"): - content = f'{{"role":"{role}"}}\n'.encode() - path = root / f"verification/semantics/{role}.json" - path.parent.mkdir(parents=True, exist_ok=True) - path.write_bytes(content) - artifact_hashes[role] = hashlib.sha256(content).hexdigest() - - raw = _revision(artifact_hashes) - intent = IntentRevision.from_json(raw) - revision_path = root / f"verification/change-intents/{intent.digest}.v1.json" - revision_path.parent.mkdir(parents=True, exist_ok=True) - revision_path.write_text(json.dumps(intent.to_json()), encoding="utf-8") - accepted = root / "verification/change-intents/accepted.v1.json" - accepted.write_text( - json.dumps({"schema_version": 1, "accepted": [intent.digest]}), - encoding="utf-8", +def _sample_revision() -> dict: + hashes = {role: hashlib.sha256(role.encode()).hexdigest() for role in SEMANTIC_ROLES} + dom = domain_json( + binding="example::choose", + inputs=("x", "y"), + observations=("allow", "deny", "other"), + codec_sha256=hashes["codec"], + observation_sha256=hashes["observation"], + environment_sha256=hashes["environment"], + ) + ctr = contract_json({"x": ["allow", "deny"]}, admissible=("x",), domain_raw=dom) + return intent_revision_json( + ctr, + source="requirements.md#choice", + statement="Either allow or deny is legal.", + binding_sha256=hashes["binding"], + artifact_prefix="verification/semantics/", ) - (root / "candidate.rs").write_text("pub fn choose() -> bool { true }\n") - git(root, "add", ".") - git(root, "commit", "-qm", "accept finite intent") - target_oid = git_output(root, "rev-parse", "HEAD") - (root / "candidate.rs").write_text("pub fn choose() -> bool { false }\n") - git(root, "add", "candidate.rs") - git(root, "commit", "-qm", "change candidate") - candidate_oid = git_output(root, "rev-parse", "HEAD") - request = { - "schema_version": 1, - "base_oid": target_oid, - "candidate_oid": candidate_oid, - "intent_sha256": intent.digest, - "claim": {"kind": "finite_contract", "contract": intent.contract.to_json()}, - } - return root, target_oid, candidate_oid, intent, raw, request - - -def git_output(root, *args): - return subprocess.check_output( - ["git", "-c", "user.email=t@vkit", "-c", "user.name=t", *args], - cwd=root, - text=True, - **NO_WINDOW, - ).strip() def test_intent_revision_round_trip_normalizes_contract_sets(): - hashes = {role: hashlib.sha256(role.encode()).hexdigest() - for role in ("binding", "codec", "observation", "environment")} - raw = _revision(hashes) + raw = _sample_revision() raw["contract"]["domain"]["inputs"].reverse() raw["contract"]["domain"]["observations"].reverse() @@ -106,9 +57,7 @@ def test_intent_revision_round_trip_normalizes_contract_sets(): @pytest.mark.parametrize("role", ["codec", "observation", "environment"]) def test_intent_revision_requires_domain_artifact_hash_coupling(role): - hashes = {name: hashlib.sha256(name.encode()).hexdigest() - for name in ("binding", "codec", "observation", "environment")} - raw = _revision(hashes) + raw = _sample_revision() raw["artifacts"][role]["sha256"] = "0" * 64 with pytest.raises(ValueError, match="artifact hashes"): @@ -116,9 +65,7 @@ def test_intent_revision_requires_domain_artifact_hash_coupling(role): def test_intent_revision_rejects_unknown_fields(): - hashes = {role: hashlib.sha256(role.encode()).hexdigest() - for role in ("binding", "codec", "observation", "environment")} - raw = _revision(hashes) + raw = _sample_revision() raw["accepted"] = True with pytest.raises(SchemaValidationError): @@ -126,16 +73,8 @@ def test_intent_revision_rejects_unknown_fields(): def test_change_request_json_projection_preserves_semantic_request(): - hashes = {role: hashlib.sha256(role.encode()).hexdigest() - for role in ("binding", "codec", "observation", "environment")} - intent = IntentRevision.from_json(_revision(hashes)) - raw = { - "schema_version": 1, - "base_oid": "1" * 40, - "candidate_oid": "2" * 40, - "intent_sha256": intent.digest, - "claim": {"kind": "finite_contract", "contract": intent.contract.to_json()}, - } + intent = IntentRevision.from_json(_sample_revision()) + raw = request_json(intent.contract.to_json(), intent_sha256=intent.digest) request = ChangeCertificationRequest.from_json(raw) @@ -145,11 +84,8 @@ def test_change_request_json_projection_preserves_semantic_request(): @pytest.mark.parametrize("record", ["accepted-list", "current-revision"]) @pytest.mark.parametrize("operation", ["edit", "delete"]) def test_preflight_rejects_candidate_intent_authority_drift(tmp_path, record, operation): - root, target_oid, _, intent, _, request = _repository(tmp_path) - directory = root / "verification/change-intents" - path = directory / ( - "accepted.v1.json" if record == "accepted-list" else f"{intent.digest}.v1.json" - ) + root, target_oid, request, _, revision_path = build_intent_repo(tmp_path) + path = root / ("verification/change-intents/accepted.v1.json" if record == "accepted-list" else revision_path) if operation == "delete": path.unlink() else: @@ -168,18 +104,16 @@ def test_preflight_rejects_candidate_intent_authority_drift(tmp_path, record, op def test_preflight_allows_unaccepted_intent_proposal_without_granting_authority(tmp_path): - root, target_oid, _, intent, raw, request = _repository(tmp_path) + root, target_oid, request, raw, _ = build_intent_repo(tmp_path) proposal_raw = json.loads(json.dumps(raw)) proposal_raw["requirement"]["statement"] = "Proposed replacement requirement." proposal = IntentRevision.from_json(proposal_raw) proposal_path = root / f"verification/change-intents/{proposal.digest}.v1.json" proposal_path.write_text(json.dumps(proposal.to_json()), encoding="utf-8") - git(root, "add", ".") - git(root, "commit", "-qm", "propose an unaccepted intent") - request["candidate_oid"] = git_output(root, "rev-parse", "HEAD") + request["candidate_oid"] = git_commit(root, "propose an unaccepted intent") bound = preflight_change_request(open_project(root), request, trusted_target_oid=target_oid) - assert bound.intent.digest == intent.digest + assert bound.intent.digest == request["intent_sha256"] assert bound.intent.digest != proposal.digest assert bound.to_json()["candidate_behavior_checked"] is False diff --git a/tests/change/test_paired.py b/tests/change/test_paired.py index 4ce7fb9..d12484a 100644 --- a/tests/change/test_paired.py +++ b/tests/change/test_paired.py @@ -1,79 +1,25 @@ from __future__ import annotations -import hashlib import json -import os -import shutil -import subprocess -import sys from pathlib import Path from types import SimpleNamespace import pytest from hypothesis import given, settings, strategies as st -from helpers import NO_WINDOW, git +from tests.change._helpers import ( + build_paired_repo as _repository, + git_output as _git_output, + json_bytes as _json_bytes, + sha256_bytes as _sha, +) from vkit.change import paired as paired_module -from vkit.change.certification import IntentRevision from vkit.change.paired import run_paired_execution +from vkit.change.paired_profiles import ProgramPlan from vkit.core.evidence import policy_identity -from vkit.change.paired_profiles import ProgramPlan, identify_environment from vkit.runtime.paths import open_project - -def _json_bytes(value: object) -> bytes: - return (json.dumps(value, sort_keys=True, separators=(",", ":")) + "\n").encode() - - -def _sha(raw: bytes) -> str: - return hashlib.sha256(raw).hexdigest() - - -def _git_output(root, *args: str) -> str: - result = subprocess.run( - ["git", "-c", "user.email=t@vkit", "-c", "user.name=t", *args], - cwd=root, - check=True, - capture_output=True, - text=True, - **NO_WINDOW, - ) - return result.stdout.strip() - - -def _tools(language: str): - if language == "python": - return None, Path(sys.executable).resolve() - if language == "rust": - raw = os.environ.get("VKIT_TEST_RUSTC") - if raw is None: - rustup = shutil.which("rustup") - if rustup is not None: - result = subprocess.run( - [rustup, "which", "rustc"], capture_output=True, text=True, - check=False, **NO_WINDOW, - ) - if result.returncode == 0: - raw = result.stdout.strip() - raw = raw or shutil.which("rustc") - if raw is None or not Path(raw).is_file(): - pytest.skip("Rust compiler is unavailable; set VKIT_TEST_RUSTC to its executable") - return Path(raw).resolve(), None - compiler = os.environ.get("VKIT_TEST_TSC") - runtime = shutil.which("node") - if compiler is None or not Path(compiler).is_file() or runtime is None: - pytest.skip("native TypeScript compiler or Node is unavailable; set VKIT_TEST_TSC") - return Path(compiler).resolve(), Path(runtime).resolve() - - -def _binding_source(language: str, delta: int) -> tuple[str, str]: - if language == "rust": - source = f"pub fn convert(value: u32) -> u32 {{ value + {delta} }}\n" - return "candidate.rs", source - if language == "typescript": - source = f"export function convert(value: number): number {{ return value + {delta}; }}\n" - return "candidate.ts", source - return "candidate.py", f"def convert(value):\n return value + {delta}\n" +__all__ = ["_git_output", "_json_bytes", "_repository"] def test_runner_identity_covers_policy_source_map_and_each_added_module( @@ -103,106 +49,6 @@ def test_runner_identity_covers_policy_source_map_and_each_added_module( assert first != second -def _repository( - tmp_path, *, language: str, candidate_delta: int, outputs: dict[str, list[str]], - semantic_changes: dict[str, object] | None = None, candidate_source: str | None = None, - wrong_tool_pin: bool = False, -): - root = tmp_path / "repo" - root.mkdir(parents=True) - git(root, "init", "-q") - - compiler, runtime = _tools(language) - measured = identify_environment(language, compiler=compiler, runtime=runtime) - environment = json.loads(json.dumps(measured)) - if wrong_tool_pin: - role = "runtime" if language == "python" else "compiler" - environment["tools"][role]["sha256"] = "0" * 64 - semantic = { - "binding": { - "schema_version": 1, - "kind": "u32_function", - "language": language, - "source": {"rust": "candidate.rs", "python": "candidate.py", - "typescript": "candidate.ts"}[language], - "symbol": "convert", - }, - "codec": {"schema_version": 1, "kind": "u32_le"}, - "observation": {"schema_version": 1, "kind": "u32_return"}, - "environment": environment, - } - if semantic_changes: - semantic.update(semantic_changes) - raw_artifacts = {role: _json_bytes(value) for role, value in semantic.items()} - hashes = {role: _sha(raw) for role, raw in raw_artifacts.items()} - revision_raw = { - "schema_version": 1, - "requirement": { - "source": "requirements.md#conversion", - "statement": "The conversion may return any listed value for each input.", - }, - "contract": { - "domain": { - "binding": "example::convert", - "inputs": ["0", "1"], - "observations": ["0", "1", "2", "3"], - "codec_sha256": hashes["codec"], - "observation_sha256": hashes["observation"], - "environment_sha256": hashes["environment"], - }, - "admissible_inputs": ["0", "1"], - "allowed_outputs": [ - {"input": token, "outputs": values} - for token, values in sorted(outputs.items()) - ], - }, - "artifacts": { - role: { - "path": f"verification/semantics/{role}.json", - "sha256": hashes[role], - } - for role in ("binding", "codec", "observation", "environment") - }, - } - revision = IntentRevision.from_json(revision_raw) - for role, content in raw_artifacts.items(): - path = root / f"verification/semantics/{role}.json" - path.parent.mkdir(parents=True, exist_ok=True) - path.write_bytes(content) - revision_path = root / f"verification/change-intents/{revision.digest}.v1.json" - revision_path.parent.mkdir(parents=True, exist_ok=True) - revision_path.write_bytes(_json_bytes(revision.to_json())) - (root / "verification/change-intents/accepted.v1.json").write_bytes( - _json_bytes({"schema_version": 1, "accepted": [revision.digest]}) - ) - source_name, base_source = _binding_source(language, 0) - source = root / source_name - source.write_text(base_source, encoding="utf-8") - git(root, "add", ".") - git(root, "commit", "-qm", "accepted target") - target_oid = _git_output(root, "rev-parse", "HEAD") - - _, generated_candidate = _binding_source(language, candidate_delta) - generated_candidate += { - "rust": "// candidate revision\n", - "python": "# candidate revision\n", - "typescript": "// candidate revision\n", - }[language] - source.write_text(candidate_source if candidate_source is not None else generated_candidate, - encoding="utf-8") - git(root, "add", source_name) - git(root, "commit", "-qm", "candidate") - candidate_oid = _git_output(root, "rev-parse", "HEAD") - request = { - "schema_version": 1, - "base_oid": target_oid, - "candidate_oid": candidate_oid, - "intent_sha256": revision.digest, - "claim": {"kind": "finite_contract", "contract": revision.contract.to_json()}, - } - return root, target_oid, request - - @pytest.mark.parametrize("language", ["rust", "python", "typescript"]) @pytest.mark.parametrize("delta,expected_status,expected_different", [ (0, "samples_within_contract", False), @@ -225,6 +71,7 @@ def test_paired_execution_runs_native_profiles_and_records_samples( input_tokens=("1",), repetitions=2, max_shrink_trials=0, + timeout_seconds=120.0 if language == "rust" else 30.0, ) assert result.status == expected_status, result.report["failures"] @@ -344,69 +191,10 @@ def _run_python_case(tmp_path, *, candidate_source=None, semantic_changes=None, ) -def test_paired_execution_retains_build_failure(tmp_path): - result = _run_python_case(tmp_path, candidate_source="def convert(value):\n return (\n") - - assert result.status == "infrastructure_failure" - assert result.report["builds"][-1]["state"] == "failed" - assert result.report["failures"][-1]["reason"] == "exit_code" - assert result.report["builds"][-1]["stderr"] is not None - - -def test_paired_execution_retains_malformed_stdout(tmp_path): - result = _run_python_case( - tmp_path, - candidate_source="import sys\nsys.stdout.write('noise\\n')\ndef convert(value):\n return value\n", - ) - - assert result.status == "infrastructure_failure" - assert result.report["failures"][-1]["reason"] == "malformed_output" - assert result.report["failures"][-1]["artifacts"][0]["path"].endswith("candidate-1-1.stdout") - - -def test_paired_execution_rejects_wrong_semantic_and_source_pins(tmp_path): - semantic = {"observation": {"schema_version": True, "kind": "u32_return"}} - wrong_semantic = _run_python_case(tmp_path / "semantic", semantic_changes=semantic) - assert wrong_semantic.status == "unknown" - assert wrong_semantic.report["failures"][-1]["reason"] == "unsupported_declaration" - - binding = { - "schema_version": 1, "kind": "u32_function", "language": "python", - "source": "missing.py", "symbol": "convert", - } - wrong_source = _run_python_case( - tmp_path / "source", semantic_changes={"binding": binding} - ) - assert wrong_source.status == "unknown" - assert wrong_source.report["failures"][-1]["reason"] == "unsupported_program" - - -def test_paired_execution_rejects_wrong_tool_pin(tmp_path): - result = _run_python_case(tmp_path, wrong_tool_pin=True) - - assert result.status == "infrastructure_failure" - assert result.report["failures"][-1]["reason"] == "tool_pin_mismatch" - - -def test_paired_execution_reports_timeout_and_cancellation_as_unknown(tmp_path): - infinite = "def convert(value):\n while True:\n pass\n" - timed_out = _run_python_case( - tmp_path / "timeout", candidate_source=infinite, timeout_seconds=0.25 - ) - assert timed_out.status == "unknown" - assert timed_out.report["failures"][-1]["reason"] == "timeout" - - cancelled = _run_python_case( - tmp_path / "cancelled", candidate_source=infinite, should_cancel=lambda: True - ) - assert cancelled.status == "unknown" - assert cancelled.report["failures"][-1]["reason"] == "cancelled" - - -def test_paired_execution_marks_unstable_repetitions_unknown(tmp_path): +def _unstable_source(tmp_path: Path) -> str: state_dir = tmp_path / "external-state" state_dir.mkdir() - source = ( + return ( "from pathlib import Path\n" f"state_dir = Path({str(state_dir)!r})\n" "state = state_dir / (Path(__file__).parents[1].name + '.txt')\n" @@ -415,11 +203,83 @@ def test_paired_execution_marks_unstable_repetitions_unknown(tmp_path): " state.write_text(str(count + 1))\n" " return count % 2\n" ) - result = _run_python_case(tmp_path, candidate_source=source) - assert result.status == "unknown" - assert result.report["failures"][-1]["reason"] == "unstable" - assert result.report["samples"][0]["stable"] is False + +_INFINITE_LOOP = "def convert(value):\n while True:\n pass\n" + +_FAILURE_MATRIX = [ + pytest.param( + lambda _: {"candidate_source": "def convert(value):\n return (\n"}, + "infrastructure_failure", + "exit_code", + lambda r: r.report["builds"][-1]["state"] == "failed" and r.report["builds"][-1]["stderr"] is not None, + id="build_failure", + ), + pytest.param( + lambda _: {"candidate_source": "import sys\nsys.stdout.write('noise\\n')\ndef convert(value):\n return value\n"}, + "infrastructure_failure", + "malformed_output", + lambda r: r.report["failures"][-1]["artifacts"][0]["path"].endswith("candidate-1-1.stdout"), + id="malformed_stdout", + ), + pytest.param( + lambda _: {"semantic_changes": {"observation": {"schema_version": True, "kind": "u32_return"}}}, + "unknown", + "unsupported_declaration", + None, + id="wrong_semantic_pin", + ), + pytest.param( + lambda _: {"semantic_changes": {"binding": { + "schema_version": 1, "kind": "u32_function", "language": "python", + "source": "missing.py", "symbol": "convert", + }}}, + "unknown", + "unsupported_program", + None, + id="wrong_source_pin", + ), + pytest.param( + lambda _: {"wrong_tool_pin": True}, + "infrastructure_failure", + "tool_pin_mismatch", + None, + id="wrong_tool_pin", + ), + pytest.param( + lambda _: {"candidate_source": _INFINITE_LOOP, "timeout_seconds": 0.25}, + "unknown", + "timeout", + None, + id="timeout", + ), + pytest.param( + lambda tmp: {"candidate_source": _unstable_source(tmp)}, + "unknown", + "unstable", + lambda r: r.report["samples"][0]["stable"] is False, + id="unstable_repetitions", + ), + pytest.param( + lambda _: {"candidate_source": _INFINITE_LOOP, "should_cancel": lambda: True}, + "unknown", + "cancelled", + lambda r: r.report["resource_usage"]["process_invocations"] == 0 and r.report["builds"][0]["state"] == "not_run", + id="cancellation_before_launch", + ), +] + + +@pytest.mark.parametrize("make_kwargs,expected_status,expected_reason,extra_check", _FAILURE_MATRIX) +def test_paired_execution_failure_matrix( + tmp_path, make_kwargs, expected_status, expected_reason, extra_check +): + result = _run_python_case(tmp_path, **make_kwargs(tmp_path)) + + assert result.status == expected_status + assert result.report["failures"][-1]["reason"] == expected_reason + if extra_check is not None: + assert extra_check(result) def test_paired_execution_process_budget_counts_builds_and_refuses_more(tmp_path, monkeypatch): @@ -496,58 +356,16 @@ def test_paired_python_reads_input_before_candidate_import(tmp_path): assert [run["candidate"]["value"] for run in sample["runs"]] == [1, 1] -def test_paired_execution_cancellation_stops_before_launching_processes(tmp_path): - result = _run_python_case(tmp_path, should_cancel=lambda: True) - - assert result.status == "unknown" - assert result.report["resource_usage"]["process_invocations"] == 0 - assert result.report["builds"][0]["state"] == "not_run" - assert result.report["failures"][-1]["reason"] == "cancelled" - - def test_paired_execution_shrinking_stops_at_globally_minimal_violation(tmp_path): + tokens = tuple(str(i) for i in range(6)) root, target_oid, request = _repository( tmp_path, language="python", candidate_delta=2, - outputs={"0": ["0"], "1": ["1"]}, - ) - # Expand admissible inputs to 0..5 where every input violates, select only "5", - # and cap shrink trials at 2 (less than 5 smaller candidates). - intent_path = root / f"verification/change-intents/{request['intent_sha256']}.v1.json" - intent_data = json.loads(intent_path.read_text(encoding="utf-8")) - tokens = [str(i) for i in range(6)] - observations = [str(i) for i in range(8)] - intent_data["contract"]["domain"]["inputs"] = tokens - intent_data["contract"]["domain"]["observations"] = observations - intent_data["contract"]["admissible_inputs"] = tokens - intent_data["contract"]["allowed_outputs"] = [{"input": t, "outputs": [t]} for t in tokens] - revision = IntentRevision.from_json({ - "schema_version": intent_data["schema_version"], - "requirement": intent_data["requirement"], - "contract": intent_data["contract"], - "artifacts": intent_data["artifacts"], - }) - new_intent_path = root / f"verification/change-intents/{revision.digest}.v1.json" - new_intent_path.write_bytes(_json_bytes(revision.to_json())) - (root / "verification/change-intents/accepted.v1.json").write_bytes( - _json_bytes({"schema_version": 1, "accepted": [revision.digest]}) + inputs=tokens, + observations=tuple(str(i) for i in range(8)), + outputs={t: [t] for t in tokens}, ) - git(root, "add", "verification/change-intents") - git(root, "commit", "-qm", "expand domain") - target_oid = _git_output(root, "rev-parse", "HEAD") - - (root / "candidate.py").write_text("def convert(value):\n return value + 2\n", encoding="utf-8") - git(root, "add", "candidate.py") - git(root, "commit", "-qm", "candidate violating all") - candidate_oid = _git_output(root, "rev-parse", "HEAD") - request = { - "schema_version": 1, - "base_oid": target_oid, - "candidate_oid": candidate_oid, - "intent_sha256": revision.digest, - "claim": {"kind": "finite_contract", "contract": revision.contract.to_json()}, - } result = run_paired_execution( open_project(root), @@ -570,50 +388,19 @@ def test_paired_execution_shrinking_stops_at_globally_minimal_violation(tmp_path def test_paired_execution_skips_shrinking_after_selected_failure(tmp_path): + tokens = ("0", "1", "2") root, target_oid, request = _repository( tmp_path, language="python", candidate_delta=2, - outputs={"0": ["0"], "1": ["1"]}, - ) - intent_path = root / f"verification/change-intents/{request['intent_sha256']}.v1.json" - intent_data = json.loads(intent_path.read_text(encoding="utf-8")) - tokens = ["0", "1", "2"] - observations = ["0", "1", "2", "3", "4"] - intent_data["contract"]["domain"]["inputs"] = tokens - intent_data["contract"]["domain"]["observations"] = observations - intent_data["contract"]["admissible_inputs"] = tokens - intent_data["contract"]["allowed_outputs"] = [{"input": t, "outputs": [t]} for t in tokens] - revision = IntentRevision.from_json({ - "schema_version": intent_data["schema_version"], - "requirement": intent_data["requirement"], - "contract": intent_data["contract"], - "artifacts": intent_data["artifacts"], - }) - (root / f"verification/change-intents/{revision.digest}.v1.json").write_bytes( - _json_bytes(revision.to_json()) - ) - (root / "verification/change-intents/accepted.v1.json").write_bytes( - _json_bytes({"schema_version": 1, "accepted": [revision.digest]}) + inputs=tokens, + observations=("0", "1", "2", "3", "4"), + outputs={t: [t] for t in tokens}, + candidate_source=( + "import sys\ndef convert(value):\n" + " if value == 2:\n sys.exit(2)\n return value + 2\n" + ), ) - git(root, "add", "verification/change-intents") - git(root, "commit", "-qm", "three-input domain") - target_oid = _git_output(root, "rev-parse", "HEAD") - - (root / "candidate.py").write_text( - "import sys\ndef convert(value):\n if value == 2:\n sys.exit(2)\n return value + 2\n", - encoding="utf-8", - ) - git(root, "add", "candidate.py") - git(root, "commit", "-qm", "violate 1 and fail 2") - candidate_oid = _git_output(root, "rev-parse", "HEAD") - request = { - "schema_version": 1, - "base_oid": target_oid, - "candidate_oid": candidate_oid, - "intent_sha256": revision.digest, - "claim": {"kind": "finite_contract", "contract": revision.contract.to_json()}, - } result = run_paired_execution( open_project(root), diff --git a/tests/change/test_witness.py b/tests/change/test_witness.py index ebee3bf..6826245 100644 --- a/tests/change/test_witness.py +++ b/tests/change/test_witness.py @@ -1,6 +1,5 @@ from __future__ import annotations -import hashlib import json import os from pathlib import Path @@ -8,14 +7,13 @@ import pytest from hypothesis import given, settings, strategies as st -from vkit.change.certification import ( - ChangeCertificationRequest, - FiniteContract, - FiniteDomain, - IntentRevision, - OutputRow, - SemanticArtifact, +from tests.change._helpers import ( + contract_json, + domain_json, + make_intent_revision, + sha256_bytes as _sha, ) +from vkit.change.certification import ChangeCertificationRequest from vkit.change.intent import BoundChangeRequest from vkit.change.witness import ( ArtifactRef, @@ -34,29 +32,14 @@ parse_witness, ) - -def _sha(raw: bytes) -> str: - return hashlib.sha256(raw).hexdigest() - - _RUNTIME_IDENTITY = b'{"compiler":"fixture rustc"}' def _binding(**changes: str) -> WitnessBinding: - domain = FiniteDomain( - "SC-03/u32", ("10",), ("before=10,after=9",), "a" * 64, "b" * 64, "c" * 64 - ) - contract = FiniteContract(domain, ("10",), (OutputRow("10", ("before=10,after=9",)),)) - intent = IntentRevision( - "SC-03 fixture", "The upper cap is ten.", contract, - ( - SemanticArtifact("binding", "binding.json", "d" * 64), - SemanticArtifact("codec", "codec.json", domain.codec_sha256), - SemanticArtifact("observation", "observation.json", domain.observation_sha256), - SemanticArtifact("environment", "environment.json", domain.environment_sha256), - ), - ) - request = ChangeCertificationRequest("0" * 40, "1" * 40, intent.digest, contract) + dom = domain_json(binding="SC-03/u32", inputs=("10",), observations=("before=10,after=9",)) + ctr = contract_json({"10": ["before=10,after=9"]}, admissible=("10",), domain_raw=dom) + intent = make_intent_revision(ctr, source="SC-03 fixture", statement="The upper cap is ten.") + request = ChangeCertificationRequest("0" * 40, "1" * 40, intent.digest, intent.contract) bound = BoundChangeRequest( request, intent, "2" * 40, "3" * 40, "4" * 40, "5" * 40, "6" * 64, "7" * 64 ) diff --git a/tests/cli/test_cli_authority.py b/tests/cli/test_cli_authority.py index c431eb7..928f63d 100644 --- a/tests/cli/test_cli_authority.py +++ b/tests/cli/test_cli_authority.py @@ -224,3 +224,93 @@ def test_committed_gate_reports_invalid_project_as_request_error(tmp_path, capsy "--output", str(tmp_path / "out"), "--project", str(tmp_path / "missing"), "--json"]) assert code == EXIT_INVALID assert "does not exist" in json.loads(capsys.readouterr().out)["error"] + + +def test_run_exit_code_and_verdict_exit_code_handle_interrupted_and_scoped(): + from vkit.core.acceptance import ( + EXIT_BLOCKED, + EXIT_FAILED, + EXIT_OK, + run_exit_code, + verdict_exit_code, + ) + + assert run_exit_code({"state": "interrupted", "outcome": None}) == EXIT_BLOCKED + assert run_exit_code({"state": "done", "outcome": {"result": "PASS"}}) == EXIT_OK + assert run_exit_code({"state": "done", "outcome": {"result": "FAIL"}}) == EXIT_FAILED + assert run_exit_code({"state": "done", "outcome": {"result": "BLOCKED"}}) == EXIT_BLOCKED + assert run_exit_code({"state": "running", "outcome": None}) == EXIT_OK + assert run_exit_code({"state": "running", "outcome": None}, unfinished=EXIT_BLOCKED) == EXIT_BLOCKED + assert verdict_exit_code("READY") == EXIT_OK + assert verdict_exit_code("READY_SCOPED") == EXIT_OK + assert verdict_exit_code("REJECTED") == EXIT_FAILED + assert verdict_exit_code("FAILED") == EXIT_FAILED + assert verdict_exit_code("BLOCKED") == EXIT_BLOCKED + + +def test_accept_proposal_refuses_unpinned_evaluator_before_mutating_tree(make_project, monkeypatch): + from helpers import DRIVER, scenario_check + from vkit.cli import EXIT_INVALID, main + from vkit.core.proposals import pending, submit + from vkit.core.store import Store + from vkit.runtime.paths import open_project + + project = make_project({"ok.py": DRIVER + 'report([("ok", True, "ok")])\n'}, + [scenario_check("ok", "ok.py", scenarios=["ok"], inputs=["ok.py"])]) + opened = open_project(project) + store = Store.of(opened) + bad_check = scenario_check("missing_driver", "does_not_exist.py", scenarios=["ok"], inputs=["ok.py"]) + proposal = submit(opened, store, { + "rationale": "Add unpinned check with a new file", + "checks": [bad_check], + "files": {"extra.txt": "should not be written\n"}, + }) + monkeypatch.setenv("VKIT_ALLOW_YES", "1") + monkeypatch.setattr("vkit.cli._parent_commands", lambda: ([], False)) + code = main(["accept", "--proposal", proposal.digest[:12], "--yes", "--project", str(project)]) + assert code == EXIT_INVALID + assert not (project / "extra.txt").exists() + assert len(pending(store)) == 1 + + +def test_cli_validation_error_writes_to_stderr_in_human_mode(make_project, capsys, tmp_path): + from vkit.cli import EXIT_INVALID, main + + project = make_project({"README.md": "hi\n"}, [], accept=False) + bad_req = tmp_path / "bad.json" + bad_req.write_text("{not-json", encoding="utf-8") + code = main(["model", "compare", "--request", str(bad_req), "--project", str(project)]) + captured = capsys.readouterr() + assert code == EXIT_INVALID + assert captured.out == "" + assert "not valid UTF-8 JSON" in captured.err + + +def test_comment_lint_supports_single_file_and_directive_exemptions(tmp_path): + import subprocess + import sys + from helpers import NO_WINDOW, ROOT + + script = ROOT / "scripts" / "tools" / "comment_lint.py" + clean = tmp_path / "clean.py" + clean.write_text( + "#!/usr/bin/env python3\n" + "x = 1 # noqa: E501\n" + "y = 2 # NOQA\n" + "z = 3 # type: ignore\n" + "a = 4 # pragma: no cover\n" + "b = 5 # ruff: noqa\n" + "c = 6 # fmt: off\n", + encoding="utf-8", + ) + done = subprocess.run([sys.executable, str(script), str(clean)], capture_output=True, text=True, **NO_WINDOW) + assert done.returncode == 0, done.stdout + done.stderr + + dirty = tmp_path / "dirty.py" + dirty.write_text("x = 1 # prose comment\n", encoding="utf-8") + done_dirty = subprocess.run([sys.executable, str(script), str(dirty)], capture_output=True, text=True, **NO_WINDOW) + assert done_dirty.returncode == 1 + assert "prose comment" in done_dirty.stdout + + missing_args = subprocess.run([sys.executable, str(script)], capture_output=True, text=True, **NO_WINDOW) + assert missing_args.returncode == 2 diff --git a/tests/cli/test_mcp.py b/tests/cli/test_mcp.py index db19b9b..c8b32eb 100644 --- a/tests/cli/test_mcp.py +++ b/tests/cli/test_mcp.py @@ -106,3 +106,31 @@ def test_vkit_mcp_imports_cleanly_in_isolation(): capture_output=True, text=True, timeout=30, **NO_WINDOW, ) assert done.returncode == 0, done.stderr + + +def test_evidence_export_rejects_in_tree_and_symlink_outputs(make_project, tmp_path): + from vkit.mcp import Server + + project = make_project({"ok.py": PASSES}, [scenario_check("ok", "ok.py", scenarios=["ok"], inputs=["ok.py"])]) + server = Server(project) + body, is_error = server.call("check_run", {"check_ids": ["ok"], "wait_seconds": 60}) + assert not is_error + run_id = body["runs"][0]["run_id"] + + inside, is_error = server.call("evidence_export", {"run_id": run_id, "output": str(project / "exported")}) + assert is_error and "outside the project working tree" in inside["error"] + + symlink_target = tmp_path / "real_out" + symlink_path = tmp_path / "link_out" + symlink_path.symlink_to(symlink_target) + linked, is_error = server.call("evidence_export", {"run_id": run_id, "output": str(symlink_path)}) + assert is_error and "symlink" in linked["error"] + + +def test_mcp_server_call_catches_project_error(tmp_path): + from vkit.mcp import Server + + not_a_repo = tmp_path / "plain" + not_a_repo.mkdir() + body, is_error = Server(not_a_repo).call("status", {}) + assert is_error and "error" in body diff --git a/tests/cli/test_plugin.py b/tests/cli/test_plugin.py index 86f5721..39d786e 100644 --- a/tests/cli/test_plugin.py +++ b/tests/cli/test_plugin.py @@ -106,10 +106,11 @@ def test_session_start_records_a_base_commit_and_stop_scopes_to_the_changed_path project = make_project({"ok.py": PASSES, "README.md": "run lookup\n"}, [scenario_check("ok", "ok.py", scenarios=["ok"], inputs=["ok.py"])]) vkit(project, "check", "run", "--check", "ok") - hook(project, "SessionStart", {}) - assert (open_project(project).git_common_dir / "vkit" / "session_base.txt").is_file() + hook(project, "SessionStart", {"session_id": "sess-alpha"}) + sessions_dir = open_project(project).git_common_dir / "vkit" / "sessions" + assert list(sessions_dir.glob("*.txt")) (project / "README.md").write_text("changed\n", encoding="utf-8") - response = hook(project, "Stop", {}) + response = hook(project, "Stop", {"session_id": "sess-alpha"}) assert "decision" not in response assert "READY_SCOPED" in response["systemMessage"] and "README.md" in response["systemMessage"] @@ -123,3 +124,19 @@ def test_stop_without_a_session_base_falls_back_to_the_full_gate_and_notes_it(ma assert hook(project, "Stop", {}) == {} log = open_project(project).git_common_dir / "vkit" / "telemetry.jsonl" assert "session_base_missing" in log.read_text(encoding="utf-8") + + +def test_parallel_session_ids_and_fresh_blocked_are_isolated_and_blocking(make_project): + from vkit.runtime.paths import open_project + + project = make_project({"ok.py": PASSES}, [scenario_check("ok", "ok.py", scenarios=["ok"], inputs=["ok.py"])], + accept=False) + hook(project, "SessionStart", {"session_id": "sess-one"}) + hook(project, "SessionStart", {"session_id": "sess-two"}) + sessions = list((open_project(project).git_common_dir / "vkit" / "sessions").glob("*.txt")) + assert len(sessions) == 2 + + spec = importlib.util.spec_from_file_location("vkit_hook", HOOK) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + assert "fresh_blocked" in module.BLOCKING diff --git a/tests/console/test_console.py b/tests/console/test_console.py index 221eeba..53a536b 100644 --- a/tests/console/test_console.py +++ b/tests/console/test_console.py @@ -591,3 +591,41 @@ def test_launcher_settings_save_does_not_require_a_selected_workspace(make_proje "Transfer-Encoding": "chunked"}, ) assert status == 400 + + +def test_console_serves_es_modules_folder_icon_lazy_doctor_and_sse_events(make_project): + project = make_project({"ok.py": PASSES}, [scenario_check("ok", "ok.py", scenarios=["ok"], inputs=["ok.py"])]) + with _serve(project) as port: + for asset_path in ( + "/js/api.js", + "/js/ui.js", + "/js/views/overview.js", + "/js/views/execution.js", + "/js/views/settings.js", + ): + status, body = _get(port, asset_path) + assert status == 200 and body, asset_path + status, icons = _get(port, "/assets/icons.svg") + assert status == 200 and b'id="folder"' in icons + + status, raw = _get(port, "/api/config?include_doctor=0") + light_config = json.loads(raw) + assert status == 200 and "doctor" not in light_config and "state_root" in light_config + + status, raw = _get(port, "/api/doctor") + doctor = json.loads(raw) + assert status == 200 and doctor["project"] == str(project) + + connection = http.client.HTTPConnection("127.0.0.1", port, timeout=10) + try: + connection.request("GET", "/api/events", headers={"Host": f"127.0.0.1:{port}"}) + response = connection.getresponse() + assert response.status == 200 + assert "text/event-stream" in response.getheader("Content-Type", "") + first_line = response.readline().decode("utf-8") + second_line = response.readline().decode("utf-8") + assert first_line.strip() == "event: state" + assert second_line.startswith("data: ") + assert "token" in json.loads(second_line[len("data: "):]) + finally: + connection.close() diff --git a/tests/core/test_budgets.py b/tests/core/test_budgets.py index 756b01e..a507a67 100644 --- a/tests/core/test_budgets.py +++ b/tests/core/test_budgets.py @@ -1,6 +1,11 @@ from __future__ import annotations +import math + +import pytest + from vkit.core.budgets import Budget, Measurement, evaluate +from vkit.core.schemas import SchemaValidationError, parse_artifact def rows(results): @@ -29,3 +34,44 @@ def test_regression_is_judged_against_the_pinned_baseline_only(): def test_a_budget_on_a_measurement_the_check_did_not_report_fails(): results, _ = evaluate((Budget("latency", limit=1),), (), None) assert rows(results) == [("budget:latency", False, "the check did not report this measurement")] + + +@pytest.mark.parametrize( + ("better", "value", "baseline", "expected"), + [ + ("lower", 0.0, 0.0, True), + ("lower", 1.0, 0.0, False), + ("lower", -1.0, 0.0, True), + ("higher", 0.0, 0.0, True), + ("higher", -1.0, 0.0, False), + ("higher", 1.0, 0.0, True), + ("higher", 80.0, 100.0, False), + ("higher", 95.0, 100.0, True), + ], +) +def test_zero_baseline_and_higher_is_better_regressions(better, value, baseline, expected): + results, unchecked = evaluate( + (Budget("metric", max_regression_pct=10),), + (Measurement("metric", value, "u", better),), + {"metric": baseline}, + ) + assert unchecked == () + assert len(results) == 1 and results[0].passed is expected + + +@pytest.mark.parametrize("bad", [math.nan, math.inf, -math.inf]) +def test_non_finite_values_and_limits_fail_budgets(bad): + limit_res, _ = evaluate((Budget("m", limit=10.0),), (Measurement("m", bad, "ms", "lower"),), None) + assert len(limit_res) == 1 and limit_res[0].passed is False + + bad_limit_res, _ = evaluate((Budget("m", limit=bad),), (Measurement("m", 5.0, "ms", "lower"),), None) + assert len(bad_limit_res) == 1 and bad_limit_res[0].passed is False + + reg_res, _ = evaluate((Budget("m", max_regression_pct=10.0),), (Measurement("m", bad, "ms", "lower"),), {"m": 5.0}) + assert len(reg_res) == 1 and reg_res[0].passed is False + + +@pytest.mark.parametrize("token", ["NaN", "Infinity", "-Infinity"]) +def test_parse_artifact_rejects_non_finite_json_constants(token): + with pytest.raises(SchemaValidationError, match="non-finite"): + parse_artifact(f'{{"value": {token}}}'.encode("utf-8")) diff --git a/tests/core/test_claimkind.py b/tests/core/test_claimkind.py index 1074006..44f3b12 100644 --- a/tests/core/test_claimkind.py +++ b/tests/core/test_claimkind.py @@ -2,7 +2,7 @@ import pytest -from helpers import vkit +from vkit.core import query @pytest.mark.parametrize("kind,fields,category,establishes,limits", [ @@ -41,9 +41,8 @@ def test_status_carries_the_registered_checks_category_and_limits( project = make_project({"README.md": "category scope\n", "Challenge.lean": "", "Model.tla": "", "Model.cfg": ""}, [check], accept=False) - code, body = vkit(project, "status") + body = query.status(query.open_context(project)) - assert code == 0, body assert body["manifest_error"] is None, body assert len(body["checks"]) == 1 reported = body["checks"][0] diff --git a/tests/core/test_container_recovery.py b/tests/core/test_container_recovery.py index 9813a60..857dae7 100644 --- a/tests/core/test_container_recovery.py +++ b/tests/core/test_container_recovery.py @@ -8,21 +8,28 @@ from vkit.core.store import Store, write_json -@pytest.mark.parametrize("case,expected,deleted", [ - ("owned", "removed", ["a" * 64]), ("absent", "removed", []), - ("foreign", "blocked", []), ("engine_error", "blocked", []), +@pytest.mark.parametrize("case,expected,deleted,expected_cid", [ + ("owned", "removed", ["a" * 64], "a" * 64), + ("absent", "removed", [], "a" * 64), + ("foreign", "blocked", [], "a" * 64), + ("engine_error", "blocked", [], "a" * 64), + ("empty_cid_labeled", "removed", ["a" * 64], "a" * 64), + ("empty_cid_absent", "absent", [], None), ]) -def test_orphan_recovery_is_exact_and_idempotent(tmp_path, monkeypatch, case, expected, deleted): +def test_orphan_recovery_is_exact_and_idempotent(tmp_path, monkeypatch, case, expected, deleted, expected_cid): store = Store(tmp_path / "state") run_id, cid = "attempt-123", "a" * 64 label = run_id + "-nonce" run_dir = store.run_dir(run_id) store.save({"run_id": run_id, "state": "running"}) + empty_cid = case.startswith("empty_cid_") write_json(container.control_path(run_dir), { "schema_version": 1, "run_id": label, "cid_file": "container.cid", - "container_id": cid, "status": "created"}) - (container.control_path(run_dir).parent / "container.cid").write_text(cid, encoding="ascii") - actual = {} if case == "absent" else {cid: "somebody-else" if case == "foreign" else label} + "container_id": None if empty_cid else cid, + "status": "creating" if empty_cid else "created", + }) + (container.control_path(run_dir).parent / "container.cid").write_text("" if empty_cid else cid, encoding="ascii") + actual = {} if case in {"absent", "empty_cid_absent"} else {cid: "somebody-else" if case == "foreign" else label} removed, commands = [], [] def docker(argv, timeout=15): @@ -44,8 +51,13 @@ def docker(argv, timeout=15): record = store.record(run_id) assert record["state"] == "interrupted" assert record["container_cleanup"]["status"] == expected + assert record["container_cleanup"]["container_id"] == expected_cid + if empty_cid: + assert record["container_cleanup"]["detail"] is None assert removed == deleted - assert store.record(run_id)["container_cleanup"]["status"] == expected + second = store.record(run_id) + assert second["container_cleanup"]["status"] == expected + assert second["container_cleanup"]["container_id"] == expected_cid assert removed == deleted assert record.get("outcome") is None @@ -60,55 +72,3 @@ def forbidden(*args, **kwargs): result = container.recover_attempt(run) assert result["status"] == "blocked" assert "does not belong" in result["detail"] - - -def test_recovery_handles_empty_cid_file_and_persists_label_discovered_container(tmp_path, monkeypatch): - run = tmp_path / "attempt-456" - label = "attempt-456-nonce" - cid = "b" * 64 - path = container.control_path(run) - write_json(path, { - "schema_version": 1, "run_id": label, "cid_file": "container.cid", - "container_id": None, "status": "creating", - }) - (path.parent / "container.cid").write_text("", encoding="ascii") - actual = {cid: label} - removed = [] - - def docker(argv, timeout=15): - if argv[0] == "ps": - return subprocess.CompletedProcess( - argv, 0, "\n".join(key for key, value in actual.items() if value == label), "", - ) - if argv[0] == "inspect": - return (subprocess.CompletedProcess(argv, 0, actual[cid], "") if cid in actual else - subprocess.CompletedProcess(argv, 1, "", "No such object")) - assert argv == ["rm", "--force", cid] - removed.append(cid) - actual.pop(cid) - return subprocess.CompletedProcess(argv, 0, cid, "") - - monkeypatch.setattr(container, "_docker", docker) - first = container.recover_attempt(run) - assert first == {"status": "removed", "container_id": cid, "detail": None} - assert removed == [cid] - second = container.recover_attempt(run) - assert second == {"status": "removed", "container_id": cid, "detail": None} - assert removed == [cid] - - -def test_recovery_reports_absent_when_empty_cid_file_and_no_labeled_container(tmp_path, monkeypatch): - run = tmp_path / "attempt-789" - path = container.control_path(run) - write_json(path, { - "schema_version": 1, "run_id": "attempt-789-nonce", "cid_file": "container.cid", - "container_id": None, "status": "creating", - }) - (path.parent / "container.cid").write_text("", encoding="ascii") - monkeypatch.setattr( - container, "_docker", - lambda argv, timeout=15: subprocess.CompletedProcess(argv, 0, "", ""), - ) - - result = container.recover_attempt(run) - assert result == {"status": "absent", "container_id": None, "detail": None} diff --git a/tests/core/test_discover.py b/tests/core/test_discover.py index 0a034c1..b088e16 100644 --- a/tests/core/test_discover.py +++ b/tests/core/test_discover.py @@ -137,55 +137,72 @@ def test_unrelated_tox_ini_does_not_create_a_test_command(repo, contents) -> Non assert any("declares no test command" in gap for gap in report.gaps) -def test_pytest_only_tox_ini_reports_pytest_and_drives_npm_ambiguity(repo) -> None: - project = repo({ - "package.json": json.dumps({"scripts": {"test": "vitest run"}}), - "tox.ini": "[pytest]\ntestpaths = tests\n", - }) - - report = inspect_repository(project) - - python_test = next(command for command in report.by_kind("test") if command.runner == "pytest") - npm_test = next(command for command in report.by_kind("test") if command.runner == "npm") - assert python_test.argv == ("python", "-m", "pytest") - assert npm_test.ambiguous and "pytest" in " ".join(npm_test.ambiguity) - assert not any(command.runner == "tox" for command in report.commands) - - -def test_tox_ini_with_pytest_and_testenv_reports_both_runners(repo) -> None: - project = repo({ - "tox.ini": "[pytest]\ntestpaths = tests\n\n[testenv]\ncommands = pytest\n", - }) - - commands = inspect_repository(project).by_kind("test") - - by_runner = {command.runner: command for command in commands} - assert by_runner["pytest"].argv == ("python", "-m", "pytest") - assert by_runner["tox"].argv == ("tox",) - assert by_runner["tox"].ambiguity == () - - -def test_unrelated_toml_tables_do_not_create_python_test_runners(repo) -> None: - project = repo({ - "package.json": json.dumps({"scripts": {"test": "vitest run"}}), - "pyproject.toml": '[pytest]\ntestpaths = ["tests"]\n\n[testenv]\ncommands = ["pytest"]\n', - }) - - report = inspect_repository(project) - - npm_test = next(command for command in report.by_kind("test") if command.runner == "npm") - assert npm_test.ambiguity == () - assert [command.runner for command in report.by_kind("test")] == ["npm"] - - -def test_python_ecosystem_is_reported_once_for_multiple_config_files(repo) -> None: - report = inspect_repository(repo({ - "pyproject.toml": '[project]\nrequires-python = ">=3.11"\n\n[tool.pytest.ini_options]\ntestpaths = ["tests"]\n', - "pytest.ini": "[pytest]\ntestpaths = tests\n", - "tox.ini": "[testenv]\ncommands = pytest\n", - })) - - assert report.ecosystem.count("python") == 1 +@pytest.mark.parametrize( + ("files", "expected_argvs", "ambiguous_runner", "expected_python_ecosystems"), + [ + ( + { + "package.json": json.dumps({"scripts": {"test": "vitest run"}}), + "tox.ini": "[pytest]\ntestpaths = tests\n", + }, + {"pytest": ("python", "-m", "pytest"), "npm": ("npm", "run", "test")}, + ("npm", "pytest"), + 1, + ), + ( + {"tox.ini": "[pytest]\ntestpaths = tests\n\n[testenv]\ncommands = pytest\n"}, + {"pytest": ("python", "-m", "pytest"), "tox": ("tox",)}, + ("tox", None), + 1, + ), + ( + { + "package.json": json.dumps({"scripts": {"test": "vitest run"}}), + "pyproject.toml": '[pytest]\ntestpaths = ["tests"]\n\n[testenv]\ncommands = ["pytest"]\n', + }, + {"npm": ("npm", "run", "test")}, + ("npm", None), + None, + ), + ( + { + "pyproject.toml": '[project]\nrequires-python = ">=3.11"\n\n[tool.pytest.ini_options]\ntestpaths = ["tests"]\n', + "pytest.ini": "[pytest]\ntestpaths = tests\n", + "tox.ini": "[testenv]\ncommands = pytest\n", + }, + {"pytest": ("python", "-m", "pytest"), "tox": ("tox",)}, + None, + 1, + ), + ], + ids=[ + "pytest_only_tox_ini", + "tox_ini_pytest_and_testenv", + "unrelated_toml_tables", + "single_python_ecosystem", + ], +) +def test_python_config_runner_and_ecosystem_detection( + repo: ProjectBuilder, + files: dict[str, str], + expected_argvs: dict[str, tuple[str, ...]], + ambiguous_runner: tuple[str, str | None] | None, + expected_python_ecosystems: int | None, +) -> None: + report = inspect_repository(repo(files)) + by_runner = {command.runner: command for command in report.by_kind("test")} + + assert set(by_runner) == set(expected_argvs) + for runner, argv in expected_argvs.items(): + assert by_runner[runner].argv == argv + if ambiguous_runner is not None: + target, token = ambiguous_runner + if token is None: + assert by_runner[target].ambiguity == () + else: + assert by_runner[target].ambiguous and token in " ".join(by_runner[target].ambiguity) + if expected_python_ecosystems is not None: + assert report.ecosystem.count("python") == expected_python_ecosystems def test_node_engine_uses_one_version_probe(repo, monkeypatch) -> None: @@ -310,38 +327,62 @@ def test_inspect_reads_make_targets_and_ci_workflow_commands( assert "npm ci" not in json.dumps(only.to_json()), "an install line was reported as a runnable command" -def test_oversized_python_config_is_a_gap_without_stopping_other_discovery( +@pytest.mark.parametrize( + ("files", "expected_gaps", "forbidden_gaps", "expected_commands", "expected_ci_files"), + [ + ( + { + "setup.cfg": "x" * (1_048_576 + 1), + "package.json": json.dumps({"scripts": {"test": "vitest run"}}), + ".github/workflows/ci.yml": "jobs:\n a:\n steps:\n - run: npm test\n", + }, + ("setup.cfg exceeds 1 MiB",), + ("no test configuration file was found",), + {"npm:test"}, + {".github/workflows/ci.yml"}, + ), + ( + { + "pyproject.toml": "x" * (1_048_576 + 1), + "pytest.ini": "[pytest]\naddopts = -q\n", + "Makefile": "test:\n\tpython -m unittest\n", + }, + ("pyproject.toml exceeds 1 MiB",), + (), + {"pytest:configured", "make:test"}, + set(), + ), + ( + { + "Makefile": "test:\n\t" + ("x" * (1_048_576 + 1)), + ".github/workflows/a_big.yml": "x" * (1_048_576 + 1), + ".github/workflows/b_ok.yml": "jobs:\n a:\n steps:\n - run: pytest\n", + }, + ("Makefile exceeds 1 MiB", "a_big.yml exceeds 1 MiB"), + (), + set(), + {".github/workflows/b_ok.yml"}, + ), + ], + ids=["setup_cfg", "pyproject", "makefile_and_workflow"], +) +def test_oversized_files_report_gaps_without_stopping_other_discovery( repo: ProjectBuilder, + files: dict[str, str], + expected_gaps: tuple[str, ...], + forbidden_gaps: tuple[str, ...], + expected_commands: set[str], + expected_ci_files: set[str], ) -> None: - project = repo({ - "setup.cfg": "x" * (1_048_576 + 1), - "package.json": json.dumps({"scripts": {"test": "vitest run"}}), - ".github/workflows/ci.yml": "jobs:\n a:\n steps:\n - run: npm test\n", - }) - - report = inspect_repository(project) - - assert any("setup.cfg exceeds 1 MiB" in gap for gap in report.gaps) - assert not any("no test configuration file was found" in gap for gap in report.gaps) - assert any(command.id == "npm:test" for command in report.commands) - assert any(command.provenance.file == ".github/workflows/ci.yml" for command in report.ci_commands) - - -def test_oversized_pyproject_does_not_hide_other_python_test_facts( - repo: ProjectBuilder, -) -> None: - project = repo({ - "pyproject.toml": "x" * (1_048_576 + 1), - "pytest.ini": "[pytest]\naddopts = -q\n", - "Makefile": "test:\n\tpython -m unittest\n", - }) - - report = inspect_repository(project) + report = inspect_repository(repo(files)) - gaps = [gap for gap in report.gaps if "pyproject.toml exceeds 1 MiB" in gap] - assert gaps == ["pyproject.toml exceeds 1 MiB"] - assert any(command.id == "pytest:configured" for command in report.commands) - assert any(command.id == "make:test" for command in report.commands) + for expected in expected_gaps: + matches = [gap for gap in report.gaps if expected in gap] + assert len(matches) == 1, f"expected one {expected!r} gap, got {report.gaps}" + for forbidden in forbidden_gaps: + assert not any(forbidden in gap for gap in report.gaps) + assert expected_commands <= {command.id for command in report.commands} + assert expected_ci_files <= {command.provenance.file for command in report.ci_commands} def test_inspect_reports_a_declared_node_engine_separately_from_a_measured_one( @@ -405,6 +446,7 @@ def test_inspect_bounds_a_report_without_dropping_the_test_command( assert len(builds) < 198, f"{len(builds)} build helpers survived; the bound is not prioritising" assert any("never dropped by this bound" in gap for gap in report.gaps) + def test_inspect_flags_prepublishOnly_as_install_hook(repo: ProjectBuilder) -> None: project = repo({"package.json": json.dumps({"scripts": {"prepublishOnly": "npm test"}})}) @@ -415,22 +457,6 @@ def test_inspect_flags_prepublishOnly_as_install_hook(repo: ProjectBuilder) -> N assert installs["npm:prepublishOnly"].ambiguous -def test_oversized_makefile_and_workflow_are_gaps_without_stopping_other_workflows( - repo: ProjectBuilder, -) -> None: - project = repo({ - "Makefile": "test:\n\t" + ("x" * (1_048_576 + 1)), - ".github/workflows/a_big.yml": "x" * (1_048_576 + 1), - ".github/workflows/b_ok.yml": "jobs:\n a:\n steps:\n - run: pytest\n", - }) - - report = inspect_repository(project) - - assert any("Makefile exceeds 1 MiB" in gap for gap in report.gaps) - assert any("a_big.yml exceeds 1 MiB" in gap for gap in report.gaps) - assert any(c.provenance.file == ".github/workflows/b_ok.yml" for c in report.ci_commands) - - def test_empty_workflows_directory_does_not_report_zero_workflow_gap(repo: ProjectBuilder) -> None: project = repo({"Makefile": "test:\n\tpytest\n"}) (project.root / ".github" / "workflows").mkdir(parents=True) diff --git a/tests/core/test_feedback.py b/tests/core/test_feedback.py index b7f4f8d..59446be 100644 --- a/tests/core/test_feedback.py +++ b/tests/core/test_feedback.py @@ -5,7 +5,6 @@ from helpers import McpClient, vkit from vkit.core.feedback import collect, submit -from vkit.runtime.paths import open_project from vkit.core.store import Store @@ -55,8 +54,8 @@ def test_real_mcp_feedback_is_append_only_bounded_and_prioritizes_formal(make_pr client.close() -def test_concurrent_feedback_deduplicates_complete_markdown(make_project): - store = Store.of(open_project(make_project({}, [], accept=False))) +def test_concurrent_feedback_deduplicates_complete_markdown(tmp_path): + store = Store(tmp_path / "state") with ThreadPoolExecutor(max_workers=4) as workers: entries = list(workers.map(lambda _: submit(store, REQUEST), range(12))) assert len({entry["id"] for entry in entries}) == 1 @@ -65,8 +64,8 @@ def test_concurrent_feedback_deduplicates_complete_markdown(make_project): assert not list((store.root / "feedback").glob("*.tmp")) -def test_feedback_collision_cannot_read_a_link_or_directory(make_project, tmp_path): - store = Store.of(open_project(make_project({}, [], accept=False))) +def test_feedback_collision_cannot_read_a_link_or_directory(tmp_path): + store = Store(tmp_path / "state") entry = submit(store, REQUEST) path = Path(entry["path"]) path.unlink() @@ -87,8 +86,8 @@ def test_feedback_collision_cannot_read_a_link_or_directory(make_project, tmp_pa @pytest.mark.parametrize("change", [{"task": " "}, {"benefit": "x" * 2001}, {"kind": "test"}, {"run_id": "missing"}]) -def test_feedback_rejects_incomplete_or_unbound_requests(make_project, change): - store = Store.of(open_project(make_project({}, [], accept=False))) +def test_feedback_rejects_incomplete_or_unbound_requests(tmp_path, change): + store = Store(tmp_path / "state") with pytest.raises(ValueError): submit(store, {**REQUEST, **change}) assert collect(store)["total"] == 0 diff --git a/tests/core/test_kernel_purity.py b/tests/core/test_kernel_purity.py new file mode 100644 index 0000000..6cb5e99 --- /dev/null +++ b/tests/core/test_kernel_purity.py @@ -0,0 +1,231 @@ +from __future__ import annotations + +import ast +import importlib +import sys + +from helpers import ROOT +from vkit.kernel import ( + assess_difference_status, + check_delegation_kernel, + check_limit, + check_regression, + classify_difference, + compare_contracts_kernel, + conclude_change_methods, + decide_gate, + def_change_kernel, + derive_assurance, + derive_claim_outcome, + intent_entails_claim_kernel, + run_exit_code_kernel, + verdict_exit_code_kernel, + verify_passing_receipt, + verify_receipt_core, +) + +KERNEL_DIR = ROOT / "src" / "vkit" / "kernel" +FORBIDDEN_IO_MODULES = frozenset({ + "os", + "subprocess", + "socket", + "http", + "urllib", + "shutil", + "tempfile", + "sqlite3", + "io", + "requests", + "ctypes", + "multiprocessing", + "threading", + "asyncio", +}) +ALLOWED_BRIDGE_STDLIB = frozenset({ + "__future__", + "collections", + "fractions", + "functools", + "importlib", + "math", + "pathlib", + "sys", + "types", + "typing", + "vkit", +}) + + +def test_kernel_python_files_forbid_io_imports_and_sys_path_mutation(): + files = sorted( + path for path in KERNEL_DIR.rglob("*.py") + if "_dafny_gen" not in path.parts + ) + assert files + for path in files: + tree = ast.parse(path.read_text(encoding="utf-8")) + for node in ast.walk(tree): + if isinstance(node, ast.Import): + for alias in node.names: + top = alias.name.split(".")[0] + assert top not in FORBIDDEN_IO_MODULES, f"{path}: forbidden import {top}" + assert top in ALLOWED_BRIDGE_STDLIB, f"{path}: unexpected import {top}" + elif isinstance(node, ast.ImportFrom): + if node.module: + top = node.module.split(".")[0] + assert top not in FORBIDDEN_IO_MODULES, f"{path}: forbidden import {top}" + assert top in ALLOWED_BRIDGE_STDLIB, f"{path}: unexpected import {top}" + elif isinstance(node, (ast.Call, ast.Assign, ast.AugAssign)): + rendered = ast.unparse(node) + assert not rendered.startswith(( + "sys.path.insert(", + "sys.path.append(", + "sys.path.extend(", + "sys.path =", + "sys.path[", + "sys.path +=", + )), f"{path}:{node.lineno}: mutates sys.path" + + +def test_importing_kernel_does_not_mutate_sys_path(): + before = list(sys.path) + import vkit.kernel.bridge as bridge + + importlib.reload(bridge) + assert sys.path == before + + +def test_gate_kernel_boundary(): + assert decide_gate( + ["fresh_pass"], [], has_inventory=True, has_ghosts=False, + has_weakened=False, has_incomparable=False, has_uncovered=False, + ) == ("READY", "ready") + assert decide_gate( + ["fresh_pass"], [], has_inventory=True, has_ghosts=False, + has_weakened=False, has_incomparable=False, has_uncovered=True, + ) == ("READY_SCOPED", "uncovered_change") + assert decide_gate( + ["fresh_pass", "fresh_fail"], [], has_inventory=True, has_ghosts=False, + has_weakened=False, has_incomparable=False, has_uncovered=False, + ) == ("REJECTED", "fresh_fail") + assert decide_gate( + ["fresh_pass"], [], has_inventory=True, has_ghosts=False, + has_weakened=True, has_incomparable=True, has_uncovered=False, + ) == ("REJECTED", "weakened_check") + assert decide_gate( + [], [], has_inventory=False, has_ghosts=False, + has_weakened=False, has_incomparable=False, has_uncovered=False, + ) == ("BLOCKED", "no_checks") + + +def test_budgets_kernel_boundary(): + assert check_limit("lower", 10.0, 10.0) is True + assert check_limit("lower", 10.5, 10.0) is False + assert check_limit("higher", 9.0, 10.0) is False + assert check_limit("lower", float("nan"), 10.0) is False + assert check_regression("lower", 0.0, 0.0, 0.0) is True + assert check_regression("lower", 1.0, 0.0, 10.0) is False + assert check_regression("lower", -1.0, 0.0, 10.0) is True + assert check_regression("higher", 1.0, 0.0, 10.0) is True + assert check_regression("higher", -1.0, 0.0, 10.0) is False + assert check_regression("lower", 110.0, 100.0, 10.0) is True + assert check_regression("lower", 111.0, 100.0, 10.0) is False + assert check_regression("lower", float("inf"), 100.0, 10.0) is False + + +def test_acceptance_kernel_boundary(): + assert run_exit_code_kernel("PASS", "done", 0) == 0 + assert run_exit_code_kernel("FAIL", "done", 0) == 1 + assert run_exit_code_kernel("BLOCKED", "done", 0) == 3 + assert run_exit_code_kernel(None, "interrupted", 0) == 3 + assert run_exit_code_kernel(None, "running", 7) == 7 + assert verdict_exit_code_kernel("READY") == 0 + assert verdict_exit_code_kernel("READY_SCOPED") == 0 + assert verdict_exit_code_kernel("REJECTED") == 1 + assert verdict_exit_code_kernel("BLOCKED") == 3 + assert def_change_kernel(False, []) == "incomparable" + assert def_change_kernel(True, []) == "unchanged" + assert def_change_kernel(True, [("list", ["a"], ["a", "b"])]) == "strengthening" + assert def_change_kernel(True, [("list", ["a", "b"], ["a"])]) == "weakening" + assert def_change_kernel(True, [("timeout", 10, 5)]) == "strengthening" + assert def_change_kernel(True, [("timeout", 5, 10)]) == "weakening" + assert def_change_kernel(True, [("opaque", 1, 2)]) == "incomparable" + + +def test_receipt_kernel_boundary(): + assert derive_assurance(has_check=True, is_shadow=False, kind="lean") == "kernel_proof" + assert derive_assurance(has_check=True, is_shadow=False, kind="tlc") == "finite_model" + assert derive_assurance(has_check=True, is_shadow=True, kind="lean") == "empirical" + assert derive_assurance(has_check=False, is_shadow=False, kind="other") == "trusted_engine" + assert derive_claim_outcome("PASS", is_lean=False, is_shadow=False) == "established" + assert derive_claim_outcome("FAIL", is_lean=True, is_shadow=False) == "unknown" + assert derive_claim_outcome("PASS", is_lean=False, is_shadow=True) == "unknown" + assert verify_receipt_core( + receipt_digest_matches=True, + artifacts_match=True, + subject_matches=True, + policy_matches=True, + job_id_matches=True, + authority_matches=True, + claim_outcome_consistent=True, + assurance_consistent=True, + ) is True + assert verify_passing_receipt( + "FAIL", + is_shadow=False, + receipt_digest_matches=True, + artifacts_match=True, + subject_matches=True, + policy_matches=True, + job_id_matches=True, + authority_matches=True, + claim_outcome_consistent=True, + assurance_consistent=True, + ) is False + + +def test_change_kernel_boundary(): + kind, o2n, n2o = compare_contracts_kernel( + "d1", ["x"], {"x": ["a", "b"]}, + "d1", ["x"], {"x": ["a"]}, + ) + assert kind == "strengthens" + assert o2n == (True, True, None, None) + assert n2o == (True, False, None, ("x", "b")) + + ent_kind, in_ok, out_ok, in_w, out_w = intent_entails_claim_kernel( + "d1", ["x"], {"x": ["a"]}, + "d1", ["x"], {"x": ["a", "b"]}, + ) + assert (ent_kind, in_ok, out_ok, in_w, out_w) == ("entailed", True, True, None, None) + + ok, err, w_in, w_out = check_delegation_kernel( + intent_digest="i1", + basis_intent_digest="i1", + intent_domain_digest="d1", + intent_inputs=["x"], + intent_outputs={"x": ["a"]}, + baseline_domain_digest="d1", + baseline_inputs=["x"], + baseline_outputs={"x": ["a", "b"]}, + assumptions_domain_digest="d1", + assumptions_inputs=["x"], + assumptions_outputs={"x": ["a", "b"]}, + claim_domain_digest="d1", + claim_inputs=["x"], + claim_outputs={"x": ["a"]}, + domain_observations=["a", "b"], + near_miss_input="x", + near_miss_output="b", + ) + assert (ok, err, w_in, w_out) == (True, "", "x", "b") + + assert classify_difference( + "a", "a", {"a"}, has_guards=False, guard_intersection=set() + ) == "preserved" + assert assess_difference_status(1, 0, ["preserved"]) == "observed_conformance" + assert assess_difference_status(1, 0, ["preserved", "violation"]) == "observed_violation" + assert assess_difference_status(1, 0, ["preserved", "unknown"]) == "unknown" + assert conclude_change_methods(["observed_conformance", "verified"]) == "model_verified" + assert conclude_change_methods(["observed_violation", "verified"]) == "observed_violation" + assert conclude_change_methods([]) == "unsupported" diff --git a/tests/core/test_query.py b/tests/core/test_query.py index 640fc72..63c49a8 100644 --- a/tests/core/test_query.py +++ b/tests/core/test_query.py @@ -9,7 +9,7 @@ import pytest -from helpers import DRIVER, McpClient, git, scenario_check, vkit +from helpers import DRIVER, PASSES, McpClient, git, scenario_check, vkit, write_manifest from vkit.runtime.paths import Project from vkit.core.query import Context, doctor, open_context, run_view, run_view_full, status from vkit.core.store import Store, write_json @@ -194,6 +194,7 @@ def test_run_view_rejects_invalid_section_selectors(tmp_path, sections): with pytest.raises(ValueError, match="sections"): run_view(context, "example-run", sections=sections) + def _install_formal_component(project, *, required=True, reserve="api::reserve"): path = project / "verification" / "manifest.json" manifest = json.loads(path.read_text(encoding="utf-8")) @@ -254,8 +255,7 @@ def test_formal_source_and_policy_changes_make_evidence_stale(tmp_path, monkeypa project.mkdir() (project / "src").mkdir() (project / "src/allocation.rs").write_bytes(b"pub fn reserve() {}\r\n") - (project / "verification").mkdir() - (project / "verification/manifest.json").write_text(json.dumps({"schema_version": 3, "checks": []}), encoding="utf-8") + write_manifest(project, []) git(project, "init", "-q") git(project, "add", ".") git(project, "commit", "-qm", "initial") @@ -280,8 +280,7 @@ def test_formal_setup_failure_is_a_blocked_status_and_doctor_finding(tmp_path, m project.mkdir() (project / "src").mkdir() (project / "src/allocation.rs").write_bytes(b"pub fn reserve() {}\r\n") - (project / "verification").mkdir() - (project / "verification/manifest.json").write_text(json.dumps({"schema_version": 3, "checks": []}), encoding="utf-8") + write_manifest(project, []) git(project, "init", "-q") git(project, "add", ".") git(project, "commit", "-qm", "initial") @@ -305,7 +304,6 @@ def unavailable(_): assert "Docker or Verus unavailable" in checked["findings"][-1]["detail"] -PASSES = DRIVER + 'report([("ok", True, "ok")])\n' GEN_DRIVER = DRIVER + 'report([("ok", open("generated/x.py", encoding="utf-8").read() == "y\\n", "gen")])\n' @@ -316,20 +314,6 @@ def gen_check(): "subject": {"paths": ["generated/x.py"], "digest": None}, "claim_id": "gen"} -def test_status_names_closure_and_scope_claim_coverage_for_requested_paths(make_project): - project = make_project({"ok.py": PASSES, "generated/x.py": "y\n", "generated/check_gen.py": GEN_DRIVER}, - [scenario_check("ok", "ok.py", scenarios=["ok"], inputs=["ok.py"]), gen_check()]) - vkit(project, "check", "run", "--needed") - (project / "generated" / "credentials").write_text("k\n", encoding="utf-8") - out = status(open_context(project), paths=["ok.py", "generated/credentials"]) - assert out["gate"]["verdict"] == "READY" - assert out["coverage_kinds"] == {"closure": ["ok.py"], "scope_claim": ["generated/credentials"]} - assert out["unmapped_paths"] == [] - closure = status(open_context(project), paths=["ok.py"]) - assert closure["gate"]["verdict"] == "READY" - assert closure["coverage_kinds"] == {"closure": ["ok.py"], "scope_claim": []} - - def test_session_status_computes_only_checks_reading_the_changed_paths(make_project, monkeypatch): from vkit.core import evidence @@ -386,9 +370,7 @@ def test_session_status_surfaces_a_deleted_accepted_obligation(make_project): [scenario_check("ok", "ok.py", scenarios=["ok"], inputs=["ok.py"]), scenario_check("gone", "ok.py", scenarios=["ok"], inputs=["ok.py"])]) vkit(project, "check", "run", "--check", "ok", "--check", "gone") - (project / "verification" / "manifest.json").write_text(json.dumps({ - "schema_version": 3, "description": "test project", - "checks": [scenario_check("ok", "ok.py", scenarios=["ok"], inputs=["ok.py"])]}), encoding="utf-8") + write_manifest(project, [scenario_check("ok", "ok.py", scenarios=["ok"], inputs=["ok.py"])]) assert vkit(project, "accept", "--check", "ok", "--yes")[0] == 0 out = status(open_context(project), paths=["ok.py"], session=True) assert out["gate"]["verdict"] == "REJECTED" and "obligation_removed" in out["gate"]["reason"] @@ -431,11 +413,19 @@ def test_a_requested_path_falls_under_exactly_one_coverage_kind(make_project): [scenario_check("ok", "ok.py", scenarios=["ok"], inputs=["ok.py"]), gen_check()]) vkit(project, "check", "run", "--needed") (project / "generated" / "credentials").write_text("k\n", encoding="utf-8") - out = status(open_context(project), paths=["ok.py", "generated/credentials", "README.md"]) - kinds = out["coverage_kinds"] - assert kinds["closure"] == ["ok.py"] and kinds["scope_claim"] == ["generated/credentials"] + ctx = open_context(project) + out = status(ctx, paths=["ok.py", "generated/credentials", "README.md"]) + assert out["coverage_kinds"] == {"closure": ["ok.py"], "scope_claim": ["generated/credentials"]} assert out["unmapped_paths"] == ["README.md"] assert out["gate"]["verdict"] == "READY_SCOPED" + covered = status(ctx, paths=["ok.py", "generated/credentials"]) + assert covered["gate"]["verdict"] == "READY" + assert covered["coverage_kinds"] == {"closure": ["ok.py"], "scope_claim": ["generated/credentials"]} + assert covered["unmapped_paths"] == [] + closure = status(ctx, paths=["ok.py"]) + assert closure["gate"]["verdict"] == "READY" + assert closure["coverage_kinds"] == {"closure": ["ok.py"], "scope_claim": []} + def test_run_view_ignores_symlinked_logs_and_handles_null_change_certification(tmp_path): store = Store(tmp_path / "state") diff --git a/tests/core/test_state_authority.py b/tests/core/test_state_authority.py index a47edc0..864571d 100644 --- a/tests/core/test_state_authority.py +++ b/tests/core/test_state_authority.py @@ -120,9 +120,10 @@ def test_a_partial_accept_cannot_rebind_a_removed_obligation(make_project): def test_dropping_a_fresh_fail_obligation_stays_rejected_until_an_acceptance_rebinds_the_slot(make_project): from vkit.core import query - project = make_project({"ok.py": PASSES, "bad.py": DRIVER + 'report([("bad", False, "nope")])\n'}, + bad_driver = DRIVER + 'import pathlib\nreport([("bad", pathlib.Path("subject.py").read_text().strip() == "ok", "read")])\n' + project = make_project({"ok.py": PASSES, "bad.py": bad_driver, "subject.py": "nope\n"}, [scenario_check("ok", "ok.py", scenarios=["ok"], inputs=["ok.py"]), - scenario_check("bad", "bad.py", scenarios=["bad"], inputs=["bad.py"])]) + scenario_check("bad", "bad.py", scenarios=["bad"], inputs=["bad.py", "subject.py"])]) vkit(project, "check", "run", "--check", "ok", "--check", "bad") _shrink(project, [scenario_check("ok", "ok.py", scenarios=["ok"], inputs=["ok.py"])]) assert vkit(project, "accept", "--drop", "bad", "--yes")[0] == 0 @@ -131,10 +132,11 @@ def test_dropping_a_fresh_fail_obligation_stays_rejected_until_an_acceptance_reb assert query.status(query.open_context(project))["gate"]["verdict"] == "REJECTED" import json + (project / "subject.py").write_text("ok\n", encoding="utf-8") (project / "verification" / "manifest.json").write_text(json.dumps({ "schema_version": 3, "description": "test project", "checks": [scenario_check("ok", "ok.py", scenarios=["ok"], inputs=["ok.py"]), - scenario_check("bad", "ok.py", scenarios=["ok"], inputs=["ok.py"])]}), encoding="utf-8") + scenario_check("bad", "bad.py", scenarios=["bad"], inputs=["bad.py", "subject.py"])]}), encoding="utf-8") assert vkit(project, "accept", "--check", "bad", "--yes")[0] == 0 assert vkit(project, "check", "run", "--check", "bad")[0] == 0 assert query.status(query.open_context(project))["gate"]["verdict"] == "READY" @@ -321,7 +323,7 @@ def test_registered_bundles_actually_flip(): name = line[4:].split("(")[0] nodes[name] = f"{path.relative_to(root).as_posix()}::{name}" env = {"PATH": os.environ.get("PATH", ""), "SYSTEMROOT": os.environ.get("SYSTEMROOT", ""), - "PYTHONPATH": str(root / "tests"), "VKIT_FLIP_MUTANT": "1", + "PYTHONPATH": os.pathsep.join([str(root / "src"), str(root / "tests")]), "VKIT_FLIP_MUTANT": "1", "VKIT_ALLOW_YES": "1", "HOME": os.environ.get("HOME", ""), "TMPDIR": os.environ.get("TMPDIR", "")} for doubt in state.DOUBTS: mutant, honest = doubt.falsifier diff --git a/tests/core/test_tool_discovery.py b/tests/core/test_tool_discovery.py index 8c07f9e..3299632 100644 --- a/tests/core/test_tool_discovery.py +++ b/tests/core/test_tool_discovery.py @@ -7,8 +7,8 @@ from helpers import DRIVER, McpClient, scenario_check, vkit from vkit.mcp import Server -from vkit.runtime.paths import open_project -from vkit.console.settings import Settings, load_settings, save_settings +from vkit.runtime.paths import Project, open_project +from vkit.console.settings import Settings, SettingsFileError, load_settings, save_settings, settings_path def _project(make_project): @@ -197,12 +197,25 @@ def test_disabled_tool_and_wrappers_remain_when_all_categories_are_off(make_proj {"disabled_categories": ["unknown"]}, {"disabled_categories": ["safety", "safety"]}, {"mcp_categories": ["unknown"]}, {"mcp_categories": "safety"}, {"mcp_exposure": "auto"}, ]) -def test_invalid_visibility_fails_closed_without_rewriting(make_project, patch): +def test_invalid_visibility_fails_closed_without_rewriting(tmp_path, patch): + project = Project(tmp_path, tmp_path / ".git") + path = settings_path(project) + path.parent.mkdir(parents=True, exist_ok=True) + config = {"version": 1, "theme": "system", "sidebar_collapsed": False, + "refresh_seconds": 2, "history_limit": 50, **patch} + path.write_text(json.dumps(config), encoding="utf-8") + before = path.read_bytes() + with pytest.raises(SettingsFileError, match="invalid settings"): + load_settings(project) + assert path.read_bytes() == before + + +def test_mcp_serve_exits_2_on_invalid_settings(make_project): project = _project(make_project) path = project / ".git" / "vkit" / "config.json" path.parent.mkdir(parents=True, exist_ok=True) config = {"version": 1, "theme": "system", "sidebar_collapsed": False, - "refresh_seconds": 2, "history_limit": 50, **patch} + "refresh_seconds": 2, "history_limit": 50, "mcp_exposure": "auto"} path.write_text(json.dumps(config), encoding="utf-8") before = path.read_bytes() code, body = vkit(project, "mcp", "serve") @@ -211,8 +224,6 @@ def test_invalid_visibility_fails_closed_without_rewriting(make_project, patch): def test_saved_retired_categories_migrate_without_widening_agent_scope(make_project): - from vkit.console.settings import load_settings - project = _project(make_project) path = project / ".git/vkit/config.json" path.parent.mkdir(parents=True, exist_ok=True) diff --git a/tests/formal/test_formal_interface.py b/tests/formal/test_formal_interface.py index e4500e9..a4161d1 100644 --- a/tests/formal/test_formal_interface.py +++ b/tests/formal/test_formal_interface.py @@ -153,3 +153,20 @@ def test_formal_replay_runs_checker_again_and_rejects_changed_working_tree(forma with pytest.raises(ValueError, match="independently captured"): jobs.replay(ctx.project, ctx.require_manifest(), bundle, store=ctx.store) assert len(calls) == 2 + + +def test_formal_verify_rejects_drifted_checker_approval_without_reuse(formal_project, monkeypatch): + root, identity, calls = formal_project + ctx = query.open_context(root) + policy = ctx.require_manifest().require_component("allocation") + ctx.store.approve({policy.digest: {"kind": "formal_policy", "policy_sha256": policy.digest, + "package_sha256": policy.package.sha256, + "checker_sha256": canonical_digest(identity["semantic"]), "accepted_at": "now"}}) + drifted = {"semantic": {"profile": "test-checker", "tool_sha256": "c" * 64}, "paths": {}} + monkeypatch.setattr(verus, "resolve_execution", lambda _: drifted) + + with pytest.raises(ValueError, match="formal policy, package or checker changed"): + service.verify(ctx, {"schema_version": 2, "claim": policy.claim.to_json(), + "candidate": {"kind": "working_tree"}, "reuse": False}) + assert not ctx.store.runs() + assert not calls diff --git a/tests/formal/test_lifecycle.py b/tests/formal/test_lifecycle.py deleted file mode 100644 index 00ea7d4..0000000 --- a/tests/formal/test_lifecycle.py +++ /dev/null @@ -1,32 +0,0 @@ -from __future__ import annotations - -import importlib.util -from pathlib import Path - -spec = importlib.util.spec_from_file_location( - "check_lifecycle", Path(__file__).resolve().parents[2] / "formal/checks/check_lifecycle.py" -) -assert spec and spec.loader -lifecycle = importlib.util.module_from_spec(spec) -spec.loader.exec_module(lifecycle) -capture_runtime_observations = lifecycle.capture_runtime_observations - - -def test_runtime_observations_cover_contention_concurrent_attempts_and_recovery(tmp_path): - observed = capture_runtime_observations(tmp_path / "runtime") - attempts = observed["attempts"] - - assert observed["concurrent_same_job"]["shared_job_id"] == observed["job_id"] - assert len(set(observed["concurrent_same_job"]["run_ids"])) == 2 - raced = observed["cancel_completion_race"]["outcome"] - assert raced["result"] in {"PASS", "BLOCKED"} - if raced["result"] == "BLOCKED": - assert raced["reason"] == "cancelled" - assert len({attempt["run_id"] for attempt in attempts}) == 3 - assert [attempt["state"] for attempt in attempts] == ["done", "interrupted", "done"] - assert attempts[0]["job_id"] == observed["job_id"] - assert attempts[1].get("outcome") is None - assert attempts[2]["outcome"]["result"] == "PASS" - assert observed["published_before_worker_loss"] == observed["published_after_worker_loss"] - assert observed["published_before_worker_loss"]["run_id"] == attempts[0]["run_id"] - assert observed["final_published"]["run_id"] == attempts[2]["run_id"] diff --git a/tests/formal/test_protocol_trace.py b/tests/formal/test_protocol_trace.py new file mode 100644 index 0000000..036186b --- /dev/null +++ b/tests/formal/test_protocol_trace.py @@ -0,0 +1,160 @@ +from __future__ import annotations + +import importlib.util +import json +import os +import subprocess +import sys +import tempfile +from pathlib import Path +from typing import Any + +import pytest +from helpers import NO_WINDOW, ROOT +from hypothesis import settings +from hypothesis.stateful import RuleBasedStateMachine, initialize, rule + +from vkit.core import jobs +from vkit.core.manifest import parse_manifest +from vkit.core.store import Store +from vkit.core.trace import emit_trace +from vkit.runtime.paths import open_project + + +def _load_module(name: str, path: Path) -> Any: + spec = importlib.util.spec_from_file_location(name, path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _resolve_tlc() -> tuple[Any, Path, Path]: + tlc_env = _load_module("vkit_tlc_env_test", ROOT / "formal" / "checks" / "_tlc_env.py") + try: + java = tlc_env.resolve_java() + jar = tlc_env.resolve_tlc_jar() + except tlc_env.ToolchainUnavailable as exc: + pytest.skip(str(exc)) + checker = _load_module("vkit_check_protocol_trace", ROOT / "formal" / "checks" / "check_protocol_trace.py") + return checker, java, jar + + +def test_protocol_model_and_stateful_trace_validation(tmp_path: Path) -> None: + checker, java, jar = _resolve_tlc() + command = [ + sys.executable, + str(ROOT / "formal" / "checks" / "check_protocol_trace.py"), + "--output", + str(tmp_path / "protocol-trace"), + ] + done = subprocess.run( + command, + cwd=ROOT, + capture_output=True, + text=True, + timeout=240, + check=False, + **NO_WINDOW, + ) + assert done.returncode == 0, done.stdout + done.stderr + summary = json.loads(done.stdout) + assert summary["result"] == "PASS" + assert summary["clean_models"] == 1 + assert summary["mutants_caught"] == 4 + assert summary["clean_trace_accepted"] is True + assert summary["mutated_trace_rejected"] is True + + report = json.loads(Path(summary["report"]).read_text(encoding="utf-8")) + for case in report["tlc_cases"]: + if case["expected_counterexample"] is None: + assert case["result"] == "invariants_hold" + assert case["distinct_states"] > 0 + else: + assert case["result"] == "counterexample" + assert case["expected_counterexample"] in case["observed_counterexamples"] + + traces_validated: list[int] = [] + mutated_rejected: list[str] = [] + + class VKitProtocolStateMachine(RuleBasedStateMachine): + def __init__(self) -> None: + super().__init__() + self._tmp = tempfile.TemporaryDirectory(prefix="vkit-hyp-") + self._work = Path(self._tmp.name) + self._trace_path = self._work / "trace.ndjson" + self._prev_env = os.environ.get("VKIT_TRACE_LOG") + os.environ["VKIT_TRACE_LOG"] = str(self._trace_path) + self._repo = checker.init_trace_fixture_repo(self._work / "repo", slow_barrier=False) + self._project = open_project(self._repo) + self._manifest = parse_manifest(self._project) + self._store = Store.of(self._project) + self._hook = checker.load_hook_module() + self._rev = 1 + self._approved = False + + @initialize() + def start_session(self) -> None: + self._hook.handle("SessionStart", {"session_id": "hyp-s1"}, str(self._repo)) + emit_trace("gate_check", verdict=checker.gate_verdict(self._project, self._manifest, self._store)) + + @rule() + def accept_check(self) -> None: + if not self._approved: + checker.approve_check(self._manifest, self._store, "app-check") + self._approved = True + emit_trace("gate_check", verdict=checker.gate_verdict(self._project, self._manifest, self._store)) + + @rule() + def edit_source(self) -> None: + self._rev += 1 + (self._repo / "app.py").write_text(f"VALUE = {self._rev}\n", encoding="utf-8") + emit_trace("source_edit", rev=self._rev) + emit_trace("gate_check", verdict=checker.gate_verdict(self._project, self._manifest, self._store)) + + @rule() + def run_check(self) -> None: + submitted = jobs.submit(self._project, self._manifest, "app-check", store=self._store) + jobs.wait(self._store, submitted["run_id"], 30) + emit_trace("gate_check", verdict=checker.gate_verdict(self._project, self._manifest, self._store)) + + @rule() + def stop_hook(self) -> None: + self._hook.handle("Stop", {"session_id": "hyp-s1"}, str(self._repo)) + + @rule() + def subagent_stop_bypass(self) -> None: + self._hook.handle("SubagentStop", {"session_id": "hyp-s1", "stop_hook_active": True}, str(self._repo)) + + def teardown(self) -> None: + try: + if self._prev_env is None: + os.environ.pop("VKIT_TRACE_LOG", None) + else: + os.environ["VKIT_TRACE_LOG"] = self._prev_env + if self._trace_path.is_file(): + res = checker.validate_ndjson_trace( + self._trace_path, self._work / "tlc-clean", java, jar, expect_valid=True + ) + assert res["accepted"] is True + traces_validated.append(res["steps"]) + if not mutated_rejected: + mutated_path = checker.mutate_trace_ndjson( + self._trace_path, self._work / "mutated.ndjson" + ) + mut_res = checker.validate_ndjson_trace( + mutated_path, self._work / "tlc-mutated", java, jar, expect_valid=False + ) + assert mut_res["accepted"] is False + mutated_rejected.append(mut_res["reason"]) + finally: + self._tmp.cleanup() + + VKitProtocolStateMachine.TestCase.settings = settings( + max_examples=6, + stateful_step_count=6, + deadline=None, + ) + VKitProtocolStateMachine.TestCase().runTest() + assert len(traces_validated) >= 6 + assert len(mutated_rejected) == 1 diff --git a/tests/formal/test_verifier_interpreters_formal.py b/tests/formal/test_verifier_interpreters_formal.py index 313bde3..1d64d3d 100644 --- a/tests/formal/test_verifier_interpreters_formal.py +++ b/tests/formal/test_verifier_interpreters_formal.py @@ -1,4 +1,4 @@ -"""Pytest entrypoint for the Lean and TLC report interpreter formal checker.""" +"""Pytest entrypoint for the verifier report interpreter formal checker.""" from __future__ import annotations from formal.checks.check_verifier_interpreters import run @@ -9,22 +9,34 @@ def test_verifier_interpreters_exhaustive_formal_check(): assert summary["ok"] is True, summary lean = summary["lean"] - assert lean["reviewed_tuples"] == 864 - assert lean["comparator_tuples"] == 4 - assert lean["total_tuples"] == 868 + assert lean["reviewed_tuples"] == 1152 + assert lean["comparator_tuples"] == 24 + assert lean["total_tuples"] == 1176 assert lean["pass_tuples"] == 2 assert lean["logical_trust_checks"] == 3 assert lean["oracle_mismatches"] == 0 assert lean["safety_violations"] == 0 tlc = summary["tlc"] - assert tlc["total_tuples"] == 384 + assert tlc["total_tuples"] == 960 assert tlc["pass_tuples"] == 1 assert tlc["oracle_mismatches"] == 0 assert tlc["safety_violations"] == 0 + prop = summary["property"] + assert prop["total_tuples"] == 144 + assert prop["pass_tuples"] == 8 + assert prop["oracle_mismatches"] == 0 + assert prop["safety_violations"] == 0 + + node = summary["node"] + assert node["total_tuples"] == 24 + assert node["pass_tuples"] == 2 + assert node["oracle_mismatches"] == 0 + assert node["safety_violations"] == 0 + mutants = summary["negative_controls"] - assert len(mutants) == 4 + assert len(mutants) == 10 assert summary["all_mutants_caught"] is True for mutant in mutants: assert mutant["caught"] is True, mutant diff --git a/tests/helpers.py b/tests/helpers.py index a292634..845edfb 100644 --- a/tests/helpers.py +++ b/tests/helpers.py @@ -18,6 +18,23 @@ def git(cwd: Path, *args: str) -> None: cwd=cwd, check=True, capture_output=True, **NO_WINDOW) +def git_head(cwd: Path) -> str: + return subprocess.run( + ["git", "rev-parse", "HEAD"], + cwd=cwd, check=True, capture_output=True, text=True, **NO_WINDOW, + ).stdout.strip() + + +def write_manifest( + project: Path, checks: list[dict[str, Any]], *, description: str = "test project", **extra: Any +) -> Path: + path = project / "verification" / "manifest.json" + path.parent.mkdir(parents=True, exist_ok=True) + payload = {"schema_version": 3, "description": description, "checks": checks, **extra} + path.write_text(json.dumps(payload, indent=2), encoding="utf-8") + return path + + def vkit_argv(project: Path, *args: str) -> list[str]: return [sys.executable, "-m", "vkit.cli", *args, "--project", str(project), "--json"] @@ -56,6 +73,7 @@ def report(results): {"id": i, "result": "PASS" if ok else "FAIL", "observation": o} for i, ok, o in results]}, handle) ''') +PASSES = DRIVER + 'report([("ok", True, "printed ok")])\n' class McpClient: diff --git a/tests/rust/test_kani_result.py b/tests/rust/test_kani_result.py index e0429fd..a5a1860 100644 --- a/tests/rust/test_kani_result.py +++ b/tests/rust/test_kani_result.py @@ -175,38 +175,6 @@ def test_constructed_self_consistent_export_does_not_claim_source_proof() -> Non } -def test_mutated_exit_codes_cannot_change_transcript_classification() -> None: - success, harness = _fixture("preservation") - rejection, _ = _fixture("regression") - assert _result(success, harness, 1)["kind"] == "unknown" - assert _result(rejection, harness, 0)["kind"] == "unknown" - assert _result(success, harness, True)["kind"] == "unknown" - - -def test_constructed_later_unreachable_assertion_keeps_named_rejection() -> None: - raw, harness = _fixture("regression") - exported = json.loads(raw) - checks = exported["verification_results"]["results"][0]["checks"] - standing = next( - check - for check in checks - if check["description"] == '"candidate_standing_intent"' - ) - relation = next( - check for check in checks if check["description"] == '"relational_policy"' - ) - standing["status"] = "Failure" - relation["status"] = "Unreachable" - details = exported["property_details"][0]["property_details"] - details.update(passed=4, failed=1, unreachable=1) - assert _result(json.dumps(exported).encode(), harness, 1) == { - "kind": "proof_rejected", - "reason": "named_candidate_standing_intent_assertion_failed", - "source_proof": False, - "approval_authority": False, - } - - @pytest.mark.parametrize( "mutated_line", ["014", "0", "\u0661\u0664"], diff --git a/tests/rust/test_rust_claim.py b/tests/rust/test_rust_claim.py index 9aea9e7..45deac6 100644 --- a/tests/rust/test_rust_claim.py +++ b/tests/rust/test_rust_claim.py @@ -33,8 +33,9 @@ FIXTURES = Path(__file__).parents[1] / "fixtures" / "kani-results" -def _delegated_inputs(tmp_path): - root, target, request = _fixture(tmp_path) +@pytest.fixture(scope="module") +def delegated_inputs(tmp_path_factory): + root, target, request = _fixture(tmp_path_factory.mktemp("delegated")) ordinary = prepare_rust_relational(open_project(root), request, trusted_target_oid=target) intent = ordinary.bound.intent domain = intent.contract.domain @@ -60,11 +61,6 @@ def _delegated_inputs(tmp_path): return bound, ordinary.base, ordinary.candidate -def _delegated_program(tmp_path, purpose="candidate_claim_satisfaction"): - bound, base, candidate = _delegated_inputs(tmp_path) - return prepare_rust_claim_program(bound, base, candidate, purpose=purpose) - - def _qualified_fixture(name: str, harness: bytes) -> tuple[bytes, int]: raw = json.loads((FIXTURES / name / "kani-results.json").read_bytes()) lines = harness.decode("utf-8").splitlines() @@ -88,8 +84,8 @@ def _qualified_fixture(name: str, harness: bytes) -> tuple[bytes, int]: return json.dumps(raw).encode(), 1 if name == "regression" else 0 -def test_claim_and_control_programs_have_distinct_bound_harnesses(tmp_path): - bound, base, candidate = _delegated_inputs(tmp_path) +def test_claim_and_control_programs_have_distinct_bound_harnesses(delegated_inputs): + bound, base, candidate = delegated_inputs satisfaction = prepare_rust_claim_program( bound, base, candidate, purpose="candidate_claim_satisfaction", ) @@ -139,9 +135,10 @@ def test_claim_and_control_programs_have_distinct_bound_harnesses(tmp_path): ], ) def test_claim_harnesses_remain_inside_strict_kani_decoder( - tmp_path, fixture, purpose, expected, + delegated_inputs, fixture, purpose, expected, ): - program = _delegated_program(tmp_path, purpose) + bound, base, candidate = delegated_inputs + program = prepare_rust_claim_program(bound, base, candidate, purpose=purpose) raw, exit_code = _qualified_fixture(fixture, program.harness) outcome = classify_kani_result(raw, exit_code=exit_code, harness=program.harness) @@ -162,8 +159,8 @@ def test_claim_factory_rejects_unbound_ordinary_program(tmp_path): ) -def test_claim_and_relational_executor_entry_points_reject_cross_purpose_programs(tmp_path): - bound, base, candidate = _delegated_inputs(tmp_path) +def test_claim_and_relational_executor_entry_points_reject_cross_purpose_programs(delegated_inputs, tmp_path): + bound, base, candidate = delegated_inputs satisfaction = prepare_rust_claim_program( bound, base, candidate, purpose="candidate_claim_satisfaction", ) @@ -183,10 +180,10 @@ def test_claim_and_relational_executor_entry_points_reject_cross_purpose_program ) -def test_claim_factory_does_not_build_relational_harness(tmp_path, monkeypatch): +def test_claim_factory_does_not_build_relational_harness(delegated_inputs, monkeypatch): from vkit.rust import rust_relational - bound, base, candidate = _delegated_inputs(tmp_path) + bound, base, candidate = delegated_inputs def fail_if_called(*args, **kwargs): raise AssertionError("relational _harness should not be called for claim programs") diff --git a/tests/rust/test_rust_source.py b/tests/rust/test_rust_source.py index f283dd7..1e8ca4b 100644 --- a/tests/rust/test_rust_source.py +++ b/tests/rust/test_rust_source.py @@ -9,6 +9,7 @@ from vkit.rust.rust_source import ( RustSourceProfile, UnsupportedRustSource, + _admit_rust_source, admit_rust_source, ) @@ -18,7 +19,7 @@ def _binding(symbol: str = "convert") -> U32Binding: def _admit(source: str, symbol: str = "convert") -> RustSourceProfile: - return admit_rust_source(source.encode("utf-8"), _binding(symbol)) + return _admit_rust_source(source.encode("utf-8"), _binding(symbol)) @pytest.mark.parametrize( @@ -177,12 +178,10 @@ def test_parser_process_faults_never_admit_source(monkeypatch, child, reason): monkeypatch.setattr(rust_source, "_PARSER_CHILD", child) monkeypatch.setattr(rust_source, "_PARSER_TIMEOUT_SECONDS", 1) with pytest.raises(UnsupportedRustSource, match=reason): - _admit("pub fn convert(value: u32) -> u32 { value }") + admit_rust_source(b"pub fn convert(value: u32) -> u32 { value }", _binding()) def test_oversized_digit_integer_literal_raises_unsupported_not_value_error(): - from vkit.rust.rust_source import _admit_rust_source - huge = ("pub fn convert(value: u32) -> u32 { " + "1" + "0" * 5000 + " }").encode("utf-8") with pytest.raises(UnsupportedRustSource, match="u32 literals"): _admit_rust_source(huge, _binding()) @@ -191,8 +190,6 @@ def test_oversized_digit_integer_literal_raises_unsupported_not_value_error(): def test_empty_block_comment_is_admitted_while_doc_comments_are_rejected(): - from vkit.rust.rust_source import _admit_rust_source - profile = _admit_rust_source(b"/**/ pub fn convert(value: u32) -> u32 { value }", _binding()) assert profile.source_sha256 for comment in ("/** doc */", "/*! inner */", "/// doc\n", "//! inner\n"): @@ -205,7 +202,6 @@ def test_empty_block_comment_is_admitted_while_doc_comments_are_rejected(): def test_property_u32_decimal_literal_admission(): from hypothesis import given, settings, strategies as st - from vkit.rust.rust_source import _admit_rust_source binding = _binding() diff --git a/tests/verifiers/test_verifiers_regressions.py b/tests/verifiers/test_verifiers_regressions.py index fab0878..f399794 100644 --- a/tests/verifiers/test_verifiers_regressions.py +++ b/tests/verifiers/test_verifiers_regressions.py @@ -1,5 +1,6 @@ from __future__ import annotations +import hashlib import json import subprocess from pathlib import Path @@ -10,7 +11,9 @@ from vkit.core.outcome import Blocked, BlockedReason from vkit.verifiers import ( comparator_runner, + dispatch, lean_adapter, + lean_runner, node_adapter, property_adapter, pytest_adapter, @@ -23,11 +26,13 @@ from vkit.verifiers.spec import ( DomainBounds, FingerprintSpec, + HypothesisSettings, LeanCheck, LeanProfile, ModuleRef, NodeTestCheck, PinnedRunner, + PropertyCheck, TlcCheck, ToolchainRef, ) @@ -106,7 +111,6 @@ def test_tlc_witness_distinguishes_int_and_bool_in_actions(): } reduced = tlc_witness.without_internal_state(doc2, 2) assert reduced is not None - # s1 -> s3 did not exist in original actions (s2 had True, not 1), so fallback descriptor is used assert reduced["counterexample"]["action"][0][1] == {"name": "Next"} @@ -285,3 +289,238 @@ def fail_run(*_args, **_kwargs): assert replayed is None assert "java missing" in reason assert not (tmp_path / "tlc-replay-input-7.json").exists() + + +def test_node_reporter_source_and_anchored_selectors(tmp_path: Path): + assert " # TODO " in node_adapter.REPORTER_SOURCE + assert ".slice(0, 4096)" in node_adapter.REPORTER_SOURCE + + files, pattern = node_adapter.argv_selectors(("a.test.js::foo", "b.test.js::bar+1")) + assert files == ("a.test.js", "b.test.js") + assert pattern == r"^(?:foo|bar\+1)$" + + bad_check = _node_check(tmp_path, ("bare_name_without_file",)) + with pytest.raises(ValueError, match="required_test_absent"): + dispatch.argv_for(bad_check, tmp_path / "run", None) + + +def test_property_adapter_enforces_independent_bounds_and_replay_settings(tmp_path: Path): + check = PropertyCheck( + id="prop", + cwd=tmp_path, + timeout_seconds=60, + artifact_name="pytest.json", + required_tests=("t.py::a", "t.py::b"), + runner=PinnedRunner("pytest", ()), + report_format="json", + expect_report_version=1, + generator=HypothesisSettings(max_examples=50, stateful_step_count=10), + ) + report = { + "version": 1, + "complete": True, + "exit_code": 0, + "tests": [ + { + "nodeid": "t.py::a", + "outcome": "passed", + "duration": 0.1, + "message": "", + "generator": { + "max_examples": 50, + "stateful_step_count": 20, + "deadline": None, + "suppress_health_check": [], + "database": None, + }, + }, + { + "nodeid": "t.py::b", + "outcome": "passed", + "duration": 0.1, + "message": "", + "generator": { + "max_examples": 100, + "stateful_step_count": 4, + "deadline": None, + "suppress_health_check": [], + "database": None, + }, + }, + ], + } + blocked = property_adapter.interpret(json.dumps(report).encode("utf-8"), check) + assert isinstance(blocked, Blocked) + assert blocked.detail.startswith("generator_weakened:") + + bad_hc = SimpleNamespace(getoption=lambda *_a, **_kw: json.dumps({ + "max_examples": 10, + "suppress_health_check": ["not_a_real_check"], + })) + with pytest.raises(property_adapter.SettingsRefused, match="unknown Hypothesis HealthCheck"): + property_adapter.pytest_configure(bad_hc) + + from hypothesis import core, settings + + prev_seed = core.global_force_seed + db_dir = str(tmp_path / "hyp-db") + cfg = SimpleNamespace(getoption=lambda *_a, **_kw: json.dumps({ + "max_examples": 25, + "replay_database": db_dir, + "replay_seed": 12345, + })) + try: + property_adapter.pytest_configure(cfg) + assert core.global_force_seed == 12345 + loaded = settings.get_profile(property_adapter.VKIT_PROFILE) + assert loaded.max_examples == 25 + assert loaded.database is not None + finally: + core.global_force_seed = prev_seed + + +@pytest.mark.parametrize( + ("overrides", "expected_token"), + [ + ({"version": 2}, "report_version"), + ({"challenge_sha256": "0" * 64}, "challenge_altered"), + ({"exit_code": 1}, "report_malformed"), + ], +) +def test_lean_comparator_enforces_version_digest_and_exit_code( + tmp_path: Path, overrides: dict, expected_token: str +): + digest = "a" * 64 + check = LeanCheck( + id="lean-comp", + cwd=tmp_path, + timeout_seconds=60, + artifact_name="comp.json", + challenge=ModuleRef("Challenge", "Challenge.lean"), + solution=ModuleRef("Solution", "Solution.lean"), + challenge_sha256=digest, + theorems=(TheoremObligation("t1", "Challenge"),), + profile=LeanProfile.UNREVIEWED, + permitted_axioms=(), + toolchain=ToolchainRef("lean", version="4.10.0", comparator="comparator"), + ) + payload = { + "version": 1, + "status": "accepted", + "challenge_sha256": digest, + "exit_code": 0, + "sandbox": "landrun", + **overrides, + } + outcome = lean_adapter.interpret(json.dumps(payload).encode("utf-8"), check) + assert isinstance(outcome, Blocked) + assert outcome.detail.startswith(f"{expected_token}:") + + +def test_lean_first_error_blank_data_argv_guard_and_hierarchical_olean(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + assert lean_adapter._first_error([{"exit_code": 1, "messages": [{"severity": "error", "data": " "}]}]) == "exit 1" + + bad_check = LeanCheck( + id="lean-unrev", + cwd=tmp_path, + timeout_seconds=60, + artifact_name="comp.json", + challenge=ModuleRef("Challenge", "Challenge.lean"), + theorems=(TheoremObligation("t1", "Challenge"),), + profile=LeanProfile.UNREVIEWED, + permitted_axioms=(), + toolchain=ToolchainRef("lean", version="4.10.0"), + ) + with pytest.raises(ValueError, match="solution module"): + lean_adapter.argv_for(bad_check, tmp_path / "run", None) + + src = tmp_path / "Bar.lean" + src.write_text("theorem t1 : True := trivial\n", encoding="utf-8") + seen_oleans: list[str] = [] + + def fake_run(argv, cwd, env=None): + if "-o" in argv: + olean_path = Path(argv[argv.index("-o") + 1]) + seen_oleans.append(olean_path.as_posix()) + olean_path.write_bytes(b"olean-bytes") + return {"argv": list(argv), "exit_code": 0, "stdout": "Lean (version 4.10.0)", "messages": [], "stderr": ""} + + monkeypatch.setattr(lean_runner, "_run", fake_run) + report_path = tmp_path / "run" / "lean.json" + lean_runner.main([ + "--lean", "lean", + "--source", str(src), + "--module", "Foo.Bar", + "--theorems", "t1", + "--profile", "reviewed_proof_sources", + "--run-dir", str(tmp_path / "run"), + "--report", str(report_path), + ]) + assert any(path.endswith("olean-1/Foo/Bar.olean") for path in seen_oleans) + assert any(path.endswith("olean-2/Foo/Bar.olean") for path in seen_oleans) + + +def test_tlc_comments_cardinality_truncation_and_pure_config(tmp_path: Path): + cfg = ( + "\\* line comment with (* unclosed block start\n" + "CONSTANT A = 5..2\n" + "CONSTANT B = {x, y}\n" + "CONSTANT C = {unclosed\n" + "INVARIANT Inv\n" + ) + assert tlc_adapter._constants(cfg) == {"A": 0, "B": 2, "C": -1} + assert tlc_adapter._checked_properties(cfg) == ("Inv",) + + big = "HEAD_BANNER\n" + ("x" * 50000) + "\nModel checking completed. No error has been found.\n" + truncated = tlc_runner._truncate(big) + assert len(truncated) <= tlc_runner.OUTPUT_LIMIT + assert truncated.startswith("HEAD_BANNER\n") + assert truncated.endswith("Model checking completed. No error has been found.\n") + + valid_cfg = "INVARIANT Inv\n" + report = { + "version": tlc_adapter.REPORT_VERSION, + "complete": True, + "tool": "tlc", + "tool_version": "TLC2 Version 2.18", + "model": "Model", + "model_path": "Model.tla", + "config": "Model.cfg", + "jar_sha256": "a" * 64, + "fingerprint": {"constants_from_config": True, "checksum_states": False, "workers": 1}, + "source_identity": { + "model_sha256": "b" * 64, + "config_sha256": hashlib.sha256(valid_cfg.encode("utf-8")).hexdigest(), + }, + "exit_code": 0, + "stdout": ( + "Model checking completed. No error has been found.\n" + "5 states generated, 2 distinct states found, 0 states left on queue.\n" + ), + "stderr": "", + "trace_json_supported": True, + "witness_validation": None, + } + res = tlc_adapter.interpret(json.dumps(report).encode("utf-8"), _tlc_check(tmp_path), config_text=valid_cfg) + assert isinstance(res, tlc_adapter.AdapterResult) + + +def test_dispatch_rejects_duplicate_scenarios_and_static_handles_null_rule_id(): + dup_payload = json.dumps({ + "schema_version": 1, + "scenarios": [ + {"id": "s1", "result": "PASS", "observation": "ok"}, + {"id": "s1", "result": "FAIL", "observation": "bad"}, + ], + }).encode("utf-8") + reading = dispatch.read_scenarios(dup_payload, ("s1",)) + assert reading.problem is not None + assert reading.problem.reason == BlockedReason.ARTIFACT_MALFORMED + assert "duplicate scenario" in reading.problem.detail + + sarif = json.dumps({ + "runs": [{"results": [{"ruleId": None, "message": {"text": "warn"}}]}], + }).encode("utf-8") + static_reading = static_adapter.read(sarif) + assert isinstance(static_reading, static_adapter.StaticReading) + assert static_reading.findings[0].rule == "?" diff --git a/verification/manifest.json b/verification/manifest.json index 96c7365..da02ab8 100644 --- a/verification/manifest.json +++ b/verification/manifest.json @@ -215,7 +215,7 @@ "tests/cli/test_plugin.py::test_formal_stop_observes_required_policy_and_acceptance[True-True-True]", "tests/cli/test_plugin.py::test_formal_stop_observes_required_policy_and_acceptance[False-True-False]", "tests/cli/test_plugin.py::test_formal_stop_observes_required_policy_and_acceptance[True-False-True]", - "tests/formal/test_lifecycle.py::test_runtime_observations_cover_contention_concurrent_attempts_and_recovery" + "tests/formal/test_protocol_trace.py::test_protocol_model_and_stateful_trace_validation" ], "runner": { "executable": "{{python}}", @@ -244,7 +244,7 @@ "src", "schemas", "tests", - "formal/checks/check_lifecycle.py", + "formal/checks/check_protocol_trace.py", "plugin", "pyproject.toml" ], @@ -252,7 +252,7 @@ "paths": [ "src", "tests", - "formal/checks/check_lifecycle.py" + "formal/checks/check_protocol_trace.py" ], "digest": null }, @@ -285,41 +285,38 @@ { "id": "lifecycle-model", "kind": "tlc", - "description": "Exhaustively checks attempt identity, cancellation, terminal outcomes, worker loss, recovery, and bounded retry safety.", + "description": "Exhaustively checks store, runner, gate, and stop-hook protocol invariants in VKitProtocol.tla.", "cwd": ".", "timeout_seconds": 120, "artifact": "checker-report.json", "inputs": [ - "formal/models/lifecycle/Attempts.tla", - "formal/models/lifecycle/Attempts.cfg" + "formal/models/VKitProtocol.tla", + "formal/models/VKitProtocol.cfg" ], "subject": { "paths": [ - "formal/models/lifecycle/Attempts.tla", - "formal/models/lifecycle/Attempts.cfg" + "formal/models/VKitProtocol.tla", + "formal/models/VKitProtocol.cfg" ], "digest": null }, "claim_id": "lifecycle-model", "model": { - "module": "Attempts", - "path": "formal/models/lifecycle/Attempts.tla" + "module": "VKitProtocol", + "path": "formal/models/VKitProtocol.tla" }, - "config": "formal/models/lifecycle/Attempts.cfg", + "config": "formal/models/VKitProtocol.cfg", "properties": [ "TypeOK", - "NoFalsePass", - "TerminalHasResult", - "InterruptedHasNoResult", - "IdentityPinned", - "PublishedAttemptComplete" + "CancelledQueuedNeverStarts", + "SourceDriftInvalidatesFreshPass", + "CrashLeavesNoOrphanContainer", + "GateNeverReadyWithStaleOrUnapproved", + "StopBlockedUnlessReadyOrBypass", + "BypassAlwaysRecordedInTelemetry" ], "bounds": { - "ExpectedJob": 1, - "ExpectedSource": 1, - "ForeignJob": 1, - "ForeignSource": 1, - "InjectFalsePass": 1 + "Mutant": 1 }, "fingerprint": { "constants_from_config": true, @@ -328,8 +325,8 @@ }, "toolchain": { "tool": "tlc", - "version": "2026.11.19.180144", - "jar_sha256": "fdffef247f563ef6edbfd44958d2a82db79e7564e07cb673262d896353fa6713" + "version": "2026.12.01.201816", + "jar_sha256": "71c10e61d3ffe3b55549a9915142f5e2da106449d83119ee5418524ac719aae7" }, "prerequisites": [ { @@ -353,6 +350,8 @@ "sarif", "--output-file", "{{run_dir}}/ruff.sarif", + "--exclude", + "src/vkit/kernel/_dafny_gen", "src", "tests", "scripts"