rsoslang 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
rsoslang/__init__.py ADDED
@@ -0,0 +1,17 @@
1
+ """RSOS Language: a spatial-symbolic programming language for humans and AI.
2
+
3
+ One program, two runtimes: an AI system and a person's practised mental model.
4
+ The core (fixed meanings), declared bindings (scoped variations) and search (meanings left open
5
+ on purpose) follow decision D80 and addition T12 of the corpus.
6
+ """
7
+
8
+ from .lexer import tokenize
9
+ from .parser import parse, Program
10
+ from .compiler import compile_source, compile_file
11
+ from .diagnostics import Diagnostic
12
+
13
+ __version__ = "0.3.0"
14
+ LANGUAGE_VERSION = "0.2"
15
+
16
+ __all__ = ["tokenize", "parse", "Program", "compile_source", "compile_file", "Diagnostic",
17
+ "__version__", "LANGUAGE_VERSION"]
rsoslang/__main__.py ADDED
@@ -0,0 +1,80 @@
1
+ """Command line: python -m rsoslang check|ir|statements|register FILE
2
+
3
+ check FILE report errors and warnings; exit 1 on errors
4
+ ir FILE print the JSON IR (and its SHA-256 on stderr)
5
+ statements list every statement with its register links and an example
6
+ register show which register rows (U1–U87) the language covers
7
+ session FILE a person's practice session: RSX program and the cue framework's timeline
8
+ mcp run the MCP server (stdio): the State Runtime and the language as tools
9
+ """
10
+
11
+ import json
12
+ import sys
13
+ from importlib import resources
14
+
15
+ from .compiler import compile_file
16
+ from .grammar import STATEMENTS
17
+
18
+
19
+ def _register():
20
+ with resources.files("rsoslang").joinpath("data/register.json").open(encoding="utf-8") as f:
21
+ return json.load(f)
22
+
23
+
24
+ def main(argv=None):
25
+ argv = list(sys.argv[1:] if argv is None else argv)
26
+ if not argv or argv[0] in ("-h", "--help"):
27
+ print(__doc__)
28
+ return 0
29
+ cmd = argv[0]
30
+ if cmd == "mcp":
31
+ from .mcp_server import main as serve
32
+ serve()
33
+ return 0
34
+ if cmd == "statements":
35
+ if "--json" in argv:
36
+ from .grammar import signature
37
+ print(json.dumps({s.kw: {"family": s.family, "refs": s.refs, "signature": signature(s), "example": s.doc}
38
+ for s in STATEMENTS.values()}, indent=1, ensure_ascii=False))
39
+ return 0
40
+ for s in STATEMENTS.values():
41
+ print(f"{s.kw:<12} {s.family:<8} {','.join(s.refs):<22} {s.doc}")
42
+ return 0
43
+ if cmd == "register":
44
+ reg = _register()
45
+ covered = {r for s in STATEMENTS.values() for r in s.refs}
46
+ for row in reg:
47
+ mark = "x" if row["id"] in covered else " "
48
+ print(f"[{mark}] {row['id']:<4} {row['name'][:70]}")
49
+ print(f"\ncovered {sum(r['id'] in covered for r in reg)} / {len(reg)} register rows")
50
+ return 0
51
+ if cmd == "session" and len(argv) >= 2:
52
+ from .mind.session import compile_session
53
+ res = compile_file(argv[1])
54
+ for d in res.diagnostics:
55
+ print(d, file=sys.stderr)
56
+ s = compile_session(res.ir, argv[1])
57
+ print(s["rsx"])
58
+ print(f"# {len(s['steps'])} steps, {len(s['timeline']['events'])} timeline events, "
59
+ f"{s['timeline'].get('duration_ms', 0) / 1000:.0f} s; skipped {s['skipped']}; {s['footer']}", file=sys.stderr)
60
+ return 0
61
+ if cmd in ("check", "ir") and len(argv) >= 2:
62
+ res = compile_file(argv[1])
63
+ for d in res.diagnostics:
64
+ print(d, file=sys.stderr)
65
+ if cmd == "ir":
66
+ print(res.to_json())
67
+ print(f"sha256 {res.digest()}", file=sys.stderr)
68
+ else:
69
+ print(f"{argv[1]}: {len(res.errors)} errors, {len(res.warnings)} warnings, {len(res.ir['ops'])} operations")
70
+ return 0 if res.ok else 1
71
+ print(__doc__)
72
+ return 2
73
+
74
+
75
+ if __name__ == "__main__":
76
+ sys.exit(main())
77
+
78
+
79
+ def cli():
80
+ sys.exit(main())
File without changes
@@ -0,0 +1,183 @@
1
+ """Guest modules: what each one does at each place in a host node (head, heart, brain, near).
2
+
3
+ The place decides the result (owner, round 3). A guest that has no meaning at a place does nothing there, and that
4
+ is reported, not hidden.
5
+ """
6
+
7
+ import re
8
+
9
+ from .tickets import CATEGORIES
10
+
11
+ VOCAB = sorted({w for spec in CATEGORIES.values() for p in spec["words"] for w in p.split()})
12
+
13
+
14
+ def _swap_variants(word):
15
+ return {word[:i] + word[i + 1] + word[i] + word[i + 2:] for i in range(1, len(word) - 2)} if len(word) >= 4 else set()
16
+
17
+
18
+ def _correct_tokens(text):
19
+ fixed = []
20
+ for tok in text.split():
21
+ bare = tok.strip(".,!?")
22
+ hit = next((v for v in VOCAB if bare != v and bare in _swap_variants(v)), None)
23
+ fixed.append(tok.replace(bare, hit) if hit else tok)
24
+ return " ".join(fixed)
25
+
26
+
27
+ # A thesaurus that knows most, not all, of the unseen phrasings (2 of 3 per category).
28
+ THESAURUS = {cat: spec["unseen"][:2] for cat, spec in CATEGORIES.items()}
29
+
30
+
31
+ class Guest:
32
+ name = "guest"
33
+ cost = {"head": 0.0, "heart": 0.0, "brain": 0.0, "near": 0.0}
34
+
35
+ def at_head(self, node, state, ctx):
36
+ pass
37
+
38
+ def at_heart(self, node, fn):
39
+ return fn
40
+
41
+ def at_brain(self, node):
42
+ return False
43
+
44
+ def at_near(self, node, state, ctx):
45
+ pass
46
+
47
+
48
+ class SpellCorrector(Guest):
49
+ """Fixes swapped letters."""
50
+ name = "spell_corrector"
51
+ cost = {"head": 1.5, "heart": 2.5, "brain": 0.0, "near": 1.5}
52
+
53
+ def at_head(self, node, state, ctx): # corrects the text before the node reads it
54
+ if "text" in state:
55
+ state["text"] = _correct_tokens(state["text"])
56
+ ctx["cost"] += self.cost["head"]
57
+
58
+ def at_heart(self, node, fn): # the node's own matching becomes tolerant of swaps
59
+ def wrapped(n, s, c, fn=fn):
60
+ if n.role != "reason" or "lexicon" not in n.knowledge:
61
+ return fn(n, s, c)
62
+ original = n.knowledge["lexicon"]
63
+ n.knowledge["lexicon"] = {k: list(v) + [x for w in v for x in _swap_variants(w)] for k, v in original.items()}
64
+ c["cost"] += self.cost["heart"]
65
+ try:
66
+ return fn(n, s, c)
67
+ finally:
68
+ n.knowledge["lexicon"] = original
69
+ return wrapped
70
+
71
+ def at_brain(self, node): # the swapped forms are learned once into the node's knowledge
72
+ if "lexicon" not in node.knowledge:
73
+ return False
74
+ node.knowledge["lexicon"] = {k: list(v) + [x for w in v for x in _swap_variants(w)]
75
+ for k, v in node.knowledge["lexicon"].items()}
76
+ return True
77
+
78
+ def at_near(self, node, state, ctx): # corrects the text for the neighbours after the node has run
79
+ if "text" in state:
80
+ state["text"] = _correct_tokens(state["text"])
81
+ ctx["cost"] += self.cost["near"]
82
+
83
+
84
+ class SynonymExpander(Guest):
85
+ """Knows other ways of saying the same thing (most, not all)."""
86
+ name = "synonym_expander"
87
+ cost = {"head": 1.0, "heart": 2.0, "brain": 0.0, "near": 1.0}
88
+
89
+ def _rewrite(self, text):
90
+ for cat, phrases in THESAURUS.items():
91
+ for p in phrases:
92
+ text = text.replace(p, CATEGORIES[cat]["words"][0])
93
+ return text
94
+
95
+ def at_head(self, node, state, ctx):
96
+ if "text" in state:
97
+ state["text"] = self._rewrite(state["text"])
98
+ ctx["cost"] += self.cost["head"]
99
+
100
+ def at_heart(self, node, fn):
101
+ def wrapped(n, s, c, fn=fn):
102
+ if "lexicon" not in n.knowledge:
103
+ return fn(n, s, c)
104
+ original = n.knowledge["lexicon"]
105
+ n.knowledge["lexicon"] = {k: list(v) + THESAURUS.get(k, []) for k, v in original.items()}
106
+ c["cost"] += self.cost["heart"]
107
+ try:
108
+ return fn(n, s, c)
109
+ finally:
110
+ n.knowledge["lexicon"] = original
111
+ return wrapped
112
+
113
+ def at_brain(self, node):
114
+ if "lexicon" not in node.knowledge:
115
+ return False
116
+ node.knowledge["lexicon"] = {k: list(v) + THESAURUS.get(k, []) for k, v in node.knowledge["lexicon"].items()}
117
+ return True
118
+
119
+ def at_near(self, node, state, ctx):
120
+ if "text" in state:
121
+ state["text"] = self._rewrite(state["text"])
122
+ ctx["cost"] += self.cost["near"]
123
+
124
+
125
+ class Cache(Guest):
126
+ """Remembers answers it has already fetched."""
127
+ name = "cache"
128
+ cost = {"head": 0.2, "heart": 0.2, "brain": 0.0, "near": 0.2}
129
+
130
+ def at_heart(self, node, fn): # inside the memory node: a hit skips the expensive lookup
131
+ def wrapped(n, s, c, fn=fn):
132
+ if n.role != "memory":
133
+ return fn(n, s, c)
134
+ key = s.get("customer")
135
+ c["cost"] += self.cost["heart"]
136
+ if key in c["cache"]:
137
+ s["tier"] = c["cache"][key]
138
+ return s
139
+ s = fn(n, s, c)
140
+ c["cache"][key] = s["tier"]
141
+ return s
142
+ return wrapped
143
+
144
+ def at_head(self, node, state, ctx): # before the node: it can only note the request; the lookup still runs
145
+ ctx["cost"] += self.cost["head"]
146
+
147
+ def at_brain(self, node): # in the knowledge: lookups become cheaper for everyone
148
+ if "lookup_cost" not in node.knowledge:
149
+ return False
150
+ node.knowledge["lookup_cost"] = 1.5
151
+ return True
152
+
153
+
154
+ class FastRetry(Guest):
155
+ """Retries a failed tool call at once."""
156
+ name = "fast_retry"
157
+ cost = {"head": 0.0, "heart": 0.5, "brain": 0.0, "near": 0.0}
158
+
159
+ def at_heart(self, node, fn):
160
+ def wrapped(n, s, c, fn=fn):
161
+ s = fn(n, s, c)
162
+ if n.role == "tool" and not s.get("tool_ok"):
163
+ c["cost"] += self.cost["heart"] + n.cost
164
+ c["visits"]["act"] = c["visits"].get("act", 0) + 1
165
+ s = fn(n, s, c)
166
+ return s
167
+ return wrapped
168
+
169
+
170
+ class AmountValidator(Guest):
171
+ """Checks that an amount was read; reads it in another way if not."""
172
+ name = "amount_validator"
173
+ cost = {"head": 0.3, "heart": 0.3, "brain": 0.0, "near": 0.3}
174
+
175
+ def at_near(self, node, state, ctx):
176
+ if state.get("amount", 0) == 0 and "amount" in state.get("text", ""):
177
+ m = re.search(r"(\d+(?:\.\d+)?)\s*eur", state["text"])
178
+ if m:
179
+ state["amount"] = float(m.group(1))
180
+ ctx["cost"] += self.cost["near"]
181
+
182
+
183
+ LIBRARY = {g.name: g for g in (SpellCorrector(), SynonymExpander(), Cache(), FastRetry(), AmountValidator())}
@@ -0,0 +1,60 @@
1
+ """A deterministic benchmark for the agent workflow: customer-support tickets with known answers.
2
+
3
+ Each ticket has a category, the right action and (for refunds) an amount. Held-out sets add typos and phrasing the
4
+ workflow has never seen, so improvements can be measured on tickets not used while building.
5
+ """
6
+
7
+ import random
8
+
9
+ CATEGORIES = {
10
+ "billing": {"words": ["invoice", "charged", "payment", "bill", "refund"], "action": "refund",
11
+ "unseen": ["debited", "overbilled", "money back"]},
12
+ "technical": {"words": ["error", "crash", "bug", "broken", "freezes"], "action": "troubleshoot",
13
+ "unseen": ["glitch", "stops working", "keeps closing"]},
14
+ "account": {"words": ["password", "login", "locked", "account", "sign in"], "action": "reset",
15
+ "unseen": ["cannot get in", "credentials", "two factor"]},
16
+ "shipping": {"words": ["delivery", "package", "shipping", "parcel", "tracking"], "action": "track",
17
+ "unseen": ["courier", "never arrived", "order is late"]},
18
+ }
19
+ TEMPLATES = [
20
+ "Hello, {w} problem with my order {cid}. {extra}",
21
+ "I have an issue: {w}. Customer {cid}. {extra}",
22
+ "{extra} My {w} is not right, id {cid}.",
23
+ "Please help, {w} again for {cid}! {extra}",
24
+ ]
25
+ EXTRAS = ["Thanks.", "This is urgent.", "Second time writing.", "", "Kind regards."]
26
+
27
+
28
+ def typo(word, rng):
29
+ if len(word) < 4:
30
+ return word
31
+ i = rng.randrange(1, len(word) - 2)
32
+ return word[:i] + word[i + 1] + word[i] + word[i + 2:]
33
+
34
+
35
+ def make_tickets(n, seed, typo_rate=0.0, unseen_rate=0.0):
36
+ rng = random.Random(seed)
37
+ out = []
38
+ for k in range(n):
39
+ cat = rng.choice(list(CATEGORIES))
40
+ spec = CATEGORIES[cat]
41
+ w = rng.choice(spec["unseen"]) if rng.random() < unseen_rate else rng.choice(spec["words"])
42
+ if rng.random() < typo_rate:
43
+ w = " ".join(typo(x, rng) for x in w.split())
44
+ cid = f"C{rng.randrange(1000, 1200)}" if rng.random() < 0.5 else f"C{rng.randrange(1000, 9999)}" # regulars
45
+ amount = round(rng.uniform(5, 400), 2) if cat == "billing" else 0.0
46
+ extra = rng.choice(EXTRAS)
47
+ text = rng.choice(TEMPLATES).format(w=w, cid=cid, extra=extra)
48
+ if amount:
49
+ text += f" Amount {amount} EUR."
50
+ out.append({"id": k, "text": text, "category": cat, "action": spec["action"], "customer": cid,
51
+ "amount": amount})
52
+ return out
53
+
54
+
55
+ def knowledge_base(seed=7):
56
+ rng = random.Random(seed)
57
+ return {f"C{i}": rng.choice(["gold", "silver", "bronze"]) for i in range(1000, 10000)}
58
+
59
+
60
+ REFUND_LIMIT = {"gold": 300.0, "silver": 150.0, "bronze": 50.0}
@@ -0,0 +1,209 @@
1
+ """A 12-module agent workflow with addressable parts, so the painting's gestures have exact program meanings.
2
+
3
+ Every node has four places a guest module can be put (owner, round 3: "each of the places will have different
4
+ result"):
5
+ head before the node: on its input (attention, alert)
6
+ heart inside the node's execution: wraps how it works
7
+ brain in the node's knowledge: its lexicon, tables, parameters
8
+ near beside the node: acts on what flows on to its neighbours, not on the node itself
9
+ """
10
+
11
+ import copy
12
+ import random
13
+ import re
14
+ from dataclasses import dataclass, field
15
+
16
+ from .tickets import knowledge_base, REFUND_LIMIT, CATEGORIES
17
+
18
+
19
+ @dataclass
20
+ class Node:
21
+ name: str
22
+ role: str
23
+ layer: int # 0 = top (supervisory) … 3 = bottom (input/output, infrastructure)
24
+ cost: float
25
+ knowledge: dict = field(default_factory=dict)
26
+ head: list = field(default_factory=list)
27
+ heart: list = field(default_factory=list)
28
+ brain: list = field(default_factory=list) # guests learned into the knowledge (shown on the painting)
29
+ near: list = field(default_factory=list)
30
+ sandboxed: bool = False
31
+ retries: int = 0
32
+
33
+ def run(self, fn, state, ctx):
34
+ for g in self.head:
35
+ g.at_head(self, state, ctx)
36
+ call = fn
37
+ for g in self.heart:
38
+ call = g.at_heart(self, call)
39
+ if self.sandboxed:
40
+ inner = call
41
+
42
+ def call(n, s, c, inner=inner):
43
+ try:
44
+ return inner(n, s, c)
45
+ except ToolCrash:
46
+ c["contained"] += 1
47
+ s["action"] = "escalate"
48
+ return s
49
+ state = call(self, state, ctx)
50
+ for g in self.near:
51
+ g.at_near(self, state, ctx)
52
+ ctx["cost"] += self.cost
53
+ ctx["visits"][self.name] = ctx["visits"].get(self.name, 0) + 1
54
+ return state
55
+
56
+
57
+ class ToolCrash(Exception):
58
+ pass
59
+
60
+
61
+ # ---- the twelve node functions ----------------------------------------------------------------------
62
+ def f_intake(n, s, c):
63
+ s["text"] = s["ticket"]["text"]
64
+ return s
65
+
66
+
67
+ def f_normalize(n, s, c):
68
+ s["text"] = re.sub(r"[^\w\s.]", " ", s["text"].lower())
69
+ return s
70
+
71
+
72
+ def f_classify(n, s, c):
73
+ text = s["text"]
74
+ best, hits = "other", 0
75
+ for cat, words in n.knowledge["lexicon"].items():
76
+ h = sum(1 for w in words if w in text)
77
+ if h > hits:
78
+ best, hits = cat, h
79
+ s["category"] = best
80
+ return s
81
+
82
+
83
+ def f_extract(n, s, c):
84
+ m = re.search(r"amount (\d+(?:\.\d+)?)", s["text"])
85
+ s["amount"] = float(m.group(1)) if m else 0.0
86
+ m = re.search(r"\bc(\d{4})\b", s["text"])
87
+ s["customer"] = f"C{m.group(1)}" if m else None
88
+ return s
89
+
90
+
91
+ def f_memory(n, s, c):
92
+ s["tier"] = n.knowledge["kb"].get(s["customer"], "bronze")
93
+ c["cost"] += n.knowledge.get("lookup_cost", 3.0)
94
+ return s
95
+
96
+
97
+ def f_priority(n, s, c):
98
+ s["priority"] = "high" if s["tier"] == "gold" or s["amount"] > 200 else "normal"
99
+ return s
100
+
101
+
102
+ ACTIONS = {cat: spec["action"] for cat, spec in CATEGORIES.items()}
103
+
104
+
105
+ def f_plan(n, s, c):
106
+ s["action"] = ACTIONS.get(s["category"], "escalate")
107
+ return s
108
+
109
+
110
+ def f_policy(n, s, c):
111
+ if s["action"] == "refund" and s["amount"] > REFUND_LIMIT[s["tier"]]:
112
+ s["action"] = "escalate"
113
+ return s
114
+
115
+
116
+ def f_act(n, s, c):
117
+ r = random.Random(f"{c['seed']}:{s['ticket']['id']}:{c['visits'].get('act', 0)}")
118
+ x = r.random()
119
+ if x < 0.05:
120
+ raise ToolCrash("tool crashed")
121
+ s["tool_ok"] = x >= 0.20 # 15% of calls fail softly
122
+ return s
123
+
124
+
125
+ def f_verify(n, s, c):
126
+ s["verified"] = s.get("tool_ok", False)
127
+ return s
128
+
129
+
130
+ def f_respond(n, s, c):
131
+ s["response"] = s["action"] if s.get("verified") else "escalate"
132
+ return s
133
+
134
+
135
+ def f_log(n, s, c):
136
+ c["log"].append((s["ticket"]["id"], s.get("category"), s.get("response")))
137
+ return s
138
+
139
+
140
+ FUNCS = {"intake": f_intake, "normalize": f_normalize, "classify": f_classify, "extract": f_extract,
141
+ "memory": f_memory, "priority": f_priority, "plan": f_plan, "policy": f_policy, "act": f_act,
142
+ "verify": f_verify, "respond": f_respond, "log": f_log}
143
+ ORDER = list(FUNCS)
144
+
145
+
146
+ def build():
147
+ lex = {cat: list(spec["words"]) for cat, spec in CATEGORIES.items()}
148
+ nodes = {
149
+ "intake": Node("intake", "input", 3, 0.5),
150
+ "normalize": Node("normalize", "transform", 2, 0.5),
151
+ "classify": Node("classify", "reason", 1, 1.0, {"lexicon": lex}),
152
+ "extract": Node("extract", "transform", 2, 1.0),
153
+ "memory": Node("memory", "memory", 2, 0.5, {"kb": knowledge_base(), "lookup_cost": 3.0}),
154
+ "priority": Node("priority", "reason", 1, 0.5),
155
+ "plan": Node("plan", "reason", 1, 1.0),
156
+ "policy": Node("policy", "policy", 0, 0.5),
157
+ "act": Node("act", "tool", 2, 2.0, retries=1),
158
+ "verify": Node("verify", "check", 1, 0.5),
159
+ "respond": Node("respond", "output", 3, 0.5),
160
+ "log": Node("log", "output", 3, 0.2),
161
+ }
162
+ return Workflow(nodes)
163
+
164
+
165
+ class Workflow:
166
+ def __init__(self, nodes):
167
+ self.nodes = nodes
168
+ self.order = list(ORDER)
169
+
170
+ def copy(self):
171
+ return copy.deepcopy(self)
172
+
173
+ def run_ticket(self, t, ctx):
174
+ s = {"ticket": t}
175
+ for name in self.order:
176
+ n = self.nodes[name]
177
+ if name == "act": # the core loop: act → verify, retried
178
+ for attempt in range(1 + n.retries):
179
+ s = n.run(FUNCS["act"], s, ctx)
180
+ if s.get("tool_ok"):
181
+ break
182
+ continue
183
+ s = n.run(FUNCS[name], s, ctx)
184
+ return s
185
+
186
+ def evaluate(self, tickets, seed=0):
187
+ ctx = {"cost": 0.0, "visits": {}, "log": [], "seed": seed, "contained": 0, "cache": {}}
188
+ correct = crashed = 0
189
+ per_node_err = {}
190
+ for t in tickets:
191
+ expected = t["action"]
192
+ if t["category"] == "billing":
193
+ tier = knowledge_base().get(t["customer"], "bronze")
194
+ if t["amount"] > REFUND_LIMIT[tier]:
195
+ expected = "escalate"
196
+ try:
197
+ s = self.run_ticket(t, ctx)
198
+ except ToolCrash:
199
+ crashed += 1
200
+ per_node_err["act"] = per_node_err.get("act", 0) + 1
201
+ continue
202
+ if s.get("category") != t["category"]:
203
+ per_node_err["classify"] = per_node_err.get("classify", 0) + 1
204
+ ok = s.get("category") == t["category"] and s.get("response") == expected
205
+ correct += ok
206
+ n = len(tickets)
207
+ return {"accuracy": correct / n, "crashed": crashed / n, "cost_per_ticket": ctx["cost"] / n,
208
+ "contained": ctx["contained"], "visits": ctx["visits"], "errors": per_node_err,
209
+ "score": correct / n - 0.01 * ctx["cost"] / n}
rsoslang/compiler.py ADDED
@@ -0,0 +1,51 @@
1
+ """Compile RSOS Language source to the JSON intermediate representation."""
2
+
3
+ import hashlib
4
+ import json
5
+ from dataclasses import dataclass
6
+
7
+ from .parser import parse
8
+ from .semantics import analyze
9
+
10
+
11
+ @dataclass
12
+ class Result:
13
+ ir: dict
14
+ diagnostics: list
15
+
16
+ @property
17
+ def ok(self):
18
+ return not any(d.is_error for d in self.diagnostics)
19
+
20
+ @property
21
+ def errors(self):
22
+ return [d for d in self.diagnostics if d.is_error]
23
+
24
+ @property
25
+ def warnings(self):
26
+ return [d for d in self.diagnostics if not d.is_error]
27
+
28
+ def to_json(self, indent=2):
29
+ return json.dumps(self.ir, indent=indent, ensure_ascii=False, sort_keys=True)
30
+
31
+ def digest(self):
32
+ """SHA-256 of the canonical IR: the same source always gives the same digest."""
33
+ canon = json.dumps(self.ir, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
34
+ return hashlib.sha256(canon.encode("utf-8")).hexdigest()
35
+
36
+
37
+ def compile_source(source: str, govern: bool = True) -> Result:
38
+ prog = parse(source)
39
+ ir, sem = analyze(prog.statements)
40
+ gov = []
41
+ if govern and ir.get("hosts"):
42
+ from .governance import govern as _govern
43
+ _, gov = _govern(ir)
44
+ diags = sorted(prog.diagnostics + sem + gov, key=lambda d: (d.line, d.code))
45
+ ir["diagnostics"] = [d.to_dict() for d in diags]
46
+ return Result(ir, diags)
47
+
48
+
49
+ def compile_file(path) -> Result:
50
+ with open(path, encoding="utf-8") as f:
51
+ return compile_source(f.read())