# Scored evaluations

> Datasets, versioned tasks, sealed episodes and tamper-aware scoring.

For evaluations whose scores must mean something, Elefork keeps the grading outside the database the agent works in:

1. **Dataset → template.** Upload a `pg_dump` or CSV once; Elefork loads it into a fresh branch, runs `ANALYZE`, checkpoints it and registers an org template. Every episode starts from that exact state.
2. **Task.** A named, versioned set of acceptance rules (SQL plus expected values). Rules live in the control plane and never enter tested databases.
3. **Episode.** A fresh branch of the task's template. The agent connects as usual.
4. **Seal.** Credentials for the branch are revoked at once and no new ones are issued; after one route lease the agent's sessions are terminated, a checkpoint is taken and the branch is deleted.
5. **Score.** A disposable copy of the sealed state is started. The scorer checks its integrity against the task's baseline, then runs the rules read-only.

```python
from elefork import Client
import psycopg

c = Client()
ds = c.upload_dataset("rl", "shop", open("shop.sql", "rb").read())   # pg_dump --format=plain
c.build_dataset(ds["id"], base_template="pg18")                       # org template "shop"

task = c.create_task("rl", "ship-order", template="shop", rules=[
    {"name": "shipped", "sql": "SELECT status FROM shop.orders WHERE id = 7", "expect": "shipped"},
    {"name": "audited", "sql": "SELECT count(*) FROM shop.audit WHERE order_id = 7", "expect": 1},
])

ep = c.start_episode(task["id"])
uri = c.credentials(ep["branch"]["id"])["uri"]
...                                       # the agent works against `uri`
result = c.seal_episode(ep["episode"]["id"])
print(result["state"], result["integrity"], result["score"])
```

## Rules

Each rule is one SQL query returning one row with one column. It passes if the value equals `expect` (any JSON value; numeric strings compare numerically), or is `true` when `expect` is omitted. `weight` (default 1) sets its share of `score`. `passed` is true when every rule passes.

Rules run in a read-only transaction with `search_path = pg_catalog, pg_temp`, so **schema-qualify your tables** (`shop.orders`, not `orders`). Functions or operators the agent created in other schemas cannot shadow the built-ins a rule uses.

## Integrity

Before scoring, the copy is compared with a fingerprint of the start state taken when the task was created:

| Checked | Examples |
|---|---|
| Triggers, rules, views, policies, row-level security | dropping or disabling an audit trigger, `DO INSTEAD NOTHING` rules, redefined views |
| Functions, operators, casts, extensions | a `public.count()` that always returns 1; a redefined trigger function |
| Database and role settings | `ALTER DATABASE ... SET search_path` |
| Existing constraints | dropping a check constraint, re-adding it `NOT VALID` |
| The episode's WAL | a catalog changed and then restored, e.g. the table owner disables a trigger, changes data and re-enables it; the final catalog is identical, only the WAL shows it |
| Prepared transactions | left open at seal time |

Creating tables, columns, indexes and new constraints is normal work and is not reported. If a task legitimately asks for one of the kinds above, list it in `allow` (for example `"allow": ["function", "trigger"]`).

The outcome is `integrity`:

- `clean`: no findings; the score stands.
- `review`: scored, but something needs a human look (for example the episode's WAL was no longer available).
- `tampered`: a change that can fake a result. The episode gets no score and its state is `tampered`.

Tasks with `role: "superuser"` are marked `tamper_evident: false` in the result. A superuser can, for example, run with `session_replication_role = replica` to skip business triggers without leaving a trace any generic check can see; only task-specific rules can catch that.

## Episode records and failure samples

`result.data_changes` lists the tables that were added, removed, changed shape or changed content compared with the start state, with row counts. `result.rules` has the value and timing of each rule, and `result.findings` the integrity findings.

The sealed state is kept as a checkpoint (`seal_checkpoint_id`): 24 hours for passed, clean episodes and 7 days for everything else (failed rules, `review`, `tampered`, errors). To reproduce a failure, create a branch from that checkpoint.

## Limits today

- Datasets: plain-format `pg_dump` of one database (psql meta-commands other than `\restrict` are rejected) or CSV; up to 256 MiB by default. Parquet is not supported yet.
- Seeds are stored with the task but not yet applied with `setseed()` at session start.
- The SQL statement log of an episode is not recorded yet; `data_changes` covers what changed.
