From d1dd0aa4f0de187ca7c55ab20b32894b1acb0200 Mon Sep 17 00:00:00 2001 From: FyreMael Date: Sat, 23 May 2026 04:15:31 -0700 Subject: [PATCH] Add local visual proof console --- README.md | 9 + docs/CONSOLE.md | 31 ++ pyproject.toml | 6 + python/laxforge_laxcert/console_server.py | 527 ++++++++++++++++++ .../console_static/console.css | 392 +++++++++++++ .../console_static/console.js | 190 +++++++ .../console_static/index.html | 96 ++++ tests/test_console_server.py | 75 +++ 8 files changed, 1326 insertions(+) create mode 100644 docs/CONSOLE.md create mode 100644 python/laxforge_laxcert/console_server.py create mode 100644 python/laxforge_laxcert/console_static/console.css create mode 100644 python/laxforge_laxcert/console_static/console.js create mode 100644 python/laxforge_laxcert/console_static/index.html create mode 100644 tests/test_console_server.py diff --git a/README.md b/README.md index 781b006..72679f3 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ This pack contains: - `docs/AETHER_LEDGER.md` — proof provenance and governance records. - `docs/ROADMAP.md` — build phases and milestones. - `docs/SPEC_TRACEABILITY.md` — ordered section 13 gap register and closeout evidence. +- `docs/CONSOLE.md` — local visual console for candidates, artifacts, job queue, and operator commands. - `schemas/laxcert_candidate.schema.json` — JSON schema for emitted candidate certificates. - `python/laxforge_laxcert/emitter_contract.py` — typed Python-side contract sketch. - `lean/` — Lean project skeleton and illustrative module boundaries. @@ -71,6 +72,14 @@ python -m laxforge_laxcert.emitter_contract artifacts/LaxforgeAKNSD2TransportZer python -m laxforge_laxcert.emitter_contract candidates/false_wrong_sign.json --repo-root . --expect-failure ``` +Local visual console: + +```bash +python -m laxforge_laxcert.console_server --repo-root . +``` + +Open `http://127.0.0.1:8765` to inspect candidates, proof artifacts, the command queue, Lake/Pytest runs, and certifier results. + For Lean/mathlib dependency refreshes, prefer WSL native storage rather than building from `/mnt/`. A reliable workflow is: diff --git a/docs/CONSOLE.md b/docs/CONSOLE.md new file mode 100644 index 0000000..507bdd2 --- /dev/null +++ b/docs/CONSOLE.md @@ -0,0 +1,31 @@ +# LAXCERT Visual Console + +The LAXCERT console is a local browser UI for inspecting candidate inputs, proof artifacts, job history, and explicit proof commands. It is intentionally repository-local and runs on `127.0.0.1` by default. + +Start it from the repository root: + +```bash +python -m laxforge_laxcert.console_server --repo-root . +``` + +or, after installing the package: + +```bash +laxcert-console --repo-root . +``` + +Then open: + +```text +http://127.0.0.1:8765 +``` + +The console currently exposes these operator commands: + +- `Validate Schema` resolves an internal candidate JSON, external LAXFORGE artifact directory, or manifest and runs schema plus semantic validation. +- `Certify Candidate` normalizes the candidate, emits Lean, runs Lake, and writes `artifacts//proof-status.json`. +- `Certify Expected Failure` passes only when a candidate is rejected or fails to prove. +- `Lake Build` runs `lake -R build LaxCert`. +- `Pytest` runs the Python regression suite. + +The UI reads candidate JSON from `candidates/*.json` and committed artifact inputs from `artifacts/*/candidate.json`. The command input accepts repository-relative paths such as `candidates/toy_lax_zero.json` and absolute paths to externally produced LAXFORGE artifact directories. diff --git a/pyproject.toml b/pyproject.toml index b71f80e..1200ced 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -11,6 +11,9 @@ dependencies = [ "jsonschema>=4.22", ] +[project.scripts] +laxcert-console = "laxforge_laxcert.console_server:main" + [project.optional-dependencies] test = [ "pytest>=8", @@ -19,5 +22,8 @@ test = [ [tool.setuptools.packages.find] where = ["python"] +[tool.setuptools.package-data] +laxforge_laxcert = ["console_static/*"] + [tool.pytest.ini_options] testpaths = ["tests"] diff --git a/python/laxforge_laxcert/console_server.py b/python/laxforge_laxcert/console_server.py new file mode 100644 index 0000000..e77e618 --- /dev/null +++ b/python/laxforge_laxcert/console_server.py @@ -0,0 +1,527 @@ +"""Local visual console backend for LAXCERT candidates, artifacts, and proof jobs.""" + +from __future__ import annotations + +from dataclasses import asdict, dataclass, field +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from importlib.resources import files +from pathlib import Path +from queue import Queue +from threading import Lock, Thread +from typing import Any +from urllib.parse import parse_qs, urlparse +import argparse +import json +import mimetypes +import os +import subprocess +import uuid + +from laxforge_laxcert.emitter_contract import ( + certify_candidate_input, + lean_toolchain, + load_candidate, + mathlib_revision, + matrix_bound, + resolve_candidate_input, + run_lake_build, + utc_timestamp, + validate_candidate, +) + + +COMMANDS: dict[str, dict[str, Any]] = { + "validate_candidate": { + "label": "Validate Schema", + "description": "Resolve a candidate input and run schema plus semantic validation.", + "requires_path": True, + "default_path": "candidates/toy_lax_zero.json", + }, + "certify_candidate": { + "label": "Certify Candidate", + "description": "Normalize, emit Lean, run Lake, and write proof-status artifacts.", + "requires_path": True, + "default_path": "candidates/toy_lax_zero.json", + }, + "certify_expected_failure": { + "label": "Certify Expected Failure", + "description": "Run the certifier and pass only when the candidate does not prove.", + "requires_path": True, + "default_path": "candidates/false_wrong_sign.json", + }, + "lake_build": { + "label": "Lake Build", + "description": "Build the Lean core with lake -R build LaxCert.", + "requires_path": False, + }, + "pytest": { + "label": "Pytest", + "description": "Run the Python regression suite.", + "requires_path": False, + }, +} + + +@dataclass +class ConsoleJob: + id: str + command: str + label: str + input_path: str | None + status: str = "queued" + queued_at: str = field(default_factory=utc_timestamp) + started_at: str | None = None + finished_at: str | None = None + exit_code: int | None = None + log: list[str] = field(default_factory=list) + result: dict[str, Any] | None = None + + +class ConsoleBackend: + """Repository-aware service layer used by both the HTTP UI and tests.""" + + def __init__(self, repo_root: Path, *, start_worker: bool = True) -> None: + self.repo_root = repo_root.resolve() + self._jobs: dict[str, ConsoleJob] = {} + self._lock = Lock() + self._queue: Queue[str | None] = Queue() + self._worker: Thread | None = None + if start_worker: + self._worker = Thread(target=self._worker_loop, daemon=True) + self._worker.start() + + def close(self) -> None: + if self._worker is not None: + self._queue.put(None) + self._worker.join(timeout=2) + self._worker = None + + def command_specs(self) -> list[dict[str, Any]]: + return [{"name": name, **spec} for name, spec in COMMANDS.items()] + + def summary(self) -> dict[str, Any]: + candidates = self.list_candidates() + artifacts = self.list_artifacts() + status_counts: dict[str, int] = {} + for artifact in artifacts: + status = str(artifact.get("status", "unknown")) + status_counts[status] = status_counts.get(status, 0) + 1 + + return { + "repo_root": str(self.repo_root), + "lean_toolchain": self._safe_toolchain(), + "mathlib_revision": self._safe_mathlib_revision(), + "candidate_count": len(candidates), + "artifact_count": len(artifacts), + "status_counts": status_counts, + "commands": self.command_specs(), + "candidates": candidates, + "artifacts": artifacts, + "jobs": self.list_jobs(), + } + + def list_candidates(self) -> list[dict[str, Any]]: + paths: list[tuple[str, Path]] = [] + paths.extend(("candidate", path) for path in sorted((self.repo_root / "candidates").glob("*.json"))) + paths.extend(("artifact", path) for path in sorted((self.repo_root / "artifacts").glob("*/candidate.json"))) + + candidates: list[dict[str, Any]] = [] + seen: set[Path] = set() + for source_kind, path in paths: + resolved = path.resolve() + if resolved in seen: + continue + seen.add(resolved) + candidates.append(self._candidate_summary(path, source_kind)) + return sorted(candidates, key=lambda item: (str(item.get("candidate_id", "")), str(item.get("path", "")))) + + def list_artifacts(self) -> list[dict[str, Any]]: + artifacts: list[dict[str, Any]] = [] + for status_path in sorted((self.repo_root / "artifacts").glob("*/proof-status.json")): + try: + status_doc = json.loads(status_path.read_text(encoding="utf-8")) + artifact_dir = status_path.parent + artifacts.append( + { + "candidate_id": status_doc.get("candidate_id", artifact_dir.name), + "status": status_doc.get("status", "unknown"), + "event_type": status_doc.get("event_type"), + "claim_type": status_doc.get("claim_type"), + "timestamp_utc": status_doc.get("timestamp_utc"), + "lean_theorem": status_doc.get("lean_theorem"), + "candidate_hash": status_doc.get("candidate_hash"), + "generated_lean_hash": status_doc.get("generated_lean_hash"), + "build_log_uri": status_doc.get("build_log_uri"), + "residual_witness": status_doc.get("residual_witness"), + "candidate_source": status_doc.get("candidate_source"), + "path": self._display_path(artifact_dir), + } + ) + except Exception as exc: + artifacts.append( + { + "candidate_id": status_path.parent.name, + "status": "unreadable", + "error": str(exc), + "path": self._display_path(status_path.parent), + } + ) + return sorted(artifacts, key=lambda item: str(item.get("candidate_id", ""))) + + def list_jobs(self) -> list[dict[str, Any]]: + with self._lock: + jobs = [asdict(job) for job in self._jobs.values()] + return sorted(jobs, key=lambda job: str(job["queued_at"]), reverse=True) + + def get_job(self, job_id: str) -> dict[str, Any] | None: + with self._lock: + job = self._jobs.get(job_id) + return asdict(job) if job is not None else None + + def submit_job(self, command: str, input_path: str | None = None) -> dict[str, Any]: + if command not in COMMANDS: + raise ValueError(f"unsupported command: {command}") + spec = COMMANDS[command] + if spec["requires_path"] and not input_path: + input_path = str(spec.get("default_path", "")) + job = ConsoleJob( + id=uuid.uuid4().hex[:12], + command=command, + label=str(spec["label"]), + input_path=input_path, + ) + with self._lock: + self._jobs[job.id] = job + if self._worker is None: + self._run_and_store(job.id) + else: + self._queue.put(job.id) + return asdict(job) + + def wait_for_job(self, job_id: str, *, timeout_seconds: float = 30) -> dict[str, Any]: + import time + + deadline = time.monotonic() + timeout_seconds + while time.monotonic() < deadline: + job = self.get_job(job_id) + if job is not None and job["status"] in {"succeeded", "failed"}: + return job + time.sleep(0.05) + raise TimeoutError(f"job did not finish: {job_id}") + + def read_repo_file(self, path: str, *, max_bytes: int = 262_144) -> dict[str, Any]: + resolved = self._resolve_repo_file(path) + data = resolved.read_bytes() + truncated = len(data) > max_bytes + text = data[:max_bytes].decode("utf-8", errors="replace") + return { + "path": self._display_path(resolved), + "size_bytes": len(data), + "truncated": truncated, + "text": text, + } + + def _candidate_summary(self, path: Path, source_kind: str) -> dict[str, Any]: + try: + candidate = load_candidate(path) + candidate_id = str(candidate.get("candidate_id", path.stem)) + operators = candidate.get("operators", {}) + l_matrix = operators.get("L", {"rows": []}) + p_matrix = operators.get("P", {"rows": []}) + rows = l_matrix.get("rows", []) if isinstance(l_matrix, dict) else [] + artifact_status = self._artifact_status(candidate_id) + errors = validate_candidate(candidate, self.repo_root) + return { + "candidate_id": candidate_id, + "source_kind": source_kind, + "path": self._display_path(path), + "fields": candidate.get("fields", []), + "claims": [claim.get("type") for claim in candidate.get("claims", []) if isinstance(claim, dict)], + "matrix_size": len(rows), + "l_bound": self._safe_matrix_bound(l_matrix), + "p_bound": self._safe_matrix_bound(p_matrix), + "laxforge_version": candidate.get("laxforge_version"), + "schema_version": candidate.get("schema_version"), + "validation_status": "schema_valid" if not errors else "schema_invalid", + "validation_error_count": len(errors), + "artifact_status": artifact_status.get("status"), + "artifact_timestamp_utc": artifact_status.get("timestamp_utc"), + } + except Exception as exc: + return { + "candidate_id": path.stem, + "source_kind": source_kind, + "path": self._display_path(path), + "validation_status": "unreadable", + "validation_error_count": 1, + "error": str(exc), + } + + def _artifact_status(self, candidate_id: str) -> dict[str, Any]: + status_path = self.repo_root / "artifacts" / candidate_id / "proof-status.json" + if not status_path.is_file(): + return {} + try: + return json.loads(status_path.read_text(encoding="utf-8")) + except Exception: + return {"status": "unreadable"} + + def _worker_loop(self) -> None: + while True: + job_id = self._queue.get() + if job_id is None: + return + self._run_and_store(job_id) + + def _run_and_store(self, job_id: str) -> None: + with self._lock: + job = self._jobs[job_id] + job.status = "running" + job.started_at = utc_timestamp() + job.log.append(f"[{job.started_at}] started {job.label}") + try: + result, log, ok = self._run_job(job) + with self._lock: + job.result = result + job.log.extend(log) + job.exit_code = 0 if ok else 1 + job.status = "succeeded" if ok else "failed" + job.finished_at = utc_timestamp() + job.log.append(f"[{job.finished_at}] finished with {job.status}") + except Exception as exc: + with self._lock: + job.result = {"error": str(exc)} + job.log.append(str(exc)) + job.exit_code = 1 + job.status = "failed" + job.finished_at = utc_timestamp() + + def _run_job(self, job: ConsoleJob) -> tuple[dict[str, Any], list[str], bool]: + if job.command == "validate_candidate": + path = self._resolve_candidate_input_path(job.input_path) + resolved = resolve_candidate_input(path) + candidate = load_candidate(resolved.candidate_path) + errors = validate_candidate(candidate, self.repo_root) + status = "schema_valid" if not errors else "schema_invalid" + return ( + { + "status": status, + "candidate_id": candidate.get("candidate_id", resolved.candidate_path.stem), + "candidate_source": resolved.metadata(), + "errors": errors, + }, + [f"resolved input: {resolved.candidate_path}", f"validation status: {status}"], + not errors, + ) + + if job.command in {"certify_candidate", "certify_expected_failure"}: + path = self._resolve_candidate_input_path(job.input_path) + result = certify_candidate_input(path, self.repo_root) + result_doc = { + "candidate_id": result.candidate_id, + "status": result.status, + "candidate_hash": result.candidate_hash, + "generated_lean_hash": result.generated_lean_hash, + "lean_file": str(result.lean_file) if result.lean_file is not None else None, + "residual_witness": result.residual_witness, + } + ok = result.status == "proof_succeeded" + if job.command == "certify_expected_failure": + ok = result.status != "proof_succeeded" + log = [ + f"candidate: {result.candidate_id}", + f"proof status: {result.status}", + ] + if result.build_log: + log.extend(result.build_log.splitlines()[-80:]) + return result_doc, log, ok + + if job.command == "lake_build": + ok, log = run_lake_build("LaxCert", self.repo_root / "lean") + return {"status": "passed" if ok else "failed"}, log.splitlines(), ok + + if job.command == "pytest": + proc = subprocess.run( + ["pytest", "-q"], + cwd=str(self.repo_root), + text=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + check=False, + env=self._command_env(), + ) + return ( + {"status": "passed" if proc.returncode == 0 else "failed"}, + proc.stdout.splitlines(), + proc.returncode == 0, + ) + + raise ValueError(f"unsupported command: {job.command}") + + def _resolve_candidate_input_path(self, input_path: str | None) -> Path: + if not input_path: + raise ValueError("input path is required") + raw = Path(input_path).expanduser() + path = raw if raw.is_absolute() else self.repo_root / raw + resolved = path.resolve() + if not resolved.exists(): + raise FileNotFoundError(f"candidate input does not exist: {input_path}") + return resolved + + def _resolve_repo_file(self, path: str) -> Path: + raw = Path(path) + resolved = (raw if raw.is_absolute() else self.repo_root / raw).resolve() + try: + resolved.relative_to(self.repo_root) + except ValueError as exc: + raise ValueError("file reads are restricted to the LAXCERT repository") from exc + if not resolved.is_file(): + raise FileNotFoundError(f"file does not exist: {path}") + return resolved + + def _display_path(self, path: Path) -> str: + try: + return path.resolve().relative_to(self.repo_root).as_posix() + except ValueError: + return str(path) + + def _safe_matrix_bound(self, matrix_json: Any) -> int | None: + try: + if isinstance(matrix_json, dict): + return matrix_bound(matrix_json) + except Exception: + return None + return None + + def _safe_toolchain(self) -> str: + try: + return lean_toolchain(self.repo_root) + except Exception: + return "unknown" + + def _safe_mathlib_revision(self) -> str: + try: + return mathlib_revision(self.repo_root) + except Exception: + return "unknown" + + def _command_env(self) -> dict[str, str]: + env = os.environ.copy() + if os.name == "nt": + env.setdefault("ELAN_HOME", "F:\\_codex\\elan") + env["PATH"] = f"{env['ELAN_HOME']}\\bin;C:\\Users\\jamie\\.elan\\bin;" + env.get("PATH", "") + return env + + +class LaxCertConsoleServer(ThreadingHTTPServer): + def __init__(self, server_address: tuple[str, int], repo_root: Path) -> None: + super().__init__(server_address, ConsoleRequestHandler) + self.backend = ConsoleBackend(repo_root) + + +class ConsoleRequestHandler(BaseHTTPRequestHandler): + server: LaxCertConsoleServer + + def log_message(self, format: str, *args: Any) -> None: + return + + def do_GET(self) -> None: + parsed = urlparse(self.path) + try: + if parsed.path == "/api/summary": + self._send_json(self.server.backend.summary()) + return + if parsed.path == "/api/candidates": + self._send_json({"candidates": self.server.backend.list_candidates()}) + return + if parsed.path == "/api/artifacts": + self._send_json({"artifacts": self.server.backend.list_artifacts()}) + return + if parsed.path == "/api/jobs": + self._send_json({"jobs": self.server.backend.list_jobs()}) + return + if parsed.path == "/api/commands": + self._send_json({"commands": self.server.backend.command_specs()}) + return + if parsed.path == "/api/file": + query = parse_qs(parsed.query) + target = query.get("path", [""])[0] + self._send_json(self.server.backend.read_repo_file(target)) + return + self._send_static(parsed.path) + except Exception as exc: + self._send_json({"error": str(exc)}, status=500) + + def do_POST(self) -> None: + parsed = urlparse(self.path) + try: + if parsed.path == "/api/jobs": + body = self._read_json_body() + job = self.server.backend.submit_job( + str(body.get("command", "")), + body.get("input_path"), + ) + self._send_json({"job": job}, status=202) + return + self._send_json({"error": "not found"}, status=404) + except Exception as exc: + self._send_json({"error": str(exc)}, status=400) + + def _read_json_body(self) -> dict[str, Any]: + size = int(self.headers.get("Content-Length", "0")) + if size == 0: + return {} + return json.loads(self.rfile.read(size).decode("utf-8")) + + def _send_json(self, data: dict[str, Any], *, status: int = 200) -> None: + payload = json.dumps(data, indent=2, sort_keys=True).encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(payload))) + self.end_headers() + self.wfile.write(payload) + + def _send_static(self, request_path: str) -> None: + name = "index.html" if request_path in {"/", "/console", "/console/"} else request_path.lstrip("/") + if "/" in name or "\\" in name: + self._send_json({"error": "not found"}, status=404) + return + static_root = files("laxforge_laxcert").joinpath("console_static") + target = static_root.joinpath(name) + if not target.is_file(): + self._send_json({"error": "not found"}, status=404) + return + data = target.read_bytes() + content_type = mimetypes.guess_type(name)[0] or "application/octet-stream" + if name.endswith(".js"): + content_type = "text/javascript" + self.send_response(200) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Run the local LAXCERT visual console.") + parser.add_argument("--repo-root", type=Path, default=Path.cwd()) + parser.add_argument("--host", default="127.0.0.1") + parser.add_argument("--port", type=int, default=8765) + args = parser.parse_args() + + server = LaxCertConsoleServer((args.host, args.port), args.repo_root) + url = f"http://{args.host}:{server.server_port}" + print(f"LAXCERT console listening on {url}") + print("Press Ctrl+C to stop.") + try: + server.serve_forever() + except KeyboardInterrupt: + pass + finally: + server.backend.close() + server.server_close() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/python/laxforge_laxcert/console_static/console.css b/python/laxforge_laxcert/console_static/console.css new file mode 100644 index 0000000..f190ea1 --- /dev/null +++ b/python/laxforge_laxcert/console_static/console.css @@ -0,0 +1,392 @@ +:root { + color-scheme: light; + --bg: #f6f4ef; + --surface: #fffdf8; + --surface-strong: #ffffff; + --ink: #1d2528; + --muted: #667276; + --line: #d9d2c3; + --accent: #0f766e; + --accent-strong: #0b5d56; + --warn: #a15c16; + --danger: #b42318; + --ok: #157347; + --code: #202624; + --shadow: 0 12px 34px rgba(41, 35, 25, 0.08); +} + +* { + box-sizing: border-box; +} + +body { + margin: 0; + min-width: 320px; + background: var(--bg); + color: var(--ink); + font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; + letter-spacing: 0; +} + +button, +input { + font: inherit; +} + +button { + min-height: 38px; + border: 1px solid transparent; + border-radius: 6px; + padding: 0 12px; + background: var(--accent); + color: #ffffff; + cursor: pointer; +} + +button:hover { + background: var(--accent-strong); +} + +button.secondary { + background: var(--surface-strong); + color: var(--ink); + border-color: var(--line); +} + +button.secondary:hover { + border-color: var(--accent); + color: var(--accent-strong); +} + +input { + width: 100%; + min-height: 38px; + border: 1px solid var(--line); + border-radius: 6px; + padding: 8px 10px; + background: var(--surface-strong); + color: var(--ink); +} + +.app-shell { + min-height: 100vh; + display: grid; + grid-template-columns: 300px minmax(0, 1fr); + grid-template-rows: auto 1fr; +} + +.topbar { + grid-column: 1 / -1; + min-height: 76px; + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + padding: 16px 22px; + border-bottom: 1px solid var(--line); + background: var(--surface); +} + +.topbar h1, +.panel h2, +.rail-block h2 { + margin: 0; + line-height: 1.1; +} + +.topbar h1 { + font-size: 24px; +} + +.eyebrow { + margin: 0 0 4px; + color: var(--muted); + font-size: 11px; + font-weight: 700; + text-transform: uppercase; +} + +.toolchain { + max-width: 48vw; + color: var(--muted); + font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; + font-size: 12px; + text-align: right; + overflow-wrap: anywhere; +} + +.command-rail { + border-right: 1px solid var(--line); + background: #eee9dd; + padding: 18px; + overflow-y: auto; +} + +.rail-block { + display: grid; + gap: 12px; + margin-bottom: 22px; +} + +.rail-block.compact { + gap: 10px; +} + +.rail-block h2, +.panel h2 { + font-size: 16px; +} + +.rail-block label { + color: var(--muted); + font-size: 12px; + font-weight: 700; +} + +.command-grid { + display: grid; + gap: 8px; +} + +.command-grid button { + width: 100%; + text-align: left; +} + +.workspace { + min-width: 0; + padding: 20px; + overflow: auto; +} + +.metrics { + display: grid; + grid-template-columns: repeat(4, minmax(140px, 1fr)); + gap: 12px; + margin-bottom: 16px; +} + +.metric, +.panel, +.artifact-card { + background: var(--surface-strong); + border: 1px solid var(--line); + border-radius: 8px; + box-shadow: var(--shadow); +} + +.metric { + padding: 14px; +} + +.metric strong { + display: block; + margin-top: 4px; + font-size: 24px; +} + +.split { + display: grid; + grid-template-columns: minmax(0, 1.45fr) minmax(320px, 0.75fr); + gap: 16px; + margin-bottom: 16px; +} + +.panel { + min-width: 0; + margin-bottom: 16px; +} + +.panel-head { + min-height: 62px; + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 14px 16px; + border-bottom: 1px solid var(--line); +} + +.table-wrap { + overflow-x: auto; +} + +table { + width: 100%; + border-collapse: collapse; + font-size: 13px; +} + +th, +td { + padding: 11px 12px; + border-bottom: 1px solid var(--line); + text-align: left; + vertical-align: top; +} + +th { + color: var(--muted); + font-size: 11px; + text-transform: uppercase; +} + +tr[data-path] { + cursor: pointer; +} + +tr[data-path]:hover { + background: #f4efe3; +} + +tr.selected { + background: #e7f4f1; +} + +.badge { + display: inline-flex; + align-items: center; + min-height: 22px; + border-radius: 999px; + padding: 2px 8px; + background: #ece7dc; + color: var(--ink); + font-size: 12px; + font-weight: 700; + white-space: nowrap; +} + +.badge.ok { + background: #dcefe4; + color: var(--ok); +} + +.badge.warn { + background: #f6ead7; + color: var(--warn); +} + +.badge.danger { + background: #fbe2df; + color: var(--danger); +} + +.badge.neutral { + background: #e8eceb; + color: #425053; +} + +.detail, +.artifact-card { + padding: 14px 16px; +} + +.detail dl, +.artifact-card dl { + display: grid; + grid-template-columns: 110px minmax(0, 1fr); + gap: 8px 12px; + margin: 0; + font-size: 13px; +} + +.detail dt, +.artifact-card dt { + color: var(--muted); + font-weight: 700; +} + +.detail dd, +.artifact-card dd { + margin: 0; + overflow-wrap: anywhere; +} + +.artifact-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); + gap: 12px; + padding: 14px; +} + +.artifact-card { + box-shadow: none; +} + +.artifact-card h3 { + margin: 0 0 10px; + font-size: 15px; +} + +.queue-list { + display: grid; + gap: 8px; +} + +.queue-item { + border: 1px solid var(--line); + border-radius: 8px; + padding: 10px; + background: var(--surface); +} + +.queue-item strong { + display: block; + margin-bottom: 6px; + font-size: 13px; +} + +.queue-item small { + color: var(--muted); + overflow-wrap: anywhere; +} + +.terminal-panel pre { + min-height: 170px; + max-height: 360px; + margin: 0; + padding: 14px 16px; + overflow: auto; + background: var(--code); + color: #f4f0e7; + font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; + font-size: 12px; + line-height: 1.5; +} + +.path { + color: var(--muted); + font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; + font-size: 12px; +} + +.empty { + color: var(--muted); + padding: 14px 16px; +} + +@media (max-width: 980px) { + .app-shell { + grid-template-columns: 1fr; + } + + .command-rail { + border-right: 0; + border-bottom: 1px solid var(--line); + } + + .split, + .metrics { + grid-template-columns: 1fr; + } + + .toolchain { + max-width: 100%; + text-align: left; + } + + .topbar { + align-items: flex-start; + flex-direction: column; + } +} diff --git a/python/laxforge_laxcert/console_static/console.js b/python/laxforge_laxcert/console_static/console.js new file mode 100644 index 0000000..d8a79be --- /dev/null +++ b/python/laxforge_laxcert/console_static/console.js @@ -0,0 +1,190 @@ +const state = { + summary: null, + selectedPath: null, +}; + +const statusClass = (status) => { + if (!status) return "neutral"; + if (status === "proof_succeeded" || status === "schema_valid" || status === "succeeded" || status === "passed") { + return "ok"; + } + if (status.includes("failed") || status.includes("invalid") || status === "unreadable") { + return "danger"; + } + if (status === "running" || status === "queued") return "warn"; + return "neutral"; +}; + +const el = (id) => document.getElementById(id); + +function badge(status) { + const label = status || "not run"; + return `${escapeHtml(label)}`; +} + +function escapeHtml(value) { + return String(value ?? "") + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll('"', """); +} + +function shortHash(value) { + if (!value) return ""; + return String(value).replace("sha256:", "").slice(0, 12); +} + +async function loadSummary() { + const response = await fetch("/api/summary"); + state.summary = await response.json(); + if (!state.selectedPath && state.summary.candidates.length) { + const preferred = state.summary.candidates.find((candidate) => candidate.candidate_id === "AKNSD2TransportZero"); + state.selectedPath = (preferred || state.summary.candidates[0]).path; + el("inputPath").value = state.selectedPath; + } + render(); +} + +function render() { + renderToolchain(); + renderCommands(); + renderMetrics(); + renderCandidates(); + renderArtifacts(); + renderQueue(); + renderDetail(); + renderJobLog(); +} + +function renderToolchain() { + const summary = state.summary; + el("toolchain").textContent = `${summary.lean_toolchain} | ${summary.mathlib_revision}`; +} + +function renderCommands() { + const commands = el("commands"); + commands.innerHTML = state.summary.commands + .map((command) => ``) + .join(""); + commands.querySelectorAll("button").forEach((button) => { + button.addEventListener("click", () => queueCommand(button.dataset.command)); + }); +} + +function renderMetrics() { + const counts = state.summary.status_counts || {}; + el("metrics").innerHTML = [ + metric("Candidates", state.summary.candidate_count), + metric("Artifacts", state.summary.artifact_count), + metric("Succeeded", counts.proof_succeeded || 0), + metric("Failed", Object.entries(counts).filter(([key]) => key !== "proof_succeeded").reduce((sum, [, value]) => sum + value, 0)), + ].join(""); +} + +function metric(label, value) { + return `
${escapeHtml(label)}${escapeHtml(value)}
`; +} + +function renderCandidates() { + const rows = state.summary.candidates.map((candidate) => { + const selected = candidate.path === state.selectedPath ? "selected" : ""; + const bounds = candidate.l_bound == null ? "" : `L:${candidate.l_bound} P:${candidate.p_bound}`; + return ` + + ${badge(candidate.artifact_status || candidate.validation_status)} + ${escapeHtml(candidate.candidate_id)}
${escapeHtml(candidate.path)}
+ ${escapeHtml(candidate.source_kind)} + ${escapeHtml((candidate.fields || []).join(", "))} + ${escapeHtml(bounds)} + ${escapeHtml((candidate.claims || []).join(", "))} + + `; + }).join(""); + el("candidateRows").innerHTML = rows || `No candidates found.`; + el("candidateRows").querySelectorAll("tr[data-path]").forEach((row) => { + row.addEventListener("click", () => { + state.selectedPath = row.dataset.path; + el("inputPath").value = state.selectedPath; + render(); + }); + }); +} + +function renderArtifacts() { + const cards = state.summary.artifacts.map((artifact) => ` +
+

${escapeHtml(artifact.candidate_id)}

+
+
Status
${badge(artifact.status)}
+
Claims
${escapeHtml(artifact.claim_type || "")}
+
Theorem
${escapeHtml(artifact.lean_theorem || "")}
+
Lean hash
${escapeHtml(shortHash(artifact.generated_lean_hash))}
+
Updated
${escapeHtml(artifact.timestamp_utc || "")}
+
+
+ `).join(""); + el("artifacts").innerHTML = cards || `
No proof artifacts found.
`; +} + +function renderQueue() { + const jobs = state.summary.jobs.slice(0, 8); + el("queue").innerHTML = jobs.map((job) => ` +
+ ${escapeHtml(job.label)} ${badge(job.status)} + ${escapeHtml(job.input_path || "repository command")} +
+ `).join("") || `
No queued jobs.
`; +} + +function renderDetail() { + const candidate = state.summary.candidates.find((item) => item.path === state.selectedPath); + if (!candidate) { + el("detail").innerHTML = `
Select a candidate.
`; + return; + } + const artifact = state.summary.artifacts.find((item) => item.candidate_id === candidate.candidate_id); + const witness = artifact?.residual_witness ? JSON.stringify(artifact.residual_witness) : ""; + el("detail").innerHTML = ` +
+
Candidate
${escapeHtml(candidate.candidate_id)}
+
Path
${escapeHtml(candidate.path)}
+
Validation
${badge(candidate.validation_status)}
+
Proof
${badge(candidate.artifact_status)}
+
Source
${escapeHtml(candidate.source_kind)}
+
Version
${escapeHtml(candidate.laxforge_version || "")}
+
Matrix
${escapeHtml(candidate.matrix_size ? `${candidate.matrix_size}x${candidate.matrix_size}` : "")}
+
Residual
${escapeHtml(witness)}
+
+ `; +} + +function renderJobLog() { + const latest = state.summary.jobs[0]; + if (!latest) { + el("jobLog").textContent = "No jobs queued."; + return; + } + const result = latest.result ? `\n\nresult:\n${JSON.stringify(latest.result, null, 2)}` : ""; + el("jobLog").textContent = `${latest.label} [${latest.status}]\n${latest.log.join("\n")}${result}`; +} + +async function queueCommand(command) { + const spec = state.summary.commands.find((item) => item.name === command); + const inputPath = spec?.requires_path ? el("inputPath").value.trim() : null; + const response = await fetch("/api/jobs", { + method: "POST", + headers: {"Content-Type": "application/json"}, + body: JSON.stringify({command, input_path: inputPath}), + }); + if (!response.ok) { + const error = await response.json(); + el("jobLog").textContent = error.error || "command failed to queue"; + } + await loadSummary(); +} + +el("refreshBtn").addEventListener("click", loadSummary); + +loadSummary(); +setInterval(loadSummary, 2500); diff --git a/python/laxforge_laxcert/console_static/index.html b/python/laxforge_laxcert/console_static/index.html new file mode 100644 index 0000000..5c16e6f --- /dev/null +++ b/python/laxforge_laxcert/console_static/index.html @@ -0,0 +1,96 @@ + + + + + + LAXCERT Console + + + +
+
+
+

LAXCERT

+

Proof Console

+
+
Loading toolchain...
+
+ + + +
+
+ +
+
+
+
+

Inputs

+

Candidates

+
+ +
+
+ + + + + + + + + + + + +
StatusCandidateSourceFieldsBoundsClaims
+
+
+ +
+
+
+

Ledger

+

Selected Result

+
+
+
+
+
+ +
+
+
+

Artifacts

+

Proof Results

+
+
+
+
+ +
+
+
+

Run Log

+

Latest Job

+
+
+
No jobs queued.
+
+
+
+ + + + diff --git a/tests/test_console_server.py b/tests/test_console_server.py new file mode 100644 index 0000000..5ed619a --- /dev/null +++ b/tests/test_console_server.py @@ -0,0 +1,75 @@ +from __future__ import annotations + +import json +import shutil +from pathlib import Path + +import pytest + +from laxforge_laxcert.console_server import ConsoleBackend + + +REPO_ROOT = Path(__file__).resolve().parents[1] + + +def test_console_summary_lists_candidates_artifacts_and_commands() -> None: + backend = ConsoleBackend(REPO_ROOT, start_worker=False) + try: + summary = backend.summary() + finally: + backend.close() + + command_names = {command["name"] for command in summary["commands"]} + candidate_ids = {candidate["candidate_id"] for candidate in summary["candidates"]} + artifact_ids = {artifact["candidate_id"] for artifact in summary["artifacts"]} + + assert {"validate_candidate", "certify_candidate", "lake_build", "pytest"} <= command_names + assert "ToyLaxZero" in candidate_ids + assert "AKNSD2TransportZero" in candidate_ids + assert "FalseWrongSign" in artifact_ids + assert summary["status_counts"]["proof_succeeded"] >= 1 + assert summary["lean_toolchain"].startswith("leanprover/lean4:") + + +def test_console_validation_job_runs_through_queue() -> None: + backend = ConsoleBackend(REPO_ROOT) + try: + queued = backend.submit_job("validate_candidate", "candidates/toy_lax_zero.json") + finished = backend.wait_for_job(queued["id"], timeout_seconds=10) + finally: + backend.close() + + assert finished["status"] == "succeeded" + assert finished["result"]["candidate_id"] == "ToyLaxZero" + assert finished["result"]["status"] == "schema_valid" + + +def test_console_expected_failure_command_passes_for_false_candidate(tmp_path: Path) -> None: + candidate = json.loads((REPO_ROOT / "candidates" / "false_wrong_sign.json").read_text(encoding="utf-8")) + candidate["candidate_id"] = "ConsoleFalseWrongSign" + candidate_path = tmp_path / "console_false_wrong_sign.json" + candidate_path.write_text(json.dumps(candidate, indent=2), encoding="utf-8") + + backend = ConsoleBackend(REPO_ROOT) + try: + queued = backend.submit_job("certify_expected_failure", str(candidate_path)) + finished = backend.wait_for_job(queued["id"], timeout_seconds=10) + finally: + backend.close() + shutil.rmtree(REPO_ROOT / "artifacts" / "ConsoleFalseWrongSign", ignore_errors=True) + + assert finished["status"] == "succeeded" + assert finished["result"]["candidate_id"] == "ConsoleFalseWrongSign" + assert finished["result"]["status"] == "proof_failed_nonzero_residual" + + +def test_console_file_reads_are_repo_scoped() -> None: + backend = ConsoleBackend(REPO_ROOT, start_worker=False) + try: + proof_status = backend.read_repo_file("artifacts/ToyLaxZero/proof-status.json") + assert "proof_succeeded" in proof_status["text"] + + with pytest.raises(ValueError): + backend.read_repo_file("../outside.json") + finally: + backend.close()