governed-objects 0.2.1__tar.gz → 0.3.0__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.0}/PKG-INFO +7 -6
  2. {governed_objects-0.2.1 → governed_objects-0.3.0}/README.md +5 -5
  3. {governed_objects-0.2.1 → governed_objects-0.3.0}/pyproject.toml +2 -1
  4. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/delegation/resolver.py +12 -1
  5. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/delegation/scope.py +14 -0
  6. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/delegation/service.py +3 -7
  7. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/delegation/validator.py +5 -2
  8. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/events/replay.py +5 -4
  9. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/idempotency/store.py +59 -23
  10. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/policy/outcomes.py +1 -0
  11. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/policy/reasons.py +1 -0
  12. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/runtime/runtime.py +238 -40
  13. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/types/registry.py +4 -1
  14. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/types/schema.py +13 -0
  15. {governed_objects-0.2.1 → governed_objects-0.3.0}/.gitignore +0 -0
  16. {governed_objects-0.2.1 → governed_objects-0.3.0}/CONTRIBUTING.md +0 -0
  17. {governed_objects-0.2.1 → governed_objects-0.3.0}/GOVERNANCE.md +0 -0
  18. {governed_objects-0.2.1 → governed_objects-0.3.0}/LICENSE +0 -0
  19. {governed_objects-0.2.1 → governed_objects-0.3.0}/LICENSING.md +0 -0
  20. {governed_objects-0.2.1 → governed_objects-0.3.0}/NOTICE +0 -0
  21. {governed_objects-0.2.1 → governed_objects-0.3.0}/PRINCIPLES.md +0 -0
  22. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/__init__.py +0 -0
  23. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/_version.py +0 -0
  24. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/adapters/base.py +0 -0
  25. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/adapters/context.py +0 -0
  26. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/adapters/mandate.py +0 -0
  27. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/adapters/registry.py +0 -0
  28. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/agent/session.py +0 -0
  29. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/applications/registry.py +0 -0
  30. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/authority/rules.py +0 -0
  31. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/delegation/configuration.py +0 -0
  32. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/delegation/mandate.py +0 -0
  33. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/delegation/materializer.py +0 -0
  34. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/delegation/projection.py +0 -0
  35. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/domain/__init__.py +0 -0
  36. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/domain/actor_manifest.py +0 -0
  37. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/domain/actors.py +0 -0
  38. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/domain/clock.py +0 -0
  39. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/domain/command.py +0 -0
  40. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/domain/command_context.py +0 -0
  41. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/domain/models.py +0 -0
  42. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/domain/traversal.py +0 -0
  43. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/events/lineage.py +0 -0
  44. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/events/reducers/__init__.py +0 -0
  45. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/events/reducers/mandate.py +0 -0
  46. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/interchange/__init__.py +0 -0
  47. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/interchange/artifact.py +0 -0
  48. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/interchange/export.py +0 -0
  49. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/interchange/governance.py +0 -0
  50. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/interchange/importer.py +0 -0
  51. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/interchange/prc.py +0 -0
  52. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/interchange/types.py +0 -0
  53. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/llm/__init__.py +0 -0
  54. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/llm/loop.py +0 -0
  55. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/llm/model.py +0 -0
  56. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/llm/tools/registry.py +0 -0
  57. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/llm/tools/results.py +0 -0
  58. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/llm/tools/schemas.py +0 -0
  59. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/llm/tools/surface.py +0 -0
  60. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/llm/trace.py +0 -0
  61. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/materialization/service.py +0 -0
  62. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/observations/__init__.py +0 -0
  63. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/observations/ingestion.py +0 -0
  64. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/observations/mapping.py +0 -0
  65. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/observations/models.py +0 -0
  66. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/observations/store.py +0 -0
  67. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/observations/validation.py +0 -0
  68. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/outbound/__init__.py +0 -0
  69. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/outbound/models.py +0 -0
  70. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/outbound/service.py +0 -0
  71. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/outbound/store.py +0 -0
  72. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/persistence/sqlite.py +0 -0
  73. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/policy/constraints.py +0 -0
  74. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/policy/context.py +0 -0
  75. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/policy/evaluator.py +0 -0
  76. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/providers/base.py +0 -0
  77. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/providers/binding.py +0 -0
  78. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/providers/capabilities.py +0 -0
  79. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/providers/errors.py +0 -0
  80. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/providers/projection.py +0 -0
  81. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/providers/registry.py +0 -0
  82. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/query/service.py +0 -0
  83. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/query/traversal.py +0 -0
  84. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/reconciliation/service.py +0 -0
  85. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/registration/detach.py +0 -0
  86. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/registration/service.py +0 -0
  87. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/relationships/canonical.py +0 -0
  88. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/relationships/sync.py +0 -0
  89. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/relationships/vocabulary.py +0 -0
  90. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/types/canonicalizers/base.py +0 -0
  91. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/types/extensions.py +0 -0
  92. {governed_objects-0.2.1 → governed_objects-0.3.0}/src/governed_objects/types/lifecycle.py +0 -0
  93. {governed_objects-0.2.1 → governed_objects-0.3.0}/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.0
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.0, `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.0 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.0 passes the Governed Objects Conformance Suite
46
+ > 0.2.0 for v0alpha1 draft2.2 Core (self-attested; not certified). Not
47
+ > executed by suite 0.2.0: 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,
@@ -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.0, `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.0 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.0 passes the Governed Objects Conformance Suite
21
+ > 0.2.0 for v0alpha1 draft2.2 Core (self-attested; not certified). Not
22
+ > executed by suite 0.2.0: 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,
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "governed-objects"
3
- version = "0.2.1"
3
+ version = "0.3.0"
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"
@@ -72,11 +72,13 @@ class MandateResolver:
72
72
  clock: Clock | None = None,
73
73
  validate_binding=None,
74
74
  scope_decoder=None,
75
+ principal_capabilities=None,
75
76
  ) -> None:
76
77
  self._store = store
77
78
  self._clock = clock or SystemClock()
78
79
  self._validate_binding = validate_binding
79
80
  self._scope_decoder = scope_decoder
81
+ self._principal_capabilities = principal_capabilities
80
82
 
81
83
  def get_object(self, mandate_id: str) -> GovernedObject | None:
82
84
  if self._validate_binding is None:
@@ -118,7 +120,11 @@ class MandateResolver:
118
120
  ancestor_reason = DenyReason.MANDATE_UNKNOWN
119
121
  break
120
122
  parent = materialize_mandate(parent_obj, self._store, scope_decoder=self._scope_decoder)
123
+ child = bounds[-1]
121
124
  bounds.append(parent)
125
+ if parent.delegate_actor_id != child.principal_id:
126
+ ancestor_reason = DenyReason.MANDATE_INVALID
127
+ break
122
128
  if parent.status == MandateStatus.REVOKED or parent_obj.state == "revoked":
123
129
  ancestor_reason = DenyReason.PARENT_MANDATE_REVOKED
124
130
  break
@@ -135,7 +141,13 @@ class MandateResolver:
135
141
  current_parent = parent.parent_mandate_id
136
142
  depth += 1
137
143
 
144
+ # No broader than any mandate in the chain, nor than what each of their
145
+ # principals holds now (DEL-NARROW-001).
146
+ if self._principal_capabilities is None:
147
+ raise ValueError('delegation configuration unavailable')
138
148
  effective_caps = mandate.capabilities
149
+ for bound in bounds:
150
+ effective_caps &= bound.capabilities & self._principal_capabilities(bound.principal_id)
139
151
  effective_scope = EffectiveScope(tuple(bound.scope for bound in bounds))
140
152
  purpose_bounds = [bound.purposes for bound in bounds if bound.purposes]
141
153
  effective_purposes = frozenset.intersection(*purpose_bounds) if purpose_bounds else frozenset()
@@ -143,7 +155,6 @@ class MandateResolver:
143
155
  effective_until = mandate.valid_until
144
156
 
145
157
  for parent in bounds[1:]:
146
- effective_caps = effective_caps & parent.capabilities
147
158
  effective_from = _max_dt(effective_from, parent.valid_from)
148
159
  effective_until = _min_dt(effective_until, parent.valid_until)
149
160
 
@@ -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,
@@ -128,7 +131,7 @@ def _time_subset(
128
131
  ) -> bool:
129
132
  if parent_from is not None and child_from is not None and child_from < parent_from:
130
133
  return False
131
- if parent_until is not None and child_until is not None and child_until > parent_until:
134
+ if parent_until is not None and (child_until is None or child_until > parent_until):
132
135
  return False
133
136
  return True
134
137
 
@@ -139,7 +142,7 @@ def _scope_subset(child: MandateScope, parent: MandateScope, store: SQLiteStore)
139
142
  if parent.is_empty():
140
143
  return True
141
144
  if child.is_empty():
142
- return True
145
+ return False
143
146
 
144
147
  for oid in child.object_ids:
145
148
  obj = store.get(oid)
@@ -73,15 +73,16 @@ class EventReplayer:
73
73
  return None
74
74
 
75
75
  events = self._admitted_events(stored, allow_legacy)
76
+ # Without a reducer nothing can be rebuilt from history, and returning
77
+ # the stored snapshot would present it as reconstructed.
78
+ reducer = self._extensions.reducer_for(stored.type)
79
+ if reducer is None:
80
+ raise ReplayRefused()
76
81
  if not events:
77
82
  return stored
78
83
 
79
- reducer = self._extensions.reducer_for(stored.type)
80
84
  type_version = stored.type_version
81
85
 
82
- if reducer is None:
83
- return stored.model_copy(update={"type_version": type_version})
84
-
85
86
  state = reducer.reduce(None, events[0])
86
87
  if state is None:
87
88
  return stored.model_copy(update={"type_version": type_version})
@@ -4,14 +4,44 @@
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
12
16
  from governed_objects.persistence.sqlite import SQLiteStore, _connection_locked
13
17
 
14
18
 
19
+ @dataclass(frozen=True)
20
+ class Receipt:
21
+ request_hash: str
22
+ result: CommandResult
23
+
24
+
25
+ def request_fingerprint(command: Command, actor: Actor, context: CommandContext) -> str | None:
26
+ """Canonical hash of everything a receipt is bound to, or None when the
27
+ payload has no canonical JSON form."""
28
+ request = {
29
+ "object_id": command.object_id,
30
+ "actor_id": actor.id,
31
+ "mandate_id": context.mandate_id,
32
+ "application_id": context.application_id,
33
+ "purpose": context.purpose,
34
+ "action": command.action,
35
+ "object_type": command.object_type,
36
+ "payload": command.payload,
37
+ }
38
+ try:
39
+ encoded = json.dumps(request, sort_keys=True, separators=(",", ":"), allow_nan=False)
40
+ except (TypeError, ValueError, RecursionError):
41
+ return None
42
+ return hashlib.sha256(encoded.encode()).hexdigest()
43
+
44
+
15
45
  class IdempotencyStore:
16
46
  """Persists idempotent command results and attempt metadata."""
17
47
 
@@ -39,57 +69,63 @@ class IdempotencyStore:
39
69
  );
40
70
  CREATE INDEX IF NOT EXISTS idx_command_attempts_command
41
71
  ON command_attempts(command_id);
72
+ CREATE TABLE IF NOT EXISTS command_receipts (
73
+ object_id TEXT NOT NULL,
74
+ actor_id TEXT NOT NULL,
75
+ idempotency_key TEXT NOT NULL,
76
+ request_hash TEXT NOT NULL,
77
+ command_id TEXT NOT NULL,
78
+ correlation_id TEXT,
79
+ result_json TEXT NOT NULL,
80
+ created_at TEXT NOT NULL,
81
+ PRIMARY KEY (object_id, actor_id, idempotency_key)
82
+ );
42
83
  """
43
84
  )
44
85
  self._store._conn.commit()
45
86
 
46
87
  @_connection_locked
47
- def get(self, object_id: str, idempotency_key: str) -> CommandResult | None:
88
+ def get(self, object_id: str, actor_id: str, idempotency_key: str) -> Receipt | None:
48
89
  row = self._store._conn.execute(
49
90
  """
50
- SELECT result_json, status FROM command_attempts
51
- WHERE object_id = ? AND idempotency_key = ?
91
+ SELECT request_hash, result_json FROM command_receipts
92
+ WHERE object_id = ? AND actor_id = ? AND idempotency_key = ?
52
93
  """,
53
- (object_id, idempotency_key),
94
+ (object_id, actor_id, idempotency_key),
54
95
  ).fetchone()
55
- if row is None or not row["result_json"]:
56
- return None
57
- if row["status"] != "succeeded":
96
+ if row is None:
58
97
  return None
59
- return _result_from_json(row["result_json"])
98
+ return Receipt(row["request_hash"], _result_from_json(row["result_json"]))
60
99
 
61
100
  @_connection_locked
62
101
  def put(
63
102
  self,
64
103
  object_id: str,
104
+ actor_id: str,
65
105
  idempotency_key: str,
106
+ request_hash: str,
66
107
  result: CommandResult,
67
108
  *,
68
109
  command_id: str | None = None,
69
110
  correlation_id: str | None = None,
70
111
  ) -> None:
71
- now = datetime.now(UTC).isoformat()
112
+ """Record the receipt of an accepted request; an existing one is never replaced."""
72
113
  self._store._conn.execute(
73
114
  """
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
115
+ INSERT INTO command_receipts (
116
+ object_id, actor_id, idempotency_key, request_hash,
117
+ command_id, correlation_id, result_json, created_at
118
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
84
119
  """,
85
120
  (
86
- command_id or "",
87
121
  object_id,
122
+ actor_id,
88
123
  idempotency_key,
124
+ request_hash,
125
+ command_id or "",
89
126
  correlation_id,
90
127
  json.dumps(_result_to_json(result)),
91
- now,
92
- now,
128
+ datetime.now(UTC).isoformat(),
93
129
  ),
94
130
  )
95
131
  self._store._commit_if_autonomous()
@@ -56,6 +56,7 @@ SEMANTIC_DENY_REASONS = frozenset(
56
56
  DenyReason.TYPE_VERSION_UNSUPPORTED,
57
57
  DenyReason.IDENTITY_EXISTS,
58
58
  DenyReason.STATE_INVALID,
59
+ DenyReason.IDEMPOTENCY_KEY_REUSED,
59
60
  }
60
61
  )
61
62
 
@@ -37,6 +37,7 @@ class DenyReason(StrEnum):
37
37
  ADAPTER_RESULT_INVALID = "ADAPTER_RESULT_INVALID"
38
38
  STATE_INVALID = "STATE_INVALID"
39
39
  PROVIDER_FAILED = "PROVIDER_FAILED"
40
+ IDEMPOTENCY_KEY_REUSED = "IDEMPOTENCY_KEY_REUSED"
40
41
 
41
42
 
42
43
  class ConflictReason(StrEnum):
@@ -4,6 +4,7 @@
4
4
 
5
5
  from __future__ import annotations
6
6
 
7
+ from copy import deepcopy
7
8
  from typing import Any
8
9
 
9
10
  from governed_objects.applications.registry import ApplicationDefinition, ApplicationRegistry
@@ -32,6 +33,8 @@ from governed_objects.delegation.projection import MandateProjection
32
33
  from governed_objects.delegation.configuration import DelegationConfiguration, DelegationConfigurationError
33
34
  from governed_objects.delegation.materializer import materialize_mandate
34
35
  from governed_objects.delegation.mandate import DelegatedMandate
36
+ from governed_objects.delegation.scope import declares_no_more_than
37
+ from governed_objects.relationships.vocabulary import DELEGATED_BY, DELEGATED_TO, DERIVED_FROM
35
38
  from governed_objects.delegation.resolver import MandateResolver, ResolvedMandateAuthority
36
39
  from governed_objects.delegation.service import MandateService
37
40
  from governed_objects.delegation.validator import DelegationSpec, DelegationValidator
@@ -39,7 +42,7 @@ from governed_objects.domain.clock import Clock, SystemClock
39
42
  from governed_objects.domain.command_context import CommandContext
40
43
  from governed_objects.domain.traversal import TraversalResult
41
44
  from governed_objects.events.replay import EventReplayer, ReplayRefused, bound_type_definition
42
- from governed_objects.idempotency.store import IdempotencyStore
45
+ from governed_objects.idempotency.store import IdempotencyStore, request_fingerprint
43
46
  from governed_objects.interchange.governance import TypeScopedGovernance
44
47
  from governed_objects.materialization.service import MaterializationService
45
48
  from governed_objects.persistence.sqlite import INT64_MAX, SQLiteStore
@@ -75,6 +78,13 @@ from governed_objects.types.lifecycle import LifecycleValidator
75
78
  from governed_objects.types.registry import TypeRegistry
76
79
  from governed_objects.types.validation import SchemaValidator
77
80
 
81
+
82
+ def _mandate_structure(relationships):
83
+ """The principal, delegate and parent links, which are fixed at creation."""
84
+ return sorted((r.relation, r.target_id) for r in relationships
85
+ if r.relation in (DELEGATED_BY, DELEGATED_TO, DERIVED_FROM))
86
+
87
+
78
88
  class GovernedObjectRuntime:
79
89
  """Shared runtime for all governed object types."""
80
90
 
@@ -142,6 +152,7 @@ class GovernedObjectRuntime:
142
152
  self._mandate_resolver = MandateResolver(
143
153
  store, clock=self._clock, validate_binding=self._validate_delegation_binding,
144
154
  scope_decoder=self._decode_legacy_scope,
155
+ principal_capabilities=self._principal_capabilities,
145
156
  )
146
157
  self._delegation_validator = DelegationValidator(store)
147
158
  self._mandate_projection = MandateProjection(store, resolver=self._mandate_resolver)
@@ -256,7 +267,9 @@ class GovernedObjectRuntime:
256
267
  ) -> CommandResult:
257
268
  result = self._finalize(result)
258
269
  if result.decision == Decision.ALLOW:
259
- return result
270
+ if isinstance(command, ReadObject):
271
+ return result
272
+ return self._shape_accepted(result, actor, command_context)
260
273
  stored = self._store.get(command.object_id) if command.object_id else None
261
274
  if stored is None or self._requester_can_read(actor, stored, command_context):
262
275
  return result
@@ -275,6 +288,78 @@ class GovernedObjectRuntime:
275
288
  )
276
289
  return result
277
290
 
291
+ def _shape_accepted(
292
+ self,
293
+ result: CommandResult,
294
+ actor: Actor,
295
+ command_context: CommandContext | None,
296
+ ) -> CommandResult:
297
+ """An accepted mutation or no-op returns content only to a requester
298
+ that may read the object, shaped as a read would shape it. Anyone else
299
+ receives a minimal receipt."""
300
+ stored = self._store.get(result.object_id) if result.object_id is not None else None
301
+ if stored is not None and self._read_denial(stored, actor, command_context) is None:
302
+ try:
303
+ shaped = self._project_accepted(result, stored, actor)
304
+ except Exception:
305
+ # The change is already accepted; withhold rather than fail it.
306
+ shaped = None
307
+ if shaped is not None:
308
+ return shaped
309
+ return CommandResult(
310
+ decision=result.decision,
311
+ outcome_category=result.outcome_category,
312
+ reason="accepted",
313
+ action=result.action,
314
+ object_id=result.object_id,
315
+ object_version=result.object_version,
316
+ )
317
+
318
+ def _project_accepted(
319
+ self, result: CommandResult, stored: GovernedObject, actor: Actor
320
+ ) -> CommandResult | None:
321
+ """Apply the read projection to every data image in an accepted result,
322
+ or None when that projection leaves the requester nothing readable."""
323
+ denied: list[str] = []
324
+
325
+ def view(data: dict[str, Any], state: str | None) -> tuple[dict[str, Any], list[str]]:
326
+ image = stored.model_copy(
327
+ deep=True, update={"data": deepcopy(data), "state": state or stored.state}
328
+ )
329
+ return self._project_read(image, actor, [])
330
+
331
+ data, hidden = view(result.data or stored.data, result.new_state)
332
+ if hidden and not data:
333
+ return None
334
+ denied.extend(hidden)
335
+ events = []
336
+ for event in result.events:
337
+ details = deepcopy(event.details)
338
+ for holder in (details, details.get("accepted_post_image")):
339
+ if isinstance(holder, dict) and "data" in holder:
340
+ holder["data"], hidden = view(holder["data"], event.new_state)
341
+ denied.extend(hidden)
342
+ events.append(event.model_copy(update={"details": details}))
343
+ checks = result.validation_checks
344
+ if denied:
345
+ # Diagnostic text may quote a withheld value.
346
+ checks = [ValidationCheck(name=c.name, passed=c.passed, message="") for c in checks]
347
+ for event in events:
348
+ if "validation_checks" in event.details:
349
+ event.details["validation_checks"] = [c.model_dump() for c in checks]
350
+ return result.model_copy(update={
351
+ "data": data if result.data else {},
352
+ "events": events,
353
+ "validation_checks": checks,
354
+ })
355
+
356
+ def _project_read(
357
+ self, obj: GovernedObject, actor: Actor, fields: list[str]
358
+ ) -> tuple[dict[str, Any], list[str]]:
359
+ """The one field projection applied to object data returned to a requester."""
360
+ adapter = self._adapters.resolve(obj)
361
+ return adapter.filter_read_data(obj, self._types.get(obj.type), actor, fields)
362
+
278
363
  def _requester_can_read(
279
364
  self,
280
365
  actor: Actor,
@@ -356,9 +441,10 @@ class GovernedObjectRuntime:
356
441
  def replay(self, object_id: str, *, allow_legacy: bool = False) -> GovernedObject | None:
357
442
  """Stage supported reconstruction before installing state and edges.
358
443
 
359
- ReplayRefused is content-free; None means only a missing target.
360
- Legacy opt-in changes ordering, not binding requirements. Supported
361
- no-history/no-reducer/decline fallback is not reconstruction proof.
444
+ ReplayRefused is content-free; None means only a missing target. A type
445
+ without a registered reducer is refused. Legacy opt-in changes ordering,
446
+ not binding requirements. Supported no-history/decline fallback is not
447
+ reconstruction proof.
362
448
  """
363
449
  stored = self._store.get(object_id)
364
450
  if stored is None:
@@ -485,8 +571,8 @@ class GovernedObjectRuntime:
485
571
  accepted-history positions, unlike timestamp-ordered ``history()``
486
572
  event/audit rows. Replay defaults to positioned accepted revisions;
487
573
  unpositioned accepted history requires explicit ``allow_legacy=True``
488
- for legacy timestamp ordering. Exact binding support still applies;
489
- supported no-history/no-reducer/decline fallbacks are not proof of
574
+ for legacy timestamp ordering. Exact binding and a registered reducer
575
+ are required; supported no-history/decline fallbacks are not proof of
490
576
  reconstruction.
491
577
  """
492
578
  return self._store.list_accepted_for_object(object_id)
@@ -650,6 +736,19 @@ class GovernedObjectRuntime:
650
736
  command_context=command_context,
651
737
  )
652
738
 
739
+ if not type_def.allows_relationship_type(relation):
740
+ return self._deny(
741
+ stored.id,
742
+ stored.type,
743
+ actor,
744
+ "add_relationship",
745
+ "relationship type is not declared for this object type",
746
+ stored.state,
747
+ stored.state,
748
+ deny_reason=DenyReason.RELATIONSHIP_INVALID,
749
+ command_context=command_context,
750
+ )
751
+
653
752
  conflict = self._check_version_conflict(
654
753
  stored, "add_relationship", actor, command_context
655
754
  )
@@ -690,6 +789,13 @@ class GovernedObjectRuntime:
690
789
  )
691
790
  if conflict is not None:
692
791
  return conflict
792
+ # A mandate change was admitted against ``stored``; a revision
793
+ # since then could make it widen the mandate.
794
+ if current.type == 'DelegatedMandate' and current.version != stored.version:
795
+ return self._conflict(
796
+ current, actor, "add_relationship", expected_version=stored.version,
797
+ actual_version=current.version, command_context=command_context,
798
+ )
693
799
  new_version = self._allocate_version(current)
694
800
  if new_version is None:
695
801
  return self._version_space_exhausted(current, actor, "add_relationship", command_context)
@@ -834,6 +940,13 @@ class GovernedObjectRuntime:
834
940
  )
835
941
  if conflict is not None:
836
942
  return conflict
943
+ # A mandate change was admitted against ``stored``; a revision
944
+ # since then could make it widen the mandate.
945
+ if current.type == 'DelegatedMandate' and current.version != stored.version:
946
+ return self._conflict(
947
+ current, actor, "remove_relationship", expected_version=stored.version,
948
+ actual_version=current.version, command_context=command_context,
949
+ )
837
950
  new_version = self._allocate_version(current)
838
951
  if new_version is None:
839
952
  return self._version_space_exhausted(
@@ -880,9 +993,7 @@ class GovernedObjectRuntime:
880
993
  decision=Decision.DENY, reason='mandate authority unavailable',
881
994
  deny_reason=DenyReason.MANDATE_INVALID.value,
882
995
  ))
883
- if (not isinstance(command.payload.get('data'), dict)
884
- or (command.payload.get('state') is not None
885
- and command.payload['state'] not in ('draft', 'active', 'revoked'))):
996
+ if not isinstance(command.payload.get('data'), dict):
886
997
  return self._finalize(CommandResult(
887
998
  decision=Decision.DENY, reason='mandate authority unavailable',
888
999
  deny_reason=DenyReason.MANDATE_INVALID.value,
@@ -894,7 +1005,9 @@ class GovernedObjectRuntime:
894
1005
  )
895
1006
  if canonicalizer is not None:
896
1007
  data = canonicalizer.canonicalize_create(data)
897
- state = command.payload.get("state") or type_def.default_state()
1008
+ # A create always starts in the type's default state.
1009
+ state = type_def.default_state()
1010
+ requested_state = command.payload.get("state")
898
1011
  relationships = command.payload.get("relationships", [])
899
1012
 
900
1013
  auth, auth_deny = self._resolve_auth(command_context)
@@ -935,6 +1048,19 @@ class GovernedObjectRuntime:
935
1048
  )
936
1049
  )
937
1050
 
1051
+ if requested_state is not None and requested_state != state:
1052
+ return self._deny(
1053
+ command.object_id or "new",
1054
+ command.object_type or "",
1055
+ actor,
1056
+ "create",
1057
+ "create starts in the type's default state",
1058
+ None,
1059
+ state,
1060
+ deny_reason=DenyReason.STATE_INVALID,
1061
+ command_context=command_context,
1062
+ )
1063
+
938
1064
  adapter = self._adapters.for_type(command.object_type or "")
939
1065
  checks: list[ValidationCheck] = []
940
1066
  if adapter:
@@ -974,10 +1100,16 @@ class GovernedObjectRuntime:
974
1100
  else None
975
1101
  )
976
1102
 
1103
+ # A create asserts only the new object's own outgoing relationships, each
1104
+ # once (REL-OWNER-001, REL-MULT-001).
1105
+ source_id = command.object_id or ""
977
1106
  try:
978
- canonical_rels = [
1107
+ foreign_source = any(
1108
+ rel_data.get("source_id", source_id) != source_id for rel_data in relationships
1109
+ )
1110
+ canonical_rels = [] if foreign_source else [
979
1111
  canonical_relationship(
980
- rel_data.get("source_id", command.object_id or ""),
1112
+ source_id,
981
1113
  rel_data["relation"], rel_data["target_id"], target_type=rel_data.get("target_type"),
982
1114
  ) for rel_data in relationships
983
1115
  ]
@@ -989,6 +1121,23 @@ class GovernedObjectRuntime:
989
1121
  deny_reason=DenyReason.MANDATE_INVALID.value,
990
1122
  ))
991
1123
 
1124
+ triples = {(r.source_id, r.relation, r.target_id) for r in canonical_rels}
1125
+ undeclared = any(not type_def.allows_relationship_type(r.relation) for r in canonical_rels)
1126
+ if foreign_source or undeclared or len(triples) != len(canonical_rels):
1127
+ return self._deny(
1128
+ source_id or "new",
1129
+ command.object_type or "",
1130
+ actor,
1131
+ "create",
1132
+ "relationship source must be the new object" if foreign_source
1133
+ else "relationship type is not declared for this object type" if undeclared
1134
+ else "duplicate relationship",
1135
+ None,
1136
+ state,
1137
+ deny_reason=DenyReason.RELATIONSHIP_INVALID,
1138
+ command_context=command_context,
1139
+ )
1140
+
992
1141
  obj = GovernedObject(
993
1142
  id=command.object_id or "",
994
1143
  type=command.object_type or "",
@@ -1109,9 +1258,8 @@ class GovernedObjectRuntime:
1109
1258
  if denied is not None:
1110
1259
  return denied
1111
1260
 
1112
- adapter = self._adapters.resolve(obj)
1113
1261
  fields = command.payload.get("fields") or []
1114
- data, denied_fields = adapter.filter_read_data(obj, type_def, actor, fields)
1262
+ data, denied_fields = self._project_read(obj, actor, fields)
1115
1263
 
1116
1264
  if denied_fields and not data:
1117
1265
  return self._deny(
@@ -1242,12 +1390,30 @@ class GovernedObjectRuntime:
1242
1390
  # A cached result is only returned to a requester already authorized
1243
1391
  # for this operation; it precedes the version check so a retry of an
1244
1392
  # accepted command still returns its original result.
1393
+ # Keys belong to the actor, and a receipt answers only the exact request
1394
+ # that produced it.
1395
+ fingerprint = None
1245
1396
  if command_context and command_context.idempotency_key:
1246
- cached = self._idempotency.get(
1247
- command.object_id or "", command_context.idempotency_key
1397
+ fingerprint = request_fingerprint(command, actor, command_context)
1398
+ if fingerprint is None:
1399
+ return self._deny(
1400
+ stored.id, stored.type, actor, action,
1401
+ "payload has no canonical form", stored.state, stored.state,
1402
+ deny_reason=DenyReason.SCHEMA_INVALID, command_context=command_context,
1403
+ )
1404
+ receipt = self._idempotency.get(
1405
+ stored.id, actor.id, command_context.idempotency_key
1248
1406
  )
1249
- if cached is not None:
1250
- return self._finalize(cached)
1407
+ if receipt is not None:
1408
+ if receipt.request_hash != fingerprint:
1409
+ return self._deny(
1410
+ stored.id, stored.type, actor, action,
1411
+ "idempotency key already used for a different request",
1412
+ stored.state, stored.state,
1413
+ deny_reason=DenyReason.IDEMPOTENCY_KEY_REUSED,
1414
+ command_context=command_context,
1415
+ )
1416
+ return self._finalize(receipt.result)
1251
1417
 
1252
1418
  conflict = self._check_version_conflict(
1253
1419
  stored, action, actor, command_context
@@ -1427,28 +1593,31 @@ class GovernedObjectRuntime:
1427
1593
  },
1428
1594
  )
1429
1595
  event = self._store.append_accepted(event)
1430
- result = self._finalize(
1431
- CommandResult(
1432
- decision=Decision.ALLOW,
1433
- reason="transition applied",
1434
- action=action,
1435
- object_id=obj.id,
1436
- previous_state=previous_state,
1437
- new_state=new_state,
1438
- object_version=obj.version,
1439
- events=[event],
1440
- validation_checks=checks,
1441
- data=obj.data,
1442
- )
1443
- )
1444
- if command_context and command_context.idempotency_key:
1445
- self._idempotency.put(
1446
- obj.id,
1447
- command_context.idempotency_key,
1448
- result,
1449
- command_id=command_context.command_id,
1450
- correlation_id=command_context.correlation_id,
1596
+ result = self._finalize(
1597
+ CommandResult(
1598
+ decision=Decision.ALLOW,
1599
+ reason="transition applied",
1600
+ action=action,
1601
+ object_id=obj.id,
1602
+ previous_state=previous_state,
1603
+ new_state=new_state,
1604
+ object_version=obj.version,
1605
+ events=[event],
1606
+ validation_checks=checks,
1607
+ data=obj.data,
1608
+ )
1451
1609
  )
1610
+ if fingerprint is not None:
1611
+ # Same transaction as the change: both are recorded or neither is.
1612
+ self._idempotency.put(
1613
+ obj.id,
1614
+ actor.id,
1615
+ command_context.idempotency_key,
1616
+ fingerprint,
1617
+ result,
1618
+ command_id=command_context.command_id,
1619
+ correlation_id=command_context.correlation_id,
1620
+ )
1452
1621
  return result
1453
1622
 
1454
1623
  def require_delegation(self):
@@ -1457,6 +1626,9 @@ class GovernedObjectRuntime:
1457
1626
  self._delegation.validate(self._types, self._adapters, self._extensions)
1458
1627
  return self._delegation
1459
1628
 
1629
+ def _principal_capabilities(self, principal_id: str) -> frozenset[str]:
1630
+ return frozenset(self.require_delegation().actor(principal_id).capabilities)
1631
+
1460
1632
  def _decode_legacy_scope(self, scoped_to, store):
1461
1633
  return self.require_delegation().scope_decoder(scoped_to, store)
1462
1634
 
@@ -1473,10 +1645,36 @@ class GovernedObjectRuntime:
1473
1645
  try:
1474
1646
  configuration = self.require_delegation()
1475
1647
  configuration.validate(self._types, self._adapters, self._extensions, obj)
1648
+ existing = None
1649
+ if action in ('add_relationship', 'remove_relationship'):
1650
+ # To change who delegates to whom, or under which parent, revoke
1651
+ # the mandate and create another.
1652
+ existing = list_canonical_for_object(self._store, obj.id)
1653
+ if _mandate_structure(existing) != _mandate_structure(relationships):
1654
+ return self._deny(obj.id, obj.type, actor, action,
1655
+ 'mandate principal, delegate and parent are fixed at creation',
1656
+ obj.state, obj.state, deny_reason=DenyReason.RELATIONSHIP_INVALID,
1657
+ command_context=command_context)
1476
1658
  mandate = materialize_mandate(obj, self._store, scope_decoder=configuration.scope_decoder,
1477
1659
  relationships=relationships)
1660
+ if existing is not None:
1661
+ current = materialize_mandate(obj, self._store, scope_decoder=configuration.scope_decoder,
1662
+ relationships=existing)
1663
+ if not declares_no_more_than(mandate.scope, current.scope):
1664
+ return self._deny(obj.id, obj.type, actor, action,
1665
+ 'mandate scope may only narrow after creation',
1666
+ obj.state, obj.state, deny_reason=DenyReason.RELATIONSHIP_INVALID,
1667
+ command_context=command_context)
1478
1668
  principal = configuration.actor(mandate.principal_id)
1479
1669
  configuration.actor(mandate.delegate_actor_id)
1670
+ if action == 'create':
1671
+ # An actor delegates only its own authority, and a create made
1672
+ # under a mandate derives from that mandate.
1673
+ if mandate.principal_id != actor.id:
1674
+ raise ValueError('principal is not the creating actor')
1675
+ bound = command_context.mandate_id if command_context else None
1676
+ if bound and mandate.parent_mandate_id != bound:
1677
+ raise ValueError('parent is not the acting mandate')
1480
1678
  if action != 'revoke':
1481
1679
  parent = None
1482
1680
  ancestors = frozenset()
@@ -123,6 +123,9 @@ def _resolve_type(kind: str, all_raw: dict[str, dict]) -> ObjectTypeDefinition:
123
123
  type_version = str(raw.get("version") or REFERENCE_RUNTIME_DEFAULT_TYPE_VERSION)
124
124
  if parent_kind and "version" not in raw:
125
125
  type_version = parent.type_version
126
+ extra = {k: v for k, v in raw.items() if k not in consumed}
127
+ if parent_kind and "relationship_types" not in raw and "relationship_types" in parent.extra:
128
+ extra["relationship_types"] = parent.extra["relationship_types"]
126
129
  return ObjectTypeDefinition(
127
130
  kind=kind,
128
131
  type_version=type_version,
@@ -135,7 +138,7 @@ def _resolve_type(kind: str, all_raw: dict[str, dict]) -> ObjectTypeDefinition:
135
138
  read_requires=read_requires,
136
139
  read_open=read_open,
137
140
  canonical_state_map=canonical_state_map,
138
- extra={k: v for k, v in raw.items() if k not in consumed},
141
+ extra=extra,
139
142
  )
140
143
 
141
144
 
@@ -75,6 +75,19 @@ class ObjectTypeDefinition(BaseModel):
75
75
  action_def = self.actions.get(action)
76
76
  return bool(action_def and action_def.open)
77
77
 
78
+ def allows_relationship_type(self, relation: str) -> bool:
79
+ """Whether an object of this type may assert ``relation`` (TYPE-VALID-001).
80
+ A non-empty declared list is exhaustive; an empty or absent list allows
81
+ any type. A declaration that is not a list allows none."""
82
+ portable = self.extra.get("interchange_portable_type")
83
+ source = self.extra if portable is None else portable
84
+ declared = source.get("relationship_types")
85
+ if declared is None:
86
+ return True
87
+ if not isinstance(declared, (list, tuple)):
88
+ return False
89
+ return not declared or relation in declared
90
+
78
91
  def transition_target(self, current_state: str, action: str) -> str | None:
79
92
  state_def = self.states.get(current_state)
80
93
  if not state_def: