Repository navigation
Description
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 infoPhase 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:
- Record IDs: Use SurrealDB's native format
nodes:\uuid`` instead of querying by UUID field - NULL values: Use
NONEkeyword instead ofnullin SurrealQL - String escaping: Escape double quotes in content with
\" - Array results: SurrealDB returns arrays even for single results - always check
[0] - Error handling: Check
results[0].status === 'ERR'for query errors - 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 removedUpdate 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:
- Download Surrealist: https://surrealdb.com/surrealist
- Connect to:
http://127.0.0.1:8000 - Namespace:
nodespace - Database:
nodes - Username:
root - 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 stopsPersistent 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)
-
Basic CRUD:
- Create text node → verify in Surrealist
- Update content → verify change in Surrealist
- Delete node → verify removal in Surrealist
-
Hierarchy:
- Create parent node
- Create child nodes
- Query children → verify correct parent_id
-
Schemas:
- Get task schema → verify fields
- Add custom field → verify in schema
- Remove field → verify deletion
-
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
- Remove NodeStore abstraction, use SurrealDB directly #470: Complete SurrealDB Migration (base migration)
- Complete SurrealDB migration - Advanced features #481: SurrealDB Advanced Features (optimistic locking, etc.)
- Complete SurrealDB migration - Advanced features #487: Review and merge SurrealDB migration
Labels
enhancement- New feature/improvementdev-infrastructure- Development toolingbackend- Backend changesfrontend- Frontend changesgood-first-issue- Well-documented, suitable for junior engineers
Activity
malibio commentedon Nov 14, 2025
Answers to Implementation Questions
Thanks for the thorough questions! Here are the answers:
1. Branching Strategy ✅
Use a single feature branch with incremental reviews:
Commit Strategy:
feat: Add SurrealDB server launch scriptsfeat: Implement surrealQuery helper in HttpAdapterfeat: Migrate createNode to SurrealQLfeat: Migrate getNode, updateNode, deleteNode to SurrealQLfeat: Migrate query operations to SurrealQLtest: Add Vitest integration tests for HttpAdapterfeat: Add schema initialization scriptrefactor: Remove old HTTP dev-server codedocs: Add browser dev mode documentationPull 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.tsUpdate 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.tsFull test suite structure:
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:Why all schemas:
Reference for exact schema definitions:
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:
Persistent mode enables the workflow:
When to use in-memory:
But for day-to-day development with Surrealist, persistent mode should be the default.
Database location:
.nodespace/dev.db/(RocksDB directory)Add to .gitignore:
Additional Implementation Notes
Testing the Implementation
Verification Checklist (run after each phase):
Commit Message Format
Use conventional commits:
When to Request Review
Request incremental reviews at these checkpoints:
After Phase 1-2 complete (SurrealDB setup + HttpAdapter migration + tests)
After Phase 3-5 complete (Schema init + cleanup + docs)
This allows parallel work (you implement, reviewer reviews earlier phases).
Summary
feature/issue-490-surrealdb-dev-serverLet me know if you need clarification on any of these! 🚀
malibio commentedon Nov 14, 2025
Test Baseline (Before Implementation)
Unit Tests (Happy-DOM):
Browser Tests:
@vitest/browserpackageImplementation Plan:
Single feature branch with incremental commits following the 5-phase approach with comprehensive Vitest tests.
feat: Add SurrealDB dev server scripts
feat: Add SurrealDB dev server scripts (#494)
feat: Add SurrealDB server launch scripts and dependency check
feat(adapter): Migrate HttpAdapter to SurrealDB HTTP API
WIP: Browser dev mode migration - Phases 1-2 complete
docs: Add SurrealDB to prerequisites in README
WIP: Phase 2b - HttpAdapter integration tests and SurrealQL fixes
style: Fix linting in HttpAdapter SurrealDB integration tests
feat: Migrate HttpAdapter mention operations to SurrealQL
WIP: Phase 2 complete - HttpAdapter fully migrated to SurrealDB
19 remaining items
feat: Migrate HttpAdapter mention operations to SurrealQL
WIP: Phase 2c complete - HttpAdapter fully functional with SurrealDB
WIP: Phases 1-4 complete - SurrealDB dev server integration
docs: Complete browser dev mode documentation and dependency checking
feat: Add SurrealDB dev server scripts (#494)
feat: Add SurrealDB server launch scripts and dependency check
feat(adapter): Migrate HttpAdapter to SurrealDB HTTP API
docs: Add SurrealDB to prerequisites in README
WIP: Phase 2b - HttpAdapter integration tests and SurrealQL fixes
style: Fix linting in HttpAdapter SurrealDB integration tests
feat: Migrate HttpAdapter mention operations to SurrealQL
WIP: Phase 2c complete - HttpAdapter fully functional with SurrealDB
WIP: Phases 1-4 complete - SurrealDB dev server integration
docs: Complete browser dev mode documentation and dependency checking
feat: Add SurrealDB dev server scripts (#494)