ememdev 2.4.5__tar.gz → 2.4.7__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: ememdev
3
- Version: 2.4.5
3
+ Version: 2.4.7
4
4
  Summary: Python client for emem: shared, verifiable memory for AI agents. One address per fact, one signature you can check. No key to read.
5
5
  Project-URL: Homepage, https://emem.dev
6
6
  Project-URL: Repository, https://github.com/Vortx-AI/emem
@@ -226,6 +226,93 @@ the receipt, `POST /v1/verify_receipt` gives `reason:
226
226
  receipt_reshaped_after_signing` instead of `signature_invalid`. It never
227
227
  accepts the changed receipt.
228
228
 
229
+ ## Verify an RLVR reward offline
230
+
231
+ emem's RLVR engine (Reinforcement Learning with Verifiable Rewards) scores
232
+ forecasts of physical quantities, such as the 2 m temperature at a place at
233
+ a time to come. `ememdev.rlvr` computes the same numbers in Python, so you
234
+ can check a reward and a time proof without asking emem.dev. It is a port of
235
+ the Rust crate `emem-rlvr`. The tests compare it with vectors that the crate
236
+ wrote: task cids and their CBOR, reference forecasts, rewards, leaderboard
237
+ skill, the tasks a deck issues, commit bytes, and RFC 3161 requests. Every
238
+ value is the same, byte for byte or float for float.
239
+
240
+ It needs the `signing` extra: BLAKE3 for content ids and log hashes, and
241
+ `cryptography` for the authority's signature.
242
+
243
+ Recompute a task's cid and a reward:
244
+
245
+ ```python
246
+ from ememdev.rlvr import Forecast, Form, Reference, Resolution, Task, reward
247
+
248
+ task = Task(
249
+ v=1, deck="", cell="defi.zb64a.cAzU.zfa27", band="era5.t2m", reader="era5@1",
250
+ window=(1796470200, 1796473800), resolution=Resolution.nearest(1796472000),
251
+ lock=1796211000, form=Form.quantiles([0.1, 0.5, 0.9]),
252
+ reference=Reference.climatology(10, 7), scale=1.8,
253
+ )
254
+ print(task.cid())
255
+ ref = Forecast.quantiles([270.772, 273.85, 277.023])
256
+ print(reward(task, Forecast.quantiles([272.0, 274.5, 277.25]), ref, 275.1))
257
+ ```
258
+
259
+ This prints `ccwm2u7kv3tu2fkstjp27stspf4hisn4i4ihpghbkzv6onkqja2q` and a
260
+ `Scored` with `reward=0.15744444444444153`, the values in the Rust crate's
261
+ vectors.
262
+
263
+ A time proof shows that a log entry, such as an agent's commit, existed by
264
+ an outside authority's clock. It has three links: the entry is in a tree
265
+ head, an anchored head is a prefix of that head, and an RFC 3161 token from
266
+ the authority stamps the anchored head. Check one from the command line:
267
+
268
+ ```bash
269
+ ememdev rlvr verify-proof proof.json token.tsr --ca-file /etc/ssl/certs/ca-certificates.crt
270
+ ```
271
+
272
+ With `proof-12345.json` and `anchor-3487000.digicert.tsr` from
273
+ `sdks/emem-py/tests/vectors/rlvr/`, the first line is
274
+ `existed by 2026-11-29T12:54:26Z (unix 1795956866), by the authority's clock`.
275
+ The exit status is 0 when every link holds and the signature verified, 1
276
+ when a link is broken (the output names it), and 3 when the links hold but
277
+ the signature was not checked.
278
+
279
+ In Python, `fixed_in_time(task, proof)` returns the stamped second, or
280
+ raises a `ProofError` that names the broken link: `AfterAnchor`,
281
+ `Inclusion`, `Consistency`, `Anchor` (the token stamps other bytes) or
282
+ `Late` (the stamp is not strictly before the task's lock).
283
+
284
+ ```python
285
+ from ememdev.rlvr import TimeProof, fixed_in_time, parse_response, verify_token
286
+
287
+ with open("proof.json") as f, open("token.tsr", "rb") as t:
288
+ proof = TimeProof.from_json(f.read(), parse_response(t.read()))
289
+ when = fixed_in_time(task, proof)
290
+ v = verify_token(proof.token, "/etc/ssl/certs/ca-certificates.crt")
291
+ print(when, v.ok, v.signer)
292
+ ```
293
+
294
+ What the checks cover:
295
+
296
+ - `fixed_in_time` does not check the authority's signature, as in the Rust
297
+ crate. `verify_token` does. It checks that the signed attributes bind the
298
+ token's content, that the signature verifies with the key of the signer's
299
+ certificate (RSA PKCS #1 v1.5, ECDSA or Ed25519), that the certificate is
300
+ for time-stamping only, and that it chains to a certificate in the CA file
301
+ you pass.
302
+ - `v.ok` is `True` only when every check ran and passed. When a check cannot
303
+ run here, for example for an RSASSA-PSS signature or a SHA-1 digest,
304
+ `v.state` is `not_checked` and `v.ok` is `False`.
305
+ - Certificates are checked at the token's genTime. Revocation, certificate
306
+ policies and name constraints are not checked.
307
+ - `verify_with_openssl` runs `openssl ts -verify` instead. It runs only
308
+ when you call it, and openssl checks certificates at the current time.
309
+ - On 29 November 2026 the DigiCert and Sectigo tokens in the test vectors
310
+ verified against `/etc/ssl/certs/ca-certificates.crt`. The FreeTSA token
311
+ verified against FreeTSA's own root, which is not in that file.
312
+ - A valid proof shows when the forecast was fixed. It does not show that the
313
+ outcome reading is correct: a reward is only as sound as the signed
314
+ readings it is computed from.
315
+
229
316
  ## License
230
317
 
231
318
  Apache-2.0, the same license as the protocol.
@@ -196,6 +196,93 @@ the receipt, `POST /v1/verify_receipt` gives `reason:
196
196
  receipt_reshaped_after_signing` instead of `signature_invalid`. It never
197
197
  accepts the changed receipt.
198
198
 
199
+ ## Verify an RLVR reward offline
200
+
201
+ emem's RLVR engine (Reinforcement Learning with Verifiable Rewards) scores
202
+ forecasts of physical quantities, such as the 2 m temperature at a place at
203
+ a time to come. `ememdev.rlvr` computes the same numbers in Python, so you
204
+ can check a reward and a time proof without asking emem.dev. It is a port of
205
+ the Rust crate `emem-rlvr`. The tests compare it with vectors that the crate
206
+ wrote: task cids and their CBOR, reference forecasts, rewards, leaderboard
207
+ skill, the tasks a deck issues, commit bytes, and RFC 3161 requests. Every
208
+ value is the same, byte for byte or float for float.
209
+
210
+ It needs the `signing` extra: BLAKE3 for content ids and log hashes, and
211
+ `cryptography` for the authority's signature.
212
+
213
+ Recompute a task's cid and a reward:
214
+
215
+ ```python
216
+ from ememdev.rlvr import Forecast, Form, Reference, Resolution, Task, reward
217
+
218
+ task = Task(
219
+ v=1, deck="", cell="defi.zb64a.cAzU.zfa27", band="era5.t2m", reader="era5@1",
220
+ window=(1796470200, 1796473800), resolution=Resolution.nearest(1796472000),
221
+ lock=1796211000, form=Form.quantiles([0.1, 0.5, 0.9]),
222
+ reference=Reference.climatology(10, 7), scale=1.8,
223
+ )
224
+ print(task.cid())
225
+ ref = Forecast.quantiles([270.772, 273.85, 277.023])
226
+ print(reward(task, Forecast.quantiles([272.0, 274.5, 277.25]), ref, 275.1))
227
+ ```
228
+
229
+ This prints `ccwm2u7kv3tu2fkstjp27stspf4hisn4i4ihpghbkzv6onkqja2q` and a
230
+ `Scored` with `reward=0.15744444444444153`, the values in the Rust crate's
231
+ vectors.
232
+
233
+ A time proof shows that a log entry, such as an agent's commit, existed by
234
+ an outside authority's clock. It has three links: the entry is in a tree
235
+ head, an anchored head is a prefix of that head, and an RFC 3161 token from
236
+ the authority stamps the anchored head. Check one from the command line:
237
+
238
+ ```bash
239
+ ememdev rlvr verify-proof proof.json token.tsr --ca-file /etc/ssl/certs/ca-certificates.crt
240
+ ```
241
+
242
+ With `proof-12345.json` and `anchor-3487000.digicert.tsr` from
243
+ `sdks/emem-py/tests/vectors/rlvr/`, the first line is
244
+ `existed by 2026-11-29T12:54:26Z (unix 1795956866), by the authority's clock`.
245
+ The exit status is 0 when every link holds and the signature verified, 1
246
+ when a link is broken (the output names it), and 3 when the links hold but
247
+ the signature was not checked.
248
+
249
+ In Python, `fixed_in_time(task, proof)` returns the stamped second, or
250
+ raises a `ProofError` that names the broken link: `AfterAnchor`,
251
+ `Inclusion`, `Consistency`, `Anchor` (the token stamps other bytes) or
252
+ `Late` (the stamp is not strictly before the task's lock).
253
+
254
+ ```python
255
+ from ememdev.rlvr import TimeProof, fixed_in_time, parse_response, verify_token
256
+
257
+ with open("proof.json") as f, open("token.tsr", "rb") as t:
258
+ proof = TimeProof.from_json(f.read(), parse_response(t.read()))
259
+ when = fixed_in_time(task, proof)
260
+ v = verify_token(proof.token, "/etc/ssl/certs/ca-certificates.crt")
261
+ print(when, v.ok, v.signer)
262
+ ```
263
+
264
+ What the checks cover:
265
+
266
+ - `fixed_in_time` does not check the authority's signature, as in the Rust
267
+ crate. `verify_token` does. It checks that the signed attributes bind the
268
+ token's content, that the signature verifies with the key of the signer's
269
+ certificate (RSA PKCS #1 v1.5, ECDSA or Ed25519), that the certificate is
270
+ for time-stamping only, and that it chains to a certificate in the CA file
271
+ you pass.
272
+ - `v.ok` is `True` only when every check ran and passed. When a check cannot
273
+ run here, for example for an RSASSA-PSS signature or a SHA-1 digest,
274
+ `v.state` is `not_checked` and `v.ok` is `False`.
275
+ - Certificates are checked at the token's genTime. Revocation, certificate
276
+ policies and name constraints are not checked.
277
+ - `verify_with_openssl` runs `openssl ts -verify` instead. It runs only
278
+ when you call it, and openssl checks certificates at the current time.
279
+ - On 29 November 2026 the DigiCert and Sectigo tokens in the test vectors
280
+ verified against `/etc/ssl/certs/ca-certificates.crt`. The FreeTSA token
281
+ verified against FreeTSA's own root, which is not in that file.
282
+ - A valid proof shows when the forecast was fixed. It does not show that the
283
+ outcome reading is correct: a reward is only as sound as the signed
284
+ readings it is computed from.
285
+
199
286
  ## License
200
287
 
201
288
  Apache-2.0, the same license as the protocol.
@@ -9,7 +9,7 @@ name = "ememdev"
9
9
  # without a framework. 1.0.1 first superseded the empty 1.0.0 on PyPI (it
10
10
  # shipped dist-info and no modules, so `import emem` raised ModuleNotFoundError;
11
11
  # PyPI versions are immutable, so the only fix was to supersede it).
12
- version = "2.4.5"
12
+ version = "2.4.7"
13
13
  description = "Python client for emem: shared, verifiable memory for AI agents. One address per fact, one signature you can check. No key to read."
14
14
  readme = "README.md"
15
15
  requires-python = ">=3.9"
@@ -51,6 +51,8 @@ dependencies = [
51
51
  # The base client is httpx-only. Signing memory writes needs ed25519 + blake3,
52
52
  # which are only pulled when you ask for them. `ememdev.signing` and the
53
53
  # `ememdev` CLI's sign/write commands raise a clear install hint without this.
54
+ # `ememdev.rlvr` uses the same extra: blake3 for content ids and log hashes,
55
+ # cryptography for the RFC 3161 authority's signature.
54
56
  [project.optional-dependencies]
55
57
  signing = [
56
58
  "blake3>=0.3",
@@ -9,6 +9,11 @@ one step.
9
9
  ememdev whoami
10
10
  ememdev sign --verb create --path /memories/by_attester/<you>/n.md --stdin
11
11
  ememdev write --path /memories/by_attester/<you>/n.md --body-file n.md
12
+ ememdev rlvr verify-proof proof.json token.tsr --ca-file <roots.pem>
13
+
14
+ `ememdev rlvr verify-proof` makes no network call and needs no identity: it
15
+ prints when a logged entry existed by an RFC 3161 authority's clock, or the
16
+ broken link (see `ememdev.rlvr.cli`).
12
17
 
13
18
  The identity comes from the standard location (see `ememdev.identity`):
14
19
  `EMEM_AGENT_KEY`, then `~/.emem/agent_ed25519.pem`, minted on first
@@ -206,7 +211,8 @@ def _add_body_args(p: argparse.ArgumentParser) -> None:
206
211
  def main(argv: Optional[list] = None) -> int:
207
212
  parser = argparse.ArgumentParser(
208
213
  prog="ememdev",
209
- description="Sign and write emem memory notes with a standard ed25519 identity.",
214
+ description="Sign and write emem memory notes with a standard ed25519 identity, "
215
+ "and check RLVR time proofs offline.",
210
216
  )
211
217
  sub = parser.add_subparsers(dest="command", required=True)
212
218
 
@@ -241,6 +247,10 @@ def main(argv: Optional[list] = None) -> int:
241
247
  )
242
248
  _add_body_args(p_write)
243
249
 
250
+ from .rlvr import cli as rlvr_cli
251
+
252
+ rlvr_cli.add_parser(sub)
253
+
244
254
  args = parser.parse_args(argv)
245
255
  if args.command == "whoami":
246
256
  return _cmd_whoami(args)
@@ -248,6 +258,8 @@ def main(argv: Optional[list] = None) -> int:
248
258
  return _cmd_sign(args)
249
259
  if args.command == "write":
250
260
  return _cmd_write(args)
261
+ if args.command == "rlvr":
262
+ return rlvr_cli.run(args)
251
263
  parser.error(f"unknown command {args.command!r}")
252
264
  return 2
253
265
 
@@ -0,0 +1,78 @@
1
+ """Check emem's RLVR rewards and time proofs offline.
2
+
3
+ A Python port of the pure core of the Rust crate `emem-rlvr`
4
+ (Reinforcement Learning with Verifiable Rewards). An agent forecasts a
5
+ physical quantity at a place for a time to come; the forecast is committed
6
+ to emem's transparency log; the log's tree head is time-stamped by outside
7
+ authorities (RFC 3161) before the outcome exists; a proper score turns
8
+ forecast and outcome into a reward.
9
+
10
+ This package recomputes the same bytes and numbers as the Rust crate, so a
11
+ third party does not need to trust emem.dev for them:
12
+
13
+ - `task`: the task, its canonical CBOR and its cid;
14
+ - `score`: proper scores and the reward;
15
+ - `baseline`: the reference forecasts;
16
+ - `commit`: the note an agent writes to fix its forecast;
17
+ - `deck`: the rule that assigns tasks;
18
+ - `anchor`: the anchored message, the RFC 3161 request, a strict reader of
19
+ the authority's response;
20
+ - `proof`: that a logged entry existed by the authority's time;
21
+ - `tsa`: the authority's signature on the token, checked against a CA file.
22
+
23
+ The golden vectors in `tests/vectors/rlvr/golden.json` are written by the
24
+ Rust crate, and the tests compare every value exactly.
25
+
26
+ Content ids, deck picks and the log's hashes need BLAKE3, and the signature
27
+ check needs `cryptography`: install the `signing` extra.
28
+
29
+ from ememdev import rlvr
30
+ proof = rlvr.TimeProof.from_json(open("proof.json").read(),
31
+ rlvr.parse_response(open("token.tsr", "rb").read()))
32
+ when = rlvr.fixed_in_time(task, proof) # the stamped second
33
+ v = rlvr.verify_token(proof.token, "/etc/ssl/certs/ca-certificates.crt")
34
+ assert v.ok, v.why # the authority signed it
35
+ """
36
+
37
+ from __future__ import annotations
38
+
39
+ from ._common import b32
40
+ from .anchor import AnchorError, Token, parse_response
41
+ from .baseline import reference
42
+ from .commit import Commit, CommitError, Track
43
+ from .deck import Deck
44
+ from .proof import ProofError, TimeProof, existed_by, fixed_in_time
45
+ from .score import MALFORMED, Forecast, Scored, reward, skill
46
+ from .task import Form, Op, Reading, Reference, Resolution, Task, TaskError
47
+ from .tsa import SignatureVerdict, verify_token, verify_with_openssl
48
+
49
+ __all__ = [
50
+ "b32",
51
+ "Task",
52
+ "Resolution",
53
+ "Form",
54
+ "Op",
55
+ "Reference",
56
+ "Reading",
57
+ "TaskError",
58
+ "Forecast",
59
+ "Scored",
60
+ "MALFORMED",
61
+ "reward",
62
+ "skill",
63
+ "reference",
64
+ "Commit",
65
+ "Track",
66
+ "CommitError",
67
+ "Deck",
68
+ "Token",
69
+ "AnchorError",
70
+ "parse_response",
71
+ "TimeProof",
72
+ "ProofError",
73
+ "existed_by",
74
+ "fixed_in_time",
75
+ "SignatureVerdict",
76
+ "verify_token",
77
+ "verify_with_openssl",
78
+ ]
@@ -0,0 +1,156 @@
1
+ """CBOR exactly as Rust's `ciborium` 0.2.2 writes a serde value.
2
+
3
+ The input is a serde-shaped value: a dict is a struct or map (keys in the
4
+ order given, never sorted), a list or tuple is a sequence, an int is an
5
+ integer, a float is an f64, a str is text. The rules that matter:
6
+
7
+ - every head is minimal (ciborium-ll `Title::from`);
8
+ - a float takes the shortest of f16, f32 and f64 whose value converts back
9
+ to the same 64 bits (ciborium-ll `Header::Float`), so 0.5 is `f9 3800`,
10
+ 1.8 is `fb ...` and -0.0 is `f9 8000`.
11
+
12
+ No library "canonical" mode is used: those sort map keys, and serde writes
13
+ struct fields in declaration order.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import struct
19
+ from typing import Any
20
+
21
+ from ._common import U64_MAX, f64_bits
22
+
23
+
24
+ def _head(major: int, n: int, out: bytearray) -> None:
25
+ if n <= 23:
26
+ out.append((major << 5) | n)
27
+ elif n <= 0xFF:
28
+ out.append((major << 5) | 24)
29
+ out.append(n)
30
+ elif n <= 0xFFFF:
31
+ out.append((major << 5) | 25)
32
+ out += n.to_bytes(2, "big")
33
+ elif n <= 0xFFFFFFFF:
34
+ out.append((major << 5) | 26)
35
+ out += n.to_bytes(4, "big")
36
+ else:
37
+ out.append((major << 5) | 27)
38
+ out += n.to_bytes(8, "big")
39
+
40
+
41
+ def f16_from_f64_bits(val: int) -> int:
42
+ """half 2.7.1 `f64_to_f16_fallback`, bit for bit."""
43
+ x = (val >> 32) & 0xFFFFFFFF
44
+ sign = x & 0x80000000
45
+ exp = x & 0x7FF00000
46
+ man = x & 0x000FFFFF
47
+ if exp == 0x7FF00000:
48
+ nan_bit = 0 if (man == 0 and (val & 0xFFFFFFFF) == 0) else 0x0200
49
+ return ((sign >> 16) | 0x7C00 | nan_bit | (man >> 10)) & 0xFFFF
50
+ half_sign = sign >> 16
51
+ unbiased_exp = (exp >> 20) - 1023
52
+ half_exp = unbiased_exp + 15
53
+ if half_exp >= 0x1F:
54
+ return (half_sign | 0x7C00) & 0xFFFF
55
+ if half_exp <= 0:
56
+ if 10 - half_exp > 21:
57
+ return half_sign & 0xFFFF
58
+ man = man | 0x00100000
59
+ half_man = man >> (11 - half_exp)
60
+ round_bit = 1 << (10 - half_exp)
61
+ if (man & round_bit) != 0 and (man & (3 * round_bit - 1)) != 0:
62
+ half_man += 1
63
+ return (half_sign | half_man) & 0xFFFF
64
+ half_exp_bits = half_exp << 10
65
+ half_man = man >> 10
66
+ round_bit = 0x00000200
67
+ if (man & round_bit) != 0 and (man & (3 * round_bit - 1)) != 0:
68
+ return ((half_sign | half_exp_bits | half_man) + 1) & 0xFFFF
69
+ return (half_sign | half_exp_bits | half_man) & 0xFFFF
70
+
71
+
72
+ def f64_bits_from_f16(i: int) -> int:
73
+ """half 2.7.1 `f16_to_f64_fallback`, bit for bit."""
74
+ if i & 0x7FFF == 0:
75
+ return (i << 48) & U64_MAX
76
+ half_sign = i & 0x8000
77
+ half_exp = i & 0x7C00
78
+ half_man = i & 0x03FF
79
+ if half_exp == 0x7C00:
80
+ if half_man == 0:
81
+ return (half_sign << 48) | 0x7FF0000000000000
82
+ return (half_sign << 48) | 0x7FF8000000000000 | (half_man << 42)
83
+ sign = half_sign << 48
84
+ unbiased_exp = (half_exp >> 10) - 15
85
+ if half_exp == 0:
86
+ e = (16 - half_man.bit_length()) - 6
87
+ exp = (1023 - 15 - e) << 52
88
+ man = (half_man << (43 + e)) & 0xFFFFFFFFFFFFF
89
+ return sign | exp | man
90
+ exp = (unbiased_exp + 1023) << 52
91
+ man = (half_man & 0x03FF) << 42
92
+ return sign | exp | man
93
+
94
+
95
+ def _float(x: float, out: bytearray) -> None:
96
+ bits = f64_bits(x)
97
+ h = f16_from_f64_bits(bits)
98
+ if f64_bits_from_f16(h) == bits:
99
+ out.append(0xF9)
100
+ out += h.to_bytes(2, "big")
101
+ return
102
+ try:
103
+ b4 = struct.pack(">f", x)
104
+ except OverflowError:
105
+ b4 = b""
106
+ if b4 and f64_bits(struct.unpack(">f", b4)[0]) == bits:
107
+ out.append(0xFA)
108
+ out += b4
109
+ return
110
+ out.append(0xFB)
111
+ out += struct.pack(">d", x)
112
+
113
+
114
+ def _enc(v: Any, out: bytearray) -> None:
115
+ if v is None:
116
+ out.append(0xF6)
117
+ elif v is True:
118
+ out.append(0xF5)
119
+ elif v is False:
120
+ out.append(0xF4)
121
+ elif isinstance(v, int):
122
+ if v >= 0:
123
+ if v > U64_MAX:
124
+ raise ValueError(f"{v} does not fit a CBOR integer")
125
+ _head(0, v, out)
126
+ else:
127
+ n = -1 - v
128
+ if n > U64_MAX:
129
+ raise ValueError(f"{v} does not fit a CBOR integer")
130
+ _head(1, n, out)
131
+ elif isinstance(v, float):
132
+ _float(v, out)
133
+ elif isinstance(v, str):
134
+ b = v.encode("utf-8")
135
+ _head(3, len(b), out)
136
+ out += b
137
+ elif isinstance(v, (list, tuple)):
138
+ _head(4, len(v), out)
139
+ for item in v:
140
+ _enc(item, out)
141
+ elif isinstance(v, dict):
142
+ _head(5, len(v), out)
143
+ for k, item in v.items():
144
+ if not isinstance(k, str):
145
+ raise TypeError("a serde struct or map key here is text")
146
+ _enc(k, out)
147
+ _enc(item, out)
148
+ else:
149
+ raise TypeError(f"no serde shape for {type(v).__name__}")
150
+
151
+
152
+ def encode(value: Any) -> bytes:
153
+ """The CBOR ciborium writes for this serde-shaped value."""
154
+ out = bytearray()
155
+ _enc(value, out)
156
+ return bytes(out)
@@ -0,0 +1,171 @@
1
+ """Small pieces every rlvr module shares: base32, BLAKE3, integer ranges,
2
+ Rust's integer division and float ordering, and error variants."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import base64
7
+ import math
8
+ import struct
9
+ from typing import Any, Callable, Type, TypeVar
10
+
11
+ U32_MAX = 0xFFFFFFFF
12
+ U64_MAX = 0xFFFFFFFFFFFFFFFF
13
+ I64_MIN = -(1 << 63)
14
+ I64_MAX = (1 << 63) - 1
15
+
16
+ E = TypeVar("E", bound=type)
17
+
18
+
19
+ def b32(data: bytes) -> str:
20
+ """Lower-case base32 without padding, the encoding every emem cid uses."""
21
+ return base64.b32encode(bytes(data)).decode("ascii").rstrip("=").lower()
22
+
23
+
24
+ def b32_decode(text: str) -> bytes:
25
+ """Read lower-case base32 without padding, refusing a non-canonical form
26
+ (upper case, padding, or set trailing bits)."""
27
+ if not isinstance(text, str):
28
+ raise ValueError("base32 text must be a string")
29
+ try:
30
+ out = base64.b32decode(text.upper() + "=" * (-len(text) % 8))
31
+ except Exception as e:
32
+ raise ValueError(f"not base32: {text!r}") from e
33
+ if b32(out) != text:
34
+ raise ValueError(f"not canonical lower-case base32: {text!r}")
35
+ return out
36
+
37
+
38
+ def blake3(*parts: bytes) -> bytes:
39
+ """BLAKE3-256 of the concatenation of `parts`."""
40
+ try:
41
+ import blake3 as _b3
42
+ except ImportError as e: # pragma: no cover - exercised without the extra
43
+ raise ImportError(
44
+ "ememdev.rlvr needs blake3 for content ids, deck picks and the log's "
45
+ "hashes: pip install 'ememdev[signing]'"
46
+ ) from e
47
+ h = _b3.blake3()
48
+ for p in parts:
49
+ h.update(bytes(p))
50
+ return h.digest()
51
+
52
+
53
+ def check_int(v: Any, lo: int, hi: int, what: str) -> int:
54
+ if isinstance(v, bool) or not isinstance(v, int):
55
+ raise TypeError(f"{what} must be an integer, not {type(v).__name__}")
56
+ if not lo <= v <= hi:
57
+ raise ValueError(f"{what} {v} is out of range")
58
+ return int(v)
59
+
60
+
61
+ def u32(v: Any, what: str) -> int:
62
+ return check_int(v, 0, U32_MAX, what)
63
+
64
+
65
+ def u64(v: Any, what: str) -> int:
66
+ return check_int(v, 0, U64_MAX, what)
67
+
68
+
69
+ def i64(v: Any, what: str) -> int:
70
+ return check_int(v, I64_MIN, I64_MAX, what)
71
+
72
+
73
+ def f64(v: Any, what: str) -> float:
74
+ """A float field. An int is taken as the float it names, as serde does for
75
+ an f64 field, so `scale=2` encodes as the float 2.0, never as an integer."""
76
+ if isinstance(v, bool) or not isinstance(v, (int, float)):
77
+ raise TypeError(f"{what} must be a number, not {type(v).__name__}")
78
+ return float(v)
79
+
80
+
81
+ def text(v: Any, what: str) -> str:
82
+ if not isinstance(v, str):
83
+ raise TypeError(f"{what} must be a string, not {type(v).__name__}")
84
+ v.encode("utf-8") # a lone surrogate is no Rust String
85
+ return v
86
+
87
+
88
+ def tdiv(a: int, b: int) -> int:
89
+ """Rust's `/` on signed integers: the quotient rounded toward zero."""
90
+ q = abs(a) // abs(b)
91
+ return q if (a < 0) == (b < 0) else -q
92
+
93
+
94
+ def trem(a: int, b: int) -> int:
95
+ """Rust's `%` on signed integers: the remainder takes the dividend's sign."""
96
+ return a - b * tdiv(a, b)
97
+
98
+
99
+ def f64_bits(x: float) -> int:
100
+ return struct.unpack(">Q", struct.pack(">d", x))[0]
101
+
102
+
103
+ def total_key(x: float) -> int:
104
+ """An integer that orders floats as Rust's `f64::total_cmp` does."""
105
+ bits = struct.unpack(">q", struct.pack(">d", x))[0]
106
+ return bits ^ 0x7FFFFFFFFFFFFFFF if bits < 0 else bits
107
+
108
+
109
+ def fdiv(a: float, b: float) -> float:
110
+ """IEEE 754 division, as Rust's `/` on f64: dividing by zero gives an
111
+ infinity or NaN where Python would raise."""
112
+ if b != 0.0:
113
+ return a / b
114
+ if math.isnan(a) or a == 0.0:
115
+ return math.nan
116
+ return math.copysign(math.inf, a) * math.copysign(1.0, b)
117
+
118
+
119
+ def rust_debug_str(s: str) -> str:
120
+ """A string as Rust's `{:?}` prints it, for error text."""
121
+ out = ['"']
122
+ for ch in s:
123
+ o = ord(ch)
124
+ if ch == '"':
125
+ out.append('\\"')
126
+ elif ch == "\\":
127
+ out.append("\\\\")
128
+ elif ch == "\n":
129
+ out.append("\\n")
130
+ elif ch == "\r":
131
+ out.append("\\r")
132
+ elif ch == "\t":
133
+ out.append("\\t")
134
+ elif ch == "\0":
135
+ out.append("\\0")
136
+ elif o < 0x20 or o == 0x7F:
137
+ out.append(f"\\u{{{o:x}}}")
138
+ else:
139
+ out.append(ch)
140
+ out.append('"')
141
+ return "".join(out)
142
+
143
+
144
+ def variant(base: Type[Exception]) -> Callable[[E], E]:
145
+ """Attach an error class to `base` under its own name without the leading
146
+ underscore, so `TaskError.Window` reads like Rust's `TaskError::Window`."""
147
+
148
+ def attach(cls: E) -> E:
149
+ name = cls.__name__.lstrip("_")
150
+ cls.__name__ = name
151
+ cls.__qualname__ = f"{base.__qualname__}.{name}"
152
+ setattr(base, name, cls)
153
+ return cls
154
+
155
+ return attach
156
+
157
+
158
+ class RustError(Exception):
159
+ """Errors compare equal when they are the same case with the same fields,
160
+ as the Rust enums derive PartialEq."""
161
+
162
+ def _fields(self) -> tuple:
163
+ return self.args
164
+
165
+ def __eq__(self, other: object) -> bool:
166
+ return type(self) is type(other) and self._fields() == other._fields() # type: ignore[attr-defined]
167
+
168
+ def __ne__(self, other: object) -> bool:
169
+ return not self == other
170
+
171
+ __hash__ = Exception.__hash__