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,310 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Brafford Labs, LLC
3
+ """Decode ``go-core-interchange-experiment/1`` or ``/2`` into an ``ImportBundle``.
4
+
5
+ EXPERIMENTAL. NON-NORMATIVE. NOT A WIRE STANDARD. This is the encoding layer
6
+ used by the experimental adapter; the runtime import API never sees JSON.
7
+
8
+ The artifact revision is read first and selects the contract: its status
9
+ marker and the one specification revision it carries. ``/1`` with Draft 2.2
10
+ content, ``/2`` with Draft 2.1 content, or either with any other revision is
11
+ refused here, because ``ImportBundle`` does not carry the artifact revision.
12
+
13
+ The decoder checks shape only and refuses, never repairs: duplicate members,
14
+ non-finite numbers, unknown members, non-string tokens, and a manifest that
15
+ does not describe the contents are refused. Named out-of-scope content
16
+ (policy, grants, credentials, provider bindings, ...) is refused as
17
+ UNSUPPORTED_SEMANTIC_FEATURE. Receiver semantics are the importer's job.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import json
23
+ from typing import Any
24
+
25
+ from governed_objects.interchange import (
26
+ ARTIFACT_CONTRACTS,
27
+ ARTIFACT_REVISION_V2,
28
+ IMPORT_ARTIFACT_REVISIONS,
29
+ )
30
+ from governed_objects.interchange.importer import (
31
+ MALFORMED_ARTIFACT,
32
+ STATE_NOT_VALID_FOR_TYPE,
33
+ UNSUPPORTED_SEMANTIC_FEATURE,
34
+ UNSUPPORTED_SPEC_REVISION,
35
+ ImportBundle,
36
+ ImportEntry,
37
+ ImportEvidence,
38
+ ImportObject,
39
+ ImportRefused,
40
+ ImportRelationship,
41
+ )
42
+
43
+ UNSUPPORTED_ARTIFACT_REVISION = "UNSUPPORTED_ARTIFACT_REVISION"
44
+
45
+ # History starts a revision recognizes but cannot carry (possibly complete under
46
+ # PRC, so not HISTORY_INCOMPLETE).
47
+ _UNCARRIED_COMPLETENESS = {ARTIFACT_REVISION_V2: ("complete-from-replay-baseline",)}
48
+
49
+ OUT_OF_SCOPE_MEMBERS = frozenset(
50
+ {
51
+ "policy", "policy_content", "governance_policy", "grants", "capabilities", "permissions",
52
+ "actors", "credentials", "secrets", "trust_roots", "provider_binding", "provider_bindings",
53
+ "observations", "mandates", "application_registrations", "profile_data",
54
+ }
55
+ )
56
+
57
+ _MANIFEST_REQUIRED = (
58
+ "artifact_status", "history_completeness", "history_position_model",
59
+ "governance_reference_model", "profiles", "identities", "type_bindings",
60
+ "governance_references", "closed",
61
+ )
62
+ _MANIFEST_OPTIONAL = ("artifact_revision", "spec_revision", "provenance")
63
+ _OBJECT_REQUIRED = (
64
+ "canonical_identity", "type_identity", "type_version", "accepted_state",
65
+ "relationships", "current_object_version", "history",
66
+ )
67
+ _ENTRY_REQUIRED = ("position", "effect", "type_identity", "type_version", "resulting_object_version")
68
+ _ENTRY_CONTENT = ("post_image", "relationships", "relationship")
69
+ _ENTRY_EVIDENCE = ("actor", "accepted_at", "action", "source_event_id")
70
+ _EFFECT_CONTENT = {
71
+ "create": {"post_image", "relationships"},
72
+ "state_change": {"post_image"},
73
+ "lifecycle_transition": {"post_image"},
74
+ "relationship_add": {"relationship"},
75
+ "relationship_remove": {"relationship"},
76
+ }
77
+
78
+
79
+ def _refuse(detail: str, identity: str | None = None, position: int | None = None, code=MALFORMED_ARTIFACT):
80
+ return ImportRefused(code, detail, identity, position)
81
+
82
+
83
+ def _pairs(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
84
+ out: dict[str, Any] = {}
85
+ for key, value in pairs:
86
+ if key in out:
87
+ raise _refuse(f"duplicate JSON member {key!r}")
88
+ out[key] = value
89
+ return out
90
+
91
+
92
+ def _constant(name: str) -> Any:
93
+ raise _refuse(f"non-finite JSON number {name}")
94
+
95
+
96
+ def _extras(raw: dict, known: tuple[str, ...], where: str, identity=None, position=None) -> None:
97
+ for name in raw:
98
+ if name in known:
99
+ continue
100
+ if name in OUT_OF_SCOPE_MEMBERS:
101
+ raise _refuse(f"{where}: out-of-scope content {name!r}", identity, position, UNSUPPORTED_SEMANTIC_FEATURE)
102
+ raise _refuse(f"{where}: unrecognized member {name!r}", identity, position)
103
+
104
+
105
+ def _string(value: Any, where: str, identity=None, position=None) -> str:
106
+ if not isinstance(value, str) or value == "":
107
+ raise _refuse(f"{where} must be a non-empty string", identity, position)
108
+ return value
109
+
110
+
111
+ def _is_int(value: Any) -> bool:
112
+ return isinstance(value, int) and not isinstance(value, bool)
113
+
114
+
115
+ def _relationship(raw: Any, where: str, identity, position=None) -> ImportRelationship:
116
+ if not isinstance(raw, dict) or not {"source", "type", "target"} <= set(raw) <= {
117
+ "source", "type", "target", "target_type", "metadata",
118
+ }:
119
+ raise _refuse(f"{where} must be {{source, type, target}} with optional target_type/metadata", identity, position)
120
+ if "target_type" in raw and not isinstance(raw["target_type"], str):
121
+ raise _refuse(f"{where}.target_type must be a string", identity, position)
122
+ if "metadata" in raw and not isinstance(raw["metadata"], dict):
123
+ raise _refuse(f"{where}.metadata must be an object", identity, position)
124
+ return ImportRelationship(
125
+ _string(raw["source"], f"{where}.source", identity, position),
126
+ _string(raw["type"], f"{where}.type", identity, position),
127
+ _string(raw["target"], f"{where}.target", identity, position),
128
+ has_evidence="target_type" in raw or "metadata" in raw,
129
+ )
130
+
131
+
132
+ def _relationships(raw: Any, where: str, identity, position=None) -> tuple[ImportRelationship, ...]:
133
+ if not isinstance(raw, list):
134
+ raise _refuse(f"{where} must be a list", identity, position)
135
+ return tuple(_relationship(r, f"{where}[{i}]", identity, position) for i, r in enumerate(raw))
136
+
137
+
138
+ def _state(raw: Any, where: str, identity, position=None) -> dict[str, Any]:
139
+ if not isinstance(raw, dict):
140
+ raise _refuse(f"{where} must be an object", identity, position)
141
+ for name, value in raw.items():
142
+ if not isinstance(value, str):
143
+ raise ImportRefused(
144
+ STATE_NOT_VALID_FOR_TYPE, f"{where}.{name} must be a string (never coerced)", identity, position
145
+ )
146
+ return dict(raw)
147
+
148
+
149
+ def _token(value: Any, where: str, identity, position=None) -> str:
150
+ if not isinstance(value, str) or value == "":
151
+ raise _refuse(f"{where} {value!r} is not an opaque string token (never coerced)", identity, position)
152
+ return value
153
+
154
+
155
+ def _entry(raw: Any, identity: str, index: int) -> ImportEntry:
156
+ where = f"history[{index}]"
157
+ if not isinstance(raw, dict):
158
+ raise _refuse(f"{where} must be an object", identity)
159
+ for name in _ENTRY_REQUIRED:
160
+ if name not in raw:
161
+ raise _refuse(f"{where}: required member {name!r} missing", identity)
162
+ position = raw["position"]
163
+ if not _is_int(position):
164
+ raise _refuse(f"{where}.position must be a JSON integer", identity)
165
+ effect = raw["effect"]
166
+ if not isinstance(effect, str) or effect not in _EFFECT_CONTENT:
167
+ raise _refuse(f"{where}.effect {effect!r} is not a known effect kind", identity, position)
168
+ present = {n for n in _ENTRY_CONTENT if n in raw}
169
+ if present != _EFFECT_CONTENT[effect]:
170
+ raise _refuse(f"{where}: effect {effect!r} requires exactly {sorted(_EFFECT_CONTENT[effect])}", identity, position)
171
+ _extras(raw, _ENTRY_REQUIRED + _ENTRY_CONTENT + _ENTRY_EVIDENCE, where, identity, position)
172
+ for name in _ENTRY_EVIDENCE:
173
+ if name in raw and not isinstance(raw[name], str):
174
+ raise _refuse(f"{where}.{name} must be a string when present", identity, position)
175
+ return ImportEntry(
176
+ position=position,
177
+ effect=effect,
178
+ type_identity=_string(raw["type_identity"], f"{where}.type_identity", identity, position),
179
+ type_version=_string(raw["type_version"], f"{where}.type_version", identity, position),
180
+ resulting_object_version=_token(raw["resulting_object_version"], f"{where}.resulting_object_version", identity, position),
181
+ post_image=_state(raw["post_image"], f"{where}.post_image", identity, position) if "post_image" in raw else None,
182
+ baseline_relationships=(
183
+ _relationships(raw["relationships"], f"{where}.relationships", identity, position)
184
+ if "relationships" in raw else None
185
+ ),
186
+ relationship=(
187
+ _relationship(raw["relationship"], f"{where}.relationship", identity, position)
188
+ if "relationship" in raw else None
189
+ ),
190
+ evidence=ImportEvidence(
191
+ actor=raw.get("actor"),
192
+ accepted_at=raw.get("accepted_at"),
193
+ action=raw.get("action"),
194
+ source_event_id=raw.get("source_event_id"),
195
+ ),
196
+ )
197
+
198
+
199
+ def _object(raw: Any, index: int) -> ImportObject:
200
+ where = f"objects[{index}]"
201
+ if not isinstance(raw, dict):
202
+ raise _refuse(f"{where} must be an object")
203
+ for name in _OBJECT_REQUIRED:
204
+ if name not in raw:
205
+ raise _refuse(f"{where}: required member {name!r} missing")
206
+ identity = _string(raw["canonical_identity"], f"{where}.canonical_identity")
207
+ _extras(raw, _OBJECT_REQUIRED + ("governance_reference",), "object", identity)
208
+ governance = raw.get("governance_reference")
209
+ if governance is not None and not isinstance(governance, str):
210
+ raise _refuse("governance_reference must be an opaque string", identity)
211
+ if not isinstance(raw["history"], list):
212
+ raise _refuse("history must be a list", identity)
213
+ return ImportObject(
214
+ canonical_identity=identity,
215
+ type_identity=_string(raw["type_identity"], "type_identity", identity),
216
+ type_version=_string(raw["type_version"], "type_version", identity),
217
+ governance_reference=governance,
218
+ accepted_state=_state(raw["accepted_state"], "accepted_state", identity),
219
+ relationships=_relationships(raw["relationships"], "relationships", identity),
220
+ current_object_version=_token(raw["current_object_version"], "current_object_version", identity),
221
+ history=tuple(_entry(e, identity, i) for i, e in enumerate(raw["history"])),
222
+ )
223
+
224
+
225
+ def decode_artifact(text: str) -> ImportBundle:
226
+ try:
227
+ doc = json.loads(text, object_pairs_hook=_pairs, parse_constant=_constant)
228
+ except ImportRefused:
229
+ raise
230
+ except (ValueError, TypeError) as exc:
231
+ raise _refuse(f"unparseable JSON: {exc}") from None
232
+ manifest = doc.get("manifest") if isinstance(doc, dict) else None
233
+ revision = manifest.get("artifact_revision") if isinstance(manifest, dict) else None
234
+ contract = ARTIFACT_CONTRACTS.get(revision) if isinstance(revision, str) else None
235
+ if contract is None:
236
+ raise ImportRefused(
237
+ UNSUPPORTED_ARTIFACT_REVISION,
238
+ f"artifact revision {revision!r} is not one of {list(IMPORT_ARTIFACT_REVISIONS)}",
239
+ )
240
+ status, carried_spec = contract
241
+ if "objects" not in doc:
242
+ raise _refuse("bundle: required member 'objects' missing")
243
+ _extras(doc, ("manifest", "objects"), "bundle")
244
+ for name in _MANIFEST_REQUIRED:
245
+ if name not in manifest:
246
+ raise _refuse(f"manifest: required member {name!r} missing")
247
+ _extras(manifest, _MANIFEST_REQUIRED + _MANIFEST_OPTIONAL, "manifest")
248
+ if manifest["artifact_status"] != status:
249
+ raise _refuse(f"manifest.artifact_status does not carry the {revision} status marker")
250
+ spec = manifest.get("spec_revision")
251
+ if spec is not None and not isinstance(spec, str):
252
+ raise _refuse("manifest.spec_revision must be a string")
253
+ for name in ("history_completeness", "history_position_model", "governance_reference_model"):
254
+ _string(manifest[name], f"manifest.{name}")
255
+ for name in ("profiles", "identities", "type_bindings", "governance_references"):
256
+ if not isinstance(manifest[name], list):
257
+ raise _refuse(f"manifest.{name} must be a list")
258
+ if not isinstance(manifest["closed"], bool):
259
+ raise _refuse("manifest.closed must be a boolean")
260
+ source_implementation = None
261
+ if "provenance" in manifest:
262
+ p = manifest["provenance"]
263
+ if not isinstance(p, dict) or not set(p) <= {"source_implementation", "exported_at"} or not all(
264
+ isinstance(v, str) for v in p.values()
265
+ ):
266
+ raise _refuse("manifest.provenance may contain only source_implementation and exported_at strings")
267
+ source_implementation = p.get("source_implementation")
268
+ if not isinstance(doc["objects"], list):
269
+ raise _refuse("objects must be a list")
270
+ objects = tuple(_object(o, i) for i, o in enumerate(doc["objects"]))
271
+ if spec != carried_spec:
272
+ raise ImportRefused(
273
+ UNSUPPORTED_SPEC_REVISION,
274
+ f"artifact revision {revision} carries only {carried_spec!r} content, not {spec!r}",
275
+ )
276
+ if manifest["history_completeness"] in _UNCARRIED_COMPLETENESS.get(revision, ()):
277
+ raise _refuse(
278
+ f"history completeness {manifest['history_completeness']!r} cannot be carried by {revision}",
279
+ code=UNSUPPORTED_SEMANTIC_FEATURE,
280
+ )
281
+
282
+ bindings = []
283
+ for i, b in enumerate(manifest["type_bindings"]):
284
+ if not isinstance(b, dict) or set(b) != {"type_identity", "type_version"}:
285
+ raise _refuse(f"manifest.type_bindings[{i}] must be {{type_identity, type_version}}")
286
+ bindings.append((_string(b["type_identity"], "type_identity"), _string(b["type_version"], "type_version")))
287
+ declared = {
288
+ "identities": [_string(x, "manifest.identities[]") for x in manifest["identities"]],
289
+ "type_bindings": bindings,
290
+ "governance_references": [_string(x, "manifest.governance_references[]") for x in manifest["governance_references"]],
291
+ }
292
+ actual = {
293
+ "identities": {o.canonical_identity for o in objects},
294
+ "type_bindings": {(o.type_identity, o.type_version) for o in objects},
295
+ "governance_references": {o.governance_reference for o in objects if o.governance_reference},
296
+ }
297
+ for name, values in declared.items():
298
+ if len(set(values)) != len(values) or set(values) != actual[name]:
299
+ raise _refuse(f"manifest.{name} does not describe the bundle contents")
300
+
301
+ return ImportBundle(
302
+ objects=objects,
303
+ closed=manifest["closed"],
304
+ spec_revision=spec,
305
+ history_completeness=manifest["history_completeness"],
306
+ history_position_model=manifest["history_position_model"],
307
+ governance_reference_model=manifest["governance_reference_model"],
308
+ profiles=tuple(manifest["profiles"]),
309
+ source_implementation=source_implementation,
310
+ )
@@ -0,0 +1,345 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Brafford Labs, LLC
3
+ """Export to ``go-core-interchange-experiment/2`` with Draft 2.2 content (EXPERIMENTAL).
4
+
5
+ Accepted-history filtering follows the interchange experiment's
6
+ history-semantics analysis, sections 5.3 and 6.3:
7
+
8
+ 1. a candidate row is ``decision == ALLOW`` with ``event_type ==
9
+ "object.<action>"``;
10
+ 2. its action is ``create``, ``add_relationship``, ``remove_relationship``,
11
+ or a state/lifecycle action declared by the portable type (never
12
+ ``read``);
13
+ 3. it advanced the Object Version, which this runtime records as an
14
+ accepted-history position assigned at append time;
15
+ 4. the object has no provider binding.
16
+
17
+ Order comes only from the recorded positions. Timestamps, event IDs, and
18
+ rowid are never used. When the criteria disagree the export is refused;
19
+ nothing is repaired, reordered, defaulted, or dropped.
20
+
21
+ Export is a governed read (PRC-EXPORT-002). Read authority for every
22
+ requested object is established before any object is classified, so a
23
+ requester without it receives the same refusal whether or not an object is
24
+ exportable (PRC-REFUSE-001, AUTH-DISCLOSE-001). Existence is not protected.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ from datetime import UTC
30
+ from typing import TYPE_CHECKING, Any
31
+
32
+ from governed_objects.domain.models import Actor, Decision, GovernanceEvent, GovernedObject
33
+ from governed_objects.interchange import (
34
+ ARTIFACT_CONTRACTS,
35
+ EXPORT_ARTIFACT_REVISION,
36
+ EXPORT_HISTORY_UNCLASSIFIABLE,
37
+ EXPORT_ORDER_INDETERMINATE,
38
+ GOVERNANCE_REFERENCE_MODEL,
39
+ HISTORY_COMPLETENESS,
40
+ HISTORY_POSITION_MODEL,
41
+ UNSUPPORTED_SEMANTIC_FEATURE,
42
+ )
43
+ from governed_objects.interchange.importer import ACTION_RECORDED, DUPLICATE_IDENTITY_IN_BUNDLE
44
+ from governed_objects.events.replay import bound_type_definition
45
+ from governed_objects.interchange.types import (
46
+ ACTION_LIFECYCLE,
47
+ ACTION_STATE,
48
+ lifecycle_field,
49
+ portable_type_of,
50
+ )
51
+
52
+ if TYPE_CHECKING:
53
+ from governed_objects.persistence.sqlite import SQLiteStore
54
+ from governed_objects.policy.evaluator import PolicyEvaluator
55
+ from governed_objects.runtime.runtime import GovernedObjectRuntime
56
+ from governed_objects.types.registry import TypeRegistry
57
+
58
+ _EXPORT_STATUS, _EXPORT_SPEC_REVISION = ARTIFACT_CONTRACTS[EXPORT_ARTIFACT_REVISION]
59
+
60
+ AUTHORIZATION_DENIED = "AUTHORIZATION_DENIED"
61
+ NOT_FOUND = "NOT_FOUND"
62
+ # Independent of the object's type and policy, which could reveal exportability.
63
+ EXPORT_READ_DENIED = "requester is not authorized to read the object for export"
64
+
65
+ _RUNTIME_EFFECTS = {
66
+ "create": "create",
67
+ "add_relationship": "relationship_add",
68
+ "remove_relationship": "relationship_remove",
69
+ }
70
+
71
+
72
+ class ExportRefused(Exception):
73
+ def __init__(self, code: str, message: str, identity: str | None = None) -> None:
74
+ super().__init__(f"{code}: {message}" + (f" ({identity})" if identity else ""))
75
+ self.code = code
76
+ self.message = message
77
+ self.identity = identity
78
+
79
+
80
+ def _token(value: Any, identity: str) -> str:
81
+ if type(value) is not int:
82
+ raise ExportRefused(
83
+ EXPORT_HISTORY_UNCLASSIFIABLE, f"native Object Version is not an int: {value!r}", identity
84
+ )
85
+ return str(value)
86
+
87
+
88
+ class InterchangeExporter:
89
+ def __init__(
90
+ self,
91
+ runtime: GovernedObjectRuntime,
92
+ store: SQLiteStore,
93
+ types: TypeRegistry,
94
+ policy: PolicyEvaluator,
95
+ ) -> None:
96
+ self._runtime = runtime
97
+ self._store = store
98
+ self._types = types
99
+ self._policy = policy
100
+
101
+ def export(
102
+ self,
103
+ identities: list[str],
104
+ *,
105
+ actor: Actor,
106
+ closed: bool,
107
+ include_timestamps: bool = False,
108
+ source_implementation: str | None = None,
109
+ ) -> dict[str, Any]:
110
+ identities = list(identities)
111
+ if len(set(identities)) != len(identities):
112
+ raise ExportRefused(
113
+ DUPLICATE_IDENTITY_IN_BUNDLE,
114
+ "export selection contains repeated identities",
115
+ )
116
+ readable = [self._authorize(i, actor) for i in identities]
117
+ objects = [self._export_object(obj, include_timestamps) for obj in readable]
118
+ manifest: dict[str, Any] = {
119
+ "artifact_status": _EXPORT_STATUS,
120
+ "artifact_revision": EXPORT_ARTIFACT_REVISION,
121
+ "spec_revision": _EXPORT_SPEC_REVISION,
122
+ "history_completeness": HISTORY_COMPLETENESS,
123
+ "history_position_model": HISTORY_POSITION_MODEL,
124
+ "governance_reference_model": GOVERNANCE_REFERENCE_MODEL,
125
+ "profiles": [],
126
+ "identities": [o["canonical_identity"] for o in objects],
127
+ "type_bindings": _unique(
128
+ {"type_identity": o["type_identity"], "type_version": o["type_version"]}
129
+ for o in objects
130
+ ),
131
+ "governance_references": _unique(
132
+ o["governance_reference"] for o in objects if o["governance_reference"] is not None
133
+ ),
134
+ "closed": closed,
135
+ }
136
+ provenance: dict[str, Any] = {}
137
+ if source_implementation:
138
+ provenance["source_implementation"] = source_implementation
139
+ if include_timestamps:
140
+ provenance["exported_at"] = self._runtime.clock.now().astimezone(UTC).isoformat()
141
+ if provenance:
142
+ manifest["provenance"] = provenance
143
+ return {"manifest": manifest, "objects": objects}
144
+
145
+ def _authorize(self, identity: str, actor: Actor) -> GovernedObject:
146
+ obj = self._runtime.get_object(identity)
147
+ if obj is None:
148
+ raise ExportRefused(NOT_FOUND, "no such object", identity)
149
+ type_def = bound_type_definition(self._types, obj)
150
+ if type_def is None:
151
+ # Read authority cannot be established without the type's policy.
152
+ raise ExportRefused(AUTHORIZATION_DENIED, EXPORT_READ_DENIED, identity)
153
+ if self._policy.evaluate(actor, "read", obj, type_def).decision != Decision.ALLOW:
154
+ raise ExportRefused(AUTHORIZATION_DENIED, EXPORT_READ_DENIED, identity)
155
+ return obj
156
+
157
+ def _export_object(self, obj: GovernedObject, include_timestamps: bool) -> dict[str, Any]:
158
+ identity = obj.id
159
+ portable = portable_type_of(self._types.get(obj.type))
160
+ if portable is None:
161
+ raise ExportRefused(
162
+ UNSUPPORTED_SEMANTIC_FEATURE,
163
+ f"type {obj.type!r} is not configured as a portable Core type",
164
+ identity,
165
+ )
166
+ if obj.metadata.get("provider_binding"):
167
+ raise ExportRefused(
168
+ UNSUPPORTED_SEMANTIC_FEATURE, "provider-bound objects are outside Core export", identity
169
+ )
170
+ if obj.governance_reference is None:
171
+ raise ExportRefused(
172
+ UNSUPPORTED_SEMANTIC_FEATURE,
173
+ "object has no stored portable governance reference",
174
+ identity,
175
+ )
176
+
177
+ lc_field = lifecycle_field(portable)
178
+ actions = portable.get("actions", {})
179
+ rows = self._accepted_rows(obj, actions)
180
+ history = [self._entry(identity, row, lc_field, actions, include_timestamps) for row in rows]
181
+
182
+ state = dict(obj.data)
183
+ if lc_field is not None:
184
+ state[lc_field] = obj.state
185
+ relationships = sorted(
186
+ (
187
+ {"source": r.source_id, "type": r.relation, "target": r.target_id}
188
+ for r in self._runtime.canonical_relationships(identity)
189
+ ),
190
+ key=lambda r: (r["type"], r["target"]),
191
+ )
192
+ return {
193
+ "canonical_identity": obj.id,
194
+ "type_identity": obj.type,
195
+ "type_version": obj.type_version,
196
+ "governance_reference": obj.governance_reference,
197
+ "accepted_state": state,
198
+ "relationships": relationships,
199
+ "current_object_version": _token(obj.version, identity),
200
+ "history": history,
201
+ }
202
+
203
+ def _accepted_rows(self, obj: GovernedObject, actions: dict[str, Any]) -> list[GovernanceEvent]:
204
+ identity = obj.id
205
+ canonical_actions = set(_RUNTIME_EFFECTS) | {
206
+ n for n, a in actions.items() if a["kind"] in (ACTION_STATE, ACTION_LIFECYCLE)
207
+ }
208
+ positioned = self._runtime.accepted_history(identity)
209
+ positioned_ids = {r.event_id for r in positioned}
210
+ read_versions: list[int] = []
211
+ for row in self._runtime.history(identity):
212
+ positioned_row = row.event_id in positioned_ids
213
+ candidate = (
214
+ row.decision == Decision.ALLOW
215
+ and row.event_type == f"object.{row.action}"
216
+ and row.action in canonical_actions
217
+ )
218
+ if candidate and not positioned_row:
219
+ raise ExportRefused(
220
+ EXPORT_ORDER_INDETERMINATE,
221
+ f"accepted {row.action!r} row {row.event_id} has no recorded position",
222
+ identity,
223
+ )
224
+ if positioned_row and not candidate:
225
+ raise ExportRefused(
226
+ EXPORT_HISTORY_UNCLASSIFIABLE,
227
+ f"positioned row {row.event_id} ({row.decision.value} {row.event_type}) "
228
+ "is not an accepted canonical change",
229
+ identity,
230
+ )
231
+ if row.decision == Decision.ALLOW and not candidate:
232
+ if row.action != "read" or row.event_type != "object.read":
233
+ raise ExportRefused(
234
+ EXPORT_HISTORY_UNCLASSIFIABLE,
235
+ f"accepted row {row.event_id} ({row.event_type}) is neither a "
236
+ "canonical change nor a read",
237
+ identity,
238
+ )
239
+ read_versions.append(row.object_version)
240
+
241
+ positions = [r.history_position for r in positioned]
242
+ if positions != list(range(1, len(positioned) + 1)):
243
+ raise ExportRefused(
244
+ EXPORT_ORDER_INDETERMINATE, f"recorded positions are not 1..n: {positions}", identity
245
+ )
246
+ if not positioned or positioned[0].action != "create":
247
+ raise ExportRefused(
248
+ EXPORT_HISTORY_UNCLASSIFIABLE, "accepted history does not begin with create", identity
249
+ )
250
+ versions = [r.object_version for r in positioned]
251
+ # Tokens are opaque: only reuse is refused. A restored history may
252
+ # carry versions that do not increase in position order (B-REORDER).
253
+ if len(set(versions)) != len(versions):
254
+ raise ExportRefused(
255
+ EXPORT_HISTORY_UNCLASSIFIABLE,
256
+ f"an Object Version is reused within accepted history: {versions}",
257
+ identity,
258
+ )
259
+ if versions[-1] != obj.version:
260
+ raise ExportRefused(
261
+ EXPORT_HISTORY_UNCLASSIFIABLE,
262
+ f"current Object Version {obj.version} is not the last accepted version {versions[-1]}",
263
+ identity,
264
+ )
265
+ stray = sorted(set(read_versions) - set(versions))
266
+ if stray:
267
+ raise ExportRefused(
268
+ EXPORT_HISTORY_UNCLASSIFIABLE,
269
+ f"read rows carry versions no accepted change produced: {stray}",
270
+ identity,
271
+ )
272
+ return positioned
273
+
274
+ def _entry(
275
+ self,
276
+ identity: str,
277
+ row: GovernanceEvent,
278
+ lc_field: str | None,
279
+ actions: dict[str, Any],
280
+ include_timestamps: bool,
281
+ ) -> dict[str, Any]:
282
+ if row.type_version is None:
283
+ raise ExportRefused(
284
+ EXPORT_HISTORY_UNCLASSIFIABLE,
285
+ f"row {row.event_id} records no Type Version",
286
+ identity,
287
+ )
288
+ effect = _RUNTIME_EFFECTS.get(row.action)
289
+ if effect is None:
290
+ kind = actions[row.action]["kind"]
291
+ effect = "state_change" if kind == ACTION_STATE else "lifecycle_transition"
292
+ entry: dict[str, Any] = {
293
+ "position": row.history_position,
294
+ "effect": effect,
295
+ "type_identity": row.object_type,
296
+ "type_version": row.type_version,
297
+ "resulting_object_version": _token(row.object_version, identity),
298
+ }
299
+ details = row.details
300
+ if effect == "create":
301
+ if "data" not in details:
302
+ raise ExportRefused(
303
+ EXPORT_HISTORY_UNCLASSIFIABLE, "create row records no post-image", identity
304
+ )
305
+ entry["post_image"] = _post_image(details["data"], row.new_state, lc_field)
306
+ entry["relationships"] = [
307
+ {"source": r["source_id"], "type": r["relation"], "target": r["target_id"]}
308
+ for r in details.get("relationships", [])
309
+ ]
310
+ elif effect in ("state_change", "lifecycle_transition"):
311
+ image = details.get("accepted_post_image")
312
+ if image is None:
313
+ raise ExportRefused(
314
+ EXPORT_HISTORY_UNCLASSIFIABLE,
315
+ f"{row.action!r} row {row.event_id} records no post-image",
316
+ identity,
317
+ )
318
+ entry["post_image"] = _post_image(image["data"], image["state"], lc_field)
319
+ else:
320
+ entry["relationship"] = {
321
+ "source": identity,
322
+ "type": details["relation"],
323
+ "target": details["target_id"],
324
+ }
325
+ entry["actor"] = row.actor_id
326
+ if include_timestamps and row.accepted_at_recorded:
327
+ entry["accepted_at"] = row.timestamp.astimezone(UTC).isoformat()
328
+ if details.get(ACTION_RECORDED, True):
329
+ entry["action"] = row.action
330
+ return entry
331
+
332
+
333
+ def _post_image(data: dict[str, Any], state: str | None, lc_field: str | None) -> dict[str, Any]:
334
+ image = dict(data)
335
+ if lc_field is not None:
336
+ image[lc_field] = state
337
+ return image
338
+
339
+
340
+ def _unique(items) -> list:
341
+ out: list = []
342
+ for item in items:
343
+ if item not in out:
344
+ out.append(item)
345
+ return out
@@ -0,0 +1,26 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Brafford Labs, LLC
3
+ """Type-scoped governance references (EXPERIMENTAL).
4
+
5
+ A governance configuration maps each supported ``(Type Identity, Type
6
+ Version)`` to one opaque reference. The runtime records the configured
7
+ reference on an object when it is created; it is never recomputed later and
8
+ never consulted for authorization. Authorization stays with the type's
9
+ capability requirements and the actor's capabilities.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections.abc import Mapping
15
+
16
+
17
+ class TypeScopedGovernance:
18
+ def __init__(self, name: str, references: Mapping[tuple[str, str], str]) -> None:
19
+ self.name = name
20
+ self._references = dict(references)
21
+
22
+ def reference_for(self, type_identity: str, type_version: str) -> str | None:
23
+ return self._references.get((type_identity, type_version))
24
+
25
+ def references(self) -> dict[tuple[str, str], str]:
26
+ return dict(self._references)