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,171 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Brafford Labs, LLC
3
+ """Permission-aware query service."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from collections.abc import Callable
8
+
9
+ from governed_objects.adapters.context import AdapterContext
10
+ from governed_objects.domain.models import Actor, GovernedObject
11
+ from governed_objects.materialization.service import MaterializationService
12
+ from governed_objects.persistence.sqlite import SQLiteStore
13
+ from governed_objects.policy.context import AuthorizationContext, AuthorizationContextError
14
+ from governed_objects.policy.evaluator import CapabilityPolicyEvaluator, PolicyEvaluator
15
+ from governed_objects.types.registry import TypeRegistry
16
+
17
+
18
+ class QueryService:
19
+ """Query governed objects with authorization applied before return."""
20
+
21
+ def __init__(
22
+ self,
23
+ store: SQLiteStore,
24
+ type_registry: TypeRegistry,
25
+ policy: PolicyEvaluator | None = None,
26
+ materializer: MaterializationService | None = None,
27
+ context: AdapterContext | None = None,
28
+ *,
29
+ resolve_auth: Callable[[AuthorizationContext | None], AuthorizationContext | None] | None = None,
30
+ ) -> None:
31
+ self._store = store
32
+ self._types = type_registry
33
+ self._policy = policy or CapabilityPolicyEvaluator()
34
+ self._materializer = materializer
35
+ self._context = context
36
+ self._resolve_auth = resolve_auth
37
+
38
+ def query(
39
+ self,
40
+ actor: Actor,
41
+ *,
42
+ object_type: str | None = None,
43
+ object_types: list[str] | None = None,
44
+ state: str | None = None,
45
+ include_subtypes: bool = False,
46
+ auth: AuthorizationContext | None = None,
47
+ ) -> list[GovernedObject]:
48
+ auth = self._current_auth(auth)
49
+ if object_types:
50
+ seen: set[str] = set()
51
+ results: list[GovernedObject] = []
52
+ for t in object_types:
53
+ for obj in self.query(
54
+ actor,
55
+ object_type=t,
56
+ state=state,
57
+ include_subtypes=include_subtypes,
58
+ auth=auth,
59
+ ):
60
+ if obj.id not in seen:
61
+ seen.add(obj.id)
62
+ results.append(obj)
63
+ return results
64
+
65
+ kinds: list[str] | None = None
66
+ if object_type:
67
+ kinds = self._types.kinds_matching(object_type, include_subtypes=include_subtypes)
68
+
69
+ if kinds and state:
70
+ candidates: list[GovernedObject] = []
71
+ for kind in kinds:
72
+ candidates.extend(self._store.list_by_state(kind, state))
73
+ elif kinds:
74
+ candidates = self._store.list_by_types(kinds)
75
+ elif object_type and state:
76
+ candidates = self._store.list_by_state(object_type, state)
77
+ elif object_type:
78
+ candidates = self._store.list_by_type(object_type)
79
+ else:
80
+ candidates = self._store.list_all()
81
+
82
+ results: list[GovernedObject] = []
83
+ for obj in candidates:
84
+ materialized = self._materialize_for_actor(obj.id, actor, auth=auth)
85
+ if materialized and self._can_read(actor, materialized, auth=auth):
86
+ results.append(materialized)
87
+ return results
88
+
89
+ def related(
90
+ self,
91
+ actor: Actor,
92
+ object_id: str,
93
+ *,
94
+ auth: AuthorizationContext | None = None,
95
+ ) -> list[GovernedObject]:
96
+ auth = self._current_auth(auth)
97
+ root = self._store.get(object_id)
98
+ if root is None or not self._can_read(actor, root, auth=auth):
99
+ return []
100
+ related_ids: set[str] = set()
101
+ for rel in self._store.list_for_source(object_id):
102
+ related_ids.add(rel.target_id)
103
+ for rel in self._store.list_for_target(object_id):
104
+ related_ids.add(rel.source_id)
105
+
106
+ results: list[GovernedObject] = []
107
+ for rid in sorted(related_ids):
108
+ materialized = self._materialize_for_actor(rid, actor, auth=auth)
109
+ if materialized and self._can_read(actor, materialized, auth=auth):
110
+ results.append(materialized)
111
+ return results
112
+
113
+ def _materialize_for_actor(
114
+ self,
115
+ object_id: str,
116
+ actor: Actor,
117
+ *,
118
+ auth: AuthorizationContext | None = None,
119
+ ) -> GovernedObject | None:
120
+ obj = self._store.get(object_id)
121
+ if obj is None or not self._can_read(actor, obj, auth=auth):
122
+ return None
123
+ if self._materializer is None or self._context is None:
124
+ return obj
125
+ try:
126
+ return self._materializer.materialize(
127
+ object_id,
128
+ self._context,
129
+ actor,
130
+ hydrate=True,
131
+ field_filter=True,
132
+ persist=True,
133
+ )
134
+ except Exception:
135
+ return None
136
+
137
+ def _current_auth(self, auth: AuthorizationContext | None) -> AuthorizationContext | None:
138
+ if self._resolve_auth is not None:
139
+ return self._resolve_auth(auth)
140
+ if auth is not None:
141
+ raise AuthorizationContextError()
142
+ return None
143
+
144
+ def _can_read(
145
+ self,
146
+ actor: Actor,
147
+ obj: GovernedObject,
148
+ *,
149
+ auth: AuthorizationContext | None = None,
150
+ ) -> bool:
151
+ if not self._types.supports_type_version(obj.type, obj.type_version):
152
+ return False
153
+ try:
154
+ type_def = self._types.get(obj.type)
155
+ except KeyError:
156
+ return False
157
+ application = auth.application if auth else None
158
+ mandate = auth.mandate if auth else None
159
+ resolved_mandate = auth.resolved_mandate if auth else None
160
+ purpose = auth.purpose if auth else None
161
+ decision = self._policy.evaluate(
162
+ actor,
163
+ "read",
164
+ obj,
165
+ type_def,
166
+ application=application,
167
+ mandate=mandate,
168
+ resolved_mandate=resolved_mandate,
169
+ purpose=purpose,
170
+ )
171
+ return decision.decision.value == "ALLOW"
@@ -0,0 +1,154 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Brafford Labs, LLC
3
+ """Permission-aware graph traversal."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from collections import deque
8
+ from collections.abc import Callable
9
+
10
+ from governed_objects.adapters.base import TypeAdapter
11
+ from governed_objects.adapters.context import AdapterContext
12
+ from governed_objects.domain.models import Actor, GovernedObject
13
+ from governed_objects.domain.traversal import TraversalResult, TraversalStep
14
+ from governed_objects.materialization.service import MaterializationService
15
+ from governed_objects.persistence.sqlite import SQLiteStore
16
+ from governed_objects.policy.context import AuthorizationContext, AuthorizationContextError
17
+ from governed_objects.policy.evaluator import CapabilityPolicyEvaluator, PolicyEvaluator
18
+ from governed_objects.types.registry import TypeRegistry
19
+
20
+
21
+ class GraphTraversalService:
22
+ """Traverse Governed Object relationships with authorization at each hop."""
23
+
24
+ def __init__(
25
+ self,
26
+ store: SQLiteStore,
27
+ type_registry: TypeRegistry,
28
+ policy: PolicyEvaluator | None = None,
29
+ adapters: list[TypeAdapter] | None = None,
30
+ materializer: MaterializationService | None = None,
31
+ context: AdapterContext | None = None,
32
+ *,
33
+ resolve_auth: Callable[[AuthorizationContext | None], AuthorizationContext | None] | None = None,
34
+ ) -> None:
35
+ self._store = store
36
+ self._types = type_registry
37
+ self._policy = policy or CapabilityPolicyEvaluator()
38
+ self._adapters = [] if adapters is None else adapters
39
+ self._materializer = materializer
40
+ self._context = context
41
+ self._resolve_auth = resolve_auth
42
+
43
+ def traverse(
44
+ self,
45
+ actor: Actor,
46
+ start_object_id: str,
47
+ *,
48
+ max_depth: int = 3,
49
+ relations: list[str] | None = None,
50
+ auth: AuthorizationContext | None = None,
51
+ ) -> list[TraversalResult]:
52
+ if self._resolve_auth is not None:
53
+ auth = self._resolve_auth(auth)
54
+ elif auth is not None:
55
+ raise AuthorizationContextError()
56
+ start = self._materialize(start_object_id, actor, auth=auth)
57
+ if start is None or not self._can_read(actor, start, auth=auth):
58
+ return []
59
+
60
+ results: list[TraversalResult] = []
61
+ visited: set[str] = set()
62
+ queue: deque[tuple[str, list[TraversalStep], int]] = deque()
63
+ queue.append((start_object_id, [], 0))
64
+
65
+ while queue:
66
+ node_id, path, depth = queue.popleft()
67
+ if node_id in visited:
68
+ continue
69
+
70
+ obj = self._materialize(node_id, actor, auth=auth)
71
+ if obj is None or not self._can_read(actor, obj, auth=auth):
72
+ continue
73
+
74
+ visited.add(node_id)
75
+ results.append(
76
+ TraversalResult(
77
+ object=obj,
78
+ depth=depth,
79
+ path=path,
80
+ )
81
+ )
82
+
83
+ if depth >= max_depth:
84
+ continue
85
+
86
+ for rel, neighbor_id, step_from, step_to in self._neighbors(node_id):
87
+ if relations is not None and rel.relation not in relations:
88
+ continue
89
+ if neighbor_id in visited:
90
+ continue
91
+
92
+ neighbor = self._materialize(neighbor_id, actor, auth=auth)
93
+ if neighbor is None or not self._can_read(actor, neighbor, auth=auth):
94
+ continue
95
+
96
+ step = TraversalStep(relation=rel.relation, from_id=step_from, to_id=step_to)
97
+ queue.append((neighbor_id, path + [step], depth + 1))
98
+
99
+ return results
100
+
101
+ def _materialize(
102
+ self, object_id: str, actor: Actor, *, auth: AuthorizationContext | None = None,
103
+ ) -> GovernedObject | None:
104
+ obj = self._store.get(object_id)
105
+ if obj is None or not self._can_read(actor, obj, auth=auth):
106
+ return None
107
+ if self._materializer is None or self._context is None:
108
+ return obj
109
+ try:
110
+ return self._materializer.materialize(
111
+ object_id,
112
+ self._context,
113
+ actor,
114
+ hydrate=True,
115
+ field_filter=True,
116
+ persist=True,
117
+ )
118
+ except Exception:
119
+ return None
120
+
121
+ def _neighbors(self, object_id: str):
122
+ for rel in self._store.list_for_source(object_id):
123
+ yield rel, rel.target_id, rel.source_id, rel.target_id
124
+ for rel in self._store.list_for_target(object_id):
125
+ yield rel, rel.source_id, rel.target_id, rel.source_id
126
+
127
+ def _can_read(
128
+ self,
129
+ actor: Actor,
130
+ obj: GovernedObject,
131
+ *,
132
+ auth: AuthorizationContext | None = None,
133
+ ) -> bool:
134
+ if not self._types.supports_type_version(obj.type, obj.type_version):
135
+ return False
136
+ try:
137
+ type_def = self._types.get(obj.type)
138
+ except KeyError:
139
+ return False
140
+ application = auth.application if auth else None
141
+ mandate = auth.mandate if auth else None
142
+ resolved_mandate = auth.resolved_mandate if auth else None
143
+ purpose = auth.purpose if auth else None
144
+ decision = self._policy.evaluate(
145
+ actor,
146
+ "read",
147
+ obj,
148
+ type_def,
149
+ application=application,
150
+ mandate=mandate,
151
+ resolved_mandate=resolved_mandate,
152
+ purpose=purpose,
153
+ )
154
+ return decision.decision.value == "ALLOW"
@@ -0,0 +1,213 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Brafford Labs, LLC
3
+ """Reconciliation — detect drift and produce external observations."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from dataclasses import dataclass, field
8
+ from datetime import UTC, datetime
9
+ from enum import StrEnum
10
+ from typing import Any
11
+
12
+ from governed_objects.adapters.context import AdapterContext
13
+ from governed_objects.adapters.registry import AdapterRegistry
14
+ from governed_objects.domain.models import GovernedObject
15
+ from governed_objects.observations.models import ExternalObservation, ObservationResult
16
+ from governed_objects.observations.ingestion import ObservationIngestionService
17
+ from governed_objects.persistence.sqlite import SQLiteStore
18
+ from governed_objects.providers.binding import ProviderBinding
19
+ from governed_objects.providers.errors import ProviderError, ProviderObjectNotFound, ProviderUnavailable
20
+ from governed_objects.observations.mapping import reconciliation_to_observation
21
+
22
+
23
+ class ReconciliationStatus(StrEnum):
24
+ IN_SYNC = "IN_SYNC"
25
+ DRIFT_DETECTED = "DRIFT_DETECTED"
26
+ PROVIDER_UNAVAILABLE = "PROVIDER_UNAVAILABLE"
27
+ PROVIDER_NOT_FOUND = "PROVIDER_NOT_FOUND"
28
+ LOCAL_OBJECT = "LOCAL_OBJECT"
29
+ OBSERVATION_INGESTED = "OBSERVATION_INGESTED"
30
+
31
+
32
+ @dataclass
33
+ class ReconciliationResult:
34
+ object_id: str
35
+ status: ReconciliationStatus
36
+ canonical_state: str | None = None
37
+ provider_state: str | None = None
38
+ differences: list[str] = field(default_factory=list)
39
+ observed_at: datetime = field(default_factory=lambda: datetime.now(UTC))
40
+ provider_binding: dict[str, Any] | None = None
41
+ observation_result: ObservationResult | None = None
42
+
43
+ def to_dict(self) -> dict[str, Any]:
44
+ return {
45
+ "object_id": self.object_id,
46
+ "status": self.status.value,
47
+ "canonical_state": self.canonical_state,
48
+ "provider_state": self.provider_state,
49
+ "differences": self.differences,
50
+ "observed_at": self.observed_at.isoformat(),
51
+ "provider_binding": self.provider_binding,
52
+ "observation_result": (
53
+ self.observation_result.model_dump() if self.observation_result else None
54
+ ),
55
+ }
56
+
57
+
58
+ class ReconciliationService:
59
+ """Compare stored canonical state with provider view; optionally ingest observations."""
60
+
61
+ def __init__(
62
+ self,
63
+ store: SQLiteStore,
64
+ adapters: AdapterRegistry,
65
+ ingestion: ObservationIngestionService | None = None,
66
+ ) -> None:
67
+ self._store = store
68
+ self._adapters = adapters
69
+ self._ingestion = ingestion
70
+
71
+ def check(self, object_id: str, context: AdapterContext) -> ReconciliationResult:
72
+ stored = self._store.get(object_id)
73
+ if stored is None:
74
+ return ReconciliationResult(
75
+ object_id=object_id,
76
+ status=ReconciliationStatus.PROVIDER_NOT_FOUND,
77
+ )
78
+
79
+ binding = ProviderBinding.from_metadata(stored.metadata)
80
+ if binding is None or binding.is_local:
81
+ return ReconciliationResult(
82
+ object_id=object_id,
83
+ status=ReconciliationStatus.LOCAL_OBJECT,
84
+ canonical_state=stored.state,
85
+ )
86
+
87
+ adapter = self._adapters.resolve(stored)
88
+ try:
89
+ hydrated = adapter.load(stored, context)
90
+ except ProviderObjectNotFound:
91
+ return ReconciliationResult(
92
+ object_id=object_id,
93
+ status=ReconciliationStatus.PROVIDER_NOT_FOUND,
94
+ canonical_state=stored.state,
95
+ provider_binding=binding.to_metadata().get("provider_binding"),
96
+ )
97
+ except (ProviderUnavailable, ProviderError):
98
+ return ReconciliationResult(
99
+ object_id=object_id,
100
+ status=ReconciliationStatus.PROVIDER_UNAVAILABLE,
101
+ canonical_state=stored.state,
102
+ provider_binding=binding.to_metadata().get("provider_binding"),
103
+ )
104
+
105
+ if hydrated is None:
106
+ return ReconciliationResult(
107
+ object_id=object_id,
108
+ status=ReconciliationStatus.IN_SYNC,
109
+ canonical_state=stored.state,
110
+ provider_binding=binding.to_metadata().get("provider_binding"),
111
+ )
112
+
113
+ return self._compare(stored, hydrated.object, binding)
114
+
115
+ def reconcile_and_ingest(
116
+ self, object_id: str, context: AdapterContext
117
+ ) -> ReconciliationResult:
118
+ """Poll provider, build observation, feed authority pipeline."""
119
+ stored = self._store.get(object_id)
120
+ if stored is None:
121
+ return ReconciliationResult(
122
+ object_id=object_id,
123
+ status=ReconciliationStatus.PROVIDER_NOT_FOUND,
124
+ )
125
+
126
+ binding = ProviderBinding.from_metadata(stored.metadata)
127
+ if binding is None or binding.is_local:
128
+ return ReconciliationResult(
129
+ object_id=object_id,
130
+ status=ReconciliationStatus.LOCAL_OBJECT,
131
+ canonical_state=stored.state,
132
+ )
133
+
134
+ if self._ingestion is None:
135
+ return self.check(object_id, context)
136
+
137
+ adapter = self._adapters.resolve(stored)
138
+ try:
139
+ hydrated = adapter.load(stored, context)
140
+ except (ProviderObjectNotFound, ProviderUnavailable, ProviderError):
141
+ return self.check(object_id, context)
142
+
143
+ if hydrated is None:
144
+ return ReconciliationResult(
145
+ object_id=object_id,
146
+ status=ReconciliationStatus.IN_SYNC,
147
+ canonical_state=stored.state,
148
+ )
149
+
150
+ observation = reconciliation_to_observation(
151
+ object_id=object_id,
152
+ provider_name=binding.provider_name,
153
+ provider_type=binding.provider_type,
154
+ external_id=binding.external_id or object_id,
155
+ canonical=stored.data,
156
+ canonical_state=stored.state,
157
+ provider_data=hydrated.object.data,
158
+ provider_state=hydrated.object.state,
159
+ )
160
+ if observation is None:
161
+ return ReconciliationResult(
162
+ object_id=object_id,
163
+ status=ReconciliationStatus.IN_SYNC,
164
+ canonical_state=stored.state,
165
+ provider_state=hydrated.object.state,
166
+ )
167
+
168
+ result = self._ingestion.ingest(observation)
169
+ differences = self._diff_labels(stored, hydrated.object)
170
+ return ReconciliationResult(
171
+ object_id=object_id,
172
+ status=ReconciliationStatus.OBSERVATION_INGESTED,
173
+ canonical_state=self._store.get(object_id).state if self._store.get(object_id) else stored.state,
174
+ provider_state=hydrated.object.state,
175
+ differences=differences,
176
+ provider_binding=binding.to_metadata().get("provider_binding"),
177
+ observation_result=result,
178
+ )
179
+
180
+ def _compare(
181
+ self,
182
+ stored: GovernedObject,
183
+ provider_view: GovernedObject,
184
+ binding: ProviderBinding,
185
+ ) -> ReconciliationResult:
186
+ differences = self._diff_labels(stored, provider_view)
187
+ status = (
188
+ ReconciliationStatus.DRIFT_DETECTED
189
+ if differences
190
+ else ReconciliationStatus.IN_SYNC
191
+ )
192
+ return ReconciliationResult(
193
+ object_id=stored.id,
194
+ status=status,
195
+ canonical_state=stored.state,
196
+ provider_state=provider_view.state,
197
+ differences=differences,
198
+ provider_binding=binding.to_metadata().get("provider_binding"),
199
+ )
200
+
201
+ @staticmethod
202
+ def _diff_labels(stored: GovernedObject, provider_view: GovernedObject) -> list[str]:
203
+ differences: list[str] = []
204
+ if stored.state != provider_view.state:
205
+ differences.append(
206
+ f"state: canonical={stored.state} provider={provider_view.state}"
207
+ )
208
+ for key, value in provider_view.data.items():
209
+ if stored.data.get(key) != value:
210
+ differences.append(
211
+ f"{key}: canonical={stored.data.get(key)} provider={value}"
212
+ )
213
+ return differences
@@ -0,0 +1,43 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Brafford Labs, LLC
3
+ """Detach a governed object from its provider backing."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from governed_objects.adapters.context import AdapterContext
8
+ from governed_objects.domain.models import GovernedObject
9
+ from governed_objects.materialization.service import MaterializationService
10
+ from governed_objects.persistence.sqlite import SQLiteStore
11
+ from governed_objects.providers.binding import ProviderBinding
12
+ from governed_objects.providers.errors import ProviderError
13
+
14
+
15
+ def detach_from_provider(
16
+ store: SQLiteStore,
17
+ materializer: MaterializationService,
18
+ context: AdapterContext,
19
+ object_id: str,
20
+ ) -> GovernedObject | None:
21
+ """Remove provider binding; canonical accepted state is already org-owned.
22
+
23
+ Detach changes only operational metadata. It records no revision and
24
+ leaves the Object Version unchanged, so it cannot exhaust the version
25
+ space and does not invalidate a current expected version."""
26
+ obj = store.get(object_id)
27
+ if obj is None:
28
+ return None
29
+
30
+ try:
31
+ materializer.materialize(object_id, context, hydrate=True, persist=True)
32
+ except ProviderError:
33
+ pass
34
+
35
+ binding = ProviderBinding.from_metadata(obj.metadata)
36
+ metadata = dict(obj.metadata)
37
+ metadata.pop("provider_binding", None)
38
+ if binding:
39
+ metadata["detached_from"] = binding.model_dump(exclude_none=True)
40
+
41
+ detached = obj.model_copy(update={"metadata": metadata})
42
+ store.save(detached)
43
+ return detached
@@ -0,0 +1,113 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Brafford Labs, LLC
3
+ """Stage provider registration before its first accepted canonical image."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from copy import deepcopy
8
+ from typing import TYPE_CHECKING
9
+
10
+ from governed_objects.adapters.context import AdapterContext
11
+ from governed_objects.adapters.registry import AdapterRegistry
12
+ from governed_objects.domain.models import ActorType, Decision, GovernedObject, GovernanceEvent
13
+ from governed_objects.materialization.service import MaterializationService
14
+ # Kept as a generic compatibility re-export; registration no longer fabricates
15
+ # a bootstrap observation after an accepted empty create.
16
+ from governed_objects.observations.mapping import reconciliation_to_observation
17
+ from governed_objects.observations.validation import (
18
+ CandidateMode, CandidateVerdict, candidate_image, capture_admission, validate_candidate,
19
+ )
20
+ from governed_objects.persistence.sqlite import IdentityAlreadyExists, SQLiteStore
21
+ from governed_objects.providers.binding import ProviderBinding
22
+ from governed_objects.providers.errors import ProviderError
23
+ from governed_objects.relationships.sync import RelationshipSyncService
24
+ from governed_objects.types.registry import TypeRegistry
25
+
26
+ if TYPE_CHECKING:
27
+ from governed_objects.observations.ingestion import ObservationIngestionService
28
+
29
+
30
+ class RegistrationRefused(Exception):
31
+ """Content-free failure to establish a valid supported initial image."""
32
+ code = "REGISTRATION_NOT_ACCEPTED"
33
+
34
+ def __init__(self) -> None:
35
+ super().__init__("registration unavailable")
36
+
37
+
38
+ class RegistrationService:
39
+ def __init__(self, store: SQLiteStore, adapter_registry: AdapterRegistry,
40
+ materializer: MaterializationService, type_registry: TypeRegistry,
41
+ observation_ingestion: ObservationIngestionService | None = None,
42
+ rel_sync: RelationshipSyncService | None = None) -> None:
43
+ self._store = store
44
+ self._adapters = adapter_registry
45
+ self._materializer = materializer
46
+ if type_registry is None:
47
+ raise ValueError("registration requires an explicit TypeRegistry")
48
+ self._types = type_registry
49
+ self._observations = observation_ingestion
50
+ self._rel_sync = rel_sync if rel_sync is not None else RelationshipSyncService(store)
51
+
52
+ def register_with_binding(self, governed_id: str, object_type: str, binding: ProviderBinding,
53
+ *, state: str | None = None, context: AdapterContext) -> GovernedObject:
54
+ definition = self._types.get(object_type)
55
+ if not definition.type_version or "type_version" not in definition.model_fields_set:
56
+ raise ValueError("registration requires a declared Type Version")
57
+ if state is None:
58
+ if not definition.initial_state and not definition.states:
59
+ raise ValueError("registration requires a declared default state or explicit state")
60
+ initial_state = definition.default_state()
61
+ else:
62
+ initial_state = state
63
+ if not initial_state or (definition.states and initial_state not in definition.states):
64
+ raise ValueError("registration state is not declared by the supplied type")
65
+ if self._store.identities_present([governed_id]):
66
+ raise IdentityAlreadyExists([governed_id])
67
+ # Carrier version1 is not issued or persisted until admission commits.
68
+ obj = GovernedObject(id=governed_id, type=object_type, type_version=definition.type_version,
69
+ version=1, state=initial_state, data={}, metadata=binding.to_metadata())
70
+ relationships = []
71
+ try:
72
+ snapshot = capture_admission(self._types, self._adapters, obj)
73
+ if not binding.is_local:
74
+ hydrated = self._materializer.observe_provider(obj, context)
75
+ if hydrated is None or (hydrated.object.id, hydrated.object.type, hydrated.object.type_version) != (
76
+ obj.id, obj.type, obj.type_version
77
+ ):
78
+ raise RegistrationRefused()
79
+ if state is not None and state != hydrated.object.state:
80
+ raise RegistrationRefused()
81
+ obj = obj.model_copy(update={"data": deepcopy(hydrated.object.data), "state": hydrated.object.state})
82
+ relationships = [rel.model_copy(deep=True) for rel in hydrated.relationships]
83
+ if any(rel.source_id != obj.id for rel in relationships):
84
+ raise RegistrationRefused()
85
+ provider_version = hydrated.provider_metadata.get("_provider_version")
86
+ if isinstance(provider_version, str):
87
+ obj.metadata["_observation_state"] = {"last_accepted_provider_version": provider_version}
88
+ verdict = validate_candidate(type_def=snapshot.definition, current=None, candidate=candidate_image(obj),
89
+ mode=CandidateMode.REGISTRATION_INITIAL, adapter=snapshot.adapter)
90
+ if verdict != CandidateVerdict.VALID or not snapshot.matches(self._types, self._adapters, obj):
91
+ raise RegistrationRefused()
92
+ except ProviderError:
93
+ raise
94
+ except Exception:
95
+ raise RegistrationRefused() from None
96
+ with self._store.observation_transaction():
97
+ if self._store.identities_present([governed_id]):
98
+ raise IdentityAlreadyExists([governed_id])
99
+ if not snapshot.matches(self._types, self._adapters, obj):
100
+ raise RegistrationRefused()
101
+ self._store.save(obj)
102
+ self._append_create_event(obj, source="provider_registration")
103
+ if relationships:
104
+ self._rel_sync.sync_provider_relationships(governed_id, relationships, provider_name=binding.provider_name)
105
+ return self._store.get(governed_id) or obj
106
+
107
+ def _append_create_event(self, obj: GovernedObject, *, source: str) -> None:
108
+ self._store.append_accepted(GovernanceEvent(
109
+ object_id=obj.id, object_type=obj.type, type_version=obj.type_version,
110
+ actor_id="system", actor_type=ActorType.SERVICE.value, action="create", decision=Decision.ALLOW,
111
+ event_type="object.create", previous_state=None, new_state=obj.state, reason="object created",
112
+ object_version=obj.version, details={"data": dict(obj.data), "source": source},
113
+ ))