> ## Documentation Index
> Fetch the complete documentation index at: https://aivision.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Read the relevant procedure and prerequisites before suggesting commands. Cite the section and give an observable check. Treat sample data as illustrative. Report product actions and results only when verified in the user's environment.

# Run custom rules in a sandbox

> Use 7 complete examples for JSON validation, generated-code tests, order reconciliation, business constraints, retrieval ranking and numerical error.

After installing OpenShell in the target Space, custom rules can import preinstalled libraries, test generated Python, reconcile tables, validate business constraints, and evaluate retrieval ranking or numerical error. Load a complete example, inspect every metric's reason and evidence, then use content actually recorded in your own Trace.

This page applies to platforms with **Integrations → Plugins → Sandbox → OpenShell**. Management requires Space administrator or developer permissions; creating custom diagnosers also requires a team space. Start with **Automatic installation**, which asks for no images, gateway, plugin endpoint or token. The advanced section below covers an independently deployed service.

## 1. Install automatically and save the Space connection

1. Switch to the target Space and open **Integrations → Plugins → Sandbox → OpenShell → Install OpenShell**.
2. Read the target host and permission requirements, then choose **Copy install command**.
3. Use the matching CLI that supports `aiv plugin setup openshell`. Run the complete copied command in a terminal on the **AI Vision deployment host**. Copying does not run it; do not use another host or Docker daemon.
4. Follow the reported phases and wait for **Space connection saved**. Setup prepares the images, dedicated gateway, secure configuration and plugin, then saves and tests the connection through the server. No technical parameters need to be entered.

See [Automatic OpenShell installation](https://aivision.mintlify.site/en/deployment/openshell.md) for prerequisites and recovery. If the installation catalog is unavailable, ask the deployment administrator for a compatible version/package. Do not invent image references or switch to a manual form. Closing or reloading the drawer resumes reads without rerunning installation.

**Service ready** and **Space connection saved** are different states. Readiness checks authentication, protocol and provider state; it creates no workload and does not validate rule execution or cleanup. Continue with the explicit default setting and trial below.

## 2. Set the Space default and execution policy explicitly

After the automatic-install drawer shows **Space connection saved**, choose **Set as Space default** if needed. The server tests the connection again and confirms the binding before showing **Space default set**. This action preserves the current “Require sandbox execution for custom rules” setting and the frozen targets of existing Tasks.

[![English dark installation drawer on a 390-pixel viewport shows seven completed stages and the server-confirmed Space default](https://mintcdn.com/aivision/W8FwR0B7OvfGW_UI/assets/figures/openshell-current-real-default.en.png?fit=max\&auto=format\&n=W8FwR0B7OvfGW_UI\&q=85\&s=acacb04e0eef1867d54d810d9614b610)](https://aivision.mintlify.site/assets/figures/openshell-current-real-default.en.png)

Actual Linux AMD64 VM: confirmed default and compact footer · Read-only English view · Click to enlarge

For an existing-service connection added through the advanced path, return to **Sandbox**, select the verified **Default connection** under **Space execution policy**, and choose **Save Space default**. Other execution-policy settings are also managed there separately.

If every custom rule must use a sandbox, also select **Require a sandbox for Custom Rule execution** and save. This setting refuses local execution; it does not install the service or configure a connection. Execution fails when no usable sandbox is available.

[![English Sandbox page with OpenShell on the left and the Space default connection and sandbox requirement on the right](https://mintcdn.com/aivision/dV2TtZMAp3g6qPp1/assets/figures/sandbox-policy.en.light.webp?fit=max\&auto=format\&n=dV2TtZMAp3g6qPp1\&q=85\&s=1f7b1d0a3655f702c4c33097339fadc2)](https://aivision.mintlify.site/assets/figures/sandbox-policy.en.light.webp)

[![English Sandbox page in dark mode showing the Space execution policy](https://mintcdn.com/aivision/dV2TtZMAp3g6qPp1/assets/figures/sandbox-policy.en.dark.webp?fit=max\&auto=format\&n=dV2TtZMAp3g6qPp1\&q=85\&s=8e1158fb4d3c8754380c25e78c0897d2)](https://aivision.mintlify.site/assets/figures/sandbox-policy.en.dark.webp)

Sandbox: provider configuration and Space execution policy · Running UI with demonstration data · Click to enlarge

## 3. Choose the custom rule's execution environment

In a team space, open **Diagnosers → New Diagnoser** and choose the rule type. Under **Execution environment**, select one of the three execution-mode buttons:

| Option | Execution behavior |
| - | - |
| **Follow Space settings** (`inherit`) | Uses the Space default connection. Without a default, only restricted rules can run locally when policy permits; enhanced rules require a compatible sandbox. |
| **Use sandbox** (`required`) | Uses the rule's explicitly selected **Sandbox connection**, or the Space default if none is selected. Fails if neither is configured. |
| **Local execution** (`local`) | Restricted rules only. Enhanced rules cannot run locally; Space sandbox requirements also reject local execution. |

With **Follow Space settings**, the field below directly displays the Space default connection. If there is no default and the Space permits local execution, it shows **Local execution**. A green check inside the connection field indicates verified readiness, with hover text and an accessible status label. With **Use sandbox**, choose a **Sandbox connection** in the same area or use the Space default when no connection is explicitly selected. If a required connection is missing, the page prompts you to choose one or configure a Space default.

[![English custom rule execution environment with Follow Space settings, Use sandbox, Local execution and the current target and readiness](https://mintcdn.com/aivision/KShepopXvGHy0ou1/assets/figures/diagnoser-sandbox.en.light.webp?fit=max\&auto=format\&n=KShepopXvGHy0ou1\&q=85\&s=858e64d58c33034850b179bdcc8f1ff4)](https://aivision.mintlify.site/assets/figures/diagnoser-sandbox.en.light.webp)

[![English custom rule execution environment in dark mode with three execution modes and the current target](https://mintcdn.com/aivision/KShepopXvGHy0ou1/assets/figures/diagnoser-sandbox.en.dark.webp?fit=max\&auto=format\&n=KShepopXvGHy0ou1\&q=85\&s=d6533963c53952236cdaad93c658c3d7)](https://aivision.mintlify.site/assets/figures/diagnoser-sandbox.en.dark.webp)

Custom rule execution: three modes, the resolved target and readiness · Running UI with API demonstration data · Click to enlarge

If a selected connection is missing, disabled, unready or unreachable, execution **does not automatically fall back to local**. Only restricted rules can keep an optional local path under an explicit Space policy and rule mode; changing the mode does not downgrade an enhanced rule.

Sandboxes are used only for custom rules. **LLM evaluators call model services through [model connections](https://aivision.mintlify.site/en/guides/model-connections.md)** and do not use this sandbox execution selection. This rule-editor example's readiness state comes from API demonstration data; it does not replace real rule execution and cleanup checks.

## Confirm the enhanced Python environment

A compatible connection shows **Enhanced Python · imports, files and code tests**. Open **Available libraries** for the Python and package versions reported by this sandbox: **pytest, NumPy, pandas, Pydantic, jsonschema and openpyxl**, alongside the standard library. You do not enter images, install packages or select another runtime mode.

* **New rules:** the editor automatically uses enhanced Python once it confirms a compatible sandbox, and saves that environment identity.
* **Existing rules:** keep their restricted Python behavior until you explicitly choose **Use enhanced Python**, review the draft and save it. Historical Task snapshots retain their original behavior.
* **Local or incompatible targets:** cannot run enhanced rules and never trigger local fallback. Choose a compatible sandbox before saving or trying the rule.
* **Plugin update required:** ask your operator for matching plugin and workload versions. Increasing timeout or memory alone does not add runtime support to an old plugin.

[![Actual Linux AMD64 VM rule editor shows sandbox execution, 30-second budget and six library versions in Chinese](https://mintcdn.com/aivision/dV2TtZMAp3g6qPp1/assets/figures/openshell-vm-enhanced-rule.zh-CN.png?fit=max\&auto=format\&n=dV2TtZMAp3g6qPp1\&q=85\&s=971e953858506992dfd0e991f6ce406f)](https://aivision.mintlify.site/assets/figures/openshell-vm-enhanced-rule.zh-CN.png)

Actual Linux AMD64 VM: saved rule, enhanced Python and six libraries · Chinese interface · Click to enlarge

You still write the rule: use `evaluate(trace)` or `evaluate(trace, context)` and return each declared metric, its `good` / `bad` verdict, reason and JSON evidence. Enhanced rules support ordinary imports, helper functions and classes. Use `context` for materials and reference tests; confirm observed field expressions with **View Trace Structure**.

New automatic installations recommend **1 CPU, 1 GiB and 30 seconds**. Existing connections are unchanged. With management permission and a compatible environment whose limits are too low, choose **Apply recommended limits**. This raises only insufficient values, preserves higher limits and checks readiness again. Read **Effective execution budget** in the summary, separately from **Connection limit**. The read-only runtime API reports the smaller of the enhanced service ceiling and the connection limit: a connection capped at 5 seconds still cannot run for 30 seconds.

## Load 7 complete examples, from starter checks to advanced evaluation

Expand **Load an example** and choose from **Starter examples** or **Advanced examples**. Each includes matching metrics, complete evaluation code, reference materials, expected values and synthetic test input. Loading replaces these draft contents and clears previous Trial results, so start with a new rule.

Inspect each metric’s reason and evidence, then deliberately change an input to confirm that the rule detects an error. The `example.*` fields are teaching conventions, not fields automatically collected from your Agent. Examples need neither network access nor package installation.

Reference materials are inputs to the evaluator. If they are malformed or internally inconsistent, fix them and rerun; an evaluator execution error is not an Agent-quality verdict.

| Level | Example | What it evaluates | Libraries |
| - | - | - | - |
| Starter | JSON structure and citation fields | Required fields, types, empty citations and unexpected fields | jsonschema |
| Starter | Combined CSV and Excel checks | Separate verdicts for a CSV total and an XLSX cell in one rule | pandas, openpyxl |
| Advanced | Parameterized tests for generated code | 9 cases for deduplication, order, empty values, Unicode and invalid input | pytest |
| Advanced | Orders and refunds across tables | Aggregate repeated refunds before joining orders; verify regional totals and net revenue | pandas |
| Advanced | Business constraints for refund decisions | Strict types and constraints across refund amount, approval status and reason | pydantic |
| Advanced | Retrieval ranking and citation coverage | Recall\@k, binary-relevance nDCG and citation-ID coverage against reference labels | numpy |
| Advanced | Pointwise tolerance and aggregate error | Absolute/relative pointwise tolerances plus MAE and an RMSE budget | numpy |

> [accordion] JSON structure and citation fields
>
> The reference `schema.json` requires a non-empty answer and at least one unique citation ID, and forbids extra fields. Change input `citations` to `[]`: expect `schema_valid: bad` and a field path. A valid structure does not establish a correct answer.
>
> Metrics loaded: `schema_valid`.
>
> ```python title="Rule code" theme={null}
> import json
> import jsonschema
>
>
> def evaluate(trace, context):
>     # Map this synthetic field to the observed Agent output in your own rule.
>     spans = trace.get("spans") or []
>     actual = spans[0].get("attributes", {}).get("example.json_output") if spans else None
>     schema = json.loads(context.read_text("schema.json"))
>     validator = jsonschema.Draft202012Validator(schema)
>     errors = list(validator.iter_errors(actual))
>     return {"metrics": [{
>         "name": "schema_valid", "verdict": "bad" if errors else "good",
>         "reason": "Validate required fields, types, citation IDs and unexpected properties",
>         "evidence": {"expected": schema, "actual": actual, "failures": [
>             {"path": "/".join(map(str, error.path)), "reason": error.message}
>             for error in errors[:10]
>         ]},
>     }]}
> ```
>
> ```json title="Synthetic test input" theme={null}
> {
>   "spans": [
>     {
>       "attributes": {
>         "example.json_output": {
>           "answer": "42 items remain in stock.",
>           "citations": [
>             "stock-2026"
>           ]
>         }
>       }
>     }
>   ]
> }
> ```
>
> ```json title="schema.json" theme={null}
> {
>   "type": "object",
>   "required": [
>     "answer",
>     "citations"
>   ],
>   "additionalProperties": false,
>   "properties": {
>     "answer": {
>       "type": "string",
>       "minLength": 1
>     },
>     "citations": {
>       "type": "array",
>       "minItems": 1,
>       "uniqueItems": true,
>       "items": {
>         "type": "string",
>         "minLength": 1
>       }
>     }
>   }
> }
> ```

> [accordion] Combined CSV and Excel checks
>
> Compare both a pandas total from `sales.csv` and the value openpyxl reads from `reference.xlsx:B2` against reported input; both references are 42. Change only `example.total` to 41: `csv_total` should become `bad` while `xlsx_match` remains `good`. Loading includes the binary workbook; no Base64 copying is needed.
>
> Metrics loaded: `csv_total`, `xlsx_match`.
>
> ```python title="Rule code" theme={null}
> import io
> import math
> import pandas as pd
> from openpyxl import load_workbook
>
>
> def evaluate(trace, context):
>     spans = trace.get("spans") or []
>     actual = spans[0].get("attributes", {}) if spans else {}
>     sales = pd.read_csv(io.StringIO(context.read_text("sales.csv")))
>     if sales.empty or "amount" not in sales:
>         raise ValueError("Reference sales.csv must contain non-empty amount rows")
>     amounts = pd.to_numeric(sales["amount"], errors="raise")
>     if amounts.isna().any() or not all(math.isfinite(float(value)) for value in amounts):
>         raise ValueError("Every reference amount must be a finite number")
>     expected_total = math.fsum(float(value) for value in amounts)
>     if not math.isfinite(expected_total):
>         raise ValueError("The reference total must be finite")
>     book = load_workbook(context.material_path("reference.xlsx"), read_only=True, data_only=True)
>     try:
>         expected_cell = book.active["B2"].value
>     finally:
>         book.close()
>     if type(expected_cell) not in (int, float) or not math.isfinite(expected_cell):
>         raise ValueError("Reference workbook B2 must contain a finite numeric value")
>     total = actual.get("example.total")
>     valid_total = type(total) in (int, float) and math.isfinite(total)
>     total_matches = valid_total and abs(total - expected_total) < 0.000001
>     cell = actual.get("example.cell_b2")
>     cell_matches = type(cell) in (int, float) and cell == expected_cell
>     return {"metrics": [
>         {"name": "csv_total", "verdict": "good" if total_matches else "bad",
>          "reason": "Recompute the reported total from CSV rows",
>          "evidence": {"expected": expected_total, "actual": total}},
>         {"name": "xlsx_match", "verdict": "good" if cell_matches else "bad",
>          "reason": "Compare the reported workbook value with the reference cell",
>          "evidence": {"path": "reference.xlsx:B2", "expected": expected_cell, "actual": cell}},
>     ]}
> ```
>
> ```json title="Synthetic test input" theme={null}
> {
>   "spans": [
>     {
>       "attributes": {
>         "example.total": 42,
>         "example.cell_b2": 42
>       }
>     }
>   ]
> }
> ```
>
> ```csv title="sales.csv" theme={null}
> item,amount
> A,12
> B,30
> ```
>
> `reference.xlsx`: This binary file loads with the example. The source workbook contains B2 = 42; you do not construct it manually.

> [accordion] Parameterized tests for generated code
>
> Candidate source provides `normalize_tags` through a temporary `candidate` module. Reference tests check case folding, deduplication, first-seen order, input preservation, empty values and invalid input. Replace `.casefold()` with `.lower()` in the candidate: the Unicode case should fail. The file uses pytest parameterization and exception assertions rather than checking only whether a process starts.
>
> Metrics loaded: `reference_tests`.
>
> ```python title="Rule code" theme={null}
> def evaluate(trace, context):
>     spans = trace.get("spans") or []
>     source = spans[0].get("attributes", {}).get("example.generated_code") if spans else None
>     if not isinstance(source, str) or not source.strip():
>         return {"metrics": [{"name": "reference_tests", "verdict": "bad",
>                              "reason": "Missing generated Python source"}]}
>     # The reference tests import candidate.normalize_tags from this generated source.
>     result = context.run_python_tests(source, "tests/test_candidate.py")
>     return {"metrics": [{
>         "name": "reference_tests", "verdict": result["verdict"].lower(),
>         "reason": "Run normalization, ordering, invalid-input and Unicode reference tests",
>         "evidence": result,
>     }]}
> ```
>
> ```json title="Synthetic test input" theme={null}
> {
>   "spans": [
>     {
>       "attributes": {
>         "example.generated_code": "def normalize_tags(tags):\n    if not isinstance(tags, list) or any(not isinstance(tag, str) for tag in tags):\n        raise ValueError(\"tags must be a list of strings\")\n    return list(dict.fromkeys(tag.strip().casefold() for tag in tags if tag.strip()))\n"
>       }
>     }
>   ]
> }
> ```
>
> ```python title="tests/test_candidate.py" theme={null}
> import pytest
> from candidate import normalize_tags
>
>
> @pytest.mark.parametrize("tags, expected", [
>     (["  Python ", "python", "DATA"], ["python", "data"]),
>     (["B", "a", "b", "c"], ["b", "a", "c"]),
>     (["", "  ", "	"], []),
>     ([], []),
>     (["Straße", "STRASSE", "数据"], ["strasse", "数据"]),
> ])
> def test_normalization_and_first_seen_order(tags, expected):
>     original = list(tags)
>     assert normalize_tags(tags) == expected
>     assert tags == original, "The candidate must not mutate its input"
>
>
> @pytest.mark.parametrize("tags", [None, "python", [1], ["ok", None]])
> def test_invalid_input(tags):
>     with pytest.raises(ValueError):
>         normalize_tags(tags)
> ```

> [accordion] Orders and refunds across tables
>
> `orders.csv` contains 3 orders and `refunds.csv` allows multiple refunds per order. Aggregate refunds before joining to avoid counting orders twice, then reconcile integer-cent amounts by region. Expected East is 2100, West is 2500 and net revenue is 4600 cents. Change only `net_revenue_cents` to see a passing regional metric and a failing net-revenue metric.
>
> Metrics loaded: `regional_totals`, `net_revenue`.
>
> ```python title="Rule code" theme={null}
> import io
> import pandas as pd
>
>
> def evaluate(trace, context):
>     orders = pd.read_csv(io.StringIO(context.read_text("orders.csv")), dtype={"order_id": "string", "region": "string", "gross_cents": "string"})
>     refunds = pd.read_csv(io.StringIO(context.read_text("refunds.csv")), dtype={"order_id": "string", "refund_cents": "string"})
>     if not {"order_id", "region", "gross_cents"} <= set(orders.columns) or orders.empty:
>         raise ValueError("Reference orders require non-empty order_id, region and gross_cents columns")
>     if not {"order_id", "refund_cents"} <= set(refunds.columns):
>         raise ValueError("Reference refunds require order_id and refund_cents columns")
>     for frame, columns in ((orders, ("order_id", "region")), (refunds, ("order_id",))):
>         for column in columns:
>             if frame[column].isna().any() or frame[column].str.strip().eq("").any():
>                 raise ValueError("Reference IDs and regions must not be blank")
>     if orders["order_id"].duplicated().any():
>         raise ValueError("Reference order IDs must be unique")
>     if not set(refunds["order_id"]) <= set(orders["order_id"]):
>         raise ValueError("Every reference refund must identify an existing order")
>     for frame, column in ((orders, "gross_cents"), (refunds, "refund_cents")):
>         # Keep cents as text until validation: float inference can round large integers.
>         raw = frame[column]
>         if raw.isna().any() or not raw.str.fullmatch(r"[0-9]+").all():
>             raise ValueError("Reference cents must use non-negative integer digits")
>         values = pd.to_numeric(raw, errors="raise")
>         if sum(int(value) for value in values) > 9223372036854775807:
>             raise ValueError("Reference cents exceed the exact integer aggregation range")
>         frame[column] = values.astype("int64")
>     # Aggregate repeated refunds before joining, so orders are not double counted.
>     refunds = refunds.groupby("order_id", as_index=False)["refund_cents"].sum()
>     # Nullable integers preserve exact cents when an order has no refund row.
>     refunds["refund_cents"] = refunds["refund_cents"].astype("Int64")
>     ledger = orders.merge(refunds, on="order_id", how="left", validate="one_to_one")
>     ledger["refund_cents"] = ledger["refund_cents"].fillna(0).astype("int64")
>     ledger["net_cents"] = ledger["gross_cents"] - ledger["refund_cents"]
>     if (ledger["net_cents"] < 0).any():
>         raise ValueError("Reference refunds must not exceed an order's gross amount")
>     expected_regions = {str(key): int(value) for key, value in
>                         ledger.groupby("region")["net_cents"].sum().items()}
>     expected_net = int(ledger["net_cents"].sum())
>     spans = trace.get("spans") or []
>     report = spans[0].get("attributes", {}).get("example.report") if spans else None
>     report = report if isinstance(report, dict) else {}
>     regions = report.get("regions")
>     region_shape = isinstance(regions, dict) and all(type(v) is int for v in regions.values())
>     region_match = region_shape and regions == expected_regions
>     net = report.get("net_revenue_cents")
>     net_match = type(net) is int and net == expected_net
>     return {"metrics": [
>         {"name": "regional_totals", "verdict": "good" if region_match else "bad",
>          "reason": "Reconcile every region after aggregating partial refunds",
>          "evidence": {"expected": expected_regions, "actual": regions}},
>         {"name": "net_revenue", "verdict": "good" if net_match else "bad",
>          "reason": "Verify the net total using integer cents",
>          "evidence": {"expected": expected_net, "actual": net, "order_count": len(ledger)}},
>     ]}
> ```
>
> ```json title="Synthetic test input" theme={null}
> {
>   "spans": [
>     {
>       "attributes": {
>         "example.report": {
>           "regions": {
>             "East": 2100,
>             "West": 2500
>           },
>           "net_revenue_cents": 4600
>         }
>       }
>     }
>   ]
> }
> ```
>
> ```csv title="orders.csv" theme={null}
> order_id,region,gross_cents
> o1,East,2400
> o2,West,3000
> o3,East,600
> ```
>
> ```csv title="refunds.csv" theme={null}
> order_id,refund_cents
> o1,700
> o1,200
> o2,500
> ```

> [accordion] Business constraints for refund decisions
>
> The Pydantic model checks strict types, extra fields and cross-field rules: refunds cannot exceed an order total; rejected decisions require zero refund; approved decisions require a positive refund; reasons cannot be blank. Set `refund_cents` to 11000 for the 10000-cent order: expect `business_valid: bad` with constraint locations and reasons.
>
> Metrics loaded: `business_valid`.
>
> ```python title="Rule code" theme={null}
> from typing import Literal
> from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator
>
>
> class RefundDecision(BaseModel):
>     model_config = ConfigDict(strict=True, extra="forbid")
>     status: Literal["approved", "rejected"]
>     order_total_cents: int = Field(gt=0)
>     refund_cents: int = Field(ge=0)
>     reason: str = Field(min_length=1, max_length=300)
>
>     @model_validator(mode="after")
>     def validate_business_rules(self):
>         if not self.reason.strip():
>             raise ValueError("A non-blank reason is required")
>         if self.refund_cents > self.order_total_cents:
>             raise ValueError("Refund cannot exceed the order total")
>         if self.status == "rejected" and self.refund_cents != 0:
>             raise ValueError("A rejected decision must have zero refund")
>         if self.status == "approved" and self.refund_cents == 0:
>             raise ValueError("An approved decision must have a positive refund")
>         return self
>
>
> def evaluate(trace, context):
>     spans = trace.get("spans") or []
>     actual = spans[0].get("attributes", {}).get("example.refund_decision") if spans else None
>     try:
>         decision = RefundDecision.model_validate(actual)
>         failures = []
>         actual = decision.model_dump()
>     except ValidationError as error:
>         # Omit exception objects in ctx so all evidence remains JSON serializable.
>         failures = error.errors(include_url=False, include_context=False, include_input=False)[:10]
>     return {"metrics": [{
>         "name": "business_valid", "verdict": "bad" if failures else "good",
>         "reason": "Check strict field types and cross-field refund constraints",
>         "evidence": {"actual": actual, "failures": failures},
>     }]}
> ```
>
> ```json title="Synthetic test input" theme={null}
> {
>   "spans": [
>     {
>       "attributes": {
>         "example.refund_decision": {
>           "status": "approved",
>           "order_total_cents": 10000,
>           "refund_cents": 2500,
>           "reason": "One of four items was damaged."
>         }
>       }
>     }
>   ]
> }
> ```

> [accordion] Retrieval ranking and citation coverage
>
> Supply relevant document IDs, k and thresholds through **Expected value (JSON)**. Change retrieved order to `["doc-x", "doc-a", "doc-b"]`: recall and citation coverage can still pass while ranking quality fails. This compares supplied relevance labels and citation IDs. It does not establish answer faithfulness or call an embedding or judge model.
>
> Metrics loaded: `retrieval_recall`, `ranking_quality`, `citation_coverage`.
>
> ```python title="Rule code" theme={null}
> import numpy as np
>
>
> def evaluate(trace, context):
>     # These are relevance labels supplied by a reference set, not semantic judgments.
>     reference = context.expected
>     relevant = set(reference["relevant_ids"])
>     k = reference["k"]
>     spans = trace.get("spans") or []
>     actual = spans[0].get("attributes", {}) if spans else {}
>     retrieved = actual.get("example.retrieved_ids")
>     citations = actual.get("example.cited_ids")
>     valid_retrieval = (isinstance(retrieved, list) and 0 < len(retrieved) <= 100
>                        and all(isinstance(item, str) for item in retrieved)
>                        and len(set(retrieved)) == len(retrieved))
>     ranked = retrieved[:k] if valid_retrieval else []
>     hits = np.asarray([1.0 if item in relevant else 0.0 for item in ranked])
>     recall = len(set(ranked) & relevant) / len(relevant)
>     discounts = np.log2(np.arange(len(ranked), dtype=float) + 2.0)
>     dcg = float((hits / discounts).sum())
>     ideal_count = min(len(relevant), k)
>     ideal_dcg = float((1.0 / np.log2(np.arange(ideal_count, dtype=float) + 2.0)).sum())
>     ndcg = dcg / ideal_dcg
>     valid_citations = (isinstance(citations, list) and 0 < len(citations) <= 100
>                        and all(isinstance(item, str) for item in citations)
>                        and len(set(citations)) == len(citations))
>     citation_set = set(citations) if valid_citations else set()
>     supported = valid_citations and valid_retrieval and citation_set <= set(ranked)
>     coverage = len(citation_set & relevant) / len(relevant)
>     return {"metrics": [
>         {"name": "retrieval_recall", "verdict": "good" if valid_retrieval and recall >= reference["min_recall"] else "bad",
>          "reason": "Measure relevant-document recall in the first k results",
>          "evidence": {"actual": recall, "expected": reference["min_recall"], "k": k, "ranked_ids": ranked}},
>         {"name": "ranking_quality", "verdict": "good" if valid_retrieval and ndcg >= reference["min_ndcg"] else "bad",
>          "reason": "Measure binary-relevance nDCG, penalizing late relevant results",
>          "evidence": {"actual": ndcg, "expected": reference["min_ndcg"]}},
>         {"name": "citation_coverage", "verdict": "good" if supported and coverage >= reference["min_citation_coverage"] else "bad",
>          "reason": "Check citation IDs against retrieved and reference IDs; this does not prove answer faithfulness",
>          "evidence": {"actual": coverage, "expected": reference["min_citation_coverage"], "supported_ids": bool(supported)}},
>     ]}
> ```
>
> ```json title="Synthetic test input" theme={null}
> {
>   "spans": [
>     {
>       "attributes": {
>         "example.retrieved_ids": [
>           "doc-a",
>           "doc-b",
>           "doc-x"
>         ],
>         "example.cited_ids": [
>           "doc-a",
>           "doc-b"
>         ]
>       }
>     }
>   ]
> }
> ```
>
> ```json title="Expected value (JSON)" theme={null}
> {
>   "relevant_ids": [
>     "doc-a",
>     "doc-b"
>   ],
>   "k": 3,
>   "min_recall": 1,
>   "min_ndcg": 0.9,
>   "min_citation_coverage": 1
> }
> ```

> [accordion] Pointwise tolerance and aggregate error
>
> Supply the reference vector, absolute/relative tolerances and RMSE ceiling through **Expected value (JSON)**. NumPy checks both each point and aggregate drift. Change the first prediction from 10.01 to 10.2: inspect the failing index, MAE and RMSE. Missing, boolean, non-numeric or mismatched-length input cannot pass.
>
> Metrics loaded: `tolerance`, `error_budget`.
>
> ```python title="Rule code" theme={null}
> import numpy as np
>
>
> def evaluate(trace, context):
>     reference = context.expected
>     expected = np.asarray(reference["values"], dtype=float)
>     spans = trace.get("spans") or []
>     values = spans[0].get("attributes", {}).get("example.predictions") if spans else None
>     valid = (isinstance(values, list) and len(values) == len(expected)
>              and all(type(value) in (int, float) for value in values))
>     actual = np.asarray(values, dtype=float) if valid else np.asarray([], dtype=float)
>     valid = bool(valid and actual.shape == expected.shape and np.isfinite(actual).all())
>     if not valid:
>         return {"metrics": [{"name": name, "verdict": "bad",
>                              "reason": "Expected a finite numeric vector with the reference shape",
>                              "evidence": {"expected_count": len(expected), "actual": values}}
>                             for name in ("tolerance", "error_budget")]}
>     with np.errstate(over="ignore", invalid="ignore"):
>         errors = actual - expected
>     if not np.isfinite(errors).all():
>         return {"metrics": [{"name": name, "verdict": "bad",
>                              "reason": "The difference exceeds the finite numeric range",
>                              "evidence": {"expected": expected.tolist(), "actual": actual.tolist()}}
>                             for name in ("tolerance", "error_budget")]}
>     matches = np.isclose(actual, expected, rtol=reference["rtol"], atol=reference["atol"])
>     # Scale before aggregation: finite large candidates must produce BAD, not Infinity evidence.
>     scale = float(np.abs(errors).max())
>     normalized = errors / scale if scale else errors
>     mae = float(np.abs(normalized).mean()) * scale
>     rmse = float(np.sqrt(np.mean(normalized ** 2))) * scale
>     failed = np.flatnonzero(~matches).tolist()
>     return {"metrics": [
>         {"name": "tolerance", "verdict": "good" if bool(matches.all()) else "bad",
>          "reason": "Check each point with absolute and relative tolerance",
>          "evidence": {"failures": [{"index": index, "expected": float(expected[index]), "actual": float(actual[index])} for index in failed[:10]],
>                       "rtol": reference["rtol"], "atol": reference["atol"]}},
>         {"name": "error_budget", "verdict": "good" if rmse <= reference["max_rmse"] else "bad",
>          "reason": "Measure aggregate error so local tolerances cannot hide global drift",
>          "evidence": {"mae": mae, "rmse": rmse, "expected": reference["max_rmse"], "actual": rmse}},
>     ]}
> ```
>
> ```json title="Synthetic test input" theme={null}
> {
>   "spans": [
>     {
>       "attributes": {
>         "example.predictions": [
>           10.01,
>           19.98,
>           30.01,
>           39.99
>         ]
>       }
>     }
>   ]
> }
> ```
>
> ```json title="Expected value (JSON)" theme={null}
> {
>   "values": [
>     10,
>     20,
>     30,
>     40
>   ],
>   "rtol": 0.001,
>   "atol": 0.02,
>   "max_rmse": 0.02
> }
> ```

### Adapt an example to an actual Trace

Use **View Trace Structure** to locate actual output or candidate source, then replace the `example.*` read locations in the code. Do not assume that output belongs to the first Span. Replace reference materials, relevance labels or error thresholds and keep every returned metric aligned with its declaration. Select the actual Trace, rerun the Trial, inspect each reason and evidence, then save. Missing source, files or tool calls are not reconstructed.

Reference tests check ordinary correctness against your requirements; they do not promise protection against deliberately cheating candidates. A business model checks rule consistency, not actual business authorization. Relevance labels, citation IDs and numerical error checks are not semantic fact-checking.

> [accordion] Real sandbox results for the new examples
>
> These Chinese UI captures show the new advanced-example catalog with descriptions and libraries. Reordering retrieval results produces nDCG of about 0.693426, below the 0.9 threshold, while citation coverage remains 1. Generated code passes all 9 reference tests with 0 skipped.
>
> [![Chinese UI: choose an advanced example by purpose and installed library](https://mintcdn.com/aivision/KShepopXvGHy0ou1/assets/figures/enhanced-rule-examples-catalog.jpg?fit=max\&auto=format\&n=KShepopXvGHy0ou1\&q=85\&s=5f61e0061628def0694f768edfa17386)](https://aivision.mintlify.site/assets/figures/enhanced-rule-examples-catalog.jpg)
>
> Chinese UI: choose an advanced example by purpose and installed library
>
> [![Chinese UI: ranking fails independently while citation coverage passes](https://mintcdn.com/aivision/KShepopXvGHy0ou1/assets/figures/enhanced-rule-ranking-quality.jpg?fit=max\&auto=format\&n=KShepopXvGHy0ou1\&q=85\&s=1e56e58b97246c41256ee42f7fb7000d)](https://aivision.mintlify.site/assets/figures/enhanced-rule-ranking-quality.jpg)
>
> Chinese UI: ranking fails independently while citation coverage passes
>
> [![Chinese UI: 9 reference tests passed, 0 failed and 0 skipped](https://mintcdn.com/aivision/KShepopXvGHy0ou1/assets/figures/enhanced-rule-reference-nine-tests.jpg?fit=max\&auto=format\&n=KShepopXvGHy0ou1\&q=85\&s=07e219f3b8b9b0a8abe0a7e3bb34d580)](https://aivision.mintlify.site/assets/figures/enhanced-rule-reference-nine-tests.jpg)
>
> Chinese UI: 9 reference tests passed, 0 failed and 0 skipped
>
> The results use an actual OpenShell provider in a prepared macOS ARM64 / OrbStack Linux ARM64 local environment with explicitly synthetic input. These views show the selected controls and two result types; they do not establish real Agent Trace ingestion, another architecture, released images or a cold installation.

> [accordion] Real sandbox captures from earlier starter examples
>
> The result UI below is Chinese. These captures come from the earlier macOS ARM64 / OrbStack Linux ARM64 local source-QA exercise: a two-test addition function and separate JSON/CSV/XLSX comparisons. They show the execution and evidence presentation of those earlier examples, not verification of these 7 new templates. Inputs are synthetic; the images do not establish actual Agent Trace ingestion or another platform’s acceptance.
>
> [![Earlier passing reference test: 2 cases](https://mintcdn.com/aivision/KShepopXvGHy0ou1/assets/figures/enhanced-rule-python-good.zh-CN.dark.jpg?fit=max\&auto=format\&n=KShepopXvGHy0ou1\&q=85\&s=cdde685a59d8e1a7c289635ebc3a366f)](https://aivision.mintlify.site/assets/figures/enhanced-rule-python-good.zh-CN.dark.jpg)
>
> Earlier passing reference test: 2 cases
>
> [![Earlier failing reference test: 2 assertion differences](https://mintcdn.com/aivision/KShepopXvGHy0ou1/assets/figures/enhanced-rule-python-bad.zh-CN.dark.jpg?fit=max\&auto=format\&n=KShepopXvGHy0ou1\&q=85\&s=e6b9401d91260e708835c6df6c7046c0)](https://aivision.mintlify.site/assets/figures/enhanced-rule-python-bad.zh-CN.dark.jpg)
>
> Earlier failing reference test: 2 assertion differences
>
> [![Earlier JSON-schema comparison](https://mintcdn.com/aivision/KShepopXvGHy0ou1/assets/figures/enhanced-rule-json.zh-CN.dark.jpg?fit=max\&auto=format\&n=KShepopXvGHy0ou1\&q=85\&s=7e54895dafc687130576ed2094ca2d0a)](https://aivision.mintlify.site/assets/figures/enhanced-rule-json.zh-CN.dark.jpg)
>
> Earlier JSON-schema comparison
>
> [![Earlier CSV-total comparison](https://mintcdn.com/aivision/KShepopXvGHy0ou1/assets/figures/enhanced-rule-csv.zh-CN.dark.jpg?fit=max\&auto=format\&n=KShepopXvGHy0ou1\&q=85\&s=27bb47aea95206c08fa452bf26dc455a)](https://aivision.mintlify.site/assets/figures/enhanced-rule-csv.zh-CN.dark.jpg)
>
> Earlier CSV-total comparison
>
> [![Earlier XLSX-cell comparison](https://mintcdn.com/aivision/KShepopXvGHy0ou1/assets/figures/enhanced-rule-xlsx.zh-CN.dark.jpg?fit=max\&auto=format\&n=KShepopXvGHy0ou1\&q=85\&s=b11dea47fc06f0df8cc60524a0f7f61e)](https://aivision.mintlify.site/assets/figures/enhanced-rule-xlsx.zh-CN.dark.jpg)
>
> Earlier XLSX-cell comparison

## Add your own tests and data materials

Expand **Tests and data materials**, choose small files or add a text file. Edit reference tests, JSON, CSV and relative paths; select XLSX files to retain their binary contents. You can also enter an optional **Expected value (JSON)** and read the parsed value through `context.expected`.

| Material | Usage or limit |
| - | - |
| Files | At most 20, with no decoded file larger than 256 KiB. |
| Combined size | Decoded files plus the UTF-8 bytes of expected JSON text must fit within 512 KiB. |
| Paths | Unique, non-overlapping relative paths such as `tests/test_candidate.py`; no parent traversal, URLs, archives or host-directory mounts. |
| Text and binary | UTF-8 text or Base64 binary transport; file limits use decoded bytes. |
| Reading materials | `context.read_text(path)`, `context.read_bytes(path)` and `context.material_path(path)`; `context.work_dir` is this execution's temporary working directory. |
| Expected JSON | Finite numbers, at most 64 nested arrays or objects; the editor preserves your original JSON text. |

> [accordion] Expected JSON format for API material submissions
>
> Send expected values as the JSON string `materials.expected_json`. For example:
>
> ```json theme={null}
> {"files": [], "expected_json": "{\"answer\":42}"}
> ```
>
> The service preserves this text and counts its original UTF-8 bytes, then parses it for `context.expected`. Legacy API `materials.expected` objects remain accepted, but cannot appear together with `expected_json`. Editing and saving an old rule converts it to the new field.

Code, material, expected-value, target or environment edits require another trial. An old passing result cannot validate the changed draft. Formal Tasks keep the same material and environment identity instead of silently selecting a different runtime later.

## Check the complete execution-input budget

Before running, inspect the editor's **input usage and effective budget**. Expand it for exact request and worker-input byte counts. Code, the complete Trace (including original `payload` and attributes), materials, expected JSON and serialization overhead share this budget. The separate 512 KiB material limit still applies.

New installations default to **8 MiB (8,388,608 bytes)**, with a **16 MiB** operator hard ceiling. The actual budget also depends on the workload image's qualified capacity. An old image without valid immutable input-capacity metadata retains the **2 MiB** compatibility limit; editing a connection does not upgrade that image.

The platform checks both the complete request and normalized worker input before reserving a lease. It never silently truncates the Trace. Recheck after code, material, expected-value or sample edits. Oversize input disables Run; `sandbox_input_limit` reports the stage, actual bytes and allowed bytes. Reduce the meaningful evaluation input or ask your operator to update the matching components. Do not discard arbitrary Spans, bypass completeness checks or raise the gRPC decoder ceiling to hide a total-budget failure. Old plugins without preflight support require an update.

## 4. Try the rule on a reviewed Trace

1. Follow the [custom rule example](https://aivision.mintlify.site/en/guides/diagnosers.md#configure-a-custom-rule) to confirm the actual field expressions in `evaluate(trace)`, declared metrics and return format.
2. Confirm the execution mode and resolved target. Under **Test and Validate**, choose a Trace you have checked manually and select **Run Diagnosis**.
3. Compare each metric's verdict, reason and evidence with the Trace. Resolve execution or cleanup failures first; they do not mean that the Agent being checked has poor quality.
4. Ask your operator to confirm that the workload was cleaned up. Neither **Readiness verified** nor a rule's exit code proves cleanup.
5. Run another trial after changing the rule, execution environment, connection or sample, then save the diagnoser. Add it to a [diagnosis task](https://aivision.mintlify.site/en/guides/diagnosis-tasks.md) for a formal run.

Trial evidence can show passed, failed, skipped and total cases, duration, failing paths, expected/actual values and bounded output. Candidate syntax errors, imports outside the provided environment and assertion mismatches produce `bad`. Invalid reference tests, environment mismatch and runtime faults are execution errors. With no observed candidate failure, zero tests or incomplete skip/xfail verification are also execution errors, never passing verification.

Restricted rules retain the original 5-second default service ceiling. Enhanced rules default to a 30-second service ceiling; the actual limit is the smaller service/connection value. The trial HTTP phase budget is 600 seconds for creation, execution and cleanup; **it does not allow a single rule to run for 600 seconds**.

New tasks freeze their resolved execution target at creation. Changing the Space default does not reroute existing tasks; historical tasks retain their recorded route. If the connection endpoint, image or resource profile changes, old tasks may report `sandbox_identity_changed`. Check the configuration and create a new task rather than expecting the old one to switch connections.

### Inspect the individual Record after a formal Task

Open the Task in [execution history](https://aivision.mintlify.site/en/guides/diagnosis-tasks.md), check selected/scanned samples, valid judgments, skips and failures, then open the corresponding diagnosis Record. Compare each metric, reason and evidence. **A Task marked `succeeded` does not establish that every rule executed successfully** or that every metric is `good`. Resolve execution failures, cleanup failures and incomplete input before interpreting Agent quality.

For programmatic acceptance, use existing authorization to read that Record's `execution_status` and execution evidence, including `backend=sandbox` and `provider=openshell`. Rules requiring a complete Trace should also check `source_complete` and `projection_failed`. Execution status, metric `good` / `bad` and human-review status are separate facts.

[![Actual OpenShell Record shows the reason and answer evidence after checking seven complete Spans; human review remains pending](https://mintcdn.com/aivision/dV2TtZMAp3g6qPp1/assets/figures/openshell-vm-record.zh-CN.png?fit=max\&auto=format\&n=dV2TtZMAp3g6qPp1\&q=85\&s=25b3058992e7d769477fae513c9c0342)](https://aivision.mintlify.site/assets/figures/openshell-vm-record.zh-CN.png)

One persisted Record from the actual Linux AMD64 VM · Chinese interface and synthetic input · Click to enlarge

This example uses an isolated nested Ubuntu 24.04 Linux AMD64 VM, prepared exact-digest image caches and a synthetic Trace. Result API and independent database reads confirmed the same successful OpenShell Record; cleanup was checked separately. This does not qualify an unprepared cold installation, released images, installation on the parent host or another architecture.

## Advanced: connect an existing OpenShell service

Use this only for an independently deployed plugin service. The recommended automatic flow does not require these fields.

Switch to the target Space and open **Integrations → Plugins → Sandbox → OpenShell → Add connection**. Obtain these values from your operator:

| Field | What to enter |
| - | - |
| **Connection name** | A recognizable name that is unique in this Space. |
| **Plugin HTTP endpoint** | The plugin HTTP(S) address **reachable from the AgentLens service**, not the OpenShell gRPC gateway. Do not include credentials, query parameters or a fragment. |
| **Workload image** | The exact operator-approved image reference, containing the rule worker and included in the plugin's allowlist. |
| **Plugin access token** | Required for a new connection. Use the plugin HTTP service token, not a SpaceKey, model key or OpenShell gateway credential. |
| **CPU cores / Memory / Timeout (seconds)** | Limits compatible with the operator's configuration. The advanced manual form retains lightweight defaults of `1`, `512Mi` and `5` seconds; enhancement recommends `1`, `1Gi` and `30` seconds. CPU is an integer from 1–64, timeout is an integer from 1–300, and memory uses values such as `512Mi` or `1Gi`. |

[![English OpenShell connection form with plugin HTTP endpoint, workload image, token and resource limits](https://mintcdn.com/aivision/W8FwR0B7OvfGW_UI/assets/figures/openshell-connection-form.en.light.webp?fit=max\&auto=format\&n=W8FwR0B7OvfGW_UI\&q=85\&s=cd15af9e5306309d090577ee25e21df0)](https://aivision.mintlify.site/assets/figures/openshell-connection-form.en.light.webp)

[![English OpenShell connection form in dark mode with no token displayed](https://mintcdn.com/aivision/W8FwR0B7OvfGW_UI/assets/figures/openshell-connection-form.en.dark.webp?fit=max\&auto=format\&n=W8FwR0B7OvfGW_UI\&q=85\&s=53fe0c6e3ae3edda77dcdaaef65fdc93)](https://aivision.mintlify.site/assets/figures/openshell-connection-form.en.dark.webp)

Add an OpenShell connection using the operator's endpoint and image · Example values; token omitted in this capture, required on create · Click to enlarge

Save, select **Check readiness**, and confirm that the connection shows **Readiness verified**. **Saving a connection does not check it or make it the Space default.** The readiness check validates authentication, protocol and provider state. It does not create a workload, run rule code or verify resource cleanup.

The token is write-only and is not shown when editing. Leave it blank during an ordinary edit to keep the saved value. **When changing the Plugin HTTP endpoint, enter the token again**; leaving it blank is not allowed for an endpoint change. Use only an endpoint your operator confirms is trusted. Check readiness again after replacing credentials.

[![English OpenShell page with a Space connection, Check readiness button and collapsed plugin deployment instructions](https://mintcdn.com/aivision/W8FwR0B7OvfGW_UI/assets/figures/openshell-connections.en.light.webp?fit=max\&auto=format\&n=W8FwR0B7OvfGW_UI\&q=85\&s=cf3f076165461d268e07683a97efc78a)](https://aivision.mintlify.site/assets/figures/openshell-connections.en.light.webp)

[![English OpenShell connection management page in dark mode](https://mintcdn.com/aivision/W8FwR0B7OvfGW_UI/assets/figures/openshell-connections.en.dark.webp?fit=max\&auto=format\&n=W8FwR0B7OvfGW_UI\&q=85\&s=ba6a57c66335bc35bfbd0f39980e7023)](https://aivision.mintlify.site/assets/figures/openshell-connections.en.dark.webp)

OpenShell: manage this Space's connections; deployment help is initially collapsed · Running UI with demonstration data · Click to enlarge

## Troubleshooting

| Symptom | Check and next step |
| - | - |
| Automatic installation catalog unavailable | Ask the deployment administrator for a matching version/package with the installer and immutable catalog. Ordinary users do not enter image names. |
| Service ready but connection not saved | Wait for enrollment confirmation. Inspect host output and, if needed, prepare another command to continue the owned installation; retain state and journal. |
| Space default unchanged | Installation and enrollment do not bind the default. Choose **Set as Space default** after the connection is saved and wait for confirmation. |
| Original command cannot be copied after reload | Capabilities are returned only when generated. If you ran it on the host, keep waiting; otherwise regenerate explicitly. The old record and host execution are retained. |
| Management buttons are missing | Confirm the Space and your role. Read-only members can only view; contact a Space administrator or developer. |
| Manually saved connection shows Not checked | Select **Check readiness**. Saving, checking and default binding are three separate steps. |
| `sandbox_required` | Check the rule mode and Space requirement, then configure the intended connection. Do not switch to local to bypass the Space policy. |
| `sandbox_unavailable` / cannot connect | Check the plugin HTTP endpoint, token and health from the AgentLens service network, not only your browser or Docker host. |
| Readiness passes but the trial fails | Ask your operator to check the workload image, nonroot / Landlock / no-network policy, rule input and output, and cleanup verification socket. |
| `sandbox_identity_changed` | Current configuration differs from the old task's frozen profile. Review the historical task and create a new one. |
| `sandbox_cleanup_pending` / connection cannot be changed or deleted | Preserve leases and journals. Ask your operator to verify the actual Docker daemon and cleanup process. Pending leases still consume capacity; deleting records does not resolve them. |

Deleting a saved connection does not uninstall the plugin service. First clear its default binding, update diagnosers that still reference it, and finish the relevant pending or running tasks and their cleanup. Then delete the connection; completed task snapshots do not need rewriting. For service removal, see [OpenShell operations](https://aivision.mintlify.site/en/deployment/openshell.md#safe-removal-and-upgrades).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.