feat(ci): warn, never fail, naming each lost core name and the plugins' catalog records
Some checks failed
Deploy Site / deploy-vercel (push) Has been cancelled
Deploy Site / deploy-docs (push) Has been cancelled
Skills Index Freshness Check / check-freshness (push) Has been cancelled
Skills Index Freshness Check / check-catalog-cors (push) Has been cancelled
Docs Search Monitor / probe (push) Has been cancelled
Build Skills Index / build-index (push) Has been cancelled
Build Skills Index / trigger-deploy (push) Has been cancelled
Some checks failed
Deploy Site / deploy-vercel (push) Has been cancelled
Deploy Site / deploy-docs (push) Has been cancelled
Skills Index Freshness Check / check-freshness (push) Has been cancelled
Skills Index Freshness Check / check-catalog-cors (push) Has been cancelled
Docs Search Monitor / probe (push) Has been cancelled
Build Skills Index / build-index (push) Has been cancelled
Build Skills Index / trigger-deploy (push) Has been cancelled
The catalog check no longer blocks a core PR. It reports every break as a warning, in three places: a check annotation per plugin, the job summary, and a warning item in the live CI review comment. The report says: - each core name the change removes, whether it is private (needs a public interface) or already on plugin_api.json (judged against the base's copy), and which plugins import it; - for each affected plugin: its title, version, tier, category and maintainer; its repository, subdir and pin; links to its plugin-catalog/<name>.yaml and its marketplace page; and a link to each import line at the pin. The breaks-catalog-plugin label is gone: with nothing to block, there is nothing to override. The step runs after setup-pm because the catalog loader needs ruamel.yaml. Review fixes in the same pass: a try nested in a branch that still runs can lose its own feature and is reported (greptile, BearHuddleston); a lost branch only names imports that resolved on the base; a bare annotation binds nothing; the daily refresh parses with Python 3.14, the shipped runtime (BearHuddleston). Co-authored-by: Bear Huddleston <196404565+BearHuddleston@users.noreply.github.com>
This commit is contained in:
2
.github/workflows/catalog-core-imports.yml
vendored
2
.github/workflows/catalog-core-imports.yml
vendored
@@ -40,7 +40,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
|
||||
with:
|
||||
python-version: "3.11"
|
||||
python-version: "3.14"
|
||||
|
||||
- name: Install ruamel.yaml
|
||||
uses: ./.github/actions/retry
|
||||
|
||||
42
.github/workflows/repo-guards.yml
vendored
42
.github/workflows/repo-guards.yml
vendored
@@ -160,21 +160,6 @@ jobs:
|
||||
if: ${{ !cancelled() }}
|
||||
run: python3 scripts/ci/check_retired_shims_manifest.py
|
||||
|
||||
# ── Pull requests, python lane: pinned catalog plugins this change breaks ─────────────
|
||||
|
||||
# Catalog plugins live in their own repos, so no test here sees a core PR remove a module or
|
||||
# name one of them imports. scripts/ci/catalog_core_imports/ records each pinned entry's
|
||||
# Hermes imports (refreshed by catalog-core-imports.yml); this resolves them against the base
|
||||
# and the merge commit from git objects alone (no network, no plugin code, a few seconds) and
|
||||
# fails naming the plugin, file:line and the import, with the fixes: an official seam PR, a
|
||||
# compat move, or the breaks-catalog-plugin label. Local:
|
||||
# `python3 scripts/ci/catalog_core_imports.py check --base "$(git merge-base origin/main HEAD)"`.
|
||||
- name: Name the pinned catalog plugins this change breaks
|
||||
if: ${{ !cancelled() && inputs.event_name == 'pull_request' && inputs.python }}
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: python3 scripts/ci/catalog_core_imports.py check --base HEAD^1 --head HEAD
|
||||
|
||||
# ── Pull requests: unrelated histories ────────────────────────────────────────────────
|
||||
|
||||
# PR #25045 was merged from a branch disconnected from main's history; GitHub's merge UI
|
||||
@@ -394,6 +379,33 @@ jobs:
|
||||
cache-python: true
|
||||
prune-python-cache: true
|
||||
|
||||
# ── Pull requests, python lane: pinned catalog plugins this change breaks (warning) ──
|
||||
|
||||
# Catalog plugins live in their own repos, so no test here sees a core PR remove a module or
|
||||
# name one of them imports. scripts/ci/catalog_core_imports/ records each pinned entry's
|
||||
# Hermes imports (refreshed by catalog-core-imports.yml); this resolves them against the base
|
||||
# and the merge commit from git objects alone (no network, no plugin code, a few seconds).
|
||||
# Never blocking: it warns (annotation, job summary, CI review comment) with each core name
|
||||
# lost, whether it is private, and each plugin's catalog entry, repo, pin and file:line, so the
|
||||
# author knows which public interface to add. After setup-pm: the catalog loader needs
|
||||
# ruamel.yaml. Local:
|
||||
# `python3 scripts/ci/catalog_core_imports.py check --base "$(git merge-base origin/main HEAD)"`.
|
||||
- name: Name the pinned catalog plugins this change breaks
|
||||
id: catalog-core-imports
|
||||
if: ${{ !cancelled() && steps.setup-pm.outcome == 'success' && inputs.event_name == 'pull_request' && inputs.python }}
|
||||
run: python3 scripts/ci/catalog_core_imports.py check --base HEAD^1 --head HEAD
|
||||
|
||||
- name: Upload review status artifact (catalog core imports)
|
||||
if: always() && steps.catalog-core-imports.outcome != 'skipped'
|
||||
continue-on-error: true
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: review-status-catalog-core-imports
|
||||
path: ${{ runner.temp }}/review-status/catalog-core-imports/review-status.json
|
||||
retention-days: 1
|
||||
overwrite: true
|
||||
if-no-files-found: ignore
|
||||
|
||||
# ── uv_lock lane: uv.lock in sync with pyproject.toml ─────────────────────────────────
|
||||
|
||||
# Blocking: the Docker build's `uv sync --frozen` fails on a stale lockfile, so catch it
|
||||
|
||||
@@ -102,15 +102,21 @@ def _is_hermes_import(module: str, name: str, core: frozenset, local: set[str])
|
||||
return module.split(".")[0] in core and module not in local and not own
|
||||
|
||||
|
||||
def is_public_import(module: str, name: str, public_api: frozenset | None = None) -> bool:
|
||||
"""True when ``from module import name`` (``import module`` for ``name`` "") is on the published plugin API
|
||||
(``public_api`` entries, default this checkout's ``plugin_api.json``)."""
|
||||
target = f"{module}.{name}" if name else module
|
||||
# A name is public under its old or its current spelling: a MOVES key may fold a module into a published one.
|
||||
public_api = _public_api() if public_api is None else public_api
|
||||
return bool({original_module(target), current_module(target)} & public_api) or any(
|
||||
f"{mod}:{name}" in public_api or (mod in public_api and not name.startswith("_")) # ``from gateway.platforms import base``
|
||||
for mod in {original_module(module), current_module(module)})
|
||||
|
||||
|
||||
def _private_target(module: str, name: str, core: frozenset, local: set[str]) -> str:
|
||||
"""The dotted target to report, or "" when the import is public, local or not Hermes's."""
|
||||
target = f"{module}.{name}" if name else module
|
||||
# A name is public under its old or its current spelling: a MOVES key may fold a module into a published one.
|
||||
public_api = _public_api()
|
||||
public = bool({original_module(target), current_module(target)} & public_api) or any(
|
||||
f"{mod}:{name}" in public_api or (mod in public_api and not name.startswith("_")) # ``from gateway.platforms import base``
|
||||
for mod in {original_module(module), current_module(module)})
|
||||
return target if _is_hermes_import(module, name, core, local) and not public else ""
|
||||
return target if _is_hermes_import(module, name, core, local) and not is_public_import(module, name) else ""
|
||||
|
||||
|
||||
def _parsed_files(plugin_dir: Path) -> list[tuple[Path, ast.AST]]:
|
||||
|
||||
@@ -14,7 +14,10 @@ plugin makes (``hermes_cli.plugin_validate_private_imports.hermes_import_sites``
|
||||
workflow and a maintainer run it, never a PR check.
|
||||
``check`` resolves every indexed import against the base and the head tree of the change,
|
||||
from git objects only (no network, no plugin code runs, nothing is imported), and
|
||||
fails when an import that resolves on the base no longer resolves on the head.
|
||||
warns, naming each import that resolves on the base but not on the head: the core
|
||||
name (private or on the published plugin API), and each plugin's catalog entry,
|
||||
repository, pin and source line. A warning, never a failure: it tells the author
|
||||
which public interface the plugins need before the break ships.
|
||||
|
||||
An import resolves when its module exists in the tree (directly or through ``hermes_agent/compat/moves.py``)
|
||||
and, for ``from module import name``, the module defines ``name`` at top level, has a submodule of that
|
||||
@@ -40,7 +43,11 @@ from pathlib import Path
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
INDEX = ROOT / "scripts" / "ci" / "catalog_core_imports"
|
||||
CATALOG = ROOT / "plugin-catalog"
|
||||
OVERRIDE_LABEL = "breaks-catalog-plugin"
|
||||
ARTIFACT = "catalog-core-imports"
|
||||
MARKETPLACE = "https://hermes-agent.nousresearch.com/marketplace"
|
||||
CATALOG_BLOB = "https://github.com/NousResearch/hermes-agent/blob/main/plugin-catalog"
|
||||
# The live CI comment is one GitHub comment (65,536 characters for every section together).
|
||||
COMMENT_DETAIL_CHARS = 30_000
|
||||
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
@@ -53,6 +60,7 @@ from hermes_cli.plugin_validate_private_imports import (
|
||||
ImportChoice,
|
||||
ImportSite,
|
||||
hermes_import_sites,
|
||||
is_public_import,
|
||||
)
|
||||
|
||||
|
||||
@@ -304,6 +312,8 @@ def _top_level_names(source: str) -> tuple[set[str], bool]:
|
||||
dynamic |= alias.name == "*"
|
||||
names.add(alias.asname or alias.name.split(".")[0])
|
||||
elif isinstance(node, (ast.Assign, ast.AnnAssign, ast.AugAssign)):
|
||||
if isinstance(node, ast.AnnAssign) and node.value is None:
|
||||
continue # ``__version__: str`` alone binds nothing
|
||||
targets = node.targets if isinstance(node, ast.Assign) else [node.target]
|
||||
names |= {n.id for t in targets for n in ast.walk(t) if isinstance(n, ast.Name)}
|
||||
elif isinstance(node, (ast.If, ast.Try, ast.With, ast.For, ast.While)):
|
||||
@@ -372,11 +382,16 @@ def _sites(branch: ImportBranch) -> list[ImportSite]:
|
||||
def _lost_sites(choice: ImportChoice, before: Resolver, after: Resolver) -> list[ImportSite]:
|
||||
"""The sites to report when no branch of ``choice`` that reaches Hermes runs on ``after`` while one did on
|
||||
``before``: what those branches no longer resolve. A ``try`` that still runs without Hermes (a handler
|
||||
with no Hermes import) has lost the feature, so it is reported too."""
|
||||
if any(_runs_on_hermes(after, branch) for branch in choice.branches):
|
||||
return []
|
||||
with no Hermes import) has lost the feature, so it is reported too. When a branch still runs on both
|
||||
trees, a ``try`` nested in it can still lose its own feature: only that branch is looked into, since an
|
||||
unused handler can resolve too."""
|
||||
surviving = [branch for branch in choice.branches if _runs_on_hermes(after, branch)]
|
||||
if surviving:
|
||||
return [site for branch in surviving if _runs_on_hermes(before, branch)
|
||||
for nested in branch.choices for site in _lost_sites(nested, before, after)]
|
||||
worked = [branch for branch in choice.branches if _runs_on_hermes(before, branch)]
|
||||
return [site for branch in worked for site in _sites(branch) if not after.resolves(site.module, site.name)]
|
||||
return [site for branch in worked for site in _sites(branch)
|
||||
if before.resolves(site.module, site.name) and not after.resolves(site.module, site.name)]
|
||||
|
||||
|
||||
def _degrades(choice: ImportChoice, after: Resolver) -> bool:
|
||||
@@ -417,55 +432,113 @@ def breaks(index: dict[str, Row], base: Tree, head: Tree) -> list[Break]:
|
||||
return found
|
||||
|
||||
|
||||
def report(found: list[Break]) -> str:
|
||||
plugins = sorted({b.plugin for b in found})
|
||||
lines = [f"This change breaks {len(plugins)} pinned catalog plugin{'s' if len(plugins) != 1 else ''} "
|
||||
f"({', '.join(plugins)}): {'they import' if len(plugins) != 1 else 'it imports'} core names "
|
||||
"this change removes or renames.", ""]
|
||||
def _source_url(entry, site: ImportSite) -> str:
|
||||
"""The import's line in the plugin's repository at its pin (GitHub and GitLab URL shapes)."""
|
||||
repo = entry.repo.removesuffix(".git").rstrip("/")
|
||||
path = f"{entry.subdir.strip('/')}/{site.rel}" if entry.subdir else site.rel
|
||||
blob = "/-/blob/" if repo.startswith("https://gitlab.com/") else "/blob/"
|
||||
return f"{repo}{blob}{entry.sha}/{path}#L{site.line}"
|
||||
|
||||
|
||||
def _plugin_lines(plugin: str, entry, found: list[Break]) -> list[str]:
|
||||
"""One plugin's catalog record, then each import the change takes from it."""
|
||||
if entry is None:
|
||||
lines = [f"- **{plugin}** (indexed, but no longer in plugin-catalog/)"]
|
||||
else:
|
||||
version = f" {entry.version}" if entry.version else ""
|
||||
lines = [f"- **{entry.title or plugin}**{version} · catalog `{plugin}` · {entry.tier} · "
|
||||
f"{entry.category} · maintainer `{entry.maintainer}`",
|
||||
f" - repo: {entry.repo}" + (f" (subdir `{entry.subdir}`)" if entry.subdir else "")
|
||||
+ f" @ `{entry.sha[:12]}`",
|
||||
f" - catalog: [{plugin}.yaml]({CATALOG_BLOB}/{plugin}.yaml) · "
|
||||
f"[marketplace]({MARKETPLACE}/{plugin})"]
|
||||
for b in found:
|
||||
how = " (inside a try: the plugin loses that feature instead of failing to load)" if b.guarded else ""
|
||||
lines.append(f" {b.plugin} {b.site.rel}:{b.site.line} imports {b.target}{how}")
|
||||
where = f"[{b.site.rel}:{b.site.line}]({_source_url(entry, b.site)})" if entry else f"{b.site.rel}:{b.site.line}"
|
||||
how = "feature lost (inside a try)" if b.guarded else "fails to load"
|
||||
lines.append(f" - {where} imports `{b.target}`: {how}")
|
||||
return lines
|
||||
|
||||
|
||||
def report(found: list[Break], catalog: dict, public_api: frozenset) -> str:
|
||||
"""Markdown: the core names to give a public interface (judged against the base's ``plugin_api.json``),
|
||||
then every affected plugin's catalog record."""
|
||||
plugins = sorted({b.plugin for b in found})
|
||||
by_target: dict[str, set[str]] = {}
|
||||
sites: dict[str, ImportSite] = {}
|
||||
for b in found:
|
||||
by_target.setdefault(b.target, set()).add(b.plugin)
|
||||
sites.setdefault(b.target, b.site)
|
||||
lines = [f"This change removes or renames {len(by_target)} core name{'s' if len(by_target) != 1 else ''} "
|
||||
f"that {len(plugins)} pinned catalog plugin{'s' if len(plugins) != 1 else ''} import. Merging it "
|
||||
"breaks them for every user on the next release.", "",
|
||||
"**Core names the plugins need** (private: needs a public interface; public API: already published in "
|
||||
"hermes_cli/data/plugin_api.json, so removing it breaks the plugin compat contract):", ""]
|
||||
for target in sorted(by_target, key=lambda t: (-len(by_target[t]), t)):
|
||||
public = "public API" if is_public_import(sites[target].module, sites[target].name, public_api) else "private"
|
||||
users = sorted(by_target[target])
|
||||
lines.append(f"- `{target}` ({public}): {len(users)} plugin{'s' if len(users) != 1 else ''}: {', '.join(users)}")
|
||||
lines += ["", "**Affected plugins:**", ""]
|
||||
for plugin in plugins:
|
||||
lines += _plugin_lines(plugin, catalog.get(plugin), [b for b in found if b.plugin == plugin])
|
||||
lines += [
|
||||
"",
|
||||
"Plugins are only promised the published plugin API (hermes_cli/data/plugin_api.json, ctx), so",
|
||||
"these imports were never supported; but merging this breaks them for every user on the next release.",
|
||||
"Pick one:",
|
||||
" 1. Open a PR for an official seam first: a ctx method, a hook, or a plugin_api.json entry that",
|
||||
" gives the plugin what it imported (plugins/AGENTS.md § Boundary lint), then tell the plugin's",
|
||||
" maintainer to move to it.",
|
||||
" 2. Keep the old name importable: a moved module gets a key in hermes_agent/compat/moves.py,",
|
||||
" a moved name stays where it was.",
|
||||
f" 3. If breaking the plugin is intended, add the `{OVERRIDE_LABEL}` label, say why in the PR body,",
|
||||
" and re-run this check.",
|
||||
"To keep these plugins working, before or with this change:",
|
||||
"1. Give each private name above a public interface: a ctx method, a hook, or a plugin_api.json entry "
|
||||
"(plugins/AGENTS.md § Boundary lint), then tell each plugin's maintainer to move to it.",
|
||||
"2. Or keep the old name importable: a moved module gets a key in hermes_agent/compat/moves.py, "
|
||||
"a moved name stays where it was.",
|
||||
"",
|
||||
"This is a warning: it does not block the merge.",
|
||||
]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def check(base_rev: str, head_rev: str, labels: list[str]) -> int:
|
||||
def _publish_warning(text: str, found: list[Break]) -> None:
|
||||
"""In CI: a warning annotation per plugin, the full report in the job summary, and a ``warning`` item in
|
||||
the live CI review comment (``review-status-catalog-core-imports``). Outside CI nothing but stdout."""
|
||||
if not os.environ.get("GITHUB_ACTIONS"):
|
||||
return
|
||||
for plugin in sorted({b.plugin for b in found}):
|
||||
targets = ", ".join(sorted({b.target for b in found if b.plugin == plugin}))
|
||||
print(f"::warning title=Breaks catalog plugin {plugin}::{plugin} imports {targets}, which this change removes")
|
||||
summary = os.environ.get("GITHUB_STEP_SUMMARY")
|
||||
if summary:
|
||||
with open(summary, "a", encoding="utf-8") as fh:
|
||||
fh.write(f"## Catalog plugins this change breaks\n\n{text}\n")
|
||||
from scripts.ci.review_status import publish
|
||||
|
||||
detail = text if len(text) <= COMMENT_DETAIL_CHARS else (
|
||||
text[:COMMENT_DETAIL_CHARS].rpartition("\n")[0] + "\n\n…cut here; the job summary has the full list.")
|
||||
plugins = len({b.plugin for b in found})
|
||||
publish([{"source": ARTIFACT, "results": [{
|
||||
"kind": "warning", "title": "Catalog plugins this change breaks",
|
||||
"summary": f"{plugins} pinned catalog plugin{'s' if plugins != 1 else ''} import core names this change "
|
||||
"removes or renames.",
|
||||
"detail": detail}]}], ARTIFACT, output=False)
|
||||
|
||||
|
||||
def _public_api(tree: Tree) -> frozenset:
|
||||
"""``plugin_api.json``'s entries as ``tree`` has them (empty when it has none)."""
|
||||
path = "hermes_cli/data/plugin_api.json"
|
||||
if path not in tree.files:
|
||||
return frozenset()
|
||||
return frozenset(entry for group in json.loads(tree.read(path))["groups"] for entry in group["entries"])
|
||||
|
||||
|
||||
def check(base_rev: str, head_rev: str) -> int:
|
||||
"""Always 0: a break is reported as a warning, never a failure."""
|
||||
from hermes_cli.plugin_catalog import load_catalog
|
||||
|
||||
index = read_index()
|
||||
found = breaks(index, Tree(ROOT, base_rev), Tree(ROOT, head_rev))
|
||||
base = Tree(ROOT, base_rev)
|
||||
found = breaks(index, base, Tree(ROOT, head_rev))
|
||||
if not found:
|
||||
print(f"no pinned catalog plugin loses a core import ({len(index)} entries indexed)")
|
||||
return 0
|
||||
print(report(found))
|
||||
if OVERRIDE_LABEL in labels:
|
||||
print(f"\nThe `{OVERRIDE_LABEL}` label accepts these breaks.")
|
||||
return 0
|
||||
return 1
|
||||
|
||||
|
||||
def _pull_request_labels() -> list[str]:
|
||||
"""The PR's labels as they are now (a re-run replays the event that started it)."""
|
||||
repo, event = os.environ.get("GITHUB_REPOSITORY", ""), os.environ.get("GITHUB_EVENT_PATH", "")
|
||||
try:
|
||||
number = json.loads(Path(event).read_text(encoding="utf-8-sig"))["pull_request"]["number"] if event else None
|
||||
except (OSError, KeyError, TypeError, json.JSONDecodeError):
|
||||
number = None
|
||||
if not repo or not number:
|
||||
return []
|
||||
out = subprocess.run(["gh", "api", f"repos/{repo}/pulls/{number}", "--jq", ".labels[].name"], capture_output=True,
|
||||
text=True, encoding="utf-8", stdin=subprocess.DEVNULL, check=False, timeout=60)
|
||||
return out.stdout.split() if out.returncode == 0 else []
|
||||
text = report(found, {e.name: e for e in load_catalog(CATALOG)}, _public_api(base))
|
||||
print(text)
|
||||
_publish_warning(text, found)
|
||||
return 0
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
@@ -475,13 +548,13 @@ def main(argv: list[str] | None = None) -> int:
|
||||
b.add_argument("names", nargs="*", help="entries to re-index (default: those whose pin changed)")
|
||||
b.add_argument("--all", action="store_true", help="re-index every entry")
|
||||
b.add_argument("--jobs", type=int, default=16)
|
||||
c = sub.add_parser("check", help="fail when the change breaks an indexed import")
|
||||
c = sub.add_parser("check", help="warn about the indexed imports the change breaks")
|
||||
c.add_argument("--base", default="HEAD^1", help="base commit (default: the merge commit's first parent)")
|
||||
c.add_argument("--head", default="HEAD", help="head commit (default: HEAD, the merge commit)")
|
||||
args = parser.parse_args(argv)
|
||||
if args.command == "build":
|
||||
return build(args.names, args.all, args.jobs)
|
||||
return check(args.base, args.head, _pull_request_labels())
|
||||
return check(args.base, args.head)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -6,6 +6,7 @@ comes from the same fetch-and-parse path the scheduled build runs.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
@@ -106,11 +107,9 @@ def _check(repo: Path, index: dict, files: dict) -> list[tuple[str, str]]:
|
||||
|
||||
|
||||
def test_removing_a_name_a_pinned_plugin_imports_is_named_and_a_kept_spelling_is_not(index, core):
|
||||
repo, base = core
|
||||
repo, _base = core
|
||||
removed = _check(repo, index, {"tools/registry.py": "def other(): ...\n"})
|
||||
assert removed == [("__init__.py:2", "tools.registry.registry_helper")]
|
||||
assert "Open a PR for an official seam" in cci.report(
|
||||
cci.breaks(index, cci.Tree(repo, base), cci.Tree(repo, "HEAD")))
|
||||
_commit(repo, {"tools/registry.py": "def registry_helper(): ...\n"})
|
||||
|
||||
# The removed module only ever stood in for sqlite_support behind the plugin's own try: nothing breaks.
|
||||
@@ -134,6 +133,8 @@ def test_removing_a_name_a_pinned_plugin_imports_is_named_and_a_kept_spelling_is
|
||||
MOVED = 'MOVES: dict[str, str] = {"tools.old": "tools.new"}\n'
|
||||
TWO_LEVELS = ("try:\n from tools.a import x\n try:\n from tools.b import y\n except ImportError:\n"
|
||||
" from tools.c import y\nexcept ImportError:\n x = None\n")
|
||||
OPTIONAL_INNER = ("try:\n from tools.a import x\n try:\n from tools.b import y\n except ImportError:\n"
|
||||
" y = None\nexcept ImportError:\n x = None\n")
|
||||
ELSE_AND_TYPING = ("from typing import TYPE_CHECKING\nif TYPE_CHECKING:\n from tools.registry import only_typing\n"
|
||||
"try:\n import json\nexcept ImportError:\n json = None\nelse:\n from tools.registry import helper\n")
|
||||
|
||||
@@ -151,6 +152,9 @@ ELSE_AND_TYPING = ("from typing import TYPE_CHECKING\nif TYPE_CHECKING:\n fro
|
||||
# A body whose nested try fails as a whole does not run, whatever its own imports do.
|
||||
(TWO_LEVELS, {"tools/a.py": "x = 1\n", "tools/b.py": "y = 1\n", "tools/c.py": "y = 1\n"},
|
||||
{"tools/b.py": "", "tools/c.py": ""}, [("__init__.py:4", "tools.b.y"), ("__init__.py:6", "tools.c.y")]),
|
||||
# A try nested in a body that still runs loses its own feature: the outer import surviving hides nothing.
|
||||
(OPTIONAL_INNER, {"tools/a.py": "x = 1\n", "tools/b.py": "y = 1\n"}, {"tools/b.py": ""},
|
||||
[("__init__.py:4", "tools.b.y")]),
|
||||
# An ``else:`` block is checked like any plain import; a ``TYPE_CHECKING`` import never loads.
|
||||
(ELSE_AND_TYPING, {"tools/registry.py": "helper = only_typing = 1\n"}, {"tools/registry.py": ""},
|
||||
[("__init__.py:9", "tools.registry.helper")]),
|
||||
@@ -224,14 +228,42 @@ def test_a_module_getattr_answers_only_the_names_it_spells(index, core):
|
||||
assert _check(repo, index, {"tools/registry.py": "def other(): ...\n"}) == []
|
||||
|
||||
|
||||
def test_the_label_lets_an_intended_break_through(index, core, monkeypatch, capsys):
|
||||
repo, base = core
|
||||
head = _commit(repo, {"agent/memory_provider.py": "class Other: ...\n"})
|
||||
monkeypatch.setattr(cci, "ROOT", repo)
|
||||
monkeypatch.setattr(cci, "read_index", lambda: index)
|
||||
assert cci.check(base, head, []) == 1
|
||||
assert "demo __init__.py:1 imports agent.memory_provider.MemoryProvider" in capsys.readouterr().out
|
||||
assert cci.check(base, head, [cci.OVERRIDE_LABEL]) == 0
|
||||
def test_a_break_is_a_warning_naming_the_core_name_and_the_plugins_catalog_record(
|
||||
index, core, tmp_path, monkeypatch, capsys):
|
||||
repo, _base = core
|
||||
# Judged against the BASE's published API: this tree publishes MemoryProvider and nothing else.
|
||||
api = json.dumps({"groups": [{"entries": ["agent.memory_provider:MemoryProvider"]}]})
|
||||
base = _commit(repo, {"hermes_cli/data/plugin_api.json": api})
|
||||
head = _commit(repo, {"agent/memory_provider.py": "class Other: ...\n",
|
||||
"hermes_state_wal.py": None, "sqlite_support.py": None})
|
||||
sha = next(iter(index.values())).sha
|
||||
catalog = tmp_path / "catalog"
|
||||
catalog.mkdir()
|
||||
(catalog / "demo.yaml").write_text(
|
||||
f"name: demo\nrepo: https://github.com/acme/demo-plugin\nsha: {sha}\nsubdir: plugin\nversion: '1.4.0'\n"
|
||||
"description: d\nmaintainer: acme\ntier: community\ncategory: memory\n", encoding="utf-8")
|
||||
for name, value in {"ROOT": repo, "CATALOG": catalog, "read_index": lambda: index}.items():
|
||||
monkeypatch.setattr(cci, name, value)
|
||||
monkeypatch.setenv("GITHUB_ACTIONS", "true")
|
||||
monkeypatch.setenv("RUNNER_TEMP", str(tmp_path / "runner"))
|
||||
monkeypatch.setenv("GITHUB_STEP_SUMMARY", str(tmp_path / "summary.md"))
|
||||
|
||||
assert cci.check(base, head) == 0 # a warning, never a failure
|
||||
out = capsys.readouterr().out
|
||||
# The core name, whether a plugin may rely on it, and who imports it.
|
||||
assert "`agent.memory_provider.MemoryProvider` (public API): 1 plugin: demo" in out
|
||||
assert "`hermes_state_wal.wal_mode` (private): 1 plugin: demo" in out
|
||||
# The plugin's catalog record: repo, subdir and pin, catalog file, and a link to the import line.
|
||||
assert f"repo: https://github.com/acme/demo-plugin (subdir `plugin`) @ `{sha[:12]}`" in out
|
||||
assert "plugin-catalog/demo.yaml" in out and "maintainer `acme`" in out and "1.4.0" in out
|
||||
assert f"https://github.com/acme/demo-plugin/blob/{sha}/plugin/__init__.py#L1" in out
|
||||
assert "::warning title=Breaks catalog plugin demo::" in out
|
||||
assert "hermes_state_wal.wal_mode" in (tmp_path / "summary.md").read_text(encoding="utf-8")
|
||||
status = (tmp_path / "runner" / "review-status" / "catalog-core-imports" / "review-status.json").read_text(
|
||||
encoding="utf-8")
|
||||
(entry,) = json.loads(status.removeprefix("review_status="))
|
||||
assert entry["results"][0]["kind"] == "warning"
|
||||
assert "acme/demo-plugin" in entry["results"][0]["detail"]
|
||||
|
||||
|
||||
def test_a_failed_read_or_a_moved_subdir_is_read_again(index):
|
||||
|
||||
@@ -392,17 +392,22 @@ They follow the `hermes_state` window: supported through v0.26 and removed no ea
|
||||
|
||||
#### Core PRs that break a pinned catalog plugin
|
||||
|
||||
A core pull request that removes or renames a module or name some pinned catalog plugin imports fails the **Name the pinned catalog plugins this change breaks** step of Repository guards. That check covers private imports too. It reads `scripts/ci/catalog_core_imports/`, which records every Hermes import each catalog entry makes at its pinned sha and is refreshed daily for new entries and repins. It resolves those imports against the PR's base and merge commit, so it needs no network, runs no plugin code and takes a few seconds. The failure names the plugin, its `file:line` and the import, for example:
|
||||
A core pull request that removes or renames a module or name some pinned catalog plugin imports gets a warning from the **Name the pinned catalog plugins this change breaks** step of Repository guards. It never blocks the merge: it tells the author which public interface the plugins need before the break ships. The check covers private imports too. It reads `scripts/ci/catalog_core_imports/`, which records every Hermes import each catalog entry makes at its pinned sha and is refreshed daily for new entries and repins. It resolves those imports against the PR's base and merge commit, so it needs no network, runs no plugin code and takes a few seconds.
|
||||
|
||||
The warning appears as a check annotation per plugin, in the job summary, and in the CI review comment on the PR. It lists each core name the change takes away, whether it is private (not in `hermes_cli/data/plugin_api.json`) and how many plugins import it, then each affected plugin's catalog record: title, version, tier, category, maintainer, repository (and subdir) at its pinned sha, a link to its `plugin-catalog/<name>.yaml` and marketplace page, and a link to each import line. For example:
|
||||
|
||||
```
|
||||
holographic store.py:227 imports hermes_state_wal.apply_wal_with_fallback
|
||||
- `hermes_state_wal.apply_wal_with_fallback` (private): 1 plugin: holographic
|
||||
...
|
||||
- **holographic** 0.29.2 · catalog `holographic` · community · memory · maintainer `...`
|
||||
- repo: https://github.com/... @ `<pin>`
|
||||
- store.py:227 imports `hermes_state_wal.apply_wal_with_fallback`: fails to load
|
||||
```
|
||||
|
||||
An import inside a `try` whose fallback still resolves is not a break. Pick one fix:
|
||||
An import inside a `try` whose fallback still resolves is not a break. To keep the plugins working:
|
||||
|
||||
1. **Open a PR for an official seam** (a `ctx` method, a hook, or a `hermes_cli/data/plugin_api.json` entry listed in [the public plugin API](public-api.md)), then ask the plugin's maintainer to move to it.
|
||||
2. **Keep the old name importable**: a moved module gets a key in `hermes_agent/compat/moves.py`, and a moved name stays where it was.
|
||||
3. **If breaking it is intended**, add the `breaks-catalog-plugin` label, say why in the PR body, and re-run the check.
|
||||
1. **Give the name a public interface** (a `ctx` method, a hook, or a `hermes_cli/data/plugin_api.json` entry listed in [the public plugin API](public-api.md)), then ask each plugin's maintainer to move to it.
|
||||
2. **Or keep the old name importable**: a moved module gets a key in `hermes_agent/compat/moves.py`, and a moved name stays where it was.
|
||||
|
||||
Run it locally with `python3 scripts/ci/catalog_core_imports.py check --base "$(git merge-base origin/main HEAD)"` (the merge base, so a branch is not blamed for what `main` added since it was cut), and re-index one entry with `python3 scripts/ci/catalog_core_imports.py build <name>`. The check only asks whether an imported name still exists. A name that stays but changes behaviour or signature passes, and so does a name read as an attribute after `import module` (`hermes_constants.get_hermes_home()`), where only the module is imported.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user