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.
- governed_objects/__init__.py +7 -0
- governed_objects/_version.py +38 -0
- governed_objects/adapters/base.py +80 -0
- governed_objects/adapters/context.py +58 -0
- governed_objects/adapters/mandate.py +45 -0
- governed_objects/adapters/registry.py +25 -0
- governed_objects/agent/session.py +111 -0
- governed_objects/applications/registry.py +39 -0
- governed_objects/authority/rules.py +63 -0
- governed_objects/delegation/configuration.py +74 -0
- governed_objects/delegation/mandate.py +44 -0
- governed_objects/delegation/materializer.py +152 -0
- governed_objects/delegation/projection.py +48 -0
- governed_objects/delegation/resolver.py +180 -0
- governed_objects/delegation/scope.py +75 -0
- governed_objects/delegation/service.py +245 -0
- governed_objects/delegation/validator.py +159 -0
- governed_objects/domain/__init__.py +21 -0
- governed_objects/domain/actor_manifest.py +40 -0
- governed_objects/domain/actors.py +55 -0
- governed_objects/domain/clock.py +28 -0
- governed_objects/domain/command.py +95 -0
- governed_objects/domain/command_context.py +35 -0
- governed_objects/domain/models.py +110 -0
- governed_objects/domain/traversal.py +25 -0
- governed_objects/events/lineage.py +71 -0
- governed_objects/events/reducers/__init__.py +2 -0
- governed_objects/events/reducers/mandate.py +31 -0
- governed_objects/events/replay.py +208 -0
- governed_objects/idempotency/store.py +160 -0
- governed_objects/interchange/__init__.py +49 -0
- governed_objects/interchange/artifact.py +310 -0
- governed_objects/interchange/export.py +345 -0
- governed_objects/interchange/governance.py +26 -0
- governed_objects/interchange/importer.py +672 -0
- governed_objects/interchange/prc.py +76 -0
- governed_objects/interchange/types.py +228 -0
- governed_objects/llm/__init__.py +16 -0
- governed_objects/llm/loop.py +130 -0
- governed_objects/llm/model.py +44 -0
- governed_objects/llm/tools/registry.py +87 -0
- governed_objects/llm/tools/results.py +53 -0
- governed_objects/llm/tools/schemas.py +67 -0
- governed_objects/llm/tools/surface.py +252 -0
- governed_objects/llm/trace.py +58 -0
- governed_objects/materialization/service.py +107 -0
- governed_objects/observations/__init__.py +3 -0
- governed_objects/observations/ingestion.py +375 -0
- governed_objects/observations/mapping.py +48 -0
- governed_objects/observations/models.py +81 -0
- governed_objects/observations/store.py +214 -0
- governed_objects/observations/validation.py +188 -0
- governed_objects/outbound/__init__.py +3 -0
- governed_objects/outbound/models.py +94 -0
- governed_objects/outbound/service.py +502 -0
- governed_objects/outbound/store.py +147 -0
- governed_objects/persistence/sqlite.py +635 -0
- governed_objects/policy/constraints.py +9 -0
- governed_objects/policy/context.py +28 -0
- governed_objects/policy/evaluator.py +301 -0
- governed_objects/policy/outcomes.py +93 -0
- governed_objects/policy/reasons.py +43 -0
- governed_objects/providers/base.py +26 -0
- governed_objects/providers/binding.py +42 -0
- governed_objects/providers/capabilities.py +27 -0
- governed_objects/providers/errors.py +48 -0
- governed_objects/providers/projection.py +25 -0
- governed_objects/providers/registry.py +59 -0
- governed_objects/query/service.py +171 -0
- governed_objects/query/traversal.py +154 -0
- governed_objects/reconciliation/service.py +213 -0
- governed_objects/registration/detach.py +43 -0
- governed_objects/registration/service.py +113 -0
- governed_objects/relationships/canonical.py +55 -0
- governed_objects/relationships/sync.py +63 -0
- governed_objects/relationships/vocabulary.py +12 -0
- governed_objects/runtime/runtime.py +1919 -0
- governed_objects/types/canonicalizers/base.py +15 -0
- governed_objects/types/extensions.py +48 -0
- governed_objects/types/lifecycle.py +65 -0
- governed_objects/types/registry.py +171 -0
- governed_objects/types/schema.py +90 -0
- governed_objects/types/validation.py +57 -0
- governed_objects-0.2.1.dist-info/METADATA +184 -0
- governed_objects-0.2.1.dist-info/RECORD +88 -0
- governed_objects-0.2.1.dist-info/WHEEL +4 -0
- governed_objects-0.2.1.dist-info/licenses/LICENSE +202 -0
- governed_objects-0.2.1.dist-info/licenses/NOTICE +12 -0
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2026 Brafford Labs, LLC
|
|
3
|
+
"""Observation admission: captured authority, pure validity, staged local effects."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
from typing import Any
|
|
9
|
+
from uuid import uuid4
|
|
10
|
+
|
|
11
|
+
from governed_objects.adapters.context import AdapterContext
|
|
12
|
+
from governed_objects.adapters.registry import AdapterRegistry
|
|
13
|
+
from governed_objects.authority.rules import AuthorityMode, AuthorityRuleResolver
|
|
14
|
+
from governed_objects.domain.models import ActorType, Decision, GovernedObject, GovernanceEvent
|
|
15
|
+
from governed_objects.events.replay import bound_type_definition
|
|
16
|
+
from governed_objects.observations.models import (
|
|
17
|
+
UNKNOWN_EXTERNAL_ACTOR, ExternalObservation, FieldChange, ObservationDecision, ObservationResult,
|
|
18
|
+
)
|
|
19
|
+
from governed_objects.observations.store import ObservationStore
|
|
20
|
+
from governed_objects.observations.validation import (
|
|
21
|
+
CandidateMode, CandidateVerdict, candidate_image, capture_admission, validate_candidate,
|
|
22
|
+
)
|
|
23
|
+
from governed_objects.outbound.models import RepairStatus
|
|
24
|
+
from governed_objects.persistence.sqlite import INT64_MAX, SQLiteStore
|
|
25
|
+
from governed_objects.providers.errors import ProviderError, ProviderProjectionUnsupported
|
|
26
|
+
from governed_objects.relationships.sync import RelationshipSyncService
|
|
27
|
+
from governed_objects.types.registry import TypeRegistry
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class _PlanRefused(Exception):
|
|
31
|
+
pass
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class ObservationIngestionService:
|
|
35
|
+
"""Partial semantic outcomes, installed as one owned local admission plan."""
|
|
36
|
+
|
|
37
|
+
def __init__(self, store: SQLiteStore, type_registry: TypeRegistry,
|
|
38
|
+
observation_store: ObservationStore | None = None,
|
|
39
|
+
rel_sync: RelationshipSyncService | None = None,
|
|
40
|
+
adapters: AdapterRegistry | None = None,
|
|
41
|
+
adapter_context: AdapterContext | None = None,
|
|
42
|
+
outbound: Any | None = None) -> None:
|
|
43
|
+
self._store = store
|
|
44
|
+
self._types = type_registry
|
|
45
|
+
self._authority = AuthorityRuleResolver(type_registry)
|
|
46
|
+
self._observations = observation_store if observation_store is not None else ObservationStore(store)
|
|
47
|
+
self._rel_sync = rel_sync
|
|
48
|
+
self._adapters = adapters
|
|
49
|
+
self._adapter_context = adapter_context
|
|
50
|
+
self._outbound = outbound
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def observation_store(self) -> ObservationStore:
|
|
54
|
+
return self._observations
|
|
55
|
+
|
|
56
|
+
@staticmethod
|
|
57
|
+
def _refusal(observation_id: str, reason: str) -> ObservationResult:
|
|
58
|
+
return ObservationResult(observation_id=observation_id, decision=ObservationDecision.REJECT, reason=reason)
|
|
59
|
+
|
|
60
|
+
def ingest(self, observation: ExternalObservation) -> ObservationResult:
|
|
61
|
+
obj = self._store.get(observation.object_id)
|
|
62
|
+
if obj is None:
|
|
63
|
+
return self._finalize(observation, self._refusal(observation.id, "OBJECT_NOT_FOUND"))
|
|
64
|
+
if bound_type_definition(self._types, obj) is None:
|
|
65
|
+
return self._refusal(observation.id, "TYPE_VERSION_UNSUPPORTED")
|
|
66
|
+
observation = observation.model_copy(deep=True)
|
|
67
|
+
if self._observations.exists_dedupe_key(observation.dedupe_key()):
|
|
68
|
+
return ObservationResult(observation_id=observation.id, decision=ObservationDecision.NO_CHANGE,
|
|
69
|
+
reason="DUPLICATE_OBSERVATION")
|
|
70
|
+
if self._is_echo(obj, observation):
|
|
71
|
+
return self._finalize(observation, ObservationResult(observation_id=observation.id,
|
|
72
|
+
decision=ObservationDecision.ECHO, reason="GOVERNED_COMMAND_ECHO"))
|
|
73
|
+
if self._is_stale(obj, observation):
|
|
74
|
+
return self._finalize(observation, ObservationResult(observation_id=observation.id,
|
|
75
|
+
decision=ObservationDecision.STALE, reason="STALE_PROVIDER_VERSION"))
|
|
76
|
+
if not observation.changes and not observation.state_change:
|
|
77
|
+
return self._finalize(observation, ObservationResult(observation_id=observation.id,
|
|
78
|
+
decision=ObservationDecision.NO_CHANGE, reason="NO_DIFFERENCES"))
|
|
79
|
+
# A legacy bootstrap marker is provenance, never an authority grant.
|
|
80
|
+
return self._process_changes(obj, observation)
|
|
81
|
+
|
|
82
|
+
def _baseline(self, obj):
|
|
83
|
+
return (self._store.version_high_water(obj.id), self._store.list_accepted_for_object(obj.id))
|
|
84
|
+
|
|
85
|
+
def _check_current(self, obj, baseline, snapshot, case=None):
|
|
86
|
+
if not snapshot.matches(self._types, self._adapters, obj):
|
|
87
|
+
raise _PlanRefused("VALIDATION_UNAVAILABLE")
|
|
88
|
+
if self._store.get(obj.id) != obj or self._baseline(obj) != baseline:
|
|
89
|
+
raise _PlanRefused("CANONICAL_CHANGED")
|
|
90
|
+
if case is not None and self._observations.get_review_case(case["id"]) != case:
|
|
91
|
+
raise _PlanRefused("CANONICAL_CHANGED")
|
|
92
|
+
|
|
93
|
+
def _verdict(self, snapshot, current, candidate, mode):
|
|
94
|
+
return validate_candidate(type_def=snapshot.definition, current=candidate_image(current),
|
|
95
|
+
candidate=candidate_image(candidate), mode=mode, adapter=snapshot.adapter)
|
|
96
|
+
|
|
97
|
+
def _process_changes(self, obj: GovernedObject, observation: ExternalObservation) -> ObservationResult:
|
|
98
|
+
baseline = self._baseline(obj)
|
|
99
|
+
try:
|
|
100
|
+
snapshot = capture_admission(self._types, self._adapters, obj)
|
|
101
|
+
rules = self._authority.rules_for_definitions(snapshot.definitions)
|
|
102
|
+
except Exception:
|
|
103
|
+
return self._refusal(observation.id, "VALIDATION_UNAVAILABLE")
|
|
104
|
+
current = obj.model_copy(deep=True)
|
|
105
|
+
steps = []
|
|
106
|
+
pending = []
|
|
107
|
+
fields = {}
|
|
108
|
+
repairs = []
|
|
109
|
+
reasons = []
|
|
110
|
+
invalid = False
|
|
111
|
+
dimensions = []
|
|
112
|
+
if observation.state_change is not None:
|
|
113
|
+
dimensions.append(("state", observation.state_change, True))
|
|
114
|
+
dimensions.extend((name, change, False) for name, change in observation.changes.items())
|
|
115
|
+
for name, change, is_state in dimensions:
|
|
116
|
+
previous = current.state if is_state else current.data.get(name)
|
|
117
|
+
if previous == change.observed:
|
|
118
|
+
fields[name] = ObservationDecision.NO_CHANGE.value
|
|
119
|
+
continue
|
|
120
|
+
rule = rules.fields.get(name)
|
|
121
|
+
mode = rule.mode if rule is not None else AuthorityMode.REQUIRES_REVIEW
|
|
122
|
+
if mode == AuthorityMode.CANONICAL_AUTHORITATIVE:
|
|
123
|
+
fields[name] = ObservationDecision.REJECT.value
|
|
124
|
+
repairs.append(name)
|
|
125
|
+
reasons.append("CANONICAL_AUTHORITATIVE")
|
|
126
|
+
continue
|
|
127
|
+
if mode == AuthorityMode.REQUIRES_REVIEW:
|
|
128
|
+
pending.append(dict(case_id=str(uuid4()), object_id=obj.id, observation_id=observation.id,
|
|
129
|
+
field_name=name, canonical_value=previous, observed_value=change.observed))
|
|
130
|
+
fields[name] = ObservationDecision.REQUIRES_REVIEW.value
|
|
131
|
+
reasons.append("REQUIRES_REVIEW")
|
|
132
|
+
continue
|
|
133
|
+
candidate = self._changed(current, name, change.observed, is_state=is_state)
|
|
134
|
+
verdict = self._verdict(snapshot, current, candidate, CandidateMode.OBSERVATION)
|
|
135
|
+
if verdict == CandidateVerdict.UNAVAILABLE:
|
|
136
|
+
return self._refusal(observation.id, "VALIDATION_UNAVAILABLE")
|
|
137
|
+
if verdict == CandidateVerdict.INVALID:
|
|
138
|
+
fields[name] = ObservationDecision.REJECT.value
|
|
139
|
+
reasons.append("CANDIDATE_INVALID")
|
|
140
|
+
invalid = True
|
|
141
|
+
continue
|
|
142
|
+
steps.append((candidate, name, change, previous))
|
|
143
|
+
current = candidate
|
|
144
|
+
fields[name] = ObservationDecision.ACCEPT.value
|
|
145
|
+
reasons.append("ACCEPTED")
|
|
146
|
+
aggregate = (ObservationDecision.ACCEPT if steps else ObservationDecision.REQUIRES_REVIEW if pending
|
|
147
|
+
else ObservationDecision.REJECT if ObservationDecision.REJECT.value in fields.values()
|
|
148
|
+
else ObservationDecision.NO_CHANGE)
|
|
149
|
+
result = ObservationResult(observation_id=observation.id, decision=aggregate,
|
|
150
|
+
reason="MULTI_FIELD" if len(fields) > 1 else reasons[0] if reasons else "NO_APPLICABLE_CHANGES",
|
|
151
|
+
field_results=fields, repair_candidates=repairs,
|
|
152
|
+
review_case_id=pending[-1]["case_id"] if pending else None, object_version=obj.version)
|
|
153
|
+
# Pending artifacts must be representable. Rejected non-JSON proposal
|
|
154
|
+
# values need not be recorded/deduped as if they were canonical data.
|
|
155
|
+
try:
|
|
156
|
+
json.dumps(pending, allow_nan=False)
|
|
157
|
+
except (TypeError, ValueError, OverflowError):
|
|
158
|
+
return self._refusal(observation.id, "VALIDATION_UNAVAILABLE")
|
|
159
|
+
record_observation = self._recordable(observation)
|
|
160
|
+
try:
|
|
161
|
+
self._check_current(obj, baseline, snapshot)
|
|
162
|
+
with self._store.observation_transaction():
|
|
163
|
+
self._check_current(obj, baseline, snapshot)
|
|
164
|
+
top = max(obj.version, baseline[0] if baseline[0] is not None else obj.version)
|
|
165
|
+
if len(steps) > INT64_MAX - top:
|
|
166
|
+
raise _PlanRefused("OBJECT_VERSION_SPACE_EXHAUSTED")
|
|
167
|
+
previous_obj = obj
|
|
168
|
+
for offset, (image, name, change, previous) in enumerate(steps, 1):
|
|
169
|
+
updated = image.model_copy(update={"version": top + offset,
|
|
170
|
+
"metadata": self._update_obs_meta(image, observation)})
|
|
171
|
+
event = self._event(previous_obj, updated, name, previous, change.observed,
|
|
172
|
+
observation, "external_observation", None)
|
|
173
|
+
self._store.save(updated)
|
|
174
|
+
event = self._store.append_accepted(event)
|
|
175
|
+
result.canonical_event_id = event.event_id
|
|
176
|
+
result.object_version = updated.version
|
|
177
|
+
previous_obj = updated
|
|
178
|
+
for case in pending:
|
|
179
|
+
self._observations.create_review_case(**case)
|
|
180
|
+
if record_observation:
|
|
181
|
+
self._observations.save_observation(observation, decision=result.decision, reason=result.reason,
|
|
182
|
+
canonical_event_id=result.canonical_event_id)
|
|
183
|
+
except _PlanRefused as exc:
|
|
184
|
+
return self._refusal(observation.id, str(exc))
|
|
185
|
+
if steps or (observation.source.value == "WEBHOOK" and not invalid):
|
|
186
|
+
self._post_sync(observation.object_id, result)
|
|
187
|
+
return result
|
|
188
|
+
|
|
189
|
+
@staticmethod
|
|
190
|
+
def _recordable(observation):
|
|
191
|
+
try:
|
|
192
|
+
json.dumps({"changes": {k: v.model_dump() for k, v in observation.changes.items()},
|
|
193
|
+
"state_change": observation.state_change.model_dump() if observation.state_change else None,
|
|
194
|
+
"raw_metadata": observation.raw_metadata}, allow_nan=False)
|
|
195
|
+
return True
|
|
196
|
+
except (TypeError, ValueError, OverflowError):
|
|
197
|
+
return False
|
|
198
|
+
|
|
199
|
+
@staticmethod
|
|
200
|
+
def _changed(obj, field, value, *, is_state=None):
|
|
201
|
+
if is_state is True or (is_state is None and field == "state"):
|
|
202
|
+
return obj.model_copy(deep=True, update={"state": value})
|
|
203
|
+
data = dict(obj.data)
|
|
204
|
+
data[field] = value
|
|
205
|
+
return obj.model_copy(deep=True, update={"data": data})
|
|
206
|
+
|
|
207
|
+
def resolve_review(self, case_id: str, *, resolution: str, resolved_by: str) -> ObservationResult:
|
|
208
|
+
case = self._observations.get_review_case(case_id)
|
|
209
|
+
if case is None or case["state"] != "open":
|
|
210
|
+
return self._refusal(case_id, "REVIEW_CASE_NOT_OPEN")
|
|
211
|
+
obj = self._store.get(case["object_id"])
|
|
212
|
+
if obj is None:
|
|
213
|
+
return self._refusal(case_id, "OBJECT_NOT_FOUND")
|
|
214
|
+
if bound_type_definition(self._types, obj) is None:
|
|
215
|
+
return self._refusal(case_id, "TYPE_VERSION_UNSUPPORTED")
|
|
216
|
+
if resolution not in ("ACCEPT_EXTERNAL", "KEEP_CANONICAL"):
|
|
217
|
+
return self._refusal(case["observation_id"], "UNKNOWN_RESOLUTION")
|
|
218
|
+
baseline = self._baseline(obj)
|
|
219
|
+
try:
|
|
220
|
+
snapshot = capture_admission(self._types, self._adapters, obj)
|
|
221
|
+
except Exception:
|
|
222
|
+
return self._refusal(case["observation_id"], "VALIDATION_UNAVAILABLE")
|
|
223
|
+
field = case["field_name"]
|
|
224
|
+
observed = json.loads(case["observed_value"])
|
|
225
|
+
previous = obj.state if field == "state" else obj.data.get(field)
|
|
226
|
+
candidate = self._changed(obj, field, observed)
|
|
227
|
+
if resolution == "ACCEPT_EXTERNAL":
|
|
228
|
+
verdict = self._verdict(snapshot, obj, candidate, CandidateMode.REVIEW_ACCEPT)
|
|
229
|
+
if verdict != CandidateVerdict.VALID:
|
|
230
|
+
return self._refusal(case["observation_id"], "CANDIDATE_INVALID" if verdict == CandidateVerdict.INVALID
|
|
231
|
+
else "VALIDATION_UNAVAILABLE")
|
|
232
|
+
changed = resolution == "ACCEPT_EXTERNAL" and previous != observed
|
|
233
|
+
result = ObservationResult(observation_id=case["observation_id"],
|
|
234
|
+
decision=ObservationDecision.ACCEPT if changed else ObservationDecision.NO_CHANGE if resolution == "ACCEPT_EXTERNAL"
|
|
235
|
+
else ObservationDecision.REJECT,
|
|
236
|
+
reason="ACCEPTED" if changed else "FIELD_UNCHANGED" if resolution == "ACCEPT_EXTERNAL" else "REVIEW_KEEP_CANONICAL",
|
|
237
|
+
review_case_id=case_id, object_version=obj.version if resolution == "ACCEPT_EXTERNAL" else None)
|
|
238
|
+
try:
|
|
239
|
+
self._check_current(obj, baseline, snapshot, case)
|
|
240
|
+
with self._store.observation_transaction():
|
|
241
|
+
self._check_current(obj, baseline, snapshot, case)
|
|
242
|
+
if changed:
|
|
243
|
+
top = max(obj.version, baseline[0] if baseline[0] is not None else obj.version)
|
|
244
|
+
if top >= INT64_MAX:
|
|
245
|
+
raise _PlanRefused("OBJECT_VERSION_SPACE_EXHAUSTED")
|
|
246
|
+
observation = ExternalObservation(id=case["observation_id"], object_id=obj.id,
|
|
247
|
+
provider_name="review", external_id="")
|
|
248
|
+
candidate = candidate.model_copy(update={"version": top + 1,
|
|
249
|
+
"metadata": self._update_obs_meta(candidate, observation)})
|
|
250
|
+
event = self._event(obj, candidate, field, previous, observed, observation,
|
|
251
|
+
"reconciliation_review", resolved_by)
|
|
252
|
+
self._store.save(candidate)
|
|
253
|
+
event = self._store.append_accepted(event)
|
|
254
|
+
result.canonical_event_id = event.event_id
|
|
255
|
+
result.object_version = candidate.version
|
|
256
|
+
self._observations.resolve_review_case(case_id, resolution=resolution, resolved_by=resolved_by,
|
|
257
|
+
canonical_event_id=result.canonical_event_id)
|
|
258
|
+
except _PlanRefused as exc:
|
|
259
|
+
return self._refusal(case["observation_id"], str(exc))
|
|
260
|
+
if resolution == "KEEP_CANONICAL":
|
|
261
|
+
self._repair_kept(obj, baseline, snapshot, field, resolved_by, case["observation_id"], result)
|
|
262
|
+
return result
|
|
263
|
+
|
|
264
|
+
def _repair_kept(self, obj, baseline, snapshot, field, resolved_by, observation_id, result):
|
|
265
|
+
if self._outbound is None or self._adapter_context is None:
|
|
266
|
+
return
|
|
267
|
+
verdict = self._verdict(snapshot, obj, obj, CandidateMode.REPAIR_EXISTING)
|
|
268
|
+
if verdict != CandidateVerdict.VALID:
|
|
269
|
+
result.field_results[field] = ("CANDIDATE_INVALID" if verdict == CandidateVerdict.INVALID else "VALIDATION_UNAVAILABLE")
|
|
270
|
+
return
|
|
271
|
+
try:
|
|
272
|
+
self._check_current(obj, baseline, snapshot)
|
|
273
|
+
except _PlanRefused as exc:
|
|
274
|
+
result.field_results[field] = str(exc)
|
|
275
|
+
return
|
|
276
|
+
try:
|
|
277
|
+
plan = self._outbound.plan(obj.id, self._adapter_context, fields=[field],
|
|
278
|
+
originating_observation_id=observation_id)
|
|
279
|
+
if plan and plan.changes:
|
|
280
|
+
repaired = self._outbound.apply(plan, self._adapter_context, initiated_by=resolved_by)
|
|
281
|
+
result.repair_candidates = [field]
|
|
282
|
+
if repaired.status == RepairStatus.UNSUPPORTED_PROVIDER:
|
|
283
|
+
result.field_results[field] = "UNSUPPORTED_PROVIDER"
|
|
284
|
+
except ProviderProjectionUnsupported:
|
|
285
|
+
result.field_results[field] = "UNSUPPORTED_PROVIDER"
|
|
286
|
+
except ProviderError:
|
|
287
|
+
result.field_results[field] = "PROVIDER_ERROR"
|
|
288
|
+
|
|
289
|
+
@staticmethod
|
|
290
|
+
def _event(previous, updated, field, old, new, observation, source, resolved_by):
|
|
291
|
+
details = {"field": field, "previous": old, "new": new, "data": dict(updated.data),
|
|
292
|
+
"source": source, "observation_id": observation.id, "provider_name": observation.provider_name,
|
|
293
|
+
"provider_event_id": observation.provider_event_id, "provider_actor_id": observation.provider_actor_id,
|
|
294
|
+
"actor_provenance": "KNOWN_EXTERNAL_ACTOR" if observation.provider_actor_id else UNKNOWN_EXTERNAL_ACTOR}
|
|
295
|
+
if resolved_by:
|
|
296
|
+
details["resolved_by"] = resolved_by
|
|
297
|
+
return GovernanceEvent(object_id=updated.id, object_type=updated.type, type_version=updated.type_version,
|
|
298
|
+
actor_id=observation.provider_actor_id or UNKNOWN_EXTERNAL_ACTOR, actor_type=ActorType.SERVICE.value,
|
|
299
|
+
action="state_changed" if field == "state" else f"{field}_changed", decision=Decision.ALLOW,
|
|
300
|
+
event_type="external_observation.accepted", previous_state=previous.state, new_state=updated.state,
|
|
301
|
+
reason="external observation accepted", object_version=updated.version, details=details)
|
|
302
|
+
|
|
303
|
+
def _finalize(self, observation, result, *, canonical_event_id=None):
|
|
304
|
+
self._observations.save_observation(observation, decision=result.decision, reason=result.reason,
|
|
305
|
+
canonical_event_id=canonical_event_id or result.canonical_event_id)
|
|
306
|
+
if result.decision == ObservationDecision.ACCEPT or observation.source.value == "WEBHOOK":
|
|
307
|
+
self._post_sync(observation.object_id, result)
|
|
308
|
+
return result
|
|
309
|
+
|
|
310
|
+
def _post_sync(self, object_id, result):
|
|
311
|
+
try:
|
|
312
|
+
self._sync_relationships(object_id)
|
|
313
|
+
except ProviderProjectionUnsupported:
|
|
314
|
+
result.field_results["provider_sync"] = "UNSUPPORTED_PROVIDER"
|
|
315
|
+
except ProviderError:
|
|
316
|
+
result.field_results["provider_sync"] = "PROVIDER_ERROR"
|
|
317
|
+
|
|
318
|
+
def _sync_relationships(self, object_id: str) -> None:
|
|
319
|
+
if self._rel_sync is None or self._adapters is None or self._adapter_context is None:
|
|
320
|
+
return
|
|
321
|
+
stored = self._store.get(object_id)
|
|
322
|
+
if stored is None:
|
|
323
|
+
return
|
|
324
|
+
binding = stored.metadata.get("provider_binding") or {}
|
|
325
|
+
provider_name = binding.get("provider_name") or binding.get("provider")
|
|
326
|
+
if not provider_name:
|
|
327
|
+
return
|
|
328
|
+
adapter = self._adapters.resolve(stored)
|
|
329
|
+
hydrated = adapter.load(stored, self._adapter_context)
|
|
330
|
+
if hydrated and hydrated.relationships:
|
|
331
|
+
self._rel_sync.sync_provider_relationships(object_id, hydrated.relationships, provider_name=provider_name)
|
|
332
|
+
|
|
333
|
+
def _is_echo(self, obj: GovernedObject, observation: ExternalObservation) -> bool:
|
|
334
|
+
repair_of = observation.raw_metadata.get("repair_of")
|
|
335
|
+
if repair_of is None:
|
|
336
|
+
repair_of = (observation.raw_metadata.get("webhook") or {}).get("repair_of")
|
|
337
|
+
repair_echo = obj.metadata.get("_provider_repair_echo") or {}
|
|
338
|
+
if repair_of and repair_echo.get("repair_id") == repair_of:
|
|
339
|
+
return True
|
|
340
|
+
echo = obj.metadata.get("_governed_echo") or {}
|
|
341
|
+
if not echo:
|
|
342
|
+
return False
|
|
343
|
+
if observation.provider_event_id and echo.get("provider_event_id") == observation.provider_event_id:
|
|
344
|
+
return True
|
|
345
|
+
echo_of = observation.raw_metadata.get("echo_of")
|
|
346
|
+
if echo_of is None:
|
|
347
|
+
echo_of = (observation.raw_metadata.get("webhook") or {}).get("echo_of")
|
|
348
|
+
return bool(echo_of and echo.get("correlation_id") == echo_of)
|
|
349
|
+
|
|
350
|
+
def _is_stale(self, obj: GovernedObject, observation: ExternalObservation) -> bool:
|
|
351
|
+
if observation.provider_version is None:
|
|
352
|
+
return False
|
|
353
|
+
last_version = (obj.metadata.get("_observation_state") or {}).get("last_accepted_provider_version")
|
|
354
|
+
if last_version is None:
|
|
355
|
+
return False
|
|
356
|
+
try:
|
|
357
|
+
return int(observation.provider_version) <= int(last_version)
|
|
358
|
+
except (TypeError, ValueError):
|
|
359
|
+
return observation.provider_version <= last_version
|
|
360
|
+
|
|
361
|
+
def _update_obs_meta(self, obj, observation):
|
|
362
|
+
meta = dict(obj.metadata)
|
|
363
|
+
state = dict(meta.get("_observation_state") or {})
|
|
364
|
+
if observation.provider_version is not None:
|
|
365
|
+
state["last_accepted_provider_version"] = observation.provider_version
|
|
366
|
+
meta["_observation_state"] = state
|
|
367
|
+
return meta
|
|
368
|
+
|
|
369
|
+
def record_governed_echo(self, obj: GovernedObject, *, correlation_id: str | None,
|
|
370
|
+
provider_event_id: str | None = None) -> GovernedObject:
|
|
371
|
+
if not correlation_id and not provider_event_id:
|
|
372
|
+
return obj
|
|
373
|
+
meta = dict(obj.metadata)
|
|
374
|
+
meta["_governed_echo"] = {"correlation_id": correlation_id, "provider_event_id": provider_event_id}
|
|
375
|
+
return obj.model_copy(update={"metadata": meta})
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2026 Brafford Labs, LLC
|
|
3
|
+
"""Map normalized reconciliation differences to external observations."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from governed_objects.observations.models import ExternalObservation, FieldChange, ObservationSource
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def reconciliation_to_observation(
|
|
13
|
+
*,
|
|
14
|
+
object_id: str,
|
|
15
|
+
provider_name: str,
|
|
16
|
+
external_id: str,
|
|
17
|
+
canonical: dict[str, Any],
|
|
18
|
+
canonical_state: str,
|
|
19
|
+
provider_data: dict[str, Any],
|
|
20
|
+
provider_state: str,
|
|
21
|
+
provider_type: str = "generic",
|
|
22
|
+
) -> ExternalObservation | None:
|
|
23
|
+
"""Build observation from canonical vs provider comparison."""
|
|
24
|
+
changes: dict[str, FieldChange] = {}
|
|
25
|
+
all_keys = set(canonical.keys()) | set(provider_data.keys())
|
|
26
|
+
for field in all_keys:
|
|
27
|
+
old_val = canonical.get(field)
|
|
28
|
+
new_val = provider_data.get(field)
|
|
29
|
+
if old_val != new_val and new_val is not None:
|
|
30
|
+
changes[field] = FieldChange(previous_observed=old_val, observed=new_val)
|
|
31
|
+
|
|
32
|
+
state_change = None
|
|
33
|
+
if canonical_state != provider_state:
|
|
34
|
+
state_change = FieldChange(previous_observed=canonical_state, observed=provider_state)
|
|
35
|
+
|
|
36
|
+
if not changes and not state_change:
|
|
37
|
+
return None
|
|
38
|
+
|
|
39
|
+
return ExternalObservation(
|
|
40
|
+
object_id=object_id,
|
|
41
|
+
provider_type=provider_type,
|
|
42
|
+
provider_name=provider_name,
|
|
43
|
+
external_id=external_id,
|
|
44
|
+
source=ObservationSource.RECONCILIATION,
|
|
45
|
+
changes=changes,
|
|
46
|
+
state_change=state_change,
|
|
47
|
+
provider_version=provider_data.get("_provider_version"),
|
|
48
|
+
)
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2026 Brafford Labs, LLC
|
|
3
|
+
"""External observation models — provider claims, not accepted canonical truth."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from datetime import UTC, datetime
|
|
8
|
+
from enum import StrEnum
|
|
9
|
+
from typing import Any
|
|
10
|
+
from uuid import uuid4
|
|
11
|
+
|
|
12
|
+
from pydantic import BaseModel, Field
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ObservationSource(StrEnum):
|
|
16
|
+
WEBHOOK = "WEBHOOK"
|
|
17
|
+
RECONCILIATION = "RECONCILIATION"
|
|
18
|
+
MANUAL_IMPORT = "MANUAL_IMPORT"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class ObservationDecision(StrEnum):
|
|
22
|
+
ACCEPT = "ACCEPT"
|
|
23
|
+
REJECT = "REJECT"
|
|
24
|
+
REQUIRES_REVIEW = "REQUIRES_REVIEW"
|
|
25
|
+
NO_CHANGE = "NO_CHANGE"
|
|
26
|
+
STALE = "STALE"
|
|
27
|
+
ECHO = "ECHO"
|
|
28
|
+
REJECT_LIFECYCLE_INVALID = "REJECT_LIFECYCLE_INVALID"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
UNKNOWN_EXTERNAL_ACTOR = "UNKNOWN_EXTERNAL_ACTOR"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class FieldChange(BaseModel):
|
|
35
|
+
previous_observed: Any | None = None
|
|
36
|
+
observed: Any
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class ExternalObservation(BaseModel):
|
|
40
|
+
"""Provider X reports that canonical-relevant fact Y currently looks like Z."""
|
|
41
|
+
|
|
42
|
+
id: str = Field(default_factory=lambda: str(uuid4()))
|
|
43
|
+
object_id: str
|
|
44
|
+
provider_type: str = "generic"
|
|
45
|
+
provider_name: str
|
|
46
|
+
external_id: str
|
|
47
|
+
observed_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
|
|
48
|
+
source: ObservationSource = ObservationSource.WEBHOOK
|
|
49
|
+
changes: dict[str, FieldChange] = Field(default_factory=dict)
|
|
50
|
+
provider_actor_id: str | None = None
|
|
51
|
+
provider_event_id: str | None = None
|
|
52
|
+
provider_version: str | None = None
|
|
53
|
+
provider_sequence: int | None = None
|
|
54
|
+
raw_metadata: dict[str, Any] = Field(default_factory=dict)
|
|
55
|
+
state_change: FieldChange | None = None
|
|
56
|
+
|
|
57
|
+
def dedupe_key(self) -> str:
|
|
58
|
+
if self.provider_event_id:
|
|
59
|
+
return f"{self.provider_name}:{self.provider_event_id}"
|
|
60
|
+
parts = [
|
|
61
|
+
self.provider_name,
|
|
62
|
+
self.external_id,
|
|
63
|
+
self.provider_version or "",
|
|
64
|
+
str(self.provider_sequence or ""),
|
|
65
|
+
",".join(sorted(self.changes.keys())),
|
|
66
|
+
]
|
|
67
|
+
if self.state_change:
|
|
68
|
+
parts.append(f"state:{self.state_change.observed}")
|
|
69
|
+
return ":".join(parts)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class ObservationResult(BaseModel):
|
|
73
|
+
observation_id: str
|
|
74
|
+
decision: ObservationDecision
|
|
75
|
+
reason: str = ""
|
|
76
|
+
differences: list[str] = Field(default_factory=list)
|
|
77
|
+
field_results: dict[str, str] = Field(default_factory=dict)
|
|
78
|
+
repair_candidates: list[str] = Field(default_factory=list)
|
|
79
|
+
canonical_event_id: str | None = None
|
|
80
|
+
review_case_id: str | None = None
|
|
81
|
+
object_version: int | None = None
|