govAgent v3.5.0
Enterprise AI Governance SDK

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.

Python >=3.10,<3.14 PyPI: govagent 3.5.0 MIT License Extras: crewai, langchain, enterprise, openai, anthropic, mcp

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 CaseEntry PointReturnsImplementation 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

PyPI Package and Optional Extras pyproject.toml 3.5.0

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
Runtime Dependency Note: 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 KeyProjected AttributeRuntime Behavior
metadatametadata, agent_nameDefaults agent_name to UnknownAgent if omitted.
tools (list of dicts with name)tool_rules, allowed_toolsContributes 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 / rulesrouting_mode, default_provider, routing_rulesDefaults to LOCAL_ONLY and local_ollama.
fiscal_governance.global_limits and/or top-level global_limitsglobal_limitsTop-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.
alignmentalignmentForwarded to SemanticGuard as mission_statement, prohibited_strategies, and min_similarity_score (default 0.85).
judiciary (top-level)judiciary_settingsDefaults 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_toolsProjected. 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:

  1. Context & Privacy: Binds the active agent on a contextvar and redacts PII from the input prompt via PrivacyGuard.redact_task.
  2. Telemetry, Semantic & Sandbox Check: Starts a telemetry trace and runs SemanticGuard on the sanitized task. If router is None, returns with status success and output Task complete (Test Sandbox Mode).
  3. LLM Inference: Constructs an LLMRequest (temperature 0.0, system instruction You are a {persona}. Corporate Policy Boundaries apply.) and invokes router.route_and_generate.
  4. Completion Check: If the response contains no tool calls, or the action is complete (including the substring β€œcomplete” in response text), terminates with Task complete.
  5. Schema Validation: Executes registry.validate_intent_schema. Invalid monetary values, schema violations, or unregistered tools terminate the run as blocked (not error).
  6. Fiscal & Judiciary Guards: Calls CircuitBreaker.evaluate (semantic thought, per-transaction ceiling, then fiscal TCO). Judiciary approval triggers when policy.is_high_risk(action) is True.
  7. Action Dispatch: perform_action enforces the allow-list, verifies Harbor when OCI fields are set, and invokes the registered callable (returning str(result)). If the action name is execute_financial_transaction, the loop exits immediately after that step (maximum 10 steps otherwise).
  8. Terminal States: Any GovernanceViolation maps to blocked; unhandled exceptions map to error; exceeding 10 steps maps to timeout.
Scope of Execution Loop: 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.

Use Case 1: Load a YAML Policy & Inspect Projected Limits Policy.from_yaml

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"))
Verified Output
πŸ“‹ 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}
Use Case 2: Legislate Tools & Validate Intents @tool + registry

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", {}))
Verified Output
πŸ“‹ 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 Case 3: Execute a Governed Task ExecutiveAgent.execute

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)
Verified Output
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")
Observed Snapshot Outcomes
# 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.
Implementation Quirks: (1) 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.
Use Case 4: Fiscal Circuit Breaker CircuitBreaker

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)
Verified Output
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'}
Use Case 5: Privacy Redaction PrivacyGuard

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."))
Verified Output
Pay <PERSON> at <LOCATION> for invoice #99.
Routing Context Note: 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.
Use Case 6: Harbor OCI Artifact Verification HarborVerifier

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 Output
{'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.

Use Case 7: Policy-Based LLM Router PolicyBasedRouter

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({}))
Verified Output
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']
Use Case 8: Evidence Pack, CFO Analytics & MetaGovernor govagent.governance

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):

Generated Policy Amendment Proposal (Threshold = 3)
{
  "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.

SymbolSignatureBehavior
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_yamlfrom_yaml(path: str) -> PolicyReads 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_configget_tool_config(tool_name) -> dictReturns rule dict for tool_name, or {} if absent.
Policy.is_high_riskis_high_risk(tool_name) -> boolTrue if the name is in high_risk_tools, or the rule has require_human_approval or risk_level == "high".
tooltool(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_schemavalidate_intent_schema(tool_name, arguments) -> dictReturns {"valid": True, "status": "AUTHORIZED"} or {"valid": False, "error": "Tool not legislated"}. Invalid amounts raise.
registry.verify_and_resolve_toolverify_and_resolve_tool(tool_name) -> CallableEnforces Harbor OCI verification when repository/digest are set. Raises GovernanceViolation.
registry.validate_against_policyvalidate_against_policy(allowed_tools) -> boolRaises 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.bootstrapbootstrap(policy_path, router_client, slack_channel=None)Factory loading YAML and configuring Slack HITL via SLACK_BOT_TOKEN / SLACK_APP_TOKEN.
ExecutiveAgent.executeasync execute(task: str) -> ExecutionSnapshotAwaitably wraps aexecute. Terminal statuses: success, blocked, error, timeout.
ExecutiveAgent.aexecuteasync aexecute(task: str) -> ExecutionSnapshotExplicit async execute loop. Sync callers can use asyncio.run(agent.aexecute(...)).
ExecutiveAgent.evaluateasync evaluate(guards, intent=None, value=0.0)Runs fiscal circuit breaker and conditional HITL judiciary checks.
ExecutiveAgent.perform_actionasync perform_action(action, params) -> strAllow-list, Harbor when OCI fields are set, then the registered callable; returns str(result).
ExecutiveAgent.post_session_cleanupasync post_session_cleanup()Runs MetaGovernor on logs/audit_trail.jsonl (threshold 3) and escalates proposals.
CircuitBreaker.check_financial_riskcheck_financial_risk(local_projected_cost)Raises GovernanceViolation (RECURSIVE TCO REJECT) when ceiling is breached.
PrivacyGuard.redact_taskredact_task(text) -> strPresidio PII anonymization. Requires en_core_web_lg.
SemanticGuard__init__(mission, prohibited, threshold=0.60) / evaluate_alignment(thought) -> floatEmpty thought or empty prohibited list returns 1.0. Breach returns 0.0.
RouterConfig / RoutingRulePydantic modelsRule schema: condition_key, expected_value, target_provider.
PolicyBasedRouter.determine_targetdetermine_target(context_metadata) -> strEvaluates routing mode and rules to select provider key.
PolicyBasedRouter.route_and_generateasync route_and_generate(request, context_metadata) -> LLMResponseResolves target client and awaits client.generate(request).
OllamaClient.generateasync generate(request) -> LLMResponsePOST /api/generate (60s timeout). Raises RuntimeError on non-200 status.
LLMRequest / LLMResponsePydantic modelsRequest/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 Helpersset_current_agent, get_current_agent, reset_current_agentContextvar accessors for parent-trace inheritance across sub-agents.
Ledger Helpersreset_fiscal_ledger, update_shared_spend, get_shared_fiscal_metricsThread-isolated swarm spend tracking (cumulative_spend, task_counter).
HITLManager.secure_approvalasync secure_approval(agent_id, reason, context=None, triggered_by="policy", config=None) -> boolQuorum 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.generategenerate(system_anchor="govagent-enterprise-mesh") -> ComplianceDossierAggregates audit logs, attaches packaged control IDs and a not-a-certification disclaimer, and seals the returned ComplianceDossier.
OpenAIClient, AzureOpenAIClient, AnthropicClientasync generate(request) -> LLMResponseOptional extras govagent[openai] and govagent[anthropic]. Map tool calls and usage/cost onto LLMResponse.
GovernedMCPGatewayasync 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_mappingload_control_mapping() -> dictLoads packaged controls.yaml (EU AI Act, ISO/IEC 42001 Annex A, NIST AI RMF). Not a certification.
CFOAnalyticsEngine.analyzeanalyze() -> CFORiskReportComputes cost center rollups, value-at-risk, and burn-rate anomalies.
MetaGovernor.analyze_frictionanalyze_friction() -> dictDetects recurring TCO rejections and generates policy limit amendments.
PricingEngine.calculate_costcalculate_cost(model, tokens) -> floatInstance method in govagent.pricing (default 10% markup).

Errors & Behavior Notes

Exception / StatusTrigger Condition
SemanticGuard without enterpriseNo longer raises ImportError. Vector checks fail open and a warning is logged until govagent[enterprise] is installed.
PermissionError UNAUTHORIZED TOOLA 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 downgradeYAML risk_level exceeds the decorator's risk_level (low < medium < high).
GovernanceViolation RECURSIVE TCO REJECTProjected swarm spend exceeds min(recursive_tco_ceiling, daily_budget_usd).
GovernanceViolation REGISTRY EXCEPTIONCalling verify_and_resolve_tool on an unregistered tool name.
GovernanceViolation HARBOR REGISTRY BLOCKHarbor v2 (or the offline malicious stub) failed image signature or CVE verification.
GovernanceViolation Human Judiciary deniedsecure_approval returned False or received a veto vote.
ValidationError / ValueErrorMalformed tool arguments; caught by execute() and surfaced as status blocked.
ValueError Router misconfigurationConfigured default_provider is not present in the router's client map.
RuntimeError Ollama inference failedNon-200 HTTP response from the Ollama /api/generate endpoint.
Execution status errorAny 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.

Metadata & Version Notes: 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.

Policy Input (JSON)
Projected Runtime Policy