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/store/uploads.py ADDED
@@ -0,0 +1,369 @@
1
+ # Copyright 2026 Ali Sasanian
2
+ # SPDX-License-Identifier: LicenseRef-PolyForm-Strict-1.0.0
3
+ """
4
+ Artifact upload (spec/contracts/rest.md §4.4): open, bytes, item, and the discard of an orphan.
5
+
6
+ An upload is bound to the principal that opened it (`Token.id`) and is live for an hour. Its bytes
7
+ are staged, never `put`, so staging never answers whether the content already exists; its item is
8
+ written `unverified` like every write. A person's bytes are promoted with the item, an agent's stay
9
+ staged until a person promotes it. The bytes and the item are two spends of one id, each an atomic
10
+ check-and-mark. Nothing staged is deleted on a timer (v0.7 §Z): an upload that expired with its
11
+ bytes staged is an orphan, listed to its opener, an agent's to the person it serves, and to an admin
12
+ until one of them discards it. What a person holds is capped once for them and every agent serving
13
+ them (v0.7 §AC). A person's tombstone of the item is the other decision: it frees the slot, and
14
+ deletes the staged bytes no other upload or staged item, a copy included, still holds (rest.md §4).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import calendar
20
+ import logging
21
+ import re
22
+ import time
23
+ from collections.abc import Callable
24
+ from typing import Any
25
+
26
+ from egzos._ids import ulid
27
+ from egzos._types import UploadRecord
28
+ from egzos.backends.base import Backend
29
+ from egzos.identity import principal_id, principal_of
30
+ from egzos.ledger import Ledger
31
+ from egzos.model import ContextItem, Node, Token
32
+ from egzos.store.blobs import BlobStore
33
+ from egzos.store.items import Store
34
+
35
+ #: §4.4 item 2: an upload's id is live for an hour after it is opened.
36
+ UPLOAD_TTL_SECONDS = 3600
37
+ #: §4.4 item 1: uploads a person may hold open, orphaned, or written but still staged, counting
38
+ #: every agent serving them; a container `Token` is a person of its own.
39
+ MAX_HELD = 16
40
+ NAME_MAX = 255
41
+ MIME_MAX = 127
42
+ #: A `type/subtype` token (RFC 6838's restricted names), no parameters.
43
+ _MIME = re.compile(r"[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]*/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]*")
44
+ _DIGEST = re.compile(r"[0-9a-f]{64}")
45
+ _ISO = "%Y-%m-%dT%H:%M:%SZ"
46
+ log = logging.getLogger(__name__)
47
+
48
+
49
+ class Promoted(Exception):
50
+ """A tombstone that refuses promoted items found one, under the lock (rest.md §4: the terminal
51
+ never tombstones what a person promoted)."""
52
+
53
+
54
+ class TooManyUploads(Exception):
55
+ """§4.4 item 1: the caller's person already holds `MAX_HELD` uploads. A fact about their own."""
56
+
57
+
58
+ def person_of(principal: str, actor: str) -> str | None:
59
+ """Whose upload it is (§4.4, v0.7 §AC), from the opener's `Token.id` and `owner`, both recorded
60
+ at open. A container `Token`'s id is a ULID, which holds no `:`: its own person, whatever owner
61
+ it names. A provider principal's id names one `(client_id, sub)` pair of one kind
62
+ (`principal_of`); a person's, recorded beside `user:<sub>`, is that person; a terminal's,
63
+ recorded beside `user:<sub>` too, is the person at that terminal; and an agent's, recorded
64
+ beside `agent:<client_id>`, serves the person whose id is `principal_id(None, sub)`. What is
65
+ counted per person stays per person (rest.md §6). An id that reads as no pair, or that was
66
+ recorded beside an owner other than its own, is nobody's: None, which answers to an admin
67
+ alone."""
68
+ if ":" not in principal:
69
+ return principal
70
+ read = principal_of(principal)
71
+ if read is None:
72
+ return None
73
+ kind, client_id, sub = read
74
+ owner = f"agent:{client_id}" if kind == "agent" else f"user:{sub}"
75
+ return principal_id(None, sub) if actor == owner else None
76
+
77
+
78
+ def valid_open(name: Any, mime: Any, size: Any, sha256: Any, *, limit: int) -> bool:
79
+ """§4.4 item 1's shape, checked before any lookup: the same answer for every container."""
80
+ return (
81
+ isinstance(name, str) and 1 <= len(name) <= NAME_MAX
82
+ and isinstance(mime, str) and len(mime) <= MIME_MAX and _MIME.fullmatch(mime) is not None
83
+ and isinstance(size, int) and not isinstance(size, bool) and 0 <= size <= limit
84
+ and isinstance(sha256, str) and _DIGEST.fullmatch(sha256) is not None
85
+ )
86
+
87
+
88
+ class Uploads:
89
+ def __init__(
90
+ self,
91
+ backend: Backend,
92
+ ledger: Ledger,
93
+ blobs: BlobStore,
94
+ store: Store,
95
+ *,
96
+ clock: Callable[[], float] = time.time,
97
+ ):
98
+ self.backend = backend
99
+ self.ledger = ledger
100
+ self.blobs = blobs
101
+ self.store = store
102
+ self.clock = clock
103
+
104
+ def _iso(self, at: float) -> str:
105
+ return time.strftime(_ISO, time.gmtime(at))
106
+
107
+ def expired(self, record: UploadRecord) -> bool:
108
+ return calendar.timegm(time.strptime(record["expires_at"], _ISO)) <= self.clock()
109
+
110
+ def _staged_item(self, record: UploadRecord) -> ContextItem | None:
111
+ """The item written from `record` while its bytes are still staged: an agent's artifact
112
+ nobody has promoted or tombstoned yet."""
113
+ if record["item"] is None or record["promoted"]:
114
+ return None
115
+ item = self.backend.get(record["item"]) # a tombstoned item reads as absent
116
+ return item if item is not None and not self.promoted(item) else None
117
+
118
+ def holds(self, record: UploadRecord) -> bool:
119
+ """Whether `record` takes one of its person's `MAX_HELD` slots: open, orphaned, or written
120
+ as an artifact whose bytes are still staged. A person's decision frees a slot."""
121
+ if record["discarded"]:
122
+ return False
123
+ if record["item"] is None:
124
+ return record["staged"] or not self.expired(record)
125
+ return self._staged_item(record) is not None
126
+
127
+ def orphan(self, record: UploadRecord) -> bool:
128
+ return (not record["discarded"] and record["staged"] and record["item"] is None
129
+ and self.expired(record))
130
+
131
+ def opened(self, token: Token, record: UploadRecord) -> bool:
132
+ """Whether `token` opened `record`: the `Token.id` and `owner` recorded at open."""
133
+ return record["principal"] == token.id and record["actor"] == token.owner
134
+
135
+ def answers_to(self, token: Token, record: UploadRecord) -> bool:
136
+ """Whether `record` is listed to and discarded by `token` short of admin: its opener, and
137
+ once it is an orphan, the person an agent or a terminal opener serves (§4.4: an open
138
+ upload is its opener's). Never another agent or terminal of that person (rest.md §6)."""
139
+ return self.opened(token, record) or (
140
+ self.orphan(record) and token.id == person_of(record["principal"], record["actor"]))
141
+
142
+ # -- 1 · open -------------------------------------------------------------------------------
143
+ def open(self, token: Token, *, scope: Node, name: str, mime: str, size: int,
144
+ sha256: str) -> UploadRecord:
145
+ """A new upload of the caller's. Appends nothing: no bytes have moved."""
146
+ now = self.clock()
147
+ record: UploadRecord = {
148
+ "id": ulid(),
149
+ "principal": token.id,
150
+ "actor": token.owner,
151
+ "scope": scope.id,
152
+ "name": name,
153
+ "mime": mime,
154
+ "size": size,
155
+ "sha256": sha256,
156
+ "opened_at": self._iso(now),
157
+ "expires_at": self._iso(now + UPLOAD_TTL_SECONDS),
158
+ "staged": False,
159
+ "item": None,
160
+ "promoted": False,
161
+ "discarded": False,
162
+ }
163
+ mine = person_of(token.id, token.owner)
164
+ with self.backend.atomic():
165
+ # Counted for the person and written under one lock: two concurrent opens never both
166
+ # take slot 16, whichever of that person's principals make them.
167
+ held = [r for r in self.backend.list_uploads()
168
+ if person_of(r["principal"], r["actor"]) == mine and self.holds(r)]
169
+ if len(held) >= MAX_HELD:
170
+ raise TooManyUploads
171
+ self.backend.put_upload(record)
172
+ return record
173
+
174
+ def live(self, token: Token, upload_id: str) -> UploadRecord | None:
175
+ """The caller's own upload, unexpired and not discarded; None for every other case."""
176
+ record = self.backend.get_upload(upload_id)
177
+ if (record is None or not self.opened(token, record) or record["discarded"]
178
+ or self.expired(record)):
179
+ return None
180
+ return record
181
+
182
+ # -- 2 · bytes ------------------------------------------------------------------------------
183
+ def put(self, token: Token, upload_id: str, data: bytes | None) -> str | None:
184
+ """Stage the bytes of a live upload of the caller's; `data` is None when what arrived was
185
+ not `size` bytes. Returns `staged` or the refusal's reason (`already`, `length`, `hash`),
186
+ each recorded by `upload.put`; None, and nothing appended, if the id is not the caller's
187
+ live upload."""
188
+ digest = BlobStore.digest(data) if data is not None else None
189
+ with self.backend.atomic():
190
+ record = self.live(token, upload_id)
191
+ if record is None:
192
+ return None
193
+ reason = None
194
+ if record["staged"]:
195
+ reason = "already"
196
+ elif data is None or len(data) != record["size"]:
197
+ reason = "length"
198
+ elif digest != record["sha256"]:
199
+ reason = "hash"
200
+ elif not self.backend.spend_upload(upload_id, "bytes"):
201
+ reason = "already"
202
+ details: dict[str, Any] = {"outcome": "staged"} if reason is None else {
203
+ "outcome": "refused", "reason": reason}
204
+ self.ledger.append("upload.put", actor=token.owner, principal=token.principal,
205
+ subject=upload_id, scope=record["scope"], size=record["size"],
206
+ sha256=record["sha256"], **details)
207
+ if reason is None:
208
+ self.backend.put_upload({**record, "staged": True})
209
+ assert data is not None
210
+ self.blobs.stage(data) # last: a failure before it rolls the spend back
211
+ return reason or "staged"
212
+
213
+ # -- 3 · item -------------------------------------------------------------------------------
214
+ def item(self, token: Token, upload_id: str, *, scope: Node | None, key: str | None,
215
+ tags: list[str]) -> ContextItem | None:
216
+ """Write the artifact item from a staged upload of the caller's, once. None when the id is
217
+ not the caller's live, staged, unwritten upload, or `scope` is not the upload's. A token
218
+ that may not write there raises `StoreError`, and nothing is spent."""
219
+ with self.backend.atomic():
220
+ record = self.live(token, upload_id)
221
+ if (record is None or not record["staged"] or record["item"] is not None
222
+ or (scope is not None and scope.id != record["scope"])):
223
+ return None
224
+ node = self.backend.get_node(record["scope"])
225
+ if node is None or not self.backend.spend_upload(upload_id, "item"):
226
+ return None
227
+ person = token.principal == "interactive"
228
+ written = self.store.add(upload=record, promote=person, kind="artifact", scope=node,
229
+ key=key, tags=tags, token=token, actor=token.owner,
230
+ principal=token.principal)
231
+ self.backend.put_upload({**record, "item": written.id, "promoted": person})
232
+ return written
233
+
234
+ # -- the orphan's discard -------------------------------------------------------------------
235
+ def discard(self, token: Token, upload_id: str, *, admin: bool) -> bool:
236
+ """Discard an upload no item was written from — the caller's own, an orphan an agent or a
237
+ terminal serving the caller opened (`answers_to`), or as an admin anyone's — with its staged
238
+ bytes, unless another upload or staged item still holds them (`_shared`). False is §3's
239
+ refusal."""
240
+ with self.backend.atomic():
241
+ record = self.backend.get_upload(upload_id)
242
+ if (record is None or record["discarded"] or record["item"] is not None
243
+ or not (admin or self.answers_to(token, record))):
244
+ return False
245
+ delete = record["staged"] and not self._shared(record["sha256"], upload=record["id"])
246
+ self.backend.put_upload({**record, "discarded": True})
247
+ self.ledger.append("upload.discard", actor=token.owner, principal=token.principal,
248
+ subject=upload_id, scope=record["scope"], size=record["size"],
249
+ sha256=record["sha256"], opener=record["actor"],
250
+ bytes_deleted=delete)
251
+ if delete: # the delete waits for this block's COMMIT, then re-checks (`release`)
252
+ self.blobs.discard(record["sha256"])
253
+ return True
254
+
255
+ def _shared(self, sha: str, *, upload: str | None = None, item: str | None = None) -> bool:
256
+ """Whether anything but `upload` and `item` still needs the staged bytes at `sha`: an
257
+ upload staged and not yet written, or an item whose bytes are staged there (`_staged_at`).
258
+ Staging is content-addressed, so all of them share one staged copy."""
259
+ return any(r["id"] != upload and r["sha256"] == sha and r["staged"] and not r["discarded"]
260
+ and r["item"] is None for r in self.backend.list_uploads()
261
+ ) or bool(self._staged_at(sha) - {item})
262
+
263
+ # -- the staged deletes that wait for a COMMIT (storage.md §3.6, §4) ---------------------------
264
+ def release(self, sha: str) -> None:
265
+ """A staged delete a committed act queued, in a short block of its own: the bytes at `sha`
266
+ go only if no live upload or staged item holds them now (`_shared`), so a stage of the
267
+ same bytes committed since keeps them. One that fails leaves them to the next open's sweep,
268
+ and never reaches the caller whose act has committed."""
269
+ try:
270
+ with self.backend.atomic():
271
+ if not self._shared(sha):
272
+ self.blobs._unstage(sha)
273
+ except Exception as e:
274
+ log.warning("a staged delete did not run (%s); the next open's sweep deletes it",
275
+ type(e).__name__)
276
+
277
+ def sweep(self) -> int:
278
+ """The open-time sweep (§3.6, §4): under the lock, every address the store's own listing
279
+ has in staging that no live upload or staged item holds is deleted, and how many is
280
+ returned. The rule is broader than its reason, a crash between a COMMIT and its delete: it
281
+ also takes bytes staged by an act whose block rolled back, which nothing recorded either,
282
+ so deleting them completes that rollback. No purge, since nothing is timed, and nothing is
283
+ appended: each such delete finishes an act the chain already holds, or one it never did."""
284
+ with self.backend.atomic():
285
+ gone = [sha for sha in self.blobs._staged_names() if not self._shared(sha)]
286
+ for sha in gone:
287
+ self.blobs._unstage(sha)
288
+ return len(gone)
289
+
290
+ def _staged_at(self, sha: str) -> set[str]:
291
+ """The live items whose bytes are staged at `sha`: an artifact written from an upload that
292
+ was never promoted, and every copy of one (a copy names its source's address,
293
+ `trust._do_copy`), until it, or an item it was copied through, is promoted: a move that
294
+ lowers a promoted item's status never puts its bytes back in staging."""
295
+ records = {r["item"]: r for r in self.backend.list_uploads() if r["item"] is not None}
296
+ every = {i.id: i for i in self.backend.query(
297
+ [n.id for n in self.backend.list_nodes()], kinds=["artifact"], include_tombstoned=True)}
298
+
299
+ def staged(item: ContextItem | None) -> bool:
300
+ while item is not None and not self.promoted(item):
301
+ if item.id in records:
302
+ return not records[item.id]["promoted"]
303
+ item = every.get(item.provenance.get("derived_from") or "")
304
+ return False # promoted on the way, or written from a file: promoted bytes
305
+
306
+ return {i.id for i in every.values() if i.content.get("sha256") == sha
307
+ and not i.lifecycle.get("tombstoned") and staged(i)}
308
+
309
+ # -- a person's tombstone (rest.md §4) -------------------------------------------------------
310
+ @staticmethod
311
+ def promoted(item: ContextItem) -> bool:
312
+ """Whether a person promoted `item`: verified now, or approved once whatever its status is
313
+ now, since a move can lower the status but never the approval. Its tombstone takes the
314
+ confirm at the door, and the terminal never tombstones it (rest.md §4)."""
315
+ return item.status == "verified" or bool(item.provenance.get("approved_by"))
316
+
317
+ def tombstonable(self, token: Token, item: ContextItem | None) -> bool:
318
+ """Whether `token` may tombstone `item`: a person, never an agent, holding `organize`
319
+ where the item sits, and an item live and not quarantined. Anything else is §3's refusal."""
320
+ if (item is None or item.status == "quarantined" or token.principal != "interactive"
321
+ or not token.has("organize")):
322
+ return False
323
+ node = self.backend.get_node(item.scope)
324
+ return node is not None and self.store.covers is not None and self.store.covers(token, node)
325
+
326
+ def tombstone(self, token: Token, item_id: str, *,
327
+ unpromoted_only: bool = False) -> ContextItem | None:
328
+ """Tombstone the item as it stands under the lock, with its `item.tombstone`, in one step;
329
+ None, and nothing written, where `token` may not. An artifact whose bytes are still staged
330
+ releases them, deleted unless another upload or staged item holds them (`_shared`), and
331
+ `staged_deleted` records only bytes there were to delete: another item's promotion may
332
+ have moved them already. The delete waits for the COMMIT, and a stage of the same bytes
333
+ committed before it keeps them (`release`). Promoted bytes are never deleted ([0.3 · 44]).
334
+ Its upload then frees its slot (`holds`). The confirm a promoted item needs is the
335
+ caller's; with `unpromoted_only`, a promoted item raises `Promoted` under the lock and
336
+ nothing is written.
337
+ """
338
+ with self.backend.atomic():
339
+ item = self.backend.get(item_id) # a tombstoned item reads as absent
340
+ if item is None or not self.tombstonable(token, item):
341
+ return None
342
+ if unpromoted_only and self.promoted(item):
343
+ raise Promoted
344
+ sha = item.content.get("sha256") if item.kind == "artifact" else None
345
+ if not (isinstance(sha, str) and item.id in self._staged_at(sha)
346
+ and not self._shared(sha, item=item.id)):
347
+ sha = None
348
+ self.backend.tombstone(item.id)
349
+ # Before the entry, inside the lock, so the entry claims only bytes there were; their
350
+ # delete waits for the COMMIT, and a failure from here on rolls the tombstone back.
351
+ released = sha is not None and self.blobs.discard(sha)
352
+ details: dict[str, Any] = {"kind": item.kind, "status": item.status}
353
+ if released:
354
+ details["staged_deleted"] = sha
355
+ self.ledger.append("item.tombstone", actor=token.owner, principal=token.principal,
356
+ subject=item.id, scope=item.scope, **details)
357
+ return item
358
+
359
+ # -- what `GET /v1/pending` lists ------------------------------------------------------------
360
+ def orphans(self, token: Token, *, admin: bool) -> list[UploadRecord]:
361
+ """The orphans the caller may see: its own and, for a person's own sign-in, its agents'
362
+ and its terminals' (`answers_to`), or as an admin every principal's."""
363
+ return [r for r in self.backend.list_uploads()
364
+ if self.orphan(r) and (admin or self.answers_to(token, r))]
365
+
366
+ def staged_items(self) -> set[str]:
367
+ """The ids of artifact items whose bytes are still staged."""
368
+ return {r["item"] for r in self.backend.list_uploads()
369
+ if r["item"] is not None and self._staged_item(r) is not None}