# VeriThink User Guide

VeriThink helps you **plan and verify** implementation before writing code: edge cases, errors, tests, security, concurrency. The engine builds a cognitive graph, symbolically checks gaps, and returns a structured Markdown plan.

The primary interface is **MCP tools in Cursor**. Alternatively, use the HTTP API directly.

---

## Installation

### Option A: Store (recommended)

1. **Add to Cursor** — one-click deeplink from [README.en.md](../../README.en.md#add-to-cursor) or [DEEPLINK.md](../DEEPLINK.md) (RU).
2. Or add manually to `.cursor/mcp.json`:

```json
{
  "mcpServers": {
    "verithink": {
      "command": "npx",
      "args": ["-y", "verithink-mcp"],
      "env": {
        "VERITHINK_AUTOSTART": "1",
        "VERITHINK_LLM_PROVIDER": "openai"
      }
    }
  }
}
```

3. Restart MCP in Cursor. Backend starts automatically (`VERITHINK_AUTOSTART=1`).

> **Important:** Cursor **does not support MCP sampling**. `VERITHINK_LLM_PROVIDER=mcp-sampling` in deeplinks/examples **does not give a real LLM** (falls back to stub). For Cursor, set **your API key** (`openai` / `anthropic` / `gemini`), **`local`** (Ollama), or **`service`** via the [account cabinet](#account-cabinet-and-billing-modes) — see [BILLING.md](BILLING.md).

### Option B: Local from repository (clone, several Cursor windows)

Do **not** launch `node …/mcp/dist/server.js` as the Cursor MCP command — Cursor will glue windows onto one process.

```powershell
powershell -File scripts/setup-cursor.ps1 -RestoreGlobalMultiProject -Lane api
powershell -File scripts/ensure-api-lane.ps1
```

That writes **project** `.cursor/mcp.json` + `.cursor/vt-mcp-bridge.cmd`. There must be no `verithink` block in `~/.cursor/mcp.json`. Another folder on this PC: `-Target "<abs path>" -NoBuild -SkipHooks`.

Example (replace the path with your clone):

```json
{
  "mcpServers": {
    "verithink": {
      "command": "E:/Orlov Production2/aithink/.cursor/vt-mcp-bridge.cmd",
      "args": ["E:/Orlov Production2/aithink"],
      "cwd": "E:/Orlov Production2/aithink",
      "env": {
        "VERITHINK_SERVICE_URL": "http://127.0.0.1:8789",
        "VERITHINK_AUTOSTART": "0",
        "VERITHINK_MCP_ASYNC": "1",
        "VERITHINK_MCP_INLINE_BUDGET_MS": "25000"
      }
    }
  }
}
```

MCP build: [ADMIN.md — Build](../ADMIN.md#сборка). Standalone `node mcp/dist/server.js` **without Cursor** is still valid.

Replace `args` path with your clone. Build: see [ADMIN.md — Build](../ADMIN.md#сборка) (RU).

### If backend is already running

Cursor agent (API lane):

```json
"env": { "VERITHINK_SERVICE_URL": "http://127.0.0.1:8789" }
```

Dashboard / browser lane: `http://127.0.0.1:8787`.

Publishing and full testing: [ADMIN.md](../ADMIN.md) (RU).

---

## Using VeriThink in Cursor (MCP)

Ensure ReasonService is running (or MCP has `VERITHINK_AUTOSTART=1`). In Cursor chat the agent can call VeriThink tools by name.

### Tool table

| Tool | Purpose | When to call | Example prompt to agent |
|------|---------|--------------|-------------------------|
| `reason_plan` | Verified step-by-step plan before code | Any non-trivial feature, refactor, bugfix | “Plan rate limiting on POST /api/login” |
| `reason_check` | Quick gap/contradiction audit | Draft plan or spec, review without full synth | “Check this plan for gaps: …” |
| `reason_testplan` | Test matrix: cases, boundaries, negative, races | Before writing tests or after a feature | “Test plan for file upload module” |
| `reason_debug` | Root-cause analysis | Stack trace, reproducible error | “Debug NullReference in OrderService, stack: …” |
| `reason_refine` | Refine prior plan by `taskId` | Extend or change an existing plan | “Refine plan task-abc: add idempotency for retry” |
| `reason_why` | Step provenance | Unclear why a step exists | “Why is deploy-migration mandatory in the plan?” |
| `reason_review` | Plan/code audit with CRITIQUE | Code review, pre-merge | “Review this diff for security and edge cases” |
| `reason_pack` | Memory pack — brief context under token budget | Move context to another chat / trim history | “Build memory pack for rate limiting task” |
| `reason_verify` | Implementation vs plan | After code / diff | “Verify task-abc: here is the diff…” |
| `reason_feedback` | Learning feedback | Plan worked / bug by category | “Record: plan task-xyz worked, category security” |

---

## Tool details

### `reason_plan`

**Input:**

| Field | Required | Description |
|-------|----------|-------------|
| `request` | yes | Task or feature description |
| `domain` | no | Domain (default `coding`) |
| `context` | no | Extra context |
| `providedFiles` | no | File paths already read by the agent |

**Output:** Markdown plan (`answerMarkdown`) + **Coverage**, **Open questions** list.

If `status` = `needs_grounding`, **Requested files** appear — read them and call `reason_plan` again with `providedFiles`.

**Tip:** call before any non-trivial code; follow the plan DoD checklist.

### `reason_check`

**Input:** `request` (plan or description), optional `context`.

**Output:** JSON with `gaps`, `contradictions`, `missingMandatoryCategories`, `coverage` — no full narrative plan. Faster than `reason_plan` when you only need an audit.

### `reason_testplan`

**Input:** `request`, `context` (code or feature description).

**Output:** Markdown + **Tests to write** block (from `synth.testsToWrite`). Server mode `options.mode: "test"`.

### `reason_debug`

**Input:** bug description, stack trace, `context` with relevant code.

**Output:** plan with hypotheses, minimal fix, regression test (`options.mode: "debug"`).

### `reason_refine`

**Input:**

| Field | Required | Description |
|-------|----------|-------------|
| `refineTaskId` | yes | `taskId` from prior `reason_plan` |
| `request` | yes | What to add or change |
| `context` | no | New context |

Loads prior task graph and runs reasoning in `refine` mode (with diff from previous plan).

### `reason_why`

**Input:** `taskId`, optional `stepId` (if empty — first plan step).

**Output:** JSON `{ taskId, stepId, provenance: [...] }` — graph nodes and categories backing the step.

### `reason_review`

**Input:** `request` (plan or code), `context`.

**Output:** full Markdown report with CRITIQUE (`options.mode: "review"`). On Free tier CRITIQUE is limited to 3 nodes; Trial/Pro — extended (`critique_extended`).

### `reason_pack`

**Input:** `request`, optional `taskId` (tie to experience), `tokenBudget` (default from `VERITHINK_PACK_TOKEN_BUDGET`).

**Output:** compressed Markdown brief for another chat.

### `reason_verify`

**Input:** `taskId` (from `reason_plan`), `artifact` (diff, code, or implementation description), optional `providedFiles`.

**Output:** JSON `VerificationReport`: `items[]` with `done` / `partial` / `missing`, `doneScore`, `mergeReady`.

Optional `verifyMode`: `steps` (default), `outcome`, `both` — for Goal mode use `outcome` after implementation.

Last report via HTTP `GET /v1/verify/{taskId}`.

### `reason_goal_session` (Goal mode)

Requires `VERITHINK_GOAL_MODE_ENABLED=1` on server. User enables in chat: “**mode: goal.** …”

1. `action=start` → `goalRunId`, scope map, `needsUser=true`
2. AskQuestion → `action=advance` with `scopeConfirm`
3. Code → `reason_verify(verifyMode=outcome)` → `action=advance` with `artifact` until `phase=Done`
4. `reason_feedback`

Details (repo): [GOAL_MODE.md](../GOAL_MODE.md) (RU).

### `reason_feedback`

**Input:**

```json
{
  "taskId": "abc123",
  "outcome": {
    "success": true,
    "category": "error_handling"
  }
}
```

`outcome` — arbitrary object; `success` and `category` update profile and learning report.

---

## Typical workflows

### 1. Plan a feature before code

1. Ask the agent to call `reason_plan` with the feature description.
2. If open questions — answer the agent, then `reason_refine` or another `reason_plan` with `context`.
3. Implement per plan; when done — `reason_feedback` with `success: true`.

### 2. Review a ready plan or diff

1. Paste plan/description in chat.
2. `reason_check` for quick JSON or `reason_review` for deep audit.

### 3. Generate a test plan

1. Describe the feature or attach code in `context`.
2. `reason_testplan` → **Tests to write** list.

### 4. Debug a bug

1. Paste stack trace and symptoms.
2. `reason_debug` → hypotheses, fix, regression test.
3. After fix — `reason_feedback` with `success: false` and problem `category`.

### 5. Refine plan from feedback

1. Save `taskId` from `reason_plan`.
2. `reason_refine` with `refineTaskId` and new request (“add OAuth”, “consider multi-tenant”).

### 6. Understand why a step exists (why)

1. `reason_why` with `taskId` and `stepId` from plan.
2. Or open resource `verithink://experience/{taskId}` (below).

### 7. Memory pack for chat context

1. After `reason_plan`, note `taskId`.
2. `reason_pack` with `request` and `taskId` → paste Markdown into a new chat.

---

## Prompt `plan-before-code`

MCP registers slash-style prompt **`plan-before-code`** with argument `task`.

When invoked it forms:

> Before writing code, call reason_plan for: {task}. Follow the returned plan and DoD checklist.

**When to use:** remind the agent at session start or before a large task — instead of typing “plan first” manually.

---

## Resource `verithink://experience/{taskId}`

MCP resource **`experience-graph`** at URI `verithink://experience/{taskId}`.

Content: full `ExperienceRecord` JSON (`graphJson`, goals, categories, coverage).

**When to use:**

- Inspect cognitive graph after reasoning
- Debug provenance without `reason_why`
- Pass structured context to another agent

---

## Direct HTTP API

Base URL: `http://127.0.0.1:8787` (configure with `VERITHINK_PORT`).

### `POST /v1/reason`

**PowerShell:**

```powershell
$body = @{
  request = "Add retry logic with exponential backoff to HTTP client"
  domain  = "coding"
} | ConvertTo-Json

Invoke-RestMethod -Uri "http://127.0.0.1:8787/v1/reason" `
  -Method Post -Body $body -ContentType "application/json"
```

**curl:**

```bash
curl -X POST http://127.0.0.1:8787/v1/reason \
  -H "Content-Type: application/json" \
  -d '{"request":"Add rate limiting to POST /api/login","domain":"coding"}'
```

Key response fields:

| Field | Description |
|-------|-------------|
| `taskId` | ID for refine/why/feedback/pack |
| `status` | `ok`, `needs_clarification`, `needs_grounding`, `abstained`, … |
| `answerMarkdown` | Ready plan (Markdown) |
| `coverage` | Share of covered categories (0–1) |
| `openQuestions` | Questions for the user |
| `reasoningHash` | Reasoning hash for tracing |

Refine via HTTP — same body + `refineTaskId`:

```json
{
  "request": "Add idempotency keys for retries",
  "refineTaskId": "prior-task-id",
  "options": { "mode": "refine" }
}
```

### `POST /v1/pack`

```powershell
$body = @{
  request     = "Rate limiting for login endpoint"
  taskId      = "your-task-id"
  tokenBudget = 1500
} | ConvertTo-Json

Invoke-RestMethod -Uri "http://127.0.0.1:8787/v1/pack" `
  -Method Post -Body $body -ContentType "application/json"
```

### `GET /v1/why/{taskId}`

```bash
curl "http://127.0.0.1:8787/v1/why/abc123?stepId=step-deploy"
```

### `GET /v1/experience/recent`

```bash
curl http://127.0.0.1:8787/v1/experience/recent
```

Returns up to 20 entries: `taskId`, `domain`, `goalTitles`, `categoriesUsed`, `coverage`, `createdAt`.

---

## Dashboard `/ui`

With `VERITHINK_UI=1` open `http://127.0.0.1:8787/ui`.

| Panel | Data |
|-------|------|
| **Health** | JSON from `/healthz` (model, store, license tier, config problems) |
| **Recent experience** | Table of recent tasks and coverage |
| **Try reason** | Interactive `/v1/reason` call |
| **Cognitive graph** | Mermaid from `answerMarkdown` |
| **Learning report** | Categories (uses/failures), lessons, promotion candidates |

---

## FAQ

**Do I need an API key?**  
No with `VERITHINK_LLM_PROVIDER=fake` or `local`. For OpenAI/Anthropic/Gemini (BYOK) — yes. **`service`** mode uses account token instead of provider key ([BILLING.md](BILLING.md)). **`mcp-sampling` does not work in Cursor** — do not treat it as “no key”.

**Where do I get `taskId`?**  
Every `reason_plan` / HTTP `/v1/reason` response — field `taskId`. Keep it for refine, why, feedback, pack.

**What does low Coverage mean?**  
The plan did not cover all mandatory categories (validation, edge cases, error handling, testing). Extend the request or call `reason_refine`.

**What to do on `needs_grounding`?**  
Read files from `requestedFiles`, pass in `providedFiles`, repeat `reason_plan`.

**How is `reason_check` different from `reason_review`?**  
`reason_check` — compact JSON (gaps/contradictions). `reason_review` — full narrative + CRITIQUE (deeper, more LLM cost).

**Works without Cursor?**  
Yes: HTTP API, `/ui` dashboard, curl/Invoke-RestMethod. MCP is only for IDE agent integration.

**How to enable Pro features?**  
Admin issues key via LicenseServer; set `VERITHINK_LICENSE_KEY`. See [ADMIN.md — Licensing](../ADMIN.md#лицензирование) (RU).

**Can plans be in Russian?**  
Yes. `VERITHINK_LANG=auto` detects language from the request; synth follows task language.

**How long to wait?**  
Typically 30–120 s; MCP timeout — `VERITHINK_REQUEST_TIMEOUT_MS` (+20 s for reason). Complex tasks with CRITIQUE/Judge take longer.

---

## Account cabinet and billing modes

Optional **AccountServer** (`tools/AccountServer`) provides registration, billing, and LLM gateway. Web cabinet default: **`http://127.0.0.1:8091/`** (remote host — your URL and HTTPS).

### Register and login

1. Open cabinet in browser.
2. **Register** tab — email and password (min 6 characters).
3. After login Bearer token is stored in browser `localStorage`; copy the same token for VeriThink.

Cabinet sections: **Balance**, **LLM mode**, **Top-up**, **Connect VeriThink**, **Usage**, **Pricing**.

### Choosing LLM mode

| Cabinet mode | Description |
|--------------|-------------|
| **Service** (`service`) | Requests via vendor keys; **10** free requests by default (`VERITHINK_FREE_QUOTA`), then balance debit |
| **BYOK** (`byok`) | Your OpenAI / Anthropic / Gemini key (encrypted on server) |
| **Local model** (`local`) | Ollama, LM Studio, etc. — default `http://127.0.0.1:11434/v1`, no VeriThink billing |

Cabinet mode affects **`POST /v1/llm/complete`**. For Cursor tools (`reason_plan`, etc.) also configure ReasonService (below).

### Connecting VeriThink (Cursor / admin)

1. Cabinet → **Connect VeriThink** → copy env or `.cursor/mcp.json`.
2. **Option A — local admin:** `http://127.0.0.1:8787/admin.html` → provider **`service`**, account server URL, token.
3. **Option B — `.cursor/mcp.json`:**

```json
{
  "mcpServers": {
    "verithink": {
      "command": "npx",
      "args": ["-y", "verithink-mcp"],
      "env": {
        "VERITHINK_AUTOSTART": "1",
        "VERITHINK_LLM_PROVIDER": "service",
        "VERITHINK_ACCOUNT_URL": "http://127.0.0.1:8091",
        "VERITHINK_ACCOUNT_TOKEN": "<token from cabinet>"
      }
    }
  }
}
```

4. Set models if needed: `VERITHINK_LLM_MODEL_CHEAP`, `VERITHINK_LLM_MODEL_STRONG` (else gateway defaults to `gpt-4o-mini`).
5. Restart MCP in Cursor.

When balance is exhausted ReasonService returns **402 insufficient_balance** — top up in cabinet.

### Top-up, usage, pricing

- **Top-up:** “Balance top-up” block → amount in USD → **Top up**. Default provider **`manual`** (instant credit for tests).
- **Usage:** table of recent calls (`GET /v1/usage`) — date, provider, model, tokens, cost, source (`free` / `balance` / `byok` / `local`).
- **Pricing:** cabinet shows final prices per 1000 tokens (USD); per-request cost in usage log.

---

## See also

- [Billing and LLM modes](BILLING.md) — formulas, pricing, security
- [Admin guide](../ADMIN.md) (RU) — deploy, env, Postgres, licenses, AccountServer
- [README.en.md — Add to Cursor](../../README.en.md#add-to-cursor) — deeplink and npx
- [DEEPLINK.md](../DEEPLINK.md) (RU) — install button generation
- [README.en.md](../../README.en.md) — quickstart
