Skip to content

Simplify Browser Dev Mode: Use SurrealDB HTTP Server Instead of Custom REST Layer #490

Closed

Description

@malibio

Simplify Browser Dev Mode: Use SurrealDB HTTP Server Instead of Custom REST Layer

Summary

Replace the custom Rust HTTP dev-server (port 3001) with SurrealDB's native HTTP server (port 8000) for browser development mode. This eliminates ~1150 lines of HTTP endpoint code, enables live database inspection with Surrealist, and simplifies the development architecture.

Context

Current Architecture (Browser Dev Mode)

Frontend (Svelte) → HttpAdapter → Custom Rust HTTP Server (port 3001)
                                          ↓
                                    SurrealStore (embedded RocksDB)
                                          ↓
                                    ~/.nodespace/database/nodespace-dev.db

Problems:
❌ Can't inspect database with Surrealist (file DB is locked by dev-server)
❌ Must maintain 1150+ lines of HTTP endpoint code (node_endpoints.rs, schema_endpoints.rs, etc.)
❌ Custom REST API duplicates SurrealDB functionality
❌ Extra serialization overhead (JSON ↔ Rust ↔ SurrealDB)

Proposed Architecture (Browser Dev Mode)

Frontend (Svelte) → HttpAdapter → SurrealDB HTTP Server (port 8000)
                                          ↓
                                    In-memory or RocksDB storage

Surrealist Inspector ───────────────────→ Same SurrealDB Server

Benefits:
✅ Live database inspection with Surrealist during development
✅ Remove entire custom HTTP server (~1150 lines)
✅ Use SurrealDB's native HTTP API (no custom endpoints needed)
✅ Simpler architecture, faster performance
✅ Future-proof for SurrealDB features (live queries, subscriptions)

Desktop Mode (Unchanged)

Desktop mode continues to use Tauri IPC → SurrealStore (embedded). This issue only affects browser development mode.


Implementation Plan

Phase 1: Add SurrealDB Server Launch Script

File: packages/desktop-app/package.json

Changes:

{
  "scripts": {
    "dev:db": "surreal start --bind 127.0.0.1:8000 --user root --pass root --log trace memory",
    "dev:db:persist": "surreal start --bind 127.0.0.1:8000 --user root --pass root --log trace rocksdb://.nodespace/dev.db",
    "dev": "concurrently --names \"DB,UI\" --prefix-colors \"blue,green\" \"bun run dev:db\" \"vite dev\""
  }
}

Explanation:

  • dev:db - Start SurrealDB in-memory server (data lost on restart, fast for testing)
  • dev:db:persist - Start SurrealDB with RocksDB persistence (data survives restarts)
  • dev - Run both SurrealDB server and Vite frontend concurrently

Verify:

# Start server
bun run dev:db

# Test with curl
curl -X POST http://127.0.0.1:8000/sql \
  -H "Authorization: Basic cm9vdDpyb290" \
  -H "Accept: application/json" \
  -H "NS: nodespace" \
  -H "DB: nodes" \
  -d "INFO FOR DB;"

# Expected: JSON response with database info

Phase 2: Update HttpAdapter to Use SurrealDB HTTP API

File: packages/desktop-app/src/lib/services/backend-adapter.ts

Current Implementation:

// HttpAdapter makes REST calls to custom Rust endpoints
async createNode(node: Node): Promise<string> {
  const response = await fetch(`${this.baseUrl}/api/nodes`, {
    method: 'POST',
    body: JSON.stringify(node)
  });
  return await response.json();
}

New Implementation:

export class HttpAdapter implements BackendAdapter {
  private readonly baseUrl: string;
  private readonly auth: string;

  constructor(baseUrl: string = 'http://localhost:8000') {
    this.baseUrl = baseUrl;
    // Development credentials (base64 encoded "root:root")
    this.auth = 'Basic ' + btoa('root:root');
  }

  /**
   * Execute SurrealQL query via HTTP API
   *
   * @param sql - SurrealQL query string
   * @returns Query result (parsed from response[0].result)
   */
  private async surrealQuery<T = any>(sql: string): Promise<T> {
    const response = await fetch(`${this.baseUrl}/sql`, {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Authorization': this.auth,
        'NS': 'nodespace',
        'DB': 'nodes'
      },
      body: sql
    });

    if (!response.ok) {
      const error = await response.text();
      throw new Error(`SurrealDB error (${response.status}): ${error}`);
    }

    const results = await response.json();

    // SurrealDB returns array of results (one per statement)
    // Check for errors in result
    if (results[0]?.status === 'ERR') {
      throw new Error(`SurrealDB query error: ${results[0]?.result}`);
    }

    return results[0]?.result;
  }

  async createNode(node: Omit<Node, 'createdAt' | 'modifiedAt' | 'version'>): Promise<string> {
    // Use SurrealDB record ID format: nodes:⟨uuid⟩
    const sql = `
      CREATE nodes:\`${node.id}\` CONTENT {
        node_type: "${node.nodeType}",
        content: "${node.content.replace(/"/g, '\\"')}",
        parent_id: ${node.parentId ? `"${node.parentId}"` : 'NONE'},
        container_node_id: ${node.containerNodeId ? `"${node.containerNodeId}"` : 'NONE'},
        before_sibling_id: ${node.beforeSiblingId ? `"${node.beforeSiblingId}"` : 'NONE'},
        properties: ${JSON.stringify(node.properties)},
        mentions: ${JSON.stringify(node.mentions || [])},
        mentioned_by: ${JSON.stringify(node.mentionedBy || [])},
        version: 1,
        created_at: time::now(),
        modified_at: time::now()
      };
    `;

    await this.surrealQuery(sql);

    // Emit events (existing code)
    eventBus.emit<NodeCreatedEvent>({
      type: 'node:created',
      namespace: 'lifecycle',
      source: 'HttpAdapter',
      nodeId: node.id,
      parentId: node.parentId ?? undefined,
      nodeType: node.nodeType
    });

    return node.id;
  }

  async getNode(id: string): Promise<Node | null> {
    const sql = `SELECT * FROM nodes:\`${id}\`;`;
    const result = await this.surrealQuery<any>(sql);

    // SurrealDB returns array, get first item
    return result?.[0] || null;
  }

  async updateNode(id: string, version: number, update: NodeUpdate): Promise<void> {
    // Build SET clauses for provided fields
    const setClauses: string[] = ['modified_at = time::now()', 'version = version + 1'];

    if (update.content !== undefined) {
      setClauses.push(`content = "${update.content.replace(/"/g, '\\"')}"`);
    }
    if (update.nodeType !== undefined) {
      setClauses.push(`node_type = "${update.nodeType}"`);
    }
    if (update.parentId !== undefined) {
      setClauses.push(`parent_id = ${update.parentId ? `"${update.parentId}"` : 'NONE'}`);
    }
    if (update.containerNodeId !== undefined) {
      setClauses.push(`container_node_id = ${update.containerNodeId ? `"${update.containerNodeId}"` : 'NONE'}`);
    }
    if (update.beforeSiblingId !== undefined) {
      setClauses.push(`before_sibling_id = ${update.beforeSiblingId ? `"${update.beforeSiblingId}"` : 'NONE'}`);
    }
    if (update.properties !== undefined) {
      setClauses.push(`properties = ${JSON.stringify(update.properties)}`);
    }

    // Optimistic concurrency control - only update if version matches
    const sql = `
      UPDATE nodes:\`${id}\`
      SET ${setClauses.join(', ')}
      WHERE version = ${version};
    `;

    const result = await this.surrealQuery(sql);

    // Check if update succeeded (version matched)
    if (!result || result.length === 0) {
      throw new Error(`Version conflict: Node ${id} version ${version} does not match current version`);
    }

    // Emit events (existing code)
    eventBus.emit<NodeUpdatedEvent>({
      type: 'node:updated',
      namespace: 'lifecycle',
      source: 'HttpAdapter',
      nodeId: id,
      updateType: 'content' in update ? 'content' : 'hierarchy'
    });
  }

  async deleteNode(id: string, version: number): Promise<void> {
    // Fetch node before deletion for events
    const nodeBeforeDeletion = await this.getNode(id);

    // Delete with version check
    const sql = `DELETE nodes:\`${id}\` WHERE version = ${version};`;
    const result = await this.surrealQuery(sql);

    if (!result || result.length === 0) {
      throw new Error(`Version conflict or node not found: ${id}`);
    }

    // Emit events if node existed
    if (nodeBeforeDeletion) {
      eventBus.emit<NodeDeletedEvent>({
        type: 'node:deleted',
        namespace: 'lifecycle',
        source: 'HttpAdapter',
        nodeId: id,
        parentId: nodeBeforeDeletion.parentId ?? undefined
      });
    }
  }

  async getChildren(parentId: string): Promise<Node[]> {
    const sql = `SELECT * FROM nodes WHERE parent_id = "${parentId}" ORDER BY created_at ASC;`;
    return await this.surrealQuery<Node[]>(sql) || [];
  }

  async queryNodes(params: QueryNodesParams): Promise<Node[]> {
    let sql = 'SELECT * FROM nodes';
    const conditions: string[] = [];

    if (params.parentId !== undefined) {
      if (params.parentId === null) {
        conditions.push('parent_id = NONE');
      } else {
        conditions.push(`parent_id = "${params.parentId}"`);
      }
    }

    if (params.containerId !== undefined) {
      conditions.push(`container_node_id = "${params.containerId}"`);
    }

    if (conditions.length > 0) {
      sql += ' WHERE ' + conditions.join(' AND ');
    }

    sql += ' ORDER BY created_at ASC;';

    return await this.surrealQuery<Node[]>(sql) || [];
  }

  async getNodesByContainerId(containerId: string): Promise<Node[]> {
    const sql = `SELECT * FROM nodes WHERE container_node_id = "${containerId}" ORDER BY created_at ASC;`;
    return await this.surrealQuery<Node[]>(sql) || [];
  }

  async mentionAutocomplete(query: string, limit: number = 10): Promise<Node[]> {
    // Search in content, case-insensitive
    const sql = `
      SELECT * FROM nodes
      WHERE string::lowercase(content) CONTAINS string::lowercase("${query.replace(/"/g, '\\"')}")
      LIMIT ${limit};
    `;
    return await this.surrealQuery<Node[]>(sql) || [];
  }

  // === Schema Management Operations ===

  async getSchema(schemaId: string): Promise<SchemaDefinition> {
    const sql = `SELECT * FROM nodes:\`${schemaId}\` WHERE node_type = "schema";`;
    const result = await this.surrealQuery<any[]>(sql);

    if (!result || result.length === 0) {
      throw new NodeOperationError(`Schema not found: ${schemaId}`, schemaId, 'getSchema');
    }

    const schemaNode = result[0];

    // Parse properties as schema definition
    return {
      isCore: schemaNode.properties.is_core,
      version: schemaNode.properties.version,
      description: schemaNode.properties.description,
      fields: schemaNode.properties.fields.map((field: any) => ({
        name: field.name,
        type: field.field_type,
        protection: field.protection,
        coreValues: field.core_values,
        userValues: field.user_values,
        indexed: field.indexed,
        required: field.required,
        extensible: field.extensible,
        default: field.default,
        description: field.description,
        itemType: field.item_type
      }))
    };
  }

  // TODO: Implement remaining schema operations (addSchemaField, removeSchemaField, etc.)
  // These will follow the same pattern: build SurrealQL, execute via surrealQuery()
}

Key Implementation Notes:

  1. Record IDs: Use SurrealDB's native format nodes:\uuid`` instead of querying by UUID field
  2. NULL values: Use NONE keyword instead of null in SurrealQL
  3. String escaping: Escape double quotes in content with \"
  4. Array results: SurrealDB returns arrays even for single results - always check [0]
  5. Error handling: Check results[0].status === 'ERR' for query errors
  6. Version conflicts: Empty result from UPDATE WHERE version = X means version mismatch

Testing Each Method:

# Start SurrealDB
bun run dev:db

# In another terminal, start frontend
bun run dev:frontend

# Test in browser console:
const adapter = getBackendAdapter();

// Test create
const nodeId = await adapter.createNode({
  id: 'test-123',
  nodeType: 'text',
  content: 'Hello SurrealDB',
  parentId: null,
  containerNodeId: null,
  beforeSiblingId: null,
  properties: {},
  mentions: [],
  mentionedBy: []
});

// Test get
const node = await adapter.getNode('test-123');
console.log(node);

// Test update
await adapter.updateNode('test-123', 1, {
  content: 'Updated content'
});

// Test delete
await adapter.deleteNode('test-123', 2);

Phase 3: Initialize Database Schema on Server Start

Problem: SurrealDB server starts empty - no tables or schemas exist.

Solution: Create initialization script that seeds core schemas.

File: packages/desktop-app/scripts/init-surrealdb.ts

/**
 * Initialize SurrealDB with NodeSpace schema
 * Run this after starting SurrealDB server
 */

async function initializeSurrealDB() {
  const baseUrl = 'http://127.0.0.1:8000';
  const auth = 'Basic ' + btoa('root:root');

  async function query(sql: string) {
    const response = await fetch(`${baseUrl}/sql`, {
      method: 'POST',
      headers: {
        'Authorization': auth,
        'NS': 'nodespace',
        'DB': 'nodes'
      },
      body: sql
    });

    const result = await response.json();

    if (result[0]?.status === 'ERR') {
      throw new Error(`SurrealDB error: ${result[0]?.result}`);
    }

    return result[0]?.result;
  }

  // 1. Create nodes table
  console.log('Creating nodes table...');
  await query('DEFINE TABLE nodes SCHEMALESS;');

  // 2. Seed core schemas (task, person, date, etc.)
  console.log('Seeding core schemas...');

  const taskSchema = {
    is_core: true,
    version: 1,
    description: 'Task tracking schema',
    fields: [
      {
        name: 'status',
        field_type: 'enum',
        protection: 'core',
        core_values: ['OPEN', 'IN_PROGRESS', 'DONE'],
        user_values: [],
        indexed: true,
        required: true,
        extensible: true,
        default: 'OPEN',
        description: 'Task status'
      },
      // Add other task fields...
    ]
  };

  await query(`
    CREATE nodes:\`task\` CONTENT {
      node_type: "schema",
      content: "Task",
      properties: ${JSON.stringify(taskSchema)},
      version: 1,
      created_at: time::now(),
      modified_at: time::now()
    };
  `);

  // TODO: Add person, date, project, text, header, code-block, quote-block, ordered-list schemas

  console.log('✅ SurrealDB initialized successfully!');
}

initializeSurrealDB().catch(console.error);

Update package.json:

{
  "scripts": {
    "dev:db:init": "bun run scripts/init-surrealdb.ts",
    "dev": "concurrently \"bun run dev:db\" \"bun run dev:db:init\" \"vite dev\""
  }
}

OR simpler - add initialization to dev:db script:

{
  "scripts": {
    "dev:db": "surreal start --bind 127.0.0.1:8000 --user root --pass root memory & sleep 2 && bun run scripts/init-surrealdb.ts",
  }
}

Phase 4: Remove Old HTTP Dev Server (Cleanup)

Files to Delete:

# Rust dev server binary
packages/desktop-app/src-tauri/src/bin/dev-server.rs

# HTTP endpoint implementations
packages/desktop-app/src-tauri/src/dev_server/mod.rs
packages/desktop-app/src-tauri/src/dev_server/node_endpoints.rs
packages/desktop-app/src-tauri/src/dev_server/schema_endpoints.rs
packages/desktop-app/src-tauri/src/dev_server/mention_endpoints.rs
packages/desktop-app/src-tauri/src/dev_server/embedding_endpoints.rs

# Total: ~1150 lines removed

Update Cargo.toml:

Remove dev-server feature and dependencies:

# Remove these:
[features]
dev-server = ["axum", "tower-http"]

[dependencies]
# Remove these:
axum = { version = "0.7", optional = true }
tower-http = { version = "0.5", optional = true }

Phase 5: Update Documentation

File: docs/architecture/development/browser-dev-mode.md (new file)

# Browser Development Mode

## Architecture

Browser dev mode uses SurrealDB HTTP server instead of Tauri IPC for database access.

### Stack

Frontend (Svelte) → HttpAdapter → SurrealDB HTTP API (port 8000)
↓
In-memory or RocksDB storage


### Starting Dev Environment

```bash
# Start both SurrealDB and frontend
bun run dev

# Or separately:
bun run dev:db        # Start SurrealDB server
bun run dev:frontend  # Start Vite dev server

Database Inspection

Surrealist can connect to the dev server for live inspection:

  1. Download Surrealist: https://surrealdb.com/surrealist
  2. Connect to: http://127.0.0.1:8000
  3. Namespace: nodespace
  4. Database: nodes
  5. Username: root
  6. Password: root

You can now see all data changes in real-time as you interact with the frontend!

Data Persistence

In-memory mode (default):

bun run dev:db
# Data lost when server stops

Persistent mode:

bun run dev:db:persist
# Data saved to .nodespace/dev.db (survives restarts)

SurrealQL Examples

-- Get all nodes
SELECT * FROM nodes;

-- Get specific node
SELECT * FROM nodes:`node-uuid`;

-- Find nodes by type
SELECT * FROM nodes WHERE node_type = "task";

-- Update node
UPDATE nodes:`node-uuid` SET content = "New content" WHERE version = 1;

-- Delete node
DELETE nodes:`node-uuid`;

**File:** `README.md` (update development section)

```markdown
## Development

### Browser Mode (Web Development)

```bash
# Start SurrealDB server + Vite dev server
bun run dev

# Database inspector (Surrealist)
# Connect to http://127.0.0.1:8000
# Credentials: root/root

Desktop Mode (Tauri App)

bun run tauri:dev

---

## Acceptance Criteria

### Functionality

- [ ] `bun run dev` starts both SurrealDB server and Vite dev server
- [ ] HttpAdapter successfully connects to SurrealDB HTTP API (port 8000)
- [ ] All CRUD operations work (create, read, update, delete nodes)
- [ ] Schema operations work (get schema, add field, remove field, etc.)
- [ ] Mention operations work (create, delete, get mentions)
- [ ] Query operations work (queryNodes, getChildren, getNodesByContainerId)
- [ ] Optimistic concurrency control works (version conflicts detected)
- [ ] All frontend tests pass with new HttpAdapter implementation
- [ ] Surrealist can connect and inspect database in real-time

### Code Quality

- [ ] Old HTTP dev-server code removed (~1150 lines)
- [ ] HttpAdapter implementation is clean and well-documented
- [ ] Error handling covers all failure cases (connection, query errors, version conflicts)
- [ ] SurrealQL queries are properly escaped to prevent injection
- [ ] All TypeScript types are correct (no `any` types)

### Documentation

- [ ] Browser dev mode documented in `docs/architecture/development/browser-dev-mode.md`
- [ ] README updated with new dev commands
- [ ] Schema initialization script documented
- [ ] Surrealist connection instructions provided

### Testing

- [ ] Manual testing of all operations in browser console
- [ ] Frontend integration tests pass
- [ ] Can create, read, update, delete nodes via UI
- [ ] Version conflicts properly handled in UI
- [ ] Data visible in Surrealist matches UI state

---

## Implementation Checklist

### Phase 1: Setup (30 minutes)

- [ ] Install SurrealDB CLI: `brew install surrealdb/tap/surreal`
- [ ] Add `dev:db` script to package.json
- [ ] Test SurrealDB server starts successfully
- [ ] Test curl connection to HTTP API

### Phase 2: HttpAdapter Migration (2-3 hours)

- [ ] Implement `surrealQuery()` helper method
- [ ] Migrate `createNode()` to SurrealQL
- [ ] Migrate `getNode()` to SurrealQL
- [ ] Migrate `updateNode()` to SurrealQL (with version check)
- [ ] Migrate `deleteNode()` to SurrealQL (with version check)
- [ ] Migrate `getChildren()` to SurrealQL
- [ ] Migrate `queryNodes()` to SurrealQL
- [ ] Migrate `getNodesByContainerId()` to SurrealQL
- [ ] Migrate `mentionAutocomplete()` to SurrealQL
- [ ] Migrate schema operations to SurrealQL
- [ ] Test each method individually in browser console

### Phase 3: Schema Initialization (1 hour)

- [ ] Create `scripts/init-surrealdb.ts`
- [ ] Implement table creation (DEFINE TABLE nodes)
- [ ] Implement schema seeding (task, person, date, etc.)
- [ ] Add initialization to dev startup flow
- [ ] Test schemas exist after startup

### Phase 4: Cleanup (30 minutes)

- [ ] Delete `src-tauri/src/bin/dev-server.rs`
- [ ] Delete `src-tauri/src/dev_server/` directory
- [ ] Remove dev-server dependencies from Cargo.toml
- [ ] Verify Rust project still compiles
- [ ] Run `cargo clean` to clear old artifacts

### Phase 5: Documentation (30 minutes)

- [ ] Create `docs/architecture/development/browser-dev-mode.md`
- [ ] Update README.md dev section
- [ ] Add Surrealist connection instructions
- [ ] Document schema initialization

### Phase 6: Testing (1 hour)

- [ ] Test `bun run dev` starts successfully
- [ ] Test all CRUD operations in browser
- [ ] Test schema operations in browser
- [ ] Test version conflicts are detected
- [ ] Connect Surrealist and verify data visibility
- [ ] Run frontend test suite
- [ ] Manual QA of all major features

---

## Resources

### SurrealDB Documentation

- HTTP API: https://surrealdb.com/docs/integration/http
- SurrealQL Syntax: https://surrealdb.com/docs/surrealql
- Authentication: https://surrealdb.com/docs/security/authentication

### Example SurrealQL Queries

```sql
-- Create with specific record ID
CREATE nodes:`test-123` CONTENT {
  node_type: "text",
  content: "Hello",
  version: 1
};

-- Select by record ID
SELECT * FROM nodes:`test-123`;

-- Update with condition
UPDATE nodes:`test-123` SET content = "Updated" WHERE version = 1;

-- Delete by record ID
DELETE nodes:`test-123`;

-- Query with filters
SELECT * FROM nodes WHERE node_type = "task" AND parent_id = NONE;

-- String search (case-insensitive)
SELECT * FROM nodes WHERE string::lowercase(content) CONTAINS "search term";

Troubleshooting

SurrealDB won't start:

# Check if port 8000 is in use
lsof -i :8000

# Kill process using port
kill -9 <PID>

Can't connect from frontend:

# Check SurrealDB is listening
curl http://127.0.0.1:8000/health

# Expected: {"status": "ok"}

Queries failing with "NS not found":

# Headers are case-sensitive, use uppercase:
-H "NS: nodespace"
-H "DB: nodes"

Version conflicts not detected:

-- Verify version is incrementing
SELECT version FROM nodes:`test-123`;

-- Update should fail if version doesn't match
UPDATE nodes:`test-123` SET content = "x" WHERE version = 999;
-- Expected: empty result (no rows updated)

Testing Plan

Unit Tests (Frontend)

Test HttpAdapter methods in isolation:

describe('HttpAdapter - SurrealDB', () => {
  let adapter: HttpAdapter;

  beforeEach(() => {
    adapter = new HttpAdapter('http://localhost:8000');
  });

  it('should create a node', async () => {
    const nodeId = await adapter.createNode({
      id: 'test-node',
      nodeType: 'text',
      content: 'Test content',
      // ...
    });
    expect(nodeId).toBe('test-node');
  });

  it('should detect version conflicts', async () => {
    // Create node (version 1)
    await adapter.createNode({ id: 'test', /* ... */ });

    // Update with correct version
    await adapter.updateNode('test', 1, { content: 'Updated' });

    // Update with stale version should fail
    await expect(
      adapter.updateNode('test', 1, { content: 'Stale' })
    ).rejects.toThrow('Version conflict');
  });

  // Add tests for all methods
});

Integration Tests (Manual)

  1. Basic CRUD:

    • Create text node → verify in Surrealist
    • Update content → verify change in Surrealist
    • Delete node → verify removal in Surrealist
  2. Hierarchy:

    • Create parent node
    • Create child nodes
    • Query children → verify correct parent_id
  3. Schemas:

    • Get task schema → verify fields
    • Add custom field → verify in schema
    • Remove field → verify deletion
  4. Version Control:

    • Create node
    • Update with correct version → succeeds
    • Update with stale version → fails with version conflict error

Success Metrics

  • Lines of Code Removed: ~1150 lines (HTTP dev-server)
  • New Dependencies Added: 0 (just use SurrealDB CLI)
  • Performance: No regressions in browser dev mode
  • Developer Experience: Can inspect database with Surrealist during development
  • Maintenance: Simpler architecture, less code to maintain

Related Issues


Labels

  • enhancement - New feature/improvement
  • dev-infrastructure - Development tooling
  • backend - Backend changes
  • frontend - Frontend changes
  • good-first-issue - Well-documented, suitable for junior engineers

Activity

  1. added
    enhancement
    good first issue
    on Nov 14, 2025
  2. malibio commented on Nov 14, 2025

    @malibio
    CollaboratorAuthor

    Answers to Implementation Questions

    Thanks for the thorough questions! Here are the answers:

    1. Branching Strategy ✅

    Use a single feature branch with incremental reviews:

    git checkout -b feature/issue-490-surrealdb-dev-server

    Commit Strategy:

    • Make incremental commits for each logical unit of work
    • Example commit sequence:
      1. feat: Add SurrealDB server launch scripts
      2. feat: Implement surrealQuery helper in HttpAdapter
      3. feat: Migrate createNode to SurrealQL
      4. feat: Migrate getNode, updateNode, deleteNode to SurrealQL
      5. feat: Migrate query operations to SurrealQL
      6. test: Add Vitest integration tests for HttpAdapter
      7. feat: Add schema initialization script
      8. refactor: Remove old HTTP dev-server code
      9. docs: Add browser dev mode documentation

    Pull Request Strategy:

    Start with Option A - single PR with incremental commits. If reviewers request splitting, we can do that later.


    2. SurrealDB CLI Installation ✅

    Add verification to setup, don't auto-install:

    Create a pre-check script: packages/desktop-app/scripts/check-dev-deps.ts

    #!/usr/bin/env bun
    
    /**
     * Verify development dependencies are installed
     */
    
    import { exec } from 'child_process';
    import { promisify } from 'util';
    
    const execAsync = promisify(exec);
    
    async function checkSurrealDB() {
      try {
        const { stdout } = await execAsync('surreal version');
        console.log('✅ SurrealDB installed:', stdout.split('\n')[0]);
        return true;
      } catch (error) {
        console.error('❌ SurrealDB not found');
        console.error('\nInstallation instructions:');
        console.error('  macOS:   brew install surrealdb/tap/surreal');
        console.error('  Linux:   curl -sSf https://install.surrealdb.com | sh');
        console.error('  Windows: iwr https://install.surrealdb.com -useb | iex');
        console.error('\nDocs: https://surrealdb.com/docs/installation');
        return false;
      }
    }
    
    async function main() {
      console.log('🔍 Checking development dependencies...\n');
      
      const surrealOk = await checkSurrealDB();
      
      if (!surrealOk) {
        process.exit(1);
      }
      
      console.log('\n✅ All dev dependencies installed!\n');
    }
    
    main();

    Update package.json:

    {
      "scripts": {
        "dev:check": "bun run scripts/check-dev-deps.ts",
        "dev": "bun run dev:check && concurrently \"bun run dev:db\" \"vite dev\""
      }
    }

    Don't auto-install - let developers install manually. The check script provides clear installation instructions.


    3. Testing Scope ✅

    Implement automated Vitest tests from the get-go:

    Create comprehensive integration tests for all HttpAdapter methods.

    Test file location: packages/desktop-app/src/lib/services/backend-adapter.surreal.test.ts

    Full test suite structure:

    import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest';
    import { HttpAdapter } from './backend-adapter';
    
    describe('HttpAdapter - SurrealDB Integration', () => {
      let adapter: HttpAdapter;
      
      beforeAll(async () => {
        // Assumes SurrealDB server is running on port 8000
        adapter = new HttpAdapter('http://localhost:8000');
      });
    
      describe('CRUD Operations', () => {
        it('should create a node', async () => {
          const nodeId = await adapter.createNode({
            id: 'test-node-1',
            nodeType: 'text',
            content: 'Test content',
            parentId: null,
            containerNodeId: null,
            beforeSiblingId: null,
            properties: {},
            mentions: [],
            mentionedBy: []
          });
          
          expect(nodeId).toBe('test-node-1');
        });
    
        it('should retrieve a created node', async () => {
          await adapter.createNode({
            id: 'test-node-2',
            nodeType: 'text',
            content: 'Test content',
            parentId: null,
            containerNodeId: null,
            beforeSiblingId: null,
            properties: {},
            mentions: [],
            mentionedBy: []
          });
    
          const node = await adapter.getNode('test-node-2');
          expect(node).toBeDefined();
          expect(node?.content).toBe('Test content');
          expect(node?.nodeType).toBe('text');
        });
    
        it('should update a node with correct version', async () => {
          const nodeId = await adapter.createNode({
            id: 'test-node-3',
            nodeType: 'text',
            content: 'Original content',
            parentId: null,
            containerNodeId: null,
            beforeSiblingId: null,
            properties: {},
            mentions: [],
            mentionedBy: []
          });
    
          await adapter.updateNode(nodeId, 1, {
            content: 'Updated content'
          });
    
          const updated = await adapter.getNode(nodeId);
          expect(updated?.content).toBe('Updated content');
          expect(updated?.version).toBe(2);
        });
    
        it('should detect version conflicts on update', async () => {
          const nodeId = await adapter.createNode({
            id: 'test-node-4',
            nodeType: 'text',
            content: 'Original',
            parentId: null,
            containerNodeId: null,
            beforeSiblingId: null,
            properties: {},
            mentions: [],
            mentionedBy: []
          });
    
          // Update once (version 1 → 2)
          await adapter.updateNode(nodeId, 1, { content: 'First update' });
    
          // Try to update with stale version (should fail)
          await expect(
            adapter.updateNode(nodeId, 1, { content: 'Stale update' })
          ).rejects.toThrow('Version conflict');
        });
    
        it('should delete a node', async () => {
          const nodeId = await adapter.createNode({
            id: 'test-node-5',
            nodeType: 'text',
            content: 'To be deleted',
            parentId: null,
            containerNodeId: null,
            beforeSiblingId: null,
            properties: {},
            mentions: [],
            mentionedBy: []
          });
    
          await adapter.deleteNode(nodeId, 1);
    
          const deleted = await adapter.getNode(nodeId);
          expect(deleted).toBeNull();
        });
    
        it('should detect version conflicts on delete', async () => {
          const nodeId = await adapter.createNode({
            id: 'test-node-6',
            nodeType: 'text',
            content: 'Test',
            parentId: null,
            containerNodeId: null,
            beforeSiblingId: null,
            properties: {},
            mentions: [],
            mentionedBy: []
          });
    
          // Update to change version
          await adapter.updateNode(nodeId, 1, { content: 'Updated' });
    
          // Try to delete with stale version (should fail)
          await expect(
            adapter.deleteNode(nodeId, 1)
          ).rejects.toThrow();
        });
      });
    
      describe('Query Operations', () => {
        beforeEach(async () => {
          // Create test hierarchy
          await adapter.createNode({
            id: 'parent-1',
            nodeType: 'text',
            content: 'Parent',
            parentId: null,
            containerNodeId: null,
            beforeSiblingId: null,
            properties: {},
            mentions: [],
            mentionedBy: []
          });
    
          await adapter.createNode({
            id: 'child-1',
            nodeType: 'text',
            content: 'Child 1',
            parentId: 'parent-1',
            containerNodeId: null,
            beforeSiblingId: null,
            properties: {},
            mentions: [],
            mentionedBy: []
          });
    
          await adapter.createNode({
            id: 'child-2',
            nodeType: 'text',
            content: 'Child 2',
            parentId: 'parent-1',
            containerNodeId: null,
            beforeSiblingId: null,
            properties: {},
            mentions: [],
            mentionedBy: []
          });
        });
    
        it('should get children of a parent node', async () => {
          const children = await adapter.getChildren('parent-1');
          
          expect(children).toHaveLength(2);
          expect(children.map(n => n.id)).toContain('child-1');
          expect(children.map(n => n.id)).toContain('child-2');
        });
    
        it('should query nodes by parent ID', async () => {
          const nodes = await adapter.queryNodes({ parentId: 'parent-1' });
          
          expect(nodes).toHaveLength(2);
          expect(nodes.every(n => n.parentId === 'parent-1')).toBe(true);
        });
    
        it('should query root nodes (parentId = null)', async () => {
          const rootNodes = await adapter.queryNodes({ parentId: null });
          
          expect(rootNodes.length).toBeGreaterThan(0);
          expect(rootNodes.every(n => n.parentId === null)).toBe(true);
        });
    
        it('should query nodes by container ID', async () => {
          await adapter.createNode({
            id: 'container-child',
            nodeType: 'text',
            content: 'In container',
            parentId: null,
            containerNodeId: 'container-1',
            beforeSiblingId: null,
            properties: {},
            mentions: [],
            mentionedBy: []
          });
    
          const nodes = await adapter.getNodesByContainerId('container-1');
          
          expect(nodes).toHaveLength(1);
          expect(nodes[0].id).toBe('container-child');
        });
    
        it('should perform mention autocomplete', async () => {
          await adapter.createNode({
            id: 'searchable',
            nodeType: 'text',
            content: 'This is a searchable node',
            parentId: null,
            containerNodeId: null,
            beforeSiblingId: null,
            properties: {},
            mentions: [],
            mentionedBy: []
          });
    
          const results = await adapter.mentionAutocomplete('searchable', 10);
          
          expect(results.length).toBeGreaterThan(0);
          expect(results.some(n => n.content.includes('searchable'))).toBe(true);
        });
      });
    
      describe('Schema Operations', () => {
        it('should get a schema definition', async () => {
          // Assumes schema initialization has run and task schema exists
          const schema = await adapter.getSchema('task');
          
          expect(schema).toBeDefined();
          expect(schema.isCore).toBe(true);
          expect(schema.fields.length).toBeGreaterThan(0);
          expect(schema.fields.some(f => f.name === 'status')).toBe(true);
        });
    
        it('should throw error for non-existent schema', async () => {
          await expect(
            adapter.getSchema('nonexistent-schema')
          ).rejects.toThrow('Schema not found');
        });
      });
    
      describe('Error Handling', () => {
        it('should handle invalid node IDs gracefully', async () => {
          const result = await adapter.getNode('nonexistent-node');
          expect(result).toBeNull();
        });
    
        it('should handle malformed updates', async () => {
          await expect(
            adapter.updateNode('nonexistent', 1, { content: 'test' })
          ).rejects.toThrow();
        });
    
        it('should handle SurrealDB connection errors', async () => {
          const badAdapter = new HttpAdapter('http://localhost:9999');
          
          await expect(
            badAdapter.createNode({
              id: 'test',
              nodeType: 'text',
              content: 'test',
              parentId: null,
              containerNodeId: null,
              beforeSiblingId: null,
              properties: {},
              mentions: [],
              mentionedBy: []
            })
          ).rejects.toThrow();
        });
      });
    });

    Update package.json to run SurrealDB before tests:

    {
      "scripts": {
        "test:adapter": "bun run dev:db & sleep 2 && vitest run src/lib/services/backend-adapter.surreal.test.ts && pkill surreal",
        "test:adapter:watch": "bun run dev:db & vitest watch src/lib/services/backend-adapter.surreal.test.ts"
      }
    }

    Testing is a REQUIRED part of this implementation, not optional.


    4. Schema Initialization ✅

    Seed ALL 9 core schemas from the start:

    The schema initialization should be complete and production-ready from day one. Seed all schemas mentioned in the old database.rs:

    1. ✅ task - Full schema with status, priority, due_date, started_at, completed_at, assignee
    2. ✅ person - With name, email fields
    3. ✅ date - Minimal schema
    4. ✅ project - With name, status fields
    5. ✅ text - Minimal schema
    6. ✅ header - Minimal markdown schema
    7. ✅ code-block - Minimal markdown schema
    8. ✅ quote-block - Minimal markdown schema
    9. ✅ ordered-list - Minimal markdown schema

    Why all schemas:

    • Frontend expects these schemas to exist
    • Schema-driven UI will break without them
    • Taking shortcuts now means fixing later
    • Copy exact schemas from old database.rs

    Reference for exact schema definitions:

    # Get the exact schema JSON from old database.rs
    git show f82cb84^:packages/core/src/db/database.rs | grep -A 50 "seed_core_schemas"

    Copy the schema definitions exactly to ensure compatibility.


    5. Data Persistence Preference ✅

    Use PERSISTENT mode as default (enable Surrealist inspection):

    {
      "scripts": {
        "dev:db": "surreal start --bind 127.0.0.1:8000 --user root --pass root --log info file://.nodespace/dev.db",
        "dev:db:memory": "surreal start --bind 127.0.0.1:8000 --user root --pass root --log info memory",
        "dev": "concurrently \"bun run dev:db\" \"vite dev\""
      }
    }

    Reasoning:

    The primary goal of this issue is to enable live database inspection with Surrealist. For that to be useful, you need:

    1. Data to persist across restarts - So you can inspect the database state after closing/reopening
    2. Ability to build up test data - Create nodes, schemas, relationships and inspect them
    3. Debugging session continuity - Stop development, come back later, data is still there

    Persistent mode enables the workflow:

    • ✅ Create nodes in UI → see them in Surrealist
    • ✅ Modify data in Surrealist → see changes in UI
    • ✅ Restart dev server → data still there
    • ✅ Build up complex test scenarios over time

    When to use in-memory:

    • Automated testing (clean slate each run)
    • CI/CD pipelines
    • When you explicitly want a fresh start

    But for day-to-day development with Surrealist, persistent mode should be the default.

    Database location: .nodespace/dev.db/ (RocksDB directory)

    Add to .gitignore:

    .nodespace/dev.db/
    

    Additional Implementation Notes

    Testing the Implementation

    Verification Checklist (run after each phase):

    # After Phase 1: SurrealDB setup
    bun run dev:db
    curl http://127.0.0.1:8000/health
    # Expected: OK response
    
    # After Phase 2: HttpAdapter migration + tests
    bun run test:adapter
    # Expected: All tests pass
    
    # Manual verification in browser console:
    const adapter = getBackendAdapter();
    await adapter.createNode({ id: 'test', nodeType: 'text', content: 'Hello', ... });
    await adapter.getNode('test');
    # Expected: Node object with content "Hello"
    
    # After Phase 3: Schema initialization
    # In Surrealist, run:
    SELECT * FROM nodes WHERE node_type = "schema";
    # Expected: 9 schema nodes (task, person, date, etc.)

    Commit Message Format

    Use conventional commits:

    feat: Add SurrealDB server launch scripts
    feat(adapter): Implement surrealQuery helper method
    feat(adapter): Migrate CRUD operations to SurrealQL
    test(adapter): Add comprehensive Vitest integration tests
    feat(schemas): Add schema initialization script
    refactor: Remove old HTTP dev-server code
    docs: Add browser dev mode documentation

    When to Request Review

    Request incremental reviews at these checkpoints:

    1. After Phase 1-2 complete (SurrealDB setup + HttpAdapter migration + tests)

      • Tag reviewer: "Phase 1-2 complete (with tests), ready for initial review"
      • Continue working on Phase 3 while waiting for feedback
    2. After Phase 3-5 complete (Schema init + cleanup + docs)

      • Tag reviewer: "All phases complete, ready for final review"

    This allows parallel work (you implement, reviewer reviews earlier phases).


    Summary

    Question Answer
    Branching Single branch: feature/issue-490-surrealdb-dev-server
    SurrealDB CLI Add verification script, don't auto-install
    Testing Automated Vitest tests required (comprehensive test suite)
    Schema Init Seed ALL 9 core schemas from day one
    Data Mode Persistent default (file://.nodespace/dev.db), in-memory opt-in for testing

    Let me know if you need clarification on any of these! 🚀

  3. malibio commented on Nov 14, 2025

    @malibio
    CollaboratorAuthor

    Test Baseline (Before Implementation)

    Unit Tests (Happy-DOM):

    • ✅ Test Files: 85 passed | 6 skipped (91)
    • ✅ Tests: 1538 passed | 49 skipped (1587)
    • ✅ Duration: 22.19s

    Browser Tests:

    • ❌ Pre-existing error: Missing @vitest/browser package
    • Note: This is a pre-existing issue, not related to this implementation

    Implementation Plan:
    Single feature branch with incremental commits following the 5-phase approach with comprehensive Vitest tests.

  4. self-assigned this
    on Nov 14, 2025
  5. 19 remaining items

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

enhancementgood first issue

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions