vogtcon 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- vogtcon-0.1.0/LICENSE +202 -0
- vogtcon-0.1.0/NOTICE +4 -0
- vogtcon-0.1.0/PKG-INFO +156 -0
- vogtcon-0.1.0/README.md +138 -0
- vogtcon-0.1.0/pyproject.toml +29 -0
- vogtcon-0.1.0/setup.cfg +4 -0
- vogtcon-0.1.0/src/vogtcon/__init__.py +47 -0
- vogtcon-0.1.0/src/vogtcon/contracts.py +84 -0
- vogtcon-0.1.0/src/vogtcon/core.py +77 -0
- vogtcon-0.1.0/src/vogtcon/execution.py +353 -0
- vogtcon-0.1.0/src/vogtcon/models.py +248 -0
- vogtcon-0.1.0/src/vogtcon/records.py +95 -0
- vogtcon-0.1.0/src/vogtcon/rules.py +216 -0
- vogtcon-0.1.0/src/vogtcon/telemetry.py +77 -0
- vogtcon-0.1.0/src/vogtcon.egg-info/PKG-INFO +156 -0
- vogtcon-0.1.0/src/vogtcon.egg-info/SOURCES.txt +28 -0
- vogtcon-0.1.0/src/vogtcon.egg-info/dependency_links.txt +1 -0
- vogtcon-0.1.0/src/vogtcon.egg-info/requires.txt +6 -0
- vogtcon-0.1.0/src/vogtcon.egg-info/top_level.txt +1 -0
- vogtcon-0.1.0/tests/test_benchmark_validation.py +178 -0
- vogtcon-0.1.0/tests/test_contracts.py +215 -0
- vogtcon-0.1.0/tests/test_core.py +247 -0
- vogtcon-0.1.0/tests/test_custom_integration.py +161 -0
- vogtcon-0.1.0/tests/test_example_agent.py +81 -0
- vogtcon-0.1.0/tests/test_execution.py +382 -0
- vogtcon-0.1.0/tests/test_models.py +427 -0
- vogtcon-0.1.0/tests/test_records.py +167 -0
- vogtcon-0.1.0/tests/test_rules.py +296 -0
- vogtcon-0.1.0/tests/test_runner_mvp_parity.py +711 -0
- vogtcon-0.1.0/tests/test_telemetry.py +230 -0
vogtcon-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
vogtcon-0.1.0/NOTICE
ADDED
vogtcon-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: vogtcon
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Deterministic contracts and runtime governance for agents.
|
|
5
|
+
Author: Jorge Carlos Urteaga Reyesvera
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Repository, https://github.com/CarlosUrteaga/vogtcon
|
|
8
|
+
Requires-Python: >=3.11
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
License-File: NOTICE
|
|
12
|
+
Requires-Dist: pydantic<3,>=2.10
|
|
13
|
+
Requires-Dist: PyYAML<7,>=6
|
|
14
|
+
Requires-Dist: opentelemetry-api<2,>=1
|
|
15
|
+
Provides-Extra: pydantic-ai
|
|
16
|
+
Requires-Dist: pydantic-ai-slim<3,>=1; extra == "pydantic-ai"
|
|
17
|
+
Dynamic: license-file
|
|
18
|
+
|
|
19
|
+
<!-- Copyright (c) 2026 Jorge Carlos Urteaga Reyesvera
|
|
20
|
+
SPDX-License-Identifier: Apache-2.0 -->
|
|
21
|
+
|
|
22
|
+
# Governor Contracts
|
|
23
|
+
|
|
24
|
+
Biblioteca Python experimental para evaluar contratos antes y después de que un agente use herramientas. El Governor actual es determinista. El ejemplo de Pydantic AI demuestra cómo conectar un agente propio; el núcleo de `vogtcon` no importa Pydantic AI.
|
|
25
|
+
|
|
26
|
+
El repositorio público, la distribución en PyPI y el import de Python se llaman `vogtcon`. El proyecto se publica bajo [Apache License 2.0](LICENSE). Algunos reportes históricos mencionan el nombre anterior `governor_contracts` y la copia vendor del benchmark; se conservaron como evidencia de esas etapas.
|
|
27
|
+
|
|
28
|
+
Para empezar con una prueba local, sigue la sección [Probar la integración](#probar-la-integración).
|
|
29
|
+
Para incorporarlo a un agente propio, sigue la [guía de integración](INTEGRACION.md).
|
|
30
|
+
|
|
31
|
+
## Usar como librería
|
|
32
|
+
|
|
33
|
+
Instala el paquete con `uv pip install .` desde este proyecto, o construye el
|
|
34
|
+
wheel con `uv build` e instala ese archivo `.whl` con `pip`. Pydantic AI es opcional;
|
|
35
|
+
se necesita el extra `pydantic-ai` solo para `examples/custom_agent.py`.
|
|
36
|
+
|
|
37
|
+
El siguiente ejemplo usa [un contrato YAML v2](examples/notification_contract_v2.yaml)
|
|
38
|
+
y una herramienta propia. El contexto proviene de la aplicación anfitriona, no
|
|
39
|
+
de los argumentos que proponga el agente:
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from vogtcon import (
|
|
43
|
+
ActionProposal, EnforcementPolicy, ExecutionContext, JsonlDecisionLog,
|
|
44
|
+
WorkflowController,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
controller = WorkflowController.from_contract_path(
|
|
48
|
+
"examples/notification_contract_v2.yaml", "run-1",
|
|
49
|
+
policy=EnforcementPolicy(mode="guarded"),
|
|
50
|
+
recorder=JsonlDecisionLog("run-1.jsonl"),
|
|
51
|
+
)
|
|
52
|
+
contract = controller.contract
|
|
53
|
+
context = ExecutionContext(
|
|
54
|
+
state={"approval_granted": False},
|
|
55
|
+
available_tools=["send_notification"],
|
|
56
|
+
observed_agent_fingerprint="notification-agent-v1",
|
|
57
|
+
observed_contract_fingerprint=contract.contract_fingerprint,
|
|
58
|
+
)
|
|
59
|
+
sent = []
|
|
60
|
+
|
|
61
|
+
def send_notification(proposal: ActionProposal) -> str:
|
|
62
|
+
sent.append(proposal.arguments["message"])
|
|
63
|
+
return "sent"
|
|
64
|
+
|
|
65
|
+
pre = controller.begin(context)
|
|
66
|
+
if controller.state == "active":
|
|
67
|
+
action = ActionProposal(
|
|
68
|
+
tool_name="send_notification",
|
|
69
|
+
arguments={"message": "Hola", "sensitive": True},
|
|
70
|
+
)
|
|
71
|
+
outcome = controller.execute(action, context, send_notification)
|
|
72
|
+
if controller.state == "active":
|
|
73
|
+
post = controller.finish(
|
|
74
|
+
context, {"status": "sent" if outcome.executed else "blocked"}
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
assert sent == [] # guarded bloqueó la acción sensible sin aprobación
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
En v2, el YAML contiene las reglas y su fingerprint, mientras que
|
|
81
|
+
`EnforcementPolicy` fija el modo para cada ejecución. El mismo contrato puede
|
|
82
|
+
usarse con `no_contract`, `advisory`, `guarded` o `strict` sin cambiar su
|
|
83
|
+
identidad. Hay que pasar la política explícitamente; la ausencia de política
|
|
84
|
+
en v2 es un error de configuración. Los contratos históricos v1, como
|
|
85
|
+
[notification_contract.yaml](examples/notification_contract.yaml), mantienen
|
|
86
|
+
su `mode` dentro del YAML y siguen aceptando la misma API sin `policy=`.
|
|
87
|
+
En `no_contract`, el registro conserva ese modo y no evalúa reglas: una lista
|
|
88
|
+
vacía de infracciones en ese modo no significa que las reglas pasaron.
|
|
89
|
+
|
|
90
|
+
`load_contract` devuelve un `ContractDocument`: `.contract` es la vista tipada y
|
|
91
|
+
`.original` conserva el documento parseado. `Governor` evalúa reglas sin ejecutar
|
|
92
|
+
herramientas; `RuleCatalog` añade reglas propias. La fábrica
|
|
93
|
+
`WorkflowController.from_contract_path` usa el mismo catálogo al cargar y
|
|
94
|
+
evaluar el contrato, y crea un controlador determinista por corrida. La
|
|
95
|
+
construcción directa de `WorkflowController` sigue disponible para inyectar un
|
|
96
|
+
`Governor` con evaluador propio. `WorkflowController` gestiona pre, runtime y
|
|
97
|
+
post; `GovernedToolExecutor` ofrece solo el check y la invocación runtime si la
|
|
98
|
+
aplicación ya gestiona el ciclo. `RunRecorder` es el protocolo para persistir
|
|
99
|
+
eventos; `JsonlDecisionLog` es su implementación local. `TelemetryObserver`
|
|
100
|
+
recibe un proveedor OpenTelemetry configurado por la aplicación y relaciona
|
|
101
|
+
spans con los registros mediante `trace_id` y `span_id`.
|
|
102
|
+
|
|
103
|
+
`pre` y `post` contienen violaciones, pero no una decisión de herramienta.
|
|
104
|
+
Consulta `controller.state` antes de seguir: en modo `strict`, una violación
|
|
105
|
+
pre/runtime aborta; en `guarded`, un bloqueo runtime permite proponer otra
|
|
106
|
+
acción. La llamada a la herramienta ocurre únicamente si la decisión runtime
|
|
107
|
+
es `allow` o `allow_with_warning`.
|
|
108
|
+
|
|
109
|
+
## Probar la integración
|
|
110
|
+
|
|
111
|
+
Desde esta carpeta:
|
|
112
|
+
|
|
113
|
+
```bash
|
|
114
|
+
uv sync --extra pydantic-ai --group test
|
|
115
|
+
PYDANTIC_AI_NO_BANNER=1 .venv/bin/python examples/custom_agent.py --log /tmp/governor-note-events.jsonl
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
El ejemplo hace dos ejecuciones con un modelo programado, sin proveedor ni credenciales: una nota pública sin aprobación confiable queda bloqueada, y otra con aprobación se guarda. El archivo JSONL registra el `run_id`, el contrato, la fase, la decisión y las reglas infringidas. Si ya existe, se añaden líneas; usa una ruta nueva para una demostración aislada. Para ver también los spans en consola, agrega `--trace-console` al segundo comando.
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
PYDANTIC_AI_NO_BANNER=1 .venv/bin/python examples/custom_agent.py --log /tmp/governor-note-traced.jsonl --trace-console
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
## Conectar otro agente y otra herramienta
|
|
125
|
+
|
|
126
|
+
1. Define un contrato YAML con las herramientas y reglas que vas a aplicar. Si necesitas una regla propia, regístrala con `RuleCatalog` y pasa el mismo catálogo a `load_contract` y `Governor`.
|
|
127
|
+
2. Crea un `WorkflowController` por ejecución con `from_contract_path(path, run_id, policy=..., rule_catalog=...)`. Para v2, pasa una política explícita; para v1, se usa el modo del YAML. La aplicación anfitriona construye `ExecutionContext` con hechos obtenidos de sus sistemas; no toma roles ni aprobaciones de los argumentos del agente.
|
|
128
|
+
3. Llama a `begin(context)` antes de iniciar el agente. Convierte cada llamada a herramienta en un `ActionProposal` y pasa su implementación real a `controller.execute(proposal, context, tool)`. Solo `allow` y `allow_with_warning` invocan la herramienta. Devuelve el bloqueo al agente como feedback o termina el flujo según el modo.
|
|
129
|
+
4. Llama a `finish(context, response)` con el resultado final. La comprobación post informa fallos, pero no revierte efectos remotos ya realizados.
|
|
130
|
+
|
|
131
|
+
En [examples/custom_agent.py](examples/custom_agent.py), `save_note` es la única herramienta con efectos registrada en Pydantic AI. Su [contrato v2](examples/custom_contract.yaml) define reglas sin modo; el host crea `EnforcementPolicy(mode="guarded")` por ejecución mediante la fábrica. La herramienta recibe controlador, contexto confiable y `NoteTool` mediante `RunContext[Deps]`, y llama a `WorkflowController.execute` antes del efecto. Un agente o herramienta externos se sustituyen en ese borde; exponer otra herramienta con efectos directamente al modelo la dejaría fuera de Governor. El ejemplo usa `FunctionModel` y no necesita credenciales. El script toma el fingerprint observado del mismo YAML solo para la demostración; una integración real debe obtener esa identidad de una fuente confiable independiente.
|
|
132
|
+
|
|
133
|
+
La salida del modelo se conserva como `untrusted_agent_output` para inspección. La aplicación debe mostrar `verified_output`, calculada por el host a partir de las acciones realmente ejecutadas; así un bloqueo no se presenta como un guardado exitoso, aunque el modelo lo afirme.
|
|
134
|
+
|
|
135
|
+
El registro es opcional: pasa `JsonlDecisionLog(path)` al controlador. La decisión se sincroniza en disco antes de invocar una herramienta; si falla esa escritura, la herramienta no se llama. Una excepción posterior a la invocación se registra como resultado incierto. Este JSONL local está pensado para una ejecución secuencial en un proceso; no promete transacciones distribuidas ni escritura concurrente.
|
|
136
|
+
|
|
137
|
+
La telemetría también es opcional. Pasa `TelemetryObserver` al controlador y mantén `with telemetry.run(run_id, contract_id)` alrededor de las tres fases. La aplicación configura el SDK/exporter de OpenTelemetry. El ejemplo activa la instrumentación nativa de Pydantic AI sin capturar prompts, argumentos ni respuestas completos; los eventos JSONL y spans comparten `trace_id`. Una caída del exporter no cambia permisos. Las trazas observan el trabajo, pero la autorización se comprueba sincrónicamente antes del efecto.
|
|
138
|
+
|
|
139
|
+
## Estado y límites
|
|
140
|
+
|
|
141
|
+
El paquete conserva `no_contract` como control experimental, además de `advisory`, `guarded` y `strict`. `guarded` bloquea una acción y permite una nueva propuesta; `strict` aborta por violaciones pre/runtime. No hay todavía CLI de producto, adaptador al benchmark dentro del paquete, ledger distribuido ni Governor con LLM. La integración con un proveedor LLM real no forma parte de las pruebas automáticas.
|
|
142
|
+
|
|
143
|
+
El piloto exploratorio incluye `S-001`, `S-013` y `S-016` en los cuatro modos. El arnés
|
|
144
|
+
`pilots/benchmark_probe.py` conserva su selección predeterminada de cuatro runs;
|
|
145
|
+
`--scenarios` y `--modes` permiten la selección de 12. Las discrepancias entre
|
|
146
|
+
el manifest y el checkout impiden presentar ese piloto como una comparación
|
|
147
|
+
histórica congelada.
|
|
148
|
+
|
|
149
|
+
Ejecuta la suite local con:
|
|
150
|
+
|
|
151
|
+
```bash
|
|
152
|
+
PYDANTIC_AI_NO_BANNER=1 GOVERNOR_BENCHMARK_ROOT=/ruta/al/agent-contracts-benchmark .venv/bin/python -m unittest discover -s tests -p 'test*.py' -q
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
Para comprobar el consumo del wheel desde otro directorio y un entorno limpio,
|
|
156
|
+
sin Pydantic AI ni el benchmark, ejecuta `sh tests/smoke_wheel_consumer.sh`.
|
vogtcon-0.1.0/README.md
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
<!-- Copyright (c) 2026 Jorge Carlos Urteaga Reyesvera
|
|
2
|
+
SPDX-License-Identifier: Apache-2.0 -->
|
|
3
|
+
|
|
4
|
+
# Governor Contracts
|
|
5
|
+
|
|
6
|
+
Biblioteca Python experimental para evaluar contratos antes y después de que un agente use herramientas. El Governor actual es determinista. El ejemplo de Pydantic AI demuestra cómo conectar un agente propio; el núcleo de `vogtcon` no importa Pydantic AI.
|
|
7
|
+
|
|
8
|
+
El repositorio público, la distribución en PyPI y el import de Python se llaman `vogtcon`. El proyecto se publica bajo [Apache License 2.0](LICENSE). Algunos reportes históricos mencionan el nombre anterior `governor_contracts` y la copia vendor del benchmark; se conservaron como evidencia de esas etapas.
|
|
9
|
+
|
|
10
|
+
Para empezar con una prueba local, sigue la sección [Probar la integración](#probar-la-integración).
|
|
11
|
+
Para incorporarlo a un agente propio, sigue la [guía de integración](INTEGRACION.md).
|
|
12
|
+
|
|
13
|
+
## Usar como librería
|
|
14
|
+
|
|
15
|
+
Instala el paquete con `uv pip install .` desde este proyecto, o construye el
|
|
16
|
+
wheel con `uv build` e instala ese archivo `.whl` con `pip`. Pydantic AI es opcional;
|
|
17
|
+
se necesita el extra `pydantic-ai` solo para `examples/custom_agent.py`.
|
|
18
|
+
|
|
19
|
+
El siguiente ejemplo usa [un contrato YAML v2](examples/notification_contract_v2.yaml)
|
|
20
|
+
y una herramienta propia. El contexto proviene de la aplicación anfitriona, no
|
|
21
|
+
de los argumentos que proponga el agente:
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
from vogtcon import (
|
|
25
|
+
ActionProposal, EnforcementPolicy, ExecutionContext, JsonlDecisionLog,
|
|
26
|
+
WorkflowController,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
controller = WorkflowController.from_contract_path(
|
|
30
|
+
"examples/notification_contract_v2.yaml", "run-1",
|
|
31
|
+
policy=EnforcementPolicy(mode="guarded"),
|
|
32
|
+
recorder=JsonlDecisionLog("run-1.jsonl"),
|
|
33
|
+
)
|
|
34
|
+
contract = controller.contract
|
|
35
|
+
context = ExecutionContext(
|
|
36
|
+
state={"approval_granted": False},
|
|
37
|
+
available_tools=["send_notification"],
|
|
38
|
+
observed_agent_fingerprint="notification-agent-v1",
|
|
39
|
+
observed_contract_fingerprint=contract.contract_fingerprint,
|
|
40
|
+
)
|
|
41
|
+
sent = []
|
|
42
|
+
|
|
43
|
+
def send_notification(proposal: ActionProposal) -> str:
|
|
44
|
+
sent.append(proposal.arguments["message"])
|
|
45
|
+
return "sent"
|
|
46
|
+
|
|
47
|
+
pre = controller.begin(context)
|
|
48
|
+
if controller.state == "active":
|
|
49
|
+
action = ActionProposal(
|
|
50
|
+
tool_name="send_notification",
|
|
51
|
+
arguments={"message": "Hola", "sensitive": True},
|
|
52
|
+
)
|
|
53
|
+
outcome = controller.execute(action, context, send_notification)
|
|
54
|
+
if controller.state == "active":
|
|
55
|
+
post = controller.finish(
|
|
56
|
+
context, {"status": "sent" if outcome.executed else "blocked"}
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
assert sent == [] # guarded bloqueó la acción sensible sin aprobación
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
En v2, el YAML contiene las reglas y su fingerprint, mientras que
|
|
63
|
+
`EnforcementPolicy` fija el modo para cada ejecución. El mismo contrato puede
|
|
64
|
+
usarse con `no_contract`, `advisory`, `guarded` o `strict` sin cambiar su
|
|
65
|
+
identidad. Hay que pasar la política explícitamente; la ausencia de política
|
|
66
|
+
en v2 es un error de configuración. Los contratos históricos v1, como
|
|
67
|
+
[notification_contract.yaml](examples/notification_contract.yaml), mantienen
|
|
68
|
+
su `mode` dentro del YAML y siguen aceptando la misma API sin `policy=`.
|
|
69
|
+
En `no_contract`, el registro conserva ese modo y no evalúa reglas: una lista
|
|
70
|
+
vacía de infracciones en ese modo no significa que las reglas pasaron.
|
|
71
|
+
|
|
72
|
+
`load_contract` devuelve un `ContractDocument`: `.contract` es la vista tipada y
|
|
73
|
+
`.original` conserva el documento parseado. `Governor` evalúa reglas sin ejecutar
|
|
74
|
+
herramientas; `RuleCatalog` añade reglas propias. La fábrica
|
|
75
|
+
`WorkflowController.from_contract_path` usa el mismo catálogo al cargar y
|
|
76
|
+
evaluar el contrato, y crea un controlador determinista por corrida. La
|
|
77
|
+
construcción directa de `WorkflowController` sigue disponible para inyectar un
|
|
78
|
+
`Governor` con evaluador propio. `WorkflowController` gestiona pre, runtime y
|
|
79
|
+
post; `GovernedToolExecutor` ofrece solo el check y la invocación runtime si la
|
|
80
|
+
aplicación ya gestiona el ciclo. `RunRecorder` es el protocolo para persistir
|
|
81
|
+
eventos; `JsonlDecisionLog` es su implementación local. `TelemetryObserver`
|
|
82
|
+
recibe un proveedor OpenTelemetry configurado por la aplicación y relaciona
|
|
83
|
+
spans con los registros mediante `trace_id` y `span_id`.
|
|
84
|
+
|
|
85
|
+
`pre` y `post` contienen violaciones, pero no una decisión de herramienta.
|
|
86
|
+
Consulta `controller.state` antes de seguir: en modo `strict`, una violación
|
|
87
|
+
pre/runtime aborta; en `guarded`, un bloqueo runtime permite proponer otra
|
|
88
|
+
acción. La llamada a la herramienta ocurre únicamente si la decisión runtime
|
|
89
|
+
es `allow` o `allow_with_warning`.
|
|
90
|
+
|
|
91
|
+
## Probar la integración
|
|
92
|
+
|
|
93
|
+
Desde esta carpeta:
|
|
94
|
+
|
|
95
|
+
```bash
|
|
96
|
+
uv sync --extra pydantic-ai --group test
|
|
97
|
+
PYDANTIC_AI_NO_BANNER=1 .venv/bin/python examples/custom_agent.py --log /tmp/governor-note-events.jsonl
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
El ejemplo hace dos ejecuciones con un modelo programado, sin proveedor ni credenciales: una nota pública sin aprobación confiable queda bloqueada, y otra con aprobación se guarda. El archivo JSONL registra el `run_id`, el contrato, la fase, la decisión y las reglas infringidas. Si ya existe, se añaden líneas; usa una ruta nueva para una demostración aislada. Para ver también los spans en consola, agrega `--trace-console` al segundo comando.
|
|
101
|
+
|
|
102
|
+
```bash
|
|
103
|
+
PYDANTIC_AI_NO_BANNER=1 .venv/bin/python examples/custom_agent.py --log /tmp/governor-note-traced.jsonl --trace-console
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
## Conectar otro agente y otra herramienta
|
|
107
|
+
|
|
108
|
+
1. Define un contrato YAML con las herramientas y reglas que vas a aplicar. Si necesitas una regla propia, regístrala con `RuleCatalog` y pasa el mismo catálogo a `load_contract` y `Governor`.
|
|
109
|
+
2. Crea un `WorkflowController` por ejecución con `from_contract_path(path, run_id, policy=..., rule_catalog=...)`. Para v2, pasa una política explícita; para v1, se usa el modo del YAML. La aplicación anfitriona construye `ExecutionContext` con hechos obtenidos de sus sistemas; no toma roles ni aprobaciones de los argumentos del agente.
|
|
110
|
+
3. Llama a `begin(context)` antes de iniciar el agente. Convierte cada llamada a herramienta en un `ActionProposal` y pasa su implementación real a `controller.execute(proposal, context, tool)`. Solo `allow` y `allow_with_warning` invocan la herramienta. Devuelve el bloqueo al agente como feedback o termina el flujo según el modo.
|
|
111
|
+
4. Llama a `finish(context, response)` con el resultado final. La comprobación post informa fallos, pero no revierte efectos remotos ya realizados.
|
|
112
|
+
|
|
113
|
+
En [examples/custom_agent.py](examples/custom_agent.py), `save_note` es la única herramienta con efectos registrada en Pydantic AI. Su [contrato v2](examples/custom_contract.yaml) define reglas sin modo; el host crea `EnforcementPolicy(mode="guarded")` por ejecución mediante la fábrica. La herramienta recibe controlador, contexto confiable y `NoteTool` mediante `RunContext[Deps]`, y llama a `WorkflowController.execute` antes del efecto. Un agente o herramienta externos se sustituyen en ese borde; exponer otra herramienta con efectos directamente al modelo la dejaría fuera de Governor. El ejemplo usa `FunctionModel` y no necesita credenciales. El script toma el fingerprint observado del mismo YAML solo para la demostración; una integración real debe obtener esa identidad de una fuente confiable independiente.
|
|
114
|
+
|
|
115
|
+
La salida del modelo se conserva como `untrusted_agent_output` para inspección. La aplicación debe mostrar `verified_output`, calculada por el host a partir de las acciones realmente ejecutadas; así un bloqueo no se presenta como un guardado exitoso, aunque el modelo lo afirme.
|
|
116
|
+
|
|
117
|
+
El registro es opcional: pasa `JsonlDecisionLog(path)` al controlador. La decisión se sincroniza en disco antes de invocar una herramienta; si falla esa escritura, la herramienta no se llama. Una excepción posterior a la invocación se registra como resultado incierto. Este JSONL local está pensado para una ejecución secuencial en un proceso; no promete transacciones distribuidas ni escritura concurrente.
|
|
118
|
+
|
|
119
|
+
La telemetría también es opcional. Pasa `TelemetryObserver` al controlador y mantén `with telemetry.run(run_id, contract_id)` alrededor de las tres fases. La aplicación configura el SDK/exporter de OpenTelemetry. El ejemplo activa la instrumentación nativa de Pydantic AI sin capturar prompts, argumentos ni respuestas completos; los eventos JSONL y spans comparten `trace_id`. Una caída del exporter no cambia permisos. Las trazas observan el trabajo, pero la autorización se comprueba sincrónicamente antes del efecto.
|
|
120
|
+
|
|
121
|
+
## Estado y límites
|
|
122
|
+
|
|
123
|
+
El paquete conserva `no_contract` como control experimental, además de `advisory`, `guarded` y `strict`. `guarded` bloquea una acción y permite una nueva propuesta; `strict` aborta por violaciones pre/runtime. No hay todavía CLI de producto, adaptador al benchmark dentro del paquete, ledger distribuido ni Governor con LLM. La integración con un proveedor LLM real no forma parte de las pruebas automáticas.
|
|
124
|
+
|
|
125
|
+
El piloto exploratorio incluye `S-001`, `S-013` y `S-016` en los cuatro modos. El arnés
|
|
126
|
+
`pilots/benchmark_probe.py` conserva su selección predeterminada de cuatro runs;
|
|
127
|
+
`--scenarios` y `--modes` permiten la selección de 12. Las discrepancias entre
|
|
128
|
+
el manifest y el checkout impiden presentar ese piloto como una comparación
|
|
129
|
+
histórica congelada.
|
|
130
|
+
|
|
131
|
+
Ejecuta la suite local con:
|
|
132
|
+
|
|
133
|
+
```bash
|
|
134
|
+
PYDANTIC_AI_NO_BANNER=1 GOVERNOR_BENCHMARK_ROOT=/ruta/al/agent-contracts-benchmark .venv/bin/python -m unittest discover -s tests -p 'test*.py' -q
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
Para comprobar el consumo del wheel desde otro directorio y un entorno limpio,
|
|
138
|
+
sin Pydantic AI ni el benchmark, ejecuta `sh tests/smoke_wheel_consumer.sh`.
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# Copyright (c) 2026 Jorge Carlos Urteaga Reyesvera
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
[build-system]
|
|
5
|
+
requires = ["setuptools>=77.0.3"]
|
|
6
|
+
build-backend = "setuptools.build_meta"
|
|
7
|
+
|
|
8
|
+
[project]
|
|
9
|
+
name = "vogtcon"
|
|
10
|
+
version = "0.1.0"
|
|
11
|
+
description = "Deterministic contracts and runtime governance for agents."
|
|
12
|
+
readme = "README.md"
|
|
13
|
+
authors = [{name = "Jorge Carlos Urteaga Reyesvera"}]
|
|
14
|
+
license = "Apache-2.0"
|
|
15
|
+
license-files = ["LICENSE", "NOTICE"]
|
|
16
|
+
requires-python = ">=3.11"
|
|
17
|
+
dependencies = ["pydantic>=2.10,<3", "PyYAML>=6,<7", "opentelemetry-api>=1,<2"]
|
|
18
|
+
|
|
19
|
+
[project.optional-dependencies]
|
|
20
|
+
pydantic-ai = ["pydantic-ai-slim>=1,<3"]
|
|
21
|
+
|
|
22
|
+
[project.urls]
|
|
23
|
+
Repository = "https://github.com/CarlosUrteaga/vogtcon"
|
|
24
|
+
|
|
25
|
+
[dependency-groups]
|
|
26
|
+
test = ["opentelemetry-sdk>=1,<2"]
|
|
27
|
+
|
|
28
|
+
[tool.setuptools.packages.find]
|
|
29
|
+
where = ["src"]
|
vogtcon-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# Copyright (c) 2026 Jorge Carlos Urteaga Reyesvera
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""Typed contracts and deterministic governance, independent of execution."""
|
|
5
|
+
|
|
6
|
+
from .contracts import load_contract
|
|
7
|
+
from .core import DeterministicEvaluator, Governor, GovernorEvaluator
|
|
8
|
+
from .execution import GovernedToolExecutor, ToolExecutionOutcome, WorkflowController
|
|
9
|
+
from .models import (
|
|
10
|
+
ActionProposal,
|
|
11
|
+
AgentContract,
|
|
12
|
+
ContractDocument,
|
|
13
|
+
ContractRulesV2,
|
|
14
|
+
EnforcementPolicy,
|
|
15
|
+
ExecutionContext,
|
|
16
|
+
GovernanceDecision,
|
|
17
|
+
GovernorInput,
|
|
18
|
+
Violation,
|
|
19
|
+
)
|
|
20
|
+
from .rules import DEFAULT_RULE_CATALOG, RuleCatalog
|
|
21
|
+
from .records import JsonlDecisionLog, RunEvent, RunRecorder
|
|
22
|
+
from .telemetry import TelemetryObserver
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"load_contract",
|
|
26
|
+
"DeterministicEvaluator",
|
|
27
|
+
"Governor",
|
|
28
|
+
"GovernorEvaluator",
|
|
29
|
+
"GovernedToolExecutor",
|
|
30
|
+
"ToolExecutionOutcome",
|
|
31
|
+
"WorkflowController",
|
|
32
|
+
"RuleCatalog",
|
|
33
|
+
"DEFAULT_RULE_CATALOG",
|
|
34
|
+
"JsonlDecisionLog",
|
|
35
|
+
"RunEvent",
|
|
36
|
+
"RunRecorder",
|
|
37
|
+
"TelemetryObserver",
|
|
38
|
+
"ActionProposal",
|
|
39
|
+
"AgentContract",
|
|
40
|
+
"ContractDocument",
|
|
41
|
+
"ContractRulesV2",
|
|
42
|
+
"EnforcementPolicy",
|
|
43
|
+
"ExecutionContext",
|
|
44
|
+
"GovernanceDecision",
|
|
45
|
+
"GovernorInput",
|
|
46
|
+
"Violation",
|
|
47
|
+
]
|