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,273 @@
1
+ """Value model of the rule evaluator (spec/edoc.md, section 5).
2
+
3
+ Values are plain JSON (null, boolean, number, string, list, object) plus
4
+ three evaluator-only kinds: Missing (a history read matched nothing),
5
+ Absent (a key that is not on an object that does exist) and Selection
6
+ (the records a `calls` node selected). Numbers are IEEE doubles; booleans
7
+ are never numbers.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from typing import Any
13
+
14
+ from .numbers import fmt_number, json_text
15
+
16
+
17
+ class EvalError(Exception):
18
+ """A rule could not be evaluated (edoc.md 7.6). Follows the rule's `on_error`."""
19
+
20
+
21
+ class _Missing:
22
+ __slots__ = ()
23
+
24
+ def __repr__(self) -> str:
25
+ return "Missing"
26
+
27
+ def __bool__(self) -> bool:
28
+ raise TypeError("Missing has no truth value; test identity with MISSING")
29
+
30
+
31
+ class _Absent:
32
+ __slots__ = ()
33
+
34
+ def __repr__(self) -> str:
35
+ return "Absent"
36
+
37
+ def __bool__(self) -> bool:
38
+ raise TypeError("Absent has no truth value; test identity with ABSENT")
39
+
40
+
41
+ MISSING = _Missing()
42
+ ABSENT = _Absent()
43
+
44
+
45
+ class Selection:
46
+ """Records a `calls` node selected, in history order, with the tool label (edoc.md 6.1)."""
47
+
48
+ __slots__ = ("records", "label")
49
+
50
+ def __init__(self, records: list, label: str) -> None:
51
+ self.records = records
52
+ self.label = label
53
+
54
+
55
+ def is_number(v: Any) -> bool:
56
+ return (type(v) is float) or (type(v) is int)
57
+
58
+
59
+ def type_name(v: Any) -> str:
60
+ """The `<type name>` of edoc.md section 11."""
61
+ if v is None:
62
+ return "null"
63
+ t = type(v)
64
+ if t is bool:
65
+ return "boolean"
66
+ if t is float or t is int:
67
+ return "number"
68
+ if t is str:
69
+ return "string"
70
+ if t is list:
71
+ return "list"
72
+ if t is dict:
73
+ return "object"
74
+ if v is MISSING:
75
+ return "missing"
76
+ if v is ABSENT:
77
+ return "absent"
78
+ if t is Selection:
79
+ return "records"
80
+ return "object"
81
+
82
+
83
+ def describe(v: Any) -> str:
84
+ """The `<description>` of edoc.md section 11: type name and rendering."""
85
+ if v is ABSENT:
86
+ return "absent (no such key)"
87
+ if v is None:
88
+ return "null"
89
+ t = type(v)
90
+ if t is bool:
91
+ return "boolean true" if v else "boolean false"
92
+ if t is float or t is int:
93
+ return f"number {fmt_number(v)}"
94
+ if t is str:
95
+ return "string " + json_text(v)
96
+ if t is Selection:
97
+ return f"{len(v.records)} records"
98
+ return type_name(v)
99
+
100
+
101
+ def equal(a: Any, b: Any) -> bool:
102
+ """Structural equality (edoc.md 8.4). Absent equals nothing."""
103
+ ta, tb = type(a), type(b)
104
+ if ta is str:
105
+ return tb is str and a == b
106
+ if ta is float or ta is int:
107
+ return (tb is float or tb is int) and a == b
108
+ if ta is bool:
109
+ return tb is bool and a == b
110
+ if a is None:
111
+ return b is None
112
+ if ta is list:
113
+ return tb is list and len(a) == len(b) and all(equal(x, y) for x, y in zip(a, b))
114
+ if ta is dict:
115
+ return tb is dict and a.keys() == b.keys() and all(equal(a[k], b[k]) for k in a)
116
+ return False
117
+
118
+
119
+ def _canonical_key(v: Any) -> Any:
120
+ """A hashable identity for `count_distinct` (edoc.md 8.5). Containers
121
+ holding a NaN equal nothing (8.4), so they get a unique key."""
122
+ t = type(v)
123
+ if v is None:
124
+ return ("null",)
125
+ if t is bool:
126
+ return ("bool", v)
127
+ if t is float or t is int:
128
+ if v != v:
129
+ return ("nan",)
130
+ return ("num", float(v) + 0.0)
131
+ if t is str:
132
+ return ("str", v)
133
+ if t is list:
134
+ if _has_nan(v):
135
+ return ("nan-container", id(v))
136
+ return ("list", tuple(_canonical_key(x) for x in v))
137
+ if t is dict:
138
+ if _has_nan(v):
139
+ return ("nan-container", id(v))
140
+ return ("obj", tuple(sorted((k, _canonical_key(x)) for k, x in v.items())))
141
+ return ("other", id(v))
142
+
143
+
144
+ def _has_nan(v: Any) -> bool:
145
+ t = type(v)
146
+ if t is float:
147
+ return v != v
148
+ if t is list:
149
+ return any(_has_nan(x) for x in v)
150
+ if t is dict:
151
+ return any(_has_nan(x) for x in v.values())
152
+ return False
153
+
154
+
155
+ def count_distinct(values: list) -> int:
156
+ return len({_canonical_key(v) for v in values})
157
+
158
+
159
+ def is_index(seg: str) -> bool:
160
+ """A list index segment: `-?[0-9]+` (edoc.md 6.4)."""
161
+ if seg.startswith("-"):
162
+ seg = seg[1:]
163
+ return seg.isdigit() and seg.isascii() and seg != ""
164
+
165
+
166
+ _SEGMENTS: dict[str, list[str]] = {}
167
+
168
+
169
+ def segments(path: str) -> list[str]:
170
+ segs = _SEGMENTS.get(path)
171
+ if segs is None:
172
+ segs = _SEGMENTS[path] = path.split(".")
173
+ return segs
174
+
175
+
176
+ def walk(value: Any, segs: list[str]) -> Any:
177
+ """Read into a JSON value one segment at a time (edoc.md 6.4)."""
178
+ cur = value
179
+ for seg in segs:
180
+ t = type(cur)
181
+ if t is dict:
182
+ if seg in cur:
183
+ cur = cur[seg]
184
+ else:
185
+ return ABSENT
186
+ elif t is list:
187
+ if is_index(seg):
188
+ i = int(seg)
189
+ if -len(cur) <= i < len(cur):
190
+ cur = cur[i]
191
+ else:
192
+ return ABSENT
193
+ else:
194
+ return ABSENT
195
+ else:
196
+ return ABSENT
197
+ return cur
198
+
199
+
200
+ RULE_FIELDS = frozenset({
201
+ "call_id", "run_id", "root_run_id", "session_id", "agent_id", "tool_id", "tool_name_raw", "args",
202
+ "result", "status", "error", "seq", "batch_id", "parent_call_id", "correlation", "attempt", "kind",
203
+ })
204
+
205
+
206
+ def record_field(rec: Any, name: str) -> Any:
207
+ """One of the 17 record fields (edoc.md 5.1) of a record object or mapping;
208
+ Absent for anything else. A record without a `kind` is `tool_call`."""
209
+ if type(rec) is dict:
210
+ if name in rec:
211
+ v = rec[name]
212
+ return "tool_call" if name == "kind" and v is None else v
213
+ return "tool_call" if name == "kind" else ABSENT
214
+ if name in RULE_FIELDS:
215
+ v = getattr(rec, name)
216
+ return "tool_call" if name == "kind" and v is None else v
217
+ return ABSENT
218
+
219
+
220
+ def record_path(rec: Any, path: str) -> Any:
221
+ """Read a record field path (`args.amount`, `result.0.id`, `status`)."""
222
+ segs = segments(path)
223
+ head = record_field(rec, segs[0])
224
+ if head is ABSENT or len(segs) == 1:
225
+ return head
226
+ return walk(head, segs[1:])
227
+
228
+
229
+ def record_view(rec: Any) -> dict:
230
+ """The record as the JSON object rules see: the 17 fields, nothing else."""
231
+ if type(rec) is dict:
232
+ out = {k: rec.get(k) for k in RULE_FIELDS if k in rec}
233
+ out.setdefault("kind", "tool_call")
234
+ if out.get("kind") is None:
235
+ out["kind"] = "tool_call"
236
+ return out
237
+ out = {k: getattr(rec, k) for k in RULE_FIELDS}
238
+ if out["kind"] is None:
239
+ out["kind"] = "tool_call"
240
+ return out
241
+
242
+
243
+ def to_double(v: Any) -> Any:
244
+ """Document literals and fixture values with every number a double."""
245
+ t = type(v)
246
+ if t is int:
247
+ return float(v)
248
+ if t is list:
249
+ return [to_double(x) for x in v]
250
+ if t is dict:
251
+ return {k: to_double(x) for k, x in v.items()}
252
+ return v
253
+
254
+
255
+ __all__ = [
256
+ "ABSENT",
257
+ "MISSING",
258
+ "EvalError",
259
+ "Selection",
260
+ "count_distinct",
261
+ "describe",
262
+ "equal",
263
+ "is_index",
264
+ "is_number",
265
+ "record_field",
266
+ "record_path",
267
+ "record_view",
268
+ "RULE_FIELDS",
269
+ "segments",
270
+ "to_double",
271
+ "type_name",
272
+ "walk",
273
+ ]
@@ -0,0 +1 @@
1
+ """The kernel (spec/kernel.md). Private; import from `amiril.core`."""
@@ -0,0 +1,245 @@
1
+ """Turning a control-plane bundle into the document the engine loads
2
+ (spec/kernel.md 8.4, spec/protocol.md 5.3 and 5.4).
3
+
4
+ `prepare_bundle` validates the body against what `bundle.response.schema.json`
5
+ requires, then the invariants (ids equal across `rules[]` and
6
+ `document.rules`, `ruleset_version` equals `version`), then applies the
7
+ environment filter and the `rules[]` overrides, sets aside the rules this
8
+ core cannot read, and intersects the rest. The engine's loader is the last
9
+ layer and runs on the document it returns. A bundle that fails here raises
10
+ `BundleError` and the current document stays.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import copy
16
+ import re
17
+ from dataclasses import dataclass, field
18
+ from typing import Any
19
+
20
+ from .._engine.rules import StandIn, agent_name
21
+ from .._engine.validate import validate_document
22
+
23
+ PROTOCOL = "amiril.protocol/1"
24
+ _ETAG = re.compile(r'(W/)?"[^"]+"\Z')
25
+ _TIMESTAMP = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z\Z")
26
+ _MODES = ("off", "shadow", "enforce")
27
+ _FAIL_MODES = ("open", "closed")
28
+ _ENTRY_KEYS = ("id", "version", "mode", "fail_mode", "hold_timeout_ms", "applies_to")
29
+ _APPLIES_KEYS = ("agents", "tools", "environments")
30
+ _IN_RULE = re.compile(r"/rules/(\d+)(?:/|\Z)")
31
+
32
+
33
+ class BundleError(ValueError):
34
+ """The bundle is not usable; the current document stays live."""
35
+
36
+
37
+ @dataclass
38
+ class PreparedBundle:
39
+ document: dict
40
+ bundle_version: str | None
41
+ skipped_environment: int = 0
42
+ warnings: list[dict] = field(default_factory=list)
43
+ stand_ins: list[StandIn] = field(default_factory=list)
44
+
45
+
46
+ def is_bundle(obj: Any) -> bool:
47
+ """A bundle response body is told from a bare document by `protocol` at the top (protocol.md 3)."""
48
+ return isinstance(obj, dict) and "protocol" in obj
49
+
50
+
51
+ def _short_string(v: Any) -> bool:
52
+ return isinstance(v, str) and 1 <= len(v) <= 256
53
+
54
+
55
+ def _string_list(v: Any) -> bool:
56
+ return isinstance(v, list) and len(v) >= 1 and all(_short_string(x) for x in v)
57
+
58
+
59
+ def _check_shape(body: dict) -> tuple[dict, list[dict], dict]:
60
+ if body.get("protocol") != PROTOCOL:
61
+ raise BundleError(f"protocol must be {PROTOCOL!r}")
62
+ bundle = body.get("bundle")
63
+ if not isinstance(bundle, dict):
64
+ raise BundleError("bundle must be an object")
65
+ for key in ("version", "etag", "published_at", "rules", "document"):
66
+ if key not in bundle:
67
+ raise BundleError(f"bundle needs {key!r}")
68
+ if not _short_string(bundle["version"]):
69
+ raise BundleError("bundle.version must be a non-empty string")
70
+ if not isinstance(bundle["etag"], str) or not _ETAG.match(bundle["etag"]):
71
+ raise BundleError("bundle.etag must be a quoted entity tag")
72
+ if not isinstance(bundle["published_at"], str) or not _TIMESTAMP.match(bundle["published_at"]):
73
+ raise BundleError("bundle.published_at must be an RFC 3339 UTC timestamp with milliseconds")
74
+ sync = body.get("sync")
75
+ if not isinstance(sync, dict) or not isinstance(sync.get("poll_interval_ms"), int) \
76
+ or isinstance(sync.get("poll_interval_ms"), bool) or sync["poll_interval_ms"] < 1 \
77
+ or not isinstance(sync.get("jitter_ms"), int) or isinstance(sync.get("jitter_ms"), bool) \
78
+ or sync["jitter_ms"] < 0:
79
+ raise BundleError("sync needs poll_interval_ms (at least 1) and jitter_ms (at least 0)")
80
+ entries = bundle["rules"]
81
+ document = bundle["document"]
82
+ if not isinstance(entries, list):
83
+ raise BundleError("bundle.rules must be a list")
84
+ if not isinstance(document, dict):
85
+ raise BundleError("bundle.document must be an object")
86
+ for key in ("schema", "ruleset_version", "rules"):
87
+ if key not in document:
88
+ raise BundleError(f"bundle.document needs {key!r}")
89
+ if document["schema"] != "amiril.rules/1":
90
+ raise BundleError("bundle.document.schema must be amiril.rules/1")
91
+ if not isinstance(document["rules"], list) or not all(isinstance(r, dict) for r in document["rules"]):
92
+ raise BundleError("bundle.document.rules must be a list of objects")
93
+ for i, e in enumerate(entries):
94
+ _check_entry(i, e)
95
+ return bundle, entries, document
96
+
97
+
98
+ def _check_entry(i: int, e: Any) -> None:
99
+ where = f"bundle.rules[{i}]"
100
+ if not isinstance(e, dict):
101
+ raise BundleError(f"{where} must be an object")
102
+ for key in _ENTRY_KEYS:
103
+ if key not in e:
104
+ raise BundleError(f"{where} needs {key!r}")
105
+ if not _short_string(e["id"]) or not _short_string(e["version"]):
106
+ raise BundleError(f"{where}: id and version must be non-empty strings")
107
+ if e["mode"] not in _MODES:
108
+ raise BundleError(f"{where}.mode must be one of {', '.join(_MODES)}")
109
+ if e["fail_mode"] not in _FAIL_MODES:
110
+ raise BundleError(f"{where}.fail_mode must be open or closed")
111
+ if e["fail_mode"] == "closed" and e["mode"] != "enforce":
112
+ raise BundleError(f"{where}: only an enforce rule may be fail-closed")
113
+ t = e["hold_timeout_ms"]
114
+ if t is not None and (isinstance(t, bool) or not isinstance(t, int) or t < 1):
115
+ raise BundleError(f"{where}.hold_timeout_ms must be null or an integer of at least 1")
116
+ applies = e["applies_to"]
117
+ if not isinstance(applies, dict):
118
+ raise BundleError(f"{where}.applies_to must be an object")
119
+ for key in _APPLIES_KEYS:
120
+ if key not in applies:
121
+ raise BundleError(f"{where}.applies_to needs {key!r}")
122
+ if applies["agents"] is not None and not _string_list(applies["agents"]):
123
+ raise BundleError(f"{where}.applies_to.agents must be null or a non-empty list of names")
124
+ if not _string_list(applies["tools"]):
125
+ raise BundleError(f"{where}.applies_to.tools must be a non-empty list of tool ids")
126
+ envs = applies["environments"]
127
+ if envs is not None and not (isinstance(envs, list) and all(_short_string(x) for x in envs)):
128
+ raise BundleError(f"{where}.applies_to.environments must be null or a list of names")
129
+
130
+
131
+ def prepare_bundle(body: dict, environment: str | None = None,
132
+ predicates: set[str] | None = None) -> PreparedBundle:
133
+ """Validate a bundle body and return the document to load (protocol.md 5.4).
134
+ `predicates` are the names the host registered; None leaves that layer to
135
+ the loader."""
136
+ bundle, entries, document = _check_shape(body)
137
+ version = bundle["version"]
138
+ if document["ruleset_version"] != version:
139
+ raise BundleError("document.ruleset_version must equal bundle.version")
140
+ by_id: dict[str, dict] = {}
141
+ for e in entries:
142
+ if e["id"] in by_id:
143
+ raise BundleError(f"rules[] lists {e['id']!r} twice")
144
+ by_id[e["id"]] = e
145
+ doc_ids = [r.get("id") for r in document["rules"]]
146
+ if set(doc_ids) != set(by_id) or len(doc_ids) != len(set(doc_ids)):
147
+ raise BundleError("rules[] and document.rules must hold the same ids")
148
+
149
+ out = copy.deepcopy(document)
150
+ groups = out.get("groups") or {}
151
+ prepared = PreparedBundle(out, version)
152
+ kept: list[dict] = []
153
+ for rule in out["rules"]:
154
+ entry = by_id[rule["id"]]
155
+ applies = entry["applies_to"]
156
+ envs = applies["environments"]
157
+ if isinstance(envs, list) and environment not in envs:
158
+ prepared.skipped_environment += 1
159
+ continue
160
+ rule["mode"] = entry["mode"]
161
+ rule["fail_mode"] = entry["fail_mode"]
162
+ if entry["hold_timeout_ms"] is not None:
163
+ rule["hold_timeout_ms"] = entry["hold_timeout_ms"]
164
+ kept.append(rule)
165
+ out["rules"] = kept
166
+
167
+ unreadable = _unreadable(out, predicates)
168
+ readable: list[dict] = []
169
+ for index, rule in enumerate(kept):
170
+ entry = by_id[rule["id"]]
171
+ applies = entry["applies_to"]
172
+ problem = unreadable.get(index)
173
+ if problem is None:
174
+ _intersect(rule, applies, groups, prepared.warnings)
175
+ readable.append(rule)
176
+ continue
177
+ prepared.warnings.append(_warn(rule["id"], "unreadable_rule",
178
+ f"{problem['code']} at {problem['path']}: {problem['message']}"))
179
+ # kernel.md 8.4: a fail-closed rule leaves a stand-in unless its phase is one that cannot block.
180
+ if entry["fail_mode"] == "closed" and rule.get("phase") not in ("post", "run_end"):
181
+ agents = applies["agents"]
182
+ prepared.stand_ins.append(StandIn(entry["id"], entry["version"],
183
+ None if agents is None else tuple(agents), tuple(applies["tools"])))
184
+ out["rules"] = readable
185
+ return prepared
186
+
187
+
188
+ def _unreadable(document: dict, predicates: set[str] | None) -> dict[int, dict]:
189
+ """The first problem the loader reports inside each rule it cannot read, by the rule's index."""
190
+ found: dict[int, dict] = {}
191
+ for problem in validate_document(document, predicates):
192
+ inside = _IN_RULE.match(problem["path"])
193
+ if inside:
194
+ found.setdefault(int(inside.group(1)), problem)
195
+ return found
196
+
197
+
198
+ def _intersect(rule: dict, applies: dict, groups: dict, warnings: list[dict]) -> None:
199
+ """Narrow the rule to what both its own targeting and `applies_to` name
200
+ (edoc.md 4). Any difference between the two is one warning for the rule,
201
+ and an empty intersection loads it off and fail-open (kernel.md 8.4)."""
202
+ mismatch: list[str] = []
203
+ empty = False
204
+ entry_agents, own_agents = applies["agents"], rule.get("agents")
205
+ if entry_agents is None or own_agents is None:
206
+ if entry_agents is not None or own_agents is not None:
207
+ mismatch.append("agents differ between the bundle entry and the document")
208
+ if entry_agents is not None:
209
+ rule["agents"] = list(entry_agents)
210
+ else:
211
+ entry_names = {agent_name(a) for a in entry_agents} # edoc.md 7.1: compared NFC-normalised and trimmed
212
+ if {agent_name(a) for a in own_agents} != entry_names:
213
+ mismatch.append("agents differ between the bundle entry and the document")
214
+ both = [a for a in own_agents if agent_name(a) in entry_names]
215
+ if both:
216
+ rule["agents"] = both
217
+ else:
218
+ empty = True
219
+ if rule.get("phase", "pre") != "run_end":
220
+ entry_tools = applies["tools"]
221
+ target = rule.get("target") or {"tools": ["*"]}
222
+ own_tools = groups.get(target["group"], []) if "group" in target else target.get("tools", [])
223
+ if "*" in entry_tools or "*" in own_tools:
224
+ if "*" not in entry_tools or "*" not in own_tools:
225
+ mismatch.append("tools differ between the bundle entry and the document")
226
+ if "*" not in entry_tools:
227
+ rule["target"] = {"tools": list(entry_tools)}
228
+ else:
229
+ if set(own_tools) != set(entry_tools):
230
+ mismatch.append("tools differ between the bundle entry and the document")
231
+ both = [t for t in own_tools if t in entry_tools]
232
+ if both:
233
+ rule["target"] = {"tools": both}
234
+ else:
235
+ empty = True
236
+ if empty:
237
+ rule["mode"] = "off"
238
+ rule["fail_mode"] = "open"
239
+ mismatch.append("the intersection is empty, so the rule is loaded off")
240
+ if mismatch:
241
+ warnings.append(_warn(rule["id"], "applies_to_target_mismatch", "; ".join(mismatch)))
242
+
243
+
244
+ def _warn(rule_id: str, code: str, text: str) -> dict:
245
+ return {"rule_id": rule_id, "code": code, "text": text}
@@ -0,0 +1,103 @@
1
+ """Argument coercion against a tool's JSON Schema (spec/kernel.md 12.1).
2
+
3
+ No framework coerces arguments before its hook, so every adapter calls
4
+ `coerce_args` before the kernel.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from collections.abc import Iterable
11
+ from typing import Any
12
+
13
+ from .normalise import to_json
14
+
15
+ _JSON_NUMBER = re.compile(r"-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?\Z")
16
+ _ASCII_WS = " \t\n\r\f\v"
17
+
18
+
19
+ def coerce_args(args: Any, json_schema: dict | None, injected: Iterable[str] = ()) -> tuple[dict, dict]:
20
+ """Returns (args, meta). `meta` keys: `coerced` (bool), `coerced_keys`,
21
+ `dropped_keys`, `injected_keys`, `uncoercible_keys`; `normalise_fallback`
22
+ when a value had no JSON form."""
23
+ meta: dict[str, Any] = {
24
+ "coerced": False,
25
+ "coerced_keys": [],
26
+ "dropped_keys": [],
27
+ "injected_keys": [],
28
+ "uncoercible_keys": [],
29
+ }
30
+ injected_set = set(injected)
31
+ plain = to_json(dict(args or {}), meta)
32
+ schema = json_schema or {}
33
+ defs = schema.get("$defs") or schema.get("definitions") or {}
34
+ props = schema.get("properties") if isinstance(schema.get("properties"), dict) else None
35
+ out: dict[str, Any] = {}
36
+ for key, value in plain.items():
37
+ if key in injected_set:
38
+ meta["injected_keys"].append(key)
39
+ continue
40
+ if props is None:
41
+ out[key] = value
42
+ continue
43
+ if key not in props:
44
+ meta["dropped_keys"].append(key)
45
+ continue
46
+ out[key] = _coerce(value, props[key], defs, key, meta)
47
+ meta["coerced"] = bool(meta["coerced_keys"])
48
+ return out, meta
49
+
50
+
51
+ def _resolve(schema: Any, defs: dict) -> dict:
52
+ if not isinstance(schema, dict):
53
+ return {}
54
+ ref = schema.get("$ref")
55
+ if isinstance(ref, str) and ref.startswith("#/"):
56
+ target = defs.get(ref.rsplit("/", 1)[-1])
57
+ if isinstance(target, dict):
58
+ return _resolve(target, defs)
59
+ return schema
60
+
61
+
62
+ def _alternatives(schema: Any, defs: dict) -> list[dict]:
63
+ schema = _resolve(schema, defs)
64
+ alts = schema.get("anyOf") or schema.get("oneOf")
65
+ if isinstance(alts, list) and alts:
66
+ out: list[dict] = []
67
+ for alt in alts:
68
+ out.extend(_alternatives(alt, defs))
69
+ return out
70
+ t = schema.get("type")
71
+ if isinstance(t, list):
72
+ return [{**schema, "type": one} for one in t]
73
+ return [schema]
74
+
75
+
76
+ def _coerce(value: Any, schema: Any, defs: dict, path: str, meta: dict) -> Any:
77
+ alts = _alternatives(schema, defs)
78
+ kinds = {a.get("type") for a in alts}
79
+ if isinstance(value, str):
80
+ if "string" in kinds or not kinds & {"number", "integer", "boolean"}:
81
+ return value
82
+ trimmed = value.strip(_ASCII_WS)
83
+ if kinds & {"number", "integer"} and _JSON_NUMBER.match(trimmed):
84
+ meta["coerced_keys"].append(path)
85
+ return float(trimmed)
86
+ if "boolean" in kinds and trimmed.lower() in ("true", "false"):
87
+ meta["coerced_keys"].append(path)
88
+ return trimmed.lower() == "true"
89
+ meta["uncoercible_keys"].append(path)
90
+ return value
91
+ if isinstance(value, list):
92
+ for alt in alts:
93
+ if alt.get("type") == "array" and isinstance(alt.get("items"), dict):
94
+ return [_coerce(v, alt["items"], defs, f"{path}[{i}]", meta) for i, v in enumerate(value)]
95
+ return value
96
+ if isinstance(value, dict):
97
+ for alt in alts:
98
+ props = alt.get("properties")
99
+ if isinstance(props, dict):
100
+ return {k: (_coerce(v, props[k], defs, f"{path}.{k}", meta) if k in props else v)
101
+ for k, v in value.items()}
102
+ return value
103
+ return value