db

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 14, 2026 License: Apache-2.0 Imports: 24 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrMessageNotFound = errors.New("mailbox message not found")

ErrMessageNotFound is returned when a requested mailbox message does not exist.

View Source
var ErrProfileNotFound = errors.New("agent profile not found")

ErrProfileNotFound is returned when a requested agent profile does not exist.

View Source
var ErrTeamNotFound = errors.New("team not found")

ErrTeamNotFound is returned when a requested team does not exist.

Functions

func AutomationJobRowToStrings

func AutomationJobRowToStrings(jsonStr string) []string

func AutomationStringsToJSON

func AutomationStringsToJSON(ss []string) string

func GenerateAutomationAPIKey

func GenerateAutomationAPIKey() (rawKey, hash, prefix string, err error)

GenerateAutomationAPIKey creates a new random key with the sats_ prefix. Returns the raw key (shown once) and its SHA-256 hash.

func HashAutomationAPIKey

func HashAutomationAPIKey(rawKey string) string

HashAutomationAPIKey returns the SHA-256 hex hash of a raw key.

func IsAutomationAPIKey

func IsAutomationAPIKey(s string) bool

IsAutomationAPIKey reports whether s looks like a sats_ prefixed key.

func MaskAutomationAPIKey

func MaskAutomationAPIKey(rawKey string) string

MaskAutomationAPIKey returns a display-safe version: "sats_****<last4>".

func TimePtrToUnix

func TimePtrToUnix(t *time.Time) *int64

func UnixNow

func UnixNow() int64

UnixNow returns the current unix timestamp.

func UnixPtrToTime

func UnixPtrToTime(u *int64) *time.Time

Types

type AutomationAPIKeyRow

type AutomationAPIKeyRow struct {
	ID        string
	KeyHash   string // SHA-256 hex of the raw key
	KeyPrefix string // first 12 chars of raw key for display ("sats_a1b2c3")
	Label     string
	OwnerID   string
	Enabled   bool
	CreatedAt int64
	// ExpiresAt is a Unix timestamp; 0 means no expiry.
	ExpiresAt int64
}

AutomationAPIKeyRow is the DB row for a daemon API key.

type AutomationJobRow

type AutomationJobRow struct {
	ID              string
	OwnerID         string // user ID from the calling app; "" = system/unowned
	Name            string
	Description     string
	TriggerType     string
	TriggerCron     string
	TriggerInterval int64 // nanoseconds
	TriggerRunAt    *int64
	AgentSlug       string // optional: slug of a named agent in seshat-ai
	AgentBaseType   string
	AgentToolsJSON  string
	AgentSkillsJSON string
	AgentModel      string
	AgentMaxTurns   int
	AgentSysPrompt  string
	Task            string
	Status          string
	LastRunAt       *int64
	NextRunAt       *int64
	LastRunStatus   string
	CreatedAt       int64
	UpdatedAt       int64
}

AutomationJobRow is the DB representation of a persisted automation job.

type AutomationRunRow

type AutomationRunRow struct {
	ID        string
	JobID     string
	StartedAt int64
	EndedAt   *int64
	Status    string
	Output    string
	Error     string
	CreatedAt int64
}

AutomationRunRow is the DB representation of a single job execution.

type Config

type Config struct {
	Driver        Driver
	DSN           string
	AutoMigrate   bool // when true, runs versioned schema migrations on Open
	BusyTimeoutMS int  // SQLite only
}

Config describes how to open and initialize an application database.

func DefaultMySQLConfig

func DefaultMySQLConfig(dsn string) Config

DefaultMySQLConfig returns a default MySQL configuration.

func DefaultPostgresConfig

func DefaultPostgresConfig(dsn string) Config

DefaultPostgresConfig returns a default PostgreSQL configuration.

func DefaultSQLiteConfig

func DefaultSQLiteConfig(path string) Config

DefaultSQLiteConfig returns a pragmatic default SQLite configuration for local Seshat persistence.

type DB

type DB struct {
	// contains filtered or unexported fields
}

DB is the shared low-level application database handle. Runtime subsystems such as session storage can depend on it now, and future app domains like users/roles can reuse the same connection and migration layer later.

func Open

func Open(ctx context.Context, cfg Config) (*DB, error)

Open creates a database handle and initializes the shared schema when AutoMigrate is enabled.

func (*DB) Close

func (db *DB) Close() error

Close closes the underlying database handle. For SQLite, PRAGMA optimize is run first to update the query planner statistics.

func (*DB) CountUnreadByAgents

func (db *DB) CountUnreadByAgents(ctx context.Context, agentIDs []string) (map[string]int, error)

CountUnreadByAgents returns a map of agentID → unread message count for each ID in the given slice. Agents with zero unread messages are absent from the result map (treat missing keys as 0). A single GROUP BY query is used regardless of how many agent IDs are provided.

func (*DB) CreateAutomationAPIKey

func (db *DB) CreateAutomationAPIKey(ctx context.Context, row AutomationAPIKeyRow) error

func (*DB) CreateAutomationJob

func (db *DB) CreateAutomationJob(ctx context.Context, row AutomationJobRow) error

func (*DB) CreateAutomationRun

func (db *DB) CreateAutomationRun(ctx context.Context, row AutomationRunRow) error

func (*DB) CreateSessionTask

func (db *DB) CreateSessionTask(ctx context.Context, task SessionTask) error

func (*DB) DSN

func (db *DB) DSN() string

DSN returns the normalized data source name used to open the database.

func (*DB) DeleteAutomationAPIKey

func (db *DB) DeleteAutomationAPIKey(ctx context.Context, id string) error

func (*DB) DeleteAutomationJob

func (db *DB) DeleteAutomationJob(ctx context.Context, id, ownerID string) error

func (*DB) DeleteCredential

func (db *DB) DeleteCredential(ctx context.Context, key string) error

DeleteCredential removes the credential for key. No-op if it does not exist.

func (*DB) DeleteMessage

func (db *DB) DeleteMessage(ctx context.Context, msgID string) error

DeleteMessage removes a message record permanently.

func (*DB) DeleteProfile

func (db *DB) DeleteProfile(ctx context.Context, id string) error

DeleteProfile removes the profile with the given ID. No-op if absent.

func (*DB) DeleteSessionTask

func (db *DB) DeleteSessionTask(ctx context.Context, sessionID, taskID string) error

func (*DB) DeleteTeam

func (db *DB) DeleteTeam(ctx context.Context, id string) error

DeleteTeam removes the team with the given ID. No-op if absent.

func (*DB) Driver

func (db *DB) Driver() Driver

Driver returns the configured driver kind.

func (*DB) FindProfilesByRole

func (db *DB) FindProfilesByRole(ctx context.Context, role string) ([]GAgentProfile, error)

FindProfilesByRole returns all profiles whose role equals the given value.

func (*DB) FindProfilesByTeam

func (db *DB) FindProfilesByTeam(ctx context.Context, teamID string) ([]GAgentProfile, error)

FindProfilesByTeam returns all profiles belonging to the given team.

func (*DB) GetAutomationAPIKeyByHash

func (db *DB) GetAutomationAPIKeyByHash(ctx context.Context, hash string) (*AutomationAPIKeyRow, error)

GetAutomationAPIKeyByHash looks up an active, non-expired key by its SHA-256 hash. Returns nil, nil when the key does not exist, is disabled, or is expired.

func (*DB) GetAutomationJob

func (db *DB) GetAutomationJob(ctx context.Context, id string) (*AutomationJobRow, error)

func (*DB) GetAutomationRun

func (db *DB) GetAutomationRun(ctx context.Context, id string) (*AutomationRunRow, error)

func (*DB) GetCredential

func (db *DB) GetCredential(ctx context.Context, key string) (string, bool, error)

GetCredential retrieves and decrypts the value stored under key. Returns ("", false, nil) when the key does not exist.

func (*DB) GetFileSessions

func (db *DB) GetFileSessions(ctx context.Context, filePath string) ([]SessionFile, error)

GetFileSessions returns all sessions that touched a given file path, ordered by most recent first.

func (*DB) GetMessage

func (db *DB) GetMessage(ctx context.Context, msgID string) (GMailboxMessage, error)

GetMessage returns a single message by ID.

func (*DB) GetMessageHistory

func (db *DB) GetMessageHistory(ctx context.Context, toAgent string, limit int) ([]GMailboxMessage, error)

GetMessageHistory returns up to limit messages for toAgent, newest first.

func (*DB) GetMessageThread

func (db *DB) GetMessageThread(ctx context.Context, rootID string) ([]GMailboxMessage, error)

GetMessageThread returns all messages in a thread rooted at rootID, including the root itself, ordered oldest first.

func (*DB) GetProfile

func (db *DB) GetProfile(ctx context.Context, id string) (GAgentProfile, error)

GetProfile returns the profile with the given ID. Returns ErrProfileNotFound when no record matches.

func (*DB) GetSessionFiles

func (db *DB) GetSessionFiles(ctx context.Context, sessionID string) ([]SessionFile, error)

GetSessionFiles returns all file operations recorded for a session, ordered by timestamp ascending.

func (*DB) GetSessionTask

func (db *DB) GetSessionTask(ctx context.Context, sessionID, taskID string) (SessionTask, error)

func (*DB) GetTeam

func (db *DB) GetTeam(ctx context.Context, id string) (GTeam, error)

GetTeam returns the team with the given ID. Returns ErrTeamNotFound when no record matches.

func (*DB) GetTeamAgents

func (db *DB) GetTeamAgents(ctx context.Context, teamID string) ([]string, error)

GetTeamAgents returns the distinct to_agent values that have received messages tagged with teamID. Used for broadcast expansion.

func (*DB) GetTeamByName

func (db *DB) GetTeamByName(ctx context.Context, name string) (GTeam, error)

GetTeamByName returns the team with the given name. Returns ErrTeamNotFound when no record matches.

func (*DB) GetUnreadMessages

func (db *DB) GetUnreadMessages(ctx context.Context, toAgent string) ([]GMailboxMessage, error)

GetUnreadMessages returns all unread messages for toAgent, oldest first.

func (*DB) GormDB

func (db *DB) GormDB() *gorm.DB

GormDB returns the underlying *gorm.DB.

func (*DB) HasSessionFileEntry

func (db *DB) HasSessionFileEntry(ctx context.Context, sessionID string) (bool, error)

HasSessionFileEntry returns true if session_files already has at least one row for the given session. Used to detect whether backfill is needed.

func (*DB) Initialize

func (db *DB) Initialize(ctx context.Context) error

Initialize applies only the public engine's core persistence migrations. Product/backend schema lives in the private product repository.

func (*DB) InitializeAutomationDaemon

func (db *DB) InitializeAutomationDaemon(ctx context.Context) error

InitializeAutomationDaemon applies daemon-specific migrations on top of the core migrations. Call this in the seshat-automation binary after Initialize.

func (*DB) InsertMessage

func (db *DB) InsertMessage(ctx context.Context, row GMailboxMessage) error

InsertMessage writes a new message record.

func (*DB) ListAutomationAPIKeys

func (db *DB) ListAutomationAPIKeys(ctx context.Context) ([]*AutomationAPIKeyRow, error)

func (*DB) ListAutomationJobs

func (db *DB) ListAutomationJobs(ctx context.Context, ownerID string) ([]*AutomationJobRow, error)

ListAutomationJobs returns all jobs, optionally filtered by owner. Pass ownerID = "" to list all jobs (system/admin use).

func (*DB) ListAutomationRuns

func (db *DB) ListAutomationRuns(ctx context.Context, jobID string, limit int) ([]*AutomationRunRow, error)

func (*DB) ListCredentialKeys

func (db *DB) ListCredentialKeys(ctx context.Context) ([]string, error)

ListCredentialKeys returns the stored keys without their values.

func (*DB) ListProfiles

func (db *DB) ListProfiles(ctx context.Context) ([]GAgentProfile, error)

ListProfiles returns all profiles ordered by nickname.

func (*DB) ListSessionTasks

func (db *DB) ListSessionTasks(ctx context.Context, sessionID string) ([]SessionTask, error)

func (*DB) ListTeams

func (db *DB) ListTeams(ctx context.Context) ([]GTeam, error)

ListTeams returns all teams ordered by name.

func (*DB) MarkAllMessagesRead

func (db *DB) MarkAllMessagesRead(ctx context.Context, toAgent string) error

MarkAllMessagesRead sets read_at to now for all unread messages of toAgent.

func (*DB) MarkMessageRead

func (db *DB) MarkMessageRead(ctx context.Context, msgID string) error

MarkMessageRead sets read_at to now for the given message ID.

func (*DB) NextSessionTaskPosition

func (db *DB) NextSessionTaskPosition(ctx context.Context, sessionID string) (int, error)

func (*DB) Ping

func (db *DB) Ping(ctx context.Context) error

Ping checks that the database connection is alive.

func (*DB) RevokeAutomationAPIKey

func (db *DB) RevokeAutomationAPIKey(ctx context.Context, id string) error

func (*DB) SQL

func (db *DB) SQL() *sql.DB

SQL exposes the underlying sql.DB for backend implementations that need transactions or driver-specific operations (e.g. sqlite_backend.go).

func (*DB) SetProfileTeam

func (db *DB) SetProfileTeam(ctx context.Context, agentID, teamID string) error

SetProfileTeam updates team_id on a single agent profile. Pass an empty teamID to remove the agent from its team.

func (*DB) UpdateAutomationJob

func (db *DB) UpdateAutomationJob(ctx context.Context, row AutomationJobRow) error

func (*DB) UpdateAutomationRun

func (db *DB) UpdateAutomationRun(ctx context.Context, row AutomationRunRow) error

func (*DB) UpdateSessionTask

func (db *DB) UpdateSessionTask(ctx context.Context, task SessionTask) error

func (*DB) UpsertCredential

func (db *DB) UpsertCredential(ctx context.Context, key, plaintext string) error

UpsertCredential encrypts plaintext and stores it under key.

func (*DB) UpsertProfile

func (db *DB) UpsertProfile(ctx context.Context, row GAgentProfile) error

UpsertProfile inserts or fully replaces a profile record.

func (*DB) UpsertProfileIfAbsent

func (db *DB) UpsertProfileIfAbsent(ctx context.Context, row GAgentProfile) error

UpsertProfileIfAbsent inserts the profile only when no record with the same ID exists. Used for seeding built-in profiles without overwriting user edits.

func (*DB) UpsertSessionFile

func (db *DB) UpsertSessionFile(ctx context.Context, sf SessionFile) error

UpsertSessionFile records a file operation for a session. When tool_use_id is non-empty, INSERT OR IGNORE silently skips duplicates (the unique index on tool_use_id WHERE tool_use_id != ” enforces this).

func (*DB) UpsertTeam

func (db *DB) UpsertTeam(ctx context.Context, row GTeam) error

UpsertTeam inserts or fully replaces a team record.

type Driver

type Driver string

Driver identifies a database driver supported by the shared DB module.

const (
	DriverSQLite   Driver = "sqlite"
	DriverPostgres Driver = "postgres"
	DriverMySQL    Driver = "mysql"
)

type GAgentProfile

type GAgentProfile struct {
	// ID is a UUID string — globally unique, generated once at creation.
	ID       string `gorm:"primaryKey;size:36"`
	Nickname string `gorm:"not null"`
	Role     string `gorm:"not null;index"`
	TeamID   string `gorm:"column:team_id;index"`
	// SystemPromptTemplate is the raw template; {{.Nickname}} is resolved at runtime.
	SystemPromptTemplate string `gorm:"column:system_prompt_template;type:text;not null"`
	Model                string `gorm:"column:model"`
	SkillsJSON           string `gorm:"column:skills_json;type:text;not null;default:'[]'"`
	MetadataJSON         string `gorm:"column:metadata_json;type:text;not null;default:'{}'"`
	CreatedAtUnix        int64  `gorm:"column:created_at_unix;autoCreateTime:unix"`
	UpdatedAtUnix        int64  `gorm:"column:updated_at_unix;autoUpdateTime:unix"`
}

GAgentProfile is the GORM model for the agent_profiles table.

func (GAgentProfile) TableName

func (GAgentProfile) TableName() string

type GMailboxMessage

type GMailboxMessage struct {
	ID        string `gorm:"primaryKey;size:36"`
	Kind      string `gorm:"not null;index"`
	FromAgent string `gorm:"column:from_agent;not null;index"`
	ToAgent   string `gorm:"column:to_agent;not null;index"`
	Subject   string `gorm:"not null"`
	Body      string `gorm:"type:text;not null"`
	ReplyTo   string `gorm:"column:reply_to;index"`
	TeamID    string `gorm:"column:team_id;index"`
	ReadAt    *int64 `gorm:"column:read_at"`
	CreatedAt int64  `gorm:"column:created_at;not null;index"`
}

GMailboxMessage is the GORM model for the mailbox_messages table.

func (GMailboxMessage) TableName

func (GMailboxMessage) TableName() string

type GTeam

type GTeam struct {
	ID            string `gorm:"primaryKey;size:36"`
	Name          string `gorm:"not null;uniqueIndex"`
	Description   string `gorm:"column:description;type:text;not null;default:''"`
	MetadataJSON  string `gorm:"column:metadata_json;type:text;not null;default:'{}'"`
	CreatedAtUnix int64  `gorm:"column:created_at_unix;autoCreateTime:unix"`
	UpdatedAtUnix int64  `gorm:"column:updated_at_unix;autoUpdateTime:unix"`
}

GTeam is the GORM model for the teams table.

func (GTeam) TableName

func (GTeam) TableName() string

type SessionFile

type SessionFile struct {
	ID            int64
	SessionID     string
	ToolUseID     string // foreign key into session_transcript_entries JSON
	FilePath      string
	Operation     string // "create" | "update" | "edit" | "patch"
	TimestampUnix int64
	LinesAdded    int
	LinesRemoved  int
}

SessionFile represents one file operation recorded against a session. ToolUseID is the tool_use_id from the transcript — use it to look up the full ToolResultContent.Metadata (structured_patch, git_diff, content, …) in session_transcript_entries without scanning the whole transcript.

type SessionTask

type SessionTask struct {
	ID            int64
	SessionID     string
	TaskID        string
	Position      int
	Subject       string
	Description   string
	Status        string
	ActiveForm    string
	Owner         string
	Blocks        []string
	BlockedBy     []string
	Metadata      map[string]any
	CreatedAtUnix int64
	UpdatedAtUnix int64
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL