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,301 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Brafford Labs, LLC
3
+ """Capability-based policy evaluation for governed objects."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from typing import Protocol
8
+
9
+ from governed_objects.applications.registry import ApplicationDefinition
10
+ from governed_objects.delegation.mandate import DelegatedMandate, MandateStatus
11
+ from governed_objects.delegation.resolver import ResolvedMandateAuthority
12
+ from governed_objects.delegation.scope import scope_allows
13
+ from governed_objects.domain.clock import Clock, SystemClock
14
+ from governed_objects.domain.models import Actor, Decision, GovernedObject
15
+ from governed_objects.persistence.sqlite import SQLiteStore
16
+ from governed_objects.policy.reasons import DenyReason
17
+ from governed_objects.policy.constraints import ConstraintHandler
18
+ from governed_objects.types.schema import ObjectTypeDefinition
19
+
20
+
21
+ class PolicyDecision:
22
+ def __init__(
23
+ self,
24
+ decision: Decision,
25
+ reason: str,
26
+ required: list[str],
27
+ satisfied: list[str],
28
+ missing: list[str],
29
+ *,
30
+ deny_reason: DenyReason | None = None,
31
+ ) -> None:
32
+ self.decision = decision
33
+ self.reason = reason
34
+ self.required_capabilities = required
35
+ self.satisfied_capabilities = satisfied
36
+ self.missing_capabilities = missing
37
+ self.deny_reason = deny_reason
38
+
39
+
40
+ class PolicyEvaluator(Protocol):
41
+ def evaluate(
42
+ self,
43
+ actor: Actor,
44
+ action: str,
45
+ obj: GovernedObject | None,
46
+ type_def: ObjectTypeDefinition,
47
+ *,
48
+ required_capabilities: list[str] | None = None,
49
+ application: ApplicationDefinition | None = None,
50
+ mandate: DelegatedMandate | None = None,
51
+ resolved_mandate: ResolvedMandateAuthority | None = None,
52
+ purpose: str | None = None,
53
+ ) -> PolicyDecision: ...
54
+
55
+
56
+ class CapabilityPolicyEvaluator:
57
+ """Deterministic capability-based policy evaluator.
58
+
59
+ Effective authority = actor ∩ mandate ∩ application capabilities,
60
+ plus mandate time/purpose/scope when a mandate is present.
61
+ """
62
+
63
+ def __init__(
64
+ self,
65
+ *,
66
+ clock: Clock | None = None,
67
+ store: SQLiteStore | None = None,
68
+ constraint_handlers: dict[str, ConstraintHandler] | None = None,
69
+ ) -> None:
70
+ self._clock = clock or SystemClock()
71
+ self._store = store
72
+ self._constraint_handlers = dict(constraint_handlers or {})
73
+ self._application_source = None
74
+ self._mandate_source = None
75
+
76
+ def bind_context_sources(self, *, application_source, mandate_source) -> None:
77
+ """Explicit local authority sources; snapshots alone are never grants."""
78
+ self._application_source = application_source
79
+ self._mandate_source = mandate_source
80
+
81
+ def evaluate(
82
+ self,
83
+ actor: Actor,
84
+ action: str,
85
+ obj: GovernedObject | None,
86
+ type_def: ObjectTypeDefinition,
87
+ *,
88
+ required_capabilities: list[str] | None = None,
89
+ application: ApplicationDefinition | None = None,
90
+ mandate: DelegatedMandate | None = None,
91
+ resolved_mandate: ResolvedMandateAuthority | None = None,
92
+ purpose: str | None = None,
93
+ ) -> PolicyDecision:
94
+ required = (
95
+ required_capabilities
96
+ if required_capabilities is not None
97
+ else type_def.required_capabilities(action)
98
+ )
99
+ open_action = required_capabilities is None and type_def.is_open(action)
100
+
101
+ if application is not None:
102
+ try:
103
+ if self._application_source is None or not isinstance(application.id, str) or not application.id:
104
+ raise ValueError('unresolved application')
105
+ application = self._application_source(application.id)
106
+ if not isinstance(application, ApplicationDefinition):
107
+ raise ValueError('unresolved application')
108
+ except (ValueError, TypeError, KeyError, AttributeError):
109
+ return PolicyDecision(Decision.DENY, 'application authority unavailable', required, [], required,
110
+ deny_reason=DenyReason.APPLICATION_UNKNOWN)
111
+ if mandate is not None or resolved_mandate is not None:
112
+ try:
113
+ identities = [value for value in (
114
+ mandate.id if mandate is not None else None,
115
+ resolved_mandate.mandate_id if resolved_mandate is not None else None,
116
+ ) if value is not None]
117
+ if (self._mandate_source is None or not identities
118
+ or any(not isinstance(value, str) or not value for value in identities)
119
+ or len(set(identities)) != 1):
120
+ raise ValueError('unresolved mandate')
121
+ resolved_mandate = self._mandate_source(identities[0])
122
+ if not isinstance(resolved_mandate, ResolvedMandateAuthority):
123
+ raise ValueError('unresolved mandate')
124
+ mandate = None
125
+ except (ValueError, TypeError, KeyError, AttributeError):
126
+ return PolicyDecision(Decision.DENY, 'mandate authority unavailable', required, [], required,
127
+ deny_reason=DenyReason.MANDATE_INVALID)
128
+
129
+ for constraint in actor.constraints:
130
+ handler = self._constraint_handlers.get(constraint)
131
+ if handler is None or handler(actor, action, obj, type_def) is not True:
132
+ return PolicyDecision(
133
+ Decision.DENY,
134
+ f"actor constraint violated: {constraint}",
135
+ required,
136
+ [],
137
+ required,
138
+ deny_reason=DenyReason.CONSTRAINT_VIOLATION,
139
+ )
140
+
141
+ actor_decision = self._evaluate_caps(
142
+ set(actor.capabilities),
143
+ required,
144
+ subject="actor",
145
+ open_action=open_action,
146
+ )
147
+ if actor_decision.decision == Decision.DENY:
148
+ actor_decision.deny_reason = DenyReason.ACTOR_CAPABILITY_MISSING
149
+ return actor_decision
150
+
151
+ if mandate is not None or resolved_mandate is not None:
152
+ mandate_deny = self._evaluate_mandate(
153
+ actor, mandate, resolved_mandate, required, purpose, obj, open_action=open_action
154
+ )
155
+ if mandate_deny is not None:
156
+ return mandate_deny
157
+
158
+ if application is not None:
159
+ app_decision = self._evaluate_caps(
160
+ set(application.capabilities),
161
+ required,
162
+ subject=f"application:{application.id}",
163
+ open_action=open_action,
164
+ )
165
+ if app_decision.decision == Decision.DENY:
166
+ app_decision.deny_reason = DenyReason.APPLICATION_CAPABILITY_MISSING
167
+ return app_decision
168
+
169
+ return PolicyDecision(
170
+ Decision.ALLOW,
171
+ "policy satisfied",
172
+ required,
173
+ actor_decision.satisfied_capabilities,
174
+ actor_decision.missing_capabilities,
175
+ )
176
+
177
+ def _evaluate_mandate(
178
+ self,
179
+ actor: Actor,
180
+ mandate: DelegatedMandate | None,
181
+ resolved: ResolvedMandateAuthority | None,
182
+ required: list[str],
183
+ purpose: str | None,
184
+ obj: GovernedObject | None,
185
+ *,
186
+ open_action: bool = False,
187
+ ) -> PolicyDecision | None:
188
+ authority = resolved
189
+ if authority is None:
190
+ return PolicyDecision(Decision.DENY, 'mandate authority unavailable', required, [], required,
191
+ deny_reason=DenyReason.MANDATE_INVALID)
192
+
193
+ if authority.delegate_actor_id != actor.id:
194
+ return PolicyDecision(
195
+ Decision.DENY,
196
+ "mandate delegate mismatch",
197
+ required,
198
+ [],
199
+ required,
200
+ deny_reason=DenyReason.MANDATE_DELEGATE_MISMATCH,
201
+ )
202
+
203
+ if authority.ancestor_ineffective_reason is not None:
204
+ return PolicyDecision(
205
+ Decision.DENY,
206
+ authority.ancestor_ineffective_reason.value.lower().replace("_", " "),
207
+ required,
208
+ [],
209
+ required,
210
+ deny_reason=authority.ancestor_ineffective_reason,
211
+ )
212
+
213
+ now = self._clock.now()
214
+ effective, time_reason = authority.is_effective_at(now)
215
+ if not effective and time_reason is not None:
216
+ return PolicyDecision(
217
+ Decision.DENY,
218
+ time_reason.value.lower().replace("_", " "),
219
+ required,
220
+ [],
221
+ required,
222
+ deny_reason=time_reason,
223
+ )
224
+
225
+ if authority.purposes or authority.purpose_restricted:
226
+ if purpose is None or purpose not in authority.purposes:
227
+ return PolicyDecision(
228
+ Decision.DENY,
229
+ "purpose mismatch",
230
+ required,
231
+ [],
232
+ required,
233
+ deny_reason=DenyReason.PURPOSE_MISMATCH,
234
+ )
235
+
236
+ mandate_decision = self._evaluate_caps(
237
+ set(authority.capabilities),
238
+ required,
239
+ subject=f"mandate:{authority.mandate_id}",
240
+ open_action=open_action,
241
+ )
242
+ if mandate_decision.decision == Decision.DENY:
243
+ mandate_decision.deny_reason = DenyReason.MANDATE_CAPABILITY_MISSING
244
+ return mandate_decision
245
+
246
+ if not authority.scope.is_empty():
247
+ if obj is None or self._store is None or not scope_allows(authority.scope, obj, self._store):
248
+ return PolicyDecision(
249
+ Decision.DENY,
250
+ "mandate scope mismatch",
251
+ required,
252
+ [],
253
+ required,
254
+ deny_reason=DenyReason.MANDATE_SCOPE_MISMATCH,
255
+ )
256
+ return None
257
+
258
+ @staticmethod
259
+ def _evaluate_caps(
260
+ caps: set[str],
261
+ required: list[str],
262
+ *,
263
+ subject: str,
264
+ open_action: bool = False,
265
+ ) -> PolicyDecision:
266
+ satisfied = [cap for cap in required if cap in caps]
267
+ missing = [cap for cap in required if cap not in caps]
268
+
269
+ if not required:
270
+ if open_action:
271
+ return PolicyDecision(
272
+ Decision.ALLOW,
273
+ f"no capabilities required for {subject} (type marked open)",
274
+ required,
275
+ satisfied,
276
+ missing,
277
+ )
278
+ return PolicyDecision(
279
+ Decision.DENY,
280
+ f"no capabilities declared for {subject} and type is not marked open",
281
+ required,
282
+ satisfied,
283
+ missing,
284
+ )
285
+
286
+ if missing:
287
+ return PolicyDecision(
288
+ Decision.DENY,
289
+ f"{subject} missing capabilities: {', '.join(missing)}",
290
+ required,
291
+ satisfied,
292
+ missing,
293
+ )
294
+
295
+ return PolicyDecision(
296
+ Decision.ALLOW,
297
+ f"{subject} policy satisfied",
298
+ required,
299
+ satisfied,
300
+ missing,
301
+ )
@@ -0,0 +1,93 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Brafford Labs, LLC
3
+ """Portable minimum outcome categories (OP-OUTCOME-001)."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from enum import StrEnum
8
+
9
+ from governed_objects.domain.models import Decision
10
+ from governed_objects.policy.reasons import ConflictReason, DenyReason
11
+
12
+
13
+ class OutcomeCategory(StrEnum):
14
+ ACCEPTED = "ACCEPTED"
15
+ AUTHORIZATION_DENIED = "AUTHORIZATION_DENIED"
16
+ SEMANTICALLY_INVALID = "SEMANTICALLY_INVALID"
17
+ CONFLICT = "CONFLICT"
18
+
19
+
20
+ # EXPERIMENTAL. A runtime capacity
21
+ # refusal: the command may be valid, authorized and current, but no unused
22
+ # Object Version remains. Deliberately outside the four portable categories.
23
+ REFUSED = "REFUSED"
24
+
25
+
26
+ AUTH_DENY_REASONS = frozenset(
27
+ {
28
+ DenyReason.READ_NOT_AUTHORIZED,
29
+ DenyReason.ACTOR_CAPABILITY_MISSING,
30
+ DenyReason.APPLICATION_CAPABILITY_MISSING,
31
+ DenyReason.MANDATE_CAPABILITY_MISSING,
32
+ DenyReason.MANDATE_SCOPE_MISMATCH,
33
+ DenyReason.MANDATE_EXPIRED,
34
+ DenyReason.MANDATE_REVOKED,
35
+ DenyReason.MANDATE_NOT_YET_VALID,
36
+ DenyReason.MANDATE_DELEGATE_MISMATCH,
37
+ DenyReason.MANDATE_UNKNOWN,
38
+ DenyReason.MANDATE_INVALID,
39
+ DenyReason.PURPOSE_MISMATCH,
40
+ DenyReason.PARENT_MANDATE_REVOKED,
41
+ DenyReason.PARENT_MANDATE_EXPIRED,
42
+ DenyReason.DELEGATION_CYCLE,
43
+ DenyReason.DELEGATION_DEPTH_EXCEEDED,
44
+ DenyReason.APPLICATION_UNKNOWN,
45
+ DenyReason.CONSTRAINT_VIOLATION,
46
+ }
47
+ )
48
+
49
+ SEMANTIC_DENY_REASONS = frozenset(
50
+ {
51
+ DenyReason.LIFECYCLE_INVALID,
52
+ DenyReason.OBJECT_POLICY_DENIED,
53
+ DenyReason.NOT_FOUND,
54
+ DenyReason.SCHEMA_INVALID,
55
+ DenyReason.RELATIONSHIP_INVALID,
56
+ DenyReason.TYPE_VERSION_UNSUPPORTED,
57
+ DenyReason.IDENTITY_EXISTS,
58
+ DenyReason.STATE_INVALID,
59
+ }
60
+ )
61
+
62
+ # Non-accepted outcomes whose condition none of the four minimum classes
63
+ # describes; reported as REFUSED, never as SEMANTICALLY_INVALID.
64
+ REFUSAL_DENY_REASONS = frozenset(
65
+ {
66
+ DenyReason.OBJECT_VERSION_SPACE_EXHAUSTED,
67
+ DenyReason.ADAPTER_RESULT_INVALID,
68
+ DenyReason.PROVIDER_FAILED,
69
+ }
70
+ )
71
+
72
+
73
+ def classify_outcome(
74
+ decision: Decision,
75
+ *,
76
+ deny_reason: str | DenyReason | None = None,
77
+ conflict_reason: str | ConflictReason | None = None,
78
+ has_validation_checks: bool = False,
79
+ ) -> OutcomeCategory:
80
+ if decision == Decision.ALLOW:
81
+ return OutcomeCategory.ACCEPTED
82
+ if decision == Decision.CONFLICT:
83
+ return OutcomeCategory.CONFLICT
84
+ reason = DenyReason(deny_reason) if isinstance(deny_reason, str) and deny_reason else deny_reason
85
+ if reason in AUTH_DENY_REASONS:
86
+ return OutcomeCategory.AUTHORIZATION_DENIED
87
+ if reason in SEMANTIC_DENY_REASONS:
88
+ return OutcomeCategory.SEMANTICALLY_INVALID
89
+ if has_validation_checks:
90
+ return OutcomeCategory.SEMANTICALLY_INVALID
91
+ if decision == Decision.DENY:
92
+ return OutcomeCategory.SEMANTICALLY_INVALID
93
+ return OutcomeCategory.SEMANTICALLY_INVALID
@@ -0,0 +1,43 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Brafford Labs, LLC
3
+ """Structured authorization and command outcome reasons."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from enum import StrEnum
8
+
9
+
10
+ class DenyReason(StrEnum):
11
+ READ_NOT_AUTHORIZED = "READ_NOT_AUTHORIZED"
12
+ ACTOR_CAPABILITY_MISSING = "ACTOR_CAPABILITY_MISSING"
13
+ APPLICATION_CAPABILITY_MISSING = "APPLICATION_CAPABILITY_MISSING"
14
+ APPLICATION_UNKNOWN = "APPLICATION_UNKNOWN"
15
+ MANDATE_CAPABILITY_MISSING = "MANDATE_CAPABILITY_MISSING"
16
+ MANDATE_SCOPE_MISMATCH = "MANDATE_SCOPE_MISMATCH"
17
+ MANDATE_EXPIRED = "MANDATE_EXPIRED"
18
+ MANDATE_REVOKED = "MANDATE_REVOKED"
19
+ MANDATE_NOT_YET_VALID = "MANDATE_NOT_YET_VALID"
20
+ MANDATE_DELEGATE_MISMATCH = "MANDATE_DELEGATE_MISMATCH"
21
+ MANDATE_UNKNOWN = "MANDATE_UNKNOWN"
22
+ MANDATE_INVALID = "MANDATE_INVALID"
23
+ PURPOSE_MISMATCH = "PURPOSE_MISMATCH"
24
+ PARENT_MANDATE_REVOKED = "PARENT_MANDATE_REVOKED"
25
+ PARENT_MANDATE_EXPIRED = "PARENT_MANDATE_EXPIRED"
26
+ DELEGATION_CYCLE = "DELEGATION_CYCLE"
27
+ DELEGATION_DEPTH_EXCEEDED = "DELEGATION_DEPTH_EXCEEDED"
28
+ OBJECT_POLICY_DENIED = "OBJECT_POLICY_DENIED"
29
+ LIFECYCLE_INVALID = "LIFECYCLE_INVALID"
30
+ NOT_FOUND = "NOT_FOUND"
31
+ CONSTRAINT_VIOLATION = "CONSTRAINT_VIOLATION"
32
+ SCHEMA_INVALID = "SCHEMA_INVALID"
33
+ RELATIONSHIP_INVALID = "RELATIONSHIP_INVALID"
34
+ TYPE_VERSION_UNSUPPORTED = "TYPE_VERSION_UNSUPPORTED"
35
+ OBJECT_VERSION_SPACE_EXHAUSTED = "OBJECT_VERSION_SPACE_EXHAUSTED"
36
+ IDENTITY_EXISTS = "IDENTITY_EXISTS"
37
+ ADAPTER_RESULT_INVALID = "ADAPTER_RESULT_INVALID"
38
+ STATE_INVALID = "STATE_INVALID"
39
+ PROVIDER_FAILED = "PROVIDER_FAILED"
40
+
41
+
42
+ class ConflictReason(StrEnum):
43
+ VERSION_MISMATCH = "VERSION_MISMATCH"
@@ -0,0 +1,26 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Brafford Labs, LLC
3
+ """Generic external object provider protocol."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from typing import Any, Protocol
8
+
9
+
10
+ class ObjectProvider(Protocol):
11
+ """Provider-native operations — domain mappers live in adapters."""
12
+
13
+ @property
14
+ def name(self) -> str: ...
15
+
16
+ def fetch(self, external_id: str) -> dict[str, Any]: ...
17
+
18
+ def apply_action(
19
+ self,
20
+ external_id: str,
21
+ action: str,
22
+ *,
23
+ idempotency_key: str | None = None,
24
+ ) -> dict[str, Any]: ...
25
+
26
+ def create(self, external_id: str, record: dict[str, Any]) -> dict[str, Any]: ...
@@ -0,0 +1,42 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Brafford Labs, LLC
3
+ """Generic provider binding — links canonical identity to external implementation."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from pydantic import BaseModel, Field
8
+
9
+
10
+ class ProviderBinding(BaseModel):
11
+ """Reusable binding between a Governed Object and an implementation provider."""
12
+
13
+ provider_type: str = "generic"
14
+ provider_name: str = "local"
15
+ external_id: str | None = None
16
+ metadata: dict = Field(default_factory=dict)
17
+
18
+ @property
19
+ def is_local(self) -> bool:
20
+ return self.provider_name == "local"
21
+
22
+ @classmethod
23
+ def from_metadata(cls, metadata: dict) -> ProviderBinding | None:
24
+ raw = metadata.get("provider_binding")
25
+ if not raw:
26
+ return None
27
+ normalized = dict(raw)
28
+ # Legacy provider fields
29
+ if "provider" in normalized and "provider_name" not in normalized:
30
+ normalized["provider_name"] = normalized.pop("provider")
31
+ if "provider_id" in normalized and "external_id" not in normalized:
32
+ normalized["external_id"] = normalized.pop("provider_id")
33
+ if "provider_type" not in normalized:
34
+ normalized["provider_type"] = "generic"
35
+ return cls(**normalized)
36
+
37
+ def to_metadata(self) -> dict:
38
+ return {"provider_binding": self.model_dump(exclude_none=True)}
39
+
40
+ @classmethod
41
+ def local_binding(cls) -> ProviderBinding:
42
+ return cls(provider_type="local", provider_name="local")
@@ -0,0 +1,27 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Brafford Labs, LLC
3
+ """Provider write/projection capability metadata."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from dataclasses import dataclass, field
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class ProviderCapabilities:
12
+ """Which canonical dimensions a provider can observe/write."""
13
+
14
+ provider_name: str
15
+ writable_fields: frozenset[str] = field(default_factory=frozenset)
16
+ representable_fields: frozenset[str] = field(default_factory=frozenset)
17
+ supports_conditional_write: bool = False
18
+ supports_webhooks: bool = False
19
+ supports_bootstrap: bool = False
20
+ supports_create_from_canonical: bool = False
21
+
22
+ def projection_gaps(self, canonical_fields: frozenset[str]) -> frozenset[str]:
23
+ return canonical_fields - self.representable_fields
24
+
25
+ def can_write(self, field_name: str) -> bool:
26
+ return field_name in self.writable_fields
27
+
@@ -0,0 +1,48 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Brafford Labs, LLC
3
+ """Structured provider failure types."""
4
+
5
+ from __future__ import annotations
6
+
7
+
8
+ class ProviderError(Exception):
9
+ """Base class for provider-layer failures."""
10
+
11
+ code: str = "PROVIDER_ERROR"
12
+
13
+ def __init__(
14
+ self,
15
+ message: str,
16
+ *,
17
+ code: str | None = None,
18
+ details: dict | None = None,
19
+ ) -> None:
20
+ super().__init__(message)
21
+ self.message = message
22
+ if code is not None:
23
+ self.code = code
24
+ self.details = details or {}
25
+
26
+
27
+ class ProviderObjectNotFound(ProviderError):
28
+ code = "PROVIDER_NOT_FOUND"
29
+
30
+
31
+ class ProviderUnavailable(ProviderError):
32
+ code = "PROVIDER_UNAVAILABLE"
33
+
34
+
35
+ class ProviderConflict(ProviderError):
36
+ code = "PROVIDER_CONFLICT"
37
+
38
+
39
+ class ProviderInvalidResponse(ProviderError):
40
+ code = "PROVIDER_INVALID_RESPONSE"
41
+
42
+
43
+ class ProviderOutcomeUnknown(ProviderError):
44
+ code = "PROVIDER_OUTCOME_UNKNOWN"
45
+
46
+
47
+ class ProviderProjectionUnsupported(ProviderError):
48
+ code = "UNSUPPORTED_PROVIDER"
@@ -0,0 +1,25 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Brafford Labs, LLC
3
+ """Supplied, exact-bound provider interpretation. Technical ability is not authority."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from dataclasses import dataclass
8
+ from typing import Any, Callable
9
+
10
+ from governed_objects.providers.capabilities import ProviderCapabilities
11
+ from governed_objects.providers.errors import ProviderProjectionUnsupported
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class ProviderProjection:
16
+ normalize: Callable[[dict[str, Any]], tuple[dict[str, Any], str]]
17
+ provider_version: Callable[[dict[str, Any]], str | None]
18
+ capabilities: ProviderCapabilities | None = None
19
+ provider_type: str = "generic"
20
+
21
+ def version(self, record: dict[str, Any]) -> str:
22
+ token = self.provider_version(record)
23
+ if not isinstance(token, str) or not token:
24
+ raise ProviderProjectionUnsupported("PROVIDER_PRECONDITION_UNAVAILABLE")
25
+ return token
@@ -0,0 +1,59 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Brafford Labs, LLC
3
+ """Provider registry — maps provider names to implementations."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from governed_objects.providers.base import ObjectProvider
8
+ from governed_objects.providers.errors import ProviderProjectionUnsupported
9
+ from governed_objects.providers.projection import ProviderProjection
10
+ from uuid import uuid4
11
+
12
+
13
+ class ProviderRegistry:
14
+ """Maps provider names to external/local implementations."""
15
+
16
+ def __init__(self) -> None:
17
+ self._providers: dict[str, ObjectProvider] = {}
18
+ self._projections: dict[tuple[str, str, str], tuple[ProviderProjection, str]] = {}
19
+
20
+ def register(self, provider: ObjectProvider) -> None:
21
+ if provider.name in self._providers and self._providers[provider.name] is not provider:
22
+ self._projections = {key: value for key, value in self._projections.items()
23
+ if key[0] != provider.name}
24
+ self._providers[provider.name] = provider
25
+
26
+ def register_projection(
27
+ self, provider_name: str, type_identity: str, type_version: str,
28
+ projection: ProviderProjection,
29
+ ) -> None:
30
+ self.get(provider_name)
31
+ if not callable(projection.normalize) or not callable(projection.provider_version):
32
+ raise ValueError("projection requires explicit normalization and provider precondition extraction")
33
+ if not all(isinstance(value, str) and value for value in
34
+ (provider_name, type_identity, type_version)):
35
+ raise ValueError("projection requires exact provider, type identity and type version")
36
+ if projection.capabilities is not None and projection.capabilities.provider_name != provider_name:
37
+ raise ValueError("projection capability provider name mismatch")
38
+ key = (provider_name, type_identity, type_version)
39
+ if key in self._projections:
40
+ if self._projections[key][0] != projection:
41
+ raise ValueError("conflicting provider projection registration")
42
+ return
43
+ self._projections[key] = (projection, str(uuid4()))
44
+
45
+ def remove_projection(self, provider_name: str, type_identity: str, type_version: str) -> None:
46
+ self._projections.pop((provider_name, type_identity, type_version), None)
47
+
48
+ def resolve_projection(
49
+ self, provider_name: str, type_identity: str, type_version: str,
50
+ ) -> tuple[ProviderProjection, str]:
51
+ try:
52
+ return self._projections[(provider_name, type_identity, type_version)]
53
+ except KeyError as exc:
54
+ raise ProviderProjectionUnsupported("PROVIDER_PROJECTION_NOT_CONFIGURED") from exc
55
+
56
+ def get(self, name: str) -> ObjectProvider:
57
+ if name not in self._providers:
58
+ raise KeyError(f"unknown provider: {name}")
59
+ return self._providers[name]