govAgent v3.5.0 - Library Documentation
govAgent is a Python library that wraps an LLM call in declarative policy enforcement, privacy redaction, tool-schema validation, a fiscal circuit breaker, and cryptographic execution snapshots. This guide documents the public package govagent as verified against current main (library version 3.5.0). The 3.5.0 tag includes the MCP gateway, packaged control mapping, optional cloud clients, and aexecute.
Which API Should I Use?
Start from the core primitives exported by from govagent import ExecutiveAgent, tool. Specialized governance engines and adapters are imported directly from their respective submodules.
| Use Case | Entry Point | Returns | Implementation Behavior |
|---|---|---|---|
| Load a YAML or dict policy | Policy.from_yaml(path) or Policy(config) |
Policy |
Projects nested fiscal_governance.global_limits and alignment, plus registry_alignment and the top-level tools: list. For a given tool name, a top-level tools: entry wins. |
| Register a tool | @tool(name=..., risk_level=..., ...) |
Original callable | Registers on the process-wide registry singleton. ExecutiveAgent.perform_action resolves the callable through Harbor and invokes it. |
| Run a governed task | await agent.execute(task) |
ExecutionSnapshot |
Redacts prompt, runs SemanticGuard, invokes router.route_and_generate or await agent.aexecute(task), validates intent, applies fiscal and judiciary rails, and calls the registered tool. execute remains an awaitable wrapper around aexecute. router=None returns sandbox success without an LLM (after the privacy and semantic checks). |
| Enforce fiscal ceilings | CircuitBreaker.check_financial_risk(cost) |
None or raises GovernanceViolation |
Compares cumulative swarm spend plus projected cost against min(recursive_tco_ceiling, daily_budget_usd). |
| Redact PII in strings | PrivacyGuard(policy).redact_task(text) |
str |
Uses Microsoft Presidio plus a custom street-address regex. Requires en_core_web_lg. |
| Score semantic alignment | SemanticGuard(...).evaluate_alignment(text) |
float |
Returns 0.0 on a breach, otherwise 1.0 - max_similarity. Called from CircuitBreaker.evaluate and from ExecutiveAgent.aexecute. Without govagent[enterprise], vector checks fail open. |
| Route an LLM request | PolicyBasedRouter.route_and_generate |
LLMResponse |
LOCAL_ONLY and CLOUD_ONLY always route to default_provider. Conditional rules execute only in HYBRID mode. |
| Verify a Harbor artifact | registry.verify_and_resolve_tool(name) |
Callable or raises | Invoked automatically by perform_action when OCI repository/digest fields are set. The offline mock-token stub remains for tests. |
| Generate audit & CFO packs | EvidencePackGenerator, CFOAnalyticsEngine, MetaGovernor |
Models / dicts | Exported directly from govagent.governance. Generated dossiers also reference the packaged control mapping (govagent.compliance); this is not a certification. |
Installation & Setup
pyproject.toml targets Python >=3.10,<3.14. The published distribution packages the core govagent library under src/.
# Core library (includes Presidio, spaCy, Slack, AWS, Azure, and OpenTelemetry dependencies) pip install govagent==3.5.0 # Optional extras declared in pyproject.toml pip install "govagent[enterprise]" # sentence-transformers (optional local SemanticGuard embeddings) pip install "govagent[crewai]" # CrewAI governance adapter pip install "govagent[langchain]" # langchain-core, langchain-openai, openai pip install "govagent[openai]" # OpenAIClient and AzureOpenAIClient pip install "govagent[anthropic]" # AnthropicClient pip install "govagent[mcp]" # official MCP SDK used by GovernedMCPGateway # Presidio's AnalyzerEngine (used by PrivacyGuard) requires the large English spaCy model python -m spacy download en_core_web_lg # Local repository development poetry install --with dev --extras "crewai enterprise" python -m spacy download en_core_web_lg
ExecutiveAgent always constructs SemanticGuard during initialization. The enterprise extra (sentence-transformers) enables local all-MiniLM-L6-v2 checks. Without it, ExecutiveAgent still constructs; SemanticGuard logs a warning and fails open. A base pip install govagent==3.5.0 is sufficient to import and instantiate the core classes. Optional extras openai, anthropic, and mcp add cloud model clients and the official MCP SDK.
Core Concepts
Policy Projection Mechanics
Policy retains the raw YAML dictionary in policy.config and projects normalized attributes for runtime enforcement:
| YAML Key | Projected Attribute | Runtime Behavior |
|---|---|---|
metadata | metadata, agent_name | Defaults agent_name to UnknownAgent if omitted. |
tools (list of dicts with name) | tool_rules, allowed_tools | Contributes to the allow-list (entries win over registry_alignment for the same name). Allow-list membership is enforced at execute / perform_action time. On initialization, validate_registry() still raises PermissionError if a tool's decorator risk_level is lower than the YAML specification. |
infrastructure.routing_mode / default_provider / rules | routing_mode, default_provider, routing_rules | Defaults to LOCAL_ONLY and local_ollama. |
fiscal_governance.global_limits and/or top-level global_limits | global_limits | Top-level keys take precedence over nested keys. Nested recursive_tco_limit is normalized to recursive_tco_ceiling. If no top-level block is defined, defaults inject daily_budget_usd: 10.0. |
alignment | alignment | Forwarded to SemanticGuard as mission_statement, prohibited_strategies, and min_similarity_score (default 0.85). |
judiciary (top-level) | judiciary_settings | Defaults to Slack, confidence 0.9, timeout 300s. If the top-level key is absent, settings are taken from oversight.judiciary. oversight itself is projected onto policy.oversight. |
registry_alignment.* | tool_rules, high_risk_tools, allowed_tools | Projected. allowed_tools / high_risk_tools seed the allow-list and high-risk set. A top-level tools: entry still wins for the same name. is_high_risk() is true when the name is in high_risk_tools or the rule has require_human_approval / risk_level == "high". |
The Execution Lifecycle
ExecutiveAgent.aexecute(task) runs an asynchronous control loop capped at 10 iterations. await agent.execute(task) is an unchanged awaitable wrapper around that method:
- Context & Privacy: Binds the active agent on a
contextvarand redacts PII from the input prompt viaPrivacyGuard.redact_task. - Telemetry, Semantic & Sandbox Check: Starts a telemetry trace and runs SemanticGuard on the sanitized task. If
router is None, returns with statussuccessand outputTask complete (Test Sandbox Mode). - LLM Inference: Constructs an
LLMRequest(temperature0.0, system instructionYou are a {persona}. Corporate Policy Boundaries apply.) and invokesrouter.route_and_generate. - Completion Check: If the response contains no tool calls, or the action is
complete(including the substring βcompleteβ in response text), terminates withTask complete. - Schema Validation: Executes
registry.validate_intent_schema. Invalid monetary values, schema violations, or unregistered tools terminate the run asblocked(noterror). - Fiscal & Judiciary Guards: Calls
CircuitBreaker.evaluate(semantic thought, per-transaction ceiling, then fiscal TCO). Judiciary approval triggers whenpolicy.is_high_risk(action)isTrue. - Action Dispatch:
perform_actionenforces the allow-list, verifies Harbor when OCI fields are set, and invokes the registered callable (returningstr(result)). If the action name isexecute_financial_transaction, the loop exits immediately after that step (maximum 10 steps otherwise). - Terminal States: Any
GovernanceViolationmaps toblocked; unhandled exceptions map toerror; exceeding 10 steps maps totimeout.
CircuitBreaker.evaluate runs semantic alignment, per-transaction caps, and fiscal TCO. Harbor verification runs from perform_action when OCI fields are present. Optional OpenAIClient, AzureOpenAIClient, and AnthropicClient can be registered on a router; GovernedMCPGateway applies the same rails to MCP or local tool calls.
Core Use Cases
All examples below are verified against src/govagent. Dynamic identifiers such as trace IDs, export IDs, and SHA-256 seals vary per execution.
Loading policies/finance_policy.yaml demonstrates how nested fiscal limits are normalized. This sample's registry_alignment is now projected, so allowed_tools and is_high_risk("execute_financial_transaction") are enforced. Omitted keys (max_per_transaction, max_tokens_per_run) still inherit default values.
from govagent.policy import Policy
policy = Policy.from_yaml("policies/finance_policy.yaml")
print(policy.agent_name)
print(policy.routing_mode, policy.default_provider)
print(policy.global_limits)
print(policy.allowed_tools)
print(policy.is_high_risk("execute_financial_transaction"))
print(hasattr(policy, "oversight"))
π Compliance Audit: Aligning code with 'Healthcare Finance Director' policy...
β
Governance Alignment: Registry and Policy are synchronized.
Healthcare Finance Director
HYBRID local_ollama
{'daily_budget_usd': 100.0, 'max_per_transaction': 2000.0, 'max_tokens_per_run': 4000, 'transaction_ceiling': 2000.0, 'recursive_tco_ceiling': 500.0}
['execute_financial_transaction', 'audit_transaction_logs']
True
True
A policy omitting fiscal configuration defaults to a 10.0 USD daily budget. Providing a top-level global_limits block overrides explicit keys without injecting unselected defaults:
Policy({"metadata": {"agent_name": "Plain"}}).global_limits
# {'daily_budget_usd': 10.0, 'max_per_transaction': 2000.0, 'max_tokens_per_run': 4000}
Policy({
"metadata": {"agent_name": "Override"},
"global_limits": {"daily_budget_usd": 7},
"fiscal_governance": {"global_limits": {"daily_budget_usd": 100, "recursive_tco_limit": 40}},
}).global_limits
# {'daily_budget_usd': 7, 'recursive_tco_ceiling': 40}
Import tool and registry from the top-level package. The decorator accepts name, description, risk_level (default "low"), oci_repository, artifact_digest, and schema. Tools named execute_financial_transaction automatically validate against FinancialTransactionIntent (amount required, extra fields forbidden) unless overridden.
from govagent import tool, registry, Policy
@tool(name="execute_financial_transaction", risk_level="high")
def execute_financial_transaction(amount: float):
return amount
policy = Policy({
"metadata": {"agent_name": "Treasury"},
"tools": [
{"name": "execute_financial_transaction", "risk_level": "high", "require_human_approval": True}
],
})
print(policy.allowed_tools)
print(policy.is_high_risk("execute_financial_transaction"))
print(registry.validate_intent_schema("execute_financial_transaction", {"amount": 10}))
print(registry.validate_intent_schema("not_a_published_tool", {}))
π Compliance Audit: Aligning code with 'Treasury' policy...
β
Governance Alignment: Registry and Policy are synchronized.
['execute_financial_transaction']
True
{'valid': True, 'status': 'AUTHORIZED'}
{'valid': False, 'error': 'Tool not legislated'}
Common boundary and schema exceptions raised during initialization or validation:
# Registered tool missing from a non-empty tools: list PermissionError: π UNAUTHORIZED TOOL DETECTED: 'unauthorized_shell' violates policy boundary. # YAML risk_level is higher than the @tool risk_level PermissionError: π GOVERNANCE VIOLATION: Risk downgrade detected for 'pay_vendor'. # Non-numeric amount on the financial schema ValidationError: Invalid monetary value: 'invalid_amt' is not a valid float. # Non-numeric amount on an unregistered tool containing an 'amount' key ValueError: Institutional Integrity Failure: 'amount' must be numeric.
Use ExecutiveAgent.bootstrap(policy_path, router_client, slack_channel=None) to load a YAML policy and initialize optional Slack HITL integration, or instantiate ExecutiveAgent directly. OllamaClient resides in govagent.llm.ollama.
Sandbox Mode (router=None)
import asyncio
from govagent.agent import ExecutiveAgent
from govagent.policy import Policy
policy = Policy({"metadata": {"agent_name": "SandboxDirector"}})
agent = ExecutiveAgent(persona="Director", policy=policy, router=None)
result = asyncio.run(agent.execute("Approve an urgent transaction of $8,500 to buy compute nodes."))
print(result.status, result.output)
print(result.metrics)
success Task complete (Test Sandbox Mode).
{'fiscal_impact': 0.0, 'total_tokens': 0, 'recursive_tco_usd': 0.0, 'selected_model': 'mock_sandbox'}
The return value is a govagent.registry.schemas.ExecutionSnapshot. Runtime telemetry metrics are populated inside result.metrics.
Custom Router Integration
Any router implementing an async route_and_generate(request, context) -> LLMResponse method can drive execution. Setting risk_level="low" avoids triggering the blocking CLI HITL prompt during automated testing:
from govagent import tool, Policy
from govagent.agent import ExecutiveAgent
from govagent.llm.base import LLMResponse
@tool(name="execute_financial_transaction", risk_level="low")
def _payment(amount: float):
return f"PAID {amount}"
class GoodRouter:
async def route_and_generate(self, request, context):
return LLMResponse(
text="I will execute the payment now.",
tool_calls=[{"name": "execute_financial_transaction", "args": {"amount": 10}}],
raw_usage={"total_tokens": 4},
model_name="scripted",
)
policy = Policy({
"metadata": {"agent_name": "Treasury"},
"fiscal_governance": {"global_limits": {"daily_budget_usd": 100.0, "recursive_tco_limit": 150.0}},
})
agent = ExecutiveAgent(persona="Director", policy=policy, router=GoodRouter())
result = await agent.execute("Pay an invoice")
# Valid tool execution
status: success
output: Action execute_financial_transaction executed with params {'amount': 10}
metrics: {'fiscal_impact': 10, 'total_tokens': 4, 'recursive_tco_usd': 0.0, 'selected_model': 'local_ollama'}
# Invalid monetary argument β mapped to blocked status
status: blocked
output: Schema Violation: 1 validation error for FinancialTransactionIntent
amount
Value error, Invalid monetary value: 'invalid_amt' is not a valid float.
# Unregistered tool call
status: blocked
output: Schema Violation: Tool not legislated
# Text response containing "complete" with no tool_calls
status: success
output: Task complete.
LLMResponse.raw_usage is strictly typed as Dict[str, int]; passing float values (e.g., estimated_cost_usd: 0.01) causes Pydantic validation to fail and sets execution status to error. (2) metrics["selected_model"] inspects response.selected_model before falling back to default_provider when local_ollama is configured.
CircuitBreaker sums the thread-isolated swarm spend ledger with the projected transaction cost and enforces min(recursive_tco_ceiling, daily_budget_usd) (evaluating to min(500, 100) = 100 for the sample finance policy). If both keys are omitted, defaults are ceiling 150.0 and daily budget 100.0.
from govagent.policy import Policy
from govagent.guards.circuit_breaker import CircuitBreaker, GovernanceViolation
from govagent.context import reset_fiscal_ledger, update_shared_spend, get_shared_fiscal_metrics
policy = Policy.from_yaml("policies/finance_policy.yaml")
reset_fiscal_ledger()
breaker = CircuitBreaker(policy, semantic_guard=None)
breaker.check_financial_risk(90.0) # Allowed (90.0 <= 100.0)
try:
breaker.check_financial_risk(150.0) # Blocked (150.0 > 100.0)
except GovernanceViolation as exc:
print(exc)
update_shared_spend(80.0)
print(get_shared_fiscal_metrics())
try:
breaker.check_financial_risk(30.0) # Blocked (80.0 + 30.0 = 110.0 > 100.0)
except GovernanceViolation as exc:
print(exc)
RECURSIVE TCO REJECT: Projected swarm spend $150.00 exceeds the institutional limit of $100.00.
{'cumulative_spend': 80.0, 'task_counter': 1.0}
RECURSIVE TCO REJECT: Projected swarm spend $110.00 exceeds the institutional limit of $100.00.
When breached during ExecutiveAgent.execute (e.g., amount=200 against a 100 limit), the run halts cleanly:
status: blocked
output: RECURSIVE TCO REJECT: Projected swarm spend $200.00 exceeds the institutional limit of $100.00.
metrics: {'fiscal_impact': 0.0, 'total_tokens': 8, 'recursive_tco_usd': 0.0, 'selected_model': 'local_ollama'}
PrivacyGuard.redact_task runs Microsoft Presidio across PERSON, LOCATION, PHONE_NUMBER, and EMAIL_ADDRESS entities alongside a custom street-address recognizer. ExecutiveAgent.execute sanitizes the user prompt prior to LLM dispatch.
from govagent.policy import Policy
from govagent.guards.privacy import PrivacyGuard
guard = PrivacyGuard(Policy({"metadata": {"agent_name": "PrivacyDemo"}}))
print(guard.redact_task("Pay John Doe at 123 Main St for invoice #99."))
Pay <PERSON> at <LOCATION> for invoice #99.
PrivacyGuard.redact_task sets last_execution_had_pii when entities are found, so HYBRID contains_pii routing can fire. anonymize() is provided as an alias of redact_task.
HarborVerifier queries Harbor v2 APIs when configured with a live robot token (HARBOR_ROBOT_TOKEN). Tokens matching "mock-token", "mock", or starting with "mock-" operate in offline stub mode, rejecting repositories containing malicious and passing all others. registry.verify_and_resolve_tool triggers verification whenever both oci_repository and artifact_digest are declared on @tool.
from govagent.registry.harbor_verifier import HarborVerifier
from govagent import tool, registry
h = HarborVerifier(robot_token="mock-token")
print(h.verify_tool_artifact("bizzteq/finance-utils", "sha256:abc"))
print(h.verify_tool_artifact("malicious/wipe", "sha256:abc"))
@tool(name="database_wipe", risk_level="high",
oci_repository="malicious/db", artifact_digest="sha256:dead")
def database_wipe():
return "wiped"
registry.verify_and_resolve_tool("database_wipe")
{'verified': True, 'reason': 'COSIGN_SIGNATURE_VALIDATED', 'details': 'Offline mock-token stub. This result is not a Harbor verdict.'}
{'verified': False, 'reason': 'CRITICAL_VULNERABILITY_FOUND', 'details': 'Scan discovered CVE-2026-9999 (High Severity Risk Level).'}
GovernanceViolation: HARBOR REGISTRY BLOCK: Tool failed image validation. Details: Scan discovered CVE-2026-9999 (High Severity Risk Level).
# Unregistered tool resolution
GovernanceViolation: REGISTRY EXCEPTION: Tool 'unregistered_arbitrary_shell_script' is not authorized.
With a live robot token, HarborVerifier fails closed: unreachable registries, non-200 HTTP responses, missing vulnerability scans, missing Cosign signatures, or High/Critical CVEs all return verified: False.
RoutingMode supports LOCAL_ONLY, CLOUD_ONLY, and HYBRID. Initialization raises a ValueError if default_provider is absent from the clients dictionary. Conditional RoutingRule evaluation executes only in HYBRID mode.
from govagent.llm.router import PolicyBasedRouter, RouterConfig, RoutingMode, RoutingRule
from govagent.llm.base import BaseLLMClient, LLMRequest, LLMResponse
class Dummy(BaseLLMClient):
async def generate(self, request: LLMRequest) -> LLMResponse:
return LLMResponse(text="ok", model_name="dummy", raw_usage={"total_tokens": 1})
clients = {"local_ollama": Dummy({}), "cloud_openai": Dummy({})}
hybrid = PolicyBasedRouter(clients, RouterConfig(
routing_mode=RoutingMode.HYBRID,
default_provider="local_ollama",
rules=[
RoutingRule(condition_key="contains_pii", expected_value=True, target_provider="local_ollama"),
RoutingRule(condition_key="tool_complexity", expected_value="high", target_provider="cloud_openai"),
],
))
print(hybrid.determine_target({"contains_pii": True}))
print(hybrid.determine_target({"tool_complexity": "high"}))
print(hybrid.determine_target({}))
local_ollama cloud_openai local_ollama # LOCAL_ONLY bypasses rules and always selects default_provider # HYBRID rules pointing to an unconfigured client log an alert and fall back to default_provider # Missing default_provider at construction: ValueError: π GOVERNANCE CRASH: Router misconfiguration. The default provider 'cloud_openai' requested by the policy was not loaded. Available clients: ['local_ollama']
govagent.governance exports MetaGovernor, CFOAnalyticsEngine, ComplianceDossier, and EvidencePackGenerator for post-execution audit, financial telemetry, and autonomous policy tuning.
EvidencePackGenerator
Ingests a JSONL audit buffer (defaulting to logs/audit_buffer.jsonl). BLOCKED or VETOED events increment EU AI Act Article 9 counters when block_reason matches PII/PRIVACY, SEMANTIC, or HARBOR/CVE. Calling seal() computes a deterministic dossier_sha256 digest.
from govagent.governance import EvidencePackGenerator dossier = EvidencePackGenerator(buffer_path="audit.jsonl").generate(system_anchor="govagent-help-demo") print(dossier.framework_version, dossier.dossier_sha256)
CFOAnalyticsEngine
record_execution (aliased as record_snapshot and record_transaction) aggregates recursive_tco_usd and total_tokens by cost_center (default CC-GENAI-DEFAULT, GL GL-640100-SOFTWARE). analyze() accumulates requested_exposure_usd into value-at-risk for exact BLOCKED or PENDING statuses and flags burn_rate_anomaly_detected when spend exceeds 0.50.
MetaGovernor
analyze_friction() inspects a JSONL audit trail (default logs/audit_trail.jsonl). Entries whose status contains both REJECT/BLOCKED and TCO/FISCAL increment the friction counter. Reaching friction_threshold (default 3) emits a POLICY_AMENDMENT_PROPOSAL setting proposed_limit = max(current_limit * 1.20, avg_request * 1.10):
{
"type": "POLICY_AMENDMENT_PROPOSAL",
"version": "1.0.0",
"reason": "Systemic blockage intercepted: 3 consecutive TCO budget rejections encountered.",
"target_policy": "finance_policy.yaml",
"metric_breached": "recursive_tco_usd",
"current_limit": 100.0,
"proposed_limit": 176.0,
"impact_assessment": "Mitigates operational friction across autonomous sub-agent delegation domains, restoring workspace automation liquidity."
}
Optional framework integrations are also available via submodules: GovAgentEnforcer(crew, policy_path) in govagent.extensions.crewai.enforcer, BobMCPProxyGateway.govern_mcp_tool(name, fn) in govagent.extensions.ibm.bob_mcp_proxy, and GovernedMCPGateway in govagent.extensions.mcp.
Complete API Reference
Top-level exports in govagent.__all__: __version__, ExecutiveAgent, Policy, tool, registry, get_current_agent, BaseLLMClient, LLMRequest, LLMResponse, PolicyBasedRouter, RouterConfig, RoutingMode.
| Symbol | Signature | Behavior |
|---|---|---|
Policy(config) | Policy(config: dict) | Projects limits, routing, alignment, oversight, and tool rules. Init still audits risk downgrades; allow-list membership is enforced at execute time. |
Policy.from_yaml | from_yaml(path: str) -> Policy | Reads UTF-8 YAML via yaml.safe_load. |
Policy.allowed_tools | @property -> list[str] | Tool names projected from registry_alignment and/or the top-level tools: list (tools win per name). |
Policy.get_tool_config | get_tool_config(tool_name) -> dict | Returns rule dict for tool_name, or {} if absent. |
Policy.is_high_risk | is_high_risk(tool_name) -> bool | True if the name is in high_risk_tools, or the rule has require_human_approval or risk_level == "high". |
tool | tool(name=None, description=None, risk_level="low", oci_repository=None, artifact_digest=None, schema=None) | Registers callable on GlobalRegistry. Name defaults to func.__name__. |
registry.validate_intent_schema | validate_intent_schema(tool_name, arguments) -> dict | Returns {"valid": True, "status": "AUTHORIZED"} or {"valid": False, "error": "Tool not legislated"}. Invalid amounts raise. |
registry.verify_and_resolve_tool | verify_and_resolve_tool(tool_name) -> Callable | Enforces Harbor OCI verification when repository/digest are set. Raises GovernanceViolation. |
registry.validate_against_policy | validate_against_policy(allowed_tools) -> bool | Raises PermissionError if a registered tool is missing from a non-empty list. |
ExecutiveAgent | __init__(persona, policy, router, telemetry=None, hitl_manager=None) | Initializes agent and constructs SemanticGuard from policy.alignment. |
ExecutiveAgent.bootstrap | bootstrap(policy_path, router_client, slack_channel=None) | Factory loading YAML and configuring Slack HITL via SLACK_BOT_TOKEN / SLACK_APP_TOKEN. |
ExecutiveAgent.execute | async execute(task: str) -> ExecutionSnapshot | Awaitably wraps aexecute. Terminal statuses: success, blocked, error, timeout. |
ExecutiveAgent.aexecute | async aexecute(task: str) -> ExecutionSnapshot | Explicit async execute loop. Sync callers can use asyncio.run(agent.aexecute(...)). |
ExecutiveAgent.evaluate | async evaluate(guards, intent=None, value=0.0) | Runs fiscal circuit breaker and conditional HITL judiciary checks. |
ExecutiveAgent.perform_action | async perform_action(action, params) -> str | Allow-list, Harbor when OCI fields are set, then the registered callable; returns str(result). |
ExecutiveAgent.post_session_cleanup | async post_session_cleanup() | Runs MetaGovernor on logs/audit_trail.jsonl (threshold 3) and escalates proposals. |
CircuitBreaker.check_financial_risk | check_financial_risk(local_projected_cost) | Raises GovernanceViolation (RECURSIVE TCO REJECT) when ceiling is breached. |
PrivacyGuard.redact_task | redact_task(text) -> str | Presidio PII anonymization. Requires en_core_web_lg. |
SemanticGuard | __init__(mission, prohibited, threshold=0.60) / evaluate_alignment(thought) -> float | Empty thought or empty prohibited list returns 1.0. Breach returns 0.0. |
RouterConfig / RoutingRule | Pydantic models | Rule schema: condition_key, expected_value, target_provider. |
PolicyBasedRouter.determine_target | determine_target(context_metadata) -> str | Evaluates routing mode and rules to select provider key. |
PolicyBasedRouter.route_and_generate | async route_and_generate(request, context_metadata) -> LLMResponse | Resolves target client and awaits client.generate(request). |
OllamaClient.generate | async generate(request) -> LLMResponse | POST /api/generate (60s timeout). Raises RuntimeError on non-200 status. |
LLMRequest / LLMResponse | Pydantic models | Request/response envelopes. raw_usage accepts int or float values such as estimated_cost_usd. selected_model aliases model_name. |
TelemetryManager | __init__(buffer_path="logs/audit_buffer.jsonl") | Manages start_trace, log_step, add_exporter, and async finalize. Writes logs/audit_trail.jsonl by default (disable with GOVAGENT_DISABLE_AUDIT_LOG=1 or persist_jsonl=False). |
| Context Helpers | set_current_agent, get_current_agent, reset_current_agent | Contextvar accessors for parent-trace inheritance across sub-agents. |
| Ledger Helpers | reset_fiscal_ledger, update_shared_spend, get_shared_fiscal_metrics | Thread-isolated swarm spend tracking (cumulative_spend, task_counter). |
HITLManager.secure_approval | async secure_approval(agent_id, reason, context=None, triggered_by="policy", config=None) -> bool | Quorum scoring: amount ≥ 5000 requires 4.0 (TIER_3), ≥ 1000 requires 2.5 (TIER_2), else 1.0. Weights: C-Suite 3.0, Director 2.0, Auditor 1.5, Lead 1.0, Clerk 0.5. Any REJECTED vote vetoes. |
EvidencePackGenerator.generate | generate(system_anchor="govagent-enterprise-mesh") -> ComplianceDossier | Aggregates audit logs, attaches packaged control IDs and a not-a-certification disclaimer, and seals the returned ComplianceDossier. |
OpenAIClient, AzureOpenAIClient, AnthropicClient | async generate(request) -> LLMResponse | Optional extras govagent[openai] and govagent[anthropic]. Map tool calls and usage/cost onto LLMResponse. |
GovernedMCPGateway | async call_tool(name, arguments, session=None, fn=None) | Optional extra govagent[mcp]. Governs MCP or local tool calls with allow-list, PrivacyGuard, SemanticGuard, fiscal breaker, HITL, and audit log. |
govagent.compliance.load_control_mapping | load_control_mapping() -> dict | Loads packaged controls.yaml (EU AI Act, ISO/IEC 42001 Annex A, NIST AI RMF). Not a certification. |
CFOAnalyticsEngine.analyze | analyze() -> CFORiskReport | Computes cost center rollups, value-at-risk, and burn-rate anomalies. |
MetaGovernor.analyze_friction | analyze_friction() -> dict | Detects recurring TCO rejections and generates policy limit amendments. |
PricingEngine.calculate_cost | calculate_cost(model, tokens) -> float | Instance method in govagent.pricing (default 10% markup). |
Errors & Behavior Notes
| Exception / Status | Trigger Condition |
|---|---|
SemanticGuard without enterprise | No longer raises ImportError. Vector checks fail open and a warning is logged until govagent[enterprise] is installed. |
PermissionError UNAUTHORIZED TOOL | A registered tool is missing from a non-empty projected allow-list (enforced at execute / perform_action; registry.validate_against_policy still raises if called). |
PermissionError Risk downgrade | YAML risk_level exceeds the decorator's risk_level (low < medium < high). |
GovernanceViolation RECURSIVE TCO REJECT | Projected swarm spend exceeds min(recursive_tco_ceiling, daily_budget_usd). |
GovernanceViolation REGISTRY EXCEPTION | Calling verify_and_resolve_tool on an unregistered tool name. |
GovernanceViolation HARBOR REGISTRY BLOCK | Harbor v2 (or the offline malicious stub) failed image signature or CVE verification. |
GovernanceViolation Human Judiciary denied | secure_approval returned False or received a veto vote. |
ValidationError / ValueError | Malformed tool arguments; caught by execute() and surfaced as status blocked. |
ValueError Router misconfiguration | Configured default_provider is not present in the router's client map. |
RuntimeError Ollama inference failed | Non-200 HTTP response from the Ollama /api/generate endpoint. |
Execution status error | Any non-governance exception during execution. Float values such as estimated_cost_usd in LLMResponse.raw_usage are accepted and do not cause this status. |
SemanticGuard Calibration Note: Evaluated against the sample finance prohibited strategies list, an empty string returns 1.0, a standard budget query scores ~0.813, and an overtly adversarial prompt (βWe should pursue aggressive tax avoidance and predatory pricing against patients.β) scores ~0.293. Because SemanticGuard triggers a breach (0.0) when cosine similarity exceeds the configured threshold, setting min_similarity_score: 0.85 is permissive for all-MiniLM-L6-v2; thresholds around 0.30β0.45 provide tighter semantic enforcement.
pyproject.toml and govagent.__version__ are 3.5.0. ComplianceDossier.framework_version defaults to that package version. Sample templates under policies/ still carry document header version 0.6.0; their registry_alignment blocks are projected and enforced. This release includes aexecute, GovernedMCPGateway, the packaged control catalogue, and the optional cloud clients. None of this is a certification.
Interactive Policy Projector
Browser port of govagent.policy._project_global_limits and Policy.is_high_risk. Paste a policy configuration as JSON to inspect how Policy normalizes limits, registry_alignment / tools: allow-lists, and effective circuit breaker ceilings at runtime.