From fba7bcab6fee39686556cb6588604805af0df03f Mon Sep 17 00:00:00 2001 From: Keath Mueller Date: Sat, 24 Oct 2026 15:24:14 -0600 Subject: [PATCH 1/3] fix(swarm): import subprocess so the QA stage can run the generated tests Stage 7 calls subprocess.run() to execute the generated unit tests, but swarm_pipeline.py never imported subprocess. The NameError was swallowed by the surrounding `except Exception`, so every run with a provider ended in "FAILED: QA Test Runner Error" at stage 7 and stages 8-10 could not run at all. Add the missing import and cover the stage with tests: a complete run now passes the runner, the runner is called with the documented command and timeout, a non-zero exit reports "QA Unit Tests Failed", and a runner that cannot start reports "QA Test Runner Error". The tests fake subprocess.run and council.call_llm, so no network is used and nothing generated is run. Note for review: with the import in place the stage really does execute the model-generated tests (and whatever they import) in the project directory, as the code already intended. Co-Authored-By: Claude Sonnet 5.5 --- swarm_pipeline.py | 1 + tests/support.py | 180 +++++++++++++++++++++++++++++++++++ tests/test_swarm_qa_stage.py | 41 ++++++++ 3 files changed, 222 insertions(+) create mode 100644 tests/support.py create mode 100644 tests/test_swarm_qa_stage.py diff --git a/swarm_pipeline.py b/swarm_pipeline.py index 9b565b8..490b264 100644 --- a/swarm_pipeline.py +++ b/swarm_pipeline.py @@ -9,6 +9,7 @@ import os import sys import json +import subprocess import time import datetime import threading diff --git a/tests/support.py b/tests/support.py new file mode 100644 index 0000000..36a38b4 --- /dev/null +++ b/tests/support.py @@ -0,0 +1,180 @@ +"""Shared fixtures for the swarm pipeline tests. + +Everything here is a fake: providers are plain dicts with a fake key, the +model call (`council.call_llm`) is replaced, and `subprocess.run` is replaced, +so no network is touched and no model-generated code is ever executed. + +Importing this module also puts the repository root on ``sys.path`` so the +tests work under ``python -I`` (isolated mode drops the working directory +from the import path). +""" + +import json +import os +import subprocess +import sys +import tempfile +import unittest +from contextlib import ExitStack +from pathlib import Path +from unittest.mock import patch + +REPO_ROOT = str(Path(os.environ.get("TENAGENT_TEST_ROOT") or Path(__file__).resolve().parent.parent)) +if REPO_ROOT not in sys.path: + sys.path.insert(0, REPO_ROOT) + +import council # noqa: E402 +import swarm_pipeline # noqa: E402 + +FAKE_KEY = "sk-FAKE-do-not-use-0123456789" +PROVIDER = {"id": "groq", "name": "Mock provider", "key": FAKE_KEY} +AGENT_IDS = [ + "01_pm", "02_arch", "03_designer", "04_dba", "05_backend", + "06_client", "07_qa", "08_security", "09_devops", "10_tech_lead", +] + +# (substring of the system prompt, output key) +STAGE_MARKERS = [ + ("Product Manager", "prd"), + ("System Architect", "adr"), + ("design tokens containing", "tokens"), + ("Screen Flow Document", "flows"), + ("Database Engineer", "sql"), + ("API Architect", "openapi"), + ("You are the Backend Engineer", "backend"), + ("Client Engineer", "client"), + ("Formulate a QA Test Matrix", "qa_matrix"), + ("executable Python unittest suite", "tests"), + ("OWASP Application Security Auditor", "security"), + ("DevOps Engineer", "docker"), + ("Technical Lead", "lead"), +] + +PROSE = " Users can create, list and remove items, and every list view shows the newest entry first." + +GOOD_OUTPUTS = { + "prd": "# Product requirements\n\nUsers can list things." + PROSE, + "adr": "# Architecture ADR\n\nClean architecture with domain, use case and repository layers." + PROSE, + "tokens": '{"colors": {"primary": "#fff"}, "typography": {}, "spacing": {}}', + "flows": "# Screen flows\n\nHome -> list -> detail." + PROSE, + "sql": "CREATE TABLE thing (id INTEGER PRIMARY KEY);", + "openapi": ( + "openapi: 3.0.0\ninfo:\n title: Mock\n version: 1.0.0\n" + "paths:\n /health:\n get:\n responses:\n '200':\n description: ok\n" + ), + "backend": "def example():\n return 1\n", + "client": "App", + "qa_matrix": "# QA test matrix\n\nHappy path, empty list, boundary sizes." + PROSE, + "tests": ( + "import unittest\n\n" + "class TestExample(unittest.TestCase):\n" + " def test_example(self):\n" + " self.assertEqual(1 + 1, 2)\n" + ), + "security": "# Advisory security review\n\nNo findings are claimed here; a scanner must confirm." + PROSE, + "docker": "FROM python:3.11-slim\n", + "lead": "[APPROVED FOR PRODUCTION]", +} + + +def stage_key(system_prompt): + for marker, key in STAGE_MARKERS: + if marker in system_prompt: + return key + raise AssertionError("unrecognised stage prompt: " + system_prompt[:60]) + + +def make_status_file(root, overall=0, phase="Phase 1", agent_overrides=None): + specs = Path(root) / "specs" + specs.mkdir(parents=True, exist_ok=True) + agents = [] + for aid in AGENT_IDS: + agent = { + "id": aid, "role": aid, "status": "IDLE", "currentTask": "", + "processDetail": "", "progress": 0, "deliverable": "", + } + agent.update((agent_overrides or {}).get(aid, {})) + agents.append(agent) + data = { + "project": {"name": "t", "phase": phase, "overallProgress": overall}, + "agents": agents, + "logs": [], + } + path = specs / "swarm-status.json" + path.write_text(json.dumps(data, indent=2), encoding="utf-8") + return path + + +def read_status(root): + return json.loads((Path(root) / "specs" / "swarm-status.json").read_text(encoding="utf-8-sig")) + + +def list_files(root): + return sorted(p.relative_to(root).as_posix() for p in Path(root).rglob("*") if p.is_file()) + + +class PipelineCase(unittest.TestCase): + """Runs the real pipeline entry point with a faked model call and a faked test runner.""" + + def setUp(self): + self.new_root() + + def new_root(self): + """Fresh project directory (also used between subTests so they cannot leak state).""" + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + (self.root / "Dockerfile").write_text("FROM original-image\n", encoding="utf-8") + (self.root / ".github" / "workflows").mkdir(parents=True) + (self.root / ".github" / "workflows" / "ci.yml").write_text("name: Original CI\n", encoding="utf-8") + self.calls = [] + self.test_runs = [] + + def run_swarm(self, outputs=None, providers=None, status=True, goal="Mock task", + call_hook=None, run_fn=None, debate=None, test_returncode=0): + merged = dict(GOOD_OUTPUTS) + merged.update(outputs or {}) + if status and not (self.root / "specs" / "swarm-status.json").exists(): + make_status_file(self.root) + providers = [PROVIDER] if providers is None else providers + + def fake_call_llm(provider, system_prompt, user_prompt, timeout=75): + key = stage_key(system_prompt) + self.calls.append(key) + if call_hook: + call_hook(key) + value = merged[key] + if isinstance(value, BaseException): + raise value + return value() if callable(value) else value + + def fake_run(args, **kwargs): + # The QA stage would run the generated tests; here nothing is ever executed. + self.test_runs.append({"args": list(args), **kwargs}) + if isinstance(test_returncode, BaseException): + raise test_returncode + return subprocess.CompletedProcess(args, test_returncode, "", "fake runner output") + + with ExitStack() as stack: + stack.enter_context(patch.object(council, "get_active_providers", return_value=providers)) + stack.enter_context(patch.object(council, "call_llm", side_effect=fake_call_llm)) + stack.enter_context(patch("subprocess.run", side_effect=fake_run)) + if debate is None: + debate_patch = patch.object( + council, "run_council_debate", return_value={"status": "native_only", "consensus": None}) + else: + debate_patch = patch.object(council, "run_council_debate", side_effect=debate) + stack.enter_context(debate_patch) + stack.enter_context(patch.object(swarm_pipeline.time, "sleep")) + stack.enter_context(patch.object(swarm_pipeline, "print", create=True)) + runner = run_fn or swarm_pipeline.execute_multi_brain_swarm + return runner(goal, str(self.root)) + + def read(self, rel): + return (self.root / rel).read_text(encoding="utf-8") + + def exists(self, rel): + return (self.root / rel).exists() + + def files(self): + return list_files(self.root) diff --git a/tests/test_swarm_qa_stage.py b/tests/test_swarm_qa_stage.py new file mode 100644 index 0000000..7194faa --- /dev/null +++ b/tests/test_swarm_qa_stage.py @@ -0,0 +1,41 @@ +"""The QA stage runs the generated tests; the run must reach (and honestly report) that step. + +`subprocess.run` is faked in every test (see support.PipelineCase), so no generated +code is executed. +""" + +import sys +import unittest + +import support # noqa: F401 (puts the repo root on sys.path for python -I) +from support import PipelineCase, read_status + + +class QaStageRunsTheGeneratedTests(PipelineCase): + def test_a_complete_run_gets_past_the_test_runner(self): + self.assertTrue(self.run_swarm()) + self.assertNotIn("FAILED", read_status(self.root)["project"]["phase"]) + self.assertEqual(self.calls[-1], "lead", "the stages after QA never ran") + + def test_the_runner_is_invoked_on_the_projects_tests_directory(self): + self.run_swarm() + self.assertEqual(len(self.test_runs), 1) + run = self.test_runs[0] + self.assertEqual(run["args"], [sys.executable, "-m", "unittest", "discover", "-s", "tests"]) + self.assertEqual(run["cwd"], str(self.root)) + self.assertGreater(run["timeout"], 0) + + def test_failing_generated_tests_stop_the_run_with_the_unit_test_phase(self): + self.assertFalse(self.run_swarm(test_returncode=1)) + data = read_status(self.root) + self.assertEqual(data["project"]["phase"], "FAILED: QA Unit Tests Failed") + self.assertNotIn("security", self.calls, "stages after a failed QA run must not start") + self.assertFalse(self.exists("specs/signoff.md")) + + def test_runner_that_cannot_start_is_reported_as_a_runner_error(self): + self.assertFalse(self.run_swarm(test_returncode=OSError("no interpreter"))) + self.assertEqual(read_status(self.root)["project"]["phase"], "FAILED: QA Test Runner Error") + + +if __name__ == "__main__": + unittest.main() From 1ee2b9e5fe8eedb2ad0e2e14cba84b0c8fdae2aa Mon Sep 17 00:00:00 2001 From: Keath Mueller Date: Sat, 24 Oct 2026 15:37:21 -0600 Subject: [PATCH 2/3] fix(swarm): run only the generated test file in the QA stage `unittest discover -s tests` runs every test in tests/, not just the file the QA stage generated. This repository keeps its own tests there, so the verdict "the generated tests passed" also depended on unrelated tests (and on how long they take against the 15 second timeout), and the stage executed more code than the generated test it reports on. Restrict discovery to the generated file with `-p test_api.py`. The shared test fixture also silences the pipeline's stdout echo for every test case instead of only inside run_swarm(). Co-Authored-By: Claude Sonnet 5.5 --- swarm_pipeline.py | 4 +++- tests/support.py | 4 +++- tests/test_swarm_qa_stage.py | 2 +- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/swarm_pipeline.py b/swarm_pipeline.py index 490b264..62cbe15 100644 --- a/swarm_pipeline.py +++ b/swarm_pipeline.py @@ -455,8 +455,10 @@ def compute_progress(step_num): # Execute test suite to verify tests pass log_swarm_message("07_qa", "Executing automated test suite: python -m unittest discover tests ...", base_dir) try: + # Only the generated file: any other test in tests/ (the framework ships its own) must + # neither decide whether the generated tests pass nor eat into the timeout. test_proc = subprocess.run( - [sys.executable, "-m", "unittest", "discover", "-s", "tests"], + [sys.executable, "-m", "unittest", "discover", "-s", "tests", "-p", "test_api.py"], cwd=base_dir, capture_output=True, text=True, diff --git a/tests/support.py b/tests/support.py index 36a38b4..28d5387 100644 --- a/tests/support.py +++ b/tests/support.py @@ -117,6 +117,9 @@ class PipelineCase(unittest.TestCase): """Runs the real pipeline entry point with a faked model call and a faked test runner.""" def setUp(self): + quiet = patch.object(swarm_pipeline, "print", create=True) # the pipeline echoes its log to stdout + quiet.start() + self.addCleanup(quiet.stop) self.new_root() def new_root(self): @@ -166,7 +169,6 @@ def fake_run(args, **kwargs): debate_patch = patch.object(council, "run_council_debate", side_effect=debate) stack.enter_context(debate_patch) stack.enter_context(patch.object(swarm_pipeline.time, "sleep")) - stack.enter_context(patch.object(swarm_pipeline, "print", create=True)) runner = run_fn or swarm_pipeline.execute_multi_brain_swarm return runner(goal, str(self.root)) diff --git a/tests/test_swarm_qa_stage.py b/tests/test_swarm_qa_stage.py index 7194faa..e68cb49 100644 --- a/tests/test_swarm_qa_stage.py +++ b/tests/test_swarm_qa_stage.py @@ -21,7 +21,7 @@ def test_the_runner_is_invoked_on_the_projects_tests_directory(self): self.run_swarm() self.assertEqual(len(self.test_runs), 1) run = self.test_runs[0] - self.assertEqual(run["args"], [sys.executable, "-m", "unittest", "discover", "-s", "tests"]) + self.assertEqual(run["args"], [sys.executable, "-m", "unittest", "discover", "-s", "tests", "-p", "test_api.py"]) self.assertEqual(run["cwd"], str(self.root)) self.assertGreater(run["timeout"], 0) From 1ca7a12545360a54dc598c7eec43e611b3822201 Mon Sep 17 00:00:00 2001 From: Keath Mueller Date: Sat, 24 Oct 2026 16:38:14 -0600 Subject: [PATCH 3/3] fix(swarm): do not count a QA run that executed zero tests as a pass The QA stage treated exit code 0 from `unittest discover` as "the generated tests passed". unittest exits 0 for an empty discovery on Python 3.11 and earlier and 5 ("NO TESTS RAN") on 3.12 and later, so a generated tests/test_api.py with no unittest cases (pytest-style functions, say) was reported as a failure on one interpreter and as "passed with zero regressions" on another. The stage now also reads the runner's "Ran N tests" summary from stderr and stdout. Zero tests, or no summary line at all, fails the stage with "FAILED: QA No Tests Ran" whatever the exit code and Python version are. The number of tests that ran is logged. The log line announcing the run now names the command that is actually executed (`unittest discover -s tests -p test_api.py`), not `unittest discover tests`. The shared test fixture's fake runner reports a one-test unittest summary by default and can be given any output. As before, this stage executes model-written tests, and whatever they import, with the user's privileges and without a sandbox. A follow-up could run the child with a scrubbed environment and `-I`. Co-Authored-By: Claude Sonnet 5.5 --- swarm_pipeline.py | 24 ++++++++++++++++++++++-- tests/support.py | 5 +++-- tests/test_swarm_qa_stage.py | 31 +++++++++++++++++++++++++++++++ 3 files changed, 56 insertions(+), 4 deletions(-) diff --git a/swarm_pipeline.py b/swarm_pipeline.py index 62cbe15..04216b6 100644 --- a/swarm_pipeline.py +++ b/swarm_pipeline.py @@ -9,6 +9,7 @@ import os import sys import json +import re import subprocess import time import datetime @@ -23,6 +24,19 @@ LOG_FILE = os.path.join(SPECS_DIR, "terminal.log") STATUS_FILE = os.path.join(SPECS_DIR, "swarm-status.json") +_RAN_LINE = re.compile(r"^Ran (\d+) tests? in ", re.M) + + +def count_tests_run(output: str): + """Number of tests unittest says it ran, or None if there is no summary line. + + A runner that exits 0 without running anything must not count as a pass: unittest + exits 0 for an empty discovery up to Python 3.11 and 5 ("NO TESTS RAN") from 3.12 on. + """ + found = _RAN_LINE.findall(output or "") + return int(found[-1]) if found else None + + def get_timestamp() -> str: return datetime.datetime.now().strftime("%H:%M:%S") @@ -453,7 +467,7 @@ def compute_progress(step_num): f.write(test_clean.strip() + "\n") # Execute test suite to verify tests pass - log_swarm_message("07_qa", "Executing automated test suite: python -m unittest discover tests ...", base_dir) + log_swarm_message("07_qa", "Executing the generated tests: python -m unittest discover -s tests -p test_api.py ...", base_dir) try: # Only the generated file: any other test in tests/ (the framework ships its own) must # neither decide whether the generated tests pass nor eat into the timeout. @@ -469,7 +483,13 @@ def compute_progress(step_num): log_swarm_message("07_qa", f"[TEST FAILURE] Unit test runner reported failures:\n{err_output[:300]}", base_dir) update_swarm_status("07_qa", "WAITING", "Test execution failed. Unit tests reported failures or syntax errors.", 50, base_dir, phase="FAILED: QA Unit Tests Failed") return False - log_swarm_message("07_qa", "Automated test suite passed with zero regressions.", base_dir) + ran = count_tests_run((test_proc.stderr or "") + "\n" + (test_proc.stdout or "")) + if not ran: # 0 tests, or no unittest summary at all (for example pytest-style functions) + why = "ran no tests" if ran == 0 else "printed no unittest summary" + log_swarm_message("07_qa", f"[TEST FAILURE] The generated tests {why}; nothing was verified.", base_dir) + update_swarm_status("07_qa", "WAITING", f"Generated tests {why}.", 50, base_dir, phase="FAILED: QA No Tests Ran") + return False + log_swarm_message("07_qa", f"Automated test suite passed ({ran} test{'s' if ran != 1 else ''} ran).", base_dir) except Exception as e: log_swarm_message("07_qa", f"[TEST RUNNER ERROR] Could not execute tests: {str(e)}", base_dir) update_swarm_status("07_qa", "WAITING", f"Test runner error: {str(e)}", 0, base_dir, phase="FAILED: QA Test Runner Error") diff --git a/tests/support.py b/tests/support.py index 28d5387..7371da5 100644 --- a/tests/support.py +++ b/tests/support.py @@ -134,7 +134,8 @@ def new_root(self): self.test_runs = [] def run_swarm(self, outputs=None, providers=None, status=True, goal="Mock task", - call_hook=None, run_fn=None, debate=None, test_returncode=0): + call_hook=None, run_fn=None, debate=None, test_returncode=0, + test_output="Ran 1 test in 0.001s\n\nOK\n"): merged = dict(GOOD_OUTPUTS) merged.update(outputs or {}) if status and not (self.root / "specs" / "swarm-status.json").exists(): @@ -156,7 +157,7 @@ def fake_run(args, **kwargs): self.test_runs.append({"args": list(args), **kwargs}) if isinstance(test_returncode, BaseException): raise test_returncode - return subprocess.CompletedProcess(args, test_returncode, "", "fake runner output") + return subprocess.CompletedProcess(args, test_returncode, "", test_output) with ExitStack() as stack: stack.enter_context(patch.object(council, "get_active_providers", return_value=providers)) diff --git a/tests/test_swarm_qa_stage.py b/tests/test_swarm_qa_stage.py index e68cb49..6600191 100644 --- a/tests/test_swarm_qa_stage.py +++ b/tests/test_swarm_qa_stage.py @@ -32,6 +32,37 @@ def test_failing_generated_tests_stop_the_run_with_the_unit_test_phase(self): self.assertNotIn("security", self.calls, "stages after a failed QA run must not start") self.assertFalse(self.exists("specs/signoff.md")) + def test_a_runner_that_exits_zero_after_running_no_tests_is_not_a_pass(self): + # unittest exits 0 for an empty discovery on Python <= 3.11 and 5 on 3.12+ + self.assertFalse(self.run_swarm(test_returncode=0, test_output="Ran 0 tests in 0.000s\n\nNO TESTS RAN\n")) + self.assertEqual(read_status(self.root)["project"]["phase"], "FAILED: QA No Tests Ran") + self.assertNotIn("security", self.calls) + + def test_a_runner_with_no_summary_line_is_not_a_pass(self): + for output in ("", "something unrelated\n", "Ran many tests\n"): + with self.subTest(output=output): + self.new_root() + self.assertFalse(self.run_swarm(test_returncode=0, test_output=output)) + self.assertEqual(read_status(self.root)["project"]["phase"], "FAILED: QA No Tests Ran") + + def test_the_number_of_tests_that_ran_is_logged(self): + self.assertTrue(self.run_swarm(test_output="Ran 3 tests in 0.002s\n\nOK\n")) + self.assertIn("3 tests ran", self.read("specs/terminal.log")) + + def test_the_log_line_names_the_command_that_is_run(self): + self.run_swarm() + self.assertIn("unittest discover -s tests -p test_api.py", self.read("specs/terminal.log")) + + def test_count_tests_run_parses_the_last_summary(self): + import swarm_pipeline + + self.assertEqual(swarm_pipeline.count_tests_run("Ran 1 test in 0.1s\nOK"), 1) + self.assertEqual(swarm_pipeline.count_tests_run("Ran 12 tests in 1s\n\nOK"), 12) + self.assertEqual(swarm_pipeline.count_tests_run("Ran 0 tests in 0s"), 0) + self.assertEqual(swarm_pipeline.count_tests_run("Ran 2 tests in 1s\nRan 5 tests in 1s"), 5) + self.assertIsNone(swarm_pipeline.count_tests_run("")) + self.assertIsNone(swarm_pipeline.count_tests_run(None)) + def test_runner_that_cannot_start_is_reported_as_a_runner_error(self): self.assertFalse(self.run_swarm(test_returncode=OSError("no interpreter"))) self.assertEqual(read_status(self.root)["project"]["phase"], "FAILED: QA Test Runner Error")