Download lgphys/protocol.py from tailot/lingologos-physics: direct link, hf CLI and curl.
- Browser
- Download file 8.13 kB
-
https://huggingface.co/datasets/tailot/lingologos-physics/resolve/main/lgphys/protocol.py
- Command line
-
hf download hf://datasets/tailot/lingologos-physics/lgphys/protocol.py
-
curl -L -o protocol.py https://huggingface.co/datasets/tailot/lingologos-physics/resolve/main/lgphys/protocol.py
8.13 kB
| """The envelope and the shared dossier of the physics topology. | |
| An envelope is the shape the orchestrator accepts: a sender, a recipient, a turn number, a clock | |
| tick and a payload holding natural language, an abstract syntax tree and an SMT program. The tree | |
| of a physics node is a short algebraic line rather than a deep term, because what matters here is | |
| the number a node read, the group it checked and the answer it recorded; the exact arithmetic | |
| travels as pinned names inside the SMT program. | |
| The dossier travels inside the natural language field, after the marker ``@@DOSSIER@@``, as one | |
| JSON object. It is the only way information moves forward in a fixed chain: each node reads the | |
| dossier it received, adds its own sections and passes it on, so the arbiter at the end of the chain | |
| holds everything the other ten agents saw. Fractions are carried as exact rational strings ("3000", | |
| "25/18"), never as binary floating point numbers, so a rational that leaves one node arrives | |
| unchanged at the next. | |
| The envelope is built here and nowhere else, which is what lets the same agents run inside one | |
| process for a quick check and across eleven orchestrated processes for a real measurement. | |
| """ | |
| import json | |
| from fractions import Fraction | |
| from typing import Dict, List, Optional, Sequence, Tuple | |
| from . import agents | |
| MARK = "@@DOSSIER@@" | |
| VERSION = 1 | |
| def _plain(value: object) -> str: | |
| """JSON fallback: fractions and other exact values become their exact textual form.""" | |
| if isinstance(value, Fraction): | |
| if value.denominator == 1: | |
| return "%d" % value.numerator | |
| return "%d/%d" % (value.numerator, value.denominator) | |
| return str(value) | |
| def encode(problem: str, dossier: Dict[str, object]) -> str: | |
| """The natural language field: the question, the marker, the dossier as one JSON object.""" | |
| return "%s\n%s%s" % (problem, MARK, json.dumps(dossier, sort_keys=True, default=_plain)) | |
| def decode(natural_language: str) -> Tuple[str, Dict[str, object]]: | |
| """Split a natural language field back into its question and its dossier. | |
| A payload without a marker is a node that was pointed at an idle seed, which is not an error: | |
| an empty dossier is what such a seed carries, and the chain still has to produce a verdict. | |
| """ | |
| text = natural_language or "" | |
| if MARK not in text: | |
| return text.strip(), {} | |
| line, _, blob = text.partition(MARK) | |
| try: | |
| data = json.loads(blob) | |
| except ValueError: | |
| return line.strip(), {} | |
| if not isinstance(data, dict): | |
| return line.strip(), {} | |
| return line.strip(), data | |
| def start(problem: str) -> Dict[str, object]: | |
| """The dossier a chain starts with: the question and nothing else.""" | |
| return {"v": VERSION, "problem": problem} | |
| def update(dossier: Dict[str, object], **fields: object) -> Dict[str, object]: | |
| """A copy of the dossier with the sections this node adds.""" | |
| merged = dict(dossier) | |
| merged.update(fields) | |
| return merged | |
| def summary(dossier: Dict[str, object]) -> str: | |
| """The abstract syntax tree line: what the chain knows so far, as one short algebraic term.""" | |
| parts: List[str] = ["PhysicsProblem"] | |
| kind = dossier.get("kind") | |
| if kind: | |
| parts.append(str(kind)) | |
| readers = dossier.get("readers") or {} | |
| parts.append("readers=%d" % len(readers)) | |
| roads = dossier.get("roads") or {} | |
| parts.append("roads=%s" % ",".join(sorted(roads)) if roads else "roads=none") | |
| if dossier.get("abstain"): | |
| parts.append("abstain=%s" % dossier["abstain"]) | |
| elif not dossier.get("delegate"): | |
| parts.append("delegation=none") | |
| else: | |
| parts.append("delegate=%s" % dossier["delegate"]) | |
| maths = dossier.get("math") or {} | |
| if maths: | |
| parts.append("math=%s" % maths.get("status")) | |
| answer = dossier.get("answer") or {} | |
| if answer: | |
| parts.append("answer=%s" % answer.get("type")) | |
| states = dossier.get("states") or {} | |
| if states: | |
| parts.append("states=%s" % ",".join("%s:%s" % (name, states[name]) for name in sorted(states))) | |
| reported = dossier.get("reported") | |
| if isinstance(reported, dict) and reported.get("status"): | |
| parts.append("verdict=%s assurance=%d" % (reported["status"], int(reported.get("assurance") or 0))) | |
| return " ".join(parts) | |
| def plain(value: object) -> str: | |
| """The JSON fallback of this module, open so a launched node can reuse it.""" | |
| return _plain(value) | |
| def triple(claim: Dict[str, object]) -> Tuple[List[str], List[str], str]: | |
| """The claim of a node in the three parts an envelope carries.""" | |
| return (list(claim.get("declarations") or []), list(claim.get("assertions") or []), | |
| str(claim.get("z3Status") or "unknown")) | |
| def envelope(sender: str, recipient: Optional[str], turn: int, tick: int, problem: str, | |
| dossier: Dict[str, object], claim: Sequence[Sequence[str]]) -> Dict[str, object]: | |
| """One envelope, ready to be printed or handed to the next node. | |
| ``claim`` is the triple the node closes its turn with: declarations, assertions and the | |
| satisfiability it expects. The orchestrator re-runs that program over the node ontology, and | |
| the driver compares the two answers afterwards. | |
| """ | |
| declarations, assertions, status = list(claim[0]), list(claim[1]), str(claim[2]) | |
| body: Dict[str, object] = { | |
| "sender": sender, | |
| "turn": turn, | |
| "volatileState": {"internalTimeTick": tick}, | |
| "payload": { | |
| "naturalLanguage": encode(problem, dossier), | |
| "abstractSyntaxTree": summary(dossier), | |
| "smtConstraints": { | |
| "declarations": declarations, | |
| "assertions": assertions, | |
| "z3Status": status, | |
| }, | |
| }, | |
| } | |
| if recipient: | |
| body["recipient"] = recipient | |
| return body | |
| def payload_of(envelope_or_payload: Dict[str, object]) -> Dict[str, object]: | |
| """The payload of an envelope, or the payload itself when it was already unwrapped.""" | |
| if "payload" in envelope_or_payload: | |
| return envelope_or_payload["payload"] or {} | |
| return envelope_or_payload or {} | |
| def incoming(envelopes: Sequence[Dict[str, object]]) -> Dict[str, object]: | |
| """The dossier carried by the last envelope of a list, empty when there is none.""" | |
| for envelope_item in reversed(list(envelopes)): | |
| text = payload_of(envelope_item).get("naturalLanguage") or "" | |
| _problem, dossier = decode(text) | |
| if dossier: | |
| return dossier | |
| return start("") | |
| def respond(role: str, handed: Dict[str, object], node_id: str) -> Dict[str, object]: | |
| """One turn of one orchestrated node: the envelope it was handed, the envelope it hands back. | |
| This is the whole difference between a node process and the quick in-process path: here the | |
| dossier arrives as text inside an envelope and leaves the same way, and the turn is booked by | |
| the orchestrator rather than by this code. The turn number and the clock tick of the incoming | |
| envelope are echoed, as the math topology does; the orchestrator keeps the count. | |
| An unexpected exception does not stop the session. It becomes a note in the dossier and an empty | |
| claim, so the chain ends and the arbiter reports that the chain shows nothing. | |
| """ | |
| payload = payload_of(handed) | |
| problem, dossier = decode(str(payload.get("naturalLanguage") or "")) | |
| if not dossier: | |
| dossier = start(problem) | |
| turn = int(handed.get("turn") or 0) | |
| tick = int((handed.get("volatileState") or {}).get("internalTimeTick") or 0) | |
| recipient = str(handed.get("sender") or "") or None | |
| claim: Tuple[List[str], List[str], str] = ([], ["(assert true)"], "sat") | |
| try: | |
| step = agents.run_step(role, dossier) | |
| dossier, claim = step["dossier"], triple(step["claim"]) | |
| except Exception as error: # noqa: BLE001 - containment is the point of this wrapper | |
| dossier.setdefault("crash", {})[role] = "%s: %s" % ( | |
| type(error).__name__, str(error)[:160]) | |
| return envelope(node_id, recipient, turn, tick, problem, dossier, claim) | |