Download coworker/graph/nodes/data.py from EnergyVenom/patchwise-agent-studio: direct link, hf CLI and curl.
- Browser
- Download file 7.64 kB
-
https://huggingface.co/spaces/EnergyVenom/patchwise-agent-studio/resolve/main/coworker/graph/nodes/data.py
- Command line
-
hf download hf://spaces/EnergyVenom/patchwise-agent-studio/coworker/graph/nodes/data.py
-
curl -L -o data.py https://huggingface.co/spaces/EnergyVenom/patchwise-agent-studio/resolve/main/coworker/graph/nodes/data.py
7.64 kB
| """Data phase: data_planner (case recipes first; keyword-overlap stub / local LLM only for cases without recipes) -> | |
| data_executor (read-only REST find via egress; seeding only with SEED_ALLOWED=1 on a test pod; BIP unsupported).""" | |
| from __future__ import annotations | |
| import re | |
| from ...adapters.recipes import load_recipes, recipe_index, render | |
| from ...llm.base import LLMRequest, Sensitivity | |
| from ...llm.schemas import RecipeChoice | |
| def _tokens(s: str) -> set[str]: | |
| return {w for w in re.findall(r"[a-z]{4,}", (s or "").lower())} | |
| def stub_plan_data(payload: dict) -> RecipeChoice: | |
| case = payload["case"] | |
| idx = payload.get("recipe_index", []) | |
| direct = [r["id"] for r in idx if case["id"] in r.get("used_by", [])] | |
| if direct: | |
| return RecipeChoice(case_id=case["id"], recipe_ids=direct[:3], reason="recipe lists the case in used_by") | |
| t = _tokens(case.get("title", "") + " " + case.get("process", "")) | |
| scored = sorted(((len(t & _tokens(r["title"] + " " + r["purpose"])), r["id"]) for r in idx), reverse=True) | |
| pick = [rid for s, rid in scored if s >= 2][:2] | |
| return RecipeChoice(case_id=case["id"], recipe_ids=pick, reason="keyword overlap of title/process vs recipe purpose (stub)") | |
| def _pod_data(svc, run_id: str) -> dict | None: | |
| """A Fusion run's test data: the pod's own values per area (discovery at the start of the run, plus the admin's | |
| overrides). None on the practice pod, whose scenarios use the data recipes and the practice app.""" | |
| pod_id = svc.fusion_pod_id(run_id) | |
| if pod_id is None: | |
| return None | |
| from ...platform.pods import PodRegistry | |
| return PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit).get(pod_id).get("test_data") or {} | |
| def data_planner(state, config, svc) -> dict: | |
| run_id = state["run_id"] | |
| if _pod_data(svc, run_id) is not None: # Fusion: no recipes; each scenario uses its area's discovered values | |
| return {"data_plan": {c["id"]: [] for c in state.get("test_cases") or []}, "approvals": {"data_gaps": []}, "llm_calls": []} | |
| lib = load_recipes() | |
| idx = recipe_index() | |
| plan, calls, gaps = {}, [], [] | |
| for c in state.get("test_cases") or []: | |
| if c.get("data_recipes"): | |
| plan[c["id"]] = list(c["data_recipes"]) | |
| continue | |
| mod_idx = [r for r in idx if c["module"] in r["id"] or c["id"] in r["used_by"] or r["id"].count("-") == 2] | |
| req = LLMRequest("plan_data", Sensitivity.CLIENT, {"case": {"id": c["id"], "title": c["title"], "process": c["process"]}, | |
| "recipe_index": mod_idx}, RecipeChoice, "data_planner", run_id, | |
| stub_plan_data({"case": c, "recipe_index": mod_idx})) | |
| resp = svc.router.call(req) | |
| calls.append(resp.record) | |
| plan[c["id"]] = list(resp.output.recipe_ids) # type: ignore[attr-defined] | |
| for cid, rids in plan.items(): | |
| for rid in rids: | |
| if rid not in lib: | |
| gaps.append({"case_id": cid, "recipe_id": rid, "reason": "unknown recipe id (E8 gap)"}) | |
| return {"data_plan": plan, "approvals": {"data_gaps": gaps}, "llm_calls": calls} | |
| REQ_RE = re.compile(r"^(GET|POST)\s+(\S+)") | |
| def _module_of_recipe(rid: str, plan: dict, cases: list[dict]) -> str | None: | |
| for c in cases: | |
| if rid in plan.get(c["id"], []): | |
| return c["module"] | |
| return None | |
| def data_executor(state, config, svc) -> dict: | |
| run_id = state["run_id"] | |
| pod_data = _pod_data(svc, run_id) | |
| if pod_data is not None: | |
| # Fusion: never the practice app. Report, per area tested, which test data values the pod offers (keys only: | |
| # the values stay with the test runner); a step needing a missing one fails saying where to set it. | |
| refs = {} | |
| for area in sorted({c["module"] for c in state.get("test_cases") or []}): | |
| keys = sorted((pod_data.get(area) or {}).keys()) | |
| refs[f"pod.{area.lower()}"] = {"recipe_id": f"pod.{area.lower()}", "strategy": "pod records (discovery)", | |
| "status": "found" if keys else "not_found", "outputs": {"keys": keys}, | |
| "note": (f"{area}: {len(keys)} value(s) from the pod's own records: {', '.join(keys)}" if keys else | |
| f"{area}: no test data found on the pod; set it on Test environments (Set test data)")} | |
| return {"data_refs": refs} | |
| lib = load_recipes() | |
| plan = state.get("data_plan") or {} | |
| cases = state.get("test_cases") or [] | |
| profile = state.get("pod_profile") or {"modules": []} | |
| persona_by_mod = {m["module"]: m.get("scout_persona") for m in profile.get("modules", [])} | |
| is_mock = bool((profile.get("about") or {}).get("is_mock")) | |
| env_ctx = {"env": {"rest_base": svc.cfg.pod_rest_base}} | |
| refs: dict = {} | |
| for rid in sorted({r for rs in plan.values() for r in rs}): | |
| d = lib.get(rid) | |
| if not d: | |
| refs[rid] = {"recipe_id": rid, "strategy": "?", "status": "not_found", "outputs": {}, "note": "unknown recipe id (E8 gap)"} | |
| continue | |
| strategy = str(d.get("strategy", "")) | |
| find = d.get("find") or {} | |
| method = str(find.get("method", "")).lower() | |
| mod = _module_of_recipe(rid, plan, cases) | |
| persona = persona_by_mod.get(mod) or "auditor_ro" | |
| ref = {"recipe_id": rid, "strategy": strategy, "status": "skipped", "outputs": {}, "note": ""} | |
| if "bip" in method: | |
| ref.update(status="unsupported", note="BIP find is a stub in this pilot (mock has no BIP)") | |
| elif method == "rest": | |
| text, missing = render(str(find.get("request", "")), env_ctx) | |
| m = REQ_RE.match(text.strip().strip('"')) | |
| if not m or missing or not m.group(2).startswith("/"): | |
| ref.update(note="find.request is prose or has unresolved placeholders; resolved by spec fixtures on the mock") | |
| else: | |
| path, q = (m.group(2).split("?", 1) + [""])[:2] | |
| try: | |
| r = svc.egress.pod_request("GET", path, persona=persona, params={"q": q} if q else None, run_id=run_id) | |
| n = len(r.json().get("items", [])) if r.status_code == 200 else None | |
| if n: | |
| ref.update(status="found", outputs={"count": n}, note=f"GET {path} as {persona}: {n} row(s) (mock)") | |
| else: | |
| ref.update(status="not_found", note=f"GET {path} as {persona}: HTTP {r.status_code}, {n or 0} row(s)") | |
| except Exception as e: # noqa: BLE001 | |
| ref.update(status="not_found", note=f"{type(e).__name__}: {e}") | |
| else: | |
| ref.update(note=f"find.method={method or 'none'}: resolved by the Scout/probers or the spec fixtures (read-only)") | |
| if ref["status"] == "not_found" and "create" in strategy: | |
| if svc.cfg.seed_allowed and svc.egress.pod.environment == "test": | |
| ref["note"] += "; seeding allowed but recipe create requests are prose in this library: not executed" | |
| else: | |
| ref.update(status="seed_refused", note=ref["note"] + "; create refused (SEED_ALLOWED=0 or pod not test)") | |
| if is_mock: | |
| ref["note"] += " [mock: spec fixtures reset and seed synthetic data per test]" | |
| refs[rid] = ref | |
| return {"data_refs": refs} | |
| STUB_TASKS = {"plan_data": stub_plan_data} | |