Skip to content

Database Overview

Thinkroid Space uses SQLite (via better-sqlite3) with a synchronous API. The schema is defined in db.js using CREATE TABLE IF NOT EXISTS statements with additive ALTER TABLE migrations for backwards compatibility.

The database file is stored at the path set by the DB_PATH environment variable, defaulting to thinkroid-space.db in the project root.

Entity-Relationship Overview

┌─────────────┐       ┌──────────────┐       ┌──────────────┐
│   providers  │◄──────│    agents    │──────►│   tasks      │
└─────────────┘       └──────┬───────┘       └──────┬───────┘
                              │                       │
                    ┌─────────┼──────────┐            │
                    ▼         ▼          ▼            ▼
             ┌──────────┐ ┌────────┐ ┌──────────┐ ┌──────────┐
             │org_members│ │dept_   │ │agent_    │ │ projects │
             └─────┬─────┘ │members │ │capabilit.│ └──────────┘
                   │       └────┬───┘ └──────────┘
                   ▼            ▼
          ┌──────────────┐ ┌────────────┐
          │organizations │ │departments │
          └──────┬───────┘ └────────────┘


            ┌─────────┐
            │ spaces  │──────►┌──────────┐──────►┌─────────────┐
            └─────────┘       │  rooms   │       │placed_items │
                              └──────────┘       └──────┬──────┘


                                               ┌───────────────┐
                                               │ item_registry │
                                               └───────────────┘

┌─────────────────┐   ┌──────────────┐   ┌───────────────────┐
│  conversations  │◄──│   messages   │──►│  read_cursors     │
└─────────────────┘   └──────────────┘   └───────────────────┘

┌──────────────┐   ┌────────────────┐   ┌──────────────────┐
│  cron_jobs   │──►│cron_executions │   │  memory_entries  │
└──────────────┘   └────────────────┘   └──────────────────┘
                                         ┌──────────────────┐
                                         │  memory_config   │
                                         └──────────────────┘

┌───────────┐   ┌────────────────┐   ┌─────────────────┐
│   skills  │◄──│  agent_skills  │   │   mcp_servers   │
└───────────┘   └────────────────┘   └─────────────────┘

┌───────────┐   ┌────────────────────┐   ┌──────────────────┐
│   users   │──►│ user_permissions   │   │  login_attempts  │
└───────────┘   └────────────────────┘   └──────────────────┘

Migration Strategy

Schema changes are applied additively via ALTER TABLE wrapped in try/catch, making initDB() safe to run against an existing database at any time. Columns that already exist are never re-created and no data is dropped.


Table Reference

PageSections
Core TablesCore, Communication, Spatial, Organization, Governance, Memory
System TablesAI and Debug, Scheduling, Skills, Auth, Config, External, All Indexes

Database: Core Tables

See also: Back to top | System Tables


1. Core

TablePurposeKey Relationships
agentsEvery AI employee in the system. No default agents are seeded at startup — all agents are created by the user or by applying an Agent Template.Links to providers for Brain/Cerebellum/Context Engine; agents belong to orgs and departments via membership tables
tasksWork unit lifecycle tracking from pending through completion or failure; supports subtask hierarchyAssigned to agents by name; belongs to projects; self-referential parent/child via parent_task_id
projectsGroups tasks under an organizational or agent ownerOwned by either an organization or an agent; contains many tasks

2. Communication

TablePurposeKey Relationships
messagesAll messages across every channel (bulletin board, DMs, meeting channels, boss channel)Belongs to a conversation via conversation_id
conversationsOne record per channel, tracking type, participants, round count, and statusOptionally linked to a room and a record (meeting conclusion)
read_cursorsTracks each agent's read position within a conversation for unread-message detectionComposite key on (agent_name, conversation_id); references messages
user_read_marksRecords which messages have been read by the human user (Boss)References messages
recordsKnowledge artifacts produced by agents: meeting conclusions, notes, reportsCreated by agents; linked to conversations via conversations.record_id
boss_notificationsPending notifications surfaced to the human operator in the message centerReferences agents and messages

3. Spatial

TablePurposeKey Relationships
spacesTop-level office map; a single default space is created at startupParent of rooms and placed_items
roomsNamed areas within a space: workspaces, meeting rooms, break roomsBelongs to spaces; optionally owned by an agent
item_registryCatalog of all placeable item types with visual and interaction parametersReferenced by placed_items
placed_itemsInstances of items actually placed in the officeBelongs to spaces; optionally scoped to a room; typed via item_registry

4. Organization

TablePurposeKey Relationships
organizationsTop-level logical groupings of agents (companies, teams)Linked to a space; contains agents via org_members
org_membersMany-to-many join between organizations and agentsReferences organizations and agents; unique per (org_id, agent_id)
departmentsSub-units within an organization; supports nested hierarchyBelongs to organizations; self-referential parent via parent_dept_id; has a head_agent_id
dept_membersMany-to-many join between departments and agentsReferences departments and agents; unique per (dept_id, agent_id)
management_relationsDerived reporting lines between agents, auto-synced from org/department structureReferences agents twice (manager + subordinate); rows with relation_type != 'manual' are regenerated by syncManagementRelations() — never edit them directly

5. Governance

TablePurposeKey Relationships
agent_capabilitiesWhich governance capabilities are active for each agent (e.g. task_assignment, orphan_detection); the params JSON column scopes capability behavior (e.g. which tools the tool_approval agent covers)References agents; unique per (agent_id, capability_id)
tool_approvalsPending and resolved approval requests for confirm/always_confirm-level tools. The decided_by TEXT column records which agent (or 'boss') made the approval decision.References agents, tasks, and spaces; stores execution context and resume state
rulesCompany-level and project-level rules injected into agent system promptsScoped to 'company' or 'project'

6. Memory

TablePurposeKey Relationships
memory_entriesStructured long-term, short-term, and skill memory for individual agents; tracks importance, decay, and retrieval frequencyReferences agents; indexed by (agent_id, type) and decay_score for efficient retrieval
memory_configPer-agent memory capacity limits and forgetting-curve parametersOne row per agent; references agents

Database: System Tables

See also: Back to top | Core Tables


7. AI and Debug

TablePurposeKey Relationships
providersReusable AI provider configurations (base URL, API key, model, rate limits) that agents reference by ID instead of storing credentials inlineReferenced by agents for Brain, Cerebellum, and Context Engine
token_usageAccounting ledger with one row per AI API call, recording token consumption and estimated costReferences agents by name and optionally tasks
debug_logsFull AI request/response payloads; only written when debug_mode is enabled in global settingsStandalone; recreated on schema change (old data not preserved)
shadow_resultsComparison records from shadow mode: shadow agent output vs original agent output on the same taskReferences tasks

8. Scheduling

TablePurposeKey Relationships
cron_jobsScheduled recurring jobs: governance routines, task dispatches, and scripts; tracks last/next run and execution statsOptionally linked to an agent; governance jobs map to a capability_id
cron_executionsExecution log for each cron job fire, recording status, timing, and any created taskReferences cron_jobs; optionally references tasks

9. Skills

TablePurposeKey Relationships
mcp_serversMCP (Model Context Protocol) server configurations for external tool integrations; stores connection info and discovered toolsReferenced by skills
skillsSkill definitions: bundles of tools with optional system prompt injections; can be builtin, MCP-backed, or customReferences mcp_servers for MCP-type skills
agent_skillsBinding table: which skills are assigned to which agents and in which engine scope (brain, cerebellum, context_engine)References agents and skills; unique per (agent_id, skill_id, scope)

10. Auth

TablePurposeKey Relationships
usersHuman user accounts for multi-user authenticationParent of user_permissions
user_permissionsFine-grained permission overrides for individual users, supplementing role-based defaultsReferences users (cascades on delete)
login_attemptsBrute-force protection: tracks login attempts per identifier and IP addressStandalone; indexed for fast rate-limit lookups by identifier and IP

11. Config

TablePurposeKey Relationships
global_settingsKey-value store for all system-wide configuration (space name, debug mode, active space ID, etc.)Standalone; read at startup and via the settings API

12. External

TablePurposeKey Relationships
outer_channelsExternal integration endpoints: Discord, Slack, Email, webhooks; stores credentials and per-channel rulesStandalone; owner_agent references an agent by name

All Indexes

Indexes are grouped by domain. The rationale is consistent: columns used in frequent WHERE filters or joins are indexed to avoid full-table scans as the dataset grows.

DomainIndexed tables (reason)
Coreagents(name) — looked up by name constantly; tasks(status, assigned_to, project_id) — task queue polling and filtering; projects(owner_type+owner_id, status) — owner lookups
Communicationmessages(channel, conversation_id, priority) — channel feed queries; conversations(type, status, channel) — active conversation lookups; read_cursors(agent_name) — per-agent unread checks; records(type, created_by) — knowledge base filtering; outer_channels(type) — channel type filtering
Spatialrooms(space_id, type, owner_agent_id) — room listing per space; item_registry(category) — item palette filtering; placed_items(space_id, room_id, registry_id) — rendering and spatial queries
Organizationorganizations(type, space_id); org_members(org_id, agent_id); departments(org_id, parent_dept_id); dept_members(dept_id, agent_id); management_relations(manager_agent_id, subordinate_agent_id) — hierarchy traversal
Governancetool_approvals(status) — pending approval queue; rules(scope, category); agent_capabilities(agent_id, capability_id)
Memorymemory_entries(agent_id+type) — scoped retrieval; memory_entries(decay_score DESC) — forgetting curve eviction; memory_entries(created_at) — chronological access
AI and Debugtoken_usage(agent_name, created_at) — cost reporting by agent and time range; shadow_results(task_id)
Schedulingcron_jobs(enabled, agent_id) — scheduler polling; cron_executions(cron_job_id, started_at) — execution history
Skillsagent_skills(agent_id+scope, skill_id); skills(type, mcp_server_id)
Authlogin_attempts(identifier+created_at, ip_address+created_at) — brute-force rate limiting