"""system-map — maps a monorepo's packages/services, which ones are
widely depended-on "commons," which own an API contract (`.proto`
— including its real gRPC `service`/`rpc` definitions — OpenAPI/Swagger,
GraphQL, Thrift, WSDL, Avro, or AsyncAPI), and how they really connect —
a system-level companion to `repo-map`'s single-directory view.
**Unlike most of this bundle, not a 1:1 port of one PinkyAI engine
module** — there's no cross-package system-mapper in the engine to port
from (`repo-map`/`dependency-graph` both work inside a single directory
or crate). Built directly from a request to see a whole monorepo's shape
in one picture, applying the same approach as this bundle's other
diagram/graph skills one level up: walk real, declared structure — not
prose, not a guess — and render it.
**Real, declared structure only, same "first-party edges only" honesty
as `dependency-graph`/`dependency-diagram`.** Understands five workspace
managers' actual manifests — specifically the ones with a real,
documented multi-package "workspace" convention this skill's whole
approach depends on existing. Most of `repo-map`'s 50 file-extension
languages have no such convention at all (see "Honest scope" below for
why this skill's ecosystem list is necessarily narrower than that one's
language list):
- npm/yarn/pnpm: a root `package.json`'s `workspaces` field, or a
`pnpm-workspace.yaml`'s `packages:` globs (both support `!exclude`
patterns). A cross-package edge is a `dependencies`/`devDependencies`/
`peerDependencies`/`optionalDependencies` entry whose name matches
another discovered package's real `name` field.
- Cargo: the root `Cargo.toml`'s `[workspace] members` (+ `exclude`). A
cross-crate edge is a dependency-table entry with a real
`path = "..."` value resolving to another discovered member.
- Python: a root `pyproject.toml`'s `[tool.uv.workspace]` `members` (+
`exclude`) — uv's real workspace mechanism, the only Python tool with
an npm/Cargo-style explicit member list. A cross-package edge is a
`[tool.uv.sources]` or `[tool.poetry.dependencies]` entry with a real
`path = "..."` value.
- Go: a root `go.work`'s `use` directives (Go's own workspace mechanism,
Go 1.18+). A cross-module edge is a `replace <module> => <path>`
directive whose target is a real local filesystem path, not a version
pin.
- Gradle (Java/Kotlin): a root `settings.gradle`/`settings.gradle.kts`'s
`include(...)` calls, each colon-path mapped to its default nested
directory. A cross-module edge is a `project(':path')` reference inside
another module's `build.gradle`/`build.gradle.kts`.
Each ecosystem without an explicit workspace manifest present (npm,
Python, Go) falls back to an unscoped scan for every manifest file under
the root — a different, less precise discovery mode, reported as such in
`--json`'s `discovery` field. Cargo and Gradle have no such fallback: no
`[workspace]`/no `include(...)` calls means no siblings to map, honestly
reported rather than guessed at.
"Commons" = a package **2 or more** other discovered packages declare a
real dependency on (`--commons-threshold` to change it) — a measured
fan-in signal, not a name guess. "Contracts" = any `.proto`, OpenAPI/
Swagger, GraphQL, Thrift, WSDL, Avro, or AsyncAPI file found anywhere
under the root, attributed to whichever discovered package's directory
contains it (the deepest/most specific containing package wins; a
contract with no containing package is still reported, just as
"unowned"). A `.proto` file's real `service Name { rpc Method(...) ...
}` blocks are parsed too — genuine gRPC service/method names, not just
"this file exists," surfaced in `--json` output and as a service count
on the owning package's diagram node.
Two more real signals, both read from data this skill already has in
hand rather than new heuristic text-scanning: **technology tags** —
each package's own already-declared dependency names, checked against a
curated, deliberately non-exhaustive lookup of well-known queue/
database/transport libraries (`categorize_dependencies`'s docstring has
the full reasoning) — and **infrastructure resources** — real CDK
TypeScript `new Queue(this, "Id", ...)`-shaped construct declarations,
scoped to npm packages that themselves declare a dependency on
`aws-cdk-lib` (see `find_infra_resources`'s docstring). Both stop at
"this package's manifest/infra code declares X" — see "Honest scope"
below for exactly where that line is drawn, and
`../../docs/research/system-map-runtime-topology-feasibility.md` for the
fuller research behind that line (Kafka topic *names*, live API traffic,
and DB schema/query analysis are deliberately out — see that doc for
why).
**Honest scope — read before treating this as a live call graph.** This
maps declared, build-time dependencies and contract-file *ownership*,
never runtime traffic: it cannot tell you "service A calls service B's
`/v1/scan` endpoint at 2am," only "service A's manifest declares a
dependency on package B, and package B owns this OpenAPI spec (or this
gRPC service)." Every manifest reader here is a small, line-based
extractor for the *common* form each format conventionally takes (see
the docstrings on `_pnpm_workspace_globs`, `_toml_section`,
`_toml_path_values`, `_go_work_members`, `_gradle_settings_members` for
exactly what each does and doesn't handle) — not a real YAML/TOML/Go-
tooling/Gradle-script parser, the same "heuristic, not a grammar"
honesty as `repo-map`'s per-line symbol extraction. Ecosystems with no
real multi-package workspace convention at all — Ruby, PHP, Java/Maven,
and the long tail of `repo-map`'s single-file-oriented languages — aren't
guessed at; see README's honest-scope section for the full list.
Technology tags and infrastructure resources have their own, narrower
honest-scope notes: tags come from a curated lookup table, not a claim
to recognize every real queue/database/transport library that exists;
infra resources are CDK TypeScript only today (Terraform/CloudFormation
are real, documented future candidates, not silently unsupported by
oversight), matched by construct class name rather than by resolving its
actual `aws-cdk-lib` import.
Pure stdlib, no network call.
"""
from __future__ import annotations
import argparse
import json
import re
import sys
from dataclasses import dataclass, field
from pathlib import Path
SKIPPED_DIR_NAMES = {
".git", "node_modules", "target", "dist", "build", ".venv", "venv",
"__pycache__", ".next", ".cache", ".gradle",
}
_DEP_TABLE_NAMES = ("dependencies", "dev-dependencies", "build-dependencies")
_NPM_DEP_FIELDS = ("dependencies", "devDependencies", "peerDependencies", "optionalDependencies")
_PYTHON_PATH_TABLE_NAMES = ("tool.uv.sources", "tool.poetry.dependencies")
@dataclass
class Package:
name: str
kind: str
dir: str
manifest: str
@dataclass
class Edge:
source: str
target: str
manager: str
@dataclass
class GrpcService:
name: str
methods: list[str]
@dataclass
class Contract:
path: str
kind: str
owner: str | None
services: list[GrpcService] = field(default_factory=list)
@dataclass
class InfraResource:
kind: str
logical_id: str
path: str
owner: str
def _rel(root: Path, path: Path) -> str:
return path.resolve().relative_to(root.resolve()).as_posix()
def _read_json(path: Path) -> dict | None:
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, UnicodeDecodeError, json.JSONDecodeError):
return None
return data if isinstance(data, dict) else None
def _npm_workspace_globs(root: Path) -> list[str]:
"""Real npm/yarn `workspaces` globs from the root `package.json`, if
any — supports both the plain-array form and yarn's
`{packages: [...], nohoist: [...]}` object form. `[]` if the file or
field is absent, unreadable, or not a list of strings.
"""
data = _read_json(root / "package.json")
if data is None:
return []
workspaces = data.get("workspaces")
if isinstance(workspaces, list):
return [g for g in workspaces if isinstance(g, str)]
if isinstance(workspaces, dict):
packages = workspaces.get("packages")
if isinstance(packages, list):
return [g for g in packages if isinstance(g, str)]
return []
def _pnpm_workspace_globs(root: Path) -> list[str]:
"""Real pnpm-workspace.yaml `packages:` globs — a small line-based
reader for the conventional block-sequence-of-strings form
(`packages:` followed by one ` - 'glob'` line per entry, `#`
comments stripped), **not a general YAML parser**. A `packages:` key
written any other way (a flow sequence `packages: [a, b]`, YAML
anchors/aliases, a value on the same line as the key) is silently not
understood — this matches this bundle's existing honesty convention
for a heuristic reader rather than a real parser.
"""
try:
lines = (root / "pnpm-workspace.yaml").read_text(encoding="utf-8").splitlines()
except OSError:
return []
globs: list[str] = []
in_packages = False
for raw_line in lines:
line = raw_line.split("#", 1)[0].rstrip()
if not in_packages:
if line.strip() == "packages:":
in_packages = True
continue
if not line.strip():
continue
if line[:1] in (" ", "\t") and line.lstrip().startswith("-"):
item = line.lstrip()[1:].strip().strip("'\"")
if item:
globs.append(item)
else:
break
return globs
def _resolve_workspace_dirs(root: Path, globs: list[str]) -> list[Path]:
"""Expands workspace glob patterns (`pathlib.Path.glob` syntax: `*`,
`**`, `?`, `[seq]`, and a plain literal path with no wildcard at all
— Go's `go.work` `use` directives are conventionally exact paths, not
globs, and `Path.glob` resolves those correctly too) to real
directories under `root`, honoring a leading `!` as a pnpm/yarn-style
exclusion applied in listed order — same semantics both tools use. An
unmatched or malformed pattern contributes nothing rather than
raising.
"""
included: list[Path] = []
excluded: set[Path] = set()
for pattern in globs:
negate = pattern.startswith("!")
pat = (pattern[1:] if negate else pattern).rstrip("/")
if pat.startswith("./"):
pat = pat[2:]
if not pat:
continue
try:
matches = sorted(p for p in root.glob(pat) if p.is_dir())
except (ValueError, NotImplementedError):
continue
if negate:
excluded.update(matches)
else:
included.extend(matches)
seen: set[Path] = set()
result: list[Path] = []
for d in included:
if d in excluded or d in seen:
continue
seen.add(d)
result.append(d)
return result
def _scan_all_manifest_dirs(root: Path, manifest_name: str) -> list[Path]:
"""Fallback for when no explicit workspace manifest is found: every
directory under `root` (skip-list applied) containing a file named
`manifest_name`, however nested — clearly a different, less precise
discovery mode than an explicit workspace list (see each
`discover_*_packages`'s `explicit` return value).
"""
dirs: list[Path] = []
def walk(current: Path) -> None:
if (current / manifest_name).is_file():
dirs.append(current)
try:
entries = list(current.iterdir())
except OSError:
return
for entry in entries:
if entry.is_dir() and not entry.name.startswith(".") and entry.name not in SKIPPED_DIR_NAMES:
walk(entry)
walk(root)
return dirs
def discover_npm_packages(root: Path) -> tuple[list[Package], bool]:
"""Returns `(packages, explicit)` — `explicit` is `False` when
neither a root `package.json` `workspaces` field nor a
`pnpm-workspace.yaml` was found, meaning discovery fell back to
`_scan_all_manifest_dirs` (an unscoped scan, not a real workspace
list).
"""
globs = _npm_workspace_globs(root) + _pnpm_workspace_globs(root)
explicit = bool(globs)
dirs = _resolve_workspace_dirs(root, globs) if explicit else _scan_all_manifest_dirs(root, "package.json")
packages: list[Package] = []
for d in dirs:
manifest = d / "package.json"
data = _read_json(manifest)
if data is None:
continue
name = data.get("name")
if isinstance(name, str) and name:
packages.append(Package(name=name, kind="npm", dir=_rel(root, d), manifest=_rel(root, manifest)))
return packages, explicit
def _has_cargo_workspace(root: Path) -> bool:
try:
text = (root / "Cargo.toml").read_text(encoding="utf-8")
except OSError:
return False
return "[workspace]" in text
def _toml_array_field(text: str, field_name: str) -> list[str]:
"""Real string entries from a top-level `field_name = [...]` array
anywhere in a TOML file — matches both the single-line and
multi-line array forms. A bracket-depth scanner (the same technique
`_grpc_services` uses for brace bodies), not a TOML parser: finds the
array's *real* matching closing `]`, correctly handling an element
that itself contains a literal `[`/`]` pair (e.g. a PEP 508 extras
specifier like `"uvicorn[standard]"`) rather than stopping at the
first `]` found. Shared by Cargo's `[workspace] members`/`exclude`
and Python's `[tool.uv.workspace] members`/`exclude`/
`[project] dependencies` — same underlying array shape.
"""
match = re.search(rf"^{field_name}\s*=\s*\[", text, re.MULTILINE)
if not match:
return []
start = match.end()
depth = 1
i = start
n = len(text)
while i < n and depth > 0:
if text[i] == "[":
depth += 1
elif text[i] == "]":
depth -= 1
i += 1
body = text[start : i - 1] if depth == 0 else text[start:]
return re.findall(r'"([^"]*)"', body)
def discover_cargo_packages(root: Path) -> list[Package]:
cargo_toml = root / "Cargo.toml"
try:
text = cargo_toml.read_text(encoding="utf-8")
except OSError:
return []
if "[workspace]" not in text:
return []
member_dirs = _resolve_workspace_dirs(root, _toml_array_field(text, "members"))
excluded_dirs = set(_resolve_workspace_dirs(root, _toml_array_field(text, "exclude")))
packages: list[Package] = []
for d in member_dirs:
if d in excluded_dirs:
continue
manifest = d / "Cargo.toml"
name = _cargo_package_name(manifest)
if name:
packages.append(Package(name=name, kind="cargo", dir=_rel(root, d), manifest=_rel(root, manifest)))
return packages
def _toml_section(text: str, name: str) -> str | None:
"""The raw body of a top-level `[name]` TOML table — from just after
its header line to the next top-level `[...]` header, or EOF. A
line-based extractor, not a real TOML parser: a `[...]`-shaped
literal inside a string value would be misread as a new table header
(not a pattern real `[package]`/`[project]` tables use).
"""
lines = text.splitlines()
start = None
for i, line in enumerate(lines):
if line.strip() == f"[{name}]":
start = i + 1
break
if start is None:
return None
end = len(lines)
for i in range(start, len(lines)):
stripped = lines[i].strip()
if stripped.startswith("[") and stripped.endswith("]"):
end = i
break
return "\n".join(lines[start:end])
def _cargo_package_name(manifest: Path) -> str | None:
try:
text = manifest.read_text(encoding="utf-8")
except OSError:
return None
section = _toml_section(text, "package")
if section is None:
return None
match = re.search(r'^\s*name\s*=\s*"([^"]+)"', section, re.MULTILINE)
return match.group(1) if match else None
def _toml_path_values(text: str, table_names: tuple[str, ...]) -> list[str]:
"""Real `path = "..."` values declared inside any of `table_names`'
top-level TOML tables — both the `name = { path = "..." }` inline-
table form and the `[table.name]` sub-table form. Shared by Cargo's
`[dependencies]`/`[dev-dependencies]`/`[build-dependencies]` and
Python's `[tool.uv.sources]`/`[tool.poetry.dependencies]` — same
underlying TOML shape, different table names. An external
(registry-only) dependency has no `path` key and is correctly never
returned, the same "first-party edges only" scoping
`dependency-graph` uses for Rust `use` paths.
"""
paths: list[str] = []
current_table: str | None = None
for raw_line in text.splitlines():
stripped = raw_line.strip()
if stripped.startswith("[") and stripped.endswith("]"):
header = stripped[1:-1].strip()
if header in table_names:
current_table = header
elif any(header.startswith(f"{t}.") for t in table_names):
current_table = header.split(".", 1)[0]
else:
current_table = None
continue
if current_table is None:
continue
paths.extend(re.findall(r'path\s*=\s*"([^"]*)"', stripped))
return paths
def _dependency_paths(text: str) -> list[str]:
"""Cargo's own entry point into `_toml_path_values`: real
`path = "..."` values in `[dependencies]`/`[dev-dependencies]`/
`[build-dependencies]`.
"""
return _toml_path_values(text, _DEP_TABLE_NAMES)
_TOML_KEY_RE = re.compile(r"^([A-Za-z0-9_.+-]+)\s*=")
def _toml_table_keys(text: str, table_names: tuple[str, ...]) -> set[str]:
"""Every real dependency *name* declared inside any of `table_names`'
top-level TOML tables — both `name = "..."`/`name = { ... }` inline
entries (collected only while directly inside a bare `[table]`
header) and `[table.name]` sub-table headers (the sub-table's own
name is a dependency name; a `path =`/`version =` line *inside* that
sub-table is one of that dependency's own attributes, not a sibling
dependency named "path" — deliberately not collected once a
`[table.name]` header is seen, until the next bare `[table]` header
if any).
"""
names: set[str] = set()
in_direct_table = False
for raw_line in text.splitlines():
stripped = raw_line.strip()
if stripped.startswith("[") and stripped.endswith("]"):
header = stripped[1:-1].strip()
if header in table_names:
in_direct_table = True
elif any(header.startswith(f"{t}.") for t in table_names):
in_direct_table = False
names.add(header.split(".", 1)[1])
else:
in_direct_table = False
continue
if not in_direct_table:
continue
match = _TOML_KEY_RE.match(stripped)
if match:
names.add(match.group(1))
return names
def _npm_dependency_names(data: dict) -> set[str]:
"""Every real dependency name declared across a package.json's
`dependencies`/`devDependencies`/`peerDependencies`/
`optionalDependencies` fields — used for technology-tag detection,
where every declared dependency matters, not just the ones matching
another discovered workspace package (`npm_edges`'s narrower job).
"""
names: set[str] = set()
for dep_field in _NPM_DEP_FIELDS:
value = data.get(dep_field)
if isinstance(value, dict):
names.update(value.keys())
return names
def _pyproject_name(manifest: Path) -> str | None:
"""Real package name from a pyproject.toml — PEP 621's
`[project] name = "..."` first, falling back to Poetry's older,
pre-PEP-621 `[tool.poetry] name = "..."` table.
"""
try:
text = manifest.read_text(encoding="utf-8")
except OSError:
return None
for section_name in ("project", "tool.poetry"):
section = _toml_section(text, section_name)
if section is not None:
match = re.search(r'^\s*name\s*=\s*"([^"]+)"', section, re.MULTILINE)
if match:
return match.group(1)
return None
def discover_python_packages(root: Path) -> tuple[list[Package], bool]:
"""Returns `(packages, explicit)` — same shape as
`discover_npm_packages`. `explicit` is `True` only when a root
pyproject.toml declares a real `[tool.uv.workspace]` table — uv's
real, documented workspace mechanism, the only Python tool with an
npm/Cargo-style explicit member-glob list. Poetry has no equivalent,
so a Poetry-only monorepo always falls back to the unscoped
pyproject.toml scan below.
"""
try:
root_text = (root / "pyproject.toml").read_text(encoding="utf-8")
except OSError:
root_text = ""
explicit = _toml_section(root_text, "tool.uv.workspace") is not None
if explicit:
member_dirs = _resolve_workspace_dirs(root, _toml_array_field(root_text, "members"))
excluded_dirs = set(_resolve_workspace_dirs(root, _toml_array_field(root_text, "exclude")))
dirs = [d for d in member_dirs if d not in excluded_dirs]
else:
dirs = _scan_all_manifest_dirs(root, "pyproject.toml")
packages: list[Package] = []
for d in dirs:
manifest = d / "pyproject.toml"
name = _pyproject_name(manifest)
if name:
packages.append(Package(name=name, kind="python", dir=_rel(root, d), manifest=_rel(root, manifest)))
return packages, explicit
_PEP508_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*")
def _python_dependency_names(text: str) -> set[str]:
"""Real dependency names from a pyproject.toml — PEP 621's
`[project] dependencies` array (PEP 508 requirement strings, e.g.
`"kafka-python>=2.0"`; just the leading package-name token, version
specifiers/extras stripped) plus `[tool.poetry.dependencies]`'s own
TOML-table keys (Poetry's older, pre-PEP-621 form) — Poetry's own
required `python` version pseudo-entry is dropped, not a real
package.
"""
names: set[str] = set()
for requirement in _toml_array_field(text, "dependencies"):
match = _PEP508_NAME_RE.match(requirement.strip())
if match:
names.add(match.group(0))
names.update(_toml_table_keys(text, ("tool.poetry.dependencies",)))
names.discard("python")
return names
def _go_work_members(root: Path) -> list[str]:
"""Real `use` directive paths from a root `go.work` — both the
parenthesized block form (`use (\n\t./a\n\t./b\n)`) and standalone
`use ./a` lines, `//` comments stripped. A line-based reader for
Go's own (non-TOML, non-YAML) `go.work` syntax, not a real
Go-tooling parser.
"""
try:
lines = (root / "go.work").read_text(encoding="utf-8").splitlines()
except OSError:
return []
members: list[str] = []
in_block = False
for raw_line in lines:
line = raw_line.split("//", 1)[0].strip()
if not line:
continue
if line == "use (":
in_block = True
continue
if in_block:
if line == ")":
in_block = False
else:
members.append(line)
continue
if line.startswith("use "):
members.append(line[len("use "):].strip())
return members
def _go_module_name(manifest: Path) -> str | None:
try:
text = manifest.read_text(encoding="utf-8")
except OSError:
return None
for raw_line in text.splitlines():
line = raw_line.split("//", 1)[0].strip()
if line.startswith("module "):
return line[len("module "):].strip()
return None
def discover_go_packages(root: Path) -> tuple[list[Package], bool]:
"""Returns `(packages, explicit)` — same shape as
`discover_npm_packages`. `explicit` is `True` only when a root
`go.work` lists real `use` members (Go's own workspace mechanism,
added in Go 1.18); otherwise falls back to an unscoped scan for
every `go.mod` under root.
"""
member_paths = _go_work_members(root)
explicit = bool(member_paths)
dirs = _resolve_workspace_dirs(root, member_paths) if explicit else _scan_all_manifest_dirs(root, "go.mod")
packages: list[Package] = []
for d in dirs:
manifest = d / "go.mod"
name = _go_module_name(manifest)
if name:
packages.append(Package(name=name, kind="go", dir=_rel(root, d), manifest=_rel(root, manifest)))
return packages, explicit
_GO_REPLACE_TARGET_RE = re.compile(r"=>\s*(\S+)")
def _go_replace_paths(text: str) -> list[str]:
"""Real local-filesystem `replace <module> => <path>` targets from a
go.mod — both the parenthesized block form and standalone lines. A
replace target only counts as a local path when it starts with `.`
or `/`, Go's own documented rule for telling a local override
(`replace foo => ../foo`) apart from a version pin
(`replace foo => bar v1.2.3`).
"""
paths: list[str] = []
in_block = False
for raw_line in text.splitlines():
line = raw_line.split("//", 1)[0].strip()
if not line:
continue
if line == "replace (":
in_block = True
continue
if in_block and line == ")":
in_block = False
continue
if in_block or line.startswith("replace "):
match = _GO_REPLACE_TARGET_RE.search(line)
if match and (match.group(1).startswith(".") or match.group(1).startswith("/")):
paths.append(match.group(1))
return paths
def go_edges(packages: list[Package], root: Path) -> list[Edge]:
by_dir = {(root / p.dir).resolve(): p.name for p in packages if p.kind == "go"}
edges: list[Edge] = []
seen: set[tuple[str, str]] = set()
for pkg in packages:
if pkg.kind != "go":
continue
try:
text = (root / pkg.manifest).read_text(encoding="utf-8")
except OSError:
continue
pkg_dir = (root / pkg.dir).resolve()
for rel_path in _go_replace_paths(text):
target_name = by_dir.get((pkg_dir / rel_path).resolve())
if target_name is None or target_name == pkg.name:
continue
key = (pkg.name, target_name)
if key not in seen:
seen.add(key)
edges.append(Edge(source=pkg.name, target=target_name, manager="go"))
return edges
def _go_dependency_names(text: str) -> set[str]:
"""Real module names from a go.mod's `require` directives — both the
parenthesized block form and standalone `require module version`
lines, `//` comments stripped.
"""
names: set[str] = set()
in_block = False
for raw_line in text.splitlines():
line = raw_line.split("//", 1)[0].strip()
if not line:
continue
if line == "require (":
in_block = True
continue
if in_block:
if line == ")":
in_block = False
else:
parts = line.split()
if parts:
names.add(parts[0])
continue
if line.startswith("require "):
parts = line[len("require "):].strip().split()
if parts:
names.add(parts[0])
return names
_GRADLE_INCLUDE_RE = re.compile(r"\binclude\b")
_GRADLE_QUOTED_PATH_RE = re.compile(r"""['"](:[^'"]+)['"]""")
_GRADLE_PROJECT_REF_RE = re.compile(r"""project\(\s*['"](:[^'"]+)['"]\s*\)""")
def _gradle_settings_members(root: Path) -> list[str]:
"""Real Gradle module paths (`:a`, `:services:api`, ...) declared via
`include(...)`/`include ...` in a root `settings.gradle` or
`settings.gradle.kts` (Kotlin DSL checked first — a repo with both is
unusual, but Kotlin DSL is the modern default for new Gradle
projects). A per-line reader: a multi-line `include(\n ...\n)` call
split across several lines isn't understood, the same "common form,
not a real Gradle-script parser" honesty as this skill's other
manifest readers.
"""
for filename in ("settings.gradle.kts", "settings.gradle"):
try:
lines = (root / filename).read_text(encoding="utf-8").splitlines()
except OSError:
continue
members: list[str] = []
for raw_line in lines:
line = raw_line.split("//", 1)[0]
if _GRADLE_INCLUDE_RE.search(line):
members.extend(_GRADLE_QUOTED_PATH_RE.findall(line))
return members
return []
def _has_gradle_settings(root: Path) -> bool:
return (root / "settings.gradle.kts").is_file() or (root / "settings.gradle").is_file()
def _gradle_module_dir(root: Path, gradle_path: str) -> Path:
"""Gradle's own default project-layout convention: a module path's
colon segments map directly to nested directories
(`:services:api` -> `services/api`). A project that overrides this
via `project(':x').projectDir = file(...)` in settings.gradle isn't
followed — see README's honest-scope note.
"""
return root.joinpath(*gradle_path.lstrip(":").split(":"))
def discover_gradle_packages(root: Path) -> list[Package]:
"""No scan-fallback mode, unlike the other four ecosystems: a Gradle
project with no `include(...)` calls in its settings file is a
single project, not a multi-module workspace with siblings worth
scanning for — the same "no `[workspace]`, no siblings to map"
reasoning `discover_cargo_packages` uses. The module's own display
name is its Gradle path with the leading colon stripped
(`:services:api` -> `services:api`), Gradle's own real unique
identifier for a module — not just its last path segment, which
could collide between differently-nested modules.
"""
packages: list[Package] = []
for gradle_path in _gradle_settings_members(root):
module_dir = _gradle_module_dir(root, gradle_path)
manifest = next(
(module_dir / name for name in ("build.gradle.kts", "build.gradle") if (module_dir / name).is_file()),
None,
)
if manifest is None:
continue
packages.append(
Package(
name=gradle_path.lstrip(":"),
kind="gradle",
dir=_rel(root, module_dir),
manifest=_rel(root, manifest),
)
)
return packages
def gradle_edges(packages: list[Package], root: Path) -> list[Edge]:
gradle_names = {p.name for p in packages if p.kind == "gradle"}
edges: list[Edge] = []
seen: set[tuple[str, str]] = set()
for pkg in packages:
if pkg.kind != "gradle":
continue
try:
text = (root / pkg.manifest).read_text(encoding="utf-8")
except OSError:
continue
for match in _GRADLE_PROJECT_REF_RE.finditer(text):
target_name = match.group(1).lstrip(":")
if target_name not in gradle_names or target_name == pkg.name:
continue
key = (pkg.name, target_name)
if key not in seen:
seen.add(key)
edges.append(Edge(source=pkg.name, target=target_name, manager="gradle"))
return edges
_GRADLE_DEP_RE = re.compile(
r"""\b(?:implementation|api|compileOnly|runtimeOnly|testImplementation)\s*[(\s]\s*['"]([^:'"]+:[^:'"]+)"""
)
def _gradle_dependency_names(text: str) -> set[str]:
"""Real `group:artifact` coordinates from Gradle dependency-
configuration lines (`implementation 'group:artifact:version'`,
Kotlin DSL's `implementation("group:artifact:version")`, and the
same for `api`/`compileOnly`/`runtimeOnly`/`testImplementation`) —
the version segment dropped, just `group:artifact`, matched against
this skill's known-dependency table using that same form.
"""
return set(_GRADLE_DEP_RE.findall(text))
def dedupe_packages(packages: list[Package]) -> list[Package]:
"""Drops later duplicates by `(kind, name)` (first discovered wins) —
keyed on kind as well as name because a real npm package and a real
Cargo crate can legitimately share a published name (this repo has
exactly that: the npm `pinkyaicode` VS Code extension and the Cargo
`pinkyaicode` crate live in different directories entirely) — deduping
by bare name would silently drop one of two genuinely different
packages. A same-kind collision (two manifests somehow claiming the
same name) is rare enough to be worth a human's eyes rather than a
silently arbitrary tie-break rule.
"""
seen: set[tuple[str, str]] = set()
result: list[Package] = []
for pkg in packages:
key = (pkg.kind, pkg.name)
if key in seen:
continue
seen.add(key)
result.append(pkg)
return result
def npm_edges(packages: list[Package], root: Path) -> list[Edge]:
by_name = {p.name for p in packages if p.kind == "npm"}
edges: list[Edge] = []
seen: set[tuple[str, str]] = set()
for pkg in packages:
if pkg.kind != "npm":
continue
data = _read_json(root / pkg.manifest) or {}
dep_names: list[str] = []
for dep_field in _NPM_DEP_FIELDS:
value = data.get(dep_field)
if isinstance(value, dict):
dep_names.extend(value.keys())
for dep_name in dep_names:
if dep_name == pkg.name or dep_name not in by_name:
continue
key = (pkg.name, dep_name)
if key not in seen:
seen.add(key)
edges.append(Edge(source=pkg.name, target=dep_name, manager="npm"))
return edges
def _manifest_path_edges(
packages: list[Package], root: Path, *, kind: str, table_names: tuple[str, ...], manager: str
) -> list[Edge]:
"""Shared TOML `path = "..."` edge-resolution: read each `kind`
package's own manifest, extract `table_names`' `path = "..."` values
via `_toml_path_values`, resolve each relative to the declaring
package's own directory, and match against a known sibling's
directory. Used by both Cargo and Python (uv/Poetry) — same
resolution rule, different table names.
"""
by_dir = {(root / p.dir).resolve(): p.name for p in packages if p.kind == kind}
edges: list[Edge] = []
seen: set[tuple[str, str]] = set()
for pkg in packages:
if pkg.kind != kind:
continue
try:
text = (root / pkg.manifest).read_text(encoding="utf-8")
except OSError:
continue
pkg_dir = (root / pkg.dir).resolve()
for rel_path in _toml_path_values(text, table_names):
target_name = by_dir.get((pkg_dir / rel_path).resolve())
if target_name is None or target_name == pkg.name:
continue
key = (pkg.name, target_name)
if key not in seen:
seen.add(key)
edges.append(Edge(source=pkg.name, target=target_name, manager=manager))
return edges
def cargo_edges(packages: list[Package], root: Path) -> list[Edge]:
return _manifest_path_edges(packages, root, kind="cargo", table_names=_DEP_TABLE_NAMES, manager="cargo")
def python_edges(packages: list[Package], root: Path) -> list[Edge]:
return _manifest_path_edges(
packages, root, kind="python", table_names=_PYTHON_PATH_TABLE_NAMES, manager="python"
)
def compute_fan_in(packages: list[Package], edges: list[Edge]) -> dict[tuple[str, str], int]:
"""Fan-in per `(kind, name)` — not bare `name` (see `dedupe_packages`'s
docstring for the real cross-manager name collision that makes this
necessary): every edge's `manager` always matches the `kind` of both
its endpoints (an npm edge only ever connects two npm packages, a
Gradle edge only ever connects two Gradle modules, and so on), so
`(edge.manager, edge.target)` is always the right key.
"""
fan_in = {(p.kind, p.name): 0 for p in packages}
for edge in edges:
key = (edge.manager, edge.target)
fan_in[key] = fan_in.get(key, 0) + 1
return fan_in
def commons(packages: list[Package], edges: list[Edge], threshold: int) -> set[tuple[str, str]]:
"""Returns the `(kind, name)` keys of every package at least
`threshold` other discovered packages declare a real dependency on.
"""
return {key for key, count in compute_fan_in(packages, edges).items() if count >= threshold}
_QUEUE_DEPENDENCIES: frozenset[str] = frozenset({
"kafkajs", "node-rdkafka", "kafka-node", "amqplib", "amqp-connection-manager",
"bullmq", "bull", "@aws-sdk/client-sqs", "@aws-sdk/client-sns", "nats",
"rdkafka", "lapin", "aws-sdk-sqs", "aws-sdk-sns", "async-nats",
"kafka-python", "confluent-kafka", "aio-pika", "pika", "celery",
"github.com/segmentio/kafka-go", "github.com/confluentinc/confluent-kafka-go",
"github.com/streadway/amqp", "github.com/aws/aws-sdk-go-v2/service/sqs",
"github.com/aws/aws-sdk-go-v2/service/sns", "github.com/nats-io/nats.go",
"org.apache.kafka:kafka-clients", "com.rabbitmq:amqp-client",
"software.amazon.awssdk:sqs", "software.amazon.awssdk:sns",
})
_DATABASE_DEPENDENCIES: frozenset[str] = frozenset({
"pg", "mysql2", "mysql", "sqlite3", "better-sqlite3", "mongodb", "mongoose",
"ioredis", "redis", "sequelize", "typeorm", "prisma", "knex", "@aws-sdk/client-dynamodb",
"sqlx", "rusqlite", "diesel", "tokio-postgres", "postgres", "mongodb", "aws-sdk-dynamodb",
"psycopg2", "psycopg", "pymysql", "sqlalchemy", "pymongo",
"github.com/lib/pq", "github.com/jackc/pgx", "github.com/go-sql-driver/mysql",
"github.com/mattn/go-sqlite3", "go.mongodb.org/mongo-driver",
"github.com/redis/go-redis/v9", "github.com/aws/aws-sdk-go-v2/service/dynamodb",
"org.postgresql:postgresql", "mysql:mysql-connector-java", "com.h2database:h2",
"org.mongodb:mongodb-driver-sync", "redis.clients:jedis", "software.amazon.awssdk:dynamodb",
})
_TRANSPORT_DEPENDENCIES: frozenset[str] = frozenset({
"express", "fastify", "koa", "@hapi/hapi", "@nestjs/core", "ws", "socket.io", "@grpc/grpc-js",
"axum", "actix-web", "warp", "rocket", "tonic", "tokio-tungstenite",
"fastapi", "flask", "django", "aiohttp", "grpcio", "websockets",
"github.com/gin-gonic/gin", "github.com/labstack/echo/v4", "github.com/gorilla/mux",
"google.golang.org/grpc", "github.com/gorilla/websocket",
"org.springframework.boot:spring-boot-starter-web", "io.grpc:grpc-netty",
"io.javalin:javalin", "io.ktor:ktor-server-core",
})
_CATEGORY_TABLES: tuple[tuple[str, frozenset[str]], ...] = (
("queue", _QUEUE_DEPENDENCIES),
("database", _DATABASE_DEPENDENCIES),
("transport", _TRANSPORT_DEPENDENCIES),
)
def categorize_dependencies(dep_names: set[str]) -> dict[str, list[str]]:
"""Groups `dep_names` (one package's own real, declared dependency
names) by which of this skill's known technology categories they
match. A curated lookup, deliberately non-exhaustive — real,
well-known libraries per category and ecosystem, not a claim to
recognize every queue/database/transport library that exists (an
obscure or in-house library is silently not tagged, not
misclassified). Answers "this package's manifest lists a known
queue/database/transport library," never "this package definitely
uses a queue/database/transport at runtime" — the same "declared,
not observed" honesty this whole skill is built on.
"""
result: dict[str, list[str]] = {}
for category, known in _CATEGORY_TABLES:
matched = sorted(dep_names & known)
if matched:
result[category] = matched
return result
def _dependency_names_for(pkg: Package, root: Path) -> set[str]:
"""Every real dependency name a package's own manifest declares —
reusing each ecosystem's own manifest-reading logic, just collecting
every name instead of only the ones this skill's edge-detection
already cares about.
"""
manifest_path = root / pkg.manifest
if pkg.kind == "npm":
data = _read_json(manifest_path)
return _npm_dependency_names(data) if data else set()
try:
text = manifest_path.read_text(encoding="utf-8")
except OSError:
return set()
if pkg.kind == "cargo":
return _toml_table_keys(text, _DEP_TABLE_NAMES)
if pkg.kind == "python":
return _python_dependency_names(text)
if pkg.kind == "go":
return _go_dependency_names(text)
if pkg.kind == "gradle":
return _gradle_dependency_names(text)
return set()
def technology_tags(packages: list[Package], root: Path) -> dict[tuple[str, str], dict[str, list[str]]]:
"""Per-`(kind, name)` `{"queue": [...], "database": [...],
"transport": [...]}` tags, derived entirely from each package's own
already-declared dependencies — zero new file-reading beyond each
ecosystem's own manifest, already read elsewhere for edge detection.
"""
tags: dict[tuple[str, str], dict[str, list[str]]] = {}
for pkg in packages:
matched = categorize_dependencies(_dependency_names_for(pkg, root))
if matched:
tags[(pkg.kind, pkg.name)] = matched
return tags
def _contract_kind(filename: str) -> str | None:
lower = filename.lower()
if lower.endswith(".proto"):
return "protobuf"
if lower.endswith((".graphql", ".gql")):
return "graphql"
if lower.endswith(".thrift"):
return "thrift"
if lower.endswith(".wsdl"):
return "wsdl"
if lower.endswith(".avsc"):
return "avro"
if lower.endswith((".json", ".yaml", ".yml")) and "asyncapi" in lower:
return "asyncapi"
if lower.endswith((".json", ".yaml", ".yml")) and ("openapi" in lower or "swagger" in lower):
return "openapi"
return None
_GRPC_SERVICE_RE = re.compile(r"\bservice\s+(\w+)\s*\{")
_GRPC_METHOD_RE = re.compile(r"\brpc\s+(\w+)\s*\(")
def _grpc_services(text: str) -> list[GrpcService]:
"""Real `service Name { rpc Method(...) returns (...); ... }` blocks
from protobuf source — a brace-depth scanner (the same technique
`dependency-diagram` uses for Rust `use { ... }` bodies), not a real
protobuf grammar: doesn't resolve imported message types and doesn't
distinguish a unary RPC from a streaming one, both real protobuf
distinctions this scanner doesn't need to know about to answer "what
services and methods exist here."
"""
services: list[GrpcService] = []
n = len(text)
for service_match in _GRPC_SERVICE_RE.finditer(text):
name = service_match.group(1)
start = service_match.end()
depth = 1
j = start
while j < n and depth > 0:
if text[j] == "{":
depth += 1
elif text[j] == "}":
depth -= 1
j += 1
body = text[start : j - 1] if depth == 0 else text[start:]
services.append(GrpcService(name=name, methods=_GRPC_METHOD_RE.findall(body)))
return services
def find_contracts(root: Path, packages: list[Package]) -> list[Contract]:
owners = sorted(
((p.name, (root / p.dir).resolve()) for p in packages),
key=lambda item: len(item[1].parts),
reverse=True,
)
contracts: list[Contract] = []
def walk(current: Path) -> None:
try:
entries = list(current.iterdir())
except OSError:
return
for entry in entries:
if entry.is_dir():
if not entry.name.startswith(".") and entry.name not in SKIPPED_DIR_NAMES:
walk(entry)
continue
kind = _contract_kind(entry.name)
if kind is None:
continue
resolved = entry.resolve()
owner = next(
(name for name, pkg_dir in owners if pkg_dir == resolved.parent or pkg_dir in resolved.parents),
None,
)
services: list[GrpcService] = []
if kind == "protobuf":
try:
services = _grpc_services(entry.read_text(encoding="utf-8"))
except (OSError, UnicodeDecodeError):
services = []
contracts.append(Contract(path=_rel(root, entry), kind=kind, owner=owner, services=services))
walk(root)
contracts.sort(key=lambda c: c.path)
return contracts
def _walk_files_with_suffixes(directory: Path, suffixes: tuple[str, ...]) -> list[Path]:
found: list[Path] = []
def walk(current: Path) -> None:
try:
entries = list(current.iterdir())
except OSError:
return
for entry in entries:
if entry.is_dir():
if not entry.name.startswith(".") and entry.name not in SKIPPED_DIR_NAMES:
walk(entry)
continue
if entry.suffix in suffixes:
found.append(entry)
walk(directory)
return found
_CDK_RESOURCE_KINDS: dict[str, str] = {
"Queue": "queue",
"Topic": "topic",
"Table": "table",
"Bucket": "bucket",
"Stream": "stream",
"EventBus": "event-bus",
"DatabaseInstance": "database",
"DatabaseCluster": "database",
"ServerlessCluster": "database",
}
_CDK_CONSTRUCT_RE = re.compile(r"""new\s+(\w+)\(\s*this\s*,\s*['"]([^'"]+)['"]""")
def _cdk_resources(text: str) -> list[tuple[str, str]]:
"""Real `new <Construct>(this, "LogicalId", ...)` calls matching a
known CDK resource construct name (see `_CDK_RESOURCE_KINDS`) — CDK's
own idiom for declaring a provisioned resource: the construct's scope
argument is always `this`, its logical ID always a literal string
(the exact shape this repo's own real
`new Topic(this, "ScanSandboxBudgetTopic", {...})` uses, dogfooded
against directly). Matches by class name only, not by resolving the
class's actual `aws-cdk-lib` import — a different class happening to
share one of these names, inside a package that also happens to
depend on `aws-cdk-lib`, would be a false positive; judged unlikely
enough not to block on, the same class of trade-off this skill's
`.proto`/OpenAPI filename-based contract detection already makes.
"""
resources: list[tuple[str, str]] = []
for match in _CDK_CONSTRUCT_RE.finditer(text):
class_name, logical_id = match.group(1), match.group(2)
kind = _CDK_RESOURCE_KINDS.get(class_name)
if kind:
resources.append((kind, logical_id))
return resources
def find_infra_resources(root: Path, packages: list[Package]) -> list[InfraResource]:
"""CDK TypeScript infra-as-code resources — scoped to `.ts`/`.tsx`
files inside npm packages that themselves declare a real dependency
on `aws-cdk-lib` (via `_dependency_names_for`, the same lookup
`technology_tags` uses), not every `.ts` file in the repo. Real,
provisioned infrastructure — a queue/topic/table this monorepo
actually stands up — not a guess at runtime traffic between services.
Terraform/CloudFormation aren't understood yet — a real, documented
gap (see README's honest-scope note), not silently unsupported by
oversight.
"""
cdk_packages = [p for p in packages if p.kind == "npm" and "aws-cdk-lib" in _dependency_names_for(p, root)]
resources: list[InfraResource] = []
for pkg in cdk_packages:
for file in _walk_files_with_suffixes(root / pkg.dir, (".ts", ".tsx")):
try:
file_text = file.read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError):
continue
for kind, logical_id in _cdk_resources(file_text):
resources.append(InfraResource(kind=kind, logical_id=logical_id, path=_rel(root, file), owner=pkg.name))
resources.sort(key=lambda r: (r.path, r.logical_id))
return resources
def neighborhood(focus: str, packages: list[Package], edges: list[Edge]) -> tuple[list[Package], list[Edge]]:
"""Restricts `packages`/`edges` to `focus` plus its *direct* (one-hop,
not transitive) dependencies and dependents — a diagram-scoping tool,
the same honest "direct neighbors only" restriction
`dependency-diagram --focus` applies to a single file.
"""
keep = {focus}
for edge in edges:
if edge.source == focus:
keep.add(edge.target)
if edge.target == focus:
keep.add(edge.source)
kept_packages = [p for p in packages if p.name in keep]
kept_edges = [e for e in edges if e.source in keep and e.target in keep]
return kept_packages, kept_edges
_SANITIZE_RE = re.compile(r"[^A-Za-z0-9_]")
def sanitize_id(text: str) -> str:
"""A Mermaid-safe node identifier — Mermaid flowchart IDs can't
contain `/`, `.`, `@`, or `-`, all common in package names/paths.
"""
return "n_" + _SANITIZE_RE.sub("_", text)
def node_key(pkg: Package) -> str:
"""A diagram-id seed unique per `(kind, name)`, not bare `name` — see
`dedupe_packages`'s docstring for the real collision this guards
against. An edge's `manager` always matches the `kind` of both its
endpoints (an npm edge only ever connects two npm packages), so
`f"{edge.manager}:{edge.source}"` is the matching key for an edge
endpoint without `Edge` needing to carry kind on both sides.
"""
return f"{pkg.kind}:{pkg.name}"
def render_diagram(
packages: list[Package],
edges: list[Edge],
contracts: list[Contract],
commons_names: set[tuple[str, str]],
*,
tags: dict[tuple[str, str], dict[str, list[str]]] | None = None,
infra: list[InfraResource] | None = None,
) -> str:
tags = tags or {}
infra = infra or []
contract_counts: dict[str, int] = {}
grpc_service_counts: dict[str, int] = {}
unowned: list[Contract] = []
for c in contracts:
if c.owner is None:
unowned.append(c)
else:
contract_counts[c.owner] = contract_counts.get(c.owner, 0) + 1
if c.services:
grpc_service_counts[c.owner] = grpc_service_counts.get(c.owner, 0) + len(c.services)
infra_counts: dict[str, int] = {}
for resource in infra:
infra_counts[resource.owner] = infra_counts.get(resource.owner, 0) + 1
def label(pkg: Package) -> str:
text = f"{pkg.name} ({pkg.kind})"
count = contract_counts.get(pkg.name, 0)
if count:
text += f"\\n{count} contract{'s' if count != 1 else ''}"
grpc_count = grpc_service_counts.get(pkg.name, 0)
if grpc_count:
text += f"\\n{grpc_count} gRPC service{'s' if grpc_count != 1 else ''}"
infra_count = infra_counts.get(pkg.name, 0)
if infra_count:
text += f"\\n{infra_count} infra resource{'s' if infra_count != 1 else ''}"
categories = tags.get((pkg.kind, pkg.name))
if categories:
text += f"\\n{', '.join(sorted(categories))}"
return text
lines = ["flowchart LR"]
commons_pkgs = [p for p in packages if (p.kind, p.name) in commons_names]
other_pkgs = [p for p in packages if (p.kind, p.name) not in commons_names]
if commons_pkgs:
lines.append(' subgraph commons["commons"]')
for pkg in commons_pkgs:
lines.append(f' {sanitize_id(node_key(pkg))}["{label(pkg)}"]')
lines.append(" end")
for pkg in other_pkgs:
lines.append(f' {sanitize_id(node_key(pkg))}["{label(pkg)}"]')
if unowned:
lines.append(' subgraph unowned_contracts["unowned contracts"]')
for c in unowned:
lines.append(f' {sanitize_id(c.path)}["{c.path}"]')
lines.append(" end")
for edge in edges:
source_id = sanitize_id(f"{edge.manager}:{edge.source}")
target_id = sanitize_id(f"{edge.manager}:{edge.target}")
lines.append(f" {source_id} --> {target_id}")
return "\n".join(lines)
def render_json(
packages: list[Package],
edges: list[Edge],
contracts: list[Contract],
commons_names: set[tuple[str, str]],
*,
discovery: dict[str, str],
tags: dict[tuple[str, str], dict[str, list[str]]] | None = None,
infra: list[InfraResource] | None = None,
) -> str:
tags = tags or {}
infra = infra or []
fan_in = compute_fan_in(packages, edges)
payload = {
"packages": [
{
"name": p.name,
"kind": p.kind,
"dir": p.dir,
"manifest": p.manifest,
"fanIn": fan_in.get((p.kind, p.name), 0),
"commons": (p.kind, p.name) in commons_names,
"technology": tags.get((p.kind, p.name), {}),
}
for p in packages
],
"edges": [{"from": e.source, "to": e.target, "manager": e.manager} for e in edges],
"contracts": [
{
"path": c.path,
"kind": c.kind,
"owner": c.owner,
"services": [{"name": s.name, "methods": s.methods} for s in c.services],
}
for c in contracts
],
"infrastructure": [
{"kind": r.kind, "logicalId": r.logical_id, "path": r.path, "owner": r.owner} for r in infra
],
"discovery": discovery,
}
return json.dumps(payload, indent=2)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
description="Map a monorepo's packages/services, commons, and API contracts as a Mermaid diagram or JSON."
)
parser.add_argument("root", help="Monorepo root directory to scan")
parser.add_argument(
"--json", action="store_true", help="Print structured package/edge/contract data as JSON instead of a diagram"
)
parser.add_argument(
"--focus",
help="Package name to scope the diagram to (that package plus its direct dependencies and dependents)",
)
parser.add_argument(
"--commons-threshold",
type=int,
default=2,
help="Minimum fan-in for a package to be flagged 'commons' (default: 2)",
)
args = parser.parse_args(argv)
root = Path(args.root)
if not root.is_dir():
print(f"system-map: {args.root!r} is not a directory", file=sys.stderr)
return 1
npm_packages, npm_explicit = discover_npm_packages(root)
cargo_packages = discover_cargo_packages(root)
python_packages, python_explicit = discover_python_packages(root)
go_packages, go_explicit = discover_go_packages(root)
gradle_packages = discover_gradle_packages(root)
packages = dedupe_packages(npm_packages + cargo_packages + python_packages + go_packages + gradle_packages)
packages.sort(key=lambda p: p.name)
edges = (
npm_edges(packages, root)
+ cargo_edges(packages, root)
+ python_edges(packages, root)
+ go_edges(packages, root)
+ gradle_edges(packages, root)
)
edges.sort(key=lambda e: (e.source, e.target, e.manager))
contracts = find_contracts(root, packages)
tags = technology_tags(packages, root)
infra = find_infra_resources(root, packages)
discovery = {
"npm": "workspace" if npm_explicit else "scan-fallback",
"cargo": "workspace" if _has_cargo_workspace(root) else "not-found",
"python": "workspace" if python_explicit else "scan-fallback",
"go": "workspace" if go_explicit else "scan-fallback",
"gradle": "settings-found" if _has_gradle_settings(root) else "not-found",
}
if args.focus:
names = {p.name for p in packages}
if args.focus not in names:
print(f"system-map: --focus package {args.focus!r} not found among discovered packages", file=sys.stderr)
return 1
packages, edges = neighborhood(args.focus, packages, edges)
focus_names = {p.name for p in packages}
contracts = [c for c in contracts if c.owner in focus_names]
infra = [r for r in infra if r.owner in focus_names]
commons_names = commons(packages, edges, args.commons_threshold)
if args.json:
print(
render_json(
packages, edges, contracts, commons_names, discovery=discovery, tags=tags, infra=infra
)
)
return 0
print(render_diagram(packages, edges, contracts, commons_names, tags=tags, infra=infra))
return 0
if __name__ == "__main__":
sys.exit(main())