egzoscore 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.
Files changed (62) hide show
  1. egzos/__init__.py +11 -0
  2. egzos/_ids.py +29 -0
  3. egzos/_signals.py +39 -0
  4. egzos/_term.py +33 -0
  5. egzos/_types.py +1023 -0
  6. egzos/api/__init__.py +150 -0
  7. egzos/api/app.py +1574 -0
  8. egzos/api/blobs.py +92 -0
  9. egzos/api/throttle.py +190 -0
  10. egzos/auth.py +176 -0
  11. egzos/authz/__init__.py +5 -0
  12. egzos/authz/presence.py +778 -0
  13. egzos/authz/values.py +32 -0
  14. egzos/backends/__init__.py +8 -0
  15. egzos/backends/base.py +91 -0
  16. egzos/backends/postgres.py +490 -0
  17. egzos/backends/sqlite.py +524 -0
  18. egzos/binding.py +309 -0
  19. egzos/cli/__init__.py +1092 -0
  20. egzos/cli/__main__.py +11 -0
  21. egzos/confirm.py +455 -0
  22. egzos/container.py +222 -0
  23. egzos/identity.py +1104 -0
  24. egzos/ledger.py +167 -0
  25. egzos/mcp/__init__.py +3 -0
  26. egzos/mcp/http.py +90 -0
  27. egzos/mcp/server.py +287 -0
  28. egzos/model.py +242 -0
  29. egzos/py.typed +0 -0
  30. egzos/resolver.py +115 -0
  31. egzos/store/__init__.py +10 -0
  32. egzos/store/autotitle.py +31 -0
  33. egzos/store/blobs.py +120 -0
  34. egzos/store/find.py +120 -0
  35. egzos/store/items.py +233 -0
  36. egzos/store/nodes.py +193 -0
  37. egzos/store/objects.py +143 -0
  38. egzos/store/uploads.py +369 -0
  39. egzos/trust.py +675 -0
  40. egzos/web/__init__.py +88 -0
  41. egzos/web/app.py +965 -0
  42. egzos/web/static/htmx.LICENSE +13 -0
  43. egzos/web/static/htmx.min.js +1 -0
  44. egzos/web/static/lifeboat.css +140 -0
  45. egzos/web/static/lifeboat.js +12 -0
  46. egzos/web/strings.py +133 -0
  47. egzos/web/templates/_manifest_row.html +3 -0
  48. egzos/web/templates/_shell.html +29 -0
  49. egzos/web/templates/_window.html +7 -0
  50. egzos/web/templates/base.html +24 -0
  51. egzos/web/templates/error.html +10 -0
  52. egzos/web/templates/home.html +39 -0
  53. egzos/web/templates/item.html +91 -0
  54. egzos/web/templates/notfound.html +6 -0
  55. egzos/web/templates/pending.html +107 -0
  56. egzos/web/tokens.css +294 -0
  57. egzoscore-0.2.0.dist-info/METADATA +135 -0
  58. egzoscore-0.2.0.dist-info/RECORD +62 -0
  59. egzoscore-0.2.0.dist-info/WHEEL +4 -0
  60. egzoscore-0.2.0.dist-info/entry_points.txt +2 -0
  61. egzoscore-0.2.0.dist-info/licenses/LICENSE +65 -0
  62. egzoscore-0.2.0.dist-info/licenses/NOTICE +6 -0
@@ -0,0 +1,524 @@
1
+ # Copyright 2026 Ali Sasanian
2
+ # SPDX-License-Identifier: LicenseRef-PolyForm-Strict-1.0.0
3
+ """sqlite backend — what `pip install` gives everyone (v0.5 §E). JSON documents in typed rows."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import json
8
+ import sqlite3
9
+ from collections.abc import Callable, Iterable, Iterator, Sequence
10
+ from contextlib import contextmanager
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ from egzos._types import (
15
+ ConfirmChallenge,
16
+ ConfirmCredential,
17
+ Registration,
18
+ StorageBusy,
19
+ ThrottleSurface,
20
+ UploadRecord,
21
+ UserGrant,
22
+ )
23
+ from egzos.backends.base import ChainConflict, refuse_nul
24
+ from egzos.model import ContextItem, Node, Token
25
+
26
+ #: How long a writer waits for the container's write lock, in seconds, before it raises
27
+ #: `StorageBusy` (storage.md §3.6): postgres's `lock_timeout`.
28
+ LOCK_TIMEOUT = 10.0
29
+
30
+ _SCHEMA = """
31
+ CREATE TABLE IF NOT EXISTS nodes (
32
+ id TEXT PRIMARY KEY, type TEXT NOT NULL, name TEXT NOT NULL, parent TEXT, doc TEXT NOT NULL);
33
+ CREATE INDEX IF NOT EXISTS nodes_parent ON nodes(parent);
34
+ CREATE TABLE IF NOT EXISTS items (
35
+ id TEXT PRIMARY KEY, kind TEXT NOT NULL, scope TEXT NOT NULL, key TEXT, status TEXT NOT NULL,
36
+ tombstoned INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, doc TEXT NOT NULL);
37
+ CREATE INDEX IF NOT EXISTS items_scope ON items(scope);
38
+ CREATE INDEX IF NOT EXISTS items_kind_key ON items(kind, key);
39
+ CREATE TABLE IF NOT EXISTS audit (
40
+ seq INTEGER PRIMARY KEY AUTOINCREMENT, ts TEXT NOT NULL, hash TEXT NOT NULL UNIQUE,
41
+ prev_hash TEXT NOT NULL, doc TEXT NOT NULL);
42
+ -- One successor per entry: two writers (the CLI and `serve --mcp` are separate processes) that read
43
+ -- the same head cannot both append after it; the loser re-reads and re-chains (Ledger.append).
44
+ CREATE UNIQUE INDEX IF NOT EXISTS audit_prev_hash ON audit(prev_hash);
45
+ CREATE TABLE IF NOT EXISTS tokens (id TEXT PRIMARY KEY, doc TEXT NOT NULL);
46
+ CREATE TABLE IF NOT EXISTS proposals (id TEXT PRIMARY KEY, status TEXT NOT NULL, doc TEXT NOT NULL);
47
+ -- append-only is a PROPERTY of the design (a3-ledger charter): no update or delete path exists.
48
+ CREATE TRIGGER IF NOT EXISTS audit_no_update BEFORE UPDATE ON audit
49
+ BEGIN SELECT RAISE(ABORT, 'audit is append-only'); END;
50
+ CREATE TRIGGER IF NOT EXISTS audit_no_delete BEFORE DELETE ON audit
51
+ BEGIN SELECT RAISE(ABORT, 'audit is append-only'); END;
52
+ -- The retired authorization server's tables (identity.md §9): never written, since the AS was
53
+ -- never mounted, and dropped from a file made before their removal.
54
+ DROP TABLE IF EXISTS as_sessions;
55
+ DROP TABLE IF EXISTS as_throttle;
56
+ DROP TABLE IF EXISTS as_clients;
57
+ DROP TABLE IF EXISTS as_codes;
58
+ DROP TABLE IF EXISTS as_decided;
59
+ DROP TABLE IF EXISTS as_devices;
60
+ DROP TABLE IF EXISTS as_refresh;
61
+ -- ThrottleState (storage.md §3.1): the door's throttle counters, on this same substrate and
62
+ -- connection as ContainerState, never process memory, so a restart lifts no throttle.
63
+ CREATE TABLE IF NOT EXISTS throttle (
64
+ surface TEXT NOT NULL, bucket_key TEXT NOT NULL, window_key TEXT NOT NULL,
65
+ count INTEGER NOT NULL, PRIMARY KEY (surface, bucket_key, window_key));
66
+ -- IdentityState and ConfigState (storage.md §3.2): identity.md §4's grants and registrations,
67
+ -- and container.md §8's settings. No column holds a credential: a grant names a provider user id.
68
+ CREATE TABLE IF NOT EXISTS user_grants (sub TEXT PRIMARY KEY, doc TEXT NOT NULL);
69
+ CREATE TABLE IF NOT EXISTS agent_registrations (
70
+ client_id TEXT NOT NULL, sub TEXT NOT NULL, doc TEXT NOT NULL, PRIMARY KEY (client_id, sub));
71
+ CREATE TABLE IF NOT EXISTS config (key TEXT PRIMARY KEY, value TEXT NOT NULL);
72
+ -- ConfirmState (storage.md §3.3): the confirm's challenges, spent once.
73
+ CREATE TABLE IF NOT EXISTS challenges (
74
+ id TEXT PRIMARY KEY, spent INTEGER NOT NULL DEFAULT 0, expires_at TEXT NOT NULL,
75
+ doc TEXT NOT NULL);
76
+ CREATE INDEX IF NOT EXISTS challenges_expiry ON challenges(expires_at);
77
+ CREATE TABLE IF NOT EXISTS credentials (
78
+ id TEXT PRIMARY KEY, person TEXT NOT NULL, doc TEXT NOT NULL);
79
+ CREATE INDEX IF NOT EXISTS credentials_person ON credentials(person);
80
+ -- UploadState (storage.md §3.4): rest.md §4.4's uploads, each step spent once.
81
+ CREATE TABLE IF NOT EXISTS uploads (
82
+ id TEXT PRIMARY KEY, principal TEXT NOT NULL, bytes_spent INTEGER NOT NULL DEFAULT 0,
83
+ item_spent INTEGER NOT NULL DEFAULT 0, doc TEXT NOT NULL);
84
+ CREATE INDEX IF NOT EXISTS uploads_principal ON uploads(principal);
85
+ -- GrantState (storage.md §3.5): rest.md §6's spent grants, by the sha256 of their sig.
86
+ CREATE TABLE IF NOT EXISTS spent_grants (sig_hash TEXT PRIMARY KEY, expires_at TEXT NOT NULL);
87
+ """
88
+
89
+
90
+ class SqliteBackend:
91
+ def __init__(self, path: Path):
92
+ self.path = Path(path)
93
+ self.path.parent.mkdir(parents=True, exist_ok=True)
94
+ # One connection, shared: safe while every caller runs on one thread at a time — the CLI,
95
+ # and the lifeboat, whose handlers are all `async def` on the event loop (its test client's
96
+ # portal included). A sync handler would run in Starlette's threadpool; add a lock here
97
+ # before writing one. Writers in other processes are serialised by sqlite itself, and the
98
+ # chain by its unique prev_hash.
99
+ self.db = sqlite3.connect(str(self.path), check_same_thread=False, timeout=LOCK_TIMEOUT)
100
+ self.db.execute("PRAGMA journal_mode=WAL")
101
+ self.db.execute("PRAGMA foreign_keys=ON")
102
+ self.db.executescript(_SCHEMA)
103
+ self._depth = 0 # > 0 inside atomic(): writes wait for its one commit
104
+ self._after: list[Callable[[], object]] = [] # what waits for that commit
105
+
106
+ @contextmanager
107
+ def atomic(self):
108
+ """Every write inside lands together or not at all. BEGIN IMMEDIATE takes the write lock
109
+ up front, so no other process can move the chain head mid-act. Not taken within
110
+ `LOCK_TIMEOUT`, it raises `StorageBusy`, and nothing was written (storage.md §3.6)."""
111
+ if self._depth == 0:
112
+ if self.db.in_transaction:
113
+ # Every write here takes this block, so only a caller of `db` leaves one open. Let
114
+ # it go, so the block holds the lock from its start (GHSA-m955-fr24-frwq).
115
+ self.db.rollback()
116
+ try:
117
+ self.db.execute("BEGIN IMMEDIATE")
118
+ except sqlite3.OperationalError as e:
119
+ if e.sqlite_errorcode & 0xFF != sqlite3.SQLITE_BUSY: # and its extended codes
120
+ raise
121
+ raise StorageBusy("the container's write lock was not taken in time") from e
122
+ self._depth += 1
123
+ try:
124
+ yield
125
+ except BaseException:
126
+ self._depth -= 1
127
+ if self._depth == 0:
128
+ self._after.clear() # dropped with the writes it waited for
129
+ self.db.rollback()
130
+ raise
131
+ self._depth -= 1
132
+ if self._depth == 0:
133
+ queued, self._after = self._after, [] # a COMMIT that raises drops them
134
+ self.db.commit()
135
+ for fn in queued:
136
+ fn()
137
+
138
+ def after_commit(self, fn: Callable[[], object]) -> None:
139
+ """Run `fn` once the outermost block commits, after the COMMIT and with no block open, in
140
+ the order queued; never if that block rolls back or its COMMIT fails. A nested block joins
141
+ the outer one, and outside any block `fn` runs at once (storage.md §3.6)."""
142
+ if self._depth:
143
+ self._after.append(fn)
144
+ else:
145
+ fn()
146
+
147
+ def _write(self, sql: str, args: Sequence[Any] = ()) -> sqlite3.Cursor:
148
+ """One write under the lock: inside a block it joins it, outside it commits alone."""
149
+ with self.atomic():
150
+ return self.db.execute(sql, args)
151
+
152
+ # -- nodes --------------------------------------------------------------------------
153
+ def put_node(self, node: Node) -> None:
154
+ refuse_nul(node.id, node.type, node.name, node.parent)
155
+ self._write(
156
+ "INSERT OR REPLACE INTO nodes(id,type,name,parent,doc) VALUES(?,?,?,?,?)",
157
+ (node.id, node.type, node.name, node.parent, json.dumps(node.to_dict())),
158
+ )
159
+
160
+ def get_node(self, node_id: str) -> Node | None:
161
+ refuse_nul(node_id)
162
+ row = self.db.execute("SELECT doc FROM nodes WHERE id=?", (node_id,)).fetchone()
163
+ return Node.from_dict(json.loads(row[0])) if row else None
164
+
165
+ def list_nodes(self, parent: str | None = None, type: str | None = None) -> list[Node]:
166
+ refuse_nul(parent, type)
167
+ sql, args = "SELECT doc FROM nodes WHERE 1=1", []
168
+ if parent is not None:
169
+ sql += " AND parent=?"
170
+ args.append(parent)
171
+ if type is not None:
172
+ sql += " AND type=?"
173
+ args.append(type)
174
+ return [
175
+ Node.from_dict(json.loads(r[0])) for r in self.db.execute(sql + " ORDER BY rowid", args)
176
+ ]
177
+
178
+ def find_root(self, type: str) -> Node | None:
179
+ refuse_nul(type)
180
+ row = self.db.execute(
181
+ "SELECT doc FROM nodes WHERE type=? AND parent IS NULL", (type,)
182
+ ).fetchone()
183
+ return Node.from_dict(json.loads(row[0])) if row else None
184
+
185
+ # -- items --------------------------------------------------------------------------
186
+ def put(self, item: ContextItem) -> None:
187
+ created_at = item.lifecycle.get("created_at", "")
188
+ refuse_nul(item.id, item.kind, item.scope, item.key, item.status, created_at)
189
+ self._write(
190
+ "INSERT OR REPLACE INTO items(id,kind,scope,key,status,tombstoned,created_at,doc) "
191
+ "VALUES(?,?,?,?,?,?,?,?)",
192
+ (
193
+ item.id,
194
+ item.kind,
195
+ item.scope,
196
+ item.key,
197
+ item.status,
198
+ 1 if item.lifecycle.get("tombstoned") else 0,
199
+ created_at,
200
+ json.dumps(item.to_dict()),
201
+ ),
202
+ )
203
+
204
+ def get(self, item_id: str) -> ContextItem | None:
205
+ refuse_nul(item_id)
206
+ row = self.db.execute(
207
+ "SELECT doc FROM items WHERE id=? AND tombstoned=0", (item_id,)
208
+ ).fetchone()
209
+ return ContextItem.from_dict(json.loads(row[0])) if row else None
210
+
211
+ def query(
212
+ self,
213
+ scopes: Iterable[str],
214
+ *,
215
+ kinds: Iterable[str] | None = None,
216
+ key: str | None = None,
217
+ statuses: Iterable[str] | None = None,
218
+ text: str | None = None,
219
+ include_tombstoned: bool = False,
220
+ ) -> list[ContextItem]:
221
+ scopes = list(scopes)
222
+ refuse_nul(scopes, key)
223
+ if not scopes:
224
+ return []
225
+ sql = f"SELECT doc FROM items WHERE scope IN ({','.join('?' * len(scopes))})"
226
+ args: list[Any] = list(scopes)
227
+ if not include_tombstoned:
228
+ sql += " AND tombstoned=0"
229
+ if kinds:
230
+ kinds = list(kinds)
231
+ refuse_nul(kinds)
232
+ sql += f" AND kind IN ({','.join('?' * len(kinds))})"
233
+ args += kinds
234
+ if key is not None:
235
+ sql += " AND key=?"
236
+ args.append(key)
237
+ if statuses:
238
+ statuses = list(statuses)
239
+ refuse_nul(statuses)
240
+ sql += f" AND status IN ({','.join('?' * len(statuses))})"
241
+ args += statuses
242
+ if text:
243
+ sql += " AND doc LIKE ?"
244
+ args.append(f"%{text}%") # SKELETON: substring; embeddings later
245
+ sql += " ORDER BY created_at DESC, id DESC" # same-second items by id (storage.md §2)
246
+ return [ContextItem.from_dict(json.loads(r[0])) for r in self.db.execute(sql, args)]
247
+
248
+ def tombstone(self, item_id: str) -> bool:
249
+ refuse_nul(item_id)
250
+ item = self.get(item_id)
251
+ if not item:
252
+ return False
253
+ item.lifecycle["tombstoned"] = True
254
+ self.put(item)
255
+ return True
256
+
257
+ # -- audit --------------------------------------------------------------------------
258
+ def audit_append(self, entry: dict[str, Any]) -> dict[str, Any]:
259
+ refuse_nul(entry["ts"], entry["hash"], entry["prev_hash"])
260
+ try: # alone, its block rolls back; inside a block the whole act unwinds, not just this
261
+ cur = self._write(
262
+ "INSERT INTO audit(ts,hash,prev_hash,doc) VALUES(?,?,?,?)",
263
+ (entry["ts"], entry["hash"], entry["prev_hash"], json.dumps(entry)),
264
+ )
265
+ except sqlite3.IntegrityError as e:
266
+ raise ChainConflict(str(e)) from e
267
+ return {**entry, "seq": cur.lastrowid}
268
+
269
+ def audit_last(self) -> dict[str, Any] | None:
270
+ row = self.db.execute("SELECT seq, doc FROM audit ORDER BY seq DESC LIMIT 1").fetchone()
271
+ return {**json.loads(row[1]), "seq": row[0]} if row else None
272
+
273
+ def audit_iter(self) -> Iterator[dict[str, Any]]:
274
+ for seq, doc in self.db.execute("SELECT seq, doc FROM audit ORDER BY seq ASC"):
275
+ yield {**json.loads(doc), "seq": seq}
276
+
277
+ def audit_tail(self, n: int) -> list[dict[str, Any]]:
278
+ rows = self.db.execute(
279
+ "SELECT seq, doc FROM audit ORDER BY seq DESC LIMIT ?", (n,)
280
+ ).fetchall()
281
+ return [{**json.loads(doc), "seq": seq} for seq, doc in reversed(rows)]
282
+
283
+ # -- tokens -------------------------------------------------------------------------
284
+ def put_token(self, token: Token) -> None:
285
+ refuse_nul(token.id)
286
+ self._write(
287
+ "INSERT OR REPLACE INTO tokens(id,doc) VALUES(?,?)",
288
+ (token.id, json.dumps(token.to_dict(with_secret_hash=True))),
289
+ )
290
+
291
+ def get_token(self, token_id: str) -> Token | None:
292
+ refuse_nul(token_id)
293
+ row = self.db.execute("SELECT doc FROM tokens WHERE id=?", (token_id,)).fetchone()
294
+ return Token.from_dict(json.loads(row[0])) if row else None
295
+
296
+ def list_tokens(self) -> list[Token]:
297
+ return [
298
+ Token.from_dict(json.loads(r[0]))
299
+ for r in self.db.execute("SELECT doc FROM tokens ORDER BY rowid")
300
+ ]
301
+
302
+ # -- proposals ----------------------------------------------------------------------
303
+ def put_proposal(self, proposal: dict[str, Any]) -> None:
304
+ refuse_nul(proposal["id"], proposal["status"])
305
+ self._write(
306
+ "INSERT OR REPLACE INTO proposals(id,status,doc) VALUES(?,?,?)",
307
+ (proposal["id"], proposal["status"], json.dumps(proposal)),
308
+ )
309
+
310
+ def get_proposal(self, proposal_id: str) -> dict[str, Any] | None:
311
+ refuse_nul(proposal_id)
312
+ row = self.db.execute("SELECT doc FROM proposals WHERE id=?", (proposal_id,)).fetchone()
313
+ return json.loads(row[0]) if row else None
314
+
315
+ def list_proposals(self, status: str | None = None) -> list[dict[str, Any]]:
316
+ refuse_nul(status)
317
+ if status:
318
+ rows = self.db.execute(
319
+ "SELECT doc FROM proposals WHERE status=? ORDER BY rowid", (status,)
320
+ )
321
+ else:
322
+ rows = self.db.execute("SELECT doc FROM proposals ORDER BY rowid")
323
+ return [json.loads(r[0]) for r in rows]
324
+
325
+ # -- ThrottleState (storage.md §3.1) ----------------------------------------------------
326
+ # The door's throttle counters, on this file and this connection, never process memory (the
327
+ # Chief on #173, option (A)).
328
+ def throttle_incr(self, surface: ThrottleSurface, bucket_key: str, window_key: str) -> int:
329
+ """Increments and returns the new count, atomically: of two concurrent callers on the
330
+ same key, each observes its own correctly incremented total, never the other's. Names no
331
+ rate and no window length (Trust's, #141); the three keys are compared as opaque values."""
332
+ refuse_nul(surface, bucket_key, window_key)
333
+ with self.atomic():
334
+ self.db.execute(
335
+ "INSERT INTO throttle(surface,bucket_key,window_key,count) VALUES(?,?,?,1) "
336
+ "ON CONFLICT(surface,bucket_key,window_key) DO UPDATE SET count=count+1",
337
+ (surface, bucket_key, window_key),
338
+ )
339
+ row = self.db.execute(
340
+ "SELECT count FROM throttle WHERE surface=? AND bucket_key=? AND window_key=?",
341
+ (surface, bucket_key, window_key),
342
+ ).fetchone()
343
+ return row[0]
344
+
345
+ def throttle_count(self, surface: ThrottleSurface, bucket_key: str, window_key: str) -> int:
346
+ refuse_nul(surface, bucket_key, window_key)
347
+ row = self.db.execute(
348
+ "SELECT count FROM throttle WHERE surface=? AND bucket_key=? AND window_key=?",
349
+ (surface, bucket_key, window_key),
350
+ ).fetchone()
351
+ return row[0] if row else 0
352
+
353
+ def throttle_buckets(self, surface: ThrottleSurface, window_key: str) -> list[tuple[str, int]]:
354
+ refuse_nul(surface, window_key)
355
+ rows = self.db.execute(
356
+ "SELECT bucket_key, count FROM throttle WHERE surface=? AND window_key=? "
357
+ "ORDER BY bucket_key",
358
+ (surface, window_key),
359
+ )
360
+ return [(k, n) for k, n in rows]
361
+
362
+ def throttle_windows(self, surface: ThrottleSurface) -> list[str]:
363
+ refuse_nul(surface)
364
+ rows = self.db.execute(
365
+ "SELECT DISTINCT window_key FROM throttle WHERE surface=? ORDER BY window_key",
366
+ (surface,),
367
+ )
368
+ return [r[0] for r in rows]
369
+
370
+ def throttle_forget(self, surface: ThrottleSurface, window_key: str) -> None:
371
+ refuse_nul(surface, window_key)
372
+ self._write("DELETE FROM throttle WHERE surface=? AND window_key=?", (surface, window_key))
373
+
374
+ # -- IdentityState (storage.md §3.2) -----------------------------------------------------
375
+ def put_user_grant(self, grant: UserGrant) -> None:
376
+ refuse_nul(grant["sub"])
377
+ self._write(
378
+ "INSERT OR REPLACE INTO user_grants(sub,doc) VALUES(?,?)",
379
+ (grant["sub"], json.dumps(grant)),
380
+ )
381
+
382
+ def get_user_grant(self, sub: str) -> UserGrant | None:
383
+ refuse_nul(sub)
384
+ row = self.db.execute("SELECT doc FROM user_grants WHERE sub=?", (sub,)).fetchone()
385
+ return json.loads(row[0]) if row else None
386
+
387
+ def list_user_grants(self) -> list[UserGrant]:
388
+ rows = self.db.execute("SELECT doc FROM user_grants ORDER BY rowid")
389
+ return [json.loads(r[0]) for r in rows]
390
+
391
+ def put_agent_registration(self, registration: Registration) -> None:
392
+ refuse_nul(registration["client_id"], registration["sub"])
393
+ self._write(
394
+ "INSERT OR REPLACE INTO agent_registrations(client_id,sub,doc) VALUES(?,?,?)",
395
+ (registration["client_id"], registration["sub"], json.dumps(registration)),
396
+ )
397
+
398
+ def get_agent_registration(self, client_id: str, sub: str) -> Registration | None:
399
+ refuse_nul(client_id, sub)
400
+ row = self.db.execute(
401
+ "SELECT doc FROM agent_registrations WHERE client_id=? AND sub=?", (client_id, sub)
402
+ ).fetchone()
403
+ return json.loads(row[0]) if row else None
404
+
405
+ def list_agent_registrations(self, client_id: str | None = None) -> list[Registration]:
406
+ refuse_nul(client_id)
407
+ if client_id is None:
408
+ rows = self.db.execute("SELECT doc FROM agent_registrations ORDER BY rowid")
409
+ else:
410
+ rows = self.db.execute(
411
+ "SELECT doc FROM agent_registrations WHERE client_id=? ORDER BY rowid", (client_id,)
412
+ )
413
+ return [json.loads(r[0]) for r in rows]
414
+
415
+ # -- ConfigState (storage.md §3.2) -------------------------------------------------------
416
+ def get_config(self) -> dict[str, Any]:
417
+ return {k: json.loads(v) for k, v in self.db.execute("SELECT key, value FROM config")}
418
+
419
+ def put_config(self, key: str, value: Any) -> None:
420
+ refuse_nul(key)
421
+ self._write(
422
+ "INSERT OR REPLACE INTO config(key,value) VALUES(?,?)", (key, json.dumps(value))
423
+ )
424
+
425
+ # -- ConfirmState (storage.md §3.3) ------------------------------------------------------
426
+ def put_challenge(self, challenge: ConfirmChallenge) -> None:
427
+ refuse_nul(challenge["id"], challenge["expires_at"])
428
+ self._write(
429
+ "INSERT INTO challenges(id,spent,expires_at,doc) VALUES(?,0,?,?)",
430
+ (challenge["id"], challenge["expires_at"], json.dumps(challenge)),
431
+ )
432
+
433
+ def forget_challenges(self, expired_before: str) -> None:
434
+ refuse_nul(expired_before)
435
+ self._write("DELETE FROM challenges WHERE expires_at < ?", (expired_before,))
436
+
437
+ def spend_challenge(self, challenge_id: str) -> ConfirmChallenge | None:
438
+ """Mark it spent and return it as it stood: of two concurrent spends, one sees it fresh."""
439
+ refuse_nul(challenge_id)
440
+ with self.atomic():
441
+ row = self.db.execute(
442
+ "SELECT spent, doc FROM challenges WHERE id=?", (challenge_id,)
443
+ ).fetchone()
444
+ if row is None:
445
+ return None
446
+ self.db.execute("UPDATE challenges SET spent=1 WHERE id=?", (challenge_id,))
447
+ return {**json.loads(row[1]), "spent": bool(row[0])}
448
+
449
+ def put_credential(self, credential: ConfirmCredential) -> None:
450
+ refuse_nul(credential["id"], credential["person"])
451
+ self._write(
452
+ "INSERT OR REPLACE INTO credentials(id,person,doc) VALUES(?,?,?)",
453
+ (credential["id"], credential["person"], json.dumps(credential)),
454
+ )
455
+
456
+ def get_credential(self, credential_id: str) -> ConfirmCredential | None:
457
+ refuse_nul(credential_id)
458
+ row = self.db.execute(
459
+ "SELECT doc FROM credentials WHERE id=?", (credential_id,)
460
+ ).fetchone()
461
+ return json.loads(row[0]) if row else None
462
+
463
+ def list_credentials(self, person: str | None = None) -> list[ConfirmCredential]:
464
+ refuse_nul(person)
465
+ if person is None:
466
+ rows = self.db.execute("SELECT doc FROM credentials ORDER BY rowid")
467
+ else:
468
+ rows = self.db.execute(
469
+ "SELECT doc FROM credentials WHERE person=? ORDER BY rowid", (person,)
470
+ )
471
+ return [json.loads(r[0]) for r in rows]
472
+
473
+ # -- UploadState (storage.md §3.4) -------------------------------------------------------
474
+ def put_upload(self, upload: UploadRecord) -> None:
475
+ refuse_nul(upload["id"], upload["principal"])
476
+ with self.atomic():
477
+ cur = self.db.execute(
478
+ "UPDATE uploads SET doc=? WHERE id=?", (json.dumps(upload), upload["id"])
479
+ )
480
+ if cur.rowcount == 0:
481
+ self.db.execute(
482
+ "INSERT INTO uploads(id,principal,doc) VALUES(?,?,?)",
483
+ (upload["id"], upload["principal"], json.dumps(upload)),
484
+ )
485
+
486
+ def get_upload(self, upload_id: str) -> UploadRecord | None:
487
+ refuse_nul(upload_id)
488
+ row = self.db.execute("SELECT doc FROM uploads WHERE id=?", (upload_id,)).fetchone()
489
+ return json.loads(row[0]) if row else None
490
+
491
+ def list_uploads(self, principal: str | None = None) -> list[UploadRecord]:
492
+ refuse_nul(principal)
493
+ if principal is None:
494
+ rows = self.db.execute("SELECT doc FROM uploads ORDER BY rowid")
495
+ else:
496
+ rows = self.db.execute(
497
+ "SELECT doc FROM uploads WHERE principal=? ORDER BY rowid", (principal,)
498
+ )
499
+ return [json.loads(r[0]) for r in rows]
500
+
501
+ def spend_upload(self, upload_id: str, step: str) -> bool:
502
+ refuse_nul(upload_id)
503
+ column = {"bytes": "bytes_spent", "item": "item_spent"}[step]
504
+ cur = self._write(
505
+ f"UPDATE uploads SET {column}=1 WHERE id=? AND {column}=0", (upload_id,) # noqa: S608
506
+ )
507
+ return cur.rowcount == 1
508
+
509
+ # -- GrantState (storage.md §3.5) --------------------------------------------------------
510
+ def spend_grant(self, sig_hash: str, expires_at: str) -> bool:
511
+ """Record a spend, committed at once: of two concurrent spends of one grant, exactly one
512
+ inserts. Refused inside `atomic()` or any open transaction, whose rollback would undo it."""
513
+ refuse_nul(sig_hash, expires_at)
514
+ if self._depth or self.db.in_transaction:
515
+ raise RuntimeError("a grant is spent outside any transaction")
516
+ cur = self._write(
517
+ "INSERT OR IGNORE INTO spent_grants(sig_hash,expires_at) VALUES(?,?)",
518
+ (sig_hash, expires_at),
519
+ )
520
+ return cur.rowcount == 1
521
+
522
+ def forget_grants(self, expired_before: str) -> None:
523
+ refuse_nul(expired_before)
524
+ self._write("DELETE FROM spent_grants WHERE expires_at < ?", (expired_before,))