// Package store holds the governance module's SQL: the organisation's model // roles. package store import ( "context" "database/sql" "errors" "fmt" "github.com/google/uuid" "github.com/jmoiron/sqlx" ) var ( // ErrProviderNameTaken means another model provider in the organisation already has the name. ErrProviderNameTaken = errors.New("another model provider has that name") // ErrProviderInUse means at least one model role still references the provider. ErrProviderInUse = errors.New("the model provider is still in use") // ErrNoProvider means no model provider has that id in the organisation. ErrNoProvider = errors.New("no such model provider") ) // ModelRole is the model an organisation chose for one role: a provider id // and a model name on it. type ModelRole struct { OrgID string `db:"org_id"` Role string `db:"role"` ProviderID uuid.UUID `db:"provider_id"` Model string `db:"model"` } // ResolvedRole is a role with the endpoint its provider names. type ResolvedRole struct { OrgID string `db:"org_id"` Role string `db:"role"` ProviderID uuid.UUID `db:"provider_id"` Provider string `db:"provider"` Model string `db:"model"` Class string `db:"class"` BaseURL string `db:"base_url"` // APIKeyCredentialID references the credential whose token authenticates // the provider, or invalid when it needs no key. APIKeyCredentialID uuid.NullUUID `db:"api_key_credential_id"` } // Provider is an endpoint models are called on: an immutable id, an editable // name, provider class, base URL and optional credential id. type Provider struct { ID uuid.UUID `db:"id"` OrgID string `db:"org_id"` Name string `db:"name"` Class string `db:"class"` BaseURL string `db:"base_url"` APIKeyCredentialID uuid.NullUUID `db:"api_key_credential_id"` } // Store is the governance module's Postgres store. type Store struct { db *sqlx.DB } // New returns a store on db. func New(db *sqlx.DB) *Store { return &Store{db: db} } // Providers lists the organisation's providers in name order. func (s *Store) Providers(ctx context.Context, orgID string) ([]Provider, error) { var out []Provider if err := s.db.SelectContext(ctx, &out, ` SELECT id, org_id, name, class, base_url, api_key_credential_id FROM governance.model_providers WHERE org_id = $1 ORDER BY name`, orgID); err != nil { return nil, fmt.Errorf("list model providers: %w", err) } return out, nil } // ProviderByID returns the provider with id in orgID; ok is false when none exists. func (s *Store) ProviderByID(ctx context.Context, orgID string, id uuid.UUID) (Provider, bool, error) { var out Provider err := s.db.GetContext(ctx, &out, ` SELECT id, org_id, name, class, base_url, api_key_credential_id FROM governance.model_providers WHERE org_id = $1 AND id = $2`, orgID, id) if errors.Is(err, sql.ErrNoRows) { return Provider{}, false, nil } if err != nil { return Provider{}, false, fmt.Errorf("read model provider %s: %w", id, err) } return out, true, nil } // CreateProvider inserts a new provider. func (s *Store) CreateProvider(ctx context.Context, p Provider) error { if _, err := s.db.NamedExecContext(ctx, ` INSERT INTO governance.model_providers (id, org_id, name, class, base_url, api_key_credential_id) VALUES (:id, :org_id, :name, :class, :base_url, :api_key_credential_id)`, p); err != nil { if isUniqueViolation(err) { return ErrProviderNameTaken } return fmt.Errorf("create model provider %q: %w", p.Name, err) } return nil } // UpdateProvider updates an existing provider's editable fields, including its name. func (s *Store) UpdateProvider(ctx context.Context, p Provider) error { res, err := s.db.NamedExecContext(ctx, ` UPDATE governance.model_providers SET name = :name, class = :class, base_url = :base_url, api_key_credential_id = :api_key_credential_id, updated_at = now() WHERE org_id = :org_id AND id = :id`, p) if err != nil { if isUniqueViolation(err) { return ErrProviderNameTaken } return fmt.Errorf("update model provider %s: %w", p.ID, err) } n, err := res.RowsAffected() if err != nil { return fmt.Errorf("update model provider %s: %w", p.ID, err) } if n == 0 { return ErrNoProvider } return nil } // DeleteProvider removes a provider and reports whether one existed. func (s *Store) DeleteProvider(ctx context.Context, orgID string, id uuid.UUID) (bool, error) { res, err := s.db.ExecContext(ctx, `DELETE FROM governance.model_providers WHERE org_id = $1 AND id = $2`, orgID, id) if err != nil { if isForeignKeyViolation(err) { return false, ErrProviderInUse } return false, fmt.Errorf("delete model provider %s: %w", id, err) } n, err := res.RowsAffected() if err != nil { return false, fmt.Errorf("delete model provider %s: %w", id, err) } return n > 0, nil } // AliasesUsingProvider names the roles that call models through providerID. func (s *Store) AliasesUsingProvider(ctx context.Context, orgID string, providerID uuid.UUID) ([]string, error) { var roles []string if err := s.db.SelectContext(ctx, &roles, ` SELECT role FROM governance.model_roles WHERE org_id = $1 AND provider_id = $2 ORDER BY role`, orgID, providerID); err != nil { return nil, fmt.Errorf("read model roles for provider %s: %w", providerID, err) } return roles, nil } // ModelRole returns the organisation's model for role with its provider's // endpoint; ok is false when none was chosen. func (s *Store) ModelRole(ctx context.Context, orgID, role string) (ResolvedRole, bool, error) { var out ResolvedRole err := s.db.GetContext(ctx, &out, ` SELECT r.org_id, r.role, r.provider_id, p.name AS provider, r.model, p.class, p.base_url, p.api_key_credential_id FROM governance.model_roles r JOIN governance.model_providers p ON p.id = r.provider_id WHERE r.org_id = $1 AND r.role = $2`, orgID, role) if errors.Is(err, sql.ErrNoRows) { return ResolvedRole{}, false, nil } if err != nil { return ResolvedRole{}, false, fmt.Errorf("read model role %q: %w", role, err) } return out, true, nil } // AgentModelRoles lists the organisation's agent roles with their providers' // endpoints, in role order. func (s *Store) AgentModelRoles(ctx context.Context, orgID string) ([]ResolvedRole, error) { var out []ResolvedRole if err := s.db.SelectContext(ctx, &out, ` SELECT r.org_id, r.role, r.provider_id, p.name AS provider, r.model, p.class, p.base_url, p.api_key_credential_id FROM governance.model_roles r JOIN governance.model_providers p ON p.id = r.provider_id WHERE r.org_id = $1 AND (r.role = 'agent' OR r.role LIKE 'agent:%') ORDER BY r.role`, orgID); err != nil { return nil, fmt.Errorf("list agent models: %w", err) } return out, nil } // PutModelRole records the organisation's model for a role. func (s *Store) PutModelRole(ctx context.Context, m ModelRole) error { if _, err := s.db.NamedExecContext(ctx, ` INSERT INTO governance.model_roles (org_id, role, provider_id, model) VALUES (:org_id, :role, :provider_id, :model) ON CONFLICT (org_id, role) DO UPDATE SET provider_id = EXCLUDED.provider_id, model = EXCLUDED.model, updated_at = now()`, m); err != nil { if isForeignKeyViolation(err) { return ErrNoProvider } return fmt.Errorf("put model role %q: %w", m.Role, err) } return nil } // ModelPolicy is which aliases workflows and chat may name. A nil list lets // any alias through. type ModelPolicy struct { OrgID string `db:"org_id"` // WorkflowAliases and ChatAliases are JSON arrays, or nil for no limit. WorkflowAliases []byte `db:"workflow_aliases"` ChatAliases []byte `db:"chat_aliases"` } // Policy returns the organisation's model policy; ok is false when none was // saved, which lets every alias through. func (s *Store) Policy(ctx context.Context, orgID string) (ModelPolicy, bool, error) { var out ModelPolicy err := s.db.GetContext(ctx, &out, ` SELECT org_id, workflow_aliases, chat_aliases FROM governance.model_policy WHERE org_id = $1`, orgID) if errors.Is(err, sql.ErrNoRows) { return ModelPolicy{}, false, nil } if err != nil { return ModelPolicy{}, false, fmt.Errorf("read model policy: %w", err) } return out, true, nil } // PutPolicy records the organisation's model policy. A nil list is stored as // SQL NULL, which lifts the limit. func (s *Store) PutPolicy(ctx context.Context, p ModelPolicy) error { var workflow, chat any if p.WorkflowAliases != nil { workflow = string(p.WorkflowAliases) } if p.ChatAliases != nil { chat = string(p.ChatAliases) } if _, err := s.db.ExecContext(ctx, ` INSERT INTO governance.model_policy (org_id, workflow_aliases, chat_aliases) VALUES ($1, $2::jsonb, $3::jsonb) ON CONFLICT (org_id) DO UPDATE SET workflow_aliases = EXCLUDED.workflow_aliases, chat_aliases = EXCLUDED.chat_aliases, updated_at = now()`, p.OrgID, workflow, chat); err != nil { return fmt.Errorf("put model policy: %w", err) } return nil } // DeleteModelRole removes the organisation's model for role and reports // whether one existed. func (s *Store) DeleteModelRole(ctx context.Context, orgID, role string) (bool, error) { res, err := s.db.ExecContext(ctx, `DELETE FROM governance.model_roles WHERE org_id = $1 AND role = $2`, orgID, role) if err != nil { return false, fmt.Errorf("delete model role %q: %w", role, err) } n, err := res.RowsAffected() if err != nil { return false, fmt.Errorf("delete model role %q: %w", role, err) } return n > 0, nil } // Settings is an organisation's settings as stored. A duration is kept in // milliseconds: Postgres has no duration type that scans into one. type Settings struct { OrgID string `db:"org_id"` // ApprovalDeadlineMS is how long an approval request waits for an answer. ApprovalDeadlineMS int64 `db:"approval_deadline_ms"` // ProposeAutonomyAfter is how many approvals in a row earn a proposal to loosen an // action type. ProposeAutonomyAfter int `db:"propose_autonomy_after"` // Frozen holds every action that changes something at propose and wait. Frozen bool `db:"frozen"` // RecurrenceThreshold is how many incidents with one cause on one target // it takes to propose a root-cause fix. RecurrenceThreshold int `db:"recurrence_threshold"` // DefaultOwner is the id of the person who answers for what has no other // owner, or empty. DefaultOwner string `db:"default_owner"` // Escalation is a JSON array of person ids, in the order an unanswered // request moves through them. Escalation string `db:"escalation"` // AttemptsPerRun is how many steps an agent may take in one run. AttemptsPerRun int `db:"attempts_per_run"` // Timing is a JSON object: business hours and blackouts. Timing string `db:"timing"` // ActionsPerRun and ActionsPerDay are the action budgets. ActionsPerRun int `db:"actions_per_run"` ActionsPerDay int `db:"actions_per_day"` } // Settings returns the organisation's settings; ok is false when none were // saved. func (s *Store) Settings(ctx context.Context, orgID string) (Settings, bool, error) { var out Settings err := s.db.GetContext(ctx, &out, ` SELECT org_id, approval_deadline_ms, propose_autonomy_after, frozen, recurrence_threshold, default_owner, escalation::text AS escalation, attempts_per_run, timing::text AS timing, actions_per_run, actions_per_day FROM governance.settings WHERE org_id = $1`, orgID) if errors.Is(err, sql.ErrNoRows) { return Settings{}, false, nil } if err != nil { return Settings{}, false, fmt.Errorf("read settings: %w", err) } return out, true, nil } // PutSettings records the organisation's settings. func (s *Store) PutSettings(ctx context.Context, set Settings) error { if _, err := s.db.NamedExecContext(ctx, ` INSERT INTO governance.settings (org_id, approval_deadline_ms, propose_autonomy_after, frozen, recurrence_threshold, default_owner, escalation, attempts_per_run, timing, actions_per_run, actions_per_day) VALUES (:org_id, :approval_deadline_ms, :propose_autonomy_after, :frozen, :recurrence_threshold, :default_owner, CAST(:escalation AS jsonb), :attempts_per_run, CAST(:timing AS jsonb), :actions_per_run, :actions_per_day) ON CONFLICT (org_id) DO UPDATE SET approval_deadline_ms = EXCLUDED.approval_deadline_ms, propose_autonomy_after = EXCLUDED.propose_autonomy_after, frozen = EXCLUDED.frozen, recurrence_threshold = EXCLUDED.recurrence_threshold, default_owner = EXCLUDED.default_owner, escalation = EXCLUDED.escalation, attempts_per_run = EXCLUDED.attempts_per_run, timing = EXCLUDED.timing, actions_per_run = EXCLUDED.actions_per_run, actions_per_day = EXCLUDED.actions_per_day, updated_at = now()`, set); err != nil { return fmt.Errorf("put settings: %w", err) } return nil } // Instructions returns the organisation's standing instructions, empty when // none were saved. func (s *Store) Instructions(ctx context.Context, orgID string) (string, error) { var body string err := s.db.GetContext(ctx, &body, `SELECT body FROM governance.instructions WHERE org_id = $1`, orgID) if errors.Is(err, sql.ErrNoRows) { return "", nil } if err != nil { return "", fmt.Errorf("read instructions: %w", err) } return body, nil } // PutInstructions records the organisation's standing instructions. func (s *Store) PutInstructions(ctx context.Context, orgID, body string) error { if _, err := s.db.ExecContext(ctx, ` INSERT INTO governance.instructions (org_id, body) VALUES ($1, $2) ON CONFLICT (org_id) DO UPDATE SET body = EXCLUDED.body, updated_at = now()`, orgID, body); err != nil { return fmt.Errorf("put instructions: %w", err) } return nil }