Metadata-Version: 2.5
Name: cohortica
Version: 0.1.0
Summary: Configurable synthetic-population study engine
Project-URL: Homepage, https://github.com/WrongerSandwich/cohortica
Project-URL: Repository, https://github.com/WrongerSandwich/cohortica
Project-URL: Issues, https://github.com/WrongerSandwich/cohortica/issues
Author-email: Evan Trout <fishyevan@gmail.com>
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: llm,personas,research,simulation,social science,survey instrument,synthetic population
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: FastAPI
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.14
Requires-Dist: anthropic<2,>=1.17
Requires-Dist: fastapi>=0.158
Requires-Dist: google-genai>=2.31
Requires-Dist: httpx>=0.28
Requires-Dist: numpy>=1.26
Requires-Dist: openai<4,>=3.30
Requires-Dist: pydantic>=2.7
Requires-Dist: python-dotenv>=1.0
Requires-Dist: pyyaml>=6.0
Requires-Dist: scikit-learn>=1.4
Requires-Dist: tenacity>=8.2
Requires-Dist: typer>=0.12
Requires-Dist: uvicorn[standard]>=0.29
Description-Content-Type: text/markdown

# cohortica

A configurable synthetic-population study engine: generate a persona
population from a schema you define, run it through a task (survey
instrument, free-form prompt, allocation exercise), score the responses into
dimensional profiles, cluster them, compare against hand-crafted prototype
vectors, and produce a report — with methodological guardrails (instrument
blinding, model separation, claims discipline) built in as first-class
features.

Use cases: structurally validating survey instruments before fielding them
to humans, synthetic market/UX research (open-ended answers scored by
rubric and theme-coded), piloting social-science study designs, and studying how different
LLMs role-play populations.

**Status:** v1 complete — full pipeline, reports, plugins, examples.
**What this is not:** a substitute for human data. Reports say so, by design.
**Where it is going:** [`docs/vision.md`](https://github.com/WrongerSandwich/cohortica/blob/main/docs/vision.md) — a study app in one
visual register, with the models a dimension of the data.

## Install

Requires Python ≥ 3.14. From PyPI (the wheel carries the built web
workbench):

```sh
uv tool install cohortica     # or: pip install cohortica
cohortica --version
```

Installed this way, drop the `uv run` prefix from the commands below. From a
source checkout, with [uv](https://docs.astral.sh/uv/):

```sh
git clone https://github.com/WrongerSandwich/cohortica && cd cohortica
uv sync
uv run pytest -q        # full suite, fully offline (no API keys)
```

## Quickstart

```sh
uv run cohortica init my-study        # scaffold a study directory
cd my-study
# put API keys in .env (only the providers you use):
#   ANTHROPIC_API_KEY / GEMINI_API_KEY / OPENAI_API_KEY / OPENROUTER_API_KEY
uv run cohortica validate             # config + guardrail checks (free)
                                      #   --online: can each pinned OpenRouter host serve? (free)
uv run cohortica pools                # preset respondent pools; `pools apply ID` (free)
uv run cohortica review               # LLM methodological critique (cheap, advisory)
uv run cohortica rehearse             # offline dress rehearsal + cost forecast (free)
uv run cohortica generate --limit 5   # pilot a few personas first
uv run cohortica generate             # full population (resumable)
uv run cohortica run                  # task stage (resumable)
uv run cohortica score                # responses -> profiles (dimensional; or rated by rubric)
uv run cohortica analyze              # descriptives / clustering / prototypes / themes
uv run cohortica report               # findings report: report.json + report.md (claims block first)
uv run cohortica status               # what each stage produced so far (+ est. cost, output per unit)
uv run cohortica pipeline             # or: all five stages in order, one line per stage
```

Every stage takes `--run NAME` to keep multiple runs side by side, and
`generate`/`run` take `--limit N` for cheap pilots. `validate` runs before
any spend and is also re-checked by the spending commands.

`cohortica pipeline` runs generate → run → score → analyze → report through
the same stage runner the commands and the browser workbench use, skipping a
stage the study lacks (no `analysis.scoring`, no analyses), then prints the
estimated cost. `--from STAGE` starts later (the stages before it are not
run); `--seed-from RUN` answers another run's people instead of generating,
only when this study's population is the one they were drawn from. The first
Ctrl-C stops at the stage boundary (a spending stage at its next commit
point) and the run stays resumable — re-run the same command; a second
Ctrl-C exits at once.

`cohortica variant SOURCE DEST [--name N] [--description D] [--from-run RUN]`
forks a study so a changed instrument, population or pool does not drift the
runs already made from the original: it copies the study directory minus its
outputs (`runs/`, `rehearsals/`, `reviews/`, `comparisons/`, `calibration/`,
dot-entries such as `.env`, `__pycache__`), gives the copy its own `name` / `description`, and
records where it came from in `variant.json`. Free; `DEST` must not exist, and
a copy that does not load as a study is removed. API keys are not copied: a
variant still finds its source study's `.env`.

Before spending anything: `review` sends your configs and instrument to an
LLM methodologist for an advisory critique (leading items, unbalanced scales,
mis-aimed axis mappings — findings land in `reviews/`, nothing is ever
blocked), and `rehearse` runs the entire pipeline offline against a stub
provider — full population size, zero API calls — writing the exact prompts
that would be sent, a banner-stamped rehearsal report, and a per-stage token +
USD forecast (with and without prompt caching) to `rehearsals/<name>/forecast.md`.
A stub cannot know thinking, which is billed as output, so where a run of
the study's own task (a small pilot under `runs/`) measured a row, the
forecast takes that row's output from the run. Elsewhere it names the models
that think by default and states the figure at the output cap. See
[Measured output in the forecast](https://github.com/WrongerSandwich/cohortica/blob/main/docs/configuration.md#measured-output-in-the-forecast).
`rehearse` also prints a time line per stage, but only where a real run in
`runs/` (or a variant's source) measured the same model at the same
concurrency, or a reference pace covers it (a preset pool member's for the
run stage, the default generator's per person for generate); otherwise the
line says why there is no figure. See
[Stage timing and the time estimate](https://github.com/WrongerSandwich/cohortica/blob/main/docs/configuration.md#stage-timing-and-the-time-estimate).

### Dig into the results

- `cohortica trace P0042` — one persona end to end: the generation prompt that
  created it, its record, the exact task prompt it received (reconstructed,
  flagged if configs drifted), its answers (every executor and replicate
  that answered it), retries, axis profile, cluster,
  and the provider request ids to quote to a provider's support. Read-only
  and free.
- `cohortica interview P0042` — chat with a persona about its answers,
  grounded in its record and actual responses and voiced by the same model
  that answered (`--model` / `models.interview` override). `--cluster 2`
  interviews the cluster's nearest-to-centroid exemplar; `--ask "…"` asks one
  question non-interactively. Transcripts land under
  `runs/<name>/interviews/` with the claims block.
- `cohortica compare baseline variant` — what changed between two runs:
  what the manifests say differs, then axis, cluster, item and theme
  differences, written to `comparisons/<name>/` with the claims block.
  Read-only and free. To isolate one change, seed the second run with the
  first run's personas (`cohortica generate --run variant --from-run
  baseline`, no calls), change the one setting, `run` and `score`, then
  compare: the same personas are *paired* and per-persona differences mean
  something. Runs on independently generated personas compare as
  distributions only, and the output says the difference mixes the change
  with sampling. See [Comparing runs](https://github.com/WrongerSandwich/cohortica/blob/main/docs/configuration.md#comparing-runs).
- `cohortica annotate --finding <id> --text "…"` — a note on one finding of
  the report (`--report` for the report as a whole); with no flag it lists
  the notes and the finding ids. Notes sit under their finding in
  `report.md` and in the app's Report view (where they are written and
  edited too), never change the generated text, and survive a re-report.
  See [Notes on a report](https://github.com/WrongerSandwich/cohortica/blob/main/docs/configuration.md#notes-on-a-report).
- `cohortica calibrate draw <run>` / `score <id>` / `lock <id>` — score a
  sample of a run's free-text answers yourself, blind to the rater, then
  see where you and the rater agree. Seeing the rater's readings locks your
  scores. Free; the free-text note then states the agreement. The app does
  the same from the report's free-text note, one answer at a time. See
  [Calibrating the rater](https://github.com/WrongerSandwich/cohortica/blob/main/docs/configuration.md#calibrating-the-rater-against-your-own-scoring).

## Browser workbench

Prefer a UI? `cohortica ui` launches a local web workbench over the same
library, in three places:

- **The Library**: your studies as a stack of cards. Hover one for its people,
  models and clusters; open it, or start a **New study**, or **Open folder…**.
- **A study**: the run's people as marks on a full screen (the Field),
  arranged by any pair of scoring axes, population fields, the cluster, the
  model or the map (a scatter, strips, a grid or groups), coloured and shaped
  by any of them, split into one mark per model's reading, and filtered by
  clicking a label, dragging across an axis or from the shelf; everything you
  choose is in the URL, so a link lands on the same picture. Open the lens
  (the people in view as a list beside the Field, sortable by any measure,
  each row opening to their raw answers side by side per model), open anyone's
  card (every model's reading on one radar, how far the models disagree and
  where, their trace and an interview), pin up to four people, read the report
  (the claims block first; every finding a live reference: click it and the
  lens beside the report lists exactly the people it is about; "On the
  Field →" shows it there, captioned with the claim; add your own notes to a
  finding or the report, kept apart from the generated text), compare runs, this study's or a variant's (paired
  runs get a scatter per axis), make a variant (a copy of the study that
  keeps this one's runs as they are, and answers the same people when the
  population is unchanged), or open Run details to launch,
  re-run or cancel any single stage. The shelf shows the estimated spend
  committed to the run manifest ("cost unavailable" without price data, never
  `$0.00`).
- **The composer**: Name it → The study → The population → Review. A new
  study starts from the composer's defaults (1,000 people, the
  `two-families` pool). The study chooses what people are asked (questions
  or a free-form prompt), shows how it is scored (the axes the scoring
  config defines, by the file's own names), and lists the analyses,
  each saying what it needs; The population sets who, how many, the
  generator, the respondent pool (a preset with its evidence, or by hand),
  how many people every model answers, and whether to ask twice. Each choice
  saves as it is made, with what it means beside it ("Edit as YAML" for the
  raw files). Review lays out every choice, the study's checks (with, for a
  study that pins an OpenRouter host, whether that host can serve the calls,
  read free from OpenRouter's public list), and the estimate: a free offline rehearsal runs on its own when none is current,
  prices are fetched from OpenRouter's public catalog only when you press
  the button, and time is shown only where a run has measured that model's
  pace. **Start the run** (disabled, with the reason, on a check error or a
  missing API key) launches one pipeline job: generate → run → score →
  analyze → report, stopping at the first failure. **Continue run** picks a
  stopped run back up; on a variant's run that never generated (a refused
  Start) it answers the source run's people, as Start would have, when the
  population still matches.

A run in progress plays live: people appear as each batch is written, light
up in their model's colour while they are being asked, and move to their
clusters when the analysis lands. Every change is a real engine event. A
rehearsal plays the same way, offline and free ("Watch it" on Review), and
ends on its estimate.
Light and dark themes; reduced motion respected.

```sh
uv run cohortica ui                   # serves http://127.0.0.1:8765 and opens a browser
uv run cohortica ui --no-open --port 9000
uv run cohortica ui --host 0.0.0.0 --allow-host workbench.lan   # trusted network only — no auth
```

There is no authentication. The server does defend itself against the
standard localhost attacks: it answers only to `Host` values it was told
about (loopback names, the bind host, this machine's hostname, and anything
passed via `--allow-host`; `--allow-host '*'` disables the check) and refuses
HTTP requests and WebSocket upgrades whose `Origin` is another site. That
blocks a web page from reaching the server via DNS rebinding — which matters
because a study can declare plugins that run arbitrary Python with your API
keys in the environment. It does **not** make a non-loopback bind safe
against anyone who can reach the port.

It does nothing the CLI can't (it's a thin client of the same stages). From a
source checkout, build the SPA once first so it can be served:

```sh
cd frontend && npm install && npm run build   # outputs to cohortica/ui/static/
```

## How it works

A study is a directory of four config files plus the task content:

| File | Owns |
|---|---|
| `study.yaml` | models per stage (provider-prefixed, e.g. `anthropic/claude-sonnet-5-5`, `openrouter/meta-llama/llama-3.3-70b-instruct`), temperature/batching/concurrency, the replication design (`replicates`, `overlap`), guardrail settings |
| `population.yaml` | population size, the persona field schema (your fields, types, guidance), stratification weights |
| `task.yaml` | task type (`instrument`, `freeform`, `allocation`) + content file + presentation + provenance |
| `analysis.yaml` | scoring (`dimensional`, `rubric` for free text, or a custom plugin) + the list of analyses |

**The full schema reference is [`docs/configuration.md`](https://github.com/WrongerSandwich/cohortica/blob/main/docs/configuration.md).**

The pipeline stages communicate only through files under `runs/<name>/`
(personas.jsonl → responses/ → scored.jsonl → analysis/ → report.json + report.md), each
stage resumable: interrupted generation continues where it stopped (a batch
the model answered short is topped up, and `status` names any stratum still
below its allocation), failed
task responses are retried simply by re-running `cohortica run`, and a
`manifest.json` records config hashes, guardrail results, and token usage
(the dollar estimate built on it is opt-in; see *Cost estimates*). Editing configs mid-run
triggers a drift warning.

## Methodological guardrails

- **Blinding** — persona generation structurally never sees the task
  content, plus a lexical-overlap check catching pasted instrument text.
- **Model separation** — warns (or errors) when the model family that
  designed the task also generates the personas, the circularity that
  undermines synthetic validation studies.
- **Sampling discipline** — a per-model capability table says which models
  accept a caller-set temperature. For those, warns at temperature 0 (the
  population collapses toward one respondent) and ≥ 1.0 (structured output
  degrades). For models that do not (current Anthropic models, OpenAI
  reasoning models other than `gpt-5.1` / `5.2` / `5.4`, whose default
  effort is `none`, and Gemini 3+, which Google advises keeping at its
  default 1.0 and, from 3.6 Flash on, ignores a temperature), the
  temperature is never sent, the check says the provider default applies, and the run manifest and report record the
  sampling actually in force per model.
- **Models it cannot call** — validate errors on a retired model, a
  Responses-API-only OpenAI model or Gemini Omni wherever the pipeline would
  call it (every call would fail), and warns on a limited-access model.
- **Stability, measurable** — `run.replicates` asks each persona the same
  task more than once, and `run.overlap` has several executors answer the
  same personas, so a run's artifacts can show how stable a profile is
  across samples and across models. The resume unit becomes (persona,
  executor, replicate). The `reliability` analysis turns replicates into
  test–retest numbers (one-way ICC per axis, with the sampling the executor
  ran under beside it) and `model_agreement` turns the overlap into
  executor-vs-executor ones (Pearson r, Lin's CCC, bias, cluster κ).
- **The respondent pool** — `run.shares` states each executor's share of
  the people it voices (a mixture of models; equal by default), and
  `cohortica pools` lists curated preset pools with what is known about
  each member. The `overlap` check warns when fewer than 30 people are
  answered by every model (Koo & Li 2016) or a model voices fewer than 30 of
  its own; it is advisory and never blocks. The `analyses` check is not: it
  errors when `model_agreement` has fewer than two executors or no shared
  people, `reliability` has one replicate (#171), or `rater_reliability`
  has one rating per response (#54).
- **Free-text raters** — `rubric` scoring rates open-ended answers and
  `theme_coding` codes them, both with `models.interpretation`; validate errors before any spend when the rater
  is missing, and model separation warns when the rater shares a family with
  an executor (a model favouring its own family's text) or with the task's
  designer.
- **Thinking discipline** — current Anthropic models think by default;
  `run.effort` sets the depth where a model takes it (`init` writes Sonnet
  5.5's own `high`, chosen by a measured pilot, #44), and validate warns
  when an executor's reasoning depth is left to the provider. The manifest,
  report and rehearsal forecast state the thinking actually in force.
- **Claims discipline** — every report opens with an auto-generated
  methodology block: results are "informed by synthetic-population
  analysis", never "validated"; synthetic results are not evidence about
  human populations. Not configurable off. A rubric-scored or theme-coded run
  adds a second note: the scores and codes are a model's readings of model
  text, not human-coded data. Until the study's author has scored a sample
  themselves (`cohortica calibrate`) it says they have not been validated
  against human coders; after, it states the rater's agreement with the
  author, filled from the calibration, and never says "validated".
- **Findings by rule** — the report leads with templated findings chosen by
  rule (where the models agreed, what separates people, the groups, where
  people lean, people worth meeting), each with its statistic, the people it
  is about and a chart; every superlative says what it was chosen from, and
  a null result is stated as plainly as a positive one. `report.json` holds
  them and `report.md` is rendered from it ([The report](https://github.com/WrongerSandwich/cohortica/blob/main/docs/configuration.md#the-report)).

## Scoring and analysis

`score` runs the config-driven `dimensional` scorer — a golden-tested port
of the Governance Compass scoring engine (recorded responses from the
original study reproduce its committed profiles byte-for-byte). All math
(axis mappings, modality fusion weights, budget sigmoid, tension and
confidence thresholds, super-dimensions) lives in the scoring config, not in
code. For a freeform task, the `rubric` scorer has `models.interpretation`
rate each response against a config-defined rubric (axes, poles, anchored
integer levels) onto the same axis scale, blind to the persona and with the
evidence it rated from; it is a resumable spend stage like `run`, and every
analysis below works on its profiles. `scoring.ratings: 2` rates each
response twice and scores the mean, which the docs recommend when a study
reads `reliability` under rubric scoring: the rater's own noise was 22–43%
of the within-person spread when measured (#54). `analyze` runs the configured list: `descriptives` (per-item answer
distributions, no scoring required), `clustering` (k-means, silhouette-swept
or explicit k), `prototype_comparison` (empirical centroids vs hand-crafted
prototype vectors, with nearest/margin/unmatched/collapsed tables),
`reliability` (test–retest per executor; needs `run.replicates >= 2`) and
`model_agreement` (executor pairs over the overlap set; needs
`run.overlap`), `rater_reliability` (the rubric rater against itself on the
same response, and under replicates the split of one score's noise between
respondent and rater; needs `scoring.ratings >= 2`) and, for freeform tasks, `theme_coding` (`models.interpretation`
codes each response against a config-defined codebook; code shares per
executor — a resumable spend stage like `rubric` scoring). See `docs/configuration.md` → analysis.yaml for each
artifact's fields.

## Cost estimates

`report` and `status` show an estimated USD cost from the token usage recorded
in run manifests. Price data **does not ship** — it goes stale and isn't vital,
so cost estimation is opt-in. Until prices are available, cost reads
*"unavailable — no price data"* (never a misleading `$0.00`). Two ways to
populate it:

```bash
# OpenRouter publishes per-token pricing via a public API; this fetches it and
# writes a (gitignored) cohortica/data/prices.yaml with the openrouter/* rows:
uv run python scripts/update_prices.py            # preview the diff
uv run python scripts/update_prices.py --write    # apply (a thin wrapper over
                                                  # cohortica.pricing_sync.update_price_table)

# Or price specific models per-study (works for any provider) in study.yaml:
#   pricing:
#     anthropic/claude-sonnet-5-5: { input: 2.0, output: 10.0 }   # USD per Mtok
```

Anthropic/OpenAI/Google expose no pricing API, so those are populated via the
study `pricing:` block. `update_prices.py --include-proxied` can also *fill in*
native `anthropic/` / `openai/` / `gemini/` rows from the price of each
model's first-party endpoint on OpenRouter (one request per model) — still an
estimate, so check it against the provider's list price. It is fill-only: it
never changes a row that is already there, and it records the rows it filled
under `proxied:` in `prices.yaml` so a later run refreshes those and nothing
else. `--overwrite-proxied` is the explicit opt-in to replace hand-kept rows.
The write is atomic and a fetch error (no network, a bad reply) leaves the
existing table untouched.

The run stage uses prompt caching where the provider supports it (the
instrument is the same for every persona): usage records cached tokens
separately, and optional `cache_read` / `cache_write` prices price them. See
[Prompt caching](https://github.com/WrongerSandwich/cohortica/blob/main/docs/configuration.md#prompt-caching), including why
`randomize_item_order: true` turns caching off in practice.

## Plugins

A study can point at study-local Python files — no packaging required:

```yaml
scoring: {type: custom, module: ./my_scorer.py}   # def score(bundle, records) -> list[dict]
analyses:
  - {type: custom, module: ./my_analysis.py}      # def run(bundle, run_path, options) -> dict
```

Typed contracts live in `cohortica/builtins/base.py`. **Plugins execute
arbitrary Python with your API keys in the environment — only run studies
you trust.**

## Examples

- **`examples/governance-compass/`** — the study this engine generalizes:
  a 61-item political-attitudes instrument (36 forced-choice, 24 scaled, one
  50-point budget allocation), a 1,000-persona globally stratified
  population, 12-axis scoring, clustering, and comparison against 12
  hand-crafted archetypes. Reproduced at full scale on 2026-10-22 with the
  original Sonnet 4.6 + Gemini 2.5 Flash pair (≈ $39 at list prices). The
  report, the analysis artifacts and a comparison with the original study are
  in `examples/governance-compass/results/`. `results/full/` is the complete
  run directory (personas, responses, scored profiles, analysis, report).
  To explore it in `cohortica ui` or with `trace` / `interview` / `compare`,
  copy it into the study's runs:
  `cp -r examples/governance-compass/results/full examples/governance-compass/runs/full`.
  `frontend/scripts/demo-studies.sh` builds it as `demo-compass` (with two
  rehearsed demo studies) in a scratch directory instead.
- **`examples/quickstart/`** — a minimal three-item consumer survey with a
  one-axis scorer and clustering; the fastest way to see the whole pipeline.
- **`examples/freeform-ux/`** — an open-ended UX question (a meal-planning
  subscription's price rise and ad-supported free tier) answered by two
  executor families, rated on a three-axis rubric and coded against a
  six-code codebook by an open-weight rater from a third family (DeepSeek
  V4.1 Flash through OpenRouter, pinned to one host; `OPENROUTER_API_KEY`);
  clustering on the rubric profiles. Rehearses offline end to end (`cohortica rehearse`); the worked
  example for `rubric` scoring and `theme_coding`.

## Development

```sh
uv run pytest -q                                  # offline Python suite
uv run ruff check cohortica tests scripts         # lint (CI also runs `ruff format --check` and `mypy`)
COHORTICA_LIVE=1 uv run pytest tests/test_live_smoke.py   # opt-in: 2 real personas (~cents)
cd frontend && npm run lint && npm test          # web UI lint + suite (offline, via MSW)
```

The per-model capability table (`cohortica/providers/capabilities.py`) is
hand-curated. To find where it has gone stale, run the warn-only drift check:

```sh
uv run python scripts/check_capabilities.py           # LiteLLM + models.dev (+ Anthropic /v1/models with a key)
uv run python scripts/check_capabilities.py --strict  # exit 1 on an uncovered id or a disagreement
```

It lists model ids no table row covers and fields where a row and a source
disagree, each with the source's URL. It never edits the table: check the
provider's docs, then fix the row and cite them.

The web workbench is a React SPA in `frontend/` (a pure client of the FastAPI
server in `cohortica/ui/`); its design specs and implementation plans are under
[`docs/design/`](https://github.com/WrongerSandwich/cohortica/tree/main/docs/design).

Agent/contributor orientation (invariants, code map, test conventions):
[`CLAUDE.md`](https://github.com/WrongerSandwich/cohortica/blob/main/CLAUDE.md). The original `governance-synth-survey` design spec
and implementation plans live in the (currently private) repo this project
was extracted from.
