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

# ttr research

> Generate synthetic Research data with known ground truth, ingest any file tree, and bench allowlisted models locally. Nothing is dropped, and no Cloudflare resource is written.

`ttr research` runs the framework-free Research CLI from a trusted platform
checkout (`packages/research-ingest/src/cli/main.ts`). The checkout comes only
from `TTR_RESEARCH_ROOT` (an absolute path) or from a link recorded once with
`ttr research link <checkout>`. Without either, the command exits with code 2.
It never searches the current directory, because a dataset under ingest can
plant a checkout look-alike, a `bunfig.toml` preload or a `.env`.

```sh theme={null}
ttr research link <checkout>
ttr research generate --scenario <pack> --size <n> [--seed <seed>] [--out <dir>] [--focus <facets>]
ttr research ingest <path> [--out <dir>] [--models <file>] [--target local|cloudflare]
ttr research bench run --data <dir> --split dev|held-out --config <file> [--models <list>] [--out <dir>]
ttr research export --from <report.json> [--out <dir>] [--format json|csv|both]
```

`link` checks that the path's `package.json` names the platform and that the
CLI entry is a regular file inside it. It then records the real path in
`research-checkout.json` (mode 0600) next to the `ttr` config file.

Link only your own checkout: a clone you created and control, never a shared,
downloaded or dataset-provided directory, because `ttr research` runs that
checkout's code. Each later run trusts the record only when it is a regular
file owned by you with mode 0600. Otherwise the command exits with code 2 and
names the problem. Fix the mode with `chmod 600`, or remove the record and link
your own checkout again.

Bun starts in the checkout root with `--no-env-file`, and the child gets only
basic process variables (`PATH`, `HOME`, locale, temp directories) and
`RESEARCH_*` settings. Relative path arguments (`<path>`, `--data`, `--config`,
`--from`, `--out`, `--models`, `RESEARCH_GENERATOR_DENYLIST_FILE`) still
resolve from where you run the command.

`up --profile` and `node add` belong to later Research lanes. Until then they
exit with code 2.

## Generate

`generate` builds a ground-truth graph first, then renders it into messy files.
The default pack is `compliance-finance`, a fictional regulated domain
(compliance and finance) with companies, officers, bank accounts, transfers,
rules, filed reports and flagged transactions.

| Output | Contents |
| - | - |
| `files/` | Text-layer PDFs, scanned PDFs and PNGs (rotated, skewed, speckled), EML and mbox with attachments, XLSX, CSV with `,` or `;`, DOCX, and ZIP archives. Some archives hold an unknown binary on purpose. Text mixes Vietnamese and English with varied number and date formats. |
| `manifest.json` | Generator version, seed, size, each file's split and SHA-256, and the held-out commitment. |
| `truth/tuning.json` | Train and dev cases, entities, facts, edges, and where each fact appears (file, page, verbatim evidence). |
| `truth/held-out.json` | Held-out cases only, for final evaluation. |

* `--size` is the number of top-level files. Each case renders up to five.
* Output is a pure function of generator version, pack, seed and size, and is
  byte-identical on every machine. A change that alters bytes for an existing
  seed must bump `generatorVersion` (a pinned test enforces this).
* Splits are assigned per case (14 train, 3 dev, 3 held-out in each block of
  20\), so a fact never spans splits. `selectSplits(..., 'tuning')` and
  `tuningView` refuse held-out data with `HeldOutAccessError`. Bench and tuning
  code reads only `truth/tuning.json`.
* Names are synthesized from syllables. To keep generated names away from real
  parties, set `RESEARCH_GENERATOR_DENYLIST_FILE` to a private file of tokens
  (one per line, kept outside the repository). The generator re-rolls any name
  that contains one.
* The command refuses a non-empty output directory.
* `--focus` keeps only files that match every listed facet, for targeted
  examples of one weak spot: `format=<f>` (`pdf-text`, `docx`, `xlsx`, `csv`,
  `pdf-scan`, `png-scan`, `mbox`, `eml`, `zip`), `language=en|vi`,
  `channel=text-layer|table|email-body|ocr`, `fact=<kind>` and `noise=<tag>`
  (`noise=rotated` also matches `rotated-90`). Repeat a facet for
  alternatives: `--focus format=png-scan,format=pdf-scan,noise=rotated`. A
  focused run renders up to 25 cases per requested file and fails if too few
  match. Without `--focus`, output is unchanged.

## Ingest

`ingest` reads a file or directory into in-memory Research stores with an
immutable local blob store under `<out>/blobs`. It writes `<out>/report.json`
(a per-file tree with status, detected format, pages, warnings and children)
and `<out>/documents.json`. When the input directory has a generator
`manifest.json`, each document keeps its split.

Formats are detected from content, not the extension:

| Format | Reader |
| - | - |
| PDF | Text layer per line with page-relative boxes. Pages without a text layer are scans: the largest image goes to OCR. |
| Images | OCR, including handwriting, through the allowlisted OCR model. |
| Email | EML and mbox (mboxrd unquoting) through `postal-mime`; Outlook MSG from its compound file. Attachments and forwarded messages become child files. |
| Office | DOCX, XLSX, PPTX and OpenDocument from bounded zip extraction; DOC, XLS (BIFF8) and PPT from their compound streams. Embedded images become children. A damaged legacy file keeps lossy text and is marked `partial`. |
| CSV/TSV | RFC 4180 rows with a detected delimiter, one segment per row. |
| Audio | Transcript segments with timestamps through the allowlisted transcription model. |
| Archives | ZIP, TAR and GZIP recurse; 7z and RAR are kept and flagged. |

Every file is hashed and stored, including unknown and unreadable ones, which
get `unknown-type` or `unreadable` flags. Only limits stop storage, and the
report lists each refusal (`limit:<name>`). The exit code is 3 when a top-level
file was refused.

| Limit | Default |
| - | - |
| File size | 64 MiB |
| Run total | 512 MiB and 10,000 files, members included |
| Nesting depth (archives, attachments) | 4 |
| Archive entries | 2,000 |
| Decompressed entry | 64 MiB, and at most 200 times its compressed size |
| Pages per document | 500 |
| OCR pages per document | 24 |
| Model calls per run | 500, at most 2 attempts each |

Archive members are extracted in memory. Their names never become paths.
Absolute, drive-relative and `..` names are kept as `_unsafe/<name>` with the
original in the report. Links inside TAR files are recorded and never followed.
No reader shells out or evaluates file content.

### Models

Without `--models`, scans and audio are stored and marked `needs-model`. To read
them, pass a models file. It names every serving host, and secrets come from
environment variables named in the file:

```json theme={null}
{
  "boundary": "our-machines",
  "endpoints": [
    {
      "host": { "id": "lab-gpu-1", "displayName": "Tuturuuu GPU node lab-gpu-1", "kind": "our-gpu-node" },
      "baseUrl": "http://127.0.0.1:8000/v1",
      "headersFromEnv": { "authorization": "RESEARCH_GPU_AUTHORIZATION" },
      "models": [
        { "id": "qwen2.5-vl-7b-instruct", "purpose": "ocr" },
        { "id": "whisper-large-v3", "purpose": "transcribe" }
      ]
    }
  ],
  "ocr": { "modelId": "qwen2.5-vl-7b-instruct", "hostId": "lab-gpu-1" },
  "transcribe": { "modelId": "whisper-large-v3", "hostId": "lab-gpu-1" }
}
```

`headersFromEnv` may set only `authorization`, `x-api-key`, `api-key` or
`cf-aig-authorization`, and each value must come from a `RESEARCH_*`
variable. Other credentials in the environment, such as forge or cloud tokens,
are never sent.

The models file must be an operator file. A `--models` path inside the ingest
`<path>` or the output (`--out`) directory, by name or through a symlink, is
refused, so ingested or generated content can never choose hosts or header
variables. When `<path>` is a single file, its directory (as given and through
the file's real path) counts as the ingest input, so a models file beside it is
refused too.

`--project` is one plain name (letters, digits, `.`, `_`, `-`, starting with a
letter or digit), used as a directory under the output. `..`, `.`, absolute
paths and separators are refused before anything is read or written.

Ingest never reads generated dataset metadata: each dataset's `manifest.json`
and `truth/` files are skipped at any depth, so ingesting a parent of datasets
cannot read held-out truth, and a `truth/held-out.json` input is refused.
Nested skips appear in the report's `skipped` list.

Endpoints speak the OpenAI-compatible API (`/chat/completions` with an image
for OCR, `/audio/transcriptions` for audio): vLLM or llama.cpp on a GPU node,
or an AI Gateway HTTPS route. Plain `http:` is accepted only for loopback
(`127.0.0.0/8`, `::1`, `localhost`). A base URL with credentials, a query or a
fragment is refused, including a bare `?` or `#`.
Redirects are refused and responses are capped at 1 MiB. Each model call
checks the project allowlist for that model on that host, then the run budget,
then the stop fence.

To stop model calls mid-run, create `<out>/STOP`. The next call sees a closed
fence. Remaining pages stay `needs-model`, and every file is still stored.

### Cloudflare target

`--target cloudflare` prints the bindings a hosted run would use and exits
without reading files. `ttr research` never creates or writes Cloudflare
resources. Hosted ingest belongs to the Research pipeline Worker.

## Bench

`bench run` scores allowlisted extraction models on one split of a generated
dataset, entirely in local in-memory adapters. It reads the split's files
through the ingest readers, sends each document's prepared pages to every
selected model, and compares the extracted facts, entities and links with the
ground truth.

* `--split dev` reads only dev files and `truth/tuning.json`. `--split
  held-out` reads only held-out files and `truth/held-out.json`. A dev run
  never opens held-out data, and a held-out run prints no tuning actions.
* `--data` must be one dataset directory holding `manifest.json` and `truth/`;
  a parent of datasets is refused before any truth file is opened. Manifest
  entries must be member files under `files/`. The manifest, the truth file
  and each member are read only as regular files whose real path stays inside
  the dataset, so symlinks cannot pull in files from elsewhere.
* `--config` is required and is the run's allowlist. Nothing is allowed by
  default. Each endpoint names its serving host with its real kind, and each
  remote model states its openness. Closed models are listed but never benched.
  It must be an operator file: a `--config` path inside the dataset (`--data`)
  or output (`--out`) directory, by name or through a symlink, is refused, so
  dataset content can never choose hosts or header variables.
* `--models` picks a subset by `<model>` or `<model>@<host>`. The default is
  every open model in the config.
* Every call is admitted against the allowlist and pinned host, a run-wide call
  budget (`--max-calls`, default 5,000, ceiling 25,000), a document budget
  (`--max-documents`, default 2,000), two attempts per document, the core
  per-document page and text caps, and the stop fence. Create `<out>/STOP` to
  halt before the next call. A stopped run exits with code 3 and keeps what it
  scored.
* Scans and recordings need a reading model that the bench does not configure.
  They count as missed, and "Where it struggles" points at the ingest models
  config.

```json theme={null}
{
  "boundary": "our-machines",
  "endpoints": [
    {
      "host": { "id": "this-machine", "displayName": "This machine", "kind": "our-gpu-node" },
      "baseline": true
    },
    {
      "host": { "id": "lab-gpu-1", "displayName": "Our GPU node lab-gpu-1", "kind": "our-gpu-node" },
      "baseUrl": "http://127.0.0.1:8000/v1",
      "headersFromEnv": { "authorization": "RESEARCH_LAB_GPU_TOKEN" },
      "models": [{ "id": "qwen3-32b", "openness": "open" }]
    }
  ]
}
```

* `baseline: true` runs `lumen-lexical-baseline`, a deterministic rule-based
  extractor in this process. It needs no weights or network and never sees the
  truth, so it is the floor every model must beat. It cannot use a gateway host.
* A remote endpoint is OpenAI-compatible (`/chat/completions` with a JSON
  schema), `https:`, or `http:` on loopback only. `headersFromEnv` follows the
  ingest models config: `authorization`, `x-api-key`, `api-key` or
  `cf-aig-authorization`, each from a `RESEARCH_*` variable.
* Host kind must match the boundary: `our-machines` uses `our-gpu-node`,
  `client-machines` uses `client-machines`, and `cloudflare-test` uses
  `gateway-routed-third-party`.

The command prints each model's score, the three plain stats, recall, entity
and link F1, files per hour, call count and cost. For a dev run it also prints
"Where it struggles", each with a runnable `ttr research generate … --focus …`
command. It writes `<out>/report.json` (owner-only). See
[Research architecture](https://docs.tuturuuu.com/build/devops/research-architecture.md#bench-and-quality)
for metric definitions and the score formula.

## Export

`export --from <report.json>` writes `results.json` (the full report and a
headline per model), `results.csv` (one row per model) and `facts.csv` (one row
per scored fact or unsupported prediction). CSV cells go through
`@tuturuuu/utils/csv-safe`, so a formula-like host or model name is escaped.
`--format json|csv` writes one kind only.

## Library use

The CLI wraps `@tuturuuu/research-ingest`, `@tuturuuu/research-generator` and
`@tuturuuu/research-bench`. The portable entrypoints import no Node, Next.js, React or Cloudflare runtime
modules. Local filesystem adapters live at `@tuturuuu/research-ingest/node`.
See [Research architecture](https://docs.tuturuuu.com/build/devops/research-architecture.md#ingestion) for
how ingest output feeds the pipeline.


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