governed-objects 0.2.1__tar.gz → 0.3.1__tar.gz

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 (93) hide show
  1. {governed_objects-0.2.1 → governed_objects-0.3.1}/PKG-INFO +13 -6
  2. {governed_objects-0.2.1 → governed_objects-0.3.1}/README.md +11 -5
  3. {governed_objects-0.2.1 → governed_objects-0.3.1}/pyproject.toml +2 -1
  4. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/delegation/resolver.py +18 -2
  5. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/delegation/scope.py +14 -0
  6. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/delegation/service.py +3 -7
  7. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/delegation/validator.py +13 -11
  8. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/domain/command.py +5 -0
  9. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/events/replay.py +29 -28
  10. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/idempotency/store.py +66 -23
  11. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/interchange/importer.py +41 -0
  12. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/interchange/types.py +10 -1
  13. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/observations/validation.py +4 -4
  14. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/policy/evaluator.py +39 -5
  15. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/policy/outcomes.py +1 -0
  16. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/policy/reasons.py +1 -0
  17. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/registration/service.py +2 -0
  18. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/runtime/runtime.py +328 -63
  19. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/types/registry.py +40 -6
  20. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/types/schema.py +51 -1
  21. {governed_objects-0.2.1 → governed_objects-0.3.1}/.gitignore +0 -0
  22. {governed_objects-0.2.1 → governed_objects-0.3.1}/CONTRIBUTING.md +0 -0
  23. {governed_objects-0.2.1 → governed_objects-0.3.1}/GOVERNANCE.md +0 -0
  24. {governed_objects-0.2.1 → governed_objects-0.3.1}/LICENSE +0 -0
  25. {governed_objects-0.2.1 → governed_objects-0.3.1}/LICENSING.md +0 -0
  26. {governed_objects-0.2.1 → governed_objects-0.3.1}/NOTICE +0 -0
  27. {governed_objects-0.2.1 → governed_objects-0.3.1}/PRINCIPLES.md +0 -0
  28. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/__init__.py +0 -0
  29. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/_version.py +0 -0
  30. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/adapters/base.py +0 -0
  31. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/adapters/context.py +0 -0
  32. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/adapters/mandate.py +0 -0
  33. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/adapters/registry.py +0 -0
  34. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/agent/session.py +0 -0
  35. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/applications/registry.py +0 -0
  36. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/authority/rules.py +0 -0
  37. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/delegation/configuration.py +0 -0
  38. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/delegation/mandate.py +0 -0
  39. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/delegation/materializer.py +0 -0
  40. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/delegation/projection.py +0 -0
  41. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/domain/__init__.py +0 -0
  42. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/domain/actor_manifest.py +0 -0
  43. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/domain/actors.py +0 -0
  44. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/domain/clock.py +0 -0
  45. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/domain/command_context.py +0 -0
  46. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/domain/models.py +0 -0
  47. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/domain/traversal.py +0 -0
  48. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/events/lineage.py +0 -0
  49. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/events/reducers/__init__.py +0 -0
  50. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/events/reducers/mandate.py +0 -0
  51. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/interchange/__init__.py +0 -0
  52. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/interchange/artifact.py +0 -0
  53. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/interchange/export.py +0 -0
  54. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/interchange/governance.py +0 -0
  55. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/interchange/prc.py +0 -0
  56. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/llm/__init__.py +0 -0
  57. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/llm/loop.py +0 -0
  58. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/llm/model.py +0 -0
  59. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/llm/tools/registry.py +0 -0
  60. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/llm/tools/results.py +0 -0
  61. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/llm/tools/schemas.py +0 -0
  62. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/llm/tools/surface.py +0 -0
  63. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/llm/trace.py +0 -0
  64. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/materialization/service.py +0 -0
  65. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/observations/__init__.py +0 -0
  66. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/observations/ingestion.py +0 -0
  67. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/observations/mapping.py +0 -0
  68. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/observations/models.py +0 -0
  69. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/observations/store.py +0 -0
  70. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/outbound/__init__.py +0 -0
  71. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/outbound/models.py +0 -0
  72. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/outbound/service.py +0 -0
  73. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/outbound/store.py +0 -0
  74. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/persistence/sqlite.py +0 -0
  75. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/policy/constraints.py +0 -0
  76. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/policy/context.py +0 -0
  77. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/providers/base.py +0 -0
  78. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/providers/binding.py +0 -0
  79. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/providers/capabilities.py +0 -0
  80. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/providers/errors.py +0 -0
  81. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/providers/projection.py +0 -0
  82. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/providers/registry.py +0 -0
  83. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/query/service.py +0 -0
  84. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/query/traversal.py +0 -0
  85. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/reconciliation/service.py +0 -0
  86. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/registration/detach.py +0 -0
  87. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/relationships/canonical.py +0 -0
  88. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/relationships/sync.py +0 -0
  89. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/relationships/vocabulary.py +0 -0
  90. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/types/canonicalizers/base.py +0 -0
  91. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/types/extensions.py +0 -0
  92. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/types/lifecycle.py +0 -0
  93. {governed_objects-0.2.1 → governed_objects-0.3.1}/src/governed_objects/types/validation.py +0 -0
@@ -1,7 +1,8 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: governed-objects
3
- Version: 0.2.1
3
+ Version: 0.3.1
4
4
  Summary: Governed Objects runtime — a reusable primitive for policy-aware organizational assets
5
+ Project-URL: Homepage, https://governedobjects.com/
5
6
  Project-URL: Source, https://github.com/governedobjects/governed-objects-python
6
7
  Project-URL: Issues, https://github.com/governedobjects/governed-objects-python/issues
7
8
  Project-URL: Specification, https://github.com/governedobjects/governed-objects-spec
@@ -34,16 +35,16 @@ for the normative rules this runtime implements and tests against.
34
35
 
35
36
  ## Status
36
37
 
37
- Experimental, version 0.2.1, `0.x`. This is not a production product,
38
+ Experimental, version 0.3.1, `0.x`. This is not a production product,
38
39
  conformance certification, or interoperability approval. It targets
39
40
  specification revision `draft2.2` and self-reports 76/0/2/0 (pass/not
40
- applicable/not executable/fail) against Core conformance suite 0.1.0 for that revision;
41
+ applicable/not executable/fail) against Core conformance suite 0.2.1 for that revision;
41
42
  see the conformance adapter below to reproduce that result yourself. The
42
43
  suite's own claim text for that run:
43
44
 
44
- > governed-objects-python 0.2.1 passes the Governed Objects Conformance Suite
45
- > 0.1.0 for v0alpha1 draft2.2 Core (self-attested; not certified). Not
46
- > executed by suite 0.1.0: D22-CON-001, D22-CS4-003. Conditional capabilities
45
+ > governed-objects-python 0.3.1 passes the Governed Objects Conformance Suite
46
+ > 0.2.1 for v0alpha1 draft2.2 Core (self-attested; not certified). Not
47
+ > executed by suite 0.2.1: D22-CON-001, D22-CS4-003. Conditional capabilities
47
48
  > claimed: create_with_relationships, governance_reconfiguration,
48
49
  > mutable_objects, relationship_add, relationship_remove, replay, restart,
49
50
  > restoration, semantic_portability_view, type_version_exposed,
@@ -166,6 +167,12 @@ WSL. The adapters are `bash` scripts.
166
167
  - `governed_objects.interchange` (artifact export/import, PRC) is a
167
168
  provisional, representation-limited, non-normative experiment, not an
168
169
  official wire standard.
170
+ - Revoking a delegated mandate, or narrowing it, is governed by capability
171
+ and is not restricted to the mandate's principal: any actor holding the
172
+ required capability can do it.
173
+ - The built-in `CapabilityPolicyEvaluator` applies the constraints of every
174
+ principal in a delegation chain. A custom policy evaluator must enforce
175
+ principals' constraints itself.
169
176
  - The SQLite store serializes operations on one store instance with a
170
177
  per-instance connection guard, and `create`/`add_relationship`/
171
178
  `remove_relationship`/transition commands re-check the expected Object
@@ -10,16 +10,16 @@ for the normative rules this runtime implements and tests against.
10
10
 
11
11
  ## Status
12
12
 
13
- Experimental, version 0.2.1, `0.x`. This is not a production product,
13
+ Experimental, version 0.3.1, `0.x`. This is not a production product,
14
14
  conformance certification, or interoperability approval. It targets
15
15
  specification revision `draft2.2` and self-reports 76/0/2/0 (pass/not
16
- applicable/not executable/fail) against Core conformance suite 0.1.0 for that revision;
16
+ applicable/not executable/fail) against Core conformance suite 0.2.1 for that revision;
17
17
  see the conformance adapter below to reproduce that result yourself. The
18
18
  suite's own claim text for that run:
19
19
 
20
- > governed-objects-python 0.2.1 passes the Governed Objects Conformance Suite
21
- > 0.1.0 for v0alpha1 draft2.2 Core (self-attested; not certified). Not
22
- > executed by suite 0.1.0: D22-CON-001, D22-CS4-003. Conditional capabilities
20
+ > governed-objects-python 0.3.1 passes the Governed Objects Conformance Suite
21
+ > 0.2.1 for v0alpha1 draft2.2 Core (self-attested; not certified). Not
22
+ > executed by suite 0.2.1: D22-CON-001, D22-CS4-003. Conditional capabilities
23
23
  > claimed: create_with_relationships, governance_reconfiguration,
24
24
  > mutable_objects, relationship_add, relationship_remove, replay, restart,
25
25
  > restoration, semantic_portability_view, type_version_exposed,
@@ -142,6 +142,12 @@ WSL. The adapters are `bash` scripts.
142
142
  - `governed_objects.interchange` (artifact export/import, PRC) is a
143
143
  provisional, representation-limited, non-normative experiment, not an
144
144
  official wire standard.
145
+ - Revoking a delegated mandate, or narrowing it, is governed by capability
146
+ and is not restricted to the mandate's principal: any actor holding the
147
+ required capability can do it.
148
+ - The built-in `CapabilityPolicyEvaluator` applies the constraints of every
149
+ principal in a delegation chain. A custom policy evaluator must enforce
150
+ principals' constraints itself.
145
151
  - The SQLite store serializes operations on one store instance with a
146
152
  per-instance connection guard, and `create`/`add_relationship`/
147
153
  `remove_relationship`/transition commands re-check the expected Object
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "governed-objects"
3
- version = "0.2.1"
3
+ version = "0.3.1"
4
4
  description = "Governed Objects runtime — a reusable primitive for policy-aware organizational assets"
5
5
  readme = "README.md"
6
6
  license = "Apache-2.0"
@@ -20,6 +20,7 @@ dependencies = [
20
20
  ]
21
21
 
22
22
  [project.urls]
23
+ Homepage = "https://governedobjects.com/"
23
24
  Source = "https://github.com/governedobjects/governed-objects-python"
24
25
  Issues = "https://github.com/governedobjects/governed-objects-python/issues"
25
26
  Specification = "https://github.com/governedobjects/governed-objects-spec"
@@ -11,7 +11,7 @@ from governed_objects.delegation.mandate import DelegatedMandate, MandateStatus
11
11
  from governed_objects.delegation.materializer import materialize_mandate
12
12
  from governed_objects.delegation.scope import EffectiveScope, MandateScope
13
13
  from governed_objects.domain.clock import Clock, SystemClock
14
- from governed_objects.domain.models import GovernedObject
14
+ from governed_objects.domain.models import Actor, GovernedObject
15
15
  from governed_objects.persistence.sqlite import SQLiteStore
16
16
  from governed_objects.policy.reasons import DenyReason
17
17
 
@@ -34,6 +34,9 @@ class ResolvedMandateAuthority:
34
34
  parent_mandate_ids: tuple[str, ...]
35
35
  ancestor_ineffective_reason: DenyReason | None = None
36
36
  purpose_restricted: bool = False
37
+ # The current local record of every principal in the chain, this mandate's
38
+ # first. Their constraints bound every use of the mandate.
39
+ principals: tuple[Actor, ...] = ()
37
40
 
38
41
  def is_effective_at(self, when: datetime) -> tuple[bool, DenyReason | None]:
39
42
  if self.ancestor_ineffective_reason is not None:
@@ -72,11 +75,13 @@ class MandateResolver:
72
75
  clock: Clock | None = None,
73
76
  validate_binding=None,
74
77
  scope_decoder=None,
78
+ principal_source=None,
75
79
  ) -> None:
76
80
  self._store = store
77
81
  self._clock = clock or SystemClock()
78
82
  self._validate_binding = validate_binding
79
83
  self._scope_decoder = scope_decoder
84
+ self._principal_source = principal_source
80
85
 
81
86
  def get_object(self, mandate_id: str) -> GovernedObject | None:
82
87
  if self._validate_binding is None:
@@ -118,7 +123,11 @@ class MandateResolver:
118
123
  ancestor_reason = DenyReason.MANDATE_UNKNOWN
119
124
  break
120
125
  parent = materialize_mandate(parent_obj, self._store, scope_decoder=self._scope_decoder)
126
+ child = bounds[-1]
121
127
  bounds.append(parent)
128
+ if parent.delegate_actor_id != child.principal_id:
129
+ ancestor_reason = DenyReason.MANDATE_INVALID
130
+ break
122
131
  if parent.status == MandateStatus.REVOKED or parent_obj.state == "revoked":
123
132
  ancestor_reason = DenyReason.PARENT_MANDATE_REVOKED
124
133
  break
@@ -135,7 +144,14 @@ class MandateResolver:
135
144
  current_parent = parent.parent_mandate_id
136
145
  depth += 1
137
146
 
147
+ # No broader than any mandate in the chain, nor than what each of their
148
+ # principals holds now (DEL-NARROW-001).
149
+ if self._principal_source is None:
150
+ raise ValueError('delegation configuration unavailable')
151
+ principals = tuple(self._principal_source(bound.principal_id) for bound in bounds)
138
152
  effective_caps = mandate.capabilities
153
+ for bound, principal in zip(bounds, principals):
154
+ effective_caps &= bound.capabilities & frozenset(principal.capabilities)
139
155
  effective_scope = EffectiveScope(tuple(bound.scope for bound in bounds))
140
156
  purpose_bounds = [bound.purposes for bound in bounds if bound.purposes]
141
157
  effective_purposes = frozenset.intersection(*purpose_bounds) if purpose_bounds else frozenset()
@@ -143,7 +159,6 @@ class MandateResolver:
143
159
  effective_until = mandate.valid_until
144
160
 
145
161
  for parent in bounds[1:]:
146
- effective_caps = effective_caps & parent.capabilities
147
162
  effective_from = _max_dt(effective_from, parent.valid_from)
148
163
  effective_until = _min_dt(effective_until, parent.valid_until)
149
164
 
@@ -161,6 +176,7 @@ class MandateResolver:
161
176
  parent_mandate_ids=tuple(parent_ids),
162
177
  ancestor_ineffective_reason=ancestor_reason,
163
178
  purpose_restricted=bool(purpose_bounds),
179
+ principals=principals,
164
180
  )
165
181
 
166
182
 
@@ -53,6 +53,20 @@ class EffectiveScope:
53
53
  return all(bound.is_empty() for bound in self.bounds)
54
54
 
55
55
 
56
+ def declares_no_more_than(new: MandateScope, old: MandateScope) -> bool:
57
+ """Whether ``new`` only drops from, or first bounds, the declaration ``old``.
58
+
59
+ Compares declarations, not the objects they match now: membership by type or
60
+ relationship changes over time.
61
+ """
62
+ if old.is_empty():
63
+ return True
64
+ if new.is_empty():
65
+ return False
66
+ return (new.object_ids <= old.object_ids and new.object_types <= old.object_types
67
+ and set(new.relationship_constraints) <= set(old.relationship_constraints))
68
+
69
+
56
70
  def scope_allows(
57
71
  scope: MandateScope | EffectiveScope,
58
72
  obj: GovernedObject,
@@ -196,16 +196,12 @@ class MandateService:
196
196
  self,
197
197
  mandate_id: str,
198
198
  *,
199
- actor: Actor | None = None,
199
+ actor: Actor,
200
200
  expected_version: int | None = None,
201
201
  ) -> DelegatedMandate | None:
202
- mandate = self.get(mandate_id)
203
- if mandate is None:
202
+ """Revoke as the calling actor; no identity is ever assumed."""
203
+ if not isinstance(actor, Actor) or self.get(mandate_id) is None:
204
204
  return None
205
- if actor is None:
206
- if self._actors is None:
207
- return None
208
- actor = self._actors.resolve(mandate.principal_id)
209
205
  obj = self._resolver.get_object(mandate_id)
210
206
  if obj is None:
211
207
  return None
@@ -22,6 +22,7 @@ class DelegationViolation(StrEnum):
22
22
  DELEGATION_CYCLE = "DELEGATION_CYCLE"
23
23
  DELEGATION_DEPTH_EXCEEDED = "DELEGATION_DEPTH_EXCEEDED"
24
24
  PRINCIPAL_CAPABILITY_MISSING = "PRINCIPAL_CAPABILITY_MISSING"
25
+ PRINCIPAL_NOT_PARENT_DELEGATE = "PRINCIPAL_NOT_PARENT_DELEGATE"
25
26
 
26
27
 
27
28
  @dataclass
@@ -86,6 +87,8 @@ class DelegationValidator:
86
87
  if not spec.capabilities.issubset(ceiling.capabilities):
87
88
  violations.append(DelegationViolation.PRINCIPAL_CAPABILITY_MISSING)
88
89
  else:
90
+ if principal.id != parent_mandate.delegate_actor_id:
91
+ violations.append(DelegationViolation.PRINCIPAL_NOT_PARENT_DELEGATE)
89
92
  ceiling = DelegationAuthority(
90
93
  capabilities=parent_mandate.capabilities,
91
94
  scope=parent_mandate.scope,
@@ -100,14 +103,12 @@ class DelegationValidator:
100
103
  if not spec.capabilities.issubset(ceiling.capabilities):
101
104
  violations.append(DelegationViolation.CAPABILITY_EXPANSION)
102
105
 
103
- if not _scope_subset(spec.scope, ceiling.scope, self._store):
106
+ if not scope_within(spec.scope, ceiling.scope, self._store):
104
107
  violations.append(DelegationViolation.SCOPE_EXPANSION)
105
108
 
106
- if ceiling.purposes:
107
- if spec.purposes and not spec.purposes.issubset(ceiling.purposes):
108
- violations.append(DelegationViolation.PURPOSE_EXPANSION)
109
- elif spec.purposes and parent_mandate is not None:
110
- pass
109
+ # Naming no purpose would be broader than any named set.
110
+ if ceiling.purposes and (not spec.purposes or not spec.purposes.issubset(ceiling.purposes)):
111
+ violations.append(DelegationViolation.PURPOSE_EXPANSION)
111
112
 
112
113
  if not _time_subset(
113
114
  spec.valid_from,
@@ -126,20 +127,21 @@ def _time_subset(
126
127
  parent_from: datetime | None,
127
128
  parent_until: datetime | None,
128
129
  ) -> bool:
129
- if parent_from is not None and child_from is not None and child_from < parent_from:
130
+ if parent_from is not None and (child_from is None or child_from < parent_from):
130
131
  return False
131
- if parent_until is not None and child_until is not None and child_until > parent_until:
132
+ if parent_until is not None and (child_until is None or child_until > parent_until):
132
133
  return False
133
134
  return True
134
135
 
135
136
 
136
- def _scope_subset(child: MandateScope, parent: MandateScope, store: SQLiteStore) -> bool:
137
+ def scope_within(child: MandateScope, parent: MandateScope | EffectiveScope, store: SQLiteStore) -> bool:
138
+ """Whether the declared scope ``child`` is no broader than ``parent``."""
137
139
  if isinstance(parent, EffectiveScope):
138
- return all(_scope_subset(child, bound, store) for bound in parent.bounds)
140
+ return all(scope_within(child, bound, store) for bound in parent.bounds)
139
141
  if parent.is_empty():
140
142
  return True
141
143
  if child.is_empty():
142
- return True
144
+ return False
143
145
 
144
146
  for oid in child.object_ids:
145
147
  obj = store.get(oid)
@@ -4,6 +4,7 @@
4
4
 
5
5
  from __future__ import annotations
6
6
 
7
+ from collections.abc import Iterable, Mapping
7
8
  from dataclasses import dataclass, field
8
9
  from pathlib import Path
9
10
  from typing import Any
@@ -29,6 +30,10 @@ class CreateObject(Command):
29
30
  metadata: dict[str, Any] | None = None,
30
31
  relationships: list[dict[str, str]] | None = None,
31
32
  ) -> None:
33
+ # A single-pass iterable is read once, here, so that every later reader
34
+ # of the command sees the same relationships.
35
+ if isinstance(relationships, Iterable) and not isinstance(relationships, (str, bytes, Mapping, list)):
36
+ relationships = list(relationships)
32
37
  object.__setattr__(self, "action", "create")
33
38
  object.__setattr__(self, "object_id", object_id)
34
39
  object.__setattr__(self, "object_type", object_type)
@@ -73,18 +73,17 @@ class EventReplayer:
73
73
  return None
74
74
 
75
75
  events = self._admitted_events(stored, allow_legacy)
76
- if not events:
77
- return stored
78
-
76
+ # Without a reducer nothing can be rebuilt from history, and returning
77
+ # the stored snapshot would present it as reconstructed.
79
78
  reducer = self._extensions.reducer_for(stored.type)
80
- type_version = stored.type_version
81
-
82
79
  if reducer is None:
83
- return stored.model_copy(update={"type_version": type_version})
80
+ raise ReplayRefused()
81
+ type_version = stored.type_version
84
82
 
83
+ # The first accepted event must establish state (EVT-BASELINE-001).
85
84
  state = reducer.reduce(None, events[0])
86
85
  if state is None:
87
- return stored.model_copy(update={"type_version": type_version})
86
+ raise ReplayRefused()
88
87
  self._check_result(stored, state)
89
88
 
90
89
  version = events[0].object_version
@@ -102,8 +101,10 @@ class EventReplayer:
102
101
  )
103
102
  version = event.object_version
104
103
  result = reducer.reduce(current_obj, event)
104
+ # An accepted event that yields no state cannot be skipped: the
105
+ # result would carry its version without its effect.
105
106
  if result is None:
106
- continue
107
+ raise ReplayRefused()
107
108
  self._check_result(stored, result)
108
109
  current_state = result.state
109
110
  data = result.data
@@ -137,6 +138,9 @@ class EventReplayer:
137
138
  if not self.check_type_version_supported(stored):
138
139
  raise ReplayRefused()
139
140
  events = self._accepted_events(stored.id, allow_legacy)
141
+ # Without history there is nothing to reconstruct from.
142
+ if not events:
143
+ raise ReplayRefused()
140
144
  # Preflight the whole selection before invoking any reducer or edge fold.
141
145
  for event in events:
142
146
  if (event.object_id, event.object_type, event.type_version) != (
@@ -178,31 +182,28 @@ class EventReplayer:
178
182
  event: GovernanceEvent,
179
183
  rel_index: dict[tuple[str, str], Relationship],
180
184
  ) -> None:
185
+ # Relationship history is replayed as recorded: a repeated addition or
186
+ # an absent removal is refused, never repaired (REL-COMPAT-001).
181
187
  if event.action == "create":
182
- for rel_data in event.details.get("relationships", []):
183
- rel = canonical_relationship(
184
- rel_data.get("source_id", object_id),
185
- rel_data["relation"],
186
- rel_data["target_id"],
187
- target_type=rel_data.get("target_type"),
188
- )
189
- rel_index[(rel.relation, rel.target_id)] = rel
188
+ added = event.details.get("relationships", [])
189
+ elif event.action == "add_relationship":
190
+ added = [event.details]
191
+ else:
192
+ if event.action == "remove_relationship":
193
+ key = (event.details["relation"], event.details["target_id"])
194
+ if rel_index.pop(key, None) is None:
195
+ raise ReplayRefused()
190
196
  return
191
-
192
- if event.action == "add_relationship":
193
- details = event.details
197
+ for rel_data in added:
194
198
  rel = canonical_relationship(
195
- object_id,
196
- details["relation"],
197
- details["target_id"],
198
- target_type=details.get("target_type"),
199
+ rel_data.get("source_id", object_id),
200
+ rel_data["relation"],
201
+ rel_data["target_id"],
202
+ target_type=rel_data.get("target_type"),
199
203
  )
204
+ if (rel.relation, rel.target_id) in rel_index:
205
+ raise ReplayRefused()
200
206
  rel_index[(rel.relation, rel.target_id)] = rel
201
- return
202
-
203
- if event.action == "remove_relationship":
204
- details = event.details
205
- rel_index.pop((details["relation"], details["target_id"]), None)
206
207
 
207
208
  def check_type_version_supported(self, obj: GovernedObject) -> bool:
208
209
  return bound_type_definition(self._types, obj) is not None
@@ -4,14 +4,51 @@
4
4
 
5
5
  from __future__ import annotations
6
6
 
7
+ import hashlib
7
8
  import json
9
+ from dataclasses import dataclass
8
10
  from datetime import UTC, datetime
9
11
  from typing import Any
10
12
 
11
- from governed_objects.domain.models import CommandResult, Decision
13
+ from governed_objects.domain.command import Command
14
+ from governed_objects.domain.command_context import CommandContext
15
+ from governed_objects.domain.models import Actor, CommandResult, Decision
16
+ from governed_objects.observations.validation import is_json_value
12
17
  from governed_objects.persistence.sqlite import SQLiteStore, _connection_locked
13
18
 
14
19
 
20
+ @dataclass(frozen=True)
21
+ class Receipt:
22
+ request_hash: str
23
+ result: CommandResult
24
+
25
+
26
+ def request_fingerprint(command: Command, actor: Actor, context: CommandContext) -> str | None:
27
+ """Canonical hash of everything a receipt is bound to, or None when the
28
+ payload is not JSON-native: encoding would let distinct values, such as the
29
+ keys ``1`` and ``"1"``, share a hash."""
30
+ request = {
31
+ "object_id": command.object_id,
32
+ "actor_id": actor.id,
33
+ "mandate_id": context.mandate_id,
34
+ "application_id": context.application_id,
35
+ "purpose": context.purpose,
36
+ "action": command.action,
37
+ "object_type": command.object_type,
38
+ "payload": command.payload,
39
+ }
40
+ # Only when set, so an unconditional request hashes as it did before.
41
+ if context.expected_version is not None:
42
+ request["expected_version"] = context.expected_version
43
+ try:
44
+ if not is_json_value(command.payload, set()):
45
+ return None
46
+ encoded = json.dumps(request, sort_keys=True, separators=(",", ":"), allow_nan=False)
47
+ except (TypeError, ValueError, RecursionError):
48
+ return None
49
+ return hashlib.sha256(encoded.encode()).hexdigest()
50
+
51
+
15
52
  class IdempotencyStore:
16
53
  """Persists idempotent command results and attempt metadata."""
17
54
 
@@ -39,57 +76,63 @@ class IdempotencyStore:
39
76
  );
40
77
  CREATE INDEX IF NOT EXISTS idx_command_attempts_command
41
78
  ON command_attempts(command_id);
79
+ CREATE TABLE IF NOT EXISTS command_receipts (
80
+ object_id TEXT NOT NULL,
81
+ actor_id TEXT NOT NULL,
82
+ idempotency_key TEXT NOT NULL,
83
+ request_hash TEXT NOT NULL,
84
+ command_id TEXT NOT NULL,
85
+ correlation_id TEXT,
86
+ result_json TEXT NOT NULL,
87
+ created_at TEXT NOT NULL,
88
+ PRIMARY KEY (object_id, actor_id, idempotency_key)
89
+ );
42
90
  """
43
91
  )
44
92
  self._store._conn.commit()
45
93
 
46
94
  @_connection_locked
47
- def get(self, object_id: str, idempotency_key: str) -> CommandResult | None:
95
+ def get(self, object_id: str, actor_id: str, idempotency_key: str) -> Receipt | None:
48
96
  row = self._store._conn.execute(
49
97
  """
50
- SELECT result_json, status FROM command_attempts
51
- WHERE object_id = ? AND idempotency_key = ?
98
+ SELECT request_hash, result_json FROM command_receipts
99
+ WHERE object_id = ? AND actor_id = ? AND idempotency_key = ?
52
100
  """,
53
- (object_id, idempotency_key),
101
+ (object_id, actor_id, idempotency_key),
54
102
  ).fetchone()
55
- if row is None or not row["result_json"]:
56
- return None
57
- if row["status"] != "succeeded":
103
+ if row is None:
58
104
  return None
59
- return _result_from_json(row["result_json"])
105
+ return Receipt(row["request_hash"], _result_from_json(row["result_json"]))
60
106
 
61
107
  @_connection_locked
62
108
  def put(
63
109
  self,
64
110
  object_id: str,
111
+ actor_id: str,
65
112
  idempotency_key: str,
113
+ request_hash: str,
66
114
  result: CommandResult,
67
115
  *,
68
116
  command_id: str | None = None,
69
117
  correlation_id: str | None = None,
70
118
  ) -> None:
71
- now = datetime.now(UTC).isoformat()
119
+ """Record the receipt of an accepted request; an existing one is never replaced."""
72
120
  self._store._conn.execute(
73
121
  """
74
- INSERT INTO command_attempts (
75
- command_id, object_id, idempotency_key, correlation_id,
76
- status, provider_outcome, result_json, created_at, updated_at
77
- ) VALUES (?, ?, ?, ?, 'succeeded', NULL, ?, ?, ?)
78
- ON CONFLICT(object_id, idempotency_key) DO UPDATE SET
79
- command_id=excluded.command_id,
80
- correlation_id=excluded.correlation_id,
81
- status=excluded.status,
82
- result_json=excluded.result_json,
83
- updated_at=excluded.updated_at
122
+ INSERT INTO command_receipts (
123
+ object_id, actor_id, idempotency_key, request_hash,
124
+ command_id, correlation_id, result_json, created_at
125
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
84
126
  """,
85
127
  (
86
- command_id or "",
87
128
  object_id,
129
+ actor_id,
88
130
  idempotency_key,
131
+ request_hash,
132
+ command_id or "",
89
133
  correlation_id,
90
134
  json.dumps(_result_to_json(result)),
91
- now,
92
- now,
135
+ datetime.now(UTC).isoformat(),
93
136
  ),
94
137
  )
95
138
  self._store._commit_if_autonomous()
@@ -308,6 +308,8 @@ class InterchangeImporter:
308
308
  self._check_declarations(bundle)
309
309
  if not bundle.objects:
310
310
  raise ImportRefused(MALFORMED_ARTIFACT, "bundle contains no objects")
311
+ for obj in bundle.objects:
312
+ self._check_names(obj)
311
313
  identities = [o.canonical_identity for o in bundle.objects]
312
314
  for ident in identities:
313
315
  if identities.count(ident) > 1:
@@ -388,6 +390,27 @@ class InterchangeImporter:
388
390
  if bundle.profiles:
389
391
  raise ImportRefused(UNSUPPORTED_SEMANTIC_FEATURE, "profile data is not supported")
390
392
 
393
+ @staticmethod
394
+ def _check_names(obj: ImportObject) -> None:
395
+ """Every identity and relationship the bundle would create is named by
396
+ non-empty strings. The bundle may not have come through the decoder."""
397
+ ident = obj.canonical_identity
398
+ if not isinstance(ident, str) or not ident:
399
+ raise ImportRefused(MALFORMED_ARTIFACT, "canonical identity must be a non-empty string")
400
+ carried = [(r, None) for r in obj.relationships]
401
+ for e in obj.history:
402
+ carried += [(r, e.position) for r in e.baseline_relationships or ()]
403
+ if e.effect in (EFFECT_RELATIONSHIP_ADD, EFFECT_RELATIONSHIP_REMOVE) or e.relationship is not None:
404
+ carried.append((e.relationship, e.position))
405
+ for r, position in carried:
406
+ if not isinstance(r, ImportRelationship) or any(
407
+ not isinstance(value, str) or not value for value in r.key()
408
+ ):
409
+ raise ImportRefused(
410
+ MALFORMED_ARTIFACT, "a relationship requires a non-empty string source, type and target",
411
+ ident, position,
412
+ )
413
+
391
414
  def _portable(self, obj: ImportObject) -> Mapping[str, Any]:
392
415
  ident = obj.canonical_identity
393
416
  try:
@@ -452,6 +475,7 @@ class InterchangeImporter:
452
475
  def _stage(self, obj: ImportObject, notes: list[str]) -> _Staged:
453
476
  ident = obj.canonical_identity
454
477
  portable = self._portable(obj)
478
+ type_def = self._types.get(obj.type_identity)
455
479
  reference = self._check_governance(obj)
456
480
  lc = lifecycle_field(portable)
457
481
  actions = portable.get("actions", {})
@@ -479,6 +503,16 @@ class InterchangeImporter:
479
503
  for e in obj.history:
480
504
  if e.relationship is not None and e.relationship.source != ident:
481
505
  raise ImportRefused(MALFORMED_ARTIFACT, "triple source is not the object", ident, e.position)
506
+ asserted = [(r, position) for _, rels, position in rel_lists for r in rels] + [
507
+ (e.relationship, e.position) for e in obj.history if e.relationship is not None
508
+ ]
509
+ for r, position in asserted:
510
+ if not type_def.allows_relationship_type(r.type):
511
+ raise ImportRefused(
512
+ HISTORY_NOT_VALID_FOR_TYPE,
513
+ f"relationship type {r.type!r} is not declared by {obj.type_identity}@{obj.type_version}",
514
+ ident, position,
515
+ )
482
516
  if any(r.has_evidence for _, rels, _ in rel_lists for r in rels) or any(
483
517
  e.relationship is not None and e.relationship.has_evidence for e in obj.history
484
518
  ):
@@ -530,6 +564,13 @@ class InterchangeImporter:
530
564
  if e.position != 1:
531
565
  raise ImportRefused(HISTORY_INCONSISTENT, "creation entry after position 1", ident, e.position)
532
566
  state = dict(e.post_image or {})
567
+ if lc and state.get(lc) != type_def.default_state():
568
+ raise ImportRefused(
569
+ HISTORY_NOT_VALID_FOR_TYPE,
570
+ f"creation in lifecycle state {state.get(lc)!r}; {obj.type_identity}@{obj.type_version} "
571
+ f"creates in {type_def.default_state()!r}",
572
+ ident, e.position,
573
+ )
533
574
  rels = {r.key() for r in e.baseline_relationships or ()}
534
575
  action = "create"
535
576
  elif e.effect == EFFECT_STATE_CHANGE:
@@ -98,9 +98,18 @@ def build_type_definition(
98
98
  lifecycle = portable["lifecycle"]
99
99
  state_names = list(lifecycle["states"])
100
100
  permitted = {(a, b) for a, b in lifecycle["transitions"]}
101
+ if not state_names:
102
+ raise PortableTypeError("lifecycle declares no states")
103
+ # Absent or empty means the first declared state.
104
+ initial = lifecycle.get("initial")
105
+ if initial is None or initial == "":
106
+ initial = state_names[0]
107
+ elif initial not in state_names:
108
+ raise PortableTypeError(f"initial state {initial!r} is not a declared state")
101
109
  else:
102
110
  state_names = [NO_LIFECYCLE_STATE]
103
111
  permitted = set()
112
+ initial = NO_LIFECYCLE_STATE
104
113
 
105
114
  def _action_def(requirement_key: str) -> ActionDef:
106
115
  """An empty requirement list denies, unless ``requirement_key`` is
@@ -146,7 +155,7 @@ def build_type_definition(
146
155
  actions=native_actions,
147
156
  read_requires=list(requirements["read"]),
148
157
  read_open="read" in open_keys,
149
- initial_state=state_names[0],
158
+ initial_state=initial,
150
159
  extra={PORTABLE_TYPE_KEY: dict(portable)},
151
160
  )
152
161