amiril 0.0.0.dev0__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.
Files changed (64) hide show
  1. amiril/__init__.py +51 -0
  2. amiril/_adapters.py +399 -0
  3. amiril/_engine/__init__.py +1 -0
  4. amiril/_engine/engine.py +113 -0
  5. amiril/_engine/expr.py +653 -0
  6. amiril/_engine/numbers.py +111 -0
  7. amiril/_engine/regex.py +262 -0
  8. amiril/_engine/rules.py +192 -0
  9. amiril/_engine/sentence.py +251 -0
  10. amiril/_engine/timeparse.py +72 -0
  11. amiril/_engine/validate.py +863 -0
  12. amiril/_engine/values.py +273 -0
  13. amiril/_kernel/__init__.py +1 -0
  14. amiril/_kernel/bundle.py +245 -0
  15. amiril/_kernel/coerce.py +103 -0
  16. amiril/_kernel/events.py +87 -0
  17. amiril/_kernel/guard.py +1196 -0
  18. amiril/_kernel/ids.py +66 -0
  19. amiril/_kernel/messages.py +30 -0
  20. amiril/_kernel/normalise.py +165 -0
  21. amiril/_kernel/records.py +131 -0
  22. amiril/_kernel/store.py +661 -0
  23. amiril/_runtime.py +617 -0
  24. amiril/adk.py +577 -0
  25. amiril/control/__init__.py +25 -0
  26. amiril/control/_delivery.py +567 -0
  27. amiril/control/_disk.py +418 -0
  28. amiril/control/_holds.py +252 -0
  29. amiril/control/_jsonschema.py +265 -0
  30. amiril/control/_pathc.py +85 -0
  31. amiril/control/_records.py +293 -0
  32. amiril/control/_redact.py +79 -0
  33. amiril/control/_transport.py +184 -0
  34. amiril/control/_wire.py +73 -0
  35. amiril/control/client.py +1313 -0
  36. amiril/control/config.py +204 -0
  37. amiril/control/schemas/bundle.response.schema.json +22 -0
  38. amiril/control/schemas/common.schema.json +593 -0
  39. amiril/control/schemas/decisions.request.schema.json +558 -0
  40. amiril/control/schemas/decisions.response.schema.json +23 -0
  41. amiril/control/schemas/error.response.schema.json +54 -0
  42. amiril/control/schemas/heartbeat.request.schema.json +305 -0
  43. amiril/control/schemas/heartbeat.response.schema.json +34 -0
  44. amiril/control/schemas/hold-create.request.schema.json +138 -0
  45. amiril/control/schemas/hold.response.schema.json +226 -0
  46. amiril/control/schemas/installation-register.request.schema.json +492 -0
  47. amiril/control/schemas/installation-register.response.schema.json +85 -0
  48. amiril/core.py +89 -0
  49. amiril/docs/README.md +14 -0
  50. amiril/docs/durability/langgraph.md +292 -0
  51. amiril/docs/frameworks/adk.md +141 -0
  52. amiril/docs/frameworks/langgraph.md +154 -0
  53. amiril/docs/frameworks/no-framework.md +238 -0
  54. amiril/docs/frameworks/write-an-adapter.md +203 -0
  55. amiril/durable.py +342 -0
  56. amiril/langgraph.py +746 -0
  57. amiril/plain.py +454 -0
  58. amiril/py.typed +0 -0
  59. amiril/seams.py +357 -0
  60. amiril/testing.py +21 -0
  61. amiril-0.0.0.dev0.dist-info/METADATA +114 -0
  62. amiril-0.0.0.dev0.dist-info/RECORD +64 -0
  63. amiril-0.0.0.dev0.dist-info/WHEEL +4 -0
  64. amiril-0.0.0.dev0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,863 @@
1
+ """Loading a rule document (spec/edoc.md, section 12).
2
+
3
+ `validate_document` runs the three layers (shape, references and syntax,
4
+ host registration) in one walk and reports every problem it finds as
5
+ `{"path": <JSON Pointer>, "code": <code>, "message": <free text>}`. The
6
+ codes and the pointers are the normative part; the messages are a
7
+ rendering.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import re
13
+ from typing import Any
14
+
15
+ from .regex import check_pattern
16
+
17
+ SCHEMA_ID = "amiril.rules/1"
18
+ # One name per addition to the rule document this loader reads beyond the
19
+ # first `amiril.rules/1` (edoc.md 13). The client sends it at registration.
20
+ CAPABILITIES: tuple[str, ...] = ()
21
+
22
+ ACTIONS = ("allow", "flag", "hold", "block")
23
+ FAIL_ACTIONS = ("flag", "hold", "block")
24
+ POST_ACTIONS = ("allow", "flag")
25
+ PHASES = ("pre", "post", "run_end")
26
+ MODES = ("off", "shadow", "enforce")
27
+ FAIL_MODES = ("open", "closed")
28
+ IF_MISSING = ("violate", "skip")
29
+ STATUSES = ("pending", "ok", "error", "blocked", "held")
30
+ PICKS = ("latest", "first", "all")
31
+ AGG_OPS = ("sum", "min", "max", "count", "count_distinct")
32
+ TYPE_NAMES = ("number", "string", "boolean", "null", "list", "object")
33
+ CONTEXT_FIELDS = ("agent_id", "agent_version", "env", "now", "run_id", "session_id")
34
+ RECORD_FIELDS = (
35
+ "call_id", "run_id", "root_run_id", "session_id", "agent_id", "tool_id", "tool_name_raw", "args",
36
+ "result", "status", "error", "seq", "batch_id", "parent_call_id", "correlation", "attempt", "kind",
37
+ )
38
+
39
+ TOP_KEYS = frozenset({"schema", "ruleset_version", "sets", "groups", "aliases", "predicates", "rules", "about"})
40
+ RULE_KEYS = frozenset({
41
+ "id", "version", "description", "target", "agents", "phase", "scope", "when", "let", "assert", "bands",
42
+ "action", "mode", "if_missing", "on_error", "fail_mode", "hold_timeout_ms", "sentence", "portable", "meta",
43
+ })
44
+ CALLS_KEYS = frozenset({"tool", "status", "join", "where", "scope", "kind"})
45
+ PRIOR_KEYS = CALLS_KEYS | {"path", "pick"}
46
+ AGG_KEYS = frozenset({"op", "of", "field", "with"})
47
+
48
+ # Operators taking a list of sub-expressions: name -> (min, max or None).
49
+ LIST_OPS: dict[str, tuple[int, int | None]] = {
50
+ "==": (2, 2), "!=": (2, 2), "<": (2, 2), "<=": (2, 2), ">": (2, 2), ">=": (2, 2),
51
+ "and": (2, None), "or": (2, None),
52
+ "+": (2, None), "*": (2, None), "-": (2, 2), "/": (2, 2), "min": (2, None), "max": (2, None),
53
+ "in": (2, 2),
54
+ }
55
+ UNARY_OPS = frozenset({"not", "abs", "len", "present", "hour_utc"})
56
+ STRING_OPS = frozenset({"arg", "path", "ctx", "set", "var", "it", "prev"})
57
+ STRUCTURED_OPS = frozenset({"lit", "is", "matches", "all", "any", "exists", "calls", "prior", "agg", "predicate"})
58
+ ALL_OPS = frozenset(LIST_OPS) | UNARY_OPS | STRING_OPS | STRUCTURED_OPS
59
+ BARE_READS = frozenset({"arg", "path", "ctx", "prior", "prev", "agg", "exists"})
60
+
61
+ _IDENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*\Z")
62
+ _SCOPE = re.compile(r"(run|session|correlation:[A-Za-z_][A-Za-z0-9_]*)\Z")
63
+ _PLACEHOLDER = re.compile(r"\{([^{}]+)\}")
64
+
65
+
66
+ def is_identifier(s: Any) -> bool:
67
+ return type(s) is str and _IDENT.match(s) is not None and "\n" not in s
68
+
69
+
70
+ def is_scope(s: Any) -> bool:
71
+ return type(s) is str and _SCOPE.match(s) is not None and "\n" not in s
72
+
73
+
74
+ def is_dotted_path(s: Any, allow_empty: bool = False) -> bool:
75
+ if type(s) is not str or "\n" in s:
76
+ return False
77
+ if s == "":
78
+ return allow_empty
79
+ return all(seg != "" for seg in s.split("."))
80
+
81
+
82
+ def pointer(*segments: Any) -> str:
83
+ return "".join("/" + str(s).replace("~", "~0").replace("/", "~1") for s in segments)
84
+
85
+
86
+ class DocumentError(ValueError):
87
+ """The document was refused. `problems` lists every `{path, code, message}`."""
88
+
89
+ def __init__(self, problems: list[dict]) -> None:
90
+ text = "; ".join(f"{p['path'] or '/'}: {p['code']} ({p['message']})" for p in problems)
91
+ super().__init__("invalid rule document: " + text)
92
+ self.problems = problems
93
+
94
+
95
+ class _Report:
96
+ def __init__(self) -> None:
97
+ self.problems: list[dict] = []
98
+
99
+ def add(self, path: str, code: str, message: str) -> None:
100
+ self.problems.append({"path": path, "code": code, "message": message})
101
+
102
+
103
+ class _Doc:
104
+ """What the rule and expression checks need from the document's top level."""
105
+
106
+ def __init__(self, sets: set[str], groups: set[str], predicates: set[str]) -> None:
107
+ self.sets, self.groups, self.predicates = sets, groups, predicates
108
+
109
+
110
+ class _RuleCtx:
111
+ def __init__(self, rule: dict, let_names: set[str]) -> None:
112
+ self.rule = rule
113
+ self.let_names = let_names
114
+ self.uses_predicate = False
115
+
116
+
117
+ def validate_document(doc: Any, registered_predicates: set[str] | None = None) -> list[dict]:
118
+ """Every problem with the document, in document order; empty means it loads.
119
+ `registered_predicates` is the host layer: None skips that layer."""
120
+ rep = _Report()
121
+ if type(doc) is not dict:
122
+ rep.add("", "not_an_object", "the document must be a JSON object")
123
+ return rep.problems
124
+
125
+ for key in ("schema", "ruleset_version", "rules"):
126
+ if key not in doc:
127
+ rep.add(pointer(key), "missing_key", f"the document needs {key!r}")
128
+ for key in doc:
129
+ if key not in TOP_KEYS:
130
+ rep.add(pointer(key), "unknown_key", f"{key!r} is not a document key")
131
+ if "schema" in doc and doc["schema"] != SCHEMA_ID:
132
+ rep.add(pointer("schema"), "bad_schema_id", f"schema must be {SCHEMA_ID!r}")
133
+ if "ruleset_version" in doc:
134
+ _nonempty_string(rep, pointer("ruleset_version"), doc["ruleset_version"], "ruleset_version")
135
+ if "about" in doc and type(doc["about"]) is not str:
136
+ rep.add(pointer("about"), "bad_type", "about must be a string")
137
+
138
+ sets: set[str] = set()
139
+ raw_sets = doc.get("sets")
140
+ if raw_sets is not None:
141
+ if type(raw_sets) is not dict:
142
+ rep.add(pointer("sets"), "bad_type", "sets must map identifiers to lists")
143
+ else:
144
+ for name, values in raw_sets.items():
145
+ if not is_identifier(name):
146
+ rep.add(pointer("sets", name), "bad_value", f"{name!r} is not an identifier")
147
+ if type(values) is not list:
148
+ rep.add(pointer("sets", name), "bad_type", "a set is a list of values")
149
+ else:
150
+ sets.add(name)
151
+
152
+ groups: set[str] = set()
153
+ raw_groups = doc.get("groups")
154
+ if raw_groups is not None:
155
+ if type(raw_groups) is not dict:
156
+ rep.add(pointer("groups"), "bad_type", "groups must map identifiers to lists of tool ids")
157
+ else:
158
+ for name, members in raw_groups.items():
159
+ if not is_identifier(name):
160
+ rep.add(pointer("groups", name), "bad_value", f"{name!r} is not an identifier")
161
+ if type(members) is not list:
162
+ rep.add(pointer("groups", name), "bad_type", "a group is a list of tool ids")
163
+ continue
164
+ if not members:
165
+ rep.add(pointer("groups", name), "bad_value", "a group needs at least one tool id")
166
+ for i, m in enumerate(members):
167
+ _nonempty_string(rep, pointer("groups", name, i), m, "a tool id")
168
+ groups.add(name)
169
+
170
+ raw_aliases = doc.get("aliases")
171
+ if raw_aliases is not None:
172
+ if type(raw_aliases) is not dict:
173
+ rep.add(pointer("aliases"), "bad_type", "aliases must be an object with tools and args")
174
+ else:
175
+ for key, mapping in raw_aliases.items():
176
+ if key not in ("tools", "args"):
177
+ rep.add(pointer("aliases", key), "unknown_key", "aliases has only tools and args")
178
+ continue
179
+ if type(mapping) is not dict:
180
+ rep.add(pointer("aliases", key), "bad_type", f"aliases.{key} must map strings to strings")
181
+ continue
182
+ for raw, canon in mapping.items():
183
+ if type(canon) is not str:
184
+ rep.add(pointer("aliases", key, raw), "bad_type", "an alias target is a string")
185
+
186
+ predicates: set[str] = set()
187
+ raw_preds = doc.get("predicates")
188
+ if raw_preds is not None:
189
+ if type(raw_preds) is not list:
190
+ rep.add(pointer("predicates"), "bad_type", "predicates must be a list of identifiers")
191
+ else:
192
+ for i, name in enumerate(raw_preds):
193
+ if type(name) is not str:
194
+ rep.add(pointer("predicates", i), "bad_type", "a predicate name is a string")
195
+ continue
196
+ if not is_identifier(name):
197
+ rep.add(pointer("predicates", i), "bad_value", f"{name!r} is not an identifier")
198
+ continue
199
+ predicates.add(name)
200
+ if registered_predicates is not None and name not in registered_predicates:
201
+ rep.add(pointer("predicates", i), "predicate_not_registered",
202
+ f"predicate {name!r} is declared but the host registered no function for it")
203
+
204
+ rules = doc.get("rules")
205
+ if "rules" in doc:
206
+ if type(rules) is not list:
207
+ rep.add(pointer("rules"), "bad_type", "rules must be a list")
208
+ else:
209
+ dctx = _Doc(sets, groups, predicates)
210
+ seen: set[str] = set()
211
+ for i, rule in enumerate(rules):
212
+ if type(rule) is not dict:
213
+ rep.add(pointer("rules", i), "not_an_object", "a rule must be a JSON object")
214
+ continue
215
+ rid = rule.get("id")
216
+ if type(rid) is str and rid:
217
+ if rid in seen:
218
+ rep.add(pointer("rules", i, "id"), "duplicate_rule_id", f"rule id {rid!r} is used twice")
219
+ seen.add(rid)
220
+ _rule(rep, pointer("rules", i), rule, dctx)
221
+ return rep.problems
222
+
223
+
224
+ def _nonempty_string(rep: _Report, path: str, value: Any, what: str) -> bool:
225
+ if type(value) is not str:
226
+ rep.add(path, "bad_type", f"{what} must be a string")
227
+ return False
228
+ if value == "":
229
+ rep.add(path, "bad_value", f"{what} must not be empty")
230
+ return False
231
+ return True
232
+
233
+
234
+ def _enum(rep: _Report, path: str, value: Any, values: tuple, what: str) -> bool:
235
+ if value not in values or type(value) is not str:
236
+ rep.add(path, "bad_value", f"{what} must be one of {', '.join(values)}")
237
+ return False
238
+ return True
239
+
240
+
241
+ def _rule(rep: _Report, where: str, rule: dict, dctx: _Doc) -> None:
242
+ for key in rule:
243
+ if key not in RULE_KEYS:
244
+ rep.add(pointer_join(where, key), "unknown_key", f"{key!r} is not a rule key")
245
+ if "id" not in rule:
246
+ rep.add(pointer_join(where, "id"), "missing_key", "a rule needs an id")
247
+ else:
248
+ _nonempty_string(rep, pointer_join(where, "id"), rule["id"], "id")
249
+ for key in ("version", "description"):
250
+ if key in rule:
251
+ _nonempty_string(rep, pointer_join(where, key), rule[key], key)
252
+
253
+ phase = rule.get("phase", "pre")
254
+ if "phase" in rule and not _enum(rep, pointer_join(where, "phase"), phase, PHASES, "phase"):
255
+ phase = "pre"
256
+ mode = rule.get("mode", "shadow")
257
+ if "mode" in rule and not _enum(rep, pointer_join(where, "mode"), mode, MODES, "mode"):
258
+ mode = None
259
+ if "if_missing" in rule:
260
+ _enum(rep, pointer_join(where, "if_missing"), rule["if_missing"], IF_MISSING, "if_missing")
261
+ if "on_error" in rule:
262
+ _enum(rep, pointer_join(where, "on_error"), rule["on_error"], ACTIONS, "on_error")
263
+ if "fail_mode" in rule:
264
+ if _enum(rep, pointer_join(where, "fail_mode"), rule["fail_mode"], FAIL_MODES, "fail_mode"):
265
+ if rule["fail_mode"] == "closed" and mode != "enforce":
266
+ rep.add(pointer_join(where, "fail_mode"), "fail_closed_requires_enforce",
267
+ "only an enforce rule can fail closed")
268
+ if "hold_timeout_ms" in rule:
269
+ v = rule["hold_timeout_ms"]
270
+ if type(v) is bool or type(v) not in (int, float):
271
+ rep.add(pointer_join(where, "hold_timeout_ms"), "bad_type", "hold_timeout_ms must be an integer")
272
+ elif not (v == v and v not in (float("inf"), float("-inf")) and v == int(v)):
273
+ rep.add(pointer_join(where, "hold_timeout_ms"), "bad_value", "hold_timeout_ms must be an integer")
274
+ elif v < 1:
275
+ rep.add(pointer_join(where, "hold_timeout_ms"), "bad_value", "hold_timeout_ms must be at least 1")
276
+ if "scope" in rule and not is_scope(rule["scope"]):
277
+ code = "bad_type" if type(rule["scope"]) is not str else "bad_value"
278
+ rep.add(pointer_join(where, "scope"), code, "scope must be run, session or correlation:<name>")
279
+ if "agents" in rule and rule["agents"] is not None:
280
+ agents = rule["agents"]
281
+ if type(agents) is not list:
282
+ rep.add(pointer_join(where, "agents"), "bad_type", "agents must be null or a list of agent ids")
283
+ elif not agents:
284
+ rep.add(pointer_join(where, "agents"), "bad_value", "agents must be null or a non-empty list")
285
+ else:
286
+ for i, a in enumerate(agents):
287
+ _nonempty_string(rep, pointer_join(where, "agents", i), a, "an agent id")
288
+ if "portable" in rule and type(rule["portable"]) is not bool:
289
+ rep.add(pointer_join(where, "portable"), "bad_type", "portable must be a boolean")
290
+ if "meta" in rule and type(rule["meta"]) is not dict:
291
+ rep.add(pointer_join(where, "meta"), "bad_type", "meta must be an object")
292
+
293
+ # Target.
294
+ target = rule.get("target")
295
+ if phase == "run_end":
296
+ if "target" in rule and target != {"tools": ["*"]}:
297
+ rep.add(pointer_join(where, "target"), "run_end_target",
298
+ 'a run_end rule has no call to target; omit target or give {"tools": ["*"]}')
299
+ elif "target" not in rule:
300
+ rep.add(pointer_join(where, "target"), "missing_key", "a rule needs a target")
301
+ else:
302
+ _target(rep, pointer_join(where, "target"), target, dctx)
303
+
304
+ # Verdict.
305
+ has_assert, has_bands = "assert" in rule, "bands" in rule
306
+ if has_assert == has_bands:
307
+ rep.add(where, "verdict_required", "a rule has exactly one of assert and bands")
308
+ if "action" in rule:
309
+ if _enum(rep, pointer_join(where, "action"), rule["action"], ACTIONS, "action"):
310
+ if has_assert and rule["action"] == "allow":
311
+ rep.add(pointer_join(where, "action"), "assert_cannot_allow",
312
+ "an assert rule's action is what happens when it fails; allow cannot be it")
313
+ if phase != "pre" and rule["action"] != "flag":
314
+ rep.add(pointer_join(where, "action"), "post_action", f"a {phase} rule can only flag")
315
+ elif has_assert:
316
+ rep.add(pointer_join(where, "action"), "action_required", "assert needs an action")
317
+ if phase != "pre" and "on_error" in rule and rule["on_error"] in ACTIONS and rule["on_error"] not in POST_ACTIONS:
318
+ rep.add(pointer_join(where, "on_error"), "post_action", f"a {phase} rule's on_error is allow or flag")
319
+
320
+ # Expressions.
321
+ let_names: set[str] = set()
322
+ let = rule.get("let")
323
+ if "let" in rule:
324
+ if type(let) is not dict:
325
+ rep.add(pointer_join(where, "let"), "bad_type", "let must be an object of name to expression")
326
+ let = None
327
+ elif not let:
328
+ rep.add(pointer_join(where, "let"), "bad_value", "let must not be empty")
329
+ let = None
330
+ else:
331
+ let_names = set(let)
332
+ rctx = _RuleCtx(rule, let_names)
333
+ if let:
334
+ for name, expr in let.items():
335
+ if not is_identifier(name):
336
+ rep.add(pointer_join(where, "let", name), "bad_value", f"{name!r} is not an identifier")
337
+ _expr(rep, pointer_join(where, "let", name), expr, dctx, rctx, it=False, in_when=False)
338
+ _let_order(rep, pointer_join(where, "let"), let)
339
+ if "when" in rule and rule["when"] is not None:
340
+ _expr(rep, pointer_join(where, "when"), rule["when"], dctx, rctx, it=False, in_when=True)
341
+ if has_assert:
342
+ _expr(rep, pointer_join(where, "assert"), rule["assert"], dctx, rctx, it=False, in_when=False)
343
+ if has_bands:
344
+ _bands(rep, pointer_join(where, "bands"), rule["bands"], dctx, rctx, phase)
345
+
346
+ # Sentence.
347
+ if "sentence" in rule:
348
+ _sentence(rep, pointer_join(where, "sentence"), rule["sentence"], rule, let_names)
349
+
350
+ if rule.get("portable") is False and not rctx.uses_predicate:
351
+ rep.add(pointer_join(where, "portable"), "portable_without_predicate",
352
+ "portable is false but the rule uses no predicate")
353
+
354
+
355
+ def pointer_join(base: str, *segments: Any) -> str:
356
+ return base + pointer(*segments)
357
+
358
+
359
+ def _target(rep: _Report, where: str, target: Any, dctx: _Doc) -> None:
360
+ if type(target) is not dict or set(target) not in ({"tools"}, {"group"}):
361
+ rep.add(where, "bad_target", 'target must be {"tools": [...]} or {"group": name}')
362
+ return
363
+ if "tools" in target:
364
+ tools = target["tools"]
365
+ if type(tools) is not list:
366
+ rep.add(pointer_join(where, "tools"), "bad_type", "target.tools must be a list of tool ids")
367
+ return
368
+ if not tools:
369
+ rep.add(pointer_join(where, "tools"), "bad_value", "target.tools must not be empty")
370
+ return
371
+ for i, t in enumerate(tools):
372
+ _nonempty_string(rep, pointer_join(where, "tools", i), t, "a tool id")
373
+ if "*" in tools and len(tools) > 1:
374
+ rep.add(pointer_join(where, "tools"), "bad_value", 'target.tools is ["*"] or a list of ids, never both')
375
+ else:
376
+ group = target["group"]
377
+ if type(group) is not str:
378
+ rep.add(pointer_join(where, "group"), "bad_type", "target.group must be a group name")
379
+ elif not is_identifier(group):
380
+ rep.add(pointer_join(where, "group"), "bad_value", f"{group!r} is not an identifier")
381
+ elif group not in dctx.groups:
382
+ rep.add(pointer_join(where, "group"), "unknown_group", f"group {group!r} is not declared in groups")
383
+
384
+
385
+ def _bands(rep: _Report, where: str, bands: Any, dctx: _Doc, rctx: _RuleCtx, phase: str) -> None:
386
+ if type(bands) is not dict:
387
+ rep.add(where, "bad_type", 'bands must be {"value": expr, "bands": [...]}')
388
+ return
389
+ for key in bands:
390
+ if key not in ("value", "bands"):
391
+ rep.add(pointer_join(where, key), "unknown_key", "bands has only value and bands")
392
+ for key in ("value", "bands"):
393
+ if key not in bands:
394
+ rep.add(pointer_join(where, key), "missing_key", f"bands needs {key!r}")
395
+ if "value" in bands:
396
+ _expr(rep, pointer_join(where, "value"), bands["value"], dctx, rctx, it=False, in_when=False)
397
+ steps = bands.get("bands")
398
+ if "bands" not in bands:
399
+ return
400
+ if type(steps) is not list:
401
+ rep.add(pointer_join(where, "bands"), "bad_type", "bands.bands must be a list")
402
+ return
403
+ if len(steps) < 2:
404
+ rep.add(pointer_join(where, "bands"), "bands_too_few", "at least two bands are needed")
405
+ last_max: float | None = None
406
+ for i, band in enumerate(steps):
407
+ bw = pointer_join(where, "bands", i)
408
+ if type(band) is not dict:
409
+ rep.add(bw, "not_an_object", "a band is an object")
410
+ continue
411
+ for key in band:
412
+ if key not in ("max", "action"):
413
+ rep.add(pointer_join(bw, key), "unknown_key", "a band has only max and action")
414
+ if "action" not in band:
415
+ rep.add(pointer_join(bw, "action"), "missing_key", "a band needs an action")
416
+ elif _enum(rep, pointer_join(bw, "action"), band["action"], ACTIONS, "action"):
417
+ if phase != "pre" and band["action"] not in POST_ACTIONS:
418
+ rep.add(pointer_join(bw, "action"), "post_action", f"a {phase} rule's bands can only allow or flag")
419
+ last = i == len(steps) - 1
420
+ if "max" in band:
421
+ mx = band["max"]
422
+ if type(mx) is bool or type(mx) not in (int, float):
423
+ rep.add(pointer_join(bw, "max"), "bad_type", "max must be a number")
424
+ else:
425
+ if last_max is not None and not mx > last_max:
426
+ rep.add(pointer_join(bw, "max"), "bands_not_ascending", "max must be above the previous band's")
427
+ else:
428
+ last_max = float(mx)
429
+ if last:
430
+ rep.add(pointer_join(bw, "max"), "bands_catch_all_has_max",
431
+ "the last band is the catch-all and has no max")
432
+ elif not last:
433
+ rep.add(bw, "bands_missing_max", "every band but the last needs a max")
434
+
435
+
436
+ def _sentence(rep: _Report, where: str, sentence: Any, rule: dict, let_names: set[str]) -> None:
437
+ templates: list[str] = []
438
+ if type(sentence) is str:
439
+ templates = [sentence]
440
+ elif type(sentence) is dict:
441
+ for key, value in sentence.items():
442
+ if key not in ("pass", "fail"):
443
+ rep.add(pointer_join(where, key), "unknown_key", "sentence has only pass and fail")
444
+ elif type(value) is not str:
445
+ rep.add(pointer_join(where, key), "bad_type", "a template is a string")
446
+ else:
447
+ templates.append(value)
448
+ else:
449
+ rep.add(where, "bad_type", 'sentence must be a string or {"pass": ..., "fail": ...}')
450
+ return
451
+ known = set(let_names) | static_paths(rule)
452
+ labels = {label_of_path(p) for p in known}
453
+ for t in templates:
454
+ for ph in _PLACEHOLDER.findall(t):
455
+ if ph not in known and ph not in labels:
456
+ rep.add(where, "unknown_placeholder", f"placeholder {{{ph}}} names nothing the rule reads or binds")
457
+
458
+
459
+ # ---------------------------------------------------------------- expressions
460
+
461
+ def _expr(rep: _Report, where: str, node: Any, dctx: _Doc, rctx: _RuleCtx, *, it: bool, in_when: bool) -> None:
462
+ if node is None or type(node) in (bool, int, float, str):
463
+ return
464
+ if type(node) is list:
465
+ rep.add(where, "bare_list", 'a bare list is not an expression; use {"lit": [...]}')
466
+ return
467
+ if type(node) is not dict:
468
+ rep.add(where, "bad_type", "an expression is a literal or an object with one operator key")
469
+ return
470
+ if len(node) != 1:
471
+ rep.add(where, "not_one_operator", "an expression object has exactly one operator key")
472
+ return
473
+ (op, arg), = node.items()
474
+ opw = pointer_join(where, op)
475
+ if op not in ALL_OPS:
476
+ rep.add(opw, "unknown_operator", f"{op!r} is not an operator")
477
+ return
478
+
479
+ def sub(i: int, n: Any, it_ok: bool = it) -> None:
480
+ _expr(rep, pointer_join(opw, i), n, dctx, rctx, it=it_ok, in_when=in_when)
481
+
482
+ if op in LIST_OPS:
483
+ lo, hi = LIST_OPS[op]
484
+ if type(arg) is not list:
485
+ rep.add(opw, "bad_type", f"{op} takes a list of expressions")
486
+ return
487
+ if len(arg) < lo or (hi is not None and len(arg) > hi):
488
+ want = str(lo) if hi == lo else f"{lo} or more" if hi is None else f"{lo} to {hi}"
489
+ rep.add(opw, "bad_arity", f"{op} takes {want} operands")
490
+ return
491
+ for i, n in enumerate(arg):
492
+ sub(i, n)
493
+ elif op in UNARY_OPS:
494
+ _expr(rep, opw, arg, dctx, rctx, it=it, in_when=in_when)
495
+ elif op in STRING_OPS:
496
+ _string_op(rep, opw, op, arg, dctx, rctx, it=it, in_when=in_when)
497
+ elif op == "lit":
498
+ if type(arg) is not list:
499
+ rep.add(opw, "bad_type", "lit takes a JSON list")
500
+ elif op == "is":
501
+ if type(arg) is not list:
502
+ rep.add(opw, "bad_type", "is takes [expression, type]")
503
+ elif len(arg) != 2:
504
+ rep.add(opw, "bad_arity", "is takes [expression, type]")
505
+ else:
506
+ sub(0, arg[0])
507
+ _enum(rep, pointer_join(opw, 1), arg[1], TYPE_NAMES, "a type name")
508
+ elif op == "matches":
509
+ if type(arg) is not list:
510
+ rep.add(opw, "bad_type", "matches takes [expression, pattern]")
511
+ elif len(arg) != 2:
512
+ rep.add(opw, "bad_arity", "matches takes [expression, pattern]")
513
+ else:
514
+ sub(0, arg[0])
515
+ if type(arg[1]) is not str:
516
+ rep.add(pointer_join(opw, 1), "bad_type", "a pattern is a string")
517
+ else:
518
+ code = check_pattern(arg[1])
519
+ if code is not None:
520
+ text = "the pattern is outside the portable subset" if code == "regex_outside_subset" \
521
+ else "the pattern is ill-formed"
522
+ rep.add(pointer_join(opw, 1), code, text)
523
+ elif op in ("all", "any"):
524
+ if type(arg) is not list:
525
+ rep.add(opw, "bad_type", f"{op} takes [items, predicate]")
526
+ elif len(arg) != 2:
527
+ rep.add(opw, "bad_arity", f"{op} takes [items, predicate]")
528
+ else:
529
+ sub(0, arg[0])
530
+ sub(1, arg[1], True)
531
+ elif op == "exists":
532
+ if type(arg) is not dict:
533
+ rep.add(opw, "not_an_object", 'exists takes {"calls": {...}}')
534
+ else:
535
+ for key in arg:
536
+ if key != "calls":
537
+ rep.add(pointer_join(opw, key), "unknown_key", "exists has only calls")
538
+ if "calls" not in arg:
539
+ rep.add(pointer_join(opw, "calls"), "missing_key", 'exists takes {"calls": {...}}')
540
+ else:
541
+ _selection(rep, pointer_join(opw, "calls"), arg["calls"], CALLS_KEYS, dctx, rctx, in_when)
542
+ elif op == "calls":
543
+ _selection(rep, opw, arg, CALLS_KEYS, dctx, rctx, in_when)
544
+ elif op == "prior":
545
+ if _selection(rep, opw, arg, PRIOR_KEYS, dctx, rctx, in_when):
546
+ if "path" not in arg:
547
+ rep.add(pointer_join(opw, "path"), "missing_key", "prior needs a record field path")
548
+ else:
549
+ _record_path(rep, pointer_join(opw, "path"), arg["path"])
550
+ if "pick" in arg:
551
+ _enum(rep, pointer_join(opw, "pick"), arg["pick"], PICKS, "pick")
552
+ elif op == "agg":
553
+ _agg(rep, opw, arg, dctx, rctx, in_when)
554
+ elif op == "predicate":
555
+ if type(arg) is not list:
556
+ rep.add(opw, "bad_type", "predicate takes [name, arguments...]")
557
+ return
558
+ if not arg:
559
+ rep.add(opw, "bad_arity", "predicate takes [name, arguments...]")
560
+ return
561
+ rctx.uses_predicate = True
562
+ name = arg[0]
563
+ if type(name) is not str:
564
+ rep.add(pointer_join(opw, 0), "bad_type", "a predicate name is a string")
565
+ elif not is_identifier(name):
566
+ rep.add(pointer_join(opw, 0), "bad_value", f"{name!r} is not an identifier")
567
+ elif name not in dctx.predicates:
568
+ rep.add(pointer_join(opw, 0), "undeclared_predicate", f"predicate {name!r} is not listed in predicates")
569
+ if rctx.rule.get("portable") is not False:
570
+ rep.add(opw, "predicate_requires_nonportable", 'a rule using a predicate must say "portable": false')
571
+ for i, n in enumerate(arg[1:], start=1):
572
+ sub(i, n)
573
+
574
+
575
+ def _string_op(rep: _Report, opw: str, op: str, arg: Any, dctx: _Doc, rctx: _RuleCtx, *,
576
+ it: bool, in_when: bool) -> None:
577
+ if type(arg) is not str:
578
+ rep.add(opw, "bad_type", f"{op} takes a string")
579
+ return
580
+ if op == "it":
581
+ if not is_dotted_path(arg, allow_empty=True):
582
+ rep.add(opw, "bad_value", "it takes a dotted path or the empty string")
583
+ if not it:
584
+ rep.add(opw, "it_outside_predicate", "it is only valid inside a where, all or any predicate")
585
+ return
586
+ if op == "arg":
587
+ if not is_dotted_path(arg):
588
+ rep.add(opw, "bad_value", "arg takes a dotted path")
589
+ return
590
+ if op == "path":
591
+ if not is_dotted_path(arg):
592
+ rep.add(opw, "bad_value", "path takes a dotted path")
593
+ elif arg.split(".", 1)[0] != "call":
594
+ rep.add(opw, "bad_path_root", "path must start with call")
595
+ return
596
+ if op == "ctx":
597
+ if not is_dotted_path(arg):
598
+ rep.add(opw, "bad_value", "ctx takes a dotted path")
599
+ return
600
+ head, _, rest = arg.partition(".")
601
+ if head not in CONTEXT_FIELDS:
602
+ rep.add(opw, "unknown_context_field", f"{head!r} is not a context field")
603
+ elif rest and head != "env":
604
+ rep.add(opw, "bad_value", f"{head} takes no further segments")
605
+ return
606
+ if op == "set":
607
+ if not is_identifier(arg):
608
+ rep.add(opw, "bad_value", f"{arg!r} is not an identifier")
609
+ elif arg not in dctx.sets:
610
+ rep.add(opw, "unknown_set", f"set {arg!r} is not declared in sets")
611
+ return
612
+ if op == "var":
613
+ if not is_identifier(arg):
614
+ rep.add(opw, "bad_value", f"{arg!r} is not an identifier")
615
+ elif in_when:
616
+ rep.add(opw, "var_in_when", "when runs before let, so no binding exists yet")
617
+ elif arg not in rctx.let_names:
618
+ rep.add(opw, "unbound_var", f"{arg!r} is not a let name of this rule")
619
+ return
620
+ if op == "prev":
621
+ _record_path(rep, opw, arg)
622
+ return
623
+
624
+
625
+ def _record_path(rep: _Report, where: str, path: Any) -> None:
626
+ if type(path) is not str:
627
+ rep.add(where, "bad_type", "a record field path is a string")
628
+ elif not is_dotted_path(path):
629
+ rep.add(where, "bad_value", "a record field path is a dotted path")
630
+ elif path.split(".", 1)[0] not in RECORD_FIELDS:
631
+ rep.add(where, "unknown_record_field", f"{path.split('.', 1)[0]!r} is not a record field")
632
+
633
+
634
+ def _selection(rep: _Report, where: str, sel: Any, allowed: frozenset, dctx: _Doc, rctx: _RuleCtx,
635
+ in_when: bool) -> bool:
636
+ if type(sel) is not dict:
637
+ rep.add(where, "not_an_object", "a selection is an object")
638
+ return False
639
+ for key in sel:
640
+ if key not in allowed:
641
+ rep.add(pointer_join(where, key), "unknown_key", f"{key!r} is not a selection key")
642
+ if "tool" not in sel:
643
+ rep.add(pointer_join(where, "tool"), "missing_key", "a selection needs a tool")
644
+ else:
645
+ tool = sel["tool"]
646
+ if type(tool) is str:
647
+ if tool == "":
648
+ rep.add(pointer_join(where, "tool"), "bad_value", "tool must not be empty")
649
+ elif type(tool) is list:
650
+ if not tool:
651
+ rep.add(pointer_join(where, "tool"), "bad_value", "tool list must not be empty")
652
+ elif "*" in tool:
653
+ rep.add(pointer_join(where, "tool"), "bad_value", 'a tool list never holds "*"')
654
+ else:
655
+ for i, t in enumerate(tool):
656
+ _nonempty_string(rep, pointer_join(where, "tool", i), t, "a tool id")
657
+ else:
658
+ rep.add(pointer_join(where, "tool"), "bad_type", 'tool is a tool id, a list of ids or "*"')
659
+ if "status" in sel:
660
+ status = sel["status"]
661
+ if type(status) is str:
662
+ if status != "any" and status not in STATUSES:
663
+ rep.add(pointer_join(where, "status"), "bad_value", "status is any, a status or a list of statuses")
664
+ elif type(status) is list:
665
+ if not status:
666
+ rep.add(pointer_join(where, "status"), "bad_value", "status list must not be empty")
667
+ for i, s in enumerate(status):
668
+ if s not in STATUSES or type(s) is not str:
669
+ rep.add(pointer_join(where, "status", i), "bad_value", f"{s!r} is not a status")
670
+ else:
671
+ rep.add(pointer_join(where, "status"), "bad_type", "status is any, a status or a list of statuses")
672
+ if "join" in sel:
673
+ join = sel["join"]
674
+ if type(join) is str:
675
+ if not is_identifier(join):
676
+ rep.add(pointer_join(where, "join"), "bad_value", "a correlation name is an identifier")
677
+ elif type(join) is list:
678
+ if not join:
679
+ rep.add(pointer_join(where, "join"), "bad_value", "join list must not be empty")
680
+ for i, j in enumerate(join):
681
+ if not is_identifier(j):
682
+ rep.add(pointer_join(where, "join", i), "bad_value", "a correlation name is an identifier")
683
+ else:
684
+ rep.add(pointer_join(where, "join"), "bad_type", "join is a correlation name or a list of them")
685
+ if "scope" in sel and not is_scope(sel["scope"]):
686
+ code = "bad_type" if type(sel["scope"]) is not str else "bad_value"
687
+ rep.add(pointer_join(where, "scope"), code, "scope must be run, session or correlation:<name>")
688
+ if "kind" in sel:
689
+ _nonempty_string(rep, pointer_join(where, "kind"), sel["kind"], "kind")
690
+ if "where" in sel:
691
+ _expr(rep, pointer_join(where, "where"), sel["where"], dctx, rctx, it=True, in_when=in_when)
692
+ return True
693
+
694
+
695
+ def _agg(rep: _Report, opw: str, agg: Any, dctx: _Doc, rctx: _RuleCtx, in_when: bool) -> None:
696
+ if type(agg) is not dict:
697
+ rep.add(opw, "not_an_object", "agg takes an object")
698
+ return
699
+ for key in agg:
700
+ if key not in AGG_KEYS:
701
+ rep.add(pointer_join(opw, key), "unknown_key", f"{key!r} is not an agg key")
702
+ for key in ("op", "of"):
703
+ if key not in agg:
704
+ rep.add(pointer_join(opw, key), "missing_key", f"agg needs {key!r}")
705
+ op = agg.get("op")
706
+ if "op" in agg:
707
+ _enum(rep, pointer_join(opw, "op"), op, AGG_OPS, "agg.op")
708
+ of = agg.get("of")
709
+ if "of" in agg:
710
+ if type(of) is not dict:
711
+ rep.add(pointer_join(opw, "of"), "not_an_object", 'agg.of takes {"calls": {...}}')
712
+ else:
713
+ for key in of:
714
+ if key != "calls":
715
+ rep.add(pointer_join(opw, "of", key), "unknown_key", "agg.of has only calls")
716
+ if "calls" not in of:
717
+ rep.add(pointer_join(opw, "of", "calls"), "missing_key", 'agg.of takes {"calls": {...}}')
718
+ else:
719
+ _selection(rep, pointer_join(opw, "of", "calls"), of["calls"], CALLS_KEYS, dctx, rctx, in_when)
720
+ if op == "count":
721
+ if "field" in agg:
722
+ rep.add(pointer_join(opw, "field"), "key_not_allowed", "count takes no field")
723
+ elif "field" not in agg:
724
+ rep.add(pointer_join(opw, "field"), "missing_key", "agg needs a field unless op is count")
725
+ else:
726
+ _record_path(rep, pointer_join(opw, "field"), agg["field"])
727
+ if "with" in agg:
728
+ w = agg["with"]
729
+ if type(w) is not list:
730
+ rep.add(pointer_join(opw, "with"), "bad_type", "with is a list of expressions")
731
+ elif not w:
732
+ rep.add(pointer_join(opw, "with"), "bad_value", "with must not be empty")
733
+ else:
734
+ for i, n in enumerate(w):
735
+ _expr(rep, pointer_join(opw, "with", i), n, dctx, rctx, it=False, in_when=in_when)
736
+
737
+
738
+ # ---------------------------------------------------------------- let order and helpers
739
+
740
+ def var_references(node: Any) -> set[str]:
741
+ """Every `{"var": name}` inside an expression."""
742
+ out: set[str] = set()
743
+
744
+ def walk(n: Any) -> None:
745
+ if type(n) is dict:
746
+ for k, v in n.items():
747
+ if k == "var" and type(v) is str:
748
+ out.add(v)
749
+ else:
750
+ walk(v)
751
+ elif type(n) is list:
752
+ for x in n:
753
+ walk(x)
754
+
755
+ walk(node)
756
+ return out
757
+
758
+
759
+ def let_order(let: dict) -> tuple[list[str], list[str], list[str]]:
760
+ """Layered Kahn order of `let` bindings (edoc.md 7.3).
761
+
762
+ Returns (order, self_references, cycle): the names in evaluation order,
763
+ the names that reference themselves, and the names left in a cycle
764
+ (empty when none)."""
765
+ deps = {name: var_references(expr) & set(let) for name, expr in let.items()}
766
+ selfref = sorted(name for name, d in deps.items() if name in d)
767
+ remaining = {name: set(d) - {name} for name, d in deps.items()}
768
+ order: list[str] = []
769
+ while remaining:
770
+ ready = sorted(name for name, d in remaining.items() if not d)
771
+ if not ready:
772
+ return order, selfref, sorted(remaining)
773
+ for name in ready:
774
+ order.append(name)
775
+ del remaining[name]
776
+ for d in remaining.values():
777
+ d.difference_update(ready)
778
+ return order, selfref, []
779
+
780
+
781
+ def _let_order(rep: _Report, where: str, let: dict) -> None:
782
+ _, selfref, cycle = let_order(let)
783
+ for name in selfref:
784
+ rep.add(pointer_join(where, name), "let_self_reference", f"binding {name!r} refers to itself")
785
+ if cycle:
786
+ rep.add(where, "let_cycle", "bindings form a cycle: " + " -> ".join(cycle))
787
+
788
+
789
+ def tool_label(tool: Any) -> str:
790
+ if type(tool) is list:
791
+ return "|".join(tool)
792
+ return "any_tool" if tool == "*" else str(tool)
793
+
794
+
795
+ def read_path_of(node: Any) -> str | None:
796
+ """The evidence path a bare read records under, or None (edoc.md 6.1, 7.3)."""
797
+ if type(node) is not dict or len(node) != 1:
798
+ return None
799
+ (op, arg), = node.items()
800
+ if op == "arg":
801
+ return f"call.args.{arg}"
802
+ if op == "path":
803
+ return arg
804
+ if op == "ctx":
805
+ return f"context.{arg}"
806
+ if op == "prev":
807
+ return f"history.prev.{arg}"
808
+ if op == "prior" and type(arg) is dict:
809
+ return f"history.{tool_label(arg.get('tool'))}.{arg.get('pick', 'latest')}.{arg.get('path')}"
810
+ if op == "exists" and type(arg) is dict and type(arg.get("calls")) is dict:
811
+ return f"history.{tool_label(arg['calls'].get('tool'))}.exists"
812
+ if op == "agg" and type(arg) is dict:
813
+ of = arg.get("of", {}).get("calls", {}) if type(arg.get("of")) is dict else {}
814
+ name = f"history.{tool_label(of.get('tool') if type(of) is dict else None)}.{arg.get('op')}"
815
+ return name + (f".{arg['field']}" if arg.get("field") else "")
816
+ return None
817
+
818
+
819
+ def static_paths(rule: dict) -> set[str]:
820
+ """Evidence paths a rule can record, derived from its text (for placeholders)."""
821
+ out: set[str] = set()
822
+
823
+ def walk(node: Any) -> None:
824
+ if type(node) is not dict or len(node) != 1:
825
+ return
826
+ path = read_path_of(node)
827
+ if path is not None:
828
+ out.add(path)
829
+ (op, arg), = node.items()
830
+ if op == "len" and type(arg) is dict and type(arg.get("calls")) is dict:
831
+ out.add(f"history.{tool_label(arg['calls'].get('tool'))}.count")
832
+ if type(arg) is list:
833
+ for n in arg:
834
+ walk(n)
835
+ elif type(arg) is dict:
836
+ if op in ("calls", "prior"):
837
+ walk(arg.get("where"))
838
+ elif op == "exists":
839
+ if type(arg.get("calls")) is dict:
840
+ walk(arg["calls"].get("where"))
841
+ elif op == "agg":
842
+ for n in arg.get("with") or []:
843
+ walk(n)
844
+ of = arg.get("of")
845
+ if type(of) is dict and type(of.get("calls")) is dict:
846
+ walk(of["calls"].get("where"))
847
+ else:
848
+ walk(arg)
849
+
850
+ let = rule.get("let") if type(rule.get("let")) is dict else {}
851
+ for expr in list(let.values()) + [rule.get("when"), rule.get("assert")]:
852
+ walk(expr)
853
+ if type(rule.get("bands")) is dict:
854
+ walk(rule["bands"].get("value"))
855
+ return out
856
+
857
+
858
+ def label_of_path(path: str) -> str:
859
+ """The sentence label of an evidence path (edoc.md 10.1)."""
860
+ for prefix in ("call.args.", "history.", "context.", "call."):
861
+ if path.startswith(prefix):
862
+ return path[len(prefix):]
863
+ return path