#!/usr/bin/env python3 """coordinator_v2 - the SWARM COORDINATOR, v2 (typed holes; PREREG_v2.md). From v1: (twin 1 of the specialist builder; Ben 2026-10-20). It reads a task's example questions, asks every standing specialist, and writes a build brief from what the swarm reveals. No language model. Per example question: readings every specialist's typed reply: READ (an accepted answer), DECLINED (an in-domain refusal with its kind), RECOGNISED (its context matches but it neither answers nor declines) dependence for each READ, the nudge test of the family runtime: each given changed by 7%, asked again; a specialist whose answer moves with every given read the question (fully read) givens the specialist network's own quantity reader (value, dimension, role) asked the network's goal reader (asked dimension) and the question-type reader (what kind of answer is asked) Per task (thresholds fixed before the first run, never tuned on the sealed briefs): boundary refuse before briefing when 3 or more of the examples fall in one boundary class (medical dosing, legal advice, a private person's data) outcome compose when 5 or more examples are fully read; build when 2 or more are engaged (read, declined or recognised) by any specialist; otherwise new neighbours specialists ranked by engagement (read 2, declined 1, recognised 1), score >= 2 or any read; at most 5 type dated questions (today, tomorrow, next ...) in 3+ examples -> new_type; givens in 3+ examples -> formula; mostly quantity-asking without givens -> table; a relation reader engaged -> relation; mostly names, codes, places or people asked -> table; else facts gap the terms the examples share that no specialist read, with the type and the refusal kinds seen sources sources already cited in the specialists' manifests whose names share those terms (neighbours first); Wikidata for a relation, Wikipedia when nothing in the swarm matches It reads ONLY the examples file given to it (audited by grep before each run). usage: coordinator_v1.py [readings_log.jsonl]""" from __future__ import annotations import collections import json import os import re import sys import time REL = os.environ.get("ORACLE7_ROOT") or os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "root") SPEC = REL + "/specialists" GATE = SPEC + "/_gate" os.environ.setdefault("ORACLE7_ROOT", REL) sys.path.insert(0, GATE) sys.path.append(REL + "/wander-train") # shared modules the relation readers import (appended: never shadows a specialist) sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from combo_runtime_v1 import _Organ, _givens, _perturb, _answer_value, _same_value, CALL_LOCK # noqa: E402 from network_v1 import read_givens, read_goal, BASE # noqa: E402 import asktype # noqa: E402 NAME_RX = re.compile(r"(? 1 else d[0] if isinstance(d, tuple): d = dict(zip(BASE, d)) items = {k: v for k, v in dict(d).items() if v} if items == {"$": 1}: return "cost" named = {(("m", 1),): "length", (("m", 2),): "area", (("m", 3),): "volume", (("kg", 1),): "mass", (("s", 1),): "duration", (("K", 1),): "temperature", (("A", 1),): "current", (("mol", 1),): "amount"} key = tuple(sorted(items.items())) if key in named: return named[key] if items.get("m") == 1 and items.get("s") == -1 and len(items) == 2: return "speed" if items.get("kg") == 1 and items.get("m") == 2 and items.get("s") == -2 and len(items) == 3: return "energy" if items.get("kg") == 1 and items.get("m") == 2 and items.get("s") == -3 and len(items) == 3: return "power" if items.get("kg") == 1 and items.get("m") == -1 and items.get("s") == -2 and len(items) == 3: return "pressure" if items.get("kg") == 1 and items.get("m") == -3 and len(items) == 2: return "density" return "/".join("%s%s" % (k, "" if v == 1 else v) for k, v in sorted(items.items())) ROLE_RULES = [ # (unit pattern, nearby-words pattern, role) - first match wins; the unit text alone decides when no words given (r"usd|\$", r"\b(a|per|each|every)\s+(year|month|week|day)\b|annual|yearly|monthly|saves?", "rate"), (r"usd|\$", r"\bper\s+(kwh|gallon|litre|liter|unit|kg|lb)\b|\ba (gallon|litre|liter)\b|cents", "price"), (r"usd|\$", r"", "cost"), (r"%", r"\b(at|interest|rate|apr|apy|yearly|a year)\b", "rate"), (r"%", r"", "fraction"), (r"mpg|l/100|litres? per|liters? per|km/l", r"", "rate"), (r"ah\b|mah|amp-hours?", r"", "capacity"), (r"kwh|wh\b|joules?|kj|mj|calories|kcal", r"", "energy"), (r"kw\b|\bw\b|watts?|horsepower|hp\b", r"", "power"), (r"\bv\b|volts?", r"", "voltage"), (r"\ba\b|amps?|ma\b", r"", "current"), (r"ohms?|kohm", r"", "resistance"), (r"hz|khz|mhz", r"", "frequency"), (r"db\b", r"", "level"), (r"psi|kpa|pa\b|atm|bar\b|hpa", r"", "pressure"), (r"km/h|mph|m/s|knots?", r"", "speed"), (r"\bc\b|\bf\b|\bk\b|celsius|fahrenheit|kelvin|degrees", r"", "temperature"), (r"days?|hours?|minutes?|seconds?|years?|months?|weeks?", r"", "duration"), (r"kg|grams?|\bg\b|pounds?|lb|tonnes?|ounces?|oz", r"", "mass"), (r"litres?|liters?|ml\b|gallons?|cubic", r"", "volume"), (r"sq|square|m2|acres?|hectares?", r"", "area"), (r"\bin\b|inch|inches|\bft\b|feet|foot|metres?|meters?|\bm\b|km|miles?|cm|mm|yards?", r"", "length"), (r"\bm\b(?=.*mol)|molar|\bm\b concentration", r"", "concentration"), ] def role_of(unit, text): u = str(unit or "").lower() for upat, wpat, role in ROLE_RULES: if re.search(upat, u) and (not wpat or re.search(wpat, str(text).lower())): return role return "" def support(r): """grade of support of a reading: proved > cited > checked > unsupported (a specialist's accepted kind is a checked route)""" resp = str(r.get("response", "")) if "proved" in resp.lower(): return 3 if re.search(r"\[[^\]\s]{2,}\]", resp): return 2 return 1 if r.get("c") == "READ" else 0 def load_family(): ids = [] for f in ("standing_net_v6.txt", "standing_new_v5.txt", "standing_stars_v1.txt", "standing_owner_v1.txt"): p = os.path.join(GATE, f) if os.path.exists(p): for s in open(p).read().split(): for m in s.split("+"): if m not in ids: ids.append(m) if os.path.isdir(os.path.join(SPEC, "decay-r2")) and "decay-r2" not in ids: ids.append("decay-r2") organs, failed = [], [] for sid in ids: d = os.path.join(SPEC, sid) try: organs.append(_Organ(os.path.join(d, "manifest.json"), d)) except Exception as e: # noqa: BLE001 failed.append((sid, str(e)[:80])) # calibration, fixed before any task: a specialist whose context pattern matches more than 20% of the 924 general # questions that ship with the release (workbench/data/core_panel.json) gives no information by matching try: panel = [x["q"] for x in json.load(open(os.path.join(os.path.dirname(REL), "workbench", "data", "core_panel.json")))["items"]] except (OSError, ValueError, KeyError): panel = [] for o in organs: if panel and sum(bool(o.ctx.search(q)) for q in panel) > 0.20 * len(panel): BROAD.add(o.id) return organs, failed BROAD: set = set() def raw_reply(o, text): """the organ's reply classified, without the accept filter: READ / DECLINED / RECOGNISED / None""" try: with CALL_LOCK, o._env(): try: a = o.organ.answer(text, "%s:coord" % o.id) except TypeError: a = o.organ.answer(text) except Exception: # noqa: BLE001 a = None ctx = bool(o.ctx.search(text)) k = a.get("kind") if isinstance(a, dict) else None if k in o.kinds and k not in o.declines: return {"id": o.id, "c": "READ", "kind": k, "response": str(a.get("response", ""))[:300]} if k in o.declines and ctx: return {"id": o.id, "c": "DECLINED", "kind": k, "response": str(a.get("response", ""))[:200]} if ctx and o.id not in BROAD: # a context that matches most general questions says nothing (calibrated below) return {"id": o.id, "c": "RECOGNISED", "kind": k} return None def dependence(o, text, resp): gv = _givens(text) if not gv: return 0, 0 base_v = _answer_value(resp, gv) dep = 0 for m in gv: alt_text = _perturb(text, m) r = raw_reply(o, alt_text) if r is None or r["c"] != "READ": dep += 1 elif base_v is None: dep += r.get("response") != resp elif not _same_value(base_v, _answer_value(r.get("response", ""), _givens(alt_text)), rel=1e-4): dep += 1 return dep, len(gv) def terms(text): return [w for w in re.findall(r"[a-z][a-z0-9'-]+", text.lower()) if w not in STOP and len(w) > 2] def boundary(examples): hits = {"medical dosing": 0, "legal advice": 0, "personal data": 0} for q in examples: if B_MED[0].search(q) and B_MED[1].search(q): hits["medical dosing"] += 1 if B_LEGAL[0].search(q) and B_LEGAL[1].search(q): hits["legal advice"] += 1 if B_PERSON[0].search(q) and B_PERSON[1].search(q): hits["personal data"] += 1 top = max(hits.items(), key=lambda kv: kv[1]) return (top[0] if top[1] >= 3 else None), hits def brief_for(task, organs, sources_index, log): ex = task["examples"] refuse, bhits = boundary(ex) if refuse: return {"id": task["id"], "outcome": "refuse", "type": "none", "neighbors": [], "givens": [], "gap": "", "refusals": [refuse], "sources": [], "evidence": {"boundary": bhits}} per = [] score = collections.Counter() read_ids = set() declined_kinds = collections.Counter() givens_all = [] fully = 0 engaged = 0 unread_terms = collections.Counter() asked = [] for q in ex: rs = [r for r in (raw_reply(o, q) for o in organs) if r is not None] full = False for r in rs: if r["c"] == "READ": o = next(x for x in organs if x.id == r["id"]) dep, n = dependence(o, q, r["response"]) r["dep"], r["n_givens"] = dep, n score[r["id"]] += 2 read_ids.add(r["id"]) r["uses_number"] = dep > 0 # the 7% check shows USE of a number, not a correct reading r["support"] = support(r) if r["support"] >= 1 and (n == 0 or dep > 0): full = True else: score[r["id"]] += 1 if r["c"] == "DECLINED": declined_kinds[r["kind"]] += 1 fully += full engaged += bool(rs) try: gq = read_givens(q) gq = gq[0] if isinstance(gq, tuple) else gq except Exception: # noqa: BLE001 gq = [] for g in gq: unit = re.sub(r"[-\d.,]+", " ", str(getattr(g, "text", ""))).strip().lower() unit = re.sub(r"\s+", " ", unit).replace("$", "usd").strip() dimn = dim_name(getattr(g, "dim", None)) givens_all.append({"name": getattr(g, "role", "") or dimn, "unit": unit, "dimension": dimn, "role": role_of(unit, q) or dimn}) try: goal = read_goal(q) except Exception: # noqa: BLE001 goal = None try: at = asktype.classify(q) except Exception: # noqa: BLE001 at = {} asked.append({"goal": dim_name(goal) if goal else None, "coarse": at.get("coarse"), "type": at.get("type"), "focus": at.get("focus")}) if not full: for w in set(terms(q)): unread_terms[w] += 1 per.append({"q": q, "readings": rs, "fully_read": full, "givens": len(gq)}) log.write(json.dumps({"task": task["id"], "q": q, "readings": rs, "fully_read": full, "asked": asked[-1]}) + "\n") named = [m.group(1) for q in ex for m in NAME_RX.finditer(q)] if fully >= max(2, -(-2 * len(ex) // 3)): # the hole is filled on two thirds of the examples (4 of 6, as tested) outcome = "compose" elif engaged >= 2: outcome = "build" else: outcome = "new" neighbors = [sid for sid, s in score.most_common() if s >= 2 or sid in read_ids][:4] n_dated = sum(bool(DATED.search(q)) for q in ex) n_givens = sum(p["givens"] > 0 for p in per) coarse = collections.Counter(a["coarse"] for a in asked) if outcome == "compose": typ = "none" elif n_dated >= 3: typ = "new_type" elif n_givens >= 3: typ = "formula" elif len(set(named)) >= 3: typ = "table" elif coarse.get("NUM", 0) >= 3: typ = "table" elif any(n.startswith("rel-") for n in neighbors): typ = "relation" elif coarse.get("ENTY", 0) + coarse.get("ABBR", 0) + coarse.get("LOC", 0) + coarse.get("HUM", 0) >= 3: typ = "table" else: typ = "facts" if len(set(named)) >= 2: givens_all.append({"name": "named thing", "unit": "name", "dimension": "name", "role": "name"}) seen = {} for g in givens_all: seen.setdefault((g["unit"], g["role"]), g) shared = [w for w, c in unread_terms.most_common() if c >= 2][:8] focus = [a["focus"] for a in asked if a.get("focus")] if outcome == "compose": gap = "" else: asked_types = [a.get("goal") or (a.get("type") or "") for a in asked] A = collections.Counter(x for x in asked_types if x).most_common(1) roles = sorted({g["role"] for g in seen.values() if g.get("role")}) gap = "[%s |- ?u : %s] %s for: %s" % (", ".join(roles) or "names", A[0][0] if A else "value", typ, ", ".join(shared or focus[:6])) if focus: gap += "; asked about: %s" % ", ".join(sorted(set(focus))[:6]) if declined_kinds: gap += "; recognised but declined: %s" % ", ".join(k for k, _ in declined_kinds.most_common(4)) gap += "; %d of %d examples read by no specialist" % (len(ex) - fully, len(ex)) srcs = [] if outcome != "compose": want = set(shared) | {w for f in focus for w in terms(f)} ranked = [] for sid, name, lic in sources_index: ov = len(want & set(terms(name))) if ov: ranked.append((sid in neighbors, ov, name, lic)) ranked.sort(key=lambda x: (x[0], x[1]), reverse=True) for _, _, name, lic in ranked[:2]: srcs.append({"repo": name, "licence": lic}) if typ in ("relation", "table") and len(set(named)) >= 2: srcs.append({"repo": "Wikidata", "licence": "CC0"}) # properties of named things if not srcs: srcs.append({"repo": "Wikipedia", "licence": "CC BY-SA"}) return {"id": task["id"], "outcome": outcome, "type": typ, "neighbors": neighbors, "givens": list(seen.values()), "gap": gap, "refusals": [k for k, v in bhits.items() if v] , "sources": srcs, "evidence": {"fully_read": fully, "engaged": engaged, "dated": n_dated, "with_givens": n_givens, "coarse": dict(coarse), "declined_kinds": dict(declined_kinds), "scores": dict(score.most_common(8))}} def main(): src, out = sys.argv[1], sys.argv[2] logp = sys.argv[3] if len(sys.argv) > 3 else out + ".readings.jsonl" tasks = json.load(open(src, encoding="utf-8"))["tasks"] t0 = time.time() organs, failed = load_family() sources_index = [] for o in organs: for s in o.m.get("sources", []) or []: sources_index.append((o.id, s.get("name", ""), s.get("licence", ""))) print("family loaded: %d specialists, %d failed to load, %d with uninformative context, %.1f s" % (len(organs), len(failed), len(BROAD), time.time() - t0), flush=True) briefs = [] with open(logp, "w", encoding="utf-8") as log: for t in tasks: b = brief_for(t, organs, sources_index, log) briefs.append(b) print(t["id"], b["outcome"], b["type"], b["neighbors"][:4], "| gap:", b["gap"][:90], flush=True) json.dump({"version": "coordinator_v2", "family": len(organs), "failed": failed, "seconds": round(time.time() - t0, 1), "briefs": briefs}, open(out, "w", encoding="utf-8"), indent=1, ensure_ascii=False) print("written", out, "%.0f s" % (time.time() - t0)) if __name__ == "__main__": main()