Files
archie/modules/governance/internal/store/store.go
T
sam 0ad4374a2a refactor(judgement): rename action classes to action types and raises to autonomy proposals
- tables judgement.action_types, action_type_resets, action_type_approvals and autonomy_proposals (migration 00063)
- governance setting propose_autonomy_after, approval request kind autonomy, policy resource kind action_type
- /api/action-types replaces /api/classes; the detail lists autonomy_proposals
- an autonomy proposal stores the identity ID of the account that answered it
2026-11-23 23:43:45 +11:00

309 lines
12 KiB
Go

// Package store holds the governance module's SQL: the organisation's model
// roles.
package store
import (
"context"
"database/sql"
"errors"
"fmt"
"github.com/jmoiron/sqlx"
)
// ModelRole is the model an organisation chose for one role: a provider and a
// model name on it.
type ModelRole struct {
OrgID string `db:"org_id"`
Role string `db:"role"`
Provider string `db:"provider"`
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"`
Provider string `db:"provider"`
Model string `db:"model"`
Class string `db:"class"`
BaseURL string `db:"base_url"`
// APIKeyCredential names the credential whose token authenticates the
// provider, or empty when it needs no key.
APIKeyCredential string `db:"api_key_credential"`
}
// Provider is an endpoint models are called on: a provider class, base URL and
// the credential whose token authenticates it.
type Provider struct {
OrgID string `db:"org_id"`
Name string `db:"name"`
Class string `db:"class"`
BaseURL string `db:"base_url"`
APIKeyCredential string `db:"api_key_credential"`
}
// 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 org_id, name, class, base_url, api_key_credential
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
}
// Provider returns the named provider; ok is false when none exists.
func (s *Store) Provider(ctx context.Context, orgID, name string) (Provider, bool, error) {
var out Provider
err := s.db.GetContext(ctx, &out, `
SELECT org_id, name, class, base_url, api_key_credential
FROM governance.model_providers WHERE org_id = $1 AND name = $2`, orgID, name)
if errors.Is(err, sql.ErrNoRows) {
return Provider{}, false, nil
}
if err != nil {
return Provider{}, false, fmt.Errorf("read model provider %q: %w", name, err)
}
return out, true, nil
}
// PutProvider records a provider.
func (s *Store) PutProvider(ctx context.Context, p Provider) error {
if _, err := s.db.NamedExecContext(ctx, `
INSERT INTO governance.model_providers (org_id, name, class, base_url, api_key_credential)
VALUES (:org_id, :name, :class, :base_url, :api_key_credential)
ON CONFLICT (org_id, name) DO UPDATE
SET class = EXCLUDED.class, base_url = EXCLUDED.base_url,
api_key_credential = EXCLUDED.api_key_credential, updated_at = now()`, p); err != nil {
return fmt.Errorf("put model provider %q: %w", p.Name, err)
}
return nil
}
// DeleteProvider removes a provider and reports whether one existed.
func (s *Store) DeleteProvider(ctx context.Context, orgID, name string) (bool, error) {
res, err := s.db.ExecContext(ctx, `DELETE FROM governance.model_providers WHERE org_id = $1 AND name = $2`, orgID, name)
if err != nil {
return false, fmt.Errorf("delete model provider %q: %w", name, err)
}
n, err := res.RowsAffected()
if err != nil {
return false, fmt.Errorf("delete model provider %q: %w", name, err)
}
return n > 0, nil
}
// AliasesUsingProvider names the roles that call models through provider.
func (s *Store) AliasesUsingProvider(ctx context.Context, orgID, provider string) ([]string, error) {
var roles []string
if err := s.db.SelectContext(ctx, &roles, `
SELECT role FROM governance.model_roles WHERE org_id = $1 AND provider = $2 ORDER BY role`, orgID, provider); err != nil {
return nil, fmt.Errorf("read model roles for provider %q: %w", provider, 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, r.model, p.class, p.base_url, p.api_key_credential
FROM governance.model_roles r
JOIN governance.model_providers p ON p.org_id = r.org_id AND p.name = r.provider
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, r.model, p.class, p.base_url, p.api_key_credential
FROM governance.model_roles r
JOIN governance.model_providers p ON p.org_id = r.org_id AND p.name = r.provider
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, model)
VALUES (:org_id, :role, :provider, :model)
ON CONFLICT (org_id, role) DO UPDATE
SET provider = EXCLUDED.provider, model = EXCLUDED.model, updated_at = now()`, m); err != nil {
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
}