vitna-mandate 0.2.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.
@@ -0,0 +1,208 @@
1
+ """vitna-mandate: Fail-closed Agent Mandate Protocol v1 (am/1) runtime for Python."""
2
+
3
+ from . import interop
4
+ from .breakers import BreakerConfig, BreakerInput, BreakerVerdict, DEFAULT_BREAKERS, evaluate_breakers
5
+ from .canonical import canonical_json, sha256_hex
6
+ from .caveats import (
7
+ BOTTOM,
8
+ EFFECT_ORDER,
9
+ REGISTERED_CAVEATS,
10
+ SETTLE_ORDER,
11
+ caveats_equal,
12
+ fold_meet,
13
+ meet_caveats,
14
+ narrows,
15
+ validate_caveats,
16
+ )
17
+ from .didkey import (
18
+ b64url_decode,
19
+ b64url_encode,
20
+ base58_decode,
21
+ base58_encode,
22
+ did_key_from_ed25519,
23
+ ed25519_from_did_key,
24
+ jwk_from_did_key,
25
+ jwk_thumbprint,
26
+ thumbprint_of_did_key,
27
+ )
28
+ from .duration import is_duration, parse_duration
29
+ from .errors import HTTP_STATUS, OK, PROBLEM_TYPE_BASE, Check, ErrorCode, fail
30
+ from .jws import (
31
+ MANDATE_TYP,
32
+ AgentKey,
33
+ ParsedJws,
34
+ agent_key_from_seed,
35
+ encode_segment,
36
+ generate_agent_key,
37
+ parse_compact_jws,
38
+ sign_detached,
39
+ sign_mandate,
40
+ verify_detached,
41
+ verify_jws_signature,
42
+ )
43
+ from .ledger import Ledger, ReserveResult
44
+ from .money import (
45
+ MONEY_SCALE,
46
+ SCALE_FACTOR,
47
+ Money,
48
+ from_atomic_units,
49
+ from_scaled,
50
+ is_money,
51
+ money_eq,
52
+ money_leq,
53
+ money_min,
54
+ parse_decimal_amount,
55
+ to_atomic_units,
56
+ to_decimal,
57
+ to_scaled,
58
+ )
59
+ from .quote import (
60
+ is_quote_hash,
61
+ quote_hash_for_http_challenge,
62
+ quote_hash_for_x402_challenge,
63
+ quote_hash_from_x402_response,
64
+ quotes_match,
65
+ raw_x402_challenge_bytes,
66
+ )
67
+ from .store import (
68
+ HISTORY_RETENTION_SECONDS,
69
+ IdempotencyRecord,
70
+ MandateNode,
71
+ Reservation,
72
+ SpendEvent,
73
+ SqliteStore,
74
+ SqliteTx,
75
+ )
76
+ from .uri import (
77
+ HostPattern,
78
+ UriPattern,
79
+ canonicalize_uri,
80
+ host_matches,
81
+ host_of_uri,
82
+ host_pattern_contains,
83
+ host_set_contains,
84
+ parse_host_pattern,
85
+ parse_uri_pattern,
86
+ uri_matches,
87
+ uri_pattern_contains,
88
+ uri_set_contains,
89
+ )
90
+ from .verify import (
91
+ ANY_LEDGER,
92
+ DEFAULT_SKEW_SECONDS,
93
+ MAX_DEPTH,
94
+ MAX_OFFLINE_WINDOW_SECONDS,
95
+ NO_REQUEST,
96
+ PROTOCOL_VERSION,
97
+ VerifyResult,
98
+ Window,
99
+ chain_hash,
100
+ check_offline_profile,
101
+ check_request,
102
+ did_key_resolver,
103
+ verify_chain,
104
+ )
105
+
106
+ __version__ = "0.2.0"
107
+
108
+ __all__ = [
109
+ "__version__",
110
+ "ANY_LEDGER",
111
+ "AgentKey",
112
+ "BOTTOM",
113
+ "BreakerConfig",
114
+ "BreakerInput",
115
+ "BreakerVerdict",
116
+ "Check",
117
+ "DEFAULT_BREAKERS",
118
+ "DEFAULT_SKEW_SECONDS",
119
+ "EFFECT_ORDER",
120
+ "ErrorCode",
121
+ "HISTORY_RETENTION_SECONDS",
122
+ "HTTP_STATUS",
123
+ "HostPattern",
124
+ "IdempotencyRecord",
125
+ "Ledger",
126
+ "MANDATE_TYP",
127
+ "MAX_DEPTH",
128
+ "MAX_OFFLINE_WINDOW_SECONDS",
129
+ "MONEY_SCALE",
130
+ "MandateNode",
131
+ "Money",
132
+ "NO_REQUEST",
133
+ "OK",
134
+ "PROBLEM_TYPE_BASE",
135
+ "PROTOCOL_VERSION",
136
+ "ParsedJws",
137
+ "REGISTERED_CAVEATS",
138
+ "Reservation",
139
+ "ReserveResult",
140
+ "SCALE_FACTOR",
141
+ "SETTLE_ORDER",
142
+ "SpendEvent",
143
+ "SqliteStore",
144
+ "SqliteTx",
145
+ "UriPattern",
146
+ "VerifyResult",
147
+ "Window",
148
+ "agent_key_from_seed",
149
+ "b64url_decode",
150
+ "b64url_encode",
151
+ "base58_decode",
152
+ "base58_encode",
153
+ "canonical_json",
154
+ "canonicalize_uri",
155
+ "caveats_equal",
156
+ "chain_hash",
157
+ "check_offline_profile",
158
+ "check_request",
159
+ "did_key_from_ed25519",
160
+ "did_key_resolver",
161
+ "ed25519_from_did_key",
162
+ "encode_segment",
163
+ "evaluate_breakers",
164
+ "fail",
165
+ "fold_meet",
166
+ "from_atomic_units",
167
+ "from_scaled",
168
+ "generate_agent_key",
169
+ "host_matches",
170
+ "host_of_uri",
171
+ "host_pattern_contains",
172
+ "host_set_contains",
173
+ "interop",
174
+ "is_duration",
175
+ "is_money",
176
+ "is_quote_hash",
177
+ "jwk_from_did_key",
178
+ "jwk_thumbprint",
179
+ "meet_caveats",
180
+ "money_eq",
181
+ "money_leq",
182
+ "money_min",
183
+ "narrows",
184
+ "parse_compact_jws",
185
+ "parse_decimal_amount",
186
+ "parse_duration",
187
+ "parse_host_pattern",
188
+ "parse_uri_pattern",
189
+ "quote_hash_for_http_challenge",
190
+ "quote_hash_for_x402_challenge",
191
+ "quote_hash_from_x402_response",
192
+ "quotes_match",
193
+ "raw_x402_challenge_bytes",
194
+ "sha256_hex",
195
+ "sign_detached",
196
+ "sign_mandate",
197
+ "thumbprint_of_did_key",
198
+ "to_atomic_units",
199
+ "to_decimal",
200
+ "to_scaled",
201
+ "uri_matches",
202
+ "uri_pattern_contains",
203
+ "uri_set_contains",
204
+ "validate_caveats",
205
+ "verify_chain",
206
+ "verify_detached",
207
+ "verify_jws_signature",
208
+ ]
@@ -0,0 +1,134 @@
1
+ """Circuit breakers for autonomous spend protection (spec section 10.4).
2
+
3
+ Implements velocity anomaly detection (median baseline), burn-rate alerting,
4
+ task spending ceiling, novel-merchant detection, and principal global kill.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass
10
+ from typing import Literal, Optional
11
+
12
+ from .store import SqliteTx
13
+
14
+ BreakerSeverity = Literal["alert", "block"]
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class BreakerVerdict:
19
+ name: str
20
+ severity: BreakerSeverity
21
+ detail: str
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class BreakerConfig:
26
+ velocity_multiple: int = 10
27
+ velocity_window_seconds: int = 3600
28
+ velocity_baseline_windows: int = 24
29
+ velocity_min_samples: int = 6
30
+ burn_rate_warn_seconds: int = 900
31
+ task_ceiling_scaled: Optional[int] = None
32
+ novel_merchant: Literal["alert", "block", "off"] = "alert"
33
+
34
+
35
+ DEFAULT_BREAKERS = BreakerConfig()
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class BreakerInput:
40
+ root: str
41
+ host: str
42
+ task_id: Optional[str]
43
+ amount_scaled: int
44
+ remaining_scaled: Optional[int]
45
+ now: int
46
+
47
+
48
+ def _median(values: list[int]) -> int:
49
+ if not values:
50
+ return 0
51
+ s = sorted(values)
52
+ mid = len(s) // 2
53
+ if len(s) % 2 == 1:
54
+ return s[mid]
55
+ return (s[mid - 1] + s[mid]) // 2
56
+
57
+
58
+ def evaluate_breakers(
59
+ tx: SqliteTx,
60
+ cfg: BreakerConfig,
61
+ inp: BreakerInput,
62
+ ) -> list[BreakerVerdict]:
63
+ """Evaluate all configured circuit breakers within the active transaction."""
64
+ verdicts: list[BreakerVerdict] = []
65
+
66
+ if tx.killed(inp.root):
67
+ verdicts.append(
68
+ BreakerVerdict(
69
+ name="global_kill",
70
+ severity="block",
71
+ detail="principal spending halted",
72
+ )
73
+ )
74
+ return verdicts
75
+
76
+ if cfg.task_ceiling_scaled is not None and inp.task_id is not None:
77
+ after = tx.task_total(inp.task_id) + inp.amount_scaled
78
+ if after > cfg.task_ceiling_scaled:
79
+ verdicts.append(
80
+ BreakerVerdict(
81
+ name="task_ceiling",
82
+ severity="block",
83
+ detail=f"task {inp.task_id} would reach {after} against ceiling {cfg.task_ceiling_scaled}",
84
+ )
85
+ )
86
+
87
+ w = cfg.velocity_window_seconds
88
+ window_start = inp.now - w
89
+ baseline_start = inp.now - w * (cfg.velocity_baseline_windows + 1)
90
+
91
+ events = tx.history_since(inp.root, min(baseline_start, window_start))
92
+ current = (
93
+ sum(e.amount_scaled for e in events if e.ts >= window_start) + inp.amount_scaled
94
+ )
95
+ prior = [e for e in events if baseline_start <= e.ts < window_start]
96
+ if len(prior) >= cfg.velocity_min_samples:
97
+ buckets: dict[int, int] = {}
98
+ for e in prior:
99
+ b = (e.ts - baseline_start) // w
100
+ buckets[b] = buckets.get(b, 0) + e.amount_scaled
101
+ base = _median(list(buckets.values()))
102
+ if base > 0 and current > base * int(round(cfg.velocity_multiple)):
103
+ verdicts.append(
104
+ BreakerVerdict(
105
+ name="velocity_anomaly",
106
+ severity="block",
107
+ detail=f"{current} in the trailing window vs baseline median {base}",
108
+ )
109
+ )
110
+
111
+ if inp.remaining_scaled is not None and current > 0:
112
+ # Exact integer cross-multiplication avoids float rounding issues:
113
+ # seconds_left = remaining / (current / w) < burn_rate_warn_seconds
114
+ # iff remaining * w < burn_rate_warn_seconds * current
115
+ if inp.remaining_scaled * w < cfg.burn_rate_warn_seconds * current:
116
+ approx = round((inp.remaining_scaled * w) / current)
117
+ verdicts.append(
118
+ BreakerVerdict(
119
+ name="burn_rate",
120
+ severity="alert",
121
+ detail=f"budget exhausts in ~{approx}s at the current rate",
122
+ )
123
+ )
124
+
125
+ if cfg.novel_merchant != "off" and not tx.merchant_seen(inp.root, inp.host):
126
+ verdicts.append(
127
+ BreakerVerdict(
128
+ name="novel_merchant",
129
+ severity=cfg.novel_merchant,
130
+ detail=f"first spend to {inp.host} for this principal",
131
+ )
132
+ )
133
+
134
+ return verdicts
@@ -0,0 +1,75 @@
1
+ """RFC 8785 (JCS) canonical JSON serialization and SHA-256 helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import math
8
+ from decimal import Decimal
9
+ from typing import Any
10
+
11
+
12
+ def _utf16_sort_key(s: str) -> bytes:
13
+ """RFC 8785 section 3.2.3 sorts object property names by UTF-16 code units."""
14
+ return s.encode("utf-16-be")
15
+
16
+
17
+ def _encode_jcs_number(value: int | float) -> str:
18
+ if isinstance(value, bool):
19
+ return "true" if value else "false"
20
+ if isinstance(value, int):
21
+ return str(value)
22
+ if not math.isfinite(value):
23
+ raise ValueError(f"RFC 8785 forbids non-finite JSON number: {value!r}")
24
+ if value == 0.0:
25
+ return "0"
26
+ # Match ECMAScript Number.prototype.toString() formatting used by RFC 8785.
27
+ abs_val = abs(value)
28
+ sign = "-" if value < 0 else ""
29
+ d = Decimal(repr(abs_val)).normalize()
30
+ _, digits, exp = d.as_tuple()
31
+ assert isinstance(exp, int)
32
+ digit_str = "".join(str(x) for x in digits)
33
+ n = exp + len(digit_str) # position of decimal point relative to first digit
34
+ k = len(digit_str)
35
+
36
+ if k <= n <= 21:
37
+ return sign + digit_str + ("0" * (n - k))
38
+ if 0 < n <= 21:
39
+ return sign + digit_str[:n] + "." + digit_str[n:]
40
+ if -6 < n <= 0:
41
+ return sign + "0." + ("0" * (-n)) + digit_str
42
+ exp_val = n - 1
43
+ exp_sign = "+" if exp_val >= 0 else "-"
44
+ if k == 1:
45
+ return f"{sign}{digit_str}e{exp_sign}{abs(exp_val)}"
46
+ return f"{sign}{digit_str[0]}.{digit_str[1:]}e{exp_sign}{abs(exp_val)}"
47
+
48
+
49
+ def canonical_json(value: Any) -> str:
50
+ """Serialize a JSON-compatible value according to RFC 8785 (JCS)."""
51
+ if value is None:
52
+ return "null"
53
+ if isinstance(value, bool):
54
+ return "true" if value else "false"
55
+ if isinstance(value, (int, float)):
56
+ return _encode_jcs_number(value)
57
+ if isinstance(value, str):
58
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
59
+ if isinstance(value, (list, tuple)):
60
+ return "[" + ",".join(canonical_json(item) for item in value) + "]"
61
+ if isinstance(value, dict):
62
+ items = sorted(value.items(), key=lambda kv: _utf16_sort_key(str(kv[0])))
63
+ parts = []
64
+ for k, v in items:
65
+ if not isinstance(k, str):
66
+ raise TypeError(f"JSON object keys must be strings, got {type(k).__name__}")
67
+ parts.append(f"{json.dumps(k, ensure_ascii=False)}:{canonical_json(v)}")
68
+ return "{" + ",".join(parts) + "}"
69
+ raise TypeError(f"Unsupported type for canonical JSON: {type(value).__name__}")
70
+
71
+
72
+ def sha256_hex(data: str | bytes) -> str:
73
+ """Compute a `sha256:<hex>` digest over UTF-8 string or raw bytes."""
74
+ raw = data.encode("utf-8") if isinstance(data, str) else data
75
+ return f"sha256:{hashlib.sha256(raw).hexdigest()}"
@@ -0,0 +1,284 @@
1
+ """Caveat registry and attenuation lattice (spec section 6).
2
+
3
+ Every caveat declares a partial order oriented by authority granted:
4
+ - Absence means TOP (maximum authority on that dimension).
5
+ - A child link is valid iff `child.cav <= parent.cav` (`narrows`).
6
+ - `meet_caveats` computes a symmetric lower bound, returning `BOTTOM` where
7
+ two operands have no common lower bound (e.g. different tasks or currencies).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from dataclasses import dataclass
13
+ from typing import Any, Callable, Mapping, Sequence
14
+
15
+ from .canonical import canonical_json
16
+ from .duration import is_duration, parse_duration
17
+ from .errors import Check, OK, fail
18
+ from .money import is_money, money_eq, money_leq, money_min
19
+ from .uri import host_set_contains, uri_set_contains
20
+
21
+ SETTLE_ORDER: tuple[str, ...] = ("immediate", "escrow_schema", "escrow_human")
22
+ EFFECT_ORDER: tuple[str, ...] = ("irreversible", "write", "read")
23
+
24
+
25
+ class _BottomType:
26
+ """Sentinel representing lattice BOTTOM (unsatisfiable caveat meet)."""
27
+
28
+ def __repr__(self) -> str:
29
+ return "BOTTOM"
30
+
31
+
32
+ BOTTOM = _BottomType()
33
+
34
+
35
+ def _is_int(v: Any) -> bool:
36
+ return isinstance(v, int) and not isinstance(v, bool)
37
+
38
+
39
+ def _is_string_array(v: Any) -> bool:
40
+ return isinstance(v, list) and len(v) > 0 and all(isinstance(x, str) and len(x) > 0 for x in v)
41
+
42
+
43
+ def _set_leq(child: list[str], parent: list[str], what: str) -> Check:
44
+ p = set(parent)
45
+ extra = [c for c in child if c not in p]
46
+ if not extra:
47
+ return OK
48
+ return fail("attenuation_violation", f"{what} not granted by parent: {', '.join(extra)}")
49
+
50
+
51
+ def _pattern_meet(
52
+ a: list[str],
53
+ b: list[str],
54
+ contains: Callable[[Sequence[str], Sequence[str]], bool],
55
+ ) -> list[str]:
56
+ kept = [x for x in a if contains(b, [x])] + [x for x in b if contains(a, [x])]
57
+ return sorted(set(kept))
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class _CaveatSpec:
62
+ validate: Callable[[Any], bool]
63
+ leq: Callable[[Any, Any], Check]
64
+ meet: Callable[[Any, Any], Any]
65
+
66
+
67
+ def _validate_rate(v: Any) -> bool:
68
+ if not isinstance(v, Mapping):
69
+ return False
70
+ return _is_int(v.get("n")) and v["n"] > 0 and is_duration(v.get("per"))
71
+
72
+
73
+ def _leq_rate(c: Mapping[str, Any], p: Mapping[str, Any]) -> Check:
74
+ cp = parse_duration(c["per"])
75
+ pp = parse_duration(p["per"])
76
+ assert cp is not None and pp is not None
77
+ if c["n"] <= p["n"] and cp >= pp:
78
+ return OK
79
+ return fail(
80
+ "attenuation_violation",
81
+ f"rate {c['n']}/{c['per']} is not uniformly narrower than {p['n']}/{p['per']}",
82
+ )
83
+
84
+
85
+ def _meet_rate(a: Mapping[str, Any], b: Mapping[str, Any]) -> dict[str, Any]:
86
+ da = parse_duration(a["per"])
87
+ db = parse_duration(b["per"])
88
+ assert da is not None and db is not None
89
+ if da == db:
90
+ per = a["per"] if a["per"] <= b["per"] else b["per"]
91
+ else:
92
+ per = a["per"] if da > db else b["per"]
93
+ return {"n": min(a["n"], b["n"]), "per": per}
94
+
95
+
96
+ def _validate_step_up(v: Any) -> bool:
97
+ return isinstance(v, Mapping) and len(v) == 1 and "over" in v and is_money(v["over"])
98
+
99
+
100
+ def _validate_currency(v: Any) -> bool:
101
+ return isinstance(v, str) and len(v) >= 3 and len(v) <= 8 and v.isalpha() and v.isupper()
102
+
103
+
104
+ REGISTRY: dict[str, _CaveatSpec] = {
105
+ "max_total": _CaveatSpec(
106
+ validate=is_money,
107
+ leq=lambda c, p: money_leq(c, p),
108
+ meet=lambda a, b: money_min(a, b) if a["cur"] == b["cur"] else BOTTOM,
109
+ ),
110
+ "max_per_txn": _CaveatSpec(
111
+ validate=is_money,
112
+ leq=lambda c, p: money_leq(c, p),
113
+ meet=lambda a, b: money_min(a, b) if a["cur"] == b["cur"] else BOTTOM,
114
+ ),
115
+ "rate": _CaveatSpec(
116
+ validate=_validate_rate,
117
+ leq=_leq_rate,
118
+ meet=_meet_rate,
119
+ ),
120
+ "aud": _CaveatSpec(
121
+ validate=_is_string_array,
122
+ leq=lambda c, p: (
123
+ OK
124
+ if host_set_contains(p, c)
125
+ else fail("attenuation_violation", f"aud {','.join(c)} not contained by {','.join(p)}")
126
+ ),
127
+ meet=lambda a, b: _pattern_meet(a, b, host_set_contains),
128
+ ),
129
+ "resources": _CaveatSpec(
130
+ validate=_is_string_array,
131
+ leq=lambda c, p: (
132
+ OK
133
+ if uri_set_contains(p, c)
134
+ else fail("attenuation_violation", f"resources {','.join(c)} not contained by {','.join(p)}")
135
+ ),
136
+ meet=lambda a, b: _pattern_meet(a, b, uri_set_contains),
137
+ ),
138
+ "purpose": _CaveatSpec(
139
+ validate=_is_string_array,
140
+ leq=lambda c, p: _set_leq(c, p, "purpose"),
141
+ meet=lambda a, b: sorted(set(x for x in a if x in set(b))),
142
+ ),
143
+ "task": _CaveatSpec(
144
+ validate=lambda v: isinstance(v, str) and len(v) > 0,
145
+ leq=lambda c, p: OK if c == p else fail("attenuation_violation", f"task {c} differs from parent {p}"),
146
+ meet=lambda a, b: a if a == b else BOTTOM,
147
+ ),
148
+ "payer": _CaveatSpec(
149
+ validate=lambda v: isinstance(v, str) and len(v) > 0,
150
+ leq=lambda c, p: OK if c == p else fail("attenuation_violation", f"payer {c} differs from parent {p}"),
151
+ meet=lambda a, b: a if a == b else BOTTOM,
152
+ ),
153
+ "depth": _CaveatSpec(
154
+ validate=lambda v: _is_int(v) and v >= 0,
155
+ leq=lambda c, p: OK if c <= p else fail("depth_exceeded", f"depth {c} exceeds parent {p}"),
156
+ meet=lambda a, b: min(a, b),
157
+ ),
158
+ "delegable": _CaveatSpec(
159
+ validate=lambda v: isinstance(v, bool),
160
+ leq=lambda c, p: OK if (p or not c) else fail("attenuation_violation", "cannot restore delegable on a sealed mandate"),
161
+ meet=lambda a, b: a and b,
162
+ ),
163
+ "currency": _CaveatSpec(
164
+ validate=_validate_currency,
165
+ leq=lambda c, p: OK if c == p else fail("currency_mismatch", f"currency {c} differs from parent {p}"),
166
+ meet=lambda a, b: a if a == b else BOTTOM,
167
+ ),
168
+ "settle": _CaveatSpec(
169
+ validate=lambda v: isinstance(v, str) and v in SETTLE_ORDER,
170
+ leq=lambda c, p: (
171
+ OK
172
+ if SETTLE_ORDER.index(c) >= SETTLE_ORDER.index(p)
173
+ else fail("attenuation_violation", f"settle {c} is looser than parent {p}")
174
+ ),
175
+ meet=lambda a, b: a if SETTLE_ORDER.index(a) >= SETTLE_ORDER.index(b) else b,
176
+ ),
177
+ "step_up": _CaveatSpec(
178
+ validate=_validate_step_up,
179
+ leq=lambda c, p: money_leq(c["over"], p["over"]),
180
+ meet=lambda a, b: {"over": money_min(a["over"], b["over"])} if a["over"]["cur"] == b["over"]["cur"] else BOTTOM,
181
+ ),
182
+ "effect": _CaveatSpec(
183
+ validate=lambda v: isinstance(v, str) and v in EFFECT_ORDER,
184
+ leq=lambda c, p: (
185
+ OK
186
+ if EFFECT_ORDER.index(c) >= EFFECT_ORDER.index(p)
187
+ else fail("attenuation_violation", f"effect {c} is broader than parent {p}")
188
+ ),
189
+ meet=lambda a, b: a if EFFECT_ORDER.index(a) >= EFFECT_ORDER.index(b) else b,
190
+ ),
191
+ }
192
+
193
+ REGISTERED_CAVEATS: tuple[str, ...] = tuple(REGISTRY.keys())
194
+
195
+
196
+ def validate_caveats(cav: Any) -> Check:
197
+ """Validate a single link's caveat dict. Unregistered keys fail closed."""
198
+ if not isinstance(cav, Mapping):
199
+ return fail("chain_invalid", "cav must be an object")
200
+ for key, value in cav.items():
201
+ spec = REGISTRY.get(key)
202
+ if spec is None:
203
+ return fail("unknown_caveat", f'unregistered caveat "{key}"')
204
+ if value is BOTTOM:
205
+ return fail("chain_invalid", f'caveat "{key}" is unsatisfiable')
206
+ if not spec.validate(value):
207
+ return fail("chain_invalid", f'malformed caveat "{key}"')
208
+ return OK
209
+
210
+
211
+ def narrows(child: Mapping[str, Any], parent: Mapping[str, Any]) -> Check:
212
+ """Return OK iff `child` is no more authoritative than `parent` on every key in `child`."""
213
+ for key, cv in child.items():
214
+ spec = REGISTRY.get(key)
215
+ if spec is None:
216
+ return fail("unknown_caveat", f'unregistered caveat "{key}"')
217
+ if not spec.validate(cv):
218
+ return fail("chain_invalid", f'malformed caveat "{key}"')
219
+ if key not in parent:
220
+ continue
221
+ pv = parent[key]
222
+ if not spec.validate(pv):
223
+ return fail("chain_invalid", f'malformed parent caveat "{key}"')
224
+ r = spec.leq(cv, pv)
225
+ if not r.ok:
226
+ return r
227
+ return OK
228
+
229
+
230
+ def meet_caveats(a: Mapping[str, Any], b: Mapping[str, Any]) -> dict[str, Any]:
231
+ """Symmetric lower bound of two caveat dicts. Absence is TOP."""
232
+ out: dict[str, Any] = {}
233
+ keys = list(a.keys()) + [k for k in b.keys() if k not in a]
234
+ for key in keys:
235
+ has_a = key in a
236
+ has_b = key in b
237
+ if not has_a and not has_b:
238
+ continue
239
+ if not has_a:
240
+ out[key] = b[key]
241
+ continue
242
+ if not has_b:
243
+ out[key] = a[key]
244
+ continue
245
+ spec = REGISTRY.get(key)
246
+ if spec is None:
247
+ continue
248
+ out[key] = spec.meet(a[key], b[key])
249
+ return out
250
+
251
+
252
+ def fold_meet(links: Sequence[Mapping[str, Any]]) -> dict[str, Any]:
253
+ """Fold effective caveats across an ordered sequence of links."""
254
+ acc: dict[str, Any] = {}
255
+ for link in links:
256
+ acc = meet_caveats(acc, link)
257
+ return acc
258
+
259
+
260
+ def caveats_equal(a: Mapping[str, Any], b: Mapping[str, Any]) -> bool:
261
+ keys = set(a.keys()) | set(b.keys())
262
+ for k in keys:
263
+ if (k in a) != (k in b):
264
+ return False
265
+ x, y = a[k], b[k]
266
+ if x is BOTTOM or y is BOTTOM:
267
+ if x is not y:
268
+ return False
269
+ continue
270
+ if k in ("max_total", "max_per_txn"):
271
+ if not money_eq(x, y):
272
+ return False
273
+ elif k == "step_up":
274
+ if not money_eq(x["over"], y["over"]):
275
+ return False
276
+ elif isinstance(x, list) and isinstance(y, list):
277
+ if sorted(x) != sorted(y):
278
+ return False
279
+ elif isinstance(x, Mapping) and isinstance(y, Mapping):
280
+ if canonical_json(dict(x)) != canonical_json(dict(y)):
281
+ return False
282
+ elif x != y:
283
+ return False
284
+ return True