Metadata-Version: 2.5
Name: stratyfy-cli
Version: 0.6.0
Summary: The pre command: predict a yes/no outcome with rules a person can read, from data, from rules you know, or both
Requires-Python: <4,>=3.12
Requires-Dist: attrs>=23
Requires-Dist: httpx<1,>=0.27
Requires-Dist: psycopg[binary]<4,>=3.1
Requires-Dist: python-dateutil>=2.8
Requires-Dist: sqlalchemy<3,>=2.0
Requires-Dist: typer>=0.12
Description-Content-Type: text/markdown

# pre-cli

The `pre` command: predict a yes/no outcome with rules a person can read, from data, from rules you know, or both.
A coding agent runs it: in a project it uploads a table or writes rules by hand, builds and tests a model, and
scores cases; from an app's database it defines an outcome in SQL, trains and predicts.
It talks to the PRE API through `packages/pre-api-client`. It never imports PRE. The `pre project`, `pre dataset`, `pre variable`, `pre model` and `pre job` commands are the project part
(`PLAN_RULE_MINING.md`): each is one call to the API and decides nothing by itself; they live in
`pre_cli/projects.py`, `datasets.py`, `variables.py` and `jobs.py`. Its sentences come from
`packages/pre-words`, so they match the report.

## Install

```bash
pipx install stratyfy-cli          # or: uv tool install stratyfy-cli
```

For development, run `poetry install` in this folder, then `poetry run pre --help`. `pre --version` prints the
version.

The wheel and the sdist bundle `pre_api_client`, `pre_words` and `pre_report` from `packages/`, so the install
needs nothing else from this repo. `hatch_build.py` copies them in at build time. The CLI uses hatchling to build,
because poetry-core cannot include files from outside this folder. Poetry still manages the development env.

## Commands

Each command prints a short text result and a next step. Add `--json` to get one JSON object instead. On
failure the command exits with 1 and prints `code`, `message` and `next_step`.

The `pre project`, `pre dataset`, `pre variable`, `pre model` and `pre job` commands name no next step, in text or in JSON: what to do next is for the agent's
manual to say. Their text is a table for a list and a line per field for one object, with every name the user
gave in double quotes. The other commands will follow.

### Start

| Command | What it does |
| --- | --- |
| `pre guide [topic]` | Prints the guide, which the API serves: its opening page, or one topic, such as `pre guide workflow`, the method from a file to a model and its scores. `pre guide setup` is the plugin's skill, held by the CLI, so it reads before the API is reachable. |
| `pre login [--no-wait] [--api-url <url>]` | Signs in as `gh auth login` does. It prints a link and a code. The user signs in with an email code and approves the device. Then it writes a new key for this machine to `.pre/config.json`. With `--no-wait` it prints the link and exits; the next `pre login` waits for that same sign-in. That way an agent can show the user the link first. The default API is `https://api.stratyfy.ai/v1`. |
| `pre status` | Checks that the API answers and accepts the key, and names the workspace. Names the project this folder uses and its running jobs, and counts the datasets and models this folder made from a database. |
| `pre setup claude [--yes] [--dry-run] [--local]` | For Claude Code. Run it in your own terminal. It writes the PRE skill to `.claude/skills/pre-onboard/`, and adds the API host and a remote Postgres host to Claude Code's sandbox network allowlist. It shows the change and asks first. It refuses to write when an agent runs it. See [Sandboxes](#sandboxes). |
| `pre try [name]` | Lists the sample apps, or downloads one into `./<name>/`: its SQLite database, a README, a copy of this folder's key, and a `CLAUDE.md` and the skill so Claude Code started there knows what to do. |
| `pre init --api-key <key> [--api-url <url>]` | Writes a key you already have to `.pre/config.json`. The key can also come from `PRE_API_KEY`. |
| `pre logout` | Revokes the key on the API and removes it from `.pre/config.json`. If the API does not answer, it still removes the key and names its id for an admin to revoke. |
| `pre version` | Prints the version, as `pre --version` does. |

### Projects: from a file, by hand, from documents

| Command | What it does |
| --- | --- |
| `pre project create <name> [--description <text>] [--no-use]` | Starts a project on the API: one piece of work, with its own variables, datasets and models. A name is unique in the workspace, whatever the case. Unless `--no-use` is given, this folder then works on it: its id goes into `.pre/config.json`. |
| `pre project list [--archived]` | Lists the workspace's projects, newest first, and marks the one this folder uses. |
| `pre project show [project]` | Reads a project from the API: its variables, its datasets and a line per model. `[project]` is a name or an id; without it, the project in use. |
| `pre project use <project>` | Makes a project the one this folder works on. |
| `pre project set [project] [--name <name>] [--description <text>]` | Changes the name or the description. |
| `pre project delete [project]` | Archives the project: it leaves the list and takes no change. Nothing is deleted. |
| `pre project restore <project>` | Brings an archived project back. |
| `pre project purge <project> [--yes]` | Deletes an archived project for good. It asks first and refuses inside a coding agent. |
| `pre dataset upload <path> [--name <name>] [--description <text>]` | Uploads a table into the project in use: a `.csv`, `.tsv`, `.xlsx` or `.parquet` file of at most 200 MB. The dataset takes the file's name, or `--name`, given without the extension. The file is sent as it is: no column is dropped, hashed or retyped. A `.csv` or `.tsv` travels gzipped and is stored unpacked. The API reads it once and answers with its rows and columns. A file whose bytes are not what its extension says is refused when it cannot be read as a table, and stored with a `Warning:` line (`warnings` in JSON) when it can. |
| `pre dataset list` | Lists the project's datasets, in the order they were added: name, id, rows, columns, upload time. `--json` holds each whole record, the description too. |
| `pre dataset profile <dataset> [--column <name>]... [--as-uploaded]` | Shows what a dataset holds, column by column: its missing and distinct values, the most frequent ones, and for a number its range and deciles. `--as-uploaded` profiles the file as it arrived, before the dictionary is applied. |
| `pre dataset split <dataset> [--test 0.2] [--stratify <column>] [--seed 42]` | Splits a dataset at random into a train part and a test part, two new datasets named `<name>_train` and `<name>_test`. `--stratify` keeps a column's shares in both parts. |
| `pre dataset segment <dataset> --by <column> (--bands N \| --values) [--missing own\|spread] [--preview]` | Cuts a dataset on one column into new datasets: equal-count bands of a number, 2 to 20, or one dataset per value. `--preview` says what it would make and writes nothing. |
| `pre dataset rank <dataset> --target <variable> [--inputs a,b] [--folds N] [--again] [--timeout <s>]` | Ranks a dataset's candidate inputs by their signal for a yes/no target, in a job it waits for. The ranking is kept per dataset and target and read back, until `--again` computes it anew. |
| `pre dataset download <dataset> [--out <path>] [--format stored\|csv] [--overwrite]` | Writes a dataset to a file on this machine: as the API stores it, or its rows as CSV. A file already there is kept, and the command refused, unless `--overwrite` is given. |
| `pre dataset set <dataset> [--name <name>] [--description <text>]` | Renames a dataset or changes its description. `<dataset>` is its name, with or without the extension, or its id. `--name` is the new name without the extension: `--name "defaults 2026"` turns `loans.csv` into `defaults 2026.csv`. |
| `pre dataset delete <dataset> [--yes]` | Deletes a dataset and its file on the API, for good. It asks first and refuses inside a coding agent. The local file is not touched. |
| `pre variable list` | Lists the project's data dictionary: name, domain, dtype, role, mapping, values and description. The table shortens the values and the description; `--json` holds them whole. |
| `pre variable infer <dataset> [--apply] [--on-conflict abort\|override\|keep] [--out <file>] [--conflicts <file>]` | Infers the dictionary from a dataset of the project (its first 10,000 rows) and shows what it adds and changes. Only `--apply` saves it. `--out` writes the resulting dictionary to a `.csv` or `.json` file. |
| `pre variable import <file> [--on-conflict abort\|override\|keep] [--replace] [--conflicts <file>]` | Sends a dictionary file (`.csv`, `.tsv`, `.xlsx` or `.json`) as it is; the API reads and merges it. `--replace` makes it the whole dictionary. |
| `pre variable export <file>` | Writes the dictionary to a `.json` file (every field, exactly) or a `.csv` file (for people). `pre variable import` reads either back. |
| `pre variable set '<json>'` | Changes or adds variables given as JSON: one object such as `'{"name": "income", "dtype": "float"}'`, a list of them, or a file holding them. A field left out keeps its value; values given are added to the variable's, and `null` clears them. A new variable needs its role and its domain or dtype. |
| `pre variable delete <name>...` | Deletes variables, named one by one, as a JSON list such as `'["zip", "region"]'`, or in a `.json` file. An unknown name deletes nothing. |
| `pre model create <name> [--type classifier\|outlier_detector\|frequency] [--target <variable>] [--description <text>]` | Makes an empty model in the project. A classifier needs a target, a variable of the dictionary. |
| `pre model list [--archived]` | Lists the project's models: name, id, type, target, rules. `--archived` adds the deleted ones. |
| `pre model show <model> [--dataset <dataset>] [--points \| --weights] [--timeout <s>]` | Shows a model: its type, target and description, its rules with their weights and anchors, every setting they were mined with, the settings its next calibration takes and what reading the dataset changed. `<model>` is its name or id. `--dataset` adds each rule's statistics on that dataset, read when the API keeps them, else measured first by a job it waits for. `--points` shows each rule's points where its weight stands; the default is the model's language. |
| `pre model inputs <model> [--timeout <s>]` | Shows each input as the model's engine holds it: the ranges a number is cut into, the groups of a category's values, and what a missing value becomes. |
| `pre model points <model> [--timeout <s>]` | Shows the model's points: the scale, which way it runs, whether rule points add up, each rule's points, and the operating point in points. |
| `pre model set <model> [--name] [--description] [--type] [--target <variable> \| --no-target] [--language weights\|points] [--pdo] [--p0] [--q0] [--more-points more-likely\|less-likely] [--default-scale] [--threshold <score> \| --threshold-points <points>] [--connotation negative\|positive]` | Renames or describes a model at any time; changes its type or target while it has no rules. The language, the points scale, the operating point and the connotation are how a model is read and judged: they change at any time, for a model with a target, and move no weight and no score. A case is flagged when its score is at or above the operating point, 0.5 until set. The connotation says who is approved: the cases not flagged (`negative`, the default) or the flagged (`positive`). |
| `pre model settings <model> (--dataset <dataset> \| --calibration) [--out <file>]` | Prints every mining setting at its default, the inputs filled from the dictionary's roles; with `--calibration`, the settings the model's next calibration takes. `--out` writes them to a `.json` file to edit. |
| `pre model mine <model> --dataset <dataset> ['<json>' \| <file>] [--target <variable>] [--wait] [--timeout <s>]` | Mines the model's rules from a dataset, replacing its rules. Only the settings that differ are given. It prints the job; `--wait` follows it and prints the rule count, the fit's AUC and what reading the dataset changed. |
| `pre model calibrate <model> --dataset <dataset> ['<json>' \| <file>] [--wait] [--timeout <s>]` | Fits the weights of the model's rules to a dataset again, keeping the rules and their anchors. Only the settings that change are given; the model keeps those the run used. It prints the job; `--wait` follows it and prints each rule's weight before and after, the rows fitted on, the settings used and the warnings. |
| `pre model performance <model> --dataset <dataset> [--threshold <score> \| --threshold-points <points>] [--again \| --kept] [--time-budget <s>] [--timeout <s>]` | Prints how well a model predicts on a dataset: the quality of its scores, observed and expected, the counts and the metrics at the operating point, the calibration bands and a table of other cut-offs. It reads the report the API keeps; none kept, or a stale one, is measured first by a job it waits for. `--threshold` reads another cut-off from the kept rows, with no new scoring; `--again` measures anew; `--kept` prints what is kept, stale or not. |
| `pre model score <model> (--case '<json>' \| --dataset <dataset> [--row N] [--save-as <name>]) [--points \| --weights] [--timeout <s>]` | Scores one case, given as JSON values or as a row of a dataset: its score, whether it is flagged at the operating point, its points, the rules that moved the score and what the model read of the inputs left out. A value that does not fit its variable is read as missing and named. `--dataset` with no `--row` scores every row and prints a summary; `--save-as` keeps the scores as a new dataset with the columns `_score`, `_points` and `_flagged`. It waits for a job. |
| `pre model delete <model>` / `pre model restore <model>` | Archives a model, which can be restored; brings an archived one back. |
| `pre model purge <model> [--yes]` | Removes an archived model for good. It asks first and refuses inside a coding agent. |
| `pre model brief <model>` | Shows what a case must state to be scored by a model, each variable with its definition, and a record to fill. Read before a document is read into a case. |
| `pre model missing <model> [--set '<json>'] [--wait]` | Shows how the model reads a missing value of each input, or sets it: "unknown" (summed over the values the input could take), a missing bin, or a fill. |
| `pre model build-from-frequencies <model> ['<json>' \| <file>] [--wait]` | Builds a frequency model's weights from its stated frequencies, through synthetic rows, and prints each rule's frequency beside the rate the build reached. |
| `pre model report <model> --dataset <dataset> [--format html\|md] [--out <path>] [--overwrite] [--threshold <score> \| --threshold-points <points>] [--metrics general,lending,fraud] [--again]` | Writes the report, in `reports/` by default: how well the model predicts on a dataset, at its operating point, with each rule as PRE writes it and its statistics there. |
| `pre rule add <model> ('<json>' \| '<text>' [--frequency \| --weight \| --points] [--anchor] [--name])` | Adds rules written by hand: one rule from its text and its number, or a JSON list of them, added whole or not at all. |
| `pre rule set <model> <rule_id> [--rule <text>] [--name] [--frequency \| --weight \| --points] [--anchor \| --anchor-points]` | Changes one rule. What is left out stays, and the rule keeps its id. The answer says what the change made stale. |
| `pre rule delete <model> <rule_id>` | Deletes one rule. The other rules keep their ids. |
| `pre job list [--active] [--project <project>]` | Lists a project's background jobs, newest first. A job is long work the API does, such as mining rules; the command that needs one starts it. |
| `pre job show <job_id> [--wait] [--timeout S]` | Reads a job: its status, progress, result or error. With `--wait` it follows the job until it ends, for at most 100 seconds by default. |
| `pre job stop <job_id>` | Asks a job to stop. A queued job ends at once, a running one at its next checkpoint. |

### From an app's database

| Command | What it does |
| --- | --- |
| `pre connect <db>` | Describes a SQLite or Postgres database: tables, row counts, columns, types, null share, sample values and foreign keys. It opens the database read-only. |
| `pre outcome define --name <slug> --sql <query> [--case account --cases accounts --event churn --event-past churned]` | Runs the outcome query and stores it. The query returns one row per case: the case id, then a 0/1 label. It refuses no rows, a label that is not 0 or 1, a repeated case id and a label that is always the same. The words go into every sentence the CLI prints. It guesses each word you leave out from the column names and says so. |
| `pre outcome show` | Lists the stored outcomes and their queries. |
| `pre extract --outcome <slug> --features <query> [--as <name>]` | Runs the features query (the case id, then the features), joins it to the label and writes `.pre/data/<slug>.csv`. With `--as <name>` it writes cases to score instead: the features alone, no label, in `.pre/data/<name>.csv`. Nothing is sent. |
| `pre extract --outcome <slug> [--as <name>] --upload [--refresh]` | Sends the CSV the dry run wrote, unchanged, into the project in use as a dataset named `<slug>` or `<name>`. Its description says what a row is and that the ids are hashed. With `--refresh`, or with no CSV yet, it runs the queries again first. |
| `pre extract --unhash <file.csv>` | Puts the case ids back on a scored file downloaded with `pre dataset download --format csv`, from the ids maps in `.pre/data/`. It writes `<file>.unhashed.csv` and sends nothing. |
| `pre train`, `pre rules`, `pre predict`, `pre threshold`, `pre report` | Retired: a model from an app's database is built in a project now. Each answers with the commands that replace it, and `pre guide database` gives the path. |

### Account

| Command | What it does |
| --- | --- |
| `pre keys list` | Lists the workspace's live keys. The key in use here is marked. |
| `pre keys create <name> [--to-file <path>]` | Makes a key for a job or an app, not tied to this machine. It is shown once. Inside a coding agent it is written only to a file, never to the screen. |
| `pre keys revoke <id>` | Revokes one key. It stops working at once, everywhere. |
| `pre usage [--days 30]` | The workspace's use per day: rows scored and calls. |
| `pre delete-data [--yes]` | Deletes every dataset and model in the workspace, on the API. It asks first and refuses inside a coding agent. Keys, outcomes and local files stay. See the docs page "Your data". |
| `pre delete-account` | Prints the page that deletes the account and everything in it, after a code sent by email. No key needed. |

**Each of these commands describes itself in its `--help`**, as a tool does for the copilot's assistant: what it
does, when to use it, every format it takes with the allowed values, and calls that work (`pre_cli/manual.py`;
the commands of the project part). The formats are blocks of text in `pre_cli/formats.json`, which
the API's code generates from the vocabulary it enforces (`python -m pre_api.projects.manual` in
`services/pre-api`); never edit the file by hand. `tests/test_manual.py` holds each description to its parts, to
78 columns and to a size, and every call a description shows is run by a test.

**JSON is read exactly, a table with tolerance.** In `pre variable set` and a `.json` import, a value must be the
dictionary's own word (`int`, `output`); anything else refuses the whole request with the allowed values. A
table's cell may use other words (`integer`, `target`), and a word that is not read is left out and named.

**Conflicts.** A change that would alter a field a variable already has (its domain, dtype, role, description
or mapping) is a conflict. `--on-conflict` decides: `abort`, the default, saves nothing, prints the
conflicts and exits with 1; `override` takes the new value; `keep` the current one. `--conflicts <file>` writes the
conflicting variables, as the source makes them, to a JSON file. One way through: import with `--on-conflict keep
--conflicts c.json`, which saves all but the conflicts; edit `c.json` to the values wanted; import it with
`--on-conflict override`.

`PRE_API_KEY` and `PRE_API_URL` win over `.pre/config.json` for every call, so a job on a server needs no config. An API URL other than the default prints a warning that the key goes there, and an `http://` URL is refused unless it is localhost. `pre logout` still revokes only the folder's own key.

`<db>` is a SQLite file path, `sqlite:///path`, or `postgresql://user:password@host:5432/db`. Use `--schema` for
a Postgres schema other than `public`.

A `<query>` is the SQL itself or a path that ends in `.sql`. It must be one SELECT or WITH statement. The CLI
opens SQLite with `mode=ro` and runs Postgres in a read-only transaction, so a query cannot change data. For
Postgres, a database user with read access only is safer still.

## What leaves the machine

The CSV that `pre extract --upload` sends. Before it writes the CSV, `pre extract`:

1. Drops a column when every word of its name is an identifier word and one of them is a core word. Core words
   are `email`, `phone`, `mobile`, `ip`, `address`, `street`, `ssn`, `name` and `username`. The other identifier
   words are `mail`, `number`, `first`, `last`, `full`, `user`, `contact`, `home` and `work`. So `work_email` and
   `first_name` go, and `plan_name` and `address_verified` stay.
2. Drops a column when a text value holds an email address or looks like a phone number.
3. Replaces the case id with an HMAC of it in a column named `id`. The key is in `.pre/secret` (mode 600).
   `.pre/data/<slug>.ids.csv` maps each hash back to the case id. It stays on this machine.

The output names each dropped column and the reason.

## Sandboxes

`pre setup` writes the smallest change it can. It merges into the file, so a second run changes nothing.

It writes `.claude/settings.local.json`, key `sandbox.network.allowedDomains`. That is Claude Code's personal
settings file; the team's `.claude/settings.json` stays as it is. Do not commit it. For a Postgres on this machine, `--local`
also sets `sandbox.network.allowLocalBinding`, which opens every local port. It never sets `allowAllUnixSockets`.
Claude Code is the only agent at launch; others are on the roadmap. It also writes the onboard skill to
`.claude/skills/pre-onboard/SKILL.md`. It records the copy's SHA-256 in `.pre/config.json`, and later replaces only
that copy: a skill you edited stays as it is. Commit the skill to share it with the team. Its source is
`tools/agent-plugin`.

These key names come from secondary sources. They live in `pre_cli/sandbox.py`.

## Local config

`.pre/config.json` holds the API URL, the key and its id, the database URL, the outcome queries and the dataset
and model ids that later commands create. It also holds `project_id`, the project this folder works on; what the
project contains is read from the API each time, never kept here. While a `pre login --no-wait` waits, it also holds that sign-in. The API
can also list every dataset and model in the workspace. Each command that writes the config also writes
`.pre/.gitignore`, so git ignores the folder. Set `PRE_DIR` to use another folder.

## Tests

`scripts/check pre-cli` runs ruff and pytest. The `pre status` tests start a Prism mock of
`services/pre-api/openapi.yaml` with `npx`. They skip when `npx` is missing.

`tests/test_package.py` builds the sdist, a wheel from that sdist and a wheel from this folder. It fails if one
holds a file outside `pre_cli` and the three bundled packages, a `services`, `apps` or `ground_truth` path, a
`seed.py` or `check.py`, or the name of the PRE library. PRE must never reach PyPI.

## Release

The CLI is on PyPI as `stratyfy-cli`. The command it installs is `pre`. `.github/workflows/release-cli.yml`
publishes it with trusted publishing, so no PyPI token is stored.

1. Set the new `version` in `pyproject.toml`. It is the only place that holds the version.
2. Merge that change to `master`. CI runs `scripts/check pre-cli`, which builds the package and checks its files.
3. Tag the merge commit and push the tag: `git tag stratyfy-cli-v<version>`, then
   `git push origin stratyfy-cli-v<version>`.
4. The workflow checks that the tag matches the version, builds, installs the wheel and runs `pre --version`. Then
   it publishes in the GitHub environment `pypi`.

Users install it with Python 3.12 or later: `pipx install stratyfy-cli`.
