Metadata-Version: 2.4
Name: herdsman
Version: 0.1.0
Summary: An independent statistical referee for AI analysts: count every test, seal the confirmation data, certify only what survives.
Author: John Christiansen
License-Expression: Apache-2.0
Keywords: e-values,false discovery rate,AI agents,multiple testing,MCP,reproducibility
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Classifier: Topic :: Scientific/Engineering :: Information Analysis
Classifier: Intended Audience :: Science/Research
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Requires-Dist: numpy>=1.24
Requires-Dist: pandas>=2.0
Requires-Dist: cryptography>=41
Provides-Extra: mcp
Requires-Dist: mcp>=1.2; extra == "mcp"
Provides-Extra: llm
Requires-Dist: anthropic>=0.40; extra == "llm"
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"
Dynamic: license-file

# Herdsman

**An independent statistical referee for AI analysts.** Count every test. Seal the confirmation data. Certify only what survives.

*Herdsman* takes its name from Buachaille Etive Mòr, the great herdsman of Etive, which stands guard at the head of Glen Coe.

AI agents now run data analyses in minutes that used to take analysts days. They also make the oldest failure in statistics cheap: try enough subgroups, outcomes and specifications and something will look significant. Herdsman sits between an agent and its data and makes a simple promise, stated precisely below: of the findings it certifies, the expected share that are false is at most your chosen level (10% by default), however hard the agent searched, however it chose and revised its claims, and however those claims depend on one another.

## How it works

1. **Seal.** When a study is created, the data are split into an open *exploration* set and several *sealed folds*. Each fold is encrypted with a key only the referee holds, and its SHA-256 hash is published as a commitment, together with a hash of the random seed.
2. **Explore and count.** The agent explores the exploration data as much as it likes. Tests run through the referee are written to a hash-chained ledger, so the size of the search behind any finding is on the record.
3. **Commit.** When the agent believes a finding, it commits a precise, testable *claim*. At that moment the referee fixes the evidence the claim will need (its e-LOND level). Nothing the agent does later can change it.
4. **Confirm on fresh data.** At the end of each episode the referee opens the next sealed fold once. Every open claim gets that fold's e-value, which multiplies into the claim's running evidence. A claim is certified when its evidence reaches the level fixed at commit. The fold is then *spent* and released to the agent, because nothing committed afterwards is ever tested on it.
5. **Sign.** Certified claims receive an Ed25519-signed certificate that records the claim, its commit time and ledger position, its evidence path, how many exploratory tests preceded it, and the guarantee.

The language model is in the loop but not in the guarantee. An LLM may group related tests into hypothesis families for disclosure, or propose which claims belong together, but every number Herdsman reports is computed by deterministic code, and no grouping can weaken the guarantee.

## The guarantee

In the default *rolling* mode, if the sealed folds are independent random samples from the study population, then across every claim committed in a study

> E[ false certified claims / max(certified claims, 1) ] ≤ α,

whatever the analyst or agent did before committing each claim, in whatever order claims were committed, however claims depend on one another, and whenever the analyst stopped. The proof combines e-LOND (Xu and Ramdas, 2024), whose level for claim *t* is fixed at commit, with Ville's inequality for each claim's evidence across folds. It does **not** require logging to be complete: validity comes from sealing, not surveillance. The ledger exists so that people can see and audit the search.

A *batch* mode is also available for teams that can pre-register one confirmation: all claims are committed, then a single sealed fold is opened and the batch is tested together with Benjamini–Yekutieli (valid under arbitrary dependence), Benjamini–Hochberg (under positive dependence) or e-BH. Batch mode is more powerful for a single round; rolling mode is the one that stays valid when an agent comes back for more.

What a certificate does not say: that an association is causal, that the population will not shift, or that the claim was the right question to ask. Those remain matters of design and judgement.

## Install

```bash
pip install herdsman            # core: numpy, pandas, cryptography
pip install "herdsman[mcp]"     # adds the MCP server for agents
pip install "herdsman[llm]"     # optional: LLM family proposals (off in demo mode)
```

From a source checkout: `pip install -e ".[mcp,dev]"`, then `pytest`.

## Quickstart (Python)

```python
import pandas as pd
from herdsman import Referee

data = pd.read_csv("experiment.csv")

# The data owner creates the study and keeps the keys directory to themselves.
referee = Referee.create(
    "studies/journey-b", "keys/journey-b", data,
    outcomes=["completed", "minutes"], bounds={"minutes": (0, 120)},
    alpha=0.10, horizon=20, n_folds=3, exploration_fraction=0.4,
    title="Journey B experiment",
)

# The analyst (human or agent) opens the study WITHOUT keys.
analyst = Referee("studies/journey-b")
explore = analyst.exploration_data()
analyst.explore_test({"outcome": "completed", "population": "device == 'mobile'",
                      "focal": "variant == 'B'", "reference": "variant == 'A'"})
analyst.commit_claim({
    "statement": "Journey B raises completion among mobile applicants",
    "outcome": "completed", "population": "device == 'mobile'",
    "focal": "variant == 'B'", "reference": "variant == 'A'", "direction": "increase",
})

# The referee closes the episode: one sealed fold is opened, evidence is updated.
print(referee.close_episode())
# ... more episodes ...
referee.close_study()
print(referee.verify())                       # ledger chain, released folds, signatures
open("report.html", "w").write(referee.report_html())
```

## Quickstart (command line)

```bash
herdsman init experiment.csv --study studies/s1 --keys keys/s1 \
    --outcome completed --outcome minutes --bounds minutes:0:120 --horizon 20
herdsman brief  --study studies/s1
herdsman explore --study studies/s1 --spec '{"outcome":"completed","focal":"variant == '"'B'"'","reference":"variant == '"'A'"'"}'
herdsman commit --study studies/s1 --claim '{...}'
herdsman close-episode --study studies/s1 --keys keys/s1
herdsman close-study   --study studies/s1 --keys keys/s1
herdsman verify --study studies/s1
herdsman verify-certificate studies/s1/certificates/C001.json --public-key <hex>
herdsman report --study studies/s1 --out report.html
herdsman bundle --study studies/s1 --out s1_audit.zip
herdsman verify-bundle s1_audit.zip --public-key <hex>
```

An *audit bundle* is a zip of the study parameters, ledger, signed checkpoint, certificates and fold hashes. It holds no keys and no data, so it can go to a validator, an auditor or a journal; `verify-bundle` checks the ledger chain, every signature and that each certificate's commit record is in the ledger. Pass `--public-key` with a key from a source you trust, otherwise the bundle is only checked against the key it carries.

## For agents: the MCP server

```json
{"mcpServers": {"herdsman": {"command": "herdsman-mcp", "args": ["--study", "/data/studies/s1"]}}}
```

Tools: `study_brief`, `describe_groups`, `explore_test`, `commit_claim`, `commit_family_claim`, `list_claims`, `budget_status`, `get_certificate`, `search_disclosure`. The agent never receives the keys; the operator closes episodes. Pass `--keys ... --allow-close` only if you deliberately let the agent trigger fold openings (it still cannot read sealed data through the tools).

## Claims

A claim is a one-sided statement about a population mean, precise enough for code to test.

| Field | Meaning |
|---|---|
| `outcome` | an outcome column (binary, or numeric with declared bounds) |
| `population` | filter defining who the claim is about (empty = everyone) |
| `focal`, `reference` | filters for the two groups compared; `reference: "rest"` means everyone else in the population |
| `direction` | `increase` (focal mean higher) or `decrease` |
| `margin` | optional minimum difference, in outcome units |
| `value` | for *level* claims instead of a reference: the mean exceeds (or falls below) this value |
| `statement` | plain-English wording; not used in the statistics |

Filters use a small, safe language: column names, constants, comparisons, `in [...]`, `and`, `or`, `not`. They are parsed with a whitelist and can never execute code. A row belongs to a group only if every column the filter mentions is observed.

*Family claims* (`commit_family`) state that at least one of several effects is real, using one claim slot; their evidence on each fold is the average of the members' e-values.

## Configuration

| Setting | Default | Notes |
|---|---|---|
| `alpha` | 0.10 | false discovery rate across the study |
| `horizon` | 50 | claim slots; the budget is spread evenly over them (`gamma="uniform"`). Set it close to the number of claims you expect: unused slots are unused power. `gamma="decaying"` allows unlimited claims at lower power. |
| `n_folds`, `exploration_fraction` | 3, 0.4 | more folds give more episodes; more sealed data gives more power |
| `n_orderings`, `max_bet` | 16, 0.5 | e-value averaging and bet cap |
| `prior_weight`, `prior_shrink` | 100, 0.5 | each claim's first bets start from its exploration estimate, halved; fixed at commit, so validity is unaffected |
| `mode` | `rolling` | or `batch` with `batch_procedure` = `by`, `bh` or `ebh` |
| `HERDSMAN_DEMO_MODE` | `1` | demo mode never calls an external model |

## Threat model

Herdsman protects against careless, motivated and adaptive analysts, human or AI, who can explore freely and choose claims after looking. It assumes the referee's keys and process are not under the analyst's control. Locally, a determined user with root on the same machine can read anything; that is what the hosted referee is for. It assumes rows are independent draws from a stable population; with `time_column` the folds are later time blocks, so certified claims have held up on later data.

## Licence

Apache 2.0. Copyright 2026 Credit Risk Models (E) Limited, trading as Nibheis.
