"""Research (scout/Send/synthesizer), design (scope/deferral/pull-in/proposals/approval rewrite), data (recipes, no POST), graph routing functions and the end-to-end stub graph.""" from __future__ import annotations import unittest from langgraph.types import Command, Send from coworker.adapters import coverage_maps from coworker.adapters.cases import load_cases, rewrite_approval_line from coworker.adapters.legacy import select_scope from coworker.adapters.recipes import load_recipes from coworker.graph import build as B from coworker.graph.nodes import data, design, research from coworker.graph.runtime import FatalNodeError from coworker.graph.services import build_services from coworker.tests.fakes import FakePod, temp_settings def svc_with(pod=None, **over): pod = pod or FakePod() return build_services(temp_settings(**over), transport=pod.transport()), pod class TestResearch(unittest.TestCase): def test_scout_profile_and_buckets(self): svc, _ = svc_with() out = research.scout({"run_id": "r", "modules_requested": ["P2P", "O2C"]}, None, svc) self.assertEqual(out["research_modules"], ["P2P", "O2C"]) self.assertEqual(out["patch_id"], "26C") mods = {m["module"]: m for m in out["pod_profile"]["modules"]} self.assertEqual(mods["P2P"]["scout_persona"], "buyer") self.assertEqual([research.usage_bucket(n) for n in (0, 1, 5, 6, 20, 21, 100, 101)], [1, 2, 2, 3, 3, 4, 4, 5]) def test_scout_refuses_prod(self): svc, _ = svc_with(FakePod(environment="production")) with self.assertRaises(FatalNodeError): research.scout({"run_id": "r"}, None, svc) def test_send_fanout_capped(self): svc, _ = svc_with(research_max_modules=3) out = research.scout({"run_id": "r"}, None, svc) sends = research.dispatch_research({**out, "run_id": "r"}) self.assertEqual(len(sends), min(3, len(out["pod_profile"]["modules"]))) self.assertTrue(all(isinstance(s, Send) and s.node == "research_module" for s in sends)) self.assertEqual(research.dispatch_research({"research_modules": []}), "synthesizer") def test_synthesizer_rows_and_gaps(self): svc, _ = svc_with() st = {"run_id": "r", "modules_requested": ["P2P", "CX"]} st.update(research.scout(st, None, svc)) st["research"] = [] for s in research.dispatch_research(st): st["research"] += research.research_module(s.arg, None, svc)["research"] cm = research.synthesizer(st, None, svc)["coverage_map"] p2p_rows = {(r["map"], r["row_id"]) for r in cm["rows"] if r["module"] == "P2P"} expected = {(m["map"], r["row_id"]) for m in coverage_maps.maps_for("P2P") for r in m["rows"]} self.assertEqual(p2p_rows, expected) self.assertTrue(all(r["usage_basis"] == "SCOUT" for r in cm["rows"] if r["module"] == "P2P")) self.assertTrue(all(r["usage_basis"] == "ASSUMED" for r in cm["rows"] if r["module"] == "CX")) self.assertTrue(any(g["module"] == "CX" and "not on the pod" in g["reason"] for g in cm["gaps"])) self.assertTrue(all(r["confidence"] <= 0.9 for r in cm["rows"])) self.assertTrue(any(r["touched_by_patch"] for r in cm["rows"])) class TestDesign(unittest.TestCase): @classmethod def setUpClass(cls): cls.svc, _ = svc_with() st = {"run_id": "d", "modules_requested": ["P2P"], "include_p2": False} st.update(research.scout(st, None, cls.svc)) st["research"] = research.research_module(research.dispatch_research(st)[0].arg, None, cls.svc)["research"] st.update(research.synthesizer(st, None, cls.svc)) cls.st = st cls.out = design.test_generator(st, None, cls.svc) def test_p1_scope_matches_legacy(self): lib = [c for c in load_cases(["P2P"]) if not c["lifecycle"]] keep, _ = select_scope(lib, False) mine = {c["id"] for c in self.out["test_cases"] if c["priority"] == "P1" and c["origin"] == "library"} self.assertEqual(mine, {c["id"] for c in keep}) def test_lifecycle_deferred_with_reason(self): lc = {c["id"]: c["lifecycle"] for c in load_cases(["P2P"]) if c["lifecycle"]} d = {x["id"]: x["reason"] for x in self.out["deferred"]} self.assertTrue(lc) for cid, cls_ in lc.items(): self.assertIn(cls_, d[cid]) def test_changed_by_patch_p2_pulled_in(self): pulled = self.out["approvals"]["pulled_in_changed_by_patch"] self.assertTrue(pulled) ids = {c["id"] for c in self.out["test_cases"]} self.assertTrue(set(pulled) <= ids) def test_proposals_generated(self): self.assertTrue(self.out["proposed_cases"]) for p in self.out["proposed_cases"]: self.assertEqual(p["origin"], "generated") self.assertTrue(p["approval_status"].startswith("draft")) def test_approval_rewrite_changes_one_line(self): from coworker.adapters.cases import find_yaml text = find_yaml("P2P-APR-001").read_text(encoding="utf-8") new = rewrite_approval_line(text, "approved 2026-10-10 by alice (run r1)") diff = [(a, b) for a, b in zip(text.split("\n"), new.split("\n")) if a != b] self.assertEqual(len(diff), 1) self.assertTrue(diff[0][1].startswith("approval_status: approved")) self.assertEqual(len(text.split("\n")), len(new.split("\n"))) def test_render_spec_fixme_on_placeholders(self): code = design.render_spec({"id": "P2P-X-001", "title": "t"}, [{"action": "login_as", "value": "{{users.requester}}"}, {"action": "fill", "target": {"role": "textbox", "name": "Req"}, "value": "{{run.req}}"}]) self.assertIn("ui.login(\"requester\"", code) self.assertIn("test.fixme(true", code) self.assertIn("@P2P-X-001", code) class TestData(unittest.TestCase): def test_recipes_resolve_or_gap(self): svc, _ = svc_with() lib = load_recipes() cases = [c for c in load_cases(["P2P"]) if c["priority"] == "P1"][:15] cases.append({"id": "P2P-ZZZ-001", "title": "x", "process": "y", "module": "P2P", "data_recipes": ["DR-DOES-NOT-EXIST"]}) out = data.data_planner({"run_id": "r", "test_cases": cases}, None, svc) gaps = {(g["case_id"], g["recipe_id"]) for g in out["approvals"]["data_gaps"]} for cid, rids in out["data_plan"].items(): for rid in rids: self.assertTrue(rid in lib or (cid, rid) in gaps) self.assertIn(("P2P-ZZZ-001", "DR-DOES-NOT-EXIST"), gaps) def test_executor_never_posts_without_seed_allowed(self): svc, pod = svc_with() st = {"run_id": "r", "modules_requested": ["P2P"]} st.update(research.scout(st, None, svc)) cases = [c for c in load_cases(["P2P"]) if c["priority"] == "P1"] st["test_cases"] = cases st.update(data.data_planner(st, None, svc)) refs = data.data_executor(st, None, svc)["data_refs"] self.assertTrue(refs) self.assertTrue(all(r.method == "GET" for r in pod.requests)) self.assertTrue(any(r["status"] in ("seed_refused", "found", "not_found", "skipped") for r in refs.values())) class TestRouting(unittest.TestCase): def test_after_execute(self): self.assertEqual(B.after_execute({"retry_count": 0, "failures": []}), "reporter") self.assertEqual(B.after_execute({"retry_count": 0, "failures": ["A"]}), "self_heal") self.assertEqual(B.after_execute({"retry_count": 1, "failures": []}), "triage") self.assertEqual(B.after_execute({"retry_count": 1, "failures": ["A"]}), "triage") def test_after_triage_and_review(self): self.assertEqual(B.after_triage({"review_items": [{"case_id": "A"}]}), "human_review") self.assertEqual(B.after_triage({"review_items": []}), "reporter") self.assertEqual(B.after_review({"review": {"A": {"confirmed": "real_defect"}}}), "ticket") self.assertEqual(B.after_review({"review": {"A": {"confirmed": "not_defect", "owner": "x"}}}), "reporter") def test_graph_has_all_nodes(self): svc, _ = svc_with() g = B.build_graph(svc) nodes = set(g.get_graph().nodes) - {"__start__", "__end__"} self.assertEqual(nodes, {n for n, _ in B.NODE_FUNCS}) self.assertEqual(len(nodes), 16) class TestEndToEndStub(unittest.TestCase): def test_flaky_retry_owner_and_go_no_go_delegated(self): svc, _ = svc_with() cp = B.sqlite_checkpointer(svc.cfg.checkpoint_path) g = B.build_graph(svc, cp) rid = "e2e" svc.db.create_run({"run_id": rid, "status": "running"}) cfg = B.run_config(rid, svc.cfg) g.invoke({"run_id": rid, "modules_requested": ["P2P"], "playwright_mode": "stub", "stub_knobs": {"STUB_FLAKY": "P2P-APR-001"}}, cfg) gates = [] while g.get_state(cfg).next: v = g.get_state(cfg).tasks[0].interrupts[0].value gates.append(v["gate"]) ans = ({"approved": [p["id"] for p in v["pending"]], "actor": "t"} if v["gate"] == "approve_cases" else {"review": {i["case_id"]: {"owner": "automation"} for i in v["items"]}, "actor": "q"}) g.invoke(Command(resume=ans), cfg) s = g.get_state(cfg).values self.assertEqual(gates, ["approve_cases", "human_review"]) self.assertEqual(len(s["attempt_files"]), 2) self.assertEqual(s["run_results"]["outcomes"]["P2P-APR-001"], "flaky") import json from pathlib import Path from coworker.adapters.report_rule import summarize tri = json.loads(Path(s["triage_path"]).read_text()) again = summarize(tri, Path(s["report_root"]), s["review"], False, "P2P") self.assertEqual(s["decisions"]["P2P"], again["decision"]) self.assertEqual(s["decision"], "NO-GO") # flaky P1 is not a pass under QA's rule cp.conn.close() if __name__ == "__main__": unittest.main()