Persistence and domain models
Semaphore stores instance settings, users, projects, project resources, run history, and execution state in one database-backed store. The persisted models connect project configuration to the content and automation described in Project configuration and content, while tasks and workflow runs connect that configuration to runners and external repositories.
Persistence boundary
Database store
The database store is the common persistence boundary for the server. It exposes one Store contract made from smaller contracts for users, projects, resources, MCP servers, tasks, schedules, runners, secrets, roles, sessions, tokens, events, and audit data. The SQL store supports SQLite, MySQL, and PostgreSQL. BoltDB is no longer supported from version 2.19. db/Store.go db/Store.go
The store keeps the same domain shape across supported database engines. It also controls reads that depend on project ownership, user visibility, pagination, and related-object checks. This lets API and service code work with domain objects instead of database-specific rules. db/Store.go db/…/SqlDb.go
Mutation paths confirm that a requested delete removed a row. This gives callers and audit records a clear not-found result instead of treating a missing row as a successful delete. Token lookup may use a sufficiently long prefix, but token deletion remains an exact-ID operation. db/…/SqlDb.go db/…/session_test.go
References: db/Store.go• L45-80 db/Store.go• L307-337 db/Store.go• L633-727 db/…/SqlDb.go• L310-350 db/…/SqlDb.go• L476-500 db/…/session_test.go• L11-34
Configuration options
Configuration has two sources with different roles. Deployment configuration selects the database and supplies process settings. Database options provide stored instance settings, which are read as flat keys and mapped into the running configuration at startup. db/config.go db/Store.go
The option model is intentionally small: a key and a string value. Keys use dotted names so related settings can become nested configuration values. Invalid key names are rejected before they become part of the stored configuration. db/Option.go
References: db/config.go• L9-47 db/Option.go• L8-24 db/Store.go• L210-217
Schema migrations
Migrations move an existing database from one schema version to the next without requiring a fresh install. The migration list is selected by database dialect, each applied version is recorded in the migrations table, and SQL is adapted for SQLite, MySQL, or PostgreSQL before execution. db/Migration.go db/…/migration.go db/…/migration.go
Each migration runs in a transaction and can have a small pre- or post-step when data must be changed before or after the schema change. Rollback SQL is optional. Some SQLite table rebuilds temporarily change foreign-key handling because referenced tables cannot be rebuilt safely while those checks are active. db/…/migration.go db/…/migration.go
Recent schema changes add the host registry, managed-inventory host data, view template statistics, and Model Context Protocol (MCP) server data for agent inventories. The host registry migration also backfills hosts from prior task records. The MCP migration adds one inventory-scoped server table and links each server's optional token to the access-key table. db/Migration.go db/…/v2.20.19.sql db/…/v2.20.20.sql db/…/v2.21.0.sql db/…/v2.21.6.sql
The later schema changes let schedules target either a template or a workflow. They also persist the source and mode of a workflow re-run, plus the nodes carried from the earlier run. Migration 2.21.3 preserves existing schedule and task links while it changes the schedule shape. Migration 2.21.5 adds the workflow re-run state. db/Migration.go db/…/v2.21.3.sql db/…/v2.21.3.err.sql db/…/v2.21.5.sql
The migration list is part of the storage contract. A schema change is complete only when the version list, forward SQL, any data conversion, and any supported rollback agree. db/Migration.go db/…/SqlDb.go
References: db/Migration.go• L15-31 db/Migration.go• L108-163 db/…/migration.go• L215-305 db/…/migration.go• L308-385 db/…/v2.20.19.sql• L1-110 db/…/v2.20.20.sql• L1-19 db/…/v2.21.0.sql• L1-24 db/…/v2.21.6.sql• L1-6 db/…/v2.21.3.sql• L1-40 db/…/v2.21.3.err.sql• L1-40 db/…/v2.21.5.sql• L1-25
Events and exported identity
Events record actions or execution information with links to a user, project, integration, and affected object. The event object type identifies the kind of persisted object, so event views can relate a record to a task, inventory, inventory host, view, template, or other domain object. db/Event.go db/Event.go
The export layer gives persisted entities a stable database key while a project moves between stores. These keys support the ID mapping used by backup and restore rather than exposing database IDs as portable references. db/ExportEntityType.go db/ExportEntityType.go db/ExportEntityType.go
References: db/Event.go• L9-24 db/Event.go• L53-74 db/ExportEntityType.go• L7-15 db/ExportEntityType.go• L49-67 db/ExportEntityType.go• L81-115
Project domain
Projects and users
A project is the top-level scope for configuration and execution. It holds its name and run limits, links to a default secret store, and owns the repositories, inventories, environments, templates, schedules, runners, and other resources used by its tasks. db/Project.go db/Store.go
Users are instance-level identities. A user may be a local or external identity and may be an administrator. Project membership is stored separately from the user record so one user can belong to many projects. Project invites provide a temporary path to add a user to a project. db/User.go db/ProjectUser.go db/Store.go
The project is also the main ownership boundary for access checks and deletion. Removing a project removes its project-owned configuration and execution links as one operation rather than leaving detached resources. db/…/project.go
References: db/Project.go• L7-17 db/User.go• L10-25 db/ProjectUser.go• L52-61 db/…/project.go• L77-131
Roles and access
Access is represented by roles and assignments rather than by copying permission flags onto each resource. Project roles grant project actions and may be shared across projects. Global roles grant instance actions and stay separate from project roles. db/Role.go db/Role.go
Project membership joins users to projects and roles. A role can also grant access to one template or workflow. Identity-provider group mappings can add project roles when a user signs in through an external identity provider. The effective permission set is the union of the applicable grants, with administrators receiving all global permissions. db/Role.go db/RoleMapping.go db/Store.go
References: db/Role.go• L48-67 db/Role.go• L137-167 db/Role.go• L183-216 db/RoleMapping.go• L5-35 db/Store.go• L605-631
Repositories and inventories
Repositories identify the source code used by a project. A repository records its URL, branch, access key, and whether templates share one checkout. Inventory records describe host or workspace input for an application. An inventory can be stored as project data or point to a repository file. db/Repository.go db/Inventory.go
These models provide source and target context for a template. The repository supplies the code and branch. The inventory supplies the hosts or workspace. Access keys and host mappings supply credentials for the main repository and related sources. The preparation of repository content is described in Repository and automation content. db/HostConfig.go db/Store.go
Managed inventories can also store shared variables and a set of named inventory hosts. Each inventory host has its own description, enabled state, and variable text. Host names are unique within one inventory, and only enabled hosts are returned when a run needs the active set. db/Inventory.go db/InventoryHost.go db/Store.go db/…/inventory_host.go
References: db/Repository.go• L19-44 db/Inventory.go• L5-55 db/InventoryHost.go• L18-28 db/HostConfig.go• L24-41 db/Store.go• L295-356 db/…/inventory_host.go• L30-84
MCP inventories
An MCP inventory is a project-scoped list of remote Model Context Protocol servers for an AI agent template. Each server has a name, an HTTP or HTTPS endpoint, and an enabled state. The server list is inventory content, while each optional authorization token is stored as a separate access key that is hidden from normal project-key views. db/Inventory.go db/InventoryMcp.go db/…/v2.21.0.sql
The store treats the server list and its tokens as one change. A complete replacement can add, edit, or remove servers, and a removed server takes its token with it. Reads that need both pieces use one database statement so a server is not paired with a token from a different edit. db/Store.go db/…/inventory_mcp.go db/…/inventory_mcp.go
References: db/Inventory.go• L5-20 db/InventoryMcp.go• L14-38 db/Store.go• L307-337 db/…/inventory_mcp.go• L13-60 db/…/inventory_mcp.go• L139-169 db/…/inventory_mcp.go• L289-440 db/…/v2.21.0.sql• L1-24
Environments and views
An environment is a named group of extra variables for task execution. It can hold JSON values, process environment values, and links to secrets. Templates may use several environments, which are combined when a task starts. db/Environment.go db/Template.go
A view is a saved project list and sort choice. It organizes how templates appear to users but does not change the task definition. A view can also request counts of its templates grouped by the status of each template's latest task. The counts are optional because they require extra task lookups, and they respect the viewer's template access. db/View.go db/View.go db/…/view.go
References: db/Environment.go• L45-66 db/Template.go• L327-336 db/View.go• L15-29 db/View.go• L75-121 db/…/view.go• L26-61
Host registry
The host registry is a cross-run record of hosts seen during automation. It keeps global host identity and aggregate run status, then relates each host to the projects and templates that used it. This is different from InventoryHost, which is a configured member of one managed inventory. db/HostStore_pro.go db/HostStore_pro.go
The registry supports project and global host lists, host task history, active-host counts, and decommissioning. The first registry migration derives its records from past task host results and ignores local connection names. db/HostStore_pro.go db/…/v2.20.19.sql
References: db/HostStore_pro.go• L12-30 db/HostStore_pro.go• L47-87 db/…/v2.20.19.sql• L52-110
Execution domain
Templates and task parameters
A template is the reusable definition of an executable project action. It joins a repository to an optional inventory and one or more environments. It also records the application type, entry file or directory, run options, survey inputs, version behavior, and runner selection. db/Template.go db/Template.go
Templates support application actions such as Ansible, Terraform-family tools, scripts, and AI agent CLIs. Agent templates use an MCP inventory for their remote tool servers and persist a prompt with an optional task-level override. db/Template.go db/Template.go db/Template_app_test.go
Task parameters are the reusable run-time overrides shared by schedules and other launch paths. A task is the concrete execution record created from a template. It captures the selected source revision, inputs, status, owner, schedule or workflow link, timing, and result metadata. db/TaskParams.go db/Task.go
Task output, stages, and stage results extend the task record into an execution history. This history supports live progress, final results, task pages, and retention of output without changing the template that created the task. Task history can be read by project, template, or workflow run. Lists use a cursor based on task ID so older history remains practical to read as it grows. db/Task.go db/Store.go db/…/task.go
References: db/Template.go• L17-65 db/Template.go• L307-313 db/Template.go• L319-415 db/Template_app_test.go• L53-67 db/TaskParams.go• L3-37 db/Task.go• L46-110 db/Task.go• L263-305 db/…/task.go• L274-356
Workflows and runs
A workflow is a graph of task, approval, note, and delay nodes. Edges describe when a next node may run and how outputs can become inputs. The workflow also owns survey inputs that are collected before a run. db/Workflow.go db/Workflow.go db/Workflow.go
Workflow graphs use immutable revisions. Saving a workflow creates a new revision, while a run pins the revision it started from. This keeps a running or historic run tied to the graph that produced it even after the workflow is edited. A run stores its status, collected environment, timing, and root task link. db/Workflow.go db/Workflow.go
Approvals and delays are persisted as run state. They allow the workflow engine to stop at a human decision or a future time and then continue without losing the run's place in the graph. db/Workflow.go db/Workflow.go
A failed-only re-run creates a new run that points to the run it repeats. Carry rows mark the nodes that count as complete without running again, while the new run still uses the pinned graph revision and stored environment. The store creates the new run and its carry state together so the workflow engine never sees a partial re-run. db/Workflow.go db/WorkflowStore_pro.go db/…/v2.21.5.sql
References: db/Workflow.go• L10-54 db/Workflow.go• L86-120 db/Workflow.go• L122-149 db/Workflow.go• L151-202 db/Workflow.go• L220-247 db/Workflow.go• L269-351 db/WorkflowStore_pro.go• L27-40 db/…/v2.21.5.sql• L1-25
Schedules and runners
A schedule starts either a template task or a workflow run at a recurring time or at one specified time. Exactly one target is required. A workflow schedule does not use template task parameters and cannot act as a repository commit checker. It may delete itself after a one-time run. db/Schedule.go db/Schedule.go db/…/schedule.go
A runner is an execution target. It may belong to a project or be global, and it uses tags, activity, and capacity to determine whether it can receive work. Authentication tokens and registration data are stored separately from the runner status shown to users. db/Runner.go db/Runner.go
The schedule store checks that its target belongs to the same project. This closes a gap that foreign keys alone cannot close because an ID can be valid in another project. The task points to its selected runner while it is assigned, so the runner links durable task history to the live execution system without becoming the owner of the task definition. db/…/integration.go db/…/schedule.go db/Task.go db/Store.go
References: db/Schedule.go• L14-38 db/Schedule.go• L49-70 db/…/schedule.go• L10-65 db/…/integration.go• L11-47 db/Runner.go• L30-67 db/Runner.go• L84-107 db/Task.go• L66-77
Secret and credential domain
Access keys
An access key is a named credential used by a repository, inventory, host mapping, environment, secret store, MCP server, or one task. The model supports SSH keys, login and password pairs, strings, and an explicit no-key type. Secret material is kept out of normal API output and may be owned by a narrower scope than the project. db/AccessKey.go db/AccessKey.go
MCP server tokens are access keys owned by one server rather than general project keys. The inventory store creates and changes them with the server so callers cannot redirect a token to another project or server. db/AccessKey.go db/…/access_key.go db/…/inventory_mcp.go
Task survey secrets use short-lived task-owned access keys. This gives a task its secret inputs without making those values part of the durable task parameters or the project secret list. db/AccessKey.go db/Store.go
References: db/AccessKey.go• L8-32 db/AccessKey.go• L49-107 db/…/access_key.go• L115-122 db/…/inventory_mcp.go• L395-440 db/Store.go• L337-383 db/Store.go• L390-459
Secret storages and synchronization
A secret storage describes where a project can read secrets. It records the storage type, connection parameters, and whether the storage is read-only. Local and external stores are represented by the same project-level model. db/SecretStorage.go
Secret synchronization is a separate persisted relationship between a storage and either the project or an environment. It records whether sync is active, its interval, its last result, and the paths to import. The API combines these sync rows with the storage or environment when it returns those models. db/SecretSync.go db/…/secret_storage.go db/…/environment.go
References: db/SecretStorage.go• L5-35 db/SecretSync.go• L5-30 db/…/secret_storage.go• L103-138 db/…/environment.go• L151-172
Persistence relationships
Configuration-to-task flow
The persisted model links stable project configuration to one concrete run. The task keeps the selected revision and input state so later reads describe what ran, not only what the template says now.
This diagram shows how project inputs become a task or workflow run and then become durable execution history.
flowchart LR
User[User and roles] --> Project[Project]
Project --> Repo[Repository]
Project --> Inventory[Inventory]
Project --> Env[Environment]
Project --> Template[Template]
Repo --> Template
Inventory --> Template
Env --> Template
Template --> Schedule[Schedule]
Template --> Task[Task]
Template --> Workflow[Workflow revision]
Workflow --> Run[Workflow run]
Schedule --> Workflow
Run --> Task
Task --> Runner[Runner]
Task --> Output[Task output and stages]
Project --> Secrets[Secret storage and access keys]
A template supplies reusable intent. A schedule or workflow supplies the launch context. A task records template execution, while a workflow run records graph execution and links to its root task. The runner performs the task, and task output records the result for users and later automation. db/Template.go db/Task.go db/Workflow.go db/Schedule.go
References: db/Template.go• L319-415 db/Schedule.go• L14-38 db/Workflow.go• L263-294 db/Task.go• L46-110 db/Runner.go• L30-67
Backup-facing model shape
Persisted models are not all exported in the same form. Some fields are database IDs or runtime-only joins. Other fields are the portable content needed to recreate a project. Backup and restore therefore depend on the model's export markers and on the project migration path rather than on copying every database row directly. db/Project.go db/Template.go db/Workflow.go db/ExportEntityType.go
Project migration loads the old store through the export layer, maps old IDs to new IDs, and restores the project into the new store. This keeps references between users, resources, templates, workflows, and tasks coherent when the storage target changes. See Project backup and restore for the transfer flow.
References: db/…/migration.go• L8-40 db/ExportEntityType.go• L23-67 db/Project.go• L7-17 db/Template.go• L319-415 db/Workflow.go• L86-120
Change checklist
When these files or sections are changed, remember to consider these:
- Add a new migration version to the dialect-aware version list and provide the matching embedded SQL and rollback SQL when supported.
- Keep model fields, SQL table mappings, migration columns, and backup markers aligned. A field that is readable but not restorable can silently break project transfer.
- When changing ownership or deletion rules, review project deletion, object reference checks, foreign keys, and role grants together.
- When changing managed inventory data, keep inventory variables, child-host scope, enabled-host reads, and the inventory migration aligned.
- When changing MCP inventory data, keep server validation, inventory type selection, project scope, token ownership, one-token uniqueness, and transactional replacement aligned.
- When changing template or workflow inputs, preserve the stored JSON shape and the link from the run or task to the exact input and graph revision used.
- When changing agent templates, keep the app whitelist, MCP inventory type, prompt rules, and task prompt override behavior aligned.
- When changing schedule targets, preserve the exactly-one-of-template-or-workflow rule, same-project target check, and removal of template task parameters for workflow schedules.
- When changing workflow re-runs, keep the run link, carry rows, node identity, and task deletion behavior aligned. Create the run and carry state atomically.
- When adding a secret source, keep the source reference separate from secret values and update the sync projection for storage and environment reads.
- When changing task, view, or runner links, preserve the distinction between durable task history, latest-task summaries, and transient runner assignment or liveness.
- When changing host identity or event object types, keep historical task links, project/template summaries, and object-name lookup behavior compatible.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A migration version is listed without its embedded SQL | Startup cannot complete the schema upgrade | Keep the version list and db/sql/migrations files in the same change |
| The MCP migration is applied without its unique server and token links | Servers can be duplicated or tokens can outlive their server | Keep the inventory foreign key, token foreign key, and unique indexes together |
| A host registry migration does not backfill or link old task hosts correctly | Historical host pages show missing runs or wrong status | Verify the host, project, template, and task-host links during migration |
| An inventory host is read without both project and inventory scope | A host from another inventory can be exposed or changed | Keep both ownership checks in inventory-host reads and writes |
| An MCP server uses an invalid name, URL, or duplicate name | Agent configuration cannot identify the server safely or the inventory write fails | Validate names and remote URLs before the transaction and enforce inventory-local uniqueness |
| An MCP token is written through the general access-key path | The token is rejected or can lose its server ownership | Create and update MCP tokens only through the inventory store |
| An MCP server list and token list are read in separate snapshots | A server can be paired with a token from a different edit | Read the pair in one statement and replace both in one transaction |
| A workflow run does not pin its graph revision | Editing a workflow can change the graph read by an active or historic run | Persist and read the run's RevisionID |
| A schedule points to a target in another project | A webhook or scheduler can start another project's template or workflow | Validate the target with both its ID and project ID |
| A schedule stores both targets or neither target | The scheduler cannot decide whether to launch a task or workflow run | Enforce the schedule target invariant before writing the row |
| A failed-only re-run omits its carry rows or creates them later | Nodes that should be reused run again or appear not started | Create the run and all carry rows in one transaction |
| A project-owned child is removed without its dependent links | Foreign-key errors or orphaned references block deletion or hide resources | Use project-scoped delete paths and review reference tables |
| View counts use an old task instead of each template's latest task | The project tab shows stale status totals | Use the latest task for the same template and apply viewer visibility |
| Secret sync fields are written only to the storage or environment row | The UI shows sync settings that the sync worker cannot find | Persist the related SecretSync row and reload it with the parent model |
| A task stores secret survey values in ordinary task parameters | Secret data becomes visible in durable task history | Use a task-owned, expiring access key for survey secrets |
| A template or workflow field changes without a backup mapping | Restored projects lose configuration or fail to reconnect references | Review export markers and the restore key mapper with the model change |
Key files
| File | Why to read it |
|---|---|
| db/Store.go | Defines the persistence boundary and the domain manager contracts. |
| db/…/SqlDb.go | Shows supported SQL dialects, table registration, ownership checks, and connection setup. |
| db/Migration.go | Defines the ordered schema version set. |
| db/…/migration.go | Shows how migrations are loaded, adapted, applied, and recorded. |
| db/Project.go | Defines the project ownership boundary. |
| db/User.go and db/Role.go | Define identity and permission models. |
| db/Repository.go, db/Inventory.go, and db/InventoryHost.go | Define source code and managed inventory inputs used by templates. |
| db/InventoryMcp.go and db/…/inventory_mcp.go | Define remote MCP servers and their atomic server-token changes. |
| db/HostStore_pro.go | Defines the cross-run host registry and its project and template links. |
| db/Environment.go and db/View.go | Define task variables and the saved template views shown to users. |
| db/Template.go and db/TaskParams.go | Define reusable execution intent, application types, prompts, and launch overrides. |
| db/Task.go and db/…/task.go | Define durable task state, output, stage history, and task reads. |
| db/Workflow.go and db/WorkflowStore_pro.go | Define workflow graphs, revisions, runs, approvals, delays, and re-run carry state. |
| db/Schedule.go and db/…/schedule.go | Define schedule targets, timing, launch parameters, and target checks. |
| db/…/integration.go | Defines the shared project ownership check for scheduled and integrated run targets. |
| db/Runner.go | Defines task execution targets. |
| db/AccessKey.go, db/SecretStorage.go, and db/SecretSync.go | Define credential ownership and external secret synchronization. |
| db/Event.go and db/ExportEntityType.go | Define event object links and portable entity identity. |
| db/…/v2.20.19.sql, v2.20.20.sql, and v2.21.6.sql | Show the host registry, managed inventory, and view statistics schema changes. |
| db/…/v2.21.0.sql and v2.21.0.err.sql | Show MCP server and token schema changes and their rollback. |
| db/…/v2.21.3.sql, v2.21.3.err.sql, and v2.21.5.sql | Show schedule workflow targets and workflow re-run persistence changes. |
| db/…/migration.go | Shows how a project moves between stores during migration or restore. |