governed-objects 0.2.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- governed_objects/__init__.py +7 -0
- governed_objects/_version.py +38 -0
- governed_objects/adapters/base.py +80 -0
- governed_objects/adapters/context.py +58 -0
- governed_objects/adapters/mandate.py +45 -0
- governed_objects/adapters/registry.py +25 -0
- governed_objects/agent/session.py +111 -0
- governed_objects/applications/registry.py +39 -0
- governed_objects/authority/rules.py +63 -0
- governed_objects/delegation/configuration.py +74 -0
- governed_objects/delegation/mandate.py +44 -0
- governed_objects/delegation/materializer.py +152 -0
- governed_objects/delegation/projection.py +48 -0
- governed_objects/delegation/resolver.py +180 -0
- governed_objects/delegation/scope.py +75 -0
- governed_objects/delegation/service.py +245 -0
- governed_objects/delegation/validator.py +159 -0
- governed_objects/domain/__init__.py +21 -0
- governed_objects/domain/actor_manifest.py +40 -0
- governed_objects/domain/actors.py +55 -0
- governed_objects/domain/clock.py +28 -0
- governed_objects/domain/command.py +95 -0
- governed_objects/domain/command_context.py +35 -0
- governed_objects/domain/models.py +110 -0
- governed_objects/domain/traversal.py +25 -0
- governed_objects/events/lineage.py +71 -0
- governed_objects/events/reducers/__init__.py +2 -0
- governed_objects/events/reducers/mandate.py +31 -0
- governed_objects/events/replay.py +208 -0
- governed_objects/idempotency/store.py +160 -0
- governed_objects/interchange/__init__.py +49 -0
- governed_objects/interchange/artifact.py +310 -0
- governed_objects/interchange/export.py +345 -0
- governed_objects/interchange/governance.py +26 -0
- governed_objects/interchange/importer.py +672 -0
- governed_objects/interchange/prc.py +76 -0
- governed_objects/interchange/types.py +228 -0
- governed_objects/llm/__init__.py +16 -0
- governed_objects/llm/loop.py +130 -0
- governed_objects/llm/model.py +44 -0
- governed_objects/llm/tools/registry.py +87 -0
- governed_objects/llm/tools/results.py +53 -0
- governed_objects/llm/tools/schemas.py +67 -0
- governed_objects/llm/tools/surface.py +252 -0
- governed_objects/llm/trace.py +58 -0
- governed_objects/materialization/service.py +107 -0
- governed_objects/observations/__init__.py +3 -0
- governed_objects/observations/ingestion.py +375 -0
- governed_objects/observations/mapping.py +48 -0
- governed_objects/observations/models.py +81 -0
- governed_objects/observations/store.py +214 -0
- governed_objects/observations/validation.py +188 -0
- governed_objects/outbound/__init__.py +3 -0
- governed_objects/outbound/models.py +94 -0
- governed_objects/outbound/service.py +502 -0
- governed_objects/outbound/store.py +147 -0
- governed_objects/persistence/sqlite.py +635 -0
- governed_objects/policy/constraints.py +9 -0
- governed_objects/policy/context.py +28 -0
- governed_objects/policy/evaluator.py +301 -0
- governed_objects/policy/outcomes.py +93 -0
- governed_objects/policy/reasons.py +43 -0
- governed_objects/providers/base.py +26 -0
- governed_objects/providers/binding.py +42 -0
- governed_objects/providers/capabilities.py +27 -0
- governed_objects/providers/errors.py +48 -0
- governed_objects/providers/projection.py +25 -0
- governed_objects/providers/registry.py +59 -0
- governed_objects/query/service.py +171 -0
- governed_objects/query/traversal.py +154 -0
- governed_objects/reconciliation/service.py +213 -0
- governed_objects/registration/detach.py +43 -0
- governed_objects/registration/service.py +113 -0
- governed_objects/relationships/canonical.py +55 -0
- governed_objects/relationships/sync.py +63 -0
- governed_objects/relationships/vocabulary.py +12 -0
- governed_objects/runtime/runtime.py +1919 -0
- governed_objects/types/canonicalizers/base.py +15 -0
- governed_objects/types/extensions.py +48 -0
- governed_objects/types/lifecycle.py +65 -0
- governed_objects/types/registry.py +171 -0
- governed_objects/types/schema.py +90 -0
- governed_objects/types/validation.py +57 -0
- governed_objects-0.2.1.dist-info/METADATA +184 -0
- governed_objects-0.2.1.dist-info/RECORD +88 -0
- governed_objects-0.2.1.dist-info/WHEEL +4 -0
- governed_objects-0.2.1.dist-info/licenses/LICENSE +202 -0
- governed_objects-0.2.1.dist-info/licenses/NOTICE +12 -0
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2026 Brafford Labs, LLC
|
|
3
|
+
"""Core domain models for the Governed Object runtime."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from datetime import UTC, datetime
|
|
8
|
+
from enum import StrEnum
|
|
9
|
+
from typing import Any
|
|
10
|
+
from uuid import uuid4
|
|
11
|
+
|
|
12
|
+
from pydantic import BaseModel, Field
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Decision(StrEnum):
|
|
16
|
+
ALLOW = "ALLOW"
|
|
17
|
+
DENY = "DENY"
|
|
18
|
+
CONFLICT = "CONFLICT"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class ActorType(StrEnum):
|
|
22
|
+
HUMAN = "human"
|
|
23
|
+
SERVICE = "service"
|
|
24
|
+
AGENT = "agent"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Relationship(BaseModel):
|
|
28
|
+
source_id: str
|
|
29
|
+
relation: str
|
|
30
|
+
target_id: str
|
|
31
|
+
target_type: str | None = None
|
|
32
|
+
metadata: dict[str, Any] = Field(default_factory=dict)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class GovernedObject(BaseModel):
|
|
36
|
+
"""Materialized state of a governed object."""
|
|
37
|
+
|
|
38
|
+
id: str
|
|
39
|
+
type: str
|
|
40
|
+
type_version: str = "1"
|
|
41
|
+
version: int = 1
|
|
42
|
+
state: str
|
|
43
|
+
data: dict[str, Any] = Field(default_factory=dict)
|
|
44
|
+
policy: dict[str, Any] = Field(default_factory=dict)
|
|
45
|
+
contract: dict[str, Any] = Field(default_factory=dict)
|
|
46
|
+
metadata: dict[str, Any] = Field(default_factory=dict)
|
|
47
|
+
storage_ref: str | None = None
|
|
48
|
+
# EXPERIMENTAL: opaque type-scoped governance
|
|
49
|
+
# reference recorded at creation from the configured governance. Grants nothing.
|
|
50
|
+
governance_reference: str | None = None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class GovernanceEvent(BaseModel):
|
|
54
|
+
"""Append-only event in object history."""
|
|
55
|
+
|
|
56
|
+
event_id: str = Field(default_factory=lambda: str(uuid4()))
|
|
57
|
+
timestamp: datetime = Field(default_factory=lambda: datetime.now(UTC))
|
|
58
|
+
object_id: str
|
|
59
|
+
object_type: str
|
|
60
|
+
type_version: str | None = None
|
|
61
|
+
actor_id: str
|
|
62
|
+
actor_type: str
|
|
63
|
+
action: str
|
|
64
|
+
decision: Decision
|
|
65
|
+
event_type: str
|
|
66
|
+
previous_state: str | None = None
|
|
67
|
+
new_state: str | None = None
|
|
68
|
+
reason: str = ""
|
|
69
|
+
object_version: int = 1
|
|
70
|
+
details: dict[str, Any] = Field(default_factory=dict)
|
|
71
|
+
# EXPERIMENTAL: per-object accepted-history
|
|
72
|
+
# position assigned by the store when an accepted canonical change is
|
|
73
|
+
# appended. None for every other row (reads, denials, conflicts, legacy rows).
|
|
74
|
+
history_position: int | None = None
|
|
75
|
+
# EXPERIMENTAL: False only on a row
|
|
76
|
+
# restored by interchange import whose artifact carried no acceptance
|
|
77
|
+
# instant; ``timestamp`` is then a placeholder, not evidence.
|
|
78
|
+
accepted_at_recorded: bool = True
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class ValidationCheck(BaseModel):
|
|
82
|
+
name: str
|
|
83
|
+
passed: bool
|
|
84
|
+
message: str | None = None
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class CommandResult(BaseModel):
|
|
88
|
+
decision: Decision
|
|
89
|
+
outcome_category: str | None = None
|
|
90
|
+
reason: str = ""
|
|
91
|
+
deny_reason: str | None = None
|
|
92
|
+
conflict_reason: str | None = None
|
|
93
|
+
expected_version: int | None = None
|
|
94
|
+
actual_version: int | None = None
|
|
95
|
+
action: str = ""
|
|
96
|
+
object_id: str | None = None
|
|
97
|
+
previous_state: str | None = None
|
|
98
|
+
new_state: str | None = None
|
|
99
|
+
object_version: int | None = None
|
|
100
|
+
events: list[GovernanceEvent] = Field(default_factory=list)
|
|
101
|
+
validation_checks: list[ValidationCheck] = Field(default_factory=list)
|
|
102
|
+
data: dict[str, Any] = Field(default_factory=dict)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class Actor(BaseModel):
|
|
106
|
+
id: str
|
|
107
|
+
type: ActorType
|
|
108
|
+
capabilities: list[str] = Field(default_factory=list)
|
|
109
|
+
constraints: list[str] = Field(default_factory=list)
|
|
110
|
+
display_name: str | None = None
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2026 Brafford Labs, LLC
|
|
3
|
+
"""Traversal result models."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from pydantic import BaseModel, Field
|
|
8
|
+
|
|
9
|
+
from governed_objects.domain.models import GovernedObject
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class TraversalStep(BaseModel):
|
|
13
|
+
"""One hop in a relationship path from the traversal start."""
|
|
14
|
+
|
|
15
|
+
relation: str
|
|
16
|
+
from_id: str
|
|
17
|
+
to_id: str
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class TraversalResult(BaseModel):
|
|
21
|
+
"""A governed object reached during authorized graph traversal."""
|
|
22
|
+
|
|
23
|
+
object: GovernedObject
|
|
24
|
+
depth: int
|
|
25
|
+
path: list[TraversalStep] = Field(default_factory=list)
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2026 Brafford Labs, LLC
|
|
3
|
+
"""Accepted-history classification and single-lineage invariants.
|
|
4
|
+
|
|
5
|
+
A stored row is an accepted revision record exactly when it carries a recorded
|
|
6
|
+
history position (``SQLiteStore.list_accepted_for_object``). The exporter and
|
|
7
|
+
the replayer both read accepted history through that query. Unpositioned rows
|
|
8
|
+
are operational audit: denials, conflicts, refusals, provider failures and
|
|
9
|
+
reads. An unpositioned ALLOW row other than a read is a record written before
|
|
10
|
+
positions existed; an object holding one has legacy history.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from itertools import groupby
|
|
16
|
+
|
|
17
|
+
from governed_objects.domain.models import Decision, GovernanceEvent
|
|
18
|
+
from governed_objects.persistence.sqlite import SQLiteStore
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def is_accepted_revision(row: GovernanceEvent) -> bool:
|
|
22
|
+
return row.history_position is not None
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def is_read_audit(row: GovernanceEvent) -> bool:
|
|
26
|
+
return row.action == "read" or row.event_type == "object.read"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def is_legacy_accepted_row(row: GovernanceEvent) -> bool:
|
|
30
|
+
return (
|
|
31
|
+
not is_accepted_revision(row)
|
|
32
|
+
and row.decision == Decision.ALLOW
|
|
33
|
+
and not is_read_audit(row)
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def has_legacy_history(store: SQLiteStore, object_id: str) -> bool:
|
|
38
|
+
return any(is_legacy_accepted_row(r) for r in store.list_for_object(object_id))
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def lineage_violations(store: SQLiteStore, object_id: str) -> list[str]:
|
|
42
|
+
"""Violations of the single accepted lineage for one object.
|
|
43
|
+
|
|
44
|
+
Each positioned record is one accepted revision, so every record's
|
|
45
|
+
resulting Object Version must be distinct (adjacent records sharing a
|
|
46
|
+
token are a reused token, not one revision). Positions must be 1..n, and
|
|
47
|
+
the current Object Version must be the last revision's token.
|
|
48
|
+
"""
|
|
49
|
+
violations: list[str] = []
|
|
50
|
+
obj = store.get(object_id)
|
|
51
|
+
rows = store.list_accepted_for_object(object_id)
|
|
52
|
+
positions = [r.history_position for r in rows]
|
|
53
|
+
if positions != list(range(1, len(rows) + 1)):
|
|
54
|
+
violations.append(f"positions are not 1..n: {positions}")
|
|
55
|
+
tokens = [r.object_version for r in rows]
|
|
56
|
+
for token, group in groupby(sorted(tokens)):
|
|
57
|
+
count = len(list(group))
|
|
58
|
+
if count > 1:
|
|
59
|
+
violations.append(f"Object Version {token} names {count} accepted revisions")
|
|
60
|
+
if rows and rows[0].action != "create":
|
|
61
|
+
violations.append(f"first accepted record is {rows[0].action!r}, not create")
|
|
62
|
+
if obj is not None:
|
|
63
|
+
if not tokens:
|
|
64
|
+
violations.append(f"current Object Version {obj.version} has no accepted revision")
|
|
65
|
+
elif obj.version != tokens[-1]:
|
|
66
|
+
violations.append(
|
|
67
|
+
f"current Object Version {obj.version} is not the last revision's {tokens[-1]}"
|
|
68
|
+
)
|
|
69
|
+
if has_legacy_history(store, object_id):
|
|
70
|
+
violations.append("unpositioned accepted rows present (legacy history)")
|
|
71
|
+
return violations
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2026 Brafford Labs, LLC
|
|
3
|
+
"""DelegatedMandate event reducer."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from governed_objects.domain.models import GovernedObject, GovernanceEvent
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class MandateEventReducer:
|
|
11
|
+
def reduce(
|
|
12
|
+
self,
|
|
13
|
+
obj: GovernedObject | None,
|
|
14
|
+
event: GovernanceEvent,
|
|
15
|
+
) -> GovernedObject | None:
|
|
16
|
+
if event.action == "create":
|
|
17
|
+
return GovernedObject(
|
|
18
|
+
id=event.object_id,
|
|
19
|
+
type="DelegatedMandate",
|
|
20
|
+
type_version=event.type_version or "1",
|
|
21
|
+
version=event.object_version,
|
|
22
|
+
state=event.new_state or "draft",
|
|
23
|
+
data=event.details.get("data", {}),
|
|
24
|
+
)
|
|
25
|
+
if obj is None:
|
|
26
|
+
return None
|
|
27
|
+
if event.action in {"activate", "revoke"}:
|
|
28
|
+
return obj.model_copy(
|
|
29
|
+
update={"state": event.new_state or obj.state, "version": event.object_version}
|
|
30
|
+
)
|
|
31
|
+
return obj
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2026 Brafford Labs, LLC
|
|
3
|
+
"""Event replay — reconstruct canonical state from event history."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from governed_objects.domain.models import Decision, GovernedObject, GovernanceEvent, Relationship
|
|
8
|
+
from governed_objects.events.lineage import has_legacy_history, is_read_audit
|
|
9
|
+
from governed_objects.persistence.sqlite import SQLiteStore
|
|
10
|
+
from governed_objects.relationships.canonical import CANONICAL_SOURCE, canonical_relationship
|
|
11
|
+
from governed_objects.types.extensions import TypeExtensionRegistry
|
|
12
|
+
from governed_objects.types.registry import TypeRegistry
|
|
13
|
+
from governed_objects.types.schema import ObjectTypeDefinition
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ReplayRefused(Exception):
|
|
17
|
+
"""Content-free refusal of unestablished reconstruction support/binding."""
|
|
18
|
+
|
|
19
|
+
code = "REPLAY_NOT_SUPPORTED"
|
|
20
|
+
|
|
21
|
+
def __init__(self) -> None:
|
|
22
|
+
super().__init__("reconstruction unavailable")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def bound_type_definition(
|
|
26
|
+
types: TypeRegistry | None, obj: GovernedObject
|
|
27
|
+
) -> ObjectTypeDefinition | None:
|
|
28
|
+
"""Resolve an explicit nonempty binding, never replacement semantics."""
|
|
29
|
+
if types is None or not obj.type or not obj.type_version:
|
|
30
|
+
return None
|
|
31
|
+
try:
|
|
32
|
+
definition = types.get(obj.type)
|
|
33
|
+
except KeyError:
|
|
34
|
+
return None
|
|
35
|
+
if (definition.kind, definition.type_version) != (obj.type, obj.type_version):
|
|
36
|
+
return None
|
|
37
|
+
return definition
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class LegacyHistoryRefused(Exception):
|
|
41
|
+
"""Replay of history without recorded positions was not explicitly requested."""
|
|
42
|
+
|
|
43
|
+
def __init__(self, object_id: str) -> None:
|
|
44
|
+
super().__init__(f"{object_id}: history has unpositioned accepted rows (legacy)")
|
|
45
|
+
self.object_id = object_id
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class EventReplayer:
|
|
49
|
+
"""Reconstruct canonical state from accepted revisions using type reducers.
|
|
50
|
+
|
|
51
|
+
Canonical mode (default) consumes only positioned accepted records, in
|
|
52
|
+
recorded position order, and restores each revision's recorded Object
|
|
53
|
+
Version. Objects whose history contains unpositioned accepted rows are
|
|
54
|
+
refused unless ``allow_legacy=True``. Legacy mode orders those rows by
|
|
55
|
+
timestamp and is not Draft 2.2-canonical replay.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
def __init__(
|
|
59
|
+
self,
|
|
60
|
+
store: SQLiteStore,
|
|
61
|
+
extensions: TypeExtensionRegistry,
|
|
62
|
+
type_registry: TypeRegistry | None = None,
|
|
63
|
+
) -> None:
|
|
64
|
+
if extensions is None:
|
|
65
|
+
raise ValueError("replay requires non-None extensions")
|
|
66
|
+
self._store = store
|
|
67
|
+
self._extensions = extensions
|
|
68
|
+
self._types = type_registry
|
|
69
|
+
|
|
70
|
+
def reconstruct(self, object_id: str, *, allow_legacy: bool = False) -> GovernedObject | None:
|
|
71
|
+
stored = self._store.get(object_id)
|
|
72
|
+
if stored is None:
|
|
73
|
+
return None
|
|
74
|
+
|
|
75
|
+
events = self._admitted_events(stored, allow_legacy)
|
|
76
|
+
if not events:
|
|
77
|
+
return stored
|
|
78
|
+
|
|
79
|
+
reducer = self._extensions.reducer_for(stored.type)
|
|
80
|
+
type_version = stored.type_version
|
|
81
|
+
|
|
82
|
+
if reducer is None:
|
|
83
|
+
return stored.model_copy(update={"type_version": type_version})
|
|
84
|
+
|
|
85
|
+
state = reducer.reduce(None, events[0])
|
|
86
|
+
if state is None:
|
|
87
|
+
return stored.model_copy(update={"type_version": type_version})
|
|
88
|
+
self._check_result(stored, state)
|
|
89
|
+
|
|
90
|
+
version = events[0].object_version
|
|
91
|
+
current_state = state.state
|
|
92
|
+
data = dict(state.data)
|
|
93
|
+
|
|
94
|
+
for event in events[1:]:
|
|
95
|
+
current_obj = GovernedObject(
|
|
96
|
+
id=object_id,
|
|
97
|
+
type=stored.type,
|
|
98
|
+
type_version=type_version,
|
|
99
|
+
version=version,
|
|
100
|
+
state=current_state,
|
|
101
|
+
data=data,
|
|
102
|
+
)
|
|
103
|
+
version = event.object_version
|
|
104
|
+
result = reducer.reduce(current_obj, event)
|
|
105
|
+
if result is None:
|
|
106
|
+
continue
|
|
107
|
+
self._check_result(stored, result)
|
|
108
|
+
current_state = result.state
|
|
109
|
+
data = result.data
|
|
110
|
+
|
|
111
|
+
return GovernedObject(
|
|
112
|
+
id=object_id,
|
|
113
|
+
type=stored.type,
|
|
114
|
+
type_version=type_version,
|
|
115
|
+
version=version,
|
|
116
|
+
state=current_state,
|
|
117
|
+
data=data,
|
|
118
|
+
metadata=stored.metadata,
|
|
119
|
+
governance_reference=stored.governance_reference,
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
def reconstruct_relationships(
|
|
123
|
+
self, object_id: str, *, allow_legacy: bool = False
|
|
124
|
+
) -> list[Relationship]:
|
|
125
|
+
stored = self._store.get(object_id)
|
|
126
|
+
if stored is None:
|
|
127
|
+
return []
|
|
128
|
+
events = self._admitted_events(stored, allow_legacy)
|
|
129
|
+
rel_index: dict[tuple[str, str], Relationship] = {}
|
|
130
|
+
for event in events:
|
|
131
|
+
self._apply_relationship_event(object_id, event, rel_index)
|
|
132
|
+
return list(rel_index.values())
|
|
133
|
+
|
|
134
|
+
def _admitted_events(
|
|
135
|
+
self, stored: GovernedObject, allow_legacy: bool
|
|
136
|
+
) -> list[GovernanceEvent]:
|
|
137
|
+
if not self.check_type_version_supported(stored):
|
|
138
|
+
raise ReplayRefused()
|
|
139
|
+
events = self._accepted_events(stored.id, allow_legacy)
|
|
140
|
+
# Preflight the whole selection before invoking any reducer or edge fold.
|
|
141
|
+
for event in events:
|
|
142
|
+
if (event.object_id, event.object_type, event.type_version) != (
|
|
143
|
+
stored.id, stored.type, stored.type_version
|
|
144
|
+
):
|
|
145
|
+
raise ReplayRefused()
|
|
146
|
+
if event.action == "create" and any(
|
|
147
|
+
rel.get("source_id", stored.id) != stored.id
|
|
148
|
+
for rel in event.details.get("relationships", [])
|
|
149
|
+
):
|
|
150
|
+
raise ReplayRefused()
|
|
151
|
+
return events
|
|
152
|
+
|
|
153
|
+
@staticmethod
|
|
154
|
+
def _check_result(stored: GovernedObject, result: GovernedObject) -> None:
|
|
155
|
+
if (result.id, result.type) != (stored.id, stored.type) or (
|
|
156
|
+
"type_version" in result.model_fields_set
|
|
157
|
+
and result.type_version is not None
|
|
158
|
+
and result.type_version != stored.type_version
|
|
159
|
+
):
|
|
160
|
+
raise ReplayRefused()
|
|
161
|
+
|
|
162
|
+
def is_legacy(self, object_id: str) -> bool:
|
|
163
|
+
return has_legacy_history(self._store, object_id)
|
|
164
|
+
|
|
165
|
+
def _accepted_events(self, object_id: str, allow_legacy: bool) -> list[GovernanceEvent]:
|
|
166
|
+
if not self.is_legacy(object_id):
|
|
167
|
+
return self._store.list_accepted_for_object(object_id)
|
|
168
|
+
if not allow_legacy:
|
|
169
|
+
raise LegacyHistoryRefused(object_id)
|
|
170
|
+
return [
|
|
171
|
+
e for e in self._store.list_for_object(object_id)
|
|
172
|
+
if e.decision == Decision.ALLOW and not is_read_audit(e)
|
|
173
|
+
]
|
|
174
|
+
|
|
175
|
+
@staticmethod
|
|
176
|
+
def _apply_relationship_event(
|
|
177
|
+
object_id: str,
|
|
178
|
+
event: GovernanceEvent,
|
|
179
|
+
rel_index: dict[tuple[str, str], Relationship],
|
|
180
|
+
) -> None:
|
|
181
|
+
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
|
|
190
|
+
return
|
|
191
|
+
|
|
192
|
+
if event.action == "add_relationship":
|
|
193
|
+
details = event.details
|
|
194
|
+
rel = canonical_relationship(
|
|
195
|
+
object_id,
|
|
196
|
+
details["relation"],
|
|
197
|
+
details["target_id"],
|
|
198
|
+
target_type=details.get("target_type"),
|
|
199
|
+
)
|
|
200
|
+
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
|
+
def check_type_version_supported(self, obj: GovernedObject) -> bool:
|
|
208
|
+
return bound_type_definition(self._types, obj) is not None
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2026 Brafford Labs, LLC
|
|
3
|
+
"""SQLite-backed durable idempotency and command attempt tracking."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
from datetime import UTC, datetime
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from governed_objects.domain.models import CommandResult, Decision
|
|
12
|
+
from governed_objects.persistence.sqlite import SQLiteStore, _connection_locked
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class IdempotencyStore:
|
|
16
|
+
"""Persists idempotent command results and attempt metadata."""
|
|
17
|
+
|
|
18
|
+
def __init__(self, store: SQLiteStore) -> None:
|
|
19
|
+
self._store = store
|
|
20
|
+
self._connection_guard = store._connection_guard
|
|
21
|
+
self._ensure_schema()
|
|
22
|
+
|
|
23
|
+
@_connection_locked
|
|
24
|
+
def _ensure_schema(self) -> None:
|
|
25
|
+
self._store._require_autonomous()
|
|
26
|
+
self._store._conn.executescript(
|
|
27
|
+
"""
|
|
28
|
+
CREATE TABLE IF NOT EXISTS command_attempts (
|
|
29
|
+
command_id TEXT NOT NULL,
|
|
30
|
+
object_id TEXT NOT NULL,
|
|
31
|
+
idempotency_key TEXT NOT NULL,
|
|
32
|
+
correlation_id TEXT,
|
|
33
|
+
status TEXT NOT NULL,
|
|
34
|
+
provider_outcome TEXT,
|
|
35
|
+
result_json TEXT,
|
|
36
|
+
created_at TEXT NOT NULL,
|
|
37
|
+
updated_at TEXT NOT NULL,
|
|
38
|
+
PRIMARY KEY (object_id, idempotency_key)
|
|
39
|
+
);
|
|
40
|
+
CREATE INDEX IF NOT EXISTS idx_command_attempts_command
|
|
41
|
+
ON command_attempts(command_id);
|
|
42
|
+
"""
|
|
43
|
+
)
|
|
44
|
+
self._store._conn.commit()
|
|
45
|
+
|
|
46
|
+
@_connection_locked
|
|
47
|
+
def get(self, object_id: str, idempotency_key: str) -> CommandResult | None:
|
|
48
|
+
row = self._store._conn.execute(
|
|
49
|
+
"""
|
|
50
|
+
SELECT result_json, status FROM command_attempts
|
|
51
|
+
WHERE object_id = ? AND idempotency_key = ?
|
|
52
|
+
""",
|
|
53
|
+
(object_id, idempotency_key),
|
|
54
|
+
).fetchone()
|
|
55
|
+
if row is None or not row["result_json"]:
|
|
56
|
+
return None
|
|
57
|
+
if row["status"] != "succeeded":
|
|
58
|
+
return None
|
|
59
|
+
return _result_from_json(row["result_json"])
|
|
60
|
+
|
|
61
|
+
@_connection_locked
|
|
62
|
+
def put(
|
|
63
|
+
self,
|
|
64
|
+
object_id: str,
|
|
65
|
+
idempotency_key: str,
|
|
66
|
+
result: CommandResult,
|
|
67
|
+
*,
|
|
68
|
+
command_id: str | None = None,
|
|
69
|
+
correlation_id: str | None = None,
|
|
70
|
+
) -> None:
|
|
71
|
+
now = datetime.now(UTC).isoformat()
|
|
72
|
+
self._store._conn.execute(
|
|
73
|
+
"""
|
|
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
|
|
84
|
+
""",
|
|
85
|
+
(
|
|
86
|
+
command_id or "",
|
|
87
|
+
object_id,
|
|
88
|
+
idempotency_key,
|
|
89
|
+
correlation_id,
|
|
90
|
+
json.dumps(_result_to_json(result)),
|
|
91
|
+
now,
|
|
92
|
+
now,
|
|
93
|
+
),
|
|
94
|
+
)
|
|
95
|
+
self._store._commit_if_autonomous()
|
|
96
|
+
|
|
97
|
+
@_connection_locked
|
|
98
|
+
def record_attempt(
|
|
99
|
+
self,
|
|
100
|
+
*,
|
|
101
|
+
command_id: str,
|
|
102
|
+
object_id: str,
|
|
103
|
+
idempotency_key: str,
|
|
104
|
+
correlation_id: str | None,
|
|
105
|
+
status: str,
|
|
106
|
+
provider_outcome: str | None = None,
|
|
107
|
+
) -> None:
|
|
108
|
+
now = datetime.now(UTC).isoformat()
|
|
109
|
+
self._store._conn.execute(
|
|
110
|
+
"""
|
|
111
|
+
INSERT INTO command_attempts (
|
|
112
|
+
command_id, object_id, idempotency_key, correlation_id,
|
|
113
|
+
status, provider_outcome, result_json, created_at, updated_at
|
|
114
|
+
) VALUES (?, ?, ?, ?, ?, ?, NULL, ?, ?)
|
|
115
|
+
ON CONFLICT(object_id, idempotency_key) DO UPDATE SET
|
|
116
|
+
command_id=excluded.command_id,
|
|
117
|
+
correlation_id=excluded.correlation_id,
|
|
118
|
+
status=excluded.status,
|
|
119
|
+
provider_outcome=excluded.provider_outcome,
|
|
120
|
+
updated_at=excluded.updated_at
|
|
121
|
+
""",
|
|
122
|
+
(
|
|
123
|
+
command_id,
|
|
124
|
+
object_id,
|
|
125
|
+
idempotency_key,
|
|
126
|
+
correlation_id,
|
|
127
|
+
status,
|
|
128
|
+
provider_outcome,
|
|
129
|
+
now,
|
|
130
|
+
now,
|
|
131
|
+
),
|
|
132
|
+
)
|
|
133
|
+
self._store._commit_if_autonomous()
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _result_to_json(result: CommandResult) -> dict[str, Any]:
|
|
137
|
+
return {
|
|
138
|
+
"decision": result.decision.value,
|
|
139
|
+
"reason": result.reason,
|
|
140
|
+
"action": result.action,
|
|
141
|
+
"object_id": result.object_id,
|
|
142
|
+
"previous_state": result.previous_state,
|
|
143
|
+
"new_state": result.new_state,
|
|
144
|
+
"object_version": result.object_version,
|
|
145
|
+
"data": result.data,
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _result_from_json(raw: str) -> CommandResult:
|
|
150
|
+
data = json.loads(raw)
|
|
151
|
+
return CommandResult(
|
|
152
|
+
decision=Decision(data["decision"]),
|
|
153
|
+
reason=data.get("reason", ""),
|
|
154
|
+
action=data.get("action", ""),
|
|
155
|
+
object_id=data.get("object_id"),
|
|
156
|
+
previous_state=data.get("previous_state"),
|
|
157
|
+
new_state=data.get("new_state"),
|
|
158
|
+
object_version=data.get("object_version"),
|
|
159
|
+
data=data.get("data"),
|
|
160
|
+
)
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2026 Brafford Labs, LLC
|
|
3
|
+
"""Provisional Core interchange (EXPERIMENTAL).
|
|
4
|
+
|
|
5
|
+
EXPERIMENTAL. NON-NORMATIVE. NOT A GOVERNED OBJECT WIRE STANDARD.
|
|
6
|
+
NOT A DRAFT 2.1 OR DRAFT 2.2 REQUIREMENT.
|
|
7
|
+
|
|
8
|
+
Export and new-target import of the frozen provisional
|
|
9
|
+
artifacts of the interchange experiment: ``go-core-interchange-experiment/1``
|
|
10
|
+
(Draft 2.1 content only) and its successor ``go-core-interchange-experiment/2``
|
|
11
|
+
(Draft 2.2 content only). Export
|
|
12
|
+
writes the successor; import restores either. Import restores accepted history
|
|
13
|
+
into an empty target; it is not sync, merge, or replication.
|
|
14
|
+
|
|
15
|
+
The artifact constants below are serialization constants of those artifact
|
|
16
|
+
revisions. Each artifact revision carries exactly one specification revision,
|
|
17
|
+
so the pair is part of artifact validity; the runtime's supported
|
|
18
|
+
specification revisions are a capability, not an artifact member.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
ARTIFACT_REVISION_V1 = "go-core-interchange-experiment/1"
|
|
22
|
+
ARTIFACT_STATUS_V1 = (
|
|
23
|
+
"EXPERIMENTAL; NON-NORMATIVE; NOT A GOVERNED OBJECT WIRE STANDARD; "
|
|
24
|
+
"NOT A DRAFT 2.1 REQUIREMENT"
|
|
25
|
+
)
|
|
26
|
+
ARTIFACT_REVISION_V2 = "go-core-interchange-experiment/2"
|
|
27
|
+
ARTIFACT_STATUS_V2 = (
|
|
28
|
+
"EXPERIMENTAL; NON-NORMATIVE; NOT A GOVERNED OBJECT WIRE STANDARD; "
|
|
29
|
+
"NOT A DRAFT 2.2 REQUIREMENT"
|
|
30
|
+
)
|
|
31
|
+
EXPORT_SPEC_REVISION = "v0alpha1/draft2.2"
|
|
32
|
+
# Public name for the Draft 2.1 revision the importer restores (artifact v1); it
|
|
33
|
+
# stays a single revision string, not the set of input revisions.
|
|
34
|
+
SPEC_REVISION = "v0alpha1/draft2.1"
|
|
35
|
+
# artifact revision -> (status marker, the one specification revision it carries)
|
|
36
|
+
ARTIFACT_CONTRACTS = {
|
|
37
|
+
ARTIFACT_REVISION_V1: (ARTIFACT_STATUS_V1, SPEC_REVISION),
|
|
38
|
+
ARTIFACT_REVISION_V2: (ARTIFACT_STATUS_V2, EXPORT_SPEC_REVISION),
|
|
39
|
+
}
|
|
40
|
+
EXPORT_ARTIFACT_REVISION = ARTIFACT_REVISION_V2
|
|
41
|
+
IMPORT_ARTIFACT_REVISIONS = tuple(ARTIFACT_CONTRACTS)
|
|
42
|
+
IMPORT_SPEC_REVISIONS = tuple(spec for _, spec in ARTIFACT_CONTRACTS.values())
|
|
43
|
+
HISTORY_COMPLETENESS = "complete-from-creation"
|
|
44
|
+
HISTORY_POSITION_MODEL = "explicit-per-object-contiguous-from-1"
|
|
45
|
+
GOVERNANCE_REFERENCE_MODEL = "type-scoped"
|
|
46
|
+
|
|
47
|
+
EXPORT_ORDER_INDETERMINATE = "EXPORT_ORDER_INDETERMINATE"
|
|
48
|
+
EXPORT_HISTORY_UNCLASSIFIABLE = "EXPORT_HISTORY_UNCLASSIFIABLE"
|
|
49
|
+
UNSUPPORTED_SEMANTIC_FEATURE = "UNSUPPORTED_SEMANTIC_FEATURE"
|