diff --git a/.gitea/workflows/build.yml b/.gitea/workflows/build.yml index 89df288..a74e619 100644 --- a/.gitea/workflows/build.yml +++ b/.gitea/workflows/build.yml @@ -121,15 +121,16 @@ jobs: run: | python3 -m unittest discover -s scripts/ci -p 'test_*.py' python3 scripts/ci/check-efcore-usage.py - - name: Validate Compose and build .NET solution + - name: Validate Compose and restore .NET solution run: | mkdir -p artifacts/tests artifacts/security dotnet --info > artifacts/dotnet-info.txt bash scripts/ci/validate-compose.sh dotnet restore Heimdall.slnx --locked-mode - dotnet build Heimdall.slnx -c Release --no-restore -m:2 - name: Plan affected test suites run: python3 scripts/ci/test-plan.py + - name: Build affected projects + run: python3 scripts/ci/build-plan.py - name: Agent tests run: bash scripts/ci/test-suite.sh Heimdall.Agent.Tests - name: API tests diff --git a/docs/gitea-builds.md b/docs/gitea-builds.md index e561c6c..8b9598b 100644 --- a/docs/gitea-builds.md +++ b/docs/gitea-builds.md @@ -14,7 +14,7 @@ Le workflow Renovate lit l’API Gitea dans la variable d’action `GITEA_API_EN ## Tests -`CI policy` sélectionne les workflows qui nécessitent une validation lourde par comparaison Git. `test-plan.py` sélectionne ensuite les suites affectées par une PR selon les fichiers modifiés et les `ProjectReference` transitifs. Un changement de solution, SDK, configuration de build, Docker ou CI élargit le plan à toutes les suites. Si la comparaison Git du plan est impossible, toutes les suites sont exécutées. Les pushes sur `main` qui passent le filtre de chemins exécutent toutes les suites ; les tags `*.*.*` ne sont pas filtrés par chemins et exécutent toutes les suites. Le plan est écrit dans `artifacts/tests/plan.json` et chaque suite apparaît dans une étape distincte. Chaque suite utilise sa propre base PostgreSQL jetable ; les tests navigateur installent Chromium seulement lorsqu'ils sont sélectionnés. +`CI policy` sélectionne les workflows qui nécessitent une validation lourde par comparaison Git. `test-plan.py` sélectionne les suites affectées et leurs projets de build selon les fichiers modifiés et les `ProjectReference` transitifs; `build-plan.py` ne compile que ces cibles sur une PR. Un changement de solution, SDK, configuration de build, Docker ou CI élargit le plan à toute la solution. Si la comparaison Git du plan est impossible, toutes les suites sont exécutées. Le restore NuGet verrouillé reste solution-wide pour la vérification des dépendances, mais les compilations ciblées ne recompilent pas les graphes Agent/Web sans lien avec les fichiers touchés. Les pushes sur `main` qui passent le filtre de chemins exécutent toutes les suites ; les tags `*.*.*` ne sont pas filtrés par chemins et exécutent toutes les suites. Le plan est écrit dans `artifacts/tests/plan.json` et chaque suite apparaît dans une étape distincte. Chaque suite utilise sa propre base PostgreSQL jetable ; les tests navigateur installent Chromium seulement lorsqu'ils sont sélectionnés. ## Publication continue diff --git a/scripts/ci/build-plan.py b/scripts/ci/build-plan.py new file mode 100644 index 0000000..f8fe2b4 --- /dev/null +++ b/scripts/ci/build-plan.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python3 +"""Build only the projects selected by test-plan.py after solution restore.""" + +import json +from pathlib import Path +import subprocess + +ROOT = Path(__file__).resolve().parents[2] +PLAN = ROOT / "artifacts" / "tests" / "plan.json" + + +def main() -> None: + plan = json.loads(PLAN.read_text()) + targets = plan.get("build_projects") + if not isinstance(targets, list) or any(not isinstance(target, str) for target in targets): + raise SystemExit("Test plan has an invalid build_projects list") + if not targets: + print("No .NET build targets selected") + return + + for target in targets: + path = ROOT / target + if not path.is_file(): + raise SystemExit(f"Build target does not exist: {target}") + print(f"Building affected target: {target}", flush=True) + subprocess.run( + ["dotnet", "build", target, "-c", "Release", "--no-restore", "-m:2"], + cwd=ROOT, + check=True, + ) + + +if __name__ == "__main__": + main() diff --git a/scripts/ci/test-plan.py b/scripts/ci/test-plan.py index cfcf80a..e893362 100644 --- a/scripts/ci/test-plan.py +++ b/scripts/ci/test-plan.py @@ -9,6 +9,8 @@ import xml.etree.ElementTree as ET ROOT = Path(__file__).resolve().parents[2] TESTS = sorted(path for path in (ROOT / "tests").glob("*/*.csproj") if path.stem != "Heimdall.TestCommon") +SOURCES = sorted((ROOT / "src").glob("*/*.csproj")) +ALL_PROJECTS = [*SOURCES, *(ROOT / "tests").glob("*/*.csproj")] def references(project: Path) -> set[Path]: @@ -19,6 +21,30 @@ def references(project: Path) -> set[Path]: } +def referenced_projects(project: Path, graph: dict[Path, set[Path]]) -> set[Path]: + result: set[Path] = set() + pending = list(graph.get(project, set())) + while pending: + dependency = pending.pop() + if dependency in result: + continue + result.add(dependency) + pending.extend(graph.get(dependency, set())) + return result + + +def build_targets(affected: set[Path], suites: list[str], graph: dict[Path, set[Path]], + mode: str) -> list[str]: + if mode == "all": + return ["Heimdall.slnx"] + + suite_projects = [project for project in TESTS if project.stem in suites] + covered_sources = set().union(*(referenced_projects(project, graph) for project in suite_projects)) if suite_projects else set() + targets = [*suite_projects, *(project for project in SOURCES + if project.resolve() in affected and project.resolve() not in covered_sources)] + return sorted({project.resolve().relative_to(ROOT).as_posix() for project in targets}) + + def changed_files() -> list[str] | None: if os.environ.get("GITEA_EVENT_NAME") != "pull_request": return None @@ -31,11 +57,11 @@ def changed_files() -> list[str] | None: def plan(changed: list[str] | None) -> dict[str, object]: if changed is None: - return {"mode": "all", "changed": [], "suites": [p.stem for p in TESTS]} + suites = [p.stem for p in TESTS] + return {"mode": "all", "changed": [], "suites": suites, + "build_projects": build_targets(set(), suites, {}, "all")} - all_paths = {p.resolve() for p in (ROOT / "src").glob("*/*.csproj")} | { - p.resolve() for p in (ROOT / "tests").glob("*/*.csproj") - } + all_paths = {p.resolve() for p in ALL_PROJECTS} graph = {project: references(project) for project in all_paths} changed_projects: set[Path] = set() broad = False @@ -59,10 +85,12 @@ def plan(changed: list[str] | None) -> dict[str, object]: or name in {"readme.md", "AGENTS.md", ".gitea/PULL_REQUEST_TEMPLATE.md"} for name in changed ): - return {"mode": "affected", "changed": changed, "suites": []} + return {"mode": "affected", "changed": changed, "suites": [], "build_projects": []} if broad or (changed and not changed_projects): - return {"mode": "all", "changed": changed, "suites": [p.stem for p in TESTS]} + suites = [p.stem for p in TESTS] + return {"mode": "all", "changed": changed, "suites": suites, + "build_projects": build_targets(set(), suites, graph, "all")} affected = set(changed_projects) while True: @@ -72,7 +100,9 @@ def plan(changed: list[str] | None) -> dict[str, object]: affected |= additions suites = [p.stem for p in TESTS if p.resolve() in affected] - return {"mode": "affected", "changed": changed, "suites": suites} + projects = build_targets(affected, suites, graph, "affected") + return {"mode": "affected", "changed": changed, "suites": suites, + "build_projects": projects} if __name__ == "__main__": @@ -81,3 +111,4 @@ if __name__ == "__main__": output.parent.mkdir(parents=True, exist_ok=True) output.write_text(json.dumps(result, indent=2) + "\n") print(f"Test plan: {result['mode']} — {', '.join(result['suites']) or 'no .NET suite'}") + print(f"Build targets: {', '.join(result['build_projects']) or 'none'}") diff --git a/scripts/ci/test_ci.py b/scripts/ci/test_ci.py index b7f1505..451a3ae 100644 --- a/scripts/ci/test_ci.py +++ b/scripts/ci/test_ci.py @@ -97,6 +97,12 @@ def load_test_plan(): spec.loader.exec_module(module) return module +def load_build_plan(): + spec = importlib.util.spec_from_file_location('heimdall_build_plan', ROOT/'build-plan.py') + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + def load_efcore_policy(): spec = importlib.util.spec_from_file_location('efcore_policy', ROOT/'check-efcore-usage.py') module = importlib.util.module_from_spec(spec) @@ -128,20 +134,54 @@ class TestPlanTests(unittest.TestCase): self.assertIn('Heimdall.E2E.Tests', suites) def test_agent_change_does_not_run_unrelated_web_tests(self): - suites = load_test_plan().plan(['src/Heimdall.Agent/Program.cs'])['suites'] + plan = load_test_plan().plan(['src/Heimdall.Agent/Program.cs']) + suites = plan['suites'] self.assertIn('Heimdall.Agent.Tests', suites) self.assertNotIn('Heimdall.Web.Tests', suites) + self.assertIn('tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj', plan['build_projects']) + self.assertFalse(any('Heimdall.Web' in target for target in plan['build_projects'])) + + def test_web_change_does_not_rebuild_agent(self): + plan = load_test_plan().plan(['src/Heimdall.Web/Components/App.razor']) + self.assertIn('Heimdall.Web.Tests', plan['suites']) + self.assertFalse(any('Heimdall.Agent' in target for target in plan['build_projects'])) + self.assertFalse(any('Heimdall.slnx' == target for target in plan['build_projects'])) def test_solution_change_runs_all_and_docs_change_runs_none(self): planner = load_test_plan() - self.assertEqual(len(planner.plan(['global.json'])['suites']), len(planner.TESTS)) - self.assertEqual(planner.plan(['docs/README.md'])['suites'], []) + solution = planner.plan(['global.json']) + self.assertEqual(len(solution['suites']), len(planner.TESTS)) + self.assertEqual(solution['build_projects'], ['Heimdall.slnx']) + docs = planner.plan(['docs/README.md']) + self.assertEqual(docs['suites'], []) + self.assertEqual(docs['build_projects'], []) def test_removed_backlog_file_does_not_skip_validation_as_docs_only(self): planner = load_test_plan() result = planner.plan(['todo.md']) self.assertEqual(result['mode'], 'all') self.assertEqual(len(result['suites']), len(planner.TESTS)) + self.assertEqual(result['build_projects'], ['Heimdall.slnx']) + +class BuildPlanTests(unittest.TestCase): + def test_builds_only_existing_targets_from_the_plan(self): + builder = load_build_plan() + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + target = 'tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj' + project = root/target + project.parent.mkdir(parents=True) + project.write_text('') + plan_path = root/'artifacts/tests/plan.json' + plan_path.parent.mkdir(parents=True) + plan_path.write_text(json.dumps({'build_projects':[target]})) + builder.ROOT = root + builder.PLAN = plan_path + with patch('subprocess.run') as run, contextlib.redirect_stdout(io.StringIO()): + builder.main() + run.assert_called_once_with( + ['dotnet','build',target,'-c','Release','--no-restore','-m:2'], + cwd=root, check=True) class GpuAgentImageTests(unittest.TestCase): def test_cpu_default_stays_independent_of_nvidia_runtime(self): diff --git a/skills/release-automation/SKILL.md b/skills/release-automation/SKILL.md index 8d0dcb0..a5f13d5 100644 --- a/skills/release-automation/SKILL.md +++ b/skills/release-automation/SKILL.md @@ -10,6 +10,7 @@ Use this skill for changes to `.gitea/workflows/build.yml`, `scripts/ci/change_s ## Delivery contract - Pull requests run `verify` and build/scan only images affected by the changed project graph. They never receive Docker Hub or Gitea publication credentials. +- `test-plan.py` computes both affected test suites and build targets from transitive `ProjectReference` edges. PRs build only those test projects and any changed source projects not covered by them; the solution is built only for main/tag runs or broad CI/build-configuration changes. The solution restore remains locked and solution-wide for the dependency security report. - A push to `main` validates the changed source and builds/scans/pushes only affected images. The affected image gets immutable `sha-` and mutable `latest` tags on Docker Hub. Main pushes do not create Gitea releases. - Runs for the same ref are serialized so a slower older `main` run cannot overwrite a newer `latest` image. - A `MAJOR.MINOR.PATCH` tag (optional prerelease suffix allowed) is a version release. It validates the complete source and builds/scans server, Agent CPU, and Agent GPU images once each. The verified images are pushed to Docker Hub as `sha-` and the application version.