From f2f33a9b5d2e0947e4b574eb6b14dd8369cbc93a Mon Sep 17 00:00:00 2001 From: iwebslogtech <5895515+iwebslogtech@users.noreply.github.com> Date: Sat, 7 Nov 2026 14:47:42 +0000 Subject: [PATCH 1/4] Improve scan reliability, tooling, and reports Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> --- .github/workflows/ci.yml | 9 +- README.md | 42 ++++- action.yml | 16 +- docs/roadmap.md | 58 ++++++ pyproject.toml | 9 +- src/codeproof/__init__.py | 2 +- src/codeproof/adapters.py | 279 ++++++++++++++++++++++++++--- src/codeproof/cli.py | 179 +++++++++++++++--- src/codeproof/config.py | 98 +++++++++- src/codeproof/core.py | 112 ++++++++++-- src/codeproof/discovery.py | 57 ++++-- src/codeproof/files.py | 49 +++++ src/codeproof/models.py | 47 ++++- src/codeproof/report_template.html | 64 +++++++ src/codeproof/reporting.py | 147 +++++++++++++-- tests/test_adapters.py | 92 ++++++++++ tests/test_config.py | 5 +- tests/test_core.py | 4 +- tests/test_discovery.py | 25 +++ tests/test_policy.py | 97 ++++++++++ tests/test_reports_cli.py | 85 +++++++++ 21 files changed, 1356 insertions(+), 120 deletions(-) create mode 100644 docs/roadmap.md create mode 100644 src/codeproof/files.py create mode 100644 src/codeproof/report_template.html create mode 100644 tests/test_adapters.py create mode 100644 tests/test_discovery.py create mode 100644 tests/test_policy.py create mode 100644 tests/test_reports_cli.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3599f56..9c36207 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -3,9 +3,16 @@ on: [push, pull_request] jobs: test: runs-on: ubuntu-latest + strategy: + matrix: + python-version: ["3.10", "3.12"] steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 - with: {python-version: "3.12"} + with: + python-version: ${{ matrix.python-version }} - run: pip install -e ".[dev]" + - run: ruff check src tests + - run: ruff format --check src tests + - run: mypy src - run: pytest diff --git a/README.md b/README.md index d292bf3..1fc1900 100644 --- a/README.md +++ b/README.md @@ -19,15 +19,47 @@ pip install -e ".[checkers]" codeproof scan . ``` + + + + ## Commands + ```bash -codeproof doctor -codeproof init -codeproof inventory . +codeproof tools # supported checks and execution behavior +codeproof doctor # availability and install guidance +codeproof init # write a default policy +codeproof inventory . # public symbols, not coverage codeproof generate-tests . --output tests/generated -codeproof scan . --format all --fail-under 70 +codeproof scan . --format all --fail-under 70 --jobs 3 +codeproof scan . --config path/to/policy.yml --checks ruff,pytest,syntax +``` + +Reports are stored under `.codeproof/reports/`. Open `codeproof-report.html` for offline search, status filters, and expandable evidence. JSON and Markdown remain available. Paths are positional; the earlier `--path` option is also supported. Exit codes: **0** policy passed, **1** policy failed, **2** invalid usage or configuration. + +### Policy and additional tools + +Partial policies overlay the six default checks; explicitly disable any you do not want. A selected or configured check cannot bypass a required tool gate. Remove a tool from `required_tools` only when intentionally changing the policy. For a quick execution-free syntax-only scan, use: + +```yaml +# .codeproof.yml +required_tools: [] +source_paths: [src] +checks: + syntax: {enabled: true, weight: 10} ``` -Reports are stored under `.codeproof/reports/`. + +```bash +codeproof scan . --checks syntax +``` + +To add dependency auditing, install `pip install 'codeproof-ai[audit]'`, provide a root `requirements.txt`, and add `pip-audit: {enabled: true, weight: 15}` under `checks`. This opt-in tool queries vulnerability services and may invoke package tooling while resolving dependencies. Unsupported manifests are reported unavailable; the developer environment is never audited as a fallback. + +`jobs: 1` (default) runs serially; `--jobs 2` through `--jobs 8` allow concurrency. Tests and imports can share resources, so choose concurrency to suit the repository. Invalid thresholds, negative/nonfinite weights, unknown tools, and unknown policy keys are rejected. + +Generated tests check symbol exposure and execute imports; review them before running. Existing files are preserved unless `--force` is passed. See the [audit and prioritized roadmap](docs/roadmap.md) for delivered changes, compatibility notes, and follow-up work. + + ## Confidence model The score is the weighted percentage of included checks that pass. Missing required tools fail policy. Missing optional tools are marked unavailable and excluded from the denominator. A passing report is evidence that configured checks passed, not proof of correctness. diff --git a/action.yml b/action.yml index c6d49dc..2cb0ea1 100644 --- a/action.yml +++ b/action.yml @@ -3,13 +3,23 @@ description: Evidence-backed Python repository verification inputs: path: {description: Repository path, required: false, default: .} fail-under: {description: Minimum score, required: false, default: "70"} + jobs: {description: Concurrent check workers (1-8), required: false, default: "1"} runs: using: composite steps: - shell: bash - run: python -m pip install "${{ github.action_path }}[checkers]" + env: + CODEPROOF_ACTION_PATH: ${{ github.action_path }} + run: python -m pip install "${CODEPROOF_ACTION_PATH}[checkers]" - shell: bash - run: codeproof scan "${{ inputs.path }}" --fail-under "${{ inputs.fail-under }}" + env: + CODEPROOF_TARGET: ${{ inputs.path }} + CODEPROOF_THRESHOLD: ${{ inputs.fail-under }} + CODEPROOF_JOBS: ${{ inputs.jobs }} + run: codeproof scan "$CODEPROOF_TARGET" --fail-under "$CODEPROOF_THRESHOLD" --jobs "$CODEPROOF_JOBS" - if: always() uses: actions/upload-artifact@v4 - with: {name: codeproof-report, path: "${{ inputs.path }}/.codeproof/"} + with: + name: codeproof-report + path: "${{ inputs.path }}/.codeproof/reports/" + include-hidden-files: true diff --git a/docs/roadmap.md b/docs/roadmap.md new file mode 100644 index 0000000..7b10c8a --- /dev/null +++ b/docs/roadmap.md @@ -0,0 +1,58 @@ + + +# CodeProof AI — repository audit and delivery roadmap + +## Product direction + +CodeProof is a local Python CLI and reusable GitHub Action. Its strongest use cases are developer preflight checks, CI policy gates, and portable evidence for code review. Keep the local CLI as the execution engine and make its reports useful to maintainers before introducing a hosted product. A score summarizes configured checks; it cannot establish correctness or replace behavioral tests. + +Audit baseline: `7043a711daefaed5a2f973d51ec856a5ef00d703`. The initial package had six adapters, a weighted score, an AST symbol inventory, exposure-test generation, three report formats, and two tests. There was no application server, database, hosted account system, or test-coverage analysis. The inventory should not be described as identifying untested behavior. + +## Audit findings and delivered repairs + +| Priority | Finding and evidence | Delivered improvement | +|---|---|---| +| P0 | `core.py` checked required gates only for executed results; disabling or omitting one bypassed its gate | Emit required skipped results and fail policy; no weighted evidence cannot pass, including at threshold zero | +| P0 | `config.py` accepted invalid weights/timeouts and replaced all default checks when a partial file existed | Validate policy ranges, unknown settings/tools and version; merge partial overrides with defaults | +| P0 | `action.yml` interpolated inputs directly into shell scripts | Pass inputs through quoted environment variables; upload report artifacts including the hidden report directory | +| P0 | Semgrep ran without `--error`, permitting successful exit despite findings | Findings now produce a failed check; this may lower previously misleading scores | +| P1 | Documented positional CLI paths were interpreted as options | Support documented positional paths and retain the existing `--path` option for compatibility | +| P1 | `adapters.py` returned almost exclusively raw output and import timeouts escaped the adapter | Normalize Ruff/Bandit/Semgrep/pip-audit findings; retain raw diagnostics; contain launch and timeout errors; enforce total import time budget | +| P1 | All adapters ran serially | Configurable worker pool (1–8), stable result order; serial remains default | +| P1 | HTML had only an unstyled summary table | Offline responsive report, policy explanation, search, status filters, expandable findings and raw evidence; keyboard focus styles and live count | +| P1 | No dependency vulnerability or execution-free syntax tools | Opt-in `pip-audit` for root requirements.txt; built-in `syntax` without execution or bytecode writes; discoverable tools and install guidance | +| P1 | Test generation wrote only the first symbol per module without force, duplicated on force, and mishandled package imports | Group symbols by module, replace once on force, preserve existing files, handle package exports and avoid module filename collisions | +| P1 | File discovery descended into environments and caches | Shared deterministic traversal prunes common generated trees, skips symlinks and deduplicates overlapping roots | +| P1 | Only grade and total weights had tests | Regression coverage for policy gates, config, parallel execution, adapter errors, structured evidence, generation, escaping and CLI workflows | + +## Compatibility and intentional changes + +- Existing six default checks and their weights (100 total) remain. Both new tools are opt-in; all report filenames and JSON schema 1.0 fields remain. Existing `--path` callers remain supported. +- A partial YAML policy now overlays defaults. Previously, specifying only `fail_under` could run no checks. To run a smaller set, disable the other checks explicitly or use `--checks`; remove a tool from `required_tools` only when that policy change is intended. +- Disabled or absent required checks fail policy, matching the README's required-tool guarantee. Empty evidence fails even if the threshold is zero. Invalid or misspelled policies now fail with CLI exit code 2. +- Semgrep findings now fail the check. Optional unavailable checks remain excluded from the score; required unavailable checks block policy. +- Generated filenames now use length-prefixed module components to avoid collisions. Existing generated files are preserved; review and remove obsolete files before regenerating into the same directory. +- Concurrent execution is opt-in because tests and imports execute repository code and may share resources. Each tool has a time budget; concurrency is not a sandbox or a process/memory quota. + +## Prioritized roadmap + +| Phase | Work | Exit criteria | Effort | +|---|---|---|---| +| 1 — Delivered | Policy integrity, actionable reports, opt-in tools, bounded workers, generation repairs and regression tests | Local CLI and Action retain compatibility; policy bypass regressions pass; report controls work on desktop and mobile | This change | +| 2 — CI adoption | SARIF export and GitHub annotations; machine-readable doctor; configurable local Semgrep rules; lockfile support for pip-audit; supported Python-version matrix | SARIF validates against its schema; annotations point to source lines; offline configuration completes without rule downloads; locked dependency fixtures yield stable findings | M | +| 3 — Faster large repositories | Benchmarked discovery, streamed/limited subprocess output, process-tree cancellation, bounded findings, incremental cache | Representative small/medium/large fixtures publish timings; no orphan processes after timeout; cache keys include source, config, dependency locks, tool/Python versions; changed inputs invalidate results | L | +| 4 — Stronger evidence | Real pytest counts and coverage ingestion; mypy normalization; severity-aware policy; changed-code baselines; versioned report schema | Inventory remains distinct from coverage; original evidence retained; high-severity gates cannot be offset by unrelated passes; schema migration and consumer contract tests pass | L | +| 5 — Team workflows | Report history and comparison; reviewable policy templates; distributable static viewer; accessible navigation/contrast audit | Compare two saved reports without rerunning code; policy changes show a clear diff; keyboard and screen-reader checks pass; report artifacts require no external assets | M | + +M and L are relative planning estimates, not delivery dates. Phase 2 should precede persistent history or a hosted service. Hosted authentication, queues, object storage and multi-tenant execution need separate product demand and a security design; this repository does not currently contain those facilities. + +## Engineering tools and delivery discipline + +- Use Ruff format/lint, mypy with PyYAML stubs, pytest regression tests, and Bandit for changes to process execution and reporting. Keep dependency auditing as an explicit extra rather than a mandatory network dependency for every local scan. +- Add packaging smoke tests so the HTML template is verified inside built wheels. Pin a reproducible CI dependency set in the next phase and document an update cadence. +- Measure p50/p95 scan time, peak memory, adapter error rates, policy pass rates with missing tools, and report size on synthetic fixtures before implementing caching or claiming speedups. Worker parallelism is delivered; no benchmarked speedup is claimed. +- Preserve the schema and exit-code contract (0 pass, 1 policy fail, 2 usage/config error). Add integration coverage for supported checker versions and hostile JSON/text fixtures. + +## Remaining limits + +Dependency auditing currently supports only a root requirements.txt and requires the optional pip-audit executable and network access. Resolution can invoke package build tooling; use isolated runners for untrusted requirements. Semgrep auto may retrieve rules. Tool processes still capture output in memory before retaining the final 50 KB; nested child processes are not comprehensively cancelled. The import adapter skips standalone package `__init__.py` files, as before. Syntax checks do not establish runtime importability, and generated tests only check symbol exposure. Reports are snapshots; filters never alter the policy score. Live GitHub Action execution requires pushing and running the workflow. Broader minimum-Python and accessibility coverage remain roadmap work. diff --git a/pyproject.toml b/pyproject.toml index 51aa695..19cdaca 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -11,10 +11,17 @@ license={text="MIT"} dependencies=["typer>=0.12,<1","rich>=13.7,<15","pydantic>=2.7,<3","PyYAML>=6,<7"] [project.optional-dependencies] checkers=["pytest>=8,<10","ruff>=0.6,<1","mypy>=1.11,<2","bandit>=1.7,<2","semgrep>=1.80,<2"] -dev=["codeproof-ai[checkers]"] +audit=["pip-audit>=2.7,<3"] +dev=["codeproof-ai[checkers]", "types-PyYAML>=6,<7"] [project.scripts] codeproof="codeproof.cli:app" [tool.hatch.build.targets.wheel] packages=["src/codeproof"] [tool.pytest.ini_options] testpaths=["tests"] + +[tool.ruff] +target-version = "py310" + +[tool.ruff.lint] +select = ["E4", "E7", "E9", "F", "I", "B", "UP"] diff --git a/src/codeproof/__init__.py b/src/codeproof/__init__.py index 40692a7..3dc1f76 100644 --- a/src/codeproof/__init__.py +++ b/src/codeproof/__init__.py @@ -1 +1 @@ -__version__="0.1.0" +__version__ = "0.1.0" diff --git a/src/codeproof/adapters.py b/src/codeproof/adapters.py index 0224e9b..42f5d02 100644 --- a/src/codeproof/adapters.py +++ b/src/codeproof/adapters.py @@ -1,25 +1,258 @@ -import json,os,shutil,subprocess,sys,time +"""Tool boundaries: normalize findings and contain process failures.""" + +import json +import os +import shutil +import subprocess +import sys +import time from pathlib import Path -from .models import CheckResult,Finding,Status -def run(name:str,root:Path,cfg:str|None,timeout:int,sources:list[str],tests:list[str])->CheckResult: - src=[x for x in sources if (root/x).exists()] or ["."] - commands={"ruff":["ruff","check",*src,"--output-format","json"],"mypy":["mypy",*src,"--no-error-summary"],"pytest":["pytest",*([x for x in tests if (root/x).exists()] or ["."]),"-q"],"bandit":["bandit","-r",*src,"-f","json","-q"],"semgrep":["semgrep","scan","--config",cfg or "auto","--json",*src]} - if name=="imports": return imports(root,src,timeout) - cmd=commands.get(name) - if not cmd:return CheckResult(name=name,status=Status.skipped,summary="unknown adapter") - if not shutil.which(cmd[0]):return CheckResult(name=name,status=Status.unavailable,command=cmd,summary=f"{cmd[0]} is not installed") - started=time.perf_counter() + +from .files import python_files +from .models import CheckResult, Finding, Status + + +def parse_findings(name: str, output: str) -> list[Finding]: + """Retain raw evidence if a tool emits text or an unfamiliar JSON schema.""" try: - cp=subprocess.run(cmd,cwd=root,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,timeout=timeout,env={**os.environ,"NO_COLOR":"1"}) - return CheckResult(name=name,status=Status.passed if cp.returncode==0 else Status.failed,command=cmd,duration_seconds=round(time.perf_counter()-started,3),exit_code=cp.returncode,summary="passed" if cp.returncode==0 else "reported findings",raw_output=(cp.stdout or "")[-50000:]) - except subprocess.TimeoutExpired as e:return CheckResult(name=name,status=Status.error,command=cmd,summary=f"timed out after {timeout}s") -def imports(root:Path,sources:list[str],timeout:int)->CheckResult: - started=time.perf_counter(); findings=[]; count=0 - for src in sources: - base=root/src - for p in base.rglob("*.py") if base.exists() else []: - if p.name=="__init__.py":continue - module=".".join(p.relative_to(base).with_suffix("").parts); count+=1 - cp=subprocess.run([sys.executable,"-c",f"import sys;sys.path.insert(0,{str(base)!r});__import__({module!r})"],cwd=root,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,timeout=timeout) - if cp.returncode:findings.append(Finding(level="error",message=(cp.stdout or "failed")[-800:],path=str(p.relative_to(root)),rule="import")) - return CheckResult(name="imports",status=Status.passed if not findings else Status.failed,duration_seconds=round(time.perf_counter()-started,3),summary=f"{count} modules checked; {len(findings)} failed",findings=findings,evidence={"modules_checked":count}) + data = json.loads(output) + if name == "ruff": + return [ + Finding( + level="warning", + message=item["message"], + path=item.get("filename"), + line=item.get("location", {}).get("row"), + rule=item.get("code"), + ) + for item in data + ] + if name == "bandit": + return [ + Finding( + level=item.get("issue_severity", "warning").lower(), + message=item["issue_text"], + path=item.get("filename"), + line=item.get("line_number"), + rule=item.get("test_id"), + ) + for item in data.get("results", []) + ] + if name == "semgrep": + return [ + Finding( + level=item["extra"].get("severity", "warning").lower(), + message=item["extra"]["message"], + path=item.get("path"), + line=item.get("start", {}).get("line"), + rule=item.get("check_id"), + ) + for item in data.get("results", []) + ] + if name == "pip-audit": + return [ + Finding( + level="warning", + message=f"{dep['name']} {dep['version']}: {vuln.get('description', vuln['id'])}", + rule=vuln["id"], + path="requirements.txt", + ) + for dep in data.get("dependencies", []) + for vuln in dep.get("vulns", []) + ] + except (ValueError, KeyError, TypeError, AttributeError): + pass + return [] + + +def run( + name: str, + root: Path, + cfg: str | None, + timeout: int, + sources: list[str], + tests: list[str], +) -> CheckResult: + if name == "syntax": + return syntax(root, sources) + if name == "imports": + return imports(root, sources, timeout) + src = [x for x in sources if (root / x).exists()] or ["."] + commands = { + "ruff": ["ruff", "check", *src, "--output-format", "json"], + "mypy": ["mypy", *src, "--no-error-summary"], + "pytest": [ + "pytest", + *([x for x in tests if (root / x).exists()] or ["."]), + "-q", + ], + "bandit": ["bandit", "-r", *src, "-f", "json", "-q"], + "semgrep": [ + "semgrep", + "scan", + "--config", + cfg or "auto", + "--json", + "--error", + *src, + ], + "pip-audit": [ + "pip-audit", + "-r", + "requirements.txt", + "--format", + "json", + "--progress-spinner", + "off", + ], + } + cmd = commands.get(name) + if not cmd: + return CheckResult(name=name, status=Status.skipped, summary="unknown adapter") + if name == "pip-audit" and not (root / "requirements.txt").is_file(): + return CheckResult( + name=name, + status=Status.unavailable, + summary="Requires requirements.txt at the project root; no environment audit performed", + ) + if not shutil.which(cmd[0]): + return CheckResult( + name=name, + status=Status.unavailable, + command=cmd, + summary=f"{cmd[0]} is not installed; install codeproof-ai[{'audit' if name == 'pip-audit' else 'checkers'}]", + ) + started = time.perf_counter() + try: + cp = subprocess.run( + cmd, + check=False, + cwd=root, + text=True, + errors="replace", + capture_output=True, + timeout=timeout, + env={**os.environ, "NO_COLOR": "1"}, + ) + findings = parse_findings(name, cp.stdout or "") + return CheckResult( + name=name, + status=Status.passed if cp.returncode == 0 else Status.failed, + command=cmd, + duration_seconds=round(time.perf_counter() - started, 3), + exit_code=cp.returncode, + summary=f"{len(findings)} findings" + if findings + else ( + "passed" + if cp.returncode == 0 + else "Check failed; expand output for details" + ), + findings=findings, + raw_output=((cp.stdout or "") + ("\n" + cp.stderr if cp.stderr else ""))[ + -50000: + ], + ) + except (subprocess.TimeoutExpired, OSError) as exc: + return CheckResult( + name=name, + status=Status.error, + command=cmd, + duration_seconds=round(time.perf_counter() - started, 3), + summary=f"timed out after {timeout}s" + if isinstance(exc, subprocess.TimeoutExpired) + else str(exc), + ) + + +def syntax(root: Path, sources: list[str]) -> CheckResult: + started = time.perf_counter() + findings: list[Finding] = [] + count = 0 + for path, _ in python_files(root, sources): + count += 1 + try: + compile(path.read_bytes(), str(path), "exec") + except (SyntaxError, UnicodeError, OSError) as exc: + findings.append( + Finding( + level="error", + message=str(exc), + path=str(path.relative_to(root)), + line=getattr(exc, "lineno", None), + rule="syntax", + ) + ) + return CheckResult( + name="syntax", + status=Status.failed + if findings + else (Status.passed if count else Status.skipped), + duration_seconds=round(time.perf_counter() - started, 3), + summary=f"{count} files compiled; {len(findings)} errors", + findings=findings, + evidence={"files_checked": count}, + ) + + +def imports(root: Path, sources: list[str], timeout: int) -> CheckResult: + started = time.perf_counter() + findings: list[Finding] = [] + count = 0 + for path, base in python_files(root, sources): + if path.name == "__init__.py": + continue + remaining = timeout - (time.perf_counter() - started) + if remaining <= 0: + return CheckResult( + name="imports", + status=Status.error, + summary=f"timed out after {timeout}s", + findings=findings, + ) + module = ".".join(path.relative_to(base).with_suffix("").parts) + count += 1 + try: + cp = subprocess.run( + [ + sys.executable, + "-c", + f"import sys;sys.path.insert(0,{str(base)!r});__import__({module!r})", + ], + check=False, + cwd=root, + text=True, + errors="replace", + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + timeout=remaining, + ) + except (subprocess.TimeoutExpired, OSError) as exc: + return CheckResult( + name="imports", + status=Status.error, + duration_seconds=round(time.perf_counter() - started, 3), + findings=findings, + summary=f"timed out after {timeout}s" + if isinstance(exc, subprocess.TimeoutExpired) + else str(exc), + ) + if cp.returncode: + findings.append( + Finding( + level="error", + message=(cp.stdout or "failed")[-800:], + path=str(path.relative_to(root)), + rule="import", + ) + ) + return CheckResult( + name="imports", + status=Status.failed + if findings + else (Status.passed if count else Status.skipped), + duration_seconds=round(time.perf_counter() - started, 3), + summary=f"{count} modules checked; {len(findings)} failed", + findings=findings, + evidence={"modules_checked": count}, + ) diff --git a/src/codeproof/cli.py b/src/codeproof/cli.py index 48c7683..8974f8a 100644 --- a/src/codeproof/cli.py +++ b/src/codeproof/cli.py @@ -1,37 +1,166 @@ +import shutil +from enum import Enum from pathlib import Path -import shutil,typer,yaml +from typing import Annotated + +import typer +import yaml from rich.console import Console from rich.table import Table -from .config import load,DEFAULT + +from .config import DEFAULT, TOOL_INFO, CheckConfig, load from .core import scan as execute -from .discovery import symbols,generate +from .discovery import generate, symbols from .reporting import write -app=typer.Typer(no_args_is_help=True);console=Console() + +app = typer.Typer( + no_args_is_help=True, + help="Evidence-backed Python repository checks. Start with doctor or init.", +) +console = Console() + + +class Format(str, Enum): + all = "all" + json = "json" + markdown = "markdown" + html = "html" + + +def policy(root: Path, config: Path | None = None): + if not root.is_dir(): + raise typer.BadParameter(f"Repository directory does not exist: {root}") + try: + return load(root, config) + except (ValueError, TypeError, OSError, yaml.YAMLError) as exc: + raise typer.BadParameter(f"Invalid policy: {exc}") from exc + + +@app.command() +def tools(): + """List supported tools, execution behavior, and installation extras.""" + table = Table("Tool", "Purpose", "Behavior", "Install extra") + for name, (purpose, description, extra) in TOOL_INFO.items(): + table.add_row(name, purpose, description, extra or "built in") + console.print(table) + + @app.command() def doctor(): - t=Table("Tool","Status") - for n in ["ruff","mypy","pytest","bandit","semgrep"]:t.add_row(n,"available" if shutil.which(n) else "missing") - console.print(t) + """Check tool availability and show how to install missing tools.""" + table = Table("Tool", "Status", "Next step") + for name, (_, _, extra) in TOOL_INFO.items(): + available = extra is None or bool(shutil.which(name)) + table.add_row( + name, + "available" if available else "missing", + "Ready" if available else f"pip install 'codeproof-ai[{extra}]'", + ) + console.print(table) + console.print( + "Dependency auditing needs requirements.txt. Semgrep auto and pip-audit use the network." + ) + + @app.command() -def init(path:Path=Path("."),force:bool=False): - p=path.resolve()/".codeproof.yml" - if p.exists() and not force:raise typer.BadParameter("policy exists; use --force") - p.write_text(yaml.safe_dump(DEFAULT.model_dump(mode="json"),sort_keys=False));console.print(f"Created {p}") +def init( + path: Annotated[Path, typer.Argument()] = Path("."), + force: bool = False, + path_option: Annotated[Path | None, typer.Option("--path", hidden=True)] = None, +): + """Create a commented policy without overwriting an existing one.""" + root = (path_option or path).resolve() + if not root.is_dir(): + raise typer.BadParameter(f"Repository directory does not exist: {root}") + dest = root / ".codeproof.yml" + if dest.exists() and not force: + raise typer.BadParameter("policy exists; use --force") + dest.write_text( + "# Weights are relative. Required checks must pass even with weight 0.\n" + "# Add syntax or pip-audit under checks to opt in; jobs: 1 is serial.\n" + + yaml.safe_dump(DEFAULT.model_dump(mode="json"), sort_keys=False), + encoding="utf-8", + ) + console.print(f"Created {dest}") + + @app.command() -def inventory(path:Path=Path(".")): - root=path.resolve();cfg=load(root);t=Table("Symbol","File","Line") - data=symbols(root,cfg.source_paths) - for n,p,l in data:t.add_row(n,str(p),str(l)) - console.print(t);console.print(f"{len(data)} public symbols") +def inventory( + path: Annotated[Path, typer.Argument()] = Path("."), + path_option: Annotated[Path | None, typer.Option("--path", hidden=True)] = None, +): + """List public top-level symbols; this is an inventory, not coverage analysis.""" + root = (path_option or path).resolve() + cfg = policy(root) + table = Table("Symbol", "File", "Line") + data = symbols(root, cfg.source_paths) + for name, file, line in data: + table.add_row(name, str(file), str(line)) + console.print(table) + console.print(f"{len(data)} public symbols") + + @app.command("generate-tests") -def generate_tests(path:Path=Path("."),output:Path=Path("tests/generated"),force:bool=False): - root=path.resolve();cfg=load(root);made=generate(root,cfg.source_paths,root/output,force);console.print(f"Created {len(made)} files") +def generate_tests( + path: Annotated[Path, typer.Argument()] = Path("."), + path_option: Annotated[Path | None, typer.Option("--path", hidden=True)] = None, + output: Path = Path("tests/generated"), + force: bool = False, +): + """Generate reviewable exposure checks. These are not behavioral tests.""" + root = (path_option or path).resolve() + cfg = policy(root) + made = generate(root, cfg.source_paths, root / output, force) + console.print( + f"Created {len(made)} files; review before running (imports execute code)." + ) + + @app.command() -def scan(path:Path=Path("."),format:str="all",fail_under:float|None=None,output:Path=Path(".codeproof/reports")): - if format not in {"all","json","markdown","html"}:raise typer.BadParameter("invalid format") - root=path.resolve();report=execute(root,load(root),fail_under);t=Table("Check","Status","Weight","Summary") - for r in report.results:t.add_row(r.name,r.status.value,str(r.weight),r.summary) - console.print(t);console.print(f"Score {report.score}/100 ({report.grade}); policy {'PASS' if report.policy_passed else 'FAIL'}") - for p in write(report,root/output,format):console.print(f"Report: {p}") +def scan( + path: Annotated[Path, typer.Argument()] = Path("."), + path_option: Annotated[Path | None, typer.Option("--path", hidden=True)] = None, + format: Format = Format.all, + fail_under: float | None = typer.Option(None, min=0, max=100), + output: Path = Path(".codeproof/reports"), + config: Path | None = None, + jobs: int | None = typer.Option(None, min=1, max=8), + checks: str | None = typer.Option( + None, help="Comma-separated tools to run. Required tools remain policy gates." + ), +): + """Run checks and write reports. Exit 0: policy passes; 1: fails; 2: invalid input.""" + root = (path_option or path).resolve() + cfg = policy(root, config) + if checks is not None: + selected = {name.strip() for name in checks.split(",") if name.strip()} + if not selected or selected - TOOL_INFO.keys(): + raise typer.BadParameter( + "--checks must name supported tools; see codeproof tools" + ) + for name in sorted(selected): + cfg.checks.setdefault(name, CheckConfig(weight=10)) + for name, check in cfg.checks.items(): + check.enabled = name in selected + with console.status("Running repository checks…"): + report = execute(root, cfg, fail_under, jobs) + table = Table("Check", "Status", "Required", "Time", "Summary") + for result in report.results: + table.add_row( + result.name, + result.status.value, + "yes" if result.required else "no", + f"{result.duration_seconds:.2f}s", + result.summary, + ) + console.print(table) + console.print( + f"Score {report.score}/100 ({report.grade}); policy {'PASS' if report.policy_passed else 'FAIL'} (threshold {report.fail_under:g})" + ) + for dest in write(report, root / output, format.value): + console.print(f"Report: {dest}") raise typer.Exit(0 if report.policy_passed else 1) -if __name__=="__main__":app() + + +if __name__ == "__main__": + app() diff --git a/src/codeproof/config.py b/src/codeproof/config.py index e13d346..a307bbb 100644 --- a/src/codeproof/config.py +++ b/src/codeproof/config.py @@ -1,11 +1,95 @@ +"""Validated scan policies, with partial files layered over safe defaults.""" + from pathlib import Path +from typing import Literal + import yaml -from pydantic import BaseModel,Field +from pydantic import BaseModel, ConfigDict, Field, model_validator + +TOOL_INFO = { + "imports": ("Import smoke", "Executes each source module in a subprocess", None), + "ruff": ("Lint", "Fast Python lint checks", "checkers"), + "mypy": ("Types", "Static type analysis", "checkers"), + "pytest": ("Tests", "Executes the repository test suite", "checkers"), + "bandit": ("Security", "Python security analysis", "checkers"), + "semgrep": ( + "Patterns", + "Security rules (auto rules may use the network)", + "checkers", + ), + "syntax": ( + "Syntax", + "Compiles source without executing it or writing bytecode", + None, + ), + "pip-audit": ( + "Dependencies", + "Audits requirements.txt against vulnerability services", + "audit", + ), +} + + class CheckConfig(BaseModel): - enabled:bool=True; weight:float=1; config:str|None=None + model_config = ConfigDict(extra="forbid") + enabled: bool = True + weight: float = Field(default=1, ge=0, allow_inf_nan=False) + config: str | None = None + + class Config(BaseModel): - version:int=1; fail_under:float=70; source_paths:list[str]=Field(default_factory=lambda:["src"]); test_paths:list[str]=Field(default_factory=lambda:["tests"]); timeout_seconds:int=300; required_tools:list[str]=Field(default_factory=lambda:["ruff","pytest"]); checks:dict[str,CheckConfig]=Field(default_factory=dict) -DEFAULT=Config(checks={"imports":CheckConfig(weight=10),"ruff":CheckConfig(weight=15),"mypy":CheckConfig(weight=15),"pytest":CheckConfig(weight=30),"bandit":CheckConfig(weight=15),"semgrep":CheckConfig(weight=15,config="auto")}) -def load(root:Path, explicit:Path|None=None)->Config: - p=explicit or root/".codeproof.yml" - return DEFAULT.model_copy(deep=True) if not p.exists() else Config.model_validate(yaml.safe_load(p.read_text()) or {}) + model_config = ConfigDict(extra="forbid") + version: Literal[1] = 1 + fail_under: float = Field(default=70, ge=0, le=100, allow_inf_nan=False) + source_paths: list[str] = Field(default_factory=lambda: ["src"]) + test_paths: list[str] = Field(default_factory=lambda: ["tests"]) + timeout_seconds: int = Field(default=300, ge=1) + jobs: int = Field(default=1, ge=1, le=8) + required_tools: list[str] = Field(default_factory=lambda: ["ruff", "pytest"]) + checks: dict[str, CheckConfig] = Field(default_factory=dict) + + @model_validator(mode="after") + def valid_policy(self): + unknown = (set(self.checks) | set(self.required_tools)) - TOOL_INFO.keys() + if unknown: + raise ValueError("Unknown tools: " + ", ".join(sorted(unknown))) + if not self.source_paths or not self.test_paths: + raise ValueError("source_paths and test_paths must not be empty") + if any(not path.strip() for path in self.source_paths + self.test_paths): + raise ValueError("Source and test paths must not be blank") + return self + + +DEFAULT = Config( + checks={ + "imports": CheckConfig(weight=10), + "ruff": CheckConfig(weight=15), + "mypy": CheckConfig(weight=15), + "pytest": CheckConfig(weight=30), + "bandit": CheckConfig(weight=15), + "semgrep": CheckConfig(weight=15, config="auto"), + } +) + + +def load(root: Path, explicit: Path | None = None) -> Config: + path = explicit if explicit is not None else root / ".codeproof.yml" + if not path.exists(): + if explicit is not None: + raise ValueError(f"Policy file not found: {path}") + return DEFAULT.model_copy(deep=True) + data = yaml.safe_load(path.read_text(encoding="utf-8")) + if data is None: + data = {} + if not isinstance(data, dict): + raise TypeError("Policy must be a YAML mapping") + defaults = DEFAULT.model_dump() + overrides = data.get("checks", {}) + if not isinstance(overrides, dict): + raise TypeError("checks must be a YAML mapping") + checks = defaults["checks"] + for name, settings in overrides.items(): + if not isinstance(settings, dict): + raise TypeError(f"Check {name} must be a YAML mapping") + checks[name] = {**checks.get(name, {}), **settings} + return Config.model_validate({**defaults, **data, "checks": checks}) diff --git a/src/codeproof/core.py b/src/codeproof/core.py index b767863..a92b010 100644 --- a/src/codeproof/core.py +++ b/src/codeproof/core.py @@ -1,19 +1,97 @@ -from datetime import datetime,timezone -from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +from datetime import datetime, timezone + from . import __version__ from .adapters import run -from .models import ScanReport,Status -def grade(x:float)->str:return "A" if x>=90 else "B" if x>=80 else "C" if x>=70 else "D" if x>=60 else "F" -def scan(root,cfg,fail_under=None): - results=[] - for name,c in cfg.checks.items(): - if not c.enabled:continue - r=run(name,root,c.config,cfg.timeout_seconds,cfg.source_paths,cfg.test_paths);r.weight=c.weight;r.required=name in cfg.required_tools;results.append(r) - included=[r for r in results if r.status not in (Status.unavailable,Status.skipped) or r.required] - denominator=sum(r.weight for r in included);score=100*sum(r.weight for r in included if r.status==Status.passed)/denominator if denominator else 0 - threshold=cfg.fail_under if fail_under is None else fail_under - required_ok=all(not r.required or r.status==Status.passed for r in results) - unavailable=[r.name for r in results if r.status==Status.unavailable and not r.required] - limitations=["Passing configured checks is not proof of correctness.","pytest and import checks may execute repository code."] - if unavailable:limitations.append("Optional checks excluded from score: "+", ".join(unavailable)) - return ScanReport(project=root.name,target=str(root),generated_at=datetime.now(timezone.utc).isoformat(),codeproof_version=__version__,score=round(score,2),grade=grade(score),policy_passed=score>=threshold and required_ok,fail_under=threshold,results=results,limitations=limitations) +from .models import CheckResult, ScanReport, Status + + +def grade(x: float) -> str: + return ( + "A" + if x >= 90 + else "B" + if x >= 80 + else "C" + if x >= 70 + else "D" + if x >= 60 + else "F" + ) + + +def scan(root, cfg, fail_under=None, jobs=None): + threshold = cfg.fail_under if fail_under is None else fail_under + workers = cfg.jobs if jobs is None else jobs + if not 0 <= threshold <= 100: + raise ValueError("fail_under must be between 0 and 100") + if not 1 <= workers <= 8: + raise ValueError("jobs must be between 1 and 8") + selected = [(name, check) for name, check in cfg.checks.items() if check.enabled] + + def execute(item): + name, check = item + result = run( + name, + root, + check.config, + cfg.timeout_seconds, + cfg.source_paths, + cfg.test_paths, + ) + result.weight = check.weight + result.required = name in cfg.required_tools + return result + + # map preserves policy order even when workers finish out of order. + with ThreadPoolExecutor(max_workers=workers) as pool: + results = list(pool.map(execute, selected)) + for name in dict.fromkeys(cfg.required_tools): + if not any(result.name == name for result in results): + results.append( + CheckResult( + name=name, + status=Status.skipped, + required=True, + summary="Required check is disabled or absent from the policy", + ) + ) + included = [ + r + for r in results + if r.status not in (Status.unavailable, Status.skipped) or r.required + ] + denominator = sum(r.weight for r in included) + score = ( + 100 * sum(r.weight for r in included if r.status == Status.passed) / denominator + if denominator + else 0 + ) + required_ok = all(not r.required or r.status == Status.passed for r in results) + unavailable = [ + r.name for r in results if r.status == Status.unavailable and not r.required + ] + limitations = [ + "Passing configured checks is not proof of correctness.", + "pytest and import checks may execute repository code.", + ] + if unavailable: + limitations.append( + "Optional checks excluded from score: " + ", ".join(unavailable) + ) + if denominator == 0: + limitations.append( + "No weighted checks contributed evidence; policy cannot pass." + ) + return ScanReport( + project=root.name, + target=str(root), + generated_at=datetime.now(timezone.utc).isoformat(), + codeproof_version=__version__, + score=round(score, 2), + grade=grade(score), + policy_passed=score >= threshold and required_ok and denominator > 0, + fail_under=threshold, + results=results, + limitations=limitations, + ) diff --git a/src/codeproof/discovery.py b/src/codeproof/discovery.py index ef78d1b..f010d17 100644 --- a/src/codeproof/discovery.py +++ b/src/codeproof/discovery.py @@ -1,19 +1,46 @@ import ast +from collections import defaultdict from pathlib import Path -def symbols(root:Path,sources:list[str]): - out=[] - for src in sources: - base=root/src - for p in base.rglob("*.py") if base.exists() else []: - try:tree=ast.parse(p.read_text()) - except SyntaxError:continue - for n in tree.body: - if isinstance(n,(ast.FunctionDef,ast.AsyncFunctionDef,ast.ClassDef)) and not n.name.startswith("_"):out.append((n.name,p.relative_to(root),n.lineno)) + +from .files import python_files + + +def symbols(root: Path, sources: list[str]): + out = [] + for path, _ in python_files(root, sources): + try: + tree = ast.parse(path.read_bytes()) + except (SyntaxError, UnicodeError): + continue + for node in tree.body: + if isinstance( + node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef) + ) and not node.name.startswith("_"): + out.append((node.name, path.relative_to(root), node.lineno)) return out -def generate(root:Path,sources:list[str],output:Path,force=False): - output.mkdir(parents=True,exist_ok=True);made=[] - for name,p,line in symbols(root,sources): - src=next((s for s in sources if str(p).startswith(s+"/")),sources[0]);mod=".".join(Path(p).relative_to(src).with_suffix("").parts);dest=output/f"test_{mod.replace('.','_')}_generated.py" - text=(dest.read_text() if dest.exists() else f'import importlib\nmodule=importlib.import_module("{mod}")\n')+f'\ndef test_{name}_is_exposed():\n assert hasattr(module,"{name}")\n' - if force or not dest.exists():dest.write_text(text);made.append(dest) + + +def generate(root: Path, sources: list[str], output: Path, force=False): + output.mkdir(parents=True, exist_ok=True) + groups = defaultdict(list) + bases = {path.relative_to(root): base for path, base in python_files(root, sources)} + for name, path, _ in symbols(root, sources): + parts = list((root / path).relative_to(bases[path]).with_suffix("").parts) + if parts[-1] == "__init__": + parts.pop() + module = ".".join(parts) + if module: + groups[module].append(name) + made = [] + for module, names in groups.items(): + # Length-prefix components to avoid collisions such as a_b.c and a.b_c. + slug = "_".join(f"{len(part)}_{part}" for part in module.split(".")) + dest = output / f"test_{slug}_generated.py" + if dest.exists() and not force: + continue + text = f"import importlib\n\nmodule = importlib.import_module({module!r})\n" + for name in names: + text += f"\n\ndef test_{name}_is_exposed():\n assert hasattr(module, {name!r})\n" + dest.write_text(text, encoding="utf-8") + made.append(dest) return made diff --git a/src/codeproof/files.py b/src/codeproof/files.py new file mode 100644 index 0000000..842eda8 --- /dev/null +++ b/src/codeproof/files.py @@ -0,0 +1,49 @@ +"""Shared deterministic traversal; never descend into caches or environments.""" + +import os +from pathlib import Path + +EXCLUDED = { + ".git", + ".venv", + "venv", + "env", + "__pycache__", + ".pytest_cache", + ".mypy_cache", + ".ruff_cache", + ".codeproof", + "node_modules", + "build", + "dist", +} + + +def python_files(root: Path, sources: list[str]): + seen = set() + for source in sources: + base = root / source + if base.is_file(): + candidates = [base] if base.suffix == ".py" else [] + else: + candidates = [] + for directory, folders, names in os.walk(base, followlinks=False): + folders[:] = sorted( + name + for name in folders + if name not in EXCLUDED + and not (Path(directory) / name).is_symlink() + ) + candidates.extend( + Path(directory) / name + for name in sorted(names) + if name.endswith(".py") + ) + for path in candidates: + if path.is_symlink(): + continue + resolved = path.resolve() + if not resolved.is_relative_to(root.resolve()) or resolved in seen: + continue + seen.add(resolved) + yield path, base if base.is_dir() else base.parent diff --git a/src/codeproof/models.py b/src/codeproof/models.py index bdf46fb..b35a30f 100644 --- a/src/codeproof/models.py +++ b/src/codeproof/models.py @@ -1,11 +1,48 @@ from enum import Enum from typing import Any + from pydantic import BaseModel, Field -class Status(str,Enum): - passed="passed"; failed="failed"; unavailable="unavailable"; error="error"; skipped="skipped" + + +class Status(str, Enum): + passed = "passed" + failed = "failed" + unavailable = "unavailable" + error = "error" + skipped = "skipped" + + class Finding(BaseModel): - level:str="info"; message:str; path:str|None=None; line:int|None=None; rule:str|None=None + level: str = "info" + message: str + path: str | None = None + line: int | None = None + rule: str | None = None + + class CheckResult(BaseModel): - name:str; status:Status; command:list[str]=Field(default_factory=list); duration_seconds:float=0; exit_code:int|None=None; summary:str=""; findings:list[Finding]=Field(default_factory=list); evidence:dict[str,Any]=Field(default_factory=dict); raw_output:str|None=None; weight:float=0; required:bool=False + name: str + status: Status + command: list[str] = Field(default_factory=list) + duration_seconds: float = 0 + exit_code: int | None = None + summary: str = "" + findings: list[Finding] = Field(default_factory=list) + evidence: dict[str, Any] = Field(default_factory=dict) + raw_output: str | None = None + weight: float = 0 + required: bool = False + + class ScanReport(BaseModel): - schema_version:str="1.0"; project:str; target:str; generated_at:str; codeproof_version:str; score:float; grade:str; policy_passed:bool; fail_under:float; results:list[CheckResult]; limitations:list[str]=Field(default_factory=list) + schema_version: str = "1.0" + project: str + target: str + generated_at: str + codeproof_version: str + score: float + grade: str + policy_passed: bool + fail_under: float + results: list[CheckResult] + limitations: list[str] = Field(default_factory=list) diff --git a/src/codeproof/report_template.html b/src/codeproof/report_template.html new file mode 100644 index 0000000..e62b987 --- /dev/null +++ b/src/codeproof/report_template.html @@ -0,0 +1,64 @@ + + + + +@@project@@ · CodeProof report + + + +
CodeProof / Repository insights
Local first · Evidence driven
+
+
Verification report

@@project@@

A clearer picture of your repository’s health.

Report snapshot · v@@version@@
+
+
@@score@@OUT OF 100
Weighted confidence

Grade @@grade@@

@@passed@@ of @@total@@ checks passed

+
Policy result
@@policy@@

Threshold: @@threshold@@ / 100
All required checks must pass

+
Needs attention
@@attention@@ checks

@@findings@@ normalized findings
Expand a check for its evidence

+
+

Check results

Inspect the evidence behind your score.

+ +
@@cards@@

+ + +
+ + + diff --git a/src/codeproof/reporting.py b/src/codeproof/reporting.py index f68a561..bfcd273 100644 --- a/src/codeproof/reporting.py +++ b/src/codeproof/reporting.py @@ -1,17 +1,134 @@ -from pathlib import Path from html import escape -def markdown(r): - rows=["| Check | Status | Weight | Summary |","|---|---|---:|---|"]+[f"| {x.name} | {x.status.value} | {x.weight:g} | {x.summary} |" for x in r.results] - return f"# CodeProof: {r.project}\n\n**Score:** {r.score}/100 ({r.grade}) \n**Policy:** {'PASS' if r.policy_passed else 'FAIL'}\n\n"+"\n".join(rows)+"\n\n## Limitations\n"+"\n".join('- '+x for x in r.limitations) -def html(r): - rows=''.join(f'{escape(x.name)}{x.status.value}{x.weight:g}{escape(x.summary)}' for x in r.results) - return f'CodeProof

CodeProof: {escape(r.project)}

{r.score}/100 ({r.grade})

Policy: {"PASS" if r.policy_passed else "FAIL"}

{rows}
CheckStatusWeightSummary
' -def write(r,out:Path,fmt:str): - out.mkdir(parents=True,exist_ok=True);made=[] - if fmt in ("all","json"):p=out/"codeproof-report.json";p.write_text(r.model_dump_json(indent=2));made.append(p) - if fmt in ("all","markdown"):p=out/"codeproof-report.md";p.write_text(markdown(r));made.append(p) - if fmt in ("all","html"):p=out/"codeproof-report.html";p.write_text(html(r));made.append(p) - raw=out.parent/"raw";raw.mkdir(parents=True,exist_ok=True) - for x in r.results: - if x.raw_output:(raw/f"{x.name}.txt").write_text(x.raw_output) +from pathlib import Path + +from .models import ScanReport, Status + + +def cell(value): + return ( + str(value) + .replace("\\", "\\\\") + .replace("|", "\\|") + .replace("\n", "
") + .replace("\r", "") + ) + + +def markdown(report: ScanReport): + rows = [ + "| Check | Status | Required | Weight | Duration | Summary |", + "|---|---|---|---:|---:|---|", + ] + for result in report.results: + rows.append( + f"| {cell(result.name)} | {result.status.value} | {'yes' if result.required else 'no'} | " + f"{result.weight:g} | {result.duration_seconds:.2f}s | {cell(result.summary)} |" + ) + text = ( + f"# CodeProof: {cell(report.project)}\n\n**Score:** {report.score}/100 ({report.grade}) \n" + f"**Policy:** {'PASS' if report.policy_passed else 'FAIL'} · threshold {report.fail_under:g}\n\n" + + "\n".join(rows) + ) + for result in report.results: + if result.findings: + text += f"\n\n## {cell(result.name)} findings\n" + for finding in result.findings: + location = f"{finding.path or ''}{':' + str(finding.line) if finding.line else ''}" + text += f"\n- {cell(finding.rule or finding.level)} · {cell(location)}: {cell(finding.message)}" + return ( + text + + "\n\n## Limitations\n" + + "\n".join("- " + cell(item) for item in report.limitations) + + "\n" + ) + + +def html(report: ScanReport): + cards = [] + for result in report.results: + findings = "".join( + f'
  • {escape(item.rule or item.level)}' + f"{escape(item.path or 'No file location')}{':' + str(item.line) if item.line else ''}
    " + f"

    {escape(item.message)}

  • " + for item in result.findings + ) + detail = ( + f'

    Findings ({len(result.findings)})

    ' + if findings + else "" + ) + if result.command: + detail += ( + "

    Command arguments

    "
    +                + escape(str(result.command))
    +                + "
    " + ) + if result.raw_output: + detail += "

    Tool output

    " + escape(result.raw_output) + "
    " + if result.evidence: + detail += "

    Evidence

    " + escape(str(result.evidence)) + "
    " + cards.append( + f'
    ' + f'
    ' + f'{escape(result.name)}{escape(result.summary)}' + f'{"Required" if result.required else "Optional"}' + f'{result.duration_seconds:.2f}s' + f'{result.status.value}⌄' + f'

    Policy weight: {result.weight:g}

    {detail or "

    No additional evidence.

    "}
    ' + "
    " + ) + template = ( + Path(__file__).with_name("report_template.html").read_text(encoding="utf-8") + ) + passed = sum(result.status == Status.passed for result in report.results) + attention = sum( + result.status in (Status.failed, Status.error) + or (result.required and result.status != Status.passed) + for result in report.results + ) + replacements = { + "project": escape(report.project), + "target": escape(report.target), + "generated": escape(report.generated_at), + "score": f"{report.score:g}", + "grade": escape(report.grade), + "policy": "Passed" if report.policy_passed else "Failed", + "policy_class": "passed" if report.policy_passed else "failed", + "threshold": f"{report.fail_under:g}", + "passed": str(passed), + "total": str(len(report.results)), + "attention": str(attention), + "findings": str(sum(len(result.findings) for result in report.results)), + "cards": "".join(cards), + "limitations": "".join( + f"
  • {escape(item)}
  • " for item in report.limitations + ), + "version": escape(report.codeproof_version), + } + # One replacement pass prevents report text from being interpreted as template tokens. + import re + + return re.sub(r"@@(\w+)@@", lambda match: replacements[match[1]], template) + + +def write(report: ScanReport, out: Path, fmt: str): + if fmt not in {"all", "json", "markdown", "html"}: + raise ValueError(f"Unsupported report format: {fmt}") + out.mkdir(parents=True, exist_ok=True) + made = [] + renderers = { + "json": ("json", lambda: report.model_dump_json(indent=2)), + "markdown": ("md", lambda: markdown(report)), + "html": ("html", lambda: html(report)), + } + for name, (suffix, render) in renderers.items(): + if fmt in ("all", name): + path = out / f"codeproof-report.{suffix}" + path.write_text(render(), encoding="utf-8") + made.append(path) + raw = out.parent / "raw" + raw.mkdir(parents=True, exist_ok=True) + for result in report.results: + if result.raw_output: + (raw / f"{result.name}.txt").write_text(result.raw_output, encoding="utf-8") return made diff --git a/tests/test_adapters.py b/tests/test_adapters.py new file mode 100644 index 0000000..607cb11 --- /dev/null +++ b/tests/test_adapters.py @@ -0,0 +1,92 @@ +import subprocess + +from codeproof.adapters import imports, parse_findings, run, syntax + + +def test_syntax_does_not_execute_or_write_bytecode(tmp_path): + (tmp_path / "valid.py").write_text('raise RuntimeError("must not execute")\n') + result = syntax(tmp_path, ["."]) + assert result.status == "passed" + assert not (tmp_path / "__pycache__").exists() + (tmp_path / "bad.py").write_text("def broken(:\n") + result = syntax(tmp_path, ["."]) + assert result.status == "failed" + assert result.findings[0].path == "bad.py" + assert result.findings[0].line == 1 + + +def test_traversal_prunes_environments_and_duplicates(tmp_path): + (tmp_path / ".venv").mkdir() + (tmp_path / ".venv" / "bad.py").write_text("def broken(:") + (tmp_path / "ok.py").write_text("x = 1") + result = syntax(tmp_path, [".", "."]) + assert result.status == "passed" + assert result.evidence["files_checked"] == 1 + assert syntax(tmp_path, ["absent"]).status == "skipped" + + +def test_import_timeout_is_a_result(monkeypatch, tmp_path): + (tmp_path / "slow.py").write_text("") + + def timeout(*args, **kwargs): + raise subprocess.TimeoutExpired(args[0], 1) + + monkeypatch.setattr(subprocess, "run", timeout) + assert imports(tmp_path, ["."], 1).status == "error" + + +def test_subprocess_timeout_and_launch_failure(monkeypatch, tmp_path): + monkeypatch.setattr("shutil.which", lambda name: "/bin/tool") + for error in (subprocess.TimeoutExpired("ruff", 1), OSError("cannot start")): + + def fail(*args, error=error, **kwargs): + raise error + + monkeypatch.setattr(subprocess, "run", fail) + assert run("ruff", tmp_path, None, 1, ["."], ["tests"]).status == "error" + + +def test_findings_parsed_before_raw_truncation_and_stderr(monkeypatch, tmp_path): + monkeypatch.setattr("shutil.which", lambda name: "/bin/ruff") + payload = ( + '[{"message":"unused","filename":"app.py","location":{"row":3},"code":"F401"}]' + ) + monkeypatch.setattr( + subprocess, + "run", + lambda *a, **k: subprocess.CompletedProcess(a[0], 1, payload, "diagnostic"), + ) + result = run("ruff", tmp_path, None, 1, ["."], ["tests"]) + assert result.findings[0].rule == "F401" + assert result.findings[0].line == 3 + assert "diagnostic" in result.raw_output + + +def test_supported_json_schemas(): + assert ( + parse_findings( + "bandit", + '{"results":[{"issue_text":"unsafe","test_id":"B1","line_number":4}]}', + )[0].rule + == "B1" + ) + assert ( + parse_findings( + "semgrep", '{"results":[{"extra":{"message":"unsafe"},"check_id":"S1"}]}' + )[0].rule + == "S1" + ) + assert ( + parse_findings( + "pip-audit", + '{"dependencies":[{"name":"demo","version":"1","vulns":[{"id":"CVE-TEST"}]}]}', + )[0].rule + == "CVE-TEST" + ) + assert parse_findings("ruff", "invalid output") == [] + + +def test_dependency_audit_does_not_fall_back_to_environment(tmp_path): + result = run("pip-audit", tmp_path, None, 1, ["."], ["tests"]) + assert result.status == "unavailable" + assert "requirements.txt" in result.summary diff --git a/tests/test_config.py b/tests/test_config.py index a0712e4..bc107ca 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -1,2 +1,5 @@ from codeproof.config import DEFAULT -def test_weights():assert sum(x.weight for x in DEFAULT.checks.values())==100 + + +def test_weights(): + assert sum(x.weight for x in DEFAULT.checks.values()) == 100 diff --git a/tests/test_core.py b/tests/test_core.py index 1ca5caf..266646e 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -1,3 +1,5 @@ from codeproof.core import grade + + def test_grade(): - assert grade(90)=="A" and grade(70)=="C" and grade(59)=="F" + assert grade(90) == "A" and grade(70) == "C" and grade(59) == "F" diff --git a/tests/test_discovery.py b/tests/test_discovery.py new file mode 100644 index 0000000..fb1ba1c --- /dev/null +++ b/tests/test_discovery.py @@ -0,0 +1,25 @@ +import ast + +from codeproof.discovery import generate + + +def test_generates_all_symbols_once_and_preserves_manual_edits(tmp_path): + src = tmp_path / "src" / "pkg" + src.mkdir(parents=True) + (src / "api.py").write_text( + "def first(): pass\nasync def second(): pass\nclass Third: pass\n" + ) + (src / "__init__.py").write_text("def exported(): pass\n") + out = tmp_path / "generated" + made = generate(tmp_path, ["src"], out) + assert len(made) == 2 + text = next(p.read_text() for p in made if "first" in p.read_text()) + tree = ast.parse(text) + assert len([n for n in tree.body if isinstance(n, ast.FunctionDef)]) == 3 + package = next(p for p in made if "exported" in p.read_text()) + assert "import_module('pkg')" in package.read_text() + package.write_text("# manual") + assert generate(tmp_path, ["src"], out) == [] + assert package.read_text() == "# manual" + assert len(generate(tmp_path, ["src"], out, force=True)) == 2 + assert "exported" in package.read_text() diff --git a/tests/test_policy.py b/tests/test_policy.py new file mode 100644 index 0000000..cae49a2 --- /dev/null +++ b/tests/test_policy.py @@ -0,0 +1,97 @@ +from pathlib import Path +from threading import Barrier + +import pytest +from pydantic import ValidationError + +from codeproof.config import DEFAULT, CheckConfig, Config, load +from codeproof.core import scan +from codeproof.models import CheckResult, Status + + +def test_partial_policy_keeps_checks_and_weights(tmp_path): + (tmp_path / ".codeproof.yml").write_text("checks:\n ruff:\n weight: 22\n") + config = load(tmp_path) + assert config.checks["ruff"].weight == 22 + assert config.checks["pytest"].weight == 30 + assert config.checks["semgrep"].config == "auto" + config.checks["pytest"].enabled = False + assert DEFAULT.checks["pytest"].enabled + + +@pytest.mark.parametrize( + "text", + [ + "[]", + "checks: []", + "checks:\n ruff: false", + "jobs: 0", + "fail_under: 101", + "fail_under: .nan", + "required_tools: [typo]", + "checks:\n ruff:\n weight: -1", + "version: 2", + "typo: true", + ], +) +def test_invalid_policy(tmp_path, text): + (tmp_path / ".codeproof.yml").write_text(text) + with pytest.raises((ValueError, TypeError, ValidationError)): + load(tmp_path) + + +def test_explicit_missing_policy(tmp_path): + with pytest.raises(ValueError, match="not found"): + load(tmp_path, Path("missing.yml")) + + +def result(name, root, cfg, timeout, sources, tests): + return CheckResult(name=name, status=Status.passed) + + +def test_disabled_and_absent_required_tools_fail(monkeypatch, tmp_path): + monkeypatch.setattr("codeproof.core.run", result) + cfg = Config( + checks={"syntax": CheckConfig(weight=100), "ruff": CheckConfig(enabled=False)} + ) + report = scan(tmp_path, cfg) + assert report.score == 100 + assert not report.policy_passed + assert {r.name for r in report.results if r.required} == {"ruff", "pytest"} + + +def test_empty_evidence_never_passes_at_zero(tmp_path): + assert not scan(tmp_path, Config(required_tools=[], fail_under=0)).policy_passed + + +def test_optional_unavailable_excluded_but_required_blocks(monkeypatch, tmp_path): + def run(name, *args): + return CheckResult( + name=name, status=Status.passed if name == "syntax" else Status.unavailable + ) + + monkeypatch.setattr("codeproof.core.run", run) + cfg = Config( + required_tools=[], checks={"syntax": CheckConfig(), "ruff": CheckConfig()} + ) + report = scan(tmp_path, cfg) + assert report.score == 100 and report.policy_passed + cfg.required_tools = ["ruff"] + report = scan(tmp_path, cfg) + assert report.score == 50 and not report.policy_passed + + +def test_parallel_checks_preserve_order(monkeypatch, tmp_path): + barrier = Barrier(2, timeout=5) + + def run(name, *args): + barrier.wait() + return CheckResult(name=name, status=Status.passed) + + monkeypatch.setattr("codeproof.core.run", run) + cfg = Config( + required_tools=[], checks={"syntax": CheckConfig(), "ruff": CheckConfig()} + ) + report = scan(tmp_path, cfg, jobs=2) + assert [r.name for r in report.results] == ["syntax", "ruff"] + assert report.policy_passed diff --git a/tests/test_reports_cli.py b/tests/test_reports_cli.py new file mode 100644 index 0000000..7933d2e --- /dev/null +++ b/tests/test_reports_cli.py @@ -0,0 +1,85 @@ +import json + +from typer.testing import CliRunner + +from codeproof.cli import app +from codeproof.config import Config +from codeproof.core import scan +from codeproof.models import CheckResult, Finding, Status +from codeproof.reporting import html, markdown, write + +runner = CliRunner() + + +def test_report_escapes_untrusted_evidence(tmp_path): + report = scan(tmp_path, Config(required_tools=[])) + report.project = "@@cards@@" + report.results = [ + CheckResult( + name="ruff", + status=Status.failed, + summary="a | b\nnext", + raw_output="", + findings=[Finding(message="", path="a.py", line=2)], + ) + ] + page = html(report) + assert " + + + +
    Local mode
    +
    BUILD WITH CONFIDENCE

    Repository overview

    Your code quality, security, and test evidence. In one place.

    +
    YOUR NEXT RELEASE STARTS HERE

    Ship with evidence.

    Find issues earlier. Understand what changed.
    Give every release a clear quality signal.

    +
    +

    Quality trend

    Your latest completed runs

    View history ↗

    Developer toolchain

    Ready for your next check

    ◇
    Explore all tools →
    +

    Latest scan results

    Start a scan to build your first report.

    Findings explorer

    0 findings
    + + + + +
    +
    START A VERIFICATION RUN

    Make your next commit count.

    Choose the right checks for this stage of your workflow.

    Checks in this run

    Required policy gates remain in effect.
    +

    Check evidence

    + diff --git a/src/codeproof/workspace.py b/src/codeproof/workspace.py new file mode 100644 index 0000000..2828dc4 --- /dev/null +++ b/src/codeproof/workspace.py @@ -0,0 +1,373 @@ +"""A repository-scoped local workspace with bounded, durable scan history.""" + +import json +import secrets +import shutil +import sqlite3 +import threading +from contextlib import contextmanager +from datetime import datetime, timezone +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from typing import Literal +from urllib.parse import urlsplit +from uuid import uuid4 + +import yaml +from pydantic import BaseModel, ConfigDict, Field + +from .config import TOOL_INFO, CheckConfig, load +from .core import scan +from .models import ScanReport +from .reporting import html, markdown, sarif + +PROFILES = { + "quality": { + "label": "Code quality", + "description": "Lint, types, tests and security before you commit.", + "tools": ["syntax", "ruff", "mypy", "pytest", "bandit"], + }, + "quick": { + "label": "Fast feedback", + "description": "Static checks plus your required policy gates.", + "tools": ["syntax", "ruff", "mypy"], + }, + "security": { + "label": "Security review", + "description": "Security patterns and dependency vulnerabilities.", + "tools": ["syntax", "bandit", "semgrep", "pip-audit"], + }, + "policy": { + "label": "Repository policy", + "description": "Run every enabled check in your policy.", + "tools": [], + }, +} + + +class ScanRequest(BaseModel): + model_config = ConfigDict(extra="forbid") + profile: Literal["quality", "quick", "security", "policy"] = "quality" + fail_under: float | None = Field(default=None, ge=0, le=100, allow_inf_nan=False) + jobs: int = Field(default=1, ge=1, le=8) + allow_execution: bool = False + allow_network: bool = False + + +def selected_policy(root: Path, request: ScanRequest): + cfg = load(root) + if request.profile != "policy": + selected = set(PROFILES[request.profile]["tools"]) | set(cfg.required_tools) + for name in PROFILES[request.profile]["tools"]: + if name not in cfg.checks: + cfg.checks[name] = CheckConfig(weight=10) + for name, check in cfg.checks.items(): + check.enabled = check.enabled and name in selected + cfg.jobs = request.jobs + if request.fail_under is not None: + cfg.fail_under = request.fail_under + return cfg + + +def capabilities(cfg, root: Path): + enabled = [name for name, check in cfg.checks.items() if check.enabled] + execution = bool(set(enabled) & {"pytest", "imports", "pip-audit", "mypy"}) + semgrep_config = ( + cfg.checks["semgrep"].config or "auto" if "semgrep" in cfg.checks else "auto" + ) + network = "pip-audit" in enabled or ( + "semgrep" in enabled + and (semgrep_config == "auto" or not (root / semgrep_config).exists()) + ) + return enabled, execution, network + + +class Workspace: + def __init__(self, root: Path): + self.root = root.resolve() + if not self.root.is_dir(): + raise ValueError("Repository directory does not exist") + self.directory = self.root / ".codeproof" / "workspace" + self.directory.mkdir(parents=True, exist_ok=True) + self.db = self.directory / "history.sqlite3" + self.lock = threading.Lock() + self.active: str | None = None + self.token = secrets.token_urlsafe(32) + with self.connect() as db: + db.execute( + "CREATE TABLE IF NOT EXISTS runs (id TEXT PRIMARY KEY, created TEXT NOT NULL, status TEXT NOT NULL, profile TEXT NOT NULL, report TEXT, error TEXT, score REAL, passed INTEGER, findings INTEGER)" + ) + db.execute( + "UPDATE runs SET status='interrupted', error='Workspace stopped before this scan completed' WHERE status='running'" + ) + + @contextmanager + def connect(self): + connection = sqlite3.connect(self.db, timeout=10) + try: + with connection: + yield connection + finally: + connection.close() + + def metadata(self): + cfg = load(self.root) + profiles = {} + for key, info in PROFILES.items(): + selected = selected_policy(self.root, ScanRequest(profile=key)) + enabled, execution, network = capabilities(selected, self.root) + profiles[key] = { + **info, + "tools": enabled, + "execution": execution, + "network": network, + } + return { + "project": self.root.name, + "target": str(self.root), + "token": self.token, + "policy": cfg.model_dump(mode="json"), + "policy_yaml": yaml.safe_dump(cfg.model_dump(mode="json"), sort_keys=False), + "profiles": profiles, + "tools": [ + { + "id": name, + "label": info[0], + "description": info[1], + "available": info[2] is None or bool(shutil.which(name)), + "install": f"pip install 'codeproof-ai[{info[2]}]'" + if info[2] + else "Included", + } + for name, info in TOOL_INFO.items() + ], + } + + def history(self): + with self.connect() as db: + rows = db.execute( + "SELECT id,created,status,profile,score,passed,findings,error FROM runs ORDER BY created DESC LIMIT 50" + ).fetchall() + summaries = [] + for id_, created, status, profile, score, passed, findings, error in rows: + summaries.append( + { + "id": id_, + "created": created, + "status": status, + "profile": profile, + "score": score, + "policy_passed": bool(passed) if passed is not None else None, + "findings": findings or 0, + "error": error, + } + ) + return summaries + + def report(self, id_: str): + with self.connect() as db: + row = db.execute("SELECT report FROM runs WHERE id=?", (id_,)).fetchone() + if not row or row[0] is None: + raise KeyError("Completed report not found") + return ScanReport.model_validate_json(row[0]) + + def start(self, request: ScanRequest): + cfg = selected_policy(self.root, request) + _, execution, network = capabilities(cfg, self.root) + if execution and not request.allow_execution: + raise ValueError( + "This profile executes repository or package code. Enable execution to continue." + ) + if network and not request.allow_network: + raise ValueError( + "This profile uses network services. Enable network access to continue." + ) + with self.lock: + if self.active: + raise RuntimeError("A scan is already running. Wait for it to finish.") + id_ = uuid4().hex + with self.connect() as db: + db.execute( + "INSERT INTO runs(id,created,status,profile) VALUES(?,?,?,?)", + ( + id_, + datetime.now(timezone.utc).isoformat(), + "running", + request.profile, + ), + ) + db.execute( + "DELETE FROM runs WHERE id NOT IN (SELECT id FROM runs ORDER BY created DESC LIMIT 50)" + ) + self.active = id_ + threading.Thread(target=self._execute, args=(id_, cfg), daemon=True).start() + return id_ + + def _execute(self, id_, cfg): + try: + report = scan(self.root, cfg) + with self.connect() as db: + db.execute( + "UPDATE runs SET status='complete',report=?,score=?,passed=?,findings=? WHERE id=?", + ( + report.model_dump_json(), + report.score, + int(report.policy_passed), + sum(len(r.findings) for r in report.results), + id_, + ), + ) + except Exception as exc: + with self.connect() as db: + db.execute( + "UPDATE runs SET status='error',error=? WHERE id=?", (str(exc), id_) + ) + finally: + with self.lock: + self.active = None + + +def make_server( + workspace: Workspace, host="127.0.0.1", port=8765, allowed_host: str | None = None +): + assets = Path(__file__).with_name("web") + allowed = {"localhost", "127.0.0.1", "::1"} + if allowed_host: + allowed.add(allowed_host.lower()) + + class Handler(BaseHTTPRequestHandler): + def setup(self): + super().setup() + self.connection.settimeout(15) + + def log_message(self, *args): + pass + + def respond( + self, data, status=200, content_type="application/json", attachment=None + ): + body = ( + json.dumps(data).encode() + if content_type == "application/json" + else data.encode() + ) + self.send_response(status) + self.send_header("Content-Type", content_type + "; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.send_header("Cache-Control", "no-store") + self.send_header("X-Content-Type-Options", "nosniff") + self.send_header("X-Frame-Options", "DENY") + self.send_header("Referrer-Policy", "no-referrer") + self.send_header( + "Content-Security-Policy", + "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'", + ) + if attachment: + self.send_header( + "Content-Disposition", f'attachment; filename="{attachment}"' + ) + self.end_headers() + self.wfile.write(body) + + def valid_host(self): + try: + return ( + urlsplit("http://" + self.headers.get("Host", "")).hostname + in allowed + ) + except ValueError: + return False + + def do_GET(self): + if not self.valid_host(): + self.respond({"error": "Host is not allowed"}, 403) + return + path = urlsplit(self.path).path + try: + if path == "/api/workspace": + self.respond(workspace.metadata()) + elif path == "/api/runs": + self.respond(workspace.history()) + elif path.startswith("/api/runs/"): + parts = path.split("/") + if len(parts) not in (4, 5): + raise KeyError("Not found") + report = workspace.report(parts[3]) + if len(parts) == 4: + self.respond(report.model_dump(mode="json")) + else: + exports = { + "json": ( + report.model_dump_json(indent=2), + "application/json", + ), + "html": (html(report), "text/html"), + "markdown": (markdown(report), "text/markdown"), + "sarif": ( + json.dumps(sarif(report), indent=2), + "application/sarif+json", + ), + } + if parts[4] not in exports: + raise KeyError("Unknown export") + content, kind = exports[parts[4]] + # Download documents rather than render tool output under the workspace origin. + self.respond( + content, + content_type=kind + if kind != "application/json" + else "application/octet-stream", + attachment=f"codeproof-{parts[3]}.{ {'markdown': 'md'}.get(parts[4], parts[4]) }", + ) + elif path in ("/", "/app.css", "/app.js"): + filename = { + "/": "index.html", + "/app.css": "app.css", + "/app.js": "app.js", + }[path] + kind = { + "/": "text/html", + "/app.css": "text/css", + "/app.js": "text/javascript", + }[path] + self.respond( + (assets / filename).read_text(encoding="utf-8"), + content_type=kind, + ) + else: + self.respond({"error": "Not found"}, 404) + except KeyError: + self.respond({"error": "Report not found"}, 404) + except (ValueError, TypeError, OSError, yaml.YAMLError) as exc: + self.respond({"error": str(exc)}, 400) + + def do_POST(self): + if not self.valid_host() or not secrets.compare_digest( + self.headers.get("X-CodeProof-Token", ""), workspace.token + ): + self.respond({"error": "Invalid workspace session"}, 403) + return + origin = self.headers.get("Origin") + if origin and origin not in ( + "http://" + self.headers.get("Host", ""), + "https://" + self.headers.get("Host", ""), + ): + self.respond({"error": "Origin is not allowed"}, 403) + return + if self.path != "/api/scan": + self.respond({"error": "Not found"}, 404) + return + try: + length = int(self.headers.get("Content-Length", "0")) + if length <= 0 or length > 65536: + raise ValueError("Request must contain 1–65536 bytes") + request = ScanRequest.model_validate_json(self.rfile.read(length)) + self.respond({"id": workspace.start(request)}, 202) + except RuntimeError as exc: + self.respond({"error": str(exc)}, 409) + except (ValueError, TypeError, OSError, yaml.YAMLError) as exc: + self.respond({"error": str(exc)}, 400) + + server = ThreadingHTTPServer((host, port), Handler) + server.daemon_threads = True + return server diff --git a/tests/test_workspace.py b/tests/test_workspace.py new file mode 100644 index 0000000..627e19f --- /dev/null +++ b/tests/test_workspace.py @@ -0,0 +1,194 @@ +import json +import threading +import time +from urllib.error import HTTPError +from urllib.request import Request, urlopen + +import pytest + +from codeproof.config import CheckConfig, Config +from codeproof.core import scan +from codeproof.models import CheckResult, Finding, Status +from codeproof.reporting import sarif, write +from codeproof.workspace import ScanRequest, Workspace, make_server, selected_policy + + +def wait_for(workspace): + end = time.monotonic() + 5 + while workspace.active and time.monotonic() < end: + time.sleep(0.01) + assert not workspace.active + + +@pytest.fixture +def root(tmp_path): + (tmp_path / ".codeproof.yml").write_text( + "required_tools: []\nsource_paths: [src]\nchecks:\n mypy: {enabled: false}\n ruff: {enabled: false}\n pytest: {enabled: false}\n" + ) + (tmp_path / "src").mkdir() + (tmp_path / "src/app.py").write_text("x = 1") + return tmp_path + + +def test_policy_profiles_preserve_required_disabled_tools(tmp_path): + (tmp_path / ".codeproof.yml").write_text("checks:\n pytest: {enabled: false}") + cfg = selected_policy(tmp_path, ScanRequest(profile="quick")) + assert "pytest" in cfg.required_tools + assert not cfg.checks["pytest"].enabled + assert cfg.checks["syntax"].enabled + assert cfg.checks["ruff"].weight == 15 + + +def test_durable_run_and_restart(root): + workspace = Workspace(root) + id_ = workspace.start(ScanRequest(profile="quick")) + wait_for(workspace) + assert workspace.history()[0]["score"] == 100 + assert workspace.report(id_).policy_passed + restored = Workspace(root) + assert restored.report(id_).results[0].name == "syntax" + with restored.connect() as db: + db.execute( + "INSERT INTO runs(id,created,status,profile) VALUES('interrupted','9999','running','quick')" + ) + assert Workspace(root).history()[0]["status"] == "interrupted" + + +def test_single_scan_admission_and_errors(root, monkeypatch): + started, release = threading.Event(), threading.Event() + + def slow(*args): + started.set() + release.wait(5) + raise ValueError("scan failed") + + monkeypatch.setattr("codeproof.workspace.scan", slow) + workspace = Workspace(root) + workspace.start(ScanRequest(profile="quick")) + assert started.wait(1) + with pytest.raises(RuntimeError, match="already running"): + workspace.start(ScanRequest(profile="quick")) + release.set() + wait_for(workspace) + assert workspace.history()[0]["status"] == "error" + assert workspace.history()[0]["error"] == "scan failed" + + +def test_history_retention(root): + workspace = Workspace(root) + with workspace.connect() as db: + db.executemany( + "INSERT INTO runs(id,created,status,profile) VALUES(?,?,?,?)", + [(str(i), f"2000-{i:03}", "error", "quick") for i in range(60)], + ) + workspace.start(ScanRequest(profile="quick")) + wait_for(workspace) + with workspace.connect() as db: + assert db.execute("SELECT count(*) FROM runs").fetchone()[0] == 50 + assert len(workspace.history()) == 50 + + +def test_execution_and_network_opt_ins(tmp_path): + workspace = Workspace(tmp_path) + with pytest.raises(ValueError, match="executes"): + workspace.start(ScanRequest(profile="quality")) + with pytest.raises(ValueError, match="network"): + workspace.start(ScanRequest(profile="security", allow_execution=True)) + with pytest.raises(ValueError): + ScanRequest.model_validate({"profile": "quick", "root": "/tmp"}) + # Remote Semgrep registry configurations also require network opt-in. + (tmp_path / ".codeproof.yml").write_text("checks:\n semgrep: {config: p/python}") + assert workspace.metadata()["profiles"]["security"]["network"] + + +@pytest.fixture +def api_server(root): + workspace = Workspace(root) + server = make_server(workspace, port=0) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + yield workspace, f"http://127.0.0.1:{server.server_port}" + server.shutdown() + server.server_close() + thread.join() + + +def call(base, path, payload=None, headers=None): + request = Request( + base + path, + data=json.dumps(payload).encode() if payload is not None else None, + headers=headers or {}, + ) + try: + with urlopen(request, timeout=5) as response: + return response.status, response.read(), response.headers + except HTTPError as response: + return response.code, response.read(), response.headers + + +def test_http_host_token_origin_and_validation(api_server): + workspace, base = api_server + assert call(base, "/api/workspace", headers={"Host": "attacker.test"})[0] == 403 + assert call(base, "/api/scan", {"profile": "quick"})[0] == 403 + headers = {"X-CodeProof-Token": workspace.token, "Origin": "https://attacker.test"} + assert call(base, "/api/scan", {"profile": "quick"}, headers)[0] == 403 + headers.pop("Origin") + assert call(base, "/api/scan", {"jobs": 9}, headers)[0] == 400 + assert call(base, "/api/scan", {"root": "/etc"}, headers)[0] == 400 + assert call(base, "/../pyproject.toml")[0] == 404 + assert call(base, "/api/runs/missing")[0] == 404 + + +def test_http_run_exports_and_assets(api_server): + workspace, base = api_server + status, data, _ = call( + base, "/api/scan", {"profile": "quick"}, {"X-CodeProof-Token": workspace.token} + ) + assert status == 202 + id_ = json.loads(data)["id"] + wait_for(workspace) + assert json.loads(call(base, f"/api/runs/{id_}")[1])["score"] == 100 + for format_ in ("json", "html", "markdown", "sarif"): + status, data, headers = call(base, f"/api/runs/{id_}/{format_}") + assert status == 200 and data + assert "attachment" in headers["Content-Disposition"] + for asset in ("/", "/app.js", "/app.css"): + status, data, headers = call(base, asset) + assert status == 200 and data + assert "frame-ancestors 'none'" in headers["Content-Security-Policy"] + assert headers["Cache-Control"] == "no-store" + + +def test_sarif_locations_rules_and_all_compatibility(tmp_path): + report = scan( + tmp_path, + Config(required_tools=[], checks={"syntax": CheckConfig(enabled=False)}), + ) + report.results = [ + CheckResult( + name="ruff", + status=Status.failed, + findings=[ + Finding( + message="first", + rule="F401", + path=str(tmp_path / "src/a b.py"), + line=3, + ), + Finding(message="second", rule="F401", path="../secret.py"), + Finding(message="third", path="/outside.py", line=-1), + ], + ) + ] + data = sarif(report) + assert data["version"] == "2.1.0" + run = data["runs"][0] + assert len(run["tool"]["driver"]["rules"]) == 2 + assert ( + run["results"][0]["locations"][0]["physicalLocation"]["artifactLocation"]["uri"] + == "src/a%20b.py" + ) + assert "locations" not in run["results"][1] + assert "locations" not in run["results"][2] + assert len(write(report, tmp_path / "reports", "all")) == 3 + assert len(write(report, tmp_path / "reports", "sarif")) == 1 From 6f4d953930a6cc7304d3e75b1220f88aad0bff73 Mon Sep 17 00:00:00 2001 From: PeaBox Date: Sun, 8 Nov 2026 23:01:51 +0530 Subject: [PATCH 3/4] Codex update 08112006.2301 Codex update 08112006.2301 --- README.md | 4 +- ROADMAP.md | 42 ++++++++++ pyproject.toml | 5 ++ src/codeproof/cli.py | 8 ++ src/codeproof/gui/__init__.py | 1 + src/codeproof/gui/app.js | 140 +++++++++++++++++++++++++++++++ src/codeproof/gui/index.html | 152 ++++++++++++++++++++++++++++++++++ src/codeproof/gui/styles.css | 81 ++++++++++++++++++ src/codeproof/web.py | 151 +++++++++++++++++++++++++++++++++ 9 files changed, 583 insertions(+), 1 deletion(-) create mode 100644 ROADMAP.md create mode 100644 src/codeproof/gui/__init__.py create mode 100644 src/codeproof/gui/app.js create mode 100644 src/codeproof/gui/index.html create mode 100644 src/codeproof/gui/styles.css create mode 100644 src/codeproof/web.py diff --git a/README.md b/README.md index d292bf3..19b927a 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ Local-first Python CLI and reusable GitHub Action for verifying Python repositor - CI-friendly exit codes - GitHub composite Action - Local-first scanning +- Modern local GUI dashboard (`codeproof gui`) for scans, findings, policy, and history ## Install ```bash @@ -26,8 +27,9 @@ codeproof init codeproof inventory . codeproof generate-tests . --output tests/generated codeproof scan . --format all --fail-under 70 +codeproof gui . --host 127.0.0.1 --port 8787 ``` -Reports are stored under `.codeproof/reports/`. +Reports are stored under `.codeproof/reports/`. The GUI runs locally and uses the same core engine/policy as the CLI. See `ROADMAP.md` for planned enhancements. ## Confidence model The score is the weighted percentage of included checks that pass. Missing required tools fail policy. Missing optional tools are marked unavailable and excluded from the denominator. A passing report is evidence that configured checks passed, not proof of correctness. diff --git a/ROADMAP.md b/ROADMAP.md new file mode 100644 index 0000000..d11e23e --- /dev/null +++ b/ROADMAP.md @@ -0,0 +1,42 @@ +# CodeProof-AI Roadmap + +## Vision +Make CodeProof-AI the most trusted, local-first evidence platform for Python repository health—transparent scoring, actionable diagnostics, and seamless workflows from CLI to CI to interactive GUI. + +## Current State (v0.1.0) +- Deterministic checks: Ruff, mypy, pytest, Bandit, Semgrep, import-smoke +- Weighted policy engine with required-tool gates and configurable thresholds +- AST-based symbol inventory and reviewable smoke-test generation +- Reports: JSON, Markdown, HTML +- Typer CLI + reusable GitHub Action +- Local-first execution model + +## Near-term (v0.2.x) — Usability & Visibility +- **Modern GUI dashboard (in progress)**: local web interface to run scans, view results, inspect findings, browse report history, and edit policy. +- **Scan history & trends**: persist run metadata/summaries; show score trends over time per project. +- **Richer finding details**: normalize adapter outputs (file/line/rule/severity) into structured findings across all tools. +- **Config UX**: validate `.codeproof.yml`, expose presets (strict/balanced/fast), and document all options. +- **Improved HTML reports**: interactive filtering, sortable tables, and deep links to evidence/raw output. +- **Doctor enhancements**: version checks, install hints, and environment diagnostics. + +## Mid-term (v0.3.x–v0.4.x) — Depth & Integrations +- **Async/background scans in GUI** with live progress and cancellation. +- **Baseline & diff mode**: compare current scan against a baseline to highlight regressions/new findings (PR-focused). +- **Plugin/adapter system**: stable interface for custom checks (coverage, pip-audit, vulture, complexity, license checks). +- **Coverage integration**: parse `coverage.xml`/pytest-cov output as a first-class evidence source. +- **Multi-language groundwork**: abstract runner/report model to support additional ecosystems (starting with JS/TS) while keeping Python best-in-class. +- **SARIF export** and better GitHub Code Scanning/PR annotation workflows. +- **Caching & incremental checks**: speed up repeated local scans. + +## Long-term (v1.0+) — Team & Trust +- **Policy packs & provenance**: signed/shareable policy profiles; clear evidence provenance in reports. +- **Workspace/monorepo support**: per-package policies, aggregated scoring, and targeted scans. +- **Optional hosted/CI insights**: opt-in aggregation for teams (never default; preserve local-first core). +- **AI-assisted, evidence-grounded explanations**: summarize findings and suggest fixes *with citations to check output* (no correctness claims). +- **Stability guarantees**: versioned report schema, backward-compatible config migrations, and documented extension API. + +## Guiding Principles +- **Evidence over claims**: reports show what ran, what passed/failed, and what was excluded. +- **Local-first & transparent**: predictable execution, explicit limitations, user-controlled network use. +- **Composable**: CLI, GUI, and CI share the same core engine and config. +- **Safe by default**: clear warnings when scanning executes untrusted code; encourage isolated environments. diff --git a/pyproject.toml b/pyproject.toml index 51aa695..ced11d2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -16,5 +16,10 @@ dev=["codeproof-ai[checkers]"] codeproof="codeproof.cli:app" [tool.hatch.build.targets.wheel] packages=["src/codeproof"] + +[tool.hatch.build.targets.wheel.force-include] +"src/codeproof/gui" = "codeproof/gui" + [tool.pytest.ini_options] testpaths=["tests"] + diff --git a/src/codeproof/cli.py b/src/codeproof/cli.py index 48c7683..34f8fc4 100644 --- a/src/codeproof/cli.py +++ b/src/codeproof/cli.py @@ -34,4 +34,12 @@ def scan(path:Path=Path("."),format:str="all",fail_under:float|None=None,output: console.print(t);console.print(f"Score {report.score}/100 ({report.grade}); policy {'PASS' if report.policy_passed else 'FAIL'}") for p in write(report,root/output,format):console.print(f"Report: {p}") raise typer.Exit(0 if report.policy_passed else 1) + +@app.command() +def gui(path:Path=Path("."),host:str="127.0.0.1",port:int=8787,no_open:bool=False): + """Launch the local CodeProof GUI dashboard.""" + from .web import serve + serve(host=host,port=port,target=path.resolve(),open_browser=not no_open) + if __name__=="__main__":app() + diff --git a/src/codeproof/gui/__init__.py b/src/codeproof/gui/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/src/codeproof/gui/__init__.py @@ -0,0 +1 @@ + diff --git a/src/codeproof/gui/app.js b/src/codeproof/gui/app.js new file mode 100644 index 0000000..8afcc7e --- /dev/null +++ b/src/codeproof/gui/app.js @@ -0,0 +1,140 @@ +const state = { report: null, findings: [] }; +const $ = (s) => document.querySelector(s); +const $$ = (s) => Array.from(document.querySelectorAll(s)); + +function fmt(n, d = 2) { return typeof n === 'number' ? n.toFixed(d).replace(/\.00$/, '') : n; } +function esc(s) { return String(s ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); } + +async function api(path, opts = {}) { + const res = await fetch(path, { headers: { 'Content-Type': 'application/json' }, ...opts }); + const data = await res.json().catch(() => ({})); + if (!res.ok) throw new Error(data.error || res.statusText); + return data; +} + +function setView(name) { + $$('.view').forEach(v => v.classList.toggle('active', v.id === `view-${name}`)); + $$('.nav-btn').forEach(b => b.classList.toggle('active', b.dataset.view === name)); + $('#view-title').textContent = name.charAt(0).toUpperCase() + name.slice(1); +} + +function scoreColor(score) { + if (score >= 80) return 'var(--good)'; + if (score >= 60) return 'var(--warn)'; + return 'var(--bad)'; +} + +function renderReport(report) { + state.report = report; + state.findings = []; + (report.results || []).forEach(r => (r.findings || []).forEach(f => state.findings.push({ check: r.name, ...f }))); + $('#project-meta').textContent = `${report.project} • ${report.target} • ${new Date(report.generated_at).toLocaleString()}`; + $('#score-value').textContent = fmt(report.score, 0); + $('#grade').textContent = `Grade ${report.grade}`; + const deg = Math.max(0, Math.min(100, report.score)) * 3.6; + $('#score-ring').style.background = `conic-gradient(${scoreColor(report.score)} ${deg}deg, rgba(255,255,255,0.06) ${deg}deg)`; + const badge = $('#policy-badge'); + badge.textContent = report.policy_passed ? 'Policy PASS' : 'Policy FAIL'; + badge.className = 'badge ' + (report.policy_passed ? 'pass' : 'fail'); + $('#kpi-checks').textContent = (report.results || []).length; + const passed = (report.results || []).filter(r => r.status === 'passed').length; + $('#kpi-checks-sub').textContent = `${passed} passed`; + $('#kpi-findings').textContent = state.findings.length; + $('#kpi-threshold').textContent = `≥ ${fmt(report.fail_under)}`; + $('#kpi-generated').textContent = `CodeProof ${report.codeproof_version}`; + renderResults(); + renderFindings(); + $('#limitations').innerHTML = (report.limitations || []).map(l => `
  • ${esc(l)}
  • `).join('') || '
  • None.
  • '; +} + +function renderResults() { + const filter = $('#status-filter').value; + const rows = (state.report?.results || []).filter(r => filter === 'all' || r.status === filter); + $('#results-table tbody').innerHTML = rows.map(r => ` + ${esc(r.name)} + ${esc(r.status)} + ${fmt(r.weight)} + ${r.required ? 'Yes' : 'No'} + ${fmt(r.duration_seconds, 3)}s + ${esc(r.summary)} + `).join('') || 'No results.'; +} + +function renderFindings() { + const q = ($('#finding-search')?.value || '').toLowerCase(); + const rows = state.findings.filter(f => !q || JSON.stringify(f).toLowerCase().includes(q)); + $('#findings-table tbody').innerHTML = rows.map(f => ` + ${esc(f.check)}${esc(f.level)}${esc(f.rule || '')} + ${esc(f.path || '')}${f.line ?? ''}${esc(f.message)} + `).join('') || 'No findings. Adapters may include structured findings in future scans.'; +} + +async function runScan() { + const btn = $('#run-scan'); + btn.disabled = true; $('#scan-status').textContent = 'Running scan… this may take a while (tools execute in the target repo).'; + try { + const target = $('#target').value.trim(); + const report = await api('/api/scan', { method: 'POST', body: JSON.stringify({ path: target }) }); + renderReport(report); + $('#scan-status').textContent = `Scan complete. Policy ${report.policy_passed ? 'PASS' : 'FAIL'}.`; + } catch (e) { + $('#scan-status').textContent = `Error: ${e.message}`; + } finally { btn.disabled = false; } +} + +async function loadDoctor() { + try { + const data = await api('/api/doctor'); + $('#doctor').innerHTML = (data.tools || []).map(t => `
    ${esc(t.name)}
    ${t.available ? 'Available' : 'Missing'}
    ${t.path ? `
    ${esc(t.path)}
    ` : ''}
    `).join(''); + } catch (e) { $('#doctor').innerHTML = `

    Error: ${esc(e.message)}

    `; } +} + +async function loadInventory() { + try { + const target = $('#target').value.trim(); + const data = await api(`/api/inventory?path=${encodeURIComponent(target)}`); + $('#inventory-table tbody').innerHTML = (data.symbols || []).map(s => `${esc(s.name)}${esc(s.file)}${s.line}`).join('') || 'No public symbols found.'; + } catch (e) { $('#inventory-table tbody').innerHTML = `Error: ${esc(e.message)}`; } +} + +async function loadPolicy() { + try { + const target = $('#target').value.trim(); + const data = await api(`/api/policy?path=${encodeURIComponent(target)}`); + $('#policy-json').textContent = JSON.stringify(data, null, 2); + } catch (e) { $('#policy-json').textContent = `Error: ${e.message}`; } +} + +async function loadHistory() { + try { + const target = $('#target').value.trim(); + const data = await api(`/api/history?path=${encodeURIComponent(target)}`); + $('#history-table tbody').innerHTML = (data.reports || []).map(r => ` + ${esc(new Date(r.generated_at).toLocaleString())}${esc(r.project)}${fmt(r.score)}${esc(r.grade)} + ${r.policy_passed ? 'PASS' : 'FAIL'} + + `).join('') || 'No saved JSON reports found in .codeproof/reports.'; + $$('#history-table [data-load-report]').forEach(btn => btn.addEventListener('click', async () => { + const report = await api(`/api/report?path=${encodeURIComponent(target)}&file=${encodeURIComponent(btn.dataset.loadReport)}`); + renderReport(report); setView('dashboard'); + })); + } catch (e) { $('#history-table tbody').innerHTML = `Error: ${esc(e.message)}`; } +} + +$$('.nav-btn').forEach(b => b.addEventListener('click', () => setView(b.dataset.view))); +$('#run-scan').addEventListener('click', runScan); +$('#status-filter').addEventListener('change', renderResults); +$('#finding-search').addEventListener('input', renderFindings); +$('#refresh-doctor').addEventListener('click', loadDoctor); +$('#load-inventory').addEventListener('click', loadInventory); +$('#load-policy').addEventListener('click', () => { loadPolicy(); loadDoctor(); }); +$('#load-history').addEventListener('click', loadHistory); +$('#open-reports').addEventListener('click', async () => { + try { await api('/api/open-reports', { method: 'POST', body: JSON.stringify({ path: $('#target').value.trim() }) }); } + catch (e) { alert(e.message); } +}); + +(async function init() { + try { const info = await api('/api/info'); $('#target').value = info.default_target || ''; } catch {} + loadDoctor(); loadHistory(); +})(); diff --git a/src/codeproof/gui/index.html b/src/codeproof/gui/index.html new file mode 100644 index 0000000..62774d4 --- /dev/null +++ b/src/codeproof/gui/index.html @@ -0,0 +1,152 @@ + + + + + + CodeProof AI — Dashboard + + + +
    + + +
    +
    +
    +

    Dashboard

    +

    No scan loaded.

    +
    +
    + + +
    +
    + +
    +
    +
    +
    —
    +
    +
    Confidence Score
    +
    —
    +
    No data
    +
    +
    +
    +
    Checks
    +
    —
    +
    +
    +
    +
    Findings
    +
    —
    +
    Structured findings reported by adapters
    +
    +
    +
    Fail Under
    +
    —
    +
    +
    +
    + +
    +
    +

    Check Results

    +
    + +
    +
    +
    + + + +
    CheckStatusWeightRequiredDurationSummary
    +
    +
    + +
    +

    Limitations

    +
      +
      +
      + +
      +
      +

      Findings

      +
      + + + +
      CheckLevelRulePathLineMessage
      +
      +
      +
      + +
      +
      +

      Public Symbols

      +
      + + + +
      SymbolFileLine
      +
      +
      +
      + +
      +
      +

      Effective Policy

      +
      
      +        
      +
      +

      Tool Availability

      +
      +
      +
      + +
      +
      +

      Report History

      +
      + + + +
      GeneratedProjectScoreGradePolicyAction
      +
      +
      +
      +
      +
      + + + diff --git a/src/codeproof/gui/styles.css b/src/codeproof/gui/styles.css new file mode 100644 index 0000000..09ad153 --- /dev/null +++ b/src/codeproof/gui/styles.css @@ -0,0 +1,81 @@ +:root { + --bg: #0b1020; + --bg-elev: #121933; + --bg-elev-2: #182142; + --border: rgba(255,255,255,0.08); + --text: #e8eefc; + --muted: #9fb0d0; + --primary: #6ea8fe; + --primary-2: #4c7dff; + --good: #2dd4bf; + --warn: #f59e0b; + --bad: #fb7185; + --neutral: #64748b; + --shadow: 0 10px 30px rgba(0,0,0,0.25); + --radius: 14px; + font-synthesis: none; +} +* { box-sizing: border-box; } +html, body { margin: 0; height: 100%; background: radial-gradient(1200px 600px at 10% -10%, #172554 0%, transparent 50%), var(--bg); color: var(--text); font: 14px/1.45 system-ui, -apple-system, Segoe UI, Roboto, sans-serif; } +button, input, select { font: inherit; color: inherit; } +.app { display: grid; grid-template-columns: 300px 1fr; min-height: 100vh; } +.sidebar { border-right: 1px solid var(--border); background: linear-gradient(180deg, rgba(18,25,51,0.95), rgba(11,16,32,0.98)); padding: 20px; display: flex; flex-direction: column; gap: 18px; position: sticky; top: 0; height: 100vh; } +.brand { display: flex; gap: 12px; align-items: center; } +.logo { width: 42px; height: 42px; border-radius: 12px; background: linear-gradient(135deg, var(--primary), #8b5cf6); display: grid; place-items: center; font-weight: 700; box-shadow: var(--shadow); } +.brand h1 { font-size: 18px; margin: 0; } +.muted { color: var(--muted); margin: 0; } +.small { font-size: 12px; } +nav { display: flex; flex-direction: column; gap: 6px; } +.nav-btn { text-align: left; padding: 10px 12px; background: transparent; border: 1px solid transparent; border-radius: 10px; cursor: pointer; color: var(--muted); } +.nav-btn:hover { background: rgba(255,255,255,0.04); color: var(--text); } +.nav-btn.active { background: rgba(110,168,254,0.12); border-color: rgba(110,168,254,0.25); color: var(--text); } +.sidebar-footer { margin-top: auto; display: flex; flex-direction: column; gap: 10px; } +.field label { display: block; font-size: 12px; color: var(--muted); margin-bottom: 6px; } +input, select { width: 100%; background: var(--bg-elev); border: 1px solid var(--border); border-radius: 10px; padding: 10px 12px; outline: none; } +input:focus, select:focus { border-color: rgba(110,168,254,0.5); } +.primary { background: linear-gradient(135deg, var(--primary-2), #6366f1); border: none; padding: 11px 14px; border-radius: 10px; font-weight: 600; cursor: pointer; } +.primary:disabled { opacity: 0.6; cursor: progress; } +.ghost { background: rgba(255,255,255,0.03); border: 1px solid var(--border); padding: 8px 12px; border-radius: 10px; cursor: pointer; } +.ghost:hover { background: rgba(255,255,255,0.06); } +.content { padding: 22px 26px 40px; } +.topbar { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 18px; } +.topbar h2 { margin: 0 0 4px; font-size: 24px; } +.topbar-actions { display: flex; gap: 8px; flex-wrap: wrap; } +.view { display: none; } +.view.active { display: block; } +.cards { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 14px; margin-bottom: 14px; } +.card, .panel { background: linear-gradient(180deg, rgba(24,33,66,0.9), rgba(18,25,51,0.92)); border: 1px solid var(--border); border-radius: var(--radius); box-shadow: var(--shadow); } +.card { padding: 16px; } +.score-card { display: flex; gap: 14px; align-items: center; } +.score-ring { width: 72px; height: 72px; border-radius: 50%; display: grid; place-items: center; background: conic-gradient(var(--neutral) 0deg, rgba(255,255,255,0.06) 0deg); position: relative; } +.score-ring::before { content: ""; position: absolute; inset: 7px; background: var(--bg-elev); border-radius: 50%; } +.score-ring span { position: relative; font-size: 18px; font-weight: 700; } +.kpi-label { color: var(--muted); font-size: 12px; text-transform: uppercase; letter-spacing: .04em; } +.kpi { font-size: 28px; font-weight: 700; margin-top: 4px; } +.grade { font-size: 22px; font-weight: 700; margin: 2px 0 6px; } +.badge { display: inline-flex; align-items: center; padding: 4px 10px; border-radius: 999px; font-size: 12px; font-weight: 600; background: rgba(100,116,139,0.2); color: var(--muted); } +.badge.pass { background: rgba(45,212,191,0.15); color: var(--good); } +.badge.fail { background: rgba(251,113,133,0.15); color: var(--bad); } +.panel { margin-bottom: 14px; overflow: hidden; } +.panel-head { padding: 14px 16px; border-bottom: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; gap: 12px; } +.panel-head h3 { margin: 0; font-size: 16px; } +.table-wrap { overflow: auto; } +table { width: 100%; border-collapse: collapse; } +th, td { padding: 11px 14px; border-bottom: 1px solid var(--border); text-align: left; vertical-align: top; } +th { color: var(--muted); font-weight: 600; font-size: 12px; text-transform: uppercase; letter-spacing: .03em; background: rgba(255,255,255,0.01); } +tbody tr:hover { background: rgba(255,255,255,0.02); } +.status { display: inline-flex; padding: 3px 9px; border-radius: 999px; font-size: 12px; font-weight: 600; text-transform: capitalize; } +.status.passed { background: rgba(45,212,191,0.15); color: var(--good); } +.status.failed { background: rgba(251,113,133,0.15); color: var(--bad); } +.status.unavailable, .status.skipped { background: rgba(100,116,139,0.2); color: #b6c2d9; } +.status.error { background: rgba(245,158,11,0.18); color: var(--warn); } +.limitations { margin: 0; padding: 12px 18px 18px 34px; color: var(--muted); } +.limitations li { margin: 6px 0; } +.codeblock { margin: 0; padding: 16px; overflow: auto; color: #cfe1ff; font: 12px/1.5 ui-monospace, SFMono-Regular, Consolas, monospace; } +.doctor-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 10px; padding: 14px 16px 16px; } +.doctor-item { padding: 12px; border: 1px solid var(--border); border-radius: 12px; background: rgba(255,255,255,0.02); } +.doctor-item .name { font-weight: 600; } +.search { max-width: 320px; } +.filters select { width: auto; min-width: 160px; } +@media (max-width: 1100px) { .cards { grid-template-columns: repeat(2, minmax(0,1fr)); } } +@media (max-width: 860px) { .app { grid-template-columns: 1fr; } .sidebar { position: static; height: auto; } } diff --git a/src/codeproof/web.py b/src/codeproof/web.py new file mode 100644 index 0000000..33e5644 --- /dev/null +++ b/src/codeproof/web.py @@ -0,0 +1,151 @@ +from __future__ import annotations +import json, mimetypes, os, shutil, subprocess, sys, webbrowser +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from urllib.parse import parse_qs, urlparse +from . import __version__ + +GUI_DIR = Path(__file__).resolve().parent / "gui" + + +def _json(handler: BaseHTTPRequestHandler, status: int, payload): + body = json.dumps(payload, default=str).encode("utf-8") + handler.send_response(status) + handler.send_header("Content-Type", "application/json; charset=utf-8") + handler.send_header("Content-Length", str(len(body))) + handler.send_header("Cache-Control", "no-store") + handler.end_headers() + handler.wfile.write(body) + +def _read_json(handler: BaseHTTPRequestHandler): + n = int(handler.headers.get("Content-Length") or 0) + raw = handler.rfile.read(n) if n else b"{}" + return json.loads(raw.decode("utf-8") or "{}") + +def _target(path: str | None, default: Path) -> Path: + p = Path(path).expanduser() if path else default + return p.resolve() + +class Handler(BaseHTTPRequestHandler): + server_version = f"CodeProofGUI/{__version__}" + default_target = Path.cwd() + + def log_message(self, fmt, *args): + sys.stderr.write(f"[gui] {self.address_string()} - {fmt % args}\n") + + def do_GET(self): + parsed = urlparse(self.path) + try: + if parsed.path in ("/", "/index.html"): + return self._serve_file(GUI_DIR / "index.html") + if parsed.path.startswith("/static/"): + rel = parsed.path.removeprefix("/static/").replace("/", os.sep) + return self._serve_file((GUI_DIR / rel).resolve()) + if parsed.path == "/api/info": + return _json(self, 200, {"version": __version__, "default_target": str(self.default_target)}) + if parsed.path == "/api/doctor": + tools = [] + for n in ["ruff", "mypy", "pytest", "bandit", "semgrep"]: + p = shutil.which(n) + tools.append({"name": n, "available": bool(p), "path": p}) + return _json(self, 200, {"tools": tools}) + if parsed.path == "/api/policy": + from .config import load + qs = parse_qs(parsed.query) + root = _target((qs.get("path") or [None])[0], self.default_target) + cfg = load(root) + return _json(self, 200, cfg.model_dump(mode="json")) + if parsed.path == "/api/inventory": + from .config import load + from .discovery import symbols + qs = parse_qs(parsed.query) + root = _target((qs.get("path") or [None])[0], self.default_target) + cfg = load(root) + data = [{"name": n, "file": str(p), "line": l} for n, p, l in symbols(root, cfg.source_paths)] + return _json(self, 200, {"root": str(root), "count": len(data), "symbols": data}) + if parsed.path == "/api/history": + qs = parse_qs(parsed.query) + root = _target((qs.get("path") or [None])[0], self.default_target) + reports_dir = root / ".codeproof" / "reports" + items = [] + if reports_dir.exists(): + for p in sorted(reports_dir.glob("*.json"), key=lambda x: x.stat().st_mtime, reverse=True): + try: + d = json.loads(p.read_text(encoding="utf-8")) + items.append({"file": p.name, "generated_at": d.get("generated_at"), "project": d.get("project"), + "score": d.get("score"), "grade": d.get("grade"), "policy_passed": d.get("policy_passed")}) + except Exception: + continue + return _json(self, 200, {"root": str(root), "reports": items}) + if parsed.path == "/api/report": + qs = parse_qs(parsed.query) + root = _target((qs.get("path") or [None])[0], self.default_target) + name = (qs.get("file") or [""])[0] + p = (root / ".codeproof" / "reports" / name).resolve() + if not name or p.parent != (root / ".codeproof" / "reports").resolve() or not p.exists(): + return _json(self, 404, {"error": "report not found"}) + return _json(self, 200, json.loads(p.read_text(encoding="utf-8"))) + return _json(self, 404, {"error": "not found"}) + except Exception as e: + return _json(self, 500, {"error": str(e)}) + + def do_POST(self): + parsed = urlparse(self.path) + try: + if parsed.path == "/api/scan": + from .config import load + from .core import scan as run_scan + from .reporting import write as write_reports + data = _read_json(self) + root = _target(data.get("path"), self.default_target) + if not root.exists(): + return _json(self, 400, {"error": f"target does not exist: {root}"}) + cfg = load(root) + report = run_scan(root, cfg, data.get("fail_under")) + write_reports(report, root / ".codeproof" / "reports", "all") + return _json(self, 200, report.model_dump(mode="json")) + if parsed.path == "/api/open-reports": + data = _read_json(self) + root = _target(data.get("path"), self.default_target) + out = root / ".codeproof" / "reports" + out.mkdir(parents=True, exist_ok=True) + if sys.platform.startswith("win"): + os.startfile(out) # type: ignore[attr-defined] + elif sys.platform == "darwin": + subprocess.Popen(["open", str(out)]) + else: + subprocess.Popen(["xdg-open", str(out)]) + return _json(self, 200, {"ok": True, "path": str(out)}) + return _json(self, 404, {"error": "not found"}) + except Exception as e: + return _json(self, 500, {"error": str(e)}) + + def _serve_file(self, path: Path): + if GUI_DIR not in path.parents and path != GUI_DIR / "index.html": + return _json(self, 403, {"error": "forbidden"}) + if not path.exists() or not path.is_file(): + return _json(self, 404, {"error": "not found"}) + body = path.read_bytes() + ctype = mimetypes.guess_type(path.name)[0] or "application/octet-stream" + self.send_response(200) + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(body))) + self.send_header("Cache-Control", "no-store") + self.end_headers() + self.wfile.write(body) + +def serve(host: str = "127.0.0.1", port: int = 8787, target: Path | None = None, open_browser: bool = True): + Handler.default_target = (target or Path.cwd()).resolve() + httpd = ThreadingHTTPServer((host, port), Handler) + url = f"http://{host}:{port}/" + print(f"CodeProof GUI running at {url}") + print(f"Default target: {Handler.default_target}") + if open_browser: + try: webbrowser.open(url) + except Exception: pass + try: + httpd.serve_forever() + except KeyboardInterrupt: + pass + finally: + httpd.server_close() From 2c0d26c4f2842ef18eb6e3906dfd3f9c7c0e3c5f Mon Sep 17 00:00:00 2001 From: PeaBox <5895515+iwebslogtech@users.noreply.github.com> Date: Sun, 8 Nov 2026 19:21:19 +0000 Subject: [PATCH 4/4] Redesign the GUI with a responsive repository overview and improve policy and report history loading Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> --- src/codeproof/gui/app.js | 21 +++-- src/codeproof/gui/index.html | 164 ++++++++++------------------------- src/codeproof/gui/styles.css | 129 ++++++++++----------------- 3 files changed, 108 insertions(+), 206 deletions(-) diff --git a/src/codeproof/gui/app.js b/src/codeproof/gui/app.js index 8afcc7e..5632f6b 100644 --- a/src/codeproof/gui/app.js +++ b/src/codeproof/gui/app.js @@ -15,7 +15,11 @@ async function api(path, opts = {}) { function setView(name) { $$('.view').forEach(v => v.classList.toggle('active', v.id === `view-${name}`)); $$('.nav-btn').forEach(b => b.classList.toggle('active', b.dataset.view === name)); - $('#view-title').textContent = name.charAt(0).toUpperCase() + name.slice(1); + const titles = { dashboard: 'Repository overview', findings: 'Findings', inventory: 'Inventory', policy: 'Policy & tools', history: 'Report history' }; + $('#view-title').textContent = titles[name]; + $('#breadcrumb').textContent = name === 'dashboard' ? 'OVERVIEW' : name.toUpperCase(); + if (name === 'policy') { loadPolicy(); loadDoctor(); } + if (name === 'history') loadHistory(); } function scoreColor(score) { @@ -57,7 +61,7 @@ function renderResults() { ${r.required ? 'Yes' : 'No'} ${fmt(r.duration_seconds, 3)}s ${esc(r.summary)} - `).join('') || 'No results.'; + `).join('') || `No results to show${state.report ? 'Try another status filter.' : 'Run a scan to see your check results here.'}`; } function renderFindings() { @@ -66,7 +70,7 @@ function renderFindings() { $('#findings-table tbody').innerHTML = rows.map(f => ` ${esc(f.check)}${esc(f.level)}${esc(f.rule || '')} ${esc(f.path || '')}${f.line ?? ''}${esc(f.message)} - `).join('') || 'No findings. Adapters may include structured findings in future scans.'; + `).join('') || `No findings to show${q ? 'Try a different search.' : state.report ? 'No structured findings were reported in this scan.' : 'Run a scan to see reported findings.'}`; } async function runScan() { @@ -77,6 +81,7 @@ async function runScan() { const report = await api('/api/scan', { method: 'POST', body: JSON.stringify({ path: target }) }); renderReport(report); $('#scan-status').textContent = `Scan complete. Policy ${report.policy_passed ? 'PASS' : 'FAIL'}.`; + loadHistory(); } catch (e) { $('#scan-status').textContent = `Error: ${e.message}`; } finally { btn.disabled = false; } @@ -115,8 +120,12 @@ async function loadHistory() { `).join('') || 'No saved JSON reports found in .codeproof/reports.'; $$('#history-table [data-load-report]').forEach(btn => btn.addEventListener('click', async () => { - const report = await api(`/api/report?path=${encodeURIComponent(target)}&file=${encodeURIComponent(btn.dataset.loadReport)}`); - renderReport(report); setView('dashboard'); + try { + const report = await api(`/api/report?path=${encodeURIComponent(target)}&file=${encodeURIComponent(btn.dataset.loadReport)}`); + renderReport(report); setView('dashboard'); + } catch (e) { + $('#history-table tbody').innerHTML = `Error: ${esc(e.message)}`; + } })); } catch (e) { $('#history-table tbody').innerHTML = `Error: ${esc(e.message)}`; } } @@ -125,7 +134,7 @@ $$('.nav-btn').forEach(b => b.addEventListener('click', () => setView(b.dataset. $('#run-scan').addEventListener('click', runScan); $('#status-filter').addEventListener('change', renderResults); $('#finding-search').addEventListener('input', renderFindings); -$('#refresh-doctor').addEventListener('click', loadDoctor); +$('#refresh-doctor').addEventListener('click', () => setView('policy')); $('#load-inventory').addEventListener('click', loadInventory); $('#load-policy').addEventListener('click', () => { loadPolicy(); loadDoctor(); }); $('#load-history').addEventListener('click', loadHistory); diff --git a/src/codeproof/gui/index.html b/src/codeproof/gui/index.html index 62774d4..b676379 100644 --- a/src/codeproof/gui/index.html +++ b/src/codeproof/gui/index.html @@ -7,144 +7,70 @@ +
      +
      WORKSPACE / OVERVIEW
      Local environment
      -
      -

      Dashboard

      -

      No scan loaded.

      -
      -
      - - -
      +
      YOUR WORKSPACE

      Repository overview

      A clearer picture of your code starts here.

      +
      -
      -
      -
      —
      -
      -
      Confidence Score
      -
      —
      -
      No data
      -
      -
      -
      -
      Checks
      -
      —
      -
      -
      -
      -
      Findings
      -
      —
      -
      Structured findings reported by adapters
      -
      -
      -
      Fail Under
      -
      —
      -
      +
      +
      EVIDENCE, NOT GUESSWORK

      Know where your
      code stands.

      Run your checks in one place and turn the results into a clearer picture of your repository’s health.

      +
      +

      Checks run locally in your target repository.

      +
      REPORT CONFIDENCE ↗
      —OUT OF 100
      No scan yet
      Awaiting results
      - -
      -
      -

      Check Results

      -
      - -
      -
      -
      - - - -
      CheckStatusWeightRequiredDurationSummary
      -
      -
      - -
      -

      Limitations

      -
        -
        -
        - -
        -
        -

        Findings

        -
        - - - -
        CheckLevelRulePathLineMessage
        -
        -
        -
        - -
        -
        -

        Public Symbols

        -
        - - - -
        SymbolFileLine
        -
        -
        -
        - -
        -
        -

        Effective Policy

        -
        
        -        
        -
        -

        Tool Availability

        -
        +
        AT A GLANCE

        Scan summary

        A snapshot of your loaded report
        +
        +
        CHECKS
        —
        Checks completed
        +
        FINDINGS
        —
        Structured findings reported
        +
        PASS THRESHOLD
        —
        Defined by your policy
        -
        - -
        -
        -

        Report History

        -
        - - - -
        GeneratedProjectScoreGradePolicyAction
        -
        +
        +
        THE DETAILS

        Check results

        See how each check performed.

        CheckStatusWeightRequiredDurationSummary
        Ready when you areRun a scan to see your check results here.
        +
        GOOD TO KNOW

        About your results

        Confidence is built from the checks in your policy. Each report shows what passed, what didn’t, and what needs a closer look.

        KEEP IN MIND
        • A passing report is evidence, not proof that code is correct.
        • Scans may execute repository code. Use an isolated environment for untrusted projects.
        +
        EXPLORE

        Findings

        Review the details reported by your checks.

        CheckLevelRulePathLineMessage
        No findings to showRun a scan to see reported findings.
        +
        EXPLORE

        Public symbols

        Browse the public symbols in your repository.

        SymbolFileLine
        Inventory is ready to loadLoad your public symbols to explore them here.
        +
        CONFIGURATION

        Effective policy

        The settings used to evaluate your repository.

        Select Reload to view your effective policy.
        ENVIRONMENT

        Tool availability

        Check which tools are available locally.

        +
        PREVIOUS RUNS

        Report history

        Return to a saved report from this repository.

        GeneratedProjectScoreGradePolicyAction
        diff --git a/src/codeproof/gui/styles.css b/src/codeproof/gui/styles.css index 09ad153..e675d9e 100644 --- a/src/codeproof/gui/styles.css +++ b/src/codeproof/gui/styles.css @@ -1,81 +1,48 @@ -:root { - --bg: #0b1020; - --bg-elev: #121933; - --bg-elev-2: #182142; - --border: rgba(255,255,255,0.08); - --text: #e8eefc; - --muted: #9fb0d0; - --primary: #6ea8fe; - --primary-2: #4c7dff; - --good: #2dd4bf; - --warn: #f59e0b; - --bad: #fb7185; - --neutral: #64748b; - --shadow: 0 10px 30px rgba(0,0,0,0.25); - --radius: 14px; - font-synthesis: none; -} -* { box-sizing: border-box; } -html, body { margin: 0; height: 100%; background: radial-gradient(1200px 600px at 10% -10%, #172554 0%, transparent 50%), var(--bg); color: var(--text); font: 14px/1.45 system-ui, -apple-system, Segoe UI, Roboto, sans-serif; } -button, input, select { font: inherit; color: inherit; } -.app { display: grid; grid-template-columns: 300px 1fr; min-height: 100vh; } -.sidebar { border-right: 1px solid var(--border); background: linear-gradient(180deg, rgba(18,25,51,0.95), rgba(11,16,32,0.98)); padding: 20px; display: flex; flex-direction: column; gap: 18px; position: sticky; top: 0; height: 100vh; } -.brand { display: flex; gap: 12px; align-items: center; } -.logo { width: 42px; height: 42px; border-radius: 12px; background: linear-gradient(135deg, var(--primary), #8b5cf6); display: grid; place-items: center; font-weight: 700; box-shadow: var(--shadow); } -.brand h1 { font-size: 18px; margin: 0; } -.muted { color: var(--muted); margin: 0; } -.small { font-size: 12px; } -nav { display: flex; flex-direction: column; gap: 6px; } -.nav-btn { text-align: left; padding: 10px 12px; background: transparent; border: 1px solid transparent; border-radius: 10px; cursor: pointer; color: var(--muted); } -.nav-btn:hover { background: rgba(255,255,255,0.04); color: var(--text); } -.nav-btn.active { background: rgba(110,168,254,0.12); border-color: rgba(110,168,254,0.25); color: var(--text); } -.sidebar-footer { margin-top: auto; display: flex; flex-direction: column; gap: 10px; } -.field label { display: block; font-size: 12px; color: var(--muted); margin-bottom: 6px; } -input, select { width: 100%; background: var(--bg-elev); border: 1px solid var(--border); border-radius: 10px; padding: 10px 12px; outline: none; } -input:focus, select:focus { border-color: rgba(110,168,254,0.5); } -.primary { background: linear-gradient(135deg, var(--primary-2), #6366f1); border: none; padding: 11px 14px; border-radius: 10px; font-weight: 600; cursor: pointer; } -.primary:disabled { opacity: 0.6; cursor: progress; } -.ghost { background: rgba(255,255,255,0.03); border: 1px solid var(--border); padding: 8px 12px; border-radius: 10px; cursor: pointer; } -.ghost:hover { background: rgba(255,255,255,0.06); } -.content { padding: 22px 26px 40px; } -.topbar { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 18px; } -.topbar h2 { margin: 0 0 4px; font-size: 24px; } -.topbar-actions { display: flex; gap: 8px; flex-wrap: wrap; } -.view { display: none; } -.view.active { display: block; } -.cards { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 14px; margin-bottom: 14px; } -.card, .panel { background: linear-gradient(180deg, rgba(24,33,66,0.9), rgba(18,25,51,0.92)); border: 1px solid var(--border); border-radius: var(--radius); box-shadow: var(--shadow); } -.card { padding: 16px; } -.score-card { display: flex; gap: 14px; align-items: center; } -.score-ring { width: 72px; height: 72px; border-radius: 50%; display: grid; place-items: center; background: conic-gradient(var(--neutral) 0deg, rgba(255,255,255,0.06) 0deg); position: relative; } -.score-ring::before { content: ""; position: absolute; inset: 7px; background: var(--bg-elev); border-radius: 50%; } -.score-ring span { position: relative; font-size: 18px; font-weight: 700; } -.kpi-label { color: var(--muted); font-size: 12px; text-transform: uppercase; letter-spacing: .04em; } -.kpi { font-size: 28px; font-weight: 700; margin-top: 4px; } -.grade { font-size: 22px; font-weight: 700; margin: 2px 0 6px; } -.badge { display: inline-flex; align-items: center; padding: 4px 10px; border-radius: 999px; font-size: 12px; font-weight: 600; background: rgba(100,116,139,0.2); color: var(--muted); } -.badge.pass { background: rgba(45,212,191,0.15); color: var(--good); } -.badge.fail { background: rgba(251,113,133,0.15); color: var(--bad); } -.panel { margin-bottom: 14px; overflow: hidden; } -.panel-head { padding: 14px 16px; border-bottom: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; gap: 12px; } -.panel-head h3 { margin: 0; font-size: 16px; } -.table-wrap { overflow: auto; } -table { width: 100%; border-collapse: collapse; } -th, td { padding: 11px 14px; border-bottom: 1px solid var(--border); text-align: left; vertical-align: top; } -th { color: var(--muted); font-weight: 600; font-size: 12px; text-transform: uppercase; letter-spacing: .03em; background: rgba(255,255,255,0.01); } -tbody tr:hover { background: rgba(255,255,255,0.02); } -.status { display: inline-flex; padding: 3px 9px; border-radius: 999px; font-size: 12px; font-weight: 600; text-transform: capitalize; } -.status.passed { background: rgba(45,212,191,0.15); color: var(--good); } -.status.failed { background: rgba(251,113,133,0.15); color: var(--bad); } -.status.unavailable, .status.skipped { background: rgba(100,116,139,0.2); color: #b6c2d9; } -.status.error { background: rgba(245,158,11,0.18); color: var(--warn); } -.limitations { margin: 0; padding: 12px 18px 18px 34px; color: var(--muted); } -.limitations li { margin: 6px 0; } -.codeblock { margin: 0; padding: 16px; overflow: auto; color: #cfe1ff; font: 12px/1.5 ui-monospace, SFMono-Regular, Consolas, monospace; } -.doctor-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 10px; padding: 14px 16px 16px; } -.doctor-item { padding: 12px; border: 1px solid var(--border); border-radius: 12px; background: rgba(255,255,255,0.02); } -.doctor-item .name { font-weight: 600; } -.search { max-width: 320px; } -.filters select { width: auto; min-width: 160px; } -@media (max-width: 1100px) { .cards { grid-template-columns: repeat(2, minmax(0,1fr)); } } -@media (max-width: 860px) { .app { grid-template-columns: 1fr; } .sidebar { position: static; height: auto; } } +:root { --ink:#1c2a29; --muted:#60716b; --border:#e5ebe8; --good:#19876b; --warn:#b97b27; --bad:#bd5d58; --neutral:#899c97; font-synthesis:none; } +* { box-sizing:border-box; } +html, body { margin:0; min-height:100%; background:#f6f8f6; color:var(--ink); font:14px/1.5 Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; } +button, input, select { font:inherit; color:inherit; } +button { cursor:pointer; } +button:focus-visible, input:focus-visible, select:focus-visible { outline:3px solid #8bd3bc; outline-offset:2px; } +svg { width:18px; height:18px; fill:none; stroke:currentColor; stroke-width:1.7; stroke-linecap:round; stroke-linejoin:round; flex:none; } +.icon-defs, .sr-only { position:absolute; width:1px; height:1px; overflow:hidden; clip:rect(0,0,0,0); white-space:nowrap; } +.app { display:grid; grid-template-columns:246px minmax(0,1fr); min-height:100vh; } +.sidebar { background:#172b28; color:#fff; padding:32px 18px 20px; display:flex; flex-direction:column; position:sticky; top:0; height:100vh; } +.brand { display:flex; align-items:center; gap:11px; padding:0 8px 42px; } +.logo { width:39px; height:39px; display:grid; place-items:center; background:#b9e4cf; color:#183a30; border-radius:12px; } +.logo svg { width:23px; height:23px; stroke-width:2; } +.brand h1 { margin:0; font-size:17px; letter-spacing:-.5px; line-height:1.2; } +.brand h1 span { color:#a6d9bf; } +.brand p { margin:4px 0 0; font-size:8px; font-weight:700; letter-spacing:1.35px; color:#91aaa0; } +.nav-label { color:#77918a; font-size:10px; font-weight:700; letter-spacing:1.2px; padding:0 14px; margin-bottom:12px; } +nav { display:flex; flex-direction:column; gap:5px; } +.nav-btn { display:flex; align-items:center; gap:13px; width:100%; text-align:left; padding:12px 14px; color:#a6bab3; background:transparent; border:0; border-radius:8px; font-weight:500; } +.nav-btn:hover { background:#233c36; color:white; } +.nav-btn.active { color:#e4f7ec; background:#31544a; font-weight:650; } +.nav-btn.active svg { color:#b2e1c8; } +.sidebar-footer { margin-top:auto; background:#223a34; border:1px solid #37534a; border-radius:12px; padding:16px; } +.local-icon { color:#bce5ce; margin-bottom:11px; } +.sidebar-footer strong { font-size:13px; } +.sidebar-footer p { font-size:12px; line-height:1.6; color:#a4b9b0; margin:7px 0 15px; } +.sidebar-footer span { color:#b6d7c4; font-size:9px; font-weight:700; letter-spacing:.9px; } +i { display:inline-block; width:6px; height:6px; border-radius:50%; background:#81caa4; margin-right:6px; vertical-align:middle; } +.sidebar-bottom { color:#789088; padding:21px 3px 0; font-size:10px; letter-spacing:1px; font-weight:700; }.sidebar-bottom span { margin:0 6px; } +.content { padding:0 42px 45px; min-width:0; max-width:1700px; width:100%; margin:0 auto; } +.utility-bar { height:58px; display:flex; align-items:center; justify-content:space-between; border-bottom:1px solid var(--border); color:#596f65; font-size:10px; font-weight:700; letter-spacing:1px; }.utility-bar span { margin:0 10px; color:#cbd5d1; }.utility-bar strong { color:#5d7369; } +.local-pill { color:#526f60; background:#edf3ef; border:1px solid #e1ebe4; border-radius:20px; padding:6px 10px; font-size:10px; letter-spacing:0; font-weight:600; } +.topbar { display:flex; justify-content:space-between; align-items:end; gap:20px; padding:31px 0 25px; }.eyebrow { font-size:10px; letter-spacing:1.35px; font-weight:750; color:#557666; }.topbar h2 { margin:4px 0 3px; font-size:30px; line-height:1.2; letter-spacing:-1.15px; }.muted { color:var(--muted); margin:0; }.topbar .muted { font-size:13px; }.topbar-actions { display:flex; gap:8px; flex-wrap:wrap; } +.ghost { display:inline-flex; align-items:center; justify-content:center; gap:8px; padding:10px 13px; border:1px solid #dfe7e2; background:#fff; border-radius:8px; font-size:12px; font-weight:650; color:#52665e; }.ghost svg { width:15px; height:15px; }.ghost:hover { background:#edf4ef; } +.view { display:none; }.view.active { display:block; } +.hero { position:relative; overflow:hidden; min-height:305px; display:grid; grid-template-columns:minmax(0,1fr) 270px; color:#fff; background:#1e3b34; border-radius:16px; } +.hero::before, .hero::after { content:""; position:absolute; pointer-events:none; border:1px solid rgba(189,224,199,.1); border-radius:50%; width:470px; height:470px; right:180px; top:-210px; }.hero::after { width:600px; height:600px; right:115px; top:-275px; } +.hero-copy { position:relative; z-index:1; padding:31px 36px 27px; }.hero-kicker { color:#b6dac4; font-size:10px; font-weight:750; letter-spacing:1.45px; }.hero-kicker span { display:inline-block; width:18px; height:2px; vertical-align:middle; margin-right:7px; background:#a7d5b8; }.hero h3 { margin:14px 0 10px; font-size:32px; line-height:1.14; font-weight:650; letter-spacing:-1px; }.hero h3 em { font-family:Georgia, serif; font-weight:400; color:#b8e2c8; }.hero-copy > p:not(.scan-status) { max-width:475px; margin:0; color:#b1c7ba; font-size:13px; line-height:1.65; } +.scan-controls { display:flex; gap:9px; max-width:590px; align-items:end; margin-top:21px; }.field { flex:1; min-width:0; }.field label { display:block; margin-bottom:6px; font-size:9px; font-weight:700; letter-spacing:1px; color:#b2c9bd; }.input-wrap { display:flex; align-items:center; gap:9px; background:#fff; color:#90a49a; border-radius:8px; padding:0 12px; }.input-wrap svg { width:16px; }.input-wrap input { min-width:0; width:100%; border:0; outline:0; padding:12px 0; color:#43574e; background:transparent; font-size:12px; }.input-wrap:focus-within { outline:3px solid #8bd3bc; }.primary { display:inline-flex; align-items:center; justify-content:center; gap:18px; min-height:42px; padding:0 17px; border:0; border-radius:8px; color:#183a2d; background:#bce5ca; font-size:12px; font-weight:750; white-space:nowrap; }.primary:hover { background:#d1f1dc; }.primary:disabled { opacity:.6; cursor:progress; }.primary svg { width:16px; } +.scan-status { color:#a7c2b2; font-size:11px; margin:9px 0 0; } +.hero-score { position:relative; z-index:1; display:flex; flex-direction:column; align-items:center; justify-content:center; border-left:1px solid rgba(213,239,222,.12); background:rgba(11,36,29,.15); padding:22px; }.score-heading { width:100%; display:flex; justify-content:space-between; color:#a7c3b3; letter-spacing:1px; font-weight:700; font-size:9px; }.score-heading span { font-size:16px; }.score-ring { width:140px; height:140px; display:grid; place-items:center; border-radius:50%; margin:17px 0 12px; background:conic-gradient(var(--neutral) 0deg, rgba(220,246,230,.14) 0deg); }.score-inner { width:122px; height:122px; border-radius:50%; background:#203e35; display:flex; flex-direction:column; align-items:center; justify-content:center; }.score-inner span { font-size:38px; font-weight:650; line-height:1; letter-spacing:-2px; }.score-inner small { margin-top:8px; font-size:8px; font-weight:700; letter-spacing:1px; color:#9ab9a8; }.grade { font-size:13px; font-weight:650; margin-bottom:7px; }.badge { display:inline-flex; align-items:center; padding:4px 9px; border-radius:20px; font-size:10px; font-weight:700; color:#c1d7ca; background:#38584b; }.badge.pass { background:#ddf3e7; color:#26785a; }.badge.fail { background:#f9e7e4; color:#a34943; } +.section-heading { display:flex; align-items:end; justify-content:space-between; margin:32px 0 14px; }.section-heading h3, .panel h3 { font-size:18px; letter-spacing:-.4px; margin:3px 0 0; }.section-note { color:#687c72; font-size:12px; }.cards { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:14px; margin-bottom:24px; }.card,.panel { background:#fff; border:1px solid var(--border); border-radius:12px; box-shadow:0 3px 12px rgba(23,48,37,.025); }.card { padding:17px 19px 16px; }.card-top { display:flex; align-items:center; justify-content:space-between; }.kpi-label { font-size:10px; color:#62766b; letter-spacing:1px; font-weight:750; }.metric-icon { display:grid; place-items:center; width:33px; height:33px; border-radius:9px; }.metric-icon svg { width:16px; }.blue { color:#6685a7; background:#edf3f8; }.peach { color:#c28768; background:#fbf1e9; }.green { color:#6e9a7b; background:#edf6ee; }.kpi { font-size:28px; line-height:1.2; font-weight:700; letter-spacing:-1px; margin:3px 0; }.small { font-size:12px; } +.dashboard-grid { display:grid; grid-template-columns:minmax(0,1.8fr) minmax(260px,1fr); gap:14px; align-items:start; }.panel { overflow:hidden; margin-bottom:14px; }.panel-head { padding:20px 21px; display:flex; justify-content:space-between; align-items:center; gap:14px; border-bottom:1px solid #edf1ee; }.panel-head p { color:#667b70; font-size:12px; margin:4px 0 0; }.table-wrap { overflow:auto; }table { width:100%; border-collapse:collapse; }th, td { padding:12px 15px; border-bottom:1px solid #f0f3f1; text-align:left; vertical-align:top; font-size:12px; }th { color:#5e7167; font-size:9px; text-transform:uppercase; letter-spacing:.8px; white-space:nowrap; background:#fafcfb; }tbody tr:last-child td { border-bottom:0; }tbody tr:hover { background:#fbfdfb; }.empty-cell { text-align:center; padding:32px 15px 37px; color:#53695f; }.empty-cell strong,.empty-cell span { display:block; }.empty-cell span { margin-top:5px; color:#5f7368; font-size:12px; }.empty-icon { margin:0 auto 10px; display:grid; place-items:center; width:38px; height:38px; background:#eef5f0; border-radius:50%; color:#8bb19a; } +select, .search { background:#fff; border:1px solid #e2eae5; border-radius:8px; padding:9px 12px; color:#60756b; font-size:12px; }.search { width:220px; }.status { display:inline-flex; padding:3px 8px; border-radius:20px; font-size:10px; font-weight:700; text-transform:capitalize; }.status.passed { background:#e5f5ea; color:#27855f; }.status.failed { background:#fae9e7; color:#b8504c; }.status.unavailable,.status.skipped { background:#f0f3f1; color:#75857d; }.status.error { background:#fbf1dd; color:#a77321; } +.insight-icon { color:#7ba38b; background:#eef6f0; width:36px; height:36px; display:grid; place-items:center; border-radius:10px; }.insight-body { padding:18px 21px 22px; color:#5e7568; font-size:12px; line-height:1.7; }.insight-body p { margin:0; }.insight-divider { border-top:1px solid #edf1ee; margin:17px 0; }.insight-title { font-size:9px; font-weight:750; letter-spacing:1px; color:#5d7367; }.limitations { margin:8px 0 0; padding-left:17px; }.limitations li { margin:7px 0; padding-left:3px; }.codeblock { margin:0; padding:20px; overflow:auto; color:#526d5e; font:12px/1.6 ui-monospace, SFMono-Regular, Consolas, monospace; }.doctor-grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(180px,1fr)); gap:10px; padding:20px; }.doctor-item { padding:14px; border:1px solid var(--border); border-radius:9px; overflow-wrap:anywhere; }.doctor-item .name { font-weight:700; margin-bottom:8px; }.doctor-item .small { margin-top:8px; } +@media (max-width:1100px) { .content { padding-left:28px; padding-right:28px; }.dashboard-grid { grid-template-columns:1fr; }.hero { grid-template-columns:minmax(0,1fr) 220px; } } +@media (max-width:760px) { .app { display:block; }.sidebar { position:static; height:auto; padding:16px; }.brand { padding:0 0 15px; }.nav-label,.sidebar-footer,.sidebar-bottom { display:none; }nav { flex-direction:row; flex-wrap:wrap; }.nav-btn { width:auto; white-space:nowrap; padding:9px 11px; }.nav-btn svg { width:15px; }.content { padding:0 18px 30px; }.utility-bar { height:45px; }.topbar { align-items:flex-start; flex-direction:column; padding:24px 0; }.topbar h2 { font-size:26px; }.hero { grid-template-columns:1fr; }.hero-copy { padding:27px 24px; }.hero-score { border-left:0; border-top:1px solid rgba(213,239,222,.12); padding:20px; }.score-ring { width:110px; height:110px; margin:10px 0; }.score-inner { width:94px; height:94px; }.score-inner span { font-size:30px; }.cards { gap:8px; }.card { padding:13px; }.kpi { font-size:24px; }.section-note { display:none; } } +@media (max-width:480px) { .scan-controls { flex-direction:column; align-items:stretch; }.cards { grid-template-columns:1fr; }.card { display:grid; grid-template-columns:1fr auto; align-items:center; }.card-top { grid-column:1 / -1; }.panel-head { align-items:flex-start; flex-direction:column; }.filters, .filters select, .search { width:100%; }.topbar-actions { width:100%; }.topbar-actions .ghost { flex:1; }.hero h3 { font-size:29px; } }