From 520931ca34a75ea0455de40c9033cdec883df0a6 Mon Sep 17 00:00:00 2001 From: cflmy Date: Fri, 27 Nov 2026 01:55:03 +0800 Subject: [PATCH] feat(impact): recursive candidate impact analysis over the union graph Implement the ECO-02 impact contract: compare the recursively expanded (global_id, parent, remote, SHA, state) identities of an accepted root commit and a candidate, expand domain gitlink changes to child identities, close over the reverse requires graph built from the union of both revisions, add parent domains, then reach a fixed point over checks_with. An unexpandable domain is reported UNVERIFIED and widens the affected set to the full candidate instead of skipping (--fail-on-unverified makes it fatal). integration.sh runs it against the accepted root ref (PR target branch or origin/main) and records changed/affected/checks_with/fallback in the candidate evidence JSON. Five contract tests build real temporary Git repositories, including a domain gitlink change and the conservative fallback. Refs cflmy/marqdo#7 --- docs/DEVELOPMENT.md | 2 +- scripts/impact.py | 333 +++++++++++++++++++++++++++++++ scripts/integration.sh | 27 +++ tests/integration/test_impact.py | 274 +++++++++++++++++++++++++ 4 files changed, 635 insertions(+), 1 deletion(-) create mode 100755 scripts/impact.py create mode 100644 tests/integration/test_impact.py diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 366d6b4..b62880f 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -57,7 +57,7 @@ bash scripts/integration.sh # 生态候选:真实 CLI 制品 + ## 影响范围与调度 -比较已接受根提交与候选递归展开的 `(global_id, parent, remote, SHA, state)`;领域指针变化必须展开差异,不能只标记父节点。变更叶子加入集合后,取反向传递依赖闭包,再加所在祖先领域及需要协同验收的 `checks_with`(固定点去重、不作为构建先决);公共协议/权限/根集成逻辑变化触发相应全量 conformance 与消费者。删除或移动组件用新旧图并集计算受影响者。无法确定影响范围时全量而非跳过;正式发行执行所有 active 组件与完整测试。 +根 `scripts/impact.py` 比较已接受根提交与候选递归展开的 `(global_id, parent, remote, SHA, state)`:领域指针变化展开到子组件身份,不能只标记父节点;变更叶子加入集合后,取 `requires` 新旧图并集的反向传递依赖闭包,再加所在祖先领域及 `checks_with` 固定点(协同验收不是构建先决)。领域无法展开(缺对象/检出)时结果标 UNVERIFIED 并**全量**扩大范围,不静默跳过;`--fail-on-unverified` 可把该情形变成硬失败。`integration.sh` 将报告写入候选证据(changed/affected/checks_with/fallback),正式发行仍执行所有 active 组件与完整测试。 ## 工单路由与状态 diff --git a/scripts/impact.py b/scripts/impact.py new file mode 100755 index 0000000..932b8ee --- /dev/null +++ b/scripts/impact.py @@ -0,0 +1,333 @@ +#!/usr/bin/env python3 +"""Recursive impact analysis between an accepted root commit and a candidate. + +Compares the recursively expanded governance tree of two root revisions. A +component identity is `(global_id, parent, remote, SHA, state)`; a domain +gitlink change is expanded to its child identities so leaf changes are visible +even when the parent pointer did not change as a string. + +The affected set is computed in the order the development contract requires: + +1. changed or removed leaves; +2. reverse transitive closure over `requires` edges from the union of both + graphs (removed edges cannot hide a consumer); +3. parent domains of affected components; +4. `checks_with` fixed point (co-validation is not a build prerequisite). + +When a domain cannot be expanded (missing object/checkout) the result is marked +UNVERIFIED and the whole domain is treated as affected rather than silently +skipping it. +""" + +from __future__ import annotations + +import argparse +import json +import subprocess +import sys +import tomllib +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +SCHEMA = "marqdo.impact" +SCHEMA_VERSION = 1 + + +class ImpactError(Exception): + pass + + +def git(repo: Path, *args: str) -> bytes: + result = subprocess.run(["git", "-C", str(repo), *args], capture_output=True) + if result.returncode != 0: + raise ImpactError( + f"git {' '.join(args)} failed in {repo}: " + f"{result.stderr.decode(errors='replace').strip()}" + ) + return result.stdout + + +def show(repo: Path, revision: str, path: str) -> bytes | None: + result = subprocess.run( + ["git", "-C", str(repo), "show", f"{revision}:{path}"], capture_output=True + ) + return result.stdout if result.returncode == 0 else None + + +def resolve(repo: Path, revision: str) -> str: + try: + return ( + git(repo, "rev-parse", "--verify", revision + "^{commit}") + .decode() + .strip() + ) + except ImpactError as error: + raise ImpactError(f"cannot resolve revision {revision!r}: {error}") from error + + +def tree_entries(repo: Path, revision: str) -> dict[str, tuple[str, str]]: + output = git(repo, "ls-tree", "-r", "-z", revision) + entries: dict[str, tuple[str, str]] = {} + for record in output.split(b"\0"): + if not record: + continue + header, _, raw_path = record.partition(b"\t") + fields = header.decode().split() + if len(fields) != 3: + raise ImpactError(f"invalid tree record in {repo}@{revision}") + mode, _kind, sha = fields + entries[raw_path.decode()] = (mode, sha) + return entries + + +def submodule_urls(repo: Path, revision: str) -> dict[str, str]: + """Map `.gitmodules` path to URL at a revision (authority for remotes).""" + raw = show(repo, revision, ".gitmodules") + if raw is None: + return {} + config = git( + repo, "config", "--null", "--blob", f"{revision}:.gitmodules", "--list" + ) + urls: dict[str, str] = {} + pending: dict[str, dict[str, str]] = {} + for record in config.split(b"\0"): + if not record: + continue + key, _, value = record.decode(errors="replace").partition("\n") + parts = key.split(".") + if len(parts) == 4 and parts[0] == "submodule" and parts[3] in ("path", "url"): + pending.setdefault(parts[1], {})[parts[3]] = value + for fields in pending.values(): + if "path" in fields and "url" in fields: + urls[fields["path"]] = fields["url"] + return urls + + +def read_catalog(repo: Path, revision: str, label: str) -> list[dict]: + raw = show(repo, revision, "components.toml") + if raw is None: + raise ImpactError(f"{label}: revision {revision} has no components.toml") + try: + catalog = tomllib.loads(raw.decode()) + except (UnicodeDecodeError, tomllib.TOMLDecodeError) as error: + raise ImpactError(f"{label}: invalid components.toml: {error}") from error + components = catalog.get("component") + if not isinstance(components, list): + raise ImpactError(f"{label}: components.toml has no [[component]] entries") + return components + + +def load_graph( + repo: Path, revision: str, label: str, depth: int = 0 +) -> tuple[dict[str, dict], list[str]]: + """Expand one governance layer (root then domains) into global identities.""" + components = read_catalog(repo, revision, label) + entries = tree_entries(repo, revision) + urls = submodule_urls(repo, revision) + gitlinks = {path: sha for path, (mode, sha) in entries.items() if mode == "160000"} + graph: dict[str, dict] = {} + unverified: list[str] = [] + for component in components: + component_id = component.get("id") + path = component.get("path") + if not isinstance(component_id, str) or not isinstance(path, str): + raise ImpactError(f"{label}: component without id/path") + sha = gitlinks.get(path) + identity = { + "id": component_id, + "parent": None, + "path": path, + "remote": urls.get(path), + "sha": sha, + "state": component.get("state"), + "kind": component.get("kind"), + "requires": sorted(component.get("requires", [])), + "checks_with": sorted(component.get("checks_with", [])), + "layer": label, + } + graph[component_id] = identity + if component.get("kind") != "domain" or depth > 0: + continue + domain_repo = repo / path + if sha is None or not (domain_repo / ".git").exists(): + unverified.append( + f"{label}: domain {component_id} ({path}) cannot be expanded: " + "missing gitlink or checkout" + ) + continue + try: + children, child_unverified = load_graph( + domain_repo, sha, f"domain {component_id}", depth + 1 + ) + except ImpactError as error: + unverified.append( + f"{label}: domain {component_id} ({path})@{sha} cannot be expanded: {error}" + ) + continue + unverified.extend(child_unverified) + for child_id, child in children.items(): + if child_id in graph: + raise ImpactError(f"{label}: duplicate global id {child_id}") + child["parent"] = component_id + graph[child_id] = child + return graph, unverified + + +def identity_fields(component: dict) -> tuple: + return ( + component.get("parent"), + component.get("remote"), + component.get("sha"), + component.get("state"), + tuple(component.get("requires", [])), + tuple(component.get("checks_with", [])), + ) + + +def changed_components( + accepted: dict[str, dict], candidate: dict[str, dict] +) -> list[dict]: + changed = [] + for component_id in sorted(set(accepted) | set(candidate)): + before = accepted.get(component_id) + after = candidate.get(component_id) + if before is None: + changed.append({"id": component_id, "reason": "added"}) + continue + if after is None: + changed.append({"id": component_id, "reason": "removed"}) + continue + if before.get("sha") != after.get("sha"): + changed.append({"id": component_id, "reason": "sha"}) + elif before.get("state") != after.get("state"): + changed.append({"id": component_id, "reason": "state"}) + elif before.get("remote") != after.get("remote"): + changed.append({"id": component_id, "reason": "remote"}) + elif before.get("parent") != after.get("parent"): + changed.append({"id": component_id, "reason": "parent"}) + elif before.get("requires") != after.get("requires") or before.get( + "checks_with" + ) != after.get("checks_with"): + changed.append({"id": component_id, "reason": "dependencies"}) + return changed + + +def affected_set( + accepted: dict[str, dict], candidate: dict[str, dict], changed: list[dict] +) -> tuple[list[str], list[str], list[str]]: + graph = {**accepted, **candidate} + dependents: dict[str, set[str]] = {component_id: set() for component_id in graph} + for component in graph.values(): + for dependency in component.get("requires", []): + dependents.setdefault(dependency, set()).add(component["id"]) + affected = {item["id"] for item in changed} + queue = list(affected) + while queue: + current = queue.pop() + for consumer in dependents.get(current, set()): + if consumer not in affected: + affected.add(consumer) + queue.append(consumer) + domains = set() + for component_id in list(affected): + parent = graph[component_id].get("parent") + while parent: + if parent not in affected: + domains.add(parent) + parent = graph[parent].get("parent") if parent in graph else None + co_validation: set[str] = set() + while True: + additions = set() + for component_id in affected: + for partner in graph[component_id].get("checks_with", []): + if partner not in affected: + additions.add(partner) + if not additions: + break + affected |= additions + co_validation |= additions + return sorted(affected), sorted(domains), sorted(co_validation) + + +def analyze(accepted_ref: str, candidate_ref: str) -> dict: + accepted_revision = resolve(ROOT, accepted_ref) + candidate_revision = resolve(ROOT, candidate_ref) + accepted, accepted_unverified = load_graph(ROOT, accepted_revision, "root") + candidate, candidate_unverified = load_graph(ROOT, candidate_revision, "root") + changed = changed_components(accepted, candidate) + affected, domains, co_validation = affected_set(accepted, candidate, changed) + unverified = accepted_unverified + candidate_unverified + fallback = None + if unverified: + # Undetermined scope must widen, never silently skip. + affected = sorted(set(accepted) | set(candidate)) + domains = [] + co_validation = [] + fallback = "full" + return { + "schema": SCHEMA, + "schema_version": SCHEMA_VERSION, + "accepted": {"ref": accepted_ref, "revision": accepted_revision}, + "candidate": {"ref": candidate_ref, "revision": candidate_revision}, + "counts": { + "accepted_components": len(accepted), + "candidate_components": len(candidate), + "changed": len(changed), + "affected": len(affected), + }, + "changed": changed, + "affected": affected, + "domain_ancestors": domains, + "checks_with": co_validation, + "fallback": fallback, + "unverified": unverified, + } + + +def main(argv: list[str]) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--accepted", required=True, help="accepted root revision") + parser.add_argument("--candidate", default="HEAD", help="candidate root revision") + parser.add_argument("--out", default=None) + parser.add_argument("--json", action="store_true") + parser.add_argument( + "--fail-on-unverified", + action="store_true", + help="exit 2 when a domain cannot be expanded", + ) + args = parser.parse_args(argv) + try: + report = analyze(args.accepted, args.candidate) + except ImpactError as error: + print(f"impact: error: {error}", file=sys.stderr) + return 1 + text = json.dumps(report, ensure_ascii=False, indent=2) + "\n" + if args.out: + Path(args.out).write_text(text) + if args.json: + print(text, end="") + else: + print( + f"accepted {report['accepted']['revision'][:12]} " + f"candidate {report['candidate']['revision'][:12]}" + ) + print( + f"changed={report['counts']['changed']} " + f"affected={report['counts']['affected']}" + ) + for item in report["changed"]: + print(f" changed {item['id']}: {item['reason']}") + print("affected: " + ", ".join(report["affected"])) + if report["checks_with"]: + print("co-validation: " + ", ".join(report["checks_with"])) + if report["fallback"]: + print("fallback: full (impact scope undetermined)") + for note in report["unverified"]: + print(f"UNVERIFIED: {note}", file=sys.stderr) + if args.fail_on_unverified and report["unverified"]: + return 2 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv[1:])) diff --git a/scripts/integration.sh b/scripts/integration.sh index 2f6ac32..eb2ba8d 100755 --- a/scripts/integration.sh +++ b/scripts/integration.sh @@ -33,6 +33,22 @@ python3 -c 'import jsonschema' python3 scripts/check-layout.py --checkouts > "$work/layout.txt" cat "$work/layout.txt" +# Recursive impact analysis against the accepted root commit: the change set +# comes from the recursively expanded (global_id, parent, remote, SHA, state) +# identities, then reverse `requires` closure, parent domains and `checks_with` +# fixed point. An undetermined scope widens to the full candidate. +accepted_ref="${MARQDO_ACCEPTED_REF:-}" +if [[ -z "$accepted_ref" && -n "${CI_COMMIT_TARGET_BRANCH:-}" ]] \ + && git rev-parse --verify "origin/$CI_COMMIT_TARGET_BRANCH" >/dev/null 2>&1; then + accepted_ref="origin/$CI_COMMIT_TARGET_BRANCH" +elif [[ -z "$accepted_ref" ]] && git rev-parse --verify origin/main >/dev/null 2>&1; then + accepted_ref="origin/main" +fi +if [[ -n "$accepted_ref" ]]; then + python3 scripts/impact.py --accepted "$accepted_ref" --candidate HEAD \ + --out "$work/impact.json" +fi + # 1. One Bundle, produced by the root-owned producer from the pinned gitlinks. python3 scripts/build-stdlib.py --out "$work/stdlib" | tee "$work/bundle.json" bundle_digest="$(python3 -c 'import json,sys; print(json.load(sys.stdin)["tree_digest"])' < "$work/bundle.json")" @@ -150,6 +166,17 @@ evidence = { "stdlib_aliases_digest": sys.argv[5], "archive": archive.name, "archive_sha256": "sha256:" + hashlib.sha256(archive.read_bytes()).hexdigest(), + "impact": ( + { + "changed": impact["changed"], + "affected": impact["affected"], + "checks_with": impact["checks_with"], + "fallback": impact["fallback"], + "unverified": impact["unverified"], + } + if impact + else None + ), "status": "PASS", } (work / "integration-evidence.json").write_text(json.dumps(evidence, indent=2) + "\n") diff --git a/tests/integration/test_impact.py b/tests/integration/test_impact.py new file mode 100644 index 0000000..2e43318 --- /dev/null +++ b/tests/integration/test_impact.py @@ -0,0 +1,274 @@ +"""Recursive impact analysis contract tests (ECO-02 / issue #7). + +Builds real temporary Git repositories for two root candidates and asserts the +ordering required by the development contract: changed leaves, reverse +`requires` closure over the union graph, parent domains, then `checks_with` +fixed point; undetermined scope widens to the full candidate instead of being +skipped. +""" + +import importlib.util +import os +import subprocess +import tempfile +import unittest +from pathlib import Path + +SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "impact.py" +SPEC = importlib.util.spec_from_file_location("impact", SCRIPT) +impact = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(impact) + +GIT_ENV = { + "GIT_AUTHOR_NAME": "test", + "GIT_AUTHOR_EMAIL": "test@example.invalid", + "GIT_COMMITTER_NAME": "test", + "GIT_COMMITTER_EMAIL": "test@example.invalid", +} + + +def git(cwd, *args, check=True): + env = os.environ.copy() + env.update(GIT_ENV) + result = subprocess.run( + ["git", "-C", str(cwd), *args], capture_output=True, env=env + ) + if check and result.returncode != 0: + raise AssertionError( + f"git {' '.join(args)} failed: {result.stderr.decode(errors='replace')}" + ) + return result.stdout.decode() + + +def init(path: Path) -> Path: + path.mkdir(parents=True, exist_ok=True) + git(path, "init", "-q") + return path + + +def write(path: Path, data) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data if isinstance(data, bytes) else data.encode()) + + +def commit(repo: Path, message: str = "fixture") -> str: + git(repo, "add", "-A") + git(repo, "commit", "-q", "-m", message) + return git(repo, "rev-parse", "HEAD").strip() + + +def component(**fields) -> str: + lines = ["[[component]]"] + for key, value in fields.items(): + if isinstance(value, list): + rendered = "[" + ", ".join(f'"{item}"' for item in value) + "]" + else: + rendered = f'"{value}"' + lines.append(f"{key} = {rendered}") + return "\n".join(lines) + + +def catalog(*components: str) -> str: + return "\n\n".join(components) + "\n" + + +def leaf(base: Path, name: str, files: dict[str, str]) -> str: + repo = init(base / name) + for relative, data in files.items(): + write(repo / relative, data) + return commit(repo) + + +def root_repo( + path: Path, catalog_text: str, links: dict[str, str], urls: dict[str, str] | None = None +) -> str: + init(path) + write(path / "components.toml", catalog_text) + if urls: + modules = ["[submodule \"x\"]"] + lines = [] + for link_path, url in urls.items(): + lines.extend([f"\tpath = {link_path}", f"\turl = {url}"]) + write(path / ".gitmodules", "\n".join(modules + lines) + "\n") + git(path, "add", ".gitmodules") + git(path, "add", "components.toml") + for link_path, sha in links.items(): + git(path, "update-index", "--add", "--cacheinfo", f"160000,{sha},{link_path}") + git(path, "commit", "-q", "-m", "root fixture") + return git(path, "rev-parse", "HEAD").strip() + + +COMPONENTS_V1 = catalog( + component(id="cli", path="cli", kind="core", state="active", owner="t", scope="s", + requires=[], checks_with=[], release="base"), + component(id="std-core", path="stdlib/core", kind="stdlib", state="active", owner="t", + scope="s", requires=["cli"], checks_with=[], release="base"), + component(id="std-text", path="stdlib/text", kind="stdlib", state="active", owner="t", + scope="s", requires=["cli", "std-core"], checks_with=["probe"], release="base"), + component(id="probe", path="tools/probe", kind="tool", state="active", owner="t", + scope="s", requires=["cli"], checks_with=["std-text"], release="optional"), + component(id="tool", path="tools/tool", kind="tool", state="active", owner="t", + scope="s", requires=["cli"], checks_with=[], release="optional"), +) + + +class ImpactTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.base = Path(self.tmp.name) + self.root = self.base / "root" + self.original_root = impact.ROOT + + def tearDown(self): + impact.ROOT = self.original_root + self.tmp.cleanup() + + def make_tree(self, catalog_text: str, leaves: dict[str, str]) -> str: + return root_repo(self.root, catalog_text, {path: leaves[name] for name, path in { + "cli": "cli", "std-core": "stdlib/core", "std-text": "stdlib/text", + "probe": "tools/probe", "tool": "tools/tool", + }.items() if name in leaves}) + + def leaf_shas(self): + return { + "cli": leaf(self.base, "cli", {"README.md": "cli"}), + "std-core": leaf(self.base, "core", {"modules/core.mq.md": "# core\n"}), + "std-text": leaf(self.base, "text", {"modules/text.mq.md": "# text\n"}), + "probe": leaf(self.base, "probe", {"README.md": "probe"}), + "tool": leaf(self.base, "tool", {"README.md": "tool"}), + } + + def analyze(self, first: str, second: str): + impact.ROOT = self.root + return impact.analyze(first, second) + + def test_changed_leaf_closes_over_requires_then_checks_with(self): + leaves = self.leaf_shas() + first = self.make_tree(COMPONENTS_V1, leaves) + leaves["std-core"] = leaf(self.base, "core2", {"modules/core.mq.md": "# core v2\n"}) + second = root_repo( + self.root, + COMPONENTS_V1, + { + "cli": leaves["cli"], + "stdlib/core": leaves["std-core"], + "stdlib/text": leaves["std-text"], + "tools/probe": leaves["probe"], + "tools/tool": leaves["tool"], + }, + ) + report = self.analyze(first, second) + self.assertEqual( + [(c["id"], c["reason"]) for c in report["changed"]], + [("std-core", "sha")], + ) + self.assertEqual(report["affected"], ["probe", "std-core", "std-text"]) + self.assertEqual(report["checks_with"], ["probe"]) + self.assertNotIn("tool", report["affected"]) + + def test_removed_component_and_its_checks_with_partner_are_affected(self): + leaves = self.leaf_shas() + first = self.make_tree(COMPONENTS_V1, leaves) + without_text = catalog( + component(id="cli", path="cli", kind="core", state="active", owner="t", + scope="s", requires=[], checks_with=[], release="base"), + component(id="std-core", path="stdlib/core", kind="stdlib", state="active", + owner="t", scope="s", requires=["cli"], checks_with=[], release="base"), + component(id="probe", path="tools/probe", kind="tool", state="active", owner="t", + scope="s", requires=["cli"], checks_with=["std-text"], release="optional"), + component(id="tool", path="tools/tool", kind="tool", state="active", owner="t", + scope="s", requires=["cli"], checks_with=[], release="optional"), + ) + second = root_repo( + self.root, + without_text, + { + "cli": leaves["cli"], + "stdlib/core": leaves["std-core"], + "tools/probe": leaves["probe"], + "tools/tool": leaves["tool"], + }, + ) + report = self.analyze(first, second) + self.assertIn({"id": "std-text", "reason": "removed"}, report["changed"]) + self.assertIn("probe", report["affected"]) + + def test_dependency_change_is_reported_and_widens_scope(self): + leaves = self.leaf_shas() + first = self.make_tree(COMPONENTS_V1, leaves) + changed_text = COMPONENTS_V1.replace( + 'requires = ["cli", "std-core"]', 'requires = ["cli", "std-core", "tool"]' + ) + second = self.make_tree(changed_text, leaves) + report = self.analyze(first, second) + self.assertEqual( + [(c["id"], c["reason"]) for c in report["changed"]], + [("std-text", "dependencies")], + ) + self.assertIn("std-text", report["affected"]) + + def test_domain_gitlink_change_expands_to_child_identity(self): + child = init(self.root / "extensions/web") + write(child / "components.toml", catalog( + component(id="web-design", path="design", kind="stdlib", state="planned", + owner="t", scope="s", requires=["cli"], checks_with=[], release="base"), + )) + design = leaf(self.base, "design", {"index.mq.md": "# design v1\n"}) + git(child, "add", "components.toml") + git(child, "update-index", "--add", "--cacheinfo", f"160000,{design},design") + git(child, "commit", "-q", "-m", "domain v1") + domain_v1 = git(child, "rev-parse", "HEAD").strip() + root_catalog = catalog( + component(id="cli", path="cli", kind="core", state="active", owner="t", + scope="s", requires=[], checks_with=[], release="base"), + component(id="web", path="extensions/web", kind="domain", state="planned", + owner="t", scope="s", requires=[], checks_with=[], release="none"), + ) + first = root_repo( + self.root, + root_catalog, + {"cli": leaf(self.base, "cli2", {"README.md": "cli"}), "extensions/web": domain_v1}, + {"extensions/web": "https://git.example.invalid/web.git"}, + ) + design_v2 = leaf(self.base, "design2", {"index.mq.md": "# design v2\n"}) + git(child, "update-index", "--cacheinfo", f"160000,{design_v2},design") + git(child, "commit", "-q", "-m", "domain v2") + domain_v2 = git(child, "rev-parse", "HEAD").strip() + second = root_repo( + self.root, + root_catalog, + {"cli": leaf(self.base, "cli3", {"README.md": "cli"}), "extensions/web": domain_v2}, + {"extensions/web": "https://git.example.invalid/web.git"}, + ) + report = self.analyze(first, second) + self.assertIn("web", [c["id"] for c in report["changed"]]) + self.assertIn("web-design", [c["id"] for c in report["changed"]]) + self.assertIn("web-design", report["affected"]) + + def test_unexpandable_domain_widens_to_full_scope(self): + root_catalog = catalog( + component(id="cli", path="cli", kind="core", state="active", owner="t", + scope="s", requires=[], checks_with=[], release="base"), + component(id="web", path="extensions/web", kind="domain", state="planned", + owner="t", scope="s", requires=[], checks_with=[], release="none"), + ) + cli = leaf(self.base, "cli4", {"README.md": "cli"}) + first = root_repo( + self.root, root_catalog, + {"cli": cli, "extensions/web": leaf(self.base, "web1", {"README.md": "web"})}, + {"extensions/web": "https://git.example.invalid/web.git"}, + ) + second = root_repo( + self.root, root_catalog, + {"cli": cli, "extensions/web": leaf(self.base, "web2", {"README.md": "web2"})}, + {"extensions/web": "https://git.example.invalid/web.git"}, + ) + # The root fixture points at a plain repository without a components.toml. + report = self.analyze(first, second) + self.assertTrue(report["unverified"]) + self.assertEqual(report["fallback"], "full") + self.assertEqual(report["affected"], ["cli", "web"]) + + +if __name__ == "__main__": + unittest.main()