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
egzos/authz/values.py ADDED
@@ -0,0 +1,32 @@
1
+ # Copyright 2026 Ali Sasanian
2
+ # SPDX-License-Identifier: LicenseRef-PolyForm-Strict-1.0.0
3
+ """
4
+ The two value helpers the container's own credentials share: `digest`, the one hash behind
5
+ `Token.secret_hash`, and `same`, the one constant-time comparison. They outlived the retired
6
+ authorization server (`identity.md` §9), whose issued values and user codes went with it.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import hmac
13
+
14
+
15
+ def digest(value: str) -> str:
16
+ """The lowercase hex sha256 of the whole value: the one hash behind `Token.secret_hash`.
17
+ `auth.py` imports it rather than keeping a copy, so no second lookup can drift from it."""
18
+ # `surrogatepass`: a lone surrogate from a JSON body hashes like any other string, never raises
19
+ return hashlib.sha256(value.encode("utf-8", "surrogatepass")).hexdigest()
20
+
21
+
22
+ def same(given: object, stored: object) -> bool:
23
+ """Constant-time equality for stored strings: a digest, the tap's path value.
24
+ Anything but two `str`s is unequal. `hmac.compare_digest` raises on a non-ASCII `str` and
25
+ `encode` on a lone surrogate, and a raise would be a second answer shape beside the refusal,
26
+ so both sides compare as bytes. The one helper every such comparison goes through."""
27
+ if not isinstance(given, str) or not isinstance(stored, str):
28
+ return False
29
+ return hmac.compare_digest(
30
+ given.encode("utf-8", "surrogatepass"), stored.encode("utf-8", "surrogatepass")
31
+ )
32
+
@@ -0,0 +1,8 @@
1
+ # Copyright 2026 Ali Sasanian
2
+ # SPDX-License-Identifier: LicenseRef-PolyForm-Strict-1.0.0
3
+ """Pluggable persistence behind the backend contract (v0.3 §8). sqlite is the default."""
4
+
5
+ from egzos.backends.base import Backend
6
+ from egzos.backends.sqlite import SqliteBackend
7
+
8
+ __all__ = ["Backend", "SqliteBackend"]
egzos/backends/base.py ADDED
@@ -0,0 +1,91 @@
1
+ # Copyright 2026 Ali Sasanian
2
+ # SPDX-License-Identifier: LicenseRef-PolyForm-Strict-1.0.0
3
+ """
4
+ The backend contract, skeleton edition (v0.3 §8): put / get / query / tombstone / audit_append.
5
+ The backend returns candidates; the resolver applies precedence, trust and key-override.
6
+
7
+ This Protocol is the UNION the skeleton needed to run. The freeze splits it (Chief, 2026-09-21,
8
+ F3) into two contracts: ItemStore — put / get / query / tombstone, pluggable and delegable
9
+ (sqlite → postgres → mem0/zep) — and ContainerState — nodes, tokens, proposals and the audit
10
+ chain, sqlite by default, postgres at Phase 5, NEVER delegated to a third-party store. Blobs are
11
+ a third seam already: the blob store sits inside the store module (v0.5 §D, R5).
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from collections.abc import Iterable, Iterator
17
+ from contextlib import AbstractContextManager
18
+ from typing import Any, Protocol
19
+
20
+ # Declared in the shared types (storage.md §3.6) and exported here too, so the ledger's and the
21
+ # sqlite backend's `from egzos.backends.base import ChainConflict` stay as they are.
22
+ from egzos._types import ChainConflict as ChainConflict
23
+ from egzos.model import ContextItem, Node, Token
24
+
25
+
26
+ def holds_nul(value: Any) -> bool:
27
+ """Whether a string in `value`, a key or an item at any depth, holds U+0000: no store keeps
28
+ one outside a document (storage.md §3.7), so every door refuses it first (rest.md §3)."""
29
+ stack = [value] # walked, not recursed, so no depth of nesting raises
30
+ while stack:
31
+ v = stack.pop()
32
+ if isinstance(v, str):
33
+ if "\0" in v:
34
+ return True
35
+ elif isinstance(v, dict):
36
+ stack.extend(v.keys())
37
+ stack.extend(v.values())
38
+ elif isinstance(v, (list, tuple)):
39
+ stack.extend(v)
40
+ return False
41
+
42
+
43
+ def refuse_nul(*values: Any) -> None:
44
+ """storage.md §3.7: a value a backend stores or matches by, outside a document, is refused
45
+ before any write when it holds U+0000, on every backend alike."""
46
+ if holds_nul(values):
47
+ raise ValueError("U+0000 is kept only inside a document")
48
+
49
+
50
+ class Backend(Protocol):
51
+ # A human-only act's writes (moves, the proposal's status, the chain) land together or not at
52
+ # all: a failure mid-act leaves nothing half-done for "Nothing changed" to misreport.
53
+ def atomic(self) -> AbstractContextManager[None]: ...
54
+
55
+ # nodes
56
+ def put_node(self, node: Node) -> None: ...
57
+ def get_node(self, node_id: str) -> Node | None: ...
58
+ def list_nodes(self, parent: str | None = None, type: str | None = None) -> list[Node]: ...
59
+ def find_root(self, type: str) -> Node | None: ...
60
+
61
+ # items
62
+ def put(self, item: ContextItem) -> None: ...
63
+ def get(self, item_id: str) -> ContextItem | None: ...
64
+ def query(
65
+ self,
66
+ scopes: Iterable[str],
67
+ *,
68
+ kinds: Iterable[str] | None = None,
69
+ key: str | None = None,
70
+ statuses: Iterable[str] | None = None,
71
+ text: str | None = None,
72
+ include_tombstoned: bool = False,
73
+ ) -> list[ContextItem]: ...
74
+ def tombstone(self, item_id: str) -> bool: ...
75
+
76
+ # audit (append-only; the ledger computes the chain, the backend only appends). A second
77
+ # append after the same `prev_hash` raises ChainConflict, so the chain cannot fork.
78
+ def audit_append(self, entry: dict[str, Any]) -> dict[str, Any]: ...
79
+ def audit_last(self) -> dict[str, Any] | None: ...
80
+ def audit_iter(self) -> Iterator[dict[str, Any]]: ...
81
+ def audit_tail(self, n: int) -> list[dict[str, Any]]: ...
82
+
83
+ # tokens
84
+ def put_token(self, token: Token) -> None: ...
85
+ def get_token(self, token_id: str) -> Token | None: ...
86
+ def list_tokens(self) -> list[Token]: ...
87
+
88
+ # pending proposals (cross-audience moves, staged artifacts)
89
+ def put_proposal(self, proposal: dict[str, Any]) -> None: ...
90
+ def get_proposal(self, proposal_id: str) -> dict[str, Any] | None: ...
91
+ def list_proposals(self, status: str | None = None) -> list[dict[str, Any]]: ...
@@ -0,0 +1,490 @@
1
+ # Copyright 2026 Ali Sasanian
2
+ # SPDX-License-Identifier: LicenseRef-PolyForm-Strict-1.0.0
3
+ """postgres backend — a container's own database (storage.md §1's reading of [0.3 · 5], §3.6,
4
+ §3.7; v0.7 §AF). The sqlite backend is the reference: each method does what its sqlite twin does,
5
+ its order, ties and quirks included, so the harness under `tests/store/` runs both alike.
6
+
7
+ psycopg 3 is the `postgres` extra's, and only this module imports it. One synchronous connection
8
+ per instance (v0.7 §AF), in autocommit outside `atomic()`. `SCHEMA` is applied by
9
+ `apply_schema`, as the role that owns the tables, from outside the container: this class never
10
+ creates or alters a table, and the role it connects as owns none (§3.7)."""
11
+
12
+ from __future__ import annotations
13
+
14
+ import hashlib
15
+ import json
16
+ from collections.abc import Callable, Iterable, Iterator, Sequence
17
+ from contextlib import contextmanager
18
+ from typing import Any
19
+
20
+ import psycopg
21
+ from psycopg import errors, pq
22
+ from psycopg.sql import SQL, Identifier
23
+
24
+ from egzos._types import (
25
+ ConfirmChallenge,
26
+ ConfirmCredential,
27
+ Registration,
28
+ StorageBusy,
29
+ ThrottleSurface,
30
+ UploadRecord,
31
+ UserGrant,
32
+ )
33
+ from egzos.backends.base import ChainConflict, refuse_nul
34
+ from egzos.model import ContextItem, Node, Token
35
+
36
+ #: How long a writer waits for the container's write lock before it raises `StorageBusy`
37
+ #: (storage.md §3.6): sqlite's busy timeout.
38
+ LOCK_TIMEOUT = "10s"
39
+
40
+ #: storage.md §3.7. Documents are the JSON text the backend wrote, never `jsonb`. `write_order`
41
+ #: is sqlite's rowid: a replaced record moves to the end of its list. Columns that are ordered,
42
+ #: ranged or matched are `COLLATE "C"`, byte-wise as sqlite's BINARY, so ILIKE folds ASCII alone.
43
+ SCHEMA = """
44
+ CREATE SCHEMA {schema};
45
+ SET LOCAL search_path TO {schema};
46
+ CREATE SEQUENCE write_order;
47
+ CREATE TABLE nodes (id text PRIMARY KEY, type text NOT NULL, name text NOT NULL, parent text,
48
+ doc text NOT NULL, write_order bigint NOT NULL DEFAULT nextval('write_order'));
49
+ CREATE INDEX nodes_parent ON nodes (parent);
50
+ CREATE TABLE items (
51
+ id text COLLATE "C" PRIMARY KEY, kind text NOT NULL, scope text NOT NULL, key text,
52
+ status text NOT NULL, tombstoned boolean NOT NULL, created_at text COLLATE "C" NOT NULL,
53
+ doc text COLLATE "C" NOT NULL, write_order bigint NOT NULL DEFAULT nextval('write_order'));
54
+ CREATE INDEX items_scope ON items (scope);
55
+ CREATE INDEX items_kind_key ON items (kind, key);
56
+ -- seq is the head's plus one, under the write lock, never a sequence's (events.md §2); one
57
+ -- successor per entry (storage.md §3.6).
58
+ CREATE TABLE audit (seq bigint PRIMARY KEY, ts text NOT NULL, hash text NOT NULL UNIQUE,
59
+ prev_hash text NOT NULL UNIQUE, doc text NOT NULL);
60
+ -- Append-only twice (events.md §4 item 1): this trigger, which refuses every role, and the
61
+ -- grants below, since the tables' owner can set a trigger aside.
62
+ CREATE FUNCTION audit_refuse() RETURNS trigger LANGUAGE plpgsql
63
+ AS $$BEGIN RAISE EXCEPTION 'audit is append-only'; END$$;
64
+ CREATE TRIGGER audit_append_only BEFORE UPDATE OR DELETE OR TRUNCATE ON audit
65
+ FOR EACH STATEMENT EXECUTE FUNCTION audit_refuse();
66
+ CREATE TABLE tokens (id text PRIMARY KEY, doc text NOT NULL,
67
+ write_order bigint NOT NULL DEFAULT nextval('write_order'));
68
+ CREATE TABLE proposals (id text PRIMARY KEY, status text NOT NULL, doc text NOT NULL,
69
+ write_order bigint NOT NULL DEFAULT nextval('write_order'));
70
+ CREATE TABLE throttle (surface text NOT NULL, bucket_key text COLLATE "C" NOT NULL,
71
+ window_key text COLLATE "C" NOT NULL, count integer NOT NULL,
72
+ PRIMARY KEY (surface, bucket_key, window_key));
73
+ CREATE TABLE user_grants (sub text PRIMARY KEY, doc text NOT NULL,
74
+ write_order bigint NOT NULL DEFAULT nextval('write_order'));
75
+ CREATE TABLE agent_registrations (client_id text NOT NULL, sub text NOT NULL, doc text NOT NULL,
76
+ write_order bigint NOT NULL DEFAULT nextval('write_order'), PRIMARY KEY (client_id, sub));
77
+ CREATE TABLE config (key text PRIMARY KEY, value text NOT NULL,
78
+ write_order bigint NOT NULL DEFAULT nextval('write_order'));
79
+ CREATE TABLE challenges (id text PRIMARY KEY, spent boolean NOT NULL DEFAULT false,
80
+ expires_at text COLLATE "C" NOT NULL, doc text NOT NULL);
81
+ CREATE INDEX challenges_expiry ON challenges (expires_at);
82
+ CREATE TABLE credentials (id text PRIMARY KEY, person text NOT NULL, doc text NOT NULL,
83
+ write_order bigint NOT NULL DEFAULT nextval('write_order'));
84
+ CREATE INDEX credentials_person ON credentials (person);
85
+ CREATE TABLE uploads (id text PRIMARY KEY, principal text NOT NULL, doc text NOT NULL,
86
+ bytes_spent boolean NOT NULL DEFAULT false, item_spent boolean NOT NULL DEFAULT false,
87
+ write_order bigint NOT NULL DEFAULT nextval('write_order'));
88
+ CREATE INDEX uploads_principal ON uploads (principal);
89
+ CREATE TABLE spent_grants (sig_hash text PRIMARY KEY, expires_at text COLLATE "C" NOT NULL);
90
+ -- The container's role holds only what the methods need, and no other role holds anything here:
91
+ -- a new schema grants nothing to PUBLIC, but a new function is PUBLIC's to execute.
92
+ REVOKE ALL ON FUNCTION audit_refuse() FROM PUBLIC;
93
+ GRANT USAGE ON SCHEMA {schema} TO {role};
94
+ GRANT USAGE ON SEQUENCE write_order TO {role};
95
+ GRANT SELECT, INSERT ON audit TO {role};
96
+ GRANT SELECT, INSERT, UPDATE ON nodes, items, tokens, proposals, user_grants,
97
+ agent_registrations, config, credentials, uploads TO {role};
98
+ GRANT SELECT, INSERT, UPDATE, DELETE ON throttle, challenges TO {role};
99
+ GRANT SELECT, INSERT, DELETE ON spent_grants TO {role};
100
+ """
101
+
102
+
103
+ def apply_schema(owner: psycopg.Connection[Any], schema: str, container_role: str) -> None:
104
+ """Create `schema` as `owner`, the role that then owns its tables, and grant `container_role`
105
+ only what `PostgresBackend` needs (storage.md §3.7). Run by the operator, from outside the
106
+ container, which never holds the owner's credentials: all of it lands, or none."""
107
+ with owner.transaction():
108
+ owner.execute(SQL(SCHEMA).format(schema=Identifier(schema),
109
+ role=Identifier(container_role)))
110
+
111
+
112
+ def _upsert(table: str, keys: str, cols: str) -> str:
113
+ """sqlite's INSERT OR REPLACE: the record is replaced, and moves last in the write order."""
114
+ names = f"{keys},{cols}".split(",")
115
+ sets = ", ".join(f"{c} = excluded.{c}" for c in cols.split(","))
116
+ return (f"INSERT INTO {table} ({', '.join(names)}) VALUES ({', '.join(['%s'] * len(names))}) "
117
+ f"ON CONFLICT ({keys}) DO UPDATE SET {sets}, write_order = DEFAULT")
118
+
119
+
120
+ _PUT = {table: _upsert(table, keys, cols) for table, keys, cols in [
121
+ ("nodes", "id", "type,name,parent,doc"),
122
+ ("items", "id", "kind,scope,key,status,tombstoned,created_at,doc"),
123
+ ("tokens", "id", "doc"),
124
+ ("proposals", "id", "status,doc"),
125
+ ("user_grants", "sub", "doc"),
126
+ ("agent_registrations", "client_id,sub", "doc"),
127
+ ("config", "key", "value"),
128
+ ("credentials", "id", "person,doc"),
129
+ ]}
130
+ _PAGE = 1000 # chain entries `audit_iter` reads at a time
131
+
132
+
133
+ class PostgresBackend:
134
+ def __init__(self, conninfo: str, schema: str):
135
+ # As the sqlite backend's: one connection, used by one caller at a time. Autocommit, so a
136
+ # read outside a block is a statement of its own; every write takes the lock (atomic()).
137
+ # The connection string is the host's secret (§3.7): used here, and kept nowhere.
138
+ self.db = psycopg.connect(conninfo, autocommit=True)
139
+ self.db.execute(SQL("SET search_path TO {}").format(Identifier(schema)))
140
+ # The container's one write lock (§3.6), keyed on its database and its schema.
141
+ name = f"egzos\0{self.db.info.dbname}\0{schema}".encode()
142
+ key = int.from_bytes(hashlib.sha256(name).digest()[:8], "big", signed=True)
143
+ self._begin = (f"BEGIN ISOLATION LEVEL READ COMMITTED; SET LOCAL lock_timeout = "
144
+ f"'{LOCK_TIMEOUT}'; SELECT pg_advisory_xact_lock({key})")
145
+ self._depth = 0 # > 0 inside atomic(): writes wait for its one commit
146
+ self._after: list[Callable[[], object]] = [] # what waits for that commit
147
+
148
+ @contextmanager
149
+ def atomic(self) -> Iterator[None]:
150
+ """Every write inside lands together or not at all. The lock is taken before the block's
151
+ first read, at READ COMMITTED, so each later statement sees every earlier commit, and a
152
+ block opened inside this one joins it. A lock not taken within `LOCK_TIMEOUT` raises
153
+ `StorageBusy`, and nothing was written (storage.md §3.6)."""
154
+ if self._depth:
155
+ self._depth += 1
156
+ try:
157
+ yield
158
+ finally:
159
+ self._depth -= 1
160
+ return
161
+ if self.db.info.transaction_status != pq.TransactionStatus.IDLE:
162
+ self.db.rollback() # as sqlite's: the block holds the lock from its start
163
+ self._depth = 1
164
+ try:
165
+ self.db.execute(self._begin, prepare=False)
166
+ yield
167
+ except BaseException as e:
168
+ self.db.rollback()
169
+ if isinstance(e, errors.LockNotAvailable):
170
+ raise StorageBusy("the container's write lock was not taken in time") from e
171
+ raise
172
+ else:
173
+ self.db.commit()
174
+ finally:
175
+ self._depth = 0
176
+ queued, self._after = self._after, [] # kept only past a COMMIT that went through
177
+ for fn in queued:
178
+ fn()
179
+
180
+ def after_commit(self, fn: Callable[[], object]) -> None:
181
+ """As sqlite's: `fn` runs once the outermost block commits, with no block open, in the
182
+ order queued; never if it rolls back or its COMMIT fails; at once outside any block."""
183
+ if self._depth:
184
+ self._after.append(fn)
185
+ else:
186
+ fn()
187
+
188
+ def _write(self, query: str, args: Sequence[Any] = ()) -> psycopg.Cursor[Any]:
189
+ """One write under the lock: inside a block it joins it, outside it commits alone."""
190
+ with self.atomic():
191
+ return self.db.execute(query, args)
192
+
193
+ def _all(self, query: str, args: Sequence[Any] = ()) -> list[Any]:
194
+ return self.db.execute(query, args).fetchall()
195
+
196
+ def _get(self, table: str, **keys: str) -> Any:
197
+ where = " AND ".join(f"{k} = %s" for k in keys)
198
+ rows = self._all(f"SELECT doc FROM {table} WHERE {where}", list(keys.values()))
199
+ return json.loads(rows[0][0]) if rows else None
200
+
201
+ def _list(self, table: str, **match: str | None) -> list[Any]:
202
+ """The table's documents in write order, filtered on each column given a value."""
203
+ given = {k: v for k, v in match.items() if v is not None}
204
+ where = "".join(f" AND {k} = %s" for k in given)
205
+ query = f"SELECT doc FROM {table} WHERE true{where} ORDER BY write_order"
206
+ return [json.loads(r[0]) for r in self._all(query, list(given.values()))]
207
+
208
+ # -- nodes --------------------------------------------------------------------------
209
+ def put_node(self, node: Node) -> None:
210
+ refuse_nul(node.id, node.type, node.name, node.parent)
211
+ self._write(_PUT["nodes"],
212
+ (node.id, node.type, node.name, node.parent, json.dumps(node.to_dict())))
213
+
214
+ def get_node(self, node_id: str) -> Node | None:
215
+ refuse_nul(node_id)
216
+ doc = self._get("nodes", id=node_id)
217
+ return Node.from_dict(doc) if doc is not None else None
218
+
219
+ def list_nodes(self, parent: str | None = None, type: str | None = None) -> list[Node]:
220
+ refuse_nul(parent, type)
221
+ return [Node.from_dict(d) for d in self._list("nodes", parent=parent, type=type)]
222
+
223
+ def find_root(self, type: str) -> Node | None:
224
+ refuse_nul(type)
225
+ rows = self._all("SELECT doc FROM nodes WHERE type = %s AND parent IS NULL "
226
+ "ORDER BY write_order LIMIT 1", (type,)) # sqlite's first, by rowid
227
+ return Node.from_dict(json.loads(rows[0][0])) if rows else None
228
+
229
+ # -- items --------------------------------------------------------------------------
230
+ def put(self, item: ContextItem) -> None:
231
+ created_at = item.lifecycle.get("created_at", "")
232
+ refuse_nul(item.id, item.kind, item.scope, item.key, item.status, created_at)
233
+ self._write(_PUT["items"], (
234
+ item.id, item.kind, item.scope, item.key, item.status,
235
+ bool(item.lifecycle.get("tombstoned")), created_at, json.dumps(item.to_dict()),
236
+ ))
237
+
238
+ def get(self, item_id: str) -> ContextItem | None:
239
+ refuse_nul(item_id)
240
+ rows = self._all("SELECT doc FROM items WHERE id = %s AND NOT tombstoned", (item_id,))
241
+ return ContextItem.from_dict(json.loads(rows[0][0])) if rows else None
242
+
243
+ def query(
244
+ self,
245
+ scopes: Iterable[str],
246
+ *,
247
+ kinds: Iterable[str] | None = None,
248
+ key: str | None = None,
249
+ statuses: Iterable[str] | None = None,
250
+ text: str | None = None,
251
+ include_tombstoned: bool = False,
252
+ ) -> list[ContextItem]:
253
+ scopes = list(scopes)
254
+ refuse_nul(scopes, key)
255
+ if not scopes:
256
+ return []
257
+ sql, args = "SELECT doc FROM items WHERE scope = ANY(%s)", [scopes]
258
+ if not include_tombstoned:
259
+ sql += " AND NOT tombstoned"
260
+ if kinds:
261
+ kinds = list(kinds)
262
+ refuse_nul(kinds)
263
+ sql += " AND kind = ANY(%s)"
264
+ args.append(kinds)
265
+ if key is not None:
266
+ sql += " AND key = %s"
267
+ args.append(key)
268
+ if statuses:
269
+ statuses = list(statuses)
270
+ refuse_nul(statuses)
271
+ sql += " AND status = ANY(%s)"
272
+ args.append(statuses)
273
+ if text:
274
+ # sqlite's `doc LIKE` over the stored JSON: ASCII letters fold (COLLATE "C"), `%` and
275
+ # `_` are wildcards, `\` is literal (ESCAPE ''), and the pattern ends at a NUL.
276
+ sql += " AND doc ILIKE %s ESCAPE ''"
277
+ args.append(f"%{text}%".split("\0", 1)[0])
278
+ sql += " ORDER BY created_at DESC, id DESC" # same-second items by id (storage.md §2)
279
+ return [ContextItem.from_dict(json.loads(r[0])) for r in self._all(sql, args)]
280
+
281
+ def tombstone(self, item_id: str) -> bool:
282
+ refuse_nul(item_id)
283
+ item = self.get(item_id)
284
+ if not item:
285
+ return False
286
+ item.lifecycle["tombstoned"] = True
287
+ self.put(item)
288
+ return True
289
+
290
+ # -- audit --------------------------------------------------------------------------
291
+ def audit_append(self, entry: dict[str, Any]) -> dict[str, Any]:
292
+ # A second successor of one entry is not inserted, so no error spoils a block it runs in:
293
+ # the block goes on, as sqlite's does after a failed statement, and the ledger re-chains.
294
+ refuse_nul(entry["ts"], entry["hash"], entry["prev_hash"])
295
+ with self.atomic():
296
+ row = self.db.execute(
297
+ "INSERT INTO audit (seq, ts, hash, prev_hash, doc) "
298
+ "SELECT coalesce(max(seq), 0) + 1, %s, %s, %s, %s FROM audit "
299
+ "ON CONFLICT DO NOTHING RETURNING seq",
300
+ (entry["ts"], entry["hash"], entry["prev_hash"], json.dumps(entry)),
301
+ ).fetchone()
302
+ if row is None:
303
+ raise ChainConflict("an entry already follows that prev_hash, or is this one")
304
+ return {**entry, "seq": row[0]}
305
+
306
+ def audit_last(self) -> dict[str, Any] | None:
307
+ rows = self._all("SELECT seq, doc FROM audit ORDER BY seq DESC LIMIT 1")
308
+ return {**json.loads(rows[0][1]), "seq": rows[0][0]} if rows else None
309
+
310
+ def audit_iter(self) -> Iterator[dict[str, Any]]:
311
+ # A page at a time, so a walk of a long chain holds one page; an entry appended during
312
+ # the walk is read too, as a later reader of the tail would read it (events.md §2).
313
+ page = self._all("SELECT seq, doc FROM audit ORDER BY seq LIMIT %s", (_PAGE,))
314
+ while page:
315
+ yield from ({**json.loads(doc), "seq": seq} for seq, doc in page)
316
+ page = self._all("SELECT seq, doc FROM audit WHERE seq > %s ORDER BY seq LIMIT %s",
317
+ (page[-1][0], _PAGE))
318
+
319
+ def audit_tail(self, n: int) -> list[dict[str, Any]]:
320
+ rows = self._all("SELECT seq, doc FROM audit ORDER BY seq DESC LIMIT %s",
321
+ (n if n >= 0 else None,)) # sqlite reads a negative LIMIT as none
322
+ return [{**json.loads(doc), "seq": seq} for seq, doc in reversed(rows)]
323
+
324
+ # -- tokens -------------------------------------------------------------------------
325
+ def put_token(self, token: Token) -> None:
326
+ refuse_nul(token.id)
327
+ self._write(_PUT["tokens"], (token.id, json.dumps(token.to_dict(with_secret_hash=True))))
328
+
329
+ def get_token(self, token_id: str) -> Token | None:
330
+ refuse_nul(token_id)
331
+ doc = self._get("tokens", id=token_id)
332
+ return Token.from_dict(doc) if doc is not None else None
333
+
334
+ def list_tokens(self) -> list[Token]:
335
+ return [Token.from_dict(d) for d in self._list("tokens")]
336
+
337
+ # -- proposals ----------------------------------------------------------------------
338
+ def put_proposal(self, proposal: dict[str, Any]) -> None:
339
+ refuse_nul(proposal["id"], proposal["status"])
340
+ self._write(_PUT["proposals"],
341
+ (proposal["id"], proposal["status"], json.dumps(proposal)))
342
+
343
+ def get_proposal(self, proposal_id: str) -> dict[str, Any] | None:
344
+ refuse_nul(proposal_id)
345
+ return self._get("proposals", id=proposal_id)
346
+
347
+ def list_proposals(self, status: str | None = None) -> list[dict[str, Any]]:
348
+ refuse_nul(status)
349
+ return self._list("proposals", status=status or None) # sqlite's `if status:`
350
+
351
+ # -- ThrottleState (storage.md §3.1) ----------------------------------------------------
352
+ def throttle_incr(self, surface: ThrottleSurface, bucket_key: str, window_key: str) -> int:
353
+ """Increments and returns the new count, atomically, under the lock."""
354
+ refuse_nul(surface, bucket_key, window_key)
355
+ return self._write(
356
+ "INSERT INTO throttle (surface, bucket_key, window_key, count) VALUES (%s, %s, %s, 1) "
357
+ "ON CONFLICT (surface, bucket_key, window_key) "
358
+ "DO UPDATE SET count = throttle.count + 1 RETURNING count",
359
+ (surface, bucket_key, window_key),
360
+ ).fetchone()[0]
361
+
362
+ def throttle_count(self, surface: ThrottleSurface, bucket_key: str, window_key: str) -> int:
363
+ refuse_nul(surface, bucket_key, window_key)
364
+ rows = self._all(
365
+ "SELECT count FROM throttle WHERE surface = %s AND bucket_key = %s AND window_key = %s",
366
+ (surface, bucket_key, window_key),
367
+ )
368
+ return rows[0][0] if rows else 0
369
+
370
+ def throttle_buckets(self, surface: ThrottleSurface, window_key: str) -> list[tuple[str, int]]:
371
+ refuse_nul(surface, window_key)
372
+ rows = self._all("SELECT bucket_key, count FROM throttle WHERE surface = %s "
373
+ "AND window_key = %s ORDER BY bucket_key", (surface, window_key))
374
+ return [(k, n) for k, n in rows]
375
+
376
+ def throttle_windows(self, surface: ThrottleSurface) -> list[str]:
377
+ refuse_nul(surface)
378
+ rows = self._all("SELECT DISTINCT window_key FROM throttle WHERE surface = %s "
379
+ "ORDER BY window_key", (surface,))
380
+ return [r[0] for r in rows]
381
+
382
+ def throttle_forget(self, surface: ThrottleSurface, window_key: str) -> None:
383
+ refuse_nul(surface, window_key)
384
+ self._write("DELETE FROM throttle WHERE surface = %s AND window_key = %s",
385
+ (surface, window_key))
386
+
387
+ # -- IdentityState (storage.md §3.2) -----------------------------------------------------
388
+ def put_user_grant(self, grant: UserGrant) -> None:
389
+ refuse_nul(grant["sub"])
390
+ self._write(_PUT["user_grants"], (grant["sub"], json.dumps(grant)))
391
+
392
+ def get_user_grant(self, sub: str) -> UserGrant | None:
393
+ refuse_nul(sub)
394
+ return self._get("user_grants", sub=sub)
395
+
396
+ def list_user_grants(self) -> list[UserGrant]:
397
+ return self._list("user_grants")
398
+
399
+ def put_agent_registration(self, registration: Registration) -> None:
400
+ refuse_nul(registration["client_id"], registration["sub"])
401
+ self._write(_PUT["agent_registrations"],
402
+ (registration["client_id"], registration["sub"], json.dumps(registration)))
403
+
404
+ def get_agent_registration(self, client_id: str, sub: str) -> Registration | None:
405
+ refuse_nul(client_id, sub)
406
+ return self._get("agent_registrations", client_id=client_id, sub=sub)
407
+
408
+ def list_agent_registrations(self, client_id: str | None = None) -> list[Registration]:
409
+ refuse_nul(client_id)
410
+ return self._list("agent_registrations", client_id=client_id)
411
+
412
+ # -- ConfigState (storage.md §3.2) -------------------------------------------------------
413
+ def get_config(self) -> dict[str, Any]:
414
+ rows = self._all("SELECT key, value FROM config ORDER BY write_order")
415
+ return {k: json.loads(v) for k, v in rows}
416
+
417
+ def put_config(self, key: str, value: Any) -> None:
418
+ refuse_nul(key)
419
+ self._write(_PUT["config"], (key, json.dumps(value)))
420
+
421
+ # -- ConfirmState (storage.md §3.3) ------------------------------------------------------
422
+ def put_challenge(self, challenge: ConfirmChallenge) -> None:
423
+ refuse_nul(challenge["id"], challenge["expires_at"])
424
+ self._write("INSERT INTO challenges (id, expires_at, doc) VALUES (%s, %s, %s)",
425
+ (challenge["id"], challenge["expires_at"], json.dumps(challenge)))
426
+
427
+ def forget_challenges(self, expired_before: str) -> None:
428
+ refuse_nul(expired_before)
429
+ self._write("DELETE FROM challenges WHERE expires_at < %s", (expired_before,))
430
+
431
+ def spend_challenge(self, challenge_id: str) -> ConfirmChallenge | None:
432
+ """Mark it spent and return it as it stood: of two concurrent spends, one sees it fresh."""
433
+ refuse_nul(challenge_id)
434
+ with self.atomic():
435
+ rows = self._all("SELECT spent, doc FROM challenges WHERE id = %s", (challenge_id,))
436
+ if not rows:
437
+ return None
438
+ self.db.execute("UPDATE challenges SET spent = true WHERE id = %s", (challenge_id,))
439
+ return {**json.loads(rows[0][1]), "spent": rows[0][0]}
440
+
441
+ def put_credential(self, credential: ConfirmCredential) -> None:
442
+ refuse_nul(credential["id"], credential["person"])
443
+ self._write(_PUT["credentials"],
444
+ (credential["id"], credential["person"], json.dumps(credential)))
445
+
446
+ def get_credential(self, credential_id: str) -> ConfirmCredential | None:
447
+ refuse_nul(credential_id)
448
+ return self._get("credentials", id=credential_id)
449
+
450
+ def list_credentials(self, person: str | None = None) -> list[ConfirmCredential]:
451
+ refuse_nul(person)
452
+ return self._list("credentials", person=person)
453
+
454
+ # -- UploadState (storage.md §3.4) -------------------------------------------------------
455
+ def put_upload(self, upload: UploadRecord) -> None:
456
+ # Rewritten in place, as sqlite's UPDATE: its open order, principal and spends stand.
457
+ refuse_nul(upload["id"], upload["principal"])
458
+ self._write("INSERT INTO uploads (id, principal, doc) VALUES (%s, %s, %s) "
459
+ "ON CONFLICT (id) DO UPDATE SET doc = excluded.doc",
460
+ (upload["id"], upload["principal"], json.dumps(upload)))
461
+
462
+ def get_upload(self, upload_id: str) -> UploadRecord | None:
463
+ refuse_nul(upload_id)
464
+ return self._get("uploads", id=upload_id)
465
+
466
+ def list_uploads(self, principal: str | None = None) -> list[UploadRecord]:
467
+ refuse_nul(principal)
468
+ return self._list("uploads", principal=principal)
469
+
470
+ def spend_upload(self, upload_id: str, step: str) -> bool:
471
+ refuse_nul(upload_id)
472
+ column = {"bytes": "bytes_spent", "item": "item_spent"}[step]
473
+ cur = self._write(f"UPDATE uploads SET {column} = true WHERE id = %s AND NOT {column}",
474
+ (upload_id,))
475
+ return cur.rowcount == 1
476
+
477
+ # -- GrantState (storage.md §3.5) --------------------------------------------------------
478
+ def spend_grant(self, sig_hash: str, expires_at: str) -> bool:
479
+ """Record a spend, committed at once: of two concurrent spends of one grant, exactly one
480
+ inserts. Refused inside `atomic()` or any open transaction, whose rollback would undo it."""
481
+ refuse_nul(sig_hash, expires_at)
482
+ if self._depth or self.db.info.transaction_status != pq.TransactionStatus.IDLE:
483
+ raise RuntimeError("a grant is spent outside any transaction")
484
+ cur = self._write("INSERT INTO spent_grants (sig_hash, expires_at) VALUES (%s, %s) "
485
+ "ON CONFLICT DO NOTHING", (sig_hash, expires_at))
486
+ return cur.rowcount == 1
487
+
488
+ def forget_grants(self, expired_before: str) -> None:
489
+ refuse_nul(expired_before)
490
+ self._write("DELETE FROM spent_grants WHERE expires_at < %s", (expired_before,))