db

package
v0.167.2 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: MIT Imports: 38 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package db provides the database interface.

Index

Constants

View Source
const (
	// FactsToCheckStated are facts as they stand.
	FactsToCheckStated = "stated"
	// FactsToCheckDated are events with a date, which a question can ask
	// the when of.
	FactsToCheckDated = "dated"
	// FactsToCheckChanged are facts a later one replaced, which a question
	// can ask about as something that changed.
	FactsToCheckChanged = "changed"
)

The facts a memory check asks about, by what they are.

View Source
const (
	FinanceTransactionLimitDefault = 50
	FinanceTransactionLimitMost    = 200
)

How many finance transactions one page holds.

View Source
const (
	FinanceTradeLimitDefault = 50
	FinanceTradeLimitMost    = 200
)

How many trades one page holds.

View Source
const (
	FinanceReceiptLimitDefault = 50
	FinanceReceiptLimitMost    = 200
)

How many finance receipts one listing holds.

View Source
const (
	FinanceTaxDocumentLimitDefault = 60
	FinanceTaxDocumentLimitMost    = 200
)

How many paystubs or tax forms one listing holds. A year of weekly paystubs is 53.

View Source
const (
	// RecordingLiveUtterancesPerRecordingMaximum bounds the utterances one
	// recording keeps; a capture saying more than this is not being kept up
	// with by anyone reading it.
	RecordingLiveUtterancesPerRecordingMaximum = 5000

	// RecordingLiveUtteranceTextBytesMaximum bounds one utterance's words.
	RecordingLiveUtteranceTextBytesMaximum = 8192
)

The bounds of what a capture keeps.

View Source
const AgentCommandChannel = "agent_command"

AgentCommandChannel is what an instance LISTENs on for a word to a turn it runs, given on another instance.

View Source
const AgentEventChannel = "agent_event"

AgentEventChannel is what an instance LISTENs on to hear the events of the turns running on the other instances.

View Source
const AnyWord = `replace(plainto_tsquery('simple', ?)::text, ' & ', ' | ')::tsquery`

AnyWord is the tsquery for "any of these words, best match first".

`plainto_tsquery` joins the words it finds with AND, and with the `simple` dictionary it drops nothing -- so "what is the portal?" asks for a row holding *what*, *is*, *the* and *portal*, and the page called Portal does not have the first three. Every question phrased as a sentence found nothing.

Joining with OR instead and letting `ts_rank` sort it out is what a search should do: a row matching three words of four comes above one matching one. The replacement is on what `plainto_tsquery` produced, so whatever the person typed has already been made safe.

`simple` cannot segment Chinese or Japanese, so a graph whose words are in those is found by meaning and not here; the tool's answer says so.

View Source
const BytesPerBook = 64 << 20

BytesPerBook is how much one address book may hold, counted in the cards themselves.

The count above bounds the wrong thing on its own. A card may be a megabyte -- a photograph makes one -- so ten thousand of them is ten gigabytes, and the listing a client reads is the whole book built in memory and then serialised whole, because the protocol library has no streaming. Two thousand legal cards were therefore a way for one account to take the server down for everybody on it.

Sixty-four megabytes is far past any address book a person keeps: sixty thousand ordinary cards, or thirteen hundred carrying a photograph. It is checked where a card is written, so a client is told plainly.

View Source
const BytesPerCalendar = 64 << 20

BytesPerCalendar is how much one calendar may hold, counted in the files themselves.

The count above bounds the wrong thing on its own: a file may be a megabyte -- a long series with an override per occurrence makes one -- so ten thousand of them is ten gigabytes, and a listing is the whole calendar built in memory and serialised whole. The same number as an address book, for the same reason, and far past any calendar a person keeps.

View Source
const ContactsPerBook = 10000

ContactsPerBook is how many contacts one address book may hold.

There has to be a number, because the listing a client reads is the whole book in one response and nothing else bounds it. It is enforced where a contact is written, so a client is told plainly, rather than by cutting the listing short, which would read to a phone as "those people were deleted". ContactsPerBook is exported because both doors into an address book -- the dashboard's API and CardDAV -- have to enforce the same number, and a limit enforced on one of two doors is not a limit.

View Source
const ExchangeRateStaleDays = 7

ExchangeRateStaleDays is how many days before the day asked the latest rate may be and still be used. The longest the ECB goes without publishing is the TARGET closing over Christmas and a weekend, four or five days. A rate older than this means the fetch has been failing or the ECB stopped publishing the currency, and an amount converted with it would be wrong without anybody noticing, so it is reported unconverted instead.

View Source
const FolderChangedChannel = "folder_changed"

FolderChangedChannel is what an instance LISTENs on to learn that a folder changed somewhere; the payload is the folder's identifier.

View Source
const MaximumInvitationAttempts = 5

MaximumInvitationAttempts is how many times reading one is tried before it is left alone. A message that cannot be read will not become readable, and retrying for ever fills the log with the same failure.

View Source
const ObjectsPerCalendar = 10000

ObjectsPerCalendar is how many events one calendar may hold.

There has to be a number, because the listing a client reads is the whole calendar in one response and nothing else bounds it. It is enforced where an object is written, so a client is told plainly, rather than by cutting the listing short, which would read to a phone as "those events were deleted". Exported because both doors into a calendar -- the dashboard's API and CalDAV -- have to enforce the same number, and a limit enforced on one of two doors is not a limit.

View Source
const OccurrencesPerWindow = 100000

OccurrencesPerWindow is how many times something happening this server will describe in one answer.

There has to be a number, because the window is chosen by whoever is asking and every occurrence in it is written out. It is not the number of events a calendar may hold: one repeating file contributes thousands of these, so bounding occurrences by that number cut a three-year window off after a few months -- and because the rows come back in order, what was cut was always the far end. Free-busy then reported somebody free for the rest of the window, which is the one mistake that code is written not to make.

View Source
const TaxDocumentUnreadRetention = 30 * 24 * time.Hour

TaxDocumentUnreadRetention is how long a file handed in as a paystub or a tax form is kept when nothing was read out of it: time enough for the reading job's retries and for the person to notice and read it again.

View Source
const TouchInterval = time.Minute

TouchInterval is how stale "last used" is allowed to get before a request writes it back.

Writing it on every request would put a row update in front of every page the dashboard loads, for a column nobody reads more precisely than "this morning". A minute is far finer than the list shows and turns a busy session from one write per request into one per minute.

The comparison is against the stored value rather than anything held in memory, so several instances do not each keep their own idea of when it was last written.

View Source
const WatchLookID = "(look)"

WatchLookID is the record a look leaves of itself, among the items.

Variables

View Source
var (
	MailEmbeddingTable = VectorTable{Table: "mail_embedding", IDColumn: "mail_id", ScopeColumn: "mailbox_id", OrderColumn: "created_at", Candidates: 3000}
	AgentMemoryTable   = VectorTable{Table: "agent_memory", IDColumn: "id", ScopeColumn: "agent_id", OrderColumn: "modified_at", Candidates: 1000}
	AgentNodeTable     = VectorTable{Table: "agent_node_vector", IDColumn: "node_id", ScopeColumn: "agent_id", OrderColumn: "created_at", Candidates: 2000}
	AgentFactTable     = VectorTable{Table: "agent_fact_vector", IDColumn: "fact_id", ScopeColumn: "agent_id", OrderColumn: "created_at", Candidates: 3000}
	AgentChunkTable    = VectorTable{Table: "agent_chunk_vector", IDColumn: "chunk_id", ScopeColumn: "agent_id", OrderColumn: "created_at", Candidates: 4000}

	// AgentOverviewSectionTable holds a vector for each section of a
	// page's overview; see migration 0136.
	AgentOverviewSectionTable = VectorTable{Table: "agent_overview_section_vector", IDColumn: "section_id", ScopeColumn: "agent_id", OrderColumn: "created_at", Candidates: 3000}
)

The tables that hold vectors. Each carries its own scope column so a search is one indexed read rather than a join.

View Source
var (
	ErrInvalidOptions   = errors.New("db: invalid options")
	ErrAlreadyExists    = errors.New("db: already exists")
	ErrInvalidEmail     = errors.New("db: invalid email")
	ErrInvalidArguments = errors.New("db: invalid arguments")
	ErrNotFound         = errors.New("db: not found")

	// ErrTooMuchAsked is a question whose answer is larger than this server
	// will build: a stretch of time holding more times something happens
	// than it will describe at once. The asker is told, because the
	// alternative -- the first hundred thousand, silently -- answers "when
	// is this person busy" with a window that stops in the middle.
	ErrTooMuchAsked = errors.New("db: more was asked for than this server answers at once")
)
View Source
var ErrBookFull = errors.New("db: that address book is full")

ErrBookFull is a book that cannot take another card. Named, because the answer a client is given for it is a status that makes it stop rather than retry for ever.

View Source
var ErrCalendarFull = errors.New("db: that calendar is full")

ErrCalendarFull is a calendar that cannot take another event.

View Source
var ErrConfigurationChanged = fmt.Errorf("db: the configuration changed while this change was being made")

ErrConfigurationChanged is returned when a change was made against a configuration that somebody else has since replaced. The caller reloads and tries again; it is not a failure, it is two people editing at once.

View Source
var ErrNoSuchFact = errors.New("db: no such fact")

ErrNoSuchFact is a fact that is not there any more: struck, or merged away, between a caller reading it and acting on it.

View Source
var ErrRecordingDeleted = errors.New("db: recording was deleted")

ErrRecordingDeleted prevents an offline retry from recreating a deleted capture.

View Source
var ErrRecordingRetryInFlight = errors.New("db: recording is still stopping; retry after its current job finishes")

ErrRecordingRetryInFlight prevents an old stopping worker racing a resumed claim.

View Source
var ErrRecordingRetryUncertain = errors.New("db: a provider outcome cannot be safely reused; request explicit paid reprocessing")

ErrRecordingRetryUncertain preserves potentially paid outcomes for explicit reprocessing.

Functions

func ContextWithAuditPrincipal

func ContextWithAuditPrincipal(ctx context.Context, principal AuditPrincipal) context.Context

ContextWithAuditPrincipal records who is acting, for TransactionContext.

func CosineSimilarity

func CosineSimilarity(left, right []float32) float64

CosineSimilarity is the cosine between two vectors, and zero where they cannot be compared. One cosine, used by both paths, so a database with the extension and one without answer the same question the same way.

func IsRecordingCaptureLive added in v0.154.0

func IsRecordingCaptureLive(captureState models.RecordingCaptureState) bool

IsRecordingCaptureLive says whether a capture can still be growing: it has not been stopped, and it was not imported from a file.

func LikePrefix added in v0.124.0

func LikePrefix(prefix string) string

LikePrefix is a LIKE pattern matching what starts with prefix, its own % and _ taken literally. Backslash is LIKE's escape by default, and no ESCAPE clause is written: with one, PostgreSQL will not use an index for the prefix.

func RecordingAudioFileID added in v0.141.0

func RecordingAudioFileID(runId string, chunkIndex int) string

RecordingAudioFileID keeps pending derived writes reachable through their ledger.

func RecordingPartFileID added in v0.140.0

func RecordingPartFileID(mediaId string, partIndex int) string

RecordingPartFileID keeps even uncommitted part writes discoverable for cleanup.

func RecordingPreviewFileID added in v0.147.0

func RecordingPreviewFileID(mediaId string) string

RecordingPreviewFileID gives one versioned playback derivative per original.

func SearchText

func SearchText(query string) string

func TemporarySpeakerNamingOf added in v0.159.9

func TemporarySpeakerNamingOf(clientCorrectionId string) (string, string)

TemporarySpeakerNamingOf reads the temporary speaker's ID and the name digest out of a client correction ID, or returns empty strings when the key did not come from naming a temporary speaker.

func VectorNorm

func VectorNorm(vector []float32) float64

VectorNorm is a vector's length.

func WatchedItemKey added in v0.114.0

func WatchedItemKey(watchedItemId, watchedItemVersion string) string

WatchedItemKey is how ListAgentWatchedItemsLooked names an item in one version.

Types

type AgentAttachmentCounts

type AgentAttachmentCounts struct {
	// Undecided has not been looked at even from the outside; Declined
	// was looked at and passed over; Described was opened and made text
	// of.
	Undecided int64
	Declined  int64
	Described int64
}

AgentAttachmentCounts is what became of one source's files.

type AgentBillingOperation added in v0.165.0

type AgentBillingOperation interface {
	// PutAgentBillingCheck writes a provider's last check, replacing the
	// one before it.
	PutAgentBillingCheck(check *models.AgentBillingCheck) error

	// GetAgentBillingCheck is a provider's last check, or nil when it has
	// not been checked.
	GetAgentBillingCheck(providerName string) (*models.AgentBillingCheck, error)

	// RecordAgentPriceChange writes an audit event for a model's price
	// that the check changed. The configuration itself is saved through
	// the configuration store, not here; this is only the record of it.
	RecordAgentPriceChange(providerName, model string, before, after any) error

	// PutAgentBilledDays writes what a provider billed per model and day,
	// replacing a row already there for the same provider, day and model.
	// The days' ProviderName is ignored; providerName says whose they are.
	PutAgentBilledDays(providerName string, days []models.AgentBilledDay) error

	// DeleteAgentBilledDaysBefore removes billed days before the UTC day
	// the time falls on.
	DeleteAgentBilledDaysBefore(day time.Time) error

	// ListAgentBilledDays is the billed days from the UTC day since falls
	// on up to, not including, the UTC day until falls on; a zero until
	// has no end. Oldest first.
	ListAgentBilledDays(since, until time.Time) ([]*models.AgentBilledDay, error)
}

AgentBillingOperation keeps what the daily check of a provider's prices against its bill last did.

type AgentChunkVector

type AgentChunkVector struct {
	ChunkID  string
	SourceID string
	Model    string
	Vector   []float32
}

AgentChunkVector is one passage's vector, for a batch write.

type AgentGraphShapeLink struct {
	FromID   string                   `gorm:"column:from_id"`
	ToID     string                   `gorm:"column:to_id"`
	Relation models.AgentEdgeRelation `gorm:"column:relation"`
}

AgentGraphShapeLink is a stated link as clustering reads it.

type AgentGraphShapePage added in v0.79.0

type AgentGraphShapePage struct {
	ID         string               `gorm:"column:id"`
	Path       string               `gorm:"column:path"`
	Kind       models.AgentNodeKind `gorm:"column:kind"`
	Importance float32              `gorm:"column:importance"`
}

AgentGraphShapePage is a page as clustering reads it: where it is, what kind it is and how much it matters, and nothing it says.

type AgentGraphVector added in v0.48.0

type AgentGraphVector struct {
	NodeID         string
	NodeModifiedAt time.Time
	FactID         string
	FactModifiedAt time.Time
	Model          string
	Vector         []float32
}

AgentGraphVector carries the versions whose words were sent to the embedder. A fact also depends on its page's name and therefore its page version.

type AgentJobFilter

type AgentJobFilter struct {
	AgentID  string
	Statuses []models.AgentJobStatus
	Kinds    []models.AgentJobKind

	// SubjectID is what the jobs are about: one message, one schedule,
	// one conversation. Since counts only the jobs made from that moment
	// on, which is how a goal knows how many turns it has taken today
	// without a column of its own.
	SubjectID string
	Since     time.Time
}

AgentJobFilter narrows a job listing.

type AgentJobOutcome added in v0.48.0

type AgentJobOutcome struct {
	JobStatus    models.AgentJobStatus
	ErrorMessage string
	NotBefore    *time.Time
	FailureCount int
	FinishedAt   time.Time
}

AgentJobOutcome records progress separately from retryable failures.

type AgentOperation

type AgentOperation interface {
	GetAgent(agentId string) (*models.Agent, error)
	GetAgentByUser(userId string) (*models.Agent, error)
	CreateAgent(agent *models.Agent) (*models.Agent, error)
	UpdateAgent(agentId string, modify func(*models.Agent) error) (*models.Agent, error)

	// MarkAgentSpokeFirst records when the agent last spoke first, when its
	// onboarding ended and until when it keeps quiet; nil leaves one alone.
	MarkAgentSpokeFirst(agentId string, spokeFirstAt, onboardedAt, snoozedUntil *time.Time) error
	DeleteAgent(agentId string) error
	ListAgents(options *Options) ([]*models.Agent, error)

	// EnqueueAgentJob adds a job, unless one for the same agent, kind and
	// subject is already queued or running, in which case that one is
	// returned: the second arrival coalesces into the first.
	EnqueueAgentJob(job *models.AgentJob) (*models.AgentJob, error)

	// PostponeAgentJob moves a queued job's start to notBefore when that is
	// later than its start now, so a burst of changes runs it once, after the
	// last of them. A job already running or finished is left as it is.
	PostponeAgentJob(jobId string, notBefore time.Time) error

	// ClaimAgentJobs takes up to limit due jobs for this instance, skipping
	// any another instance has locked, and marks them running.
	ClaimAgentJobs(instance string, limit int, now time.Time) ([]*models.AgentJob, error)

	// ClaimAgentJobsKeepingRoom is ClaimAgentJobs with the background
	// reading (ingest, dream, backfill) held to backgroundLimit jobs
	// running on this instance at once, so a slot stays for work somebody
	// is waiting on.
	ClaimAgentJobsKeepingRoom(instance string, limit, backgroundLimit int, now time.Time, shouldExcludeMailboxJobs ...bool) ([]*models.AgentJob, error)

	// FinishAgentJob changes only the running claim named by claimId.
	// False means that claim was released or replaced while its worker ran.
	FinishAgentJob(jobId, claimId string, outcome *AgentJobOutcome) (bool, error)

	// RetryAgentJob returns a terminal job to the queue with a fresh failure allowance.
	RetryAgentJob(jobId string) (bool, error)

	// ReleaseStaleAgentJobs puts back jobs claimed before the given time
	// whose instance never finished them.
	ReleaseStaleAgentJobs(before time.Time) (int64, error)

	// ReleaseStaleAgentJobsOfKind is the same for one kind of job with
	// its own idea of how long is too long: the night may take an hour.
	ReleaseStaleAgentJobsOfKind(kind models.AgentJobKind, before time.Time) (int64, error)

	// ReleaseAgentJobsClaimedBy puts back every job an instance holds:
	// for that instance's own start-up, when whatever it held before is
	// certainly not running any more.
	ReleaseAgentJobsClaimedBy(instance string) (int64, error)

	// CancelAgentJobs cancels what is queued for an agent, or for one of its
	// mailboxes when mailboxId is given.
	CancelAgentJobs(agentId, mailboxId string) (int64, error)

	GetAgentJob(jobId string) (*models.AgentJob, error)
	ListAgentJobs(filter *AgentJobFilter, options *Options) ([]*models.AgentJob, error)
	CountAgentJobs(filter *AgentJobFilter) (int64, error)

	// ScavengeAgentJobs removes finished jobs older than the given time.
	ScavengeAgentJobs(before time.Time) (int64, error)

	// PutAgentUsage adds tokens to the hourly row for this agent, source,
	// model and kind.
	PutAgentUsage(usage *AgentUsage) error

	// SumAgentUsage totals an agent's rows since a time; an empty agentId
	// totals the whole server.
	SumAgentUsage(agentId string, since time.Time) (models.AgentUsageTotals, error)

	// QueryAgentUsage totals rows since a time under one key: "day",
	// "kind", "mailbox" or "model". An empty agentId is the whole server.
	QueryAgentUsage(agentId string, since, until time.Time, by string) ([]models.AgentUsageRow, error)

	// QueryAgentUsageByModel is the same, with the model kept beside the
	// key so a caller can price what it reads.
	QueryAgentUsageByModel(agentId string, since, until time.Time, by string) ([]models.AgentUsageModelRow, error)

	// ScavengeAgentUsage removes rows older than the retention. Nothing
	// calls it; see the implementation for why.
	ScavengeAgentUsage(before time.Time) (int64, error)

	// TouchUserLocation records where a person is and what they read in, as
	// their browser or command line said. The zone is kept only while the
	// account follows the browser. A locale the person chose in the
	// dashboard replaces the one kept; one a client only passed along, a
	// browser's or a shell's, fills it in when nothing is kept yet. Not
	// audited: crossing a border is not an administrative change.
	TouchUserLocation(userId, timezone, locale string, isLocaleChosen bool, at time.Time) error
}

AgentOperation is the agent, its queue and its usage.

type AgentProjectPostCount added in v0.79.0

type AgentProjectPostCount struct {
	ProjectPath             string
	PostCount               int
	OpenIssueCount          int
	OpenedIssueCount        int
	MergedMergeRequestCount int
}

AgentProjectPostCount is the posts about one project on a code host, counted: ProjectPath in lower case as the post named it ("core/example-lib"), how many of its posts are issues or merge requests, how many issues are open, how many were opened since the time asked about, and how many merge requests were merged since then.

type AgentReadingCounts

type AgentReadingCounts struct {
	// Waiting has been indexed and not read yet; Read has been.
	Waiting int64
	Read    int64

	// Undecided is a file the night has not yet looked at the outside of,
	// and Declined one it looked at and decided against opening. Described
	// is one it opened and made text of, which is a document like any
	// other and is counted in Waiting or Read as well -- it is here so
	// that a source's page can say how many of its pictures were read
	// rather than only how many were not.
	Undecided int64
	Declined  int64
	Described int64
}

AgentReadingCounts is how far the night has got through what was indexed, and what became of the pictures and files a record came with.

The last three are apart from the first two because two of them are neither waiting nor read. An attachment with no text -- a picture whose bytes are kept and which nothing has described -- is not waiting for a night that could do nothing with it, and calling it read would be a lie: a source of fifty thousand screenshots would say it was all read and nothing would have been.

type AgentReplyFilter

type AgentReplyFilter struct {
	AgentID     string
	MailboxID   string
	MailID      string
	ThreadID    string
	DraftItemID string
	Statuses    []models.AgentReplyStatus

	// Since keeps replies created at or after it; SentSince the ones sent
	// at or after it.
	Since     time.Time
	SentSince time.Time
}

AgentReplyFilter narrows a listing; every field set must hold.

type AgentRunFilter

type AgentRunFilter struct {
	JobID string
	Kinds []string
	Query string
}

AgentRunFilter narrows a listing of runs: to one job's (a dream makes many, one per call), to some kinds, to titles carrying some words.

type AgentUsage

type AgentUsage struct {
	AgentID   string
	MailboxID string
	Model     string
	Kind      string
	At        time.Time
	Values    []uint64 // models.AgentUsageValueCount long
}

AgentUsage is one addition to the usage rows.

type AlertOperation added in v0.82.0

type AlertOperation interface {
	// CreateAgentAlertCandidate adds a candidate, waiting. A budget
	// candidate whose budget key the agent already has is not added, and
	// answers nil with no error.
	CreateAgentAlertCandidate(candidate *models.AgentAlertCandidate) (*models.AgentAlertCandidate, error)

	// ListWaitingAgentAlertCandidates is the candidates neither told nor
	// dropped: those that may not wait first (the sorting said now, or a
	// burst), then the rest, each oldest first. A backlog held for the
	// morning does not hide what came in pressing behind it.
	ListWaitingAgentAlertCandidates(agentId string, limit int) ([]*models.AgentAlertCandidate, error)

	// DropAgentAlertCandidatesMadeBefore drops the agent's waiting
	// candidates made before the moment given, with the reason given.
	DropAgentAlertCandidatesMadeBefore(agentId string, createdBefore time.Time, dropReason string, droppedAt time.Time) error

	// ListAgentAlertCandidatesByID is these candidates of the agent,
	// whatever became of them, oldest first.
	ListAgentAlertCandidatesByID(agentId string, candidateIds []string) ([]*models.AgentAlertCandidate, error)

	// LatestAgentBurstCandidate is the newest burst candidate of a
	// mailbox with this key made since the moment given, or nil.
	LatestAgentBurstCandidate(agentId, mailboxId, burstKey string, since time.Time) (*models.AgentAlertCandidate, error)

	// ListMailSubjectsFromSender is the subjects of the messages from an
	// address that were received since the moment given and are in a
	// mailbox, leaving out Junk, Trash, Drafts and Sent: what a burst is
	// counted over. Old mail moved or copied in since is not counted: it
	// was received before. One query over the mailbox's items by the time
	// they were added, which is indexed (mailbox_item_list); an item is
	// never added before its message was received, so bounding both by
	// the same moment leaves nothing out.
	ListMailSubjectsFromSender(mailboxId, senderAddress string, since time.Time, limit int) ([]string, error)

	// LockWaitingAgentAlertCandidates takes these candidates for telling
	// or dropping, holding them until the transaction ends, and returns
	// those still waiting: a run that finds one already told does not
	// tell it again.
	LockWaitingAgentAlertCandidates(agentId string, candidateIds []string) ([]*models.AgentAlertCandidate, error)

	// MarkAgentAlertCandidatesAlerted records the alert that told the
	// person about these candidates.
	MarkAgentAlertCandidatesAlerted(candidateIds []string, alertId string) error

	// DropAgentAlertCandidates records that these candidates were not
	// worth telling, and why.
	DropAgentAlertCandidates(candidateIds []string, dropReason string, droppedAt time.Time) error

	// CreateAgentAlert records what the person was told, under the id it
	// carries when it has one.
	CreateAgentAlert(alert *models.AgentAlert) (*models.AgentAlert, error)

	// ListAgentAlertsSince is what the person was told since the moment
	// given, newest first.
	ListAgentAlertsSince(agentId string, since time.Time) ([]*models.AgentAlert, error)

	// AdvanceAgentJob brings a queued job of this agent, kind and subject
	// forward to the moment given, when it was waiting for later.
	AdvanceAgentJob(agentId string, kind models.AgentJobKind, subjectId string, notBefore time.Time) error

	// GetAgentAlert is one alert of the agent, or nil.
	GetAgentAlert(agentId, alertId string) (*models.AgentAlert, error)

	// ListRecentAgentAlerts is the agent's latest alerts, newest first.
	ListRecentAgentAlerts(agentId string, limit int) ([]*models.AgentAlert, error)

	// CreateAgentAlertMute keeps a mute. One with the same scope and
	// target already there is returned as it is rather than kept twice.
	CreateAgentAlertMute(mute *models.AgentAlertMute) (*models.AgentAlertMute, error)

	// ListAgentAlertMutes is the agent's mutes, newest first.
	ListAgentAlertMutes(agentId string) ([]*models.AgentAlertMute, error)

	// DeleteAgentAlertMute removes one mute of the agent, saying whether
	// there was one.
	DeleteAgentAlertMute(agentId, muteId string) (bool, error)

	// HasAgentBudgetAlert says a budget crossing with this key was already
	// written as a candidate, whatever became of it, or told as an alert
	// under it as its subject key: the code that finds crossings after
	// every sync writes each one once.
	HasAgentBudgetAlert(agentId, budgetKey string) (bool, error)
}

AlertOperation is what might be worth telling a person about unasked, and what they were told.

type AliasOperation

type AliasOperation interface {
	GetAlias(aliasId string) (*models.Alias, error)
	CreateAlias(alias *models.Alias) (*models.Alias, error)
	UpdateAlias(aliasId string, modify func(*models.Alias) error) (*models.Alias, error)
	DeleteAlias(aliasId string) error

	// ReorderAliases puts a domain's aliases in this order; ones not named
	// keep their relative order after the named ones.
	ReorderAliases(domainId string, aliasIds []string) error
}

AliasOperation changes a domain's aliases.

type AliasUsageOperation

type AliasUsageOperation interface {
	// store new alias usages
	PutAliasUsages(aliasUsagesMap map[string][]models.Usage, options *Options) error

	// query and sum up alias usages later than specified timestamp
	SumAliasUsages(aliasIds []string, interval uint64, timestamp uint64, options *Options) ([]models.Usage, error)

	// query alias usages later than specified timestamp
	QueryAliasUsages(aliasIds []string, interval uint64, timestamp uint64, options *Options) ([][]models.Usage, error)

	// scavenge usages
	ScavengeAliasUsages(options *Options) error
}

type AttachmentOperation

type AttachmentOperation interface {
	CreateAgentAttachment(attachment *models.AgentAttachment) (*models.AgentAttachment, error)
	GetAgentAttachment(attachmentId string) (*models.AgentAttachment, error)

	// GetAgentAttachments reads several by id, in the order given; one
	// that does not exist is left out.
	GetAgentAttachments(attachmentIds []string) ([]*models.AgentAttachment, error)

	// ClaimAgentAttachments binds uploaded files to the message they came
	// with, so that they are the conversation's from then on.
	ClaimAgentAttachments(attachmentIds []string, conversationId, messageId string) error

	// ListAgentAttachments is every file of a conversation, oldest first,
	// or every file of an agent when the conversation is empty.
	ListAgentAttachments(agentId, conversationId string) ([]*models.AgentAttachment, error)

	// ListOrphanAgentAttachments is what was uploaded and never sent with
	// a turn, older than the given time, for the sweep. A photo or PDF a
	// finance receipt was read from is not an orphan: the receipt holds
	// it. Nor is one uploaded to a finance transaction as its receipt,
	// waiting to be read, while that finance transaction exists, nor one
	// handed in as a paystub or a tax form, until TaxDocumentUnreadRetention
	// has passed with nothing read out of it.
	ListOrphanAgentAttachments(before time.Time) ([]*models.AgentAttachment, error)

	// DetachReceiptAttachments takes a conversation's files that a finance
	// receipt was read from, and those handed in as a paystub or a tax
	// form, out of the conversation, for deleting the conversation without
	// them: they no longer name a conversation or a message, and go when
	// their receipt, paystub or tax form is deleted.
	DetachReceiptAttachments(agentId, conversationId string) error

	DeleteAgentAttachment(attachmentId string) error

	// SetAgentAttachmentFinanceTransaction records the finance transaction
	// an upload of the agent's is the receipt for. ErrNotFound when the
	// agent has no such upload or no such finance transaction.
	SetAgentAttachmentFinanceTransaction(agentId, attachmentId, financeTransactionId string) error

	// MarkAgentAttachmentTaxDocument records that an upload of the agent's
	// was handed in as a paystub or a tax form, and forgets the text kept
	// of it, unless a message of a conversation carries it: the turns
	// after it read that text, already masked when it was kept, and
	// would lose the file. ErrNotFound when the agent has no such upload.
	MarkAgentAttachmentTaxDocument(agentId, attachmentId string) error
}

AttachmentOperation is the files a person hands their agent in a conversation: the rows here, the bytes in the spool under the same id.

type AuditOperation

type AuditOperation interface {
	ListAuditEvents(options *AuditOptions) ([]*models.AuditEvent, error)
	CountAuditEvents(options *AuditOptions) (int64, error)

	// ScavengeAuditEvents removes rows older than the retention.
	ScavengeAuditEvents(before time.Time) (int64, error)
}

AuditOperation reads the audit log. Writing it is not an operation anybody calls: every audited write in this package goes through applyMutation.

type AuditOptions

type AuditOptions struct {
	ResourceType string
	ResourceID   string
	ActorUserID  string
	Since        *time.Time
	Until        *time.Time
	Limit        int
	Offset       int
}

AuditOptions narrows a listing. Every filter is optional.

type AuditPrincipal

type AuditPrincipal struct {
	ActorKind models.AuditActorKind
	UserID    string
	TokenID   string
	SourceIP  string

	// ImpersonatorUserID is the operator signed in as UserID, when the
	// request comes from an impersonation.
	ImpersonatorUserID string
}

AuditPrincipal is who is making the changes in a transaction: derived once from the request by the authentication layer and carried on the context the transaction was opened with, so that every audited write in it names the same actor without each caller passing one.

func PrincipalFromContext

func PrincipalFromContext(ctx context.Context) AuditPrincipal

PrincipalFromContext is the actor a context carries. A context that carries none is the server acting on its own behalf.

type BackgroundWorkOperation added in v0.81.0

type BackgroundWorkOperation interface {
	// CreateAgentBackgroundWork records a piece of work, queued.
	CreateAgentBackgroundWork(work *models.AgentBackgroundWork) (*models.AgentBackgroundWork, error)

	// GetAgentBackgroundWork is one of the agent's, or nil.
	GetAgentBackgroundWork(agentId, workId string) (*models.AgentBackgroundWork, error)

	// ListAgentBackgroundWork is the agent's work, newest first.
	ListAgentBackgroundWork(agentId string, limit int) ([]*models.AgentBackgroundWork, error)

	// StartAgentBackgroundWork marks a piece of work running, and says
	// whether it is still to run: false when it was stopped or has
	// finished. One already running, whose job was claimed again after a
	// restart, runs again.
	StartAgentBackgroundWork(workId string, at time.Time) (bool, error)

	// FinishAgentBackgroundWork writes how a running piece of work ended:
	// its status, result, runs and error. It says whether it did, which
	// it does not for work that was stopped while it ran.
	FinishAgentBackgroundWork(work *models.AgentBackgroundWork) (bool, error)

	// StopAgentBackgroundWork marks one of the agent's stopped, when it is
	// queued or running, and returns it as it stands after. ErrNotFound
	// when the agent has no such work.
	StopAgentBackgroundWork(agentId, workId string, at time.Time) (*models.AgentBackgroundWork, error)

	// MarkAgentBackgroundWorkWoken notes that the conversation was told.
	MarkAgentBackgroundWorkWoken(workIds []string, at time.Time) error

	// ClaimAgentBackgroundWorkWake takes the waking of the conversation
	// for a piece of finished work, and says whether the caller has it:
	// false when the conversation has been told, or when somebody else
	// claimed it at or after claimExpiredBefore. Only the claimer wakes,
	// so two instances never both do.
	ClaimAgentBackgroundWorkWake(workId string, at, claimExpiredBefore time.Time) (bool, error)

	// ReleaseAgentBackgroundWorkWakes lets go of claims whose wake was
	// given up, for the sweep to take again without waiting for them to
	// expire.
	ReleaseAgentBackgroundWorkWakes(workIds []string) error

	// ListAgentBackgroundWorkToWake is the work that finished between the
	// two moments, done or failed, whose conversation should be woken and
	// has not been, and which nobody has claimed since claimExpiredBefore:
	// what a wake lost to a restart left behind.
	ListAgentBackgroundWorkToWake(finishedAfter, finishedBefore, claimExpiredBefore time.Time, limit int) ([]*models.AgentBackgroundWork, error)

	// FailStaleAgentBackgroundWork marks work still queued or running that
	// was made before the moment as failed, with the reason given.
	FailStaleAgentBackgroundWork(createdBefore time.Time, reason string) (int64, error)

	// ScavengeAgentBackgroundWork removes finished work made before the
	// moment.
	ScavengeAgentBackgroundWork(before time.Time) (int64, error)
}

BackgroundWorkOperation keeps the agent's background work: the surveys and subagents it started and did not wait for, what came of each, and whether the conversation that started it has been told.

type BimiLogo struct {
	Domain      string    `gorm:"primary_key:true;column:domain;type:text"`
	Selector    string    `gorm:"primary_key:true;column:selector;type:text"`
	CheckedAt   time.Time `gorm:"column:checked_at"`
	LogoURL     string    `gorm:"column:logo_url;type:text"`
	ContentType string    `gorm:"column:content_type;size:64"`
	Content     []byte    `gorm:"column:content"`
	Error       string    `gorm:"column:error;type:text"`
}

BimiLogo is one domain's logo as this server holds it.

func (*BimiLogo) TableName

func (self *BimiLogo) TableName() string

type BimiPublication

type BimiPublication struct {
	DomainID   string `gorm:"primary_key:true;column:domain_id;size:32"`
	FileID     string `gorm:"column:file_id;size:32"`
	Filename   string `gorm:"column:filename;type:text"`
	Title      string `gorm:"column:title;type:text"`
	CreatedAt  time.Time
	ModifiedAt time.Time
}

BimiPublication is a logo this server publishes for one of its own domains. The bytes are in the file store under FileID; this is what they are.

func (*BimiPublication) TableName

func (self *BimiPublication) TableName() string

type BimiQuery

type BimiQuery interface {
	// been looked up.
	GetBimiLogo(domain, selector string) (*BimiLogo, error)

	// ListBimiLogos is what is cached for these domains, keyed by domain, for
	// a listing that needs many at once.
	ListBimiLogos(domains []string, selector string) (map[string]*BimiLogo, error)

	SaveBimiLogo(logo *BimiLogo) error

	// mail comes from that have not been looked up since the given time —
	// what the background job works through.
	ListSenderDomainsWithoutLogo(before time.Time, limit int) ([]string, error)

	// ListBimiPublications is the logos published for several domains at
	// once, keyed by domain. For a listing, which would otherwise ask once
	// per row.
	ListBimiPublications(domainIds []string) (map[string]*BimiPublication, error)

	// GetBimiPublication is the logo this server publishes for one of its own
	// domains, or nil when it publishes none.
	GetBimiPublication(domainId string) (*BimiPublication, error)

	// GetBimiPublicationByFile is the same row found by the name in the
	// address a receiver fetches.
	GetBimiPublicationByFile(fileId string) (*BimiPublication, error)

	// SaveBimiPublication records an uploaded logo, replacing whatever the
	// domain published before.
	SaveBimiPublication(publication *BimiPublication) error

	// DeleteBimiPublication stops publishing one, and says which file to
	// remove from storage.
	DeleteBimiPublication(domainId string) (string, error)
}

type BudgetOperation added in v0.87.0

type BudgetOperation interface {
	// ListSpendingCategories is the agent's spending categories by name.
	ListSpendingCategories(agentId string) ([]*models.SpendingCategory, error)

	// GetSpendingCategory is one spending category of the agent, or nil.
	GetSpendingCategory(agentId, spendingCategoryId string) (*models.SpendingCategory, error)

	// CreateSpendingCategory adds a spending category. ErrAlreadyExists
	// when the agent has one of that name.
	CreateSpendingCategory(spendingCategory *models.SpendingCategory) (*models.SpendingCategory, error)

	// UpdateSpendingCategory changes a spending category of the agent
	// through a function given a copy.
	UpdateSpendingCategory(agentId, spendingCategoryId string, modify func(*models.SpendingCategory) error) (*models.SpendingCategory, error)

	// DeleteSpendingCategory removes a spending category of the agent,
	// with its budgets and the spending rules that assign it. Its finance
	// transactions become uncategorized, the person's choices included,
	// so they are categorized again. The transfer category and the other
	// category are refused.
	DeleteSpendingCategory(agentId, spendingCategoryId string) error

	// EnsureDefaultSpendingCategories gives an agent with no spending
	// categories but the built-in ones (transfer and other) the rest of
	// the default list, and does nothing for one that has any: a person
	// who deleted a default does not get it back. It makes the built-in
	// ones too where they are missing. It answers how many defaults it
	// made, the built-in ones not counted.
	EnsureDefaultSpendingCategories(agentId string) (int, error)

	// EnsureTransferSpendingCategory is the agent's transfer category,
	// made when the agent has none: every agent is given one when it is
	// made, so this only mends one that somehow lost it.
	EnsureTransferSpendingCategory(agentId string) (*models.SpendingCategory, error)

	// EnsureOtherSpendingCategory is the agent's other category, made when
	// the agent has none, as EnsureTransferSpendingCategory is.
	EnsureOtherSpendingCategory(agentId string) (*models.SpendingCategory, error)

	// ListSpendingRules is the agent's spending rules in the order they
	// are tried.
	ListSpendingRules(agentId string) ([]*models.SpendingRule, error)

	// GetSpendingRule is one spending rule of the agent, or nil.
	GetSpendingRule(agentId, spendingRuleId string) (*models.SpendingRule, error)

	// CreateSpendingRule adds a spending rule and applies the rules again.
	CreateSpendingRule(spendingRule *models.SpendingRule) (*models.SpendingRule, error)

	// CreateSpendingRules adds several spending rules and applies the
	// rules again once, after the last.
	CreateSpendingRules(spendingRules []*models.SpendingRule) ([]*models.SpendingRule, error)

	// UpdateSpendingRule changes a spending rule of the agent through a
	// function given a copy, and applies the rules again.
	UpdateSpendingRule(agentId, spendingRuleId string, modify func(*models.SpendingRule) error) (*models.SpendingRule, error)

	// DeleteSpendingRule removes a spending rule of the agent and applies
	// the rest again.
	DeleteSpendingRule(agentId, spendingRuleId string) error

	// SetSpendingRulePriorities moves spending rules of the agent to the
	// priorities given, by id, recording each move, without applying the
	// rules: the caller adds the rules the room was made for with
	// CreateSpendingRules, which applies them once. ErrNotFound when an id
	// is none of the agent's.
	SetSpendingRulePriorities(agentId string, rulePriorities map[string]int) error

	// FirstMatchingSpendingRules is, for each finance transaction of the
	// agent named, the id of the first spending rule by priority that
	// matches it, as ApplySpendingRules judges it; one no rule matches,
	// or that is none of the agent's, is left out.
	FirstMatchingSpendingRules(agentId string, financeTransactionIds []string) (map[string]string, error)

	// CountSpendingRuleChanges is, for each spending rule proposed, how
	// many of the agent's finance transactions it would recategorize once
	// placed ahead of the rule it names (after every rule when it names
	// none): those it matches that no earlier rule matches, whose spending
	// category would change, leaving out what ApplySpendingRules never
	// touches (the person's choices, transfers something else gave) and
	// the finance transactions excluded. One answer per proposal, in
	// order.
	CountSpendingRuleChanges(agentId string, proposedSpendingRules []*ProposedSpendingRule, excludedTransactionIds []string) ([]int, error)

	// ApplySpendingRules applies the agent's spending rules to all of its
	// finance transactions in one statement: each takes the first rule
	// that matches by priority. A spending category the person chose is
	// never touched. A spending category a rule gave that no rule matches
	// any more is cleared, to be categorized again, the transfer category
	// included. A rule does not take over a transfer something else gave
	// first (transfer detection, the provider category mapping), so
	// deleting the rule leaves that one as it was. It answers how many
	// finance transactions changed.
	ApplySpendingRules(agentId string) (int, error)

	// SetBudget keeps the monthly amount of a spending category from a
	// month on, replacing the one already set from that same month, and
	// deletes the later rows that then say nothing (dropRepeatedBudgets).
	// On an income spending category it is the income expected each month.
	// The transfer category, which is neither spending nor income, is
	// refused.
	SetBudget(budget *models.Budget) (*models.Budget, error)

	// ListBudgets is every budget row of the agent, by spending category
	// and month.
	ListBudgets(agentId string) ([]*models.Budget, error)

	// BudgetsForMonth is the budget in force in a month ("2006-01") for
	// each spending category: the row with the latest EffectiveFrom on or
	// before it. A budget ended by a zero is left out.
	BudgetsForMonth(agentId, month string) ([]*models.Budget, error)

	// ListSavingsTargets is the agent's savings targets, open ones first.
	ListSavingsTargets(agentId string) ([]*models.SavingsTarget, error)

	// GetSavingsTarget is one savings target of the agent, or nil.
	GetSavingsTarget(agentId, savingsTargetId string) (*models.SavingsTarget, error)

	// CreateSavingsTarget adds a savings target with the assets and
	// finance accounts it
	// measures, each of which must be the agent's.
	CreateSavingsTarget(savingsTarget *models.SavingsTarget) (*models.SavingsTarget, error)

	// UpdateSavingsTarget changes a savings target of the agent through a
	// function given a copy; its AssetIDs and FinanceAccountIDs replace
	// the ones it had.
	UpdateSavingsTarget(agentId, savingsTargetId string, modify func(*models.SavingsTarget) error) (*models.SavingsTarget, error)

	// CloseSavingsTarget records the day a savings target was closed; an
	// empty day opens it again.
	CloseSavingsTarget(agentId, savingsTargetId, closedOn string) (*models.SavingsTarget, error)

	// DeleteSavingsTarget removes a savings target of the agent.
	DeleteSavingsTarget(agentId, savingsTargetId string) error

	// ListSpendingCategoryDays is each day's spending in a month
	// ("2006-01") per spending category and currency: money out less
	// refunds in the same spending category, the transfer category,
	// income categories and mirrored copies left out. The other category
	// and what is not categorized yet count money out only, since their
	// money in is income: money out not categorized yet is counted under
	// an empty spending category.
	ListSpendingCategoryDays(agentId, month string) ([]*models.SpendingCategoryDay, error)

	// ListIncomeCategoryDays is each day's income in a month ("2006-01")
	// per income spending category and currency: money in less money
	// taken back, transfers and mirrored copies left out. Money in under
	// the other category or not categorized yet is left out, since no
	// income budget can count it; ListCashFlowDays counts it as income.
	ListIncomeCategoryDays(agentId, month string) ([]*models.IncomeCategoryDay, error)

	// ListCashFlowDays is each day's income and spending per currency from
	// one day to another, both included ("2006-01-02"), counted as
	// ListSpendingCategoryDays counts spending, so the two agree: a refund
	// in a spending category lowers spending rather than counting as
	// income, and money in under the other category or not categorized
	// yet is income. Transfers and mirrored copies are left out.
	ListCashFlowDays(agentId, from, to string) ([]*models.CashFlowDay, error)

	// ListMerchantMonthSpending is what each merchant charged each
	// spending category in each of the three full months before a month
	// ("2006-01"), per currency, transfers and mirrored copies left out:
	// what the budget pace reads to expect a fixed monthly charge.
	ListMerchantMonthSpending(agentId, month string) ([]*models.MerchantMonthSpending, error)
}

BudgetOperation is a person's spending categories, spending rules, budgets and savings targets, and the raw spending the budget pace is computed from. The projection itself is the agent's. Every call takes the agent id and filters on it.

type CalendarRequestOperation added in v0.48.0

type CalendarRequestOperation interface {
	GetCalendarRequest(userId, requestId string) (*models.CalendarRequestReceipt, error)
	// LockCalendarRequest serializes even absent identities until commit.
	LockCalendarRequest(userId, requestId string) (*models.CalendarRequestReceipt, error)
	CreateCalendarRequest(receipt *models.CalendarRequestReceipt) error
	IsCalendarRequestCancelled(userId, requestId string) (bool, error)
	CancelCalendarRequest(userId, requestId string) error
}

CalendarRequestOperation stores receipts on the same transaction as the calendar command and accepted notification mail. It does not authorize callers.

type ChannelOperation

type ChannelOperation interface {
	// PutAgentChannel writes or replaces the person's bot for an app. A
	// bot linked, linked again, given a new token or switched back on
	// sends the agent's own turns from the main conversation's newest
	// message on, never what was said while it was not listening.
	PutAgentChannel(channel *models.AgentChannel) (*models.AgentChannel, error)
	GetAgentChannel(agentId string, kind models.AgentChannelKind) (*models.AgentChannel, error)
	ListAgentChannels(agentId string) ([]*models.AgentChannel, error)
	// ListEnabledAgentChannels is every bot that should be running, for
	// the manager that runs them.
	ListEnabledAgentChannels() ([]*models.AgentChannel, error)
	DeleteAgentChannel(agentId string, kind models.AgentChannelKind) error

	// ClaimAgentChannel takes or renews the claim to run a bot for this
	// instance until the moment given, and says whether it holds: it does
	// when nobody holds it, when the holder's claim has lapsed, or when
	// this instance holds it already.
	ClaimAgentChannel(channelId, instance string, until time.Time) (bool, error)
	// ReleaseAgentChannel gives a claim up, if this instance holds it.
	ReleaseAgentChannel(channelId, instance string) error
	// NoteAgentChannel records what the running bot saw: its name, the
	// last time it was heard from, and what went wrong.
	NoteAgentChannel(channelId, botName, lastError string, seenAt *time.Time) error

	// AdvanceAgentChannelRelay moves how far the bot has looked for the
	// agent's own turns from one message to another, and says whether it
	// did: it does only while this instance holds the bot and nobody moved
	// it since it was read, which is what keeps a turn from being sent
	// twice.
	AdvanceAgentChannelRelay(channelId, instance, fromMessageId, throughMessageId string) (bool, error)
}

ChannelOperation is a person's chat-app bots.

type ConfigurationOperation

type ConfigurationOperation interface {
	// ConfigurationVersion is what the stored configuration is at, for an
	// instance checking whether its copy is stale.
	ConfigurationVersion() (int64, error)

	// LoadConfiguration reads every section, and the version they were read
	// at.
	LoadConfiguration() (*ConfigurationRows, error)

	// SaveConfiguration replaces the sections, refusing when the caller's
	// copy is stale, and returns the new version.
	SaveConfiguration(rows *ConfigurationRows) (int64, error)
}

ConfigurationOperation reads and writes the settings.

type ConfigurationRows

type ConfigurationRows struct {
	// Version is what the configuration was when it was read. Passing it
	// back to SaveConfiguration is how a write refuses to overwrite somebody
	// else's.
	Version int64

	// Settings holds each section as a YAML document, keyed by section name.
	//
	// YAML rather than JSON, and not because of taste: a secret is raw
	// bytes, and encoding/json replaces a byte that is not valid UTF-8 with
	// the replacement character. A server secret that came back changed
	// would invalidate every SMTP password on the server, silently. YAML
	// writes such a string as !!binary.
	Settings map[string]string
}

ConfigurationRows is the settings as stored.

type ConnectionOperation

type ConnectionOperation interface {
	// PutAgentConnection writes or replaces the person's connection to a
	// server.
	PutAgentConnection(connection *models.AgentConnection) (*models.AgentConnection, error)
	GetAgentConnection(agentId, serverName string) (*models.AgentConnection, error)
	ListAgentConnections(agentId string) ([]*models.AgentConnection, error)
	DeleteAgentConnection(agentId, serverName string) error
	DeleteAgentConnections(agentId string) (int64, error)
}

ConnectionOperation is a person's connections to the servers the operator declared.

type CredentialOperation

type CredentialOperation interface {
	GetCredential(credentialId string) (*models.Credential, error)
	CreateCredential(credential *models.Credential) (*models.Credential, error)
	UpdateCredential(credentialId string, modify func(*models.Credential) error) (*models.Credential, error)
	DeleteCredential(credentialId string) error
}

CredentialOperation changes a domain's credentials.

type CredentialUsageOperation

type CredentialUsageOperation interface {
	// store new credential usages
	PutCredentialUsages(credentialUsagesMap map[string][]models.Usage, options *Options) error

	// query and sum up credential usages later than specified timestamp
	SumCredentialUsages(credentialIds []string, interval uint64, timestamp uint64, options *Options) ([]models.Usage, error)

	// query credential usages later than specified timestamp
	QueryCredentialUsages(credentialIds []string, interval uint64, timestamp uint64, options *Options) ([][]models.Usage, error)

	// scavenge usages
	ScavengeCredentialUsages(options *Options) error
}

type Database

type Database interface {
	// The settings, read on start and on every change made elsewhere.
	ConfigurationOperation

	// SetSecret hands over the server secret the domain table's secrets are
	// sealed with, once the settings that hold it have been read.
	SetSecret(secret []byte) error

	// Users are looked up on every authenticated request, outside any
	// transaction.
	UserLookup

	// MailExists says whether a stored message still has a row, for the
	// spool sweep deciding what it may remove.
	MailExists(mailId string) (bool, error)

	// ListenFolderChanges delivers the id of each folder any instance
	// changes, until the context ends.
	ListenFolderChanges(ctx context.Context) (<-chan string, error)

	// NotifyAgentEvent tells every instance about an event of a turn, and
	// ListenAgentEvents delivers what the others said, until the context
	// ends. The payload is the instance's to shape; what a slow listener
	// misses is not kept.
	NotifyAgentEvent(payload string) error
	ListenAgentEvents(ctx context.Context) (<-chan string, error)

	// NotifyAgentCommand and ListenAgentCommands are the same for a word
	// to a turn — stop, an answer, a decision on a card — from an instance
	// that is not running it.
	NotifyAgentCommand(payload string) error
	ListenAgentCommands(ctx context.Context) (<-chan string, error)

	// Sessions, API tokens and passkeys are read and written outside a
	// transaction: every authenticated request looks one up, and wrapping
	// that in a transaction would buy nothing.
	SessionOperation
	TokenOperation
	OAuthOperation
	PasskeyOperation

	// Media is read on every request for a picture in a sent message, which
	// arrives from a mail program with no session and no transaction to join.
	MediaOperation
	MediaLinkOperation

	// The built-in spam filter reads its learned counts while scoring a
	// message, outside any transaction the delivery is in: an advisory score
	// must not be able to hold a delivery's transaction open.
	SpamOperation

	// VectorIndexing says whether the database ranks vectors itself, and
	// EnsureVectorIndex builds the index one table needs for one model.
	// Both are outside any transaction: the first is asked once at start,
	// the second is DDL. See database_vector.go.
	VectorIndexing() bool
	EnsureVectorIndex(table VectorTable, model string, dimension int) error

	// migrate database schema
	Migrate() error
	UnknownMigrations() ([]string, error)

	// close opened database
	Close() error

	// Transaction runs a function in a transaction, as the server itself.
	Transaction(func(Transaction) error) error

	// TransactionContext runs a function in a transaction on behalf of
	// whoever the context says is acting, so that every audited write in it
	// names them. See ContextWithAuditPrincipal.
	TransactionContext(ctx context.Context, function func(Transaction) error) error
}

func Open

func Open(settings *Settings) (Database, error)

Open database.

type DeliveryOperation

type DeliveryOperation interface {
	// retry deliveries
	ListDeliveriesToRetry(options *Options) ([]*models.Delivery, error)
	// DeferDeliveryRetry changes a storage-read retry only while the caller still owns its lease.
	DeferDeliveryRetry(deliveryId string, claimedRetryAt, retryAt time.Time) (bool, error)

	// list deliveries that belong to a specific domain (via mail's domain_id)
	ListDeliveriesByDomainID(domainId string, options *Options) ([]*models.Delivery, error)

	// list delivieries that belongs to specific mails
	ListDeliveries(mailIds []string, options *Options) ([]*models.Delivery, error)

	// get delivery by id
	GetDelivery(deliveryId string, options *Options) (*models.Delivery, error)

	// get multiple deliveries
	GetDeliveries(deliveryIds []string, options *Options) ([]*models.Delivery, error)

	// create delivery
	CreateDelivery(delivery *models.Delivery, options *Options) (*models.Delivery, error)

	// create multiple deliveries
	CreateDeliveries(deliveries []*models.Delivery, options *Options) ([]*models.Delivery, error)

	// save delivery
	ModifyDelivery(deliveryId string, modifier func(*models.Delivery) error, options *Options) (*models.Delivery, error)

	// save multiple deliveries
	ModifyDeliveries(deliveryIds []string, modifier func([]*models.Delivery) error, options *Options) ([]*models.Delivery, error)

	// delete delivery
	DeleteDelivery(deliveryId string, options *Options) error
}

type DomainOperation

type DomainOperation interface {
	ListDomains() ([]*models.Domain, error)
	GetDomain(domainId string) (*models.Domain, error)
	GetDomainByName(name string) (*models.Domain, error)
	CreateDomain(domain *models.Domain) (*models.Domain, error)
	UpdateDomain(domainId string, modify func(*models.Domain) error) (*models.Domain, error)
	DeleteDomain(domainId string) error

	// SetDomainCertificate stores a certificate obtained for the domain's own
	// mail server name. The server's own doing, on renewal, so no audit row.
	SetDomainCertificate(domainId string, certificate models.DomainCertificate) error
}

DomainOperation changes the domain table, in a transaction and with an audit row for every change. A domain is read with its aliases and credentials, which are its own tables and have their own operations.

type DomainUsageOperation

type DomainUsageOperation interface {
	// store new domain usages
	PutDomainUsages(domainUsagesMap map[string][]models.Usage, options *Options) error

	// query and sum up domain usages later than specified timestamp
	SumDomainUsages(domainIds []string, interval uint64, timestamp uint64, options *Options) ([]models.Usage, error)

	// query domain usages later than specified timestamp
	QueryDomainUsages(domainIds []string, interval uint64, timestamp uint64, options *Options) ([][]models.Usage, error)

	// scavenge usages
	ScavengeDomainUsages(options *Options) error
}

type DreamOperation

type DreamOperation interface {
	StartAgentDream(dream *models.AgentDream) (*models.AgentDream, error)
	FinishAgentDream(dream *models.AgentDream) error

	AdvanceAgentDreamProgress(dream *models.AgentDream, digestedCount, filedCount int) error
	ListAgentDreams(agentId string, limit int) ([]*models.AgentDream, error)

	// CountAgentDocumentsReading is how far the night has got, by the same
	// rule that decides what a night reads: every document but a chat
	// unit, and a chat unit only when the person was in it and it was a
	// conversation.
	CountAgentDocumentsReading(agentId string, names []string) (*AgentReadingCounts, error)

	// ListAgentDocumentsToDigest is what has been indexed and not yet
	// read, in the order a night should read it, and how much is waiting
	// altogether.
	//
	// The order is the priority the person would choose: what they wrote
	// themselves, then what they took part in, then the rest newest
	// first. The count beside it is what the log reports, so a backlog is
	// a number the person can see rather than work silently dropped.
	//
	// names are what the person is called in chat: a thread they took
	// part in is read before anything else, and a chat they were not in
	// is not read at all -- it stays searchable, and is not counted as
	// waiting.
	ListAgentDocumentsToDigest(agentId string, names []string, limit int) ([]*models.AgentDocument, int64, error)

	// MarkAgentDocumentsDigested says these have been read, and every
	// unread document that says the same with them.
	MarkAgentDocumentsDigested(documentIds []string, at time.Time) error

	// MarkAgentDocumentsGarbled says the night could not make sense of
	// what came back about these, and counts it; AgentDocumentsGivenUpOn
	// says how often that has happened to each.
	MarkAgentDocumentsGarbled(documentIds []string, at time.Time) error
	AgentDocumentsGivenUpOn(documentIds []string) (map[string]int, error)

	// MeasureAgentDocuments is how many characters of text each of these
	// documents actually holds, by id, leaving out the ones that hold
	// none.
	//
	// The night asks before deciding that something is too slight to be
	// worth a call. A document's recorded size is the size of a file on
	// somebody's disk, and the kinds that are not files -- a commit, a
	// message -- never had one, so a night that read the size took them
	// all for empty. The text is in the passages, so the passages are
	// what is measured.
	MeasureAgentDocuments(agentId string, documentIds []string) (map[string]int64, error)

	// ListAgentAttachmentsToDecide is the pictures and files a record came
	// with that nobody has read and the night has not decided about:
	// newest first, and only the ones whose bytes this server actually
	// holds, since a file it cannot fetch is not one it can decide to
	// open.
	//
	// Apart from ListAgentDocumentsToDigest because it is the opposite
	// question. That one asks what to read; this one asks what is worth
	// opening at all, which is asked of what has no text and therefore
	// nothing to read.
	ListAgentAttachmentsToDecide(agentId string, limit int) ([]*models.AgentDocument, error)

	// MarkAgentDocumentsDeclined records that the night decided against
	// opening these, and why, so that it is not paid for twice.
	MarkAgentDocumentsDeclined(documentIds []string, reason string, at time.Time) error

	// MarkAgentDocumentsPassedOver counts that a night showed these files
	// and could not judge them, so the queue puts them behind the rest.
	MarkAgentDocumentsPassedOver(documentIds []string) error

	// UnmarkAgentDocumentsDigested puts back into the queue everything
	// marked read since the given time: for a night that marked what it
	// never read. Says how many.
	UnmarkAgentDocumentsDigested(agentId string, since time.Time) (int64, error)

	// ListAgentNodesToConsolidate is the pages whose facts have changed
	// since their summary was written.
	ListAgentNodesToConsolidate(agentId string, limit int) ([]*models.AgentNode, error)
	MarkAgentNodeConsolidated(nodeId string, at time.Time) error

	// ListAgentNodesEmpty is the pages that say nothing: no opening, no
	// facts, nothing under them, no links, and made before the given
	// time. The roots and the period pages are never among them.
	ListAgentNodesEmpty(agentId string, before time.Time, limit int) ([]*models.AgentNode, error)

	// ListAgentMonthsToWriteUp is the months that hold at least so much of
	// the person's own record -- facts placed in them, their commits,
	// threads they took part in -- and have no page yet, or a page that
	// is blank or reads like a guess (matches the pattern), as
	// "2025/08". Months with no page or a blank one come first, then most
	// recent first.
	ListAgentMonthsToWriteUp(agentId string, names []string, least, limit int, guessed string, writtenBefore time.Time) ([]string, error)

	// ListAgentNodesCrowded is the pages holding more than so many facts,
	// most crowded first, never a folder.
	ListAgentNodesCrowded(agentId string, above, limit int) ([]*models.AgentNode, error)

	// ListAgentFactsSaidTwice is every fact whose page already carries
	// the same words on a lower number, of the same kind and not on
	// another date: the later copies, never the first. The same words on
	// two dates are two occurrences, not one said twice.
	ListAgentFactsSaidTwice(agentId string, limit int) ([]*models.AgentFact, error)

	// FirstAgentFactSayingIt is the live fact on the same page as said
	// that says its words on a lower number, of the same kind and not on
	// another date, or nothing where there is none.
	//
	// Asked of the database, because the page is where the pair is and a
	// page may hold more facts than any caller wants to carry. Scanning a
	// listing instead meant a duplicate the query above had found could
	// not be folded, and on a page with more facts than the listing took
	// it never could.
	FirstAgentFactSayingIt(agentId string, said *models.AgentFact) (*models.AgentFact, error)

	// RecomputeAgentImportance rewrites what the index is ordered by, and
	// RetireAgentFacts marks what has not been wanted in a long time
	// dormant. Neither deletes anything.
	RecomputeAgentImportance(agentId string, now time.Time) (int64, error)
	RetireAgentFacts(agentId string, before time.Time) (int, error)

	// The deterministic half of a night: links strengthened by being used
	// together and weakened by not being, a threshold that rises as the
	// graph grows, and the pages that fall under it.
	StrengthenAgentEdges(agentId string, since time.Time, rise, factor float64) (int64, error)
	AgentImportanceThreshold(agentId string, target int) (float64, error)
	RetireAgentNodes(agentId string, threshold float64, before time.Time) (int, error)

	// Walking the graph, for the pass that looks for relations nobody
	// wrote down.
	WalkAgentGraph(agentId, fromId string, steps int) ([]*models.AgentNode, error)
	ListAgentNodesForWalking(agentId string, limit int) ([]*models.AgentNode, error)

	// ListAgentFactsWrittenBefore is what an older build of this program
	// filed, oldest first, so a newer one can go back over it under the
	// rules it has now. See migration 0073.
	ListAgentFactsWrittenBefore(agentId, version string, limit int) ([]*models.AgentFact, error)

	// MarkAgentFactsSeen stamps rows with the build that has looked at
	// them, so the same pass does not look again.
	MarkAgentFactsSeen(agentId string, factIds []string) error
}

DreamOperation is the nightly run's own store.

type EmbeddingOperation

type EmbeddingOperation interface {
	// PutMailEmbedding writes or replaces a message's vector for a model.
	PutMailEmbedding(mailboxId, mailId, model string, vector []float32) error

	// ListMailEmbeddings is the newest vectors a mailbox has for a model,
	// the candidates a search ranks.
	ListMailEmbeddings(mailboxId, model string, limit int) ([]*MailEmbedding, error)

	// ListMailWithoutEmbedding is the newest messages of a mailbox that
	// have no vector for the model yet, for a backfill.
	ListMailWithoutEmbedding(mailboxId, model string, limit int) ([]string, error)

	// DeleteMailEmbeddings forgets a mailbox's vectors.
	DeleteMailEmbeddings(mailboxId string) (int64, error)

	// ScavengeMailEmbeddings removes vectors of a mailbox for models other
	// than the one given: what a change of model left behind.
	ScavengeMailEmbeddings(mailboxId, model string) (int64, error)
}

EmbeddingOperation is the meaning of messages, as vectors.

type EvaluationOperation added in v0.61.0

type EvaluationOperation interface {
	// CreateAgentEvaluationQuestion records a question: put to the person,
	// supplied by them, or imported from a file.
	CreateAgentEvaluationQuestion(question *models.AgentEvaluationQuestion) (*models.AgentEvaluationQuestion, error)

	// GetAgentEvaluationQuestion is one of the agent's questions, or nil.
	GetAgentEvaluationQuestion(agentId, questionId string) (*models.AgentEvaluationQuestion, error)

	// UpdateAgentEvaluationQuestion changes one of the agent's questions.
	UpdateAgentEvaluationQuestion(agentId, questionId string, modify func(*models.AgentEvaluationQuestion) error) (*models.AgentEvaluationQuestion, error)

	// ListAgentEvaluationQuestions is the agent's questions, newest first,
	// in any of the states given, or in every state when none are.
	ListAgentEvaluationQuestions(agentId string, questionStates []models.EvaluationQuestionState) ([]*models.AgentEvaluationQuestion, error)

	// ListAgentFactsToCheck is a random few facts from the person's own
	// pages of one sort (FactsToCheckStated, FactsToCheckDated or
	// FactsToCheckChanged), leaving out those given.
	ListAgentFactsToCheck(agentId, factsToCheck string, excludeFactIds []string, limit int) ([]*models.AgentFact, error)

	// CountAgentFactsToCheck is how many stated facts the person's own
	// pages hold.
	CountAgentFactsToCheck(agentId string) (int64, error)

	// LastAgentMessageStartingWith is when a conversation's latest message
	// that begins with the words given was written, or nil.
	LastAgentMessageStartingWith(conversationId, opening string) (*time.Time, error)

	// CreateAgentEvaluationRun starts a run of the memory check.
	CreateAgentEvaluationRun(agentId string) (*models.AgentEvaluationRun, error)

	// GetAgentEvaluationRun is one of the agent's runs, or nil.
	GetAgentEvaluationRun(agentId, runId string) (*models.AgentEvaluationRun, error)

	// FinishAgentEvaluationRun writes what a run came to.
	FinishAgentEvaluationRun(run *models.AgentEvaluationRun) error

	// ListAgentEvaluationRuns is the agent's runs, newest first.
	ListAgentEvaluationRuns(agentId string, limit int) ([]*models.AgentEvaluationRun, error)

	// PutAgentEvaluationAnswer records one question answered from one
	// source in a run, replacing an earlier answer to the same.
	PutAgentEvaluationAnswer(answer *models.AgentEvaluationAnswer) (*models.AgentEvaluationAnswer, error)

	// ListAgentEvaluationAnswers is every answer of a run, oldest first.
	ListAgentEvaluationAnswers(runId string) ([]*models.AgentEvaluationAnswer, error)
}

EvaluationOperation is the person's memory check: the questions on record, and (with Milestone 5) the runs that grade the agent on them.

type ExchangeRateOperation added in v0.87.0

type ExchangeRateOperation interface {
	// UpsertExchangeRates keeps rates, replacing any for the same day,
	// currency and source. Fetching the same file twice changes nothing.
	UpsertExchangeRates(exchangeRates []models.ExchangeRate) (int, error)

	// LatestExchangeRateDay is the newest day stored from a source,
	// "2006-01-02", or empty when there is none.
	LatestExchangeRateDay(rateSource models.RateSource) (string, error)

	// EuroRatesOn is, for each currency asked, what one euro bought on the
	// latest day on or before the day given that the ECB published it, no
	// more than ExchangeRateStaleDays before it. The euro is one, dated the
	// day given. A currency with no rate that recent is absent.
	EuroRatesOn(currencyCodes []string, on string) (map[string]*models.ExchangeRate, error)

	// ExchangeRate is what one unit of one currency bought in the other on
	// a day, from the latest published rates on or before it, with the day
	// those are from (the older of the two currencies'). A currency with
	// no rate within ExchangeRateStaleDays of the day is a
	// *finance.ErrNoExchangeRate naming it.
	ExchangeRate(fromCurrencyCode, toCurrencyCode, on string) (*models.CurrencyPairRate, error)
}

ExchangeRateOperation is the stored euro reference rates, server-wide: rates are public facts, not anyone's data. Fetching them is the caller's (internal/finance), which asks LatestExchangeRateDay first.

type Facet

type Facet struct {
	Value string
	Count int
}

Facet is one value of a column and how many rows carry it: what fills a filter menu, and the number beside each option.

type FinanceAccountDeleted added in v0.108.0

type FinanceAccountDeleted struct {
	// DeletedTransactionCount is the finance transactions deleted with the
	// account, and DeletedAssetCount the assets.
	DeletedTransactionCount int
	DeletedAssetCount       int

	// ReleasedTransactionIDs are the transactions on other accounts that
	// were paired with a deleted one as a transfer and are uncategorized
	// now; EarliestPostedOn is the first day a deleted transaction posted,
	// where detecting transfers again starts. Empty when none.
	ReleasedTransactionIDs []string
	EarliestPostedOn       string
}

FinanceAccountDeleted is what one DeleteFinanceAccount deleted.

type FinanceAccountRename added in v0.110.0

type FinanceAccountRename struct {
	// AccountName is the person's name for the account; empty leaves the
	// name as it is.
	AccountName string

	// AccountMask is the last digits of the account's number as the
	// person gives them (finance.NormalizePersonAccountMask); nil leaves
	// the number as it is, and empty takes back the person's, so the
	// statement's shows again.
	AccountMask *string
}

FinanceAccountRename is what a rename of a finance account changes. At least one of the two is given.

type FinanceOperation added in v0.87.0

type FinanceOperation interface {
	// ListFinanceAccounts is the agent's finance accounts, of one finance
	// source when sourceId is not empty, oldest first.
	ListFinanceAccounts(agentId, sourceId string) ([]*models.FinanceAccount, error)

	// GetFinanceAccount is one finance account of the agent, or nil.
	GetFinanceAccount(agentId, financeAccountId string) (*models.FinanceAccount, error)

	// RenameFinanceAccount gives a finance account the person's own name,
	// the last digits of its number, or both, kept in its metadata too so
	// the imports that follow keep them (only a statement account's
	// imports read them; a provider's sync names its accounts itself). The
	// asset that values the account takes the new name when it still has
	// the old one. ErrNotFound when the agent has no such finance account.
	RenameFinanceAccount(agentId, financeAccountId string, rename FinanceAccountRename) (*models.FinanceAccount, error)

	// DeleteFinanceAccount deletes a finance account with its finance
	// transactions and every asset that values it, with their history.
	// A transaction on another account that transfer detection had paired
	// with one of the deleted ones is let go of, uncategorized, so the
	// caller can detect transfers again and pair it with what remains.
	// ErrNotFound when the agent has no such finance account.
	DeleteFinanceAccount(agentId, financeAccountId string) (*FinanceAccountDeleted, error)

	// ApplyFinanceSync writes one sync of a finance source, all or
	// nothing: it upserts the finance accounts and the added finance
	// transactions, deletes the removed ones and the pending ones the
	// result replaced, makes an asset for each finance account seen for
	// the first time, and records each finance account's balance as its
	// asset's valuation for syncedOn, the person's local day ("2006-01-02").
	// A transaction the provider sends again unchanged is not written.
	ApplyFinanceSync(agentId, sourceId string, syncResult *finance.SyncResult, syncedOn string) (*FinanceSyncApplied, error)

	// GetFinanceTransaction is one finance transaction of the agent, or nil.
	GetFinanceTransaction(agentId, financeTransactionId string) (*models.FinanceTransaction, error)

	// GetFinanceTransactions is the finance transactions of the agent among
	// the ids given, in no particular order. An id that is none of the
	// agent's is left out, so the caller compares the counts.
	GetFinanceTransactions(agentId string, financeTransactionIds []string) ([]*models.FinanceTransaction, error)

	// ListFinanceTransactions is a page of the agent's finance
	// transactions, newest first, narrowed by the filter.
	ListFinanceTransactions(agentId string, filter *FinanceTransactionFilter) (*FinanceTransactionPage, error)

	// ListFinanceTrades is a page of the agent's trades, newest first,
	// narrowed by the filter, each with its security.
	ListFinanceTrades(agentId string, filter *FinanceTradeFilter) (*FinanceTradePage, error)

	// ListUncategorizedFinanceTransactions is the agent's finance
	// transactions with no spending category (a transfer has the transfer
	// category) that the person has not decided about, that are not
	// mirrored copies (whose category counts for nothing), and that the
	// categorize model has not already been asked about and failed to
	// place: what
	// the categorize model is asked about. Newest first, since this
	// month's spending is what a budget is judged by; a run that places
	// nothing still marks what it was asked about, so older history gets
	// its turn on the next.
	ListUncategorizedFinanceTransactions(agentId string, limit int) ([]*models.FinanceTransaction, error)

	// MarkCategorizeAttempted records that the categorize model was asked
	// about these finance transactions and placed none of them, so they
	// are not listed for it again until their merchant, description or
	// provider category changes, or a spending category they had is taken
	// away by what gave it. One that has a spending category by now is
	// left alone. It answers how many it marked.
	MarkCategorizeAttempted(agentId string, financeTransactionIds []string) (int, error)

	// SetTransactionCategorization gives a finance transaction a spending
	// category (empty for none), saying what gave it and, for the decision
	// model, its confidence. The transfer category makes it a transfer and
	// any other takes that away. It refuses, answering false, to overwrite
	// what the person chose unless the person is choosing again.
	// ErrNotFound when the agent has no such finance transaction or no
	// such spending category; the categorize model is never let give the
	// transfer category, since what it cannot place is spending until
	// something surer says otherwise.
	//
	// The person never clears a spending category: no spending category
	// means not decided yet, and the person's "fits nothing" is the other
	// category, so an empty one from the person is refused.
	SetTransactionCategorization(agentId, financeTransactionId, spendingCategoryId string, categorizedBy models.CategorizedBy, categorizationConfidence *string) (bool, error)

	// CategorizeTransactionsByPerson gives every finance transaction named
	// the spending category as the person's choice, in one statement, as
	// SetTransactionCategorization does for one; an empty one is refused,
	// as it is there. It writes nothing and answers ErrNotFound when any
	// id is none of the agent's or the spending category is not theirs;
	// otherwise it answers how many it wrote.
	CategorizeTransactionsByPerson(agentId string, financeTransactionIds []string, spendingCategoryId string) (int, error)

	// DetectFinanceTransfers gives the transfer category to the finance
	// transactions posted on or after sinceDate in one finance source's
	// accounts (every source's when sourceId is empty) whose provider
	// category is a transfer (categorized by the provider category
	// mapping), and to pairs of the same absolute amount and currency,
	// opposite signs, on two different finance accounts of the agent,
	// posted within three days of each other, each finance transaction in
	// at most one pair and each pair the closest in days for both of its
	// sides (categorized by transfer detection). A finance transaction
	// already a transfer, or whose spending category the person chose, is
	// neither marked nor paired. It answers how many it marked.
	DetectFinanceTransfers(agentId, sourceId, sinceDate string) (int, error)

	// DetectMirroredFinanceTransactions decides again which finance
	// transactions of one finance source (every source of the agent's when
	// sourceId is empty) are mirrored copies: on two or more different
	// finance accounts of one Plaid finance source, every one of them an
	// investment account, with the same day, amount, currency and
	// description (trimmed, in any case), pending or posted. One of each
	// set is counted, a posted one before a pending one, then the one
	// stored first and then the one on the oldest finance account, and the
	// rest become duplicates of it.
	// Two on one account are never copies of each other. Other providers'
	// sources and other kinds of account are not looked at, and neither is
	// a finance transaction the person counted. A copy whose set no longer
	// holds (a member deleted or changed) counts again, and a set whose
	// counted copy went counts another. It locks the finance source first.
	// It answers how many changed.
	DetectMirroredFinanceTransactions(agentId, sourceId string) (int, error)

	// SetFinanceTransactionCountedByPerson records the person saying a
	// mirrored copy is real and counts, after which detection leaves it
	// alone; with isCountedByPerson false it forgets that, and detection
	// decides again at once. Counting a finance transaction that is not a
	// duplicate is refused, since it counts already. ErrNotFound when the
	// agent has no such finance transaction.
	SetFinanceTransactionCountedByPerson(agentId, financeTransactionId string, isCountedByPerson bool) error

	// FinanceSpendingSummary is money out and money in per group per
	// currency over a range of posted days, transfers (the transfer
	// category) and mirrored copies left out, biggest money out first.
	FinanceSpendingSummary(agentId string, filter *FinanceSpendingSummaryFilter) ([]*models.FinanceSpendingSummaryRow, error)
}

FinanceOperation is a person's finance accounts and finance transactions: what their finance sources' syncs write, and the reads the finance tool, the command line and the dashboard answer from. Every call takes the agent id and filters on it, so an id from another person finds nothing.

type FinancePaystubFilter added in v0.155.0

type FinancePaystubFilter struct {
	// From and To bound the pay date, both included, "2006-01-02".
	From string
	To   string

	// Limit is at most FinanceTaxDocumentLimitMost; zero is
	// FinanceTaxDocumentLimitDefault. Offset is how many to pass over.
	Limit  int
	Offset int

	// ShouldCountTotal fills the page's TotalCount.
	ShouldCountTotal bool
}

FinancePaystubFilter narrows a listing of paystubs. Every field is optional.

type FinancePaystubPage added in v0.155.0

type FinancePaystubPage struct {
	FinancePaystubs []*models.FinancePaystub
	HasMore         bool
	TotalCount      int
}

FinancePaystubPage is one page of paystubs, and whether there are more.

type FinanceReceiptDeleted added in v0.118.0

type FinanceReceiptDeleted struct {
	FinanceReceipt           *models.FinanceReceipt
	DeletedAgentAttachmentID string
}

FinanceReceiptDeleted is what one DeleteFinanceReceipt deleted: the receipt as it was, and the uploaded file whose row went with it, whose bytes the caller removes from storage. Empty when no file went.

type FinanceReceiptFilter added in v0.118.0

type FinanceReceiptFilter struct {
	// ReceiptID keeps only this receipt: how a link to one receipt opens it.
	ReceiptID string

	// FinanceTransactionID keeps the receipts matched to this finance
	// transaction.
	FinanceTransactionID string

	// From and To bound the day of purchase, both included, "2006-01-02".
	// A receipt that prints no day is left out when either is given, and
	// listed after every dated one when neither is.
	From string
	To   string

	// IsUndated keeps only the receipts that print no day of purchase;
	// it cannot be given with From or To.
	IsUndated bool

	// IsUnmatched keeps the receipts matched to no finance transaction.
	IsUnmatched bool

	// ShouldSkipLeftToPerson leaves out the receipts a match was taken off
	// by hand, which the receipt matcher no longer matches on its own.
	ShouldSkipLeftToPerson bool
	// Text keeps the receipts whose merchant, receipt number or any line's
	// description holds it, matched case-insensitively.
	Text string

	// Limit is at most FinanceReceiptLimitMost; zero is
	// FinanceReceiptLimitDefault.
	Limit int

	// After is the NextCursor of the page before. Offset is how many to
	// pass over first, for a page by its number; with After it counts
	// from the cursor.
	After  string
	Offset int

	// ShouldCountTotal fills the page's TotalCount, which costs one more
	// statement.
	ShouldCountTotal bool
}

FinanceReceiptFilter narrows a listing of finance receipts. Every field is optional.

type FinanceReceiptMatchDropped added in v0.118.0

type FinanceReceiptMatchDropped struct {
	ReceiptMatch *models.FinanceReceiptMatch
	DropReason   string
}

FinanceReceiptMatchDropped is a match DropUnfittingFinanceReceiptMatches took off, and why it no longer fits, in words.

type FinanceReceiptOperation added in v0.118.0

type FinanceReceiptOperation interface {
	// SetFinanceTransactionAnnotation writes what the person or their
	// agent says about a finance transaction; empty takes it away. It
	// refuses, answering false and writing no audit event, to let the
	// agent overwrite or take away what the person wrote, unless
	// canReplacePersonAnnotation (the person asked for it, there with the
	// agent); the person always may. ErrNotFound when the agent has no
	// such finance transaction.
	SetFinanceTransactionAnnotation(agentId, financeTransactionId, annotation string, annotatedBy models.AnnotatedBy, canReplacePersonAnnotation bool) (bool, error)

	// PutFinanceReceipt writes a receipt with its lines. When the agent
	// already holds a receipt read from the same source, this one takes
	// its place under the same id: its lines are replaced and its matches
	// kept, for the caller to match again and to check with
	// DropUnfittingFinanceReceiptMatches. The check state and difference
	// are written as given. It answers the receipt as stored, with its
	// lines and matches. ErrInvalidArguments for an amount or a quantity
	// larger than its column holds.
	PutFinanceReceipt(receipt *models.FinanceReceipt) (*models.FinanceReceipt, error)

	// DropUnfittingFinanceReceiptMatches takes off a receipt the matches
	// that no longer fit it, as PutFinanceReceiptMatch would refuse them
	// now: after the receipt was read again with a lower total or in
	// another currency, say. The oldest match is kept first, and each
	// later one is weighed against those kept before it. It answers the
	// matches taken off, each with why. ErrNotFound when the agent has no
	// such receipt.
	DropUnfittingFinanceReceiptMatches(agentId, receiptId string) ([]*FinanceReceiptMatchDropped, error)

	// GetFinanceReceipt is one receipt of the agent with its lines and
	// matches, or nil.
	GetFinanceReceipt(agentId, receiptId string) (*models.FinanceReceipt, error)

	// IsFinanceReceiptLeftToPerson says the person took a match off the
	// receipt by hand, so nothing matches it on its own again.
	IsFinanceReceiptLeftToPerson(agentId, receiptId string) (bool, error)

	// FindFinanceReceiptBySource is the agent's receipt read from a
	// source, or nil: the kind and the id the kind names.
	FindFinanceReceiptBySource(agentId string, receiptSourceKind models.ReceiptSourceKind, sourceId string) (*models.FinanceReceipt, error)

	// ListFinanceReceipts is one page of the agent's receipts the filter
	// keeps, with their lines and matches, the newest purchase first and
	// the receipts that print no day after every dated one.
	ListFinanceReceipts(agentId string, filter *FinanceReceiptFilter) (*FinanceReceiptPage, error)

	// FinanceReceiptMatchCoverage is what receipts already explain of each
	// of these finance transactions, for matching receiptId: from every
	// receipt, from receipts other than it, and whether another is matched
	// at all. A finance transaction no receipt is matched to is left out.
	FinanceReceiptMatchCoverage(agentId, receiptId string, financeTransactionIds []string) (map[string]*finance.ReceiptMatchCoverage, error)

	// DeleteFinanceReceipt deletes a receipt with its lines and matches,
	// and its uploaded photo or PDF unless a message of a conversation
	// holds the same file. ErrNotFound when the agent has no such receipt.
	DeleteFinanceReceipt(agentId, receiptId string) (*FinanceReceiptDeleted, error)

	// PutFinanceReceiptMatch matches a receipt to a finance transaction,
	// or changes the amount and source of the match they have. The
	// receipt matcher never replaces a match the person made, and answers
	// false when it would have. ErrNotFound when either is not the
	// agent's. ErrInvalidArguments when the charge is in another currency
	// than the receipt, is not money out, the amount has more places than
	// the currency has, or the receipts matched to the charge would then
	// explain more than it took.
	PutFinanceReceiptMatch(agentId string, match *models.FinanceReceiptMatch) (bool, error)

	// DeleteFinanceReceiptMatch takes a receipt off a finance transaction,
	// answering whether there was a match. With a source, only a match of
	// that source is taken off, so the receipt matcher never removes the
	// person's. With none, the match is taken off by hand, and the receipt
	// is left to the person from then on: the matcher no longer matches it
	// on its own to a charge a sync brings (ShouldSkipLeftToPerson).
	DeleteFinanceReceiptMatch(agentId, receiptId, financeTransactionId string, receiptMatchSource models.ReceiptMatchSource) (bool, error)
}

FinanceReceiptOperation is the annotations on a person's finance transactions and their receipts: what a merchant printed, line by line, and which charges each receipt explains. Every call takes the agent id and filters on it, so an id from another person finds nothing. The checking and the matching are the finance package's; this keeps what they decided.

type FinanceReceiptPage added in v0.118.0

type FinanceReceiptPage struct {
	FinanceReceipts []*models.FinanceReceipt
	NextCursor      string
	TotalCount      int
}

FinanceReceiptPage is one page of receipts, and the cursor for the next, empty on the last. TotalCount is how many match the filter on every page, when it was asked for.

type FinanceSpendingSummaryFilter added in v0.87.0

type FinanceSpendingSummaryFilter struct {
	// From and To bound the posted day, both included, "2006-01-02";
	// either may be empty.
	From string
	To   string

	GroupBy models.FinanceSpendingSummaryGroupBy

	// FinanceAccountID limits it to one finance account; empty is all.
	FinanceAccountID string
}

FinanceSpendingSummaryFilter is what a spending summary covers.

type FinanceSyncApplied added in v0.87.0

type FinanceSyncApplied struct {
	// InsertedFinanceAccountIDs are the finance accounts seen for the
	// first time, and CreatedAssetIDs the assets made for them.
	InsertedFinanceAccountIDs []string
	CreatedAssetIDs           []string

	// WrittenTransactionCount is the finance transactions inserted or
	// changed; one sent again unchanged is not counted.
	// InsertedTransactionCount is those of them that were new.
	WrittenTransactionCount  int
	InsertedTransactionCount int

	// RemovedTransactionCount is the finance transactions the provider
	// removed, and ReplacedPendingTransactionCount the pending ones it
	// stopped reporting inside the window it replaced.
	RemovedTransactionCount         int
	ReplacedPendingTransactionCount int

	// SkippedTransactionCount is the transactions for a finance account
	// neither the result nor the store knows, which were not written.
	SkippedTransactionCount int

	// RecordedValuationCount is the finance accounts and holdings whose
	// value was recorded as their asset's valuation for the day.
	RecordedValuationCount int

	// WrittenTradeCount is the trades inserted or changed; one sent again
	// unchanged is not counted. SkippedTradeCount is those for a finance
	// account neither the result nor the store knows.
	WrittenTradeCount int
	SkippedTradeCount int

	// FinanceTransactionIDsToCategorize are the inserted or changed finance
	// transactions left without a spending category that are not
	// transfers: new ones, and those whose merchant, description or
	// provider category changed under a spending category the person did
	// not choose.
	FinanceTransactionIDsToCategorize []string

	// InsertedFinanceTransactionIDs are the finance transactions seen for
	// the first time, pending or posted, the posted one a stored pending
	// one became included: receipts recorded before their charge arrived
	// are matched against these.
	InsertedFinanceTransactionIDs []string
}

FinanceSyncApplied is what one ApplyFinanceSync wrote.

type FinanceTaxDocumentDeleted added in v0.155.0

type FinanceTaxDocumentDeleted struct {
	DeletedAgentAttachmentID string
}

FinanceTaxDocumentDeleted is the uploaded file whose row went with a deleted paystub or tax form, whose bytes the caller removes from storage; empty when no file went.

type FinanceTaxFormFilter added in v0.155.0

type FinanceTaxFormFilter struct {
	// TaxYear keeps one year's forms; zero keeps every year's.
	TaxYear int

	Limit            int
	Offset           int
	ShouldCountTotal bool
}

FinanceTaxFormFilter narrows a listing of tax forms. Every field is optional.

type FinanceTaxFormPage added in v0.155.0

type FinanceTaxFormPage struct {
	FinanceTaxForms []*models.FinanceTaxForm
	HasMore         bool
	TotalCount      int
}

FinanceTaxFormPage is one page of tax forms, and whether there are more.

type FinanceTaxOperation added in v0.155.0

type FinanceTaxOperation interface {
	// PutFinancePaystub writes a paystub with its lines. When the agent
	// already holds a paystub read from the same upload, this one takes
	// its place under the same id; a tax form read from it before is
	// deleted, since one file is one document. ErrNotFound when the
	// upload is not the agent's; ErrInvalidArguments for an amount larger
	// than its column holds.
	PutFinancePaystub(paystub *models.FinancePaystub) (*models.FinancePaystub, error)

	// GetFinancePaystub is one paystub of the agent with its lines, or nil.
	GetFinancePaystub(agentId, paystubId string) (*models.FinancePaystub, error)

	// ListFinancePaystubs is one page of the agent's paystubs the filter
	// keeps, with their lines, the latest pay date first.
	ListFinancePaystubs(agentId string, filter *FinancePaystubFilter) (*FinancePaystubPage, error)

	// DeleteFinancePaystub deletes a paystub with its lines and its
	// uploaded file, unless a message of a conversation holds the same
	// file. ErrNotFound when the agent has no such paystub.
	DeleteFinancePaystub(agentId, paystubId string) (*FinanceTaxDocumentDeleted, error)

	// PutFinanceTaxForm writes a tax form with its boxes, as
	// PutFinancePaystub writes a paystub: in the place of the one read
	// from the same upload, deleting a paystub read from it before.
	PutFinanceTaxForm(taxForm *models.FinanceTaxForm) (*models.FinanceTaxForm, error)

	// DeleteFinanceTaxFormsOfAttachment deletes the tax forms read from an
	// upload of the agent's whose kind is not one of keptKinds, with their
	// boxes, keeping the upload: a statement read again that holds fewer
	// forms than before.
	DeleteFinanceTaxFormsOfAttachment(agentId, attachmentId string, keptKinds []models.TaxFormKind) error

	// GetFinanceTaxForm is one tax form of the agent with its boxes, or nil.
	GetFinanceTaxForm(agentId, taxFormId string) (*models.FinanceTaxForm, error)

	// ListFinanceTaxForms is one page of the agent's tax forms the filter
	// keeps, with their boxes, the latest tax year first.
	ListFinanceTaxForms(agentId string, filter *FinanceTaxFormFilter) (*FinanceTaxFormPage, error)

	// DeleteFinanceTaxForm deletes a tax form with its boxes and its
	// uploaded file, as DeleteFinancePaystub does.
	DeleteFinanceTaxForm(agentId, taxFormId string) (*FinanceTaxDocumentDeleted, error)
}

FinanceTaxOperation is a person's paystubs and tax forms, each read out of one uploaded file. Every call takes the agent id and filters on it, so an id from another person finds nothing. The checking is the finance package's; this keeps what it decided.

type FinanceTradeFilter added in v0.88.0

type FinanceTradeFilter struct {
	// From and To bound the traded day, both included, "2006-01-02".
	From string
	To   string

	FinanceAccountID  string
	FinanceSecurityID string

	// Limit is at most FinanceTradeLimitMost; zero is
	// FinanceTradeLimitDefault.
	Limit int

	// After is the NextCursor of the page before. Offset is how many to
	// pass over first, for a page by its number; with After it counts
	// from the cursor.
	After  string
	Offset int

	// ShouldCountTotal fills the page's TotalCount, which costs one more
	// statement.
	ShouldCountTotal bool
}

FinanceTradeFilter narrows a page of trades. Every field is optional.

type FinanceTradePage added in v0.88.0

type FinanceTradePage struct {
	FinanceTrades []*models.FinanceTrade
	NextCursor    string
	TotalCount    int
}

FinanceTradePage is one page of trades, and the cursor for the next, empty on the last. TotalCount is how many match the filter on every page, the cursor and the offset aside, when the filter asked for it.

type FinanceTransactionFilter added in v0.87.0

type FinanceTransactionFilter struct {
	// From and To bound the posted day, both included, "2006-01-02".
	From string
	To   string

	FinanceAccountID string

	// Text is matched case-insensitively within the description or the
	// merchant.
	Text string

	// MinimumAmount and MaximumAmount bound the signed amount, both ends
	// included: money out is negative.
	MinimumAmount string
	MaximumAmount string

	// ProviderCategory matches the provider's primary or detailed
	// category exactly.
	ProviderCategory string

	SpendingCategoryID string

	// IsUncategorized keeps only finance transactions with no spending
	// category; a transfer has the transfer category, and a mirrored copy
	// is left out, since its category counts for nothing.
	IsUncategorized bool

	// IsTransferExcluded leaves out the transfers, the finance
	// transactions in the transfer category.
	IsTransferExcluded bool

	// IsDuplicateExcluded leaves out the mirrored copies, the finance
	// transactions that are duplicates of another.
	IsDuplicateExcluded bool

	// DuplicateOfTransactionID keeps only the duplicates of this finance
	// transaction.
	DuplicateOfTransactionID string

	// FinanceTransactionIDs keeps only these finance transactions, so one
	// can be read by its id with the same fields as a page.
	FinanceTransactionIDs []string

	// Limit is at most FinanceTransactionLimitMost; zero is
	// FinanceTransactionLimitDefault.
	Limit int

	// After is the NextCursor of the page before. Offset is how many to
	// pass over first, for a page by its number; with After it counts
	// from the cursor.
	After  string
	Offset int

	// ShouldCountTotal fills the page's TotalCount, and with
	// IsDuplicateExcluded its LeftOutDuplicateCount: one more statement,
	// so the reads that walk every page by the cursor leave it off.
	ShouldCountTotal bool

	// ShouldReadIDsOnly reads each finance transaction's id and posted
	// day alone, which is all a read that collects ids needs; every
	// other field of the rows it gives is empty.
	ShouldReadIDsOnly bool
}

FinanceTransactionFilter narrows a listing of finance transactions. Every field is optional.

type FinanceTransactionPage added in v0.87.0

type FinanceTransactionPage struct {
	FinanceTransactions   []*models.FinanceTransaction
	NextCursor            string
	TotalCount            int
	LeftOutDuplicateCount int
}

FinanceTransactionPage is one page of finance transactions, and the cursor for the next, empty on the last. TotalCount is how many match the filter on every page, the cursor and the offset aside, when the filter asked for it; LeftOutDuplicateCount is then how many mirrored copies would match too but IsDuplicateExcluded left out.

type FolderOptions added in v0.78.0

type FolderOptions struct {
	// ShouldExcludeDeleted leaves out items flagged with IMAP's \Deleted.
	// The dashboard shows a folder without them, since they are on their way
	// out; IMAP has to count them, because a client that flagged one still
	// sees it until it expunges.
	ShouldExcludeDeleted bool

	// ShouldCountNotes counts the items of each folder that hold a phone's
	// note, so the dashboard can show a folder of notes as notes. Only the
	// dashboard asks: it costs a join with every message, and IMAP has no
	// use for the answer.
	ShouldCountNotes bool
}

FolderOptions says what a folder's counts count.

type GoalOperation added in v0.111.0

type GoalOperation interface {
	// ListAgentGoals is the agent's goal conversations in the states
	// given, every state when none is, the most recently active first.
	ListAgentGoals(agentId string, goalStates []models.AgentGoalState, limit int) ([]*models.AgentConversation, error)

	// AddAgentGoalActivity writes one row of a goal's log.
	AddAgentGoalActivity(activity *models.AgentGoalActivity) (*models.AgentGoalActivity, error)

	// ListAgentGoalActivity is a goal's log, newest first.
	ListAgentGoalActivity(agentId, conversationId string, limit int) ([]*models.AgentGoalActivity, error)

	// AddAgentGoalArtifact records something a goal made.
	AddAgentGoalArtifact(artifact *models.AgentGoalArtifact) (*models.AgentGoalArtifact, error)

	// ListAgentGoalArtifacts is what a goal made, oldest first.
	ListAgentGoalArtifacts(agentId, conversationId string) ([]*models.AgentGoalArtifact, error)

	// ListAgentGoalsWithoutNextTurn is every goal, across agents, that is
	// working with no next turn of its own: one its schedule keeps, or one
	// whose schedule has since gone and that needs a turn again.
	ListAgentGoalsWithoutNextTurn(limit int) ([]*models.AgentConversation, error)

	// ListAgentGoalsToSurface is every goal, across agents, that waits on
	// its person and has not yet been said in their main conversation.
	ListAgentGoalsToSurface(limit int) ([]*models.AgentConversation, error)
}

GoalOperation keeps what a goal did and made: its activity, which the person reads as the goal's log, and the artifacts that carry no conversation of their own. The goal itself is a conversation of the kind goal, kept with the rest of them.

type GraphOperation

type GraphOperation interface {
	// AsActor says who the writes in this transaction are by, so the
	// history can say. Unset means the agent itself.
	//
	// On the transaction rather than on every call because it is true of
	// the whole run: a nightly pass is the nightly run from beginning to
	// end, and threading it through fifteen signatures would be fifteen
	// chances to pass the wrong one.
	AsActor(actor models.RevisionActor)

	// EnsureAgentRoots makes the pages every graph starts with, and is
	// idempotent. Called the first time an agent's graph is touched.
	EnsureAgentRoots(agentId string) error

	// GetAgentNode is a page by its path, or nil. GetAgentNodeByID is the
	// same by identifier, which is what the API and the vector search use.
	GetAgentNode(agentId, path string) (*models.AgentNode, error)
	GetAgentNodeByID(agentId, nodeId string) (*models.AgentNode, error)
	GetAgentNodes(agentId string, nodeIds []string) ([]*models.AgentNode, error)

	// PutAgentNode creates the page at its path or updates the one there,
	// filling in the parent from the path and making any missing page
	// above it as a folder. The node it answers with carries the
	// identifier and the times.
	PutAgentNode(node *models.AgentNode) (*models.AgentNode, error)

	// SetAgentNodeSummary writes a page's opening and nothing else, and
	// says whether it changed. For a writer that owns only the opening,
	// the nightly rewrite: saving the whole page from a copy read before a
	// model call put back whatever a rename, an alias, a pin or an archive
	// had changed in the meantime.
	SetAgentNodeSummary(agentId, nodeId, summary string) (bool, error)

	// MoveAgentNode puts a page under another, rewriting the paths of
	// everything beneath it.
	MoveAgentNode(agentId, path, newParentPath string) (*models.AgentNode, error)

	// DeleteAgentNode removes a page and everything under it. Only a
	// person does this; the nightly run marks dormant instead.
	DeleteAgentNode(agentId, path string) (int64, error)

	// ListAgentNodeChildren is the pages directly under one.
	ListAgentNodeChildren(agentId, nodeId string) ([]*models.AgentNode, error)

	// FirstAgentFactLines is one line per page -- the first fact on each
	// -- for a list that has to tell one row from the next where the page
	// has no opening. One query for the whole page of rows.
	FirstAgentFactLines(agentId string, nodeIds []string) (map[string]string, error)

	// ListAgentNodeChildrenPage is a page of them, by name,
	// with how many there are altogether: a folder of two thousand
	// projects is browsed fifty at a time and the heading says two
	// thousand.
	ListAgentNodeChildrenPage(agentId, nodeId string, limit, offset int) ([]*models.AgentNode, int64, error)

	// ListAgentIndex is the top of the graph, pinned first then by
	// importance: what a prompt carries. Dormant pages are never in it.
	ListAgentIndex(agentId string, limit int) ([]*models.AgentNode, error)
	ListAgentNodesOfKind(agentId string, kind models.AgentNodeKind, searchText string, limit int) ([]*models.AgentNode, error)

	// ListAgentNodesUnder is every page at or below a path, oldest first,
	// for a tree view and for the move above.
	ListAgentNodesUnder(agentId, path string, limit int) ([]*models.AgentNode, error)

	// FindAgentNodeByName is the page filed directly under a parent that
	// answers to a name, by its name or by one of its aliases, whatever
	// slug its path uses.
	//
	// Asked of the database rather than by listing the parent and looking
	// through what comes back. That listing is of the whole subtree,
	// sorted by path and capped, so under a parent with more pages beneath
	// it than the cap the one being looked for was usually not in what
	// came back, the caller concluded there was no such page, and it made
	// a second one.
	FindAgentNodeByName(agentId, parent string, kind models.AgentNodeKind, name string) (*models.AgentNode, error)

	// AddAgentFact puts a sentence on a page, taking the next number.
	AddAgentFact(fact *models.AgentFact) (*models.AgentFact, error)

	// CountAgentNodeChildren is how many pages are filed under each of
	// the given ones, in one query.
	CountAgentNodeChildren(agentId string, nodeIds []string) (map[string]int, error)

	// MergeAgentNodes folds one page into another: its facts move over,
	// its links are re-pointed, its children go under the other, its
	// aliases and name join the other's aliases, and it is deleted. Two
	// pages for one thing is the graph's commonest wrong shape.
	MergeAgentNodes(agentId, fromPath, intoPath string) (*models.AgentNode, error)

	// MoveAgentFact puts a fact on another page, keeping its identifier
	// and taking the next number there; both pages' histories say so.
	MoveAgentFact(agentId, factId, toNodeId string) (*models.AgentFact, error)

	// UpdateAgentFact changes one, by identifier.
	UpdateAgentFact(agentId, factId string, modify func(*models.AgentFact) error) (*models.AgentFact, error)

	// FoldAgentFact marks a fact as standing behind another one: dormant,
	// pointing at the row the page now states, kept. StrikeAgentFact
	// marks one dormant with nothing in its place. Both are what the
	// agent does on its own, and neither deletes -- only the person's own
	// forgetting reaches DeleteAgentFact. The reason is what the page's
	// history shows, since the same two columns move for several quite
	// different decisions.
	FoldAgentFact(agentId, factId, intoFactId, reason string) (*models.AgentFact, error)
	StrikeAgentFact(agentId, factId, reason string) (*models.AgentFact, error)

	// GetAgentFact is one fact by node and number -- how a person and a
	// model name one -- and GetAgentFacts several by identifier.
	GetAgentFact(agentId, nodeId string, number int) (*models.AgentFact, error)
	GetAgentFacts(agentId string, factIds []string) ([]*models.AgentFact, error)

	// ListAgentFacts is a page's facts, live ones first by use.
	ListAgentFacts(agentId, nodeId string, includeDormant bool, limit int) ([]*models.AgentFact, error)
	// ListAgentFactsLively is the same, most recently wanted or changed
	// first, for a reader that has room for only some of them.
	ListAgentFactsLively(agentId, nodeId string, limit int) ([]*models.AgentFact, error)

	// ListAgentFactsStartingWith is every live fact whose text starts with
	// a prefix, on whatever page it now sits: the lines a checkout's
	// profile writes ("The checkout is at <directory> on <computer>.",
	// "Lives at <remote>.") are how a coding session finds its project.
	ListAgentFactsStartingWith(agentId, prefix string, limit int) ([]*models.AgentFact, error)

	// ListAgentFactsOfKindNewestFirst is a page's live facts of one kind,
	// the most recently filed first.
	ListAgentFactsOfKindNewestFirst(agentId, nodeId string, factKind models.AgentFactKind, limit int) ([]*models.AgentFact, error)

	// ListAgentFactsForAudience is what an unattended run of a kind
	// reads, newest and most used first.
	ListAgentFactsForAudience(agentId string, audience models.AgentAudience, limit int) ([]*models.AgentFact, error)

	// ListAgentFactsBetween is every fact that happened in a stretch of
	// time, oldest first: what a period page is written from.
	ListAgentFactsBetween(agentId string, from, until time.Time, limit int) ([]*models.AgentFact, error)

	// ListAgentFactsLearnedSince is what has been filed lately, newest
	// first: what the agent page shows under "Learned today", and what a
	// person struck from it corrects.
	ListAgentFactsLearnedSince(agentId string, since time.Time, limit int) ([]*models.AgentFact, error)

	// DeleteAgentFact forgets one.
	DeleteAgentFact(agentId, factId string) error

	// SearchAgentGraph finds pages and facts by words, best match first.
	SearchAgentGraph(agentId, query string, limit int) ([]*models.AgentNode, []*models.AgentFact, error)

	// SearchAgentGraphFrom is the same search read on from an offset: the
	// pages and the facts past the first offset of each, in the same
	// order, so that one page of results carries on from the last.
	SearchAgentGraphFrom(agentId, query string, offset, limit int) ([]*models.AgentNode, []*models.AgentFact, error)

	// PutAgentEdge joins two pages, or changes the join.
	PutAgentEdge(edge *models.AgentEdge) error
	DeleteAgentEdge(agentId, fromId, toId string, relation models.AgentEdgeRelation) error

	// ListAgentEdges is everything joined to a page, in either direction,
	// with the other end's path filled in.
	ListAgentEdges(agentId, nodeId string) ([]*models.AgentEdge, error)

	// ListAgentEdgesByRelation is every link of one relation an agent's
	// graph holds, with both ends' paths filled in: what a writer that
	// owns a relation's links reads before replacing its own.
	ListAgentEdgesByRelation(agentId string, relation models.AgentEdgeRelation) ([]*models.AgentEdge, error)

	// TouchAgentNodes and TouchAgentFacts mark what a prompt carried or a
	// search found as used. Used time feeds the nightly importance; it
	// does not order the index, because a prompt whose order moves every
	// turn cannot be cached.
	TouchAgentNodes(nodeIds []string, at time.Time) error
	TouchAgentFacts(factIds []string, at time.Time) error

	// The vectors. Put writes one; ListWithout says what is still waiting
	// for one, so a change of model catches up a few at a time.
	PutAgentGraphVectors(agentId string, vectors []AgentGraphVector) (int, error)
	PutAgentNodeVector(agentId, nodeId, model string, vector []float32) error
	PutAgentFactVector(agentId, factId, model string, vector []float32) error
	ListAgentNodesWithoutVector(agentId, model string, limit int) ([]*models.AgentNode, error)
	ListAgentFactsWithoutVector(agentId, model string, limit int) ([]*models.AgentFact, error)

	// CountAgentGraph is how much there is, for the dashboard and for the
	// nightly run's own report.
	CountAgentGraph(agentId string) (nodes, facts int64, err error)

	// SetUserContact names the address book entry that is the account
	// itself, and GetUserContact reads it back.
	SetUserContact(userId, contactId string) error

	// PutAgentRecordLink joins a page to one of the person's own records,
	// or changes the join: the same page, record and relation said again
	// is the same link. A statement is never turned back into a proposal
	// by being proposed again. DeleteAgentRecordLink takes a page's links
	// to a record away, those of one relation or, with none given, all of
	// them, and says how many there were. A range limits it to one
	// passage of a recording. Deleting is the person's removal, which the
	// automatic passes remember; WithdrawAgentRecordLink is the same
	// without that memory, for the agent taking back its own proposal and
	// for a card swapped for another. A stated link to a person page's
	// card sets the page's contact, and removing that link clears it.
	PutAgentRecordLink(link *models.AgentRecordLink) (*models.AgentRecordLink, error)
	DeleteAgentRecordLink(agentId, nodeId string, recordKind models.AgentRecordKind, recordId string, recordRelation models.AgentRecordRelation, startMS, endMS int64) (int64, error)
	WithdrawAgentRecordLink(agentId, nodeId string, recordKind models.AgentRecordKind, recordId string, recordRelation models.AgentRecordRelation, startMS, endMS int64) (int64, error)
	GetAgentRecordLink(agentId, linkId string) (*models.AgentRecordLink, error)

	// ListAgentRecordLinkDismissals is the links the person took off a
	// page by hand, keyed as models.RecordLinkKey, which the automatic
	// passes must not make again. Making the link by hand clears it.
	ListAgentRecordLinkDismissals(agentId string) (map[string]bool, error)

	// ListAgentRecordLinkStatuses is every link of the agent keyed as
	// models.RecordLinkKey, with its status.
	ListAgentRecordLinkStatuses(agentId string) (map[string]models.AgentEdgeStatus, error)

	// ListAgentNodesOfKinds is the live pages of these kinds, most important
	// first, up to the limit (at most 5000), for a pass that matches names.
	ListAgentNodesOfKinds(agentId string, kinds []models.AgentNodeKind, limit int) ([]*models.AgentNode, error)

	// ListAgentRecordLinks is everything a page is linked to, grouped by
	// the kind of record and newest first. ListAgentRecordBacklinks is the
	// other direction: the pages linked to one record, with their paths
	// filled in. For a passage of a recording, a range narrows it to the
	// passages that overlap it.
	ListAgentRecordLinks(agentId, nodeId string) ([]*models.AgentRecordLink, error)
	ListAgentRecordBacklinks(agentId string, recordKind models.AgentRecordKind, recordId string, startMS, endMS int64, limit int) ([]*models.AgentRecordLink, error)

	// SetAgentNodeContact names the address book entry a page is about,
	// and empty clears it. It writes that one column: saving the whole
	// page from a copy read earlier would put back whatever else changed.
	SetAgentNodeContact(agentId, nodeId, contactId string) error
}

GraphOperation is the graph as the rest of the server reaches it.

type GroupOperation

type GroupOperation interface {
	ListGroups() ([]*models.Group, error)
	GetGroup(groupId string) (*models.Group, error)
	GetGroupByName(name string) (*models.Group, error)
	CreateGroup(group *models.Group) (*models.Group, error)

	// UpdateGroup applies a change to the group and its users, roles and
	// domains as they stand, and records the before and after.
	UpdateGroup(groupId string, modify func(*models.Group) error) (*models.Group, error)

	DeleteGroup(groupId string) error

	// EffectivePermissions is what a user may do, from every group they are
	// in: the groups' roles crossed with the groups' domains.
	EffectivePermissions(userId string) (*models.EffectivePermissions, error)

	// GroupPermissions is what belonging to one group carries.
	GroupPermissions(groupId string) (*models.EffectivePermissions, error)

	// ProposedGroupPermissions is what a group would carry if it were
	// given these roles over these domains.
	ProposedGroupPermissions(roleIds, domainIds []string) (*models.EffectivePermissions, error)
}

GroupOperation changes the group table and the three tables that hang off it, in a transaction and with an audit row for every change.

type IdeaOperation added in v0.76.0

type IdeaOperation interface {
	// UpsertAgentIdea records an idea, or refreshes the words, the tools,
	// the evidence, the rank and the expiry of the one with the same key,
	// leaving what became of it alone: reading the catalog again never
	// brings back an idea the person dismissed.
	UpsertAgentIdea(idea *models.AgentIdea) (*models.AgentIdea, error)

	// GetAgentIdea is one of the agent's ideas, or nil.
	GetAgentIdea(agentId, ideaId string) (*models.AgentIdea, error)

	// UpdateAgentIdea changes one of the agent's ideas.
	UpdateAgentIdea(agentId, ideaId string, modify func(*models.AgentIdea) error) (*models.AgentIdea, error)

	// ListAgentIdeas is the agent's ideas in any of the statuses and kinds
	// given, or in every one when none are, the highest ranked first and
	// then the newest.
	ListAgentIdeas(agentId string, statuses []models.AgentIdeaStatus, kinds []models.AgentIdeaKind) ([]*models.AgentIdea, error)

	// MarkAgentIdeasShown notes that ideas were put in front of the person,
	// for those not shown before.
	MarkAgentIdeasShown(agentId string, ideaIds []string, at time.Time) error
}

IdeaOperation keeps the agent's ideas: offers of work it can do for the person, and what became of each.

type IdentityOperation

type IdentityOperation interface {
	GetIdentity(provider, subject string) (*models.UserIdentity, error)
	ListIdentities(userId string) ([]*models.UserIdentity, error)
	CreateIdentity(identity *models.UserIdentity) (*models.UserIdentity, error)
	TouchIdentity(identityId string, email string, at time.Time) error
	DeleteIdentity(identityId string) error
}

IdentityOperation is the user_identity table: who a person is at an identity provider.

type ImportedMediaReference added in v0.153.0

type ImportedMediaReference struct {
	UserID           string
	RecordingMediaID string
}

ImportedMediaReference names an imported original and the account that owns it.

type InsightOperation

type InsightOperation interface {
	// PutMailInsight writes sorting fields, preserving existing proposals and
	// research notes. New insights may include initial proposals and notes.
	PutMailInsight(insight *models.MailInsight) error

	// SetMailInsightNotes writes what research found onto an insight.
	SetMailInsightNotes(mailId, mailboxId, notes, runId string) error

	// GetMailInsights reads the insights a mailbox has for these messages,
	// by mail id.
	GetMailInsights(mailboxId string, mailIds []string) (map[string]*models.MailInsight, error)
	LockMailInsight(mailboxId, mailId string) (*models.MailInsight, error)
	SetMailProposalStatus(mailboxId, mailId string, index int, proposalStatus string) error
	ReplaceMailProposals(mailboxId, mailId string, proposals []models.MailProposal) error

	// ListMailWithoutInsight is the newest messages of a mailbox — in any
	// folder but Junk, Trash, Drafts and Sent, since a rule may have filed
	// a message before the agent saw it — that have no insight yet, for a
	// backfill.
	ListMailWithoutInsight(mailboxId string, limit int) ([]string, error)

	// DeleteMailInsights forgets everything a mailbox was told.
	DeleteMailInsights(mailboxId string) (int64, error)

	// PutThreadSummary writes or replaces a conversation's summary.
	PutThreadSummary(summary *models.ThreadSummary) error

	// GetThreadSummary reads a conversation's summary, nil when there is
	// none.
	GetThreadSummary(mailboxId, threadId string) (*models.ThreadSummary, error)

	// DeleteThreadSummaries forgets every summary a mailbox has.
	DeleteThreadSummaries(mailboxId string) (int64, error)

	CreateAgentConversation(conversation *models.AgentConversation) (*models.AgentConversation, error)
	// MainAgentConversation is the agent's one continuous conversation,
	// made with the given surface the first time it is needed.
	MainAgentConversation(agentId string, surface string) (*models.AgentConversation, error)
	// FreshMainAgentConversation starts a new main conversation; the old one
	// becomes a named one, due for a title.
	FreshMainAgentConversation(agentId string, surface string) (*models.AgentConversation, error)
	GetAgentConversation(conversationId string) (*models.AgentConversation, error)

	// FindAgentConversationBySubject is the newest conversation of a kind
	// whose subject is the one given, not archived, or nil.
	FindAgentConversationBySubject(agentId string, kind models.AgentConversationKind, subjectId string) (*models.AgentConversation, error)

	// UpdateAgentConversation changes a conversation. When its goal becomes
	// met, the ideas it was carrying out are done, and started again when
	// it is taken back up.
	UpdateAgentConversation(conversationId string, modify func(*models.AgentConversation) error) (*models.AgentConversation, error)

	// AddAgentConversationBackgroundWake counts one more turn woken by
	// background commands or work in a conversation, and
	// ResetAgentConversationBackgroundWakes starts the count again, for
	// the person having written.
	AddAgentConversationBackgroundWake(conversationId string) error
	ResetAgentConversationBackgroundWakes(conversationId string) error
	ListAgentConversations(agentId string, kinds []models.AgentConversationKind, options *Options) ([]*models.AgentConversation, error)

	// ListAgentRuns is the runs, newest first, narrowed by the filter and
	// paged by the options; CountAgentRuns is how many the filter leaves.
	// An empty agent is every agent's, for an operator.
	ListAgentRuns(agentId string, filter *AgentRunFilter, options *Options) ([]*models.AgentConversation, error)
	CountAgentRuns(agentId string, filter *AgentRunFilter) (int64, error)

	// SumAgentRunUsage is what each of these conversations cost: every
	// message's usage added up, keyed by conversation.
	SumAgentRunUsage(conversationIds []string) (map[string]models.AgentUsageNote, error)

	// SumAgentMessageCost is what every run of an agent has cost, from
	// the usage on its messages: what a scenario run has spent so far.
	SumAgentMessageCost(agentId string) (float64, error)

	// SumAgentDreamCost is what each of these dreams cost, keyed by
	// dream: its job's model calls made while it ran. By its own hours
	// rather than its whole job, because a dream a restart cut short and
	// the dream that took the job up again share one job.
	SumAgentDreamCost(dreams []*models.AgentDream) (map[string]float64, error)
	DeleteAgentConversation(conversationId string) error

	// SearchAgentConversations finds a person's conversations by words in
	// the title or in what was said, newest first, archived ones included.
	SearchAgentConversations(agentId, query string, limit int) ([]*models.AgentConversation, error)

	// ListAgentConversationsToRemember is every conversation with
	// something said in it that no remember run has read yet, quiet since
	// the moment given so that one still being typed into is left alone.
	ListAgentConversationsToRemember(quietSince time.Time, limit int) ([]*models.AgentConversation, error)

	// MarkAgentConversationRemembered records how far a remember run got.
	// Called in the same transaction as the facts it wrote.
	MarkAgentConversationRemembered(conversationId, messageId string, at time.Time) error

	// ListAgentConversationsToDescribe is every conversation quiet since
	// the given time with something said since it was last described.
	ListAgentConversationsToDescribe(quietSince time.Time, limit int) ([]*models.AgentConversation, error)

	// ListDueAgentGoals is every conversation whose goal is working and
	// whose next turn is due.
	ListDueAgentGoals(now time.Time, limit int) ([]*models.AgentConversation, error)

	// ScavengeAgentConversations removes run transcripts older than the
	// given time.
	ScavengeAgentConversations(kind models.AgentConversationKind, before time.Time) (int64, error)

	AppendAgentMessage(message *models.AgentMessage) (*models.AgentMessage, error)
	// RedactAgentConversationMessages rewrites the text of a conversation's
	// messages through redact, answering how many changed: a run that read
	// a person's taxpayer number off a picture keeps no more of it than its
	// last four digits.
	RedactAgentConversationMessages(conversationId string, redact func(string) string) (int, error)
	// ListAgentMessages is a conversation's messages, oldest first, each
	// with its reactions.
	ListAgentMessages(conversationId string, options *Options) ([]*models.AgentMessage, error)
	// GetAgentConversationMessage is one message of the conversation
	// given, with its reactions, or nil when the conversation has no
	// message by that id.
	GetAgentConversationMessage(conversationId, messageId string) (*models.AgentMessage, error)
	// ListAgentOwnTurnAnswers is what the agent answered in a conversation
	// in turns of its own -- its last word of each round, never a round
	// that went on to call a tool -- after the message given and before
	// the moment given, oldest first. A turn of its own is one whose
	// opening message carries one of models.OwnTurnMarkers: nobody wrote
	// to it, so nobody's chat followed it.
	ListAgentOwnTurnAnswers(conversationId, afterMessageId string, before time.Time, limit int) ([]*models.AgentMessage, error)
	// LastAgentMessageID is the newest message of a conversation written
	// before the moment given, or empty.
	LastAgentMessageID(conversationId string, before time.Time) (string, error)
	// HasAgentToolAnswerContaining says whether a tool's answer in the
	// conversation holds any of the texts: what a page, a search or a
	// message showed the agent, as opposed to what the agent wrote.
	HasAgentToolAnswerContaining(conversationId string, texts ...string) (bool, error)
	// LastAgentPersonMessageAt is when the person last wrote in the
	// conversation: their own words, not a goal check-in the agent was
	// handed as a user turn. Nil when they never have.
	LastAgentPersonMessageAt(conversationId string) (*time.Time, error)
	// LastAgentPersonWordAt is when the person last wrote to this agent in
	// any of their own conversations: their words, not a goal check-in.
	// Nil when they never have.
	LastAgentPersonWordAt(agentId string) (*time.Time, error)
}

InsightOperation is what the agent worked out about messages, and the transcripts of it working.

type InteractionOperation added in v0.61.4

type InteractionOperation interface {
	// CreateAgentInteraction records a card as it is raised.
	CreateAgentInteraction(interaction *models.AgentInteraction) (*models.AgentInteraction, error)

	// GetAgentInteractionByCall is the card a tool call raised in a run,
	// or nil. By the run as well as the call: some providers number calls
	// afresh in every answer, so a call id alone names many cards.
	GetAgentInteractionByCall(agentId, runId, callId string) (*models.AgentInteraction, error)

	// ListOpenAgentInteractions is a conversation's unanswered cards,
	// oldest first.
	ListOpenAgentInteractions(conversationId string) ([]*models.AgentInteraction, error)

	// ListAgentWaitingInteractions is an agent's unanswered cards across
	// all its conversations, newest first, at most limit of them, and how
	// many there are in all.
	ListAgentWaitingInteractions(agentId string, limit int) ([]*models.AgentInteraction, int64, error)

	// ClaimAgentInteraction resolves a card with an answer if it is still
	// open, and says whether it was: of the turn waiting on it and a late
	// answer, exactly one acts on it.
	ClaimAgentInteraction(interactionId, interactionAnswer string) (bool, error)
}

InteractionOperation keeps the questions and approvals the agent put to the person until they are answered.

type ItemOptions

type ItemOptions struct {
	// Unseen, Flagged: only items with the flag in that state, when set.
	Unseen  *bool
	Flagged *bool

	// SinceUID lists items with a UID at or above this, for IMAP ranges.
	SinceUID uint64

	// UIDs lists exactly these, when set: what a FETCH or STORE names.
	UIDs []uint64

	// Deleted, when set, only items with IMAP's \Deleted in that state.
	Deleted *bool

	// SinceModSeq lists items changed since this modseq, for CONDSTORE.
	SinceModSeq uint64

	// Search is a full text query over the messages' search document.
	Search string

	// MailboxID searches every folder of a mailbox rather than one folder,
	// when the folder id given is empty.
	MailboxID string

	// ExcludeKinds leaves out the folders of these kinds. Mail in Trash or
	// Junk is not part of a subscription — what you threw away is not a
	// subscription you have, and what a filter caught is not one you agreed
	// to — so the listing of subscriptions leaves both out, and reading one
	// has to leave out the same mail or the two disagree about what a list
	// has sent.
	ExcludeKinds []models.MailboxFolderKind

	// ExcludeMailKinds leaves out messages of these kinds: a search over a
	// whole mailbox is a search of its mail, and a phone's notes are kept
	// in the mailbox without being any.
	ExcludeMailKinds []models.MailKind

	// ListKey lists the mail of one mailing list, the way ThreadID lists the
	// mail of one conversation.
	ListKey string

	// From, To and Subject match a part of the header, case-insensitively.
	From    string
	To      string
	Subject string

	// Category, Priority and NeedsReply narrow to what the owner's agent
	// worked out about a message, when set.
	Category   string
	Priority   string
	NeedsReply *bool

	// MailIDs keeps only items of these messages: what a search by meaning
	// ranked, read back as rows.
	MailIDs []string

	// Since and Before bound when the message was received.
	Since  time.Time
	Before time.Time
	// BeforeItemID breaks received-time ties when ByReceived is set.
	BeforeItemID string

	// HasAttachment, when set, only messages with or without one.
	HasAttachment *bool

	// ThreadID lists items whose message is in this conversation.
	ThreadID string

	Limit  int
	Offset int

	// Cursor lists items added before the item with this id, for a page
	// that follows another.
	Cursor string

	// Ascending lists oldest first, which is UID order; the default is
	// newest first, which is what a list shows.
	Ascending bool

	// ByReceived orders by when the message was written rather than by when
	// the item was added to its folder. A conversation is read in the order
	// it was said, and moving a message to another folder makes a new item
	// with a new added_at — so without this, archiving the first message of
	// a conversation moves it to the top of it.
	ByReceived bool
}

ItemOptions narrows a listing of items.

type KnowledgeOperation

type KnowledgeOperation interface {
	// Sources.
	// PutAgentSource advances the generation. Existing rows must be read under
	// LockAgentSource so concurrent ingestion progress is preserved.
	PutAgentSource(source *models.AgentKnowledgeSource) (*models.AgentKnowledgeSource, error)
	SetAgentSourceUnknownAuthors(sourceId string, addresses []string) error
	GetAgentSource(agentId, sourceId string) (*models.AgentKnowledgeSource, error)
	LockAgentSource(agentId, sourceId string) (*models.AgentKnowledgeSource, error)
	GetAgentSourceByName(agentId, name string) (*models.AgentKnowledgeSource, error)

	// ListAgentSourceCheckouts is the checkouts a source's commits were
	// read from, as directories relative to the source: where each of its
	// files belongs, since a file does not say.
	ListAgentSourceCheckouts(sourceId string) ([]string, error)

	// ListAgentCodingDocuments is the newest chat units a coding tool's
	// session in a directory was filed as, newest first: the documents
	// whose metadata names that working directory and an assistant.
	// Where sourceIds is not empty, only theirs.
	ListAgentCodingDocuments(agentId, directory string, sourceIds []string, limit int) ([]*models.AgentDocument, error)

	// RequestAgentSourceRun makes an enabled source due at a moment and
	// records the request, touching nothing else: unlike PutAgentSource it
	// leaves the generation alone, so a pass already running is not
	// abandoned as if the source had been edited under it, and the request
	// outlives that pass writing its next time (see run_requested_at).
	RequestAgentSourceRun(sourceId string, at time.Time) error

	// ClearAgentSourceRunRequest forgets a request made at or before the
	// moment a pass started, which that pass answers.
	ClearAgentSourceRunRequest(sourceId string, passStarted time.Time) error
	ListAgentSources(agentId string) ([]*models.AgentKnowledgeSource, error)
	DeleteAgentSource(agentId, sourceId string) error

	// ListDueAgentSources is every enabled source whose time has come, or
	// which said last time that it had more to do.
	ListDueAgentSources(now time.Time, limit int) ([]*models.AgentKnowledgeSource, error)

	// ListDueAgentSourcesOfKinds is ListDueAgentSources narrowed to some
	// kinds: finance sources are queued whether or not the knowledge
	// feature is on, and are not crowded out by document sources with a
	// backlog.
	ListDueAgentSourcesOfKinds(now time.Time, kinds []models.AgentKnowledgeKind, limit int) ([]*models.AgentKnowledgeSource, error)

	// MarkAgentSourceRun records what a pass did and when the next is due.
	MarkAgentSourceRun(sourceId string, cursor map[string]any, counts SourceCounts, more bool, lastError string, nextRun *time.Time) error

	// Documents.
	PutAgentDocument(document *models.AgentDocument) (*models.AgentDocument, error)
	GetAgentDocument(agentId, documentId string) (*models.AgentDocument, error)
	GetAgentDocuments(agentId string, documentIds []string) ([]*models.AgentDocument, error)
	GetAgentDocumentByExternal(sourceId, externalId string) (*models.AgentDocument, error)
	DeleteAgentDocument(agentId, documentId string) error

	// CountAgentProjectPosts is the issues and merge requests an agent's
	// sources read about projects on code hosts, counted per project, in
	// one statement over every post: a pass counts them once for all its
	// checkouts, and reads no post's text to do it. A post's project is
	// what its metadata says, or what its identifier names, which is how
	// a source type that carries no metadata about it names a post:
	// "core/example-lib#12" for an issue and "core/example-lib!7" for a
	// merge request, after the name of the file of records it came in.
	// What a post is comes from its metadata's kind, or else from that
	// mark. since is where "lately" begins.
	CountAgentProjectPosts(agentId string, since time.Time) ([]*AgentProjectPostCount, error)

	// ListAgentDocumentHashes is what a source already holds, so a pass
	// can tell an unchanged file from one to read again without reading
	// either.
	ListAgentDocumentHashes(sourceId string) (map[string]string, error)

	// AgentDocumentStorageKey is the key some document of this agent
	// keeps the bytes of this hash under, and "" where none does.
	//
	// An attachment is identified by the hash of its bytes, so the same
	// picture pasted into four threads -- or found again by another
	// source -- is bytes this server already holds. Asked before the
	// computer is asked for them, it is what keeps a second pass from
	// carrying twenty-four gigabytes across the socket again.
	AgentDocumentStorageKey(agentId, hash string) (string, error)

	// MarkAgentDocumentsSeen says the source still has these, named the
	// way the source names them. One statement for a whole page of a
	// scan, because a page of an archive is two thousand names.
	MarkAgentDocumentsSeen(sourceId string, externalIds []string, at time.Time) error

	// RetitleAgentDocuments writes the title and metadata a source now
	// gives documents whose text it still has unchanged, where the title
	// is not the one stored, and says how many it changed.
	RetitleAgentDocuments(sourceId string, documents []*models.AgentDocument) (int64, error)

	// CountAgentSourceDocuments is how many documents and passages a
	// source holds, counted rather than kept: a pass adds what it files,
	// and a document filed again under the same name was added twice.
	CountAgentSourceDocuments(sourceId string) (documents, chunks int, err error)

	// DeleteAgentDocumentsUnseen removes what a source no longer has:
	// the documents it did not name in a pass that began at the given
	// time and reached the end of the tree, with their passages and
	// their symbols. It answers how many went.
	DeleteAgentDocumentsUnseen(sourceId string, before time.Time) (int, error)

	// ListAgentDocumentsBetween is what happened in a stretch of time:
	// what a period page is written from.
	ListAgentDocumentsBetween(agentId string, kinds []models.AgentDocumentKind, from, until time.Time, limit int) ([]*models.AgentDocument, error)

	// ListAgentChunkTexts is the words of every passage an agent's sources
	// hold, keyed by document, for a scenario run to say whether a thing
	// was ever said at all.
	ListAgentChunkTexts(agentId string, limit int) (map[string][]string, error)

	// Chunks.
	ReplaceAgentChunks(document *models.AgentDocument, chunks []*models.AgentChunk) error
	GetAgentChunks(agentId string, chunkIds []string) ([]*models.AgentChunk, error)
	ListAgentChunks(agentId, documentId string) ([]*models.AgentChunk, error)

	// HasAgentChunks says whether a document has any passages: whether
	// anything was read out of it.
	HasAgentChunks(agentId, documentId string) (bool, error)
	SearchAgentChunks(agentId string, sourceIds []string, documentPrefix string, query string, limit int) ([]*models.AgentChunk, error)
	SearchAgentChunksEveryWord(agentId string, query string, limit int) ([]*models.AgentChunk, error)

	// ListAgentChunksWithoutVector is what is still waiting to be
	// embedded, oldest first so a backlog drains in the order it arrived.
	ListAgentChunksWithoutVector(agentId, model string, limit int) ([]*models.AgentChunk, error)
	PutAgentChunkVector(agentId, sourceId, chunkId, model string, vector []float32) error

	// PutAgentChunkVectors writes a batch in a fixed order, so that two
	// runs writing overlapping batches wait for each other rather than
	// deadlocking.
	PutAgentChunkVectors(agentId string, vectors []AgentChunkVector) error

	// CountAgentChunksWithoutVector is how much is left, for the page
	// that says how far along the first pass is.
	CountAgentChunksWithoutVector(agentId, model string) (int64, error)

	// Symbols.
	ReplaceAgentSymbols(agentId, documentId string, symbols []*models.AgentSymbol) error
	LookupAgentSymbols(agentId string, names []string, limit int) ([]*models.AgentSymbol, error)

	// CountAgentKnowledge is how much there is, per source.
	CountAgentKnowledge(agentId, sourceId string) (documents, chunks int64, err error)

	// CountAgentAttachmentsBySource is what became of the pictures and
	// files each source carried, keyed by the source's identifier: how
	// many wait for the night to decide about them, how many it decided
	// against opening, and how many it opened and read.
	//
	// The same three numbers reading.Progress reports for the whole
	// agent, cut by source, because a person looking at a card wants to
	// know which of their sources the fifty thousand screenshots are in.
	CountAgentAttachmentsBySource(agentId string) (map[string]AgentAttachmentCounts, error)

	// ListAgentAttachmentsDeclined is the files the night decided against
	// opening, newest first, for one source or for every source when no
	// source is named. Each carries the reason on its metadata, which is
	// the whole point of keeping the row rather than deleting the file.
	ListAgentAttachmentsDeclined(agentId, sourceId string, limit int) ([]*models.AgentDocument, error)
}

KnowledgeOperation is knowledge as the rest of the server reaches it.

type LayoutOperation

type LayoutOperation interface {
	// list layouts by domain id
	ListLayouts(domainId string, options *Options) ([]*models.Layout, error)

	// get layout by id
	GetLayout(layoutId string, options *Options) (*models.Layout, error)

	// get multiple layouts
	GetLayouts(layoutIds []string, options *Options) ([]*models.Layout, error)

	// create layout
	CreateLayout(layout *models.Layout, options *Options) (*models.Layout, error)

	// create multiple layouts
	CreateLayouts(layouts []*models.Layout, options *Options) ([]*models.Layout, error)

	// save layout
	ModifyLayout(layoutId string, modifier func(*models.Layout) error, options *Options) (*models.Layout, error)

	// save multiple layouts
	ModifyLayouts(layoutIds []string, modifier func([]*models.Layout) error, options *Options) ([]*models.Layout, error)

	// delete layout
	DeleteLayout(layoutId string, options *Options) error
}

type MailEmbedding

type MailEmbedding struct {
	MailID    string
	MailboxID string
	Model     string
	Vector    []float32
	CreatedAt time.Time
}

MailEmbedding is one message's vector.

type MailOperation

type MailOperation interface {
	// list mails by domain id
	ListMails(domainId string, options *Options) ([]*models.Mail, error)

	// CountMailsBy groups mail by a column and counts each group, for a
	// filter menu that says how many rows each option would leave.
	CountMailsBy(domainIds []string, field string, options *Options) ([]*Facet, error)

	// get mail by id
	GetMail(mailId string, options *Options) (*models.Mail, error)

	// GetMails answers positionally: one entry per identifier given, in the
	// same order, and nil in the place of any identifier that names no mail.
	// A caller has to check for that — the identifiers usually come from a
	// page somebody is looking at, and retention deletes messages underneath
	// it.
	GetMails(mailIds []string, options *Options) ([]*models.Mail, error)

	// create mail
	CreateMail(mail *models.Mail, options *Options) (*models.Mail, error)

	// create multiple mails
	CreateMails(mails []*models.Mail, options *Options) ([]*models.Mail, error)

	// save mail
	ModifyMail(mailId string, modifier func(*models.Mail) error, options *Options) (*models.Mail, error)

	// save multiple mails
	ModifyMails(mailIds []string, modifier func([]*models.Mail) error, options *Options) ([]*models.Mail, error)

	// delete mail
	DeleteMail(mailId string, options *Options) error

	// ScavengeMails removes messages that have been unreferenced for longer
	// than the retention, up to a limit, and returns their identifiers so
	// the caller can remove what is stored for them.
	ScavengeMails(before time.Time, limit int) ([]string, error)

	// FindThreadID is the conversation any of these message identifiers is
	// part of, or empty when none of them is known: how a reply joins the
	// thread of what it answers.
	FindThreadID(messageIds []string) (string, error)

	// SetMailSearch writes the search document: subject, sender, recipients
	// and the message's text, bounded by the caller.
	SetMailSearch(mailId string, text string, attachments int) error

	// ListMailNeedingList is mail a mailbox holds whose list headers have not
	// been read yet, newest first. Mail stored before this server knew what a
	// subscription was: the headers are in object storage, so the caller
	// fetches them and hands back what they said.
	ListMailNeedingList(limit int) ([]string, error)

	// SetMailList records what a message said about its list, and that it was
	// asked. An empty key is an answer: most mail belongs to no list.
	SetMailList(mailId string, info mailparse.ListInfo) error

	// ListMailNeedingNote is mail stored before this server looked for notes
	// that could be one: a copy of something written by the account's owner,
	// in a folder the owner made. The caller reads its headers and hands back
	// what they said. In order of id, after afterMailId, so a caller walking
	// through them passes the last id of one page to get the next.
	ListMailNeedingNote(afterMailId string, limit int) ([]string, error)

	// SetMailNote records a message's note identifier, and that it was
	// looked for. A non-empty identifier makes the message a note; an empty
	// one is an answer too, since most such messages are not notes.
	SetMailNote(mailId, noteIdentifier string) error
}

type MailboxOperation

type MailboxOperation interface {
	ListMailboxes(userId string) ([]*models.Mailbox, error)
	GetMailbox(mailboxId string) (*models.Mailbox, error)
	CreateMailbox(mailbox *models.Mailbox) (*models.Mailbox, error)
	UpdateMailbox(mailboxId string, modify func(*models.Mailbox) error) (*models.Mailbox, error)
	DeleteMailbox(mailboxId string) error

	// ListFolders is the folder tree of a mailbox, with its counts. Options
	// may be nil, which counts every item.
	ListFolders(mailboxId string, options *FolderOptions) ([]*models.MailboxFolder, error)
	GetFolder(folderId string) (*models.MailboxFolder, error)
	GetFolderByKind(mailboxId string, kind models.MailboxFolderKind) (*models.MailboxFolder, error)
	CreateFolder(folder *models.MailboxFolder) (*models.MailboxFolder, error)
	UpdateFolder(folderId string, modify func(*models.MailboxFolder) error) (*models.MailboxFolder, error)

	// DeleteFolder removes a folder and everything under it; its items are
	// expunged and the messages they held may become unreferenced.
	DeleteFolder(folderId string) error

	// AddItem places a message in a folder, with the folder's next UID.
	// AddItem puts a message in a folder. subscriptionId names the list it
	// arrived from, for the delivery that knows; "" everywhere else.
	AddItem(folderId, mailId, subscriptionId string, flags models.MailboxItemFlags) (*models.MailboxItem, error)
	GetItem(itemId string) (*models.MailboxItem, error)
	// LockItem reads current flags while excluding concurrent changes through transaction end.
	LockItem(itemId string) (*models.MailboxItem, error)
	ListItems(folderId string, options *ItemOptions) ([]*models.MailboxItem, error)
	CountItems(folderId string, options *ItemOptions) (int64, error)

	// ListThreads is ListItems grouped into conversations: one row per
	// conversation, holding the newest of its messages in this folder.
	ListThreads(folderId string, options *ItemOptions) ([]*models.MailboxThread, error)
	CountThreads(folderId string, options *ItemOptions) (int64, error)
	SetItemFlags(itemIds []string, flags models.MailboxItemFlags) (int64, error)

	// SetItemImages remembers that the reader loaded a message's remote
	// pictures, so that opening it again does not ask a question they have
	// already answered.
	SetItemImages(itemIds []string, show bool) error

	// ImagesAllowedFor says whether this message's pictures may be shown
	// without asking: allowed for the message, or for the list it came from.
	ImagesAllowedFor(mailboxIds []string, mailId, listKey string) (bool, error)

	// MoveItems puts items in another folder: new items with that folder's
	// next UIDs, the old ones expunged, both folders' modseq bumped. Returns
	// the new items.
	MoveItems(itemIds []string, folderId string) ([]*models.MailboxItem, error)

	// DeleteItems expunges items; the messages they held may become
	// unreferenced.
	DeleteItems(itemIds []string) (int64, error)

	// ListItemsByMail is every item, in any mailbox, holding a message: what
	// says who may read it.
	ListItemsByMail(mailId string) ([]*models.MailboxItem, error)

	// FirstOwnedItemIDsByMail is, for each of these stored messages, the
	// first item holding it in a mailbox the user owns, by mail id: where
	// each is now for that user, in one statement. A message the user
	// holds nowhere is left out.
	FirstOwnedItemIDsByMail(userId string, mailIds []string) (map[string]string, error)

	// MailIsInMailbox says whether a message is already filed in a mailbox,
	// anywhere but its Sent and Drafts folders. Asked on every delivery, so
	// it is one existence query rather than a list of everything.
	MailIsInMailbox(mailId, mailboxId string) (bool, error)

	// FindItemByMessageID is the earliest item in a folder whose message
	// carries this Message-ID, or nil. What tells a copy of a sent message
	// from the message itself.
	FindItemByMessageID(folderId, messageId string) (*models.MailboxItem, error)

	// ListNoteItems is every item of a mailbox holding a note, or holding
	// the note with this identifier when one is given, flagged deleted or
	// not, newest item first, each with its message. Items in the trash
	// and junk are left out.
	ListNoteItems(mailboxId, noteIdentifier string) ([]*models.MailboxItem, error)

	// ListExpunged is what vanished from a folder since a modseq.
	ListExpunged(folderId string, sinceModSeq uint64) ([]*models.MailboxFolderExpunge, error)

	// ScavengeExpunged drops expunge rows older than the retention.
	ScavengeExpunged(before time.Time) (int64, error)

	// Addresses learned from traffic: everyone this mailbox has written to
	// or heard from, which is what the compose page completes from and what
	// the "sender is known" rule asks about. They are not the address book,
	// which is the person's own and lives in database_contact.go; an address
	// learned here becomes a contact there only when somebody saves it.
	// ClaimAutoReply counts one automatic reply from a mailbox in the hour it
	// falls in, and says whether it was under the limit: one statement, so two
	// instances deciding at the same moment cannot both send past it.
	//
	// A count per hour and no addresses. What stood here kept a row for every
	// address that had ever written, so that a sender could be left alone for
	// a week after one reply -- a ledger of everybody who has written, built to
	// avoid writing back twice.
	ClaimAutoReply(mailboxId string, at time.Time, limit int) (bool, error)

	// App passwords, one per device.
	ListAppPasswords(mailboxId string) ([]*models.MailboxAppPassword, error)

	// GetAppPasswordBySelector is the one password a sign-in offers, named
	// by the tag the password carries.
	GetAppPasswordBySelector(mailboxId, selector string) (*models.MailboxAppPassword, error)
	GetAppPassword(appPasswordId string) (*models.MailboxAppPassword, error)
	CreateAppPassword(appPassword *models.MailboxAppPassword) (*models.MailboxAppPassword, error)
	TouchAppPassword(appPasswordId string, at time.Time) error
	DeleteAppPassword(appPasswordId string) error
}

MailboxOperation is the mailbox, its folders and its items.

Everything here is shared state, and every counter — a folder's next UID, its modseq — is allocated in the transaction that needs it, with the row locked, so that two instances adding to one folder at once get two different UIDs and IMAP's promise that they only ever grow holds.

type MediaCompositionOperation added in v0.48.0

type MediaCompositionOperation interface {
	GetMedia(mediaId string) (*models.Media, error)
	CreateMediaLink(link *models.MediaLink) (*models.MediaLink, error)
}

MediaCompositionOperation resolves images and records their message-specific links on the same connection as message composition.

type MediaLinkOperation

type MediaLinkOperation interface {
	// CreateMediaLink records one address, made while a message is being
	// sent.
	CreateMediaLink(link *models.MediaLink) (*models.MediaLink, error)

	// GetMediaLink resolves an address, or nil when there is no such token.
	GetMediaLink(token string) (*models.MediaLink, error)

	// RecordMediaLinkOpen notes that an address was fetched: the first time
	// if it is the first, the last time always, and one more on the count.
	RecordMediaLinkOpen(token string, at time.Time, ip, userAgent string) error

	// ListMediaLinksForEnvelope returns the addresses put in one message,
	// which is how the dashboard answers whether it was opened.
	ListMediaLinksForEnvelope(envelopeId string) ([]*models.MediaLink, error)

	// ListMediaLinksForEnvelopes is the same question about a page of
	// messages, in one query. The mail list asks it about every row it is
	// showing, and one query per row would be five hundred.
	ListMediaLinksForEnvelopes(envelopeIds []string) ([]*models.MediaLink, error)
}

MediaLinkOperation is what the send path and the picture endpoint need of the per-message addresses.

The write on a fetch is deliberately not an update of arbitrary columns: this is reached by anybody on the internet, and the only thing such a request may change is that it happened.

type MediaOperation

type MediaOperation interface {
	// CreateMedia stores the metadata of an uploaded file. The bytes are
	// written to storage separately, under the same identifier.
	CreateMedia(media *models.Media) (*models.Media, error)

	// GetMedia returns one by identifier, or nil when there is none. Nil
	// rather than an error because the caller is usually answering a request
	// for a name that may simply not exist, and a 404 is not a failure.
	GetMedia(mediaId string) (*models.Media, error)

	// ListMediaForDomain returns a domain's files, newest first.
	ListMediaForDomain(domainId string) ([]*models.Media, error)

	// DeleteMedia removes the metadata. The bytes are removed separately, and
	// in that order: a row with no bytes answers 404, while bytes with no row
	// are unreachable and swept later.
	DeleteMedia(mediaId string) error
}

MediaOperation is what the dashboard and the send path need of the media table.

Narrow, like the passkey and token operations: a row here decides what is served from the operator's own domain over HTTPS, so there is no general update that would let a caller point an existing picture at other bytes. Replacing a picture means uploading another and changing the template, which is a change somebody can see.

type MemoryOperation

type MemoryOperation interface {
	CreateAgentMemory(memory *models.AgentMemory) (*models.AgentMemory, error)
	GetAgentMemory(memoryId string) (*models.AgentMemory, error)
	UpdateAgentMemory(memoryId string, modify func(*models.AgentMemory) error) (*models.AgentMemory, error)
	DeleteAgentMemory(memoryId string) error

	// ListAgentMemories is an agent's memories, pinned first, then by last
	// use; for an audience when one is given.
	ListAgentMemories(agentId string, audience models.AgentAudience, limit int) ([]*models.AgentMemory, error)

	// SearchAgentMemories is the memories whose title, content or tags
	// contain the words.
	SearchAgentMemories(agentId, query string, limit int) ([]*models.AgentMemory, error)

	// RecallAgentMemories is the memories any one of the words touches,
	// for putting what is already known in front of a turn. Where the
	// search above narrows with every word, this widens: a sentence is a
	// handful of chances to remember, not a filter.
	RecallAgentMemories(agentId string, words []string, limit int) ([]*models.AgentMemory, error)

	// ListAgentMemoriesWithVector is every memory this model has given a
	// vector to, for ranking a turn against; ListAgentMemoriesWithoutVector
	// is the ones still waiting for one. PutAgentMemoryVector writes it.
	ListAgentMemoriesWithVector(agentId, model string, limit int) ([]*models.AgentMemory, error)
	ListAgentMemoriesWithoutVector(agentId, model string, limit int) ([]*models.AgentMemory, error)
	PutAgentMemoryVector(agentId, memoryId, model string, vector []float32) error

	// TouchAgentMemories marks memories used now.
	TouchAgentMemories(memoryIds []string, at time.Time) error

	// DeleteAgentMemories forgets everything an agent remembers.
	DeleteAgentMemories(agentId string) (int64, error)

	CreateAgentFeedback(feedback *models.AgentFeedback) (*models.AgentFeedback, error)
	ListAgentFeedback(agentId string, kinds []models.AgentFeedbackKind, limit int) ([]*models.AgentFeedback, error)
	ScavengeAgentFeedback(before time.Time) (int64, error)

	CreateAgentSchedule(schedule *models.AgentSchedule) (*models.AgentSchedule, error)
	GetAgentSchedule(scheduleId string) (*models.AgentSchedule, error)
	UpdateAgentSchedule(scheduleId string, modify func(*models.AgentSchedule) error) (*models.AgentSchedule, error)
	DeleteAgentSchedule(scheduleId string) error
	ListAgentSchedules(agentId string) ([]*models.AgentSchedule, error)

	// ListDueAgentSchedules is every enabled schedule whose next run is at
	// or before the moment, locked for the caller.
	ListDueAgentSchedules(now time.Time, limit int) ([]*models.AgentSchedule, error)

	// The skills the operator installed, which belong to the server and
	// whose tools are offered to everybody. PutAgentSkill installs one or
	// replaces the one of that name, which is what updating is.
	// A person's own values for the secrets a skill declared as theirs.
	// The operator's live in the configuration; these are per person and
	// sealed.
	// Where a person's skills and connected servers make their requests
	// from, when that is one of their computers rather than the server.
	ListAgentReaches(agentId string) ([]*models.AgentReach, error)
	PutAgentReach(reach *models.AgentReach) error

	ListAgentSkillSecrets(agentId string) ([]*models.AgentSkillSecret, error)
	PutAgentSkillSecret(secret *models.AgentSkillSecret) error
	DeleteAgentSkillSecret(agentId, skill, key string) error
	SweepAgentSkillSecrets(skill string) error
	SweepAgentSkillSecretsExcept(skill string, keep map[string]bool) error

	// The address book: a person's own contacts, kept as vCards. Distinct
	// from the learned addresses above, which are what a mailbox has seen
	// go past rather than what somebody chose to keep.
	ListAddressBooks(userId string) ([]*models.AddressBook, error)
	GetAddressBook(addressBookId string) (*models.AddressBook, error)
	LockAddressBook(addressBookId string) (*models.AddressBook, error)
	CreateAddressBook(book *models.AddressBook) (*models.AddressBook, error)
	UpdateAddressBook(book *models.AddressBook) (*models.AddressBook, error)
	DeleteAddressBook(addressBookId string) error
	ListContacts(addressBookId, query string, limit int) ([]*models.Contact, error)
	GetContact(addressBookId, contactId string) (*models.Contact, error)
	LockContact(addressBookId, contactId string) (*models.Contact, error)
	GetContactByUID(addressBookId, uid string) (*models.Contact, error)
	PutContact(contact *models.Contact) (*models.Contact, error)
	DeleteContact(addressBookId, contactId string) error
	CountContacts(addressBookId string) (int64, error)

	// FindContactByAddress is the person's own contact carrying an address,
	// across their address books, or nil. What "the sender is known" means:
	// somebody they keep, rather than anybody who has ever written.
	FindContactByAddress(userId, address string) (*models.Contact, error)

	// The calendar: a person's own events, kept as iCalendar text. The
	// occurrences beside them are derived from that text and rewritten
	// whenever it is, so that "what is on this week" and "when is this
	// person busy" are answered by reading a window rather than by
	// expanding every recurrence rule in the calendar.
	ListCalendars(userId string) ([]*models.Calendar, error)
	GetCalendar(calendarId string) (*models.Calendar, error)
	LockCalendar(calendarId string) (*models.Calendar, error)
	CreateCalendar(calendar *models.Calendar) (*models.Calendar, error)

	// EnsureCalendar is the person's calendar of a kind, made from the
	// template when they have none: one calendar and one reminders list each.
	EnsureCalendar(userId string, kind models.CalendarKind, template *models.Calendar) (*models.Calendar, error)
	UpdateCalendar(calendar *models.Calendar) (*models.Calendar, error)
	DeleteCalendar(userId, calendarId string) error
	ListCalendarObjects(calendarId string) ([]*models.CalendarObject, error)

	// ListCalendarObjectsStartingBetween are the objects whose first
	// occurrence starts in the window, earliest first and at most the
	// limit, for a pass that must not read a whole calendar.
	ListCalendarObjectsStartingBetween(calendarId string, from, until time.Time, limit int) ([]*models.CalendarObject, error)
	GetCalendarObject(calendarId, objectId string) (*models.CalendarObject, error)
	LockCalendarObject(calendarId, objectId string) (*models.CalendarObject, error)
	GetCalendarObjectByUID(calendarId, uid string) (*models.CalendarObject, error)
	LockCalendarObjectByUID(calendarId, uid string) (*models.CalendarObject, error)
	PutCalendarObject(object *models.CalendarObject, occurrences []models.Occurrence) (*models.CalendarObject, error)
	DeleteCalendarObject(calendarId, objectId string) error
	CountCalendarObjects(calendarId string) (int64, error)
	ListOccurrences(calendarId string, from, until time.Time) ([]*models.Occurrence, error)
	ListCalendarObjectsRunningOut(before, since time.Time, limit int) ([]*models.CalendarObject, error)
	TouchCalendarObjectHorizon(calendarId, objectId string, until time.Time) (bool, error)

	// Invitations that arrived as mail. Delivery notes one and does no
	// more; a worker claims it and reads the message afterwards, because
	// fetching a message from storage inside the SMTP transaction would
	// mean a slow read bouncing mail this server had already accepted.
	NoteCalendarInvitation(invitation *models.CalendarInvitation) (*models.CalendarInvitation, error)
	ClaimCalendarInvitations(instance string, limit int, now time.Time) ([]*models.CalendarInvitation, error)
	FinishCalendarInvitation(invitation *models.CalendarInvitation) error
	GetCalendarInvitationForItem(mailboxId, itemId string) (*models.CalendarInvitation, error)
	GetCalendarInvitation(invitationId string) (*models.CalendarInvitation, error)
	SweepCalendarInvitations(before time.Time) (int64, error)

	ListAgentSkills() ([]*models.AgentSkill, error)
	GetAgentSkill(name string) (*models.AgentSkill, error)
	PutAgentSkill(skill *models.AgentSkill) (*models.AgentSkill, error)
	DeleteAgentSkill(name string) error

	// The source types installed on this server, offered to everyone.
	ListAgentSourceTypes() ([]*models.AgentSourceType, error)
	GetAgentSourceType(name string) (*models.AgentSourceType, error)
	PutAgentSourceType(sourceType *models.AgentSourceType) (*models.AgentSourceType, error)
	DeleteAgentSourceType(name string) error
	CountAgentSourcesOfType(name string) (int64, error)
	ListAgentSourcesOfType(name string) ([]*models.AgentKnowledgeSource, error)

	// The secrets a source's type declares, filled in for that source.
	ListAgentSourceSecrets(sourceId string) ([]*models.AgentSourceSecret, error)
	PutAgentSourceSecret(agentId string, secret *models.AgentSourceSecret) error
	DeleteAgentSourceSecret(agentId, sourceId, key string) error

	CreateAgentTodo(todo *models.AgentTodo) (*models.AgentTodo, error)
	UpdateAgentTodo(todoId string, modify func(*models.AgentTodo) error) (*models.AgentTodo, error)
	DeleteAgentTodo(conversationId, todoId string) error
	ListAgentTodos(conversationId string) ([]*models.AgentTodo, error)
}

MemoryOperation is what the agent keeps between conversations: memories, corrections, schedules, and a conversation's task list.

type NetWorthOperation added in v0.87.0

type NetWorthOperation interface {
	// CreateAsset adds an asset. Its IsLiability follows its kind; its
	// valuation source is manual unless it says otherwise.
	CreateAsset(asset *models.Asset) (*models.Asset, error)

	// UpdateAsset changes an asset of the agent through a function given
	// a copy. Its id, owner, finance account and creation stay as they
	// were, and IsLiability follows the kind. ErrNotFound when the agent
	// has no such asset.
	UpdateAsset(agentId, assetId string, modify func(*models.Asset) error) (*models.Asset, error)

	// CloseAsset records the day an asset was sold or paid off; it counts
	// until that day and not after. An empty day opens it again.
	CloseAsset(agentId, assetId, closedOn string) (*models.Asset, error)

	// DeleteAsset removes an asset of the agent and its whole history.
	DeleteAsset(agentId, assetId string) error

	// GetAsset is one asset of the agent, or nil.
	GetAsset(agentId, assetId string) (*models.Asset, error)

	// ListAssets is the agent's assets, open ones first, each with the
	// valuation that counts now as its LatestValuation.
	ListAssets(agentId string) ([]*models.Asset, error)

	// RecordValuation keeps one value of an asset of the agent for a day
	// and a valuation source, replacing the one already kept for the same
	// three. Its currency is the asset's unless it says otherwise.
	RecordValuation(valuation *models.AssetValuation) (*models.AssetValuation, error)

	// DeleteValuation removes one valuation of the agent.
	DeleteValuation(agentId, valuationId string) error

	// ListAssetValuations is one asset's history, newest day first, and
	// on one day the winning valuation first.
	ListAssetValuations(agentId, assetId string) ([]*models.AssetValuation, error)

	// NetWorthSeries is, for each day from one to the other, both
	// included, the sum per currency of the winning valuation of every
	// asset open that day, liabilities subtracted. The winning valuation
	// is the latest on or before the day; among one day's, manual wins,
	// then finance_sync and agent_reading, then agent_estimate. A day and
	// currency with nothing to sum has no row. Converting is the caller's.
	NetWorthSeries(agentId, from, to string) ([]*models.NetWorthPoint, error)

	// DetachAssetsOfSource turns the assets valued by one finance source's
	// finance accounts into manual assets closed on closedOn, "2006-01-02",
	// before the source is deleted: their history stays, they stop counting
	// toward net worth after that day, and the finance account link is
	// cleared by the delete. An asset already closed keeps its day. It
	// answers how many it turned.
	DetachAssetsOfSource(agentId, sourceId, closedOn string) (int, error)
}

NetWorthOperation is what a person owns and owes and what each was worth on each day. Every call takes the agent id and filters on it.

type OAuthOperation added in v0.49.0

type OAuthOperation interface {
	CreateOAuthClient(client *models.OAuthClient) (*models.OAuthClient, error)
	GetOAuthClient(clientId string) (*models.OAuthClient, error)
	TouchOAuthClientApproval(clientId string, at time.Time) error

	CreateOAuthAuthorization(authorization *models.OAuthAuthorization, keyHash string) (*models.OAuthAuthorization, error)

	// SpendOAuthAuthorization takes an unexpired approval and deletes it,
	// returning it and the hash of its secret for the caller to check.
	//
	// Taking and deleting are one statement because they have to be one
	// decision: two programs collecting the same approval at once must not
	// both be told yes, and an approval that is read, checked and then
	// deleted has a gap between the reading and the deleting where exactly
	// that happens. The secret is checked by the caller, the way GetToken
	// hands back a hash rather than comparing one here.
	SpendOAuthAuthorization(authorizationId string, now time.Time) (*models.OAuthAuthorization, string, error)

	CreateOAuthConnectCode(code *models.OAuthConnectCode, codeHash string) (*models.OAuthConnectCode, error)

	// SpendOAuthConnectCode takes an unexpired connect code and deletes it, in
	// one statement, so a code signs in one phone however many present it at
	// once. Nil when there was nothing to spend.
	SpendOAuthConnectCode(codeHash string, now time.Time) (*models.OAuthConnectCode, error)

	ScavengeOAuth(now time.Time) (int64, error)
}

OAuthOperation is what authorizing a program needs from the database.

type Options

type Options struct {
	// if supplied, limit the number of rows to return
	Limit uint64

	// if supplied, offset the returned rows
	Offset uint64

	// if supplied, offset the returned rows
	Cursor string

	// Aggregations is the filter, sort and distinct pipeline the caller
	// asked for. Running it here rather than in the browser is the point:
	// the browser only has the rows it fetched, and "which domains have
	// mail" is a question about all of them.
	Aggregations aggregate.Pipeline

	// Columns says which fields the pipeline may name, for the table being
	// queried. A query with a pipeline and no columns refuses everything,
	// which is the safe direction to be wrong in.
	Columns aggregate.Columns
}

type OverviewOperation added in v0.79.0

type OverviewOperation interface {
	// ListAgentNodesForOverview is the pages whose overview is due and
	// ready to be written, most important first. Due: a live page, not a
	// theme, with at least leastFactCount live facts or a live page under
	// it, as important as the median page with that many facts or more,
	// whose inputs have changed since its overview was written. Ready:
	// no page directly under it is due as well, so a page is written
	// after the pages it is written from, a night later, rather than
	// from what they said last week. See ListAgentThemesForOverview for
	// the themes.
	ListAgentNodesForOverview(agentId string, leastFactCount, limit int) ([]*models.AgentNode, error)

	// ListAgentThemesForOverview is the same for the theme pages: a theme
	// with members, or with a theme under it, whose inputs have changed,
	// and with no theme directly under it due. A theme does not wait for
	// its members: they are shown by their overview where they have one
	// and by their opening and facts where not, and a member written
	// later makes the theme due again. Its own listing so that a night
	// can write the themes, the top of the structure, before the pages.
	ListAgentThemesForOverview(agentId string, limit int) ([]*models.AgentNode, error)

	// AgentNodeOverviewInputs is the hash of a page's inputs as they are
	// now, which is what an overview written from them is marked with.
	AgentNodeOverviewInputs(agentId, nodeId string) (string, error)

	// IsAgentNodeOverviewStale says whether a page's inputs have changed
	// since its overview was written, or a rewrite was asked for.
	IsAgentNodeOverviewStale(agentId, nodeId string) (bool, error)

	// SetAgentNodeOverview writes a page's overview, what it cites, and
	// the hash of what it was written from. Nothing else of the page is
	// touched, and it is not a change to the page's words: the opening,
	// the facts and the links are what the history records, and the
	// overview is written from them.
	SetAgentNodeOverview(agentId, nodeId, overview string, evidence []models.Evidence, overviewInputs string, writtenAt time.Time) error

	// ClearAgentNodeOverviewInputs makes a page's overview due at the
	// next night, keeping the one it has until then.
	ClearAgentNodeOverviewInputs(agentId, nodeId string) error
}

OverviewOperation is what the night's overview phase reads and writes.

An overview is written from a page's inputs: its opening, its facts, the overviews of the pages under it and the openings of the pages it is linked to. What it was written from is kept as a hash of those inputs, and a page is due when the hash of its inputs as they are now is different. The hash is worked out here, in one statement, because every part of it is a column: a page nobody touched costs no model call and no read of its facts to find that out.

type OverviewSectionOperation added in v0.89.0

type OverviewSectionOperation interface {
	// ListAgentOverviewSectionVectorPageIds is every section id holding
	// a vector of the model, with the id of the page it is a section of,
	// so the embedding pass can tell what is missing and what is gone.
	ListAgentOverviewSectionVectorPageIds(agentId, model string) (map[string]string, error)

	// PutAgentOverviewSectionVector writes one section's vector.
	PutAgentOverviewSectionVector(agentId, nodeId, sectionId, model string, vector []float32) error

	// DeleteAgentOverviewSectionVectors removes the vectors of sections
	// that are no longer in any overview.
	DeleteAgentOverviewSectionVectors(agentId, model string, sectionIds []string) error
}

OverviewSectionOperation keeps the vectors of the sections of pages' overviews.

type PasskeyOperation

type PasskeyOperation interface {
	// CreatePasskey stores a newly registered credential.
	CreatePasskey(passkey *models.Passkey) (*models.Passkey, error)

	// GetPasskey returns one by identifier, or nil.
	GetPasskey(passkeyId string) (*models.Passkey, error)

	// GetPasskeyByCredentialID returns the credential an authenticator named,
	// or nil. This is the sign-in lookup: a discoverable credential means the
	// server is never told who is signing in, so the credential identifier is
	// all there is to go on.
	GetPasskeyByCredentialID(credentialId []byte) (*models.Passkey, error)

	// ListPasskeysForUser returns an account's credentials, newest first.
	ListPasskeysForUser(userId string) ([]*models.Passkey, error)

	// RenamePasskey changes what somebody calls an authenticator.
	RenamePasskey(passkeyId, name string) error

	// RecordPasskeyUse stores the counter the authenticator reported and when
	// it was used. The counter is how a cloned credential is noticed, so it
	// has to be written on every successful assertion.
	RecordPasskeyUse(passkeyId string, signCount int64, backupState bool, at time.Time, ip, userAgent string) error

	// DeletePasskey removes one credential.
	DeletePasskey(passkeyId string) error
}

PasskeyOperation is what the WebAuthn resolvers need of the passkey table.

Narrow, like the session and token operations, and for the same reason: what is stored here decides who can sign in, so there is no general update that would let a caller move a credential to another account.

type PhoneOperation added in v0.128.0

type PhoneOperation interface {
	// PutAgentPhone writes a phone, keyed on the OAuth client the app
	// registered as: a phone registering again updates its row, whichever
	// of the client's tokens it registers with. A new phone is sent the
	// agent's own turns from the main conversation's newest message on,
	// never what was said before it was connected.
	PutAgentPhone(phone *models.AgentPhone) (*models.AgentPhone, error)
	// GetAgentPhone, ListAgentPhones and ListNotifiableAgentPhones see only
	// phones still signed in: their client holds a token that works or can
	// be renewed. A phone signed out any other way, its token revoked or
	// every session ended, drops out with it.
	GetAgentPhone(agentId, phoneId string) (*models.AgentPhone, error)
	ListAgentPhones(agentId string) ([]*models.AgentPhone, error)
	// ListNotifiableAgentPhones is every such phone with a registration, for
	// the loop that sends the agent's own turns.
	ListNotifiableAgentPhones() ([]*models.AgentPhone, error)
	UpdateAgentPhoneSettings(agentId, phoneId, phoneName string, notificationKinds []string) error
	DeleteAgentPhone(agentId, phoneId string) error

	// NoteAgentPhoneDelivery records how the last notification went; an
	// empty pushRegistration with isGone clears the registration, which is
	// what Apple saying the phone is gone means.
	NoteAgentPhoneDelivery(phoneId string, at time.Time, deliveryError string, isGone bool) error

	// AdvanceAgentPhonePush moves how far the agent's own turns have been
	// sent from one message to another, and says whether it did: only if
	// nobody moved it since it was read, which is what keeps a turn from
	// being sent twice when two instances look at once.
	AdvanceAgentPhonePush(phoneId, fromMessageId, throughMessageId string) (bool, error)

	// MarkAgentPhoneToured says the agent showed the person around the
	// phone, and whether this call was the one that did: of two instances
	// starting the tour at once, one goes on.
	MarkAgentPhoneToured(phoneId string, at time.Time) (bool, error)
}

PhoneOperation is the phones people talk to their agent from.

type PlanUsageOperation added in v0.85.2

type PlanUsageOperation interface {
	// PutAgentPlanUsage writes a provider's reading, unless the one
	// written already is newer: two instances may hear the same plan.
	PutAgentPlanUsage(provider string, observedAt time.Time, planUsage []byte) error

	// ListAgentPlanUsages is every provider's last reading, by provider.
	ListAgentPlanUsages() (map[string][]byte, error)
}

PlanUsageOperation keeps what each subscription plan last said of its allowance, so that a restart does not forget it.

type ProposedSpendingRule added in v0.103.0

type ProposedSpendingRule struct {
	MatchText             string
	SpendingCategoryID    string
	AheadOfSpendingRuleID string
}

ProposedSpendingRule is a spending rule not yet saved, for CountSpendingRuleChanges: what it matches, what it assigns, and the existing rule it would be placed ahead of, empty for after every rule.

type ReactionOperation added in v0.134.0

type ReactionOperation interface {
	// SetAgentMessageReaction puts a reactor's emoji on a message of the
	// conversation given, replacing the one it had; an empty emoji takes it
	// away. It says whether anything changed, and ErrNotFound when the
	// conversation has no such message or is not the agent's. The emoji is
	// the caller's to check (models.ValidateReactionEmoji).
	SetAgentMessageReaction(agentId, conversationId, messageId string, reactorKind models.AgentReactorKind, reactionEmoji string) (bool, error)

	// GetAgentMessage is a message by its id alone, with its reactions, or
	// nil; whose conversation it is in is the caller's to check.
	GetAgentMessage(messageId string) (*models.AgentMessage, error)

	// LastAgentPersonMessageID is the newest message the person wrote in a
	// conversation, leaving out the turns the agent took on its own, or
	// empty when they never wrote there.
	LastAgentPersonMessageID(conversationId string) (string, error)
}

ReactionOperation is the emoji the person and the agent put on the messages of a conversation. The rows go with their message and their conversation, by foreign keys that cascade (migration 0162).

type RecordingGlossaryCorrectionInput added in v0.153.0

type RecordingGlossaryCorrectionInput struct {
	RecordingTranscriptSegmentID string
	OriginalPhrase               string
	CorrectedPhrase              string
	GlossaryTerm                 string
}

RecordingGlossaryCorrectionInput is one fix the term correction pass proposes for a passage: OriginalPhrase, found in the passage's current text, becomes CorrectedPhrase, which spells GlossaryTerm.

type RecordingHandoffPublication added in v0.154.0

type RecordingHandoffPublication struct {
	HandoffStartMS   int64
	HandoffEndMS     int64
	HandoffAttemptID string
}

RecordingHandoffPublication says how a piece was stitched to the piece before it: its audio was sent again from HandoffStartMS, through HandoffEndMS, as the chunk whose attempt is HandoffAttemptID.

type RecordingKnowledgeOperation added in v0.144.0

type RecordingKnowledgeOperation interface {
	ListRecordingsAwaitingKnowledgeInitialization(afterRecordingId string, pageSize int) ([]*models.Recording, error)
	InitializeRecordingKnowledge(userId, recordingId string) (bool, error)
	ReadRecordingLearning(userId, recordingId string) (*models.RecordingLearningView, error)
	SyncRecordingKnowledge(userId, recordingId string) error
	SyncRecordingKnowledgeStep(userId, recordingId string, progress *RecordingKnowledgeSyncProgress) (bool, error)
	QueueRecordingKnowledgeSync(userId, recordingId string) error
	ListRecordingsAwaitingKnowledgeSync(pageSize int) ([]*models.Recording, error)
	ResumeRecordingLearning(userId, recordingId string, expectedSourceGeneration int64) (*models.RecordingLearningView, error)
	CheckRecordingKnowledgeEvidence(userId string, documents []*models.AgentDocument) error
	ReconcileDeletedRecordingKnowledge(recordingId string) error
}

RecordingKnowledgeOperation uses the existing source, document, evidence and revision stores.

type RecordingKnowledgeSyncProgress added in v0.154.0

type RecordingKnowledgeSyncProgress struct {
	// PassStartedAt is when the pass began: a document the pass did not write
	// since then is no longer in the transcript.
	PassStartedAt time.Time
	// RunID is the transcript run being read, and SegmentCursorStartMS and
	// SegmentCursorID the last passage of it that was.
	RunID                string
	IsRunFinished        bool
	SegmentCursorStartMS int64
	SegmentCursorID      string
	// HasStarted is whether the first slice has run, and SourceGeneration the
	// recording's generation then: the one the finished pass is recorded as
	// having synced, so a change made during the pass leaves it behind.
	HasStarted       bool
	SourceGeneration int64
	// HasChangedEvidence is whether any slice of the pass wrote a document
	// that differs from the one before it.
	HasChangedEvidence bool
}

RecordingKnowledgeSyncProgress carries one pass over a recording's passages across the transactions that make it, so that a long recording is read in slices and the recording's row lock is never held for the whole pass. A zero value starts a pass.

type RecordingLiveUtteranceOperation added in v0.154.0

type RecordingLiveUtteranceOperation interface {
	// SaveRecordingLiveUtterance stores one utterance of a capture that is
	// still going; the same provider utterance id again replaces it.
	SaveRecordingLiveUtterance(userId, recordingId string, utterance *models.RecordingLiveUtterance) error

	// ListRecordingLiveUtterances are the utterances no completed run
	// covers, in timeline order.
	ListRecordingLiveUtterances(userId, recordingId string) ([]*models.RecordingLiveUtterance, error)

	// DeleteSettledRecordingLiveUtterances deletes the utterances of up to
	// limit recordings whose words are in the saved transcript now.
	DeleteSettledRecordingLiveUtterances(limit int) (int64, error)
}

RecordingLiveUtteranceOperation keeps the words heard while a recording is being captured until the saved audio has been transcribed.

type RecordingMediaCandidate added in v0.142.0

type RecordingMediaCandidate struct {
	UserID           string
	RecordingMediaID string
}

RecordingMediaCandidate is an owned completed original with no initial version.

type RecordingMetadataOperation added in v0.144.0

type RecordingMetadataOperation interface {
	UpdateRecordingMetadata(userId, recordingId string, expectedSourceGeneration int64, recordingTitle *string, recordedAt *time.Time) (*models.Recording, error)
	ListRecordingsAwaitingSummary(afterRecordingId string, limit int) ([]*models.Recording, error)
	MarkRecordingSummaryQueued(userId, recordingId string) error
	StoreGeneratedRecordingSummary(userId, recordingId, recordingTitle, recordingSummary string) error
	SetRecordingRecordedAtIfUnset(userId, recordingId string, recordedAt time.Time) (bool, error)
	SetRecordingMediaDurationIfUnknown(userId, mediaId string, mediaDurationMS int64) (bool, error)
	ListImportedMediaWithoutDuration(afterMediaId string, limit int) ([]ImportedMediaReference, error)
}

RecordingMetadataOperation edits source metadata without requesting transcription.

type RecordingOperation added in v0.140.0

type RecordingOperation interface {
	CreateRecording(*models.Recording) (*models.Recording, error)
	GetRecording(userId, recordingId string) (*models.Recording, error)
	LockRecording(userId, recordingId string) (*models.Recording, error)
	ListRecordings(userId, beforeId, searchText string, limit int) ([]*models.Recording, error)
	UpdateRecordingCapture(userId, recordingId string, expectedGeneration int64, captureState models.RecordingCaptureState, durationMS int64, gaps []models.RecordingGap) (*models.Recording, error)
	CreateRecordingMedia(userId string, media *models.RecordingMedia, maximumMediaBytes, maximumAccountBytes int64) (*models.RecordingMedia, error)
	GetRecordingMedia(userId, mediaId string) (*models.RecordingMedia, error)
	ListRecordingMedia(userId, recordingId string) ([]*models.RecordingMedia, error)
	ListRecordingMediaParts(userId, mediaId string) ([]*models.RecordingMediaPart, error)
	PutRecordingMediaPart(userId string, part *models.RecordingMediaPart) (*models.RecordingMediaPart, error)
	CompleteRecordingMedia(userId, mediaId, verifiedSha256 string) (*models.RecordingMedia, bool, error)
	DeleteRecording(userId, recordingId string) error
	ListRecordingsForCleanup(limit int) ([]*models.Recording, error)
	ListRecordingMediaForCleanup(recordingId string) ([]*models.RecordingMedia, error)
	AdvanceRecordingMediaCleanup(recordingId, mediaId string, expectedPartIndex int) error
	FinishRecordingCleanup(recordingId string) error
}

RecordingOperation owns recording manifests and durable part receipts.

type RecordingPiece added in v0.154.0

type RecordingPiece struct {
	RecordingMediaID         string
	TimelineStartMS          int64
	IsUploadComplete         bool
	VerifiedAt               *time.Time
	RecordingTranscriptRunID string
	RecordingProcessingState models.RecordingProcessingState
	PublishedAt              *time.Time
	RunUpdatedAt             time.Time
	DerivedDurationMS        int64
	// HasLiveJob says a job for the run is queued or running. A run with none
	// is not going to move by itself, so nothing waits for it.
	HasLiveJob bool
}

RecordingPiece is one original of a capture and the latest version of its transcript, in the order the pieces were recorded.

func (*RecordingPiece) IsPending added in v0.154.0

func (self *RecordingPiece) IsPending() bool

IsPending says the piece is still on its way to being published: its latest version is not finished and a job is going to work on it.

type RecordingPreviewOperation added in v0.147.0

type RecordingPreviewOperation interface {
	ReserveRecordingPreview(userId, mediaId string, blob *models.RecordingBlob, maximumAccountBytes int64) (*models.RecordingBlob, error)
	ReadRecordingPreview(userId, mediaId string) (*models.RecordingBlob, error)
}

RecordingPreviewOperation reserves browser playback derivatives before their bytes are written, using the existing recording quota and cleanup references.

type RecordingReferenceOperation added in v0.144.0

type RecordingReferenceOperation interface {
	ListRecordingReferenceInvalidations(userId, recordingId string) ([]*models.RecordingReferenceInvalidation, error)
	ListRecordingsAwaitingReferenceReconciliation(pageSize int) ([]*models.Recording, error)
	ReconcileRecordingReferenceInvalidations(userId, recordingId string) error
}

RecordingReferenceOperation tracks dependent attribution after a reference changes.

type RecordingRetryOperation added in v0.144.0

type RecordingRetryOperation interface {
	RetryRecordingTranscriptRun(userId, runId, agentId string) (*models.RecordingTranscriptRun, error)
}

RecordingRetryOperation resumes known unfinished processing without replacing generated evidence.

type RecordingSpeakerCorrectionInput added in v0.144.0

type RecordingSpeakerCorrectionInput struct {
	RecordingID                     string
	RecordingTranscriptionAttemptID string
	ClientCorrectionID              string
	LocalSpeakerID                  string
	ConfirmedName                   string
	// IsAccountOwner marks the confirmed speaker as the person; an empty
	// ConfirmedName then defaults to the person's display name.
	IsAccountOwner           bool
	ExpectedSourceGeneration int64
	PassageStartMS           int64
	PassageEndMS             int64
}

RecordingSpeakerCorrectionInput names a request-local group or one selected interval.

type RecordingSpeakerOperation added in v0.144.0

type RecordingSpeakerOperation interface {
	ReadRecordingTranscriptPassageOffset(userId, runId string, passageStartMS, passageEndMS int64) (int, error)
	ProjectRecordingSpeakerCorrections(userId string, segments []*models.RecordingTranscriptSegment) error
	CheckRecordingVoiceReferenceNames(userId string, referenceBlobIds, confirmedNames []string) error
	GetRecordingSpeakerEvidence(userId, recordingId, attemptId string) (*models.RecordingTranscriptRun, *models.RecordingTranscriptionAttempt, error)
	HasRecordingSpeakerOverlap(userId, runId, attemptId, localSpeakerId string, passageStartMS, passageEndMS int64) (bool, error)
	ListRecordingsAwaitingSpeakerCuration(pageSize int) ([]*models.Recording, error)
	MarkRecordingSpeakerCuration(userId, recordingId string, sourceGeneration int64) error
	QueueRecordingSpeakerCuration(userId, recordingId string) error
	CreateRecordingVoiceReference(userId string, reference *models.RecordingVoiceReference, blob *models.RecordingBlob, maximumAccountBytes int64) (*models.RecordingVoiceReference, error)
	ListUsableRecordingVoiceReferences(userId string, referenceLimit int) ([]*models.RecordingVoiceReference, error)
	ListRevokedRecordingVoiceReferencesForCleanup(afterReferenceId string, pageSize int) ([]*RecordingVoiceReferenceCleanupCandidate, error)
	LockRevokedRecordingVoiceReferenceForCleanup(userId, recordingId, referenceId string) (*models.RecordingVoiceReference, error)
	DeleteRevokedRecordingVoiceReference(userId, recordingId, referenceId string) error
	ListRecordingSpeakerIdentities(userId string) ([]*models.RecordingSpeakerIdentity, error)
	ListRecordingSpeakerIdentitiesInUse(userId string) ([]*models.RecordingSpeakerIdentity, error)
	ListRecordingSpeakerCorrections(userId, recordingId string) ([]*models.RecordingSpeakerCorrection, error)
	ListRecordingVoiceReferences(userId, recordingId string) ([]*models.RecordingVoiceReference, error)
	CorrectRecordingSpeaker(userId string, correction RecordingSpeakerCorrectionInput) ([]*models.RecordingSpeakerCorrection, error)
	RenameRecordingSpeaker(userId, recordingId, speakerIdentityId, confirmedName string, expectedSourceGeneration int64) error
	RemoveRecordingSpeakerCorrection(userId, recordingId, correctionId string, expectedSourceGeneration int64) error
	UndoRecordingSpeakerNaming(userId, recordingId, correctionId string, expectedSourceGeneration int64) (int, error)
	RevokeRecordingVoiceReference(userId, recordingId, referenceId string, expectedSourceGeneration int64) error
}

RecordingSpeakerOperation keeps confirmed labels separate from generated evidence.

type RecordingTemporarySpeakerOperation added in v0.154.0

type RecordingTemporarySpeakerOperation interface {
	ListRecordingTemporarySpeakers(userId, recordingId string) ([]*models.RecordingTemporarySpeaker, error)
	CreateRecordingTemporarySpeaker(userId string, speaker *models.RecordingTemporarySpeaker, blob *models.RecordingBlob, maximumAccountBytes int64) (*models.RecordingTemporarySpeaker, error)
	NameRecordingTemporarySpeaker(userId, recordingId, speakerLabel, confirmedName string, isAccountOwner bool) error
	MergeRecordingTemporarySpeaker(userId, recordingId, speakerLabel, intoSpeakerLabel string) error
	SeparateRecordingTemporarySpeaker(userId, recordingId, speakerLabel string) error
	MarkRecordingTemporarySpeakerMergeChecked(userId, speakerId string) error
}

RecordingTemporarySpeakerOperation keeps the speakers of a recording that is still being captured, until the person names them.

type RecordingTextCorrectionOperation added in v0.144.0

type RecordingTextCorrectionOperation interface {
	ListRecordingTranscriptTextCorrections(userId, recordingId string) ([]*models.RecordingTranscriptTextCorrection, error)
	CorrectRecordingTranscriptText(userId string, input RecordingTranscriptTextCorrectionInput) (*models.RecordingTranscriptTextCorrection, error)
	RemoveRecordingTranscriptTextCorrection(userId, recordingId, correctionId string, expectedSourceGeneration int64) error

	// ApplyRecordingGlossaryCorrections makes the fixes the term correction
	// pass proposed that are still allowed, and answers with the ones it made.
	ApplyRecordingGlossaryCorrections(userId, recordingId string, proposals []RecordingGlossaryCorrectionInput) ([]*models.RecordingTranscriptTextCorrection, error)
	ProjectRecordingTranscriptTextCorrections(userId string, segments []*models.RecordingTranscriptSegment) error
}

RecordingTextCorrectionOperation keeps original recognized speech immutable.

type RecordingTranscriptOperation added in v0.141.0

type RecordingTranscriptOperation interface {
	ReadRecordingTranscriptTimelinePage(userId, recordingId string, segmentOffset, pageSize int) ([]*models.RecordingTranscriptSegment, []*models.RecordingTranscriptRun, int64, error)
	ReadUnnamedRecordingTranscriptSegments(userId, recordingId string) ([]*models.RecordingTranscriptSegment, []*models.RecordingTranscriptRun, error)
	GetLatestRecordingChunkAttempt(userId, chunkId string) (*models.RecordingTranscriptionAttempt, error)
	GetRecordingTranscriptionAttemptEvidence(userId, attemptId string) (*models.RecordingTranscriptionAttempt, error)
	CancelRecordingTranscriptRun(userId, runId string) (*models.RecordingTranscriptRun, error)
	ReadRecordingTranscriptPage(userId, runId string, segmentOffset, pageSize int) ([]*models.RecordingTranscriptSegment, int64, error)
	HasUnfinishedRecordingTranscription(userId, recordingId string) (bool, error)
	ListRecordingMediaAwaitingTranscription(afterMediaId string, limit int) ([]*RecordingMediaCandidate, error)
	CreateRecordingTranscriptRun(userId, mediaId, agentId, clientRunId, providerModelName string, isReprocessingRequested bool) (*models.RecordingTranscriptRun, error)
	GetRecordingTranscriptRun(userId, runId string) (*models.RecordingTranscriptRun, error)
	ListRecordingTranscriptRuns(userId, recordingId string) ([]*models.RecordingTranscriptRun, error)
	PublishRecordingTranscriptRun(userId, runId string, claim RecordingWorkerClaim, handoff *RecordingHandoffPublication) error
	ListRecordingPieces(userId, recordingId string) ([]*RecordingPiece, error)
	WakeRecordingTranscriptionJobs(userId, recordingId string, limit int) (int64, error)
	UpdateRecordingTranscriptProgress(userId, runId string, claim RecordingWorkerClaim, processingState models.RecordingProcessingState, errorMessage string, derivedDurationMS int64) error
	CreateRecordingAudioChunk(userId, runId string, claim RecordingWorkerClaim, chunk *models.RecordingAudioChunk, blob *models.RecordingBlob, maximumAccountBytes int64) (*models.RecordingAudioChunk, error)
	ListRecordingAudioChunks(userId, runId string) ([]*models.RecordingAudioChunk, error)
	GetRecordingBlob(userId, blobId string) (*models.RecordingBlob, error)
	VerifyRecordingBlob(userId, blobId, verifiedSha256 string) error
	ListRecordingBlobsForCleanup(recordingId string, limit int) ([]*models.RecordingBlob, error)
	DeleteRecordingBlobReference(recordingId, blobId string) error
	CreateRecordingTranscriptionAttempt(userId, runId, chunkId string, claim RecordingWorkerClaim, currencyCode string, referenceBlobIds []string) (*models.RecordingTranscriptionAttempt, error)
	ListRecordingTranscriptionAttempts(userId, runId string) ([]*models.RecordingTranscriptionAttempt, error)
	GetRecordingTranscriptionAttempt(userId, attemptId string) (*models.RecordingTranscriptionAttempt, error)
	SubmitRecordingTranscriptionAttempt(userId, attemptId string, claim RecordingWorkerClaim) error
	FinishRecordingTranscriptionAttempt(userId, attemptId string, claim RecordingWorkerClaim, finished *models.RecordingTranscriptionAttempt, segments []*models.RecordingTranscriptSegment) (bool, error)
	ListRecordingTranscriptSegments(userId, runId string) ([]*models.RecordingTranscriptSegment, error)
	SetRecordingAccurateWords(userId, runId string, claim RecordingWorkerClaim, accurateTexts map[string]string) error
}

RecordingTranscriptOperation versions generated evidence and tracks derived blobs.

type RecordingTranscriptTextCorrectionInput added in v0.144.0

type RecordingTranscriptTextCorrectionInput struct {
	RecordingID                  string
	RecordingTranscriptSegmentID string
	ClientCorrectionID           string
	CorrectedTranscriptText      string
	ExpectedSourceGeneration     int64
}

type RecordingVoiceReferenceCleanupCandidate added in v0.144.0

type RecordingVoiceReferenceCleanupCandidate struct {
	UserID    string
	Reference *models.RecordingVoiceReference
}

RecordingVoiceReferenceCleanupCandidate carries the current owner for storage maintenance.

type RecordingWorkerClaim added in v0.141.0

type RecordingWorkerClaim struct {
	JobID   string
	ClaimID string
}

RecordingWorkerClaim keeps expired workers from publishing a transcript.

type ReplyOperation

type ReplyOperation interface {
	CreateAgentReply(reply *models.AgentReply) (*models.AgentReply, error)
	GetAgentReply(replyId string) (*models.AgentReply, error)
	UpdateAgentReply(replyId string, modify func(*models.AgentReply) error) (*models.AgentReply, error)
	ListAgentReplies(filter *AgentReplyFilter, options *Options) ([]*models.AgentReply, error)
	CountAgentReplies(filter *AgentReplyFilter) (int64, error)

	// ScavengeAgentReplies removes replies that are over — sent, cancelled,
	// refused or failed — before the given time.
	ScavengeAgentReplies(before time.Time) (int64, error)
}

ReplyOperation is the replies the agent writes on a person's behalf.

type ReportOperation

type ReportOperation interface {
	// list reports by domain id
	ListReports(domainId string, options *Options) ([]*models.Report, error)

	// get report by id
	GetReport(reportId string, options *Options) (*models.Report, error)

	// get multiple reports
	GetReports(reportIds []string, options *Options) ([]*models.Report, error)

	// create report
	CreateReport(report *models.Report, options *Options) (*models.Report, error)

	// create multiple reports
	CreateReports(reports []*models.Report, options *Options) ([]*models.Report, error)

	// save report
	ModifyReport(reportId string, modifier func(*models.Report) error, options *Options) (*models.Report, error)

	// save multiple reports
	ModifyReports(reportIds []string, modifier func([]*models.Report) error, options *Options) ([]*models.Report, error)

	// delete report
	DeleteReport(reportId string, options *Options) error
}

type RevisionOperation

type RevisionOperation interface {
	// RecordAgentRevision files one change against a page.
	RecordAgentRevision(revision *models.AgentRevision) (*models.AgentRevision, error)

	// ListAgentRevisions is a page's history, newest first.
	ListAgentRevisions(agentId, nodeId string, limit int) ([]*models.AgentRevision, error)

	// ListAgentRevisionsSince is everything that changed lately, across
	// the graph: what a person reads to see what their agent has been
	// doing.
	ListAgentRevisionsSince(agentId string, since time.Time, limit int) ([]*models.AgentRevision, error)
}

RevisionOperation is the history as the rest of the server reaches it.

type RoleOperation

type RoleOperation interface {
	ListRoles() ([]*models.Role, error)
	GetRole(roleId string) (*models.Role, error)
	GetRoleByName(name string) (*models.Role, error)
	CreateRole(role *models.Role) (*models.Role, error)
	UpdateRole(roleId string, modify func(*models.Role) error) (*models.Role, error)
	DeleteRole(roleId string) error
}

RoleOperation changes the role table, in a transaction and with an audit row for every change.

type Scored

type Scored struct {
	ID    string
	Score float64
}

Scored is one row and how near it was, best first. The score is cosine similarity: one is the same direction, zero unrelated.

type SessionOperation

type SessionOperation interface {
	// CreateSession stores a new session. The hash of the secret half is
	// passed separately and is never part of the model: the model is what
	// the API returns, and a hash that reaches the dashboard is one somebody
	// can work on offline.
	CreateSession(session *models.Session, keyHash string) (*models.Session, error)

	// GetSession returns one by identifier together with that hash, or nil
	// when there is no such row. Revoked and expired sessions are returned;
	// deciding what to do about them is the caller's.
	GetSession(sessionId string) (*models.Session, string, error)

	// ListSessions returns an account's sessions, newest first.
	ListSessions(userId string, options *SessionOptions) ([]*models.Session, error)

	// TouchSession records that a session was used, from an address and a
	// user agent, unless it was already recorded within TouchInterval.
	TouchSession(sessionId string, at time.Time, ip, userAgent string) error

	// RevokeSession ends one session. Ending one that is already ended is not
	// an error.
	RevokeSession(sessionId string, at time.Time) error

	// RevokeSessionsByUser ends every session an account has, and returns how
	// many it ended. Excluding one, when the caller wants to keep the session
	// they are using.
	RevokeSessionsByUser(userId string, at time.Time, except string) (int64, error)

	// ScavengeSessions removes rows that are no longer worth keeping.
	ScavengeSessions(now time.Time) (int64, error)
}

SessionOperation is what the authenticator needs of the session table.

Deliberately narrow. There is no general Modify here: a session is created, looked at, touched and ended, and offering more would invite a caller to change who a session belongs to.

type SessionOptions

type SessionOptions struct {
	// IncludeRevoked returns ended sessions as well, which is what the list
	// shows so that "revoked an hour ago" is visible rather than the row
	// disappearing.
	IncludeRevoked bool

	// Limit bounds the rows returned. Zero means the default.
	Limit int
}

SessionOptions narrows a listing.

type Settings

type Settings struct {
	Host     string
	Port     uint16
	User     string
	Password string
	DBName   string
	SSLMode  string

	// SSLRootCertificate is the PEM file the server's certificate is verified
	// against. Only meaningful for the verify-ca and verify-full modes.
	SSLRootCertificate string

	// LogQueries echoes every SQL statement to the log. Very noisy; off
	// unless the operator asks for it.
	LogQueries bool

	BackendID string
}

type SourceCounts

type SourceCounts struct {
	Documents int
	Chunks    int
	Refused   int

	// Seen is how many things the source named, changed or not. Unlike
	// the three above it is not kept on the source's row: it is only
	// what tells the end of a pass that it really read the tree, rather
	// than having been handed an empty answer by a folder nothing had
	// mounted.
	Seen int

	// CheckoutsKeptToProfile is how many checkouts the pass kept to what
	// git says about them, their files left unread, and
	// FilesKeptToProfile how many files that was.
	//
	// Both are counted over the whole tree by whoever walked it, so a
	// page carries the same numbers as the page before it: they are
	// written down as they arrive rather than added up.
	CheckoutsKeptToProfile int
	FilesKeptToProfile     int
}

SourceCounts is what one pass of a source did.

type SpamOperation

type SpamOperation interface {
	// LearnSpamTokens applies token deltas.
	//
	// Deltas rather than values, applied by the database rather than read and
	// written back, because two instances may be learning at the same time
	// and a read-modify-write would lose one of them.
	LearnSpamTokens(deltas []models.SpamTokenDelta) error

	// LoadSpamTokens reads the counts for the tokens of one message. Tokens
	// that have never been seen are absent from the result rather than zero,
	// so a caller can tell "never seen" from "seen and neutral".
	LoadSpamTokens(tokens []string) (map[string]models.SpamTokenCount, error)

	// GetSpamTraining returns the label a message was marked with, or nil
	// when it has not been used for training.
	GetSpamTraining(mailId string) (*models.SpamTraining, error)

	// SetSpamTraining records the label a message was marked with.
	SetSpamTraining(training *models.SpamTraining) error

	// DeleteSpamTraining forgets that a message was used.
	DeleteSpamTraining(mailId string) error

	// CountSpamTraining says how many messages carry each label, which is
	// what the classifier's minimum is compared against.
	CountSpamTraining() (spam int64, ham int64, err error)

	// SpamRuleSetVersion is what the stored rule set is at, for an instance
	// checking whether the copy it parsed is stale. Empty when there is
	// none. Cheap enough to ask on a timer, which is the point of it being
	// separate from LoadSpamRuleSet.
	SpamRuleSetVersion(channel string) (string, error)

	// LoadSpamRuleSet reads one channel's stored rules, or nil.
	LoadSpamRuleSet(channel string) (*models.SpamRuleSet, error)

	// SaveSpamRuleSet replaces one channel's stored rules.
	SaveSpamRuleSet(ruleSet *models.SpamRuleSet) error

	// ListSpamRuleSets is what the dashboard shows: every channel, with how
	// much of it this server could use.
	ListSpamRuleSets() ([]*models.SpamRuleSet, error)
}

SpamOperation is what the built-in spam filter needs of the database.

The counts live here rather than on an instance's disk because several instances can run against one database, and a classifier that differed between them would score the same message differently depending on which one received it.

type SubmissionOperation added in v0.48.0

type SubmissionOperation interface {
	// GetDomainSubmission reads acceptance without waiting for an in-flight send.
	GetDomainSubmission(principalId, submissionId string) (*models.DomainSubmission, error)
	// LockDomainSubmission serializes an account or console identity until commit.
	LockDomainSubmission(principalId, submissionId string) (*models.DomainSubmission, error)
	CreateDomainSubmission(submission *models.DomainSubmission) error
	// GetSubmission reads a committed acceptance without claiming or locking it.
	GetSubmission(ownerId, submissionId string) (*models.Submission, error)
	GetDraftSubmission(ownerId, mailboxId, draftItemId string) (*models.Submission, error)
	// LockSubmission serializes this owner's identifier through transaction end,
	// including when no record exists. A nil result allows initial acceptance.
	LockSubmission(ownerId, submissionId string) (*models.Submission, error)
	CreateSubmission(submission *models.Submission) error
	// CancelSubmission locks the identity and either returns its acceptance or
	// permanently prevents it from being accepted. The caller must commit.
	CancelSubmission(ownerId, submissionId string) (*models.Submission, error)
	IsSubmissionCancelled(ownerId, submissionId string) (bool, error)
	// ListSubmissionsToReconcile locks pending records without waiting for other
	// workers. Reconcile and mark them in this same transaction.
	ListSubmissionsToReconcile(limit int) ([]*models.Submission, error)
	MarkSubmissionReconciled(ownerId, submissionId string, reconciledAt time.Time) error
	DeferSubmissionReconciliation(ownerId, submissionId string, retryAt time.Time) error
}

SubmissionOperation keeps local acceptance and later mailbox reconciliation in the same database as mail. Callers must bind a retry to its request digest.

type SubscriptionQuery

type SubscriptionQuery interface {
	// ListSubscriptions is the mailing lists a mailbox receives, newest
	// first, with how much of each it holds and what has been asked of it.
	//
	// side chooses which of them: the ones still subscribed to, the ones
	// left, or either. matching narrows to the lists whose name, sending
	// address or key contains it; empty is all of them.
	ListSubscriptions(mailboxId string, limit, offset int, side SubscriptionSide, matching string) ([]*models.MailboxSubscription, error)

	// CountSubscriptions is how many there are on one side, for the count
	// beside the switch between them, narrowed the same way.
	CountSubscriptions(mailboxId string, side SubscriptionSide, matching string) (int64, error)

	// GetSubscription is one of them, or nil when the mailbox has no mail
	// from that list.
	GetSubscription(mailboxId, listKey string) (*models.MailboxSubscription, error)

	// RecordUnsubscribe stores what was asked and how it went. Asking again
	// writes the same row: a second attempt after a failure is an attempt,
	// not a second subscription.
	RecordUnsubscribe(mailboxId, listKey, method string, failed bool, reason string) error

	// SetSubscriptionMuted turns a list's mail away from the Inbox, or lets it
	// back. The row outlives the mail, so a list muted while it was quiet is
	// still muted when it writes again.
	SetSubscriptionMuted(mailboxId, listKey string, muted bool) error

	// SubscriptionIsMuted is asked by delivery for every message that names a
	// list, so it is one row by primary key and nothing more.
	SubscriptionIsMuted(mailboxId, listKey string) (bool, error)

	// SetSubscriptionImages says that this list's pictures may be loaded
	// without asking, every time, or takes that back.
	SetSubscriptionImages(mailboxId, listKey string, show bool) error

	// EnsureSubscription is the row for a list this mailbox has heard from,
	// made the first time it writes. Delivery calls it for every message that
	// names a list, so it is one lookup by the unique key and an insert only
	// on the first.
	EnsureSubscription(mailboxId, listKey string) (string, error)

	// GetSubscriptionByID is one list by the identity a link names.
	GetSubscriptionByID(mailboxId, subscriptionId string) (*models.MailboxSubscription, error)
}

type SubscriptionSide

type SubscriptionSide int

SubscriptionSide is which side of a subscription list somebody is looking at. A list they have left is not one they are subscribed to, and the page shows one or the other rather than both at once — so the counts beside each are counts of that side.

A request that failed is not a list left: nothing was accepted and the mail keeps coming, so it belongs with the subscribed.

const (
	// SubscribedTo is every list still writing that has not been left.
	SubscribedTo SubscriptionSide = iota

	// Left is the ones asked to stop, and honoured.
	Left

	// EitherSide is both, for looking one up rather than listing them.
	EitherSide
)

type SyncOperation added in v0.139.0

type SyncOperation interface {
	ListSyncCredentials(userId string) ([]*models.SyncCredential, error)
	GetSyncCredential(selector string) (*models.SyncCredential, error)
	CreateSyncCredential(credential *models.SyncCredential) (*models.SyncCredential, error)
	DeleteSyncCredential(userId, credentialId string) error
	TouchSyncCredential(credentialId string, at time.Time) error
}

SyncOperation manages account-owned collection credentials.

type TaxYearOperation added in v0.159.0

type TaxYearOperation interface {
	// GetTaxYearSetting is the agent's settings for a tax year, or nil.
	GetTaxYearSetting(agentId string, taxYear int) (*models.TaxYearSetting, error)

	// PutTaxYearSetting writes the agent's settings for a tax year in the
	// place of the ones before. ErrInvalidArguments for a count out of
	// range or an amount its column does not hold.
	PutTaxYearSetting(setting *models.TaxYearSetting) (*models.TaxYearSetting, error)

	// ListAccountInvestmentIncome adds up, by finance account and kind,
	// the interest and dividends posted to the agent's accounts from from
	// to to, both included ("2006-01-02"): money in that the provider
	// calls interest earned or dividends, or, from a provider that names
	// no category, whose description says interest or dividend. Mirrored
	// copies are counted once; the currency is the account's, and only
	// USD accounts are kept.
	ListAccountInvestmentIncome(agentId, from, to string) ([]*models.AccountInvestmentIncome, error)
}

TaxYearOperation is a person's tax year settings, what the estimate needs that no document says, and the investment income their linked accounts were paid.

type TemplateOperation

type TemplateOperation interface {
	// list templates by domain id
	ListTemplates(domainId string, options *Options) ([]*models.Template, error)

	// get template by id
	GetTemplate(templateId string, options *Options) (*models.Template, error)

	// get multiple templates
	GetTemplates(templateIds []string, options *Options) ([]*models.Template, error)

	// get template by name
	GetTemplateByName(domainId, name string, options *Options) (*models.Template, error)

	// create template
	CreateTemplate(template *models.Template, options *Options) (*models.Template, error)

	// create multiple templates
	CreateTemplates(templates []*models.Template, options *Options) ([]*models.Template, error)

	// save template
	ModifyTemplate(templateId string, modifier func(*models.Template) error, options *Options) (*models.Template, error)

	// save multiple templates
	ModifyTemplates(templateIds []string, modifier func([]*models.Template) error, options *Options) ([]*models.Template, error)

	// delete template
	DeleteTemplate(templateId string, options *Options) error
}

type ThemeOperation added in v0.79.0

type ThemeOperation interface {
	// ListAgentGraphShape is every live page, as little of each as
	// clustering needs, and every stated link between two live pages.
	// Proposed links are left out: a guess the nightly walk made is not
	// evidence that two pages belong together.
	ListAgentGraphShape(agentId string) ([]*AgentGraphShapePage, []*AgentGraphShapeLink, error)

	// ListAgentThemesToReflect is the live themes with an overview written
	// since the night last reflected on them, most important first.
	ListAgentThemesToReflect(agentId string, limit int) ([]*models.AgentNode, error)

	// AgentNodeReflectedAt is when the night last reflected on a page, or
	// nil if it never has. MarkAgentNodeReflected writes it.
	AgentNodeReflectedAt(agentId, nodeId string) (*time.Time, error)
	MarkAgentNodeReflected(agentId, nodeId string, at time.Time) error

	// ListAgentFactsOnNodesSince is the live facts on any of the given
	// pages filed since a time, newest first.
	ListAgentFactsOnNodesSince(agentId string, nodeIds []string, since time.Time, limit int) ([]*models.AgentFact, error)

	// ListAgentTopThemes is the live pages directly under themes, the
	// most important first: the themes of themes and the themes in no
	// group, which is the top of the structure a survey and the prompt's
	// index start from.
	ListAgentTopThemes(agentId string, limit int) ([]*models.AgentNode, error)

	// ListAgentNodesWithOverviews is the live pages that have an
	// overview, the most important first, for a survey of a graph the
	// night has not grouped into themes yet.
	ListAgentNodesWithOverviews(agentId string, limit int) ([]*models.AgentNode, error)
}

ThemeOperation is what the night's theme and reflection phases read and write beyond an ordinary page.

type TokenChange added in v0.52.0

type TokenChange struct {
	Name            *string
	ShouldSetExpiry bool
	ExpiresAt       time.Time
}

TokenChange is what UpdateToken changes: a name when Name is set, and the expiry when ShouldSetExpiry is, to ExpiresAt, or to never where that is zero.

type TokenOperation

type TokenOperation interface {
	CreateToken(token *models.Token, keyHash string) (*models.Token, error)

	// CreateAuthorizedToken mints a token a program holds, with the hash of
	// the secret it refreshes with.
	CreateAuthorizedToken(token *models.Token, keyHash, refreshHash string) (*models.Token, error)

	GetToken(tokenId string) (*models.Token, string, error)

	// GetTokenRefresh is the hash a refresh secret is checked against.
	GetTokenRefresh(tokenId string) (*models.Token, string, error)
	ListTokens(userId string, options *SessionOptions) ([]*models.Token, error)
	TouchToken(tokenId string, at time.Time, ip, userAgent string) error
	RevokeToken(tokenId string, at time.Time) error

	// UpdateToken renames a token or moves when it expires, leaving the
	// secret alone, and is the token as it now stands.
	UpdateToken(tokenId string, change *TokenChange, at time.Time) (*models.Token, error)

	// RetireToken revokes a token and says whether this call was the one that
	// did it, so that two callers racing to retire the same token cannot both
	// go on as though they had.
	RetireToken(tokenId string, at time.Time) (bool, error)
	RevokeTokensByUser(userId string, at time.Time) (int64, error)

	// RenameClientTokens renames every token one app holds for a person.
	// A renewal carries the name over, so the name lasts.
	RenameClientTokens(userId, clientId, name string, at time.Time) (int64, error)

	// RevokeClientTokens ends every token one app holds for a person, which
	// is disconnecting it: with no token left it has nothing to renew.
	RevokeClientTokens(userId, clientId string, at time.Time) (int64, error)

	ScavengeTokens(now time.Time) (int64, error)
}

TokenOperation is the same for API tokens.

type Transaction

type Transaction interface {
	Commit() error

	// AfterCommit queues a non-durable in-memory update after successful SQL
	// commit. Rollback discards it, including rollback of a nested command.
	// Callbacks must be short in-memory operations and must not panic or use
	// the completed transaction. Durable work belongs in database queue records.
	AfterCommit(callback func())

	// TransactionContext runs one command under a savepoint on this connection.
	// A failure rolls back only that command; success remains subject to the
	// outer transaction's commit. The nested transaction cannot commit early.
	TransactionContext(ctx context.Context, function func(Transaction) error) error

	// TryAdvisoryLock takes an advisory lock for the rest of the
	// transaction, or says another transaction holds it.
	TryAdvisoryLock(key int64) (bool, error)

	DomainOperation
	AliasOperation
	CredentialOperation
	UserOperation
	RoleOperation
	GroupOperation
	AuditOperation
	SyncOperation
	MailboxOperation
	SubscriptionQuery
	BimiQuery
	IdentityOperation
	AgentOperation
	InsightOperation
	ReactionOperation
	AttachmentOperation
	RecordingTextCorrectionOperation
	RecordingReferenceOperation
	RecordingSpeakerOperation
	RecordingTemporarySpeakerOperation
	RecordingKnowledgeOperation
	RecordingTranscriptOperation
	RecordingLiveUtteranceOperation
	RecordingPreviewOperation
	RecordingOperation
	RecordingMetadataOperation
	RecordingRetryOperation
	ReplyOperation
	EmbeddingOperation
	VectorOperation
	PlanUsageOperation
	AgentBillingOperation
	OverviewSectionOperation
	GraphOperation
	KnowledgeOperation
	DreamOperation
	OverviewOperation
	ThemeOperation
	RevisionOperation
	MemoryOperation
	ConnectionOperation
	ChannelOperation
	PhoneOperation
	EvaluationOperation
	InteractionOperation
	IdeaOperation
	BackgroundWorkOperation
	GoalOperation
	WatchedItemOperation
	AlertOperation
	FinanceOperation
	FinanceReceiptOperation
	FinanceTaxOperation
	TaxYearOperation
	ExchangeRateOperation
	NetWorthOperation
	BudgetOperation

	DomainUsageOperation
	AliasUsageOperation
	CredentialUsageOperation
	MailOperation
	SubmissionOperation
	CalendarRequestOperation
	MediaCompositionOperation
	DeliveryOperation
	ReportOperation
	LayoutOperation
	TemplateOperation
}

type UserLookup

type UserLookup interface {
	// GetUser returns one by identifier, or nil.
	GetUser(userId string) (*models.User, error)

	// GetUserByUsername returns one by the name they sign in with, without
	// regard to case, or nil.
	GetUserByUsername(username string) (*models.User, error)

	// CountUsers says whether this server has been claimed: zero means the
	// next visitor is asked to create the first account.
	CountUsers() (int64, error)
}

UserLookup is what authenticating a request needs of the user table, read outside any transaction because every request does it.

type UserOperation

type UserOperation interface {
	UserLookup

	ListUsers() ([]*models.User, error)
	CreateUser(user *models.User) (*models.User, error)

	// UpdateUser applies a change to the row as it stands, locked for the
	// duration, and records the before and after.
	UpdateUser(userId string, modify func(*models.User) error) (*models.User, error)

	DeleteUser(userId string) error
}

UserOperation changes the user table, in a transaction and with an audit row for every change.

type VectorOperation

type VectorOperation interface {
	// Nearest is the rows of a table nearest the query, best first, above
	// the floor. Where the extension is present this is one indexed query;
	// where it is not, it is a bounded read and cosine in the server.
	Nearest(table VectorTable, scope, model string, query []float32, limit int, narrow VectorQuery) ([]Scored, error)

	// NoteVectorModel records the width a model writes, the first time one
	// is seen. The server reads these at start to build one index per
	// model, since the dimension is part of the index and differs.
	NoteVectorModel(model string, dimension int) error
	ListVectorModels() (map[string]int, error)
}

VectorOperation ranks stored vectors against a query vector.

type VectorQuery

type VectorQuery struct {
	Where     []string
	Arguments []any

	// Floor is the least similarity worth answering with. Below it the
	// honest answer is that nothing here is about this.
	Floor float64
}

VectorQuery narrows a search beyond the scope: the source a chunk must belong to, the node a fact must be on. Each clause is SQL with a `?` per argument, joined with AND, and is written here rather than passed in from a caller outside this package.

type VectorTable

type VectorTable struct {
	// Table is the table, IDColumn the column naming what the vector is
	// about, and ScopeColumn the column a search narrows by -- the agent
	// whose memory it is, the mailbox the message is in.
	Table       string
	IDColumn    string
	ScopeColumn string

	// OrderColumn is what "the newest" means for this table, which is how
	// the server-side path chooses the bounded set it ranks. Empty means
	// the rows come in whatever order the table gives them, which is only
	// right for a table small enough to read whole.
	OrderColumn string

	// Candidates is how many rows the server-side path ranks. Ignored
	// where the database ranks for us.
	Candidates int
}

VectorTable says where vectors of one kind live and how the server-side path should pick its candidates when there is no index to ask.

type WatchedItemOperation added in v0.114.0

type WatchedItemOperation interface {
	// ListAgentWatchedItemsLooked says which of the items given, each by
	// its id and version, the watch has already looked at; the answer is
	// keyed by WatchedItemKey.
	ListAgentWatchedItemsLooked(agentId, skillName, watchName string, watchedItemIds []string) (map[string]bool, error)

	// AddAgentWatchedItem records an item looked at; one already recorded
	// in that version is left as it is.
	AddAgentWatchedItem(watched *models.AgentWatchedItem) error

	// LatestAgentWatchLookedAt is when the watch last looked, or nil when
	// it never has.
	LatestAgentWatchLookedAt(agentId, skillName, watchName string) (*time.Time, error)

	// MarkAgentWatchLooked records that the watch looked, at the moment
	// given, whatever it found: the next look starts from it.
	MarkAgentWatchLooked(agentId, skillName, watchName string, lookedAt time.Time) error

	// DeleteAgentWatchedItemsBefore forgets the items last looked at before
	// the moment given, which no look reaches back to any more.
	DeleteAgentWatchedItemsBefore(agentId, skillName, watchName string, before time.Time) error
}

WatchedItemOperation keeps which items a skill's watch has looked at, in which version, so that the next look, which overlaps this one, judges none of them twice, and an item that changed is judged again.

Source Files

Directories

Path Synopsis
Package dbtest provides test helpers for database operations.
Package dbtest provides test helpers for database operations.
Package migrations provides database schema migrations.
Package migrations provides database schema migrations.

Jump to

Keyboard shortcuts

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