diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 7e8767dd..c4b62460 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -12,10 +12,21 @@ -- [ ] `make check` passes (format, lint, typecheck) -- [ ] `make dev` passes (format, lint, tests) +- [ ] `make verify` passes (format, lint, types, lockstep, READMEs, manifest, tests) - [ ] Manual testing of affected commands +## Risk + + + +## How to revert + + + ## Related issues diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index dcf007f2..c611d96d 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -76,6 +76,12 @@ jobs: - name: Type check run: uv run mypy src/ packages/*/src scripts/ + # The sub-package READMEs and the marked sections of the root README + # are generated from pyproject metadata. Nothing else notices a stale + # one. Run `make readmes` to fix it. + - name: Check generated READMEs + run: make readmes-check + lockstep: name: Lockstep versions runs-on: ubuntu-latest diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..2301fb16 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,160 @@ +# Working in this repository + +Guidance for AI coding agents, and a fast orientation for people. It says what +the project guarantees, how to check your work, and where your authority ends. +[CONTRIBUTING.md](CONTRIBUTING.md) has the contributor workflow and the release +mechanics; [REVIEW.md](REVIEW.md) has the review rubric. This file does not +repeat them. + +## What this is + +`dg` (the `deepctl` distribution) is the Deepgram CLI: Python 3.10+, a `uv` +workspace of 30 first-party packages that ship at one version. + +| Path | Holds | +|---|---| +| `src/deepctl/` | Entry point, lazy command loading, the command manifest and help specs | +| `packages/deepctl-core/` | Config, credentials, transport, output, agent detection, the command base classes | +| `packages/deepctl-cmd-*/` | One package per command | +| `packages/deepctl-plugin-example/` | The third-party plugin fixture; versions on its own | +| `npm/` | The `@deepgram/cli` launcher (Node) | +| `web/` | The website | +| `bench/` | Benchmark harness and its gates | +| `tests/` | Cross-package tests; each package also has `tests/` | + +## Check your work + +One command runs what CI's lint, lockstep and test jobs run: + +```bash +make verify # everything +make verify-fast # everything except the test suite +make verify ARGS="--json" # one JSON document on stdout +make verify ARGS="--only lint types" +``` + +With `--json`, every failure is a finding with a file, a line, a rule and, +where one exists, the command that fixes it. Work the loop: run it, fix what it +reports, run it again. + +- Run `make verify-fast` after each change and `make verify` before you call + the work done. +- Stop after three rounds on the same failure. Report what you tried and the + findings that remain; do not keep going. +- Never make a check pass by weakening it. Editing a golden file, an + allowlist, `bench/gates.json`, a test's expectation or a skip marker is a + change to the project's rules. Do it only when the new behaviour is the + point of the change, and say so in the PR description. + +CI also builds every package, installs at the lowest allowed dependency +versions, and runs the npm launcher on three operating systems. `make verify` +does not; a change to packaging, dependency floors or `npm/` needs CI. + +## What must stay true + +Most of these are enforced by a test, named in brackets. The test's docstring +holds the reason; read it before changing the behaviour. A rule with no test +named is held by review. Each rule says what its test checks and no more: do +not read a wider rule into it. + +**Output** + +- Warnings, errors and notices go to stderr, and each warning prints once. In + a machine format (`-o json`, `yaml`, `csv`), stdout holds the result and + nothing else (`tests/unit/test_stream_discipline.py`). +- Exit codes: `0` success, `1` error, `2` cancelled. Callers branch on them. + `tests/unit/test_main.py` covers the root handlers; a command's own paths + are held by review. +- Output must not fail on a stream whose encoding lacks a character, such as + cp1252 on Windows (`tests/unit/test_output_encoding.py`). + +**Help and the manifest** + +- Each built-in command has a fragment in `src/deepctl/_manifest.d/`. Its + `help` block is the command's `--help` as data, and must match the command + byte for byte (`tests/unit/test_help_parity.py`, + `tests/unit/test_manifest.py`). After changing a command's options or help + text, run `uv run python -m deepctl._manifest_build --write-help`. +- Every example a command advertises must parse against its real options + (`tests/unit/test_command_examples.py`). Agents are handed those examples. + +**Startup cost** + +- Command modules import no network stack at module level: `asyncio`, `ssl`, + `httpx`, `websockets` and the Deepgram SDK belong inside the functions that + use them (`tests/unit/test_command_imports.py`). +- `dg --version` and the `dg mcp` handshake start without Click or + `deepctl_core` (`tests/unit/test_import_budget.py`, `bench/gates.json`). + +**Dependencies and versions** + +- Every runtime dependency, direct or transitive, is named in + `tests/unit/dependency_allowlist.txt`. `numpy`, `ffmpeg-python`, `future` + and `aiohttp` must not come back + (`tests/unit/test_dependency_allowlist.py`). +- All first-party packages share one version and pin each other with `==`. + `make floors-check` fails on drift and `make floors-fix` repairs it. + +**Credentials and trust** + +- Shipped text never shows an API key on a `dg` command line or in an MCP + config's `args`: the READMEs, the website, the sources and the help specs. + `dg login --api-key` is the one exemption + (`tests/unit/test_mcp_docs_lint.py`). This is about what docs and examples + show. The root `--api-key` option exists and is not a violation. +- A user config that fails to parse never has its content shown; a line can + hold a key (`tests/unit/test_config_load_errors.py`). +- A base URL from `--base-url` or `DEEPGRAM_BASE_URL` is never saved to config + (`tests/unit/test_base_url_persistence.py`). +- User-facing strings about hosts, credentials and config live in + `deepctl_core/messages.py`, keyed by message ID. Hints from the host check + in agent mode never name a config key, environment variable or flag an + agent could use to approve its own host + (`packages/deepctl-core/tests/unit/test_agent_hints.py`). +- `deepctl_core/agents.py` is the one table for detecting agents + (`packages/deepctl-core/tests/unit/test_agents.py`). `is_agentic()` decides + presentation and prompts; `is_ai_agent()` decides trust, and trust follows + the raw agent markers, never `DG_AGENT` + (`packages/deepctl-core/tests/unit/test_agent_trust.py`). Do not use one + for the other's job. + +**Docs** + +- Shipped text must not promise `dg mcp` behaviour it doesn't have + (`tests/unit/test_mcp_docs_lint.py`). +- Sub-package READMEs and the marked sections of the root README are + generated. Run `make readmes`; do not edit them by hand. + +**Tests** + +- Tests run with `DEEPGRAM_*` variables stripped and telemetry off + (`conftest.py`). +- The live end-to-end suite in `tests/e2e/` calls the real API and is opt-in. + Do not set `RUN_LIVE_E2E` or `RUN_LIVE_E2E_PRODUCTION`. + +## Changing things + +- **A new command or package:** follow "Adding a New Command" in + [CONTRIBUTING.md](CONTRIBUTING.md). It lists every file that has to change. +- **A flag, option, output shape, exit code, environment variable or config + key:** this is public surface. Prefer adding the new form and deprecating + the old one over changing it in place. +- **Commits:** Conventional Commits. release-please builds the changelog and + picks the version bump from them, so `feat` versus `fix` is a decision, not + a label. +- **Pull requests:** one purpose each. There is no limit on size. + +## Where your authority ends + +You may read anything in the repository, and edit code, tests and docs on a +working branch. Leave these to a person unless one has asked you for exactly +that: + +- Merging, releasing, or pushing to `main`. +- Changing workflow `permissions`, `allowed_non_write_users`, or anything + else under `.github/` that decides who or what can act on the repository. +- Loosening a gate, allowlist or golden file, as described above. +- Anything that needs a real API key or reaches a real Deepgram account. + +When you are blocked, stop and leave the work legible: what is done, what is +not, and what you found. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 00000000..43c994c2 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 629895c3..339f6ebd 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -13,15 +13,25 @@ cd cli uv sync --group dev # Run all checks -make dev # format + lint + test +make verify # what CI's lint, lockstep and test jobs check +make verify-fast # the same, without the test suite +make dev # format + fix lints + test make check # format + lint + typecheck (no tests) ``` +`make verify` reports each failure with its file, line and rule, and the +command that fixes it. `make verify ARGS="--json"` prints the same report as +one JSON document ([schema](docs/contracts/verify.schema.json)), which is the +form a coding agent should read. [AGENTS.md](AGENTS.md) lists what the project +guarantees and the test behind each guarantee; [REVIEW.md](REVIEW.md) is what +a review looks for. + ## Development Workflow 1. **Create a branch** from `main` 2. **Make your changes** following the conventions below -3. **Run `make dev`** to ensure everything passes +3. **Run `make dev`** to format and fix lints, then **`make verify`** to + check what CI checks 4. **Run `make readmes`** if you added or modified packages 5. **Submit a pull request** diff --git a/Makefile b/Makefile index aff388c0..8c9bc433 100644 --- a/Makefile +++ b/Makefile @@ -30,6 +30,8 @@ help: ## Show this help message @echo "🧪 \033[1mTesting:\033[0m" @echo " \033[36mtest\033[0m Run tests (development)" @echo " \033[36mcheck\033[0m Quick quality check (no tests)" + @echo " \033[36mverify\033[0m Everything CI's lint, lockstep and test jobs check" + @echo " \033[36mverify-fast\033[0m verify without the test suite" @echo "" @echo "🔧 \033[1mCode Quality:\033[0m" @echo " \033[36mformat\033[0m Auto-format code" @@ -81,6 +83,18 @@ dev: format lint-fix test ## Run full development cycle: format, fix lints, test check: format-check lint-check typecheck ## Quick quality check (no tests) @echo "✅ Quick check complete!" +# What CI's lint, lockstep and test jobs check, as findings: a file, a line, a +# rule and the command that fixes it. ARGS passes options through, for example +# `make verify ARGS="--json"` or `make verify ARGS="--only lint types"`. +# See scripts/verify.py. +# The recipes are silent (`@`): make would otherwise echo the command to +# stdout, ahead of the JSON document. +verify: ## Run every check CI's lint, lockstep and test jobs run + @uv run python scripts/verify.py $(ARGS) + +verify-fast: ## verify without the test suite + @uv run python scripts/verify.py --skip tests $(ARGS) + # =================================================================== # TESTING # =================================================================== diff --git a/README.md b/README.md index 45b1d244..4d500444 100644 --- a/README.md +++ b/README.md @@ -516,6 +516,7 @@ git clone https://github.com/deepgram/cli && cd cli uv sync --group dev make dev # Format + lint + test make check # Format + lint + typecheck (no tests) +make verify # What CI's lint, lockstep and test jobs check ``` ### Architecture diff --git a/REVIEW.md b/REVIEW.md new file mode 100644 index 00000000..0c68adb2 --- /dev/null +++ b/REVIEW.md @@ -0,0 +1,169 @@ +# Review rubric + +What a review of a pull request in this repository looks for, written so a +person or an agent can apply it and so each finding can be traced to a rule. +[AGENTS.md](AGENTS.md) lists what the project guarantees and which test +enforces each guarantee; read it first. + +## Who decides what + +- **CI decides validity.** Formatting, lint, types, lockstep versions and the + test suite either pass or fail. A reviewer does not repeat them. +- **The reviewer judges fitness.** Is this the right change, made safely, for + the people and agents who use `dg`? That is what the rules below are for. +- **A person decides whether to merge.** An agent's review is advice. It does + not approve, request changes, or block. + +## Before reviewing + +1. Read the PR description and any linked issue. The review is against what + the change set out to do. +2. Read the whole diff, and every file it changes. No change is too large + for that: a large one takes more reading. If something kept you from part + of it, say which files you did not cover. +3. Check whether the PR changes any check: a test, a golden file, + `tests/unit/dependency_allowlist.txt`, `bench/gates.json`, a workflow. If + it does, review that change first (rule `TEST-2`). + +## Rules + +Severity says how much a finding should weigh with the person merging: +`blocker` (do not merge as is), `should-fix`, or `note`. A fourth label, +`pre-existing`, marks a problem in code this PR did not change. It is worth +knowing about and is not the author's to fix here. + +### Public surface + +| Rule | Look for | Default severity | +|---|---|---| +| `CLI-1` | A flag, option, default, output shape (`-o json`, `yaml`, `csv`, `text`), exit code, environment variable, config key or plugin API changed in place, with no deprecation path and no `!` or `BREAKING CHANGE` in the commit. | blocker | +| `CLI-2` | A new code path that writes diagnostics to stdout, or a result to stderr, in a place the stream tests do not reach. | should-fix | +| `CLI-3` | A new prompt with no flag that answers it, a destructive action that runs without `--yes`, or behaviour that only works with a terminal attached. | should-fix | +| `CLI-4` | Agent mode treated as a trust signal, or a trust decision made from `is_agentic()`. | blocker | + +For a PR that changes many signatures, the step-by-step procedure in +[.github/prompts/pr-interface-review.md](.github/prompts/pr-interface-review.md) +goes deeper than `CLI-1`. + +### Security + +| Rule | Look for | Default severity | +|---|---|---| +| `SEC-1` | A credential that can reach a log, an error message, a command line, a saved file it should not be in, or a host that is not a Deepgram API host. | blocker | +| `SEC-2` | A weaker host or config trust rule, or a hint that tells an agent how to approve something a person must approve. | blocker | +| `SEC-3` | In `.github/`: wider workflow `permissions`, a new `allowed_non_write_users`, an action not pinned to a commit, or a secret reachable from a fork's pull request. | blocker | + +### Cost + +| Rule | Look for | Default severity | +|---|---|---| +| `PERF-1` | A module-level import of a heavy or network module, or new work on a fast path (`--version`, `--help`, the `dg mcp` handshake). | should-fix | +| `DEP-1` | A new runtime dependency. Is it needed, and does the PR say why? An allowlist edit with no explanation is a finding. | should-fix | + +### Tests and checks + +| Rule | Look for | Default severity | +|---|---|---| +| `TEST-1` | A behaviour change with no test, or a bug fix with no test that fails without it. | should-fix | +| `TEST-2` | A check made weaker: a deleted or loosened test, an edited golden file, allowlist or gate, a new skip. Acceptable only when the new behaviour is the stated point of the PR. | blocker | + +### Correctness and portability + +| Rule | Look for | Default severity | +|---|---|---| +| `BUG-1` | A logic error. Name the input or state that triggers it and what goes wrong. | by impact | +| `XP-1` | Code that assumes POSIX: paths, signals, file modes, encodings, or a shell. CI runs on Linux, macOS and Windows. | should-fix | + +### Docs and release + +| Rule | Look for | Default severity | +|---|---|---| +| `DOC-1` | Help text, an example, the README or the website left describing the old behaviour, or describing behaviour that does not exist. | should-fix | +| `REL-1` | A commit type that does not match the change (`fix` for a new feature, `chore` for a user-visible change). The type sets the version bump and the changelog section. | should-fix | +| `REL-2` | A new package missing a step from "Adding a New Command" in [CONTRIBUTING.md](CONTRIBUTING.md). | should-fix | + +### Scope + +| Rule | Look for | Default severity | +|---|---|---| +| `SCOPE-1` | More than one purpose in one PR: changes that could be merged, released or reverted apart. Name the purposes. The size of a change is not a finding. | note | + +## What not to raise + +- Anything a required check already enforces: formatting, import order, lint + rules, type errors. +- Style or naming preferences that no rule here covers. +- Praise, summaries of the diff, or restatements of the PR description. +- A guess. If you cannot name the line and say what goes wrong, it is not a + finding. + +"No findings" is a complete review. + +## Files to skip + +These are generated. Do not report findings in them. If one is wrong, the +finding belongs on its source or its generator. + +- `uv.lock` and `web/package-lock.json`. +- `packages/*/README.md`, and the sections of the root `README.md` between + `` and `` markers. `make readmes` writes + them. +- The `help` block of each fragment in `src/deepctl/_manifest.d/`. + `uv run python -m deepctl._manifest_build --write-help` writes it. + +Golden files, `tests/unit/dependency_allowlist.txt` and `bench/gates.json` are +not on this list. A change to one of them is reviewed first (rule `TEST-2`). + +## What a finding contains + +Every finding has the same fields, so a person can check it and an agent can +act on it. An invented example: + +```json +{ + "rule": "CLI-2", + "severity": "should-fix", + "file": "packages/deepctl-cmd-usage/src/deepctl_cmd_usage/command.py", + "line": 118, + "claim": "The retry notice is printed with the stdout console.", + "evidence": "`dg usage -o json` with a 429 from the API prints the notice before the JSON, so stdout no longer parses.", + "suggestion": "Print it with `stderr_console`.", + "confidence": "high" +} +``` + +- `rule` is an ID from this file. A finding that fits no rule is either not a + finding or a reason to add a rule. +- `evidence` is a concrete scenario or the text of the rule broken, not a + feeling. +- `confidence` is `high`, `medium` or `low`. Report a `low` finding only when + its severity would be `blocker`. + +Report at most ten findings, most severe first. If there are more, say so. + +Open the review with a count by severity, such as "1 blocker, 2 should-fix", +or with "No findings". The findings follow, and nothing else. + +## Reviewing again + +A review and its fixes have to converge. When a PR is reviewed a second time: + +- Review what changed since the last review, not the whole diff again. +- Do not repeat a finding already posted. If it was not answered, it stands. +- When one mistake appears in several places, report it once. Put the finding + on the first place and list the others in `evidence`, so one fix covers + them all. +- After three rounds of review and fixes on one PR, raise no new findings. + Say that the approach needs a person's look, and stop. + +## Changing this rubric + +This file is the reviewer's whole brief, so it changes the way code does: by +pull request. + +- When a person overrules a finding, or catches something a review missed, + that is a signal about a rule. Tighten the rule, add one, or remove one. +- When a rule can be checked mechanically, turn it into a test and delete it + from here. A test is cheaper and more reliable than a reviewer. +- An agent's reviews stay advisory until a person decides otherwise, rule by + rule, on the evidence of how its findings have held up. diff --git a/docs/contracts/verify.schema.json b/docs/contracts/verify.schema.json new file mode 100644 index 00000000..e69b711d --- /dev/null +++ b/docs/contracts/verify.schema.json @@ -0,0 +1,84 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/deepgram/cli/blob/main/docs/contracts/verify.schema.json", + "title": "scripts/verify.py --json", + "description": "The report `make verify ARGS=\"--json\"` prints on stdout: one entry per check, and for a failed check the findings to fix.", + "type": "object", + "additionalProperties": false, + "required": ["version", "ok", "checks"], + "properties": { + "version": { + "description": "The format version. A change that removes or renames a field raises it.", + "const": 1 + }, + "ok": { + "description": "True when no check that ran failed. Mirrors the exit code: 0 when true, 1 when false.", + "type": "boolean" + }, + "checks": { + "type": "array", + "items": { "$ref": "#/$defs/check" } + } + }, + "$defs": { + "check": { + "type": "object", + "additionalProperties": false, + "required": ["name", "status", "command", "seconds", "fix", "findings", "output"], + "properties": { + "name": { + "enum": ["format", "lint", "types", "lockstep", "readmes", "manifest", "tests"] + }, + "status": { + "description": "From the command's exit code. `skipped` means --only or --skip left it out.", + "enum": ["pass", "fail", "skipped"] + }, + "command": { + "description": "The command, with globs unexpanded, for a person to rerun.", + "type": "string" + }, + "seconds": { "type": "number", "minimum": 0 }, + "fix": { + "description": "On a failed check, a command that repairs this kind of failure, when one exists.", + "type": ["string", "null"] + }, + "findings": { + "description": "Empty unless the check failed and its output could be read.", + "type": "array", + "items": { "$ref": "#/$defs/finding" } + }, + "output": { + "description": "On a failed check with no findings, the tail of the command's raw output.", + "type": ["string", "null"] + } + } + }, + "finding": { + "type": "object", + "additionalProperties": false, + "required": ["rule", "message", "file", "line", "column", "hint", "detail"], + "properties": { + "rule": { + "description": "The tool's rule or error code (`F401`, `return-value`), or the kind of failure (`lockstep`, `readme-stale`, `manifest`, `test-failure`, `test-error`).", + "type": "string", + "minLength": 1 + }, + "message": { "type": "string" }, + "file": { + "description": "Relative to the repository root, with forward slashes.", + "type": ["string", "null"] + }, + "line": { "type": ["integer", "null"], "minimum": 1 }, + "column": { "type": ["integer", "null"], "minimum": 1 }, + "hint": { + "description": "How to fix or reproduce this one finding, when the tool says.", + "type": ["string", "null"] + }, + "detail": { + "description": "For a test, the end of its failure output.", + "type": ["string", "null"] + } + } + } + } +} diff --git a/scripts/verify.py b/scripts/verify.py new file mode 100644 index 00000000..7b934880 --- /dev/null +++ b/scripts/verify.py @@ -0,0 +1,485 @@ +#!/usr/bin/env python3 +"""Run the checks CI's lint, lockstep and test jobs run, and report findings. + +One entry point for a person or a coding agent to learn whether a change is +acceptable, before CI says so. Each check is the command CI runs +(`.github/workflows/test.yml`), asked for machine-readable output where the +tool has one, and every failure becomes a finding: a file, a line, a rule, a +message and, where there is one, the command that fixes it. + + uv run python scripts/verify.py # every check, human report + uv run python scripts/verify.py --json # one JSON document on stdout + uv run python scripts/verify.py --skip tests # everything but the test suite + uv run python scripts/verify.py --only lint types + uv run python scripts/verify.py --list + +stdout carries the report and nothing else; progress goes to stderr. The exit +code is 0 when every check that ran passed and 1 otherwise. A check's status +comes from its command's exit code, never from whether findings could be +parsed, so output this script fails to understand is still a failure: the +tail of the raw output is reported in place of findings. + +The JSON document is described by `docs/contracts/verify.schema.json`. + +Not covered here, and still required by CI: the package build, the install at +the lowest allowed dependency versions, and the npm launcher jobs. +""" + +from __future__ import annotations + +import argparse +import glob +import io +import json +import subprocess +import sys +import tempfile +import time +import xml.etree.ElementTree as ET +from dataclasses import asdict, dataclass, field +from pathlib import Path +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + +REPO = Path(__file__).resolve().parents[1] + +# What CI lints and type-checks. tests/unit/test_verify.py holds this, and the +# commands built from it, against .github/workflows/test.yml. +SOURCES = ("src/", "packages/*/src", "scripts/") + +SCHEMA_VERSION = 1 +OUTPUT_TAIL_LINES = 40 +DETAIL_TAIL_LINES = 30 + + +@dataclass(frozen=True) +class Finding: + """One thing to fix.""" + + rule: str + message: str + file: str | None = None + line: int | None = None + column: int | None = None + hint: str | None = None + detail: str | None = None + + +@dataclass(frozen=True) +class Run: + """What a check's command did.""" + + returncode: int + stdout: str + stderr: str + report: Path | None = None + + +@dataclass(frozen=True) +class Check: + """One check: the command, how to read its failures, and how to fix them. + + `ci` is the command as `.github/workflows/test.yml` spells it, or None for + a check CI runs some other way (the manifest check through the unit + tests, the tests through an explicit list of paths). + """ + + name: str + summary: str + command: tuple[str, ...] + parse: Callable[[Run], list[Finding]] + ci: str | None = None + fix: str | None = None + paths: tuple[str, ...] = () + junit: bool = False + + +@dataclass +class Result: + name: str + status: str + command: str + seconds: float + fix: str | None = None + findings: list[Finding] = field(default_factory=list) + output: str | None = None + + +def relative(path: str) -> str: + """`path` relative to the repository, with forward slashes.""" + candidate = Path(path) + if candidate.is_absolute(): + try: + candidate = candidate.resolve().relative_to(REPO) + except ValueError: + return candidate.as_posix() + return candidate.as_posix() + + +def tail(text: str, lines: int) -> str: + return "\n".join(text.rstrip().splitlines()[-lines:]) + + +# -- parsers ----------------------------------------------------------------- + + +def parse_ruff(run: Run) -> list[Finding]: + """`ruff check` and `ruff format --check` with `--output-format json`.""" + findings = [] + for item in json.loads(run.stdout): + fix = item.get("fix") or {} + location = item.get("location") or {} + findings.append( + Finding( + rule=item.get("code") or "syntax-error", + message=item["message"], + file=relative(item["filename"]), + line=location.get("row"), + column=location.get("column"), + hint=fix.get("message"), + ) + ) + return findings + + +def parse_mypy(run: Run) -> list[Finding]: + """`mypy --output json`: one JSON object per line.""" + findings = [] + for line in run.stdout.splitlines(): + if not line.startswith("{"): + continue + item = json.loads(line) + if item.get("severity") != "error": + continue + column = item.get("column") + findings.append( + Finding( + rule=item.get("code") or "mypy", + message=item["message"], + file=relative(item["file"]), + line=item.get("line"), + # mypy's JSON counts columns from 0, and uses -1 for "none". + column=column + 1 if isinstance(column, int) and column >= 0 else None, + hint=item.get("hint"), + ) + ) + return findings + + +def parse_lockstep(run: Run) -> list[Finding]: + """`scripts/check_dependency_floors.py`: ` - where: message` on stderr.""" + findings = [] + for line in run.stderr.splitlines(): + if not line.startswith(" - "): + continue + where, _, message = line[4:].partition(": ") + if message and (REPO / where).is_file(): + findings.append(Finding(rule="lockstep", message=message, file=where)) + else: + findings.append(Finding(rule="lockstep", message=line[4:])) + return findings + + +def parse_readmes(run: Run) -> list[Finding]: + """`scripts/generate_readmes.py --check`: ` — out of date`.""" + findings = [] + for line in run.stdout.splitlines(): + name, marker, _ = line.strip().partition(" — out of date") + if not marker: + continue + file = name if name == "README.md" else f"packages/{name}" + findings.append( + Finding( + rule="readme-stale", + message="generated README is out of date", + file=file, + ) + ) + return findings + + +def parse_manifest(run: Run) -> list[Finding]: + """`python -m deepctl._manifest_build --check`: `manifest: ...` on stderr.""" + return [ + Finding(rule="manifest", message=line[len("manifest: ") :]) + for line in run.stderr.splitlines() + if line.startswith("manifest: ") + ] + + +def parse_junit(run: Run) -> list[Finding]: + """pytest's JUnit XML (`junit_family=xunit1`, which records file and line).""" + if run.report is None: + return [] + findings = [] + for case in ET.parse(run.report).getroot().iter("testcase"): + for outcome in case: + if outcome.tag not in ("failure", "error"): + continue + file = case.get("file") + line = case.get("line") + name = case.get("name") or case.get("classname") or "test" + message = (outcome.get("message") or outcome.tag).strip() + findings.append( + Finding( + rule=f"test-{outcome.tag}", + message=f"{name}: {message.splitlines()[0] if message else outcome.tag}", + file=relative(file) if file else None, + # pytest counts lines from 0. + line=int(line) + 1 if line is not None else None, + hint=f"uv run pytest {relative(file)}" if file else None, + detail=tail(outcome.text or "", DETAIL_TAIL_LINES) or None, + ) + ) + return findings + + +# -- checks ------------------------------------------------------------------ + +PYTHON = "python" + +CHECKS: tuple[Check, ...] = ( + Check( + name="format", + summary="ruff format --check", + command=(PYTHON, "-m", "ruff", "format", "--check", "--output-format", "json"), + paths=SOURCES, + parse=parse_ruff, + ci=f"ruff format --check {' '.join(SOURCES)}", + fix="make format", + ), + Check( + name="lint", + summary="ruff check", + command=(PYTHON, "-m", "ruff", "check", "--output-format", "json"), + paths=SOURCES, + parse=parse_ruff, + ci=f"ruff check {' '.join(SOURCES)}", + fix="make lint-fix", + ), + Check( + name="types", + summary="mypy (strict)", + command=(PYTHON, "-m", "mypy", "--output", "json"), + paths=SOURCES, + parse=parse_mypy, + ci=f"mypy {' '.join(SOURCES)}", + ), + Check( + name="lockstep", + summary="one version and exact pins across first-party packages", + command=(PYTHON, "scripts/check_dependency_floors.py"), + parse=parse_lockstep, + ci="make floors-check", + fix="make floors-fix", + ), + Check( + name="readmes", + summary="generated READMEs are current", + command=(PYTHON, "scripts/generate_readmes.py", "--check"), + parse=parse_readmes, + ci="make readmes-check", + fix="make readmes", + ), + Check( + name="manifest", + summary="command manifest and help blocks match the commands", + command=(PYTHON, "-m", "deepctl._manifest_build", "--check"), + parse=parse_manifest, + fix="uv run python -m deepctl._manifest_build --write-help", + ), + Check( + name="tests", + summary="the test suite (several minutes)", + command=(PYTHON, "-m", "pytest", "-q", "--timeout=300"), + parse=parse_junit, + junit=True, + ), +) + +NAMES = tuple(check.name for check in CHECKS) + + +def expand(paths: Sequence[str]) -> list[str]: + """Expand the globs in `paths` the way the shell does for CI.""" + expanded: list[str] = [] + for path in paths: + if "*" in path: + expanded.extend(sorted(glob.glob(path, root_dir=REPO))) + else: + expanded.append(path) + return expanded + + +def execute(argv: Sequence[str]) -> Run: + """Run one command from the repository root and capture what it prints.""" + done = subprocess.run( + list(argv), + cwd=REPO, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + check=False, + ) + return Run(done.returncode, done.stdout, done.stderr) + + +def shown(check: Check) -> str: + """The command as a person would type it, globs unexpanded.""" + return " ".join([*check.command, *check.paths]) + + +def run_check(check: Check, runner: Callable[[Sequence[str]], Run] = execute) -> Result: + argv = [sys.executable if part == PYTHON else part for part in check.command] + started = time.monotonic() + with tempfile.TemporaryDirectory(prefix="dg-verify-") as scratch: + report = Path(scratch) / "junit.xml" if check.junit else None + if report is not None: + argv += [f"--junitxml={report}", "-o", "junit_family=xunit1"] + try: + run = runner([*argv, *expand(check.paths)]) + except OSError as exc: + return Result( + check.name, + "fail", + shown(check), + round(time.monotonic() - started, 2), + output=f"could not run the command: {exc}", + ) + if report is not None and report.is_file(): + run = Run(run.returncode, run.stdout, run.stderr, report) + result = Result(check.name, "pass", shown(check), 0.0) + if run.returncode != 0: + result.status = "fail" + result.fix = check.fix + try: + result.findings = check.parse(run) + except ( + ValueError, + LookupError, + TypeError, + AttributeError, + OSError, + ET.ParseError, + ): + result.findings = [] + if not result.findings: + result.output = tail(f"{run.stdout}\n{run.stderr}", OUTPUT_TAIL_LINES) + result.seconds = round(time.monotonic() - started, 2) + return result + + +# -- reports ----------------------------------------------------------------- + + +def document(results: Sequence[Result]) -> dict[str, Any]: + return { + "version": SCHEMA_VERSION, + "ok": all(result.status != "fail" for result in results), + "checks": [asdict(result) for result in results], + } + + +def location(finding: Finding) -> str: + if finding.file is None: + return "" + parts = [finding.file] + if finding.line is not None: + parts.append(str(finding.line)) + if finding.column is not None: + parts.append(str(finding.column)) + return ":".join(parts) + + +def render(result: Result) -> str: + """One check, for a person.""" + head = f"{result.status.upper():<7} {result.name:<9}" + if result.status == "skipped": + return head.rstrip() + head += f" {result.seconds:>7.2f}s" + if result.status == "pass": + return head + count = len(result.findings) + if count: + head += f" {count} finding{'s' if count != 1 else ''}" + if result.fix: + head += f" (fix: {result.fix})" + lines = [head] + for finding in result.findings: + where = location(finding) + lines.append( + f" {where + ' ' if where else ''}{finding.rule} {finding.message}" + ) + if result.output: + lines.extend(f" | {line}" for line in result.output.splitlines()) + return "\n".join(lines) + + +def summary(results: Sequence[Result]) -> str: + ran = [result for result in results if result.status != "skipped"] + failed = [result.name for result in ran if result.status == "fail"] + if failed: + return f"{len(failed)} of {len(ran)} checks failed: {', '.join(failed)}" + return f"all {len(ran)} checks passed" + + +def main( + argv: Sequence[str] | None = None, + runner: Callable[[Sequence[str]], Run] = execute, +) -> int: + parser = argparse.ArgumentParser( + description="Run the checks CI's lint, lockstep and test jobs run.", + ) + parser.add_argument("--json", action="store_true", help="print one JSON document") + parser.add_argument("--list", action="store_true", help="list the checks and exit") + choose = parser.add_mutually_exclusive_group() + choose.add_argument( + "--only", nargs="+", choices=NAMES, metavar="CHECK", help="run only these" + ) + choose.add_argument( + "--skip", nargs="+", choices=NAMES, metavar="CHECK", help="run all but these" + ) + args = parser.parse_args(argv) + + # A test's failure message can hold any character; the report must not + # fail on a stream whose encoding lacks it. + for stream in (sys.stdout, sys.stderr): + if isinstance(stream, io.TextIOWrapper): + stream.reconfigure(errors="backslashreplace") + + if args.list: + for check in CHECKS: + print(f"{check.name:<9} {check.summary}") + return 0 + + selected = set(args.only or NAMES) - set(args.skip or ()) + results = [] + for check in CHECKS: + if check.name not in selected: + result = Result(check.name, "skipped", shown(check), 0.0) + else: + # Progress, for a report that only appears at the end (--json) + # and for the one check that takes minutes. + if args.json or check.junit: + print( + f"verify: {check.name}: {check.summary}", + file=sys.stderr, + flush=True, + ) + result = run_check(check, runner) + results.append(result) + if not args.json: + print(render(result), flush=True) + + if args.json: + print(json.dumps(document(results), indent=2)) + else: + print(f"\n{summary(results)}") + return 0 if all(result.status != "fail" for result in results) else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/unit/test_verify.py b/tests/unit/test_verify.py new file mode 100644 index 00000000..80535322 --- /dev/null +++ b/tests/unit/test_verify.py @@ -0,0 +1,396 @@ +"""Tests for scripts/verify.py, the one command that runs CI's checks locally. + +A person or a coding agent decides whether a change is acceptable from what +this script reports, so three things have to hold: + +* it checks what CI checks. The commands are held against + `.github/workflows/test.yml`; a check that passes here and fails there (or + the reverse) sends the fix loop after the wrong target. +* a failure is never reported as a pass. Status comes from the exit code, and + output the script can't read is still a failure, with the raw output. +* with `--json`, stdout is one document that matches + `docs/contracts/verify.schema.json`, and nothing else. + +No test here runs ruff, mypy or the suite itself: each check's command is +replaced by a stand-in, so these run wherever the unit tests do. +""" + +from __future__ import annotations + +import importlib.util +import json +import re +import subprocess +import sys +from pathlib import Path +from typing import TYPE_CHECKING, Any + +import pytest + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + +REPO = Path(__file__).resolve().parents[2] +SCRIPT = REPO / "scripts" / "verify.py" +SCHEMA = REPO / "docs" / "contracts" / "verify.schema.json" +WORKFLOW = REPO / ".github" / "workflows" / "test.yml" +MAKEFILE = REPO / "Makefile" + + +def _load() -> Any: + spec = importlib.util.spec_from_file_location("dg_verify_script", SCRIPT) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + # dataclasses looks its module up in sys.modules while the class is built. + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +verify = _load() + + +def check(name: str) -> Any: + return next(c for c in verify.CHECKS if c.name == name) + + +def stand_in(returncode: int, stdout: str = "", stderr: str = "") -> Callable[..., Any]: + """A runner that returns the same result for any command.""" + + def runner(argv: Sequence[str]) -> Any: + runner.calls.append(list(argv)) # type: ignore[attr-defined] + return verify.Run(returncode, stdout, stderr) + + runner.calls = [] # type: ignore[attr-defined] + return runner + + +RUFF_JSON = json.dumps( + [ + { + "code": "F401", + "filename": str(REPO / "packages" / "deepctl-core" / "src" / "a.py"), + "fix": {"applicability": "safe", "edits": [], "message": "Remove import"}, + "location": {"column": 8, "row": 3}, + "message": "`os` imported but unused", + }, + { + "code": None, + "filename": str(REPO / "scripts" / "b.py"), + "fix": None, + "location": {"column": 1, "row": 9}, + "message": "Expected an expression", + }, + ] +) + +MYPY_JSON = "\n".join( + [ + json.dumps( + { + "file": "scripts/b.py", + "line": 3, + "column": 11, + "message": 'Incompatible return value type (got "int", expected "str")', + "hint": None, + "code": "return-value", + "severity": "error", + } + ), + json.dumps( + { + "file": "scripts/b.py", + "line": 3, + "column": -1, + "message": "See the docs", + "hint": None, + "code": None, + "severity": "note", + } + ), + "", + ] +) + +JUNIT = """ + + + +def test_bad(): +> assert f() == 2 +E assert 1 == 2 +tests/unit/test_x.py:14: AssertionError + + +boom + + +""" + + +class TestParsers: + def test_ruff_findings_carry_rule_place_and_fix(self) -> None: + first, second = verify.parse_ruff(verify.Run(1, RUFF_JSON, "")) + assert (first.rule, first.file, first.line, first.column) == ( + "F401", + "packages/deepctl-core/src/a.py", + 3, + 8, + ) + assert first.message == "`os` imported but unused" + assert first.hint == "Remove import" + # ruff reports a file it can't parse with no code. + assert (second.rule, second.hint) == ("syntax-error", None) + + def test_mypy_reports_errors_only_with_one_based_columns(self) -> None: + (finding,) = verify.parse_mypy(verify.Run(1, MYPY_JSON, "")) + assert (finding.rule, finding.file, finding.line, finding.column) == ( + "return-value", + "scripts/b.py", + 3, + 12, + ) + + def test_lockstep_names_the_file_when_the_line_starts_with_one(self) -> None: + stderr = ( + "lockstep check FAILED:\n" + " - pyproject.toml: version is 1.0.0, root is 2.0.0\n" + " - release manifest: no entry for '.'\n" + "\nRun `make floors-fix` to set every version and pin.\n" + ) + named, unnamed = verify.parse_lockstep(verify.Run(1, "", stderr)) + assert (named.file, named.message) == ( + "pyproject.toml", + "version is 1.0.0, root is 2.0.0", + ) + assert (unnamed.file, unnamed.message) == ( + None, + "release manifest: no entry for '.'", + ) + + def test_readmes_lists_each_stale_file(self) -> None: + stdout = ( + " deepctl-cmd-keys/README.md — up to date\n" + " deepctl-cmd-usage/README.md — out of date\n" + " README.md — out of date\n" + "\n2 README(s) out of date. Run: make readmes\n" + ) + findings = verify.parse_readmes(verify.Run(1, stdout, "")) + assert [f.file for f in findings] == [ + "packages/deepctl-cmd-usage/README.md", + "README.md", + ] + + def test_manifest_keeps_the_message_and_its_remedy(self) -> None: + stderr = ( + "manifest: help blocks out of date (run python -m " + "deepctl._manifest_build --write-help): usage.json\n" + ) + (finding,) = verify.parse_manifest(verify.Run(1, "", stderr)) + assert finding.rule == "manifest" + assert finding.message.startswith("help blocks out of date") + assert finding.message.endswith("usage.json") + + def test_junit_reports_failures_and_errors_not_passes(self, tmp_path: Path) -> None: + report = tmp_path / "junit.xml" + report.write_text(JUNIT, encoding="utf-8") + failure, error = verify.parse_junit(verify.Run(1, "", "", report)) + assert failure.rule == "test-failure" + assert failure.message == "test_bad[a-b]: assert 1 == 2" + # pytest counts lines from 0. + assert (failure.file, failure.line) == ("tests/unit/test_x.py", 12) + assert failure.hint == "uv run pytest tests/unit/test_x.py" + assert failure.detail is not None + assert failure.detail.endswith("tests/unit/test_x.py:14: AssertionError") + assert (error.rule, error.line) == ("test-error", 1) + assert "café" in error.message + + def test_junit_without_a_report_has_no_findings(self) -> None: + assert verify.parse_junit(verify.Run(2, "", "usage error")) == [] + + +class TestRunCheck: + def test_a_zero_exit_passes_whatever_was_printed(self) -> None: + # A passing mypy run can still print notes; they are not findings. + result = verify.run_check(check("types"), stand_in(0, MYPY_JSON)) + assert (result.status, result.findings, result.fix, result.output) == ( + "pass", + [], + None, + None, + ) + + def test_a_failure_carries_findings_and_the_fix(self) -> None: + result = verify.run_check(check("lint"), stand_in(1, RUFF_JSON)) + assert result.status == "fail" + assert [f.rule for f in result.findings] == ["F401", "syntax-error"] + assert result.fix == "make lint-fix" + assert result.output is None + + @pytest.mark.parametrize("stdout", ["", "not json", '{"an": "object"}', "[1]"]) + def test_unreadable_output_is_still_a_failure(self, stdout: str) -> None: + result = verify.run_check(check("lint"), stand_in(1, stdout, "ruff crashed\n")) + assert result.status == "fail" + assert result.findings == [] + assert result.output is not None + assert "ruff crashed" in result.output + + def test_a_failure_with_nothing_to_parse_is_still_a_failure(self) -> None: + # Exit 1 with a clean report: never a pass. + result = verify.run_check(check("lockstep"), stand_in(1)) + assert (result.status, result.findings) == ("fail", []) + + def test_a_command_that_cannot_start_fails(self) -> None: + def runner(argv: Sequence[str]) -> Any: + raise FileNotFoundError("no such tool") + + result = verify.run_check(check("format"), runner) + assert result.status == "fail" + assert result.output is not None + assert "no such tool" in result.output + + def test_globs_are_expanded_for_the_tool(self) -> None: + runner = stand_in(0) + verify.run_check(check("lint"), runner) + (argv,) = runner.calls # type: ignore[attr-defined] + assert argv[0] == sys.executable + assert "packages/*/src" not in argv + expanded = [a.replace("\\", "/") for a in argv] + assert "packages/deepctl-core/src" in expanded + assert "src/" in expanded + assert "scripts/" in expanded + + def test_the_tests_check_reads_the_report_pytest_writes(self) -> None: + def runner(argv: Sequence[str]) -> Any: + (option,) = [a for a in argv if a.startswith("--junitxml=")] + Path(option.split("=", 1)[1]).write_text(JUNIT, encoding="utf-8") + # xunit1 is the family that records each test's file and line. + assert "junit_family=xunit1" in argv + return verify.Run(1, "2 failed", "") + + result = verify.run_check(check("tests"), runner) + assert result.status == "fail" + assert [f.rule for f in result.findings] == ["test-failure", "test-error"] + + +class TestReport: + def test_json_mode_prints_one_valid_document_on_stdout( + self, capsys: pytest.CaptureFixture[str] + ) -> None: + import jsonschema # a test dependency: this must never skip + + schema = json.loads(SCHEMA.read_text(encoding="utf-8")) + jsonschema.Draft202012Validator.check_schema(schema) + + code = verify.main( + ["--json", "--only", "lint", "types"], stand_in(1, RUFF_JSON) + ) + captured = capsys.readouterr() + document = json.loads(captured.out) + jsonschema.validate(document, schema) + + assert code == 1 + assert document["ok"] is False + by_name = {c["name"]: c for c in document["checks"]} + assert list(by_name) == list(verify.NAMES) + assert by_name["lint"]["status"] == "fail" + assert by_name["lint"]["findings"][0]["rule"] == "F401" + # mypy got ruff's output: unreadable, so a failure with the raw text. + assert by_name["types"]["status"] == "fail" + assert by_name["types"]["output"] + assert by_name["tests"]["status"] == "skipped" + # Progress is on stderr, never in the document's stream. + assert "verify: lint" in captured.err + + def test_all_passing_exits_zero(self, capsys: pytest.CaptureFixture[str]) -> None: + import jsonschema + + code = verify.main(["--json", "--skip", "tests"], stand_in(0)) + document = json.loads(capsys.readouterr().out) + jsonschema.validate(document, json.loads(SCHEMA.read_text(encoding="utf-8"))) + assert code == 0 + assert document["ok"] is True + + def test_the_human_report_names_place_rule_and_fix( + self, capsys: pytest.CaptureFixture[str] + ) -> None: + code = verify.main(["--only", "lint"], stand_in(1, RUFF_JSON)) + out = capsys.readouterr().out + assert code == 1 + assert "FAIL" in out + assert "(fix: make lint-fix)" in out + assert ( + "packages/deepctl-core/src/a.py:3:8 F401 `os` imported but unused" in out + ) + assert "1 of 1 checks failed: lint" in out + + def test_the_schema_names_every_check(self) -> None: + schema = json.loads(SCHEMA.read_text(encoding="utf-8")) + names = schema["$defs"]["check"]["properties"]["name"]["enum"] + assert names == list(verify.NAMES) + + def test_list_runs_from_a_fresh_interpreter(self) -> None: + done = subprocess.run( + [sys.executable, str(SCRIPT), "--list"], + capture_output=True, + text=True, + check=False, + ) + assert done.returncode == 0, done.stderr + assert [line.split()[0] for line in done.stdout.splitlines()] == list( + verify.NAMES + ) + + +class TestSameAsCI: + """Each check is the command `.github/workflows/test.yml` runs.""" + + workflow = WORKFLOW.read_text(encoding="utf-8") + makefile = MAKEFILE.read_text(encoding="utf-8") + + @pytest.mark.parametrize( + "name", [c.name for c in verify.CHECKS if c.ci is not None] + ) + def test_ci_runs_the_same_command(self, name: str) -> None: + ci = check(name).ci + runs = re.findall(r"^\s+run: (.+)$", self.workflow, flags=re.MULTILINE) + assert ci in runs or f"uv run {ci}" in runs, ( + f"test.yml has no step that runs `{ci}`; scripts/verify.py's " + f"`{name}` check and CI have drifted apart" + ) + + def test_the_tools_get_the_paths_ci_gives_them(self) -> None: + for name, tool in (("format", "ruff"), ("lint", "ruff"), ("types", "mypy")): + item = check(name) + assert item.paths == verify.SOURCES + assert tool in item.command + + def test_ci_tests_every_package_the_local_run_does(self) -> None: + # Locally pytest collects `packages/*/tests` (pyproject's testpaths); + # CI names each directory. A package missing from CI's list is tested + # here and nowhere that gates a merge. + (command,) = re.findall(r"uv run pytest (.+)$", self.workflow, re.MULTILINE) + listed = set(command.split()) + assert "tests" in listed + missing = sorted( + f"packages/{path.parent.name}/tests" + for path in REPO.glob("packages/*/tests") + if f"packages/{path.parent.name}/tests" not in listed + ) + assert not missing, f"test.yml's pytest step does not run: {missing}" + + @pytest.mark.parametrize( + "name", [c.name for c in verify.CHECKS if (c.fix or "").startswith("make ")] + ) + def test_each_make_fix_is_a_real_target(self, name: str) -> None: + target = check(name).fix.split()[1] + assert re.search(rf"^{re.escape(target)}:", self.makefile, re.MULTILINE) + + def test_make_verify_runs_this_script_and_prints_nothing_else(self) -> None: + # Without the `@`, make echoes the recipe to stdout and + # `make verify ARGS="--json"` no longer prints one JSON document. + assert "\n\t@uv run python scripts/verify.py $(ARGS)\n" in self.makefile + assert ( + "\n\t@uv run python scripts/verify.py --skip tests $(ARGS)\n" + in self.makefile + )