Database schema
About 3406 wordsAbout 11 min
ORM: Eloquent Capsule | Engines: SQLite 3.35+ (default), MySQL 5.7+ / MariaDB 10.4+ Column types: cross-engine only — TEXT + $casts for JSON payloads, no engine-specific types for JSON payloads. (The one native json column is agent_prompt_templates.variables.) Schema management: DatabaseSchemaInstaller — versioned, component-aware, idempotent (see app/Core/DatabaseSchemaInstaller.php).
Tables
| Table | Model | Purpose |
|---|---|---|
users | Spora\Models\User | Managed by delight-im/auth. Spora adds created_at/updated_at, plus profile fields (name, date_of_birth, about_me, height_cm, weight_kg). locale (varchar(10), nullable — added in migration 0096) holds the language one person reads Spora in. null means “auto”: the language falls through to SPORA_DEFAULT_LANG and then to English, so every account renders as it did before the column existed and no backfill was needed. The column is on users and not on principal_preferences because the locale belongs to the person, who acts as a user-principal and any number of group principals — on a principal-scoped column the language would change with the active principal. |
users_2fa, users_audit_log, users_confirmations, users_otps, users_remembered, users_resets, users_throttling | — | delight-im/auth auxiliary tables. Do not modify. |
agents | Spora\Models\Agent | Stores identity, llm_driver_config_id (nullable FK), system_prompt, max_steps (the agent’s step cap — an INT UNSIGNED, so the storage is not what decides the ceiling; the instance’s SPORA_MAX_STEPS ceiling is 200 by default and a new agent carries 100), allow_followup, retry_after_minutes, max_retries, default_effort (nullable — the agent’s own reasoning-effort default). recipe_id was dropped in migration 0055 — Agent templates are files on disk, not database entities, so they have no canonical id to key on. Updated in spora-core PR #209: agents.user_id is dropped in favour of agents.principal_id (NOT NULL, FK to principals.id with ON DELETE RESTRICT). Ownership is now principal-scoped, not user-scoped — a single agent may be owned by a user-principal or by a group-principal. agents.principal_id cannot be deleted while the agent exists; controllers surface a structured 409 (PrincipalHasDependentsException) with agent_ids so the operator can transfer or delete the dependents first via POST /api/v1/agents/{id}/transfer. |
tool_configurations | Spora\Models\ToolConfiguration | Global per-tool settings. One row per tool class. settings is encrypted via SecurityManager. All access via ToolConfigService only. |
agent_tools | Spora\Models\AgentTool | Junction: which tools are enabled per agent. Per-operation approval lives in agent_tool_operation_overrides. |
agent_tool_overrides | Spora\Models\AgentToolOverride | Per-agent credential overrides. Merged on top of global settings by ToolConfigService. |
agent_tool_operation_overrides | Spora\Models\AgentToolOperationOverride | Per-agent per-operation enablement/approval flags. enabled and default_requires_approval are nullable 3-state — never cast to boolean. |
tasks | Spora\Models\Task | One record per agent run. Status lifecycle: QUEUED → RUNNING → COMPLETED / FAILED / PENDING_APPROVAL ⇄ RUNNING / CANCELLED, RUNNING → AWAITING_SUB_AGENTS → RUNNING (sync) | QUEUED (worker) (added in spora-core PR #196 — suspends the parent while every spawned sub_agent child terminates), and RUNNING → ABORTED / AWAITING_SUB_AGENTS → ABORTED (added in spora-core PR #207 — user-initiated quiescent state, resumable), plus RUNNING → ABORTED from the step cap (system-initiated, added in spora-core PR #266 — the row carries data.max_steps_reached: true to distinguish it from operator aborts). DB default PENDING, but the orchestrator always sets QUEUED or RUNNING on create. CANCELLED is set by TaskService::cancelRetryChain (app/Services/TaskService.php:250). ABORTED is set by Orchestrator::abort (app/Agents/Orchestrator.php) and stamped with data.aborted_at — the step-cap variant additionally sets data.max_steps_reached: true via TaskStatusWriter::autoAbortTransition (added in spora-core PR #266); Orchestrator::continue() clears aborted_at (and data.max_steps_reached where present) on resume and accepts {COMPLETED, FAILED, ABORTED, RUNNING} as valid sources (a RUNNING source auto-aborts and writes an abort_marker history row before re-prompting). parent_task_id enables follow-up lineage; retry columns (retry_of_task_id, retry_count, retry_after) from migration 0042. Book-keeping for the multi-child resume gate lives in data.spawned_sub_task_ids (live child ids) and data.sub_agent_expected_count (set after each spawn so the gate can compare against the live count at the batch boundary). data.sub_agent_batch_open (added in spora-core PR #227 / Plan D): a per-batch cross-process lock set by the first spawn of a multi-child batch and cleared by the batch-boundary hook, so the per-child resume hook cannot race the boundary hook in worker mode and prematurely resume mid-batch. The WorkerReaper extends to AWAITING_SUB_AGENTS rows whose lease has expired — a healthy multi-child batch keeps the parent’s lease alive via LeaseGuard::extend (which covers both RUNNING and AWAITING_SUB_AGENTS) and is left alone. Both pending_state and data are MEDIUMTEXT. error_code/error_message from migration 0017. effort (nullable, migration 0099) — the effort resolved for a task, as the canonical level name (low, medium, …); NULL means no level was resolved; the driver then decides what to send. |
tool_calls | Spora\Models\ToolCall | Audit log of every tool invocation. Stores proposed_arguments, human_description (frozen at creation), approved_arguments, result. Status: PENDING → APPROVED / REJECTED (set on execution). Per-call rejection (migration 0062) adds rejected_at (timestamp), rejected_by (FK to users.id, onDelete SET NULL), and reject_reason (TEXT) — populated by Orchestrator::resume() when an entry in the per-call decision list has decision: 'reject'. The task-level reject() path does not write these columns. approvedBy() / rejectedBy() relations both target Spora\Models\User. |
task_history | Spora\Models\TaskHistory | Append-only LLM conversation history. Ordered by sequence. content nullable (assistant tool-call messages have no text). content_blocks (JSON) holds the structured blocks (text, thinking, redacted_thinking, tool_use) — supersedes the old reasoning column. summarized_sequence_range records compaction (migration 0045). attachments (JSON, nullable — migration 0057) holds a list of {media_id, kind} archive references: the operator’s attachment on an attachment row, the tool-result image channel on a tool row. The row stores the reference, never the bytes. |
usage | Spora\Models\Usage | 1:1 with task_history. Per-message token accounting (input_tokens, output_tokens, reasoning_tokens, cached_tokens, cache_creation_tokens, cache_read_tokens) + provider, raw_usage and driver_meta_info. Added by migration 0061. |
llm_driver_configurations | Spora\Models\LLMDriverConfiguration | Per-principal LLM driver configs (principal_id nullable FK to principals.id after migration 0067; was user_id before). principal_id IS NULL marks a global config (is_global = true) — LLMDriverConfiguration::validateGlobalXor enforces the XOR. settings is encrypted JSON. is_default marks the row as its owner’s default: the installation’s on a global row, the principal’s on a principal-owned row, one per scope. context_window and max_tokens_output override defaults. |
notifications | Spora\Models\Notification | User notification inbox. type in {task_completed, task_failed, pending_approval, scheduled_run_completed}. data is MEDIUMTEXT and carries {task_id, agent_id} (plus run_id for scheduled_run_completed). read_at marks read state. |
agent_prompt_templates | Spora\Models\AgentPromptTemplate | Reusable prompt templates per agent. Stores prompt_template with Mustache vars, variables (native JSON), max_steps override, effort override. |
scheduled_runs | Spora\Models\ScheduledRun | Scheduled or one-shot task triggers. Stores cron_expression or run_at, template_id FK, effort_override, next_run_at precomputed. scheduled_runs_next holds one concrete due execution per row. All timestamp columns (run_at, next_run_at, last_run_at, created_at, updated_at) are stored in UTC; the timezone column is the user-chosen IANA id (UTC if omitted) used as the reference frame for cron_expression evaluation and run_at anchoring, not a storage format. UTC timestamps mean the worker can compare due_at (on the sibling scheduled_runs_next table) against wall-clock UTC on any host regardless of the OS timezone — see Worker deployment → Cron Mode. |
scheduled_runs_next | Spora\Models\ScheduledRunNext | One row per concrete scheduled execution. Status enum: PENDING → CLAIMED → DONE / SKIPPED. Atomic claim: UPDATE scheduled_runs_next SET status = 'CLAIMED' WHERE status = 'PENDING' AND due_at <= $now LIMIT 1. Unique (scheduled_run_id, due_at) prevents duplicates. next_run_at on scheduled_runs is a cached derivative updated whenever a new PENDING row is inserted. All timestamp columns (due_at, claimed_at, completed_at, created_at, updated_at) are stored in UTC. |
principal_locations | Spora\Models\PrincipalLocation | Saved locations, scoped to a principal — a person or a group (migration 0099). principal_id FK to principals.id with ON DELETE CASCADE, name (≤ 100), address (text), is_default (boolean). One principal may hold several locations; setting is_default clears the flag on the others in the same principal. It replaces user_locations, which migration 0099 copied into this table and dropped. |
tool_user_settings | Spora\Models\ToolUserSetting | Per-principal tool settings overrides (NOT NULL principal_id FK to principals.id after migration 0067; was user_id before). Merged between global and agent overrides by ToolConfigService. |
principal_preferences | Spora\Models\PrincipalPreference | Per-principal LLM-driver preference (preferred_llm_config_id FK). One row per principal, carrying the speech-to-text preference (preferred_speech_config_id) alongside it — clearing the LLM preference nulls the LLM column only, so the row and the speech preference stay. Renamed from user_preferences in migration 0067 — agents and tool_user_settings now key on principal_id instead of user_id, so the row’s natural key is the principal id, not the user id. A group principal can carry its own preferred_llm_config_id that differs from any member’s user-principal. |
principals | Spora\Models\Principal | Unified ownership pointer (added in migration 0067). type enum ∈ {user, group}; exactly one of user_id / group_id is non-null. UNIQUE(user_id) and UNIQUE(group_id) prevent duplicates. One row is bulk-inserted per user during migration 0067 (idempotent via the unique index + INSERT OR IGNORE); PrincipalService::ensureUserPrincipal() materialises the caller’s row on demand if missing. agents, tool_user_settings, principal_preferences, and llm_driver_configurations all FK into this table — it is the single ownership axis across the application. |
groups | Spora\Models\Group | Operator-owned container (added in migration 0067). name (≤ 120), description (≤ 500), information (MEDIUMTEXT, nullable — added in migration 0100), created_by_user_id FK to users (RESTRICT on delete). description is the short blurb the group lists show; information is the rich, Markdown-formatted “about the organisation” block, and an agent can read both. Groups materialise a 1:1 group-principal on creation (PrincipalService::materialiseGroupPrincipal); deleting the group cascades into the group-principal via ON DELETE CASCADE. |
group_memberships | Spora\Models\GroupMembership | Junction: group_id × user_id with role enum ∈ {owner, admin, member} (default member). UNIQUE(group_id, user_id) prevents duplicate rows. group_id FK is CASCADE on delete; user_id FK is CASCADE on delete. |
group_pictures | Spora\Models\GroupPicture | 1:1 with groups (migration 0068). Mirrors agent_pictures: either an archetype avatar (archetype / variant_key / palette_key) or an uploaded image (media_asset_id FK with NULL ON DELETE). The XOR invariant is enforced in GroupPictureService, not at the DB level. Migration 0069 backfills a default row for every existing group (collaborative / null / slate). |
mail_templates | Spora\Models\MailTemplate | Editable email templates. Rendered with {{var}} placeholders. |
memories | Spora\Models\Memory | Per-agent (or global) persistent memory entries. content is LONGTEXT. |
settings | — | The runtime settings registry (migration 0092) — the layer that lets an admin change a setting from the SPA instead of editing a file. One row per saved override: group_key, setting_key, value, encrypted, updated_by, with UNIQUE(group_key, setting_key). A row here is what makes the database layer win over config.php and the environment for every key that is not read before the database opens. encrypted is an explicit column rather than a sniff, so a short plaintext secret is never misread as ciphertext; updated_by is ON DELETE SET NULL, so deleting the account that set a setting does not delete the setting. |
api_keys | Spora\Models\ApiKey | One credential for one of the three API scopes (migration 0093, renamed and widened in 0098), presented as spk_<id>_<secret>. id is the primary key — the random hex that appears in the key string — so verification is one indexed lookup and key ids cannot be walked. secret_hash holds the SHA-256 hex digest of the secret half; the plaintext is never stored and no endpoint can return it. last_used_at records the last request the key authenticated, at minute granularity. created_by is the user who minted the key — nullable, and ON DELETE SET NULL, so deleting that account leaves the key alive but unowned. The global scope depends on that column: a group created through the global API is owned by the key’s created_by user, and a key with no owner to create a group with answers 403. scope says what the key may reach — agent, group or global — and which of agent_id / group_id names the target; the rule is enforced in code, not by a CHECK constraint, because SQLite and MySQL spell those differently. agent_id and group_id both cascade on delete. |
api_callbacks | Spora\Models\ApiCallback | The callback outbox — one row per chat started with a callback_url, holding the status the receiver is still owed (migration 0094, renamed in 0098). Written while the task is still QUEUED, so delivery needs no task-lifecycle hook. pending_status is what is owed, delivered_status is what the receiver last acknowledged, and the pair is what lets a chat that settles twice deliver twice while a failed POST only retries. chat_id and key_id both cascade on delete. |
media_scope_materialisations | — | The marker table migration 0105 writes. One row per agent the migration materialised the media tool’s scope: 'agent' for: agent_id (primary key), prior_settings (text, nullable — the settings the agent’s agent_tool_overrides row held before the migration wrote to it, NULL when that row did not exist), created_at (nullable). The migration’s down() reads these rows to restore exactly the override rows it wrote and then drops the table, so a scope an operator set by hand is never reversed. No Eloquent model — the migration writes the table directly. |
Mail templates
Migration 0065_rename_body_text_to_body_in_mail_templates.php renames the stored body_text column to body without changing its SQL type or contents. body now contains CommonMark Markdown rather than a pre-rendered plain-text alternative. body_html is an optional trusted HTML shell and may contain the {markdown_html} injection token.
There is no stored body_text field after migration 0065. Plain text is derived from the rendered Markdown at send or preview time.
Key Decisions
Nullable TINYINT columns must NOT use Eloquent boolean cast — (bool) null === false collapses “use class default” into “OFF”, breaking three-state semantics. agent_tool_operation_overrides.enabled and default_requires_approval both rely on this.
TEXT not JSON columns — SQLite has no JSON type. TEXT + $casts is the only cross-engine approach for SQLite, MySQL 5.7, and MariaDB 10.4. (The one exception is agent_prompt_templates.variables, a native json column — kept narrow on purpose.)
pending_state is MEDIUMTEXT — full conversation history at high step counts exceeds MySQL TEXT’s 65,535-byte cap. (tasks.data and notifications.data are also MEDIUMTEXT for the same reason.)
human_description stored at creation — frozen so approval UI stays correct even after a plugin is removed or updated.
Both tool_name and tool_class stored in tool_calls — tool_name is what the LLM uses; tool_class is what PHP uses to instantiate. Both needed for unambiguous resolution and audit.
tasks.effort is nullable and never holds an empty string — it carries the reasoning effort resolved for the task, and NULL means no level was resolved. An empty string would be a second way of saying “not set”, which is exactly the ambiguity the column exists to remove. NULL does not mean “nothing is sent”: it means the driver’s own rules decide what to send, and one of them sends an explicit level of its own — see Concepts → LLM drivers.
The effort columns are string(16) and nullable — agents.default_effort, agent_prompt_templates.effort and scheduled_runs.effort_override, each a level name and each nullable. The cap is 16 characters because the name has to fit the same width as tasks.effort; widening that column is a full table rebuild on SQLite. A nullable effort column means inherit, not “the model’s own default”: the agent’s column falls back to the configuration’s default, the template’s falls back to the agent’s, and the run’s falls back to the template’s. The chain and the fallbacks are in Concepts → Reasoning effort. Schedule timestamps are UTC — scheduled_runs.run_at, next_run_at, last_run_at, created_at, updated_at and every column on scheduled_runs_next (due_at, claimed_at, completed_at, created_at, updated_at) are stored in UTC. The scheduled_runs.timezone column is the IANA reference frame the scheduler uses to evaluate cron_expression and anchor offset-less run_at strings — not a per-row storage format. The worker pins UTC internally before any due_at <= $now comparison (see Worker deployment), so a shared-host operator never has to configure their PHP date.timezone ini to match their schedule.
Migration order (on disk): users (+ auth) → agents → tool_configurations / agent_tools / agent_tool_overrides → tasks → tool_calls → task_history → usage → llm_driver_configurations → notifications → agent_prompt_templates / scheduled_runs → scheduled_runs_next → agent_tool_operation_overrides → tool_user_settings / user_preferences / mail_templates / memories → principal_locations (plus assorted column-altering migrations interleaved). The version number in the stamp hash is the highest numbered filename.
Migration 0067 (introduce_principals_and_groups) is forward-only. The down() method is a no-op: the user_preferences → principal_preferences rename, the bulk-inserted user-principal rows, and the FK swap on agents cannot be losslessly reversed. Operators who need to roll back must restore from a backup taken before the upgrade. The migration runs the column swap outside any transaction so SQLite’s PRAGMA foreign_keys = OFF actually takes effect — without that, the table rebuild would cascade-delete every dependent row (tasks, task_history, tool_calls, agent_tools, the override tables, scheduled_runs, scheduled_runs_next, agent_prompt_templates, agent_pictures, usage). The pragma state is read back after each OFF / ON and the migration throws if the pragma was silently ignored.
Migrations 0068 / 0069 are also forward-only (creating / backfilling group_pictures); both have no-op down() methods.
Locations belong to the principal, not to the user — principal_locations is keyed on principal_id, so a group’s saved addresses are the group’s and not the first owner’s. Migration 0099 copied the user_locations rows into the table and dropped the old one; that copy is a one-way door for an external consumer.
Rolling migration 0099 back deletes every group location. Its down() recreates user_locations, copies back only the rows whose principal is a user principal, and then drops principal_locations — a group’s saved addresses have no user-scoped home, so they are gone. Take a backup before rolling this migration back; nothing recovers them afterwards.
groups.information is not groups.description — description is the short blurb a group list shows and that is set at creation; information is the rich Markdown block that says how to reach the organisation. An agent can read both, and folding them into one column would have thrown away the longer of the two.
Agent ownership transfer: an agent’s principal_id is mutable via POST /api/v1/agents/{id}/transfer. agents.principal_id FK uses ON DELETE RESTRICT — deleting a principal surfaces a structured 409 from the controller so the operator can re-target the orphan agents first; the controller response carries agent_ids and reassign_endpoint: /api/v1/agents/{id}/transfer.
Database Schema Installer
All database tables are created and upgraded automatically by Spora\Core\DatabaseSchemaInstaller during application boot. This mechanism wraps Laravel’s Migrator but is optimized for Spora’s zero-config, plugin-heavy environment:
- Auto-derived core version: The core schema version is derived at runtime by scanning
database/migrations/for the highest-numbered file. There is noCORE_VERSIONconstant to bump — adding a new migration file (e.g.0050_new_feature.php) automatically increments the effective version. - O(1) Hot Path Cache:
install()is called on every application boot. To prevent executing multiple database queries per request, it computes a composite version hash (core_v49|plugin-a_v2|plugin-b_v1) and compares it to a local filesystem stamp (storage/.schema_stamp). If the hash matches, the installer returns immediately (0 DB queries). - Component isolation: Each plugin (and the Core itself) has a tracked version in the
schema_versionstable. Plugins declare a staticschemaVersion()in their manifest — see the Plugin system page. - Migration file format: Migrations should use zero-padded numbers (e.g.
000001_create_table.php), an anonymous class pattern (return new class extends Migration {}), and directly useCapsule::schema()instead of the LaravelSchemafacade. - Plugin Migration Constraints: Plugin migration files must be globally prefixed with the plugin’s slug (
{slug}_000001_name.php) to avoid file collision in the sharedmigrationstracking table.RuntimeExceptionis thrown if this is violated. - Boot Lifecycle:
Database::getCapsule()exposes the static Eloquent capsule afterbootDatabaseConnectionOnly()to allow the Installer to retrieve theDatabaseManagerbefore the rest of the application loads.
Schema Installer API (for UI Install Script)
For shared-host deployments that cannot run CLI commands, invoke the installer directly from PHP:
use Spora\Core\Database;
use Spora\Core\DatabaseSchemaInstaller;
Database::boot(); // runs install() automatically
// Or manually:
$installer = new DatabaseSchemaInstaller(pluginLoader: null, stampPath: null);
$installer->install();The DatabaseSchemaInstaller constructor accepts:
$pluginLoader— passnullduring early install before plugins are loaded$stampPath— passnullto force migrations to run (no stamp caching), useful for one-shot install scripts
After pulling new code, touching the storage/.schema_stamp file (e.g. deleting it) will force the installer to re-run all migrations on the next boot.