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,76 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2026 Brafford Labs, LLC
|
|
3
|
+
"""Draft 2.2 Portable Restoration Continuity claim of this runtime (EXPERIMENTAL).
|
|
4
|
+
|
|
5
|
+
A semantic declaration of what the native export
|
|
6
|
+
(:mod:`governed_objects.interchange.export`) and import
|
|
7
|
+
(:mod:`governed_objects.interchange.importer`) paths do, for PRC-CLAIM-001,
|
|
8
|
+
PRC-CAP-001, PRC-EVID-001, and PRC-HANDOFF-001. It is not an encoding or a
|
|
9
|
+
discovery protocol. Type bindings are read from the runtime's type registry;
|
|
10
|
+
every other item names the constant or behavior that the native paths enforce.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from typing import TYPE_CHECKING, Any
|
|
16
|
+
|
|
17
|
+
from governed_objects.interchange import EXPORT_SPEC_REVISION, IMPORT_SPEC_REVISIONS
|
|
18
|
+
from governed_objects.interchange.importer import NATIVE_TOKEN_GRAMMAR, REQUIRED_PROVENANCE
|
|
19
|
+
from governed_objects.interchange.types import portable_type_of
|
|
20
|
+
|
|
21
|
+
if TYPE_CHECKING:
|
|
22
|
+
from governed_objects.types.registry import TypeRegistry
|
|
23
|
+
|
|
24
|
+
PRC_PROFILE = "Portable Restoration Continuity"
|
|
25
|
+
PRC_ROLES = ("exporter", "restorer")
|
|
26
|
+
EFFECT_EQUIVALENT = "effect-equivalent"
|
|
27
|
+
TIME_PRECISION = "microsecond"
|
|
28
|
+
# Carried provenance the importer does not retain (PRC-EVID-001); export never
|
|
29
|
+
# presents a value for it.
|
|
30
|
+
PROVENANCE_NOT_RETAINED = (
|
|
31
|
+
"source_event_id",
|
|
32
|
+
"action, unless it names the native action that encodes the entry's effect",
|
|
33
|
+
"relationship target_type and metadata",
|
|
34
|
+
)
|
|
35
|
+
HANDOFF = {
|
|
36
|
+
"model": "operator-procedure",
|
|
37
|
+
"declaration": (
|
|
38
|
+
"For each restored identity, the operator ensures that the source accepts no canonical "
|
|
39
|
+
"change for the identity after the revision carried in the portable representation, for "
|
|
40
|
+
"example by retiring the source or making it read-only for the identity, so that the "
|
|
41
|
+
"source's and this runtime's accepted revisions form one lineage."
|
|
42
|
+
),
|
|
43
|
+
"enforced_by_runtime": False,
|
|
44
|
+
"verified_by_runtime": False,
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def supported_type_bindings(types: TypeRegistry) -> list[str]:
|
|
49
|
+
"""``identity@version`` of every portable type configured in ``types``:
|
|
50
|
+
the bindings the importer's Type Identity and Type Version checks accept."""
|
|
51
|
+
bindings = []
|
|
52
|
+
for kind in types.list_types():
|
|
53
|
+
type_def = types.get(kind)
|
|
54
|
+
if portable_type_of(type_def) is not None:
|
|
55
|
+
bindings.append(f"{type_def.kind}@{type_def.type_version}")
|
|
56
|
+
return sorted(bindings)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def prc_declaration(types: TypeRegistry) -> dict[str, Any]:
|
|
60
|
+
return {
|
|
61
|
+
"profile": PRC_PROFILE,
|
|
62
|
+
"roles": list(PRC_ROLES),
|
|
63
|
+
"export_spec_revision": EXPORT_SPEC_REVISION,
|
|
64
|
+
"capabilities": {
|
|
65
|
+
"spec_revisions": list(IMPORT_SPEC_REVISIONS),
|
|
66
|
+
"type_bindings": supported_type_bindings(types),
|
|
67
|
+
"object_version_forms": NATIVE_TOKEN_GRAMMAR,
|
|
68
|
+
"baseline_relationships": True,
|
|
69
|
+
"time_precision": TIME_PRECISION,
|
|
70
|
+
"required_provenance": list(REQUIRED_PROVENANCE),
|
|
71
|
+
"evidence_level": EFFECT_EQUIVALENT,
|
|
72
|
+
"provenance_not_retained": list(PROVENANCE_NOT_RETAINED),
|
|
73
|
+
"all_or_nothing": True,
|
|
74
|
+
},
|
|
75
|
+
"handoff": dict(HANDOFF),
|
|
76
|
+
}
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2026 Brafford Labs, LLC
|
|
3
|
+
"""Declarative portable Core types (EXPERIMENTAL).
|
|
4
|
+
|
|
5
|
+
Builds native ``ObjectTypeDefinition`` values from a portable type definition
|
|
6
|
+
(the shape of the experiment's portable type-definition JSON)
|
|
7
|
+
so the fixture runs under its exact Type Identity and Type Version strings,
|
|
8
|
+
with no type mapping table.
|
|
9
|
+
|
|
10
|
+
Native mapping:
|
|
11
|
+
|
|
12
|
+
- non-lifecycle state fields become required string fields in ``data``;
|
|
13
|
+
- the lifecycle field (kind ``lifecycle``) is the native ``state``;
|
|
14
|
+
- a lifecycle action becomes a native transition from each declared source
|
|
15
|
+
state; a state action becomes a self-transition in every state and is
|
|
16
|
+
applied by :class:`PortableTypeAdapter`;
|
|
17
|
+
- a type without a lifecycle gets one native bookkeeping state,
|
|
18
|
+
``NO_LIFECYCLE_STATE``. It is not canonical state and is never exported.
|
|
19
|
+
|
|
20
|
+
The portable definition is kept in ``extra[PORTABLE_TYPE_KEY]``; the exporter
|
|
21
|
+
reads the lifecycle field and action kinds from there.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import re
|
|
27
|
+
from collections.abc import Collection, Mapping
|
|
28
|
+
from typing import Any
|
|
29
|
+
|
|
30
|
+
from governed_objects.adapters.base import TypeAdapter
|
|
31
|
+
from governed_objects.adapters.context import AdapterContext, AdapterExecuteResult, AdapterFailure
|
|
32
|
+
from governed_objects.domain.command import Command
|
|
33
|
+
from governed_objects.domain.models import Actor, GovernedObject, ValidationCheck
|
|
34
|
+
from governed_objects.types.registry import TypeRegistry
|
|
35
|
+
from governed_objects.types.schema import ActionDef, FieldSchema, ObjectTypeDefinition, StateDef
|
|
36
|
+
from governed_objects.observations.validation import CandidateImage, CandidateMode, CandidateVerdict
|
|
37
|
+
|
|
38
|
+
PORTABLE_TYPE_KEY = "interchange_portable_type"
|
|
39
|
+
NO_LIFECYCLE_STATE = "active"
|
|
40
|
+
|
|
41
|
+
FIELD_STRING = "string"
|
|
42
|
+
FIELD_DECIMAL = "decimal-string"
|
|
43
|
+
FIELD_LIFECYCLE = "lifecycle"
|
|
44
|
+
ACTION_STATE = "state"
|
|
45
|
+
ACTION_LIFECYCLE = "lifecycle"
|
|
46
|
+
|
|
47
|
+
REQUIREMENT_KEYS = ("read", "create", "state", "lifecycle", "relationship_add", "relationship_remove")
|
|
48
|
+
|
|
49
|
+
_DECIMAL = re.compile(r"^-?[0-9]+(\.[0-9]+)?$")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class PortableTypeError(ValueError):
|
|
53
|
+
pass
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def lifecycle_field(portable: Mapping[str, Any]) -> str | None:
|
|
57
|
+
for name, kind in portable["state_fields"].items():
|
|
58
|
+
if kind == FIELD_LIFECYCLE:
|
|
59
|
+
return name
|
|
60
|
+
return None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def portable_type_of(type_def: ObjectTypeDefinition) -> Mapping[str, Any] | None:
|
|
64
|
+
return type_def.extra.get(PORTABLE_TYPE_KEY)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def build_type_definition(
|
|
68
|
+
portable: Mapping[str, Any],
|
|
69
|
+
requirements: Mapping[str, list[str]],
|
|
70
|
+
*,
|
|
71
|
+
open_keys: Collection[str] = (),
|
|
72
|
+
) -> ObjectTypeDefinition:
|
|
73
|
+
"""``requirements`` holds the capability requirements selected by the
|
|
74
|
+
local governance for this binding, keyed by ``REQUIREMENT_KEYS``.
|
|
75
|
+
|
|
76
|
+
An empty requirement list for a key denies that action/read to every
|
|
77
|
+
actor, the same as the native runtime default. ``open_keys`` names the
|
|
78
|
+
``REQUIREMENT_KEYS`` local governance has deliberately chosen to leave
|
|
79
|
+
open to every actor regardless of declared capabilities; pass a key
|
|
80
|
+
there only when openness is the intended behavior, not merely because
|
|
81
|
+
its requirement list happens to be empty."""
|
|
82
|
+
missing = [k for k in REQUIREMENT_KEYS if k not in requirements]
|
|
83
|
+
if missing:
|
|
84
|
+
raise PortableTypeError(f"governance requirements missing {missing}")
|
|
85
|
+
fields = dict(portable["state_fields"])
|
|
86
|
+
for name, kind in fields.items():
|
|
87
|
+
if kind not in (FIELD_STRING, FIELD_DECIMAL, FIELD_LIFECYCLE):
|
|
88
|
+
raise PortableTypeError(f"unsupported field kind {kind!r} for {name!r}")
|
|
89
|
+
lc_fields = [n for n, k in fields.items() if k == FIELD_LIFECYCLE]
|
|
90
|
+
if len(lc_fields) > 1:
|
|
91
|
+
raise PortableTypeError("more than one lifecycle field")
|
|
92
|
+
actions = dict(portable.get("actions", {}))
|
|
93
|
+
for reserved in ("create", "read", "add_relationship", "remove_relationship"):
|
|
94
|
+
if reserved in actions:
|
|
95
|
+
raise PortableTypeError(f"type action {reserved!r} collides with a runtime operation")
|
|
96
|
+
|
|
97
|
+
if lc_fields:
|
|
98
|
+
lifecycle = portable["lifecycle"]
|
|
99
|
+
state_names = list(lifecycle["states"])
|
|
100
|
+
permitted = {(a, b) for a, b in lifecycle["transitions"]}
|
|
101
|
+
else:
|
|
102
|
+
state_names = [NO_LIFECYCLE_STATE]
|
|
103
|
+
permitted = set()
|
|
104
|
+
|
|
105
|
+
def _action_def(requirement_key: str) -> ActionDef:
|
|
106
|
+
"""An empty requirement list denies, unless ``requirement_key`` is
|
|
107
|
+
named in ``open_keys``, in which case the action is explicitly
|
|
108
|
+
opened to every actor."""
|
|
109
|
+
caps = list(requirements[requirement_key])
|
|
110
|
+
return ActionDef(requires=caps, open=requirement_key in open_keys)
|
|
111
|
+
|
|
112
|
+
native_actions: dict[str, ActionDef] = {
|
|
113
|
+
"create": _action_def("create"),
|
|
114
|
+
"add_relationship": _action_def("relationship_add"),
|
|
115
|
+
"remove_relationship": _action_def("relationship_remove"),
|
|
116
|
+
}
|
|
117
|
+
transitions: dict[str, dict[str, str]] = {s: {} for s in state_names}
|
|
118
|
+
for name, spec in actions.items():
|
|
119
|
+
kind = spec["kind"]
|
|
120
|
+
if kind == ACTION_STATE:
|
|
121
|
+
native_actions[name] = _action_def("state")
|
|
122
|
+
for s in state_names:
|
|
123
|
+
transitions[s][name] = s
|
|
124
|
+
elif kind == ACTION_LIFECYCLE:
|
|
125
|
+
if not lc_fields:
|
|
126
|
+
raise PortableTypeError(f"lifecycle action {name!r} on a type without lifecycle")
|
|
127
|
+
native_actions[name] = _action_def("lifecycle")
|
|
128
|
+
for source in spec["from"]:
|
|
129
|
+
if (source, spec["to"]) not in permitted:
|
|
130
|
+
raise PortableTypeError(
|
|
131
|
+
f"action {name!r} {source}->{spec['to']} is not a declared transition"
|
|
132
|
+
)
|
|
133
|
+
transitions[source][name] = spec["to"]
|
|
134
|
+
else:
|
|
135
|
+
raise PortableTypeError(f"unsupported action kind {kind!r} for {name!r}")
|
|
136
|
+
|
|
137
|
+
return ObjectTypeDefinition(
|
|
138
|
+
kind=portable["type_identity"],
|
|
139
|
+
type_version=str(portable["type_version"]),
|
|
140
|
+
fields={
|
|
141
|
+
n: FieldSchema(type="string", required=True)
|
|
142
|
+
for n, k in fields.items()
|
|
143
|
+
if k != FIELD_LIFECYCLE
|
|
144
|
+
},
|
|
145
|
+
states={s: StateDef(transitions=t) for s, t in transitions.items()},
|
|
146
|
+
actions=native_actions,
|
|
147
|
+
read_requires=list(requirements["read"]),
|
|
148
|
+
read_open="read" in open_keys,
|
|
149
|
+
initial_state=state_names[0],
|
|
150
|
+
extra={PORTABLE_TYPE_KEY: dict(portable)},
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def data_problems(portable: Mapping[str, Any], data: Mapping[str, Any], *, partial: bool) -> list[str]:
|
|
155
|
+
"""Problems with non-lifecycle field values. ``partial`` allows a subset
|
|
156
|
+
(a state action's ``set``); otherwise every declared field is required."""
|
|
157
|
+
declared = {n: k for n, k in portable["state_fields"].items() if k != FIELD_LIFECYCLE}
|
|
158
|
+
problems = [f"unknown or non-state field {n!r}" for n in sorted(set(data) - set(declared))]
|
|
159
|
+
if not partial:
|
|
160
|
+
problems += [f"missing declared field {n!r}" for n in sorted(set(declared) - set(data))]
|
|
161
|
+
for name in sorted(set(declared) & set(data)):
|
|
162
|
+
value = data[name]
|
|
163
|
+
if not isinstance(value, str):
|
|
164
|
+
problems.append(f"field {name!r} must be a string")
|
|
165
|
+
elif declared[name] == FIELD_DECIMAL and not _DECIMAL.match(value):
|
|
166
|
+
problems.append(f"field {name!r} is not a decimal string")
|
|
167
|
+
return problems
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
class PortableTypeAdapter(TypeAdapter):
|
|
171
|
+
"""Validation and state-action handling for types built by
|
|
172
|
+
:func:`build_type_definition`."""
|
|
173
|
+
|
|
174
|
+
def __init__(self, types: TypeRegistry) -> None:
|
|
175
|
+
self._types = types
|
|
176
|
+
|
|
177
|
+
def validate_observation_candidate(
|
|
178
|
+
self, *, type_def: ObjectTypeDefinition, current: CandidateImage | None,
|
|
179
|
+
candidate: CandidateImage, mode: CandidateMode,
|
|
180
|
+
) -> CandidateVerdict:
|
|
181
|
+
portable = portable_type_of(type_def)
|
|
182
|
+
if portable is None:
|
|
183
|
+
return CandidateVerdict.UNAVAILABLE
|
|
184
|
+
return (CandidateVerdict.INVALID if data_problems(portable, candidate.data, partial=False)
|
|
185
|
+
else CandidateVerdict.VALID)
|
|
186
|
+
|
|
187
|
+
def supports(self, object_type: str) -> bool:
|
|
188
|
+
try:
|
|
189
|
+
return portable_type_of(self._types.get(object_type)) is not None
|
|
190
|
+
except KeyError:
|
|
191
|
+
return False
|
|
192
|
+
|
|
193
|
+
def validate_create(
|
|
194
|
+
self, type_def: ObjectTypeDefinition, data: dict[str, Any]
|
|
195
|
+
) -> tuple[bool, list[ValidationCheck], str]:
|
|
196
|
+
problems = data_problems(portable_type_of(type_def), data, partial=False)
|
|
197
|
+
checks = [ValidationCheck(name="portable_state", passed=not problems, message="; ".join(problems))]
|
|
198
|
+
return not problems, checks, "; ".join(problems)
|
|
199
|
+
|
|
200
|
+
def validate_transition(
|
|
201
|
+
self, obj: GovernedObject, type_def: ObjectTypeDefinition, action: str, actor: Actor
|
|
202
|
+
) -> tuple[bool, list[ValidationCheck], str]:
|
|
203
|
+
return True, [], ""
|
|
204
|
+
|
|
205
|
+
def adapter_execute(
|
|
206
|
+
self, obj: GovernedObject, command: Command, context: AdapterContext
|
|
207
|
+
) -> AdapterExecuteResult | None:
|
|
208
|
+
portable = portable_type_of(self._types.get(obj.type))
|
|
209
|
+
spec = portable.get("actions", {}).get(command.action)
|
|
210
|
+
if spec is None or spec["kind"] != ACTION_STATE:
|
|
211
|
+
return None
|
|
212
|
+
changes = dict(command.payload.get("set") or {})
|
|
213
|
+
problems = data_problems(portable, changes, partial=True)
|
|
214
|
+
if not changes:
|
|
215
|
+
problems.append("state action requires at least one field")
|
|
216
|
+
if problems:
|
|
217
|
+
return AdapterExecuteResult(
|
|
218
|
+
success=False,
|
|
219
|
+
error_code="STATE_INVALID",
|
|
220
|
+
error_message="; ".join(problems),
|
|
221
|
+
failure=AdapterFailure.INVALID,
|
|
222
|
+
)
|
|
223
|
+
return AdapterExecuteResult(
|
|
224
|
+
success=True,
|
|
225
|
+
object=obj.model_copy(
|
|
226
|
+
update={"data": {**obj.data, **changes}, "version": obj.version + 1}
|
|
227
|
+
),
|
|
228
|
+
)
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2026 Brafford Labs, LLC
|
|
3
|
+
"""Experimental optional-use model harness; not a default or provider integration."""
|
|
4
|
+
|
|
5
|
+
from governed_objects.llm.loop import GovernedAgentLoop, AgentLoopResult
|
|
6
|
+
from governed_objects.llm.model import ModelResponse, ReasoningModel, ToolCall
|
|
7
|
+
from governed_objects.llm.tools.surface import GovernedAgentTools
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"AgentLoopResult",
|
|
11
|
+
"GovernedAgentLoop",
|
|
12
|
+
"GovernedAgentTools",
|
|
13
|
+
"ModelResponse",
|
|
14
|
+
"ReasoningModel",
|
|
15
|
+
"ToolCall",
|
|
16
|
+
]
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2026 Brafford Labs, LLC
|
|
3
|
+
"""Bounded model/tool execution loop."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from governed_objects.llm.model import ReasoningModel
|
|
11
|
+
from governed_objects.llm.tools.results import ToolResult
|
|
12
|
+
from governed_objects.llm.tools.surface import GovernedAgentTools
|
|
13
|
+
from governed_objects.llm.trace import AgentExecutionTrace
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class AgentLoopResult:
|
|
18
|
+
trace: AgentExecutionTrace
|
|
19
|
+
completed: bool = False
|
|
20
|
+
stopped_reason: str = ""
|
|
21
|
+
business_actions_allowed: int = 0
|
|
22
|
+
duplicate_transitions: int = 0
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class GovernedAgentLoop:
|
|
26
|
+
"""Bounded loop: model proposes tool calls, substrate executes and returns results."""
|
|
27
|
+
|
|
28
|
+
DEFAULT_MAX_STEPS = 8
|
|
29
|
+
DEFAULT_MAX_TOOL_CALLS = 16
|
|
30
|
+
|
|
31
|
+
def __init__(
|
|
32
|
+
self,
|
|
33
|
+
model: ReasoningModel,
|
|
34
|
+
tools: GovernedAgentTools,
|
|
35
|
+
*,
|
|
36
|
+
task: str = "",
|
|
37
|
+
max_steps: int = DEFAULT_MAX_STEPS,
|
|
38
|
+
max_tool_calls: int = DEFAULT_MAX_TOOL_CALLS,
|
|
39
|
+
) -> None:
|
|
40
|
+
self._model = model
|
|
41
|
+
self._tools = tools
|
|
42
|
+
self._task = task
|
|
43
|
+
self._max_steps = max_steps
|
|
44
|
+
self._max_tool_calls = max_tool_calls
|
|
45
|
+
|
|
46
|
+
def run(self) -> AgentLoopResult:
|
|
47
|
+
trace = AgentExecutionTrace(
|
|
48
|
+
task=self._task,
|
|
49
|
+
model_provider=self._model.provider,
|
|
50
|
+
model_name=self._model.model_name,
|
|
51
|
+
bound_context=self._tools.bound_context,
|
|
52
|
+
)
|
|
53
|
+
messages: list[dict[str, Any]] = [{"role": "user", "content": self._task}]
|
|
54
|
+
tool_call_count = 0
|
|
55
|
+
business_allowed = 0
|
|
56
|
+
seen_executions: set[tuple[str, str, int]] = set()
|
|
57
|
+
duplicate_transitions = 0
|
|
58
|
+
|
|
59
|
+
for step in range(self._max_steps):
|
|
60
|
+
trace.steps = step + 1
|
|
61
|
+
response = self._model.respond(messages, self._tools.definitions())
|
|
62
|
+
if response.final is not None:
|
|
63
|
+
trace.final_message = response.final
|
|
64
|
+
return AgentLoopResult(
|
|
65
|
+
trace=trace,
|
|
66
|
+
completed=True,
|
|
67
|
+
stopped_reason="model_final",
|
|
68
|
+
business_actions_allowed=business_allowed,
|
|
69
|
+
duplicate_transitions=duplicate_transitions,
|
|
70
|
+
)
|
|
71
|
+
if not response.tool_calls:
|
|
72
|
+
trace.final_message = "No tool calls — stopping."
|
|
73
|
+
return AgentLoopResult(
|
|
74
|
+
trace=trace,
|
|
75
|
+
completed=True,
|
|
76
|
+
stopped_reason="no_tool_calls",
|
|
77
|
+
business_actions_allowed=business_allowed,
|
|
78
|
+
duplicate_transitions=duplicate_transitions,
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
for tool_call in response.tool_calls:
|
|
82
|
+
if tool_call_count >= self._max_tool_calls:
|
|
83
|
+
trace.final_message = "Max tool calls reached."
|
|
84
|
+
return AgentLoopResult(
|
|
85
|
+
trace=trace,
|
|
86
|
+
completed=False,
|
|
87
|
+
stopped_reason="max_tool_calls",
|
|
88
|
+
business_actions_allowed=business_allowed,
|
|
89
|
+
duplicate_transitions=duplicate_transitions,
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
result = self._tools.execute(tool_call)
|
|
93
|
+
trace.record(step + 1, tool_call.name, tool_call.arguments, result)
|
|
94
|
+
tool_call_count += 1
|
|
95
|
+
|
|
96
|
+
if (
|
|
97
|
+
tool_call.name == "execute_action"
|
|
98
|
+
and result.decision == "ALLOW"
|
|
99
|
+
):
|
|
100
|
+
key = (result.object_id or "", tool_call.arguments.get("action", ""), result.version or 0)
|
|
101
|
+
if key in seen_executions:
|
|
102
|
+
duplicate_transitions += 1
|
|
103
|
+
seen_executions.add(key)
|
|
104
|
+
business_allowed += 1
|
|
105
|
+
|
|
106
|
+
if result.decision == "CONFLICT":
|
|
107
|
+
trace.refreshes += 1
|
|
108
|
+
|
|
109
|
+
messages.append({
|
|
110
|
+
"role": "assistant",
|
|
111
|
+
"tool_calls": [{
|
|
112
|
+
"id": tool_call.id,
|
|
113
|
+
"name": tool_call.name,
|
|
114
|
+
"arguments": tool_call.arguments,
|
|
115
|
+
}],
|
|
116
|
+
})
|
|
117
|
+
messages.append({
|
|
118
|
+
"role": "tool",
|
|
119
|
+
"tool_call_id": tool_call.id,
|
|
120
|
+
"content": result.to_model_dict(),
|
|
121
|
+
})
|
|
122
|
+
|
|
123
|
+
trace.final_message = "Max steps reached."
|
|
124
|
+
return AgentLoopResult(
|
|
125
|
+
trace=trace,
|
|
126
|
+
completed=False,
|
|
127
|
+
stopped_reason="max_steps",
|
|
128
|
+
business_actions_allowed=business_allowed,
|
|
129
|
+
duplicate_transitions=duplicate_transitions,
|
|
130
|
+
)
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2026 Brafford Labs, LLC
|
|
3
|
+
"""Reasoning model protocol — vendor-neutral LLM adapter boundary."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from typing import Any, Protocol
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True)
|
|
12
|
+
class ToolCall:
|
|
13
|
+
id: str
|
|
14
|
+
name: str
|
|
15
|
+
arguments: dict[str, Any]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class ModelResponse:
|
|
20
|
+
tool_calls: list[ToolCall] = field(default_factory=list)
|
|
21
|
+
final: str | None = None
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class ToolDefinition:
|
|
26
|
+
name: str
|
|
27
|
+
description: str
|
|
28
|
+
parameters: dict[str, Any]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class ReasoningModel(Protocol):
|
|
32
|
+
"""Vendor-neutral interface for probabilistic reasoning models."""
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def provider(self) -> str: ...
|
|
36
|
+
|
|
37
|
+
@property
|
|
38
|
+
def model_name(self) -> str: ...
|
|
39
|
+
|
|
40
|
+
def respond(
|
|
41
|
+
self,
|
|
42
|
+
messages: list[dict[str, Any]],
|
|
43
|
+
tools: list[ToolDefinition],
|
|
44
|
+
) -> ModelResponse: ...
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2026 Brafford Labs, LLC
|
|
3
|
+
"""Fixed governed tool registry — no dynamic runtime exposure."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from governed_objects.llm.model import ToolDefinition
|
|
8
|
+
|
|
9
|
+
REGISTERED_TOOL_NAMES = frozenset({
|
|
10
|
+
"query_objects",
|
|
11
|
+
"read_object",
|
|
12
|
+
"traverse_relationships",
|
|
13
|
+
"execute_action",
|
|
14
|
+
"get_history",
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def tool_definitions() -> list[ToolDefinition]:
|
|
19
|
+
return [
|
|
20
|
+
ToolDefinition(
|
|
21
|
+
name="query_objects",
|
|
22
|
+
description="Query governed objects visible to this session.",
|
|
23
|
+
parameters={
|
|
24
|
+
"type": "object",
|
|
25
|
+
"properties": {
|
|
26
|
+
"object_type": {"type": "string"},
|
|
27
|
+
"include_subtypes": {"type": "boolean"},
|
|
28
|
+
"state": {"type": "string"},
|
|
29
|
+
},
|
|
30
|
+
"required": ["object_type"],
|
|
31
|
+
"additionalProperties": False,
|
|
32
|
+
},
|
|
33
|
+
),
|
|
34
|
+
ToolDefinition(
|
|
35
|
+
name="read_object",
|
|
36
|
+
description="Read one authorized governed object.",
|
|
37
|
+
parameters={
|
|
38
|
+
"type": "object",
|
|
39
|
+
"properties": {"object_id": {"type": "string"}},
|
|
40
|
+
"required": ["object_id"],
|
|
41
|
+
"additionalProperties": False,
|
|
42
|
+
},
|
|
43
|
+
),
|
|
44
|
+
ToolDefinition(
|
|
45
|
+
name="traverse_relationships",
|
|
46
|
+
description="Traverse authorized relationships from an object.",
|
|
47
|
+
parameters={
|
|
48
|
+
"type": "object",
|
|
49
|
+
"properties": {
|
|
50
|
+
"object_id": {"type": "string"},
|
|
51
|
+
"relation": {"type": "string"},
|
|
52
|
+
"max_depth": {"type": "integer"},
|
|
53
|
+
},
|
|
54
|
+
"required": ["object_id"],
|
|
55
|
+
"additionalProperties": False,
|
|
56
|
+
},
|
|
57
|
+
),
|
|
58
|
+
ToolDefinition(
|
|
59
|
+
name="execute_action",
|
|
60
|
+
description="Execute a governed lifecycle action on an object.",
|
|
61
|
+
parameters={
|
|
62
|
+
"type": "object",
|
|
63
|
+
"properties": {
|
|
64
|
+
"object_id": {"type": "string"},
|
|
65
|
+
"action": {"type": "string"},
|
|
66
|
+
"expected_version": {"type": "integer"},
|
|
67
|
+
"parameters": {"type": "object"},
|
|
68
|
+
},
|
|
69
|
+
"required": ["object_id", "action", "expected_version"],
|
|
70
|
+
"additionalProperties": False,
|
|
71
|
+
},
|
|
72
|
+
),
|
|
73
|
+
ToolDefinition(
|
|
74
|
+
name="get_history",
|
|
75
|
+
description="Get authorized object event/audit history, which may include accepted changes and nonaccepted or audit activity.",
|
|
76
|
+
parameters={
|
|
77
|
+
"type": "object",
|
|
78
|
+
"properties": {"object_id": {"type": "string"}},
|
|
79
|
+
"required": ["object_id"],
|
|
80
|
+
"additionalProperties": False,
|
|
81
|
+
},
|
|
82
|
+
),
|
|
83
|
+
]
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def is_registered_tool(name: str) -> bool:
|
|
87
|
+
return name in REGISTERED_TOOL_NAMES
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2026 Brafford Labs, LLC
|
|
3
|
+
"""Structured tool results returned to the reasoning model."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass
|
|
12
|
+
class ToolResult:
|
|
13
|
+
tool_call_id: str
|
|
14
|
+
tool_name: str
|
|
15
|
+
success: bool
|
|
16
|
+
decision: str | None = None
|
|
17
|
+
reason: str | None = None
|
|
18
|
+
message: str | None = None
|
|
19
|
+
object_id: str | None = None
|
|
20
|
+
state: str | None = None
|
|
21
|
+
version: int | None = None
|
|
22
|
+
actual_version: int | None = None
|
|
23
|
+
expected_version: int | None = None
|
|
24
|
+
objects: list[dict[str, Any]] = field(default_factory=list)
|
|
25
|
+
error: str | None = None
|
|
26
|
+
schema_rejected: bool = False
|
|
27
|
+
|
|
28
|
+
def to_model_dict(self) -> dict[str, Any]:
|
|
29
|
+
payload: dict[str, Any] = {"tool_call_id": self.tool_call_id}
|
|
30
|
+
if self.error:
|
|
31
|
+
payload["error"] = self.error
|
|
32
|
+
if self.schema_rejected:
|
|
33
|
+
payload["schema_rejected"] = True
|
|
34
|
+
return payload
|
|
35
|
+
if self.decision:
|
|
36
|
+
payload["decision"] = self.decision
|
|
37
|
+
if self.reason:
|
|
38
|
+
payload["reason"] = self.reason
|
|
39
|
+
if self.message:
|
|
40
|
+
payload["message"] = self.message
|
|
41
|
+
if self.object_id:
|
|
42
|
+
payload["object_id"] = self.object_id
|
|
43
|
+
if self.state is not None:
|
|
44
|
+
payload["state"] = self.state
|
|
45
|
+
if self.version is not None:
|
|
46
|
+
payload["version"] = self.version
|
|
47
|
+
if self.actual_version is not None:
|
|
48
|
+
payload["actual_version"] = self.actual_version
|
|
49
|
+
if self.expected_version is not None:
|
|
50
|
+
payload["expected_version"] = self.expected_version
|
|
51
|
+
if self.objects:
|
|
52
|
+
payload["objects"] = self.objects
|
|
53
|
+
return payload
|