# rSpace Ontology

> A composable, local-first platform for collaborative knowledge work,
> democratic governance, and programmable economic flows.

```
┌─────────────────────────────────────────────────────────┐
│                    rStack Foundation                     │
│  Identity · Data · Payments · Crypto · Sync             │
├─────────────────────────────────────────────────────────┤
│                    rSpace Platform                       │
│  Spaces · Canvas · Modules · Flows · Nesting            │
├─────────────────────────────────────────────────────────┤
│                 rApps (26+ Modules)                      │
│  Information · Economic · Democratic · Creative         │
└─────────────────────────────────────────────────────────┘
```

---

## 1. rStack — Foundation Layer

rStack is the infrastructure substrate that all rApps share. No module
implements its own auth, sync, encryption, or payments — they inherit
these capabilities from the stack.

### 1.1 rIdentity (EncryptID)

Self-sovereign identity via WebAuthn passkeys. No passwords, no seed
phrases, no custodial accounts.

```
Passkey (biometric/PIN on device)
  → PRF extension yields hardware-bound salt
    → HKDF Master Key (256-bit)
      ├→ AES-256-GCM    — encrypt documents, files, backups
      ├→ Ed25519         — DID (did:key:z6Mk...) for identity
      ├→ ECDSA P-256     — TLS-grade signing
      └→ secp256k1       — Ethereum EOA for wallets & payments
```

**Auth Levels** (time-decaying, re-escalated by fresh passkey tap):
1. **Basic** — session token, read-only public content
2. **Standard** — recent auth (<15 min), normal operations
3. **Elevated** — fresh auth, wallet proposals & sensitive writes
4. **Critical** — fresh auth + explicit consent, key operations

**Social Recovery** — no seed phrases, ever:
- Guardian types: secondary passkey, trusted contact (DID), hardware key,
  institutional, time-delayed self-recovery (48h default)
- Threshold approval (e.g. 3-of-5 guardians)
- Old credential revoked, new one activated

**Cross-app portability**: One DID works across all `r*.online` domains.
Passkey ceremony scoped to `rspace.online` RP ID, cookie shared across
subdomains.

### 1.2 Local-First Data (Automerge CRDT)

All data is local-first. Users own their data, the server is a
replication peer — not the source of truth.

```
┌──────────────┐     WebSocket      ┌──────────────┐
│   Browser    │ ←── sync msgs ──→  │   Server     │
│  IndexedDB   │    (Automerge)     │  Filesystem  │
│  (primary)   │                    │  (replica)   │
└──────────────┘                    └──────────────┘
        ↕                                  ↕
   Works offline                   Relays to peers
   Merges on reconnect             Persists for durability
```

**7-Layer Stack:**
1. **Crypto** — per-space, per-document AES-256-GCM encryption via HKDF
   key hierarchy. Server stores only ciphertext.
2. **Document** — typed Automerge docs with versioned schemas and
   migrations. IDs: `{space}:{module}:{collection}[:{item}]`
3. **Storage** — IndexedDB (client) + filesystem (server) with 2s
   debounced persistence
4. **Sync** — single WebSocket per space, multiplexed across documents.
   Incremental sync via Automerge `SyncState` (only deltas sent)
5. **Compute** — deterministic transforms (filter, aggregate, rollup)
6. **Query** — materialized views, full-text search indexes
7. **Application** — module-specific logic

**Byzantine Fault Tolerance via CRDT:**
- Commutative: edit order doesn't matter
- Idempotent: replay-safe
- No coordinator: any peer can merge any version
- Causally consistent: happens-before relationships preserved
- Conflict-free: mathematical resolution, no manual merge

### 1.3 Micropayments (x402)

HTTP 402 Payment Required as a first-class protocol. Any route can
require payment by adding middleware.

```
Client                          Server                    Facilitator
  │                               │                          │
  ├── GET /resource ──────────→   │                          │
  │                               │                          │
  ←── 402 + requirements ──────   │                          │
  │   (payTo, amount, network)    │                          │
  │                               │                          │
  │  [user signs with passkey     │                          │
  │   via EOA or Safe wallet]     │                          │
  │                               │                          │
  ├── GET /resource ──────────→   │                          │
  │   X-PAYMENT: <proof>          ├── verify(proof) ──────→  │
  │                               ←── { valid: true } ──────  │
  ←── 200 OK + resource ──────   │                          │
```

- **EVM chains**: Base, Ethereum, Optimism, Polygon, Arbitrum, etc.
- **Any ERC20**: USDC, native ETH, etc.
- **Wallet-abstracted**: passkey-derived EOA signs directly, or proposes
  through Gnosis Safe multisig
- **Use cases**: file upload gates, AI generation costs, premium content,
  per-query API access

### 1.4 Wallet Abstraction (Gnosis Safe + Passkey EOA)

```
Passkey (biometric)
  → secp256k1 private key (derived via HKDF)
    → EOA address (Ethereum account)
      → Safe owner/signer (multisig)
        → Multi-chain treasury
          ├→ Ethereum mainnet
          ├→ Base / Optimism / Arbitrum (L2 rollups)
          ├→ Polygon / Gnosis / Celo
          └→ ... any EVM chain
```

No MetaMask. No hardware wallet required. Passkey IS the wallet.

- **Safe Transaction Service**: propose → threshold confirm → execute
- **Multi-chain detection**: auto-discovers Safes across 12+ chains
- **Rollup-first**: L2 by default for low-cost transactions, settle to
  L1 when needed

---

## 2. rSpace — Platform Layer

rSpace is the unification layer: routing, spaces, the spatial canvas,
module composition, and inter-module flows.

### 2.1 Spaces

A **space** is a collaborative context — a team, community, project, or
individual workspace. Each space has:

- **Slug** + optional subdomain (`alice.rspace.online`)
- **Visibility**: `public` (👁 green — anyone reads, sign in to write) | `permissioned` (🔑 yellow — sign in to read & write) | `private` (🔒 red — invite-only)
- **Members**: `viewer` → `member` → `moderator` → `admin`
- **Enabled modules**: which rApps are available in this space
- **Module scoping**: per-module `space` (data lives in space) vs
  `global` (data follows identity)
- **Automerge document**: the space itself is a CRDT — collaborative,
  offline-capable, conflict-free

**Nesting**: spaces can embed other spaces as shapes on their canvas.
Permissions (read, write, reshare) are scoped per-nest with optional
expiry. Consent policies: open, members-only, approval-required, closed.

### 2.2 Canvas (FolkJS)

The spatial substrate. An infinite 2D canvas where shapes (web
components) are positioned, connected, and composed.

```
Canvas (folk-canvas)
  ├→ folk-markdown    — rich text
  ├→ folk-arrow       — directed connections
  ├→ folk-rapp        — embedded module UI
  ├→ folk-embed       — external iframes
  ├→ folk-image-gen   — AI image generation
  ├→ folk-map         — geographic view
  ├→ folk-calendar    — time view
  ├→ folk-token-mint  — ERC20 creation
  ├→ folk-choice-vote — governance
  ├→ folk-canvas      — nested canvas (recursive)
  └→ ... 25+ shape types
```

Each shape stores `{ type, id, x, y, width, height, rotation, content, ... }`
in the space's Automerge document. Real-time collaborative: multiple
users see each other's cursors, selections, and edits.

### 2.3 Module System

Every rApp implements `RSpaceModule`:

```typescript
interface RSpaceModule {
  id: string;                    // 'rcal', 'rfunds', 'rvote'
  name: string;                  // 'rCal', 'rFunds', 'rVote'
  icon: string;                  // emoji
  description: string;
  routes: Hono;                  // mounted at /:space/:moduleId
  standaloneDomain?: string;     // 'rcal.online'
  scoping: ModuleScoping;        // space vs global
  docSchemas?: DocSchema[];      // Automerge schemas
  feeds?: FeedDefinition[];      // data this module exposes
  acceptsFeeds?: FlowKind[];     // flow types it can consume
  landingPage?: () => string;    // standalone marketing page
  onInit?, onSpaceCreate?, onSpaceDelete?: (ctx) => Promise<void>;
}
```

Modules are composable: they expose **feeds** (typed data streams) and
consume feeds from other modules. The canvas visualizes these as
inter-layer flows.

### 2.4 Flow Kinds

Flows are typed connections between modules:

| Kind | Description | Example |
|------|-------------|---------|
| `data` | Information flow | rDocs → rPubs (publish) |
| `economic` | Value/payment flow | rFunds → rWallet (treasury) |
| `trust` | Reputation/attestation | rVote → rNetwork (delegation) |
| `attention` | Signal/notification | rInbox → rForum (mentions) |
| `governance` | Decision/policy flow | rVote → rSpace (access control) |
| `creative` | Content generation | rDesign → rSwag (merch) |

### 2.5 Routing

```
rcal.online           → 301 → rspace.online/rcal (landing page)
alice.rcal.online     → 301 → alice.rspace.online/rcal (space)
alice.rspace.online/rcal     → /:space/rcal routes (module UI)
alice.rspace.online/rcal/api → /:space/rcal/api (REST API)
rspace.online/rcal           → landing page (no space context)
```

Traefik → Cloudflare tunnel → Hono server. Each `r*.online` domain
redirects to the unified server with subdomain-based space routing.

---

## 3. rApps — Module Layer

26+ modules organized by function:

### Information

| Module | Domain | Purpose |
|--------|--------|---------|
| **rDocs** | rdocs.online | Rich editor — notebooks, voice transcription, AI, import/export (TipTap + Automerge) |
| **rNotes** | rnotes.online | Vault sync & browse for Obsidian and Logseq |
| **rPubs** | rpubs.online | Long-form publishing (Typst PDF) |
| **rBooks** | rbooks.online | PDF library with flipbook reader |
| **rData** | rdata.online | Data visualization & analysis |

### Planning & Spatial

| Module | Domain | Purpose |
|--------|--------|---------|
| **rCal** | rcal.online | Spatio-temporal calendar with map + lunar overlay |
| **rMaps** | rmaps.online | Geographic mapping & location hierarchy |
| **rTrips** | rtrips.online | Trip planning with itineraries |
| **rTasks** | rtasks.online | Task boards & project management |
| **rSchedule** | rschedule.online | Persistent cron-based job scheduling with email, webhooks & briefings |

### Communication

| Module | Domain | Purpose |
|--------|--------|---------|
| **rForum** | rforum.online | Threaded discussions |
| **rInbox** | rinbox.online | Unified inbox (IMAP sync) |
| **rSocials** | rsocials.online | Social posts & feeds |

### Democratic

| Module | Domain | Purpose |
|--------|--------|---------|
| **rChoices** | rchoices.online | Multi-criteria decision-making (spider plots, ranking) |
| **rVote** | rvote.online | Proposal voting with delegation |

### Economic

| Module | Domain | Purpose |
|--------|--------|---------|
| **rFunds** | rfunds.online | Community funding & crowdfunding |
| **rWallet** | rwallet.online | Multi-chain Safe wallet interface |
| **rCart** | rcart.online | E-commerce & shopping |
| **rNetwork** | rnetwork.online | Social graph & reputation |

### Creative

| Module | Domain | Purpose |
|--------|--------|---------|
| **rSwag** | rswag.online | Merchandise design & production |
| **rPhotos** | rphotos.online | Photo galleries |
| **rTube** | rtube.online | Video hosting |
| **rSplat** | rsplat.online | 3D Gaussian splatting |
| **rDesign** | rdesign.online | Design system & components |
| **rFiles** | rfiles.online | Encrypted file storage |

---

## 4. Design Principles

### Data Sovereignty
Users own their data. Automerge documents live on-device first.
The server is a replication peer, not a gatekeeper. Per-document
encryption means the server stores only ciphertext.

### Composability over Monolith
Each module is independently useful (`rcal.online` works standalone)
but gains power through composition on the canvas. Modules communicate
via typed feeds, not hard-wired integrations.

### Identity without Custody
EncryptID derives all keys from a single passkey tap. No passwords,
no seed phrases, no custodial key storage. Social recovery replaces
mnemonic backup. The same identity works for signing documents,
encrypting data, and authorizing blockchain transactions.

### Payments as Protocol
x402 makes payment a protocol primitive, not a product feature. Any
HTTP endpoint can require payment. The wallet is derived from the same
passkey — no separate wallet app needed.

### Spatial-First
The canvas is the primary interface. Modules render as shapes that can
be positioned, connected, resized, and composed spatially. This enables
non-linear knowledge work: a funding proposal (rFunds) sits next to
the vote (rVote), the budget spreadsheet (rData), and the project
plan (rTasks) — all on one canvas, all synced in real-time.

### Offline-First
Every interaction works offline. Changes queue locally and merge
conflict-free on reconnect. No loading spinners, no "connection lost"
errors, no data loss.

---

## 5. Token & Value Architecture

### Layer 1: Micropayments (x402)
Per-request payments for API access, file uploads, AI generation.
Settled on EVM L2 rollups (Base, Optimism) for sub-cent transaction
costs. Facilitator verifies payment proofs without requiring the app
to run its own blockchain node.

### Layer 2: Treasury (Gnosis Safe)
Spaces can have multi-sig treasuries. Funding proposals (rFunds)
flow into Safe wallets. Threshold signing by space admins/moderators.
Multi-chain: same Safe address across L1 and L2s.

### Layer 3: Governance Tokens (planned)
Module-minted ERC20 tokens via `folk-token-mint`. Voting power
in rVote tied to token holdings or delegation. Quadratic funding
in rFunds weighted by token-gated participation.

### Layer 4: BFT Consensus via CRDT
Automerge provides Byzantine-fault-tolerant data replication without
a blockchain. For pure data collaboration (notes, calendars, tasks),
no on-chain settlement is needed. The CRDT IS the consensus mechanism.
Blockchain is used only when economic finality is required (payments,
token transfers, governance outcomes).

### Rollup Strategy
```
Data consensus     → Automerge CRDT (off-chain, free, instant)
Payment settlement → L2 rollup (Base/Optimism, ~$0.001/tx)
Governance finality → L1 or L2 (when needed)
Token issuance     → L2 (low-cost ERC20 deployment)
```

The principle: **use the cheapest layer that provides sufficient
guarantees**. Most operations never touch a blockchain.
