### LangChain Quickstart Example Source: https://github.com/akios-ai/enforcecore/blob/main/CHANGELOG.md A copy-paste example demonstrating the EnforceCore callback handler with LangChain. This example requires no API key setup. ```python # examples/quickstart_langchain.py # This file demonstrates the EnforceCoreCallbackHandler in action. # No API key is required for this example. ``` -------------------------------- ### AutoGen Quickstart Example Source: https://github.com/akios-ai/enforcecore/blob/main/CHANGELOG.md A basic example demonstrating EnforceCore integration with AutoGen, including per-agent policy scoping. ```python import enforcecore # Example usage (replace with actual AutoGen integration) agent_message = "User message with sensitive data." enforced_message = enforcecore.enforce_sync(agent_message) print(enforced_message) ``` -------------------------------- ### LangGraph Quickstart Example Source: https://github.com/akios-ai/enforcecore/blob/main/CHANGELOG.md A basic example demonstrating EnforceCore integration with LangGraph for allow/deny enforcement and PII redaction. ```python import enforcecore # Example usage (replace with actual LangGraph integration) agent_output = "This is a tool output with PII like email@example.com." enforced_output = enforcecore.enforce_sync(agent_output) print(enforced_output) ``` -------------------------------- ### Development Quick Start Source: https://github.com/akios-ai/enforcecore/blob/main/CONTRIBUTING.md Clone the repository and set up a development environment, including installing dependencies and running initial tests. ```bash git clone git@github.com:akios-ai/EnforceCore.git cd EnforceCore python3 -m venv .venv && source .venv/bin/activate pip install -e ".[dev]" pytest ``` -------------------------------- ### Quick Start Example Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api/witness.md Demonstrates how to collect witness hashes using CallbackWitness and verify them with verify_with_witness. ```APIDOC ## Quick Start Example This example shows how to use `CallbackWitness` to collect hashes and then verify them using `verify_with_witness`. ### Code ```python from enforcecore.auditor import Auditor from enforcecore.auditor.witness import CallbackWitness, verify_with_witness # Collect witness hashes hashes = [] witness = CallbackWitness(hashes.append) auditor = Auditor(output_path="audit.jsonl", witness=witness) # Record some entries auditor.record(tool_name="search", policy_name="strict") auditor.record(tool_name="calculator", policy_name="strict") # Verify trail against witness result = verify_with_witness("audit.jsonl", witness_hashes=[r.entry_hash for r in hashes]) assert result.is_valid ``` ``` -------------------------------- ### CrewAI Quickstart Example Source: https://github.com/akios-ai/enforcecore/blob/main/CHANGELOG.md A basic example demonstrating EnforceCore integration with CrewAI, focusing on automatic PII redaction for tool outputs. ```python import enforcecore # Example usage (replace with actual CrewAI integration) tool_result = "Tool result containing PII: John Doe, 123 Main St." enforced_result = enforcecore.enforce_sync(tool_result) print(enforced_result) ``` -------------------------------- ### Install and Use EnforceCore with Hatch Source: https://github.com/akios-ai/enforcecore/blob/main/docs/dev-guide.md An alternative setup using Hatch. Install Hatch, create a new environment, and then run commands within that environment. This is useful if you prefer Hatch for environment management. ```bash pip install hatch hatch env create hatch run python -c "import enforcecore; print(enforcecore.__version__)" ``` -------------------------------- ### Install EnforceCore Source: https://github.com/akios-ai/enforcecore/blob/main/docs/index.md Install the EnforceCore package using pip. ```bash pip install enforcecore ``` -------------------------------- ### Install EnforceCore Source: https://github.com/akios-ai/enforcecore/blob/main/docs/quickstart.md Install the EnforceCore library using pip. Use the `[all]` extra to include optional dependencies. ```bash pip install enforcecore ``` ```bash pip install enforcecore[all] ``` -------------------------------- ### Clone and Install EnforceCore with Pip Source: https://github.com/akios-ai/enforcecore/blob/main/docs/dev-guide.md Clone the repository, set up a Python virtual environment, and install EnforceCore in development mode with all dependencies. This is the standard method for setting up the project for local development. ```bash git clone git@github-akiosai:akios-ai/EnforceCore.git cd EnforceCore python3 -m venv .venv source .venv/bin/activate pip install -e ".[dev]" python -c "import enforcecore; print(enforcecore.__version__)" ``` -------------------------------- ### Install LangChain Integration Source: https://github.com/akios-ai/enforcecore/blob/main/docs/quickstart.md Install the `langchain-core` package to enable EnforceCore integration with LangChain. ```bash pip install langchain-core ``` -------------------------------- ### Install Auditstore Source: https://github.com/akios-ai/enforcecore/blob/main/docs/auditstore.md Install Auditstore as part of EnforceCore v1.2.0 or later using pip. ```bash pip install enforcecore>=1.2.0 ``` -------------------------------- ### Pre-release Version Examples Source: https://github.com/akios-ai/enforcecore/blob/main/docs/versioning.md Provides examples of pre-release identifiers used before stable releases. ```plaintext 1.0.0a1, 1.0.0b1, 1.0.0rc1 ``` -------------------------------- ### Install EnforceCore with Observability Options Source: https://github.com/akios-ai/enforcecore/blob/main/docs/roadmap.md Install EnforceCore with optional packages for OpenTelemetry traces and logs, or Prometheus metrics. These packages enable enhanced observability for enforcement decisions. ```bash pip install enforcecore pip install enforcecore[otel] # OpenTelemetry traces + logs pip install enforcecore[prometheus] # Prometheus metrics ``` -------------------------------- ### Clone and Setup EnforceCore Project Source: https://github.com/akios-ai/enforcecore/blob/main/README.md Clone the EnforceCore repository and set up a Python virtual environment with development dependencies. This is the initial step for contributing to or running the project locally. ```bash git clone https://github.com/akios-ai/EnforceCore.git cd EnforceCore python -m venv .venv && source .venv/bin/activate pip install -e ".[dev]" ``` -------------------------------- ### Configure Auditstore via Python Source: https://github.com/akios-ai/enforcecore/blob/main/docs/auditstore.md Instantiate an Auditor with a specific backend and configuration. This example shows setting up SQLite backend. ```python from enforcecore import enforce, Auditor from enforcecore.auditstore.backends import SQLiteBackend # Create auditor with auditstore auditor = Auditor( backend="sqlite", backend_config={"db_path": "audit.db"} ) # Use with decorator @enforce(policy="policy.yaml") def search(query: str) -> str: return api.search(query) # Auditor will now store to SQLite instead of JSONL ``` -------------------------------- ### Cascade Example Policies Source: https://github.com/akios-ai/enforcecore/blob/main/docs/formal/policy-algebra.md Illustrates the composition of three policies (org, team, project) with specific configurations for denied and allowed tools. ```yaml # org.yaml denied_tools: [dangerous_tool] allowed_tools: null # unrestricted ``` ```yaml # team.yaml denied_tools: [risky_tool] allowed_tools: [search, browse, code_exec] ``` ```yaml # project.yaml denied_tools: [] allowed_tools: [search, browse] ``` -------------------------------- ### Install EnforceCore for Multi-Tenant Support Source: https://github.com/akios-ai/enforcecore/blob/main/docs/roadmap.md Install the base EnforceCore package, which includes support for the MultiTenantEnforcer. This version enables hierarchical policy support and multi-tenant enforcement. ```bash pip install enforcecore # includes MultiTenantEnforcer ``` -------------------------------- ### Benchmark JSON Output Example Source: https://github.com/akios-ai/enforcecore/blob/main/docs/benchmarks.md Example of the JSON output format for benchmark results, including metadata and performance metrics. ```json { "metadata": { "timestamp": "2026-02-21T15:56:09Z", "python_version": "3.14.2", "platform": "Darwin arm64", "cpu": "arm", "machine": "arm64", "enforcecore_version": "1.0.0", "total_duration_ms": 1372.34 }, "results": [ { "name": "policy_pre_call", "iterations": 1000, "warmup_iterations": 100, "mean_ms": 0.0927, "p50_ms": 0.0118, "p95_ms": 0.0196, "p99_ms": 0.2275, "p999_ms": 69.3257, "std_dev_ms": 2.1955 } ] } ``` -------------------------------- ### Install PII Redaction Dependencies Source: https://github.com/akios-ai/enforcecore/blob/main/docs/faq.md Install EnforceCore with optional PII redaction capabilities, which include Presidio and spaCy. ```bash pip install enforcecore[pii] # installs presidio-analyzer + spaCy ``` -------------------------------- ### Run Multi-Framework Script Source: https://github.com/akios-ai/enforcecore/blob/main/examples/scenarios/multi_framework/README.md Navigate to the scenario directory and execute the main Python script to run the multi-framework agent example. This script will demonstrate EnforceCore's policy enforcement across different agent frameworks. ```bash cd examples/scenarios/multi_framework python multi_framework.py ``` -------------------------------- ### Example of Allowed and Blocked Tools Source: https://github.com/akios-ai/enforcecore/blob/main/README.md Demonstrates calling an allowed tool and defines a blocked tool. Calling a denied tool will raise a `ToolDeniedError`. ```python # ✅ Allowed — tool is in the allowed list result = await search_web("latest AI papers") # ❌ Blocked — tool not allowed, raises ToolDeniedError @enforce(policy="policy.yaml") async def execute_shell(cmd: str) -> str: return subprocess.run(cmd, capture_output=True).stdout ``` -------------------------------- ### Export EnforceCore Metrics with Prometheus Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Utilize EnforceCorePrometheusExporter to expose EnforceCore metrics in Prometheus format. Requires `enforcecore[prometheus]` installation. Can start an HTTP server to expose metrics. ```python from enforcecore import EnforceCorePrometheusExporter # Requires: pip install enforcecore[prometheus] exporter = EnforceCorePrometheusExporter() exporter.instrument() exporter.start_http_server(port=9090) ``` ```python def __init__(self, *, registry: Any = None) -> None # registry: prometheus_client.CollectorRegistry or None (uses global registry). # Operates in no-op mode if prometheus_client not installed — never raises on init. def instrument(self) -> None def uninstrument(self) -> None def start_http_server(self, port: int = 9090, addr: str = "0.0.0.0") -> None @property def is_instrumented(self) -> bool @property def is_available(self) -> bool ``` -------------------------------- ### CLI Crashes on Bare Install Source: https://github.com/akios-ai/enforcecore/blob/main/docs/issues-v1.1.1.md This reproduction demonstrates the crash when running `enforcecore --help` after a bare install due to missing 'typer' dependency. ```bash pip install enforcecore enforcecore --help # ModuleNotFoundError: No module named 'typer' ``` -------------------------------- ### Policy Inheritance Example Source: https://github.com/akios-ai/enforcecore/blob/main/docs/roadmap.md Example of policy inheritance using the 'extends' keyword in YAML. This allows for composable policies at different organizational granularities. ```yaml # agent_deployer.yaml extends: team_dev.yaml tools: allowed: [search, calculate, deploy_service] context: environment: [staging] ``` -------------------------------- ### Install EnforceCore with NER support Source: https://github.com/akios-ai/enforcecore/blob/main/CHANGELOG.md Install the optional NER tier for EnforceCore using pip. This includes Presidio's Named Entity Recognition pipeline. ```bash pip install enforcecore[ner] ``` -------------------------------- ### Load Sensitivity Configuration from YAML Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Example of a YAML configuration for sensitivity labels, defining default clearance, enforcement status, and fallback behavior. ```yaml sensitivity_labels: enabled: true default_clearance: internal enforce: true fallback: redact ``` -------------------------------- ### Quick Start: Collect and Verify Witness Hashes Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api/witness.md This snippet demonstrates how to collect witness hashes during the auditing process and then verify the audit trail against these collected hashes. ```python from enforcecore.auditor import Auditor from enforcecore.auditor.witness import CallbackWitness, verify_with_witness # Collect witness hashes hashes = [] witness = CallbackWitness(hashes.append) auditor = Auditor(output_path="audit.jsonl", witness=witness) # Record some entries auditor.record(tool_name="search", policy_name="strict") auditor.record(tool_name="calculator", policy_name="strict") # Verify trail against witness result = verify_with_witness("audit.jsonl", witness_hashes=[r.entry_hash for r in hashes]) assert result.is_valid ``` -------------------------------- ### Dockerfile for EnforceCore Agent Source: https://github.com/akios-ai/enforcecore/blob/main/docs/defense-in-depth.md This Dockerfile sets up a Python environment, installs EnforceCore, and configures a non-root user for running the agent. ```dockerfile FROM python:3.12-slim # Drop all capabilities, add only what's needed # (handled at runtime via docker run --cap-drop=ALL) # Read-only root filesystem # (handled at runtime via docker run --read-only) # Install EnforceCore RUN pip install enforcecore # Non-root user RUN useradd -m agent USER agent COPY policy.yaml /app/policy.yaml COPY agent.py /app/agent.py CMD ["python", "/app/agent.py"] ``` -------------------------------- ### List Installed EnforceCore Plugins via CLI Source: https://github.com/akios-ai/enforcecore/blob/main/CHANGELOG.md Use the `enforcecore plugin list` command to display all discovered EnforceCore plugins. The output includes the plugin name, kind, version, and entry-point information. Supports filtering by kind. ```bash $ enforcecore plugin list ┌─────────────────────────────────────────────────────────┐ │ Installed EnforceCore Plugins (2) │ ├──────────────────────┬─────────────────┬───────┬────────┤ │ Name │ Kind │ Ver │ EP │ ├──────────────────────┼─────────────────┼───────┼────────┤ │ toxicity-guard │ guard │ 1.0.0 │ ... │ │ employee-id-redactor │ redactor │ 2.1.0 │ ... │ └──────────────────────┴─────────────────┴───────┴────────┘ ``` -------------------------------- ### EnforceCore Security Warning Example Source: https://github.com/akios-ai/enforcecore/blob/main/docs/faq.md This warning appears when `fail_open` is enabled without `ENFORCECORE_DEV_MODE=1` in production. It indicates a potential security risk. ```text SECURITY WARNING: fail_open is enabled without ENFORCECORE_DEV_MODE=1. ``` -------------------------------- ### Load and Use Plugins with PluginManager Source: https://github.com/akios-ai/enforcecore/blob/main/CHANGELOG.md Instantiate PluginManager to discover and load plugins from installed packages. Use the `load_all` method to load plugins, optionally ignoring errors. Iterate through loaded guards to perform checks. ```python from enforcecore import PluginManager manager = PluginManager() n = manager.load_all(ignore_errors=True) # skip broken plugins print(f"Loaded {n} plugins") for guard in manager.guards: result = guard.check("my_tool", args, kwargs) ``` -------------------------------- ### Connect to Remote Policy Server Source: https://github.com/akios-ai/enforcecore/blob/main/docs/roadmap.md Example of initializing an Enforcer to connect to a remote policy server. This allows for centralized policy management with caching and versioning. ```python Enforcer.from_server( "https://policy.acme.com/agents/chatbot-v2", token=os.environ["POLICY_SERVER_TOKEN"], cache_ttl=300, ) ``` -------------------------------- ### Implement AuditBackend Get Entry Method Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Implement `get_entry` in a custom `AuditBackend` to retrieve an audit record by its ID. ```python @abstractmethod def get_entry(self, entry_id: str) -> AuditEntry | None ``` -------------------------------- ### Example Version Timeline for Deprecation Source: https://github.com/akios-ai/enforcecore/blob/main/docs/versioning.md Illustrates the timeline for deprecating a public API symbol, showing when a DeprecationWarning is issued and when the symbol is eventually removed. ```text v1.2.0 — guard_sync() deprecated with DeprecationWarning v1.3.0 — guard_sync() still works, warning persists v1.4.0 — guard_sync() still works, warning persists v2.0.0 — guard_sync() removed ``` -------------------------------- ### Enable Verbose Enforcement Logging Source: https://github.com/akios-ai/enforcecore/blob/main/docs/dev-guide.md Configure structlog to capture DEBUG level logs for detailed enforcement tracing. Ensure structlog is installed. ```python import structlog structlog.configure( wrapper_class=structlog.make_filtering_bound_logger(0), # DEBUG level ) ``` -------------------------------- ### Instrument EnforceCore with OpenTelemetry Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Use EnforceCoreInstrumentor to integrate with OpenTelemetry for tracing and metrics. Requires `enforcecore[otel]` installation. Optionally provide custom tracer and meter providers. ```python from enforcecore import EnforceCoreInstrumentor # Requires: pip install enforcecore[otel] instrumentor = EnforceCoreInstrumentor() instrumentor.instrument( tracer_provider=my_provider, # optional; falls back to global OTel provider meter_provider=my_meter, # optional ) ``` ```python def instrument( self, *, tracer_provider: Any = None, meter_provider: Any = None, ) -> None def uninstrument(self) -> None @property def metrics(self) -> EnforceCoreMetrics @property def is_instrumented(self) -> bool ``` -------------------------------- ### Require Package Utility Source: https://github.com/akios-ai/enforcecore/blob/main/CHANGELOG.md Verifies the presence of optional dependencies and provides clear installation messages if they are missing. This utility is exported at the top level of the `enforcecore` package. ```python from enforcecore import require_package require_package("langchain", "langchain") ``` -------------------------------- ### PostgreSQLBackend.__init__ Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Initializes the PostgreSQLBackend for production-grade audit log storage. ```APIDOC ## PostgreSQLBackend.__init__ ### Description Initializes the PostgreSQLBackend, a production-ready backend offering connection pooling, JSONB support for context, TIMESTAMPTZ, and concurrent write safety. Requires `psycopg2` to be installed. ### Method `__init__(self, host: str, database: str, user: str, password: str, port: int = 5432, verify_merkle: bool = True, pool_size: int = 5, ssl_mode: str = "prefer")` ### Parameters - **host** (str) - Required - The database host. - **database** (str) - Required - The database name. - **user** (str) - Required - The database user. - **password** (str) - Required - The database password. - **port** (int) - Optional - The database port (default: 5432). - **verify_merkle** (bool) - Optional - Whether to enable Merkle chain verification (default: True). - **pool_size** (int) - Optional - The size of the connection pool (default: 5). - **ssl_mode** (str) - Optional - SSL mode for the connection ('disable', 'allow', 'prefer', 'require') (default: 'prefer'). ``` -------------------------------- ### Streaming Adapter Layer Overview Source: https://github.com/akios-ai/enforcecore/blob/main/docs/architecture.md Lists the available adapter modules for integrating EnforceCore's streaming capabilities with popular AI frameworks. These adapters are designed for lazy imports, ensuring the core library functions even if optional framework dependencies are not installed. ```plaintext enforcecore.streaming.adapters ├── EnforceCoreStreamingCallback LangChain BaseCallbackHandler thin wrapper ├── autogen_stream_enforce() AutoGen: async generator → async generator └── langgraph_stream_enforce() LangGraph: @asynccontextmanager for graph.astream() ``` -------------------------------- ### Initialize and Run Benchmark Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Create a BenchmarkRunner instance and execute all benchmarks with a specified number of iterations. ```python bench = BenchmarkRunner() suite: BenchmarkSuite = bench.run_all(iterations=1000) ``` -------------------------------- ### Initialize PostgreSQLBackend Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Instantiate `PostgreSQLBackend` for production-grade PostgreSQL storage. Requires `psycopg2` and supports connection pooling and SSL modes. ```python from enforcecore.auditstore.backends import PostgreSQLBackend # Requires: pip install enforcecore[postgres] backend = PostgreSQLBackend( host="localhost", database="enforcecore", user="postgres", password="secret", port=5432, verify_merkle=True, pool_size=5, ssl_mode="prefer", # "disable" | "allow" | "prefer" | "require" ) ``` ```python def __init__(self, db_path: str = "audit.db", verify_merkle: bool = True) ``` -------------------------------- ### Conventional Commit Message Examples Source: https://github.com/akios-ai/enforcecore/blob/main/docs/dev-guide.md Examples of commit messages following the Conventional Commits specification for various types of changes. ```text feat(policy): add YAML policy loading with Pydantic validation fix(enforcer): handle async generator functions correctly docs(readme): add quickstart guide test(auditor): add Merkle chain integrity tests chore(ci): add macOS to test matrix ``` -------------------------------- ### Deprecation Warning Example Source: https://github.com/akios-ai/enforcecore/blob/main/docs/migration.md This is an example of the DeprecationWarning message you will see when importing deprecated Tier 2 symbols from the top-level package. ```text DeprecationWarning: Importing 'JsonlBackend' from 'enforcecore' is deprecated and will be removed in v2.0.0. Use 'from enforcecore.auditor.backends import JsonlBackend' instead. ``` -------------------------------- ### Basic Auditstore Usage with SQLite Source: https://github.com/akios-ai/enforcecore/blob/main/docs/auditstore.md Demonstrates creating an AuditStore with a SQLite backend, recording an enforced call, retrieving an entry, listing entries, and verifying the Merkle chain. ```python from enforcecore.auditstore import AuditStore from enforcecore.auditstore.backends import SQLiteBackend # Create audit store with SQLite backend backend = SQLiteBackend(db_path="audit.db") store = AuditStore(backend=backend) # Record an enforced call entry = store.record( policy_name="agent-policy", policy_version="1.0", tool_name="search", decision="allowed", call_duration_ms=45.2, enforcement_overhead_ms=0.8, cost_usd=0.05, ) # Retrieve entry stored_entry = store.get_entry(entry.entry_id) # Query entries entries = store.list_entries( policy_name="agent-policy", tool_name="search", decision="allowed", limit=100, ) # Verify Merkle chain is_valid = store.verify_chain() print(f"Chain is valid: {is_valid}") ``` -------------------------------- ### Run Compliance Demo Source: https://github.com/akios-ai/enforcecore/blob/main/examples/scenarios/compliance/README.md Execute the compliance demonstration script. Navigate to the directory and run the Python script. ```bash cd examples/scenarios/compliance python compliance_demo.py ``` -------------------------------- ### Initialize JSONL Backend Source: https://github.com/akios-ai/enforcecore/blob/main/docs/auditstore.md Use the JSONL backend for development and file-based storage. It works out-of-the-box without requiring a database and is suitable for single-machine deployments. ```python from enforcecore.auditstore.backends import JSONLBackend backend = JSONLBackend(path="audit_logs/trail.jsonl") store = AuditStore(backend=backend) ``` -------------------------------- ### AuditStore.__init__ Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Initializes the AuditStore with a specific backend and verification setting. ```APIDOC ## AuditStore.__init__ ### Description Initializes the AuditStore, which acts as a query interface over an AuditBackend. ### Method `__init__(self, backend: AuditBackend, verify_on_read: bool = True)` ### Parameters - **backend** (AuditBackend) - Required - The audit storage backend to use. - **verify_on_read** (bool) - Optional - Whether to verify data on read (default: True). ``` -------------------------------- ### Run Default Benchmarks (CLI) Source: https://github.com/akios-ai/enforcecore/blob/main/docs/benchmarks.md Execute benchmarks with default settings (1000 iterations) and Markdown output. ```bash python -m benchmarks.run ``` -------------------------------- ### PluginManager Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Manages the discovery, loading, and access of installed EnforceCore plugins. ```APIDOC ## PluginManager Manages the lifecycle of EnforceCore plugins. ### Methods - **`discover() -> list[PluginInfo]`**: Discovers installed plugins and returns their metadata without loading them. - **`load_all(ignore_errors: bool = False) -> int`**: Loads all installed plugins. If `ignore_errors` is `False`, raises `PluginLoadError` if any plugin fails to load. - **`load(name: str) -> None`**: Loads a single plugin by its registered name. Raises `PluginLoadError` if the plugin is not found or fails to instantiate. ### Properties - **`guards`**: Returns a list of loaded `GuardPlugin` instances. - **`redactors`**: Returns a list of loaded `RedactorPlugin` instances. - **`audit_backends`**: Returns a list of loaded `AuditBackendPlugin` instances. ### Example Usage ```python from enforcecore import PluginManager manager = PluginManager() # Discover without loading infos = manager.discover() # Load all plugins count = manager.load_all(ignore_errors=False) # Load a specific plugin manager.load("my-guard") # Access loaded plugins loaded_guards = manager.guards loaded_redactors = manager.redactors loaded_backends = manager.audit_backends ``` ``` -------------------------------- ### AuditStore Initialization (v1.1.3 - JSONL) Source: https://github.com/akios-ai/enforcecore/blob/main/docs/auditstore.md Initialize the Auditor with the default JSONL backend. This is the behavior in older versions. ```python from enforcecore import Auditor auditor = Auditor() # Uses JSONL backend # Stores to: audit_logs/trail.jsonl ``` -------------------------------- ### AuditBackend.get_chain_tail Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Abstract method to get the last entry in the audit chain. ```APIDOC ## AuditBackend.get_chain_tail ### Description Abstract method to retrieve the last entry in the audit chain. ### Method `@abstractmethod get_chain_tail(self)` ### Returns - **AuditEntry | None** - The last audit entry in the chain, or None if the chain is empty. ``` -------------------------------- ### Get All Registered Scenarios Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Retrieve a list of all available adversarial scenarios. ```python scenarios: list[Scenario] = get_all_scenarios() ``` -------------------------------- ### Building Custom Adapters Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Guidance on creating custom integration adapters using `wrap_with_policy`. ```APIDOC ### Building Custom Adapters Use `wrap_with_policy` to build adapters for any framework: ```python from enforcecore.integrations import wrap_with_policy def my_framework_tool(func, policy): """Example custom adapter.""" enforced = wrap_with_policy(func, policy=policy) return MyFramework.register_tool(enforced) ``` ``` -------------------------------- ### Get Scenarios by Category Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Fetch scenarios belonging to a specific threat category. ```python scenarios: list[Scenario] = get_scenarios_by_category(ThreatCategory.tool_abuse) ``` -------------------------------- ### Initialize PostgreSQL Backend Source: https://github.com/akios-ai/enforcecore/blob/main/docs/auditstore.md For production deployments requiring high-volume auditing and multi-user access, the PostgreSQL backend is recommended. It supports concurrent writes, horizontal scalability, and advanced query performance with connection pooling. ```python from enforcecore.auditstore.backends import PostgreSQLBackend backend = PostgreSQLBackend( host="postgres.example.com", database="enforcecore_audits", user="enforcecore", password="...", pool_size=10, ) store = AuditStore(backend=backend) ``` -------------------------------- ### Load Policies in Python Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Demonstrates loading policies from a YAML file or a Python dictionary. Also shows how to validate a policy file without loading it. ```python from enforcecore import Policy, load_policy # From YAML file policy = load_policy("policies/strict.yaml") # From dict (programmatic) policy = Policy( name="my-policy", rules={ "allowed_tools": ["search", "calculator"], "pii_redaction": {"enabled": True, "categories": ["email", "phone"]}, "resource_limits": {"max_call_duration_seconds": 30}, }, on_violation="block", ) # Validate without loading errors = Policy.validate_file("policies/strict.yaml") if errors: print(f"Policy has errors: {errors}") ``` -------------------------------- ### Non-Breaking Change Examples Source: https://github.com/akios-ai/enforcecore/blob/main/docs/versioning.md Lists types of changes that are considered non-breaking and can be included in MINOR or PATCH releases. ```plaintext Adding new symbols to `__all__` Adding optional parameters with defaults Adding new enum members Adding new methods to existing classes Adding new exception subclasses Performance improvements Bug fixes that correct documented behavior Internal implementation changes ``` -------------------------------- ### Breaking Change Examples Source: https://github.com/akios-ai/enforcecore/blob/main/docs/versioning.md Lists types of changes that are considered breaking and necessitate a MAJOR version increment. ```plaintext Removing a public symbol from `__all__` Renaming a public class, function, or method Changing a function signature incompatibly Changing exception hierarchy Changing enum member values Changing return types Removing a configuration setting Changing default behavior ``` -------------------------------- ### Filter Scenarios by Tags Source: https://github.com/akios-ai/enforcecore/blob/main/docs/evaluation.md Run scenarios associated with a specific set of tags, for example, 'pii' and 'redaction'. ```python suite = runner.run_all(tags={"pii", "redaction"}) ``` -------------------------------- ### Get a Specific Audit Entry Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Retrieve a single audit entry by its unique ID using `get_entry`. ```python def get_entry(self, entry_id: str) -> AuditEntry | None ``` -------------------------------- ### Run Benchmarks with All Formats and Output to Disk (CLI) Source: https://github.com/akios-ai/enforcecore/blob/main/docs/benchmarks.md Execute benchmarks generating both Markdown and JSON outputs, saving them to a specified directory. ```bash python -m benchmarks.run --format all --output results/ ``` -------------------------------- ### Resulting Merged Policy Source: https://github.com/akios-ai/enforcecore/blob/main/docs/formal/policy-algebra.md Shows the final merged policy after applying the cascade example, highlighting how conflicts are resolved. ```text denied_tools: [dangerous_tool, risky_tool] # union of all allowed_tools: [search, browse] # project override wins ``` -------------------------------- ### AuditStore Initialization (v1.2.0+ - Pluggable Backends) Source: https://github.com/akios-ai/enforcecore/blob/main/docs/auditstore.md Initialize the Auditor with different backends: default JSONL, SQLite, or PostgreSQL. All options maintain identical functionality with the @enforce decorator. ```python from enforcecore import Auditor # Option 1: Default (still JSONL) auditor = Auditor() # Option 2: SQLite auditor = Auditor(backend="sqlite", backend_config={"db_path": "audit.db"}) # Option 3: PostgreSQL auditor = Auditor(backend="postgresql", backend_config={ "host": "postgres.example.com", "database": "audits", "user": "app", "password": "...", }) # All three work identically with @enforce decorator ``` -------------------------------- ### Integrate EnforceCore Callback Handler in LangChain Source: https://github.com/akios-ai/enforcecore/blob/main/docs/roadmap.md Add EnforceCoreCallbackHandler to LangChain for policy enforcement. Requires installation of langchain-community. ```python from langchain_community.callbacks import EnforceCoreCallbackHandler handler = EnforceCoreCallbackHandler(policy="policy.yaml") llm = ChatOpenAI(callbacks=[handler]) ``` -------------------------------- ### EnforceCore Configuration via Environment Variables Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Configure EnforceCore settings by setting environment variables prefixed with ENFORCECORE_. Note that FAIL_OPEN should never be true in production. ```bash ENFORCECORE_DEFAULT_POLICY=policies/default.yaml ``` ```bash ENFORCECORE_AUDIT_PATH=./audit_logs/ ``` ```bash ENFORCECORE_AUDIT_ENABLED=true ``` ```bash ENFORCECORE_REDACTION_ENABLED=true ``` ```bash ENFORCECORE_LOG_LEVEL=INFO ``` ```bash ENFORCECORE_COST_BUDGET_USD=100.0 ``` ```bash ENFORCECORE_FAIL_OPEN=false # NEVER set to true in production ``` ```bash ENFORCECORE_DEV_MODE=false # Set to true/1/yes to suppress fail_open warnings ``` -------------------------------- ### FileWitness Initialization Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api/witness.md Demonstrates how to initialize FileWitness to append hashes to a specified file. ```APIDOC ## FileWitness Initialization `FileWitness` appends witness hashes to a separate JSONL file. This is useful when the witness file needs to be on a different volume or owned by a different user. ### Code ```python from enforcecore.auditor.witness import FileWitness witness = FileWitness("/var/log/ec-witness.jsonl") ``` ``` -------------------------------- ### Initialize MultiTenantEnforcer and Register Tenants Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Instantiate MultiTenantEnforcer with a default policy and register specific policies for different tenants. Raises ValueError if tenant_id is empty. ```python from enforcecore import MultiTenantEnforcer mt = MultiTenantEnforcer(default_policy="base_policy.yaml") mt.register("team_a", "team_a_policy.yaml") mt.register("team_b", "team_b_policy.yaml") ``` -------------------------------- ### Implement AuditBackend Get Chain Tail Method Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Implement `get_chain_tail` in a custom `AuditBackend` to retrieve the last entry in the audit chain. ```python @abstractmethod def get_chain_tail(self) -> AuditEntry | None ``` -------------------------------- ### Initialize PolicyServerClient for Remote Policies Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Create a PolicyServerClient to fetch policies from a remote server. Configure URL, authentication token, cache TTL, and signature verification. Raises ValueError if url/token empty or cache_ttl < 0. ```python from enforcecore import PolicyServerClient client = PolicyServerClient( url="https://policy.acme.com/agents/chatbot-v2", token=os.environ["POLICY_SERVER_TOKEN"], cache_ttl=300, # seconds; 0 disables caching verify_signature=True, # HMAC-SHA256 verification ) enforcer = Enforcer.from_server(client) ``` -------------------------------- ### Initialize SQLiteBackend Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Instantiate `SQLiteBackend` for local SQLite database storage. The `verify_merkle` flag enables chain verification. ```python from enforcecore.auditstore.backends import SQLiteBackend backend = SQLiteBackend("audit.db") ``` ```python def __init__(self, db_path: str = "audit.db", verify_merkle: bool = True) ``` -------------------------------- ### Initialize JSONLBackend Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Instantiate `JSONLBackend` to use a JSON Lines file for audit logging. Parent directories are created automatically. ```python from enforcecore.auditstore.backends import JSONLBackend backend = JSONLBackend("audit_logs/trail.jsonl") ``` ```python def __init__(self, path: str = "audit_logs/trail.jsonl") ``` -------------------------------- ### FileWitness via Environment Variable Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api/witness.md Shows how to automatically create a FileWitness using an environment variable. ```APIDOC ## FileWitness via Environment Variable This demonstrates how to configure `FileWitness` to be automatically created when using the `@enforce()` decorator by setting an environment variable. ### Environment Variable ```bash export ENFORCECORE_AUDIT_WITNESS_FILE=/var/log/ec-witness.jsonl ``` This will automatically create a `FileWitness` that appends witness hashes to the specified file. ``` -------------------------------- ### Get Current Enforcement Depth Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Retrieves the current nesting level of enforcement scopes. Returns 0 if not currently within any enforcement scope. ```python get_enforcement_depth() -> int ``` -------------------------------- ### LogWitness Initialization Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api/witness.md Shows how to initialize LogWitness to emit witness hashes via Python's logging module. ```APIDOC ## LogWitness Initialization `LogWitness` emits witness hashes using Python's `logging` module. This allows routing to syslog, journald, or any other configured log handler. ### Code ```python from enforcecore.auditor.witness import LogWitness witness = LogWitness() # uses "enforcecore.witness" logger ``` ``` -------------------------------- ### JSONLBackend.__init__ Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Initializes the JSONLBackend to store audit logs in a JSONL file. ```APIDOC ## JSONLBackend.__init__ ### Description Initializes the JSONLBackend, which stores audit entries in an append-only JSON Lines (jsonl) file. Parent directories are created automatically. ### Method `__init__(self, path: str = "audit_logs/trail.jsonl")` ### Parameters - **path** (str) - Optional - The path to the JSONL file (default: 'audit_logs/trail.jsonl'). ``` -------------------------------- ### Enforce Function with Policy Source: https://github.com/akios-ai/enforcecore/blob/main/docs/quickstart.md Use the `@enforce` decorator to apply a policy file to a Python function. This example shows an allowed function and a blocked function. ```python from enforcecore import enforce @enforce(policy="policies/strict.yaml") async def search_web(query: str) -> str: """This function is now enforced by the policy.""" return await api.search(query) # Allowed — search_web is in the allowed list result = await search_web("Python tutorials") # Blocked — execute_shell is in the denied list @enforce(policy="policies/strict.yaml") async def execute_shell(cmd: str) -> str: return await shell.run(cmd) await execute_shell("ls -la") # raises EnforcementViolation ``` -------------------------------- ### SQLiteBackend.__init__ Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Initializes the SQLiteBackend for storing audit logs in a local SQLite database. ```APIDOC ## SQLiteBackend.__init__ ### Description Initializes the SQLiteBackend, which uses a local SQLite database for storing audit entries. It includes a `merkle_chain` table for verification and indices for efficient querying. ### Method `__init__(self, db_path: str = "audit.db", verify_merkle: bool = True)` ### Parameters - **db_path** (str) - Optional - The path to the SQLite database file (default: 'audit.db'). - **verify_merkle** (bool) - Optional - Whether to enable Merkle chain verification (default: True). ``` -------------------------------- ### PluginManager Usage Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md The `PluginManager` class is used to discover and load installed EnforceCore plugins. It provides access to loaded guards, redactors, and audit backends. ```python from enforcecore import PluginManager manager = PluginManager() # Discover without loading (metadata only): infos = manager.discover() # Load all installed plugins: count = manager.load_all(ignore_errors=False) # Raises PluginLoadError if any plugin fails and ignore_errors=False. # Load a single plugin by name: manager.load("my-guard") # Access loaded plugins: manager.guards # list[GuardPlugin] manager.redactors # list[RedactorPlugin] manager.audit_backends # list[AuditBackendPlugin] ``` -------------------------------- ### Run Benchmarks with Custom Iterations and JSON Output (CLI) Source: https://github.com/akios-ai/enforcecore/blob/main/docs/benchmarks.md Run benchmarks with 5000 iterations and generate output in JSON format. ```bash python -m benchmarks.run --iterations 5000 --format json ``` -------------------------------- ### Handle ImportError for NER in RedactionStrategy Source: https://github.com/akios-ai/enforcecore/blob/main/CHANGELOG.md This fix prevents crashes when the 'enforcecore[ner]' extra is not installed. The RedactionStrategy.NER now gracefully skips initialization with an informative message. ```python try: from enforcecore.redactor.ner import NERRedactor except ImportError: NERRedactor = None class RedactionStrategy: # ... other strategies ... NER = NERRedactor or "skipped — install enforcecore[ner]" ``` -------------------------------- ### SubprocessSandbox Initialization and Execution Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Instantiates the SubprocessSandbox with a configuration and demonstrates synchronous and asynchronous execution of a tool. ```python from enforcecore import SubprocessSandbox sandbox = SubprocessSandbox(config) # Synchronous execution result = sandbox.run(my_tool, *args, tool_name="my_tool", **kwargs) # Asynchronous execution result = await sandbox.run_async(my_tool, *args, tool_name="my_tool", **kwargs) ``` -------------------------------- ### Testing Allowed Calls with Pytest Source: https://github.com/akios-ai/enforcecore/blob/main/docs/dev-guide.md Demonstrates how to test that a function decorated with `@enforce` correctly allows calls when the policy permits. Requires `pytest` and `enforcecore` to be installed. ```python import pytest from enforcecore import enforce, EnforcementViolation # Test that allowed calls pass through @pytest.mark.asyncio async def test_allowed_call_succeeds(): @enforce(policy="tests/fixtures/allow_all.yaml") async def allowed_tool(): return "result" assert await allowed_tool() == "result" ``` -------------------------------- ### Initialize SQLite Backend Source: https://github.com/akios-ai/enforcecore/blob/main/docs/auditstore.md The SQLite backend is ideal for local development, testing, and small deployments. It offers fast local queries, a schema with indices, and Merkle chain verification, all within a portable single file. ```python from enforcecore.auditstore.backends import SQLiteBackend backend = SQLiteBackend(db_path="audit.db") store = AuditStore(backend=backend) ``` -------------------------------- ### Initialize AuditStore Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Initialize the AuditStore with a specific AuditBackend. The `verify_on_read` flag controls chain verification during read operations. ```python def __init__(self, backend: AuditBackend, verify_on_read: bool = True) -> None ``` -------------------------------- ### Quick Start: Protect and Verify Append-Only File Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api/immutable.md Directly protect an existing file using protect_append_only() and then verify that the append-only attribute is set using is_append_only(). ```python from enforcecore.auditor.immutable import protect_append_only, is_append_only # Protect an existing file protect_append_only("audit.jsonl") assert is_append_only("audit.jsonl") ``` -------------------------------- ### Initialize AuditStoreBackendAdapter Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Use AuditStoreBackendAdapter to bridge any AuditBackend to the Auditor write API. It automatically translates the Auditor's dict format to AuditEntry. ```python from enforcecore import AuditStoreBackendAdapter adapter = AuditStoreBackendAdapter(backend) auditor = Auditor(backend=adapter) ``` -------------------------------- ### Run Framework Comparison Source: https://github.com/akios-ai/enforcecore/blob/main/CHANGELOG.md Execute the adversarial scenario suite to compare EnforceCore against baseline agent frameworks. Generates a detailed markdown report. ```python python -m enforcecore.eval.framework_comparison ``` -------------------------------- ### Automatic OpenTelemetry Instrumentation with @enforce() Source: https://github.com/akios-ai/enforcecore/blob/main/docs/architecture.md The @enforce() decorator automatically instruments calls as OpenTelemetry spans. Install enforcecore[otel] and call EnforceCoreInstrumentor().instrument() at startup for metrics and tracing. ```python @enforce() async def my_tool(...): # ← span begins: "enforcecore.my_tool" ... # ← span attributes set: decision, overhead_ms, redactions # ← span ends; counters incremented ``` -------------------------------- ### Get Enforcement Call Chain Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Returns a list representing the current sequence of nested enforcement scopes, with the outermost scope listed first. This provides a history of the active enforcement context. ```python get_enforcement_chain() -> list[str] ``` -------------------------------- ### Minimum Viable Security Deployment Source: https://github.com/akios-ai/enforcecore/blob/main/docs/defense-in-depth.md This diagram illustrates the simplest deployment of EnforceCore for development and testing purposes. ```text Python process └── EnforceCore (policy enforcement) ``` -------------------------------- ### platform_info() Function Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Retrieves information about the current platform's sandbox capabilities and configuration. ```python from enforcecore.sandbox.runner import platform_info info = platform_info() # Returns dict: {platform, subprocess_isolation, resource_limits, # memory_limits, cpu_time_limits, env_restriction, # wasm_sandbox, python_version} ``` -------------------------------- ### Lint and Format Code with Ruff Source: https://github.com/akios-ai/enforcecore/blob/main/docs/dev-guide.md Use Ruff to check for linting errors and automatically format the code according to project standards. This ensures code consistency and adherence to style guides. ```bash ruff check . ruff format . ``` -------------------------------- ### Deep Redaction Example Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Recursively redacts string values within nested data structures using a provided redaction function. Useful for sanitizing sensitive information before logging or external exposure. ```python from enforcecore import deep_redact data = { "user": {"name": "John Doe", "email": "john@example.com"}, "notes": ["Contact Jane at jane@test.com"], } redacted = deep_redact(data, redactor.redact_string) # {"user": {"name": "[REDACTED]", "email": "[REDACTED]"}, ...} ``` -------------------------------- ### Configuration Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Global settings and configuration management. ```APIDOC ## Config ### `Settings` **Description**: Class for global configuration settings. ### `settings` **Description**: Module-level singleton instance for global configuration. ``` -------------------------------- ### Configure PII Redaction and Secret Detection Policy Source: https://github.com/akios-ai/enforcecore/blob/main/docs/compliance/gdpr.md Example YAML policy configuration for enabling PII redaction and secret detection. This demonstrates how to specify enabled features, categories, and redaction strategies. ```yaml rules: pii_redaction: enabled: true categories: [email, phone, ssn, credit_card, ip_address] strategy: "placeholder" secret_detection: enabled: true categories: [aws_access_key, github_token, generic_api_key] ``` -------------------------------- ### Simple Agent Deployment (Low Risk) Source: https://github.com/akios-ai/enforcecore/blob/main/docs/security/tool-selection.md This pattern is suitable for internal tools with trusted models and no sensitive data. It focuses on basic EnforceCore configuration with allowed tools, enabled audit trails, and optional rate limiting. ```text Python process └── EnforceCore ├── Policy: allowed_tools only ├── Audit trail: enabled └── Rate limiting: optional ``` -------------------------------- ### Policy-Enforced Function with EnforceCore Source: https://github.com/akios-ai/enforcecore/blob/main/README.md Use the `@enforce` decorator to apply a policy to an asynchronous function. The policy is defined in a YAML file and enforced before the function's code is executed. Ensure the 'enforcecore' library is installed. ```python from enforcecore import enforce @enforce(policy="policies/strict.yaml") async def search_web(query: str) -> str: """This call is policy-enforced before execution.""" return await api.search(query) ``` -------------------------------- ### Initialize Redactor with Default Settings Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Create a Redactor instance using default PII categories and the placeholder redaction strategy. ```python from enforcecore.redactor import Redactor # Default: all categories, placeholder strategy redactor = Redactor() ``` -------------------------------- ### Initialize ScenarioRunner Source: https://github.com/akios-ai/enforcecore/blob/main/docs/evaluation.md Instantiate the ScenarioRunner with a policy to begin running scenarios. ```python runner = ScenarioRunner(policy) suite = runner.run_all() ``` -------------------------------- ### Enforce Decorator Tool Name Mismatch Source: https://github.com/akios-ai/enforcecore/blob/main/docs/issues-v1.1.1.md This example shows how the `enforce()` decorator uses the function name as `tool_name` by default, which can lead to `ToolDeniedError` if it doesn't match policy entries. Specify `tool_name=` for custom names. ```python @enforce(policy="policy.yaml") async def my_search_function(query: str) -> str: # <- "my_search_function" ≠ "search_web" return await api.search(query) await my_search_function("test") # ToolDeniedError! ``` -------------------------------- ### Run Financial Agent Scenario Source: https://github.com/akios-ai/enforcecore/blob/main/examples/scenarios/financial/README.md Navigate to the financial agent directory and execute the Python script to run the scenario. ```bash cd examples/scenarios/financial python financial_agent.py ``` -------------------------------- ### Initialize EUAIActQueries Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Instantiate EUAIActQueries to query audit data related to the EU AI Act. All methods accept date filters and an optional policy name, returning dictionaries. ```python from enforcecore.auditstore.queries.eu_ai_act import EUAIActQueries queries = EUAIActQueries(store) ``` -------------------------------- ### EnforceCore Exception Hierarchy Source: https://github.com/akios-ai/enforcecore/blob/main/docs/api-design.md Outlines the custom exception classes in EnforceCore, starting from the base EnforceCoreError and branching into specific errors for policy issues, enforcement violations, redaction failures, audit problems, and hardening validations. ```python class EnforceCoreError(Exception): """Base exception for all EnforceCore errors.""" class PolicyError(EnforceCoreError): """Errors related to policy loading/validation/evaluation.""" class PolicyLoadError(PolicyError): """Policy file not found or unparseable.""" class PolicyValidationError(PolicyError): """Policy does not conform to schema.""" class EnforcementViolation(EnforceCoreError): """A call was blocked due to policy violation.""" tool_name: str policy_name: str reason: str class ToolDeniedError(EnforcementViolation): """Tool is not in the allowed list or is explicitly denied.""" class DomainDeniedError(EnforcementViolation): """Network domain is not allowed by policy.""" class CostLimitError(EnforcementViolation): """Cumulative cost exceeds budget.""" class ResourceLimitError(EnforcementViolation): """Resource limit (time, memory) exceeded.""" class RedactionError(EnforceCoreError): """Error during PII redaction (fails closed — call is blocked).""" class AuditError(EnforceCoreError): """Error writing audit entry (fails closed — call is blocked).""" class HardeningError(EnforceCoreError): """Base exception for hardening validation failures (v1.0.6).""" class InvalidToolNameError(HardeningError): """Tool name is empty, too long, or contains invalid characters.""" class InputTooLargeError(HardeningError): """Combined input payload exceeds MAX_INPUT_SIZE_BYTES.""" class EnforcementDepthError(HardeningError): """Recursive enforcement nesting exceeds MAX_ENFORCEMENT_DEPTH.""" ``` -------------------------------- ### Add __main__.py for Module Execution Source: https://github.com/akios-ai/enforcecore/blob/main/docs/issues-v1.1.1.md This snippet provides the content for `enforcecore/__main__.py` to enable execution via `python -m enforcecore`. ```python from enforcecore.cli.main import app app() ```