## Lean Research Backend

FastAPI service for checking generated Lean conjectures and, optionally, running the backend-owned research loop.

### What it does

- accepts generated Lean code
- strips markdown fences if present
- compiles it with Lean
- classifies failures as `verified`, `typecheck_error`, `timeout`, `missing_imports`, `malformed_output`, `unsafe_placeholder`, `checker_unavailable`, or `no_code`
- returns `is_true: true` when Lean accepts the file
- rejects placeholders such as `sorry`, `admit`, and `axiom` before invoking Lean
- stores verified lemmas in the Supabase `verified_lemmas` table
- can own a background research worker that watches Supabase, verifies provider outputs, and enqueues repairs

### Install

```bash
python3 -m venv .venv
source .venv/bin/activate
pip install -r backend/requirements.txt
```

### Environment

```bash
export LEAN_PROJECT_DIR="/absolute/path/to/lean/project"
export SUPABASE_URL="https://YOUR_PROJECT.supabase.co"
export SUPABASE_SERVICE_ROLE_KEY="YOUR_SERVICE_ROLE_KEY"
export RESEARCH_BACKEND_ENABLED=1
```

The backend-owned worker calls privileged orchestration RPCs, so production deployments should use the Supabase service-role key. `SUPABASE_KEY` is still accepted as a fallback for older local setups, but it is not the recommended production configuration.

If `LEAN_PROJECT_DIR` is set, the checker uses `lake env lean`. Otherwise it uses plain `lean`.

### Run

```bash
uvicorn backend.main:app --reload
```

If `RESEARCH_BACKEND_ENABLED=1`, the backend starts an internal worker on FastAPI startup that:
- polls active `research_jobs`
- creates `research_episodes`
- verifies generated provider outputs
- enqueues proof-repair prompts when Lean rejects an attempt

For curl examples below, set a base URL first. It defaults to the deployed Azure app, but you can point it at local dev if needed:

```bash
export BACKEND_URL="${BACKEND_URL:-https://capacitor-backend-egfucye9gjdcdram.canadacentral-01.azurewebsites.net}"
```

### Request

```bash
curl -X POST "$BACKEND_URL/check-conjecture" \
  -H "Content-Type: application/json" \
  -d '{
    "conjecture": "theorem trivial_truth : True := by\n  trivial",
    "source_task_id": "example-task"
  }'
```

Successful responses now include:
- `verification_status`
- `verification_summary`
- `normalized_code`
- `document_id` for the inserted `verified_lemmas` row
- `compiler`
- `stdout` / `stderr`

### Submit a research job

```bash
curl -X POST "$BACKEND_URL/research-jobs" \
  -H "Content-Type: application/json" \
  -d '{
    "requester_node_id": "YOUR_NODE_ID",
    "requester_secret_hash": "YOUR_SHA256_SECRET_HASH",
    "domain": "naturals",
    "model": "TheBloke/llemma_7b-GGUF",
    "total_budget": 2.0,
    "budget_per_attempt": 0.5
  }'
```
