Skip to main content

Database Schema Domain Map

This document is a domain map of the Open ACE database. For column-level reference, the authoritative source is schema/schema-postgres.sql, which contains all 104 tables + 1 materialized view. When this document and that file disagree, the SQL file wins. Open ACE supports both SQLite (single-machine) and PostgreSQL (production); schema changes go through the Alembic migrations in migrations/versions/ (see SCHEMA_MIGRATION_GUIDE.md).

Domain Map — all 104 tables​

Every table defined in schema/schema-postgres.sql, grouped by domain, one line of responsibility each. Column-level details for the 46 most-used tables follow in Common tables in detail; for all other tables, see the SQL file.

Users & Authentication (8)​

TableResponsibility
usersCore accounts: role (platform_admin/tenant_admin/manager/user/readonly), tenant membership, soft delete, per-user token/request quotas, token-invalidation watermark
sessionsAPI auth sessions: token, user, expiry, active flag
web_user_auth_sessionsWeb UI session tokens with their own expiry lifecycle
user_permissionsPer-user permission overrides granted by an admin
role_permissionsRole → permission template rows backing RBAC checks
login_attemptsFailed-login counters powering account lockout
user_tool_accountsMapping of discovered tool/OS accounts to platform users (mapping source, status, verification)
tool_account_mapping_rulesUser-defined pattern rules that auto-map discovered tool accounts

Messages & Sessions (3)​

TableResponsibility
daily_messagesAnalytical fact table of every AI message across tools/hosts; not a Workspace runtime source (see the session data contract)
agent_sessionsAuthoritative Workspace session summary, one row per session
session_messagesAuthoritative Workspace transcript per session (source-tagged, idempotent by external_message_id)

The three session tables are governed by ../contracts/WORKSPACE_SESSION_DATA_CONTRACT.md, which defines the data boundary between them and the single product semantics of request_count.

Statistics & Metering (8)​

TableResponsibility
daily_statsPre-aggregated daily stats per tool/host/sender
hourly_statsHourly usage breakdown per tool/host
daily_usageTenant-scoped daily usage incl. cache tokens; sync target for autonomous usage
usage_summaryAll-time per-tool/host summary for dashboards
user_daily_statsPer-user daily aggregates
session_daily_usagePer-session, per-day incremental usage for long-running WebUI sessions (Issue #3338)
request_performanceRaw request performance events (TTFT, durations; Issue #3080)
response_time_statsPre-aggregated response-time percentiles per day/tool/host

Multi-Tenant (4)​

TableResponsibility
tenantsTenant registry: status, plan, billing cycle, over-limit strategy, soft delete
tenant_settings1:1 tenant settings: filters, audit/retention knobs, SSO, branding, allowed_tools
tenant_quotas1:1 tenant limits (token/request quotas, max users, max sessions per user)
tenant_usagePer-tenant daily usage counters

SSO (4)​

TableResponsibility
sso_providersSSO provider configs (oauth2/oidc/saml) with encrypted secrets, tenant-scoped
sso_identitiesProvider identity → local user links
sso_sessionsSSO session tokens with provider access/refresh tokens
sso_auth_statesShort-lived OAuth login-flow state (PKCE verifier, nonce) with TTL cleanup

Autonomous Development (8)​

TableResponsibility
agent_runsRun timeline anchor, 1:1 with agent_sessions (run_id == session_id)
agent_run_eventsAppend-only run event stream (run_id is a plain index, not an FK, by design)
agent_approvalsDurable permission request/response pairs keyed by request_id
autonomous_workflowsAutonomous dev workflow state: requirements, repo/PR binding, CI repair, retries, locks
workflow_eventsPer-workflow event log (optionally milestone-scoped)
workflow_milestonesMilestone/phase tracking per workflow: dev rounds, review sessions, GitHub issue/PR numbers
policy_rulesVersioned policy rule definitions with matchers
policy_decisionsPer-request policy evaluation audit trail

Compliance & Retention (5)​

TableResponsibility
retention_policiesPer-tenant, per-data-type retention rules (days, action, archive target)
retention_executionsEach retention run: status, locking, scanned/affected counts
retention_evidencePer-execution proof: before/after counts, archive location and checksum
legal_holdsLegal hold markers that block retention deletion
recycle_binSoft-deleted records awaiting expiry or restore

Notification & Integrations (5)​

TableResponsibility
webhook_settingsSingleton outbound-webhook config (encrypted secret, private-URL policy)
webhook_deliveriesPer-alert webhook delivery attempts with retry/cooldown state
dingtalk_settingsSingleton DingTalk integration config (encrypted signing key)
feishu_settingsSingleton Feishu integration config (verification status)
tenant_sensitive_keywordsTenant-scoped custom sensitive keywords (Issue #2789)

Scheduling & Operations (9)​

TableResponsibility
scheduler_runsPer-job scheduler execution history incl. lock strategy and fencing tokens (Issue #2187/#2333)
scheduler_leadersDistributed leader-election state per scheduler job
consistency_violationsDetected data drift with expected/actual values and repair status
deregister_failuresFailed session-termination batches during machine deregistration, replayed in background (Issue #2596)
parse_failure_recordsTool-output parse failures with retry tracking (Issue #2589)
config_import_stateImport state per config key when config moves into the database
schema_metadataSchema init/version marker used as a DB-level compatibility guard (Issue #2330)
tenant_migrationsTenant-move batches: affected users/sessions/projects and progress (Issue #2163)
mapping_migration_statusProgress bookkeeping for tool-account mapping backfills

Metering & Billing (10)​

TableResponsibility
tenant_plansPlan catalog: quota defaults, pricing, feature flags
tenant_period_historyPer-tenant period usage archived at each quota reset
usage_report_receiptsIdempotency receipts for remote usage reports (Issue #1891)
usage_report_rate_limitsSliding-window rate limiting for usage report ingestion
aggregation_historyTenant usage aggregation runs with quality report and error state
aggregation_locksDatabase-backed distributed locks for aggregation jobs
backfill_logsHistorical backfill job logs (counts, date range, status)
alerts_historyDelivery history of sent alerts (recipients, channels, status)
archive_filesArchived data files with checksum, record count and expiry
tenant_keywords_versionKeyword-list version counter per tenant for multi-process cache consistency

Security (7)​

TableResponsibility
proxy_token_jtisJTI registry for proxy tokens: single-use/replay protection (Issue #1758)
external_identity_noncesReplay-protection nonces for the external-identity HMAC probes (issuer + nonce + expiry; Issue #3459)
encryption_keysEncryption key metadata (fingerprint, status, rotation); plaintext lives in env vars, never in the DB
permission_checkpointsResumable checkpoints for async permission setup scans
permission_tasksAsync shared-project permission setup tasks with progress (Issue #2746)
tool_account_conflictsConflict events when tool-account mappings collide (Issue #2761)
test_execution_evidenceStructured per-command test verdicts (framework results, coverage)
command_execution_evidenceAuthoritative per-command execution record for autonomous runs

Remote Runtime (7)​

TableResponsibility
remote_machinesRegistered remote machines: capabilities, heartbeat, token revoke timeout
remote_runtime_commandsHTTP-polling command queue for remote agents (request/response)
remote_runtime_outputsPersistent SSE replay buffer per remote session
machine_assignmentsUser → machine permission assignments
agent_tokensHashed agent tokens with rotation, pending revoke and versioning (Issues #2499/#2530)
registration_tokensOne-time machine registration tokens (hash + consumption)
api_key_storeEncrypted AI provider API keys per tenant with CLI routing config

Other Domains (25)​

Governance & audit:

TableResponsibility
audit_logsPlatform audit trail (actor, action, severity, tenant resolution)
compliance_reportsGenerated compliance report payloads per period
insights_reportsAI-generated usage insight reports
anomaly_statusDeduplicated anomaly detection state with processing status
content_filter_rulesGlobal content filter rules
security_settingsSecurity configuration key-value store
retention_historyLegacy retention report snapshots (timestamp + report data)

Workspace & projects:

TableResponsibility
projectsRegistered project workspaces, tenant-scoped, with permission-setup status
user_projectsPer-user project rollups (sessions, tokens, requests, duration)
project_categoriesProject category dictionary
prompt_templatesReusable prompt templates; name is unique for idempotent seeding (Issue #2577)

Alerting & quotas:

TableResponsibility
alertsUser-facing alert inbox with action links
quota_usagePer-user, per-period (and per-tool) quota consumption
quota_alertsQuota threshold alerts with acknowledgment tracking
notification_preferencesPer-user notification channels (email/push/webhook, severity floor)

Collaboration & sync:

TableResponsibility
teamsTeams with settings
team_membersTeam membership with roles
shared_sessionsSession share links with permissions and access counters
knowledge_baseTeam knowledge-base entries
annotationsSession/message annotations with threading
sync_eventsMulti-source sync event log

Platform settings:

TableResponsibility
ai_agent_settingsAI agent configuration key-value store
model_gateway_configSingleton LiteLLM-compatible model gateway config
smtp_settingsSMTP relay config with encrypted password
email_notification_logsEmail delivery attempts with retry state

Common tables in detail (46 tables)​

The tables below are the ones most referenced in code and docs, with condensed column-level detail. All other tables (the remaining 58 of the 104) are documented only by schema/schema-postgres.sql — consult it directly.

Users & Authentication​

users​

Core user table with role-based access control.

ColumnTypeNotes
idinteger PKAuto-increment
usernamevarcharUNIQUE, NOT NULL
password_hashvarcharbcrypt (12 rounds)
emailvarchar
is_adminbooleanDEFAULT false
is_activebooleanDEFAULT true
rolevarcharCHECK IN ('platform_admin','tenant_admin','manager','user','readonly')
daily_token_quotabigintStored in M units (Issue #3018)
monthly_token_quotabigintStored in M units (Issue #3018)
daily_request_quotabigintStored as actual count (Issue #3018)
monthly_request_quotabigintStored as actual count (Issue #3018)
tenant_idintegerFK → tenants(id) ON DELETE SET NULL
must_change_passwordbooleanDEFAULT false
system_accounttextOS username for multi-user mode
deleted_attimestampSoft delete
avatar_urlvarchar(500)Avatar URL
auto_mapping_enabledbooleanAuto tool-account mapping toggle
tenant_versionintegerTenant-move tracking (Issue #2163)
tokens_valid_aftertimestampRejects tokens minted before this stamp (Issue #3379)

Indexes: idx_users_active, idx_users_deleted, idx_users_email, idx_users_role, idx_users_tenant

sessions​

Authentication sessions with token-based access.

ColumnTypeNotes
idinteger PK
tokenvarcharUNIQUE, NOT NULL
user_idintegerFK → users(id) ON DELETE CASCADE
created_attimestamp
expires_attimestampNOT NULL
is_activebooleanDEFAULT true

Indexes: idx_sessions_active, idx_sessions_expires, idx_sessions_token, idx_sessions_user_id

web_user_auth_sessions​

Web UI authentication sessions.

ColumnTypeNotes
idinteger PK
user_idintegerFK → users(id)
session_tokentextUNIQUE
created_attimestamp
expires_attimestamp

user_tool_accounts​

Maps system accounts to platform users for different AI tools.

ColumnTypeNotes
idinteger PK
user_idintegerFK → users(id) ON DELETE CASCADE
tool_accountvarchar(255)UNIQUE
tool_typevarchar(50)
descriptionvarchar(255)
mapping_sourcevarcharHow the mapping was created (Issue #2761)
mapping_statusvarcharMapping lifecycle status
verification_statusvarcharAccount-mapping verification (Issue #3273)
verified_attimestampVerification time
tenant_idintegerTenant scope

user_daily_stats​

Pre-aggregated daily usage per user for optimized queries.

ColumnTypeNotes
idinteger PK
user_idintegerFK → users(id) ON DELETE CASCADE
datedate
requestsintegerDEFAULT 0
tokensintegerDEFAULT 0
input_tokensintegerDEFAULT 0
output_tokensintegerDEFAULT 0
cache_tokensintegerDEFAULT 0

Unique: (user_id, date)

Messages & Sessions​

The read/write boundaries for these three tables are contractual — see ../contracts/WORKSPACE_SESSION_DATA_CONTRACT.md.

daily_messages​

Core message fact table — the analytical store for all AI interactions.

ColumnTypeNotes
idinteger PK
datevarcharNOT NULL
tool_namevarcharNOT NULL
host_namevarcharDEFAULT 'localhost'
message_idvarcharNOT NULL
parent_idvarchar
rolevarcharNOT NULL (user/assistant/system)
contenttext
full_entrytext
tokens_usedintegerDEFAULT 0
input_tokensintegerDEFAULT 0
output_tokensintegerDEFAULT 0
modelvarchar
timestamptimestamp
sender_idvarchar
sender_namevarchar
message_sourcevarchar
conversation_idvarchar
agent_session_idvarcharLinks to agent_sessions
user_idinteger
project_pathtext
tenant_idintegerTenant scope
feishu_conversation_idvarcharFeishu group chat
group_subject / is_group_chatvarchar / booleanGroup-chat context

Unique: (date, tool_name, message_id, host_name). 18 indexes covering query patterns.

agent_sessions​

Authoritative Workspace session summary table (one row per session).

ColumnTypeNotes
idinteger PK
session_idtextUNIQUE
tenant_idintegerDEFAULT 1; tenant-scoped session lookup and write boundary
tenant_versionintegerTenant-move tracking
session_typetextDEFAULT 'chat'
titletext
tool_nametextNOT NULL
host_nametextDEFAULT 'localhost'
user_idinteger
statustextDEFAULT 'active'
total_tokensintegerDEFAULT 0
total_input_tokens / total_output_tokensintegerDEFAULT 0
total_cache_read_tokens / total_cache_write_tokensintegerCache token totals
message_countintegerDEFAULT 0
request_countintegerDistinct assistant responses (see the session data contract)
modeltext
project_idinteger
project_pathvarchar(500)
context / settings / tagstextSession context, settings, tags
created_at / updated_at / completed_at / expires_at / paused_attimestampLifecycle timestamps
workspace_typetextDEFAULT 'local'
remote_machine_idtextAssociated remote machine
cli_session_idtextCLI-side session identifier
daily_usage_syncedbooleanIdempotent sync flag to daily_usage (Issue #2585)

session_messages​

Authoritative transcript table within an agent session.

ColumnTypeNotes
idinteger PK
session_idtextFK → agent_sessions(session_id)
tenant_idintegerDEFAULT 1; tenant-scoped message lookup
roletextNOT NULL
contenttext
tokens_usedintegerDEFAULT 0
modeltext
timestamptimestamp
metadatatext
milestone_idvarcharAutonomous milestone linkage
sourcevarcharWrite-path source tag
source_timestamptimestampOriginal event time
external_message_idvarcharProvider message id; idempotency key with (session_id, role)
content_blockstextStructured content replay

Session indexes include idx_agent_sessions_tenant_user, idx_agent_sessions_tenant_updated, idx_session_messages_tenant_session, and idx_session_messages_tenant_session_timestamp.

Statistics​

daily_stats​

Aggregated daily statistics per tool/host/sender.

ColumnTypeNotes
datevarchar(10)NOT NULL
tool_namevarchar(50)NOT NULL
host_namevarchar(100)DEFAULT 'localhost'
sender_namevarchar(100)
total_tokensbigintNOT NULL
total_input_tokensbigintNOT NULL
total_output_tokensbigintNOT NULL
message_countintegerNOT NULL
project_idinteger
project_pathvarchar(500)
user_idinteger
tenant_idintegerTenant scope

Unique: (date, tool_name, host_name, sender_name)

hourly_stats​

Hourly breakdown of usage.

ColumnTypeNotes
datevarchar(10)NOT NULL
hourintegerNOT NULL
tool_namevarchar(50)NOT NULL
host_namevarchar(100)DEFAULT 'localhost'
total_tokensbigintNOT NULL
total_input_tokensbigintNOT NULL
total_output_tokensbigintNOT NULL
message_countintegerNOT NULL
tenant_idintegerTenant scope

Unique: (date, hour, tool_name, host_name)

daily_usage​

Daily usage with cache token tracking.

ColumnTypeNotes
idinteger PK
tenant_idintegerDEFAULT 1; tenant-scoped usage aggregation key
datedateNOT NULL
tool_namevarcharNOT NULL
host_namevarcharDEFAULT 'localhost'
tokens_usedintegerDEFAULT 0
input_tokensintegerDEFAULT 0
output_tokensintegerDEFAULT 0
cache_tokensintegerDEFAULT 0
request_countintegerDEFAULT 0
models_usedtext

Unique: (tenant_id, date, tool_name, host_name)

Indexes: idx_usage_date, idx_usage_date_tool_host(tenant_id, date, tool_name, host_name), idx_usage_tenant_date

usage_summary​

Overall summary per tool/host for dashboard.

ColumnTypeNotes
tool_namevarchar(50)NOT NULL
host_namevarchar(100)
days_countintegerNOT NULL
total_tokensbigintNOT NULL
avg_tokensbigintNOT NULL
total_requestsintegerNOT NULL
total_input_tokensbigintNOT NULL
total_output_tokensbigintNOT NULL
first_datevarchar(10)
last_datevarchar(10)

Unique: (tool_name, host_name)

session_stats (Materialized View)​

Aggregated from daily_messages where agent_session_id IS NOT NULL. Provides session-level token counts, message counts, and timestamp ranges. This is the schema's single materialized view.

Multi-Tenant​

tenants​

ColumnTypeNotes
idinteger PK
nametextNOT NULL
slugtextUNIQUE
statustextCHECK IN ('active','suspended','trial','inactive')
plantextCHECK IN ('free','standard','premium','enterprise')
contact_email / contact_phone / contact_nametextContact details
quota / settingstextJSON blobs
user_countintegerDEFAULT 0
total_tokens_usedintegerDEFAULT 0
total_requests_madeintegerDEFAULT 0
billing_day / billing_cycle_type / billing_cycle_start / billing_cycle_endvariedBilling cycle
current_cycle_tokensbigintTokens in the current cycle
over_limit_strategy / over_limit_price_per_tokentext/numericOver-limit handling
usage_alert_threshold / usage_critical_threshold / alert_silence_hoursnumericUsage alerting
trial_ends_at / subscription_ends_attimestampLifecycle
deleted_attimestampSoft delete

tenant_settings (1:1 with tenants)​

ColumnTypeNotes
tenant_idintegerUNIQUE FK → tenants(id) ON DELETE CASCADE
content_filter_enabledbooleanDEFAULT true
audit_log_enabledbooleanDEFAULT true
audit_log_retention_daysintegerDEFAULT 90
data_retention_daysintegerDEFAULT 365
sso_enabledbooleanDEFAULT false
sso_providertextDefault provider name
custom_branding / branding_name / branding_logo_urlvariedBranding
auto_provision_userstextAuto-provisioning policy
block_sensitive_keyword / sensitive_keyword_match_modeboolean/textSensitive keyword policy
allowed_tools / roi_assumptionstextJSON config (Issue #2788)

tenant_quotas (1:1 with tenants)​

ColumnTypeNotes
tenant_idintegerUNIQUE FK → tenants(id) ON DELETE CASCADE
daily_token_limitbigintDEFAULT 1,000,000 (actual token count, Issue #1259)
monthly_token_limitbigintDEFAULT 30,000,000 (actual token count, Issue #1259)
daily_request_limitbigintDEFAULT 10,000 (Issue #3018)
monthly_request_limitbigintDEFAULT 300,000 (Issue #3018)
max_usersintegerDEFAULT 100
max_sessions_per_userintegerDEFAULT 5

tenant_usage​

ColumnTypeNotes
idinteger PK
tenant_idintegerFK → tenants(id) ON DELETE CASCADE
datedateNOT NULL
tokens_usedintegerDEFAULT 0
requests_madeintegerDEFAULT 0
active_usersintegerDEFAULT 0
new_usersintegerDEFAULT 0

Unique: (tenant_id, date)

SSO​

sso_providers​

ColumnTypeNotes
idinteger PK
nametextUNIQUE
provider_typetextNOT NULL (oauth2/oidc/saml)
configtextNOT NULL (JSON; stores encrypted client_secret_encrypted instead of plaintext client_secret)
tenant_idintegerFK → tenants(id)
is_activebooleanDEFAULT true

sso_identities​

ColumnTypeNotes
idinteger PK
user_idintegerFK → users(id)
provider_nametextNOT NULL
provider_user_idtextNOT NULL
provider_datatextRaw provider claims

Unique: (provider_name, provider_user_id)

sso_sessions​

ColumnTypeNotes
idinteger PK
session_tokentextUNIQUE
user_idintegerFK → users(id)
provider_nametextNOT NULL
access_tokentext
refresh_tokentext
expires_attimestamp

Governance & Compliance​

audit_logs​

ColumnTypeNotes
idinteger PK
timestamptimestampDEFAULT CURRENT_TIMESTAMP
user_idinteger
tenant_idintegerResolved from the actor when available for tenant-scoped audit queries
usernametext
actiontextNOT NULL
severitytextDEFAULT 'info'
resource_typetext
resource_idtext
detailstext
ip_addresstext
user_agenttext
session_idtext
successbooleanDEFAULT true
error_messagetext

Indexes: idx_audit_timestamp, idx_audit_user_id, idx_audit_tenant_id, idx_audit_action, idx_audit_severity

content_filter_rules​

ColumnTypeNotes
idinteger PK
patterntextNOT NULL
typetextDEFAULT 'keyword'
severitytextDEFAULT 'medium'
actiontextDEFAULT 'warn'
is_enabledbooleanDEFAULT true
descriptiontext

security_settings​

Key-value store for security configuration.

ColumnTypeNotes
idinteger PK
setting_keyvarchar(100)UNIQUE
setting_valuetext
descriptiontext

anomaly_status​

Anomaly status tracking.

ColumnTypeNotes
idinteger PKAuto-increment
anomaly_idtextStable anomaly identity (Issue #2749)
anomaly_typevarcharAnomaly type
affected_users_hashvarcharAffected users hash
tenant_idintegerTenant scope
statusvarcharProcessing status
processed_byintegerProcessor ID
processed_attimestampProcessing time
created_attimestampCreation time

insights_reports​

AI-generated usage insight reports.

ColumnTypeNotes
idinteger PKAuto-increment
user_idintegerUser ID
start_datevarcharStart date
end_datevarcharEnd date
overall_scoreintegerOverall score
overall_assessmenttextOverall assessment
strengthstextStrengths (JSON)
areas_for_improvementtextAreas for improvement (JSON)
suggestionstextSuggestions (JSON)
usage_summarytextUsage summary (JSON)
modelvarcharModel used
raw_responsetextRaw AI response
created_attimestampCreation time

Security & Permissions​

login_attempts​

Failed login attempt tracking for account lockout.

ColumnTypeNotes
usernamevarcharNOT NULL, lookup key
attempt_countintegerDEFAULT 0
locked_untiltimestampLock expiry time

user_permissions​

User-level permission overrides.

ColumnTypeNotes
idinteger PKAuto-increment
user_idintegerNOT NULL
permissiontextNOT NULL
granted_byintegerGrantor
granted_attimestampDEFAULT CURRENT_TIMESTAMP

Indexes: idx_user_permissions_user, idx_user_permissions_permission

role_permissions​

Role permission templates.

ColumnTypeNotes
idinteger PKAuto-increment
roletextNOT NULL
permissiontextNOT NULL

Indexes: idx_role_permissions_role, idx_role_permissions_permission

Alerts & Quotas​

alerts​

ColumnTypeNotes
idinteger PK
alert_idtextUNIQUE
alert_typetextNOT NULL
severitytextNOT NULL
titletextNOT NULL
messagetext
user_idinteger
usernametext
tool_nametext
metadatatext
readbooleanDEFAULT false
action_url / action_texttextInline action link

quota_usage​

ColumnTypeNotes
idinteger PK
user_idintegerFK → users(id) ON DELETE CASCADE
datedateNOT NULL
periodtextDEFAULT 'daily'
tool_nametextPer-tool quota dimension
tokens_usedintegerDEFAULT 0
requests_usedintegerDEFAULT 0

Unique: (user_id, date, period, tool_name)

quota_alerts​

ColumnTypeNotes
idinteger PK
user_idintegerFK → users(id) ON DELETE CASCADE
alert_typetextNOT NULL
quota_typetextNOT NULL
periodtextQuota period
thresholdrealNOT NULL
current_usageintegerNOT NULL
quota_limitintegerNOT NULL
percentagerealNOT NULL
messagetext
acknowledgedbooleanDEFAULT false
acknowledged_at / acknowledged_bytimestamp/integerAcknowledgment tracking

notification_preferences​

ColumnTypeNotes
user_idintegerPK
email_enabledbooleanDEFAULT true
push_enabledbooleanDEFAULT true
webhook_urltextPersonal webhook
alert_typestextSubscribed alert types
min_severitytextDEFAULT 'warning'
notification_emailtextDedicated notification address
email_verifiedbooleanAddress verification
dingtalk_webhook_secrettextEncrypted DingTalk secret

Workspace & Projects​

projects​

ColumnTypeNotes
idinteger PK
tenant_idintegerDEFAULT 1; used for tenant-scoped project lookup and uniqueness
pathvarchar(500)UNIQUE per active (tenant_id, path)
namevarchar(200)
descriptiontext
created_byinteger
is_activebooleanDEFAULT true
is_sharedbooleanDEFAULT false
permission_statustextShared-project permission setup status (Issue #2746)
permission_task_idtextAssociated permission_tasks task

Indexes: idx_projects_created_by, idx_projects_is_active, idx_projects_path(tenant_id, path), idx_projects_tenant_created_by

user_projects​

ColumnTypeNotes
idinteger PK
user_idintegerNOT NULL
project_idintegerNOT NULL
first_access_at / last_access_attimestampAccess window
total_sessionsintegerDEFAULT 0
total_tokensbigintDEFAULT 0
total_requestsintegerDEFAULT 0
total_duration_secondsintegerDEFAULT 0

Unique: (user_id, project_id)

prompt_templates​

ColumnTypeNotes
idinteger PK
nametextNOT NULL, UNIQUE (Issue #2577)
descriptiontext
categorytextDEFAULT 'general'
contenttextNOT NULL
variablestext
tagstext
author_idinteger
author_nametext
is_publicbooleanDEFAULT false
is_featuredbooleanDEFAULT false
use_countintegerDEFAULT 0

Remote Workspace​

remote_machines​

Remote workspace machine registry.

ColumnTypeNotes
idinteger PKAuto-increment
machine_idtextMachine unique identifier
machine_nametextMachine name
hostnametextHostname
os_typetextOS type
os_versiontextOS version
ip_addresstextIP address
statustextStatus
agent_versiontextAgent version
capabilitiestextCapabilities (JSON)
cli_pathtextCLI path
work_dirtextWorking directory
tenant_idintegerTenant ID
created_byintegerCreator ID
created_at / updated_attimestampTimestamps
last_heartbeattimestampLast heartbeat time
legacy_modebooleanLegacy protocol flag
token_revoke_timeoutintegerDelayed revocation window (Issue #2499)

remote_runtime_commands​

Persistent HTTP-polling command queue for remote agents.

ColumnTypeNotes
idinteger PK
command_idvarchar(64)UNIQUE; request_id for command-response calls
machine_idtextTarget remote machine
session_idtextOptional remote session
command_typetextCommand name
payloadtextJSON command payload
statusvarchar(32)pending, delivered, or responded
response_payloadtextJSON response payload for synchronous commands
created_attimestampCreation time
delivered_attimestampAgent poll claim time
responded_attimestampResponse arrival time
expires_attimestampRetention cutoff

Indexes: idx_remote_runtime_commands_machine_status, idx_remote_runtime_commands_expires

remote_runtime_outputs​

Persistent SSE replay buffer for remote session output.

ColumnTypeNotes
idinteger PK
session_idtextRemote session ID
event_indexintegerMonotonic per-session output index
streamtextstdout, stderr, system, permission, request_state
payloadtextJSON output payload
created_attimestampCreation time
expires_attimestampRetention cutoff

Unique: (session_id, event_index)

Indexes: idx_remote_runtime_outputs_session_index, idx_remote_runtime_outputs_expires

machine_assignments​

User-to-remote-machine assignment relationships.

ColumnTypeNotes
idinteger PKAuto-increment
machine_idtextMachine ID
user_idintegerUser ID
permissiontextPermission level
granted_byintegerGrantor ID
granted_attimestampGrant time

api_key_store​

Encrypted API key storage.

ColumnTypeNotes
idinteger PKAuto-increment
tenant_idintegerTenant ID
providertextAI service provider
key_nametextKey name
encrypted_keytextEncrypted key
key_hashtextKey hash
base_urltextAPI base URL
is_activebooleanDEFAULT true
scope / priority / weighttext/integerRouting attributes
resolved_ips / resolved_attext/timestampPinned egress IPs (Issue #1894)
created_byintegerCreator ID
created_at / updated_attimestampTimestamps
cli_toolstextCLI tools configuration
cli_settingstextCLI settings

Collaboration​

teams​

ColumnTypeNotes
idinteger PK
team_idtextUNIQUE
nametextNOT NULL
descriptiontext
owner_idinteger
settingstextTeam settings (JSON)

team_members​

ColumnTypeNotes
idinteger PK
team_idtextNOT NULL
user_idintegerNOT NULL
usernametextDenormalized member name
roletextDEFAULT 'member'
joined_attimestamp

Unique: (team_id, user_id)

shared_sessions​

ColumnTypeNotes
idinteger PK
share_idtextUNIQUE
session_idtextNOT NULL
shared_byinteger
shared_by_nametextDenormalized sharer name
permissiontextDEFAULT 'view'
share_type / target_id / target_nametextShare target (user/team/link)
allow_commentsbooleanDEFAULT true
allow_copybooleanDEFAULT true
expires_attimestamp
access_countintegerDEFAULT 0
last_accessedtimestamp

knowledge_base​

ColumnTypeNotes
idinteger PK
entry_idtextUNIQUE
team_idtext
titletextNOT NULL
contenttext
categorytextDEFAULT 'general'
tagstext
author_idinteger
author_nametext
is_publishedbooleanDEFAULT false
view_countintegerDEFAULT 0

annotations​

ColumnTypeNotes
idinteger PK
annotation_idtextUNIQUE
session_idtextNOT NULL
message_idtext
user_idinteger
usernametextDenormalized author name
contenttext
annotation_typetextDEFAULT 'comment'
parent_idtextThreading

Sync & Retention Snapshots​

sync_events​

ColumnTypeNotes
idinteger PK
event_idtextUNIQUE
event_typetextNOT NULL
sourcetext
session_idtext
user_idinteger
tool_nametext
datatext
metadatatext

retention_history​

ColumnTypeNotes
idinteger PK
timestamptimestampDEFAULT CURRENT_TIMESTAMP
report_datatextNOT NULL

Foreign Key Summary​

Child TableColumnParent TableOn Delete
userstenant_idtenantsSET NULL
sessionsuser_idusersCASCADE
web_user_auth_sessionsuser_idusers—
user_tool_accountsuser_idusersCASCADE
user_daily_statsuser_idusersCASCADE
session_messagessession_idagent_sessions—
quota_usageuser_idusersCASCADE
quota_alertsuser_idusersCASCADE
sso_identitiesuser_idusers—
sso_sessionsuser_idusers—
sso_providerstenant_idtenants—
tenant_quotastenant_idtenantsCASCADE
tenant_settingstenant_idtenantsCASCADE
tenant_usagetenant_idtenantsCASCADE
anomaly_statusprocessed_byusers—
insights_reportsuser_idusers—

Cross-Database Compatibility​

See DATABASE_CONVENTIONS.md for naming conventions. The adapt_sql() function in app/repositories/database.py handles placeholder conversion (? → %s) automatically.