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/trust.py ADDED
@@ -0,0 +1,675 @@
1
+ # Copyright 2026 Ali Sasanian
2
+ # SPDX-License-Identifier: LicenseRef-PolyForm-Strict-1.0.0
3
+ """
4
+ The trust engine (a3-trust body 1): statuses, the pending queue, promotion, quarantine with
5
+ derived_from propagation, and THE CONDITIONAL GATE (v0.4 §2): compute the audience delta of a
6
+ move. Zero delta = instant + silently logged (audience_delta:none). Nonzero = a proposal parked
7
+ in pending naming people AND agents with roles plus the inheritance blast radius. Approval is
8
+ bound to a manifest hash (item ids + target + audience snapshot) and executes only if it still
9
+ matches — TOCTOU closed (v0.4 §5).
10
+
11
+ Human-only acts (approve-from-pending, confirming a publish) demand the interactive principal.
12
+ No capability reaches them: a maximally granted client can only PROPOSE.
13
+
14
+ Trust alone mints a `BlobGrant` (F5, rest.md §6): artifact download IS fetch, so a grant is minted
15
+ on the check a fetch applies, and a redemption runs that check again, as things stand then.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import hashlib
21
+ import hmac
22
+ import time
23
+ from collections.abc import Callable, Iterable
24
+ from datetime import UTC, datetime
25
+ from typing import Any
26
+
27
+ from egzos._ids import ulid
28
+ from egzos._types import BLOB_GRANT_LIFETIME_SECONDS, BlobGrant
29
+ from egzos.backends.base import Backend
30
+ from egzos.ledger import Ledger
31
+ from egzos.model import RING_RANK, ROLE_BUNDLES, ContextItem, Node, Token, canonical, now_iso
32
+ from egzos.store.blobs import _is_digest
33
+ from egzos.store.nodes import NodeService
34
+
35
+
36
+ class TrustError(Exception):
37
+ pass
38
+
39
+
40
+ class HumanOnly(TrustError):
41
+ """Raised when a client principal attempts a human-only act."""
42
+
43
+
44
+ # One refusal for both branches of the gate (container.md §6, capabilities.md §1).
45
+ _MOVE_REFUSED = "moving items needs `organize` (and `publish` where the audience widens)"
46
+ #: rest.md §6 (a1p): the grant key's file in the container's home, and its length.
47
+ GRANT_KEY_FILE = "grant.key"
48
+ GRANT_KEY_BYTES = 32
49
+ _UTC = "%Y-%m-%dT%H:%M:%S.%fZ"
50
+
51
+
52
+ def _utc(at: float) -> str:
53
+ """UTC ISO-8601, fixed width to the microsecond, so two of these compare as the times they
54
+ are."""
55
+ return datetime.fromtimestamp(at, UTC).strftime(_UTC)
56
+
57
+
58
+ _UTC_WIDTH = len(_utc(0.0))
59
+
60
+
61
+ def grant_expiry(text: str) -> float | None:
62
+ """A descriptor's `expires_at` as a time, or None when it is not written as `_utc` writes."""
63
+ if len(text) != _UTC_WIDTH:
64
+ return None
65
+ try:
66
+ return datetime.strptime(text, _UTC).replace(tzinfo=UTC).timestamp()
67
+ except ValueError:
68
+ return None
69
+
70
+
71
+ def _after(text: str, when: float) -> bool:
72
+ """Whether an ISO-8601 time is later than `when`. One nobody can read counts as later."""
73
+ try:
74
+ at = datetime.fromisoformat(text)
75
+ except (TypeError, ValueError):
76
+ return True
77
+ return (at if at.tzinfo else at.replace(tzinfo=UTC)).timestamp() > when
78
+
79
+
80
+ class TrustEngine:
81
+ def __init__(self, backend: Backend, ledger: Ledger, nodes: NodeService):
82
+ self.backend = backend
83
+ self.ledger = ledger
84
+ self.nodes = nodes
85
+ # The audience beyond minted tokens: the container wires in its grants and registrations
86
+ # (identity.md §4), and how to re-read a caller under the lock, whichever kind it is.
87
+ self.principals: Callable[[], Iterable[Token]] = list
88
+ self.refresh: Callable[[Token], Token | None] = lambda t: self.backend.get_token(t.id)
89
+ # Moves a staged artifact's bytes into the promoted store on promotion, True if any moved
90
+ # (storage.md §4); the container wires in its blob store's `promote`.
91
+ self.promote_blob: Callable[[str], bool] = lambda sha: False
92
+ # Whether the promoted store holds an address already: an approval whose promote moved
93
+ # nothing goes on only then (§3.6). The container wires in its blob store's `exists`.
94
+ self.blob_exists: Callable[[str], bool] = lambda sha: False
95
+ # rest.md §6, wired by the container: the grant key, read at every use so a new one
96
+ # reaches every process; the principal a grant names, as it stands now; and the serving
97
+ # predicate a fetch applies (`find.shown`). Unwired, nothing is signed and nothing served.
98
+ self.grant_key: Callable[[], bytes] = bytes
99
+ self.named: Callable[[str], Token | None] = lambda token_id: None
100
+ self.shown: Callable[[Token, ContextItem, Node], bool] = lambda token, item, node: False
101
+ self.clock: Callable[[], float] = time.time
102
+
103
+ # -- coverage & audience -----------------------------------------------------------------
104
+ def covers(self, token: Token, node: Node) -> bool:
105
+ """Grants bind to container ids; coverage is computed at check time down the path."""
106
+ if not token.live:
107
+ return False
108
+ if "*" in token.scopes:
109
+ return True
110
+ ancestor_ids = {n.id for n in self.nodes.ancestors(node)}
111
+ return any(s in ancestor_ids for s in token.scopes)
112
+
113
+ def audience(self, node: Node) -> list[dict[str, Any]]:
114
+ """Who can see `node`: every live token whose coverage reaches it — people AND agents —
115
+ and every live user grant and agent registration (identity.md §4), counted the same way."""
116
+ out = []
117
+ for t in [*self.backend.list_tokens(), *self.principals()]:
118
+ if self.covers(t, node):
119
+ out.append(
120
+ {
121
+ "token": t.id,
122
+ "owner": t.owner,
123
+ "client": t.client,
124
+ "principal": t.principal,
125
+ "role": _role_name(t.capabilities),
126
+ }
127
+ )
128
+ return sorted(out, key=lambda a: a["token"])
129
+
130
+ def blast_radius(self, node: Node) -> int:
131
+ """Inheritance consequence: how many descendants (current) inherit what lands here."""
132
+ count = 0
133
+ stack = [node.id]
134
+ while stack:
135
+ pid = stack.pop()
136
+ kids = self.backend.list_nodes(parent=pid)
137
+ count += len(kids)
138
+ stack.extend(k.id for k in kids)
139
+ return count
140
+
141
+ @staticmethod
142
+ def manifest_hash(item_ids: list[str], target: str, audience: list[dict[str, Any]]) -> str:
143
+ return hashlib.sha256(
144
+ canonical({"items": sorted(item_ids), "target": target, "audience": audience}).encode()
145
+ ).hexdigest()
146
+
147
+ # -- BlobGrant (F5, rest.md §6) --------------------------------------------------------------
148
+ def authorize_pull(self, token: Token, item: ContextItem) -> BlobGrant | None:
149
+ """A grant to pull this artifact's bytes, or silence: `pull_refusal`'s check, the one a
150
+ redemption runs again. A mint appends `blob.grant`; silence appends nothing of its own, as
151
+ the read that served the item is already on the record. A key that cannot be read is
152
+ silence too: downloads stop, and reads go on."""
153
+ sha, key = item.content.get("sha256"), self._key()
154
+ if (key is None or item.kind != "artifact" or not _is_digest(sha)
155
+ or self.pull_refusal(token, item)):
156
+ return None
157
+ now = self.clock()
158
+ # rest.md §6: a spent record is kept a lifetime past its grant's expiry, then forgotten.
159
+ self.backend.forget_grants(_utc(now - BLOB_GRANT_LIFETIME_SECONDS))
160
+ expires_at = _utc(now + BLOB_GRANT_LIFETIME_SECONDS)
161
+ grant: BlobGrant = {"sha256": sha, "item": item.id, "token": token.id,
162
+ "expires_at": expires_at, "sig": ""}
163
+ grant["sig"] = self._sign(grant, key)
164
+ self.ledger.append("blob.grant", actor=token.owner, principal=token.principal,
165
+ subject=item.id, scope=item.scope, token=token.id, sha256=sha,
166
+ expires_at=expires_at)
167
+ return grant
168
+
169
+ def _key(self) -> bytes | None:
170
+ """The container's grant key, read afresh at every use; None when it cannot be read or is
171
+ not `GRANT_KEY_BYTES` long, so nothing is signed or verified under it and reads go on
172
+ without a grant (a1r on #304)."""
173
+ try:
174
+ key = self.grant_key()
175
+ except OSError:
176
+ return None
177
+ return key if len(key) == GRANT_KEY_BYTES else None
178
+
179
+ @staticmethod
180
+ def _sign(grant: BlobGrant, key: bytes) -> str:
181
+ """[0.3 · 45]: HMAC-SHA256 under the container's key over every descriptor field but
182
+ `sig`, as `canonical` JSON — each value a quoted string under its name, so no two
183
+ descriptors share a message, and a field added later is covered with no edit here."""
184
+ body = canonical({k: v for k, v in grant.items() if k != "sig"})
185
+ return hmac.new(key, body.encode("utf-8"), hashlib.sha256).hexdigest()
186
+
187
+ def verify_grant(self, grant: BlobGrant) -> bool:
188
+ """rest.md §6 check 2: `sig` verifies under the container key, in constant time."""
189
+ key = self._key()
190
+ return key is not None and hmac.compare_digest(
191
+ self._sign(grant, key).encode(), grant["sig"].encode())
192
+
193
+ def spend_grant(self, grant: BlobGrant) -> bool:
194
+ """Check 4: the first verified redemption spends the grant, atomically, whatever the
195
+ later checks decide. Keyed on the sha256 of its `sig`, kept at least until it expires."""
196
+ digest = hashlib.sha256(grant["sig"].encode()).hexdigest()
197
+ return self.backend.spend_grant(digest, grant["expires_at"])
198
+
199
+ def pull_refusal(
200
+ self, token: Token | None, item: ContextItem | None, minted: float | None = None
201
+ ) -> int | None:
202
+ """rest.md §6's checks 5 and 6, as they stand now: 5 when the token is not live, lacks
203
+ `fetch` over the item's scope, or was granted after `minted` (revoked and granted again
204
+ since, it is not the grant the descriptor named); 6 when the item is not served to it —
205
+ absent or tombstoned, quarantined, outside the serving policy, or its bytes still staged.
206
+ None when both pass."""
207
+ node = self.backend.get_node(item.scope) if item is not None else None
208
+ if (token is None or not token.has("fetch") or (node and not self.covers(token, node))
209
+ or (minted is not None and _after(token.created_at, minted))):
210
+ return 5
211
+ if (item is None or node is None or item.status == "quarantined"
212
+ or not self.shown(token, item, node) or self._staged(item)):
213
+ return 6
214
+ return None
215
+
216
+ def _staged(self, item: ContextItem) -> bool:
217
+ """Whether an artifact's bytes are still staged (storage.md §4): an agent's, until a person
218
+ promotes the item; a copy's, which names its source's bytes, until it or its source is
219
+ promoted. A source no longer read is judged by what the copy carries of it. Never by
220
+ whether the bytes are stored, which would answer for some other item ([0.3 · 41])."""
221
+ seen: set[str] = set()
222
+ while item.provenance.get("approved_by") is None:
223
+ source_id = item.provenance.get("derived_from")
224
+ source = self.backend.get(source_id) if source_id and source_id not in seen else None
225
+ if source is None:
226
+ return item.provenance.get("principal") != "interactive"
227
+ seen.add(item.id)
228
+ item = source
229
+ return False
230
+
231
+ # -- pending -------------------------------------------------------------------------------
232
+ def pending(self) -> dict[str, Any]:
233
+ items = [i for i in self._all_items() if i.status == "unverified"]
234
+ proposals = self.backend.list_proposals(status="open")
235
+ return {"items": items, "proposals": proposals}
236
+
237
+ def _all_items(self) -> list[ContextItem]:
238
+ scopes = [n.id for n in self.backend.list_nodes()]
239
+ return self.backend.query(scopes)
240
+
241
+ # -- promotion / quarantine ------------------------------------------------------------------
242
+ def promote(self, item: ContextItem, *, token: Token, actor: str) -> ContextItem:
243
+ self._human_only(token, "approve.pending")
244
+ node = self.backend.get_node(item.scope)
245
+ # Human is not enough: the human must also cover the item (#131). An uncovered item gets
246
+ # the answer an absent one gets, before anything about it (even quarantine) is said.
247
+ if node is None or not self.covers(token, node):
248
+ raise TrustError("not found")
249
+ if item.status == "quarantined":
250
+ raise TrustError("quarantined items are not promoted; lift the quarantine deliberately")
251
+ with self.backend.atomic():
252
+ # Promoted as it stands under the lock: a quarantine or a move since it was read is
253
+ # observed, never written over (a6 on #289).
254
+ item = self._fresh(item, refusal="quarantined items are not promoted; lift the "
255
+ "quarantine deliberately")
256
+ audience = self.audience(node)
257
+ manifest = self.manifest_hash([item.id], item.scope, audience)
258
+ item.trust = {"status": "verified", "promoted_at": now_iso(), "manifest": manifest}
259
+ item.provenance["approved_by"] = actor
260
+ item.lifecycle["updated_at"] = now_iso()
261
+ item.lifecycle["version"] = int(item.lifecycle.get("version", 1)) + 1
262
+ self.backend.put(item)
263
+ self.ledger.append(
264
+ "approval.promote",
265
+ actor=actor,
266
+ principal=token.principal,
267
+ subject=item.id,
268
+ scope=item.scope,
269
+ manifest=manifest,
270
+ audience=[a["client"] for a in audience],
271
+ )
272
+ # An agent's artifact waited staged for this (rest.md §4.4): its bytes move now, and
273
+ # only a promotion that moved bytes says so (storage.md §4, [0.3 · 43]). One that moved
274
+ # none goes on only where the promoted store holds them, which had their `blob.put`
275
+ # when they arrived; else nothing was staged, and the raise undoes the act (§3.6).
276
+ sha = item.content.get("sha256") if item.kind == "artifact" else None
277
+ if isinstance(sha, str) and not self.promote_blob(sha):
278
+ if not self.blob_exists(sha):
279
+ raise TrustError("nothing staged: the artifact's bytes are not stored")
280
+ elif isinstance(sha, str):
281
+ self.ledger.append(
282
+ "blob.put",
283
+ actor=actor,
284
+ principal=token.principal,
285
+ subject=sha,
286
+ scope=item.scope,
287
+ size=item.content.get("size"),
288
+ mime=item.content.get("mime"),
289
+ )
290
+ return item
291
+
292
+ def quarantine(self, item: ContextItem, *, token: Token, actor: str, reason: str) -> list[str]:
293
+ self._may_quarantine(item, token)
294
+ # The item, every derived copy and the chain entry land together, or none of them.
295
+ with self.backend.atomic():
296
+ # Quarantined as it stands under the lock, checked again there: a write since the
297
+ # caller read it is observed, never written over (storage.md §3.6;
298
+ # GHSA-m955-fr24-frwq).
299
+ item = self._fresh(item, refusal="already quarantined")
300
+ self._may_quarantine(item, token)
301
+ affected = [item.id]
302
+ item.trust = {"status": "quarantined", "reason": reason, "at": now_iso()}
303
+ self.backend.put(item)
304
+ # propagates immediately to descendants via derived_from (v0.3 §5)
305
+ for other in self._all_items():
306
+ if (other.provenance.get("derived_from") == item.id
307
+ and other.status != "quarantined"):
308
+ other.trust = {
309
+ "status": "quarantined",
310
+ "reason": f"derived from {item.id}",
311
+ "at": now_iso(),
312
+ }
313
+ self.backend.put(other)
314
+ affected.append(other.id)
315
+ self.ledger.append(
316
+ "trust.quarantine",
317
+ actor=actor,
318
+ principal=token.principal,
319
+ subject=item.id,
320
+ scope=item.scope,
321
+ reason=reason,
322
+ affected=affected,
323
+ )
324
+ # The caller learns only what it may see; the chain keeps the whole propagation.
325
+ return [
326
+ i
327
+ for i in affected
328
+ if (it := self.backend.get(i))
329
+ and (n := self.backend.get_node(it.scope))
330
+ and self.covers(token, n)
331
+ ]
332
+
333
+ def _may_quarantine(self, item: ContextItem, token: Token) -> None:
334
+ """A quarantine's checks, before its lock and again under it: coverage, then `curate`."""
335
+ node = self.backend.get_node(item.scope)
336
+ if node is None or not self.covers(token, node):
337
+ raise TrustError("not found") # the same answer as an item that does not exist
338
+ if not token.has("curate"):
339
+ raise TrustError("quarantine needs `curate`")
340
+
341
+ # -- the gate ------------------------------------------------------------------------------
342
+ def gate(
343
+ self, item: ContextItem, to: Node, *, token: Token, act: str = "move"
344
+ ) -> tuple[Node, list[dict[str, Any]]]:
345
+ """The gate's checks for a move or a copy, in `container.md` §6's order, and the audience
346
+ delta they reach: coverage, then quarantine, then the floor (`organize`, and `remember`
347
+ on the destination for a copy), and only then the delta, with `publish` needed to widen.
348
+ Raises `TrustError` with the floor's text for every refusal past coverage, so a token that
349
+ may not do the act never learns whether the destination's audience is wider."""
350
+ frm = self.backend.get_node(item.scope)
351
+ if frm is None or not self.covers(token, frm) or not self.covers(token, to):
352
+ # Coverage lives here, not per surface: an item or target the token cannot see answers
353
+ # exactly like one that does not exist (silence-not-errors).
354
+ raise TrustError("not found")
355
+ if act == "copy" and not token.has("fetch"):
356
+ raise TrustError("not found") # a copy reads its source: no `fetch`, no source
357
+ if item.status == "quarantined":
358
+ # A quarantined item does not move, silently or by proposal (step-up spec R5).
359
+ raise TrustError("quarantined items do not move; lift the quarantine deliberately")
360
+ # The floor is checked BEFORE the delta (container.md §6): a token that may not move the
361
+ # item never learns from the refusal whether the destination's audience is wider.
362
+ if not token.has("organize") or (act == "copy" and not token.has("remember")):
363
+ raise TrustError(_MOVE_REFUSED)
364
+ before = self.audience(frm)
365
+ after = self.audience(to)
366
+ delta = [a for a in after if a["token"] not in {b["token"] for b in before}]
367
+ if delta and not token.has("publish"):
368
+ raise TrustError(_MOVE_REFUSED) # the floor's text: the branch is not disclosed
369
+ return frm, delta
370
+
371
+ def move(self, item: ContextItem, to: Node, *, token: Token, actor: str) -> dict[str, Any]:
372
+ """cp/mv landing at a different audience halts at the gate (v0.3 §5). Inward = instant."""
373
+ frm, delta = self.gate(item, to, token=token)
374
+ outward = RING_RANK.get(to.type, -1) > RING_RANK.get(frm.type, -1)
375
+
376
+ if not delta:
377
+ # Zero audience delta (true solo — counting agents) → instant, silently logged.
378
+ with self.backend.atomic(): # the move and its gate entry, together
379
+ item = self._fresh(item)
380
+ reset = self._reset_if_agent_run(item, token.principal)
381
+ self._do_move(item, to, actor, token.principal)
382
+ self.ledger.append(
383
+ "gate.pass.silent",
384
+ actor=actor,
385
+ principal=token.principal,
386
+ subject=item.id,
387
+ scope=to.id,
388
+ audience_delta="none",
389
+ from_=frm.id,
390
+ outward=outward,
391
+ reset=[item.id] if reset else [],
392
+ )
393
+ return {"moved": True, "gate": "silent", "audience_delta": []}
394
+
395
+ # Nonzero delta: this is a publish. Park it — even for the interactive owner the gate
396
+ # shows the RESOLVED audience; the confirm is a separate human act (`trust approve`
397
+ # behind the presence tap, or the REST door's inline confirm, `move_confirmed`).
398
+ return self._park(item, frm, to, token, actor, delta, reason="audience widens")
399
+
400
+ def copy(self, item: ContextItem, to: Node, *, token: Token, actor: str) -> dict[str, Any]:
401
+ """A copy is a new item at the destination, derived from the source, through the same
402
+ gate as a move (v0.7 §V): silent when nobody new would see it, parked when they would."""
403
+ frm, delta = self.gate(item, to, token=token, act="copy")
404
+ if not delta:
405
+ with self.backend.atomic():
406
+ new = self._do_copy(self._fresh(item), to, actor, token.principal)
407
+ self.ledger.append(
408
+ "gate.pass.silent",
409
+ actor=actor,
410
+ principal=token.principal,
411
+ subject=new.id,
412
+ scope=to.id,
413
+ audience_delta="none",
414
+ from_=frm.id,
415
+ copy_of=item.id,
416
+ )
417
+ return {"copied": True, "gate": "silent", "item": new, "audience_delta": []}
418
+ return self._park(item, frm, to, token, actor, delta, reason="audience widens",
419
+ kind="copy")
420
+
421
+ def confirmed(
422
+ self,
423
+ item: ContextItem,
424
+ to: Node,
425
+ *,
426
+ token: Token,
427
+ actor: str,
428
+ act: str,
429
+ delta: list[dict[str, Any]],
430
+ step_up: int | None,
431
+ ) -> ContextItem:
432
+ """A widening move or copy the person confirmed inline (rest.md §4.2): the gate's own
433
+ entry, then the act's. The caller holds the transaction the confirm was spent in."""
434
+ self._human_only(token, "gate.confirm")
435
+ item = self._fresh(item)
436
+ self.ledger.append(
437
+ "gate.pass.confirmed",
438
+ actor=actor,
439
+ principal=token.principal,
440
+ subject=item.id,
441
+ scope=to.id,
442
+ audience_delta=[d["token"] for d in delta],
443
+ step_up=step_up,
444
+ act=act,
445
+ )
446
+ if act == "copy":
447
+ return self._do_copy(item, to, actor, token.principal)
448
+ self._do_move(item, to, actor, token.principal)
449
+ return item
450
+
451
+ def _fresh(self, item: ContextItem, *, refusal: str = "") -> ContextItem:
452
+ """The item as it stands now, read under the caller's write lock: what the gate checked
453
+ before the lock is checked again, so a quarantine or a move that landed in between is
454
+ observed rather than written over by a stale copy (a6 on #289)."""
455
+ current = self.backend.get(item.id)
456
+ if current is None or current.scope != item.scope:
457
+ raise TrustError("not found")
458
+ if current.status == "quarantined":
459
+ raise TrustError(refusal or "quarantined items do not move; lift the quarantine "
460
+ "deliberately")
461
+ return current
462
+
463
+ def _park(
464
+ self,
465
+ item: ContextItem,
466
+ frm: Node,
467
+ to: Node,
468
+ token: Token,
469
+ actor: str,
470
+ delta: list[dict[str, Any]],
471
+ *,
472
+ reason: str,
473
+ kind: str = "move",
474
+ ) -> dict[str, Any]:
475
+ audience = self.audience(to)
476
+ proposal = {
477
+ "id": ulid(),
478
+ "status": "open",
479
+ "kind": kind,
480
+ "items": [item.id],
481
+ "from": frm.id,
482
+ "to": to.id,
483
+ "from_path": self.nodes.path(frm),
484
+ "to_path": self.nodes.path(to),
485
+ "audience": audience,
486
+ "audience_delta": delta,
487
+ "blast_radius": self.blast_radius(to),
488
+ "manifest": self.manifest_hash([item.id], to.id, audience),
489
+ "proposed_by": {"actor": actor, "principal": token.principal, "client": token.client},
490
+ "reason": reason,
491
+ "created_at": now_iso(),
492
+ }
493
+ with self.backend.atomic(): # the proposal and its entry, together (GHSA-2478-6jv5-83ff)
494
+ self.backend.put_proposal(proposal)
495
+ self.ledger.append(
496
+ "gate.propose",
497
+ actor=actor,
498
+ principal=token.principal,
499
+ subject=proposal["id"],
500
+ scope=to.id,
501
+ items=[item.id],
502
+ audience_delta=[d["client"] for d in delta],
503
+ reason=reason,
504
+ )
505
+ return {"moved": False, "gate": "pending", "proposal": proposal}
506
+
507
+ def execute(self, proposal_id: str, *, token: Token, actor: str) -> dict[str, Any]:
508
+ self._human_only(token, "gate.confirm")
509
+ p = self.backend.get_proposal(proposal_id)
510
+ if not p or p["status"] != "open" or not self.decides_over(token, p):
511
+ raise TrustError("no open proposal with that id")
512
+ # Everything the decision rests on is read under the write lock that the move takes, so
513
+ # what is executed is exactly what was checked: the proposal still open (#118) and still
514
+ # the decider's to decide, the target, no quarantined item, and the manifest and source
515
+ # unchanged (approve-what-you-saw; a1r on #146 and #149). A racing decider waits on
516
+ # BEGIN IMMEDIATE and then reads the outcome.
517
+ stale_reason = None
518
+ copies: list[str] = []
519
+ with self.backend.atomic():
520
+ self._still_open(p["id"], token)
521
+ to = self.backend.get_node(p["to"])
522
+ if not to:
523
+ raise TrustError("target scope no longer exists")
524
+ items = [self.backend.get(x) for x in p["items"]]
525
+ if any(i and i.status == "quarantined" for i in items):
526
+ # Quarantined after it was parked: the manifest still matches, but a manifest
527
+ # holding a quarantined item cannot be approved (step-up spec §11, R5). The
528
+ # proposal stays open, because Deny still is. Which event the ENGINE writes for
529
+ # this refusal is #125 (approval.stale means drift and a stale proposal); until
530
+ # then the presence layer records it (step_up `closed`, reason `refused`).
531
+ raise TrustError("Contains a quarantined item. It cannot move.")
532
+ current = self.manifest_hash(p["items"], p["to"], self.audience(to))
533
+ moved = [i for i in items if not i or i.scope != p["from"]] # the source is bound too
534
+ if current != p["manifest"] or moved:
535
+ p["status"] = "stale"
536
+ self.backend.put_proposal(p)
537
+ stale_reason = (
538
+ "an item moved since the proposal (TOCTOU)"
539
+ if moved
540
+ else "manifest changed since proposal (TOCTOU)"
541
+ )
542
+ # A TOCTOU refusal is not a human "no": its own event (freeze item 39).
543
+ self.ledger.append(
544
+ "approval.stale",
545
+ actor=actor,
546
+ principal=token.principal,
547
+ subject=p["id"],
548
+ reason=stale_reason,
549
+ )
550
+ else:
551
+ proposer = (p.get("proposed_by") or {}).get("principal", "client")
552
+ reset = []
553
+ # Every move, the status and the chain entry land together: a failure on item k
554
+ # rolls back items 1…k-1 too, so a failed approval has moved nothing.
555
+ for item in items:
556
+ if not item:
557
+ continue
558
+ if p.get("kind") == "copy":
559
+ # A copy is a new write: it lands unverified whoever proposed it.
560
+ copies.append(self._do_copy(item, to, actor, token.principal).id)
561
+ continue
562
+ if self._reset_if_agent_run(item, proposer):
563
+ reset.append(item.id)
564
+ self._do_move(item, to, actor, token.principal)
565
+ p["status"] = "executed"
566
+ p["executed_at"] = now_iso()
567
+ p["approved_by"] = actor
568
+ self.backend.put_proposal(p)
569
+ self.ledger.append(
570
+ "approval.execute",
571
+ actor=actor,
572
+ principal=token.principal,
573
+ subject=p["id"],
574
+ scope=to.id,
575
+ items=p["items"],
576
+ manifest=p["manifest"],
577
+ reset=reset,
578
+ )
579
+ if stale_reason:
580
+ # Raised after the transaction commits, so the stale status and its event stay.
581
+ raise TrustError("manifest changed since the proposal was made — re-propose")
582
+ # A copy's caller learns the new items, which the stored proposal does not name.
583
+ return {**p, "copies": copies} if copies else p
584
+
585
+ def deny(self, proposal_id: str, *, token: Token, actor: str) -> dict[str, Any]:
586
+ self._human_only(token, "gate.confirm")
587
+ p = self.backend.get_proposal(proposal_id)
588
+ if not p or p["status"] != "open" or not self.decides_over(token, p):
589
+ raise TrustError("no open proposal with that id")
590
+ p["status"] = "denied"
591
+ with self.backend.atomic():
592
+ self._still_open(p["id"], token)
593
+ self.backend.put_proposal(p)
594
+ self.ledger.append(
595
+ "approval.deny", actor=actor, principal=token.principal, subject=p["id"]
596
+ )
597
+ return p
598
+
599
+ def _still_open(self, proposal_id: str, token: Token) -> None:
600
+ """Re-read the proposal under the write lock and refuse unless it is still open (#118)
601
+ and still the decider's: the token re-read (a revoke since the pre-lock check counts) and
602
+ its coverage of both ends re-checked against the tree as it now stands (a1r on #149).
603
+ The checks above run before the lock, so two deciders (a lifeboat tab and a CLI `trust
604
+ approve`) could both see it open; `atomic()` takes BEGIN IMMEDIATE, so whichever decides
605
+ second waits here, then finds it decided and lands nothing. The answer is the one a
606
+ missing id gets."""
607
+ current = self.backend.get_proposal(proposal_id)
608
+ fresh = self.refresh(token)
609
+ if not current or current["status"] != "open" or not fresh:
610
+ raise TrustError("no open proposal with that id")
611
+ if not self.decides_over(fresh, current):
612
+ raise TrustError("no open proposal with that id")
613
+
614
+ def decides_over(self, token: Token, proposal: dict[str, Any]) -> bool:
615
+ """Whether `token` may decide (or see) this proposal: it covers both ends of the move,
616
+ as `move` requires of whoever proposes one (#131). A token that does not is answered as
617
+ if the proposal did not exist."""
618
+ frm, to = self.backend.get_node(proposal["from"]), self.backend.get_node(proposal["to"])
619
+ return bool(frm and to and self.covers(token, frm) and self.covers(token, to))
620
+
621
+ # -- internals -------------------------------------------------------------------------------
622
+ @staticmethod
623
+ def _reset_if_agent_run(item: ContextItem, principal: str) -> bool:
624
+ """An agent-run move lands its item unverified, on every path (silent or approved): the
625
+ landing is a write, and writes land unverified (step-up spec §11). Whether a human-run
626
+ move keeps a verified status is the freeze's open trust-on-copy question (#121); until it
627
+ is settled, human-run moves keep it. The reset is recorded on the chain by the caller."""
628
+ if principal == "interactive" or item.status != "verified":
629
+ return False
630
+ item.trust = {"status": "unverified"}
631
+ return True
632
+
633
+ def _do_move(self, item: ContextItem, to: Node, actor: str, principal: str) -> None:
634
+ frm = item.scope
635
+ item.scope = to.id
636
+ item.visibility["ring"] = to.type
637
+ item.lifecycle["updated_at"] = now_iso()
638
+ self.backend.put(item)
639
+ self.ledger.append(
640
+ "item.move", actor=actor, principal=principal, subject=item.id, scope=to.id, from_=frm
641
+ )
642
+
643
+ def _do_copy(self, item: ContextItem, to: Node, actor: str, principal: str) -> ContextItem:
644
+ """A new item at `to`: a fresh id, unverified (a copy is a new write), derived from the
645
+ source, so quarantining the source reaches the copy too. An artifact's bytes are not
646
+ duplicated: the copy names the same `content.sha256` ([0.3 · 41]'s dedup)."""
647
+ now = now_iso()
648
+ new = ContextItem.from_dict(item.to_dict())
649
+ new.id = ulid()
650
+ new.scope = to.id
651
+ new.trust = {"status": "unverified"}
652
+ new.provenance = {k: v for k, v in item.provenance.items() if k != "approved_by"} | {
653
+ "derived_from": item.id
654
+ }
655
+ new.lifecycle = {"created_at": now, "updated_at": now, "version": 1}
656
+ new.visibility = {**item.visibility, "ring": to.type}
657
+ self.backend.put(new)
658
+ self.ledger.append(
659
+ "item.copy", actor=actor, principal=principal, subject=new.id, scope=to.id,
660
+ **{"from": item.id},
661
+ )
662
+ return new
663
+
664
+ @staticmethod
665
+ def _human_only(token: Token, act: str) -> None:
666
+ if token.principal != "interactive":
667
+ raise HumanOnly(f"{act} is a human-only act; a client principal can only propose")
668
+
669
+
670
+ def _role_name(capabilities: list[str]) -> str:
671
+ """The largest role bundle the capabilities hold, read from `ROLE_BUNDLES` — never a second
672
+ mapping beside it."""
673
+ caps = set(capabilities)
674
+ held = [role for role, bundle in ROLE_BUNDLES.items() if bundle <= caps]
675
+ return max(held, key=lambda role: len(ROLE_BUNDLES[role]), default="reader")