npm package: @mantra.ai/cli
Description: Hypothesis generator hooked to Claude Code
Latest version: 0.2.1

# mantra

Autonomous hypothesis generator powered by LLM agent swarms. Give it any combination of seed papers, tabular data, and a research question, then run `mantra go` to launch a swarm of agents that discover related work, map the research landscape, and generate novel hypotheses across multiple iterative rounds. Supports Claude, Codex, and Pi as AI backends.

## Install

```bash
npm i -g @mantra.ai/cli
```

Requires [Bun](https://bun.sh) runtime.

## Quick start

```bash
mantra init "my-project"
mantra add 10.1038/s41586-024-07386-0
mantra discover "CRISPR base editing efficiency"
mantra go -r "crispr-efficiency"
```

That's it. `mantra go` handles the full pipeline: it prepares your papers, maps the research landscape, generates hypotheses, then spawns scientist agents that pursue each hypothesis through new rounds of discovery and refinement.

Monitor progress with:

```bash
mantra status              # see running agent sessions
mantra dashboard           # open the web dashboard
mantra watch               # start the health watchdog
tmux attach -t <session>   # watch a specific agent
```

## How `mantra go` works

```
                          ┌─────────────────────────────┐
                          │           INPUTS            │
                          │                             │
                          │  papers + data + question   │
                          │     (any combination)       │
                          └──────────────┬──────────────┘
                                         │
                          ┌─────────────────────────────┐
                          │         SEED PHASE          │
                          │                             │
                          │   generate investigation    │
                          │   brief, discover starter   │
                          │      papers if needed       │
                          └──────────────┬──────────────┘
                                         │
                          ┌─────────────────────────────┐
                          │        COORDINATOR          │
                          │                             │
                          │    reads brief, spawns      │
                          │     scientists, waits,      │
                          │    consolidates results     │
                          └──────────────┬──────────────┘
                                         │
                            
                             one agent per focus area
                             or hypothesis to expand

                                         │
          ┌──────────────────────────────┼──────────────────────────────┐
          │                              │                              │
 ┌──────────────────────┐     ┌──────────────────────┐     ┌──────────────────────┐
 │    SCIENTIST #1      │     │    SCIENTIST #2      │     │    SCIENTIST #N      │
 │                      │     │                      │     │                      │
 │  mantra discover     │     │  mantra discover     │     │  mantra discover     │
 │  mantra prep         │     │  mantra prep         │     │  mantra prep         │
 │  mantra map          │     │  mantra map          │     │  mantra map          │
 │  mantra hypothesize  │     │  mantra hypothesize  │     │  mantra hypothesize  │
 └──────────┬───────────┘     └──────────┬───────────┘     └──────────┬───────────┘
            │                            │                            │
            └────────────────────────────┼────────────────────────────┘
                                         │
                               
                                merge all findings

                                         │
                          ┌─────────────────────────────┐
                          │        CONSOLIDATE          │
                          │                             │
                          │  mantra reconcile           │
                          │  mantra prep                │
                          │  mantra map                 │
                          │  mantra hypothesize --prior │
                          │  mantra prune               │
                          └──────────────┬──────────────┘
                                         │
                                         ▼
                               ┌──────────────────┐
                               │      assess      │
                               └────┬────────┬────┘
                                    │        │
                        hypotheses have    hypotheses are
                         weak evidence     experiment-ready
                         or open gaps      or max rounds hit
                                    │        │
                                    ▼        ▼
                               round N+1    done
                                   
```

The seed phase generates an investigation brief from your inputs, which guides the coordinator's strategy. If you only provided data or a question without papers, the brief triggers automatic literature discovery to bootstrap the library.

Scientists run in isolated Docker containers by default. The coordinator spawns them, polls for completion, reconciles their papers into the global library, then consolidates. A watchdog starts automatically alongside the coordinator to monitor agent health.

All sessions run in tmux. You can attach, detach, and check on them at any time.

```bash
mantra go -r "my-run" --max-rounds 6 --max-threads 3 --attach
```

### `go` options

| Flag | Description |
|------|-------------|
| `-r, --run <name>` | Investigation run name (required) |
| `-q, --question <text>` | Research question to focus the swarm |
| `--data <paths...>` | Dataset files or directories to register before launch |
| `-m, --model <model>` | Model for orchestration |
| `--runtime <runtime>` | AI runtime backend (claude, pi, codex) |
| `--profile <name>` | Named runtime/model profile |
| `--max-rounds <n>` | Maximum iteration rounds (default: 4) |
| `--max-threads <n>` | Max parallel scientist threads per round (default: 5) |
| `--attach` | Attach to the coordinator tmux session after spawning |
| `--dry-run` | Generate brief and show plan without launching |

## Running steps individually

You can also run each stage of the pipeline yourself:

```bash
mantra prep                # extract Methods, Results, Discussion from papers
mantra map                 # map the research landscape (connections, gaps)
mantra hypothesize         # generate hypotheses from the landscape map
mantra scientist <hypothesis>   # pursue a single hypothesis through a full cycle
```

## Commands

### Project and library

| Command | Description |
|---------|-------------|
| `init [name]` | Initialize a new project in the current directory |
| `papers` | List papers in the library or current project |
| `add [inputs...]` | Add papers by DOI, PDF path, search query, or file of DOIs |
| `show <id>` | Display detailed information about a paper |
| `search <query>` | Full-text search across papers |
| `remove <id>` | Remove a paper from the library or unlink from a project |
| `export` | Export papers as BibTeX, JSON, or CSV |
| `update [id]` | Re-resolve metadata from upstream sources |
| `library` | Show library statistics |
| `data <paths...>` | Register dataset files to a project |

### Discovery

| Command | Description |
|---------|-------------|
| `discover [inputs...]` | Find papers across all sources and add to current project |
| `scan` | Scan local PDF directories and Zotero library |
| `auth` | Set up institutional access via browser login |

### Hypothesis generation

| Command | Description |
|---------|-------------|
| `go` | Run the full iterative hypothesis swarm |
| `prep` | Extract structured sections from papers for analysis |
| `map` | Map the research landscape using Claude |
| `hypothesize` | Generate hypotheses from prepared papers and landscape map |
| `scientist <file>` | Pursue a single hypothesis through a full discovery cycle |
| `scientist --focus <text>` | Run brief-directed discovery without a hypothesis file |

The `scientist` command also accepts `--round <n>`, `--foreground` (run inline, no tmux), and `--container` (run in Docker).

### Run management

| Command | Description |
|---------|-------------|
| `status` | Show running agent sessions |
| `dashboard` | Open the web dashboard to monitor a running swarm |
| `stop [session]` | Kill running sessions and orphaned containers |
| `watch` | Start the health watchdog daemon |
| `chronicle` | Show run execution history |
| `resume` | Resume an interrupted coordinator or scientist from checkpoint |
| `reconcile` | Reconcile run state from events and messages |
| `run-state` | Query or update run state directly |
| `tokens` | Show token usage by agent |
| `msg` | Send or check inter-agent messages |
| `prune` | Remove papers not referenced by any hypothesis |

### Configuration

| Command | Description |
|---------|-------------|
| `config list` | Show all config keys with current values |
| `config list --resolved` | Show effective merged values with source attribution |
| `config get <key>` | Get a config value |
| `config get <key> --project` | Get a project-level override |
| `config set <key> <value>` | Set a user-level config value |
| `config set <key> <value> --project` | Set a project-level override in `mantra.json` |
| `config set-role` | Set runtime/model for a specific agent role |
| `config resolve` | Show fully merged runtime routing |
| `profile` | Manage named runtime/model profiles |
| `setup` | Run interactive setup wizard |

#### Project-level config overrides

Projects can override selected general settings via the `config` field in `mantra.json`:

```json
{
  "name": "my-project",
  "created": "2026-01-15T00:00:00.000Z",
  "config": {
    "defaultOutput": "json",
    "pdfDirs": ["./papers"],
    "disabledSources": ["institutional"]
  }
}
```

**Precedence:** schema defaults → user config (`~/.mantra/config.json`) → project config (`mantra.json`) → env vars.

Overrides use **shallow key replacement** -- if the project sets `pdfDirs`, it replaces the user's `pdfDirs` entirely (no merge).

Runtime routing config (`.mantra/config.json`) is separate and unaffected.

**Project-overridable keys:** `defaultOutput`, `pdfDirs`, `disabledSources`, `runtime`, `zoteroFetchEnabled`, `zoteroFetchTimeoutMs`, `institutionalFetchEnabled`, `institutionalFetchTimeoutMs`.

## Data sources

- **Crossref** for discovery and work metadata
- **OpenCitations** for citation graph expansion
- **Semantic Scholar** for paper metadata
- **arXiv** preprint search and metadata
- **bioRxiv / medRxiv** preprint search and metadata
- **Europe PMC** for open-access biomedical literature
- **PLOS** journal search
- **Local PDFs** with automatic DOI extraction
- **Zotero** library synchronization

## Agent roles

The swarm uses four agent roles. Each can be assigned a different model via runtime routing.

| Role | Purpose | Default model |
|------|---------|---------------|
| `coordinator` | Runs the iterative seed/expand/consolidate pipeline | opus |
| `scientist` | Pursues a single hypothesis through discover/prep/map/hypothesize | opus |
| `generator` | Proposes hypotheses from papers and landscape (in-process LLM) | opus |
| `contestor` | Critiques hypotheses for evidence, novelty, and testability (in-process LLM) | opus |

Configure routing with `mantra config set-role` or use named profiles with `mantra profile`.

## Containerized scientists

Scientists can run in isolated Docker containers instead of tmux sessions. This gives each scientist its own filesystem and `MANTRA_HOME`, so runs cannot interfere with each other or the host.

```bash
mantra scientist hypothesis.json --container
```

The container image is built automatically from `oven/bun:latest` with mantra and claude-code installed. It includes a health check, handles SIGTERM for graceful shutdown, and writes messages/events to files that the host ingests after the run. `mantra stop` cleans up orphaned containers.

## Run state and checkpointing

A run progresses through phases: `waiting` -> `seeding` -> `starting` -> `expansion` -> `consolidation` -> `done`. The current phase, round number, and hypothesis counts are tracked in SQLite and visible via `mantra run-state` or the dashboard.

Scientists checkpoint after each pipeline step (discover, prep, map, hypothesize). If a scientist is interrupted, `mantra resume` picks up from the last completed step instead of starting over.

Events (spawn, consolidate, assess, reconcile) are logged to the `run_events` table and shown by `mantra chronicle`.

## Inter-agent messaging

Agents communicate through a run-scoped messaging system stored in SQLite. The coordinator sends directives to scientists, and scientists report results back. Use `mantra msg` to inspect or send messages manually.

## Watchdog

`mantra watch` monitors all active agent sessions and intervenes when things go wrong.

**Health states:**

- `healthy` -- producing output normally
- `stale` -- quiet for 3+ minutes
- `idle` -- quiet for 5+ minutes, escalated to triage
- `zombie` -- tmux session exists but the process inside is dead

**Escalation:**

1. After 3 minutes of silence, the session is marked stale.
2. After 5 minutes, the watchdog calls Claude to triage the session. The verdict is one of: nudge (send a keystroke to unstick), extend (give more time), or terminate.
3. After 10 minutes with no recovery, the session is killed.

The watchdog uses WAL-reactive polling (watching SQLite write-ahead log changes) for fast response, with a 60-second fallback poll for tmux liveness.

## Web dashboard

`mantra dashboard` starts a local web server that shows the state of a running swarm in real time.

```bash
mantra dashboard              # auto-detects the active run
mantra dashboard -r my-run    # specify a run explicitly
```

The dashboard connects over WebSocket for live updates and falls back to polling. It has three views:

**Overview** -- run phase, round, hypothesis count, agent grid, hypothesis tracker, cost tracker, paper counter, and a chronicle summary.

**Timeline** -- chronological event log (spawns, consolidations, assessments, errors).

**Projects** -- browse all projects and their hypotheses across runs.

### API

The dashboard exposes a REST API:

| Endpoint | Returns |
|----------|---------|
| `GET /api/run-state` | Phase, round, hypothesis count |
| `GET /api/agents` | Agent status per session |
| `GET /api/events` | Event history |
| `GET /api/hypotheses` | Hypotheses per round |
| `GET /api/tokens` | Token usage summary |
| `GET /api/papers` | Paper count |
| `GET /api/chronicle` | Run execution summary |
| `GET /api/brief` | Seed brief details |
| `GET /api/projects` | All projects |
| `GET /api/project-hypotheses` | Run-specific hypotheses |
| `WS /ws` | Real-time state updates |

## Multi-runtime support

Mantra supports multiple AI backends. Each agent role can be routed to a different runtime and model.

Supported runtimes:
- **claude** -- Anthropic Claude (default)
- **pi** -- Anthropic internal runtime
- **codex** -- OpenAI Codex

Set the runtime per command with `--runtime` and `--model`, or configure defaults with `mantra config set-role` and `mantra profile`.

## Global options

```
--json              Output as JSON
--no-interactive    Suppress interactive prompts
```