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,672 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Brafford Labs, LLC
3
+ """Privileged new-target import of accepted Core history (EXPERIMENTAL).
4
+
5
+ EXPERIMENTAL. NON-NORMATIVE. NOT A GOVERNED OBJECT API. Part of the
6
+ interchange experiment.
7
+
8
+ The input is a runtime-neutral semantic structure (:class:`ImportBundle`),
9
+ not artifact JSON; decoding the provisional artifact is the adapter's job
10
+ (``governed_objects.interchange.artifact``). The importer:
11
+
12
+ * restores already-accepted history *as history*: no command is re-run, no
13
+ authorization is re-evaluated for historical actors, no Object Version is
14
+ generated, and no import event is appended to accepted history;
15
+ * resolves the declared governance reference against the local
16
+ ``TypeScopedGovernance``; a match selects local governance and grants
17
+ nothing;
18
+ * checks the receiver-specific constraints of this runtime (identity absent,
19
+ exact Type Identity and Type Version, representable Object Version tokens,
20
+ native encodability of each history effect, representable evidence) and
21
+ folds the history natively so the stored snapshot is the one the history
22
+ produces;
23
+ * writes everything in one SQLite transaction
24
+ (:meth:`SQLiteStore.restore_imported`). Either the whole bundle is restored
25
+ or the store is unchanged.
26
+
27
+ Import provenance is Operational Metadata in ``interchange_imports``; it is
28
+ never part of accepted Canonical History.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import re
34
+ from dataclasses import dataclass, field
35
+ from datetime import UTC, datetime, timedelta, timezone
36
+ from typing import TYPE_CHECKING, Any, Mapping
37
+ from uuid import uuid4
38
+
39
+ from governed_objects.domain.models import Actor, Decision, GovernanceEvent, GovernedObject
40
+ from governed_objects.interchange import (
41
+ GOVERNANCE_REFERENCE_MODEL,
42
+ HISTORY_COMPLETENESS,
43
+ HISTORY_POSITION_MODEL,
44
+ IMPORT_SPEC_REVISIONS,
45
+ )
46
+ from governed_objects.interchange.types import (
47
+ ACTION_LIFECYCLE,
48
+ ACTION_STATE,
49
+ NO_LIFECYCLE_STATE,
50
+ data_problems,
51
+ lifecycle_field,
52
+ portable_type_of,
53
+ )
54
+ from governed_objects.relationships.canonical import canonical_relationship
55
+
56
+ if TYPE_CHECKING:
57
+ from governed_objects.domain.clock import Clock
58
+ from governed_objects.interchange.governance import TypeScopedGovernance
59
+ from governed_objects.persistence.sqlite import SQLiteStore
60
+ from governed_objects.types.registry import TypeRegistry
61
+
62
+ IMPORT_CAPABILITY = "interchange.import"
63
+ IMPORT_EXPERIMENT_REVISION = "governed-objects-import-experiment/1"
64
+
65
+ # Native actor_type recorded on restored rows: the actor id is historical
66
+ # evidence from the source, not a principal of this runtime.
67
+ HISTORICAL_ACTOR_TYPE = "historical"
68
+ # Stored in the NOT NULL timestamp column when the artifact carries no
69
+ # acceptance instant; accepted_at_recorded is False on such rows.
70
+ UNRECORDED_ACCEPTED_AT = datetime(1, 1, 1, tzinfo=UTC)
71
+ # Provenance every history entry must carry (NOT NULL native columns).
72
+ REQUIRED_PROVENANCE = ("actor",)
73
+ # False in a restored row's details when its native action encodes the effect but
74
+ # was not carried as action evidence; export then carries no action for it.
75
+ ACTION_RECORDED = "action_recorded"
76
+
77
+ EFFECT_CREATE = "create"
78
+ EFFECT_STATE_CHANGE = "state_change"
79
+ EFFECT_LIFECYCLE_TRANSITION = "lifecycle_transition"
80
+ EFFECT_RELATIONSHIP_ADD = "relationship_add"
81
+ EFFECT_RELATIONSHIP_REMOVE = "relationship_remove"
82
+ POST_IMAGE_EFFECTS = (EFFECT_CREATE, EFFECT_STATE_CHANGE, EFFECT_LIFECYCLE_TRANSITION)
83
+
84
+ # Refusal codes: the experimental taxonomy of the interchange repository,
85
+ # plus IDENTITY_ALREADY_EXISTS for new-target transfer and AUTHORIZATION_DENIED.
86
+ AUTHORIZATION_DENIED = "AUTHORIZATION_DENIED"
87
+ IDENTITY_ALREADY_EXISTS = "IDENTITY_ALREADY_EXISTS"
88
+ UNSUPPORTED_SPEC_REVISION = "UNSUPPORTED_SPEC_REVISION"
89
+ MALFORMED_ARTIFACT = "MALFORMED_ARTIFACT"
90
+ DUPLICATE_IDENTITY_IN_BUNDLE = "DUPLICATE_IDENTITY_IN_BUNDLE"
91
+ UNSUPPORTED_TYPE = "UNSUPPORTED_TYPE"
92
+ UNSUPPORTED_TYPE_VERSION = "UNSUPPORTED_TYPE_VERSION"
93
+ STATE_NOT_VALID_FOR_TYPE = "STATE_NOT_VALID_FOR_TYPE"
94
+ HISTORY_NOT_VALID_FOR_TYPE = "HISTORY_NOT_VALID_FOR_TYPE"
95
+ DUPLICATE_RELATIONSHIP = "DUPLICATE_RELATIONSHIP"
96
+ MULTISET_HISTORY = "MULTISET_HISTORY"
97
+ HISTORY_INCOMPLETE = "HISTORY_INCOMPLETE"
98
+ HISTORY_INCONSISTENT = "HISTORY_INCONSISTENT"
99
+ HISTORY_SNAPSHOT_MISMATCH = "HISTORY_SNAPSHOT_MISMATCH"
100
+ VERSION_TOKEN_REUSE = "VERSION_TOKEN_REUSE"
101
+ UNSUPPORTED_OBJECT_VERSION_REPRESENTATION = "UNSUPPORTED_OBJECT_VERSION_REPRESENTATION"
102
+ GOVERNANCE_REFERENCE_MISSING = "GOVERNANCE_REFERENCE_MISSING"
103
+ UNRESOLVED_GOVERNANCE_REFERENCE = "UNRESOLVED_GOVERNANCE_REFERENCE"
104
+ UNSUPPORTED_SEMANTIC_FEATURE = "UNSUPPORTED_SEMANTIC_FEATURE"
105
+ BUNDLE_CLOSURE_VIOLATED = "BUNDLE_CLOSURE_VIOLATED"
106
+
107
+ # Native Object Versions are SQLite INTEGER (signed 64-bit) values issued from
108
+ # 1 upward. A portable token is representable only if it is the canonical
109
+ # base-10 form of such a value, so parsing and re-rendering reproduce it.
110
+ NATIVE_TOKEN_GRAMMAR = r"^[1-9][0-9]*$ with value <= 9223372036854775807"
111
+ _TOKEN = re.compile(r"^[1-9][0-9]*$")
112
+ _NATIVE_VERSION_MAX = 2**63 - 1
113
+
114
+ _INSTANT = re.compile(
115
+ r"^(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$"
116
+ )
117
+
118
+
119
+ class ImportRefused(Exception):
120
+ def __init__(
121
+ self, code: str, message: str, identity: str | None = None, position: int | None = None
122
+ ) -> None:
123
+ where = ".".join(
124
+ p for p in (identity, f"history[position={position}]" if position else None) if p
125
+ )
126
+ super().__init__(f"{code}: {where + ': ' if where else ''}{message}")
127
+ self.code = code
128
+ self.message = message
129
+ self.identity = identity
130
+ self.position = position
131
+
132
+
133
+ @dataclass(frozen=True)
134
+ class ImportRelationship:
135
+ source: str
136
+ type: str
137
+ target: str
138
+ # OPTIONAL EVIDENCE (target-type hint, metadata); not retained natively.
139
+ has_evidence: bool = False
140
+
141
+ def key(self) -> tuple[str, str, str]:
142
+ return (self.source, self.type, self.target)
143
+
144
+
145
+ @dataclass(frozen=True)
146
+ class ImportEvidence:
147
+ actor: str | None = None
148
+ accepted_at: str | None = None
149
+ action: str | None = None
150
+ source_event_id: str | None = None
151
+
152
+
153
+ @dataclass(frozen=True)
154
+ class ImportEntry:
155
+ position: int
156
+ effect: str
157
+ type_identity: str
158
+ type_version: str
159
+ resulting_object_version: str
160
+ post_image: Mapping[str, Any] | None = None
161
+ baseline_relationships: tuple[ImportRelationship, ...] | None = None
162
+ relationship: ImportRelationship | None = None
163
+ evidence: ImportEvidence = field(default_factory=ImportEvidence)
164
+
165
+
166
+ @dataclass(frozen=True)
167
+ class ImportObject:
168
+ canonical_identity: str
169
+ type_identity: str
170
+ type_version: str
171
+ governance_reference: str | None
172
+ accepted_state: Mapping[str, Any]
173
+ relationships: tuple[ImportRelationship, ...]
174
+ current_object_version: str
175
+ history: tuple[ImportEntry, ...]
176
+
177
+
178
+ @dataclass(frozen=True)
179
+ class ImportBundle:
180
+ """Semantic content of a portable bundle, independent of its encoding.
181
+
182
+ The declared models are the experiment's semantic feature set; the
183
+ importer refuses any it does not implement."""
184
+
185
+ objects: tuple[ImportObject, ...]
186
+ closed: bool
187
+ spec_revision: str | None
188
+ history_completeness: str
189
+ history_position_model: str
190
+ governance_reference_model: str
191
+ profiles: tuple[Any, ...] = ()
192
+ source_implementation: str | None = None
193
+
194
+
195
+ @dataclass(frozen=True)
196
+ class ImportProvenance:
197
+ """Operational Metadata about the transfer. Never semantic."""
198
+
199
+ artifact_sha256: str | None = None
200
+ source_implementation: str | None = None
201
+ adapter: str | None = None
202
+
203
+
204
+ @dataclass(frozen=True)
205
+ class ImportResult:
206
+ import_id: str
207
+ identities: tuple[str, ...]
208
+ # Optional evidence this runtime could not retain or had to derive. Only
209
+ # evidence the frozen comparator treats as informational or excluded can
210
+ # appear here; unrepresentable actor or accepted_at evidence refuses.
211
+ evidence_notes: tuple[str, ...]
212
+
213
+
214
+ @dataclass
215
+ class _Staged:
216
+ obj: GovernedObject
217
+ events: list[GovernanceEvent]
218
+ relationships: list
219
+
220
+
221
+ def native_version(token: Any, identity: str, position: int | None = None) -> int:
222
+ """Parse a portable token into the native Object Version, refusing any
223
+ token whose native value would not re-render to the same string."""
224
+ if not isinstance(token, str) or not _TOKEN.match(token):
225
+ raise ImportRefused(
226
+ UNSUPPORTED_OBJECT_VERSION_REPRESENTATION,
227
+ f"token {token!r} is not a canonical positive base-10 integer; the native Object "
228
+ "Version is an integer and the token would not survive exactly",
229
+ identity,
230
+ position,
231
+ )
232
+ value = int(token)
233
+ if value > _NATIVE_VERSION_MAX:
234
+ raise ImportRefused(
235
+ UNSUPPORTED_OBJECT_VERSION_REPRESENTATION,
236
+ f"token {token!r} exceeds the native signed 64-bit Object Version range",
237
+ identity,
238
+ position,
239
+ )
240
+ if str(value) != token: # defensive: the grammar already guarantees this
241
+ raise ImportRefused(
242
+ UNSUPPORTED_OBJECT_VERSION_REPRESENTATION, f"token {token!r} does not round-trip",
243
+ identity, position,
244
+ )
245
+ return value
246
+
247
+
248
+ def native_accepted_at(text: str, identity: str, position: int) -> datetime:
249
+ """Parse RFC 3339 evidence into a native UTC datetime, refusing any
250
+ instant this runtime cannot hold exactly (the native timestamp has
251
+ microsecond precision)."""
252
+ m = _INSTANT.match(text) if isinstance(text, str) else None
253
+ if not m:
254
+ raise ImportRefused(MALFORMED_ARTIFACT, "accepted_at is not an RFC 3339 instant", identity, position)
255
+ year, month, day, hour, minute, second = (int(g) for g in m.groups()[:6])
256
+ frac, zone = m.group(7), m.group(8)
257
+ try:
258
+ if zone in ("Z", "z"):
259
+ tz = UTC
260
+ else:
261
+ sign = 1 if zone[0] == "+" else -1
262
+ tz = timezone(sign * timedelta(hours=int(zone[1:3]), minutes=int(zone[4:6])))
263
+ except (ValueError, OverflowError):
264
+ raise ImportRefused(MALFORMED_ARTIFACT, f"accepted_at {text!r} is not a valid instant", identity, position) from None
265
+ digits = frac[1:] if frac else ""
266
+ if len(digits.rstrip("0")) > 6:
267
+ raise ImportRefused(
268
+ UNSUPPORTED_SEMANTIC_FEATURE,
269
+ f"accepted_at {text!r} has sub-microsecond precision; the native timestamp would "
270
+ "not hold this instant exactly (evidence is never truncated)",
271
+ identity,
272
+ position,
273
+ )
274
+ micros = int((digits + "000000")[:6]) if digits else 0
275
+ try:
276
+ local = datetime(year, month, day, hour, minute, second, micros, tzinfo=tz)
277
+ instant = local.astimezone(UTC)
278
+ except (ValueError, OverflowError):
279
+ raise ImportRefused(MALFORMED_ARTIFACT, f"accepted_at {text!r} is not a valid instant", identity, position)
280
+ if instant == UNRECORDED_ACCEPTED_AT:
281
+ raise ImportRefused(
282
+ UNSUPPORTED_SEMANTIC_FEATURE,
283
+ f"accepted_at {text!r} coincides with the native 'not recorded' marker",
284
+ identity,
285
+ position,
286
+ )
287
+ return instant
288
+
289
+
290
+ class InterchangeImporter:
291
+ def __init__(
292
+ self,
293
+ store: SQLiteStore,
294
+ types: TypeRegistry,
295
+ governance: TypeScopedGovernance | None,
296
+ clock: Clock,
297
+ ) -> None:
298
+ self._store = store
299
+ self._types = types
300
+ self._governance = governance
301
+ self._clock = clock
302
+
303
+ def import_bundle(
304
+ self, bundle: ImportBundle, *, actor: Actor, provenance: ImportProvenance | None = None
305
+ ) -> ImportResult:
306
+ if IMPORT_CAPABILITY not in actor.capabilities:
307
+ raise ImportRefused(AUTHORIZATION_DENIED, f"actor {actor.id!r} holds no import grant")
308
+ self._check_declarations(bundle)
309
+ if not bundle.objects:
310
+ raise ImportRefused(MALFORMED_ARTIFACT, "bundle contains no objects")
311
+ identities = [o.canonical_identity for o in bundle.objects]
312
+ for ident in identities:
313
+ if identities.count(ident) > 1:
314
+ raise ImportRefused(DUPLICATE_IDENTITY_IN_BUNDLE, "appears more than once", ident)
315
+ if bundle.closed:
316
+ present = set(identities)
317
+ for obj in bundle.objects:
318
+ for r in obj.relationships:
319
+ if r.target not in present:
320
+ raise ImportRefused(
321
+ BUNDLE_CLOSURE_VIOLATED,
322
+ f"bundle declares closure but target {r.target!r} is absent",
323
+ obj.canonical_identity,
324
+ )
325
+ existing = self._store.identities_present(identities)
326
+ if existing:
327
+ raise ImportRefused(
328
+ IDENTITY_ALREADY_EXISTS,
329
+ f"identities already exist in this runtime: {existing}; new-target import "
330
+ "never overwrites, merges, or skips",
331
+ existing[0],
332
+ )
333
+
334
+ notes: list[str] = []
335
+ staged = [self._stage(obj, notes) for obj in bundle.objects]
336
+
337
+ import_id = str(uuid4())
338
+ record = {
339
+ "import_id": import_id,
340
+ "imported_at": self._clock.now().astimezone(UTC).isoformat(),
341
+ "importing_actor": actor.id,
342
+ "identities": identities,
343
+ "source_implementation": (provenance.source_implementation if provenance else None)
344
+ or bundle.source_implementation,
345
+ "artifact_sha256": provenance.artifact_sha256 if provenance else None,
346
+ "adapter": provenance.adapter if provenance else None,
347
+ "experiment_revision": IMPORT_EXPERIMENT_REVISION,
348
+ "evidence_notes": notes,
349
+ }
350
+ from governed_objects.persistence.sqlite import IdentityAlreadyExists
351
+
352
+ try:
353
+ self._store.restore_imported(
354
+ [s.obj for s in staged],
355
+ [e for s in staged for e in s.events],
356
+ [r for s in staged for r in s.relationships],
357
+ record,
358
+ )
359
+ except IdentityAlreadyExists as exc:
360
+ raise ImportRefused(
361
+ IDENTITY_ALREADY_EXISTS, f"identities already exist in this runtime: {exc.identities}",
362
+ exc.identities[0],
363
+ ) from None
364
+ return ImportResult(import_id=import_id, identities=tuple(identities), evidence_notes=tuple(notes))
365
+
366
+ # --- checks ------------------------------------------------------------
367
+
368
+ @staticmethod
369
+ def _check_declarations(bundle: ImportBundle) -> None:
370
+ if bundle.spec_revision not in IMPORT_SPEC_REVISIONS:
371
+ raise ImportRefused(
372
+ UNSUPPORTED_SPEC_REVISION, f"specification revision {bundle.spec_revision!r} is not supported"
373
+ )
374
+ if bundle.history_completeness != HISTORY_COMPLETENESS:
375
+ raise ImportRefused(
376
+ HISTORY_INCOMPLETE,
377
+ f"history completeness {bundle.history_completeness!r}; only complete history is imported",
378
+ )
379
+ if bundle.history_position_model != HISTORY_POSITION_MODEL:
380
+ raise ImportRefused(
381
+ MALFORMED_ARTIFACT, f"history position model {bundle.history_position_model!r} is not supported"
382
+ )
383
+ if bundle.governance_reference_model != GOVERNANCE_REFERENCE_MODEL:
384
+ raise ImportRefused(
385
+ UNSUPPORTED_SEMANTIC_FEATURE,
386
+ f"governance reference model {bundle.governance_reference_model!r} is not supported",
387
+ )
388
+ if bundle.profiles:
389
+ raise ImportRefused(UNSUPPORTED_SEMANTIC_FEATURE, "profile data is not supported")
390
+
391
+ def _portable(self, obj: ImportObject) -> Mapping[str, Any]:
392
+ ident = obj.canonical_identity
393
+ try:
394
+ type_def = self._types.get(obj.type_identity)
395
+ except KeyError:
396
+ raise ImportRefused(UNSUPPORTED_TYPE, f"Type Identity {obj.type_identity!r} is not configured", ident)
397
+ portable = portable_type_of(type_def)
398
+ if portable is None:
399
+ raise ImportRefused(UNSUPPORTED_TYPE, f"{obj.type_identity!r} is not a portable Core type", ident)
400
+ if type_def.type_version != obj.type_version:
401
+ raise ImportRefused(
402
+ UNSUPPORTED_TYPE_VERSION,
403
+ f"{obj.type_identity}@{obj.type_version} is not supported; this runtime is configured "
404
+ f"with @{type_def.type_version} (never upcast, downcast, or migrated)",
405
+ ident,
406
+ )
407
+ for e in obj.history:
408
+ if e.type_identity != obj.type_identity:
409
+ raise ImportRefused(
410
+ HISTORY_INCONSISTENT, f"entry Type Identity {e.type_identity!r} differs from the object's",
411
+ ident, e.position,
412
+ )
413
+ if e.type_version != obj.type_version:
414
+ raise ImportRefused(
415
+ HISTORY_INCONSISTENT, f"entry Type Version {e.type_version!r} differs from the object's",
416
+ ident, e.position,
417
+ )
418
+ return portable
419
+
420
+ def _check_governance(self, obj: ImportObject) -> str:
421
+ ident = obj.canonical_identity
422
+ if not obj.governance_reference:
423
+ raise ImportRefused(GOVERNANCE_REFERENCE_MISSING, "object carries no governance reference", ident)
424
+ local = (
425
+ self._governance.reference_for(obj.type_identity, obj.type_version)
426
+ if self._governance is not None
427
+ else None
428
+ )
429
+ if local != obj.governance_reference:
430
+ raise ImportRefused(
431
+ UNRESOLVED_GOVERNANCE_REFERENCE,
432
+ f"{obj.governance_reference!r} does not resolve for {obj.type_identity}@{obj.type_version} "
433
+ f"under local governance {getattr(self._governance, 'name', None)!r}",
434
+ ident,
435
+ )
436
+ return local
437
+
438
+ @staticmethod
439
+ def _state_problems(portable: Mapping[str, Any], state: Mapping[str, Any]) -> list[str]:
440
+ lc = lifecycle_field(portable)
441
+ problems: list[str] = []
442
+ if lc is not None:
443
+ if lc not in state:
444
+ problems.append(f"missing lifecycle field {lc!r}")
445
+ elif not isinstance(state[lc], str) or state[lc] not in portable["lifecycle"]["states"]:
446
+ problems.append(f"lifecycle value {state[lc]!r} is not a declared state")
447
+ problems += data_problems(portable, {k: v for k, v in state.items() if k != lc}, partial=False)
448
+ return problems
449
+
450
+ # --- staging -----------------------------------------------------------
451
+
452
+ def _stage(self, obj: ImportObject, notes: list[str]) -> _Staged:
453
+ ident = obj.canonical_identity
454
+ portable = self._portable(obj)
455
+ reference = self._check_governance(obj)
456
+ lc = lifecycle_field(portable)
457
+ actions = portable.get("actions", {})
458
+
459
+ for where, state, position in [("accepted_state", obj.accepted_state, None)] + [
460
+ ("post_image", e.post_image, e.position) for e in obj.history if e.post_image is not None
461
+ ]:
462
+ problems = self._state_problems(portable, state)
463
+ if problems:
464
+ raise ImportRefused(STATE_NOT_VALID_FOR_TYPE, f"{where}: {'; '.join(problems)}", ident, position)
465
+
466
+ rel_lists = [("relationships", obj.relationships, None)] + [
467
+ ("baseline relationships", e.baseline_relationships, e.position)
468
+ for e in obj.history
469
+ if e.baseline_relationships is not None
470
+ ]
471
+ for where, rels, position in rel_lists:
472
+ keys = [r.key() for r in rels]
473
+ for r in rels:
474
+ if r.source != ident:
475
+ raise ImportRefused(MALFORMED_ARTIFACT, f"{where}: triple source {r.source!r} is not the object", ident, position)
476
+ for k in keys:
477
+ if keys.count(k) > 1:
478
+ raise ImportRefused(DUPLICATE_RELATIONSHIP, f"{where}: triple {k} listed more than once", ident, position)
479
+ for e in obj.history:
480
+ if e.relationship is not None and e.relationship.source != ident:
481
+ raise ImportRefused(MALFORMED_ARTIFACT, "triple source is not the object", ident, e.position)
482
+ if any(r.has_evidence for _, rels, _ in rel_lists for r in rels) or any(
483
+ e.relationship is not None and e.relationship.has_evidence for e in obj.history
484
+ ):
485
+ notes.append(f"{ident}: relationship target-type/metadata evidence not retained (informational)")
486
+
487
+ current = native_version(obj.current_object_version, ident)
488
+ natives: dict[int, str] = {}
489
+ for e in obj.history:
490
+ value = native_version(e.resulting_object_version, ident, e.position)
491
+ if value in natives:
492
+ raise ImportRefused(
493
+ VERSION_TOKEN_REUSE,
494
+ f"resulting Object Version {e.resulting_object_version!r} collides with "
495
+ f"{natives[value]!r} natively; tokens are never merged or repaired",
496
+ ident,
497
+ e.position,
498
+ )
499
+ natives[value] = e.resulting_object_version
500
+
501
+ if not obj.history:
502
+ raise ImportRefused(HISTORY_INCOMPLETE, "history is empty", ident)
503
+ positions = sorted(e.position for e in obj.history)
504
+ if positions != list(range(1, len(obj.history) + 1)):
505
+ raise ImportRefused(HISTORY_INCONSISTENT, f"positions are not exactly 1..n: {positions}", ident)
506
+ ordered = sorted(obj.history, key=lambda e: e.position)
507
+ if ordered[0].effect != EFFECT_CREATE:
508
+ raise ImportRefused(HISTORY_INCOMPLETE, "position 1 is not a creation baseline", ident, 1)
509
+ if ordered[-1].resulting_object_version != obj.current_object_version:
510
+ raise ImportRefused(
511
+ HISTORY_INCONSISTENT,
512
+ f"current Object Version {obj.current_object_version!r} is not the last entry's "
513
+ f"{ordered[-1].resulting_object_version!r}",
514
+ ident,
515
+ )
516
+
517
+ events: list[GovernanceEvent] = []
518
+ state: dict[str, Any] = {}
519
+ rels: set[tuple[str, str, str]] = set()
520
+ for e in ordered:
521
+ for item in REQUIRED_PROVENANCE:
522
+ if not getattr(e.evidence, item):
523
+ raise ImportRefused(
524
+ UNSUPPORTED_SEMANTIC_FEATURE,
525
+ f"entry carries no {item} evidence; the native history row requires one",
526
+ ident, e.position,
527
+ )
528
+ before_lc = state.get(lc) if lc else NO_LIFECYCLE_STATE
529
+ if e.effect == EFFECT_CREATE:
530
+ if e.position != 1:
531
+ raise ImportRefused(HISTORY_INCONSISTENT, "creation entry after position 1", ident, e.position)
532
+ state = dict(e.post_image or {})
533
+ rels = {r.key() for r in e.baseline_relationships or ()}
534
+ action = "create"
535
+ elif e.effect == EFFECT_STATE_CHANGE:
536
+ new = dict(e.post_image or {})
537
+ if lc and new.get(lc) != state.get(lc):
538
+ raise ImportRefused(
539
+ HISTORY_NOT_VALID_FOR_TYPE,
540
+ "state_change alters the lifecycle; lifecycle changes must be lifecycle_transition",
541
+ ident, e.position,
542
+ )
543
+ action = self._native_action(e, actions, ACTION_STATE, None, None, ident, notes)
544
+ state = new
545
+ elif e.effect == EFFECT_LIFECYCLE_TRANSITION:
546
+ new = dict(e.post_image or {})
547
+ if lc is None:
548
+ raise ImportRefused(
549
+ HISTORY_NOT_VALID_FOR_TYPE, f"{obj.type_identity} declares no lifecycle", ident, e.position
550
+ )
551
+ before, after = state.get(lc), new.get(lc)
552
+ if [before, after] not in [list(t) for t in portable["lifecycle"]["transitions"]]:
553
+ raise ImportRefused(
554
+ HISTORY_NOT_VALID_FOR_TYPE,
555
+ f"lifecycle transition {before!r} -> {after!r} is not permitted by "
556
+ f"{obj.type_identity}@{obj.type_version}",
557
+ ident, e.position,
558
+ )
559
+ action = self._native_action(e, actions, ACTION_LIFECYCLE, before, after, ident, notes)
560
+ state = new
561
+ elif e.effect == EFFECT_RELATIONSHIP_ADD:
562
+ key = e.relationship.key()
563
+ if key in rels:
564
+ raise ImportRefused(MULTISET_HISTORY, f"addition of already-present triple {key}", ident, e.position)
565
+ rels.add(key)
566
+ action = "add_relationship"
567
+ elif e.effect == EFFECT_RELATIONSHIP_REMOVE:
568
+ key = e.relationship.key()
569
+ if key not in rels:
570
+ raise ImportRefused(HISTORY_INCONSISTENT, f"removal of absent triple {key}", ident, e.position)
571
+ rels.discard(key)
572
+ action = "remove_relationship"
573
+ else:
574
+ raise ImportRefused(MALFORMED_ARTIFACT, f"unknown effect {e.effect!r}", ident, e.position)
575
+ if e.evidence.action is not None and e.evidence.action != action:
576
+ notes.append(
577
+ f"{ident}@{e.position}: action evidence {e.evidence.action!r} not retained; "
578
+ f"native action {action!r} encodes the effect (informational)"
579
+ )
580
+ elif e.evidence.action is None and e.effect in (EFFECT_STATE_CHANGE, EFFECT_LIFECYCLE_TRANSITION):
581
+ notes.append(f"{ident}@{e.position}: no action evidence; native action {action!r} derived from the effect")
582
+ if e.evidence.source_event_id is not None:
583
+ notes.append(f"{ident}@{e.position}: source_event_id evidence not retained (excluded dimension)")
584
+ events.append(self._row(obj, e, action, before_lc, state, lc, reference))
585
+
586
+ declared = dict(obj.accepted_state)
587
+ if state != declared or any(type(state[k]) is not type(declared[k]) for k in state):
588
+ raise ImportRefused(HISTORY_SNAPSHOT_MISMATCH, "accepted_state is not the state the history produces", ident)
589
+ if rels != {r.key() for r in obj.relationships}:
590
+ raise ImportRefused(
591
+ HISTORY_SNAPSHOT_MISMATCH, "relationship set is not the set the history produces", ident
592
+ )
593
+
594
+ stored = GovernedObject(
595
+ id=ident,
596
+ type=obj.type_identity,
597
+ type_version=obj.type_version,
598
+ version=current,
599
+ state=declared[lc] if lc else NO_LIFECYCLE_STATE,
600
+ data={k: v for k, v in declared.items() if k != lc},
601
+ governance_reference=reference,
602
+ )
603
+ relationships = [canonical_relationship(s, t, g) for s, t, g in sorted(rels)]
604
+ return _Staged(stored, events, relationships)
605
+
606
+ @staticmethod
607
+ def _native_action(e, actions, kind, before, after, ident, notes) -> str:
608
+ """The native row encodes the effect by action name. Choose the
609
+ declared action the evidence names when it fits the effect, else the
610
+ unique declared action that fits."""
611
+ def fits(name: str) -> bool:
612
+ spec = actions.get(name)
613
+ if spec is None or spec["kind"] != kind:
614
+ return False
615
+ return kind == ACTION_STATE or (before in spec["from"] and spec["to"] == after)
616
+
617
+ if e.evidence.action is not None and fits(e.evidence.action):
618
+ return e.evidence.action
619
+ candidates = sorted(n for n in actions if fits(n))
620
+ if len(candidates) != 1:
621
+ raise ImportRefused(
622
+ UNSUPPORTED_SEMANTIC_FEATURE,
623
+ f"{e.effect} {before!r} -> {after!r} has {len(candidates)} native encodings "
624
+ f"{candidates} and the action evidence does not select one",
625
+ ident, e.position,
626
+ )
627
+ return candidates[0]
628
+
629
+ def _row(self, obj, e: ImportEntry, action, before_lc, state, lc, reference) -> GovernanceEvent:
630
+ after_lc = state.get(lc) if lc else NO_LIFECYCLE_STATE
631
+ data = {k: v for k, v in state.items() if k != lc}
632
+ details: dict[str, Any] = {"validation_checks": []}
633
+ if e.effect == EFFECT_CREATE:
634
+ details["data"] = data
635
+ if e.baseline_relationships:
636
+ details["relationships"] = [
637
+ {"source_id": r.source, "relation": r.type, "target_id": r.target, "target_type": None}
638
+ for r in e.baseline_relationships
639
+ ]
640
+ details["governance_reference"] = reference
641
+ elif e.effect in (EFFECT_STATE_CHANGE, EFFECT_LIFECYCLE_TRANSITION):
642
+ details["accepted_post_image"] = {"data": data, "state": after_lc}
643
+ elif e.effect == EFFECT_RELATIONSHIP_ADD:
644
+ details.update({"relation": e.relationship.type, "target_id": e.relationship.target, "target_type": None})
645
+ else:
646
+ details.update({"relation": e.relationship.type, "target_id": e.relationship.target})
647
+ if e.evidence.action != action:
648
+ details[ACTION_RECORDED] = False
649
+ recorded = e.evidence.accepted_at is not None
650
+ timestamp = (
651
+ native_accepted_at(e.evidence.accepted_at, obj.canonical_identity, e.position)
652
+ if recorded
653
+ else UNRECORDED_ACCEPTED_AT
654
+ )
655
+ return GovernanceEvent(
656
+ timestamp=timestamp,
657
+ object_id=obj.canonical_identity,
658
+ object_type=obj.type_identity,
659
+ type_version=e.type_version,
660
+ actor_id=e.evidence.actor,
661
+ actor_type=HISTORICAL_ACTOR_TYPE,
662
+ action=action,
663
+ decision=Decision.ALLOW,
664
+ event_type=f"object.{action}",
665
+ previous_state=None if e.effect == EFFECT_CREATE else before_lc,
666
+ new_state=after_lc,
667
+ reason="",
668
+ object_version=native_version(e.resulting_object_version, obj.canonical_identity, e.position),
669
+ details=details,
670
+ history_position=e.position,
671
+ accepted_at_recorded=recorded,
672
+ )