Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

31.5 KB
Raw Blame
// Code generated by sqlc. DO NOT EDIT.
// versions:
//   sqlc v1.29.0
// source: reminder.sql

package store

import (
	"context"

	"github.com/jackc/pgx/v5/pgtype"
)

const advanceRoomReminderSchedule = `-- name: AdvanceRoomReminderSchedule :one
UPDATE room_reminders
SET next_run_at=$1::timestamptz,
    updated_at=clock_timestamp()
WHERE id=$2::text
  AND enabled
  AND next_run_at=$3::timestamptz
RETURNING id, tenant_id, room_id, created_by_actor_id, instruction, mention_actor_id, cadence_kind, timezone, hour, minute, enabled, next_run_at, revision, created_at, updated_at, name, weekdays, template_agent_actor_id, template_routine_key, trigger, run_at, tracking_item_id, tracking_purpose, interval_minutes
`

type AdvanceRoomReminderScheduleParams struct {
	NextRunAt         pgtype.Timestamptz `json:"next_run_at"`
	ID                string             `json:"id"`
	ExpectedNextRunAt pgtype.Timestamptz `json:"expected_next_run_at"`
}

func (q *Queries) AdvanceRoomReminderSchedule(ctx context.Context, arg AdvanceRoomReminderScheduleParams) (RoomReminder, error) {
	row := q.db.QueryRow(ctx, advanceRoomReminderSchedule, arg.NextRunAt, arg.ID, arg.ExpectedNextRunAt)
	var i RoomReminder
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.RoomID,
		&i.CreatedByActorID,
		&i.Instruction,
		&i.MentionActorID,
		&i.CadenceKind,
		&i.Timezone,
		&i.Hour,
		&i.Minute,
		&i.Enabled,
		&i.NextRunAt,
		&i.Revision,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.Name,
		&i.Weekdays,
		&i.TemplateAgentActorID,
		&i.TemplateRoutineKey,
		&i.Trigger,
		&i.RunAt,
		&i.TrackingItemID,
		&i.TrackingPurpose,
		&i.IntervalMinutes,
	)
	return i, err
}

const countRoomReminders = `-- name: CountRoomReminders :one
SELECT count(*)::bigint
FROM room_reminders
WHERE room_id=$1::text AND tenant_id=$2::text
  AND (cadence_kind<>'once' OR enabled)
`

type CountRoomRemindersParams struct {
	RoomID   string `json:"room_id"`
	TenantID string `json:"tenant_id"`
}

// A one-shot Routine that already fired is done and does not count.
func (q *Queries) CountRoomReminders(ctx context.Context, arg CountRoomRemindersParams) (int64, error) {
	row := q.db.QueryRow(ctx, countRoomReminders, arg.RoomID, arg.TenantID)
	var column_1 int64
	err := row.Scan(&column_1)
	return column_1, err
}

const createRoomReminder = `-- name: CreateRoomReminder :one
INSERT INTO room_reminders (
    id, tenant_id, room_id, created_by_actor_id, name, instruction, mention_actor_id,
    cadence_kind, timezone, hour, minute, weekdays, interval_minutes, run_at,
    enabled, next_run_at, template_agent_actor_id, template_routine_key, "trigger",
    tracking_item_id, tracking_purpose
) VALUES (
    $1, $2, $3, $4,
    $5, $6, $7, $8, $9,
    $10, $11, $12::text[], $13,
    $14, $15, $16, $17,
    $18, $19::jsonb,
    $20, $21
)
RETURNING id, tenant_id, room_id, created_by_actor_id, instruction, mention_actor_id, cadence_kind, timezone, hour, minute, enabled, next_run_at, revision, created_at, updated_at, name, weekdays, template_agent_actor_id, template_routine_key, trigger, run_at, tracking_item_id, tracking_purpose, interval_minutes
`

type CreateRoomReminderParams struct {
	ID                   string             `json:"id"`
	TenantID             string             `json:"tenant_id"`
	RoomID               string             `json:"room_id"`
	CreatedByActorID     string             `json:"created_by_actor_id"`
	Name                 string             `json:"name"`
	Instruction          string             `json:"instruction"`
	MentionActorID       pgtype.Text        `json:"mention_actor_id"`
	CadenceKind          pgtype.Text        `json:"cadence_kind"`
	Timezone             string             `json:"timezone"`
	Hour                 pgtype.Int4        `json:"hour"`
	Minute               pgtype.Int4        `json:"minute"`
	Weekdays             []string           `json:"weekdays"`
	IntervalMinutes      pgtype.Int4        `json:"interval_minutes"`
	RunAt                pgtype.Timestamptz `json:"run_at"`
	Enabled              bool               `json:"enabled"`
	NextRunAt            pgtype.Timestamptz `json:"next_run_at"`
	TemplateAgentActorID pgtype.Text        `json:"template_agent_actor_id"`
	TemplateRoutineKey   pgtype.Text        `json:"template_routine_key"`
	TriggerSpec          []byte             `json:"trigger_spec"`
	TrackingItemID       pgtype.Text        `json:"tracking_item_id"`
	TrackingPurpose      pgtype.Text        `json:"tracking_purpose"`
}

func (q *Queries) CreateRoomReminder(ctx context.Context, arg CreateRoomReminderParams) (RoomReminder, error) {
	row := q.db.QueryRow(ctx, createRoomReminder,
		arg.ID,
		arg.TenantID,
		arg.RoomID,
		arg.CreatedByActorID,
		arg.Name,
		arg.Instruction,
		arg.MentionActorID,
		arg.CadenceKind,
		arg.Timezone,
		arg.Hour,
		arg.Minute,
		arg.Weekdays,
		arg.IntervalMinutes,
		arg.RunAt,
		arg.Enabled,
		arg.NextRunAt,
		arg.TemplateAgentActorID,
		arg.TemplateRoutineKey,
		arg.TriggerSpec,
		arg.TrackingItemID,
		arg.TrackingPurpose,
	)
	var i RoomReminder
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.RoomID,
		&i.CreatedByActorID,
		&i.Instruction,
		&i.MentionActorID,
		&i.CadenceKind,
		&i.Timezone,
		&i.Hour,
		&i.Minute,
		&i.Enabled,
		&i.NextRunAt,
		&i.Revision,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.Name,
		&i.Weekdays,
		&i.TemplateAgentActorID,
		&i.TemplateRoutineKey,
		&i.Trigger,
		&i.RunAt,
		&i.TrackingItemID,
		&i.TrackingPurpose,
		&i.IntervalMinutes,
	)
	return i, err
}

const deleteRoomReminder = `-- name: DeleteRoomReminder :one
DELETE FROM room_reminders
WHERE id=$1::text
  AND tenant_id=$2::text
  AND room_id=$3::text
  AND revision=$4::bigint
RETURNING id, tenant_id, room_id, created_by_actor_id, instruction, mention_actor_id, cadence_kind, timezone, hour, minute, enabled, next_run_at, revision, created_at, updated_at, name, weekdays, template_agent_actor_id, template_routine_key, trigger, run_at, tracking_item_id, tracking_purpose, interval_minutes
`

type DeleteRoomReminderParams struct {
	ID               string `json:"id"`
	TenantID         string `json:"tenant_id"`
	RoomID           string `json:"room_id"`
	ExpectedRevision int64  `json:"expected_revision"`
}

func (q *Queries) DeleteRoomReminder(ctx context.Context, arg DeleteRoomReminderParams) (RoomReminder, error) {
	row := q.db.QueryRow(ctx, deleteRoomReminder,
		arg.ID,
		arg.TenantID,
		arg.RoomID,
		arg.ExpectedRevision,
	)
	var i RoomReminder
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.RoomID,
		&i.CreatedByActorID,
		&i.Instruction,
		&i.MentionActorID,
		&i.CadenceKind,
		&i.Timezone,
		&i.Hour,
		&i.Minute,
		&i.Enabled,
		&i.NextRunAt,
		&i.Revision,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.Name,
		&i.Weekdays,
		&i.TemplateAgentActorID,
		&i.TemplateRoutineKey,
		&i.Trigger,
		&i.RunAt,
		&i.TrackingItemID,
		&i.TrackingPurpose,
		&i.IntervalMinutes,
	)
	return i, err
}

const deleteTemplateRoomReminders = `-- name: DeleteTemplateRoomReminders :many
DELETE FROM room_reminders
WHERE template_routine_key=$1::text
RETURNING id, tenant_id, room_id, created_by_actor_id, instruction, mention_actor_id, cadence_kind, timezone, hour, minute, enabled, next_run_at, revision, created_at, updated_at, name, weekdays, template_agent_actor_id, template_routine_key, trigger, run_at, tracking_item_id, tracking_purpose, interval_minutes
`

func (q *Queries) DeleteTemplateRoomReminders(ctx context.Context, templateRoutineKey string) ([]RoomReminder, error) {
	rows, err := q.db.Query(ctx, deleteTemplateRoomReminders, templateRoutineKey)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []RoomReminder{}
	for rows.Next() {
		var i RoomReminder
		if err := rows.Scan(
			&i.ID,
			&i.TenantID,
			&i.RoomID,
			&i.CreatedByActorID,
			&i.Instruction,
			&i.MentionActorID,
			&i.CadenceKind,
			&i.Timezone,
			&i.Hour,
			&i.Minute,
			&i.Enabled,
			&i.NextRunAt,
			&i.Revision,
			&i.CreatedAt,
			&i.UpdatedAt,
			&i.Name,
			&i.Weekdays,
			&i.TemplateAgentActorID,
			&i.TemplateRoutineKey,
			&i.Trigger,
			&i.RunAt,
			&i.TrackingItemID,
			&i.TrackingPurpose,
			&i.IntervalMinutes,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const deleteTrackingItemRoomReminders = `-- name: DeleteTrackingItemRoomReminders :many
DELETE FROM room_reminders
WHERE tenant_id=$1::text
  AND tracking_item_id=ANY($2::text[])
RETURNING id, tenant_id, room_id, created_by_actor_id, instruction, mention_actor_id, cadence_kind, timezone, hour, minute, enabled, next_run_at, revision, created_at, updated_at, name, weekdays, template_agent_actor_id, template_routine_key, trigger, run_at, tracking_item_id, tracking_purpose, interval_minutes
`

type DeleteTrackingItemRoomRemindersParams struct {
	TenantID        string   `json:"tenant_id"`
	TrackingItemIds []string `json:"tracking_item_ids"`
}

// The Routines serving Tracking Items about to be deleted go first, so each
// deletion is recorded in its Room instead of cascading silently.
func (q *Queries) DeleteTrackingItemRoomReminders(ctx context.Context, arg DeleteTrackingItemRoomRemindersParams) ([]RoomReminder, error) {
	rows, err := q.db.Query(ctx, deleteTrackingItemRoomReminders, arg.TenantID, arg.TrackingItemIds)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []RoomReminder{}
	for rows.Next() {
		var i RoomReminder
		if err := rows.Scan(
			&i.ID,
			&i.TenantID,
			&i.RoomID,
			&i.CreatedByActorID,
			&i.Instruction,
			&i.MentionActorID,
			&i.CadenceKind,
			&i.Timezone,
			&i.Hour,
			&i.Minute,
			&i.Enabled,
			&i.NextRunAt,
			&i.Revision,
			&i.CreatedAt,
			&i.UpdatedAt,
			&i.Name,
			&i.Weekdays,
			&i.TemplateAgentActorID,
			&i.TemplateRoutineKey,
			&i.Trigger,
			&i.RunAt,
			&i.TrackingItemID,
			&i.TrackingPurpose,
			&i.IntervalMinutes,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const finishRoomReminderSchedule = `-- name: FinishRoomReminderSchedule :one
UPDATE room_reminders
SET enabled=false,
    next_run_at=NULL,
    revision=revision+1,
    updated_at=clock_timestamp()
WHERE id=$1::text
  AND enabled
  AND next_run_at=$2::timestamptz
RETURNING id, tenant_id, room_id, created_by_actor_id, instruction, mention_actor_id, cadence_kind, timezone, hour, minute, enabled, next_run_at, revision, created_at, updated_at, name, weekdays, template_agent_actor_id, template_routine_key, trigger, run_at, tracking_item_id, tracking_purpose, interval_minutes
`

type FinishRoomReminderScheduleParams struct {
	ID                string             `json:"id"`
	ExpectedNextRunAt pgtype.Timestamptz `json:"expected_next_run_at"`
}

// A one-shot Routine past its occurrence is done: disabled, nothing scheduled.
func (q *Queries) FinishRoomReminderSchedule(ctx context.Context, arg FinishRoomReminderScheduleParams) (RoomReminder, error) {
	row := q.db.QueryRow(ctx, finishRoomReminderSchedule, arg.ID, arg.ExpectedNextRunAt)
	var i RoomReminder
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.RoomID,
		&i.CreatedByActorID,
		&i.Instruction,
		&i.MentionActorID,
		&i.CadenceKind,
		&i.Timezone,
		&i.Hour,
		&i.Minute,
		&i.Enabled,
		&i.NextRunAt,
		&i.Revision,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.Name,
		&i.Weekdays,
		&i.TemplateAgentActorID,
		&i.TemplateRoutineKey,
		&i.Trigger,
		&i.RunAt,
		&i.TrackingItemID,
		&i.TrackingPurpose,
		&i.IntervalMinutes,
	)
	return i, err
}

const getAgentOwnedTrackingItem = `-- name: GetAgentOwnedTrackingItem :one
SELECT item.id, item.content
FROM memory_index.tracking_items item
JOIN agent_registrations registration ON registration.represented_human_actor_id=item.owner_actor_id
 AND registration.tenant_id=item.tenant_id
WHERE item.id=$1::text AND registration.actor_id=$2::text
  AND registration.agent_type='anotherme' AND registration.status<>'revoked'
`

type GetAgentOwnedTrackingItemParams struct {
	ID           string `json:"id"`
	AgentActorID string `json:"agent_actor_id"`
}

type GetAgentOwnedTrackingItemRow struct {
	ID      string `json:"id"`
	Content string `json:"content"`
}

// A Tracking Item of the Human this AnotherMe represents.
func (q *Queries) GetAgentOwnedTrackingItem(ctx context.Context, arg GetAgentOwnedTrackingItemParams) (GetAgentOwnedTrackingItemRow, error) {
	row := q.db.QueryRow(ctx, getAgentOwnedTrackingItem, arg.ID, arg.AgentActorID)
	var i GetAgentOwnedTrackingItemRow
	err := row.Scan(&i.ID, &i.Content)
	return i, err
}

const getHumanActorTenantID = `-- name: GetHumanActorTenantID :one
SELECT tenant_id FROM actors WHERE id=$1::text AND kind='human'
`

func (q *Queries) GetHumanActorTenantID(ctx context.Context, id string) (string, error) {
	row := q.db.QueryRow(ctx, getHumanActorTenantID, id)
	var tenant_id string
	err := row.Scan(&tenant_id)
	return tenant_id, err
}

const getLatestActiveHumanMessageAuthorID = `-- name: GetLatestActiveHumanMessageAuthorID :one
SELECT actor.id
FROM messages message
JOIN actors actor
  ON actor.id=message.author_actor_id
 AND actor.tenant_id=message.tenant_id
JOIN active_room_members membership
  ON membership.room_id=message.room_id
 AND membership.tenant_id=message.tenant_id
 AND membership.actor_id=actor.id
WHERE message.room_id=$1::text
  AND message.tenant_id=$2::text
  AND message.message_kind='conversation'
  AND actor.kind='human'
  AND message.created_at<=$3::timestamptz
ORDER BY message.created_at DESC, message.id DESC
LIMIT 1
`

type GetLatestActiveHumanMessageAuthorIDParams struct {
	RoomID   string             `json:"room_id"`
	TenantID string             `json:"tenant_id"`
	Before   pgtype.Timestamptz `json:"before"`
}

func (q *Queries) GetLatestActiveHumanMessageAuthorID(ctx context.Context, arg GetLatestActiveHumanMessageAuthorIDParams) (string, error) {
	row := q.db.QueryRow(ctx, getLatestActiveHumanMessageAuthorID, arg.RoomID, arg.TenantID, arg.Before)
	var id string
	err := row.Scan(&id)
	return id, err
}

const getRoomReminder = `-- name: GetRoomReminder :one
SELECT id, tenant_id, room_id, created_by_actor_id, instruction, mention_actor_id, cadence_kind, timezone, hour, minute, enabled, next_run_at, revision, created_at, updated_at, name, weekdays, template_agent_actor_id, template_routine_key, trigger, run_at, tracking_item_id, tracking_purpose, interval_minutes
FROM room_reminders
WHERE id=$1::text AND tenant_id=$2::text AND room_id=$3::text
`

type GetRoomReminderParams struct {
	ID       string `json:"id"`
	TenantID string `json:"tenant_id"`
	RoomID   string `json:"room_id"`
}

func (q *Queries) GetRoomReminder(ctx context.Context, arg GetRoomReminderParams) (RoomReminder, error) {
	row := q.db.QueryRow(ctx, getRoomReminder, arg.ID, arg.TenantID, arg.RoomID)
	var i RoomReminder
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.RoomID,
		&i.CreatedByActorID,
		&i.Instruction,
		&i.MentionActorID,
		&i.CadenceKind,
		&i.Timezone,
		&i.Hour,
		&i.Minute,
		&i.Enabled,
		&i.NextRunAt,
		&i.Revision,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.Name,
		&i.Weekdays,
		&i.TemplateAgentActorID,
		&i.TemplateRoutineKey,
		&i.Trigger,
		&i.RunAt,
		&i.TrackingItemID,
		&i.TrackingPurpose,
		&i.IntervalMinutes,
	)
	return i, err
}

const getRoomReminderRoomID = `-- name: GetRoomReminderRoomID :one
SELECT room_id
FROM room_reminders
WHERE id=$1::text
`

// The Room a Routine write authorizes in; the Routine row is locked afterwards.
func (q *Queries) GetRoomReminderRoomID(ctx context.Context, id string) (string, error) {
	row := q.db.QueryRow(ctx, getRoomReminderRoomID, id)
	var room_id string
	err := row.Scan(&room_id)
	return room_id, err
}

const getRoutineLatestOccurrenceState = `-- name: GetRoutineLatestOccurrenceState :one
WITH latest_wake AS (
    SELECT wake.created_at
    FROM proactive_pending_wakes wake
    WHERE wake.room_id=$1::text
      AND wake.fired_routine_id=$2::text
      AND wake.delivered_at IS NULL
    ORDER BY wake.created_at DESC, wake.id DESC
    LIMIT 1
),
latest_message AS (
    SELECT m.id, m.created_at, m.mentioned_actor_ids
    FROM messages m
    WHERE m.room_id=$1::text
      AND m.fired_routine_id=$2::text
    ORDER BY m.created_at DESC, m.id DESC
    LIMIT 1
)
SELECT
    (SELECT created_at FROM latest_wake)::timestamptz AS latest_undelivered_wake_at,
    (SELECT created_at FROM latest_message)::timestamptz AS latest_message_created_at,
    coalesce((
        SELECT (
            EXISTS (
                SELECT 1
                FROM agent_runtime_inputs input
                JOIN agent_local_run_inputs relation
                  ON relation.context_key=input.context_key
                 AND relation.input_id=input.input_id
                JOIN agent_local_runs run
                  ON run.context_key=relation.context_key
                 AND run.run_id=relation.run_id
                WHERE input.source_kind='inbox'
                  AND input.source_message_id=lm.id
                  AND run.status IN ('succeeded', 'failed', 'canceled')
            )
            OR EXISTS (
                SELECT 1
                FROM agent_execution_contexts ctx
                JOIN agent_runtime_inputs input
                  ON input.context_key=ctx.context_key
                JOIN agent_local_run_inputs relation
                  ON relation.context_key=input.context_key
                 AND relation.input_id=input.input_id
                JOIN agent_local_runs run
                  ON run.context_key=relation.context_key
                 AND run.run_id=relation.run_id
                WHERE ctx.context_kind='meta'
                  AND ctx.room_id=$1::text
                  AND ctx.agent_actor_id=ANY(lm.mentioned_actor_ids)
                  AND input.source_kind='inbox'
                  AND input.created_at>=lm.created_at
                  AND jsonb_typeof(input.payload->'invocationMessageIds')='array'
                  AND (input.payload->'invocationMessageIds') ? lm.id
                  AND run.status IN ('succeeded', 'failed', 'canceled')
            )
        )
        FROM latest_message lm
    ), false)::boolean AS latest_message_terminal
`

type GetRoutineLatestOccurrenceStateParams struct {
	RoomID    string `json:"room_id"`
	RoutineID string `json:"routine_id"`
}

type GetRoutineLatestOccurrenceStateRow struct {
	LatestUndeliveredWakeAt pgtype.Timestamptz `json:"latest_undelivered_wake_at"`
	LatestMessageCreatedAt  pgtype.Timestamptz `json:"latest_message_created_at"`
	LatestMessageTerminal   bool               `json:"latest_message_terminal"`
}

// Reports the Routine's newest undelivered quiet wake and newest trigger
// Message (and whether that Message reached a terminal Run), so the scheduler
// can skip overlapping fires without blocking forever after 24 hours.
func (q *Queries) GetRoutineLatestOccurrenceState(ctx context.Context, arg GetRoutineLatestOccurrenceStateParams) (GetRoutineLatestOccurrenceStateRow, error) {
	row := q.db.QueryRow(ctx, getRoutineLatestOccurrenceState, arg.RoomID, arg.RoutineID)
	var i GetRoutineLatestOccurrenceStateRow
	err := row.Scan(&i.LatestUndeliveredWakeAt, &i.LatestMessageCreatedAt, &i.LatestMessageTerminal)
	return i, err
}

const isTrackingItemClosed = `-- name: IsTrackingItemClosed :one
SELECT EXISTS (
  SELECT 1 FROM memory_index.tracking_items WHERE id=$1::text AND status='done'
)::boolean
`

// A Routine serving a done Tracking Item has nothing left to do.
func (q *Queries) IsTrackingItemClosed(ctx context.Context, id string) (bool, error) {
	row := q.db.QueryRow(ctx, isTrackingItemClosed, id)
	var column_1 bool
	err := row.Scan(&column_1)
	return column_1, err
}

const listActiveHumanRoomMemberIDs = `-- name: ListActiveHumanRoomMemberIDs :many
SELECT actor.id
FROM active_room_members membership
JOIN actors actor
  ON actor.id=membership.actor_id
 AND actor.tenant_id=membership.tenant_id
WHERE membership.room_id=$1::text
  AND membership.tenant_id=$2::text
  AND actor.kind='human'
ORDER BY actor.id
`

type ListActiveHumanRoomMemberIDsParams struct {
	RoomID   string `json:"room_id"`
	TenantID string `json:"tenant_id"`
}

func (q *Queries) ListActiveHumanRoomMemberIDs(ctx context.Context, arg ListActiveHumanRoomMemberIDsParams) ([]string, error) {
	rows, err := q.db.Query(ctx, listActiveHumanRoomMemberIDs, arg.RoomID, arg.TenantID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []string{}
	for rows.Next() {
		var id string
		if err := rows.Scan(&id); err != nil {
			return nil, err
		}
		items = append(items, id)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listOverdueRoomReminderOccurrences = `-- name: ListOverdueRoomReminderOccurrences :many
SELECT reminder.id, reminder.next_run_at
FROM room_reminders reminder
JOIN rooms room ON room.id=reminder.room_id AND room.tenant_id=reminder.tenant_id
WHERE reminder.enabled
  AND reminder.next_run_at<clock_timestamp()-interval '2 minutes'
  AND room.deleted_at IS NULL
ORDER BY reminder.next_run_at, reminder.id
`

type ListOverdueRoomReminderOccurrencesRow struct {
	ID        string             `json:"id"`
	NextRunAt pgtype.Timestamptz `json:"next_run_at"`
}

func (q *Queries) ListOverdueRoomReminderOccurrences(ctx context.Context) ([]ListOverdueRoomReminderOccurrencesRow, error) {
	rows, err := q.db.Query(ctx, listOverdueRoomReminderOccurrences)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListOverdueRoomReminderOccurrencesRow{}
	for rows.Next() {
		var i ListOverdueRoomReminderOccurrencesRow
		if err := rows.Scan(&i.ID, &i.NextRunAt); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listRoomReminders = `-- name: ListRoomReminders :many
SELECT id, tenant_id, room_id, created_by_actor_id, instruction, mention_actor_id, cadence_kind, timezone, hour, minute, enabled, next_run_at, revision, created_at, updated_at, name, weekdays, template_agent_actor_id, template_routine_key, trigger, run_at, tracking_item_id, tracking_purpose, interval_minutes
FROM room_reminders
WHERE room_id=$1::text
  AND tenant_id=$2::text
  AND (
    $3::timestamptz IS NULL
    OR (created_at, id) < ($3::timestamptz, $4::text)
  )
ORDER BY created_at DESC, id DESC
LIMIT $5::int
`

type ListRoomRemindersParams struct {
	RoomID          string             `json:"room_id"`
	TenantID        string             `json:"tenant_id"`
	CursorCreatedAt pgtype.Timestamptz `json:"cursor_created_at"`
	CursorID        pgtype.Text        `json:"cursor_id"`
	ListLimit       int32              `json:"list_limit"`
}

func (q *Queries) ListRoomReminders(ctx context.Context, arg ListRoomRemindersParams) ([]RoomReminder, error) {
	rows, err := q.db.Query(ctx, listRoomReminders,
		arg.RoomID,
		arg.TenantID,
		arg.CursorCreatedAt,
		arg.CursorID,
		arg.ListLimit,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []RoomReminder{}
	for rows.Next() {
		var i RoomReminder
		if err := rows.Scan(
			&i.ID,
			&i.TenantID,
			&i.RoomID,
			&i.CreatedByActorID,
			&i.Instruction,
			&i.MentionActorID,
			&i.CadenceKind,
			&i.Timezone,
			&i.Hour,
			&i.Minute,
			&i.Enabled,
			&i.NextRunAt,
			&i.Revision,
			&i.CreatedAt,
			&i.UpdatedAt,
			&i.Name,
			&i.Weekdays,
			&i.TemplateAgentActorID,
			&i.TemplateRoutineKey,
			&i.Trigger,
			&i.RunAt,
			&i.TrackingItemID,
			&i.TrackingPurpose,
			&i.IntervalMinutes,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const lockDueRoomReminderOccurrence = `-- name: LockDueRoomReminderOccurrence :one
SELECT reminder.id, reminder.tenant_id, reminder.room_id, reminder.created_by_actor_id, reminder.instruction, reminder.mention_actor_id, reminder.cadence_kind, reminder.timezone, reminder.hour, reminder.minute, reminder.enabled, reminder.next_run_at, reminder.revision, reminder.created_at, reminder.updated_at, reminder.name, reminder.weekdays, reminder.template_agent_actor_id, reminder.template_routine_key, reminder.trigger, reminder.run_at, reminder.tracking_item_id, reminder.tracking_purpose, reminder.interval_minutes
FROM room_reminders reminder
JOIN rooms room ON room.id=reminder.room_id AND room.tenant_id=reminder.tenant_id
WHERE reminder.id=$1::text
  AND reminder.enabled
  AND reminder.next_run_at=$2::timestamptz
  AND room.deleted_at IS NULL
FOR UPDATE OF reminder
`

type LockDueRoomReminderOccurrenceParams struct {
	ID    string             `json:"id"`
	DueAt pgtype.Timestamptz `json:"due_at"`
}

// Locks one scheduled occurrence. An edited, paused, deleted, or already advanced
// Reminder has no row at this due time, so its stale job does nothing.
func (q *Queries) LockDueRoomReminderOccurrence(ctx context.Context, arg LockDueRoomReminderOccurrenceParams) (RoomReminder, error) {
	row := q.db.QueryRow(ctx, lockDueRoomReminderOccurrence, arg.ID, arg.DueAt)
	var i RoomReminder
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.RoomID,
		&i.CreatedByActorID,
		&i.Instruction,
		&i.MentionActorID,
		&i.CadenceKind,
		&i.Timezone,
		&i.Hour,
		&i.Minute,
		&i.Enabled,
		&i.NextRunAt,
		&i.Revision,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.Name,
		&i.Weekdays,
		&i.TemplateAgentActorID,
		&i.TemplateRoutineKey,
		&i.Trigger,
		&i.RunAt,
		&i.TrackingItemID,
		&i.TrackingPurpose,
		&i.IntervalMinutes,
	)
	return i, err
}

const lockRoomReminder = `-- name: LockRoomReminder :one
SELECT id, tenant_id, room_id, created_by_actor_id, instruction, mention_actor_id, cadence_kind, timezone, hour, minute, enabled, next_run_at, revision, created_at, updated_at, name, weekdays, template_agent_actor_id, template_routine_key, trigger, run_at, tracking_item_id, tracking_purpose, interval_minutes
FROM room_reminders
WHERE id=$1::text AND tenant_id=$2::text AND room_id=$3::text
FOR NO KEY UPDATE
`

type LockRoomReminderParams struct {
	ID       string `json:"id"`
	TenantID string `json:"tenant_id"`
	RoomID   string `json:"room_id"`
}

// NO KEY UPDATE still lets a listener poll record deliveries, which reference
// the Routine, while a write holds it.
func (q *Queries) LockRoomReminder(ctx context.Context, arg LockRoomReminderParams) (RoomReminder, error) {
	row := q.db.QueryRow(ctx, lockRoomReminder, arg.ID, arg.TenantID, arg.RoomID)
	var i RoomReminder
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.RoomID,
		&i.CreatedByActorID,
		&i.Instruction,
		&i.MentionActorID,
		&i.CadenceKind,
		&i.Timezone,
		&i.Hour,
		&i.Minute,
		&i.Enabled,
		&i.NextRunAt,
		&i.Revision,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.Name,
		&i.Weekdays,
		&i.TemplateAgentActorID,
		&i.TemplateRoutineKey,
		&i.Trigger,
		&i.RunAt,
		&i.TrackingItemID,
		&i.TrackingPurpose,
		&i.IntervalMinutes,
	)
	return i, err
}

const resolveReminderAgentRoomAuthority = `-- name: ResolveReminderAgentRoomAuthority :one
SELECT room.tenant_id, caller.id AS actor_id, membership.role
FROM rooms room
JOIN actors caller
  ON caller.tenant_id=room.tenant_id
 AND caller.id=$1::text
 AND caller.kind='agent'
JOIN agent_registrations registration
  ON registration.actor_id=caller.id
 AND registration.tenant_id=caller.tenant_id
 AND registration.agent_management_id=$2::text
 AND registration.status='active'
JOIN room_members membership
  ON membership.room_id=room.id
 AND membership.actor_id=caller.id
WHERE room.id=$3::text
  AND room.deleted_at IS NULL
  AND room_actor_participating(room.id, caller.id)
FOR KEY SHARE OF membership, registration
`

type ResolveReminderAgentRoomAuthorityParams struct {
	ActorID           string `json:"actor_id"`
	AgentManagementID string `json:"agent_management_id"`
	RoomID            string `json:"room_id"`
}

type ResolveReminderAgentRoomAuthorityRow struct {
	TenantID string `json:"tenant_id"`
	ActorID  string `json:"actor_id"`
	Role     string `json:"role"`
}

func (q *Queries) ResolveReminderAgentRoomAuthority(ctx context.Context, arg ResolveReminderAgentRoomAuthorityParams) (ResolveReminderAgentRoomAuthorityRow, error) {
	row := q.db.QueryRow(ctx, resolveReminderAgentRoomAuthority, arg.ActorID, arg.AgentManagementID, arg.RoomID)
	var i ResolveReminderAgentRoomAuthorityRow
	err := row.Scan(&i.TenantID, &i.ActorID, &i.Role)
	return i, err
}

const resolveReminderHumanRoomAuthority = `-- name: ResolveReminderHumanRoomAuthority :one
SELECT room.tenant_id, caller.id AS actor_id, membership.role
FROM rooms room
JOIN actors caller
  ON caller.tenant_id=room.tenant_id
 AND caller.account_id=$1::text
 AND caller.kind='human'
JOIN room_members membership
  ON membership.room_id=room.id
 AND membership.actor_id=caller.id
WHERE room.id=$2::text
  AND room.deleted_at IS NULL
  AND room_actor_participating(room.id, caller.id)
FOR KEY SHARE OF membership
`

type ResolveReminderHumanRoomAuthorityParams struct {
	AccountID string `json:"account_id"`
	RoomID    string `json:"room_id"`
}

type ResolveReminderHumanRoomAuthorityRow struct {
	TenantID string `json:"tenant_id"`
	ActorID  string `json:"actor_id"`
	Role     string `json:"role"`
}

func (q *Queries) ResolveReminderHumanRoomAuthority(ctx context.Context, arg ResolveReminderHumanRoomAuthorityParams) (ResolveReminderHumanRoomAuthorityRow, error) {
	row := q.db.QueryRow(ctx, resolveReminderHumanRoomAuthority, arg.AccountID, arg.RoomID)
	var i ResolveReminderHumanRoomAuthorityRow
	err := row.Scan(&i.TenantID, &i.ActorID, &i.Role)
	return i, err
}

const updateRoomReminder = `-- name: UpdateRoomReminder :one
UPDATE room_reminders
SET name=$1,
    instruction=$2,
    mention_actor_id=$3,
    cadence_kind=$4,
    timezone=$5,
    hour=$6,
    minute=$7,
    weekdays=$8::text[],
    interval_minutes=$9,
    run_at=$10,
    enabled=$11,
    next_run_at=$12,
    revision=revision+1,
    updated_at=clock_timestamp()
WHERE id=$13::text
  AND tenant_id=$14::text
  AND room_id=$15::text
  AND revision=$16::bigint
  AND (NOT $11::boolean OR template_agent_actor_id IS NULL OR EXISTS (
      SELECT 1 FROM agent_registrations registration
      WHERE registration.actor_id=room_reminders.template_agent_actor_id AND registration.status='active'
  ))
RETURNING id, tenant_id, room_id, created_by_actor_id, instruction, mention_actor_id, cadence_kind, timezone, hour, minute, enabled, next_run_at, revision, created_at, updated_at, name, weekdays, template_agent_actor_id, template_routine_key, trigger, run_at, tracking_item_id, tracking_purpose, interval_minutes
`

type UpdateRoomReminderParams struct {
	Name             string             `json:"name"`
	Instruction      string             `json:"instruction"`
	MentionActorID   pgtype.Text        `json:"mention_actor_id"`
	CadenceKind      pgtype.Text        `json:"cadence_kind"`
	Timezone         string             `json:"timezone"`
	Hour             pgtype.Int4        `json:"hour"`
	Minute           pgtype.Int4        `json:"minute"`
	Weekdays         []string           `json:"weekdays"`
	IntervalMinutes  pgtype.Int4        `json:"interval_minutes"`
	RunAt            pgtype.Timestamptz `json:"run_at"`
	Enabled          bool               `json:"enabled"`
	NextRunAt        pgtype.Timestamptz `json:"next_run_at"`
	ID               string             `json:"id"`
	TenantID         string             `json:"tenant_id"`
	RoomID           string             `json:"room_id"`
	ExpectedRevision int64              `json:"expected_revision"`
}

func (q *Queries) UpdateRoomReminder(ctx context.Context, arg UpdateRoomReminderParams) (RoomReminder, error) {
	row := q.db.QueryRow(ctx, updateRoomReminder,
		arg.Name,
		arg.Instruction,
		arg.MentionActorID,
		arg.CadenceKind,
		arg.Timezone,
		arg.Hour,
		arg.Minute,
		arg.Weekdays,
		arg.IntervalMinutes,
		arg.RunAt,
		arg.Enabled,
		arg.NextRunAt,
		arg.ID,
		arg.TenantID,
		arg.RoomID,
		arg.ExpectedRevision,
	)
	var i RoomReminder
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.RoomID,
		&i.CreatedByActorID,
		&i.Instruction,
		&i.MentionActorID,
		&i.CadenceKind,
		&i.Timezone,
		&i.Hour,
		&i.Minute,
		&i.Enabled,
		&i.NextRunAt,
		&i.Revision,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.Name,
		&i.Weekdays,
		&i.TemplateAgentActorID,
		&i.TemplateRoutineKey,
		&i.Trigger,
		&i.RunAt,
		&i.TrackingItemID,
		&i.TrackingPurpose,
		&i.IntervalMinutes,
	)
	return i, err
}