Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(inventory): package usage, component inventory, CycloneDX export and advisory-source seam (#3806)

Raghav Chamadiyafd4f1f12597a
diff --git a/docs/README.md b/docs/README.md
index 5a1cd2fdb..7af52e243 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -138,6 +138,7 @@ For a map of every layer and how they feed each other, read
| [reference/MCP_RESPONSE_FIELDS.md](reference/MCP_RESPONSE_FIELDS.md) | The field dictionary for every MCP response, including the `_meta` envelope |
| [reference/HOOKS_REFERENCE.md](reference/HOOKS_REFERENCE.md) | The exact settings entries each hook install writes |
| [reference/CHANGE_REVIEW_API.md](reference/CHANGE_REVIEW_API.md) | Reviewing a change from Python, with or without a checkout |
+| [reference/PACKAGE_USAGE.md](reference/PACKAGE_USAGE.md) | Where third-party packages are imported, the CycloneDX export, and reading Syft, SPDX or OSV files |
| [reference/WORKSPACE_CONTRACTS.md](reference/WORKSPACE_CONTRACTS.md) | How a workspace names, reads and matches cross-repo contracts |
| [reference/COMPUTED_GLOSSARY.md](reference/COMPUTED_GLOSSARY.md) | Definitions for every computed metric |
| [reference/TELEMETRY.md](reference/TELEMETRY.md) | What anonymous telemetry collects, and how to turn it off |
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index 06aa46b6d..4b35af377 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -161,7 +161,7 @@ A triage card for files, modules or symbols: summary, symbols with signatures an
| Parameter | Type | Default | Meaning |
|-----------|------|---------|---------|
-| `targets` | list[string] | required | File paths, module paths, `"path::Symbol"` ids, `"component:<name>"`, or `"change:<id>"` |
+| `targets` | list[string] | required | File paths, module paths, `"path::Symbol"` ids, `"component:<name>"`, `"change:<id>"`, or `"package:<name>"` |
| `include` | list[string] | none | Any of `full_doc`, `ownership`, `last_change`, `callers`, `callees`, `references`, `metrics`, `community`, `decisions`, `skeleton`, `health`, `doc_drift`, `symbols`, `changes`, `provenance` |
| `compact` | bool | `true` | `false` adds the structure block, imports and docstrings |
| `repo` | string | default repo | Workspace repo alias. `"all"` is not supported (returns an error) |
@@ -172,6 +172,8 @@ A `component:<name>` target returns the component's declared context (owner, sys
A `change:<id>` target (`change:pr-123`, or a commit sha the change landed) returns the [Change Record](../reference/CLI_REFERENCE.md#repowise-changes): title, forge ref, `merged_at`, category, files and provenance with its coverage. On a file target, `changes` lists the newest Change Records that touched it, and `provenance` gives the file's commits by source (agent, human-attested, unknown) with coverage; the agent share is withheld below 30% coverage. With attribution off, `provenance` reads `{"unavailable": "attribution_off"}` and change rows carry none.
+A `package:<name>` target (`package:requests`, or `package:npm:lodash`) returns where that third-party package is imported: its manifest declarations, a summary, the components and declared owner teams, and up to 25 import sites with line, `mapping` (`declared` or `inferred`) and `reachability` (`reachable`, `unreachable`, `test` or `unknown`, with a basis). See [PACKAGE_USAGE.md](../reference/PACKAGE_USAGE.md).
+
A file's compact symbol list holds its top 15 symbols: types (classes, interfaces, structs, traits, enums, type aliases, impls, modules) first, then functions and methods, then the rest, each group by centrality. `symbols_truncated` gives the total, and `include=["symbols"]` lists them all. When the response budget trims the list further, it keeps symbols by kind and name match, not centrality. A row without `symbol_id` is `path::name`; methods and overload variants carry theirs, so pass a row's id to `get_symbol` when it has one.
`full_doc` returns the page as `content_md`, plus `digest_md` on pages that carry an agent digest: the questions the page answers, its concept index, public API and git signals. Both are dropped first when the response is over budget. `skeleton` renders a file with bodies elided: every signature, the imports, and the bodies of its most central symbols, with line ranges on every elision. `doc_drift` lists the documents that name the file and whether they carry drift. An empty `callers` or `callees` list comes with a `*_basis` saying how much of that language's calls the graph resolved; read it before concluding nothing calls a symbol.
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index dd9a6b009..02400a6f8 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -1596,6 +1596,18 @@ repowise components ownership [--path PATH] [--format table|json]
---
+### `repowise packages`
+
+`where` lists the files that import a third-party package (a name or `ecosystem:name`) with the import line, component, declared owner teams and reachability, each with its basis. `export --format cyclonedx` writes the declared packages and their import sites as CycloneDX 1.6 JSON (`evidence.occurrences`); it is not an SBOM. `import` joins a Syft, SPDX, CycloneDX or OSV JSON file you supply to usage by package name; nothing is fetched and no vulnerability is matched. See [PACKAGE_USAGE.md](PACKAGE_USAGE.md).
+
+```bash
+repowise packages where NAME [--path PATH] [--format text|json]
+repowise packages export [--format cyclonedx] [-o FILE] [--path PATH]
+repowise packages import FILE [--path PATH] [--format text|json]
+```
+
+---
+
### `repowise changes`
Merged changes read back from git at each index and update: one per first-parent commit, identified by the PR or MR number its message names, then a Gerrit `Change-Id`, then the merge or commit sha. A merge lands the commits its branch brought in, and rebase merges read as one change per commit. `show` takes an id (`pr-123`) or any commit sha the change landed, and prints the versioned JSON record or, with `--format in-toto`, an in-toto Statement v1 whose subjects are the commits.
@@ -1645,6 +1657,7 @@ repowise report assessment [PATH] [--sections a,b] [--format json|markdown|html]
| Section | Measures | Basis |
|---|---|---|
| `components` | Each component's NLOC-weighted health, catalog facts and `components ownership` findings | `measured`; `gated` on a language health is held back on |
+| `inventory` | Each component's declared owner teams, languages, entry points and the third-party packages its files import ([package usage](PACKAGE_USAGE.md)) | `measured`; owners `declared` |
| `hotspots` | Files with high recent churn, per component | `measured` |
| `bus-factor` | Fewest primary owners holding over half of each component's owned files; components at 1 or 2 are counted and named in the summary unless the catalog marks them | `measured`; `inferred` under five owned files |
| `dead-code` | Open findings by confidence tier; `safe_to_delete` is not used | `inferred`; `gated` for held-back languages |
@@ -1654,6 +1667,8 @@ repowise report assessment [PATH] [--sections a,b] [--format json|markdown|html]
| `provenance` | Commits in the last 90 indexed days with a known source (a count, not a score), and the agents and models named (listed, not counted) | `measured`, `declared`; `unresolved` with no markers |
| `trend` | What moved since a same-stamp snapshot at least 90 days older, by the `events` diff rules and only for the event kinds the repository has on | `measured` |
+`repowise report inventory [PATH]` renders the `inventory` section alone, with the same `--format`, `--out`, `--workspace`, `--no-workspace` and `--repo` options: the component inventory a software inventory review (PCI DSS 6.3.2) asks for. Its JSON `data` keeps every component's owner teams, languages, entry points and packages; the text lists the components with no declared owner team.
+
Basis `unresolved` means the evidence is missing. Each per-component section opens with one summary row counting components by outcome; a component gets its own item only when there is something to note (an ownership finding, a bus factor of 2 or less on a component the catalog gives a criticality or tags, hotspots, a stale decision, provided contracts, or unresolved or gated evidence), the rest are named in the summary, and the JSON `data` keeps every component's figures. Local paths are removed from every item. A section is a `Section` on `SeamRegistry("report-section")`: each module in `repowise/core/report/sections/` registers one, a plugin registers its own the same way, and a section whose data is absent returns `None` and is left out (an outcomes section is added this way once change outcomes exist). Renderers live on `SeamRegistry("report-renderer")` and are picked with `--format`. Modernization candidates are not reported, since no existing signal measures them.
---
diff --git a/docs/reference/PACKAGE_USAGE.md b/docs/reference/PACKAGE_USAGE.md
new file mode 100644
index 000000000..960c92daf
--- /dev/null
+++ b/docs/reference/PACKAGE_USAGE.md
@@ -0,0 +1,19 @@
+# Package usage
+
+`repowise packages where <name>` lists the files that import a third-party package, with the import line, the component each file belongs to, its declared owner teams, and whether it is reachable. Packages come from the manifests the index already parses (`package.json`, `pyproject.toml`, `requirements*.txt`, `Cargo.toml`, `go.mod`, `.csproj`, `pom.xml`); import sites come from the import graph. The same answer is served by `get_context(targets=["package:<name>"])` and `GET /api/repos/{id}/external-systems/{package}/usage`.
+
+## What each field rests on
+
+| Field | Basis |
+|---|---|
+| `mapping: declared` | Indexing linked the import to the package's manifest declaration: the module is the declared name or starts with it (`requests.adapters`, `lodash/merge`). Each entry in `modules` carries its own mapping, and a file's symbols and line come from its declared modules when it has any. |
+| `mapping: inferred` | No declaration is linked; the module merely starts with the name asked for. A Python distribution imported under another name (`PyYAML` as `yaml`) is found only by asking for the import name. |
+| `line` | The first import statement in the file that names the module: a line that starts with an import keyword (comments never count), or a line inside a Go `import ( ... )` block. Absent when none matches. |
+| `owners` | Declared teams only: the catalog `spec.owner` and CODEOWNERS teams. Individual owners, and bare `@name` handles that may be a person or a GitLab group (`unresolved`), are counted in `owner_counts` and never named. |
+| `reachability` | `reachable`: an entry point loads the file through stored import edges or the dynamic loads indexing resolves (`importlib.import_module`, `"module:attr"` string tables such as lazily loaded CLI commands). `unreachable`: an open `unreachable_file` finding that the dead-code surface serves. `test`: a test file. `unknown`: neither, since a framework, script or reflection may still load it. |
+
+## Export and import
+
+`repowise packages export --format cyclonedx` writes a CycloneDX 1.6 JSON document: one `library` component per declared package (spellings that name the same package, such as `PyYAML` and `pyyaml`, merge into one), with `evidence.occurrences` (`location`, `line`, `symbol`, `additionalContext`) for each declared import site. It records where packages are used. It is not an SBOM: there are no hashes or licenses, no transitive dependencies, and no resolved versions; the manifest's version specifier is kept as the `repowise:declared_version` property.
+
+`repowise packages import <file>` reads a Syft JSON, SPDX 2.x JSON, CycloneDX JSON or OSV JSON file you supply (a record, a list of records, or OSV-Scanner output) and joins its packages to usage by name, and by ecosystem when the file gives one. Repowise never fetches advisory feeds and never matches vulnerabilities itself: an OSV file's own affected-package list is joined by name and its version ranges are not evaluated. The reader is the local default of the `advisory-source` seam (`REPOWISE_SEAM_ADVISORY_SOURCE`); a plugin can register another source, which receives the repository's declared packages.
diff --git a/packages/cli/src/repowise/cli/commands/packages_cmd.py b/packages/cli/src/repowise/cli/commands/packages_cmd.py
new file mode 100644
index 000000000..ace5141b2
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/packages_cmd.py
@@ -0,0 +1,180 @@
+"""``repowise packages`` - where third-party packages are used, from the index.
+
+``where`` lists the files importing a package with their component, declared
+owner teams and reachability. ``export --format cyclonedx`` writes that as a
+CycloneDX 1.6 document (``evidence.occurrences``); it records usage and is not
+an SBOM. ``import`` reads a Syft, SPDX, CycloneDX or OSV JSON file the user
+supplies and joins its packages to usage by name. Nothing is fetched.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+import click
+
+from repowise.cli.helpers import console, repo_index_session, resolve_command_target, run_async
+from repowise.cli.output import emit_json, format_option
+
+_NO_INDEX = "No index found for this repository; run `repowise init` first."
+
+
+def _repo_root(path: str | None) -> Path:
+ target = resolve_command_target(path=path, no_workspace_flag=True)
+ assert target.repo_path is not None
+ return Path(target.repo_path).resolve()
+
+
+async def _with_index(root: Path, fn: Any) -> Any:
+ async with repo_index_session(root) as opened:
+ if opened is None:
+ raise click.ClickException(_NO_INDEX)
+ session, repo_id = opened
+ return await fn(session, repo_id)
+
+
[email protected]("packages")
+def packages_group() -> None:
+ """Where third-party packages are used (import sites, components, owners)."""
+
+
+def _owners(site: dict[str, Any]) -> str:
+ """Declared teams by name; individual and unresolved owners only by count."""
+ counts = site.get("owner_counts", {})
+ parts = [
+ *site["owners"],
+ *(f"{n} {'individual(s)' if kind == 'individual' else kind}" for kind, n in counts.items()),
+ ]
+ return ", ".join(parts)
+
+
+def _reach(site: dict[str, Any]) -> str:
+ r = site["reachability"]
+ return r["state"] if r["state"] != "unknown" else f"unknown ({r['basis']})"
+
+
+@packages_group.command("where")
[email protected]("--path", "repo", default=None, help="Repo path (defaults to cwd).")
+@format_option(choices=("text", "json"), default="text")
+def packages_where(name: str, repo: str | None, fmt: str) -> None:
+ """Files that import NAME (a package name or ecosystem:name)."""
+ from repowise.core.inventory.usage import package_usage
+
+ root = _repo_root(repo)
+ doc = run_async(_with_index(root, lambda s, rid: package_usage(s, rid, root, name)))
+ if fmt == "json":
+ emit_json(doc)
+ return
+ from rich.markup import escape
+ from rich.table import Table
+
+ for decl in doc["declared"]:
+ version = f" {decl['version']}" if decl["version"] else ""
+ dev = " (dev)" if decl["dev"] else ""
+ console.print(
+ f"Declared {escape(decl['package_key'])}{escape(version)} "
+ f"in {escape(decl['declared_in'])}{dev}"
+ )
+ if doc.get("note"):
+ console.print(f"[dim]{escape(doc['note'])}[/dim]")
+ if not doc["sites"]:
+ return
+ # The path is the answer, so it folds onto a second line rather than being
+ # cut; the other columns give way first.
+ inferred = any(s["mapping"] == "inferred" for s in doc["sites"])
+ table = Table()
+ table.add_column("File", overflow="fold", ratio=3)
+ table.add_column("Imports", overflow="ellipsis", no_wrap=True, max_width=24)
+ table.add_column("Component", overflow="fold", max_width=20)
+ table.add_column("Owners", overflow="fold", max_width=24)
+ table.add_column("Reachability", overflow="fold", max_width=24)
+ if inferred:
+ table.add_column("Mapping")
+ for s in doc["sites"]:
+ where = f"{s['path']}:{s['line']}" if "line" in s else s["path"]
+ row = [
+ escape(where),
+ escape(", ".join(s["symbols"] or [m["name"] for m in s["modules"]])),
+ escape(s.get("component", "")),
+ escape(_owners(s)),
+ _reach(s),
+ ]
+ table.add_row(*row, *([s["mapping"]] if inferred else []))
+ console.print(table)
+ summary = doc["summary"]
+ reach = ", ".join(f"{n} {k}" for k, n in summary["reachability"].items() if n)
+ console.print(
+ f"{summary['files']} file(s) in {summary['components']} component(s): {reach}."
+ )
+
+
+@packages_group.command("export")
+@format_option(choices=("cyclonedx",), default="cyclonedx", help="CycloneDX 1.6 JSON.")
+ "--output",
+ "-o",
+ type=click.Path(dir_okay=False),
+ default=None,
+ help="Write to a file instead of stdout.",
+)
[email protected]("--path", "repo", default=None, help="Repo path (defaults to cwd).")
+def packages_export(fmt: str, output: str | None, repo: str | None) -> None:
+ """Declared packages and where they are imported, as CycloneDX 1.6 JSON (not an SBOM)."""
+ import json
+
+ from repowise.core.inventory.cyclonedx import cyclonedx_bom
+
+ root = _repo_root(repo)
+ bom = run_async(_with_index(root, lambda s, rid: cyclonedx_bom(s, rid, root, root.name)))
+ text = json.dumps(bom, indent=2)
+ if output:
+ Path(output).write_text(text + "\n", encoding="utf-8")
+ console.print(f"Wrote {len(bom['components'])} component(s) to {output}.")
+ else:
+ click.echo(text)
+
+
+@packages_group.command("import")
[email protected]("file", type=click.Path(exists=True, dir_okay=False))
[email protected]("--path", "repo", default=None, help="Repo path (defaults to cwd).")
+@format_option(choices=("text", "json"), default="text")
+def packages_import(file: str, repo: str | None, fmt: str) -> None:
+ """Join a Syft, SPDX, CycloneDX or OSV JSON FILE to where its packages are used."""
+ from repowise.core.inventory.advisories import join_usage
+
+ root = _repo_root(repo)
+ try:
+ result = run_async(_with_index(root, lambda s, rid: join_usage(s, rid, root, file)))
+ except ValueError as exc:
+ raise click.ClickException(str(exc)) from exc
+ if fmt == "json":
+ emit_json(result)
+ return
+ from rich.markup import escape
+ from rich.table import Table
+
+ console.print(
+ f"Read {result['mentions']} package(s) from a {result['format']} file; "
+ f"{len(result['matched'])} declared or imported here, {result['not_found']} not found."
+ )
+ if result["matched"]:
+ table = Table("Package", "Advisories", "Files", "Reachable", "Unknown", "Components")
+ for row in result["matched"]:
+ reach = row["summary"]["reachability"]
+ table.add_row(
+ escape(f"{row['ecosystem'] or '?'}:{row['name']}"),
+ escape(", ".join(a["id"] for a in row.get("advisories", []))),
+ str(row["summary"]["files"]),
+ str(reach["reachable"]),
+ str(reach["unknown"]),
+ escape(", ".join(row["components"])),
+ )
+ console.print(table)
+ for row in result["not_found_with_advisories"]:
+ ids = ", ".join(a["id"] for a in row["advisories"])
+ console.print(
+ f"[dim]{escape(row['name'])} ({escape(ids)}): not declared or imported here.[/dim]"
+ )
+ console.print(f"[dim]{escape(result['method'])}.[/dim]")
diff --git a/packages/cli/src/repowise/cli/commands/report_cmd.py b/packages/cli/src/repowise/cli/commands/report_cmd.py
index 0e72a8d63..bb28e6adc 100644
--- a/packages/cli/src/repowise/cli/commands/report_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/report_cmd.py
@@ -13,12 +13,13 @@ from repowise.core.registry import LazyCommand
#: ``"module:attr"`` of each ``repowise report`` subcommand.
_SUBCOMMANDS: tuple[str, ...] = (
"repowise.cli.commands.report_assessment_cmd:assessment_command",
+ "repowise.cli.commands.report_inventory_cmd:inventory_command",
)
@click.group("report")
def report_group() -> None:
- """Evidence reports built from the index: assessment."""
+ """Evidence reports built from the index: assessment, inventory."""
for _target in _SUBCOMMANDS:
diff --git a/packages/cli/src/repowise/cli/commands/report_inventory_cmd.py b/packages/cli/src/repowise/cli/commands/report_inventory_cmd.py
new file mode 100644
index 000000000..90043858a
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/report_inventory_cmd.py
@@ -0,0 +1,67 @@
+"""``repowise report inventory`` - the software inventory for a repo or workspace.
+
+The ``inventory`` report section alone, built and rendered the way
+``report assessment`` builds its document (JSON, Markdown or HTML).
+"""
+
+from __future__ import annotations
+
+import click
+
+from repowise.cli.helpers import (
+ err_console,
+ resolve_command_target,
+ run_async,
+ silence_logs_for_machine_output_until_close,
+)
+
+
[email protected]("inventory")
[email protected]("path", required=False, type=click.Path(exists=True, file_okay=False))
+ "--format",
+ "fmt",
+ default="markdown",
+ show_default=True,
+ help="Renderer: json, markdown or html (or one a plugin registers).",
+)
[email protected]("--out", "out_path", type=click.Path(dir_okay=False), help="Write to this file.")
[email protected]("--workspace", "workspace_flag", is_flag=True, help="Cover every workspace repo.")
[email protected]("--no-workspace", is_flag=True, help="Force single-repo mode.")
[email protected]("--repo", "repo_alias", default=None, help="Workspace repo alias to cover.")
+def inventory_command(
+ path: str | None,
+ fmt: str,
+ out_path: str | None,
+ workspace_flag: bool,
+ no_workspace: bool,
+ repo_alias: str | None,
+) -> None:
+ """Software inventory: components, owner teams, languages, entry points, packages."""
+ from repowise.cli.commands.report_assessment_cmd import (
+ _build,
+ _emit,
+ _pick_sections,
+ _scope,
+ )
+ from repowise.core.report.render import report_renderers
+
+ if not out_path:
+ silence_logs_for_machine_output_until_close() # stdout carries only the report
+ if fmt not in report_renderers.names:
+ raise click.BadParameter(
+ f"unknown format {fmt!r}; available: {', '.join(report_renderers.names)}",
+ param_hint="--format",
+ )
+ sections = _pick_sections("inventory")
+ target = resolve_command_target(
+ path=path,
+ workspace_flag=workspace_flag,
+ no_workspace_flag=no_workspace,
+ repo_alias=repo_alias,
+ )
+ target.notice(err_console, command="report inventory")
+ repos, scope = _scope(target)
+ document = run_async(_build(repos, sections, scope))
+ document["kind"] = "inventory"
+ _emit(report_renderers.get(fmt)(document), fmt, out_path, document)
diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.py
index aba555d1a..26268d4ed 100644
--- a/packages/cli/src/repowise/cli/main.py
+++ b/packages/cli/src/repowise/cli/main.py
@@ -72,6 +72,7 @@ _OSS_COMMANDS: tuple[tuple[str, str], ...] = (
("decision", "decision_cmd:decision_group"),
("coverage", "coverage_cmd:coverage_group"),
("components", "components_cmd:components_group"),
+ ("packages", "packages_cmd:packages_group"),
("changes", "changes_cmd:changes_group"),
("check", "check_cmd:check_command"),
("events", "events_cmd:events_command"),
diff --git a/packages/core/src/repowise/core/inventory/__init__.py b/packages/core/src/repowise/core/inventory/__init__.py
new file mode 100644
index 000000000..6536b173c
--- /dev/null
+++ b/packages/core/src/repowise/core/inventory/__init__.py
@@ -0,0 +1,8 @@
+"""Inventory: where third-party packages are used, and what each component is made of.
+
+:mod:`.usage` answers "where is package X used" from the import graph;
+:mod:`.cyclonedx` exports that as CycloneDX 1.6 ``evidence.occurrences``;
+:mod:`.advisories` reads a user-supplied Syft, SPDX, CycloneDX or OSV file
+(the ``advisory-source`` seam) and joins it to usage by name;
+:mod:`.components` builds the component inventory document.
+"""
diff --git a/packages/core/src/repowise/core/inventory/advisories.py b/packages/core/src/repowise/core/inventory/advisories.py
new file mode 100644
index 000000000..a6220a749
--- /dev/null
+++ b/packages/core/src/repowise/core/inventory/advisories.py
@@ -0,0 +1,337 @@
+"""Package lists and advisories from a file the user supplies: the ``advisory-source`` seam.
+
+The local default, ``file``, reads one JSON document and returns the packages it
+names. Four shapes are recognised:
+
+* Syft JSON (``artifacts[]``: name, version, purl);
+* SPDX 2.x JSON (``packages[]``: name, versionInfo, a purl external ref);
+* CycloneDX JSON (``components[]``: name, version, purl);
+* OSV JSON: one record, a list of records, ``{"vulns": [...]}``, or OSV-Scanner
+ output (``results[].packages[]``). Each record's ``affected[].package`` is a
+ package, carrying the record's id and aliases.
+
+Nothing here fetches a feed or decides whether a version is affected. An OSV
+file's affected list is the user's own data, joined to usage by package name
+only; its version ranges are not evaluated. A plugin registers another source
+(a hosted advisory feed) under ``SeamRegistry("advisory-source")``, selected
+with ``REPOWISE_SEAM_ADVISORY_SOURCE``; it receives the repository's declared
+packages so it can look them up.
+"""
+
+from __future__ import annotations
+
+import json
+from collections import deque
+from collections.abc import Sequence
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Protocol
+from urllib.parse import unquote
+
+from repowise.core.registry.plugins import SeamRegistry
+
+#: Larger inputs are refused rather than parsed into memory.
+MAX_FILE_BYTES = 200_000_000
+
+#: OSV ecosystem names and purl types to the manifest ecosystems the index uses.
+_ECOSYSTEMS = {
+ "pypi": "pypi",
+ "npm": "npm",
+ "crates.io": "cargo",
+ "cargo": "cargo",
+ "go": "go",
+ "golang": "go",
+ "nuget": "nuget",
+ "maven": "maven",
+ "packagist": "composer",
+ "composer": "composer",
+}
+
+
+@dataclass(frozen=True)
+class Advisory:
+ id: str
+ aliases: tuple[str, ...] = ()
+ summary: str | None = None
+
+
+@dataclass(frozen=True)
+class PackageMention:
+ """One package a supplied document names, as the document names it."""
+
+ name: str
+ ecosystem: str | None = None
+ version: str | None = None
+ advisories: tuple[Advisory, ...] = ()
+
+
+@dataclass(frozen=True)
+class SourceDocument:
+ format: str # "syft" | "spdx" | "cyclonedx" | "osv"
+ mentions: tuple[PackageMention, ...]
+
+
+class AdvisorySource(Protocol):
+ def read(self, location: str, *, packages: Sequence[tuple[str, str]] = ()) -> SourceDocument:
+ """The packages (and advisories) at *location*. *packages* are the
+ repository's declared ``(ecosystem, name)`` pairs, for a source that looks
+ them up; a file source ignores them."""
+ ...
+
+
+def _ecosystem(raw: Any) -> str | None:
+ if not isinstance(raw, str) or not raw:
+ return None
+ return _ECOSYSTEMS.get(raw.split(":", 1)[0].casefold())
+
+
+def from_purl(purl: str) -> tuple[str | None, str | None, str | None]:
+ """``(ecosystem, name, version)`` from a package URL; Nones where it has none."""
+ if not isinstance(purl, str) or not purl.startswith("pkg:"):
+ return None, None, None
+ body = purl[4:].split("#", 1)[0].split("?", 1)[0]
+ kind, _, rest = body.partition("/")
+ # The version follows the last "@" after the last "/": a raw npm scope
+ # (``@scope/[email protected]``) keeps its own "@".
+ at = rest.rfind("@", rest.rfind("/") + 1)
+ path, version = (rest[:at], rest[at + 1 :]) if at > 0 else (rest, "")
+ parts = [unquote(p) for p in path.split("/") if p]
+ if not parts:
+ return None, None, None
+ eco = _ecosystem(kind)
+ if eco == "maven" and len(parts) >= 2:
+ name = f"{parts[-2]}:{parts[-1]}"
+ elif eco == "composer" or eco == "npm" or eco == "go":
+ name = "/".join(parts)
+ else:
+ name = parts[-1]
+ return eco, name, unquote(version) or None
+
+
+def _mention(name: Any, version: Any, purl: Any, eco: Any = None) -> PackageMention | None:
+ p_eco, p_name, p_version = from_purl(purl) if isinstance(purl, str) else (None, None, None)
+ name = p_name or name
+ if not isinstance(name, str) or not name.strip():
+ return None
+ version = version if isinstance(version, str) and version else p_version
+ return PackageMention(name.strip(), p_eco or _ecosystem(eco), version)
+
+
+def _syft(doc: dict) -> list[PackageMention]:
+ return [
+ m
+ for a in doc.get("artifacts") or []
+ if isinstance(a, dict) and (m := _mention(a.get("name"), a.get("version"), a.get("purl")))
+ ]
+
+
+def _spdx(doc: dict) -> list[PackageMention]:
+ out = []
+ for pkg in doc.get("packages") or []:
+ if not isinstance(pkg, dict):
+ continue
+ purl = next(
+ (
+ ref.get("referenceLocator")
+ for ref in pkg.get("externalRefs") or []
+ if isinstance(ref, dict) and ref.get("referenceType") == "purl"
+ ),
+ None,
+ )
+ if (m := _mention(pkg.get("name"), pkg.get("versionInfo"), purl)) is not None:
+ out.append(m)
+ return out
+
+
+def _cyclonedx(doc: dict) -> list[PackageMention]:
+ out: list[PackageMention] = []
+ stack = deque(doc.get("components") or [])
+ while stack:
+ comp = stack.popleft()
+ if not isinstance(comp, dict):
+ continue
+ stack.extend(comp.get("components") or [])
+ if (m := _mention(comp.get("name"), comp.get("version"), comp.get("purl"))) is not None:
+ out.append(m)
+ return out
+
+
+def _advisory(rec: dict) -> Advisory | None:
+ if not isinstance(rec.get("id"), str):
+ return None
+ return Advisory(
+ rec["id"],
+ tuple(a for a in rec.get("aliases") or [] if isinstance(a, str)),
+ rec["summary"] if isinstance(rec.get("summary"), str) else None,
+ )
+
+
+def _osv_record(rec: dict) -> list[PackageMention]:
+ advisory = _advisory(rec)
+ if advisory is None:
+ return []
+ out = []
+ for aff in rec.get("affected") or []:
+ pkg = aff.get("package") if isinstance(aff, dict) else None
+ if not isinstance(pkg, dict):
+ continue
+ m = _mention(pkg.get("name"), None, pkg.get("purl"), pkg.get("ecosystem"))
+ if m is not None:
+ out.append(PackageMention(m.name, m.ecosystem, None, (advisory,)))
+ return out
+
+
+def _osv_scanner(doc: dict) -> list[PackageMention]:
+ out = []
+ for result in doc.get("results") or []:
+ for entry in (result.get("packages") or []) if isinstance(result, dict) else []:
+ if not isinstance(entry, dict) or not isinstance(entry.get("package"), dict):
+ continue
+ pkg = entry["package"]
+ m = _mention(pkg.get("name"), pkg.get("version"), pkg.get("purl"), pkg.get("ecosystem"))
+ if m is None:
+ continue
+ advisories = tuple(
+ a
+ for v in entry.get("vulnerabilities") or []
+ if isinstance(v, dict) and (a := _advisory(v)) is not None
+ )
+ out.append(PackageMention(m.name, m.ecosystem, m.version, advisories))
+ return out
+
+
+def parse_document(data: Any) -> SourceDocument:
+ """Recognise and read one decoded document; ``ValueError`` when it is none of the four."""
+ if isinstance(data, list):
+ return SourceDocument("osv", tuple(m for r in data if isinstance(r, dict) for m in _osv_record(r)))
+ if not isinstance(data, dict):
+ raise ValueError("not a Syft, SPDX, CycloneDX or OSV JSON document")
+ if "artifacts" in data and ("descriptor" in data or "source" in data):
+ return SourceDocument("syft", tuple(_syft(data)))
+ if str(data.get("spdxVersion", "")).startswith("SPDX-"):
+ return SourceDocument("spdx", tuple(_spdx(data)))
+ if data.get("bomFormat") == "CycloneDX":
+ return SourceDocument("cyclonedx", tuple(_cyclonedx(data)))
+ if isinstance(data.get("results"), list):
+ return SourceDocument("osv", tuple(_osv_scanner(data)))
+ if isinstance(data.get("vulns"), list):
+ records = [r for r in data["vulns"] if isinstance(r, dict)]
+ return SourceDocument("osv", tuple(m for r in records for m in _osv_record(r)))
+ if isinstance(data.get("id"), str) and isinstance(data.get("affected"), list):
+ return SourceDocument("osv", tuple(_osv_record(data)))
+ raise ValueError("not a Syft, SPDX, CycloneDX or OSV JSON document")
+
+
+class FileAdvisorySource:
+ """Reads one local JSON file; never touches the network."""
+
+ def read(self, location: str, *, packages: Sequence[tuple[str, str]] = ()) -> SourceDocument:
+ path = Path(location)
+ try:
+ if path.stat().st_size > MAX_FILE_BYTES:
+ raise ValueError(f"{location}: larger than {MAX_FILE_BYTES} bytes; not read")
+ data = json.loads(path.read_text(encoding="utf-8"))
+ except OSError as exc:
+ raise ValueError(f"{location}: cannot be read ({exc.strerror or exc})") from exc
+ except RecursionError as exc:
+ raise ValueError(f"{location}: JSON nested too deeply to read") from exc
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
+ raise ValueError(f"{location}: not valid UTF-8 JSON") from exc
+ try:
+ return parse_document(data)
+ except RecursionError as exc:
+ raise ValueError(f"{location}: document nested too deeply to read") from exc
+
+
+def _merge(mentions: Sequence[PackageMention]) -> dict[tuple[str | None, str], dict[str, Any]]:
+ merged: dict[tuple[str | None, str], dict[str, Any]] = {}
+ for m in mentions:
+ row = merged.setdefault((m.ecosystem, m.name), {"versions": [], "advisories": {}})
+ if m.version and m.version not in row["versions"]:
+ row["versions"].append(m.version)
+ for a in m.advisories:
+ row["advisories"].setdefault(a.id, a)
+ return merged
+
+
+async def join_usage(
+ session: Any,
+ repository_id: str,
+ repo_root: Path | str,
+ location: str,
+ *,
+ source: str | None = None,
+) -> dict[str, Any]:
+ """Read *location* through the selected advisory source and join its packages
+ to where this repository uses them, by name. ``ValueError`` on an unreadable
+ document."""
+ from repowise.core.inventory.usage import load_usage_index, package_usages
+
+ index = await load_usage_index(session, repository_id)
+ declared = sorted({(d.ecosystem, d.name) for d in index.declarations})
+ document = advisory_sources.get(source).read(location, packages=declared)
+ merged = _merge(document.mentions)
+ keys = list(merged)
+ docs = await package_usages(
+ session, repository_id, repo_root, [(n, e) for e, n in keys], index=index
+ )
+ matched: list[dict[str, Any]] = []
+ not_found: list[dict[str, Any]] = []
+ for (eco, name), doc in zip(keys, docs, strict=True):
+ info = merged[(eco, name)]
+ row: dict[str, Any] = {"name": name, "ecosystem": eco, "versions": info["versions"]}
+ if info["advisories"]:
+ row["advisories"] = [
+ {"id": a.id, "aliases": list(a.aliases), **({"summary": a.summary} if a.summary else {})}
+ for a in info["advisories"].values()
+ ]
+ if not doc["declared"] and not doc["sites"]:
+ not_found.append(row)
+ continue
+ row.update(
+ declared=bool(doc["declared"]),
+ summary=doc["summary"],
+ components=[c["name"] for c in doc["components"]],
+ sites=[
+ {
+ k: site[k]
+ for k in ("path", "line", "component", "mapping", "reachability")
+ if k in site
+ }
+ for site in doc["sites"]
+ ],
+ )
+ matched.append(row)
+
+ def order(row: dict[str, Any]) -> tuple:
+ reach = row["summary"]["reachability"]
+ return (not row.get("advisories"), -reach["reachable"], -row["summary"]["files"], row["name"])
+
+ matched.sort(key=order)
+ return {
+ "format": document.format,
+ "mentions": len(keys),
+ "matched": matched,
+ "not_found": len(not_found),
+ # Only the ones carrying advisories: the rest are usually transitive.
+ "not_found_with_advisories": [r for r in not_found if r.get("advisories")],
+ "method": "joined by package name (and ecosystem when the file gives one); "
+ "advisory version ranges are not evaluated",
+ }
+
+
+advisory_sources: SeamRegistry[AdvisorySource] = SeamRegistry("advisory-source")
+advisory_sources.register("file", FileAdvisorySource(), default=True)
+
+
+__all__ = [
+ "Advisory",
+ "AdvisorySource",
+ "FileAdvisorySource",
+ "PackageMention",
+ "SourceDocument",
+ "advisory_sources",
+ "from_purl",
+ "join_usage",
+ "parse_document",
+]
diff --git a/packages/core/src/repowise/core/inventory/components.py b/packages/core/src/repowise/core/inventory/components.py
new file mode 100644
index 000000000..5eb933645
--- /dev/null
+++ b/packages/core/src/repowise/core/inventory/components.py
@@ -0,0 +1,121 @@
+"""Component inventory: each component with its owners, languages, entry points
+and the third-party packages its files import.
+
+A plain document built from the index (components from :mod:`repowise.core.components`,
+declared teams through the ``team-directory`` seam, packages from
+:mod:`.usage`). It is what a software inventory review asks for (PCI DSS 6.3.2
+names one): what the code is made of and who answers for each part.
+"""
+
+from __future__ import annotations
+
+from collections import Counter
+from pathlib import Path
+from typing import Any
+
+from sqlalchemy import select
+
+from repowise.core.analysis.external_systems import package_key
+from repowise.core.inventory.usage import load_usage_index, lookup_key
+
+INVENTORY_VERSION = 1
+
+
+def _key(decl: Any) -> str:
+ """One key per package however its manifests spell it."""
+ return package_key(decl.ecosystem, lookup_key(decl.ecosystem, decl.name))
+
+
+async def component_inventory(
+ session: Any, repository_id: str, repo_root: Path | str
+) -> dict[str, Any]:
+ """The inventory document for one indexed repository."""
+ from repowise.core.components.ownership import Activity, assess_component
+ from repowise.core.components.store import load_repo_components, workspace_services
+ from repowise.core.ownership.directory import team_directories
+ from repowise.core.persistence.models import GraphNode
+
+ root = Path(repo_root)
+ found = await load_repo_components(session, repository_id, root, services=workspace_services(root))
+ declared = team_directories.get().load(root)
+ nodes = (
+ await session.execute(
+ select(GraphNode.node_id, GraphNode.language, GraphNode.is_entry_point).where(
+ GraphNode.repository_id == repository_id, GraphNode.node_type == "file"
+ )
+ )
+ ).all()
+ language = {n: lang for n, lang, _e in nodes}
+ entries = {n for n, _l, e in nodes if e}
+
+ index = await load_usage_index(session, repository_id)
+ decl_by_id = {d.id: d for d in index.declarations}
+ packages_of: dict[str, set[str]] = {}
+ for src, dst, _names in index.edges:
+ decl = decl_by_id.get(index.nodes.get(dst)) # type: ignore[arg-type]
+ if decl is not None:
+ packages_of.setdefault(src, set()).add(_key(decl))
+
+ components = []
+ imported: set[str] = set()
+ for comp in found.resolved.components:
+ files = found.resolved.files.get(comp.name, [])
+ prod = [f for f in files if f not in found.test_files]
+ owners = assess_component(comp, files, declared, Activity())
+ pkg_files: Counter[str] = Counter(k for f in prod for k in packages_of.get(f, ()))
+ test_only = {k for f in files if f in found.test_files for k in packages_of.get(f, ())}
+ test_only -= set(pkg_files)
+ imported |= set(pkg_files) | test_only
+ row: dict[str, Any] = {
+ "name": comp.name,
+ "source": comp.source,
+ "file_count": len(files),
+ "test_file_count": len(files) - len(prod),
+ "owners": {
+ "teams": [
+ {"team": t["team"], "files": t["files"]}
+ for t in owners.get("declared_teams", [])
+ ],
+ "files_with_declared_owner": owners.get("files_with_declared_owner", 0),
+ },
+ "languages": dict(Counter(language[f] for f in files if language.get(f)).most_common()),
+ "entry_points": sorted(f for f in files if f in entries),
+ "packages": [
+ {"package_key": k, "files": n}
+ for k, n in sorted(pkg_files.items(), key=lambda kv: (-kv[1], kv[0]))
+ ],
+ }
+ if test_only:
+ row["test_only_packages"] = sorted(test_only)
+ for key in ("criticality", "system", "lifecycle"):
+ if getattr(comp, key):
+ row[key] = getattr(comp, key)
+ components.append(row)
+
+ declared_keys = {_key(d) for d in index.declarations}
+ return {
+ "kind": "repowise.inventory",
+ "version": INVENTORY_VERSION,
+ "components": components,
+ "unassigned_files": len(found.resolved.unassigned),
+ "packages": {
+ "declared": len(declared_keys),
+ "imported": len(imported),
+ "declared_not_imported": sorted(declared_keys - imported),
+ },
+ "catalog_sources": list(found.catalog.sources),
+ "directory_issues": list(declared.issues),
+ "method": {
+ "components": "declared in the catalog, else derived from the index",
+ "owners": "declared teams from the catalog spec.owner and CODEOWNERS",
+ "languages": "file count per language of the indexed files",
+ "entry_points": "files the index marks as entry points",
+ "packages": "manifest-declared packages the component's production files import, "
+ "with the number of importing files; test_only_packages are imported by tests only",
+ "declared_not_imported": "declared packages no import edge links to; the import "
+ "name may differ from the package name, so this is not proof of non-use",
+ },
+ }
+
+
+__all__ = ["INVENTORY_VERSION", "component_inventory"]
diff --git a/packages/core/src/repowise/core/inventory/cyclonedx.py b/packages/core/src/repowise/core/inventory/cyclonedx.py
new file mode 100644
index 000000000..81bac29ff
--- /dev/null
+++ b/packages/core/src/repowise/core/inventory/cyclonedx.py
@@ -0,0 +1,135 @@
+"""Package usage as a CycloneDX 1.6 JSON document.
+
+One ``library`` component per package a manifest declares, with
+``evidence.occurrences`` listing the files that import it (``location``,
+``line``, ``symbol``, ``additionalContext``: the keys the 1.6 schema allows on
+an occurrence). This records where packages are used. It is not an SBOM: no
+hashes, no licenses, no transitive resolution, and no version beyond the
+specifier a manifest declares, which is kept as a property rather than as
+``version`` because a range is not a resolved version.
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any
+from urllib.parse import quote
+
+from repowise.core.inventory.usage import (
+ dist_key,
+ load_usage_index,
+ lookup_key,
+ package_usages,
+)
+
+SPEC_VERSION = "1.6"
+_PURL_TYPE = {
+ "npm": "npm",
+ "pypi": "pypi",
+ "cargo": "cargo",
+ "go": "golang",
+ "nuget": "nuget",
+ "maven": "maven",
+}
+
+
+def purl(ecosystem: str, name: str) -> str | None:
+ """A versionless package URL, or ``None`` for an ecosystem purl has no type for."""
+ kind = _PURL_TYPE.get(ecosystem)
+ if kind is None:
+ return None
+ if ecosystem == "pypi":
+ name = dist_key(name)
+ if ecosystem == "maven":
+ group, sep, artifact = name.partition(":")
+ if not sep or not group or not artifact:
+ return None # a purl names a Maven package by group and artifact
+ return f"pkg:maven/{quote(group)}/{quote(artifact)}"
+ return f"pkg:{kind}/" + "/".join(quote(part) for part in name.split("/"))
+
+
+def _occurrence(site: dict[str, Any]) -> dict[str, Any]:
+ out: dict[str, Any] = {"location": site["path"]}
+ if "line" in site:
+ out["line"] = site["line"]
+ if site["symbols"]:
+ out["symbol"] = ", ".join(site["symbols"])
+ if "statement" in site:
+ out["additionalContext"] = site["statement"]
+ return out
+
+
+def _component(ecosystem: str, name: str, doc: dict[str, Any]) -> dict[str, Any]:
+ # One component per package however its manifests spell it (``PyYAML``,
+ # ``pyyaml``): the bom-ref uses the same normalised name the lookup does.
+ ref = f"{ecosystem}:{lookup_key(ecosystem, name)}"
+ comp: dict[str, Any] = {"type": "library", "bom-ref": ref, "name": name}
+ if (url := purl(ecosystem, name)) is not None:
+ comp["purl"] = url
+ props = [{"name": "repowise:ecosystem", "value": ecosystem}]
+ seen: set[tuple[str, str]] = set()
+ for decl in doc["declared"]:
+ if not decl["package_key"].startswith(f"{ecosystem}:"):
+ continue
+ for key in ("declared_in", "version"):
+ value = decl[key]
+ if value and (key, value) not in seen:
+ seen.add((key, value))
+ label = "declared_in" if key == "declared_in" else "declared_version"
+ props.append({"name": f"repowise:{label}", "value": value})
+ states = doc["summary"]["reachability"]
+ props.extend(
+ {"name": f"repowise:importing_files_{state}", "value": str(n)}
+ for state, n in states.items()
+ if n
+ )
+ comp["properties"] = props
+ # Only declared links: an occurrence matched by import name alone is a guess.
+ sites = [s for s in doc["sites"] if s["mapping"] == "declared"]
+ if sites:
+ comp["evidence"] = {"occurrences": [_occurrence(s) for s in sites]}
+ return comp
+
+
+async def cyclonedx_bom(
+ session: Any, repository_id: str, repo_root: Path | str, repo_name: str
+) -> dict[str, Any]:
+ """The CycloneDX 1.6 document for one indexed repository."""
+ from repowise.core import __version__
+
+ index = await load_usage_index(session, repository_id)
+ names: dict[tuple[str, str], str] = {}
+ for d in sorted(index.declarations, key=lambda d: d.name):
+ names.setdefault((d.ecosystem, lookup_key(d.ecosystem, d.name)), d.name)
+ keys = sorted((eco, name) for (eco, _key), name in names.items())
+ docs = await package_usages(
+ session, repository_id, repo_root, [(name, eco) for eco, name in keys], index=index
+ )
+ return {
+ "bomFormat": "CycloneDX",
+ "specVersion": SPEC_VERSION,
+ "serialNumber": uuid.uuid4().urn,
+ "version": 1,
+ "metadata": {
+ "timestamp": datetime.now(UTC).replace(microsecond=0).isoformat(),
+ "tools": {
+ "components": [{"type": "application", "name": "repowise", "version": __version__}]
+ },
+ "component": {"type": "application", "bom-ref": "repository", "name": repo_name},
+ "properties": [
+ {
+ "name": "repowise:scope",
+ "value": "declared packages and where the import graph uses them; "
+ "not an SBOM (no hashes, no transitive resolution, no resolved versions)",
+ }
+ ],
+ },
+ "components": [
+ _component(eco, name, doc) for (eco, name), doc in zip(keys, docs, strict=True)
+ ],
+ }
+
+
+__all__ = ["SPEC_VERSION", "cyclonedx_bom", "purl"]
diff --git a/packages/core/src/repowise/core/inventory/usage.py b/packages/core/src/repowise/core/inventory/usage.py
new file mode 100644
index 000000000..85b260c9c
--- /dev/null
+++ b/packages/core/src/repowise/core/inventory/usage.py
@@ -0,0 +1,603 @@
+"""Where a third-party package is used: import sites, components, owners, reachability.
+
+Read from what the index already holds. Declarations are the ``external_systems``
+rows the manifest parsers wrote (:mod:`repowise.core.ingestion.external_systems`);
+import sites are ``imports`` edges from a file to an ``external:`` graph node.
+A node counts for a package in one of two ways, and every row says which:
+
+* ``declared``: ingestion linked the node to the package's manifest
+ declaration (``graph_nodes.external_system_id``): the import module is the
+ declared name or starts with it (``requests.adapters``, ``lodash/merge``).
+* ``inferred``: no link; the import module starts with the asked name but no
+ manifest declaration was matched to it. A Python distribution whose import
+ name differs (``PyYAML`` / ``yaml``) is found only by asking for the import
+ name, and then only as inferred.
+
+Reachability per importing file, from the stored graph: ``reachable`` when an
+entry point or other reachability root imports it, directly or transitively;
+``unreachable`` when dead-code analysis reported the file as ``unreachable_file``;
+``test`` for test files; otherwise ``unknown``. A file no import path reaches
+may still be loaded by a framework, a script or reflection, so that is never
+reported as unreachable on the import graph alone.
+
+Owners are declared teams only (catalog ``spec.owner`` and CODEOWNERS through the
+``team-directory`` seam). Individuals are never named.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from collections import Counter, deque
+from collections.abc import Iterable, Sequence
+from dataclasses import dataclass, field
+from functools import lru_cache
+from pathlib import Path
+from typing import Any
+
+from sqlalchemy import select
+
+from repowise.core.analysis.external_systems import (
+ EXTERNAL_NODE_PREFIX,
+ IMPORT_EDGE_TYPE,
+ declaration_name_candidates,
+ package_key,
+)
+from repowise.core.ids import SYMBOL_SEP
+
+#: Language tag of an importing file to the manifest ecosystem its imports
+#: come from. Used only to keep an undeclared import name from matching a
+#: package of another ecosystem when the caller names one.
+LANGUAGE_ECOSYSTEM = {
+ "python": "pypi",
+ "javascript": "npm",
+ "typescript": "npm",
+ "tsx": "npm",
+ "jsx": "npm",
+ "rust": "cargo",
+ "go": "go",
+ "csharp": "nuget",
+ "java": "maven",
+ "kotlin": "maven",
+ "scala": "maven",
+}
+
+#: A statement that imports, anchored at the start of the line so a comment or a
+#: string that mentions a module never counts. ``const x = require(...)`` is the
+#: one form where the keyword is not first (and its ``import(...)`` twin).
+_IMPORT_LINE = re.compile(
+ r"(?:(?:import|from|use|using|require|include|load|extern|export|open)\b"
+ r"|\}\s*from\b" # the last line of a multi-line JS/TS import
+ r"|#\s*include\b|#import\b"
+ r"|(?:const|let|var)\b.*\b(?:require|import)\s*\()"
+)
+#: First characters :data:`_IMPORT_LINE` can match on, checked before the regex.
+_IMPORT_STARTS = tuple("iufrleo}#cv")
+#: Opens an ``import ( ... )`` block (Go): each line inside names one module.
+_BLOCK_OPEN = re.compile(r"import\s*\(\s*$")
+#: Files larger than this are not read for the import line; the site keeps no line.
+_MAX_READ_BYTES = 2_000_000
+#: File-to-file edges that load the target: static imports, and the dynamic
+#: loads the parsers resolve (``importlib.import_module`` and ``"module:attr"``
+#: string tables, such as the CLI's lazily loaded commands).
+_LOAD_EDGE_TYPES = (IMPORT_EDGE_TYPE, "dynamic_imports", "dynamic_uses")
+#: Bound parameters per ``IN`` list, well under SQLite's variable limit.
+_CHUNK = 500
+
+METHOD = {
+ "import_sites": "imports edges from a file to an external graph node",
+ "mapping": "declared: linked to the manifest declaration by ingestion; "
+ "inferred: matched by import name only, no declaration linked",
+ "line": "first import statement of the file (a line starting with an import "
+ "keyword, or inside a Go import block) that names the module; absent when none does",
+ "reachability": "reachable: an entry point or reachability root loads the file "
+ "through stored import or resolved dynamic-load edges; unreachable: an open dead-code unreachable_file finding; "
+ "test: a test file; unknown: neither",
+ "owners": "declared teams from the catalog spec.owner and CODEOWNERS; individual "
+ "and unresolved owners are counted in owner_counts, never named",
+}
+
+
+def dist_key(name: str) -> str:
+ """PEP 503 spelling, so ``PyYAML`` and ``pyyaml`` compare equal."""
+ return re.sub(r"[-_.]+", "-", name).casefold()
+
+
+def _same_name(ecosystem: str, a: str, b: str) -> bool:
+ return lookup_key(ecosystem, a) == lookup_key(ecosystem, b)
+
+
+def parse_query(query: str) -> tuple[str, str | None]:
+ """``name`` or ``ecosystem:name`` (a package key) to ``(name, ecosystem)``."""
+ head, sep, rest = query.partition(":")
+ if sep and rest and head in _KNOWN_ECOSYSTEMS:
+ return rest, head
+ return query, None
+
+
+_KNOWN_ECOSYSTEMS = frozenset(
+ {"npm", "pypi", "cargo", "go", "nuget", "maven", "bazel", "cmake", "composer"}
+)
+
+
+@dataclass(frozen=True)
+class Declaration:
+ id: int
+ ecosystem: str
+ name: str
+ version: str | None
+ declared_in: str
+ is_dev_dep: bool
+
+ @property
+ def key(self) -> str:
+ return package_key(self.ecosystem, self.name)
+
+
+@dataclass
+class UsageIndex:
+ """Declarations, external nodes and the import edges reaching them, read once."""
+
+ declarations: list[Declaration] = field(default_factory=list)
+ #: ``external:`` node id to its linked declaration id, or ``None``.
+ nodes: dict[str, int | None] = field(default_factory=dict)
+ #: ``(source file, external node, imported names)``.
+ edges: list[tuple[str, str, list[str]]] = field(default_factory=list)
+
+ def __post_init__(self) -> None:
+ # Built once so each query below is a few dict lookups, however many a
+ # supplied SBOM asks about.
+ self.by_target: dict[str, list[tuple[str, list[str]]]] = {}
+ for src, dst, names in self.edges:
+ self.by_target.setdefault(dst, []).append((src, names))
+ self._decls_by_name: dict[str, list[Declaration]] = {}
+ for d in self.declarations:
+ self._decls_by_name.setdefault(lookup_key(d.ecosystem, d.name), []).append(d)
+ self._nodes_by_decl: dict[int, list[str]] = {}
+ self._unlinked_by_name: dict[str, list[str]] = {}
+ for node_id, decl_id in self.nodes.items():
+ if decl_id is not None:
+ self._nodes_by_decl.setdefault(decl_id, []).append(node_id)
+ continue
+ suffix = node_id[len(EXTERNAL_NODE_PREFIX) :]
+ for cand in {c.casefold() for c in declaration_name_candidates(suffix)}:
+ self._unlinked_by_name.setdefault(cand, []).append(node_id)
+
+ def match(
+ self, name: str, ecosystem: str | None = None
+ ) -> tuple[list[Declaration], dict[str, str]]:
+ """The declarations of *name* and each matching external node's mapping basis."""
+ found = {
+ d.id: d
+ for key in dict.fromkeys((name.casefold(), dist_key(name)))
+ for d in self._decls_by_name.get(key, ())
+ if (ecosystem is None or d.ecosystem == ecosystem)
+ and _same_name(d.ecosystem, d.name, name)
+ }
+ mapped: dict[str, str] = {}
+ for decl_id in found:
+ for node_id in self._nodes_by_decl.get(decl_id, ()):
+ mapped[node_id] = "declared"
+ for node_id in self._unlinked_by_name.get(name.casefold(), ()):
+ mapped[node_id] = "inferred"
+ return list(found.values()), mapped
+
+
+def lookup_key(ecosystem: str, name: str) -> str:
+ """One spelling per package within an ecosystem: PEP 503 for PyPI, else case-folded."""
+ return dist_key(name) if ecosystem == "pypi" else name.casefold()
+
+
+def _is_file(node_id: str) -> bool:
+ return SYMBOL_SEP not in node_id and not node_id.startswith(("external:", "framework:"))
+
+
+async def load_usage_index(session: Any, repository_id: str) -> UsageIndex:
+ from repowise.core.persistence.models import ExternalSystem, GraphEdge, GraphNode
+
+ decls = (
+ await session.execute(
+ select(
+ ExternalSystem.id,
+ ExternalSystem.ecosystem,
+ ExternalSystem.name,
+ ExternalSystem.version,
+ ExternalSystem.declared_in,
+ ExternalSystem.is_dev_dep,
+ ).where(ExternalSystem.repository_id == repository_id)
+ )
+ ).all()
+ nodes = (
+ await session.execute(
+ select(GraphNode.node_id, GraphNode.external_system_id).where(
+ GraphNode.repository_id == repository_id,
+ GraphNode.node_id.startswith(EXTERNAL_NODE_PREFIX),
+ )
+ )
+ ).all()
+ edges = (
+ await session.execute(
+ select(
+ GraphEdge.source_node_id, GraphEdge.target_node_id, GraphEdge.imported_names_json
+ ).where(
+ GraphEdge.repository_id == repository_id,
+ GraphEdge.edge_type == IMPORT_EDGE_TYPE,
+ GraphEdge.target_node_id.startswith(EXTERNAL_NODE_PREFIX),
+ )
+ )
+ ).all()
+ return UsageIndex(
+ declarations=[Declaration(*row) for row in decls],
+ nodes={n: d for n, d in nodes},
+ edges=[(s, t, _names(raw)) for s, t, raw in edges if _is_file(s)],
+ )
+
+
+def _names(raw: str | None) -> list[str]:
+ try:
+ names = json.loads(raw or "[]")
+ except ValueError:
+ return []
+ return [str(n) for n in names if n and n != "*"] if isinstance(names, list) else []
+
+
+# -- file facts: component, owners, reachability -------------------------------
+
+
+@dataclass
+class FileFacts:
+ """What the rows need about the importing files, read once per call."""
+
+ component_of: dict[str, str] = field(default_factory=dict)
+ component_owner: dict[str, str | None] = field(default_factory=dict)
+ language: dict[str, str] = field(default_factory=dict)
+ reachability: dict[str, dict[str, str]] = field(default_factory=dict)
+ declared: Any = None # DeclaredOwnership
+ #: Path to its import statements as ``(1-based line, stripped text)``, read once.
+ import_lines: dict[str, list[tuple[int, str]]] = field(default_factory=dict)
+ repo_root: Path | None = None
+
+ def owners(self, path: str) -> tuple[list[str], dict[str, int]]:
+ """Declared owner teams of *path* (the component's, then CODEOWNERS'), and
+ how many other declared owners there are by kind: ``individual`` and
+ ``unresolved`` (a bare ``@name`` that may be a person or a GitLab group).
+ Those are counted, never named, as in ``components ownership``."""
+ refs = []
+ comp_owner = self.component_owner.get(self.component_of.get(path, ""))
+ if comp_owner and self.declared is not None:
+ refs.append(self.declared.from_backstage(comp_owner))
+ if self.declared is not None and self.declared.rules:
+ refs.extend(self.declared.from_codeowners(o) for o in self.declared.codeowners_of(path))
+ teams = list(dict.fromkeys(r.name for r in refs if r.kind == "team"))
+ others = Counter(r.kind for r in dict.fromkeys(refs) if r.kind != "team")
+ return teams, dict(sorted(others.items()))
+
+ def line_of(self, path: str, tokens: Sequence[str]) -> tuple[int, str] | None:
+ """``(1-based line, text)`` of the first import statement naming a token."""
+ if self.repo_root is None:
+ return None
+ if path not in self.import_lines:
+ self.import_lines[path] = _import_lines(self.repo_root / path)
+ patterns = [_token_pattern(t) for t in tokens if t]
+ for number, text in self.import_lines[path]:
+ if any(p.search(text) for p in patterns):
+ return number, text
+ return None
+
+
+@lru_cache(maxsize=4096)
+def _token_pattern(token: str) -> re.Pattern[str]:
+ return re.compile(rf"(?<![\w@/.-]){re.escape(token)}(?![\w-])")
+
+
+def _import_lines(path: Path) -> list[tuple[int, str]]:
+ """The file's import statements, as ``(1-based line, stripped text)``; empty
+ when it is unreadable or too large. The text itself is not kept."""
+ try:
+ if path.stat().st_size > _MAX_READ_BYTES:
+ return []
+ lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
+ except OSError:
+ return []
+ out: list[tuple[int, str]] = []
+ in_block = False
+ for number, raw in enumerate(lines, 1):
+ text = raw.strip()
+ if in_block:
+ if text.startswith(")"):
+ in_block = False
+ elif text and not text.startswith("//"):
+ out.append((number, text[:200]))
+ # The cheap prefix test skips most lines before any regex runs.
+ elif text.startswith(_IMPORT_STARTS):
+ if _BLOCK_OPEN.match(text):
+ in_block = True
+ elif _IMPORT_LINE.match(text):
+ out.append((number, text[:200]))
+ return out
+
+
+async def load_file_facts(
+ session: Any, repository_id: str, repo_root: Path | str, files: Iterable[str]
+) -> FileFacts:
+ """Components, declared owners and reachability for *files*."""
+ from repowise.core.components.store import load_repo_components, workspace_services
+ from repowise.core.ownership.directory import team_directories
+
+ root = Path(repo_root)
+ wanted = set(files)
+ found = await load_repo_components(session, repository_id, root, services=workspace_services(root))
+ facts = FileFacts(repo_root=root, declared=team_directories.get().load(root))
+ for comp in found.resolved.components:
+ facts.component_owner[comp.name] = comp.owner
+ for path in found.resolved.files.get(comp.name, ()):
+ if path in wanted:
+ facts.component_of[path] = comp.name
+ facts.reachability, facts.language = await _reachability(
+ session, repository_id, wanted, found.test_files
+ )
+ return facts
+
+
+async def _file_nodes(
+ session: Any, repository_id: str, files: set[str]
+) -> tuple[list[str], dict[str, str]]:
+ """The reachability roots (entry points and other roots), and each of
+ *files*' language."""
+ from repowise.core.persistence.models import GraphNode
+
+ nodes = (
+ await session.execute(
+ select(
+ GraphNode.node_id,
+ GraphNode.language,
+ GraphNode.is_entry_point,
+ GraphNode.is_reachability_root,
+ ).where(GraphNode.repository_id == repository_id, GraphNode.node_type == "file")
+ )
+ ).all()
+ language = {n: lang for n, lang, _e, _r in nodes if n in files and lang}
+ roots = [n for n, _l, entry, root in nodes if entry or root]
+ return roots, language
+
+
+async def _reached_from(session: Any, repository_id: str, roots: list[str]) -> set[str]:
+ """Every file the stored load edges reach from *roots*, the roots included."""
+ from repowise.core.persistence.models import GraphEdge
+
+ # Ceiling: every file-to-file load edge is read to walk from the roots;
+ # one read per call, a few MB on the largest indexes measured so far.
+ edges = (
+ await session.execute(
+ select(GraphEdge.source_node_id, GraphEdge.target_node_id).where(
+ GraphEdge.repository_id == repository_id,
+ GraphEdge.edge_type.in_(_LOAD_EDGE_TYPES),
+ )
+ )
+ ).all()
+ adjacency: dict[str, list[str]] = {}
+ for src, dst in edges:
+ if _is_file(src) and _is_file(dst):
+ adjacency.setdefault(src, []).append(dst)
+ reached = set(roots)
+ queue = deque(roots)
+ while queue:
+ for nxt in adjacency.get(queue.popleft(), ()):
+ if nxt not in reached:
+ reached.add(nxt)
+ queue.append(nxt)
+ return reached
+
+
+async def _unreachable_findings(session: Any, repository_id: str, files: set[str]) -> set[str]:
+ """*files* with an unreachable_file finding the dead-code surface serves:
+ open, of a shown kind, in no gated language."""
+ from repowise.core.analysis.dead_code.models import DeadCodeKind
+ from repowise.core.persistence.crud import get_dead_code_findings
+
+ unreachable: set[str] = set()
+ ordered = sorted(files)
+ for i in range(0, len(ordered), _CHUNK):
+ found = await get_dead_code_findings(
+ session,
+ repository_id,
+ kind=DeadCodeKind.UNREACHABLE_FILE.value,
+ file_paths=ordered[i : i + _CHUNK],
+ )
+ unreachable.update(f.file_path for f in found)
+ return unreachable
+
+
+def _file_reachability(
+ path: str,
+ *,
+ test_files: set[str],
+ reached: set[str],
+ unreachable: set[str],
+ has_roots: bool,
+) -> dict[str, str]:
+ """One file's state and the basis it rests on, in order of precedence."""
+ if path in test_files:
+ return {"state": "test", "basis": "is_test"}
+ if path in reached:
+ return {"state": "reachable", "basis": "import_graph"}
+ if path in unreachable:
+ return {"state": "unreachable", "basis": "dead_code"}
+ if not has_roots:
+ return {"state": "unknown", "basis": "no_entry_points"}
+ return {"state": "unknown", "basis": "no_import_path"}
+
+
+async def _reachability(
+ session: Any, repository_id: str, files: set[str], test_files: set[str]
+) -> tuple[dict[str, dict[str, str]], dict[str, str]]:
+ roots, language = await _file_nodes(session, repository_id, files)
+ reached = await _reached_from(session, repository_id, roots) if roots and files else set()
+ unreachable = await _unreachable_findings(session, repository_id, files)
+ out = {
+ path: _file_reachability(
+ path,
+ test_files=test_files,
+ reached=reached,
+ unreachable=unreachable,
+ has_roots=bool(roots),
+ )
+ for path in files
+ }
+ return out, language
+
+
+# -- the answer -----------------------------------------------------------------
+
+
+def _sites(
+ index: UsageIndex, mapped: dict[str, str], ecosystem: str | None, facts: FileFacts | None
+) -> list[dict[str, Any]]:
+ by_file: dict[str, dict[str, dict[str, Any]]] = {}
+ pairs = ((src, dst, names) for dst in mapped for src, names in index.by_target.get(dst, ()))
+ for src, dst, names in pairs:
+ basis = mapped[dst]
+ if (
+ ecosystem is not None
+ and basis == "inferred"
+ and index.nodes.get(dst) is None
+ and facts is not None
+ and LANGUAGE_ECOSYSTEM.get(facts.language.get(src, "")) != ecosystem
+ ):
+ continue # an undeclared import name from another ecosystem
+ module = dst[len(EXTERNAL_NODE_PREFIX) :]
+ entry = by_file.setdefault(src, {}).setdefault(
+ module, {"name": module, "mapping": basis, "symbols": []}
+ )
+ entry["symbols"].extend(n for n in names if n not in entry["symbols"])
+ sites = []
+ for path in sorted(by_file):
+ modules = sorted(by_file[path].values(), key=lambda m: m["name"])
+ declared = [m for m in modules if m["mapping"] == "declared"]
+ # A declared link outranks an import-name match in the same file: the
+ # site's symbols and line come from the declared modules alone.
+ chosen = declared or modules
+ sites.append(
+ {
+ "path": path,
+ "modules": [{"name": m["name"], "mapping": m["mapping"]} for m in modules],
+ "symbols": list(dict.fromkeys(n for m in chosen for n in m["symbols"])),
+ "mapping": "declared" if declared else "inferred",
+ }
+ )
+ return sites
+
+
+def _enrich(site: dict[str, Any], name: str, facts: FileFacts) -> dict[str, Any]:
+ path = site["path"]
+ names = [m["name"] for m in site["modules"] if m["mapping"] == site["mapping"]]
+ tokens = [*names, *(c for m in names for c in declaration_name_candidates(m)), name]
+ found = facts.line_of(path, list(dict.fromkeys(tokens)))
+ if found is not None:
+ site["line"], site["statement"] = found
+ if path in facts.component_of:
+ site["component"] = facts.component_of[path]
+ site["owners"], others = facts.owners(path)
+ if others:
+ site["owner_counts"] = others
+ site["reachability"] = facts.reachability.get(path, {"state": "unknown", "basis": "not_in_graph"})
+ return site
+
+
+def _document(
+ query: str, ecosystem: str | None, decls: list[Declaration], sites: list[dict[str, Any]]
+) -> dict[str, Any]:
+ components: dict[str, dict[str, Any]] = {}
+ for s in sites:
+ comp = s.get("component")
+ if comp is None:
+ continue
+ row = components.setdefault(comp, {"name": comp, "files": 0, "owners": []})
+ row["files"] += 1
+ row["owners"].extend(o for o in s["owners"] if o not in row["owners"])
+ states = Counter(s["reachability"]["state"] for s in sites)
+ doc: dict[str, Any] = {
+ "package": query,
+ "declared": [
+ {
+ "package_key": d.key,
+ "version": d.version,
+ "declared_in": d.declared_in,
+ "dev": d.is_dev_dep,
+ }
+ for d in sorted(decls, key=lambda d: (d.key, d.declared_in))
+ ],
+ "summary": {
+ "files": len(sites),
+ "components": len(components),
+ "reachability": {k: states.get(k, 0) for k in ("reachable", "unreachable", "test", "unknown")},
+ "inferred_files": sum(1 for s in sites if s["mapping"] == "inferred"),
+ },
+ "sites": sites,
+ "components": sorted(components.values(), key=lambda c: (-c["files"], c["name"])),
+ "method": METHOD,
+ }
+ if ecosystem:
+ doc["ecosystem"] = ecosystem
+ if not decls:
+ doc["note"] = (
+ "No manifest declares this name; any sites are matched by import name only."
+ if sites
+ else "No manifest declares this name and no import matches it."
+ )
+ elif not sites:
+ doc["note"] = (
+ "Declared but no import edge resolves to it. Its import name may differ from "
+ "the package name (ask for the import name), or it is loaded without an import."
+ )
+ return doc
+
+
+async def package_usages(
+ session: Any,
+ repository_id: str,
+ repo_root: Path | str,
+ queries: Sequence[tuple[str, str | None]],
+ *,
+ index: UsageIndex | None = None,
+) -> list[dict[str, Any]]:
+ """One usage document per ``(name, ecosystem)`` query; the index and the
+ file facts are read once for the whole batch."""
+ index = index or await load_usage_index(session, repository_id)
+ matched = [(name, eco, *index.match(name, eco)) for name, eco in queries]
+ candidate_files = {
+ src
+ for _n, _e, _d, mapped in matched
+ for dst in mapped
+ for src, _names in index.by_target.get(dst, ())
+ }
+ facts = await load_file_facts(session, repository_id, repo_root, candidate_files)
+ docs = []
+ for name, eco, decls, mapped in matched:
+ sites = [_enrich(s, name, facts) for s in _sites(index, mapped, eco, facts)]
+ docs.append(_document(name, eco, decls, sites))
+ return docs
+
+
+async def package_usage(
+ session: Any, repository_id: str, repo_root: Path | str, query: str
+) -> dict[str, Any]:
+ """Usage of one package, named as ``name`` or ``ecosystem:name``."""
+ name, eco = parse_query(query)
+ return (await package_usages(session, repository_id, repo_root, [(name, eco)]))[0]
+
+
+__all__ = [
+ "LANGUAGE_ECOSYSTEM",
+ "METHOD",
+ "Declaration",
+ "FileFacts",
+ "UsageIndex",
+ "dist_key",
+ "load_file_facts",
+ "load_usage_index",
+ "lookup_key",
+ "package_usage",
+ "package_usages",
+ "parse_query",
+]
diff --git a/packages/core/src/repowise/core/report/render.py b/packages/core/src/repowise/core/report/render.py
index 748c3eb6e..f879d4d9c 100644
--- a/packages/core/src/repowise/core/report/render.py
+++ b/packages/core/src/repowise/core/report/render.py
@@ -56,10 +56,15 @@ def _code(text: Any) -> str:
return "`" + " ".join(str(text).split()).replace("`", "'") + "`"
+def _title(document: dict[str, Any]) -> str:
+ kind = str(document.get("kind") or "assessment").capitalize()
+ return f"{kind}: {document['scope'].get('name') or document['scope']['kind']}"
+
+
def render_markdown(document: dict[str, Any]) -> str:
gen = document["generator"]
lines = [
- f"# Assessment: {_line(document['scope'].get('name') or document['scope']['kind'])}",
+ f"# {_line(_title(document))}",
"",
document["notice"],
"",
@@ -126,7 +131,7 @@ ul.details { margin: .25rem 0 0; padding-left: 1.1rem; color: var(--muted); }
def render_html(document: dict[str, Any]) -> str:
e = html.escape
gen = document["generator"]
- title = f"Assessment: {document['scope'].get('name') or document['scope']['kind']}"
+ title = _title(document)
out = [
"<!doctype html>",
'<html lang="en"><head><meta charset="utf-8">',
diff --git a/packages/core/src/repowise/core/report/sections/inventory.py b/packages/core/src/repowise/core/report/sections/inventory.py
new file mode 100644
index 000000000..8810f6705
--- /dev/null
+++ b/packages/core/src/repowise/core/report/sections/inventory.py
@@ -0,0 +1,106 @@
+"""Software inventory: each component's declared owner teams, languages, entry
+points and the third-party packages it imports (:mod:`repowise.core.inventory.components`).
+
+Like the other per-component sections it opens with one summary row; a
+component gets an item of its own only when no team is declared for it, and the
+JSON ``data`` keeps every component's full row.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from repowise.core.report.model import (
+ ReportContext,
+ Section,
+ capped,
+ check,
+ component_summary,
+ report_sections,
+)
+
+
+def _details(comp: dict[str, Any]) -> list[str]:
+ langs = ", ".join(f"{lang} {n}" for lang, n in comp["languages"].items())
+ return capped(
+ [
+ *([f"languages: {langs}"] if langs else []),
+ *(f"entry point: {p}" for p in comp["entry_points"]),
+ *(f"package: {p['package_key']} ({p['files']} file(s))" for p in comp["packages"]),
+ *(f"test-only package: {k}" for k in comp.get("test_only_packages", [])),
+ ]
+ )
+
+
+async def collect(ctx: ReportContext) -> list[dict[str, Any]]:
+ from repowise.core.inventory.components import component_inventory
+
+ inv = await component_inventory(ctx.session, ctx.repository_id, ctx.repo_root)
+ method = inv["method"]
+ packages = inv["packages"]
+ comps = inv["components"]
+ unowned = [c for c in comps if not c["owners"]["teams"] and c["file_count"]]
+ owned = [c["name"] for c in comps if c["owners"]["teams"]]
+ empty = [c["name"] for c in comps if not c["file_count"]]
+ comp_method = (
+ f"owners: {method['owners']}; languages: {method['languages']}; "
+ f"entry points: {method['entry_points']}; packages: {method['packages']}"
+ )
+ out = [
+ check(
+ "inventory",
+ reason=(
+ f"{len(comps)} component(s); {packages['declared']} declared package(s), "
+ f"{packages['imported']} imported through the import graph"
+ ),
+ details=capped(
+ [
+ *(f"declared, no linked import: {k}" for k in packages["declared_not_imported"]),
+ *(f"team directory: {issue}" for issue in inv["directory_issues"]),
+ ]
+ ),
+ method=f"{method['packages']}; {method['declared_not_imported']}",
+ basis="measured",
+ data={"packages": packages, "unassigned_files": inv["unassigned_files"]},
+ ),
+ component_summary(
+ "inventory:components",
+ outcomes={
+ "with a declared owner team": len(owned),
+ "no declared owner team": len(unowned),
+ "no files": len(empty),
+ },
+ quiet=owned,
+ named={"no files": empty},
+ method=comp_method,
+ basis="declared",
+ data={"components": {c["name"]: c for c in comps}},
+ ),
+ ]
+ for comp in unowned:
+ out.append(
+ check(
+ f"inventory:{comp['name']}",
+ reason=(
+ f"{comp['file_count']} file(s) and no declared owner team; "
+ f"{len(comp['entry_points'])} entry point(s), "
+ f"{len(comp['packages'])} third-party package(s)"
+ ),
+ details=_details(comp),
+ method=comp_method,
+ basis="declared",
+ data=comp,
+ )
+ )
+ return out
+
+
+report_sections.register(
+ "inventory",
+ Section(
+ title="Software inventory",
+ summary="Each component's owner teams, languages, entry points and third-party packages.",
+ collect=collect,
+ order=15,
+ ),
+)
diff --git a/packages/server/src/repowise/server/mcp_server/_packages.py b/packages/server/src/repowise/server/mcp_server/_packages.py
new file mode 100644
index 000000000..f131b21ca
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/_packages.py
@@ -0,0 +1,73 @@
+"""``package:<name>`` targets for get_context: where a third-party package is used.
+
+Opt-in like ``component:`` and ``change:``; a default call never reads it. The
+card is :func:`repowise.core.inventory.usage.package_usage` with its sites
+capped, the rest recoverable through the omission store.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from repowise.core.inventory.usage import package_usages, parse_query
+from repowise.server.mcp_server._budget import OmissionCollector, cap_collection
+
+PACKAGE_PREFIX = "package:"
+_SITES_CAP = 25
+
+
+def is_package_target(target: str) -> bool:
+ return target.startswith(PACKAGE_PREFIX)
+
+
+def _site_row(site: dict[str, Any]) -> dict[str, Any]:
+ row = {k: site[k] for k in ("path", "line", "component", "mapping") if k in site}
+ if site["symbols"]:
+ row["symbols"] = site["symbols"]
+ if site["owners"]:
+ row["owners"] = site["owners"]
+ if "owner_counts" in site:
+ row["owner_counts"] = site["owner_counts"]
+ row["reachability"] = site["reachability"]
+ return row
+
+
+async def package_cards(
+ session: Any,
+ repository: Any,
+ targets: list[str],
+ *,
+ repo_root: Any,
+ collector: OmissionCollector,
+) -> dict[str, dict[str, Any]]:
+ """Cards for ``package:<name>`` targets (a name or ``ecosystem:name``), one read for the batch."""
+ cards: dict[str, dict[str, Any]] = {
+ t: {"target": t, "error": "Name a package: package:<name> or package:<ecosystem>:<name>."}
+ for t in targets
+ if not t[len(PACKAGE_PREFIX) :].strip()
+ }
+ asked = [t for t in targets if t not in cards]
+ if not asked:
+ return cards
+ queries = [parse_query(t[len(PACKAGE_PREFIX) :].strip()) for t in asked]
+ docs = await package_usages(session, repository.id, repo_root, queries)
+ for target, doc in zip(asked, docs, strict=True):
+ card: dict[str, Any] = {"target": target, "type": "package", "package": doc["package"]}
+ if "ecosystem" in doc:
+ card["ecosystem"] = doc["ecosystem"]
+ card["declared"] = doc["declared"]
+ card["summary"] = doc["summary"]
+ if doc["components"]:
+ card["components"] = doc["components"]
+ cap_collection(
+ card,
+ "sites",
+ [_site_row(s) for s in doc["sites"]],
+ _SITES_CAP,
+ collector,
+ label=f"{target} import sites beyond cap={_SITES_CAP}",
+ )
+ if "note" in doc:
+ card["note"] = doc["note"]
+ cards[target] = card
+ return cards
diff --git a/packages/server/src/repowise/server/mcp_server/_workspace_routing.py b/packages/server/src/repowise/server/mcp_server/_workspace_routing.py
index bdb8b15b1..611608dba 100644
--- a/packages/server/src/repowise/server/mcp_server/_workspace_routing.py
+++ b/packages/server/src/repowise/server/mcp_server/_workspace_routing.py
@@ -7,8 +7,8 @@ a path from another repo silently answers about the default repo.
Rules, exact matches only:
- ``<alias>:<target>`` names the repo outright (``backend:src/app.py``,
- ``backend:src/app.py::App``). ``component:``, ``change:`` and ``module:``
- stay target kinds, never repo prefixes.
+ ``backend:src/app.py::App``). ``component:``, ``change:``, ``module:`` and
+ ``package:`` stay target kinds, never repo prefixes.
- A path, or the file part of ``path::Name`` / ``path:120-140``, is served by
the default repo when it exists there, as before. Otherwise it is routed to
the one other repo whose checkout has it; when several do, the candidates
@@ -47,7 +47,7 @@ from repowise.server.mcp_server._query_shape import _LINE_SUFFIX_RE, _is_path
_log = logging.getLogger("repowise.mcp")
-_TARGET_KINDS = frozenset({"component", "change", "module"})
+_TARGET_KINDS = frozenset({"component", "change", "module", "package"})
# A dotted identifier: the only bare targets the symbol locator routes.
_IDENTIFIER_RE = re.compile(r"[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*")
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/context.py b/packages/server/src/repowise/server/mcp_server/tool_context/context.py
index 7e5475fe9..6b353c745 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context/context.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/context.py
@@ -74,6 +74,7 @@ from repowise.server.mcp_server._helpers import (
)
from repowise.server.mcp_server._meta import build_meta as _build_meta
from repowise.server.mcp_server._meta import completeness_line as _completeness_line
+from repowise.server.mcp_server._packages import is_package_target, package_cards
from repowise.server.mcp_server._workspace_routing import (
needs_routing,
route_targets,
@@ -151,8 +152,8 @@ async def get_context(
Include-gated blocks are projections, not omissions.
Args:
- targets: paths, "path::Symbol" ids, "component:<name>", or
- "change:<id>" (pr-123 or a commit sha).
+ targets: paths, "path::Symbol" ids, "component:<name>",
+ "change:<id>" (pr-123 or a sha), "package:<name>".
include: opt-in blocks: full_doc | ownership | last_change | callers
| callees | references | metrics | community | decisions | skeleton
| skeleton+ | health | doc_drift (docs naming this file)
@@ -223,6 +224,9 @@ async def get_context(
cards |= await _change_cards(
session, repository, [t for t in targets if is_change_target(t)], collector
)
+ cards |= await _package_cards(
+ session, repository, [t for t in targets if is_package_target(t)], ctx, collector
+ )
gathered = await asyncio.gather(
*[
_resolve_one_target(
@@ -374,6 +378,20 @@ async def _component_cards(
return {t: exc for t in targets}
+async def _package_cards(
+ session: Any, repository: Any, targets: list[str], ctx: Any, collector: OmissionCollector
+) -> dict[str, Any]:
+ """Cards for the batch's ``package:`` targets; a failure becomes each one's error."""
+ if not targets:
+ return {}
+ try:
+ return await package_cards(
+ session, repository, targets, repo_root=ctx.path, collector=collector
+ )
+ except Exception as exc:
+ return {t: exc for t in targets}
+
+
async def _change_cards(
session: Any, repository: Any, targets: list[str], collector: OmissionCollector
) -> dict[str, Any]:
diff --git a/packages/server/src/repowise/server/routers/external_systems.py b/packages/server/src/repowise/server/routers/external_systems.py
index 0be2df1a7..547e93301 100644
--- a/packages/server/src/repowise/server/routers/external_systems.py
+++ b/packages/server/src/repowise/server/routers/external_systems.py
@@ -17,11 +17,13 @@ from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.external_systems import build_registry
from repowise.core.persistence.models import ExternalSystem
from repowise.server.deps import get_db_session, verify_api_key
+from repowise.server.routers._local_git import local_repo_path
from repowise.server.schemas.external_systems import (
ExternalSystemImportingFilesResponse,
ExternalSystemRelationshipGraphResponse,
ExternalSystemsResponse,
ExternalSystemsSummaryResponse,
+ PackageUsageResponse,
)
from repowise.server.services.external_system_relationships import (
DEFAULT_FILE_LIMIT,
@@ -62,6 +64,26 @@ async def summarize_external_systems(
)
+ "/{repo_id}/external-systems/{package_key:path}/usage",
+ response_model=PackageUsageResponse,
+)
+async def external_system_usage(
+ repo_id: str,
+ package_key: str,
+ session: AsyncSession = Depends(get_db_session),
+) -> PackageUsageResponse:
+ """Where a package is imported; *package_key* is ``ecosystem:name`` or a bare name.
+
+ Reads the importing files from the local checkout for line numbers, so it
+ needs one (a 404 says when there is none)."""
+ from repowise.core.inventory.usage import package_usage
+
+ repo_root = await local_repo_path(session, repo_id)
+ doc = await package_usage(session, repo_id, repo_root, package_key)
+ return PackageUsageResponse.model_validate(doc)
+
+
@router.get(
"/{repo_id}/external-systems/{package_key:path}/graph/files",
response_model=ExternalSystemImportingFilesResponse,
diff --git a/packages/server/src/repowise/server/schemas/external_systems.py b/packages/server/src/repowise/server/schemas/external_systems.py
index 3e09a7c22..dcb65058b 100644
--- a/packages/server/src/repowise/server/schemas/external_systems.py
+++ b/packages/server/src/repowise/server/schemas/external_systems.py
@@ -150,3 +150,66 @@ class ExternalSystemImportingFilesResponse(BaseModel):
offset: int
truncated: bool
scope: ExternalSystemsSummaryScope
+
+
+class PackageUsageDeclaration(BaseModel):
+ package_key: str
+ version: str | None = None
+ declared_in: str
+ dev: bool = False
+
+
+class PackageUsageReachability(BaseModel):
+ #: reachable | unreachable | test | unknown
+ state: str
+ #: import_graph | dead_code | is_test | no_import_path | no_entry_points | not_in_graph
+ basis: str
+
+
+class PackageUsageModule(BaseModel):
+ """One module the file imports and how it was matched to the package."""
+
+ name: str
+ mapping: Literal["declared", "inferred"]
+
+
+class PackageUsageSite(BaseModel):
+ """One file importing the package."""
+
+ path: str
+ modules: list[PackageUsageModule]
+ symbols: list[str]
+ mapping: Literal["declared", "inferred"]
+ line: int | None = None
+ statement: str | None = None
+ component: str | None = None
+ owners: list[str]
+ #: Declared owners that are not teams, by kind (individual, unresolved): counted, never named.
+ owner_counts: dict[str, int] | None = None
+ reachability: PackageUsageReachability
+
+
+class PackageUsageComponent(BaseModel):
+ name: str
+ files: int
+ owners: list[str]
+
+
+class PackageUsageSummary(BaseModel):
+ files: int
+ components: int
+ reachability: dict[str, int]
+ inferred_files: int
+
+
+class PackageUsageResponse(BaseModel):
+ """Where one package is imported: sites, components, owner teams, reachability."""
+
+ package: str
+ ecosystem: str | None = None
+ declared: list[PackageUsageDeclaration]
+ summary: PackageUsageSummary
+ sites: list[PackageUsageSite]
+ components: list[PackageUsageComponent]
+ method: dict[str, str]
+ note: str | None = None
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index a7345a4ff..772e07462 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -2642,6 +2642,63 @@ export interface OwnershipEntry {
is_silo: boolean;
}
+export interface PackageUsageComponent {
+ name: string;
+ files: number;
+ owners: string[];
+}
+
+export interface PackageUsageDeclaration {
+ package_key: string;
+ version?: string | null;
+ declared_in: string;
+ dev?: boolean;
+}
+
+/** One module the file imports and how it was matched to the package. */
+export interface PackageUsageModule {
+ name: string;
+ mapping: "declared" | "inferred";
+}
+
+export interface PackageUsageReachability {
+ state: string;
+ basis: string;
+}
+
+/** Where one package is imported: sites, components, owner teams, reachability. */
+export interface PackageUsageResponse {
+ package: string;
+ ecosystem?: string | null;
+ declared: PackageUsageDeclaration[];
+ summary: PackageUsageSummary;
+ sites: PackageUsageSite[];
+ components: PackageUsageComponent[];
+ method: Record<string, string>;
+ note?: string | null;
+}
+
+/** One file importing the package. */
+export interface PackageUsageSite {
+ path: string;
+ modules: PackageUsageModule[];
+ symbols: string[];
+ mapping: "declared" | "inferred";
+ line?: number | null;
+ statement?: string | null;
+ component?: string | null;
+ owners: string[];
+ owner_counts?: Record<string, number> | null;
+ reachability: PackageUsageReachability;
+}
+
+export interface PackageUsageSummary {
+ files: number;
+ components: number;
+ reachability: Record<string, number>;
+ inferred_files: number;
+}
+
/** PATCH body for /lookup/notes. ``None`` clears the note. */
export interface PageNotesUpdate {
human_notes?: string | null;
diff --git a/tests/fixtures/advisories/osv-scanner.json b/tests/fixtures/advisories/osv-scanner.json
new file mode 100644
index 000000000..f66d41bad
--- /dev/null
+++ b/tests/fixtures/advisories/osv-scanner.json
@@ -0,0 +1,17 @@
+{
+ "results": [
+ {
+ "source": {"path": "requirements.txt", "type": "lockfile"},
+ "packages": [
+ {
+ "package": {"name": "requests", "version": "2.31.0", "ecosystem": "PyPI"},
+ "vulnerabilities": [{"id": "GHSA-9wx4-h78v-vm56", "aliases": ["CVE-2024-35195"], "affected": []}]
+ },
+ {
+ "package": {"name": "jinja2", "version": "3.1.2", "ecosystem": "PyPI"},
+ "vulnerabilities": [{"id": "GHSA-h5c8-rqwp-cp95", "aliases": ["CVE-2024-22195"]}]
+ }
+ ]
+ }
+ ]
+}
diff --git a/tests/fixtures/advisories/osv.json b/tests/fixtures/advisories/osv.json
new file mode 100644
index 000000000..0a9ee3543
--- /dev/null
+++ b/tests/fixtures/advisories/osv.json
@@ -0,0 +1,12 @@
+{
+ "schema_version": "1.6.0",
+ "id": "GHSA-9wx4-h78v-vm56",
+ "aliases": ["CVE-2024-35195"],
+ "summary": "Requests session verify=False persists",
+ "affected": [
+ {
+ "package": {"ecosystem": "PyPI", "name": "requests", "purl": "pkg:pypi/requests"},
+ "ranges": [{"type": "ECOSYSTEM", "events": [{"introduced": "0"}, {"fixed": "2.32.0"}]}]
+ }
+ ]
+}
diff --git a/tests/fixtures/advisories/spdx.json b/tests/fixtures/advisories/spdx.json
new file mode 100644
index 000000000..beb7724ce
--- /dev/null
+++ b/tests/fixtures/advisories/spdx.json
@@ -0,0 +1,17 @@
+{
+ "spdxVersion": "SPDX-2.3",
+ "dataLicense": "CC0-1.0",
+ "SPDXID": "SPDXRef-DOCUMENT",
+ "name": "demo",
+ "packages": [
+ {
+ "SPDXID": "SPDXRef-Package-pypi-PyYAML",
+ "name": "PyYAML",
+ "versionInfo": "6.0.1",
+ "externalRefs": [
+ {"referenceCategory": "PACKAGE-MANAGER", "referenceType": "purl", "referenceLocator": "pkg:pypi/[email protected]"}
+ ]
+ },
+ {"SPDXID": "SPDXRef-Package-requests", "name": "requests", "versionInfo": "2.31.0"}
+ ]
+}
diff --git a/tests/fixtures/advisories/syft.json b/tests/fixtures/advisories/syft.json
new file mode 100644
index 000000000..f05f62460
--- /dev/null
+++ b/tests/fixtures/advisories/syft.json
@@ -0,0 +1,10 @@
+{
+ "artifacts": [
+ {"name": "requests", "version": "2.31.0", "type": "python", "purl": "pkg:pypi/[email protected]"},
+ {"name": "urllib3", "version": "2.0.7", "type": "python", "purl": "pkg:pypi/[email protected]"},
+ {"name": "left-pad", "version": "1.3.0", "type": "npm", "purl": "pkg:npm/[email protected]"}
+ ],
+ "source": {"type": "directory", "target": "."},
+ "descriptor": {"name": "syft", "version": "1.0.0"},
+ "schema": {"version": "16.0.0"}
+}
diff --git a/tests/unit/cli/test_lazy_commands.py b/tests/unit/cli/test_lazy_commands.py
index 34d684696..116533b32 100644
--- a/tests/unit/cli/test_lazy_commands.py
+++ b/tests/unit/cli/test_lazy_commands.py
@@ -38,7 +38,7 @@ _EXPECTED_NAMES = frozenset(
"dead-code", "decision", "delete", "distill", "doc-drift", "doctor",
"events", "expand",
"export", "generate", "generate-claude-md", "health", "hook",
- "impacted-tests", "init", "login", "logout", "mcp", "next", "overlap", "plugins",
+ "impacted-tests", "init", "login", "logout", "mcp", "next", "overlap", "packages", "plugins",
"publish", "reindex", "report",
"restyle",
"risk", "saved", "savings", "search", "security", "serve", "status", "symbol",
diff --git a/tests/unit/cli/test_packages_cmd.py b/tests/unit/cli/test_packages_cmd.py
new file mode 100644
index 000000000..6cb9069cf
--- /dev/null
+++ b/tests/unit/cli/test_packages_cmd.py
@@ -0,0 +1,106 @@
+"""``repowise packages where | export | import`` against a small on-disk index."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from pathlib import Path
+
+import pytest
+from click.testing import CliRunner
+
+from repowise.cli.main import cli
+from tests.unit.core.inventory_fixture import rows, write_repo
+
+FIXTURES = Path(__file__).resolve().parents[2] / "fixtures" / "advisories"
+
+
+async def _seed(root: Path) -> None:
+ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
+
+ from repowise.core.persistence.database import init_db, resolve_db_url
+
+ engine = create_async_engine(resolve_db_url(root))
+ await init_db(engine)
+ async with async_sessionmaker(engine, class_=AsyncSession)() as session:
+ session.add_all(rows(root))
+ await session.commit()
+ await engine.dispose()
+
+
+def repo(tmp_path: Path, monkeypatch) -> Path:
+ monkeypatch.delenv("REPOWISE_DB_URL", raising=False)
+ monkeypatch.delenv("REPOWISE_DATABASE_URL", raising=False)
+ write_repo(tmp_path)
+ asyncio.run(_seed(tmp_path))
+ return tmp_path
+
+
+def _invoke(args: list[str]):
+ return CliRunner().invoke(cli, args, catch_exceptions=False)
+
+
+def test_where_json_and_text(repo):
+ result = _invoke(["packages", "where", "requests", "--path", str(repo), "--format", "json"])
+ assert result.exit_code == 0, result.output
+ doc = json.loads(result.output)
+ assert doc["summary"]["files"] == 4
+ assert doc["sites"][0]["path"] == "src/app/util.py"
+
+ text = _invoke(["packages", "where", "pypi:requests", "--path", str(repo)])
+ assert text.exit_code == 0, text.output
+ assert "src/app/util.py:2" in text.output
+ assert "1 reachable" in text.output
+ assert "1 individual(s)" in text.output # counted, never named
+ assert "someone" not in text.output
+
+
+def test_export_writes_cyclonedx(repo, tmp_path):
+ out = tmp_path / "bom.json"
+ result = _invoke(["packages", "export", "--format", "cyclonedx", "-o", str(out), "--path", str(repo)])
+ assert result.exit_code == 0, result.output
+ bom = json.loads(out.read_text(encoding="utf-8"))
+ assert bom["specVersion"] == "1.6"
+ assert {c["name"] for c in bom["components"]} == {"requests", "PyYAML", "pytest"}
+
+
+def test_import_joins_an_osv_file(repo):
+ result = _invoke(
+ ["packages", "import", str(FIXTURES / "osv.json"), "--path", str(repo), "--format", "json"]
+ )
+ assert result.exit_code == 0, result.output
+ data = json.loads(result.output)
+ assert [r["name"] for r in data["matched"]] == ["requests"]
+
+ text = _invoke(["packages", "import", str(FIXTURES / "syft.json"), "--path", str(repo)])
+ assert text.exit_code == 0, text.output
+ assert "from a syft file" in text.output
+
+
+def test_import_rejects_an_unknown_file(repo, tmp_path):
+ bad = tmp_path / "x.json"
+ bad.write_text('{"hello": 1}', encoding="utf-8")
+ result = CliRunner().invoke(cli, ["packages", "import", str(bad), "--path", str(repo)])
+ assert result.exit_code != 0
+ assert "not a Syft, SPDX, CycloneDX or OSV" in result.output
+
+
+def test_no_index_is_a_clear_error(tmp_path, monkeypatch):
+ monkeypatch.delenv("REPOWISE_DB_URL", raising=False)
+ monkeypatch.delenv("REPOWISE_DATABASE_URL", raising=False)
+ result = CliRunner().invoke(cli, ["packages", "where", "x", "--path", str(tmp_path)])
+ assert result.exit_code != 0
+ assert "run `repowise init`" in result.output
+
+
+def test_report_inventory(repo):
+ result = _invoke(["report", "inventory", str(repo), "--format", "json", "--no-workspace"])
+ assert result.exit_code == 0, result.output
+ doc = json.loads(result.output)
+ assert doc["kind"] == "inventory"
+ assert [s["id"] for s in doc["sections"]] == ["inventory"]
+
+ md = _invoke(["report", "inventory", str(repo), "--no-workspace"])
+ assert md.exit_code == 0, md.output
+ assert md.output.startswith("# Inventory: ")
diff --git a/tests/unit/core/inventory_fixture.py b/tests/unit/core/inventory_fixture.py
new file mode 100644
index 000000000..c66f12d69
--- /dev/null
+++ b/tests/unit/core/inventory_fixture.py
@@ -0,0 +1,159 @@
+"""A small indexed repository with third-party imports, for the inventory tests."""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime
+from pathlib import Path
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
+from sqlalchemy.pool import StaticPool
+
+from repowise.core.persistence.database import init_db
+from repowise.core.persistence.models import (
+ DeadCodeFinding,
+ ExternalSystem,
+ GraphEdge,
+ GraphNode,
+ Repository,
+)
+
+REPO = "repo1"
+_NOW = datetime(2026, 10, 1, tzinfo=UTC)
+
+CATALOG = """\
+apiVersion: backstage.io/v1alpha1
+kind: Component
+metadata:
+ name: app
+ annotations:
+ repowise.dev/paths: src/app/**
+spec: {type: service, lifecycle: production, owner: group:default/platform}
+---
+apiVersion: backstage.io/v1alpha1
+kind: Component
+metadata:
+ name: jobs
+ annotations:
+ repowise.dev/paths: src/jobs/**
+spec: {type: service, lifecycle: production}
+"""
+
+SOURCES = {
+ "src/app/main.py": "from src.app import util\n",
+ "src/app/util.py": "import os\nfrom requests import get\nfrom requests.compat import urljoin\n",
+ # A comment naming the module is not an import statement.
+ "src/jobs/worker.py": "# import requests directly\nfrom requests.adapters import HTTPAdapter\n"
+ "import yaml\n",
+ "src/old/legacy.py": "import requests\n",
+ "tests/test_util.py": "import requests\n",
+}
+
+
+def write_repo(root: Path) -> None:
+ for rel, text in SOURCES.items():
+ (root / rel).parent.mkdir(parents=True, exist_ok=True)
+ (root / rel).write_text(text, encoding="utf-8")
+ (root / ".repowise").mkdir(exist_ok=True)
+ (root / ".repowise" / "components.yaml").write_text(CATALOG, encoding="utf-8")
+ (root / ".github").mkdir(exist_ok=True)
+ (root / ".github" / "CODEOWNERS").write_text(
+ "/src/jobs/ @acme/batch-team\n/src/old/ @someone\n", encoding="utf-8"
+ )
+
+
+def rows(root: Path) -> list:
+ out: list = [
+ Repository(
+ id=REPO,
+ name="demo",
+ local_path=str(root),
+ settings_json="{}",
+ created_at=_NOW,
+ updated_at=_NOW,
+ ),
+ ExternalSystem(
+ id=1, repository_id=REPO, name="requests", ecosystem="pypi",
+ version=">=2.31", declared_in="pyproject.toml",
+ ),
+ ExternalSystem(
+ id=2, repository_id=REPO, name="PyYAML", ecosystem="pypi",
+ version="6.0", declared_in="pyproject.toml",
+ ),
+ ExternalSystem(
+ id=3, repository_id=REPO, name="pytest", ecosystem="pypi",
+ declared_in="pyproject.toml", is_dev_dep=True,
+ ),
+ # The same distribution spelled another way in a second manifest.
+ ExternalSystem(
+ id=4, repository_id=REPO, name="pyyaml", ecosystem="pypi",
+ version="6.0.1", declared_in="requirements.txt",
+ ),
+ ] # fmt: skip
+ for path in SOURCES:
+ out.append(
+ GraphNode(
+ repository_id=REPO,
+ node_id=path,
+ node_type="file",
+ language="python",
+ is_entry_point=path == "src/app/main.py",
+ is_test=path.startswith("tests/"),
+ )
+ )
+ for node_id, system in (
+ ("external:requests", 1),
+ ("external:requests.adapters", 1),
+ ("external:yaml", None),
+ ("external:requests.compat", None),
+ ):
+ out.append(
+ GraphNode(
+ repository_id=REPO,
+ node_id=node_id,
+ node_type="external",
+ external_system_id=system,
+ )
+ )
+ for src, dst, names in (
+ ("src/app/main.py", "src/app/util.py", '["util"]'),
+ ("src/app/util.py", "external:requests", '["get"]'),
+ ("src/jobs/worker.py", "external:requests.adapters", '["HTTPAdapter"]'),
+ ("src/jobs/worker.py", "external:yaml", "[]"),
+ ("src/app/util.py", "external:requests.compat", '["urljoin"]'),
+ ("src/old/legacy.py", "external:requests", "[]"),
+ ("tests/test_util.py", "external:requests", "[]"),
+ ):
+ out.append(
+ GraphEdge(
+ repository_id=REPO,
+ source_node_id=src,
+ target_node_id=dst,
+ imported_names_json=names,
+ edge_type="imports",
+ )
+ )
+ out.append(
+ DeadCodeFinding(
+ repository_id=REPO, kind="unreachable_file", file_path="src/old/legacy.py",
+ confidence=0.9,
+ )
+ ) # fmt: skip
+ return out
+
+
+async def session(tmp_path):
+ engine = create_async_engine(
+ "sqlite+aiosqlite:///:memory:",
+ connect_args={"check_same_thread": False},
+ poolclass=StaticPool,
+ )
+ await init_db(engine)
+ write_repo(tmp_path)
+ factory = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
+ async with factory() as s:
+ s.add_all(rows(tmp_path))
+ await s.commit()
+ yield s
+ await engine.dispose()
diff --git a/tests/unit/core/test_advisory_source.py b/tests/unit/core/test_advisory_source.py
new file mode 100644
index 000000000..4a876f244
--- /dev/null
+++ b/tests/unit/core/test_advisory_source.py
@@ -0,0 +1,154 @@
+"""The ``advisory-source`` seam: reading Syft, SPDX, CycloneDX and OSV files, and the join."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from repowise.core.inventory.advisories import (
+ FileAdvisorySource,
+ advisory_sources,
+ from_purl,
+ join_usage,
+ parse_document,
+)
+from tests.unit.core.inventory_fixture import REPO, session # noqa: F401 (fixture)
+
+FIXTURES = Path(__file__).resolve().parents[2] / "fixtures" / "advisories"
+
+
+def _read(name: str):
+ return FileAdvisorySource().read(str(FIXTURES / name))
+
+
+def test_local_file_source_is_the_default():
+ assert advisory_sources.default == "file"
+ assert isinstance(advisory_sources.get(), FileAdvisorySource)
+
+
+def test_syft():
+ doc = _read("syft.json")
+ assert doc.format == "syft"
+ assert [(m.ecosystem, m.name, m.version) for m in doc.mentions] == [
+ ("pypi", "requests", "2.31.0"),
+ ("pypi", "urllib3", "2.0.7"),
+ ("npm", "left-pad", "1.3.0"),
+ ]
+
+
+def test_spdx_takes_the_purl_and_keeps_packages_without_one():
+ doc = _read("spdx.json")
+ assert doc.format == "spdx"
+ assert [(m.ecosystem, m.name, m.version) for m in doc.mentions] == [
+ ("pypi", "pyyaml", "6.0.1"),
+ (None, "requests", "2.31.0"),
+ ]
+
+
+def test_osv_record_and_scanner_output():
+ record = _read("osv.json")
+ assert record.format == "osv"
+ (m,) = record.mentions
+ assert (m.ecosystem, m.name, m.version) == ("pypi", "requests", None)
+ assert m.advisories[0].id == "GHSA-9wx4-h78v-vm56"
+ assert m.advisories[0].aliases == ("CVE-2024-35195",)
+
+ scanner = _read("osv-scanner.json")
+ assert [(m.name, m.version, [a.id for a in m.advisories]) for m in scanner.mentions] == [
+ ("requests", "2.31.0", ["GHSA-9wx4-h78v-vm56"]),
+ ("jinja2", "3.1.2", ["GHSA-h5c8-rqwp-cp95"]),
+ ]
+ # A list of records and an API ``vulns`` page read the same way.
+ data = json.loads((FIXTURES / "osv.json").read_text(encoding="utf-8"))
+ assert parse_document([data]).mentions == record.mentions
+ assert parse_document({"vulns": [data]}).mentions == record.mentions
+
+
+def test_cyclonedx_input_reads_nested_components():
+ doc = parse_document(
+ {
+ "bomFormat": "CycloneDX",
+ "specVersion": "1.6",
+ "components": [
+ {
+ "type": "library",
+ "name": "a",
+ "purl": "pkg:npm/%40s/[email protected]",
+ "components": [{"type": "library", "name": "b", "version": "2"}],
+ }
+ ],
+ }
+ )
+ assert [(m.ecosystem, m.name, m.version) for m in doc.mentions] == [
+ ("npm", "@s/a", "1.0.0"),
+ (None, "b", "2"),
+ ]
+
+
+def test_unknown_documents_are_refused(tmp_path):
+ with pytest.raises(ValueError):
+ parse_document({"hello": "world"})
+ bad = tmp_path / "x.json"
+ bad.write_text("{nope", encoding="utf-8")
+ with pytest.raises(ValueError):
+ FileAdvisorySource().read(str(bad))
+ with pytest.raises(ValueError, match="cannot be read"):
+ FileAdvisorySource().read(str(tmp_path / "missing.json"))
+ with pytest.raises(ValueError, match="cannot be read"):
+ FileAdvisorySource().read(str(tmp_path)) # a directory
+ deep = tmp_path / "deep.json"
+ deep.write_text("[" * 100_000 + "]" * 100_000, encoding="utf-8")
+ with pytest.raises(ValueError, match="nested too deeply"):
+ FileAdvisorySource().read(str(deep))
+
+
+def test_from_purl():
+ assert from_purl("pkg:maven/org.apache/[email protected]") == (
+ "maven",
+ "org.apache:commons-text",
+ "1.9",
+ )
+ assert from_purl("pkg:golang/github.com/x/[email protected]?type=module") == (
+ "go",
+ "github.com/x/y",
+ "v1.2.0",
+ )
+ assert from_purl("not a purl") == (None, None, None)
+ # A raw npm scope keeps its "@"; the version is after the last "@".
+ assert from_purl("pkg:npm/@scope/[email protected]") == ("npm", "@scope/pkg", "1.0.0")
+ assert from_purl("pkg:npm/@scope/pkg") == ("npm", "@scope/pkg", None)
+
+
+async def test_join_by_name_reports_usage_and_unfound_advisories(session, tmp_path): # noqa: F811
+ result = await join_usage(session, REPO, tmp_path, str(FIXTURES / "osv-scanner.json"))
+ assert result["format"] == "osv"
+ assert result["mentions"] == 2
+ (row,) = result["matched"]
+ assert row["name"] == "requests" and row["declared"] is True
+ assert [a["id"] for a in row["advisories"]] == ["GHSA-9wx4-h78v-vm56"]
+ assert row["summary"]["reachability"]["reachable"] == 1
+ assert {s["path"] for s in row["sites"]} >= {"src/app/util.py"}
+ assert result["not_found"] == 1
+ assert [r["name"] for r in result["not_found_with_advisories"]] == ["jinja2"]
+ assert "not evaluated" in result["method"]
+
+
+async def test_join_passes_declared_packages_to_a_plugged_source(session, tmp_path): # noqa: F811
+ from repowise.core.inventory.advisories import PackageMention, SourceDocument
+
+ seen = {}
+
+ class Feed:
+ def read(self, location, *, packages=()):
+ seen["packages"] = list(packages)
+ return SourceDocument("osv", (PackageMention("requests", "pypi"),))
+
+ advisory_sources.register("test-feed", Feed())
+ try:
+ result = await join_usage(session, REPO, tmp_path, "ignored", source="test-feed")
+ finally:
+ advisory_sources._impls.pop("test-feed")
+ assert ("pypi", "requests") in seen["packages"]
+ assert [r["name"] for r in result["matched"]] == ["requests"]
diff --git a/tests/unit/core/test_package_usage.py b/tests/unit/core/test_package_usage.py
new file mode 100644
index 000000000..912094dcf
--- /dev/null
+++ b/tests/unit/core/test_package_usage.py
@@ -0,0 +1,223 @@
+"""Package usage, the component inventory and the CycloneDX export, over a small index."""
+
+from __future__ import annotations
+
+from repowise.core.inventory.components import component_inventory
+from repowise.core.inventory.cyclonedx import cyclonedx_bom, purl
+from repowise.core.inventory.usage import package_usage, package_usages, parse_query
+from tests.unit.core.inventory_fixture import REPO, session # noqa: F401 (fixture)
+
+
+def _by_path(doc):
+ return {s["path"]: s for s in doc["sites"]}
+
+
+async def test_sites_carry_line_component_owners_and_reachability(session, tmp_path): # noqa: F811
+ doc = await package_usage(session, REPO, tmp_path, "requests")
+ assert [d["package_key"] for d in doc["declared"]] == ["pypi:requests"]
+ sites = _by_path(doc)
+ assert list(sites) == [
+ "src/app/util.py",
+ "src/jobs/worker.py",
+ "src/old/legacy.py",
+ "tests/test_util.py",
+ ]
+ util = sites["src/app/util.py"]
+ assert util["line"] == 2 and util["statement"] == "from requests import get"
+ # requests.compat has no declaration link: it stays inferred, and the
+ # declared module alone gives the site its symbols and line.
+ assert util["modules"] == [
+ {"name": "requests", "mapping": "declared"},
+ {"name": "requests.compat", "mapping": "inferred"},
+ ]
+ assert util["symbols"] == ["get"]
+ assert util["component"] == "app"
+ assert util["owners"] == ["platform"]
+ assert util["mapping"] == "declared"
+ assert util["reachability"] == {"state": "reachable", "basis": "import_graph"}
+
+ worker = sites["src/jobs/worker.py"]
+ assert worker["modules"] == [{"name": "requests.adapters", "mapping": "declared"}]
+ assert worker["line"] == 2 # line 1 is a comment that names requests
+ assert worker["owners"] == ["batch-team"]
+ # Nothing imports it, but no dead-code finding says so: unknown, not unreachable.
+ assert worker["reachability"] == {"state": "unknown", "basis": "no_import_path"}
+
+ legacy = sites["src/old/legacy.py"]
+ assert legacy["reachability"] == {"state": "unreachable", "basis": "dead_code"}
+ assert legacy["owners"] == [] # an individual CODEOWNERS entry is never named
+ assert legacy["owner_counts"] == {"individual": 1} # but it is counted
+ assert "owner_counts" not in util
+ assert legacy["component"] == "src" # the derived top-level directory
+
+ assert sites["tests/test_util.py"]["reachability"]["state"] == "test"
+ assert doc["summary"]["reachability"] == {
+ "reachable": 1,
+ "unreachable": 1,
+ "test": 1,
+ "unknown": 1,
+ }
+ assert [c["name"] for c in doc["components"]] == ["app", "jobs", "src", "tests"]
+
+
+async def test_import_name_alone_is_inferred_and_ecosystem_scoped(session, tmp_path): # noqa: F811
+ yaml, yaml_npm, pyyaml = await package_usages(
+ session, REPO, tmp_path, [("yaml", None), ("yaml", "npm"), ("pyyaml", "pypi")]
+ )
+ assert [(s["path"], s["mapping"]) for s in yaml["sites"]] == [("src/jobs/worker.py", "inferred")]
+ assert yaml["sites"][0]["line"] == 3
+ assert "No manifest declares" in yaml["note"]
+ assert yaml_npm["sites"] == [] # a Python file's import is not an npm package
+ # Declared under its distribution name (in two spellings), imported as
+ # ``yaml``: no link, said so.
+ assert [d["package_key"] for d in pyyaml["declared"]] == ["pypi:PyYAML", "pypi:pyyaml"]
+ assert pyyaml["sites"] == []
+ assert "import name may differ" in pyyaml["note"]
+
+
+def test_parse_query():
+ assert parse_query("npm:@scope/pkg") == ("@scope/pkg", "npm")
+ assert parse_query("requests") == ("requests", None)
+ assert parse_query("com.google:guava") == ("com.google:guava", None)
+
+
+async def test_component_inventory(session, tmp_path): # noqa: F811
+ inv = await component_inventory(session, REPO, tmp_path)
+ comps = {c["name"]: c for c in inv["components"]}
+ app = comps["app"]
+ assert app["owners"]["teams"] == [{"team": "platform", "files": 2}]
+ assert app["languages"] == {"python": 2}
+ assert app["entry_points"] == ["src/app/main.py"]
+ assert app["packages"] == [{"package_key": "pypi:requests", "files": 1}]
+ assert comps["jobs"]["owners"]["teams"] == [{"team": "batch-team", "files": 1}]
+ assert inv["packages"]["declared_not_imported"] == ["pypi:pytest", "pypi:pyyaml"]
+ assert inv["packages"]["declared"] == 3 # PyYAML and pyyaml are one package
+ text = repr(inv)
+ assert "someone" not in text # individuals never appear
+
+
+# Keys the CycloneDX 1.6 JSON schema allows (bom-1.6.schema.json, additionalProperties false).
+_OCCURRENCE_KEYS = {"bom-ref", "location", "line", "offset", "symbol", "additionalContext"}
+_EVIDENCE_KEYS = {"identity", "occurrences", "callstack", "licenses", "copyright"}
+_COMPONENT_TYPES = {
+ "application", "framework", "library", "container", "platform", "operating-system",
+ "device", "device-driver", "firmware", "file", "machine-learning-model", "data",
+ "cryptographic-asset",
+} # fmt: skip
+_COMPONENT_KEYS = {
+ "type", "mime-type", "bom-ref", "supplier", "manufacturer", "authors", "author",
+ "publisher", "group", "name", "version", "description", "scope", "hashes", "licenses",
+ "copyright", "cpe", "purl", "omniborId", "swhid", "swid", "modified", "pedigree",
+ "externalReferences", "components", "evidence", "releaseNotes", "modelCard", "data",
+ "cryptoProperties", "properties", "tags", "signature",
+} # fmt: skip
+_TOP_KEYS = {
+ "$schema", "bomFormat", "specVersion", "serialNumber", "version", "metadata",
+ "components", "services", "externalReferences", "dependencies", "compositions",
+ "vulnerabilities", "annotations", "formulation", "declarations", "definitions",
+ "properties", "signature",
+} # fmt: skip
+
+
+async def test_cyclonedx_shape_matches_the_1_6_schema_keys(session, tmp_path): # noqa: F811
+ import re
+
+ bom = await cyclonedx_bom(session, REPO, tmp_path, "demo")
+ assert set(bom) <= _TOP_KEYS
+ assert bom["bomFormat"] == "CycloneDX" and bom["specVersion"] == "1.6"
+ assert re.fullmatch(
+ r"urn:uuid:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",
+ bom["serialNumber"],
+ )
+ assert set(bom["metadata"]["tools"]) == {"components"}
+ refs = [c["bom-ref"] for c in bom["components"]]
+ assert len(refs) == len(set(refs))
+ for comp in bom["components"]:
+ assert set(comp) <= _COMPONENT_KEYS
+ assert comp["type"] in _COMPONENT_TYPES and comp["name"]
+ assert "version" not in comp and "hashes" not in comp # not an SBOM
+ for prop in comp["properties"]:
+ assert set(prop) == {"name", "value"} and isinstance(prop["value"], str)
+ if "evidence" in comp:
+ assert set(comp["evidence"]) <= _EVIDENCE_KEYS
+ for occ in comp["evidence"]["occurrences"]:
+ assert set(occ) <= _OCCURRENCE_KEYS and "location" in occ
+ assert isinstance(occ.get("line", 0), int) and occ.get("line", 0) >= 0
+
+ by_ref = {c["bom-ref"]: c for c in bom["components"]}
+ req = by_ref["pypi:requests"]
+ assert req["purl"] == "pkg:pypi/requests"
+ occ = {o["location"]: o for o in req["evidence"]["occurrences"]}
+ assert occ["src/app/util.py"] == {
+ "location": "src/app/util.py",
+ "line": 2,
+ "symbol": "get",
+ "additionalContext": "from requests import get",
+ }
+ assert {"name": "repowise:declared_version", "value": ">=2.31"} in req["properties"]
+ # Only declared modules become occurrences, from the declared statement.
+ assert len(req["evidence"]["occurrences"]) == 4
+ # Two spellings of one distribution are one component.
+ yaml = by_ref["pypi:pyyaml"]
+ assert yaml["name"] == "PyYAML" and yaml["purl"] == "pkg:pypi/pyyaml"
+ assert [p["value"] for p in yaml["properties"] if p["name"] == "repowise:declared_in"] == [
+ "pyproject.toml",
+ "requirements.txt",
+ ]
+ assert "evidence" not in yaml # declared, no linked import
+ assert sum(1 for c in bom["components"] if c["bom-ref"].startswith("pypi:pyyaml")) == 1
+
+
+def test_purl():
+ assert purl("npm", "@scope/pkg") == "pkg:npm/%40scope/pkg"
+ assert purl("pypi", "Foo_Bar") == "pkg:pypi/foo-bar"
+ assert purl("maven", "com.google.guava:guava") == "pkg:maven/com.google.guava/guava"
+ assert purl("go", "github.com/x/y") == "pkg:golang/github.com/x/y"
+ assert purl("bazel", "x") is None
+ assert purl("maven", "guava") is None # no group
+
+
+
+async def test_only_open_served_dead_code_findings_mark_a_file_unreachable(session, tmp_path): # noqa: F811
+ from sqlalchemy import update
+
+ from repowise.core.persistence.models import DeadCodeFinding
+
+ await session.execute(update(DeadCodeFinding).values(status="acknowledged"))
+ await session.commit()
+ doc = await package_usage(session, REPO, tmp_path, "requests")
+ legacy = _by_path(doc)["src/old/legacy.py"]
+ assert legacy["reachability"] == {"state": "unknown", "basis": "no_import_path"}
+
+
+def test_import_lines_skip_comments_and_read_go_blocks(tmp_path):
+ from repowise.core.inventory.usage import _import_lines
+
+ src = tmp_path / "main.go"
+ src.write_text(
+ 'package main\n// import "fmt" in a comment\nimport (\n\t"fmt"\n\t// "os"\n'
+ '\t"github.com/x/y"\n)\nvar s = "import fmt"\n',
+ encoding="utf-8",
+ )
+ assert _import_lines(src) == [(4, '"fmt"'), (6, '"github.com/x/y"')]
+ js = tmp_path / "a.js"
+ js.write_text("// require('lodash')\nconst _ = require('lodash')\n", encoding="utf-8")
+ assert _import_lines(js) == [(2, "const _ = require('lodash')")]
+
+
+async def test_a_resolved_dynamic_load_reaches_a_file(session, tmp_path): # noqa: F811
+ from repowise.core.persistence.models import GraphEdge
+
+ # A "module:attr" string table in an entry point loads the file lazily.
+ session.add(
+ GraphEdge(
+ repository_id=REPO,
+ source_node_id="src/app/main.py",
+ target_node_id="src/jobs/worker.py",
+ edge_type="dynamic_uses",
+ )
+ )
+ await session.commit()
+ doc = await package_usage(session, REPO, tmp_path, "requests")
+ worker = _by_path(doc)["src/jobs/worker.py"]
+ assert worker["reachability"] == {"state": "reachable", "basis": "import_graph"}
diff --git a/tests/unit/core/test_report_inventory.py b/tests/unit/core/test_report_inventory.py
new file mode 100644
index 000000000..b0f77b413
--- /dev/null
+++ b/tests/unit/core/test_report_inventory.py
@@ -0,0 +1,29 @@
+"""The ``inventory`` report section over the package-usage fixture index."""
+
+from __future__ import annotations
+
+from repowise.core.report.build import available_sections, collect_repo
+from repowise.core.report.model import ReportContext
+from tests.unit.core.inventory_fixture import REPO, session # noqa: F401 (fixture)
+
+
+async def test_inventory_report_section(session, tmp_path): # noqa: F811
+ sections = [(n, s) for n, s in available_sections() if n == "inventory"]
+ _entry, (section,) = await collect_repo(ReportContext(session, REPO, tmp_path), sections)
+ checks = {c["name"]: c for c in section["checks"]}
+ assert checks["inventory"]["basis"] == "measured"
+ assert "declared, no linked import: pypi:pyyaml" in checks["inventory"]["details"]
+
+ summary = checks["inventory:components"]
+ assert summary["score"] is None # descriptive, never scored
+ assert "with a declared owner team: 2" in summary["reason"]
+ # Every component's row stays in the JSON data.
+ app = summary["data"]["components"]["app"]
+ assert app["entry_points"] == ["src/app/main.py"]
+ assert app["packages"] == [{"package_key": "pypi:requests", "files": 1}]
+
+ # Only components with no declared owner team get an item of their own.
+ assert "inventory:app" not in checks and "inventory:jobs" not in checks
+ src = checks["inventory:src"]
+ assert "no declared owner team" in src["reason"]
+ assert "package: pypi:requests (1 file(s))" in src["details"]
diff --git a/tests/unit/server/mcp/test_packages_mcp.py b/tests/unit/server/mcp/test_packages_mcp.py
new file mode 100644
index 000000000..1eccc9ecd
--- /dev/null
+++ b/tests/unit/server/mcp/test_packages_mcp.py
@@ -0,0 +1,64 @@
+"""``package:<name>`` targets in get_context."""
+
+from __future__ import annotations
+
+import pytest
+
+
+async def _seed(session, tmp_path) -> None:
+ from repowise.core.persistence.models import ExternalSystem, GraphEdge, GraphNode
+
+ (tmp_path / "src/db").mkdir(parents=True, exist_ok=True)
+ (tmp_path / "src/db/models.py").write_text("import sqlalchemy\n", encoding="utf-8")
+ session.add_all(
+ [
+ ExternalSystem(
+ id=10,
+ repository_id="repo1",
+ name="sqlalchemy",
+ ecosystem="pypi",
+ declared_in="pyproject.toml",
+ ),
+ GraphNode(
+ repository_id="repo1",
+ node_id="external:sqlalchemy",
+ node_type="external",
+ external_system_id=10,
+ ),
+ GraphEdge(
+ repository_id="repo1",
+ source_node_id="src/db/models.py",
+ target_node_id="external:sqlalchemy",
+ imported_names_json="[]",
+ ),
+ ]
+ )
+ await session.commit()
+
+
+async def test_package_target_lists_import_sites(setup_mcp, session, tmp_path):
+ from repowise.server.mcp_server import get_context
+
+ await _seed(session, tmp_path)
+ result = await get_context(targets=["package:sqlalchemy", "package:"])
+ card = result["targets"]["package:sqlalchemy"]
+ assert card["type"] == "package"
+ assert [d["package_key"] for d in card["declared"]] == ["pypi:sqlalchemy"]
+ (site,) = card["sites"]
+ assert site["path"] == "src/db/models.py"
+ assert site["line"] == 1
+ assert site["mapping"] == "declared"
+ # The fixture's entry point src/auth/service.py imports src/db/models.py.
+ assert site["reachability"] == {"state": "reachable", "basis": "import_graph"}
+ assert card["summary"]["files"] == 1
+ assert "error" in result["targets"]["package:"]
+
+
+async def test_default_get_context_has_no_package_block(setup_mcp, session, tmp_path):
+ from repowise.server.mcp_server import get_context
+
+ await _seed(session, tmp_path)
+ result = await get_context(targets=["src/db/models.py"])
+ assert "package" not in str(sorted(result["targets"]["src/db/models.py"]))
diff --git a/tests/unit/server/test_external_systems.py b/tests/unit/server/test_external_systems.py
index 1e6d04f88..2edb836d0 100644
--- a/tests/unit/server/test_external_systems.py
+++ b/tests/unit/server/test_external_systems.py
@@ -778,3 +778,58 @@ async def test_relationship_graph_query_count_is_constant(
# declared packages. Composition moved to a session-free fold, so the third
# read replaces the aggregate the graph query used to push down.
assert len(selects) == 3
+
+
+async def test_usage_lists_import_sites_with_line_and_reachability(
+ client: AsyncClient, app, tmp_path
+) -> None:
+ repo = await create_test_repo(client, tmp_path)
+ root = tmp_path / "test-repo"
+ (root / "src").mkdir()
+ (root / "src/app.py").write_text("import os\nimport fastapi\n", encoding="utf-8")
+ async with get_session(app.state.session_factory) as session:
+ system = ExternalSystem(
+ repository_id=repo["id"],
+ name="fastapi",
+ ecosystem="pypi",
+ declared_in="pyproject.toml",
+ )
+ session.add(system)
+ await session.flush()
+ session.add_all(
+ [
+ GraphNode(
+ repository_id=repo["id"],
+ node_id="src/app.py",
+ node_type="file",
+ language="python",
+ is_entry_point=True,
+ ),
+ GraphNode(
+ repository_id=repo["id"],
+ node_id="external:fastapi",
+ node_type="external",
+ external_system_id=system.id,
+ ),
+ GraphEdge(
+ repository_id=repo["id"],
+ source_node_id="src/app.py",
+ target_node_id="external:fastapi",
+ imported_names_json="[]",
+ ),
+ ]
+ )
+
+ resp = await client.get(f"/api/repos/{repo['id']}/external-systems/pypi:fastapi/usage")
+ assert resp.status_code == 200, resp.text
+ data = resp.json()
+ assert data["ecosystem"] == "pypi"
+ (site,) = data["sites"]
+ assert (site["path"], site["line"], site["mapping"]) == ("src/app.py", 2, "declared")
+ assert site["reachability"] == {"state": "reachable", "basis": "import_graph"}
+
+ bare = await client.get(f"/api/repos/{repo['id']}/external-systems/fastapi/usage")
+ assert bare.json()["summary"]["files"] == 1
+ missing = await client.get("/api/repos/nope/external-systems/fastapi/usage")
+ assert missing.status_code == 404