diff --git a/.github/labels.yml b/.github/labels.yml index d138385768..e546642920 100644 --- a/.github/labels.yml +++ b/.github/labels.yml @@ -215,6 +215,10 @@ color: "C2E0C6" description: "Output formats of commands: JSON, YAML and tables" +- name: "scope/research" + color: "5319E7" + description: "The research agent: the pins of the project and the news about them" + - name: "autorelease: pending" color: "EDEDED" description: "The release pull request that release-please keeps open" diff --git a/.github/workflows/pr-title.yml b/.github/workflows/pr-title.yml index ed39e0f921..80dceffe06 100644 --- a/.github/workflows/pr-title.yml +++ b/.github/workflows/pr-title.yml @@ -73,6 +73,7 @@ jobs: rag release repos + research review roadmap sandbox diff --git a/README.md b/README.md index 14adfde415..08f7289512 100644 --- a/README.md +++ b/README.md @@ -490,6 +490,7 @@ and draft readiness. | | [**tui**](docs/commands/tui.md) | `devops tui [OPTIONS]` | Interactive terminal UI dashboard for workstation situational awareness. | | [**status**](docs/commands/status.md) | `devops status [OPTIONS]` | Inspect published operational status of upstream cloud platforms (GitHub, Cloudflare) | | [**survey**](docs/commands/survey.md) | `devops survey [OPTIONS]` | Outward-facing capability and upstream maturity survey. | +| [**research**](docs/commands/research.md) | `devops research inventory [OPTIONS]` | List every pin of the project as a typed component: Python packages, tools, container images, GitHub Actions, Helm charts and Terraform providers. It reads files only. | | [**format**](docs/commands/format.md) | `devops format [OPTIONS]` | Format codebase with ruff format (or verify in check-only mode with --check). | | [**lint**](docs/commands/lint.md) | `devops lint [OPTIONS]` | Run ruff linter across the project, automatically applying fixes by default. | diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.md index 5b0d212d01..b3437b743f 100644 --- a/docs/CLI_REFERENCE.md +++ b/docs/CLI_REFERENCE.md @@ -43,6 +43,7 @@ Complete command-line reference for `devops-cli`, automatically generated from C - [`devops tui`](#devops-tui) — Interactive terminal UI dashboard (alias) - [`devops status`](#devops-status) — Inspect published operational status of upstream platforms (GitHub, Cloudflare) - [`devops survey`](#devops-survey) — Outward-facing capability and upstream maturity survey. +- [`devops research`](#devops-research) — Read what the project pins and watch the upstream of each pin. - [`devops format`](#devops-format) — Automatically apply code formatting in-place (ruff format). - [`devops lint`](#devops-lint) — Run static analysis checks and automatically apply fixes (ruff check --fix). @@ -10451,6 +10452,28 @@ devops survey [OPTIONS] --- +## devops research + +Read what the project pins and watch the upstream of each pin. + +### `devops research inventory` + +**List every pin of the project as a typed component: Python packages, tools, container images, GitHub Actions, Helm charts and Terraform providers. It reads files only.** + +```bash +devops research inventory [OPTIONS] +``` + +**Options:** + +| Option / Flag | Type | Default | Description | +|---|---|---|---| +| `--root` | `path` | - | Root of the repository to read. Default: the repository of the current directory. | +| `--format`, `-f` | `string` | `table` | Output format type (table, json, yaml, markdown). | +| `--json`, `-j` | `boolean` | - | Output findings or metrics as JSON. | + +--- + ## devops format Automatically apply code formatting in-place (ruff format). diff --git a/docs/ERRORS.md b/docs/ERRORS.md index dac965ad00..b632e3a2e2 100644 --- a/docs/ERRORS.md +++ b/docs/ERRORS.md @@ -67,6 +67,7 @@ Each exception class declares its `error_code` and `exit_code`. A command that a | `ImplementEvalError` | `ROADMAP_EVAL_REFUSED` | `1` | Roadmap | Raised when `devops roadmap eval implement` cannot read or use a fixture, or is asked for | | `InvalidBranchNameError` | `INVALID_BRANCH_NAME` | `1` | Git | Raised when a proposed Git branch name violates naming conventions. | | `InvalidURLError` | `INVALID_URL` | `1` | Validation | Raised when an invalid URL or URI scheme is provided. | +| `InventoryError` | `RESEARCH_INVENTORY_ERROR` | `1` | Research | Raised when `devops research inventory` cannot read or parse a file that holds pins (#3896). | | `KeyringUnavailableError` | `KEYRING_UNAVAILABLE` | `3` | Security | Raised when the OS Keyring service is unreachable or uninitialized. | | `KubernetesContextError` | `K8S_CONTEXT_ERROR` | `1` | K8s | Raised when a Kubernetes context cannot be resolved or is invalid. | | `KubernetesDeployError` | `K8S_DEPLOY_ERROR` | `1` | K8s | Raised when deploying manifests or Helm charts fails. | diff --git a/docs/MCP_TOOLS.md b/docs/MCP_TOOLS.md index 3483c9fb1c..3b5273eead 100644 --- a/docs/MCP_TOOLS.md +++ b/docs/MCP_TOOLS.md @@ -72,7 +72,7 @@ The `devops-cli` FastMCP server exposes DevOps automation and AI review capabili | [`gh_views_spec`](#gh-views-spec) | `true` | Output JSON schema specification for all configured project views. | | [`gh_views_sync`](#gh-views-sync) | `false` | Synchronize standardized views with the remote GitHub Projects v2 board. | | [`grafana_dashboards_list`](#grafana-dashboards-list) | `true` | List all dashboards. | -| [`hydrate_tool_domain`](#hydrate-tool-domain) | `true` | Advertise the tools for one domain, which are withheld from the listing by default. Call this before browsing a domain's tools. Available lazy domains include `argo`, `benchmark`, `branches`, `ci`, `docker`, `docs`, `gh`, `grafana`, `k8s`, `pr`, `prometheus`, `rag`, `repos`, `roadmap`, `sandbox`, `scan`, `security`, `ssh`, `telemetry`, `tf`, `tls`, `valkey`, `vault` and `verify`. Pass the domain name alone, for example `k8s`. | +| [`hydrate_tool_domain`](#hydrate-tool-domain) | `true` | Advertise the tools for one domain, which are withheld from the listing by default. Call this before browsing a domain's tools. Available lazy domains include `argo`, `benchmark`, `branches`, `ci`, `docker`, `docs`, `gh`, `grafana`, `k8s`, `pr`, `prometheus`, `rag`, `repos`, `research`, `roadmap`, `sandbox`, `scan`, `security`, `ssh`, `telemetry`, `tf`, `tls`, `valkey`, `vault` and `verify`. Pass the domain name alone, for example `k8s`. | | [`k8s_audit`](#k8s-audit) | `true` | Sanitize active K8s/Minikube cluster resource health using Derailed Popeye. | | [`k8s_bootstrap`](#k8s-bootstrap) | `false` | Bootstrap homelab Kubernetes cluster with Minikube, Calico, and ingress. | | [`k8s_chaos`](#k8s-chaos) | `false` | Run resilience and chaos experiments against Kubernetes workloads. | @@ -105,6 +105,7 @@ The `devops-cli` FastMCP server exposes DevOps automation and AI review capabili | [`prometheus_query`](#prometheus-query) | `true` | Execute an instant PromQL query. | | [`repos_list`](#repos-list) | `true` | List all cloned repositories. | | [`repos_sync`](#repos-sync) | `false` | Fetch (and optionally pull) all tracking branches across repos. | +| [`research_inventory`](#research-inventory) | `true` | List every pin of the project as a typed component: Python packages, tools, container images, GitHub Actions, Helm charts and Terraform providers. It reads files only. | | [`review_branch`](#review-branch) | `true` | Review a git branch diff. | | [`review_export_feedback`](#review-export-feedback) | `true` | Append review verdicts to the JSONL feedback dataset, which `devops ai prompt-eval` reads. Each session's findings.json and candidates.json are read, and only the findings whose verdict the dataset does not hold yet are appended. An export that finds none leaves the dataset as it was. Without --status only INVALIDATED verdicts are exported. The dataset changes no prompt and no later review. A subject reviewed more than once is exported once: its sessions share their findings by fingerprint v2. Each finding has the newest verdict a person gave it in any of those sessions, or else the verdict of the session that review history counts. --status selects by that verdict. A session that records no subject, and a finding with no fingerprint v2, are exported on their own. | | [`review_findings`](#review-findings) | `true` | Inspect structured findings for a review session. Each finding keeps its number, its place in findings.json, whatever filter the list applies, and `devops review verify --index` takes that number. With `--candidates` the list is candidates.json: every finding the review raised, the ones verification invalidated included, numbered for `devops review verify --candidate`. | @@ -1166,8 +1167,8 @@ Advertise the tools for one domain, which are withheld from the listing by defau Call this before browsing a domain's tools. Available lazy domains include `argo`, `benchmark`, `branches`, `ci`, `docker`, `docs`, `gh`, `grafana`, `k8s`, `pr`, -`prometheus`, `rag`, `repos`, `roadmap`, `sandbox`, `scan`, `security`, `ssh`, `telemetry`, -`tf`, `tls`, `valkey`, `vault` and `verify`. +`prometheus`, `rag`, `repos`, `research`, `roadmap`, `sandbox`, `scan`, `security`, `ssh`, +`telemetry`, `tf`, `tls`, `valkey`, `vault` and `verify`. Pass the domain name alone, for example `k8s`. **Annotations:** `readOnlyHint: true` @@ -1702,6 +1703,14 @@ Fetch (and optionally pull) all tracking branches across repos. | `pull` | `boolean` | No | `True` | - | | `dry_run` | `boolean` | No | `False` | Preview execution plan without mutating external state. | +### `research_inventory` + +List every pin of the project as a typed component: Python packages, tools, container images, GitHub Actions, Helm charts and Terraform providers. It reads files only. + +**Annotations:** `readOnlyHint: true` + +*No parameters required.* + ### `review_branch` Review a git branch diff. diff --git a/docs/commands/research.md b/docs/commands/research.md new file mode 100644 index 0000000000..5639a2df00 --- /dev/null +++ b/docs/commands/research.md @@ -0,0 +1,23 @@ +# `devops research` + +Read what the project pins and watch the upstream of each pin. + +## Commands + +## `devops research inventory` + +**List every pin of the project as a typed component: Python packages, tools, container images, GitHub Actions, Helm charts and Terraform providers. It reads files only.** + +```bash +devops research inventory [OPTIONS] +``` + +**Options:** + +| Option / Flag | Type | Default | Description | +|---|---|---|---| +| `--root` | `path` | - | Root of the repository to read. Default: the repository of the current directory. | +| `--format`, `-f` | `string` | `table` | Output format type (table, json, yaml, markdown). | +| `--json`, `-j` | `boolean` | - | Output findings or metrics as JSON. | + +--- diff --git a/openspec/changes/archive/2026-11-07-3896-research-inventory/.openspec.yaml b/openspec/changes/archive/2026-11-07-3896-research-inventory/.openspec.yaml new file mode 100644 index 0000000000..e582ee4a2c --- /dev/null +++ b/openspec/changes/archive/2026-11-07-3896-research-inventory/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-07 diff --git a/openspec/changes/archive/2026-11-07-3896-research-inventory/design.md b/openspec/changes/archive/2026-11-07-3896-research-inventory/design.md new file mode 100644 index 0000000000..64eee1dd5a --- /dev/null +++ b/openspec/changes/archive/2026-11-07-3896-research-inventory/design.md @@ -0,0 +1,40 @@ +# Design + +## Context + +The research agent needs one list of what the project pins before it can look for news upstream. The list is an input to later steps, so it must be stable (same files, same list, same order) and typed. + +## Goals / Non-Goals + +**Goals:** +- One `Component` for each pin in the files, with a kind, an ecosystem, a name, a version, a file and a line. +- No model, no network, no store, and no program started. +- Tests on fixture files that copy the shapes of the repository, and one test over the real tree. + +**Non-Goals:** +- The mapping file `.devops/research-watch.toml`, the purl and the upstream repository of a component, and pins outside the repository. +- The images that Helm renders from a chart. +- Any lookup of a newer version. + +## Decisions + +- **Decision: One component for each place a pin is written.** + *Choice:* The list holds the same action once for each `uses:` line, so `actions/checkout` has about twenty-two components. A later step groups them by name and version. The file and line of each stay known. + *Rejected alternative:* One component for each name and version, with a list of places. It loses the line of a pin that a later step must edit, and gives a model with a list inside a record. +- **Decision: A direct Python dependency has the pin of `pyproject.toml`; `uv.lock` adds only the packages that no direct dependency names.** + *Choice:* The count of Python components equals the packages of the lock plus the groups that declare them. + *Rejected alternative:* A component for each package of `uv.lock` and one more for each declaration. It counts one pin twice. +- **Decision: Lines come from the parser when it gives one, else from the text.** + *Choice:* PyYAML nodes and tree-sitter nodes give lines. For TOML, JSON and HCL, `LineIndex` finds the line that shows the pin, and gives 0 when none does. A test over the real tree fails on a 0. + *Rejected alternative:* A TOML library that keeps positions, such as `tomlkit`. It adds a dependency for one number. +- **Decision: Read the images in the files, not the rendered ones.** + *Choice:* `image_nodes` of `devops_cli.k8s.image_pins` reads an `image` value, and the reader adds the `repository` with `tag` form of a values file. + *Rejected alternative:* Reuse the renderer of `devops k8s image-pins`. It runs `helm template --repo` and `kubectl kustomize`, which start programs and fetch charts. The acceptance criteria forbid a network request. +- **Decision: The ecosystem is `unknown` when the pin does not show it.** + *Choice:* A binary tool with a GitHub `source` is `github-release`; any other source is `unknown`. The summary counts `unknown`. + *Rejected alternative:* Drop the component. A tool that nobody can map would then be invisible. +- **Decision: A parse failure raises `InventoryError`.** + *Choice:* A file that does not parse stops the run with the file name (`RESEARCH_INVENTORY_ERROR`). A partial list would look complete. + *Rejected alternative:* Skip the file and go on. It hides a pin. +- **Decision: The MCP tool takes no argument.** + *Choice:* `--root` is not an option of the tool, so a model cannot point the reader at another path. diff --git a/openspec/changes/archive/2026-11-07-3896-research-inventory/proposal.md b/openspec/changes/archive/2026-11-07-3896-research-inventory/proposal.md new file mode 100644 index 0000000000..f3bae133d9 --- /dev/null +++ b/openspec/changes/archive/2026-11-07-3896-research-inventory/proposal.md @@ -0,0 +1,45 @@ +# Proposal + +## Why + +Issue #3896: no tool reads all the pins of the project. `devops survey` reads `pyproject.toml` only, and `devops k8s image-pins` checks that an image exists in its registry, not what it is. Nothing lists GitHub Actions versions, Dockerfile `FROM` lines, `tools.lock` entries and chart versions in one list. A research agent cannot watch what it cannot list. This change is the first slice of the research agent: a reader that lists the pins, with no model, no network and no store. + +## What Changes + +- New command group `devops research` with one command, `devops research inventory`. It reads the files of a repository and prints a typed list of components. A component has a kind, an ecosystem, a name, a version, a source file and a line. `--json` and `--format yaml` print the list and a summary with the count of each kind and each ecosystem, and the count of components with the ecosystem `unknown`. +- The reader covers these files: `pyproject.toml`, `uv.lock`, the `tools.lock` of the tools and its hashed requirement and Node lock files, the Dockerfiles, the devcontainer lock, the workflows and composite actions of `.github/`, the Argo CD Applications and the YAML under `k8s/`, and the Terraform files under `tf/`. +- A component of a source that the reader cannot map to a registry (a binary tool whose source is no GitHub repository) has the ecosystem `unknown`. It stays in the list and in the count. +- The command has the `no-external-request` dry-run class and an MCP tool (`research_inventory`, read only, with no path argument). +- `devops_cli.k8s.image_pins` makes `yaml_mappings` and `yaml_scalar` public, and adds `key_line` and `image_nodes`, so the reader reuses the way that `devops k8s image-pins` reads an image. `image_values` keeps its result. +- Observable behavior changes (a command, an MCP tool, an error code), so the change carries a spec delta for the new capability `research-inventory`. +- The change fits one pull request. + +## Capabilities + +### New Capabilities + +- `research-inventory`: The typed list of components that `devops research inventory` reads from the files of a repository. + +### Modified Capabilities + +None. + +## Impact + +- Code: `src/devops_cli/research/`, `src/devops_cli/commands/research.py`, `src/devops_cli/exceptions/research.py`, `src/devops_cli/k8s/image_pins.py`, `src/devops_cli/main.py`, `src/devops_cli/config/constants.py` (MCP exposure table), `src/devops_cli/ai/mcp/generator.py`, `src/devops_cli/lang/en/`. +- Tests: `tests/research/`, `tests/commands/test_research_inventory.py`, `tests/fixtures/research/repo/`. +- Documents: `README.md`, `docs/CLI_REFERENCE.md`, `docs/commands/research.md`, `docs/MCP_TOOLS.md` and `docs/ERRORS.md`, all generated. +- No new dependency, no network egress and no secret. +- Not in this change: the file `.devops/research-watch.toml` with the OSV mapping and the pins outside the repository, the purl and upstream repository of a component, and the images that Helm renders. Another issue holds them. + +## Feasibility + +- Checked on 2026-11-07 at `origin/main` b6af763b by running the reader on the real tree: 548 components in eight kinds (312 Python packages, 74 actions, 58 Node packages, 46 container images, 24 tools, 18 charts, 9 Terraform providers, 7 devcontainer features), every one with a line and a version. The Python count agrees with the design result: 98 declared dependencies plus 139 transitive packages are the 237 packages that `uv.lock` lists with the project itself left out, and 18 of the 31 Argo CD Applications pin a chart. +- Parsers are the ones that the project already ships: `tomllib`, PyYAML (composed nodes give lines), `packaging` (requirements), `python-hcl2` 8.1.4, `tree-sitter-dockerfile` through `tree-sitter` 0.26, and `docker.utils.parse_repository_tag` of docker-py for image references. +- python-hcl2 8.1.4 gives no line for an attribute: `with_meta=True` adds none for the `required_providers` block. The line is the one that opens the provider's attribute. A parser gives no line for a key of TOML or JSON either, so the line of those comes from the text. +- tree-sitter 0.26 warns that the integer language of `tree-sitter-dockerfile` 0.2.0 is deprecated. The reader silences this one warning where it loads the grammar, as `devops ai ast` loads it. +- The renderer of `devops k8s image-pins` runs `helm template --repo`, which fetches the chart. The reader must make no request, so it reads the images in the files as they stand, and the rendered images stay for the follow-up issue. + +## Existing Tool Considered + +Renovate extracts the same pins, but its `extract` step gives no list that code can read here and it needs a service to run. Dependabot is off for this repository. `osv-scanner` reads lock files for advisories, not workflow, image and chart pins. The reader uses `tomllib`, PyYAML, `packaging`, `python-hcl2`, tree-sitter and docker-py, which the project already depends on, and the `tools_lock` model. No new parser library is needed. The code that the change adds is the walk over eight file formats (about 600 lines with the model); it deletes no internal code. diff --git a/openspec/changes/archive/2026-11-07-3896-research-inventory/specs/research-inventory/spec.md b/openspec/changes/archive/2026-11-07-3896-research-inventory/specs/research-inventory/spec.md new file mode 100644 index 0000000000..98eeeb49cb --- /dev/null +++ b/openspec/changes/archive/2026-11-07-3896-research-inventory/specs/research-inventory/spec.md @@ -0,0 +1,51 @@ +## Purpose +How `devops research inventory` reads the pins of a repository from its files into one typed list of components, with a count of each kind and each ecosystem, and without a model, a network request or a started program. + +## ADDED Requirements + +### Requirement: The inventory lists each pin as a typed component +`devops research inventory` SHALL read the pins in `pyproject.toml`, `uv.lock`, the tools lock and its requirement and Node lock files, the Dockerfiles, the devcontainer lock, the workflows and composite actions of `.github/`, the YAML files under `k8s/` and the Terraform files under `tf/`. It SHALL list one component for each pin, with a kind, an ecosystem, a name, a version, the file from the repository root and the line, ordered by file, then line, then name. + +#### Scenario: Each kind of pin gives a component +- **WHEN** the repository holds one pin of each kind in the formats above +- **THEN** the list holds the components of the expected kind, name, version, file and line, and no other + +#### Scenario: The same action at two versions +- **WHEN** two workflow steps use `astral-sh/setup-uv` at two releases +- **THEN** the list holds two components for it, one for each release and line + +#### Scenario: A pinned action shows its release +- **WHEN** a step reads `uses: actions/checkout@ # v7` +- **THEN** the version of the component is `v7` + +### Requirement: A pin with no ecosystem is listed and counted +A component that the reader cannot map to a registry SHALL have the ecosystem `unknown`. The summary SHALL count it in `unknown`, and the total SHALL include it. + +#### Scenario: A tool from a source that is no GitHub repository +- **WHEN** a binary tool of the tools lock names a `source` outside `github.com` +- **THEN** the list holds it with the ecosystem `unknown` and the summary counts one unknown component + +### Requirement: The reader reaches nothing outside the files +The inventory SHALL start no program and open no network connection. + +#### Scenario: Programs and sockets refuse +- **WHEN** the inventory reads a repository while a program start and a socket connection fail +- **THEN** the inventory is read in full + +### Requirement: A file that does not parse stops the run +When a file does not parse, the inventory SHALL raise `InventoryError` (`RESEARCH_INVENTORY_ERROR`, exit code 1) with the path of the file. + +#### Scenario: A broken pyproject.toml +- **WHEN** `pyproject.toml` is not valid TOML +- **THEN** the command fails with `RESEARCH_INVENTORY_ERROR` and the message names `pyproject.toml` + +### Requirement: The command prints the list and the summary +The command SHALL print a table, or with `--json` or `--format yaml` the components and a summary with the total, the unknown count and the count of each kind and each ecosystem. It SHALL have the `no-external-request` dry-run class and an MCP tool that takes no argument. + +#### Scenario: JSON output +- **WHEN** `devops research inventory --root --json` runs +- **THEN** the output is the JSON of the inventory of that repository + +#### Scenario: The real repository +- **WHEN** the inventory reads the repository of devops-cli +- **THEN** it holds at least one component of every kind, and every component has a line and a version diff --git a/openspec/changes/archive/2026-11-07-3896-research-inventory/tasks.md b/openspec/changes/archive/2026-11-07-3896-research-inventory/tasks.md new file mode 100644 index 0000000000..a80b8ea07e --- /dev/null +++ b/openspec/changes/archive/2026-11-07-3896-research-inventory/tasks.md @@ -0,0 +1,25 @@ +# Tasks + +## 1. Inventory reader and command + +Reads: `src/devops_cli/k8s/image_pins.py`, `src/devops_cli/tools_lock/__init__.py`, `src/devops_cli/commands/survey.py`. Changes: `src/devops_cli/research/`, `src/devops_cli/commands/research.py`, `src/devops_cli/exceptions/research.py`, `src/devops_cli/k8s/image_pins.py`, `src/devops_cli/main.py`, `src/devops_cli/config/constants.py`, `src/devops_cli/ai/mcp/generator.py`, `src/devops_cli/lang/en/`, `tests/research/`, `tests/commands/test_research_inventory.py`, `tests/fixtures/research/repo/`. + +- [x] 1.1 Add the fixture repository, with one pin of each kind and the same action at two versions, and the tests of the list, the order, the unknown count, the refusal of programs and sockets, the parse error and the real tree + - Verification: `uv run devops ci test tests/research/test_inventory.py` +- [x] 1.2 Add `devops_cli.research` (the model, one reader for each format and `read_inventory`) and `InventoryError` + - Verification: `uv run devops ci test tests/research` +- [x] 1.3 Add the group `devops research` with the command `inventory`, its dry-run class, its MCP tool and its tests + - Verification: `uv run devops ci test tests/commands/test_research_inventory.py` +- [x] 1.4 Make the YAML helpers of `devops_cli.k8s.image_pins` public and add `key_line` and `image_nodes` + - Verification: `uv run devops ci test tests/k8s` + +## 2. Documentation + +Reads: `README.md`. Changes: `README.md`, `docs/CLI_REFERENCE.md`, `docs/commands/research.md`, `docs/MCP_TOOLS.md`, `docs/ERRORS.md`. + +- [x] 2.1 Regenerate the command pages, the error table and the MCP tool list + - Verification: `uv run devops docs generate --sync-readme` + +## Workflow follow-up + +- Pending a person: review the diff in tuicr (tuicr -r origin/main..HEAD). diff --git a/openspec/specs/research-inventory/spec.md b/openspec/specs/research-inventory/spec.md new file mode 100644 index 0000000000..ad5b9cebe7 --- /dev/null +++ b/openspec/specs/research-inventory/spec.md @@ -0,0 +1,53 @@ +# research-inventory Specification + +## Purpose +How `devops research inventory` reads the pins of a repository from its files into one typed list of components, with a count of each kind and each ecosystem, and without a model, a network request or a started program. + +## Requirements + +### Requirement: The inventory lists each pin as a typed component +`devops research inventory` SHALL read the pins in `pyproject.toml`, `uv.lock`, the tools lock and its requirement and Node lock files, the Dockerfiles, the devcontainer lock, the workflows and composite actions of `.github/`, the YAML files under `k8s/` and the Terraform files under `tf/`. It SHALL list one component for each pin, with a kind, an ecosystem, a name, a version, the file from the repository root and the line, ordered by file, then line, then name. + +#### Scenario: Each kind of pin gives a component +- **WHEN** the repository holds one pin of each kind in the formats above +- **THEN** the list holds the components of the expected kind, name, version, file and line, and no other + +#### Scenario: The same action at two versions +- **WHEN** two workflow steps use `astral-sh/setup-uv` at two releases +- **THEN** the list holds two components for it, one for each release and line + +#### Scenario: A pinned action shows its release +- **WHEN** a step reads `uses: actions/checkout@ # v7` +- **THEN** the version of the component is `v7` + +### Requirement: A pin with no ecosystem is listed and counted +A component that the reader cannot map to a registry SHALL have the ecosystem `unknown`. The summary SHALL count it in `unknown`, and the total SHALL include it. + +#### Scenario: A tool from a source that is no GitHub repository +- **WHEN** a binary tool of the tools lock names a `source` outside `github.com` +- **THEN** the list holds it with the ecosystem `unknown` and the summary counts one unknown component + +### Requirement: The reader reaches nothing outside the files +The inventory SHALL start no program and open no network connection. + +#### Scenario: Programs and sockets refuse +- **WHEN** the inventory reads a repository while a program start and a socket connection fail +- **THEN** the inventory is read in full + +### Requirement: A file that does not parse stops the run +When a file does not parse, the inventory SHALL raise `InventoryError` (`RESEARCH_INVENTORY_ERROR`, exit code 1) with the path of the file. + +#### Scenario: A broken pyproject.toml +- **WHEN** `pyproject.toml` is not valid TOML +- **THEN** the command fails with `RESEARCH_INVENTORY_ERROR` and the message names `pyproject.toml` + +### Requirement: The command prints the list and the summary +The command SHALL print a table, or with `--json` or `--format yaml` the components and a summary with the total, the unknown count and the count of each kind and each ecosystem. It SHALL have the `no-external-request` dry-run class and an MCP tool that takes no argument. + +#### Scenario: JSON output +- **WHEN** `devops research inventory --root --json` runs +- **THEN** the output is the JSON of the inventory of that repository + +#### Scenario: The real repository +- **WHEN** the inventory reads the repository of devops-cli +- **THEN** it holds at least one component of every kind, and every component has a line and a version diff --git a/src/devops_cli/ai/mcp/dispatcher.py b/src/devops_cli/ai/mcp/dispatcher.py index e22aeab2bc..99c43065af 100644 --- a/src/devops_cli/ai/mcp/dispatcher.py +++ b/src/devops_cli/ai/mcp/dispatcher.py @@ -72,6 +72,7 @@ "sandbox": "security", "workspace": "workspace", "roadmap": "roadmap", + "research": "research", } diff --git a/src/devops_cli/ai/mcp/generator.py b/src/devops_cli/ai/mcp/generator.py index 12a2d297f9..34c89952be 100644 --- a/src/devops_cli/ai/mcp/generator.py +++ b/src/devops_cli/ai/mcp/generator.py @@ -39,6 +39,8 @@ "allowed": frozenset({"trace_id"}), "required": frozenset({"trace_id"}), }, + # No `root`: the tool reads the repository of the server's working directory. + ("research", "inventory"): {"allowed": frozenset(), "required": frozenset()}, ("valkey", "ping"): {"allowed": frozenset(), "required": frozenset()}, ("valkey", "stats"): {"allowed": frozenset(), "required": frozenset()}, ("valkey", "info"): {"allowed": frozenset({"section"}), "required": frozenset()}, diff --git a/src/devops_cli/ai/mcp/server.py b/src/devops_cli/ai/mcp/server.py index c8d909d684..bc62115cd8 100644 --- a/src/devops_cli/ai/mcp/server.py +++ b/src/devops_cli/ai/mcp/server.py @@ -527,8 +527,8 @@ def hydrate_tool_domain(domain: str, ctx: Context | None = None) -> dict[str, An Call this before browsing a domain's tools. Available lazy domains include `argo`, `benchmark`, `branches`, `ci`, `docker`, `docs`, `gh`, `grafana`, `k8s`, `pr`, - `prometheus`, `rag`, `repos`, `roadmap`, `sandbox`, `scan`, `security`, `ssh`, `telemetry`, - `tf`, `tls`, `valkey`, `vault` and `verify`. + `prometheus`, `rag`, `repos`, `research`, `roadmap`, `sandbox`, `scan`, `security`, `ssh`, + `telemetry`, `tf`, `tls`, `valkey`, `vault` and `verify`. Pass the domain name alone, for example `k8s`. """ key = domain.strip().lower().removesuffix("_") diff --git a/src/devops_cli/commands/research.py b/src/devops_cli/commands/research.py new file mode 100644 index 0000000000..8a6b40881e --- /dev/null +++ b/src/devops_cli/commands/research.py @@ -0,0 +1,75 @@ +"""The research agent: read what the project pins and watch the upstream of each pin (#3896).""" + +from __future__ import annotations + +from pathlib import Path +from typing import Annotated + +import typer + +from devops_cli.config.constants import CONST_OUTPUT_FORMAT_TABLE +from devops_cli.config.defaults import DEFAULT_TABLE_FORMAT +from devops_cli.core.cli import new_typer +from devops_cli.core.repo import find_repo_root +from devops_cli.dry_run.decorator import dry_run_class +from devops_cli.lang import HELP, MESSAGES +from devops_cli.output import print_info, print_table +from devops_cli.output.serialization import emit_serialized, resolve_format +from devops_cli.research.inventory import read_inventory +from devops_cli.telemetry import trace_span + +app = new_typer( + help=HELP.research.app, + no_args_is_help=True, +) + + +@app.callback() +def research() -> None: + """Keep the group a group while it holds one command: `devops research inventory`.""" + + +@app.command("inventory", help=HELP.research.inventory) +@dry_run_class("no-external-request") +@trace_span("research.inventory") +def inventory( + root: Annotated[ + Path | None, + typer.Option("--root", help=HELP.research.inventory_root), + ] = None, + output_format: Annotated[ + str, + typer.Option("--format", "-f", help=HELP.options.format_type), + ] = DEFAULT_TABLE_FORMAT, + json_output: Annotated[ + bool, + typer.Option("--json", "-j", help=HELP.options.json_output), + ] = False, +) -> None: + """List every pin of the project.""" + result = read_inventory(find_repo_root(root)) + resolved = resolve_format(output_format, json_output=json_output) + if resolved != CONST_OUTPUT_FORMAT_TABLE: + emit_serialized(result.model_dump(mode="json"), resolved) + return + + messages = MESSAGES.research + print_table( + messages.inventory_title, + [ + (messages.kind_column, "bold cyan"), + messages.ecosystem_column, + messages.name_column, + messages.version_column, + messages.location_column, + ], + [ + [c.kind.value, c.ecosystem.value, c.name, c.version, f"{c.file}:{c.line}"] + for c in result.components + ], + ) + print_info( + messages.inventory_summary.format( + total=result.summary.total, unknown=result.summary.unknown + ) + ) diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py index aa4679b181..e2c777df2a 100644 --- a/src/devops_cli/config/constants.py +++ b/src/devops_cli/config/constants.py @@ -251,6 +251,7 @@ "prometheus", "rag", "repos", + "research", "roadmap", "sandbox", "scan", @@ -371,6 +372,7 @@ (("pr", "threads", "resolve"), 60.0, False, False), (("pr", "update"), 60.0, False, False), (("prometheus", "query"), 30.0, True, False), + (("research", "inventory"), 30.0, True, True), (("repos", "list"), 30.0, True, False), (("repos", "sync"), 120.0, False, False), (("review", "branch"), 300.0, True, False), diff --git a/src/devops_cli/exceptions/research.py b/src/devops_cli/exceptions/research.py new file mode 100644 index 0000000000..579c53d458 --- /dev/null +++ b/src/devops_cli/exceptions/research.py @@ -0,0 +1,11 @@ +"""Research agent exception definitions for devops-cli.""" + +from __future__ import annotations + +from devops_cli.exceptions.base import DevOpsCLIError + + +class InventoryError(DevOpsCLIError): + """Raised when `devops research inventory` cannot read or parse a file that holds pins (#3896).""" + + error_code = "RESEARCH_INVENTORY_ERROR" diff --git a/src/devops_cli/k8s/image_pins.py b/src/devops_cli/k8s/image_pins.py index f25a35aaf1..71e5535151 100644 --- a/src/devops_cli/k8s/image_pins.py +++ b/src/devops_cli/k8s/image_pins.py @@ -114,49 +114,67 @@ def is_local_registry(registry: str) -> bool: return True -def _mappings(node: yaml.Node) -> Iterator[yaml.MappingNode]: +def yaml_mappings(node: yaml.Node) -> Iterator[yaml.MappingNode]: + """`node`, if it is a mapping, and every mapping below it.""" if isinstance(node, yaml.MappingNode): yield node for _, value in node.value: - yield from _mappings(value) + yield from yaml_mappings(value) elif isinstance(node, yaml.SequenceNode): for item in node.value: - yield from _mappings(item) + yield from yaml_mappings(item) -def _scalar(node: yaml.MappingNode, key: str) -> str | None: +def yaml_scalar(node: yaml.MappingNode, key: str) -> str | None: + """The text of the scalar that `key` holds in `node`, or `None` if `key` holds none.""" for key_node, value in node.value: if key_node.value == key and isinstance(value, yaml.ScalarNode): return str(value.value) return None -def image_values(rendered: str) -> list[str]: - """Every `image` value of the objects in `rendered`, in order. +def key_line(node: yaml.MappingNode, key: str) -> int: + """The line (from 1) of the key `key` in `node`, or 0 if `node` has no such key.""" + for key_node, _ in node.value: + if key_node.value == key: + return int(key_node.start_mark.line) + 1 + return 0 + + +def image_nodes(rendered: str) -> list[tuple[str, int]]: + """Every `image` value of the objects in `rendered`, in order, with its line (from 1). The YAML is composed and not constructed, so a scalar keeps its text whatever tag YAML 1.1 gives it, such as the `value` tag of a lone `=` that a CRD schema writes. """ - found: list[str] = [] + found: list[tuple[str, int]] = [] for document in yaml.compose_all(rendered, Loader=YAML_SAFE_LOADER): - for mapping in _mappings(document) if document is not None else (): - image = _scalar(mapping, "image") + for mapping in yaml_mappings(document) if document is not None else (): + image = yaml_scalar(mapping, "image") if image: - version = _scalar(mapping, "version") + version = yaml_scalar(mapping, "version") if version and ":" not in image.rsplit("/", 1)[-1] and "@" not in image: image = f"{image}:{version}" - found.append(image) + found.append((image, key_line(mapping, "image"))) return found +def image_values(rendered: str) -> list[str]: + """Every `image` value of the objects in `rendered`, in order.""" + return [image for image, _ in image_nodes(rendered)] + + def updater_repositories(rendered: str) -> list[str]: """The repositories that the `ImageUpdater` objects in `rendered` name.""" repositories: list[str] = [] for document in yaml.compose_all(rendered, Loader=YAML_SAFE_LOADER): - if not isinstance(document, yaml.MappingNode) or _scalar(document, "kind") != _UPDATER_KIND: + if ( + not isinstance(document, yaml.MappingNode) + or yaml_scalar(document, "kind") != _UPDATER_KIND + ): continue - for mapping in _mappings(document): - name = _scalar(mapping, "imageName") + for mapping in yaml_mappings(document): + name = yaml_scalar(mapping, "imageName") if name: repositories.append("/".join(image_reference(name))) return repositories diff --git a/src/devops_cli/lang/en/help.py b/src/devops_cli/lang/en/help.py index c43134dee5..d978d638c9 100644 --- a/src/devops_cli/lang/en/help.py +++ b/src/devops_cli/lang/en/help.py @@ -2190,6 +2190,18 @@ class SurveyCommandHelp: capabilities_only: str = "Run comparable tools capability survey only." +@dataclass(frozen=True) +class ResearchCommandHelp: + app: str = "Read what the project pins and watch the upstream of each pin." + inventory: str = ( + "List every pin of the project as a typed component: Python packages, tools, container " + "images, GitHub Actions, Helm charts and Terraform providers. It reads files only." + ) + inventory_root: str = ( + "Root of the repository to read. Default: the repository of the current directory." + ) + + @dataclass(frozen=True) class HelpCatalog: main: MainHelp = field(default_factory=MainHelp) @@ -2197,6 +2209,7 @@ class HelpCatalog: ai: AICommandHelp = field(default_factory=AICommandHelp) cloudflare: CloudflareCommandHelp = field(default_factory=CloudflareCommandHelp) survey: SurveyCommandHelp = field(default_factory=SurveyCommandHelp) + research: ResearchCommandHelp = field(default_factory=ResearchCommandHelp) ai_cache: AICacheCommandHelp = field(default_factory=AICacheCommandHelp) ai_harness: AIHarnessCommandHelp = field(default_factory=AIHarnessCommandHelp) diff --git a/src/devops_cli/lang/en/messages.py b/src/devops_cli/lang/en/messages.py index a057b7f139..58b5152933 100644 --- a/src/devops_cli/lang/en/messages.py +++ b/src/devops_cli/lang/en/messages.py @@ -4631,6 +4631,17 @@ class ReleaseMessages: usage_app: str = "The login of the release App, as `[bot]`." +@dataclass(frozen=True) +class ResearchMessages: + inventory_title: str = "Pins of the project" + inventory_summary: str = "{total} components, {unknown} with an unknown ecosystem." + kind_column: str = "Kind" + ecosystem_column: str = "Ecosystem" + name_column: str = "Name" + version_column: str = "Version" + location_column: str = "File" + + @dataclass(frozen=True) class LanguageCatalog: persona_titles: PersonaTitles = field(default_factory=PersonaTitles) @@ -4641,6 +4652,7 @@ class LanguageCatalog: ai: AIMessages = field(default_factory=AIMessages) survey: SurveyMessages = field(default_factory=SurveyMessages) release: ReleaseMessages = field(default_factory=ReleaseMessages) + research: ResearchMessages = field(default_factory=ResearchMessages) benchmark: BenchmarkMessages = field(default_factory=BenchmarkMessages) config: ConfigMessages = field(default_factory=ConfigMessages) install: InstallMessages = field(default_factory=InstallMessages) diff --git a/src/devops_cli/main.py b/src/devops_cli/main.py index 8a44cd6bd7..fdce699c41 100644 --- a/src/devops_cli/main.py +++ b/src/devops_cli/main.py @@ -78,6 +78,7 @@ def _print_elapsed() -> None: "Inspect published operational status of upstream platforms (GitHub, Cloudflare)", ), "survey": ("devops_cli.commands.survey", HELP.survey.app), + "research": ("devops_cli.commands.research", HELP.research.app), "format": ("devops_cli.commands.ci", HELP.ci.format_cmd), "lint": ("devops_cli.commands.ci", HELP.ci.lint), } diff --git a/src/devops_cli/research/__init__.py b/src/devops_cli/research/__init__.py new file mode 100644 index 0000000000..a8b5d08565 --- /dev/null +++ b/src/devops_cli/research/__init__.py @@ -0,0 +1 @@ +"""The research agent: what the project pins, and the upstream of each pin (#3896).""" diff --git a/src/devops_cli/research/container_pins.py b/src/devops_cli/research/container_pins.py new file mode 100644 index 0000000000..7d44e68c10 --- /dev/null +++ b/src/devops_cli/research/container_pins.py @@ -0,0 +1,115 @@ +"""The container pins: the images of Dockerfiles and the features of the devcontainer lock (#3896). + +A Dockerfile is read with the tree-sitter grammar that `devops ai ast` loads. The images are those +of a `FROM` line and of a `COPY --from=`. A name that an earlier `FROM ... AS ` gave to +a stage is no image, and neither is a reference with a variable. +""" + +from __future__ import annotations + +import json +import warnings +from pathlib import Path +from typing import Any + +from devops_cli.research.files import ( + LineIndex, + is_template, + matching_files, + parse_errors, + relative, + split_image, +) +from devops_cli.research.models import Component, ComponentKind, Ecosystem + +DOCKERFILE_GLOBS = ("Dockerfile*", ".devcontainer/Dockerfile*") +DEVCONTAINER_LOCK = ".devcontainer/devcontainer-lock.json" +_FROM_FLAG = "--from=" + + +def image_component(reference: str, file: str, line: int) -> Component: + """The component for the image `reference`, pinned at `line` of `file`.""" + name, version = split_image(reference) + return Component( + kind=ComponentKind.CONTAINER_IMAGE, + ecosystem=Ecosystem.DOCKER, + name=name, + version=version, + file=file, + line=line, + ) + + +def _dockerfile_parser() -> Any: + import tree_sitter + import tree_sitter_dockerfile + + # The 0.2 grammar hands out its language as an integer, which tree-sitter 0.26 still accepts + # and warns about. `devops ai ast` loads the grammar the same way. + with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", message="int argument support", category=DeprecationWarning + ) + return tree_sitter.Parser(tree_sitter.Language(tree_sitter_dockerfile.language())) + + +def _text(node: Any) -> str: + return str(node.text.decode("utf-8")) + + +def _dockerfile_images(source: bytes) -> list[tuple[str, int]]: + """The images of a Dockerfile in file order, each with its line (from 1).""" + stages: set[str] = set() + images: list[tuple[str, int]] = [] + for instruction in _dockerfile_parser().parse(source).root_node.children: + line = instruction.start_point.row + 1 + if instruction.type == "from_instruction": + spec = next(c for c in instruction.children if c.type == "image_spec") + alias = next((c for c in instruction.children if c.type == "image_alias"), None) + if _text(spec) not in stages: + images.append((_text(spec), line)) + if alias is not None: + stages.add(_text(alias)) + elif instruction.type == "copy_instruction": + for param in (c for c in instruction.children if c.type == "param"): + source_name = _text(param).removeprefix(_FROM_FLAG) + if _text(param).startswith(_FROM_FLAG) and source_name not in stages: + images.append((source_name, line)) + return [(image, line) for image, line in images if not is_template(image)] + + +def _read_dockerfile(root: Path, path: Path) -> list[Component]: + with parse_errors(root, path): + images = _dockerfile_images(path.read_bytes()) + file = relative(root, path) + # A stage number, as in `COPY --from=0`, names a stage and no image. + return [image_component(image, file, line) for image, line in images if not image.isdigit()] + + +def _read_devcontainer_lock(root: Path) -> list[Component]: + path = root / DEVCONTAINER_LOCK + if not path.is_file(): + return [] + with parse_errors(root, path): + text = path.read_text(encoding="utf-8") + lines = LineIndex(text) + return [ + Component( + kind=ComponentKind.DEVCONTAINER_FEATURE, + ecosystem=Ecosystem.DEVCONTAINER_FEATURE, + name=split_image(key)[0], + version=feature["version"], + file=DEVCONTAINER_LOCK, + line=lines.find(f'"{key}"'), + ) + for key, feature in json.loads(text).get("features", {}).items() + ] + + +def read_container_pins(root: Path) -> list[Component]: + """The container components of `root`.""" + found: list[Component] = [] + for path in matching_files(root, *DOCKERFILE_GLOBS): + found.extend(_read_dockerfile(root, path)) + found.extend(_read_devcontainer_lock(root)) + return found diff --git a/src/devops_cli/research/files.py b/src/devops_cli/research/files.py new file mode 100644 index 0000000000..bb553d9f9c --- /dev/null +++ b/src/devops_cli/research/files.py @@ -0,0 +1,100 @@ +"""Shared helpers of the readers of the inventory: file lookup, line lookup and parse errors (#3896).""" + +from __future__ import annotations + +from collections.abc import Callable, Iterator +from contextlib import contextmanager +from pathlib import Path + +import yaml + +from devops_cli.exceptions.research import InventoryError + +# The prefix of the digest in an image reference. +_DIGEST_PREFIX = "sha256:" + + +def relative(root: Path, path: Path) -> str: + """The path of `path` from `root`, with `/` separators.""" + return path.relative_to(root).as_posix() + + +def matching_files(root: Path, *patterns: str) -> list[Path]: + """The files of `root` that match a glob pattern, sorted, with none below a hidden directory. + + The first segment of a pattern may be hidden (`.github`): only the segments after it are held + to the rule, so a copy of the repository under `.data/` or a `.terraform/` cache is not read. + """ + found: set[Path] = set() + for pattern in patterns: + for path in root.glob(pattern): + below = path.relative_to(root).parts[1:] + if path.is_file() and not any(part.startswith(".") for part in below[:-1]): + found.add(path) + return sorted(found) + + +@contextmanager +def parse_errors(root: Path, path: Path) -> Iterator[None]: + """Raise `InventoryError` that names `path` when the code in the block cannot read or parse it.""" + try: + yield + except (OSError, ValueError, yaml.YAMLError) as exc: + raise InventoryError( + f"Cannot read the pins of {relative(root, path)}: {exc}", + details={"file": relative(root, path)}, + ) from exc + + +def split_image(reference: str) -> tuple[str, str]: + """The name and the version of an image reference. + + The version is the tag; a reference with a digest and no tag gives the digest, and a reference + with neither gives `latest`, which is what a pull of it gets. docker-py splits the reference + by the Docker grammar. It strips only the digest of a reference with a tag and a digest, so the + split is applied twice. docker-py is imported here, as a module-level import would slow every + command that imports this module. + """ + from docker.utils import parse_repository_tag + + name, tag = parse_repository_tag(reference) + if tag and tag.startswith(_DIGEST_PREFIX): + name, inner_tag = parse_repository_tag(name) + return name, inner_tag or tag + return name, tag or "latest" + + +def is_template(value: str) -> bool: + """Whether `value` holds a template or a variable, so it names no image or version yet.""" + return any(mark in value for mark in ("{{", "${", "$(")) + + +class LineIndex: + """Finds the lines of a text that show a pin, for a file whose parser gives no line. + + Each call for the same text gives the next line that shows it, so two pins with the same text + get two lines. A text that no line shows gives 0. + """ + + def __init__(self, text: str) -> None: + self._lines = text.splitlines() + self._cursor: dict[str, int] = {} + + def find(self, needle: str) -> int: + """The next line (from 1) that holds `needle`.""" + return self._next(needle, lambda line: needle in line) + + def find_line(self, text: str) -> int: + """The next line (from 1) that is `text`, with no space at either end.""" + return self._next(text, lambda line: line.strip() == text) + + def find_where(self, key: str, match: Callable[[str], bool]) -> int: + """The next line (from 1) that `match` accepts. `key` names the search for the cursor.""" + return self._next(key, match) + + def _next(self, key: str, match: Callable[[str], bool]) -> int: + for index in range(self._cursor.get(key, 0), len(self._lines)): + if match(self._lines[index]): + self._cursor[key] = index + 1 + return index + 1 + return 0 diff --git a/src/devops_cli/research/inventory.py b/src/devops_cli/research/inventory.py new file mode 100644 index 0000000000..0d100cbf57 --- /dev/null +++ b/src/devops_cli/research/inventory.py @@ -0,0 +1,43 @@ +"""Every pin of a repository as one typed list of components (#3896). + +The readers parse the files of the repository with a parser for each format. They start no program +and make no request. +""" + +from __future__ import annotations + +from collections import Counter +from pathlib import Path + +from devops_cli.research.container_pins import read_container_pins +from devops_cli.research.k8s_pins import read_k8s_pins +from devops_cli.research.models import Component, Ecosystem, Inventory, InventorySummary +from devops_cli.research.python_pins import read_python_pins +from devops_cli.research.terraform_pins import read_terraform_pins +from devops_cli.research.tool_pins import read_tool_pins +from devops_cli.research.workflow_pins import read_workflow_pins + + +def summarize(components: list[Component]) -> InventorySummary: + """The counts of `components` in total and for each kind and ecosystem.""" + by_ecosystem = Counter(component.ecosystem.value for component in components) + return InventorySummary( + total=len(components), + unknown=by_ecosystem[Ecosystem.UNKNOWN.value], + by_kind=dict(sorted(Counter(component.kind.value for component in components).items())), + by_ecosystem=dict(sorted(by_ecosystem.items())), + ) + + +def read_inventory(root: Path) -> Inventory: + """The inventory of the repository at `root`, ordered by file, then line, then name.""" + components = [ + *read_python_pins(root), + *read_tool_pins(root), + *read_container_pins(root), + *read_workflow_pins(root), + *read_k8s_pins(root), + *read_terraform_pins(root), + ] + components.sort(key=lambda c: (c.file, c.line, c.name, c.version)) + return Inventory(components=components, summary=summarize(components)) diff --git a/src/devops_cli/research/k8s_pins.py b/src/devops_cli/research/k8s_pins.py new file mode 100644 index 0000000000..765dfe6128 --- /dev/null +++ b/src/devops_cli/research/k8s_pins.py @@ -0,0 +1,65 @@ +"""The pins under `k8s/`: the Helm charts of the Argo CD Applications and the images in YAML (#3896). + +The files are read as they stand, so the reader needs no `helm` or `kubectl` and makes no request: +a chart that an Application pins is a component, and so is each image that a manifest or a values +file names. `devops k8s image-pins` renders each Application and resolves each image in its +registry; this reader lists what the files say. It finds an image in two shapes: an `image` value, +read as `devops k8s image-pins` reads it, and a mapping with a `repository` and a `tag`, the form +of a values file. A `tag` with no `repository` beside it is a chart's own default, and no image. +An Application source with no `chart` tracks a branch, and is no pin. +""" + +from __future__ import annotations + +from pathlib import Path + +import yaml + +from devops_cli.core.serialization import YAML_SAFE_LOADER +from devops_cli.k8s.image_pins import image_nodes, key_line, yaml_mappings, yaml_scalar +from devops_cli.research.container_pins import image_component +from devops_cli.research.files import is_template, matching_files, parse_errors, relative +from devops_cli.research.models import Component, ComponentKind, Ecosystem + +K8S_GLOBS = ("k8s/**/*.yaml", "k8s/**/*.yml") + + +def _read_file(root: Path, path: Path) -> list[Component]: + with parse_errors(root, path): + text = path.read_text(encoding="utf-8") + file = relative(root, path) + found = [ + image_component(image, file, line) + for image, line in image_nodes(text) + if not is_template(image) + ] + for document in yaml.compose_all(text, Loader=YAML_SAFE_LOADER): + for mapping in yaml_mappings(document) if document is not None else (): + chart = yaml_scalar(mapping, "chart") + revision = yaml_scalar(mapping, "targetRevision") + if chart and revision: + found.append( + Component( + kind=ComponentKind.CHART, + ecosystem=Ecosystem.HELM, + name=chart, + version=revision, + file=file, + line=key_line(mapping, "targetRevision"), + ) + ) + repository = yaml_scalar(mapping, "repository") + tag = yaml_scalar(mapping, "tag") + if repository and tag and not is_template(f"{repository}{tag}"): + found.append( + image_component(f"{repository}:{tag}", file, key_line(mapping, "tag")) + ) + return found + + +def read_k8s_pins(root: Path) -> list[Component]: + """The chart and image components of the YAML files under `k8s/` in `root`.""" + found: list[Component] = [] + for path in matching_files(root, *K8S_GLOBS): + found.extend(_read_file(root, path)) + return found diff --git a/src/devops_cli/research/models.py b/src/devops_cli/research/models.py new file mode 100644 index 0000000000..ad1731cfdb --- /dev/null +++ b/src/devops_cli/research/models.py @@ -0,0 +1,75 @@ +"""The typed list of components that a repository pins (#3896).""" + +from __future__ import annotations + +from enum import StrEnum + +from pydantic import BaseModel, ConfigDict + + +class ComponentKind(StrEnum): + """The class of file or entry that holds a pin.""" + + PYTHON_PACKAGE = "python-package" + NODE_PACKAGE = "node-package" + TOOL = "tool" + CONTAINER_IMAGE = "container-image" + DEVCONTAINER_FEATURE = "devcontainer-feature" + ACTION = "action" + CHART = "chart" + TERRAFORM_PROVIDER = "terraform-provider" + + +class Ecosystem(StrEnum): + """The registry or release channel that publishes a pinned component. + + `unknown` is a component whose publisher the reader cannot name from the pin alone. It stays + in the list and in the count, so a later step can map it. + """ + + PYPI = "pypi" + NPM = "npm" + DOCKER = "docker" + GITHUB_ACTIONS = "github-actions" + GITHUB_RELEASE = "github-release" + HELM = "helm" + TERRAFORM = "terraform" + DEVCONTAINER_FEATURE = "devcontainer-feature" + UNKNOWN = "unknown" + + +class Component(BaseModel): + """One pin: a named component at a version, in one place of one file. + + `file` is the path from the repository root, with `/` separators. `line` counts from 1, and is + 0 when the file's parser gives no line and the text of the file does not show it. + """ + + model_config = ConfigDict(frozen=True) + + kind: ComponentKind + ecosystem: Ecosystem + name: str + version: str + file: str + line: int + + +class InventorySummary(BaseModel): + """How many components the inventory holds, in total and for each kind and ecosystem.""" + + model_config = ConfigDict(frozen=True) + + total: int + unknown: int + by_kind: dict[str, int] + by_ecosystem: dict[str, int] + + +class Inventory(BaseModel): + """Every pin of a repository, ordered by file, then line, then name.""" + + model_config = ConfigDict(frozen=True) + + components: list[Component] + summary: InventorySummary diff --git a/src/devops_cli/research/python_pins.py b/src/devops_cli/research/python_pins.py new file mode 100644 index 0000000000..b850f0ec1a --- /dev/null +++ b/src/devops_cli/research/python_pins.py @@ -0,0 +1,119 @@ +"""The Python pins: pyproject.toml, uv.lock and the hashed requirements of the tools lock (#3896). + +A direct dependency has the pin of pyproject.toml. A package that only uv.lock holds is a +transitive one, and has the version of the lock. The project itself, which uv.lock lists with an +editable or virtual source, is no pin. +""" + +from __future__ import annotations + +import tomllib +from pathlib import Path +from typing import Any + +from packaging.requirements import Requirement +from packaging.utils import canonicalize_name + +from devops_cli.research.files import LineIndex, matching_files, parse_errors, relative +from devops_cli.research.models import Component, ComponentKind, Ecosystem + +PYPROJECT = "pyproject.toml" +UV_LOCK = "uv.lock" +REQUIREMENTS_GLOB = "src/devops_cli/tools_lock/*.txt" + + +def _component(name: str, version: str, file: str, line: int) -> Component: + return Component( + kind=ComponentKind.PYTHON_PACKAGE, + ecosystem=Ecosystem.PYPI, + name=canonicalize_name(name), + version=version, + file=file, + line=line, + ) + + +def _pinned_version(requirement: Requirement) -> str: + """The version of an `==` pin, else the specifier as written (`>=1.2`), else empty.""" + for spec in requirement.specifier: + if spec.operator in ("==", "==="): + return spec.version + return str(requirement.specifier) + + +def _declared_requirements(data: dict[str, Any]) -> list[str]: + """Every requirement string of pyproject.toml: dependencies, extras and dependency groups.""" + project = data.get("project", {}) + declared: list[str] = list(project.get("dependencies", [])) + for extra in project.get("optional-dependencies", {}).values(): + declared.extend(extra) + for group in data.get("dependency-groups", {}).values(): + # An entry that is a table, `{include-group = "dev"}`, includes another group. + declared.extend(entry for entry in group if isinstance(entry, str)) + return declared + + +def _read_pyproject(root: Path) -> list[Component]: + path = root / PYPROJECT + if not path.is_file(): + return [] + with parse_errors(root, path): + text = path.read_text(encoding="utf-8") + lines = LineIndex(text) + return [ + _component( + requirement.name, + _pinned_version(requirement), + PYPROJECT, + lines.find(f'"{raw}"'), + ) + for raw in _declared_requirements(tomllib.loads(text)) + for requirement in [Requirement(raw)] + ] + + +def _read_uv_lock(root: Path, direct: set[str]) -> list[Component]: + path = root / UV_LOCK + if not path.is_file(): + return [] + with parse_errors(root, path): + text = path.read_text(encoding="utf-8") + lines = LineIndex(text) + found: list[Component] = [] + for package in tomllib.loads(text).get("package", []): + name = package["name"] + line = lines.find_line(f'name = "{name}"') + source = package.get("source", {}) + if "editable" in source or "virtual" in source or canonicalize_name(name) in direct: + continue + found.append(_component(name, package.get("version", ""), UV_LOCK, line)) + return found + + +def _read_requirements(root: Path, path: Path) -> list[Component]: + """The pins of a requirements file that `uv pip compile --generate-hashes` wrote.""" + with parse_errors(root, path): + found: list[Component] = [] + for number, raw in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1): + # A requirement starts at the left edge; its hashes and `# via` notes are indented. + if not raw or raw[0].isspace() or raw.startswith("#"): + continue + requirement = Requirement(raw.removesuffix("\\").strip()) + found.append( + _component( + requirement.name, _pinned_version(requirement), relative(root, path), number + ) + ) + return found + + +def read_python_pins(root: Path) -> list[Component]: + """The Python components of `root`.""" + direct = _read_pyproject(root) + found = [ + *direct, + *_read_uv_lock(root, {component.name for component in direct}), + ] + for path in matching_files(root, REQUIREMENTS_GLOB): + found.extend(_read_requirements(root, path)) + return found diff --git a/src/devops_cli/research/terraform_pins.py b/src/devops_cli/research/terraform_pins.py new file mode 100644 index 0000000000..6350e3c762 --- /dev/null +++ b/src/devops_cli/research/terraform_pins.py @@ -0,0 +1,72 @@ +"""The Terraform pins: each provider in a `required_providers` block under `tf/` (#3896). + +python-hcl2 parses the files. Its result has no line for an attribute, so the line is the one +that opens the provider's block. The version of a provider is its constraint, as written (`~> 5.0`). +""" + +from __future__ import annotations + +from collections.abc import Callable +from pathlib import Path + +from devops_cli.exceptions.research import InventoryError +from devops_cli.research.files import LineIndex, matching_files, relative +from devops_cli.research.models import Component, ComponentKind, Ecosystem + +TERRAFORM_GLOBS = ("tf/**/*.tf",) +_NOT_A_PROVIDER = "__is_block__" +_DEFAULT_NAMESPACE = "hashicorp" + + +def _opens_block(key: str) -> Callable[[str], bool]: + """A test for the line that opens the attribute `key = {`.""" + + def opens(line: str) -> bool: + return line.strip().startswith(key) and line.rstrip().endswith("{") + + return opens + + +def _read_file(root: Path, path: Path) -> list[Component]: + import hcl2 + + text = path.read_text(encoding="utf-8") + file = relative(root, path) + try: + document = hcl2.loads( + text, + serialization_options=hcl2.SerializationOptions( + strip_string_quotes=True, with_comments=False + ), + ) + # python-hcl2 raises the parse errors of lark, a library of its own that this project does not import. + except Exception as exc: + raise InventoryError( + f"Cannot read the pins of {file}: {exc}", details={"file": file} + ) from exc + lines = LineIndex(text) + found: list[Component] = [] + for block in document.get("terraform", []): + for providers in block.get("required_providers", []): + for local_name, provider in providers.items(): + if local_name == _NOT_A_PROVIDER or not isinstance(provider, dict): + continue + found.append( + Component( + kind=ComponentKind.TERRAFORM_PROVIDER, + ecosystem=Ecosystem.TERRAFORM, + name=provider.get("source", f"{_DEFAULT_NAMESPACE}/{local_name}"), + version=provider.get("version", ""), + file=file, + line=lines.find_where(local_name, _opens_block(local_name)), + ) + ) + return found + + +def read_terraform_pins(root: Path) -> list[Component]: + """The provider components of the `.tf` files under `tf/` in `root`.""" + found: list[Component] = [] + for path in matching_files(root, *TERRAFORM_GLOBS): + found.extend(_read_file(root, path)) + return found diff --git a/src/devops_cli/research/tool_pins.py b/src/devops_cli/research/tool_pins.py new file mode 100644 index 0000000000..41968f8018 --- /dev/null +++ b/src/devops_cli/research/tool_pins.py @@ -0,0 +1,85 @@ +"""The pins of the tools lock: each tool, and each package of the lock of a Node tool (#3896). + +The lock is read with the model of `devops_cli.tools_lock`, so a lock that the installer refuses is +refused here too. A binary tool has the ecosystem `github-release` when its `source` is a GitHub +repository, and `unknown` for any other source. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from urllib.parse import urlsplit + +from devops_cli.research.files import LineIndex, matching_files, parse_errors, relative +from devops_cli.research.models import Component, ComponentKind, Ecosystem +from devops_cli.tools_lock import LOCK_FILENAME, read_tools_lock + +LOCK_DIR = "src/devops_cli/tools_lock" +_NODE_MODULES = "node_modules/" + + +def _binary_ecosystem(source: str) -> Ecosystem: + return ( + Ecosystem.GITHUB_RELEASE if urlsplit(source).hostname == "github.com" else Ecosystem.UNKNOWN + ) + + +def _read_tools(root: Path, lock_dir: Path) -> list[Component]: + lock_path = lock_dir / LOCK_FILENAME + if not lock_path.is_file(): + return [] + with parse_errors(root, lock_path): + lock = read_tools_lock(lock_dir) + lines = LineIndex(lock_path.read_text(encoding="utf-8")) + file = relative(root, lock_path) + found: list[Component] = [] + groups = ( + ("binary", lock.binary, None), + ("python", lock.python, Ecosystem.PYPI), + ("npm", lock.npm, Ecosystem.NPM), + ) + for table, tools, ecosystem in groups: + for name, tool in tools.items(): + found.append( + Component( + kind=ComponentKind.TOOL, + ecosystem=ecosystem or _binary_ecosystem(tool.source), + name=name, + version=tool.version, + file=file, + line=lines.find_line(f"[{table}.{name}]"), + ) + ) + return found + + +def _read_node_packages(root: Path, path: Path) -> list[Component]: + """The packages of a `package-lock.json`, by the name that follows the last `node_modules/`.""" + with parse_errors(root, path): + text = path.read_text(encoding="utf-8") + lines = LineIndex(text) + file = relative(root, path) + found: list[Component] = [] + for key, package in json.loads(text).get("packages", {}).items(): + if _NODE_MODULES not in key or "version" not in package: + continue + found.append( + Component( + kind=ComponentKind.NODE_PACKAGE, + ecosystem=Ecosystem.NPM, + name=key.rsplit(_NODE_MODULES, 1)[1], + version=package["version"], + file=file, + line=lines.find(f'"{key}"'), + ) + ) + return found + + +def read_tool_pins(root: Path) -> list[Component]: + """The components of the tools lock of `root`.""" + found = _read_tools(root, root / LOCK_DIR) + for path in matching_files(root, f"{LOCK_DIR}/*/package-lock.json"): + found.extend(_read_node_packages(root, path)) + return found diff --git a/src/devops_cli/research/workflow_pins.py b/src/devops_cli/research/workflow_pins.py new file mode 100644 index 0000000000..4aea223d4a --- /dev/null +++ b/src/devops_cli/research/workflow_pins.py @@ -0,0 +1,76 @@ +"""The GitHub Actions pins: each `uses:` of the workflows and of the composite actions (#3896). + +A repository pins an action to a commit and writes the release after it, as in +`uses: actions/checkout@ # v7`. The version of the component is that release; an action with +no such comment has its ref. YAML parsers drop comments, so the comment comes from the line that +the parser gives for the key. A local action (`./...`) is no pin, and `docker://` is an +image. +""" + +from __future__ import annotations + +from pathlib import Path + +import yaml + +from devops_cli.core.serialization import YAML_SAFE_LOADER +from devops_cli.k8s.image_pins import key_line, yaml_mappings, yaml_scalar +from devops_cli.research.container_pins import image_component +from devops_cli.research.files import matching_files, parse_errors, relative +from devops_cli.research.models import Component, ComponentKind, Ecosystem + +WORKFLOW_GLOBS = ( + ".github/workflows/*.yml", + ".github/workflows/*.yaml", + ".github/actions/*/action.yml", + ".github/actions/*/action.yaml", +) +_DOCKER_PREFIX = "docker://" + + +def _comment_version(line_text: str) -> str: + """The first word of the comment at the end of `line_text`, or an empty string.""" + words = line_text.partition(" #")[2].split() + return words[0] if words else "" + + +def _component(uses: str, comment: str, file: str, line: int) -> Component | None: + if uses.startswith("./"): + return None + if uses.startswith(_DOCKER_PREFIX): + return image_component(uses.removeprefix(_DOCKER_PREFIX), file, line) + name, _, ref = uses.partition("@") + return Component( + kind=ComponentKind.ACTION, + ecosystem=Ecosystem.GITHUB_ACTIONS, + name=name, + version=comment or ref, + file=file, + line=line, + ) + + +def _read_file(root: Path, path: Path) -> list[Component]: + with parse_errors(root, path): + text = path.read_text(encoding="utf-8") + text_lines = text.splitlines() + file = relative(root, path) + found: list[Component] = [] + for document in yaml.compose_all(text, Loader=YAML_SAFE_LOADER): + for mapping in yaml_mappings(document) if document is not None else (): + uses = yaml_scalar(mapping, "uses") + if uses is None: + continue + line = key_line(mapping, "uses") + component = _component(uses, _comment_version(text_lines[line - 1]), file, line) + if component is not None: + found.append(component) + return found + + +def read_workflow_pins(root: Path) -> list[Component]: + """The action and image components of the workflows of `root`.""" + found: list[Component] = [] + for path in matching_files(root, *WORKFLOW_GLOBS): + found.extend(_read_file(root, path)) + return found diff --git a/tests/ai/mcp/__snapshots__/test_mcp_tool_listing/test_the_tool_listing_matches_the_snapshot.json b/tests/ai/mcp/__snapshots__/test_mcp_tool_listing/test_the_tool_listing_matches_the_snapshot.json index 9bb9a67064..52f5b1cc25 100644 --- a/tests/ai/mcp/__snapshots__/test_mcp_tool_listing/test_the_tool_listing_matches_the_snapshot.json +++ b/tests/ai/mcp/__snapshots__/test_mcp_tool_listing/test_the_tool_listing_matches_the_snapshot.json @@ -2702,7 +2702,7 @@ } }, "hydrate_tool_domain": { - "description": "Advertise the tools for one domain, which are withheld from the listing by default.\n\nCall this before browsing a domain's tools. Available lazy domains include `argo`,\n`benchmark`, `branches`, `ci`, `docker`, `docs`, `gh`, `grafana`, `k8s`, `pr`,\n`prometheus`, `rag`, `repos`, `roadmap`, `sandbox`, `scan`, `security`, `ssh`, `telemetry`,\n`tf`, `tls`, `valkey`, `vault` and `verify`.\nPass the domain name alone, for example `k8s`.", + "description": "Advertise the tools for one domain, which are withheld from the listing by default.\n\nCall this before browsing a domain's tools. Available lazy domains include `argo`,\n`benchmark`, `branches`, `ci`, `docker`, `docs`, `gh`, `grafana`, `k8s`, `pr`,\n`prometheus`, `rag`, `repos`, `research`, `roadmap`, `sandbox`, `scan`, `security`, `ssh`,\n`telemetry`, `tf`, `tls`, `valkey`, `vault` and `verify`.\nPass the domain name alone, for example `k8s`.", "input_schema": { "additionalProperties": false, "properties": { @@ -4136,6 +4136,14 @@ "type": "object" } }, + "research_inventory": { + "description": "List every pin of the project as a typed component: Python packages, tools, container images, GitHub Actions, Helm charts and Terraform providers. It reads files only.", + "input_schema": { + "additionalProperties": false, + "properties": {}, + "type": "object" + } + }, "review_branch": { "description": "Review a git branch diff.", "input_schema": { diff --git a/tests/commands/test_all_commands_help_dryrun.py b/tests/commands/test_all_commands_help_dryrun.py index c035acba9b..daeb93745c 100644 --- a/tests/commands/test_all_commands_help_dryrun.py +++ b/tests/commands/test_all_commands_help_dryrun.py @@ -145,6 +145,7 @@ def test_all_command_specs_registered(cli: Any) -> None: "lint", "status", "survey", + "research", } for cmd in expected_commands: assert cmd in result.output diff --git a/tests/commands/test_research_inventory.py b/tests/commands/test_research_inventory.py new file mode 100644 index 0000000000..a5f8a2ec2e --- /dev/null +++ b/tests/commands/test_research_inventory.py @@ -0,0 +1,35 @@ +"""Tests for `devops research inventory`.""" + +from __future__ import annotations + +import json +from collections.abc import Callable +from typing import Any + +from devops_cli.research.inventory import read_inventory +from tests.support.paths import FIXTURES + +FIXTURE_REPO = FIXTURES / "research" / "repo" + + +def test_inventory_json_is_the_inventory_of_the_root(cli: Callable[..., Any]) -> None: + result = cli("research", "inventory", "--root", FIXTURE_REPO, "--json") + + assert result.exit_code == 0 + assert json.loads(result.output) == json.loads(read_inventory(FIXTURE_REPO).model_dump_json()) + + +def test_inventory_table_lists_each_component_and_the_unknown_count( + cli: Callable[..., Any], +) -> None: + result = cli("research", "inventory", "--root", FIXTURE_REPO) + + assert result.exit_code == 0 + assert "astral-sh/setup-uv" in result.output + assert "27 components, 1 with an unknown ecosystem." in result.output + + +def test_inventory_refuses_an_unknown_format(cli: Callable[..., Any]) -> None: + result = cli("research", "inventory", "--root", FIXTURE_REPO, "--format", "xml") + + assert result.exit_code == 1 diff --git a/tests/fixtures/research/repo/.devcontainer/devcontainer-lock.json b/tests/fixtures/research/repo/.devcontainer/devcontainer-lock.json new file mode 100644 index 0000000000..b6f196a724 --- /dev/null +++ b/tests/fixtures/research/repo/.devcontainer/devcontainer-lock.json @@ -0,0 +1,9 @@ +{ + "features": { + "ghcr.io/devcontainers/features/common-utils:2": { + "version": "2.5.9", + "resolved": "ghcr.io/devcontainers/features/common-utils@sha256:cb0c4d3c276f157eed17935747e364178d75fee17f55c4e129966f64633deb3a", + "integrity": "sha256:cb0c4d3c276f157eed17935747e364178d75fee17f55c4e129966f64633deb3a" + } + } +} diff --git a/tests/fixtures/research/repo/.github/actions/setup/action.yml b/tests/fixtures/research/repo/.github/actions/setup/action.yml new file mode 100644 index 0000000000..6929ac2bd4 --- /dev/null +++ b/tests/fixtures/research/repo/.github/actions/setup/action.yml @@ -0,0 +1,5 @@ +name: setup +runs: + using: composite + steps: + - uses: actions/cache@dddddddddddddddddddddddddddddddddddddddd # v6.1.0 diff --git a/tests/fixtures/research/repo/.github/workflows/ci.yml b/tests/fixtures/research/repo/.github/workflows/ci.yml new file mode 100644 index 0000000000..d9ed385768 --- /dev/null +++ b/tests/fixtures/research/repo/.github/workflows/ci.yml @@ -0,0 +1,15 @@ +name: CI +on: [push] +jobs: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa # v7 + - uses: astral-sh/setup-uv@bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb # v10.2.0 + - uses: ./.github/actions/setup + test: + runs-on: ubuntu-latest + steps: + - uses: astral-sh/setup-uv@cccccccccccccccccccccccccccccccccccccccc # v10.0.1 + - uses: docker://ghcr.io/example-org/linter:3.4.5 + - uses: example-org/no-comment@v2 diff --git a/tests/fixtures/research/repo/Dockerfile b/tests/fixtures/research/repo/Dockerfile new file mode 100644 index 0000000000..82e3a1bb60 --- /dev/null +++ b/tests/fixtures/research/repo/Dockerfile @@ -0,0 +1,8 @@ +# syntax=docker/dockerfile:1 +FROM ghcr.io/astral-sh/uv:0.13.6@sha256:af22a52f5eafef3d78e551599d405c02df61919d18028f0cea8eda93bc9986d0 AS uv + +FROM python:3.14-slim-trixie AS builder +COPY --from=uv /uv /usr/local/bin/ +COPY --from=ghcr.io/example-org/tool:1.2.3 /tool /usr/local/bin/tool + +FROM builder AS runner diff --git a/tests/fixtures/research/repo/k8s/argocd/apps/qdrant.yaml b/tests/fixtures/research/repo/k8s/argocd/apps/qdrant.yaml new file mode 100644 index 0000000000..87cecd5c89 --- /dev/null +++ b/tests/fixtures/research/repo/k8s/argocd/apps/qdrant.yaml @@ -0,0 +1,12 @@ +apiVersion: argoproj.io/v1alpha1 +kind: Application +metadata: + name: qdrant +spec: + sources: + - repoURL: https://qdrant.github.io/qdrant-helm + chart: qdrant + targetRevision: 1.19.1 + - repoURL: https://git.example.com/example/repo + targetRevision: main + ref: values diff --git a/tests/fixtures/research/repo/k8s/llm/valkey.yaml b/tests/fixtures/research/repo/k8s/llm/valkey.yaml new file mode 100644 index 0000000000..5bbfeb5b5b --- /dev/null +++ b/tests/fixtures/research/repo/k8s/llm/valkey.yaml @@ -0,0 +1,12 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: valkey +spec: + template: + spec: + containers: + - name: valkey + image: valkey/valkey:9.1.2-alpine + - name: untagged + image: example/untagged diff --git a/tests/fixtures/research/repo/k8s/llm/values-web.yaml b/tests/fixtures/research/repo/k8s/llm/values-web.yaml new file mode 100644 index 0000000000..9c15ee8254 --- /dev/null +++ b/tests/fixtures/research/repo/k8s/llm/values-web.yaml @@ -0,0 +1,3 @@ +image: + repository: ghcr.io/example-org/web + tag: "v0.11.4" diff --git a/tests/fixtures/research/repo/pyproject.toml b/tests/fixtures/research/repo/pyproject.toml new file mode 100644 index 0000000000..42a2d820cc --- /dev/null +++ b/tests/fixtures/research/repo/pyproject.toml @@ -0,0 +1,12 @@ +[project] +name = "example" +version = "0.1.0" +dependencies = [ + "httpx2==2.13.1", + "PyYAML==6.0.3", +] + +[dependency-groups] +dev = [ + "pytest==9.1.1", +] diff --git a/tests/fixtures/research/repo/src/devops_cli/tools_lock/bandit.txt b/tests/fixtures/research/repo/src/devops_cli/tools_lock/bandit.txt new file mode 100644 index 0000000000..7f4a8a3646 --- /dev/null +++ b/tests/fixtures/research/repo/src/devops_cli/tools_lock/bandit.txt @@ -0,0 +1,8 @@ +# This file was autogenerated by uv via the following command: +# uv pip compile --universal --generate-hashes --python-version 3.14 bandit.in -o bandit.txt +bandit==1.9.4 \ + --hash=sha256:b589e5de2afe70bd4d53fa0c1da6199f4085af666fde00e8a034f152a52cd628 + # via -r bandit.in +colorama==0.4.6 ; sys_platform == 'win32' \ + --hash=sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44 + # via bandit diff --git a/tests/fixtures/research/repo/src/devops_cli/tools_lock/example-npm/package-lock.json b/tests/fixtures/research/repo/src/devops_cli/tools_lock/example-npm/package-lock.json new file mode 100644 index 0000000000..79ad076bb1 --- /dev/null +++ b/tests/fixtures/research/repo/src/devops_cli/tools_lock/example-npm/package-lock.json @@ -0,0 +1,18 @@ +{ + "name": "example-npm-tool", + "lockfileVersion": 3, + "packages": { + "": { + "name": "example-npm-tool", + "dependencies": { + "example-npm": "1.14.3" + } + }, + "node_modules/@example/helper": { + "version": "0.4.2" + }, + "node_modules/example-npm": { + "version": "1.14.3" + } + } +} diff --git a/tests/fixtures/research/repo/src/devops_cli/tools_lock/tools.lock b/tests/fixtures/research/repo/src/devops_cli/tools_lock/tools.lock new file mode 100644 index 0000000000..6d166484dd --- /dev/null +++ b/tests/fixtures/research/repo/src/devops_cli/tools_lock/tools.lock @@ -0,0 +1,36 @@ +python_version = "3.14" + +[binary.kubectl] +version = "1.37.1" +description = "Kubernetes CLI" +source = "https://github.com/kubernetes/kubernetes" +bin = "kubectl" +format = "binary" + +[binary.kubectl.platforms.linux-amd64] +url = "https://dl.k8s.io/release/v1.37.1/bin/linux/amd64/kubectl" +sha256 = "0000000000000000000000000000000000000000000000000000000000000000" + +[binary.homebrewed] +version = "2.0.0" +description = "A tool whose source is no GitHub repository" +source = "https://downloads.example.com/homebrewed" +bin = "homebrewed" +format = "binary" + +[binary.homebrewed.platforms.linux-amd64] +url = "https://downloads.example.com/homebrewed/2.0.0/homebrewed" +sha256 = "1111111111111111111111111111111111111111111111111111111111111111" + +[python.bandit] +version = "1.9.4" +description = "PyCQA Bandit Python security linter" +source = "https://github.com/PyCQA/bandit" +requirements = "bandit.txt" +entry_points = ["bandit"] + +[npm.example-npm] +version = "1.14.3" +description = "An example Node tool" +source = "https://github.com/example-org/example-npm" +bin = "example-npm" diff --git a/tests/fixtures/research/repo/tf/aws/versions.tf b/tests/fixtures/research/repo/tf/aws/versions.tf new file mode 100644 index 0000000000..3fc806d942 --- /dev/null +++ b/tests/fixtures/research/repo/tf/aws/versions.tf @@ -0,0 +1,10 @@ +terraform { + required_version = ">= 1.6.0" + + required_providers { + aws = { + source = "hashicorp/aws" + version = "~> 5.0" + } + } +} diff --git a/tests/fixtures/research/repo/uv.lock b/tests/fixtures/research/repo/uv.lock new file mode 100644 index 0000000000..a912f71662 --- /dev/null +++ b/tests/fixtures/research/repo/uv.lock @@ -0,0 +1,34 @@ +version = 1 +revision = 5 + +[[package]] +name = "certifi" +version = "2026.9.1" +source = { registry = "https://pypi.org/simple" } + +[[package]] +name = "example" +version = "0.1.0" +source = { editable = "." } +dependencies = [ + { name = "httpx2" }, + { name = "pyyaml" }, +] + +[[package]] +name = "httpx2" +version = "2.13.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, +] + +[[package]] +name = "pytest" +version = "9.1.1" +source = { registry = "https://pypi.org/simple" } + +[[package]] +name = "pyyaml" +version = "6.0.3" +source = { registry = "https://pypi.org/simple" } diff --git a/tests/research/__init__.py b/tests/research/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/research/test_inventory.py b/tests/research/test_inventory.py new file mode 100644 index 0000000000..3d9fec2bb5 --- /dev/null +++ b/tests/research/test_inventory.py @@ -0,0 +1,204 @@ +"""The inventory lists every pin of a repository as a typed component, and reaches nothing outside the files.""" + +from __future__ import annotations + +import socket +import subprocess +from pathlib import Path +from typing import Any + +import pytest + +from devops_cli.exceptions.research import InventoryError +from devops_cli.research.inventory import read_inventory +from devops_cli.research.models import Component, ComponentKind, Ecosystem +from tests.support.paths import FIXTURES + +FIXTURE_REPO = FIXTURES / "research" / "repo" + +_PIP = (ComponentKind.PYTHON_PACKAGE, Ecosystem.PYPI) +_NODE = (ComponentKind.NODE_PACKAGE, Ecosystem.NPM) +_TOOL = ComponentKind.TOOL +_IMAGE = (ComponentKind.CONTAINER_IMAGE, Ecosystem.DOCKER) +_ACTION = (ComponentKind.ACTION, Ecosystem.GITHUB_ACTIONS) + + +def _component( + kind_and_ecosystem: tuple[ComponentKind, Ecosystem], + name: str, + version: str, + file: str, + line: int, +) -> Component: + kind, ecosystem = kind_and_ecosystem + return Component( + kind=kind, ecosystem=ecosystem, name=name, version=version, file=file, line=line + ) + + +EXPECTED = [ + _component(_IMAGE, "ghcr.io/astral-sh/uv", "0.13.6", "Dockerfile", 2), + _component(_IMAGE, "python", "3.14-slim-trixie", "Dockerfile", 4), + _component(_IMAGE, "ghcr.io/example-org/tool", "1.2.3", "Dockerfile", 6), + _component( + (ComponentKind.DEVCONTAINER_FEATURE, Ecosystem.DEVCONTAINER_FEATURE), + "ghcr.io/devcontainers/features/common-utils", + "2.5.9", + ".devcontainer/devcontainer-lock.json", + 3, + ), + _component(_ACTION, "actions/checkout", "v7", ".github/workflows/ci.yml", 7), + _component(_ACTION, "astral-sh/setup-uv", "v10.2.0", ".github/workflows/ci.yml", 8), + _component(_ACTION, "astral-sh/setup-uv", "v10.0.1", ".github/workflows/ci.yml", 13), + _component(_IMAGE, "ghcr.io/example-org/linter", "3.4.5", ".github/workflows/ci.yml", 14), + _component(_ACTION, "example-org/no-comment", "v2", ".github/workflows/ci.yml", 15), + _component(_ACTION, "actions/cache", "v6.1.0", ".github/actions/setup/action.yml", 5), + _component( + (ComponentKind.CHART, Ecosystem.HELM), "qdrant", "1.19.1", "k8s/argocd/apps/qdrant.yaml", 9 + ), + _component(_IMAGE, "valkey/valkey", "9.1.2-alpine", "k8s/llm/valkey.yaml", 10), + _component(_IMAGE, "example/untagged", "latest", "k8s/llm/valkey.yaml", 12), + _component(_IMAGE, "ghcr.io/example-org/web", "v0.11.4", "k8s/llm/values-web.yaml", 3), + _component(_PIP, "httpx2", "2.13.1", "pyproject.toml", 5), + _component(_PIP, "pyyaml", "6.0.3", "pyproject.toml", 6), + _component(_PIP, "pytest", "9.1.1", "pyproject.toml", 11), + _component( + _NODE, + "@example/helper", + "0.4.2", + "src/devops_cli/tools_lock/example-npm/package-lock.json", + 11, + ), + _component( + _NODE, + "example-npm", + "1.14.3", + "src/devops_cli/tools_lock/example-npm/package-lock.json", + 14, + ), + _component(_PIP, "bandit", "1.9.4", "src/devops_cli/tools_lock/bandit.txt", 3), + _component(_PIP, "colorama", "0.4.6", "src/devops_cli/tools_lock/bandit.txt", 6), + Component( + kind=_TOOL, + ecosystem=Ecosystem.GITHUB_RELEASE, + name="kubectl", + version="1.37.1", + file="src/devops_cli/tools_lock/tools.lock", + line=3, + ), + Component( + kind=_TOOL, + ecosystem=Ecosystem.UNKNOWN, + name="homebrewed", + version="2.0.0", + file="src/devops_cli/tools_lock/tools.lock", + line=14, + ), + Component( + kind=_TOOL, + ecosystem=Ecosystem.PYPI, + name="bandit", + version="1.9.4", + file="src/devops_cli/tools_lock/tools.lock", + line=25, + ), + Component( + kind=_TOOL, + ecosystem=Ecosystem.NPM, + name="example-npm", + version="1.14.3", + file="src/devops_cli/tools_lock/tools.lock", + line=32, + ), + _component( + (ComponentKind.TERRAFORM_PROVIDER, Ecosystem.TERRAFORM), + "hashicorp/aws", + "~> 5.0", + "tf/aws/versions.tf", + 5, + ), + _component(_PIP, "certifi", "2026.9.1", "uv.lock", 5), +] + + +def test_inventory_lists_one_component_for_each_pin_of_the_fixture_repository() -> None: + inventory = read_inventory(FIXTURE_REPO) + + assert sorted(inventory.components, key=_sort_key) == sorted(EXPECTED, key=_sort_key) + + +def _sort_key(component: Component) -> tuple[str, int, str]: + return (component.file, component.line, component.name) + + +def test_inventory_order_is_stable() -> None: + first = read_inventory(FIXTURE_REPO) + second = read_inventory(FIXTURE_REPO) + + assert first.model_dump_json() == second.model_dump_json() + assert first.components == sorted(first.components, key=_sort_key) + + +def test_the_same_action_at_two_versions_is_two_components() -> None: + setup_uv = [ + component.version + for component in read_inventory(FIXTURE_REPO).components + if component.name == "astral-sh/setup-uv" + ] + + assert setup_uv == ["v10.2.0", "v10.0.1"] + + +def test_a_pin_with_no_ecosystem_is_listed_and_counted() -> None: + inventory = read_inventory(FIXTURE_REPO) + + unknown = [c.name for c in inventory.components if c.ecosystem == Ecosystem.UNKNOWN] + + assert unknown == ["homebrewed"] + assert inventory.summary.unknown == 1 + assert inventory.summary.total == len(EXPECTED) + + +def test_summary_counts_each_kind_and_ecosystem() -> None: + summary = read_inventory(FIXTURE_REPO).summary + + assert summary.by_kind == { + "action": 5, + "chart": 1, + "container-image": 7, + "devcontainer-feature": 1, + "node-package": 2, + "python-package": 6, + "terraform-provider": 1, + "tool": 4, + } + assert sum(summary.by_ecosystem.values()) == summary.total + + +def test_the_reader_starts_no_program_and_opens_no_connection( + monkeypatch: pytest.MonkeyPatch, +) -> None: + def refuse(*_args: Any, **_kwargs: Any) -> None: + raise AssertionError("the inventory reached beyond its files") + + monkeypatch.setattr(subprocess, "Popen", refuse) + monkeypatch.setattr(socket.socket, "connect", refuse) + monkeypatch.setattr(socket, "getaddrinfo", refuse) + + assert len(read_inventory(FIXTURE_REPO).components) == len(EXPECTED) + + +def test_a_file_that_does_not_parse_is_an_error_that_names_the_file(tmp_path: Path) -> None: + (tmp_path / "pyproject.toml").write_text("dependencies = [", encoding="utf-8") + + with pytest.raises(InventoryError, match=r"pyproject\.toml") as raised: + read_inventory(tmp_path) + + assert raised.value.error_code == "RESEARCH_INVENTORY_ERROR" + assert raised.value.exit_code == 1 + + +def test_a_repository_with_none_of_the_files_has_no_components(tmp_path: Path) -> None: + inventory = read_inventory(tmp_path) + + assert (inventory.components, inventory.summary.total) == ([], 0) diff --git a/tests/research/test_inventory_repository.py b/tests/research/test_inventory_repository.py new file mode 100644 index 0000000000..31a0cbc875 --- /dev/null +++ b/tests/research/test_inventory_repository.py @@ -0,0 +1,22 @@ +"""The inventory finds pins of every kind in the real repository.""" + +from __future__ import annotations + +import pytest + +from devops_cli.research.inventory import read_inventory +from devops_cli.research.models import ComponentKind +from tests.support.paths import REPO_ROOT + + +@pytest.mark.parametrize("kind", list(ComponentKind)) +def test_the_repository_has_at_least_one_pin_of_each_kind(kind: ComponentKind) -> None: + summary = read_inventory(REPO_ROOT).summary + + assert summary.by_kind.get(kind.value, 0) > 0 + + +def test_every_pin_of_the_repository_has_a_line_and_a_version_or_a_constraint() -> None: + components = read_inventory(REPO_ROOT).components + + assert [c for c in components if c.line == 0 or not c.version] == []