# Configure Aphoria Remote Mode

**When to use:** Connecting Aphoria to a remote StemeDB instance for org-wide claim sharing.

> **Architecture Note:** Remote mode uses direct HTTP API calls, not sync/push/pull. When configured for remote mode, all claims are stored in the remote StemeDB instance via REST API.

## Current Status (as of Phase 3)

**Working Today:**
- ✅ Claims stored in StemeDB (local or remote via Phase 1)
- ✅ Observations flow through StemeDB
- ✅ `HostedConfig` exists with remote URL + auth fields

**In Progress (Phase 3):**
- 🚧 StemeDB API `/claims/*` endpoints (create, list, fetch, update)
- 🚧 HTTP client for `EpistemeClaimStore` (calls API instead of local WAL)
- 🚧 `aphoria init --remote <url>` CLI command

**See:** [Gap Closure Phase 3 in roadmap.md](../../../roadmap.md) for implementation details.

## Prerequisites

- Aphoria installed (`cargo install --path applications/aphoria`)
- A running StemeDB server with `/api/v1/claims` endpoints
- Network access to the server
- API key for authentication

## Quick Start (After Phase 3 Complete)

```bash
# Initialize Aphoria with remote StemeDB
aphoria init --remote https://stemedb.acme.corp

# Verify connection
aphoria check-remote

# Scan as usual (claims stored remotely)
aphoria scan
```

This creates `.aphoria/config.toml`:
```toml
[hosted]
url = "https://stemedb.acme.corp"
sync_mode = "remote_only"
api_key_env = "STEMEDB_API_KEY"
offline_fallback = "warn"
```

## Architecture

**Remote Mode (No Sync):**
```
┌──────────────┐  ┌──────────────┐  ┌──────────────┐
│ Developer A  │  │ Developer B  │  │ Developer C  │
│ aphoria scan │  │ aphoria scan │  │ aphoria scan │
└──────┬───────┘  └──────┬───────┘  └──────┬───────┘
       │                 │                 │
       │ HTTP API        │ HTTP API        │ HTTP API
       ▼                 ▼                 ▼
    ┌─────────────────────────────────────────┐
    │      Team StemeDB Server                │
    │  GET  /v1/claims?filters=...            │
    │  POST /v1/claims (create)               │
    │  PUT  /v1/claims/{path}/{pred} (update) │
    └─────────────────────────────────────────┘
```

**Key Difference from Sync:**
- No push/pull operations
- No local storage of claims
- Direct API queries on every scan
- Offline fallback uses cached state

## Configuration Options

### Remote-Only Mode (Recommended)

```toml
[hosted]
url = "https://stemedb.acme.corp"
sync_mode = "remote_only"           # All claims on remote only
api_key_env = "STEMEDB_API_KEY"     # Auth token
offline_fallback = "warn"           # Warn and continue if unreachable
```

### Local-and-Remote Mode (Hybrid)

```toml
[hosted]
url = "https://stemedb.acme.corp"
sync_mode = "local_and_remote"      # Write to both local + remote
api_key_env = "STEMEDB_API_KEY"
offline_fallback = "error"          # Fail if remote unreachable
```

## Offline Fallback Modes

| Mode | Behavior | When to Use |
|------|----------|-------------|
| `warn` | Log warning, continue with cached claims | Developer workflow (default) |
| `error` | Abort scan with error | CI/CD where remote is mandatory |
| `silent` | Continue silently with cache | Background jobs |

**Caching:** When remote is unreachable, Aphoria uses last-known claims cached locally at `.aphoria/cache.toml`.

## Authentication

Set API key via environment variable:

```bash
export STEMEDB_API_KEY="your-secret-token"
```

The HTTP client sends:
```
Authorization: Bearer your-secret-token
```

**Never commit API keys.** Use environment variables only.

## Claim Discovery Workflow (Phase 4 - Future)

Once remote mode works, developers can discover org patterns:

```bash
# Search for claims matching a concept
aphoria claims search --concept-path "*/imports/tokio"

# Output shows:
# - Tier 1 (RFC): "Core MUST NOT import tokio" (23 projects)
# - Tier 3 (Expert): "CLI MAY import tokio" (5 projects)

# Developer decides: align code or create counter-claim
```

**See:** [Gap Closure Phase 4 in roadmap.md](../../../roadmap.md) for discovery workflows.

## CI/CD Integration

### GitHub Actions

```yaml
- name: Aphoria Scan
  env:
    STEMEDB_API_KEY: ${{ secrets.STEMEDB_API_KEY }}
  run: aphoria scan --exit-code
```

### Pre-commit Hook

```bash
#!/bin/sh
# .git/hooks/pre-commit
aphoria scan --staged --exit-code
```

With remote mode configured, claims are queried from remote on every scan.

## Verifying Setup

```bash
# Check connection
aphoria check-remote
# Expected: ✓ Connected to https://stemedb.acme.corp

# Test scan with verbose logging
RUST_LOG=aphoria=debug aphoria scan

# Expected log: "Queried N claims from remote StemeDB"
```

## Server Setup

The remote StemeDB server must have `/claims/*` endpoints:

```bash
# Start server with API endpoints
cargo run -p stemedb-api -- --bind 0.0.0.0:18180

# Verify endpoints exist
curl https://stemedb.acme.corp/api/v1/claims
```

**Server Requirements:**
- StemeDB API with `/v1/claims` routes (Phase 3)
- API key validation middleware
- HTTPS/TLS configured (production)

## Troubleshooting

### "Remote connection failed"

Check:
- URL is correct in `.aphoria/config.toml`
- Server is running and reachable
- Network/firewall allows connection on port 18180

### "Authentication failed (401)"

Check:
- `STEMEDB_API_KEY` environment variable is set
- API key is valid on server
- `api_key_env` in config matches env var name

### Claims not found remotely

Possible causes:
1. Claims not yet created on remote (run `aphoria claims create`)
2. API key lacks read permission
3. Concept path mismatch (case-sensitive)

### Offline mode not working

Check:
- `.aphoria/cache.toml` exists (created on first successful remote fetch)
- `offline_fallback` is set to `warn` or `silent` (not `error`)

## Migration from Local to Remote

**Step 1:** Configure remote URL
```bash
aphoria init --remote https://stemedb.acme.corp
```

**Step 2:** Migrate existing claims (if any in `.aphoria/claims.toml`)
```bash
aphoria migrate claims-to-remote
# Uploads all TOML claims to remote via API
```

**Step 3:** Verify
```bash
aphoria scan
# Should query claims from remote
```

**Step 4:** Delete local TOML (optional)
```bash
rm .aphoria/claims.toml
# Remote is now source of truth
```

## Related

- [Gap Closure Phase 3](../../../roadmap.md#gap-closure-phase-3-remote-hosted-mode-current) - Remote mode implementation
- [Gap Closure Phase 4](../../../roadmap.md#gap-closure-phase-4-claim-discovery--manual-convergence-future) - Discovery workflows
- [Aphoria Config Reference](../../../ai-lookup/features/aphoria-config.md) - Full config options
