governed-objects 0.2.1__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 (88) hide show
  1. governed_objects/__init__.py +7 -0
  2. governed_objects/_version.py +38 -0
  3. governed_objects/adapters/base.py +80 -0
  4. governed_objects/adapters/context.py +58 -0
  5. governed_objects/adapters/mandate.py +45 -0
  6. governed_objects/adapters/registry.py +25 -0
  7. governed_objects/agent/session.py +111 -0
  8. governed_objects/applications/registry.py +39 -0
  9. governed_objects/authority/rules.py +63 -0
  10. governed_objects/delegation/configuration.py +74 -0
  11. governed_objects/delegation/mandate.py +44 -0
  12. governed_objects/delegation/materializer.py +152 -0
  13. governed_objects/delegation/projection.py +48 -0
  14. governed_objects/delegation/resolver.py +180 -0
  15. governed_objects/delegation/scope.py +75 -0
  16. governed_objects/delegation/service.py +245 -0
  17. governed_objects/delegation/validator.py +159 -0
  18. governed_objects/domain/__init__.py +21 -0
  19. governed_objects/domain/actor_manifest.py +40 -0
  20. governed_objects/domain/actors.py +55 -0
  21. governed_objects/domain/clock.py +28 -0
  22. governed_objects/domain/command.py +95 -0
  23. governed_objects/domain/command_context.py +35 -0
  24. governed_objects/domain/models.py +110 -0
  25. governed_objects/domain/traversal.py +25 -0
  26. governed_objects/events/lineage.py +71 -0
  27. governed_objects/events/reducers/__init__.py +2 -0
  28. governed_objects/events/reducers/mandate.py +31 -0
  29. governed_objects/events/replay.py +208 -0
  30. governed_objects/idempotency/store.py +160 -0
  31. governed_objects/interchange/__init__.py +49 -0
  32. governed_objects/interchange/artifact.py +310 -0
  33. governed_objects/interchange/export.py +345 -0
  34. governed_objects/interchange/governance.py +26 -0
  35. governed_objects/interchange/importer.py +672 -0
  36. governed_objects/interchange/prc.py +76 -0
  37. governed_objects/interchange/types.py +228 -0
  38. governed_objects/llm/__init__.py +16 -0
  39. governed_objects/llm/loop.py +130 -0
  40. governed_objects/llm/model.py +44 -0
  41. governed_objects/llm/tools/registry.py +87 -0
  42. governed_objects/llm/tools/results.py +53 -0
  43. governed_objects/llm/tools/schemas.py +67 -0
  44. governed_objects/llm/tools/surface.py +252 -0
  45. governed_objects/llm/trace.py +58 -0
  46. governed_objects/materialization/service.py +107 -0
  47. governed_objects/observations/__init__.py +3 -0
  48. governed_objects/observations/ingestion.py +375 -0
  49. governed_objects/observations/mapping.py +48 -0
  50. governed_objects/observations/models.py +81 -0
  51. governed_objects/observations/store.py +214 -0
  52. governed_objects/observations/validation.py +188 -0
  53. governed_objects/outbound/__init__.py +3 -0
  54. governed_objects/outbound/models.py +94 -0
  55. governed_objects/outbound/service.py +502 -0
  56. governed_objects/outbound/store.py +147 -0
  57. governed_objects/persistence/sqlite.py +635 -0
  58. governed_objects/policy/constraints.py +9 -0
  59. governed_objects/policy/context.py +28 -0
  60. governed_objects/policy/evaluator.py +301 -0
  61. governed_objects/policy/outcomes.py +93 -0
  62. governed_objects/policy/reasons.py +43 -0
  63. governed_objects/providers/base.py +26 -0
  64. governed_objects/providers/binding.py +42 -0
  65. governed_objects/providers/capabilities.py +27 -0
  66. governed_objects/providers/errors.py +48 -0
  67. governed_objects/providers/projection.py +25 -0
  68. governed_objects/providers/registry.py +59 -0
  69. governed_objects/query/service.py +171 -0
  70. governed_objects/query/traversal.py +154 -0
  71. governed_objects/reconciliation/service.py +213 -0
  72. governed_objects/registration/detach.py +43 -0
  73. governed_objects/registration/service.py +113 -0
  74. governed_objects/relationships/canonical.py +55 -0
  75. governed_objects/relationships/sync.py +63 -0
  76. governed_objects/relationships/vocabulary.py +12 -0
  77. governed_objects/runtime/runtime.py +1919 -0
  78. governed_objects/types/canonicalizers/base.py +15 -0
  79. governed_objects/types/extensions.py +48 -0
  80. governed_objects/types/lifecycle.py +65 -0
  81. governed_objects/types/registry.py +171 -0
  82. governed_objects/types/schema.py +90 -0
  83. governed_objects/types/validation.py +57 -0
  84. governed_objects-0.2.1.dist-info/METADATA +184 -0
  85. governed_objects-0.2.1.dist-info/RECORD +88 -0
  86. governed_objects-0.2.1.dist-info/WHEEL +4 -0
  87. governed_objects-0.2.1.dist-info/licenses/LICENSE +202 -0
  88. governed_objects-0.2.1.dist-info/licenses/NOTICE +12 -0
@@ -0,0 +1,635 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Brafford Labs, LLC
3
+ """SQLite persistence for governed objects."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import json
8
+ import sqlite3
9
+ from contextlib import contextmanager
10
+ from datetime import UTC, datetime
11
+ from functools import wraps
12
+ from pathlib import Path
13
+ from threading import RLock
14
+ from typing import Any, Protocol
15
+
16
+ from governed_objects.domain.models import Actor, ActorType, Decision, GovernedObject, GovernanceEvent, Relationship
17
+
18
+ INT64_MAX = 2**63 - 1
19
+
20
+
21
+ def _connection_locked(method):
22
+ """Serialize a complete synchronous store/sidecar operation, including reads."""
23
+ @wraps(method)
24
+ def locked(self, *args, **kwargs):
25
+ with self._connection_guard:
26
+ return method(self, *args, **kwargs)
27
+ return locked
28
+
29
+
30
+ class ObjectVersionSpaceExhausted(Exception):
31
+ """No unused Object Version remains for the object (OBJECT_VERSION_SPACE_EXHAUSTED)."""
32
+
33
+ code = "OBJECT_VERSION_SPACE_EXHAUSTED"
34
+
35
+ def __init__(self, object_id: str) -> None:
36
+ super().__init__(f"object version space exhausted: {object_id}")
37
+ self.object_id = object_id
38
+
39
+
40
+ class IdentityAlreadyExists(Exception):
41
+ def __init__(self, identities: list[str]) -> None:
42
+ super().__init__(f"identities already present: {identities}")
43
+ self.identities = identities
44
+
45
+
46
+ class ObjectRepository(Protocol):
47
+ def save(self, obj: GovernedObject) -> None: ...
48
+ def get(self, object_id: str) -> GovernedObject | None: ...
49
+ def list_all(self) -> list[GovernedObject]: ...
50
+ def list_by_type(self, object_type: str) -> list[GovernedObject]: ...
51
+ def list_by_state(self, object_type: str, state: str) -> list[GovernedObject]: ...
52
+
53
+
54
+ class EventStore(Protocol):
55
+ def append(self, event: GovernanceEvent) -> None: ...
56
+ def list_for_object(self, object_id: str) -> list[GovernanceEvent]: ...
57
+ def list_all(self) -> list[GovernanceEvent]: ...
58
+
59
+
60
+ class RelationshipStore(Protocol):
61
+ def add(self, rel: Relationship) -> None: ...
62
+ def list_for_source(self, source_id: str) -> list[Relationship]: ...
63
+ def list_for_target(self, target_id: str) -> list[Relationship]: ...
64
+ def list_all(self) -> list[Relationship]: ...
65
+
66
+
67
+ class ActorRepository(Protocol):
68
+ def save(self, actor: Actor) -> None: ...
69
+ def get(self, actor_id: str) -> Actor | None: ...
70
+
71
+
72
+ class SQLiteStore:
73
+ """Combined SQLite persistence for objects, events, and relationships."""
74
+
75
+ def __init__(self, db_path: Path) -> None:
76
+ self._connection_guard = RLock()
77
+ self._db_path = db_path
78
+ db_path.parent.mkdir(parents=True, exist_ok=True)
79
+ self._conn = sqlite3.connect(str(db_path), check_same_thread=False)
80
+ self._conn.row_factory = sqlite3.Row
81
+ self._observation_transaction_active = False
82
+ self._init_schema()
83
+
84
+ @_connection_locked
85
+ def close(self) -> None:
86
+ if self._observation_transaction_active:
87
+ raise RuntimeError("operation requires an autonomous connection")
88
+ self._conn.close()
89
+
90
+ @contextmanager
91
+ def observation_transaction(self):
92
+ """Owned local admission only; callbacks/provider I/O stay outside."""
93
+ with self._connection_guard:
94
+ self._require_autonomous()
95
+ self._conn.execute("BEGIN IMMEDIATE")
96
+ self._observation_transaction_active = True
97
+ try:
98
+ yield
99
+ self._conn.commit()
100
+ except BaseException:
101
+ self._conn.rollback()
102
+ raise
103
+ finally:
104
+ self._observation_transaction_active = False
105
+
106
+ def _require_autonomous(self) -> None:
107
+ # Called under the shared guard, before any SQL/DDL or close effects.
108
+ if self._observation_transaction_active or self._conn.in_transaction:
109
+ raise RuntimeError("operation requires an autonomous connection")
110
+
111
+ @_connection_locked
112
+ def _commit_if_autonomous(self) -> None:
113
+ if not self._observation_transaction_active:
114
+ self._conn.commit()
115
+
116
+ @_connection_locked
117
+ def _init_schema(self) -> None:
118
+ self._require_autonomous()
119
+ self._conn.executescript(
120
+ """
121
+ CREATE TABLE IF NOT EXISTS objects (
122
+ id TEXT PRIMARY KEY,
123
+ type TEXT NOT NULL,
124
+ type_version TEXT NOT NULL DEFAULT '1',
125
+ version INTEGER NOT NULL,
126
+ state TEXT NOT NULL,
127
+ data_json TEXT NOT NULL,
128
+ policy_json TEXT NOT NULL,
129
+ contract_json TEXT NOT NULL,
130
+ metadata_json TEXT NOT NULL,
131
+ storage_ref TEXT
132
+ );
133
+ CREATE TABLE IF NOT EXISTS events (
134
+ event_id TEXT PRIMARY KEY,
135
+ timestamp TEXT NOT NULL,
136
+ object_id TEXT NOT NULL,
137
+ object_type TEXT NOT NULL,
138
+ type_version TEXT,
139
+ actor_id TEXT NOT NULL,
140
+ actor_type TEXT NOT NULL,
141
+ action TEXT NOT NULL,
142
+ decision TEXT NOT NULL,
143
+ event_type TEXT NOT NULL,
144
+ previous_state TEXT,
145
+ new_state TEXT,
146
+ reason TEXT,
147
+ object_version INTEGER,
148
+ details_json TEXT
149
+ );
150
+ CREATE INDEX IF NOT EXISTS idx_events_object ON events(object_id);
151
+ CREATE TABLE IF NOT EXISTS relationships (
152
+ source_id TEXT NOT NULL,
153
+ relation TEXT NOT NULL,
154
+ target_id TEXT NOT NULL,
155
+ target_type TEXT,
156
+ metadata_json TEXT DEFAULT '{}',
157
+ PRIMARY KEY (source_id, relation, target_id)
158
+ );
159
+ CREATE INDEX IF NOT EXISTS idx_rel_source ON relationships(source_id);
160
+ CREATE INDEX IF NOT EXISTS idx_rel_target ON relationships(target_id);
161
+ """
162
+ )
163
+ self._conn.commit()
164
+ self._migrate_schema()
165
+
166
+ @_connection_locked
167
+ def _migrate_schema(self) -> None:
168
+ self._require_autonomous()
169
+ rel_cols = {row[1] for row in self._conn.execute("PRAGMA table_info(relationships)")}
170
+ if "metadata_json" not in rel_cols:
171
+ self._conn.execute(
172
+ "ALTER TABLE relationships ADD COLUMN metadata_json TEXT DEFAULT '{}'"
173
+ )
174
+ self._conn.commit()
175
+ obj_cols = {row[1] for row in self._conn.execute("PRAGMA table_info(objects)")}
176
+ if "type_version" not in obj_cols:
177
+ self._conn.execute(
178
+ "ALTER TABLE objects ADD COLUMN type_version TEXT NOT NULL DEFAULT '1'"
179
+ )
180
+ self._conn.commit()
181
+ event_cols = {row[1] for row in self._conn.execute("PRAGMA table_info(events)")}
182
+ if "type_version" not in event_cols:
183
+ self._conn.execute("ALTER TABLE events ADD COLUMN type_version TEXT")
184
+ self._conn.commit()
185
+ # EXPERIMENTAL. Legacy rows keep NULL:
186
+ # positions are never back-filled from timestamps or rowid.
187
+ if "history_position" not in event_cols:
188
+ self._conn.execute("ALTER TABLE events ADD COLUMN history_position INTEGER")
189
+ self._conn.commit()
190
+ self._conn.execute(
191
+ "CREATE UNIQUE INDEX IF NOT EXISTS idx_events_history_position "
192
+ "ON events(object_id, history_position) WHERE history_position IS NOT NULL"
193
+ )
194
+ if "governance_reference" not in obj_cols:
195
+ self._conn.execute("ALTER TABLE objects ADD COLUMN governance_reference TEXT")
196
+ # EXPERIMENTAL. NULL means the
197
+ # timestamp column is the acceptance instant (every native row).
198
+ if "accepted_at_recorded" not in event_cols:
199
+ self._conn.execute("ALTER TABLE events ADD COLUMN accepted_at_recorded INTEGER")
200
+ # EXPERIMENTAL. Highest Object
201
+ # Version ever issued for the object: allocation metadata, never
202
+ # canonical state and never exported. NULL means "equal to version",
203
+ # which holds for every object whose versions only ever increased.
204
+ if "version_high_water" not in obj_cols:
205
+ self._conn.execute("ALTER TABLE objects ADD COLUMN version_high_water INTEGER")
206
+ # Import provenance is Operational Metadata, kept outside accepted history.
207
+ self._conn.execute(
208
+ """
209
+ CREATE TABLE IF NOT EXISTS interchange_imports (
210
+ import_id TEXT PRIMARY KEY,
211
+ record_json TEXT NOT NULL
212
+ )
213
+ """
214
+ )
215
+ self._conn.commit()
216
+
217
+ # --- Objects ---
218
+
219
+ @_connection_locked
220
+ def save(self, obj: GovernedObject) -> None:
221
+ self._conn.execute(
222
+ """
223
+ INSERT INTO objects (id, type, type_version, version, state, data_json, policy_json,
224
+ contract_json, metadata_json, storage_ref, governance_reference,
225
+ version_high_water)
226
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
227
+ ON CONFLICT(id) DO UPDATE SET
228
+ type=excluded.type,
229
+ type_version=excluded.type_version,
230
+ version_high_water=MAX(COALESCE(objects.version_high_water, objects.version),
231
+ excluded.version),
232
+ version=excluded.version,
233
+ state=excluded.state,
234
+ data_json=excluded.data_json,
235
+ policy_json=excluded.policy_json,
236
+ contract_json=excluded.contract_json,
237
+ metadata_json=excluded.metadata_json,
238
+ storage_ref=excluded.storage_ref,
239
+ governance_reference=excluded.governance_reference
240
+ """,
241
+ (
242
+ obj.id,
243
+ obj.type,
244
+ obj.type_version,
245
+ obj.version,
246
+ obj.state,
247
+ json.dumps(obj.data),
248
+ json.dumps(obj.policy),
249
+ json.dumps(obj.contract),
250
+ json.dumps(obj.metadata),
251
+ obj.storage_ref,
252
+ obj.governance_reference,
253
+ obj.version,
254
+ ),
255
+ )
256
+ self._commit_if_autonomous()
257
+
258
+ @_connection_locked
259
+ def version_high_water(self, object_id: str) -> int | None:
260
+ """Highest Object Version ever issued for the object (EXPERIMENTAL
261
+ allocation metadata), or None when the object does not exist."""
262
+ row = self._conn.execute(
263
+ "SELECT COALESCE(version_high_water, version) FROM objects WHERE id = ?", (object_id,)
264
+ ).fetchone()
265
+ return None if row is None else row[0]
266
+
267
+ @_connection_locked
268
+ def next_object_version(self, obj: GovernedObject) -> int | None:
269
+ """Next unused Object Version for obj, or None when the version space
270
+ is exhausted.
271
+
272
+ Allocation is implementation-defined: one above the highest version ever
273
+ issued for the identity (imported tokens included), so a new version never
274
+ equals any prior one even when imported history is not monotonic. Only
275
+ saving the accepted change advances the high-water mark.
276
+ """
277
+ issued = self.version_high_water(obj.id)
278
+ top = obj.version if issued is None else max(obj.version, issued)
279
+ if top >= INT64_MAX:
280
+ return None
281
+ return top + 1
282
+
283
+ @_connection_locked
284
+ def get(self, object_id: str) -> GovernedObject | None:
285
+ row = self._conn.execute("SELECT * FROM objects WHERE id = ?", (object_id,)).fetchone()
286
+ if row is None:
287
+ return None
288
+ return self._row_to_object(row)
289
+
290
+ @_connection_locked
291
+ def list_all(self) -> list[GovernedObject]:
292
+ rows = self._conn.execute("SELECT * FROM objects ORDER BY id").fetchall()
293
+ return [self._row_to_object(r) for r in rows]
294
+
295
+ @_connection_locked
296
+ def list_by_type(self, object_type: str) -> list[GovernedObject]:
297
+ rows = self._conn.execute(
298
+ "SELECT * FROM objects WHERE type = ? ORDER BY id", (object_type,)
299
+ ).fetchall()
300
+ return [self._row_to_object(r) for r in rows]
301
+
302
+ @_connection_locked
303
+ def list_by_types(self, object_types: list[str]) -> list[GovernedObject]:
304
+ if not object_types:
305
+ return []
306
+ placeholders = ",".join("?" for _ in object_types)
307
+ rows = self._conn.execute(
308
+ f"SELECT * FROM objects WHERE type IN ({placeholders}) ORDER BY id",
309
+ object_types,
310
+ ).fetchall()
311
+ return [self._row_to_object(r) for r in rows]
312
+
313
+ @_connection_locked
314
+ def list_by_state(self, object_type: str, state: str) -> list[GovernedObject]:
315
+ rows = self._conn.execute(
316
+ "SELECT * FROM objects WHERE type = ? AND state = ? ORDER BY id",
317
+ (object_type, state),
318
+ ).fetchall()
319
+ return [self._row_to_object(r) for r in rows]
320
+
321
+ @staticmethod
322
+ def _row_to_object(row: sqlite3.Row) -> GovernedObject:
323
+ type_version = row["type_version"] if "type_version" in row.keys() else "1"
324
+ return GovernedObject(
325
+ id=row["id"],
326
+ type=row["type"],
327
+ type_version=type_version,
328
+ version=row["version"],
329
+ state=row["state"],
330
+ data=json.loads(row["data_json"]),
331
+ policy=json.loads(row["policy_json"]),
332
+ contract=json.loads(row["contract_json"]),
333
+ metadata=json.loads(row["metadata_json"]),
334
+ storage_ref=row["storage_ref"],
335
+ governance_reference=(
336
+ row["governance_reference"] if "governance_reference" in row.keys() else None
337
+ ),
338
+ )
339
+
340
+ # --- Events ---
341
+
342
+ @_connection_locked
343
+ def append(self, event: GovernanceEvent) -> None:
344
+ self._conn.execute(
345
+ """
346
+ INSERT INTO events (event_id, timestamp, object_id, object_type, type_version,
347
+ actor_id, actor_type, action, decision, event_type,
348
+ previous_state, new_state, reason, object_version, details_json,
349
+ history_position)
350
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
351
+ """,
352
+ (*self._event_values(event), event.history_position),
353
+ )
354
+ self._commit_if_autonomous()
355
+
356
+ @_connection_locked
357
+ def append_accepted(self, event: GovernanceEvent) -> GovernanceEvent:
358
+ """Append an accepted canonical change and assign its per-object
359
+ accepted-history position (1 + highest position already recorded for
360
+ the object) in the same statement. Returns the event with its position.
361
+
362
+ EXPERIMENTAL. The position is the only
363
+ source of accepted-history order; timestamps and rowid are not used.
364
+ """
365
+ self._conn.execute(
366
+ """
367
+ INSERT INTO events (event_id, timestamp, object_id, object_type, type_version,
368
+ actor_id, actor_type, action, decision, event_type,
369
+ previous_state, new_state, reason, object_version, details_json,
370
+ history_position)
371
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
372
+ (SELECT COALESCE(MAX(history_position), 0) + 1
373
+ FROM events WHERE object_id = ?))
374
+ """,
375
+ (*self._event_values(event), event.object_id),
376
+ )
377
+ self._commit_if_autonomous()
378
+ row = self._conn.execute(
379
+ "SELECT history_position FROM events WHERE event_id = ?", (event.event_id,)
380
+ ).fetchone()
381
+ return event.model_copy(update={"history_position": row["history_position"]})
382
+
383
+ @staticmethod
384
+ def _event_values(event: GovernanceEvent) -> tuple:
385
+ return (
386
+ event.event_id,
387
+ event.timestamp.isoformat(),
388
+ event.object_id,
389
+ event.object_type,
390
+ event.type_version,
391
+ event.actor_id,
392
+ event.actor_type,
393
+ event.action,
394
+ event.decision.value,
395
+ event.event_type,
396
+ event.previous_state,
397
+ event.new_state,
398
+ event.reason,
399
+ event.object_version,
400
+ json.dumps(event.details),
401
+ )
402
+
403
+ @_connection_locked
404
+ def list_for_object(self, object_id: str) -> list[GovernanceEvent]:
405
+ rows = self._conn.execute(
406
+ "SELECT * FROM events WHERE object_id = ? ORDER BY timestamp",
407
+ (object_id,),
408
+ ).fetchall()
409
+ return [self._row_to_event(r) for r in rows]
410
+
411
+ @_connection_locked
412
+ def list_accepted_for_object(self, object_id: str) -> list[GovernanceEvent]:
413
+ """Rows carrying an accepted-history position, in position order."""
414
+ rows = self._conn.execute(
415
+ "SELECT * FROM events WHERE object_id = ? AND history_position IS NOT NULL "
416
+ "ORDER BY history_position",
417
+ (object_id,),
418
+ ).fetchall()
419
+ return [self._row_to_event(r) for r in rows]
420
+
421
+ @_connection_locked
422
+ def list_all_events(self) -> list[GovernanceEvent]:
423
+ rows = self._conn.execute("SELECT * FROM events ORDER BY timestamp").fetchall()
424
+ return [self._row_to_event(r) for r in rows]
425
+
426
+ @staticmethod
427
+ def _row_to_event(row: sqlite3.Row) -> GovernanceEvent:
428
+ ts = datetime.fromisoformat(row["timestamp"])
429
+ if ts.tzinfo is None:
430
+ ts = ts.replace(tzinfo=UTC)
431
+ return GovernanceEvent(
432
+ event_id=row["event_id"],
433
+ timestamp=ts,
434
+ object_id=row["object_id"],
435
+ object_type=row["object_type"],
436
+ type_version=row["type_version"] if "type_version" in row.keys() else None,
437
+ actor_id=row["actor_id"],
438
+ actor_type=row["actor_type"],
439
+ action=row["action"],
440
+ decision=Decision(row["decision"]),
441
+ event_type=row["event_type"],
442
+ previous_state=row["previous_state"],
443
+ new_state=row["new_state"],
444
+ reason=row["reason"] or "",
445
+ object_version=row["object_version"] or 1,
446
+ details=json.loads(row["details_json"] or "{}"),
447
+ history_position=(
448
+ row["history_position"] if "history_position" in row.keys() else None
449
+ ),
450
+ accepted_at_recorded=(
451
+ "accepted_at_recorded" not in row.keys()
452
+ or row["accepted_at_recorded"] is None
453
+ or bool(row["accepted_at_recorded"])
454
+ ),
455
+ )
456
+
457
+ # --- Interchange import (EXPERIMENTAL) ---
458
+
459
+ @_connection_locked
460
+ def identities_present(self, identities: list[str]) -> list[str]:
461
+ """Identities for which this store holds an object, an accepted
462
+ history row, or a canonical outgoing relationship."""
463
+ return [i for i in identities if self._identity_present(i)]
464
+
465
+ def _identity_present(self, identity: str) -> bool:
466
+ conn = self._conn
467
+ return bool(
468
+ conn.execute("SELECT 1 FROM objects WHERE id = ?", (identity,)).fetchone()
469
+ or conn.execute(
470
+ "SELECT 1 FROM events WHERE object_id = ? AND history_position IS NOT NULL",
471
+ (identity,),
472
+ ).fetchone()
473
+ or conn.execute(
474
+ "SELECT 1 FROM relationships WHERE source_id = ?", (identity,)
475
+ ).fetchone()
476
+ )
477
+
478
+ @_connection_locked
479
+ def restore_imported(
480
+ self,
481
+ objects: list[GovernedObject],
482
+ events: list[GovernanceEvent],
483
+ relationships: list[Relationship],
484
+ record: dict[str, Any],
485
+ ) -> None:
486
+ """Write a fully validated import in ONE transaction: the objects, their
487
+ accepted history rows (positions and versions exactly as given), their
488
+ canonical relationships, and the import provenance record. The identity
489
+ check is repeated inside the transaction; on any failure everything is
490
+ rolled back and :class:`IdentityAlreadyExists` or the error propagates."""
491
+ conn = self._conn
492
+ with self.observation_transaction():
493
+ present = [o.id for o in objects if self._identity_present(o.id)]
494
+ if present:
495
+ raise IdentityAlreadyExists(present)
496
+ for obj in objects:
497
+ self._insert_restored_object(obj)
498
+ for event in events:
499
+ self._insert_restored_event(event)
500
+ for rel in relationships:
501
+ self._insert_restored_relationship(rel)
502
+ for obj in objects:
503
+ self._initialize_version_high_water(obj.id)
504
+ conn.execute(
505
+ "INSERT INTO interchange_imports (import_id, record_json) VALUES (?, ?)",
506
+ (record["import_id"], json.dumps(record, sort_keys=True)),
507
+ )
508
+
509
+ def _insert_restored_object(self, obj: GovernedObject) -> None:
510
+ self._conn.execute(
511
+ """
512
+ INSERT INTO objects (id, type, type_version, version, state, data_json, policy_json,
513
+ contract_json, metadata_json, storage_ref, governance_reference)
514
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
515
+ """,
516
+ (
517
+ obj.id, obj.type, obj.type_version, obj.version, obj.state,
518
+ json.dumps(obj.data), json.dumps(obj.policy), json.dumps(obj.contract),
519
+ json.dumps(obj.metadata), obj.storage_ref, obj.governance_reference,
520
+ ),
521
+ )
522
+
523
+ def _initialize_version_high_water(self, object_id: str) -> None:
524
+ # Imported tokens need not be monotonic, so the current version alone
525
+ # does not bound them.
526
+ self._conn.execute(
527
+ """
528
+ UPDATE objects SET version_high_water = MAX(version, COALESCE((
529
+ SELECT MAX(object_version) FROM events
530
+ WHERE events.object_id = objects.id AND history_position IS NOT NULL
531
+ ), version))
532
+ WHERE id = ?
533
+ """,
534
+ (object_id,),
535
+ )
536
+
537
+ def _insert_restored_event(self, event: GovernanceEvent) -> None:
538
+ self._conn.execute(
539
+ """
540
+ INSERT INTO events (event_id, timestamp, object_id, object_type, type_version,
541
+ actor_id, actor_type, action, decision, event_type,
542
+ previous_state, new_state, reason, object_version, details_json,
543
+ history_position, accepted_at_recorded)
544
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
545
+ """,
546
+ (*self._event_values(event), event.history_position, int(event.accepted_at_recorded)),
547
+ )
548
+
549
+ def _insert_restored_relationship(self, rel: Relationship) -> None:
550
+ self._conn.execute(
551
+ """
552
+ INSERT INTO relationships (source_id, relation, target_id, target_type, metadata_json)
553
+ VALUES (?, ?, ?, ?, ?)
554
+ """,
555
+ (rel.source_id, rel.relation, rel.target_id, rel.target_type, json.dumps(rel.metadata)),
556
+ )
557
+
558
+ @_connection_locked
559
+ def list_imports(self) -> list[dict[str, Any]]:
560
+ rows = self._conn.execute(
561
+ "SELECT record_json FROM interchange_imports ORDER BY rowid"
562
+ ).fetchall()
563
+ return [json.loads(r["record_json"]) for r in rows]
564
+
565
+ @_connection_locked
566
+ def dump_tables(self) -> dict[str, list[dict[str, Any]]]:
567
+ """Every row of every table, in a deterministic order (diagnostic)."""
568
+ out: dict[str, list[dict[str, Any]]] = {}
569
+ tables = [
570
+ r[0]
571
+ for r in self._conn.execute(
572
+ "SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name"
573
+ )
574
+ ]
575
+ for table in tables:
576
+ rows = [dict(r) for r in self._conn.execute(f'SELECT * FROM "{table}"')]
577
+ out[table] = sorted(rows, key=lambda r: json.dumps(r, sort_keys=True, default=str))
578
+ return out
579
+
580
+ # --- Relationships ---
581
+
582
+ @_connection_locked
583
+ def add(self, rel: Relationship) -> None:
584
+ self._conn.execute(
585
+ """
586
+ INSERT OR REPLACE INTO relationships (source_id, relation, target_id, target_type, metadata_json)
587
+ VALUES (?, ?, ?, ?, ?)
588
+ """,
589
+ (
590
+ rel.source_id,
591
+ rel.relation,
592
+ rel.target_id,
593
+ rel.target_type,
594
+ json.dumps(rel.metadata),
595
+ ),
596
+ )
597
+ self._commit_if_autonomous()
598
+
599
+ @_connection_locked
600
+ def remove(self, source_id: str, relation: str, target_id: str) -> None:
601
+ self._conn.execute(
602
+ "DELETE FROM relationships WHERE source_id = ? AND relation = ? AND target_id = ?",
603
+ (source_id, relation, target_id),
604
+ )
605
+ self._commit_if_autonomous()
606
+
607
+ @_connection_locked
608
+ def list_for_source(self, source_id: str) -> list[Relationship]:
609
+ rows = self._conn.execute(
610
+ "SELECT * FROM relationships WHERE source_id = ?", (source_id,)
611
+ ).fetchall()
612
+ return [self._row_to_rel(r) for r in rows]
613
+
614
+ @_connection_locked
615
+ def list_for_target(self, target_id: str) -> list[Relationship]:
616
+ rows = self._conn.execute(
617
+ "SELECT * FROM relationships WHERE target_id = ?", (target_id,)
618
+ ).fetchall()
619
+ return [self._row_to_rel(r) for r in rows]
620
+
621
+ @_connection_locked
622
+ def list_all_relationships(self) -> list[Relationship]:
623
+ rows = self._conn.execute("SELECT * FROM relationships").fetchall()
624
+ return [self._row_to_rel(r) for r in rows]
625
+
626
+ @staticmethod
627
+ def _row_to_rel(row: sqlite3.Row) -> Relationship:
628
+ meta_raw = row["metadata_json"] if "metadata_json" in row.keys() else "{}"
629
+ return Relationship(
630
+ source_id=row["source_id"],
631
+ relation=row["relation"],
632
+ target_id=row["target_id"],
633
+ target_type=row["target_type"],
634
+ metadata=json.loads(meta_raw or "{}"),
635
+ )
@@ -0,0 +1,9 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Brafford Labs, LLC
3
+ """Optional required-constraint interpreters can only narrow base authority."""
4
+ from collections.abc import Callable
5
+
6
+ from governed_objects.domain.models import Actor, GovernedObject
7
+ from governed_objects.types.schema import ObjectTypeDefinition
8
+
9
+ ConstraintHandler = Callable[[Actor, str, GovernedObject | None, ObjectTypeDefinition], bool]
@@ -0,0 +1,28 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Brafford Labs, LLC
3
+ """Authorization context passed through query and command pipelines."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from dataclasses import dataclass
8
+
9
+ from governed_objects.applications.registry import ApplicationDefinition
10
+ from governed_objects.delegation.mandate import DelegatedMandate
11
+ from governed_objects.delegation.resolver import ResolvedMandateAuthority
12
+
13
+
14
+ class AuthorizationContextError(ValueError):
15
+ """Requested authorization context could not be established safely."""
16
+
17
+ def __init__(self) -> None:
18
+ super().__init__("authorization context unavailable")
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class AuthorizationContext:
23
+ application: ApplicationDefinition | None = None
24
+ mandate: DelegatedMandate | None = None
25
+ resolved_mandate: ResolvedMandateAuthority | None = None
26
+ purpose: str | None = None
27
+ application_id: str | None = None
28
+ mandate_id: str | None = None