Build an AI Action Simulator That Shows Side Effects Before They Happen

The most dangerous sentence in an AI-powered product is not “I cannot do that.”

It is: “I can do that. Approve?”

The user sees a friendly confirmation box. The agent sees a tool call. Your backend sees a request to update records, send email, cancel subscriptions, create invoices, or deploy a config change. Nobody is looking at the same thing.

The user thinks they are approving a summary. The model thinks it has described its intent. Your system is about to execute a mutation that may be irreversible, expensive, or far broader than anyone realized.

An AI action simulator fixes this by adding a missing layer between tool-call intent and execution. It takes a proposed action, runs it through a controlled simulation path, and produces a concrete preview of expected side effects: what will change, what will be sent, how many records are affected, whether the action is reversible, and what approval is required.

This is not a confirmation dialog. It is not the model summarizing itself. It is an engineering boundary.

TL;DR

  • Treat AI tool calls as proposals, not commands.
  • Build adapters that can validate, simulate, and execute each action.
  • Derive previews from code and data, not from model prose.
  • Classify effects by risk, reversibility, and blast radius.
  • Use read-only queries and bounded simulations for database changes.
  • Mark external side effects as partially predictable.
  • Enforce approval policies server-side.
  • Store the proposal, simulation, approval, and execution as one audit chain.

📋 Table of Contents


The Missing Layer Between Tool Calls and Real-World Damage

Most AI agents are built around a loop:

model decides → tool is called → something happens

That loop works for read-only tools. It becomes dangerous when tools mutate state.

A model may propose:

{
  "action": "archive_stale_orders",
  "arguments": {
    "older_than_days": 90
  }
}

The model does not know whether that affects 12 orders or 120,000. It does not know whether the operation is reversible. It does not know whether there are open refunds, pending invoices, or regulatory retention rules. It only knows that the tool exists and the arguments look plausible.

An action simulator sits between the proposal and execution:

model proposes → simulator previews → policy decides → human approves if needed → executor runs

The simulator’s job is to answer practical questions:

  • What will change?
  • How many things will change?
  • Who will receive messages?
  • How much money will move?
  • Can this be undone?
  • What assumptions is the simulation making?
  • Does this require approval?

If you are building AI features that can write to databases, call third-party APIs, send messages, modify infrastructure, or trigger workflows, this layer is not optional. It is the difference between an assistant and a liability.


1. Stop Asking the Model to Describe Its Own Side Effects

Scenario: Your agent says, “This will update the customer’s email address.” In reality, the tool also triggers a password reset, sends a security notification, and invalidates active sessions. The model did not mention those side effects because it does not know they exist.

Why it matters: Model-generated explanations are useful for conversation, but they are not a safe source of truth for execution. The model can omit side effects, phrase them too gently, or hallucinate consequences that do not exist.

The first rule of an AI action simulator is simple:

The preview must be generated from the same code path that would execute the action.

Not from the prompt. Not from the model’s summary. Not from a UI label.

The model can propose an action. The simulator should explain it.

For example, the model may return:

{
  "action": "update_customer_email",
  "arguments": {
    "customer_id": "cus_812",
    "new_email": "new@example.com"
  }
}

Your simulator should transform that into something like:

{
  "summary": "Update email address for customer cus_812",
  "effects": [
    {
      "kind": "update",
      "resource_type": "customer",
      "description": "Change email from old@example.com to new@example.com",
      "reversible": true,
      "risk": "medium"
    },
    {
      "kind": "send",
      "resource_type": "email",
      "description": "Send security notification to old@example.com",
      "reversible": false,
      "risk": "medium"
    },
    {
      "kind": "delete",
      "resource_type": "session",
      "description": "Invalidate 3 active sessions",
      "reversible": false,
      "risk": "high"
    }
  ],
  "approval_required": true
}

That structure is more useful than a paragraph of natural language because it can be checked, tested, styled, logged, and enforced.

⚠️ Gotcha: Letting the model write the confirmation text is fine as a secondary explanation. Letting the model define the confirmation boundaries is how bad things get executed.


2. Model the Proposal, Not Just the Tool Call

Scenario: Your agent receives a tool call from the model and immediately passes the raw JSON to a handler. Later, you need to know who approved it, which session created it, whether it was retried, and whether the simulation matched the execution.

Why it matters: Raw tool-call JSON is transport. It is not enough for safety, auditing, or idempotency.

Create an explicit proposal object.

from dataclasses import dataclass, field
from typing import Any

@dataclass(frozen=True)
class ActionProposal:
    id: str
    action: str
    arguments: dict[str, Any]
    actor_id: str
    session_id: str
    idempotency_key: str
    requested_at: str
    metadata: dict[str, Any] = field(default_factory=dict)

This object should be created before simulation and should stay attached through approval and execution.

The idempotency_key is especially important. AI systems retry. Users click twice. Network calls time out. If the same proposal is replayed, you need to know whether it represents one logical action or several.

A good idempotency key often combines:

session id + action name + stable arguments hash + user intent id

For example:

idempotency_key = f"{session_id}:{action}:{args_hash}:{intent_id}"

Do not use a random UUID generated at execution time unless you also store it with the original proposal. If the key changes every retry, deduplication becomes impossible.

The proposal object also gives you a clean place to attach authorization context:

  • Who is the actor?
  • What scopes do they have?
  • Is this an admin action?
  • Is the AI acting on behalf of a user?
  • Is the request coming from a chat UI, background job, or API?

An action simulator should never evaluate a tool call in isolation. The same action may be acceptable for one actor and forbidden for another.


3. Classify Actions by Blast Radius, Not Just Name

Scenario: You have a tool called update_record. It sounds harmless. But updating one feature flag can affect thousands of users. Updating a billing setting can move money. Updating a user’s email can trigger security emails.

Why it matters: Action names are weak signals. The simulator needs to classify effects by consequence.

A useful taxonomy:

Effect classExamplesTypical concern
Readfetch records, summarize datalow risk, but may expose sensitive data
Internal writeupdate DB row, create ticketneeds scope and validation
Bulk writeupdate many rows, archive old datablast radius and reversibility
External communicationemail, SMS, push, webhookirreversible once sent
Financialrefund, charge, invoicehigh assurance required
Infrastructuredeploy, config change, feature flagwide impact, often delayed consequences
Irreversible deletiondrop table, delete accountrequires strong confirmation

You can represent effects with typed objects:

from enum import Enum

class EffectKind(str, Enum):
    READ = "read"
    CREATE = "create"
    UPDATE = "update"
    DELETE = "delete"
    SEND = "send"
    CHARGE = "charge"
    DEPLOY = "deploy"

class RiskLevel(str, Enum):
    LOW = "low"
    MEDIUM = "medium"
    HIGH = "high"
    CRITICAL = "critical"

Then define an effect:

@dataclass(frozen=True)
class Effect:
    kind: EffectKind
    resource_type: str
    description: str
    risk: RiskLevel
    reversible: bool
    details: dict[str, Any] = field(default_factory=dict)

This structure forces the simulator to think in terms of consequences, not labels.

For example, archive_stale_orders might produce:

Effect(
    kind=EffectKind.UPDATE,
    resource_type="order",
    description="Move closed orders older than 90 days to archive",
    risk=RiskLevel.HIGH,
    reversible=True,
    details={
        "affected_count": 4821,
        "sample_ids": ["ord_1001", "ord_1002", "ord_1003"],
        "archive_table": "orders_archive",
    },
)

Now your policy engine can make decisions based on actual risk:

  • If affected_count > 1000, require approval.
  • If any effect is SEND, show recipients.
  • If any effect is CHARGE, require explicit confirmation.
  • If any effect is CRITICAL and not reversible, require a second approver.

🔍 Why this matters: A good simulator does not ask, “What tool is being called?” It asks, “What will happen, to whom, and how badly can this go wrong?”


4. Give Every Action an Adapter With simulate and execute

Scenario: Your execution code is a giant dispatcher that knows a little about every tool. Some tools validate arguments, some do not. Some have dry-run logic, some just execute. Adding a new tool means copying patterns from older tools and hoping nothing was missed.

Why it matters: Safety features need a consistent extension point. If simulation is optional, developers will skip it under deadline pressure.

Use an adapter pattern.

Each action has an adapter that knows how to:

  1. Validate arguments.
  2. Simulate effects.
  3. Execute the real action.
from typing import Protocol

class ActionAdapter(Protocol):
    name: str

    def validate(self, arguments: dict[str, Any]) -> list[str]:
        ...

    def simulate(
        self,
        ctx: ActionContext,
        arguments: dict[str, Any],
    ) -> SimulationResult:
        ...

    def execute(
        self,
        ctx: ActionContext,
        arguments: dict[str, Any],
    ) -> ExecutionResult:
        ...

The context object carries dependencies and actor information:

from datetime import datetime

@dataclass(frozen=True)
class ActionContext:
    actor_id: str
    session_id: str
    db: Any
    services: Any
    now: datetime

The simulator uses a registry:

class ActionSimulator:
    def __init__(self, registry: dict[str, ActionAdapter]):
        self.registry = registry

    def preview(
        self,
        ctx: ActionContext,
        proposal: ActionProposal,
    ) -> SimulationResult:
        adapter = self.registry.get(proposal.action)

        if adapter is None:
            return SimulationResult(
                ok=False,
                summary=f"Unknown action: {proposal.action}",
                effects=[],
                warnings=["The requested action is not registered."],
                approval_required=True,
                confidence=0.0,
            )

        errors = adapter.validate(proposal.arguments)

        if errors:
            return SimulationResult(
                ok=False,
                summary="Action arguments are invalid",
                effects=[],
                warnings=errors,
                approval_required=True,
                confidence=0.0,
            )

        return adapter.simulate(ctx, proposal.arguments)

This gives you a clean architectural rule:

If an action cannot be simulated, it should say so explicitly. It should not silently execute without a preview.

Some adapters will have high-fidelity simulation. Others will only be able to validate inputs and say, “This calls an external system; exact outcome cannot be previewed.” That honesty is valuable.

💡 Practical note: Keep simulate() and execute() in the same adapter. If they drift apart, your preview becomes fiction.


5. Use Read-Only Transactions and Query Probes to Predict Database Effects

Scenario: An AI assistant proposes to archive old orders. The user asks, “How many will this affect?” If you execute first, the answer is too late. If you guess, the preview is useless.

Why it matters: Database mutations are often predictable if you are willing to query before you write. The simulator can run the same filtering logic in a read-only mode and estimate the result.

For PostgreSQL, you can use a read-only transaction:

class ArchiveStaleOrdersAdapter:
    name = "archive_stale_orders"

    def validate(self, arguments: dict[str, Any]) -> list[str]:
        errors = []

        older_than_days = arguments.get("older_than_days")

        if older_than_days is None:
            errors.append("older_than_days is required")
        elif not isinstance(older_than_days, int) or older_than_days < 1:
            errors.append("older_than_days must be a positive integer")

        return errors

    def simulate(self, ctx: ActionContext, arguments: dict[str, Any]) -> SimulationResult:
        older_than_days = arguments["older_than_days"]

        with ctx.db.transaction() as tx:
            tx.execute("SET TRANSACTION READ ONLY")

            count_row = tx.execute(
                """
                SELECT COUNT(*)
                FROM orders
                WHERE status = 'closed'
                  AND updated_at < now() - (%s::text || ' days')::interval
                """,
                (older_than_days,),
            ).fetchone()

            affected_count = count_row[0] if count_row else 0

            sample_rows = tx.execute(
                """
                SELECT id, customer_id, updated_at
                FROM orders
                WHERE status = 'closed'
                  AND updated_at < now() - (%s::text || ' days')::interval
                ORDER BY updated_at
                LIMIT 5
                """,
                (older_than_days,),
            ).fetchall()

        if affected_count == 0:
            risk = RiskLevel.LOW
        elif affected_count < 100:
            risk = RiskLevel.MEDIUM
        else:
            risk = RiskLevel.HIGH

        effects = [
            Effect(
                kind=EffectKind.UPDATE,
                resource_type="order",
                description=(
                    f"Archive {affected_count} closed orders older than "
                    f"{older_than_days} days"
                ),
                risk=risk,
                reversible=True,
                details={
                    "affected_count": affected_count,
                    "sample_ids": [row["id"] for row in sample_rows],
                    "archive_table": "orders_archive",
                },
            )
        ]

        warnings = []

        if affected_count > 1000:
            warnings.append(
                "This action affects a large number of records and should be reviewed."
            )

        return SimulationResult(
            ok=True,
            summary=f"Archive {affected_count} stale orders",
            effects=effects,
            warnings=warnings,
            approval_required=affected_count >= 100,
            confidence=0.9,
        )

This works because the simulation uses the same business criteria that execution will use. It is not asking the model to estimate row count. It is asking the database.

But there are important limits.

A read-only simulation cannot always predict:

  • concurrent writes that happen before execution,
  • database triggers that create secondary effects,
  • cascading foreign-key actions,
  • application-level events fired after commit,
  • replica lag if you simulate against a replica,
  • constraint violations that only appear under concurrency.

So the preview should be explicit about confidence. A count from the primary database is more reliable than a count from a stale replica. A simple UPDATE is easier to preview than a trigger-heavy schema.

🧠 The important part: A database preview is not “what will happen if we execute this.” It is “what would happen if we executed this against the current visible state.” That distinction matters.


6. Render Side Effects as Diffs, Counts, and Recipients Humans Can Inspect

Scenario: The simulator returns a technically correct object with 47 fields. The UI shows a wall of JSON. The user clicks “Approve” because they cannot tell what matters.

Why it matters: A simulator is only useful if humans can understand the preview quickly. The output needs to be both machine-readable and UI-friendly.

A good simulation result might look like this:

@dataclass(frozen=True)
class SimulationResult:
    ok: bool
    summary: str
    effects: list[Effect]
    warnings: list[str]
    approval_required: bool
    confidence: float

For a record update, include a diff:

def customer_email_diff(current_email: str, new_email: str) -> dict[str, Any]:
    return {
        "field": "email",
        "before": current_email,
        "after": new_email,
    }

For bulk operations, include aggregates and samples:

{
  "summary": "Archive 4,821 closed orders",
  "effects": [
    {
      "kind": "update",
      "resource_type": "order",
      "description": "Move closed orders older than 90 days to archive",
      "risk": "high",
      "reversible": true,
      "details": {
        "affected_count": 4821,
        "sample_ids": ["ord_1001", "ord_1002", "ord_1003"]
      }
    }
  ],
  "warnings": [
    "This action affects a large number of records and should be reviewed."
  ],
  "approval_required": true,
  "confidence": 0.9
}

For communication, show recipients and template details:

{
  "kind": "send",
  "resource_type": "email",
  "description": "Send refund notification to customer@example.com",
  "risk": "medium",
  "reversible": false,
  "details": {
    "to": ["customer@example.com"],
    "template": "refund_issued",
    "subject": "Your refund has been processed"
  }
}

For financial actions, show amounts and balances where safe:

{
  "kind": "charge",
  "resource_type": "invoice",
  "description": "Charge $250.00 to customer cus_812",
  "risk": "critical",
  "reversible": false,
  "details": {
    "amount_cents": 25000,
    "currency": "USD",
    "invoice_id": "inv_3321"
  }
}

Do not show everything. Show what a reviewer needs to make a decision.

A useful UI structure:

Summary
Primary effect
Affected count
Sample records
Irreversible effects
Warnings
Required approval reason

If the action affects thousands of records, do not render thousands of rows. Show a count, a query preview, and a sample. If the action sends email, show the recipient list or recipient criteria. If the action changes configuration, show before and after values.

Redact sensitive data before storing or displaying previews. If a diff contains a password hash, API key, or personal identifier, the simulator should mask it.

⚠️ Gotcha: A preview that hides the recipient list behind “send notification” is not a preview. It is a shrug.


7. Simulate External Systems With Bounded Lies

Scenario: Your agent wants to send an email through a third-party provider. You cannot actually send it during simulation. You also cannot guarantee delivery, open tracking, spam filtering, or provider-side validation.

Why it matters: Many important AI actions involve external systems. Those systems often do not offer perfect dry-run APIs. Your simulator still needs to be useful, but it must be honest about uncertainty.

For external actions, simulation usually has three layers:

  1. Local validation
    Are the arguments well-formed? Is the recipient valid? Is the template available? Does the actor have permission?

  2. Local rendering
    What message, payload, webhook, or request would be sent?

  3. Provider sandbox or test mode, if available
    Can the external system validate the request without causing the real effect?

Example email adapter:

class SendEmailAdapter:
    name = "send_email"

    def validate(self, arguments: dict[str, Any]) -> list[str]:
        errors = []

        to = arguments.get("to")
        template = arguments.get("template")

        if not isinstance(to, str) or "@" not in to:
            errors.append("A valid recipient email is required")

        if not template:
            errors.append("Email template is required")

        return errors

    def simulate(self, ctx: ActionContext, arguments: dict[str, Any]) -> SimulationResult:
        to = arguments["to"]
        template = arguments["template"]
        context = arguments.get("context", {})

        rendered = ctx.services.email_templates.render(template, context)

        effects = [
            Effect(
                kind=EffectKind.SEND,
                resource_type="email",
                description=f"Send {template} email to {to}",
                risk=RiskLevel.MEDIUM,
                reversible=False,
                details={
                    "to": [to],
                    "template": template,
                    "subject": rendered.subject,
                },
            )
        ]

        warnings = [
            "External email delivery cannot be fully simulated.",
            "Once sent, the message cannot be reliably recalled.",
        ]

        return SimulationResult(
            ok=True,
            summary=f"Send {template} email to {to}",
            effects=effects,
            warnings=warnings,
            approval_required=True,
            confidence=0.7,
        )

This is a “bounded lie” in the best sense. It is not pretending to know exactly what the email provider will do. It is showing enough for a human to understand the intended side effect.

For payments, do not simulate by guessing gateway behavior. Validate the amount, currency, customer, and payment method. If the provider has a test mode, use it only in environments where test mode is clearly separated from production. Do not let a production simulator accidentally hit a live endpoint.

For deployments or infrastructure changes, use plan-style outputs where possible. Terraform-style plan output is a good model: show resources to be created, modified, or destroyed. If your system does not have a real plan mechanism, create one. If you cannot plan safely, the action may be too dangerous for autonomous AI proposals.

The simulator should include confidence:

confidence = 0.95  # local database count
confidence = 0.70  # external email rendering
confidence = 0.40  # third-party API without dry-run support

Do not show a precise confidence number to end users unless it means something. But internally, it helps policy engines and debugging.

🚨 Production warning: If an external action is irreversible and cannot be simulated, the correct response is often to require approval, delay execution, or route it through a human workflow. Do not let “cannot simulate” become “execute anyway.”


8. Turn Policy into an Approval Engine, Not a Thousand If Statements

Scenario: One action requires approval if it affects more than 100 records. Another requires approval if it sends email. Another requires approval if the user is not an admin. These rules are scattered across handlers, UI components, and prompt logic. Nobody knows the real policy.

Why it matters: Approval decisions are security decisions. They need to be centralized, testable, and auditable.

Create a policy engine that evaluates the simulation result.

@dataclass(frozen=True)
class PolicyDecision:
    approval_required: bool
    reason: str
    warnings: list[str]

class PolicyEngine:
    def evaluate(
        self,
        proposal: ActionProposal,
        simulation: SimulationResult,
    ) -> PolicyDecision:
        warnings = list(simulation.warnings)

        critical_effects = [
            effect for effect in simulation.effects
            if effect.risk == RiskLevel.CRITICAL
        ]

        irreversible_external_effects = [
            effect for effect in simulation.effects
            if not effect.reversible and effect.kind == EffectKind.SEND
        ]

        bulk_effects = [
            effect for effect in simulation.effects
            if effect.details.get("affected_count", 0) >= 100
        ]

        if critical_effects:
            return PolicyDecision(
                approval_required=True,
                reason="Action contains critical effects",
                warnings=warnings,
            )

        if irreversible_external_effects:
            return PolicyDecision(
                approval_required=True,
                reason="Action sends external communication",
                warnings=warnings,
            )

        if bulk_effects:
            return PolicyDecision(
                approval_required=True,
                reason="Action affects 100 or more records",
                warnings=warnings,
            )

        return PolicyDecision(
            approval_required=False,
            reason="No approval policy triggered",
            warnings=warnings,
        )

Then combine it with the simulator:

from dataclasses import replace

class SimulateAndPolicy:
    def __init__(
        self,
        simulator: ActionSimulator,
        policy_engine: PolicyEngine,
    ):
        self.simulator = simulator
        self.policy_engine = policy_engine

    def preview(
        self,
        ctx: ActionContext,
        proposal: ActionProposal,
    ) -> SimulationResult:
        simulation = self.simulator.preview(ctx, proposal)

        if not simulation.ok:
            return replace(simulation, approval_required=True)

        decision = self.policy_engine.evaluate(proposal, simulation)

        return replace(
            simulation,
            approval_required=decision.approval_required,
            warnings=simulation.warnings + [decision.reason],
        )

The policy engine can become more sophisticated over time:

  • role-based rules,
  • resource ownership rules,
  • monetary thresholds,
  • time-of-day restrictions,
  • rate limits,
  • break-glass workflows,
  • dual approval for destructive actions,
  • environment-specific rules.

The key is that the policy is evaluated against structured effects, not against vibes.

This also prevents a common failure mode: the UI asks for confirmation, but the backend executes without checking. Approval must be enforced where execution happens.


9. Store the Proposal, Simulation, Approval, and Execution as One Audit Chain

Scenario: Something goes wrong. The AI says it only updated one record. The database says 2,000 records changed. The user says they never approved it. The approval UI says it showed a preview. Nobody can prove what the preview contained.

Why it matters: If the simulation is not stored, it did not happen. An audit chain lets you reconstruct the sequence: what was proposed, what was shown, who approved it, and what was executed.

Store a record like this:

@dataclass(frozen=True)
class ApprovalDecision:
    approved_by: str | None
    approved_at: str | None
    decision: str
    reason: str | None

@dataclass(frozen=True)
class ExecutionResult:
    ok: bool
    summary: str
    details: dict[str, Any]

@dataclass(frozen=True)
class ActionAuditRecord:
    proposal: ActionProposal
    simulation: SimulationResult
    policy_decision: PolicyDecision
    approval: ApprovalDecision | None
    execution: ExecutionResult | None
    recorded_at: str

The audit record should be written before execution, not after.

A practical flow:

1. Create proposal
2. Simulate proposal
3. Store proposal + simulation + policy decision
4. If approval required, wait for approval
5. Store approval decision
6. Execute action using same idempotency key
7. Store execution result

This gives you a durable explanation of the action’s lifecycle.

It also helps with replay. If execution fails after approval, you can retry the same proposal without generating a different simulation. If the simulation becomes stale, you can detect that and require re-approval.

For example, a database simulation may include a state hash:

details = {
    "affected_count": 4821,
    "state_hash": "orders:closed:90d:8f2c1a",
}

Before execution, the executor can check whether the state hash still matches. If it does not, the simulator should run again.

Be careful with sensitive data. The simulation may contain personal data, credentials, or internal identifiers. Encrypt audit records where appropriate, redact fields that should not persist, and define retention policies.

🔍 Why this matters: The audit chain is not only for compliance. It is how you debug the difference between what the AI intended, what the user approved, and what the system actually did.


10. Test the Simulator Like a Flight Simulator

Scenario: The simulator works for the happy path. Then an adapter throws, the database is slow, the external provider is down, or the model proposes an action with missing arguments. The preview either crashes or silently says everything is fine.

Why it matters: The simulator is safety-critical. If it fails quietly, it becomes worse than no simulator because users trust it.

Test at least four categories.

Happy-path previews

Verify that known actions produce expected effects.

def test_archive_preview_counts_records():
    fake_db = FakeDatabase(orders=[...])
    adapter = ArchiveStaleOrdersAdapter()
    simulator = ActionSimulator({"archive_stale_orders": adapter})

    proposal = ActionProposal(
        id="prop_1",
        action="archive_stale_orders",
        arguments={"older_than_days": 90},
        actor_id="user_1",
        session_id="sess_1",
        idempotency_key="sess_1:archive:abc",
        requested_at="2026-01-01T00:00:00Z",
    )

    ctx = ActionContext(
        actor_id="user_1",
        session_id="sess_1",
        db=fake_db,
        services=FakeServices(),
        now=datetime(2026, 1, 1),
    )

    result = simulator.preview(ctx, proposal)

    assert result.ok
    assert result.effects[0].details["affected_count"] == 3

Policy tests

Verify approval triggers.

def test_bulk_archive_requires_approval():
    policy = PolicyEngine()

    simulation = SimulationResult(
        ok=True,
        summary="Archive 500 orders",
        effects=[
            Effect(
                kind=EffectKind.UPDATE,
                resource_type="order",
                description="Archive orders",
                risk=RiskLevel.HIGH,
                reversible=True,
                details={"affected_count": 500},
            )
        ],
        warnings=[],
        approval_required=False,
        confidence=0.9,
    )

    decision = policy.evaluate(proposal, simulation)

    assert decision.approval_required

Failure tests

Verify behavior when adapters fail.

class BrokenAdapter:
    name = "broken"

    def validate(self, arguments):
        return []

    def simulate(self, ctx, arguments):
        raise RuntimeError("database unavailable")

    def execute(self, ctx, arguments):
        raise RuntimeError("database unavailable")

The simulator should catch adapter exceptions and return a failed simulation rather than crashing the whole agent loop.

try:
    simulation = adapter.simulate(ctx, proposal.arguments)
except Exception as exc:
    return SimulationResult(
        ok=False,
        summary="Simulation failed",
        effects=[],
        warnings=[f"Simulation error: {exc}"],
        approval_required=True,
        confidence=0.0,
    )

Drift tests

Verify that simulate() and execute() remain aligned.

If execution changes, simulation should change with it. One way to enforce this is to require both methods to use shared query builders or shared command objects.

For example:

def stale_order_filter(older_than_days: int) -> str:
    return """
        status = 'closed'
        AND updated_at < now() - (%s::text || ' days')::interval
    """

Then both simulation and execution use the same filter.

This is not perfect, but it reduces the chance that the preview uses one rule while execution uses another.

💡 Practical note: Add a test that fails when a registered action has no simulator. If an action can execute but cannot simulate, make that visible in code review.


When an Action Simulator Becomes Theater

An action simulator can still fail even when it exists.

It becomes theater when:

  • the preview is generated from a different code path than execution,
  • the UI shows a generic warning for every action,
  • approval is required so often that users click through blindly,
  • the simulation is stale by the time execution happens,
  • external effects are hidden behind vague labels,
  • the audit log stores only “approved” without the preview,
  • the executor ignores the approval decision,
  • the simulator is bypassed for “urgent” or “admin” paths.

The worst version is a system that says “This action may have side effects” for everything. Users learn to ignore it. Then the simulator provides the appearance of safety without the substance.

A better approach is to be selective and specific.

Use strong friction for actions that are:

  • irreversible,
  • high-cost,
  • externally visible,
  • bulk,
  • financial,
  • security-sensitive,
  • difficult to audit.

Use lighter friction for actions that are:

  • read-only,
  • easily reversible,
  • scoped to the current user,
  • low-volume,
  • already constrained by policy.

The goal is not to add confirmation everywhere. The goal is to make dangerous actions legible before they happen.


What I Would Ship

If I were building an AI action simulator for a production system, I would not start with a perfect universal model of every side effect. I would start with a narrow, enforceable pipeline.

The baseline would look like this:

  1. The model can propose actions, but it cannot execute them directly.
  2. Every proposal is typed and includes actor, session, and idempotency information.
  3. Every registered action has an adapter.
  4. Every adapter must implement validate, simulate, and execute.
  5. Simulation results are structured effects, not only prose.
  6. Database actions use read-only probes where practical.
  7. External actions are marked as partially predictable.
  8. Approval policy runs server-side against structured effects.
  9. Approvals are tied to a stored simulation snapshot.
  10. Execution uses the same proposal and idempotency key.
  11. Audit records store the full chain.
  12. The simulator fails closed when it cannot produce a trustworthy preview.

The mental model is simple:

AI proposes.
Simulator explains.
Policy decides.
Human approves when necessary.
Executor acts.
Audit remembers.

An AI action simulator does not make side effects go away. It makes them visible while they are still avoidable.

That is the entire point. The best time to stop a bad action is not after the database has changed, the email has gone out, or the payment has been captured. It is while the action is still just a proposal.

Post a Comment

Previous Post Next Post