---
name: remora
description: "Use when working with the REMORA system — calling MCP tools for document analysis, legal verification, or security research, OR developing/deploying REMORA workers and benchmarks, OR working with the PreToolUse safety hook or Lyapunov session tracker. Triggers on: analyze document, verify claim, check letter, legal citation, REMORA, RAG query, deploy worker, agent control, audit log, session status, lyapunov, intent drift, hook, remora_hook, safety substrate."
---

# REMORA — Multi-Oracle Consensus Framework

> **Adaptation notice** — This skill is configured for the author's own Cloudflare infrastructure.
> Several components are proprietary and not publicly available. The skill is shared as
> **inspiration for how to combine REMORA with Claude Code** — not as a drop-in setup.
> See [Configuration checklist](#configuration-checklist) below for everything you must replace.

REMORA provides calibrated AI consensus for document analysis, legal citation verification, and security research via four Cloudflare Workers, backed by a 5-stage cascade verification pipeline and a 3-phase PreToolUse safety substrate for Claude Code.

---

## Configuration Checklist

The following items are **author-specific** and must be replaced before this skill works in another environment. Items marked *proprietary* are not publicly available and require building or substituting an equivalent.

### Cloudflare Workers (required infrastructure)

All MCP tools and the PreToolUse hook depend on live Cloudflare Workers. You must deploy your own instances or substitute compatible endpoints.

| Worker | URL pattern | Status | Notes |
|--------|-------------|--------|-------|
| `go-star-remora` | `*.workers.dev` | *Proprietary* | 5-stage cascade consensus engine (Groq + Mistral oracles). Not public — build your own multi-oracle consensus layer or replace with a single LLM call. |
| `remora-rag-oracle` | `*.workers.dev` | *Proprietary* | RAG synthesis worker (bge-m3, reranker, 93-chunk corpus). Corpus is domain-specific. Replace with your own Vectorize index + AI binding. |
| `remora-law-search` | `*.workers.dev` | *Proprietary* | Norwegian law database (D1 + Vectorize). Only relevant in Norwegian legal context. Replace with a law database for your jurisdiction, or omit if unused. |
| `remora-agent-control` | `*.workers.dev` | Open-source (this repo) | Policy gate + D1 audit ledger. Fully reproducible — deploy from `workers/agent-control/`. |

> All four workers run under the author's `razorsharp.workers.dev` Cloudflare subdomain. You will deploy under your own account subdomain.

### Resource IDs (must replace)

These are tied to the author's Cloudflare account and are non-functional for anyone else:

| Resource | Author's ID | How to replace |
|----------|-------------|----------------|
| D1 database `remora-audit` | `642489ab-6c3d-4709-9ad0-d58896e1ce5f` | `npx wrangler d1 create remora-audit` → update `wrangler.toml` |
| KV namespace `remora-sessions` | `c085347bc8be49f3afc38a0e263e5d87` | `npx wrangler kv:namespace create remora-sessions` → update `wrangler.toml` |
| R2 bucket `remora-artifacts` | (author's account) | `npx wrangler r2 bucket create remora-artifacts` |

### Secrets (never committed — must be set per environment)

| Secret | Where used | How to set |
|--------|-----------|------------|
| `CONTROL_SECRET` | agent-control worker — gates all POST/DELETE | `printf '%s' '<secret>' \| npx wrangler secret put CONTROL_SECRET` |
| `AGENT_CONTROL_SECRET` | MCP server → agent-control auth header | `claude_desktop_config.json` under `mcpServers.remora.env` |
| `ORACLE_SECRET` | go-star-remora oracle authentication | `printf '%s' '<secret>' \| npx wrangler secret put ORACLE_SECRET` |
| `GROQ_API_KEY` | go-star-remora LLM calls | Wrangler secret on go-star-remora worker |
| `OPENROUTER_API_KEY` | go-star-remora LLM calls | Wrangler secret on go-star-remora worker |

### Hook path (must replace)

The hook command in `.claude/settings.json` uses an absolute path:
```json
{"command": "python C:/Users/Stian/REMORA/scripts/remora_hook.py"}
```
Replace `C:/Users/Stian/REMORA` with the absolute path to your local clone. Use forward slashes even on Windows.

### MCP server registration

`claude_desktop_config.json` must point to your local `servers/mcp_remora.py` and include your worker URLs and secrets. See the MCP Integration section in `README.md` for the full config block.

### Automated infrastructure setup

If you have a Cloudflare account with wrangler authenticated, run:
```bash
# Preview what will be created
python scripts/setup_cloudflare_infra.py --dry-run

# Provision D1, KV, R2 and patch wrangler.toml
python scripts/setup_cloudflare_infra.py
```

The script creates `remora-audit` (D1), `remora-sessions` (KV), and `remora-artifacts` (R2), patches `workers/agent-control/wrangler.toml` with the new IDs, and prompts for `CONTROL_SECRET`. It then prints the remaining manual steps.

> This only provisions infrastructure for `agent-control`. The other three workers (`go-star-remora`, `remora-rag-oracle`, `remora-law-search`) are proprietary and require separate setup — see the table above.

### What you can use as-is

- `workers/agent-control/` — fully open-source, deploy to your own Cloudflare account
- `scripts/remora_hook.py` — the PreToolUse hook (no worker URLs hardcoded; reads from env/config)
- `remora/agent_hook/` — risk classifier, intent anchor, Lyapunov tracker (pure Python, no external deps)
- `servers/mcp_remora.py` — MCP server (point `CONSENSUS_URL`, `RAG_URL`, `LAW_URL`, `AGENT_CONTROL_URL` to your own workers via env vars)
- All test suites under `tests/`

---

**MCP server:** `servers/mcp_remora.py`  
**Workers:** `workers/`  
**Consensus engine:** `https://go-star-remora.razorsharp.workers.dev` *(author's reference deployment — set `CONSENSUS_URL` env var for your own)*  
**RAG oracle:** `https://remora-rag-oracle.razorsharp.workers.dev` *(set `REMORA_RAG_WORKER_URL` env var for your own)*  
**Law search:** `https://remora-law-search.razorsharp.workers.dev` *(set `LAW_URL` env var for your own)*  
**Agent control:** `https://remora-agent-control.razorsharp.workers.dev` *(author's reference; deploy from `workers/agent-control/` for your own — D1 + KV + R2, CONTROL_SECRET required)*

---

## Tool Decision Tree

```
Norwegian document (letter, debt collection, contract)?
  → 1. remora_verify_legal_citations  — catches hallucinated case references
  → 2. remora_legal_analysis          — full legal analysis with law basis

Single factual claim (yes/no)?
  → remora_verify_claim

Regulatory text (GDPR art. X, ISO 27001 ...)?
  → remora_rag_query (domain=specialised or science)

Norwegian law directly (§-reference, law name)?
  → remora_norwegian_law_search

General document (non-legal)?
  → remora_analyze_document

GO-STAR security finding?
  → remora_verify_claim for isolated consensus
  → See go-star skill for full pipeline

Agentic tool calls through policy gate + audit?
  → 1. agent_start_session   — create session with audit trail
  → 2. agent_execute_tool    — run tool (remora_verify_claim / dce_search_law / store_artifact / audit_decision)
  → 3. agent_audit_log       — inspect what the agent did, approve/reject pending actions

Live safety telemetry (Lyapunov V(t), drift, intent anchor)?
  → remora_session_status    — reports V(t), H, D, convergence and formal stability guarantee

System slow or down?
  → remora_status
```

---

## Confidence Thresholds

| Confidence | Trust | Action |
|------------|-------|--------|
| >= 0.85 | HIGH | Reliable basis for decision |
| 0.65–0.84 | MEDIUM | Useful — verify against primary source |
| 0.40–0.64 | LOW | Indicative only |
| < 0.40 | VERY LOW | Abstain — seek expert advice |

**Cascade pipeline thresholds (internal verification):**

| Stage | Threshold | Trigger |
|-------|-----------|---------|
| FastGate (Stage 1) | conf ≥ 0.90 | ACCEPT directly (1 oracle call) |
| ConsensusGate (Stage 2) | trust ≥ 0.65 | ACCEPT; trust < 0.12 → ABSTAIN |
| VerifierGate (Stage 3) | judge conf ≥ 0.70 | ACCEPT (supported) / ABSTAIN (refuted) |
| CritiqueRevision (Stage 3b) | — | Revision loop on challenged answers (max 2 rounds) |
| SelfConsistency (Stage 4) | agreement ≥ 0.72 | ACCEPT; < 0.50 → ABSTAIN |

**Citation verification verdicts:**

| DB status | Oracle status | Conclusion |
|-----------|---------------|------------|
| FOUND_IN_DATABASE | NEEDS_CONTENT_CHECK | Partially verified — check content |
| NOT_FOUND | CANNOT_VERIFY | Likely hallucinated |
| NOT_FOUND | LIKELY_HALLUCINATED | Likely hallucinated |
| FOUND_IN_DATABASE | LIKELY_HALLUCINATED | Exists, but content is wrong |

---

## Development & Deploy

```bash
# Deploy RAG oracle (after changes to workers/rag-oracle/src/index.ts)
cd workers/rag-oracle && npx wrangler deploy

# Deploy law-search
cd workers/law-search && npx wrangler deploy

# TypeScript type-check
cd workers/rag-oracle && npx tsc --noEmit

# Agent-control is DEPLOYED: https://remora-agent-control.razorsharp.workers.dev
# D1: remora-audit (642489ab-6c3d-4709-9ad0-d58896e1ce5f, EEUR/ARN)
# KV: remora-sessions (c085347bc8be49f3afc38a0e263e5d87)
# R2: remora-artifacts
# Re-deploy on changes:
# cd workers/agent-control && npx wrangler deploy

# Ingest corpus
python scripts/ingest_corpus.py --url <URL> --domain specialised

# Run all tests (~700 selected, ~2 min)
python -m pytest tests/ -q

# Run agent_hook tests only
python -m pytest tests/test_agent_hook.py -v

# MCP smoke test
echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}' | python servers/mcp_remora.py
echo '{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}' | python servers/mcp_remora.py

# Check live workers
curl https://go-star-remora.razorsharp.workers.dev/status
curl https://remora-rag-oracle.razorsharp.workers.dev/status
curl https://remora-law-search.razorsharp.workers.dev/status
```

---

## PreToolUse Safety Hook — Agent Hook Substrate

REMORA acts as a **three-phase safety substrate** intercepting all Claude Code tool calls via `scripts/remora_hook.py` (registered in `.claude/settings.json`).

### Pipeline

```
Claude Code tool call (Bash/Edit/Write/WebFetch/WebSearch/Agent)
    │
    ▼
Phase 1: Deterministic risk classification
    │  LOW  → fast-path allow (no network call)
    │  LOCAL_BLOCK → blocked immediately (rm -rf, dd, wrangler secret, drop table ...)
    │  MEDIUM/HIGH → Phase 2
    ▼
Phase 2: Intent drift detection
    │  drift = 1 − min(1, Jaccard(anchor∩action) + 0.3·substring_bonus)
    │  drift ≥ 0.92 → blocked with explanation
    │  drift ≥ 0.75 → warning, but allowed
    │  → REMORA oracle cascade (5-stage)
    ▼
Phase 3: Lyapunov V(t) tracking
       V(t) = H(t) + λ·D(t)     λ = 0.3
       H(t) = Shannon entropy over oracle distribution
       D(t) = weighted dissensus index
       Non-increasing V(t) → formal stability guarantee
```

### Risk Tiers

| Tier | Examples | Action |
|------|----------|--------|
| LOW | Read, Glob, Grep | Fast-path allow, Lyapunov record |
| MEDIUM | git commit, wrangler deploy, pip install | Oracle verification, block if confidence < 0.35 |
| HIGH | sudo, chmod 777, SECRET/TOKEN in command | Oracle verification, **fail-closed** on error |
| LOCAL_BLOCK | rm -rf, dd, mkfs, drop table, wrangler secret | Deterministically blocked — no network call |

### Installation

**Step 1** — copy the skill to Claude Code's skills directory:
```bash
# macOS/Linux
cp -r .claude/skills/remora ~/.claude/skills/remora

# Windows (PowerShell)
Copy-Item -Recurse .claude\skills\remora $env:USERPROFILE\.claude\skills\remora
```

**Step 2** — register the hook in `.claude/settings.json` (use absolute path with forward slashes):
```json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash|Edit|Write|WebFetch|WebSearch|Agent",
        "hooks": [
          {"type": "command", "command": "python /path/to/REMORA/scripts/remora_hook.py"}
        ]
      }
    ]
  }
}
```

> **Windows note:** Use forward slashes in the path — POSIX shlex strips backslashes.
> Example: `python C:/Users/YourName/REMORA/scripts/remora_hook.py`

**Step 3** — configure secrets (never in source files):
```bash
# Set CONTROL_SECRET on worker
printf '%s' '<secret>' | npx wrangler secret put CONTROL_SECRET

# Add AGENT_CONTROL_SECRET to claude_desktop_config.json under mcpServers env
```

### Intent Anchor CLI

```bash
# Set intent anchor for the session (reduces false drift warnings)
python scripts/remora_anchor.py "Refactor RAG oracle chunking strategy"

# Show current anchor
python scripts/remora_anchor.py --show

# Clear
python scripts/remora_anchor.py --clear
```

### Environment Variables (hook configuration)

| Variable | Default | Description |
|----------|---------|-------------|
| `REMORA_HOOK_MEDIUM_BLOCK_THRESHOLD` | 0.35 | Block MEDIUM if oracle confidence < threshold |
| `REMORA_HOOK_DRIFT_WARN_THRESHOLD` | 0.75 | Warning threshold for intent drift |
| `REMORA_HOOK_DRIFT_BLOCK_THRESHOLD` | 0.92 | Block threshold for intent drift |
| `REQUIRE_REMOTE_FOR_HIGH` | 0 | 1 = fail-closed for HIGH when REMORA is unreachable |
| `REMORA_SESSION_DIR` | `.remora_session` | Local session directory (Lyapunov + intent state) |

### MCP: remora_session_status

Exposes live session telemetry to Claude Desktop:
```json
{
  "V": 0.142,
  "H": 0.098,
  "D": 0.148,
  "tool_calls": 12,
  "converging": true,
  "total_V_reduction": 0.311,
  "formal_guarantee": "V(t) non-increasing over 12 tool calls — session is Lyapunov-stable",
  "intent_anchor": "Refactor RAG oracle chunking strategy",
  "drift_last": 0.21
}
```

---

## MCP Tools — Overview

| Tool | Endpoint | Use when |
|------|----------|----------|
| `remora_analyze_document` | REMORA `/assess` | Free-text analysis |
| `remora_verify_claim` | REMORA `/assess` | Single yes/no factual claim |
| `remora_legal_analysis` | RAG `/query` + REMORA `/assess` | Legal document + law basis |
| `remora_rag_search` | RAG GET `/search` | Raw source search in knowledge base |
| `remora_rag_query` | RAG POST `/query` | Factual question with synthesis and reranking |
| `remora_norwegian_law_search` | Law POST `/search` | Norwegian law text directly |
| `remora_verify_legal_citations` | Law `/verify-citation` + REMORA `/assess` | Hallucinated case references |
| `remora_status` | `/status` | System health check |
| `agent_start_session` | Agent Control `/sessions` | Start audited agent session (UUID, 24h TTL) |
| `agent_execute_tool` | Agent Control `/execute` | Run tool through egress policy + D1 audit |
| `agent_audit_log` | Agent Control `/audit` | Fetch audit log, inspect verdict/confidence per call |
| `remora_session_status` | Local `.remora_session/` | Live V(t), drift, intent anchor, stability guarantee |

---

## Architecture

```
Claude Desktop / Claude Code
    |
Claude Code (PreToolUse hook: scripts/remora_hook.py)
    |-- Phase 1: Deterministic risk classification (LOW/MEDIUM/HIGH/LOCAL_BLOCK)
    |-- Phase 2: Intent drift detection (Jaccard + substring-bonus, thresholds 0.75/0.92)
    `-- Phase 3: Lyapunov V(t) = H(t) + λ·D(t) tracking (formal stability guarantee)
         |
mcp_remora.py (MCP stdio — JSON-RPC, 12 tools)
    |-- go-star-remora.razorsharp.workers.dev    <- 5-stage cascade (FastGate→Consensus→Verifier→CritiqueRevision→SelfConsistency)
    |                                               3 oracles: Groq 8B, 70B, Mistral
    |-- remora-rag-oracle.razorsharp.workers.dev <- RAG synthesis (bge-m3 multi, bge-base-en, reranker, 93 chunks)
    |-- remora-law-search.razorsharp.workers.dev <- Norwegian law database (D1 + Vectorize, 1024d)
    `-- remora-agent-control.razorsharp.workers.dev <- Policy gate + D1 audit ledger (4 tools: verify/law/store/audit)
```

## Live Worker Status (last verified 2026-05-28)

| Worker | Status | Models / Details |
|--------|--------|-----------------|
| go-star-remora | LIVE | Llama 8B + 70B + Mistral 7B |
| remora-rag-oracle | LIVE | bge-m3 (multi), bge-base-en, reranker, 93 chunks |
| remora-law-search | LIVE | norges-lover-law-index, 1024d |
| remora-agent-control | LIVE | D1 audit-log, KV sessions, R2 artifacts, Bearer auth, service bindings → go-star-remora + remora-law-search |

**Security:** CONTROL_SECRET required for all POST/DELETE endpoints. Set with `printf '%s' '<secret>' | npx wrangler secret put CONTROL_SECRET` (avoid PowerShell echo — adds newline).

**Diagnostics:** `GET /test-bindings` (no auth) — confirms both service bindings respond.

**Secret in claude_desktop_config.json:** `AGENT_CONTROL_SECRET` must match CONTROL_SECRET in the worker.
