db

package
v0.252.0 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 50 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 (
	// PlacePageDefault and PlacePageMost bound a page of places
	// or of visits when the caller names no limit or too large a one.
	PlacePageDefault = 50
	PlacePageMost    = 200

	// PassByDurationMost is how long a visit from a place's circle may last
	// and still be a pass-by: iOS tells of crossing a watched circle the
	// moment it happens, with no least stay, so driving past a place the
	// person labeled would otherwise be a visit to it.
	PassByDurationMost = 3 * time.Minute

	// PassBySpeedMetersPerSecondLeast is a speed that says the person was
	// travelling through: faster than a jog (4 m/s is 14 km/h).
	PassBySpeedMetersPerSecondLeast = 4.0

	// PassByStoppedSpeedMetersPerSecondMost is a speed that says the person
	// stopped, as for a drop-off at a school: a short visit with such a
	// position during it is a visit.
	PassByStoppedSpeedMetersPerSecondMost = 0.5

	// PlaceCountMost is how many places one person may have.
	PlaceCountMost = 5000
)
View Source
const (
	MaximumPhotoDescriptionCharacters = 4000
	MaximumPhotoVisibleTextCharacters = 8000
)

The most a description and the words read in a picture hold, in characters. A job cuts what a model wrote to these before it is kept.

View Source
const (
	MaximumPhotoDocumentTitleCharacters = 200
	MaximumPhotoDocumentTextCharacters  = 100000
)

The most a kept document's title and text hold, in characters.

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 ChatCallEventChannel = "chat_call_event"

ChatCallEventChannel is what an instance LISTENs on to hear that a call in a chat changed, so that the people with a part in it are told wherever their tabs and phones are connected.

View Source
const ChatEventChannel = "chat_event"

ChatEventChannel is what an instance LISTENs on to hear what happened in the chats of the people the other instances serve: a message said, edited or taken back, a reaction, a read mark, somebody typing. A channel of its own, because chats exist on a server that runs no agent, which listens on AgentEventChannel only when it has a model.

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 FeedEventChannel = "feed_event"

FeedEventChannel is what an instance LISTENs on to hear that a card of an agent's feed changed, so that a feed open on this one updates.

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 LocationEventChannel = "location_event"

LocationEventChannel is what an instance LISTENs on to hear that somebody's location was reported on another instance, so that a live map open on this one moves. A channel of its own, because reports arrive whether or not the server runs an agent.

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

LocationNotificationMuteLongest is how far ahead a timed mute may end. A mute that should last longer is one that lasts until the person unmutes.

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

LocationPauseLongest is how far ahead a timed pause may end. A pause that should last longer is one that lasts until the person resumes.

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 MaximumMergedPhotoFaceGroups = 50

MaximumMergedPhotoFaceGroups bounds how many groups one merge names.

View Source
const MaximumRankedPhotos = 500

MaximumRankedPhotos is how many photos a search by words ranks. A search asks for the best, and the best are on the first pages.

View Source
const MinimumContactPictureFaceAreaFraction = 0.03

MinimumContactPictureFaceAreaFraction is the share of its photo a face's box must cover to be cut into a contact's picture: a face smaller than that is a few dozen pixels of the large preview, and a picture made of it is blown up and blurred. A person alone in the frame is around a tenth of it; a face in a group of four or five about a thirtieth.

View Source
const MinimumUnnamedPhotoFaceGroupFaceCount = 3

MinimumUnnamedPhotoFaceGroupFaceCount is how many faces a group nobody has named needs to be listed: a pair of faces is more often a chance likeness than a person.

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 PhotoDocumentCandidateWordsLength = 80

PhotoDocumentCandidateWordsLength is how many characters of words read in a picture make it a candidate to be read again as a document.

View Source
const PresenceEventChannel = "presence_event"

PresenceEventChannel carries a person's tab's or phone's report that it is shown (agent.PresenceReport as JSON, with the instance that was given it), so that every instance knows who is looking at what.

View Source
const ShoppingEventChannel = "shopping_event"

ShoppingEventChannel is what an instance LISTENs on to hear that a shopping list changed on another instance, so that a list open on this one ticks as somebody checks it off in the store.

View Source
const SkillShareIdentifierShortestCharacters = 6

SkillShareIdentifierShortestCharacters is the shortest identifier that counts as one an earlier call made. A short one would be found in any output by chance, and the identifiers a payment service gives are long.

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 TravelPeriodsMost = 400

TravelPeriodsMost is how many periods one ListTravelTotals call answers.

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

TripLongestDuration is longer than any trip lasts: a trip that began this long before a range cannot reach into it, so listings leave those out and need not look through all earlier history.

View Source
const TripsMissingVisitMost = 500

TripsMissingVisitMost bounds how many trips ListTripsMissingVisit lists.

View Source
const WatchLookID = "(look)"

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

Variables

View Source
var (
	// ErrPasswordRevisionStale is a save, or an edit, that was based on an
	// older revision of the item than the stored one.
	ErrPasswordRevisionStale = errors.New("db: the password item changed since it was read")

	// ErrPasswordKeyStale is a key sealed for a public key that is no longer
	// the recipient's.
	ErrPasswordKeyStale = errors.New("db: the recipient's public key changed")

	// ErrPasswordRecipientFull is a save or re-key that makes an item larger
	// when a person it is shared with, and holds a key for, would go past
	// models.PasswordsSharedBytesMost or
	// models.PasswordsSharedBytesFromOneOwnerMost. The error is a
	// *PasswordRecipientFullError that names the person.
	ErrPasswordRecipientFull = errors.New("db: an item shared with a person would grow past what they may hold")

	// ErrPasswordCardNotUsableByAgent is a card offered to the agent, which is
	// never allowed.
	ErrPasswordCardNotUsableByAgent = errors.New("db: a card cannot be used by the agent")

	// ErrPasswordsFull is a change that would take the sealed text of the
	// person's items that are not deleted over models.PasswordsBytesMost.
	ErrPasswordsFull = errors.New("db: Passwords is full")

	// ErrPasswordsKeptFull is a change that is not the person's own tap and
	// would add to the deleted items and kept versions when those already hold
	// models.PasswordsKeptBytesMost.
	ErrPasswordsKeptFull = errors.New("db: Passwords keeps too many deleted items and old versions")

	// ErrPasswordSharesFull is a change of shares that would take the owner
	// over models.PasswordSharePairsMost pairs of an item and a person it
	// reaches.
	ErrPasswordSharesFull = errors.New("db: the owner's items reach too many people")

	// ErrPasswordsBusy is a change that waited longer than
	// passwordsLockTimeout for the locks every change of Passwords takes, because
	// others were holding them. Nothing was changed; trying again is fine.
	ErrPasswordsBusy = errors.New("db: Passwords is busy")

	// ErrPasswordTapRequired is a change that only the person's own tap may
	// make (adding a grantee to an item, making a device stay unlocked for
	// longer), decided in the database under the locks of the change.
	ErrPasswordTapRequired = errors.New("db: this change needs the person's own tap")
)
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")

	// ErrLimitReached is a bound on what one person may make or do, such as
	// how many circles they made or how many people a group chat holds. The
	// error says which in words the person can act on, and is shown to them.
	ErrLimitReached = errors.New("db: a limit is reached")
)
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 ErrCircleNeedsAdmin = errors.New("db: a circle needs at least one admin")

ErrCircleNeedsAdmin is the refusal of a change that would leave a circle with members and no admin: the last admin leaving or being made a member. The circle has to name another admin first.

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 ErrJournalChanged = errors.New("db: the journal was saved elsewhere since this was read")

ErrJournalChanged is a save of words or looking back that was based on an older version: somebody saved since the caller read it. Nothing changed.

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 (
	// ErrPhotoBlobGone is a file refused because the blob it names was deleted
	// between the bytes being stored and the file being recorded. The caller
	// stores the bytes again.
	ErrPhotoBlobGone = errors.New("db: the photo blob was deleted")
)
View Source
var ErrPlaceCountMost = fmt.Errorf("%w: a person may have at most %d places; forget some first", ErrInvalidArguments, PlaceCountMost)

ErrPlaceCountMost is the answer to making a place for a person who has PlaceCountMost of them. It is an ErrInvalidArguments, and one a caller that has other things to store can tell apart and go on without.

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.

View Source
var ErrShoppingPictureChanged = errors.New("db: the item's picture changed meanwhile")

ErrShoppingPictureChanged is a picture found on the web arriving after the item's picture changed, or a person uploaded one: the newer stays.

View Source
var PhotoVectorTable = VectorTable{Table: "photo_vector", IDColumn: "photo_id", ScopeColumn: "user_id", OrderColumn: "created_at", Candidates: 5000}

PhotoVectorTable is where the meaning of photos' descriptions is kept.

Functions

func ChatMessageAsAgentMessage added in v0.170.0

func ChatMessageAsAgentMessage(message *models.ChatMessage, conversationId string, quoted map[string]*models.ChatMessage) *models.AgentMessage

ChatMessageAsAgentMessage is a chat message as the conversation of one of its members shows it: a person's is a user message and an agent's an assistant message, so that the screens that draw a conversation draw a chat. quoted holds the messages that replies are to, by id.

func ChatViewOf added in v0.170.0

func ChatViewOf(chat *models.Chat, userId string) *models.ChatView

ChatViewOf is a chat as one member sees it, without what is theirs alone (the unread count and the mute): its title for them, and who is in it.

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 DecodeFeedCursor added in v0.230.0

func DecodeFeedCursor(text string) (*models.FeedCursor, error)

DecodeFeedCursor reads what EncodeFeedCursor wrote; empty is no cursor.

func EncodeFeedCursor added in v0.230.0

func EncodeFeedCursor(cursor *models.FeedCursor) string

EncodeFeedCursor is a cursor as the text a client hands back to read the next page.

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 LockKey added in v0.206.2

func LockKey(lockName string) int64

LockKey is the advisory lock key for a name: what makes one piece of work one instance's at a time, whichever instance asks. A name rather than a number chosen by hand, so that two callers cannot pick the same number without seeing that they picked the same name.

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 AcmeChallengeKey added in v0.206.2

type AcmeChallengeKey struct {
	ChallengeKind string
	ChallengeKey  string
}

AcmeChallengeKey names one challenge: its kind and its key.

type AcmeChallengeOperation added in v0.206.2

type AcmeChallengeOperation interface {
	// PutAcmeChallenge stores the answer to a challenge, replacing one under
	// the same key, so that whichever instance the certificate authority's
	// check reaches can give it. The challengeKey is the token for http-01
	// and the lower case domain name for tls-alpn-01. Answers that expired
	// before now are removed on the way, so that one that is never cleaned
	// up (an instance that stopped mid-order) does not stay.
	PutAcmeChallenge(challengeKey, challengeKind, keyAuthorization string, expiresAt, now time.Time) error

	// DeleteAcmeChallenge removes the answer to a challenge. Not an error
	// when there is none.
	DeleteAcmeChallenge(challengeKey string) error

	// FindAcmeChallenge returns the key authorization stored for a challenge
	// of that kind that has not expired at now. ErrNotFound when there is
	// none.
	FindAcmeChallenge(challengeKey, challengeKind string, now time.Time) (string, error)

	// ListAcmeChallenges is every challenge that has not expired at now, by
	// kind and key: usually none, and never more than an order has names.
	ListAcmeChallenges(now time.Time) (map[AcmeChallengeKey]string, error)
}

AcmeChallengeOperation is the challenges a certificate authority is about to check (acme_challenge).

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 AgentComputerAttachmentOperation added in v0.206.2

type AgentComputerAttachmentOperation interface {
	// PutAgentComputerAttachment says an instance holds the computer, or says
	// so again under whichever instance now does.
	PutAgentComputerAttachment(agentId, computerName, instance string, now time.Time) error

	// DeleteAgentComputerAttachment forgets that an instance holds the
	// computer. A row another instance has since written is left alone.
	DeleteAgentComputerAttachment(agentId, computerName, instance string) error

	// DeleteAgentComputerAttachmentsOfInstance forgets every computer an
	// instance said it held, for the instance starting: it holds none yet.
	DeleteAgentComputerAttachmentsOfInstance(instance string) error

	// HeartbeatAgentComputerAttachments says an instance is still holding the
	// computers it has not let go of.
	HeartbeatAgentComputerAttachments(instance string, now time.Time) error

	// FindAgentComputerAttachment is the name of the instance that holds the
	// computer and has been heard of since freshAfter, or empty when none
	// does. An empty computerName is any computer of the agent, the one
	// heard of most recently. A computer name is matched without regard to
	// case, as the person's choice of computer for a skill is.
	FindAgentComputerAttachment(agentId, computerName string, freshAfter time.Time) (string, error)
}

AgentComputerAttachmentOperation is which instance holds the websocket of a person's computer (agent_computer_attachment). Only the instance holding the socket can read the computer, so the others look here to see that a job for it is that instance's to run.

type AgentConversationActivity added in v0.202.0

type AgentConversationActivity struct {
	ConversationID string
	Title          string
	Summary        string
	MessageCount   int

	// IsMain is the person's main conversation with their agent, which is
	// called that and not by a title a turn once gave it.
	IsMain bool

	// FirstMessageID is the first message said in the stretch, which is where
	// a link to the conversation opens it.
	FirstMessageID string
	FirstAt        time.Time
	LastAt         time.Time
}

AgentConversationActivity is one conversation with the agent in a stretch of time: how many messages were said in it then, and when the first and the last were.

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

	// ClaimAgentFollowUpBackfill writes that the look back over past mail
	// for follow-ups runs now, and answers whether this call is the one
	// that made it: false when it already ran, so it never runs twice.
	// MarkAgentFollowUpBackfilled writes it without asking, for the person
	// who has it run again.
	ClaimAgentFollowUpBackfill(agentId string, at time.Time) (bool, error)
	MarkAgentFollowUpBackfilled(agentId string, at 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)

	// RenewAgentJobClaim moves the time the running claim named by claimId
	// was taken to at, and says whether that claim still holds: a job with
	// no deadline of its own is kept from being put back in the queue as a
	// lost one by renewing its claim while it runs.
	RenewAgentJobClaim(jobId, claimId string, at time.Time) (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 AgentProviderAccessToken added in v0.206.2

type AgentProviderAccessToken struct {
	ProviderName string

	// AccessToken is sealed with the server secret in the table.
	AccessToken string

	// ForRefreshToken is the refresh token held when the access token was
	// fetched. The access token is only usable by an instance whose refresh
	// token is this one: after a new sign-in it may belong to another account.
	ForRefreshToken string
	ExpiresAt       time.Time
}

AgentProviderAccessToken is the access token a provider's sign-in was last traded for, and the refresh token it was traded with, so that an instance that finds its own access token run out can use the one another instance fetched instead of rotating the refresh token again.

type AgentProviderSignIn added in v0.206.2

type AgentProviderSignIn struct {
	ID                  string
	ProviderName        string
	UserCode            string
	VerificationAddress string

	// DeviceAuthID is what the service asks for again when it is polled.
	// Sealed with the server secret in the table.
	DeviceAuthID string

	PollInterval time.Duration
	ExpiresAt    time.Time
}

AgentProviderSignIn is a model provider's sign-in waiting for its code to be entered: what the instance that began it was given, so that the instance the dashboard's next request reaches can wait on it too.

type AgentProviderSignInOperation added in v0.206.2

type AgentProviderSignInOperation interface {
	// CreateAgentProviderSignIn stores a sign-in that waits for its code, and
	// removes the ones that expired before now on the way.
	CreateAgentProviderSignIn(signIn *AgentProviderSignIn, now time.Time) error

	// GetAgentProviderSignIn returns a sign-in by its id, expired or not.
	// ErrNotFound when there is none.
	GetAgentProviderSignIn(signInID string) (*AgentProviderSignIn, error)

	// DeleteAgentProviderSignIn removes a sign-in, finished or expired. Not an
	// error when there is none.
	DeleteAgentProviderSignIn(signInID string) error

	// PutAgentProviderAccessToken stores the access token of a provider,
	// replacing the one before it.
	PutAgentProviderAccessToken(accessToken *AgentProviderAccessToken) error

	// GetAgentProviderAccessToken returns the access token stored for a
	// provider. ErrNotFound when there is none.
	GetAgentProviderAccessToken(providerName string) (*AgentProviderAccessToken, error)
}

AgentProviderSignInOperation is the model provider sign-ins waiting for their code (agent_provider_sign_in), and the access tokens signed-in providers were last given (agent_provider_access_token).

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 AgentTurnOperation added in v0.206.2

type AgentTurnOperation interface {
	// PutAgentTurn records a turn as running, or records it again under
	// whichever instance now runs it.
	PutAgentTurn(turn *models.AgentTurn) error

	// DeleteAgentTurn forgets a turn that ended.
	DeleteAgentTurn(runId string) error

	// GetAgentTurn is a recorded turn, nil when there is none.
	GetAgentTurn(runId string) (*models.AgentTurn, error)

	// HeartbeatAgentTurns says an instance is running exactly these turns
	// as of now: they are written as running, and the instance's other turns
	// that were not cut and were last heard of before now are forgotten.
	HeartbeatAgentTurns(instance string, running []*models.AgentTurn, now time.Time) error

	// CutAgentTurns marks the turns an instance is stopping with as cut, so
	// another instance may carry them on at once.
	CutAgentTurns(instance string, now time.Time) (int64, error)

	// ListLiveAgentTurns is the turns of a conversation that some instance
	// is running: not cut, and heard of since freshAfter.
	ListLiveAgentTurns(conversationId string, freshAfter time.Time) ([]*models.AgentTurn, error)

	// ClaimCutAgentTurns takes, and forgets, the turns that were cut or whose
	// instance has not been heard of since staleBefore, for the caller to
	// carry on. Each is taken by one caller only.
	ClaimCutAgentTurns(staleBefore time.Time, limit int) ([]*models.AgentTurn, error)
}

AgentTurnOperation is the turns running on some instance (agent_turn).

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, nor
	// is a follow-up candidate whose subject key it has; both answer 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)

	// UpsertAgentFollowUp keeps a follow-up, new or by the agent and key it
	// already has, and says whether it was created. An update keeps the id,
	// the time it was created and the state, takes the
	// fields the message gave and leaves alone those it left empty, and
	// adds the message ids to those it came from.
	UpsertAgentFollowUp(followUp *models.AgentFollowUp) (*models.AgentFollowUp, bool, error)

	// ListOpenAgentFollowUps is the agent's follow-ups still being watched
	// (open, overdue, stalled), the nearest date first and those with none
	// last.
	ListOpenAgentFollowUps(agentId string) ([]*models.AgentFollowUp, error)

	// ListAgentFollowUps is the agent's follow-ups in any state, newest
	// first.
	ListAgentFollowUps(agentId string, limit int) ([]*models.AgentFollowUp, error)

	// GetAgentFollowUps is the agent's follow-ups with these ids, in any
	// state, the nearest day first; one that is gone is left out.
	GetAgentFollowUps(agentId string, followUpIds []string) ([]*models.AgentFollowUp, error)

	// UpdateAgentFollowUp changes one follow-up under a lock, so two runs
	// that close or tell it take turns. ErrNotFound when there is none; an
	// error from the function leaves it as it was.
	UpdateAgentFollowUp(id string, update func(*models.AgentFollowUp) error) (*models.AgentFollowUp, 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 AllFinanceShareOperation added in v0.210.0

type AllFinanceShareOperation interface {
	// ShareAllFinance gives a person or a circle a level of access to all of
	// the sharer's finance, or changes the level they have. ErrNotFound unless
	// the sharer has an agent and, for a person, the two share a circle, or,
	// for a circle, the sharer is in it. ErrInvalidArguments for a level that
	// cannot be given, a grantee that is not exactly one, or the sharer
	// themselves.
	ShareAllFinance(ownerUserId string, share *models.AllFinanceShare) (*models.AllFinanceShare, error)

	// UnshareAllFinance takes one of the owner's whole-finance shares back.
	// ErrNotFound when the owner has no such share.
	UnshareAllFinance(ownerUserId, shareId string) error

	// ListAllFinanceSharesBy are the whole-finance shares the person has made,
	// oldest first, with who each is for.
	ListAllFinanceSharesBy(ownerUserId string) ([]*models.AllFinanceShare, error)

	// ListAllFinanceSharesReaching are the whole-finance shares that reach the
	// person now, oldest first, each with whose finance it is. A share to a
	// person reaches them only while the two still share a circle, and a share
	// to a circle only while both are in it. Not the person's own.
	ListAllFinanceSharesReaching(viewerUserId string) ([]*models.AllFinanceShare, error)

	// ReachAllFinance is the finance of another person as the viewer reaches
	// it as a whole, at the highest level of the shares that reach them, or nil
	// when none does (or the person who owns it, or they, can no longer use
	// finance).
	ReachAllFinance(viewerUserId, ownerUserId string) (*models.ReachedAllFinance, error)

	// ListReachedAllFinance are the people whose whole finance reaches the
	// viewer, each once at the highest level, by username.
	ListReachedAllFinance(viewerUserId string) ([]*models.ReachedAllFinance, error)

	// ListSharedAllFinanceSpending is the owner's money out and in by month
	// and spending category across all their finance accounts, newest month
	// first, in each currency, for the days from and to ("2006-01-02", either
	// may be empty). ErrNotFound unless the owner's whole finance reaches the
	// viewer at the spending level or better. A finance account shared on its
	// own at a higher level is not read here: this is the level of the share
	// of the whole.
	ListSharedAllFinanceSpending(viewerUserId, ownerUserId, from, to string) ([]*models.SharedFinanceSpendingRow, error)

	// ListSharedAllFinanceTransactions is a page of the transactions of all
	// the owner's finance accounts together, newest first. ErrNotFound unless
	// the owner's whole finance reaches the viewer at the transactions level.
	ListSharedAllFinanceTransactions(viewerUserId, ownerUserId string, filter *SharedFinanceTransactionFilter) (*SharedFinanceTransactionPage, error)
}

AllFinanceShareOperation is a person's whole finance shared with another person or with a circle at a level (spending or transactions): every finance account the owner holds now and every one they link later, read together. It sits beside FinanceShareOperation, which is of one account at a time, and follows its rules: the same conditions decide who is reached (financeShareReachesViewerSQL), the same circles make a share possible, and the reads return types that have no field for an account's name, mask or balance, so that what a whole-finance share leaves out is not something a caller has to remember to apply.

type AttachmentOperation

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

	// GetAgentAttachmentOfPhoto is the copy of a photo made to be read as a
	// document, or nil when there is none.
	GetAgentAttachmentOfPhoto(agentId, photoId 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

	// ChatAttachmentBytes is how much the agent's person keeps of the files
	// they sent in chats: the size of the agent's files that came with a chat
	// message that is still there. A file handed to the agent, or one
	// uploaded and not sent yet, is not counted.
	ChatAttachmentBytes(agentId string) (int64, 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

	// QueueAgentAttachmentForMainChat marks a file of the agent's as sent
	// to the main chat, with the line sent with it and who sent it, to be
	// posted once no turn runs there. ErrNotFound when the agent has no
	// such file.
	QueueAgentAttachmentForMainChat(agentId, attachmentId, caption, sentBy string) error

	// ListAgentAttachmentsWaitingForMainChat is the files sent to a main
	// chat and not posted yet, oldest first; one still waiting for its
	// upload is not among them.
	ListAgentAttachmentsWaitingForMainChat(limit int) ([]*models.AgentAttachment, error)

	// PostedAgentAttachmentToMainChat records that a waiting file was
	// posted into the main chat: it is that conversation's, and waits no
	// more. False when it was not waiting, because another sweep posted it.
	PostedAgentAttachmentToMainChat(attachmentId, conversationId string) (bool, error)

	// FinishAgentAttachmentUpload records that the bytes of a file waiting
	// for its upload arrived, with their size and type: one for the main
	// chat is then handed over, one for the feed kept for its card. False
	// when the file is not waiting for one, because it was uploaded already.
	FinishAgentAttachmentUpload(attachmentId, contentType string, size int64) (bool, error)
	// ReopenAgentAttachmentUploadForFeed puts an upload for the feed whose
	// card could not be posted back to waiting for its bytes, so the
	// program can send them again. Only a file no message holds.
	ReopenAgentAttachmentUploadForFeed(attachmentId string) error

	// KeepAgentAttachmentForFeed marks a file of the agent's as shown by a
	// card of the feed, with the line sent with it, who sent it, and the
	// text a model reads of it: it belongs to no conversation, and is kept
	// while a card holds it. ErrNotFound when the agent has no such file.
	KeepAgentAttachmentForFeed(agentId, attachmentId, caption, sentBy, text 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 and has no queued or running job to run it
	// 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 CalendarShareOperation added in v0.170.0

type CalendarShareOperation interface {
	// CalendarAccess is what the person may do with the calendar:
	// ShareLevelOwner and true for their own, ShareLevelEdit for every member
	// of the circle a circle calendar belongs to, the highest of the shares
	// reaching them for another person's, and the empty level for anything
	// else. A share to a circle reaches a member only while the calendar's
	// owner is still in that circle, and a share to a person only while the
	// two still share a circle.
	CalendarAccess(principalUserId string, found *models.Calendar) (models.ShareLevel, bool, error)

	// ListReachableCalendars are every calendar the person reaches, oldest
	// first within each group: their own, then their circles' calendars, then
	// the ones shared with them at any level.
	ListReachableCalendars(userId string) ([]*models.ReachableCalendar, error)

	// FindCalendar is the person's own calendar of a kind, or nil. Unlike
	// EnsureCalendar it makes nothing.
	FindCalendar(userId string, kind models.CalendarKind) (*models.Calendar, error)

	// CreateCircleCalendar makes a circle's calendar of events. ErrNotFound
	// when there is no such circle, ErrAlreadyExists when it has one: a circle
	// has one.
	CreateCircleCalendar(circleId, name, timezone string) (*models.Calendar, error)

	// DeleteCircleCalendar takes away the calendar a circle keeps for itself,
	// with every event in it. ErrNotFound when there is no such circle or it
	// has none. The caller has checked that the person may.
	DeleteCircleCalendar(circleId string) error

	// GetCircleCalendar is the circle's calendar, or nil.
	GetCircleCalendar(circleId string) (*models.Calendar, error)

	// ShareCalendar gives a person or a circle a level of access to the
	// sharer's own events calendar, or changes the level they have. ErrNotFound
	// unless the calendar is the sharer's and, for a person, the two share a
	// circle, or, for a circle, the sharer is in it. ErrInvalidArguments for a
	// level that cannot be given or a grantee that is not exactly one.
	ShareCalendar(sharerUserId string, share *models.CalendarShare) (*models.CalendarShare, error)

	// GetCalendarShare is one share, or nil.
	GetCalendarShare(shareId string) (*models.CalendarShare, error)

	// ListCalendarShares are a calendar's shares with who they are for, by
	// who they were made for.
	ListCalendarShares(calendarId string) ([]*models.CalendarShare, error)

	// DeleteCalendarShare takes one back. ErrNotFound when there is none.
	DeleteCalendarShare(shareId string) error

	// ReadCalendarObject is GetCalendarObject for a reader at a level: the
	// owner's and an editor's get the event as it is, and anybody else's what
	// calendar.Redact leaves. This and ReadCalendarObjects are the only places
	// a reader's view of an event is made.
	ReadCalendarObject(calendarId, objectId string, shareLevel models.ShareLevel) (*models.CalendarObject, error)

	// ReadCalendarObjects is ListCalendarObjects for a reader at a level.
	ReadCalendarObjects(calendarId string, shareLevel models.ShareLevel) ([]*models.CalendarObject, error)
}

CalendarShareOperation is who may read and write which calendar: a person's calendar shared with another person or with a circle at a level, and the calendar a circle keeps for itself.

"May this person read or write this calendar, and at what level" has one answer, CalendarAccess, and every door asks it: the dashboard's API, CalDAV, the command line and the agent. A caller that compares a calendar's UserID with the person instead is wrong for a circle's calendar, which has none.

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 ChatActivity added in v0.202.0

type ChatActivity struct {
	ChatID       string
	MessageCount int

	// FirstMessageID is the first message said in the stretch, which is where
	// a link to the chat opens it.
	FirstMessageID string
	FirstAt        time.Time
	LastAt         time.Time
}

ChatActivity is one chat in a stretch of time: how many messages the person could read that were said in it then, and when the first and the last were.

type ChatAgentOperation added in v0.170.0

type ChatAgentOperation interface {
	// SetChatAgentReading makes a member's agent remember the chat, or stop.
	// Turning it on makes the chat a knowledge source of the member's agent
	// (kind chat), read from now: what was said before is not read, nor what
	// is said while it is off. Turning it off switches the source off at once;
	// what the agent learned stays, as with any source. It answers the source,
	// nil when there is none. ErrNotFound when the member is not in the chat.
	SetChatAgentReading(chatId, userId string, isReading bool) (*models.AgentKnowledgeSource, error)

	// SetChatAgentAskableByOthers lets the others in a chat address a
	// member's agent, or stops them. ErrNotFound when the member is not in
	// the chat.
	SetChatAgentAskableByOthers(chatId, userId string, isAskable bool) error

	// ListChatTurnRows is what a turn of a member's agent reads of their chat
	// conversation: the chat's messages from the time the member joined until
	// they left, interleaved with the member's own agent's rows in the
	// conversation, oldest first. Without a compaction it is the newest limit
	// of them; with one, everything from the message it stands in for, which
	// is kept, and the compaction's note. A deleted message is left out.
	// With isChatOnly it is the chat's messages alone, the newest limit of
	// them, with none of the member's own agent's rows and no compaction, and
	// only those every current member of the chat could read (created at or
	// after the latest time any of them joined): what a turn somebody else
	// asked for may read, since those rows hold what the member's own agent
	// found, and the answer goes to everybody in the room.
	ListChatTurnRows(conversation *models.AgentConversation, limit int, isChatOnly bool) ([]*models.AgentMessage, error)

	// ListChatMessagesAfter is the messages of a chat newer than the one
	// given, oldest first, for the reading of a chat as a source. A message
	// deleted is left out. An empty id starts at the beginning.
	ListChatMessagesAfter(chatId, afterMessageId string, limit int) ([]*models.ChatMessage, error)

	// NewestChatMessageID is the id of the newest message of a chat, empty
	// when there is none.
	NewestChatMessageID(chatId string) (string, error)
}

ChatAgentOperation is what agents in chats need beyond the chat itself: the two switches a member has for their own agent, the history a turn of it reads, and the messages its reading of the chat files.

type ChatCallEvent added in v0.212.0

type ChatCallEvent struct {
	CallID  string   `json:"callId"`
	UserIDs []string `json:"userIds"`
}

ChatCallEvent is what travels on ChatCallEventChannel: which call changed, and who to tell. What changed is read from the tables.

type ChatOperation added in v0.170.0

type ChatOperation interface {
	// EnsureAgent is the person's agent row, made switched off when they
	// have none. Everybody who can chat needs one, because their
	// conversations and phones hang from it; a switched-off agent does
	// nothing else (agent.Active is false), and the settings page offers to
	// turn it on as it does for a person who never had one.
	EnsureAgent(userId string) (*models.Agent, error)

	// EnsureChatConversation is the agent's own conversation for a chat,
	// made when there is none.
	EnsureChatConversation(agentId, chatId string) (*models.AgentConversation, error)

	// SyncChatsOf makes what the person's circles imply true: the circle
	// chat of each circle they are in (circles older than chats have none
	// until now), and a conversation for each chat they are in. Cheap when
	// there is nothing to do.
	SyncChatsOf(userId string) error

	// OpenDirectChat is the direct chat between two people, made when there
	// is none and the same one every time. That they know each other is the
	// caller's to check. ErrNotFound when either account is not there.
	OpenDirectChat(userId, otherUserId string) (*models.Chat, error)

	// CreateGroupChat makes a group chat with the maker as its first admin and
	// the others as members. That each shares a circle with the maker is the
	// caller's to check.
	CreateGroupChat(creatorUserId, title string, memberUserIds []string) (*models.Chat, error)

	// GetChat is a chat with everybody who is or was in it, or nil.
	GetChat(chatId string) (*models.Chat, error)

	// GetCircleChat is the chat a circle has, with everybody who is or was in
	// it, or nil when it has none yet.
	GetCircleChat(circleId string) (*models.Chat, error)

	// ListChatsOf are the chats the person is in now, with everybody who is or
	// was in each. It is how the caller learns whom to tell before a change
	// takes the person out of some of them.
	ListChatsOf(userId string) ([]*models.Chat, error)

	// ListChatActivityBetween is what was said in the chats the person is or
	// was in, in a stretch of time: for each chat with a message created from
	// from up to but not including until that the person could read (after
	// they joined, and up to when they left), not counting deleted ones, how
	// many and the times of the first and the last, earliest first.
	ListChatActivityBetween(userId string, from, until time.Time) ([]*ChatActivity, error)

	// GetDirectChat is the direct chat between two people, or nil when
	// they have none.
	GetDirectChat(userId, otherUserId string) (*models.Chat, error)

	// GetChatOfConversation is the chat a member's conversation is for, or
	// nil when the conversation is not a chat's.
	GetChatOfConversation(conversationId string) (*models.Chat, error)

	// RenameChat changes a group's title; an empty one leaves it unnamed.
	RenameChat(chatId, title string) (*models.Chat, error)

	// AddChatMembers puts people in a group chat who are not in it, and back
	// in those who left; they read it from then on. ErrNotFound for a
	// direct chat or a circle chat, whose members are not chosen.
	AddChatMembers(chatId string, userIds []string) (*models.Chat, error)

	// RemoveChatMember takes a person out of a group chat, who then reads
	// what was said until now. The last admin leaving makes the member who
	// joined first an admin, and the last member leaving deletes the chat,
	// answering nil. ErrNotFound when they are not in it, or it is a direct
	// chat or a circle chat.
	RemoveChatMember(chatId, userId string) (*models.Chat, error)

	// ChatViewsFor describes these conversations' chats as the person sees
	// them, setting each conversation's Chat; conversations that are not a
	// chat's are left as they are.
	ChatViewsFor(userId string, conversations []*models.AgentConversation) error

	// ListChatConversations are the conversations of the agent that are
	// chats', newest first.
	ListChatConversations(agentId string) ([]*models.AgentConversation, error)

	// AppendChatMessage stores what a member said and tells the chat there
	// is something new: its last message, the members' conversations and the
	// author's own read mark. ErrNotFound when the author is not in the
	// chat.
	AppendChatMessage(message *models.ChatMessage) (*models.ChatMessage, error)

	// GetChatMessage is one message with its reactions, or nil.
	GetChatMessage(messageId string) (*models.ChatMessage, error)

	// EditChatMessage changes what a message says and marks it edited.
	// ErrNotFound when it is deleted.
	EditChatMessage(messageId, body string) (*models.ChatMessage, error)

	// DeleteChatMessage deletes a message: its text and files go and the
	// message stays, drawn as deleted.
	DeleteChatMessage(messageId string) (*models.ChatMessage, error)

	// ClaimVoiceMessageTranscript takes a voice message whose words are
	// still to be written, for one server to write: nil when it is not
	// waiting, is deleted, or another server claimed it within retryAfter.
	ClaimVoiceMessageTranscript(messageId string, retryAfter time.Duration) (*models.ChatMessage, error)

	// FinishVoiceMessageTranscript writes the words of a waiting voice
	// message and its new state (done, failed or off), without marking it
	// edited. nil when it is no longer waiting.
	FinishVoiceMessageTranscript(messageId, transcriptState, transcriptText string) (*models.ChatMessage, error)

	// WriteVoiceMessageWords gives a voice message that has no words (they
	// were off, or failed) the words a member asked for; nil when it has
	// words, is waiting for them, or is gone.
	WriteVoiceMessageWords(messageId, transcriptText string) (*models.ChatMessage, error)

	// ListWaitingVoiceMessageIDs are the voice messages still waiting for
	// their words, oldest first, that nobody claimed within retryAfter.
	ListWaitingVoiceMessageIDs(retryAfter time.Duration, limit int) ([]string, error)

	// FailStaleVoiceMessages gives up on the voice messages that have waited
	// since before the given time, and answers them as they now are.
	FailStaleVoiceMessages(before time.Time) ([]*models.ChatMessage, error)

	// CreateChatCall starts a call in a chat: the one who started it is on
	// it, and the people given are being rung. ErrAlreadyExists when a call is
	// going in the chat already.
	CreateChatCall(chatId, startedByUserId, instance string, rungUserIds []string) (*models.ChatCall, error)

	// GetChatCall is a call with each member's part in it; nil when there is
	// none.
	GetChatCall(callId string) (*models.ChatCall, error)

	// GetGoingChatCall is the call going in a chat; nil when none is.
	GetGoingChatCall(chatId string) (*models.ChatCall, error)

	// ListChatCalls is a chat's calls, newest first, started before the time
	// given when one is.
	ListChatCalls(chatId string, before *time.Time, limit int) ([]*models.ChatCall, error)

	// ListGoingChatCallsOfUser is the calls going that the person has a part
	// in: rung by, on, or left.
	ListGoingChatCallsOfUser(userId string) ([]*models.ChatCall, error)

	// ListGoingChatCalls is the calls going that a server instance holds.
	ListGoingChatCalls(instance string) ([]*models.ChatCall, error)

	// JoinChatCall puts the person on a going call: answered when they were
	// rung, and added when they came into the chat after it started. The call
	// is answered from the first time somebody other than its starter joins.
	JoinChatCall(callId, userId string) (*models.ChatCall, error)

	// DeclineChatCall is the person saying no while they are rung.
	DeclineChatCall(callId, userId string) (*models.ChatCall, error)

	// LeaveChatCall takes the person off a going call.
	LeaveChatCall(callId, userId string) (*models.ChatCall, error)

	// SetChatCallVideo records whether the person's camera is on.
	SetChatCallVideo(callId, userId string, isVideoOn bool) (*models.ChatCall, error)

	// SetChatCallMuted records whether the person's microphone is off.
	SetChatCallMuted(callId, userId string, isMuted bool) (*models.ChatCall, error)

	// EndChatCall ends a going call: whoever is still rung missed it, and
	// whoever is on it has left. A transcript asked for on a call that was
	// answered is then waiting to be written.
	EndChatCall(callId string, endReason models.ChatCallEndReason) (*models.ChatCall, error)

	// StopRingingChatCall marks whoever is still rung on a going call as
	// having missed it.
	StopRingingChatCall(callId string) (*models.ChatCall, error)

	// AskChatCallTranscription marks a going call as asked to be
	// transcribed, by the first to ask: everybody on it is transcribed.
	AskChatCallTranscription(callId, userId string) (*models.ChatCall, error)

	// ClaimChatCallTranscript claims a call whose transcript is waiting, so
	// one server writes it; nil when it is not waiting or another server
	// claimed it within retryAfter.
	ClaimChatCallTranscript(callId string, retryAfter time.Duration) (*models.ChatCall, error)

	// ListWaitingChatCallTranscriptIDs is the calls whose transcript is
	// waiting and that nobody claimed within retryAfter, oldest first.
	ListWaitingChatCallTranscriptIDs(retryAfter time.Duration, limit int) ([]string, error)

	// SetChatCallRecording names the recording a call waiting for its
	// transcript became; nil when it was not waiting or has one already.
	SetChatCallRecording(callId, recordingId string) (*models.ChatCall, error)

	// FinishChatCallTranscript says how a call's transcript ended (done or
	// failed), with the summary's message; nil when it was not waiting.
	FinishChatCallTranscript(callId, transcriptState string, summaryMessageId string) (*models.ChatCall, error)

	// SharesChat says whether two different people are both current members
	// of one chat, whatever circles they are in: a chat shows each member to
	// the others by name, so their picture goes with it.
	SharesChat(userId, otherUserId string) (bool, error)

	// ListChatConversationMessages is the newest page of what a member
	// reads in their conversation for a chat -- the chat's messages from the
	// time they joined until the time they left, if they did, and their own
	// agent's rows in the conversation, by time -- with how many there are
	// in all. Offset counts back from the newest. A page is oldest first.
	ListChatConversationMessages(conversation *models.AgentConversation, limit, offset int) ([]*models.AgentMessage, int, error)

	// ListChatMemberTurnMessages is the same page as a turn somebody else
	// asked the member's agent for may read it: the chat's messages alone,
	// none of the agent's own rows in the conversation, and only those that
	// every current member of the chat could read, the ones created at or
	// after the latest time any current member joined. Whoever asked was
	// shown the chat from their own joining, which may be later than the
	// owner's, and what the owner's agent says in answer goes to all of them.
	ListChatMemberTurnMessages(conversation *models.AgentConversation, limit, offset int) ([]*models.AgentMessage, int, error)

	// SetChatMessageReaction puts a reactor's emoji on a message, replacing
	// the one they had; an empty emoji takes it away. It says whether
	// anything changed.
	SetChatMessageReaction(messageId string, reactorKind models.AgentReactorKind, reactorId, reactorName, reactionEmoji string) (bool, error)

	// MarkChatRead moves a member's read mark forward to a message of the
	// chat, and never back. It says whether the mark moved. ErrNotFound when
	// the message is not the chat's.
	MarkChatRead(chatId, userId, throughMessageId string) (bool, error)

	// SetChatNotificationLevel sets what a member's phone is told of in a
	// chat.
	SetChatNotificationLevel(chatId, userId string, notificationLevel models.ChatNotificationLevel) error

	// GetUsersByID reads accounts, without their groups, by id. One that is
	// gone is left out.
	GetUsersByID(userIds []string) (map[string]*models.User, error)
}

ChatOperation is the chats: who is in them, what was said, and every member's own conversation for them. docs/subsystems/conversations.md says how a chat is read.

type CircleOperation added in v0.170.0

type CircleOperation interface {
	// CreateCircle makes a circle with its maker as the first admin.
	CreateCircle(circle *models.Circle, creatorUserId string) (*models.Circle, error)

	// GetCircle returns a circle with its members, or nil.
	GetCircle(circleId string) (*models.Circle, error)

	// ListCircles returns the circles a person is in, with their members,
	// by name.
	ListCircles(userId string) ([]*models.Circle, error)

	// RenameCircle changes a circle's name. ErrNotFound when there is none.
	RenameCircle(circleId, name string) (*models.Circle, error)

	// DeleteCircle removes a circle with its members and invitations.
	// ErrNotFound when there is none.
	DeleteCircle(circleId string) error

	// AddCircleMember puts an account in a circle. A person who is already in
	// it is left as they are. ErrNotFound when the circle or the account is
	// not there. A waiting invitation to the same circle is closed as
	// accepted. An account put in is recorded in the audit log, naming the
	// actor of the transaction.
	AddCircleMember(circleId, userId string, memberRole models.MemberRole, invitedByUserId string) (*models.Circle, error)

	// SetCircleMemberRole changes a member's role. ErrNotFound when the
	// person is not in the circle; ErrCircleNeedsAdmin when it would take
	// the last admin's.
	SetCircleMemberRole(circleId, userId string, memberRole models.MemberRole) (*models.Circle, error)

	// RemoveCircleMember takes a person out of a circle, whether they left
	// or were removed. It returns the circle as it is now, or nil when that
	// was its last member and the circle went with them. ErrNotFound when
	// the person is not in the circle; ErrCircleNeedsAdmin when they are
	// its last admin and others remain.
	RemoveCircleMember(circleId, userId string) (*models.Circle, error)

	// SharesCircle says whether two different people are in a circle
	// together.
	SharesCircle(userId, otherUserId string) (bool, error)

	// CircleHasSensitiveShare says whether anybody has shared Health, a
	// finance account or all their finance with the circle, so that a new member of it would read
	// that. Sharing either with somebody new is the sharer's own tap, and so
	// is bringing somebody into a circle that has such a share.
	CircleHasSensitiveShare(circleId string) (bool, error)

	// CircleUserIDs returns everybody who shares a circle with the person,
	// once each and not the person.
	CircleUserIDs(userId string) ([]string, error)

	// ListCirclePeople returns everybody who shares a circle with the person,
	// once each, with their accounts. JoinedAt is the earliest they joined
	// any of the circles the two share; the role is left empty, because it
	// belongs to one circle.
	ListCirclePeople(userId string) ([]*models.CircleMember, error)

	// RecordCircleInvitationSend counts one call that invites somebody against
	// the person who made it, and refuses it with ErrLimitReached when they
	// have sent models.CircleInvitationsPerHourMost in the hour before sentAt.
	// It is called for every invitation however it ends, before anything about
	// the person invited is looked at, and its rows outlive the circles the
	// invitations were to, so neither whether a username exists nor deleting
	// a circle changes the count.
	RecordCircleInvitationSend(inviterUserId string, sentAt time.Time) error

	// CreateCircleInvitation writes an invitation, and says whether it is a
	// new one. A person already in the circle is not invited again and
	// nothing is written (nil, false). A waiting invitation to the same
	// person is renewed with the new role and a new lifetime rather than
	// doubled (false). ErrNotFound when the circle is not there.
	CreateCircleInvitation(invitation *models.CircleInvitation) (*models.CircleInvitation, bool, error)

	// GetCircleInvitation returns one invitation, answered or not, or nil.
	GetCircleInvitation(invitationId string) (*models.CircleInvitation, error)

	// ListCircleInvitationsTo returns the invitations to a person that can
	// still be answered at this moment, the newest first.
	ListCircleInvitationsTo(userId string, now time.Time) ([]*models.CircleInvitation, error)

	// ListCircleInvitationsOf returns the invitations of a circle that can
	// still be answered at this moment, the newest first.
	ListCircleInvitationsOf(circleId string, now time.Time) ([]*models.CircleInvitation, error)

	// AnswerCircleInvitation ends an invitation that can still be answered.
	// Accepting puts the person in the circle with the role they were
	// invited with and returns it; the other answers return nil. ErrNotFound
	// when it was answered already, has expired, or is not there.
	AnswerCircleInvitation(invitationId string, invitationAnswer models.InvitationAnswer, now time.Time) (*models.Circle, error)
}

CircleOperation is circles, who is in them and who has been invited.

Every change to who is in a circle takes the circle's row for update first, so that two changes made at once take turns and the rules that depend on the other members (an admin is always left; a circle whose last member leaves is deleted) are decided on the members as they stand.

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)
	// LockAgentConnection is GetAgentConnection that also locks the row until
	// the transaction ends, waiting for another transaction that holds it: for
	// a caller that reads the connection, does something that must not be done
	// twice at once, and writes it back (refreshing the tokens).
	LockAgentConnection(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.
	// LockSession, TryLockSession and WhileLocked hold an advisory lock
	// across transactions, on a connection of their own: what makes a long
	// sweep, or a name, one instance's at a time (see LockKey).
	LockSession(ctx context.Context, key int64) (func(), error)
	TryLockSession(ctx context.Context, key int64) (func(), bool, error)
	WhileLocked(ctx context.Context, key int64, work func(context.Context) error) (bool, error)
	DescribeSessionLockHolder(ctx context.Context, key int64) (string, error)

	NotifyAgentEvent(payload string) error
	ListenAgentEvents(ctx context.Context) (<-chan string, error)

	// NotifyChatEvent and ListenChatEvents are the same for what happens in a
	// chat, which exists whether or not the server runs an agent.
	NotifyChatEvent(payload string) error
	ListenChatEvents(ctx context.Context) (<-chan string, error)

	// NotifyLocationEvent and ListenLocationEvents are the same for a
	// person's location having been reported: the payload is a LocationEvent
	// holding the person's id and never a coordinate, and the ids of people who
	// were reading it and now cannot, when a share ended.
	NotifyLocationEvent(userId string, endedForUserIds ...string) error
	ListenLocationEvents(ctx context.Context) (<-chan string, error)

	// NotifyShoppingEvent and ListenShoppingEvents are the same for a
	// shopping list having changed: the payload is a ShoppingEvent holding
	// the list's id, and the ids of people who could read it until now.
	NotifyShoppingEvent(shoppingListId string, endedForUserIds ...string) error
	ListenShoppingEvents(ctx context.Context) (<-chan string, error)

	// NotifyChatCallEvent and ListenChatCallEvents are the same for a call
	// in a chat: it rang, somebody joined or left, it ended. The people
	// given are those with a part in it, told so that every tab and phone of
	// theirs on any instance reads the call again.
	NotifyChatCallEvent(callId string, userIds []string) error
	ListenChatCallEvents(ctx context.Context) (<-chan string, error)

	// NotifyFeedEvent and ListenFeedEvents are the same for a card of an
	// agent's feed posted, replaced, settled or dismissed: the payload is a
	// models.FeedEvent naming the person it is for.
	NotifyFeedEvent(event *models.FeedEvent) error
	ListenFeedEvents(ctx context.Context) (<-chan string, error)

	// NotifyPresenceEvent and ListenPresenceEvents carry what a person's
	// tabs and phones report about being shown, to every instance.
	NotifyPresenceEvent(payload string) error
	ListenPresenceEvents(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

	// Items deleted long enough ago are swept outside a transaction, as
	// sessions and tokens are.
	PasswordsScavengeOperation

	// 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. A limit of zero or less lists every one.
	//
	// 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

	// 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)

	// ListMailEmbeddingsPage is one page of all of a mailbox's vectors for a
	// model, newest first, from offset: a search reads every page in turn so
	// that no vector is left out and none but one page is held at a time.
	ListMailEmbeddingsPage(mailboxId, model string, offset, limit int) ([]*MailEmbedding, error)

	// ListMailWithoutEmbedding is the newest messages of a mailbox that
	// have no vector for the model yet, for a backfill. A limit of zero or
	// less lists every one.
	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, or only those filed after since when it is given.
	CountAgentFactsToCheck(agentId string, since *time.Time) (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 FailedAgentTurn added in v0.237.0

type FailedAgentTurn struct {
	ConversationID    string
	ConversationKind  models.AgentConversationKind
	ConversationTitle string
	AgentID           string
	OwnerUsername     string
	OwnerName         string
	FailedAt          time.Time
	ErrorText         string
}

FailedAgentTurn is a turn that ended in a failed note.

type FailedTurnFilter added in v0.237.0

type FailedTurnFilter struct {
	AgentID string
	Since   *time.Time
}

FailedTurnFilter narrows the failed turns.

type FeedDismissSelection added in v0.235.0

type FeedDismissSelection struct {
	// FeedItemIDs are those cards.
	FeedItemIDs []string

	// FeedStackKey is every open card of that stack: its read cards, since
	// an unread one is not in the stack yet.
	FeedStackKey string

	// IsEveryReadCard is every card that is read and has no open choice.
	IsEveryReadCard bool
}

FeedDismissSelection says which cards to dismiss: exactly one of its three fields is set.

type FeedOperation added in v0.230.0

type FeedOperation interface {
	// UpsertAgentFeedItem stores a card. One whose coalesce key matches an
	// open card of the same agent replaces that card's content, moves it to
	// the top and makes it unread; the change says which it was.
	UpsertAgentFeedItem(item *models.AgentFeedItem, now time.Time) (*models.AgentFeedItem, models.FeedChange, error)

	// GetAgentFeedItem is one card, or nil.
	GetAgentFeedItem(feedItemId string) (*models.AgentFeedItem, error)

	// GetOpenAgentFeedItemByCoalesceKey is the agent's card that is not
	// dismissed and has the key, or nil.
	GetOpenAgentFeedItemByCoalesceKey(agentId, coalesceKey string) (*models.AgentFeedItem, error)

	// FindOpenAgentFeedItemBySourceURL is the agent's card, not dismissed and
	// posted since the time, that lists the page among its source links, or
	// nil: a card about it is not posted twice.
	FindOpenAgentFeedItemBySourceURL(agentId, sourceUrl string, since time.Time) (*models.AgentFeedItem, error)

	// ListAgentFeedItems is a person's feed, newest first, at most limit
	// entries, after the cursor when there is one, and the cursor of the page
	// after this one, nil when this is the last. An entry is a card that
	// stands alone or the newest card of a stack. Dismissed cards only when
	// asked for, and cards past their expiry never.
	ListAgentFeedItems(userId string, cursor *models.FeedCursor, limit int, includeDismissed bool, now time.Time) ([]*models.AgentFeedItem, *models.FeedCursor, error)

	// ListUnreadAgentFeedItems is the feed's entries the person has not
	// read: a card not yet read, and a stack holding one, newest first.
	ListUnreadAgentFeedItems(userId string, cursor *models.FeedCursor, limit int, now time.Time) ([]*models.AgentFeedItem, *models.FeedCursor, error)

	// ListDismissedAgentFeedItems is a person's dismissed cards that have not
	// expired, the most recently dismissed first, at most limit, after the
	// cursor when there is one, and the cursor of the next page, nil on the
	// last. A stack is not folded: each dismissed card is an entry.
	ListDismissedAgentFeedItems(userId string, cursor *models.FeedCursor, limit int, now time.Time) ([]*models.AgentFeedItem, *models.FeedCursor, error)

	// ListUnsettledAgentFeedItemsBySource is the agent's cards of a source
	// that are neither chosen nor dismissed.
	ListUnsettledAgentFeedItemsBySource(agentId string, feedSourceKind models.FeedSourceKind, feedSourceId string) ([]*models.AgentFeedItem, error)

	// ListGoalCardReactions is what the person did with each card a goal
	// posted, the oldest card first: liked, discussed (a message of theirs
	// points the agent at it), acted on, dismissed, read. Cards that have
	// expired are gone and are not counted.
	ListGoalCardReactions(agentId, goalId string) ([]*models.GoalCardReaction, error)

	// ListAgentFeedStackItems is the cards of one stack from the offset: those
	// with a position first, the lowest first, then the rest newest first. It
	// says where the next page starts, or -1 on the last. A stack is its read
	// cards unless the selection says otherwise: an unread card is an entry of
	// the feed on its own until it is read.
	ListAgentFeedStackItems(userId, feedStackKey string, offset, limit int, selection *FeedStackSelection, now time.Time) ([]*models.AgentFeedItem, int, error)

	// CountAgentFeedStacks is what each of the stacks holds, by key: the read
	// cards in it that are not dismissed or expired.
	CountAgentFeedStacks(userId string, feedStackKeys []string, now time.Time) (map[string]*models.FeedStackCounts, error)

	// CountUnreadAgentFeedItems is how many of a person's cards are neither
	// read, dismissed nor expired.
	CountUnreadAgentFeedItems(userId string, now time.Time) (int, error)

	// CountAgentFeedItemsInRun is how many cards a run conversation posted.
	CountAgentFeedItemsInRun(runConversationId string) (int, error)

	// UpdateAgentFeedItem changes what a card says; the choice made on it,
	// its readings and its likes are not part of that.
	UpdateAgentFeedItem(feedItemId string, modify func(*models.AgentFeedItem) error, now time.Time) (*models.AgentFeedItem, error)

	// SettleAgentFeedItem records the choice made on a card and what came of
	// it, and says whether this call was the one that did: a card is settled
	// once.
	SettleAgentFeedItem(feedItemId string, settlement *models.FeedSettlement, now time.Time) (bool, error)

	// ResolveAgentFeedItem marks a card resolved and says whether this call
	// was the one that did: a card is resolved once, so the first resolution
	// and its note stand. The card does not move, become unread or expire
	// later.
	ResolveAgentFeedItem(feedItemId string, resolution *models.FeedResolution, now time.Time) (bool, error)

	// UnresolveAgentFeedItem takes the mark off and says whether the card was
	// resolved.
	UnresolveAgentFeedItem(feedItemId string, now time.Time) (bool, error)

	// SetAgentFeedItemOutcome writes the line a chosen card ends with and
	// says the turn behind it is over.
	SetAgentFeedItemOutcome(feedItemId, outcomeText string, now time.Time) error

	// SetAgentFeedItemLiked records a like or an unlike.
	SetAgentFeedItemLiked(feedItemId string, isLiked bool, now time.Time) error

	// MarkAgentFeedItemsRead marks the person's cards read and says how many
	// were newly read.
	MarkAgentFeedItemsRead(userId string, feedItemIds []string, now time.Time) (int, error)

	// DismissAgentFeedItems closes the person's cards the selection names
	// and answers the ones this call closed; a card already closed is left
	// out. A selection by every read card leaves out a decision still waiting
	// for an answer.
	DismissAgentFeedItems(userId string, selection *FeedDismissSelection, now time.Time) ([]*models.AgentFeedItem, error)

	// RestoreAgentFeedItems brings back the person's dismissed cards and
	// answers the ones this call brought back, still read. A card a dismiss
	// choice settled has the answer cleared, so it can be answered again; one
	// answered with an action keeps its answer, since the action was carried
	// out. A card whose coalesce key a card that is not dismissed holds is
	// left out, as is one that expired.
	RestoreAgentFeedItems(userId string, feedItemIds []string, now time.Time) ([]*models.AgentFeedItem, error)

	// DismissAgentFeedItemsAnsweredBefore dismisses every card answered with a
	// choice before the time that is not dismissed yet, and answers them.
	DismissAgentFeedItemsAnsweredBefore(before, now time.Time) ([]*models.AgentFeedItem, error)

	// DeleteAgentFeedItem removes a card for good: one the agent took back
	// is not among the dismissed cards to be restored.
	DeleteAgentFeedItem(feedItemId string) error

	// ExpireAgentFeedItems deletes cards that expired before the time, and
	// says how many.
	ExpireAgentFeedItems(before time.Time) (int64, error)
}

FeedOperation keeps the cards of an agent's feed: what it said without being asked, newest first. See docs/planning/agent-feed-execplan.md.

type FeedStackSelection added in v0.251.0

type FeedStackSelection struct {
	// IsDismissedIncluded adds the dismissed cards.
	IsDismissedIncluded bool

	// IsUnreadIncluded adds the unread cards, which the feed shows on their
	// own: for counting what was posted to the stack.
	IsUnreadIncluded bool
}

FeedStackSelection says which of a stack's cards to read besides its open, read ones.

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 FinanceImportOperation added in v0.249.0

type FinanceImportOperation interface {
	// SetFinanceTransactionsAgentJob records the import job that inserted
	// the finance transactions, which the caller has just inserted.
	SetFinanceTransactionsAgentJob(agentId string, financeTransactionIds []string, agentJobId string) error

	// ListFinanceImportRecords is what each of the jobs created, by job id;
	// a job that created nothing is not in the map.
	ListFinanceImportRecords(agentId string, agentJobIds []string) (map[string]*FinanceImportRecords, error)
}

FinanceImportOperation is what the list of finance imports reads of the rows its jobs created.

type FinanceImportRecords added in v0.249.0

type FinanceImportRecords struct {
	FinanceReceiptIDs       []string
	FinanceTaxFormIDs       []string
	TaxYear                 int // of the first tax form, zero when there is none
	FinanceTransactionCount int
	FinanceAccountIDs       []string
}

FinanceImportRecords is what one import job created: the receipts and tax forms, to open them, how many transactions, and the finance accounts those are on. Rows from before the job was remembered are in none.

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 FinanceShareOperation added in v0.194.0

type FinanceShareOperation interface {
	// ShareFinanceAccount gives a person or a circle a level of access to a
	// finance account of the sharer, or changes the level they have.
	// ErrNotFound unless the account is held by the sharer's agent and, for a
	// person, the two share a circle, or, for a circle, the sharer is in it.
	// ErrInvalidArguments for a level that cannot be given, a grantee that is
	// not exactly one, or the sharer themselves.
	ShareFinanceAccount(sharerUserId string, share *models.FinanceShare) (*models.FinanceShare, error)

	// UnshareFinanceAccount takes one of the owner's shares back. ErrNotFound
	// when the owner has no such share.
	UnshareFinanceAccount(ownerUserId, shareId string) error

	// ListFinanceSharesBy are the shares the person has made, oldest first,
	// with which account each is of and who it is for.
	ListFinanceSharesBy(ownerUserId string) ([]*models.FinanceShare, error)

	// ListFinanceSharesReaching are the shares that reach the person now,
	// oldest first, one per finance account: at the highest level that reaches
	// them, with whose account it is. When a share to the person by name
	// reaches them too, the row is that share, so they can decline it. A share
	// to a person reaches them only while the two still share a circle, and a
	// share to a circle only while both are in it. Not the person's own.
	ListFinanceSharesReaching(userId string) ([]*models.FinanceShare, error)

	// ListReachedFinanceAccounts are the finance accounts of other people that
	// reach the viewer, oldest first, each at the highest level that reaches
	// them; of one owner, or, with an empty identifier, of all of them.
	ListReachedFinanceAccounts(viewerUserId, ownerUserId string) ([]*models.ReachedFinanceAccount, error)

	// ReachFinanceAccount is one finance account of another person as the
	// viewer reaches it, or nil when it is not shared with them (or the
	// person who owns it, or they, can no longer use finance).
	ReachFinanceAccount(viewerUserId, financeAccountId string) (*models.ReachedFinanceAccount, error)

	// ListSharedFinanceSpending is a shared finance account's money out and in
	// by month and spending category, newest month first, for the days from
	// and to ("2006-01-02", either may be empty). ErrNotFound unless the
	// account reaches the viewer at the spending level or better.
	ListSharedFinanceSpending(viewerUserId, financeAccountId, from, to string) ([]*models.SharedFinanceSpendingRow, error)

	// ListSharedFinanceTransactions is a page of a shared finance account's
	// transactions, newest first. ErrNotFound unless the account reaches the
	// viewer at the transactions level.
	ListSharedFinanceTransactions(viewerUserId, financeAccountId string, filter *SharedFinanceTransactionFilter) (*SharedFinanceTransactionPage, error)
}

FinanceShareOperation is who may see which finance account, and how much: a person's finance account shared with another person or with a circle at a level (balance, spending or transactions).

"May this person see this finance account, and at what level" has one answer, ReachFinanceAccount, and every read of a shared account asks it. A caller that compares an account's owner with the person itself is wrong for somebody who left the circle that made the share possible. The reads here return types that have no field for what a level does not show, so that the level is not a thing a caller has to remember to apply.

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)

	// ListAgentGoalsWaitingForMail is the agent's working goals that take a
	// turn when mail they wait for arrives.
	ListAgentGoalsWaitingForMail(agentId string) ([]*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(metSince time.Time, 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)

	// ListAgentNodesOfContact is the pages that say they are about the
	// contact (their contact_id), the most recently changed first.
	ListAgentNodesOfContact(agentId, contactId string, limit int) ([]*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 HealthLockOperation added in v0.183.0

type HealthLockOperation interface {
	// LockHealth waits for, and then holds until the transaction ends, the
	// lock on one person's Health records. A phone that sends a batch again
	// while the first send is still being stored, and an erase at the same
	// moment as a report, would otherwise interleave: the erase would leave
	// the rows the report was about to write.
	LockHealth(userId string) error
}

HealthLockOperation orders the writers of one person's Health data.

type HealthOperation added in v0.183.0

type HealthOperation interface {
	// InsertHealthSamples stores readings and says how many were new. A
	// reading already stored (the same person and HealthKit identifier) adds
	// nothing, which is what lets a phone send a batch again until it knows
	// the server has it. ErrInvalidArguments for a reading with no identifier
	// or kind, one that ends before it starts, or metadata that is not a JSON
	// object. Names are cut to the width of their columns.
	InsertHealthSamples(userId string, samples []*models.HealthSample) (newCount int, err error)

	// DeleteHealthSamples deletes the readings with these HealthKit
	// identifiers, and the routes of the workouts among them, and answers the
	// kind and times of each that was deleted, oldest first. A phone that
	// deleted a reading knows only its identifier; the answer is how it learns
	// which days to work out again. The answer is the same when the phone
	// asks again for readings already deleted, because what was deleted is
	// kept for models.HealthDeletedSampleDays. The summaries of the days are
	// not changed.
	DeleteHealthSamples(userId string, healthSampleIds []string) ([]*models.DeletedHealthSample, error)

	// UpsertHealthDaySummaries stores the days the phone worked out, replacing
	// a day it already had unless that one was worked out later, and says how
	// many days it stored. A summary says when it was worked out
	// (WorkedOutAt), the time of the call when it does not; given a day twice
	// the one worked out later is kept, and the later in the list when they
	// are the same. ErrInvalidArguments for a day that is not a date, a kind
	// with no identifier, a negative count or metadata that is not a JSON
	// object.
	UpsertHealthDaySummaries(userId string, summaries []*models.HealthDaySummary) (int, error)

	// UpsertHealthRoutes stores the paths of workouts, replacing one it
	// already had, and says how many were kept and the identifiers of those
	// left out. A route whose workout the server does not have is left out: it
	// would be a path nobody could reach and that an erase of the workouts
	// could not find. Every route is checked before the first is stored.
	UpsertHealthRoutes(userId string, routes []*models.HealthRoute) (keptCount int, unmatchedHealthSampleIds []string, err error)

	// UpsertHealthCharacteristics stores the facts about the person,
	// replacing the value of a kind it already had.
	UpsertHealthCharacteristics(userId string, characteristics []*models.HealthCharacteristic) error

	// ListHealthTypes lists the kinds of reading the person has, by kind: the
	// readings kept (from the totals the database keeps, not by counting
	// them), the first and last day with a summary and the latest day's
	// summary. A kind with readings and no summary, or a summary and no
	// readings, is listed. Characteristics are not readings and are not here.
	ListHealthTypes(userId string) ([]*models.HealthTypeSummary, error)

	// ForgetDeletedHealthSamples deletes what is kept of deleted readings
	// (the kind and times of each) once it is older than
	// models.HealthDeletedSampleDays, for every person, at most
	// models.HealthDeletedSampleForgetMost rows at a time, the oldest first.
	// Every report and every erase calls it, so that the table does not grow
	// with the deletions of a person who never deletes again. It answers how
	// many rows it deleted.
	ForgetDeletedHealthSamples() (int, error)

	// ListHealthTypeNames lists the kinds the person has readings or day
	// summaries of: from the totals the database keeps, and the kinds of the
	// day summaries, found one kind at a time in the index.
	ListHealthTypeNames(userId string) ([]string, error)

	// ListHealthPeriods adds up a kind's days from fromDay to toDay, both
	// included and written YYYY-MM-DD, into days, weeks that start on Monday,
	// or months, oldest first. A period with no day summarized is not in the
	// answer. See HealthPeriodSummary for how the days add up. The unit is the
	// one the last day was sent in, empty when there are no days.
	ListHealthPeriods(userId, healthType, fromDay, toDay string, period health.Period) (periods []*models.HealthPeriodSummary, quantityUnit string, err error)

	// ListHealthSamples pages the readings of one kind that started in the
	// range (either end may be nil), newest first. limitCount is at least one.
	// Whether a reading follows the page is found by reading one more, and
	// the count is only made when shouldCountTotal: with no range it is the
	// total the database keeps, and with one it counts at most
	// models.HealthSampleCountMost.
	ListHealthSamples(userId, healthType string, from, until *time.Time, limitCount, offset int, shouldCountTotal bool) (*models.HealthSamplePage, error)

	// GetHealthRoute is the path of a workout, or ErrNotFound.
	GetHealthRoute(userId, healthSampleId string) (*models.HealthRoute, error)

	// GetHealthChoices is what the person has decided about their Health, read
	// from their account alone. ErrNotFound for a person who does not exist.
	GetHealthChoices(userId string) (*models.HealthChoices, error)

	// GetHealthStatus is what the person's Health holds and what they have
	// decided about it. ErrNotFound for a person who does not exist.
	GetHealthStatus(userId string) (*models.HealthStatus, error)

	// SetCanAgentReadHealth turns the agent's health tool on or off for the
	// person. ErrNotFound for a person who does not exist.
	SetCanAgentReadHealth(userId string, canAgentReadHealth bool) error

	// EraseHealthData deletes the person's readings, summaries and routes of
	// one kind, and the characteristic of that name, and answers how many
	// readings that was. With an empty kind it deletes all of them and every
	// characteristic, and records the time as when the person erased their
	// Health, which the phone reads to stop sending. Sharing and the agent
	// switch are kept.
	EraseHealthData(userId, healthType string) (erasedSampleCount int, err error)
}

HealthOperation is a person's Apple Health data: the readings their phone copied, the summary of each day the phone worked out, the paths of their workouts, the facts about them that HealthKit keeps once, and what the person has decided about all of it. All of it belongs to one person and every method takes that person, so that reading or changing somebody else's is not a question of which call to make.

The server never adds readings up to make a day: only the phone can merge an iPhone and a Watch counting the same walk the way the Health app does, so a day is what the phone sent. What sharing reaches is in HealthShareOperation.

type HealthShareOperation added in v0.183.0

type HealthShareOperation interface {
	// SetHealthShare gives a person or a circle the categories of the sharer's
	// Health, and answers the share as stored. Sharing again with the same
	// grantee replaces the categories. An empty list takes the share back and
	// answers nil, also when there was none. ErrInvalidArguments for a
	// category nobody knows, a grantee that is both or neither, or the sharer
	// themselves. ErrNotFound for a person the sharer shares no circle with
	// and for a circle the sharer is not in, which is all the caller says.
	SetHealthShare(sharerUserId string, share *models.HealthShare) (*models.HealthShare, error)

	// ListHealthShares are the shares the person has made, oldest first, with
	// who each is for.
	ListHealthShares(sharerUserId string) ([]*models.HealthShare, error)

	// ListHealthSharesReaching are the shares that reach the viewer now,
	// oldest first, with whose Health each is. A share to a person reaches
	// them only while the two still share a circle, and a share to a circle
	// only while both are in it. Not the viewer's own.
	ListHealthSharesReaching(viewerUserId string) ([]*models.HealthShare, error)

	// GetSharedHealthCategories are the categories of the owner's Health that
	// the shares reaching the viewer give together, in the order of the Health
	// app, and none for anything else. The owner is not asked about: a person
	// reads their own Health without a share.
	GetSharedHealthCategories(viewerUserId, ownerUserId string) ([]string, error)
}

HealthShareOperation is who may see whose Health, and how much: a person's Health shared with another person or with a circle by Health category, as a location is shared at a level.

What a share gives is the day summaries of the kinds in its categories and the list of those kinds, never the readings, the routes or the characteristics. "Which categories of this person's Health may that person see" has one answer, GetSharedHealthCategories, and every door asks it. A caller that compares the two user ids itself is wrong for a person who left the circle that made the share possible.

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)

	// ListAgentConversationActivityBetween is what was said with the agent in
	// a stretch of time: for each of the person's own conversations (the main
	// one and the named ones, not a run's transcript or a chat) that had a
	// message from the person, or an answer in words, created from from up to
	// but not including until, how many such messages and the times of the
	// first and the last, earliest first.
	ListAgentConversationActivityBetween(agentId string, from, until time.Time) ([]*AgentConversationActivity, 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)

	// ListMailInsightHeads is the newest messages of a mailbox received
	// since the moment given that have an insight, with just enough of it
	// to choose from: the category, whether sorting asked for an extract,
	// and the subject. Only messages still in a folder that is not Junk,
	// Trash, Drafts or Sent, and whose category is not one of those left
	// out. For the one look back over past mail for follow-ups.
	ListMailInsightHeads(mailboxId string, since time.Time, leftOutCategories []string, limit int) ([]*MailInsightHead, 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)

	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.
	// What was said in a private turn (see privateturn) is searched only with
	// isPrivateIncluded, which is for the person's own screen: a search that
	// says where some words are is a way to read them out one letter at a time.
	SearchAgentConversations(agentId, query string, limit int, isPrivateIncluded bool) ([]*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)
	// ListLatestAgentMessages is the newest limit messages of a
	// conversation, oldest first, without their reactions.
	ListLatestAgentMessages(conversationId string, limit int) ([]*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)

	// ListAgentOwnTurnFiles is the answers of share_file in turns of the
	// agent's own in a conversation, after the first message given and up to
	// and including the second, oldest first: the files it handed the person
	// there, which a chat app is sent beside what the agent said.
	ListAgentOwnTurnFiles(conversationId, afterMessageId, throughMessageId string) ([]*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)

	// GetAgentPersonWordAfter is the first thing the person wrote in a
	// conversation after a message and before a moment, passing over the
	// turns the agent opened itself. Nil when they wrote nothing.
	GetAgentPersonWordAfter(conversationId, afterMessageId string, before time.Time) (*models.AgentMessage, 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 JournalOperation added in v0.202.0

type JournalOperation interface {
	// GetJournalDay is one day's row; ErrNotFound when nothing was ever kept
	// for it.
	GetJournalDay(userId, day string) (*models.JournalDay, error)

	// ListJournalDays is the person's days from fromDay to untilDay (both
	// included; empty for no bound), newest first, that have anything in them
	// (facts with activity, words or a mood), and how many there are in all.
	ListJournalDays(userId, fromDay, untilDay string, offset, limit int) ([]*models.JournalDay, int, error)

	// ListJournalDaysCountedBefore is the person's days, newest first, whose
	// facts were worked out an older way than factsVersion
	// (models.JournalFactsVersion), at most limit of them.
	ListJournalDaysCountedBefore(userId string, factsVersion, limit int) ([]string, error)

	// FirstJournalDay is the earliest day with anything in it, empty for
	// none.
	FirstJournalDay(userId string) (string, error)

	// SetJournalWords replaces a day's words. The save is refused with
	// ErrJournalChanged unless the day's words were last saved at
	// baseModifiedAt (compared to the microsecond), or, with nil, were never
	// saved.
	SetJournalWords(userId, day, timeZone, words string, baseModifiedAt *time.Time, at time.Time) (*models.JournalDay, error)

	// SetJournalMood sets or clears (moodLevel nil) a day's mood. A mood from
	// Apple Health (moodSource health) never replaces one the person chose.
	SetJournalMood(userId, day, timeZone string, moodLevel *int, moodWords string, moodSource models.JournalMoodSource, at time.Time) (*models.JournalDay, error)

	// PutJournalFacts stores a day's numbers, making the row when the day has
	// activity and keeping no row for a day with nothing in it.
	PutJournalFacts(userId, day, timeZone string, facts models.JournalFacts, at time.Time) error

	// PutJournalWeather stores a day's weather; nil clears it.
	PutJournalWeather(userId, day string, weather *models.JournalWeather) error

	// GetJournalPeriod is a period's row; ErrNotFound when nothing was ever
	// kept for it.
	GetJournalPeriod(userId string, periodKind models.JournalPeriodKind, periodStart string) (*models.JournalPeriod, error)

	// ListJournalPeriods is the person's periods of a kind from fromStart to
	// untilStart (both included), oldest first.
	ListJournalPeriods(userId string, periodKind models.JournalPeriodKind, fromStart, untilStart string) ([]*models.JournalPeriod, error)

	// SetJournalLookingBack replaces a period's looking back, with the same
	// check as SetJournalWords.
	SetJournalLookingBack(userId string, periodKind models.JournalPeriodKind, periodStart, lookingBack string, baseModifiedAt *time.Time, at time.Time) (*models.JournalPeriod, error)

	// RequestJournalTouchUp turns touching up on for a target (or asks for
	// another version), with how the instruction (nil keeps the last), and
	// marks it waiting (TouchUpRequestedAt). ErrInvalidArguments when the
	// original is empty.
	RequestJournalTouchUp(userId string, target models.JournalTarget, timeZone string, how *string, at time.Time) error

	// PutJournalTouchedUp stores a touched-up text made from the original
	// whose digest is fromDigest (models.JournalWordsDigest), and clears the
	// wait. It stores nothing, and answers false, when touching up was turned
	// off meanwhile.
	PutJournalTouchedUp(userId string, target models.JournalTarget, touchedUp, fromDigest string) (bool, error)

	// StopJournalTouchUp turns touching up off for a target and deletes the
	// touched-up text.
	StopJournalTouchUp(userId string, target models.JournalTarget) error

	// ListJournalTouchUpsWaiting is the targets of a person whose touch-up was
	// asked for and not yet made, or whose touched-up text was made from
	// words that have changed since.
	ListJournalTouchUpsWaiting(userId string) ([]models.JournalTarget, error)

	// PutJournalNarrative stores what a writing of a target made: the
	// headline, the narrative, the digest of what it was written from, the
	// cover photo (days) or chapters (years), and the choices, which replace
	// the target's earlier agent choices except the hidden ones (a choice of
	// a record the person hid is kept hidden). It clears the failure and the
	// wait.
	PutJournalNarrative(userId string, target models.JournalTarget, timeZone string, narrative models.JournalNarrativeWriting, at time.Time) error

	// PutJournalNarrativeFailure records why a writing was refused and clears
	// the wait.
	PutJournalNarrativeFailure(userId string, target models.JournalTarget, timeZone, failure string, at time.Time) error

	// RequestJournalNarrative marks a target as waiting to be written now
	// (NarrativeRequestedAt); for a day it also sets IsNarrativeRequested.
	RequestJournalNarrative(userId string, target models.JournalTarget, timeZone string, at time.Time) error

	// ListJournalNarrativesWaiting is the targets of a person waiting to be
	// written now, oldest request first.
	ListJournalNarrativesWaiting(userId string) ([]models.JournalTarget, error)

	// DeleteJournalNarrative deletes a target's headline, narrative and
	// agent choices that are not hidden.
	DeleteJournalNarrative(userId string, target models.JournalTarget) error

	// AddJournalCorrection adds a correction to a target's narrative and marks
	// it waiting to be written. A correction the narrative already keeps, the
	// same words but for case and spacing, adds nothing and isAdded is false.
	AddJournalCorrection(userId string, target models.JournalTarget, timeZone, correctionText string, at time.Time) (isAdded bool, err error)

	// RemoveJournalCorrection removes the correction at correctionIndex and
	// marks the target waiting to be written. ErrNotFound for an index that
	// is not there.
	RemoveJournalCorrection(userId string, target models.JournalTarget, correctionIndex int, at time.Time) error

	// ListJournalLinks is the links of a day (journalDayId) or a period
	// (journalPeriodId), by rank.
	ListJournalLinks(userId, journalDayId, journalPeriodId string) ([]*models.JournalLink, error)

	// PinJournalRecord pins a record to a day (making its row), or answers the
	// pin that is already there. A record the agent had chosen becomes the
	// person's pin.
	PinJournalRecord(userId, day, timeZone string, recordKind models.AgentRecordKind, recordId, linkReason string, at time.Time) (*models.JournalLink, error)

	// RemoveJournalLink deletes a pin, or hides an agent choice. ErrNotFound
	// for a link that is not the person's.
	RemoveJournalLink(userId, linkId string) error

	// SearchJournal is the days and periods whose words, looking back,
	// touched-up text, headline or narrative contain the query (any case),
	// newest first, and how many there are.
	SearchJournal(userId, query string, offset, limit int) ([]*models.JournalSearchHit, int, error)

	// GetJournalSettings and SetJournalSettings are what the person decided.
	GetJournalSettings(userId string) (*models.JournalSettings, error)
	SetJournalSettings(userId string, settings models.JournalSettings) error

	// EraseJournal deletes every day, period and link of the person and says
	// how many of each went.
	EraseJournal(userId string) (dayCount, periodCount, linkCount int, err error)
}

JournalOperation is a person's journal: their days, the weeks, months and years above them, and the records those link to. All of it belongs to one person and every method takes that person, so that reading or changing somebody else's is not a question of which call to make.

A day is YYYY-MM-DD. A day's row is made the first time something is kept for it (words, a mood, facts); timeZone is given then and kept, so a later change of the person's zone does not move the day. Methods that may make the row take it; on a row that exists it is ignored.

A target names a day or a period (models.JournalTarget). Changing a day's or a period's own parts never touches the records it links to.

type JournalSourceOperation added in v0.202.0

type JournalSourceOperation interface {
	// LatestJournalSourceTimeBefore is the latest time before the given one at
	// which any of the sources a journal day reads has something of the
	// person's: a photo, a visit, a mail, a recording, a message with the
	// agent or in a chat, a document, a calendar event, a transaction, a
	// Health day or a trip of theirs to the shops. Nil when there is nothing earlier. It is how the journal
	// walks back over past days without trying every empty one: the day it
	// finds is the next to work out.
	//
	// A source's own limits are not applied (a document a day does not count
	// because it does not involve the person still counts here), so a day it
	// names may turn out to have nothing in it; the journal then moves on to
	// the day before.
	//
	// A chat in the agent's documents counts when one of chatNames (the
	// person's username and the words of their name, lowered) took part in it
	// and it is an exchange of two posts or more, the rule the journal reads
	// a chat by; an archive of other people's channels is not the person's
	// day.
	LatestJournalSourceTimeBefore(userId, agentId string, chatNames []string, before time.Time) (*time.Time, error)
}

JournalSourceOperation answers, for a person, where their sources of a journal day end. The journal reads each source by the day's time range (see JournalOperation); this is the one question that has no day to ask about yet.

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)

	// ListAgentDocumentChunkTexts is the chunk texts of these documents, each
	// document's in order: the transcripts of a day's coding stretches, read
	// whole at once.
	ListAgentDocumentChunkTexts(agentId string, documentIds []string) (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)

	// ListAgentChunkPosts is the posts of each of these chat units in the
	// order they were written: the clock and author of every line that begins
	// "15:04 author: ", found by the database so that a day of transcripts is
	// not read to know who wrote when.
	ListAgentChunkPosts(agentId string, documentIds []string) (map[string][]models.AgentChunkPost, 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 LinkPreview added in v0.191.0

type LinkPreview struct {
	// URL is the page's address without its tracking parameters or fragment.
	URL string `gorm:"column:url;primaryKey;type:text"`

	Title       string `gorm:"column:title;type:text"`
	Description string `gorm:"column:description;type:text"`
	SiteName    string `gorm:"column:site_name;type:text"`

	// ImageFileID is the file store's name for the page's picture, empty when
	// there is none.
	ImageFileID       string `gorm:"column:image_file_id;size:128"`
	ImageSizeBytes    int    `gorm:"column:image_size_bytes"`
	ImageWidthPixels  int    `gorm:"column:image_width_pixels"`
	ImageHeightPixels int    `gorm:"column:image_height_pixels"`

	FetchedAt time.Time `gorm:"column:fetched_at"`

	// FetchFailure is empty for a page that was read, and a short word for why
	// when it could not be.
	FetchFailure string `gorm:"column:fetch_failure;type:text"`
}

LinkPreview is what one page said about itself when it was last fetched.

func (*LinkPreview) TableName added in v0.191.0

func (self *LinkPreview) TableName() string

type LinkPreviewOperation added in v0.191.0

type LinkPreviewOperation interface {
	// ListLinkPreviews is what is cached for these addresses, keyed by
	// address. An address that was never fetched is absent.
	ListLinkPreviews(urls []string) (map[string]*LinkPreview, error)

	// HasLinkNotWrittenByAgent says whether any of the texts appears, exactly
	// and anywhere in the text, in a message of the conversation that its agent
	// did not write: a person's, or what a tool answered. For a chat that is
	// its messages by a person and not deleted; for any other conversation,
	// its user and tool messages, less those opening a turn the agent took on
	// its own. It is the rule
	// that decides which links the server may fetch for a card: a reply can be
	// made to carry what the agent read in a link's query, and fetching it
	// would send that to whoever runs the site.
	HasLinkNotWrittenByAgent(conversation *models.AgentConversation, texts ...string) (bool, error)

	// HasLinkInToolAnswer says whether any of the texts appears, exactly, in
	// what a tool answered in the conversation. It decides which pages the
	// server may fetch a picture from for a card the agent posts, on the same
	// grounds as HasLinkNotWrittenByAgent.
	HasLinkInToolAnswer(conversationId string, texts ...string) (bool, error)

	// GetLinkPreviewByImageFile is the row whose picture is stored under the
	// file, or nil when no row names it.
	GetLinkPreviewByImageFile(imageFileId string) (*LinkPreview, error)

	// SaveLinkPreview keeps a page's preview, replacing the row for the same
	// address, and says which picture file the row named before, so the caller
	// can remove it once this commits. Empty when the row is new or named none.
	SaveLinkPreview(preview *LinkPreview) (replacedImageFileId string, err error)

	// ListLinkPreviewsFetchedBefore is the oldest rows fetched before the
	// time, at most limit of them, for removal.
	ListLinkPreviewsFetchedBefore(before time.Time, limit int) ([]*LinkPreview, error)

	// DeleteLinkPreviews removes the rows for these addresses.
	DeleteLinkPreviews(urls []string) error
}

LinkPreviewOperation is the cache of what web pages say about themselves. Fetching a page is the caller's (internal/linkpreview); a row is the answer, or the record that there was none.

type LocationEvent added in v0.175.0

type LocationEvent struct {
	UserID string `json:"userId"`

	// EndedForUserIDs are people who could read this person's location until
	// now and cannot any longer, because a share ended. They are told too,
	// though they may not see the location any more, so that a map they have
	// open reads it again and drops it.
	EndedForUserIDs []string `json:"endedForUserIds,omitempty"`
}

LocationEvent is what travels on LocationEventChannel: whose location changed and nothing else. Coordinates never go through NOTIFY; a listener reads the latest position from the tables, checking what the viewer may see.

type LocationGrantee added in v0.175.0

type LocationGrantee struct {
	UserID  string
	AgentID string

	// SharedAt is when the earliest share that reaches them was made. What the
	// owner did before it is not theirs to be told.
	SharedAt time.Time
}

LocationGrantee is a person the owner's location reaches, and the agent row their phones hang from.

type LocationKnowledgeOperation added in v0.175.0

type LocationKnowledgeOperation interface {
	// EnsureLocationSource answers the agent's location source, making it,
	// switched on, the first time. It has no schedule: nothing reads it from
	// anywhere, the documents are put in directly.
	EnsureLocationSource(agentId string) (*models.AgentKnowledgeSource, error)

	// PutLocationDayDocument files the text of one finished day. The day is
	// its start in the person's own time zone. Text that is the same as what
	// is filed already changes nothing, so the day is not read again, and
	// isChanged says whether anything was written.
	PutLocationDayDocument(agentId, sourceId string, day time.Time, text string) (isChanged bool, err error)

	// DeleteLocationDayDocument deletes the document of one day, with its
	// chunks, when there is one: a day whose visits are all gone has nothing
	// to say, and what it said before must not stay filed.
	DeleteLocationDayDocument(sourceId string, day time.Time) error

	// GetLatestLocationDayStart answers when the newest day filed in the
	// source began, or nil when none is.
	GetLatestLocationDayStart(sourceId string) (*time.Time, error)

	// GetEarliestLocationDayStart answers when the oldest day filed in the
	// source began, or nil when none is.
	GetEarliestLocationDayStart(sourceId string) (*time.Time, error)
}

LocationKnowledgeOperation is what the memory is told of where a person went: one source for each agent, and one document in it for each finished day. The text of a day is written by the caller from the person's visits; the dream's reading takes the documents like any others.

type LocationLockOperation added in v0.175.0

type LocationLockOperation interface {
	// LockLocation waits for, and then holds until the transaction ends, the
	// lock on one person's location records. A phone that sends a batch again
	// while the first send is still being stored, and a check-in at the same
	// moment as a report, would otherwise both find no visit for a key or no
	// place at one position, and each make one.
	LockLocation(userId string) error
}

LocationLockOperation orders the writers of one person's location.

type LocationNotificationMuteOperation added in v0.198.0

type LocationNotificationMuteOperation interface {
	// MuteLocationNotifications mutes, for userId, the notices of where
	// mutedUserId arrives and leaves, until mutedUntil, or until unmuted when
	// it is nil. Muting again changes the end. ErrInvalidArguments for an end
	// that is not after now or is more than LocationNotificationMuteLongest
	// after it, or for muting oneself.
	MuteLocationNotifications(userId, mutedUserId string, mutedUntil *time.Time, now time.Time) (*models.LocationNotificationMute, error)

	// UnmuteLocationNotifications ends the mute, and says whether one was in
	// effect at now.
	UnmuteLocationNotifications(userId, mutedUserId string, now time.Time) (isUnmuted bool, err error)

	// GetLocationNotificationMutes is the person's mutes of the people named
	// that are in effect at the instant, by the muted person's id. A person
	// not muted is not in the answer.
	GetLocationNotificationMutes(userId string, mutedUserIds []string, at time.Time) (map[string]*models.LocationNotificationMute, error)

	// ListLocationNotificationMuters is the ids of the people who have muted
	// mutedUserId's notices at the instant.
	ListLocationNotificationMuters(mutedUserId string, at time.Time) ([]string, error)
}

LocationNotificationMuteOperation is the people whose arrivals and departures a person muted. docs/subsystems/location.md says what a mute does; what is here is only the rows, one for each pair of people.

type LocationOperation added in v0.175.0

type LocationOperation interface {
	// InsertLocationPoints stores positions and says how many were new. A
	// position already stored (the same person, instant and source) adds
	// nothing, which is what lets a phone send a batch again until it knows
	// the server has it. ErrInvalidArguments for coordinates that are not on
	// the earth, a negative accuracy or an unknown source.
	InsertLocationPoints(userId string, points []*models.LocationPoint) (newCount int, err error)

	// GetLatestLocationPoint is the most recently measured position, or nil
	// when there is none.
	GetLatestLocationPoint(userId string) (*models.LocationPoint, error)

	// GetLatestLocationReportAt is the latest time the person's phone reported
	// anything: the latest of a position's measured time and the arrival or
	// departure of a visit. It is the zero time when there is none.
	GetLatestLocationReportAt(userId string) (time.Time, error)

	// GetLatestLocationPoints is GetLatestLocationPoint for many people in one
	// query. A person with no position is not in the answer.
	GetLatestLocationPoints(userIds []string) (map[string]*models.LocationPoint, error)

	// ListLocationPoints reads the positions measured in a range, oldest
	// first, at most limitCount of them. A caller that must refuse a range
	// holding more asks for one more than it will take.
	ListLocationPoints(userId string, from, until time.Time, limitCount int) ([]*models.LocationPoint, error)

	// FindPlaceAt is the person's place whose radius holds the point, the
	// nearest center first, or nil when there is none.
	FindPlaceAt(userId string, latitudeDegrees, longitudeDegrees float64) (*models.Place, error)

	// ListPlacesNear is the person's places that hold the point or whose
	// center is within radiusMeters of it, nearest first, at most limitCount.
	// Each carries its distance.
	ListPlacesNear(userId string, latitudeDegrees, longitudeDegrees, radiusMeters float64, limitCount int) ([]*PlaceDistance, error)

	// FindPlaceIDsByOSM maps the OpenStreetMap objects the person already has
	// a place for to that place. A place with no OpenStreetMap object is never
	// in the answer.
	FindPlaceIDsByOSM(userId string, references []OSMReference) (map[OSMReference]string, error)

	// SummarizePlaceVisits counts the visits to each of the places and says
	// when the last one was, for the places that have any.
	SummarizePlaceVisits(userId string, placeIds []string) (map[string]*PlaceVisitSummary, error)

	// CreatePlace makes a place for the person. ErrInvalidArguments for a
	// position off the earth, a radius outside what a person can set (zero
	// takes the default), or a label or OpenStreetMap type nobody knows. Names,
	// categories and addresses are cut to the width of their columns and have
	// line breaks and control characters taken out, as SetPlaceNamed does.
	CreatePlace(userId string, place *models.Place) (*models.Place, error)

	// SavePlace changes a place and answers it as it is now. A place moved
	// farther than its radius loses what the provider said about the old
	// position (the OpenStreetMap object, name and address, and the time it was
	// named), so that it is named again. ErrNotFound unless it is the person's,
	// ErrInvalidArguments for a change that is not allowed.
	SavePlace(userId, placeId string, changes PlaceChanges) (*models.Place, error)

	// GetPlace is one of the person's places, or ErrNotFound.
	GetPlace(userId, placeId string) (*models.Place, error)

	// ForgetPlace deletes a place and every visit to it, and with them the
	// location journal documents of the days those visits were on, in the
	// same transaction. ErrNotFound unless it is the person's.
	ForgetPlace(userId, placeId string) error

	// ForgetPlaceVisit deletes one of the person's visits, one they say did
	// not happen, and with it the location journal documents of the days it
	// was on. The place stays, unless no visit to it is left and the person
	// neither named nor labeled it. ErrNotFound unless it is the person's;
	// ErrInvalidArguments for a visit in progress, which the phone would
	// report the end of as a visit again.
	ForgetPlaceVisit(userId, placeVisitId string) error

	// ListPlaces pages the person's places, each with its number of visits and
	// the time of the last one: labeled places first, then the ones the
	// person named, then the rest, each group by last visit. nextOffset is
	// the offset that reads on, and zero when this page is the last.
	ListPlaces(userId string, filter PlaceFilter) (places []*models.Place, nextOffset int, err error)

	// PutPlaceVisit stores a visit, or completes the one stored under the same
	// client_visit_key: a later report fills in the departure, and the
	// arrival if it was missing. Visits to one place less than ten minutes
	// apart are then joined into one, so that iOS splitting a visit in two
	// does not show as two; the key of a visit that was joined into another
	// stays known, and a report under it completes the visit it became. A
	// departure before the arrival already stored is the arrival. A new visit
	// with an arrival ends every other visit of the person that is still open
	// and began no later, at that arrival. An arrival delivered after the
	// visits that followed it is ended by NormalizePlaceVisits, which the caller
	// runs once its report is stored. isNew is whether the key was
	// unknown. The visit passed in is updated to what is stored. ErrNotFound
	// unless the place is the person's, ErrInvalidArguments for a visit with
	// neither time or that ends before it starts.
	PutPlaceVisit(userId string, visit *models.PlaceVisit) (isNew bool, err error)

	// GetPlaceVisitByClientKey is the visit the phone calls by this key, or the
	// visit that one was joined into, with its place, or nil when there is none.
	GetPlaceVisitByClientKey(userId, clientVisitKey string) (*models.PlaceVisit, error)

	// GetPlaceVisitByArrival is the person's visit from iOS visit monitoring
	// (VisitSourceVisit) that arrived in the same second, or nil when there is
	// none. iOS reports a visit again with its departure and a position it
	// has made more exact, and the phone keys a visit by its position, so the
	// departure can come under a key the server has not seen.
	GetPlaceVisitByArrival(userId string, arrivedAt time.Time) (*models.PlaceVisit, error)

	// DeletePassByVisits deletes the person's pass-bys that ended in the
	// range, or near enough to it for a position in it to tell of them, and
	// answers the ids of the visits it deleted. A pass-by is a
	// visit from a place's circle (VisitSourceRegion) shorter than
	// PassByDurationMost, with a position near it at
	// PassBySpeedMetersPerSecondLeast or faster and none during it at
	// PassByStoppedSpeedMetersPerSecondMost or slower: the phone crossing the
	// circle on the way somewhere else. Call it once the positions and the
	// visits of a report are stored.
	DeletePassByVisits(userId string, from, until time.Time) ([]string, error)

	// GetOpenPlaceVisit is the visit in progress, the latest one with no
	// departure, with its place; nil when there is none.
	GetOpenPlaceVisit(userId string) (*models.PlaceVisit, error)

	// GetOpenPlaceVisits is GetOpenPlaceVisit for many people in two queries.
	// A person with no visit in progress is not in the answer.
	GetOpenPlaceVisits(userIds []string) (map[string]*models.PlaceVisit, error)

	// NormalizePlaceVisits makes the person's visits that touch the range, and
	// the ten minutes round it, a sequence that does not overlap, whatever
	// order the reports of them arrived in: ordered by arrival, a visit still
	// open ends at the arrival of the next visit, a visit whose departure runs
	// past the arrival of the next visit at another place ends at that
	// arrival, a joined visit that has a visit at another place begin inside
	// it is split in two there, a departure from a watched place with no
	// arrival noticed inside a visit at another place moves to before that
	// visit, one that came less than PassByDurationMost after the visit before
	// it ended is taken out (into that visit when it was to the same place),
	// any departure with no arrival less than PassByDurationMost from the end
	// of the visit before it to the same place is taken into that visit, as
	// the same departure told twice, a visit from the phone shorter than
	// PassByDurationMost that began and ended inside a visit at another place
	// is taken out (with the place iOS made for it, unless the person named or
	// labeled it), and visits to one place less than ten minutes apart with
	// nothing between them are joined. Call it once the visits of a report are
	// stored.
	NormalizePlaceVisits(userId string, from, until time.Time) error

	// ListOverlappedVisitRanges finds the people with a visit that began
	// after the arrival of a visit of theirs at another place and before it
	// ended, or a departure from a watched place with no arrival inside such a
	// visit or less than PassByDurationMost after a visit ended, or any
	// departure with no arrival less than PassByDurationMost from the end of
	// a visit to its place, among visits
	// that began since the instant, and for each the range
	// from the first such visit's arrival to the end of the last one, for
	// NormalizePlaceVisits. Visits put in order overlap none.
	ListOverlappedVisitRanges(since time.Time) ([]VisitRange, error)

	// EndOpenPlaceVisit sets the departure of the visit in progress and answers
	// it, or answers nil when there is none.
	EndOpenPlaceVisit(userId string, at time.Time) (*models.PlaceVisit, error)

	// GetPlaceVisit is one of the person's visits with its place, or nil when
	// they have no such visit.
	GetPlaceVisit(userId, visitId string) (*models.PlaceVisit, error)

	// ListPlaceVisits pages visits newest first, each with its place.
	// nextOffset is as in ListPlaces.
	ListPlaceVisits(userId string, filter PlaceVisitFilter) (visits []*models.PlaceVisit, nextOffset int, err error)

	// EraseLocationHistory deletes positions and visits that started in the
	// range (all of them when both ends are nil), and then the places left
	// with no visit that the person neither named nor labeled. Pauses that
	// began in the range and are over go too; the pause in effect stays, so
	// erasing does not resume recording. Trips, legs, motion activity and
	// corrections of the way of travel that started in the range go too. It deletes in
	// the same transaction the location journal documents of the days the
	// range touches, with their chunks, since those say where the person was
	// as plainly as the visits did. Anything the agent already learned from
	// those days stays in its memory until the person removes it.
	EraseLocationHistory(userId string, from, until *time.Time) (pointCount, visitCount, placeCount int, err error)

	// ClaimPlacesToName takes up to limitCount places that wait for a name and
	// that no instance has taken in the last ten minutes, oldest first and at
	// most a few of each person's, and marks them taken, so that two instances
	// do not ask a provider about the same place. Places of a person who may
	// not use Location are left alone.
	ClaimPlacesToName(limitCount int, now time.Time) ([]*models.Place, error)

	// ClaimPlaceToName takes one place that waits for a name, for the caller
	// that has just made it and names it at once, with the claim
	// ClaimPlacesToName makes. It answers nil when the place is gone, is named
	// already or was claimed in the last ten minutes, which is a place the
	// caller should leave alone.
	ClaimPlaceToName(placeId string, now time.Time) (*models.Place, error)

	// SetPlaceNamed records what a provider answered for a place. With an
	// errorMessage nothing else changes and the place stays unnamed, to be
	// claimed again once its claim is old. Without one, found is what the
	// provider knows about the position, or nil when it knows nothing, and either
	// way the place is named from now on. A name the person gave is never
	// replaced. ErrNotFound when there is no such place. claimedAt is the claim
	// the answer was asked under (Place.NamingClaimedAt); the answer is dropped
	// if the place has been moved, and so lost that claim, since it is about
	// where the place used to be. Nil skips that check.
	SetPlaceNamed(placeId string, claimedAt *time.Time, found *NamedPlace, errorMessage string, now time.Time) error

	// ReleasePlaceClaim gives back the claim on a place that was claimed to be
	// named but that nothing was asked about (the provider was busy), so that
	// the next run takes it at once instead of when the claim is old. The
	// errorMessage is kept on the place for the Location page. The claim is
	// kept if the place was claimed again since, and a place that is gone is
	// not an error.
	ReleasePlaceClaim(placeId string, claimedAt *time.Time, errorMessage string, now time.Time) error
}

LocationOperation is where a person has been: the positions their phone or browser reported, the places those are at and the visits to them. All of it belongs to one person, and every method takes that person, so that reading or changing somebody else's is not a question of which call to make.

A person can be asked about only through these. Sharing a person's location with a circle is a later addition to this interface, not part of it.

type LocationPauseOperation added in v0.195.0

type LocationPauseOperation interface {
	// PauseLocation pauses the person's location from now, ending at endedAt,
	// or never when endedAt is nil. When a pause is in effect at now, it is
	// that pause whose end changes, and nothing is added: isStarted says
	// whether the pause is a new one. ErrInvalidArguments for an end that is
	// not after now or is more than LocationPauseLongest after it.
	PauseLocation(userId string, endedAt *time.Time, now time.Time) (pause *models.LocationPause, isStarted bool, err error)

	// ResumeLocation ends the pause in effect at now, at now, and says whether
	// there was one. A pause that began at now or later is deleted, since it
	// would end before it began.
	ResumeLocation(userId string, now time.Time) (isResumed bool, err error)

	// GetLocationPauseInEffect is the pause in effect at the instant, or nil.
	GetLocationPauseInEffect(userId string, at time.Time) (*models.LocationPause, error)

	// GetLocationPausesInEffect is GetLocationPauseInEffect for many people in
	// one query. A person who is not paused is not in the answer.
	GetLocationPausesInEffect(userIds []string, at time.Time) (map[string]*models.LocationPause, error)

	// ListLocationPauses reads the pauses that overlap the range, newest
	// first: those that began before until and were not over by from. At most
	// limitCount of them, all of them when it is zero or less; a caller that
	// must refuse a range holding more asks for one more than it will take.
	ListLocationPauses(userId string, from, until time.Time, limitCount int) ([]*models.LocationPause, error)
}

LocationPauseOperation is the times a person stopped their location being recorded. docs/subsystems/location.md says what a pause does; what is here is only the rows. A caller that changes pauses holds the person's location lock (LockLocation), which is what keeps one pause in effect at a time.

type LocationPermissionOperation added in v0.226.0

type LocationPermissionOperation interface {
	// ReportLocationPermission keeps the app's newest report, replacing the
	// one before. ErrInvalidArguments for a permission that is not one of
	// the three.
	ReportLocationPermission(permission *models.LocationPermission) error

	// GetLocationPermission is the newest report, nil when the app never
	// sent one.
	GetLocationPermission(userId string) (*models.LocationPermission, error)

	// GetLocationSharingLimits is the limit for each person at the instant,
	// from their report and the pause in effect then. Everybody asked about is
	// in the answer.
	GetLocationSharingLimits(userIds []string, at time.Time) (map[string]models.LocationSharingLimit, error)
}

LocationPermissionOperation is what each person's app last said about their phone's location permission, and the limit it and a pause put on how much of their location anybody sees. docs/subsystems/location.md says why that is also the most of anybody else's location they see.

type LocationShareOperation added in v0.175.0

type LocationShareOperation interface {
	// ShareLocation gives a person or a circle a level of access to the
	// sharer's location, and answers the share as stored. Sharing again with
	// the same grantee changes the level. ErrInvalidArguments for a level
	// nobody can be given, a grantee that is both or neither, or the sharer
	// themselves. ErrNotFound for a person the sharer shares no circle with
	// and for a circle the sharer is not in, which is all the caller says.
	ShareLocation(sharerUserId string, share *models.LocationShare) (*models.LocationShare, error)

	// UnshareLocation takes one of the sharer's shares back. ErrNotFound
	// unless it is the sharer's.
	UnshareLocation(sharerUserId, shareId string) error

	// ListLocationShares are the shares the person has made, oldest first,
	// with who each is for.
	ListLocationShares(sharerUserId string) ([]*models.LocationShare, error)

	// GetLocationShareLevel is how much of the owner's location the viewer
	// may see: LocationShareLevelOwner for their own, and for another
	// person's the lower of what the owner shares with the viewer and what
	// the viewer shares back (seenLocationShareLevel), the empty level for
	// nothing. A share to a person reaches them only while the two still
	// share a circle, and a share to a circle only while both are in it.
	GetLocationShareLevel(viewerUserId, ownerUserId string) (models.LocationShareLevel, error)

	// ListLocationSharers are the people who share their location with the
	// viewer, once each, by name, with what their shares give and what the
	// viewer sees of it. One the viewer sees nothing of, because the viewer
	// shares nothing back, is still listed, so a screen can say why. Not the
	// viewer.
	ListLocationSharers(viewerUserId string) ([]*LocationSharer, error)

	// ListLocationGrantees are the people who see the owner's location now,
	// by GetLocationShareLevel, and share at least neededSharedBackLevel of
	// their own back (arrivals and departures are told only to people who
	// share their visits), once each, who have an agent row their phones
	// hang from. Not the owner, and not a person whose
	// account is disabled or whose roles no longer give location:use: they
	// cannot read the location, so they are not told of it either.
	ListLocationGrantees(ownerUserId string, neededSharedBackLevel models.LocationShareLevel) ([]*LocationGrantee, error)

	// FilterLocationGrantees answers which of the people named by userIds see
	// the owner's current location now, by the conditions of
	// ListLocationGrantees but for the people given and without needing them
	// to have an agent: one query for all the maps open on an instance.
	FilterLocationGrantees(ownerUserId string, userIds []string) ([]string, error)
}

LocationShareOperation is who may see whose location, and how much: a person's location shared with another person or with a circle at a level, as a calendar is.

"How much of this person's location may that person see" has one answer, GetLocationShareLevel, and every door asks it. A caller that compares the two user ids itself is wrong for a person who left the circle that made the share possible.

type LocationSharer added in v0.175.0

type LocationSharer struct {
	UserID   string
	Username string
	// Name is the name they gave, or their username.
	Name string
	// ShareLevel is how much of their location the viewer sees: the empty
	// level when the viewer shares nothing back.
	ShareLevel models.LocationShareLevel
	// GrantedShareLevel is the highest level their shares give the viewer,
	// before what the viewer shares back is counted.
	GrantedShareLevel models.LocationShareLevel
	// User holds the fields the picture's address and color are made from.
	User *models.User
}

LocationSharer is a person whose location reaches the viewer.

type LocationVisitNotice added in v0.206.2

type LocationVisitNotice struct {
	ID             string     `gorm:"column:id;primaryKey"`
	UserID         string     `gorm:"column:user_id"`
	ClientVisitKey string     `gorm:"column:client_visit_key"`
	IsArrival      bool       `gorm:"column:is_arrival"`
	HappenedAt     time.Time  `gorm:"column:happened_at"`
	DueAt          time.Time  `gorm:"column:due_at"`
	ClaimedAt      *time.Time `gorm:"column:claimed_at"`
	CreatedAt      time.Time  `gorm:"column:created_at"`
}

LocationVisitNotice is an arrival or a departure that waits to be told.

func (LocationVisitNotice) TableName added in v0.206.2

func (LocationVisitNotice) TableName() string

type LocationVisitNoticeOperation added in v0.206.2

type LocationVisitNoticeOperation interface {
	// CreateLocationVisitNotice stores a notice to be told at its due time.
	CreateLocationVisitNotice(notice *LocationVisitNotice, now time.Time) error

	// ClaimDueLocationVisitNotices takes the notices that are due, at most
	// limit, so that no other claimer gets them: a notice another transaction
	// is claiming is skipped, and one claimed less than reclaimAfter ago is
	// left to whoever claimed it. A notice claimed longer ago than that
	// returns to the queue, for the claimer that died before telling it.
	ClaimDueLocationVisitNotices(limit int, reclaimAfter time.Duration, now time.Time) ([]*LocationVisitNotice, error)

	// DeleteLocationVisitNotice forgets a notice that was told.
	DeleteLocationVisitNotice(noticeId string) error
}

LocationVisitNoticeOperation is the arrivals and departures that wait before they are told (location_visit_notice).

type MailEmbedding

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

MailEmbedding is one message's vector.

type MailInsightHead added in v0.169.0

type MailInsightHead struct {
	MailID         string
	MailboxID      string
	Category       string
	Subject        string
	IsExtractAsked bool
	ReceivedAt     time.Time
}

MailInsightHead is the part of a message and its insight that a choice among past messages reads.

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)

	// ListNoteItemsBetween is every version of the notes of a mailbox that
	// were created or changed from from up to but not including until: the
	// notes with a version filed here in that stretch, or written then
	// (their first version's date), each with all its versions, newest item
	// first, flagged deleted or not, each with its message. Items in the
	// trash and junk are left out.
	ListNoteItemsBetween(mailboxId string, from, until time.Time) ([]*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 McpHeldResult added in v0.206.2

type McpHeldResult struct {
	ID     string `gorm:"column:id;primaryKey"`
	Holder string `gorm:"column:holder"`

	// ResultText is the whole text, whose offsets result_more is given.
	ResultText string `gorm:"column:result_text"`

	// IsUntrusted is text from outside, which every page wraps, and IsError a
	// tool's failure, which every page is marked as.
	IsUntrusted bool      `gorm:"column:is_untrusted"`
	IsError     bool      `gorm:"column:is_error"`
	StoredAt    time.Time `gorm:"column:stored_at"`
}

McpHeldResult is one tool's whole text, whose it is, and what kind of answer it was.

func (McpHeldResult) TableName added in v0.206.2

func (McpHeldResult) TableName() string

type McpHeldResultLimits added in v0.206.2

type McpHeldResultLimits struct {
	// HeldFor is how long a result is held after it was stored.
	HeldFor time.Duration

	// ByteCountPerHolder bounds what one holder has held at once; ByteCount
	// bounds everything held, for every holder.
	ByteCountPerHolder int
	ByteCount          int
}

McpHeldResultLimits are the bounds of what is held, enforced by KeepMcpHeldResult.

type McpHeldResultOperation added in v0.206.2

type McpHeldResultOperation interface {
	// KeepMcpHeldResult holds a result for its holder and enforces the limits
	// in the same transaction: what was held longer than limits.HeldFor goes,
	// then the holder's oldest results until the new one fits in the holder's
	// count and bytes, then the oldest of everybody's until it fits in the
	// total bytes. The result is written last, so it is never the one dropped.
	KeepMcpHeldResult(held *McpHeldResult, limits McpHeldResultLimits, now time.Time) error

	// FindMcpHeldResult is the result held under id for holder, nil when there
	// is none, it was held before notBefore, or it is another holder's: the
	// same as an id that never existed.
	FindMcpHeldResult(holder, id string, notBefore time.Time) (*McpHeldResult, error)

	// DeleteMcpHeldResultsStoredBefore forgets the results held since before
	// a time, which nobody can read on any more.
	DeleteMcpHeldResultsStoredBefore(before time.Time) (int64, error)
}

McpHeldResultOperation is the long tool results read on with result_more (mcp_held_result).

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)

	// 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 are the person's own books only. A circle has an
	// address book of its own too, kept by its members: ListReachableAddressBooks
	// has both, and AddressBookAccess is the one answer to who may use a book.
	ListAddressBooks(userId string) ([]*models.AddressBook, error)
	ListReachableAddressBooks(userId string) ([]*models.ReachableAddressBook, error)
	AddressBookAccess(userId string, book *models.AddressBook) (models.AddressBookAccess, error)
	GetCircleAddressBook(circleId string) (*models.AddressBook, error)
	// CreateCircleAddressBook makes the circle's book. ErrNotFound when the
	// circle is gone, ErrAlreadyExists when it has one.
	CreateCircleAddressBook(circleId, name 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)

	// AddressBookChangeTag is CalendarChangeTag for an address book.
	AddressBookChangeTag(addressBookId string) (string, 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)

	// SetContactAccount links a contact to the account on this server it is,
	// or clears the link when accountUserId is empty. The only writer of the
	// link; refuses the owner's own account and one they share no circle with
	// (ErrInvalidArguments), and an account another contact in the book is
	// already linked to (ErrAlreadyExists).
	SetContactAccount(addressBookId, contactId, accountUserId string) error

	// FindContactByAccount is the owner's contact linked to an account, in
	// the first address book that has one, while they share a circle.
	FindContactByAccount(ownerUserId, accountUserId string) (*models.Contact, error)

	// ListContactAccountLinks are all of the owner's linked contacts, books
	// in the order they were made, while they share a circle with each.
	ListContactAccountLinks(ownerUserId string) ([]*models.Contact, error)

	// ListPhotoPeopleAccountUserIDs are the linked accounts a face group of
	// the owner is named by.
	ListPhotoPeopleAccountUserIDs(ownerUserId string) ([]string, error)

	// ListContactAccountSuggestions are the owner's unlinked contacts that
	// carry a mailbox address of an account in their circles.
	ListContactAccountSuggestions(ownerUserId string) ([]*models.ContactAccountSuggestion, 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)

	// CalendarChangeTag names the calendar's contents as they are now: it
	// changes whenever an object is added, changed or deleted, which is how a
	// phone knows to read the calendar again.
	CalendarChangeTag(calendarId string) (string, 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)

	// ListCalendarObjectsDoneSince are the objects of a reminders list that
	// are marked done and were last written at or after since, earliest first
	// and at most limit, for the journal's reminders done on a day. The time a
	// reminder says it was done is in its file, and a file written again later
	// (renamed, say) lists under its later time, so the caller reads the file
	// and keeps the ones done in its window.
	ListCalendarObjectsDoneSince(calendarId string, since 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 NamedPlace added in v0.175.0

type NamedPlace struct {
	PlaceName   string
	OSMType     string
	OSMID       int64
	OSMCategory string
	AddressText string
}

NamedPlace is what a provider knows about a position, for SetPlaceNamed.

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 OSMReference added in v0.175.0

type OSMReference struct {
	OSMType string
	OSMID   int64
}

OSMReference names an object on the OpenStreetMap map.

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 OversightConversation added in v0.237.0

type OversightConversation struct {
	Conversation  *models.AgentConversation
	OwnerUsername string
	OwnerName     string
	IsRunning     bool
}

OversightConversation is a conversation with whose it is and whether a turn is running in it.

type OversightConversationModel added in v0.237.0

type OversightConversationModel = agentConversationModel

OversightConversationModel is the conversation's row under an exported name, which is what lets it be embedded in a row that scans it.

type OversightFilter added in v0.237.0

type OversightFilter struct {
	// AgentID is one person's agent; empty is everybody's.
	AgentID string

	// Kinds are conversation kinds (main, named, goal) and the kinds of run
	// (a run's job kind). Empty is every conversation but a chat between
	// people, which is never listed.
	Kinds []string

	// Since and Until bound the conversation's last activity.
	Since *time.Time
	Until *time.Time

	// IsRunningOnly keeps the conversations with a turn in flight, one that
	// was not cut and whose instance was heard of since LiveAfter.
	IsRunningOnly bool
	LiveAfter     time.Time

	// JobID narrows to the runs one job made, Query to titles carrying the
	// words.
	JobID string
	Query string
}

OversightFilter narrows the listing. Every field is optional.

type OversightOperation added in v0.237.0

type OversightOperation interface {
	// ListOversightConversations is every person's conversations and runs,
	// newest activity first, narrowed by the filter and paged by the options.
	// CountOversightConversations is how many the filter leaves.
	ListOversightConversations(filter *OversightFilter, options *Options) ([]*OversightConversation, error)
	CountOversightConversations(filter *OversightFilter) (int64, error)

	// ListFailedAgentTurns is the turns that ended in a failed note, newest
	// first, and CountFailedAgentTurns how many there are.
	ListFailedAgentTurns(filter *FailedTurnFilter, options *Options) ([]*FailedAgentTurn, error)
	CountFailedAgentTurns(filter *FailedTurnFilter) (int64, error)

	// RecordConversationObserved writes the audit row of the transaction's
	// actor reading another person's conversation, folded to one per reader
	// and conversation per interval. It says whether a row was written.
	RecordConversationObserved(conversation *models.AgentConversation, readerUserId, ownerUserId string, interval time.Duration, now time.Time) (bool, error)
}

OversightOperation is what an operator who may observe sees across every person's agent: their conversations and runs, which are in flight, and the turns that failed. Reading only.

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 PageShareOperation added in v0.170.0

type PageShareOperation interface {
	// SharePage shares the sharer's own page, and everything under it, with a
	// person or a circle, or changes whether the quotes are shared when it is
	// shared with them already. ErrNotFound unless there is a page at the
	// path in the sharer's graph and, for a person, the two share a circle,
	// or, for a circle, the sharer is in it. ErrInvalidArguments for a path
	// that is not one or a grantee that is not exactly one.
	SharePage(sharerUserId string, share *models.AgentPageShare) (*models.AgentPageShare, error)

	// GetPageShare is one share, or nil.
	GetPageShare(shareId string) (*models.AgentPageShare, error)

	// ListPageSharesBy are the shares the person made of their own pages,
	// by path, with who each is for.
	ListPageSharesBy(ownerUserId string) ([]*models.AgentPageShare, error)

	// DeletePageShare takes one back. ErrNotFound when there is none.
	DeletePageShare(shareId string) error

	// ListPageSharesReaching are the shares that reach the person as a
	// reader: made to them, or to a circle they are in, by somebody who
	// still shares that circle or a circle with them, with the owner named.
	// By owner name and then path.
	ListPageSharesReaching(readerUserId string) ([]*models.AgentPageShare, error)

	// SearchAgentGraphWithin finds pages and facts by words in the graph of
	// one agent, only on the pages at these roots or under them. A page is
	// found by its path, name, aliases and summary, except that the pages
	// named in hiddenSummaryNodeIds are found by their path, name and
	// aliases alone: their summary is not shown to the reader, so a word on
	// it must not find them. The shared-memory reader is the only caller.
	SearchAgentGraphWithin(agentId string, roots, hiddenSummaryNodeIds []string, query string, limit int) ([]*models.AgentNode, []*models.AgentFact, error)

	// ListAgentFactsWithin are the live facts on the pages at these roots or
	// under them, by identifier, at most limit of those after afterFactId
	// (empty to start). The shared-memory reader counts what a share would
	// keep from its reader with it, a batch at a time.
	ListAgentFactsWithin(agentId string, roots []string, afterFactId string, limit int) ([]*models.AgentFact, error)

	// ListOwnCalendarObjectsByID are the objects with these identifiers in
	// the calendars the person owns, in one read. An object of a circle's
	// calendar, or one that is gone, is not among them. The shared-memory
	// reader classifies the events a fact cites with it.
	ListOwnCalendarObjectsByID(userId string, objectIds []string) ([]*models.CalendarObject, error)
}

PageShareOperation is who may read which of a person's pages: a page of the agent's graph, and everything under it, shared with another person or with a circle.

This is only the table and the questions about it. Reading what a share reaches is internal/agent/shared_memory.go, which is the one place another agent's graph is read, and which asks ListPageSharesReaching what it may read before it does.

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 PasswordRecipientFullError added in v0.193.0

type PasswordRecipientFullError struct {
	RecipientName string
}

PasswordRecipientFullError is ErrPasswordRecipientFull with the name of the person who has too much shared with them.

func (*PasswordRecipientFullError) Error added in v0.193.0

func (self *PasswordRecipientFullError) Error() string

func (*PasswordRecipientFullError) Is added in v0.193.0

func (self *PasswordRecipientFullError) Is(target error) bool

type PasswordsOperation added in v0.193.0

type PasswordsOperation interface {
	// GetPasswordsSetup is the person's setup, nil if they have none.
	GetPasswordsSetup(userId string) (*models.PasswordSetup, error)

	// CreatePasswordsSetup stores a first setup. ErrAlreadyExists if the
	// person has one. The lock time is the default.
	CreatePasswordsSetup(setup *models.PasswordSetup) (*models.PasswordSetup, error)

	// CheckPasswordsProof says whether the proof, given as base64, is the
	// proof of the person's passphrase or, with isRecoveryKey, of their
	// recovery key: the stored hash is compared in constant time with the
	// SHA-256 of the proof. ErrNotFound when the person has no setup.
	CheckPasswordsProof(userId, proof string, isRecoveryKey bool) (bool, error)

	// RecordPasswordsUnlockFailure writes the audit event for a wrong proof.
	// RecordPasswordsUnlocked writes the one for a right proof that unlocked,
	// and RecordPasswordsUnlockRefused the one for a try turned away because
	// there were too many, at most one for each person in
	// models.PasswordsUnlockRefusedAuditSpacing. None holds a proof, a key or a
	// hash.
	RecordPasswordsUnlockFailure(userId string, isRecoveryKey bool) error
	RecordPasswordsUnlocked(userId string, isRecoveryKey bool) error
	RecordPasswordsUnlockRefused(userId string, isRecoveryKey bool) error

	// ChangePasswordsPassphrase replaces what the passphrase makes.
	ChangePasswordsPassphrase(userId string, change *models.PasswordPassphraseChange) (*models.PasswordSetup, error)

	// ReplacePasswordsRecoveryKey replaces what the recovery key makes.
	ReplacePasswordsRecoveryKey(userId, accountKeyByRecoveryKey, recoveryKeyProofHash string) (*models.PasswordSetup, error)

	// SetPasswordsLockAfterMinutes is how long a device stays unlocked.
	// ErrInvalidArguments outside PasswordsLockAfterMinutesLeast to Most.
	// Making it longer than it is, read under the row lock, is
	// ErrPasswordTapRequired unless isByPerson says the call is the person's
	// own tap.
	SetPasswordsLockAfterMinutes(userId string, lockAfterMinutes int, isByPerson bool) (*models.PasswordSetup, error)

	// ErasePasswords deletes the person's setup, items, shares and the keys
	// sealed for them, and answers how many items it deleted. The items of
	// other people shared with this person lose their key for them and wait.
	ErasePasswords(userId string) (int, error)

	// CountPasswordItems is how many items the person has that are not
	// deleted.
	CountPasswordItems(userId string) (int, error)

	// SavePasswordItem stores an item of the owner, new (baseRevision nil) or
	// changed (baseRevision the revision it was based on) and raises its
	// revision. IsSavedByPerson on the item says the save is the person's own
	// tap, which decides which replaced versions are kept. ErrPasswordRevisionStale
	// when baseRevision is not the stored revision, ErrNotFound for somebody
	// else's item or a deleted one, ErrInvalidArguments for a change of kind,
	// ErrLimitReached beyond PasswordItemsMost items that are not deleted or
	// PasswordRowsMost items counting deleted ones (for a new item; a save that
	// is not the person's tap stops at PasswordRowsForProgramsMost, so that the
	// last places are the person's),
	// ErrPasswordRecipientFull when the item is shared and a person it holds a
	// key for would pass the shared allowance, ErrPasswordsFull when the
	// items that are not deleted would pass models.PasswordsBytesMost, and, for
	// a save that is not the person's tap, ErrPasswordsKeptFull when the version
	// it would keep does not fit in models.PasswordsKeptBytesMost (a tap's save
	// then goes ahead without keeping the version). A refused save draws no
	// revision number.
	SavePasswordItem(item *models.PasswordItem, baseRevision *int64) (*models.PasswordItem, error)

	// RekeyPasswordItem replaces the fields and the item key of the owner's
	// item with ones sealed under a new item key, because access to the item
	// narrowed, in one change with one revision. Every key sealed for a
	// recipient is deleted and the given ones are stored; each must be for a
	// recipient the item's shares reach now and sealed for the public key they
	// have now (ErrNotFound, ErrPasswordKeyStale as for SetPasswordItemShares).
	// Recipients reached and not given a key wait. The agent's copy is replaced
	// when the item is usable by the agent and a copy is given, and agent use
	// ends when none is given; a copy for an item that is not usable by the
	// agent is ErrInvalidArguments. ErrPasswordRevisionStale when baseRevision
	// is not the stored revision, ErrNotFound for somebody else's item,
	// ErrPasswordsFull, ErrPasswordsKeptFull and ErrPasswordRecipientFull as for SavePasswordItem (a
	// deleted item's size counts against the kept allowance). A deleted item can be
	// re-keyed (so that a restore can follow); it takes no share keys. The
	// item's NeedsNewKey is cleared. The replaced version is kept as a save
	// keeps it.
	RekeyPasswordItem(ownerUserId string, rekey *models.PasswordItemRekey) (*models.PasswordItem, error)

	// GetPasswordItem is the owner's item, deleted or not, with its shares.
	// ErrNotFound for somebody else's.
	GetPasswordItem(ownerUserId, itemId string) (*models.PasswordItem, error)

	// DeletePasswordItem marks the owner's item deleted, ends the keys sealed
	// for its recipients and the agent's use, and raises its revision. Its
	// bytes move from the room of items that are not deleted to the kept
	// allowance: when that is full, the delete is ErrPasswordsKeptFull unless
	// isByPerson says it is the person's own tap, which always goes ahead.
	DeletePasswordItem(ownerUserId, itemId string, isByPerson bool) (*models.PasswordItem, error)

	// RestorePasswordItem undoes a deletion and raises its revision. The
	// shares of the item reach its recipients again, so it is ErrPasswordTapRequired
	// unless isByPerson says the call is the person's own tap. The keys that
	// were ended are not made again: the item's recipients wait.
	// ErrPasswordsFull when the item would take the person's items that are
	// not deleted over models.PasswordsBytesMost, ErrLimitReached when the
	// person already has models.PasswordItemsMost items that are not deleted.
	RestorePasswordItem(ownerUserId, itemId string, isByPerson bool) (*models.PasswordItem, error)

	// ListPasswordItemVersions are the earlier versions the server kept of the
	// owner's item, newest first, deleted item too. ErrNotFound for somebody
	// else's item. What it answers is sealed content, so the API lets only the
	// person's tap ask.
	ListPasswordItemVersions(ownerUserId, itemId string) ([]*models.PasswordItemVersion, error)

	// RestorePasswordItemVersion makes the fields and the item key of one of
	// the item's kept versions (named by the revision the item had then) the
	// item's own. The content it replaces is kept as a version too, whatever
	// the spacing rule of saves says (unless the kept allowance has no room for
	// it, which a tap does not stop). Every key stored for a recipient and the
	// agent's copy are deleted (they were sealed under the key now replaced, and
	// the agent's use ends), the item is marked NeedsNewKey, and it gets the next
	// revision. It is
	// ErrPasswordTapRequired unless isByPerson says the call is the person's own
	// tap, ErrPasswordRevisionStale when baseRevision is not the item's revision,
	// ErrNotFound for somebody else's item, a deleted one, or a version that is
	// not kept, and ErrPasswordsFull as for a save.
	RestorePasswordItemVersion(ownerUserId, itemId string, versionRevision, baseRevision int64, isByPerson bool) (*models.PasswordItem, error)

	// PurgePasswordItem removes the owner's deleted item at once, with its
	// versions, shares and keys, which frees its kept bytes. ErrNotFound for
	// somebody else's item, ErrInvalidArguments for one that is not deleted. It
	// draws no revision: deleted items are not among the identifiers a listing
	// answers, so a device drops the item as it does when the sweep removes it.
	PurgePasswordItem(ownerUserId, itemId string) error

	// ListPasswordItems is what the viewer can reach now: their own items
	// (deleted ones too, with their shares) and those shared with them for
	// which a key sealed for their current public key exists, those with a
	// revision above sinceRevision in full and every identifier. It reads a
	// view in which no change can commit meanwhile, so the revision it
	// answers never passes an item it left out.
	ListPasswordItems(viewerUserId string, sinceRevision int64) (*models.PasswordItemList, error)

	// ListPasswordRecipients are the people a share with a person or a circle
	// reaches, for the caller to seal keys for: the person, if the caller
	// shares a circle with them, or the circle's members other than the
	// caller, if the caller is in it. Only people who may use Passwords.
	// ErrNotFound as for any share when the caller has no such reach.
	ListPasswordRecipients(callerUserId, granteeUserId, granteeCircleId string) ([]*models.PasswordRecipient, error)

	// SetPasswordItemShares replaces who the owner's item is shared with and
	// stores the keys sealed for recipients that are reached. A grantee the
	// item is not already shared with is ErrPasswordTapRequired unless
	// isByPerson says the call is the person's own tap, decided under the locks
	// so that a change that is waiting behind another is judged on what that
	// one left. Each key names, in ItemKeyByAccountKey, the item key it was
	// sealed from (required) and is ErrPasswordRevisionStale when that is no
	// longer the item's. A key for somebody not reached is ErrNotFound, one
	// sealed for a public key that is not the recipient's now is
	// ErrPasswordKeyStale. Keys of recipients no longer reached are deleted. A
	// key row already stored is replaced only by a tap, and only when a token
	// stored it or it was sealed for another public key; a call that is not a
	// tap never replaces one. A grantee the owner cannot share with is
	// ErrNotFound. The revision is raised only once every check has passed.
	// When a grantee is removed, or a stored key is deleted, the item's
	// NeedsNewKey is set.
	SetPasswordItemShares(ownerUserId, itemId string, grantees []models.PasswordShareGrantee, keys []*models.PasswordShareKey, isByPerson bool) (*models.PasswordItem, error)

	// AddPasswordShareKeys stores keys for recipients already reached by the
	// owner's items. Each key names, in ItemKeyByAccountKey, the item key it
	// was sealed from, and is ErrPasswordRevisionStale when that is no longer
	// the item's. Same refusals and same rule about replacing a stored key as
	// SetPasswordItemShares. Only the items whose stored keys changed get a new
	// revision. Answers how many keys it stored.
	AddPasswordShareKeys(ownerUserId string, keys []*models.PasswordShareKey, isByPerson bool) (int, error)

	// ListWaitingPasswordShares are the recipients of the owner's items who
	// have set up Passwords and have no key sealed for their current public
	// key.
	ListWaitingPasswordShares(ownerUserId string) ([]*models.PasswordWaitingShare, error)

	// SetPasswordItemUsableByAgent turns "Let the agent use this" on, with the
	// item key sealed for the server's agent key, or off. ErrPasswordCard...
	// for a card, ErrInvalidArguments for on without a key.
	SetPasswordItemUsableByAgent(ownerUserId, itemId string, isUsable bool, itemKeyByAgentKey string) (*models.PasswordItem, error)

	// ListAgentUsablePasswordItems are the owner's items they let the agent
	// use, not deleted, with the item key sealed for the agent key. None when
	// the owner's account is disabled or no longer holds passwords:use.
	ListAgentUsablePasswordItems(ownerUserId string) ([]*models.PasswordItem, error)

	// RecordPasswordItemAgentUse notes that the agent used the item on a host,
	// for the item's page and the audit log. It sets the time of the use and
	// nothing else: the item's revision does not change, so a device that has
	// the item open can still save it, and a device learns the new time on its
	// next full read of the item, not from the changes after a revision.
	// ErrNotFound unless the item is the owner's and usable by the agent.
	RecordPasswordItemAgentUse(ownerUserId, itemId, host string, usedAt time.Time) error

	// GetPasswordAgentKey is the server's agent key, nil if none was made.
	GetPasswordAgentKey() (*models.PasswordAgentKey, error)

	// CreatePasswordAgentKey stores the agent key unless one exists, and
	// answers the one stored.
	CreatePasswordAgentKey(key *models.PasswordAgentKey) (*models.PasswordAgentKey, error)
}

PasswordsOperation stores a person's Passwords: what they set up, their items and who the items are shared with. Everything sealed is stored as given; nothing here opens it. Which of these may be called by whom, and which need a person's tap, is the API's to decide.

type PasswordsScavengeOperation added in v0.193.0

type PasswordsScavengeOperation interface {
	// ScavengePasswordItems deletes the items deleted before the time, with
	// their shares and keys, and the earlier versions that saves replaced
	// before the time, and answers how many items it deleted.
	ScavengePasswordItems(before time.Time) (int64, error)
}

PasswordsScavengeOperation removes what Passwords no longer keeps. It is outside a transaction, like the sweeps of sessions and tokens.

type PersonCardMail added in v0.188.0

type PersonCardMail struct {
	Item      *models.MailboxItem
	MailboxID string

	// IsFromAddress says one of the addresses wrote it, rather than only
	// being among its recipients.
	IsFromAddress bool
}

PersonCardMail is one mail with one of the addresses: the item, with its message, and the mailbox it is in.

type PersonCardOperation added in v0.188.0

type PersonCardOperation interface {
	// ListMailWithAddresses is the person's recent mail from or to any of the
	// addresses, across every mailbox they own, newest first, and whether
	// there is more than limit of it. An address matches only as a whole, in
	// any case: an address inside a longer one is another address. The trash,
	// the junk folder, drafts and a phone's notes are left out, and so are
	// the copies of one mail that a sender made by writing to each of the
	// person's addresses separately. mailboxIds, when not nil, keeps to
	// those of the person's mailboxes (none, when empty).
	ListMailWithAddresses(userId string, mailboxIds []string, addresses []string, limit int) ([]*PersonCardMail, bool, error)
}

PersonCardOperation is what a person's card reads that no other part of the app asks the same way.

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

	// SetAgentPhoneVoIPPushRegistration replaces the registration a phone is
	// rung through. An empty one clears it, which is what Apple saying the
	// VoIP token is gone means: the phone's ordinary registration is left
	// alone, since the two tokens go stale separately.
	SetAgentPhoneVoIPPushRegistration(phoneId, voipPushRegistration string) 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 PhotoAlbumOperation added in v0.171.0

type PhotoAlbumOperation interface {
	// ListPhotoAlbums lists the albums the person reaches, the most recently
	// changed first: their own, their circles', and those shared with them,
	// each with its photo count, its cover, the dates of its photos and what
	// the person may do with it.
	ListPhotoAlbums(userId string) ([]*models.PhotoAlbum, error)

	// ListCirclePhotoAlbums lists, the same way, the albums of one circle the
	// person is in: the circle's own, and those shared with the whole circle
	// that the person reaches, their own among them. A circle the person is
	// not in is not found.
	ListCirclePhotoAlbums(userId, circleId string) ([]*models.PhotoAlbum, error)

	// GetPhotoAlbum is one album the person reaches at any level.
	GetPhotoAlbum(userId, photoAlbumId string) (*models.PhotoAlbum, error)

	// CreatePhotoAlbum makes an album of the person's holding the named
	// photos, which must all be the person's.
	CreatePhotoAlbum(userId, albumTitle string, photoIds []string) (*models.PhotoAlbum, error)

	// CreateCirclePhotoAlbum makes an album that belongs to a circle the
	// person is in, holding the named photos, which must all be the
	// person's own: they stay theirs. ErrNotFound for a circle they are not
	// in.
	CreateCirclePhotoAlbum(userId, circleId, albumTitle string, photoIds []string) (*models.PhotoAlbum, error)

	// RenamePhotoAlbum, DeletePhotoAlbum and SetPhotoAlbumCover are for the
	// album's manager: its owner, or an admin of the circle that owns it.
	RenamePhotoAlbum(userId, photoAlbumId, albumTitle string) (*models.PhotoAlbum, error)

	// DeletePhotoAlbum deletes the album and nothing else: its photos stay in
	// their owners' libraries.
	DeletePhotoAlbum(userId, photoAlbumId string) error

	// AddPhotosToAlbum puts the named photos, which must all be the person's
	// own, in an album they may contribute to, leaving alone those already in
	// it, and says how many were added.
	AddPhotosToAlbum(userId, photoAlbumId string, photoIds []string) (int, error)

	// RemovePhotosFromAlbum takes photos out of the album and says how many
	// were in it. The photos stay in their owners' libraries. The album's
	// manager may take out any photo, and somebody who contributes only the
	// photos they added; those that are not the person's to take out are left
	// where they are and not counted. If the cover goes, the album is left
	// with no chosen cover.
	RemovePhotosFromAlbum(userId, photoAlbumId string, photoIds []string) (int, error)

	// SetPhotoAlbumCover chooses the album's cover from among its photos.
	SetPhotoAlbumCover(userId, photoAlbumId, photoId string) (*models.PhotoAlbum, error)

	// ListPhotoAlbumsOfPhoto lists, by title, the albums a photo is in that
	// the person reaches. ErrNotFound unless the person may read the photo.
	ListPhotoAlbumsOfPhoto(userId, photoId string) ([]*models.PhotoAlbumReference, error)

	// ListPhotosInNoAlbum lists, in time order, the person's photos that are
	// not in the trash, are in no album and say when they were taken, taken
	// within the dates. Only the columns that say where and when are filled
	// in. A question with more answers than a suggestion needs is refused with
	// ErrTooMuchAsked, so that the dates are narrowed.
	ListPhotosInNoAlbum(userId string, takenAfter, takenBefore *time.Time) ([]*models.Photo, error)
}

PhotoAlbumOperation owns the albums: named sets of photos that belong to a person or to a circle. Who may do what with an album is decided here, in GetPhotoAlbumAccess: the owner, a member of the circle that owns it, and the people it is shared with each have their own part, and an album nobody reaches is not found.

An album holds references. A photo in the trash stays in its albums but is not counted or listed there until it is restored.

type PhotoAlbumShareOperation added in v0.171.0

type PhotoAlbumShareOperation interface {
	// GetPhotoAlbumAccess is what the person may do with the album. ErrNotFound
	// when there is no such album or the person reaches it at no level: an
	// album they own, one that belongs to a circle they are in, or one shared
	// with them. A share to a circle reaches a member only while the album's
	// owner is still in that circle, and a share to a person only while the
	// two still share a circle.
	GetPhotoAlbumAccess(userId, photoAlbumId string) (*models.PhotoAlbumAccess, error)

	// GetPhotoAccess is why the person may read the photo. ErrNotFound unless
	// it is theirs or is in an album they reach, and not in the trash for
	// anybody but its owner.
	GetPhotoAccess(userId, photoId string) (*models.PhotoAccess, error)

	// GetPhotoFaceOwnerUserID is whose photo the face was found in, for the
	// route that serves a face's picture and has only the face's identifier
	// to start from. ErrNotFound when there is no such face.
	GetPhotoFaceOwnerUserID(photoFaceId string) (string, error)

	// SharePhotoAlbum gives a person or a circle a level of access to an album
	// the sharer manages, or changes the level they have. ErrNotFound unless
	// the sharer manages the album and, for a person, the two share a circle,
	// or, for a circle, the sharer is in it. ErrInvalidArguments for a level
	// that cannot be given, a grantee that is not exactly one, oneself, and an
	// album that belongs to a circle: every member of it has it already.
	SharePhotoAlbum(sharerUserId string, share *models.PhotoAlbumShare) (*models.PhotoAlbumShare, error)

	// UpdatePhotoAlbumShare changes the level of a share and whether it
	// includes where photos were taken and the names of the faces in them.
	// ErrNotFound unless the person manages
	// the album it is for.
	UpdatePhotoAlbumShare(userId, photoAlbumShareId string, shareLevel models.PhotoAlbumShareLevel, isLocationIncluded, isFaceNamesIncluded bool) (*models.PhotoAlbumShare, error)

	// DeletePhotoAlbumShare takes a share back, and with it the photos of the
	// people it reached that are no longer theirs to have in the album.
	// ErrNotFound unless the person manages the album it is for.
	DeletePhotoAlbumShare(userId, photoAlbumShareId string) error

	// ListPhotoAlbumShares are an album's shares with who they are for, by
	// when they were made. ErrNotFound unless the person manages the album.
	ListPhotoAlbumShares(userId, photoAlbumId string) ([]*models.PhotoAlbumShare, error)

	// ListPhotoAlbumReaderUserIDs are everybody who can open the album now, its
	// owner and the members of the circle that owns it included, once each:
	// the people photoAlbumReachQuery lets in, so a share from an owner who is
	// disabled or no longer has photos:use reaches nobody here either.
	ListPhotoAlbumReaderUserIDs(photoAlbumId string) ([]string, error)
}

PhotoAlbumShareOperation is who may read and write which album: an album shared with another person or with a circle at a level, and the albums a circle keeps for itself.

"May this person read this photo or this album, and how far" has one answer, GetPhotoAccess and GetPhotoAlbumAccess, and every door asks it: the dashboard's API, the phone, the command line and the agent. A caller that compares a photo's or an album's owner with the person instead is wrong for a circle's album, which has none, and for a photo somebody else added to it.

type PhotoDescription added in v0.171.0

type PhotoDescription struct {
	// PhotoDescription is the sentences, and VisibleText the words it could
	// read in the picture.
	PhotoDescription string
	VisibleText      string

	// ModelName is the model that wrote them.
	ModelName string

	// PhotoDocumentKind is what the model said the picture is.
	PhotoDocumentKind models.PhotoDocumentKind
}

PhotoDescription is what a model wrote about a picture.

type PhotoDocument added in v0.252.0

type PhotoDocument struct {
	// Title names the document in a few words, and Text is everything
	// written in the picture, as Markdown.
	Title string
	Text  string

	// DocumentDate is the date the document says it is of, nil when it says
	// none. The knowledge document is filed at that date, else at the
	// photo's own.
	DocumentDate *time.Time
}

PhotoDocument is what the transcription job read from a picture.

type PhotoFaceGroupVector added in v0.171.0

type PhotoFaceGroupVector struct {
	ID string

	// VectorSum is the sum of the unit vectors of the faces in the group.
	// Its direction is the group's average direction, which is all a
	// similarity looks at, and a sum can take one more face without reading
	// the others.
	VectorSum []float32
}

PhotoFaceGroupVector is a group as a face is compared with it.

type PhotoFaceOperation added in v0.171.0

type PhotoFaceOperation interface {
	// IsPhotoFaceRecognitionEnabled is the person's own switch for having
	// faces found in their photos; on until they turn it off.
	IsPhotoFaceRecognitionEnabled(userId string) (bool, error)

	// SetPhotoFaceRecognition switches the person's faces on or off. Off
	// deletes every face and group they have and forgets that any photo was
	// read, in this transaction, so that turning it on again reads the
	// photos again.
	SetPhotoFaceRecognition(userId string, isEnabled bool) error

	// ListPhotosWaitingForFaces lists up to limit ready photos, oldest first,
	// that have a large preview and whose faces have not been found, of
	// people who have faces switched on. The photos named are left out.
	ListPhotosWaitingForFaces(limit int, skippedPhotoIds []string) ([]*models.Photo, error)

	// LockPhotoFaceGrouping takes the lock that makes one person's grouping
	// happen one photo after another, even on two instances, until the
	// transaction ends.
	LockPhotoFaceGrouping(userId string) error

	// StorePhotoFaces keeps the faces found in a photo and records that they
	// were found; the photos found again are those whose pixels changed, which
	// is when the record is cleared. An old face the person confirmed lives
	// on in the new face found at about the same place, with its group. The
	// faces come back as stored, in the order given, with their vectors. The
	// photo is not found when it is not the person's or is being deleted, and
	// ErrAlreadyExists says another instance found its faces first.
	StorePhotoFaces(userId, photoId string, found []*models.PhotoFace) ([]*models.PhotoFace, error)

	// ListPhotoFaceGroupVectors lists the person's groups that have faces,
	// with the vectors a face is compared with, the hidden ones too: a hidden
	// group goes on taking its person's faces.
	ListPhotoFaceGroupVectors(userId string) ([]*PhotoFaceGroupVector, error)

	// StartPhotoFaceGroup makes a group of one face and says its identifier.
	StartPhotoFaceGroup(userId, photoFaceId string) (string, error)

	// JoinPhotoFaceGroup puts a face that has no group in a group, adding
	// its vector to the group's.
	JoinPhotoFaceGroup(userId, photoFaceId, photoFaceGroupId string) error

	// DeleteEmptyPhotoFaceGroups deletes groups that no face is in, which
	// are left behind when photos are deleted forever, and says how many.
	DeleteEmptyPhotoFaceGroups() (int, error)

	// ListPhotoFaceGroups lists the person's groups worth showing: those a
	// contact names, first by the contact's name, and the rest with at least
	// MinimumUnnamedPhotoFaceGroupFaceCount faces, the largest first. Hidden
	// groups are left out unless asked for.
	ListPhotoFaceGroups(userId string, isHiddenIncluded bool) ([]*models.PhotoFaceGroup, error)
	GetPhotoFaceGroup(userId, photoFaceGroupId string) (*models.PhotoFaceGroup, error)

	// ListPhotoFaces lists the faces of photos, each with the contact its
	// group is named for.
	ListPhotoFaces(userId string, photoIds []string) ([]*models.PhotoFace, error)
	GetPhotoFace(userId, photoFaceId string) (*models.PhotoFace, error)

	// FindPhotoFaceForContactPicture finds the face of a group to cut a
	// contact's picture from: the one detected with the highest confidence
	// among those that take up at least MinimumContactPictureFaceAreaFraction
	// of their photo, in the person's own photos that are not in the trash and
	// have a large preview. It is ErrNotFound when no face qualifies.
	FindPhotoFaceForContactPicture(userId, photoFaceGroupId string) (*models.PhotoFace, error)

	// NamePhotoFaceGroup names a group by a contact, which must be in one of
	// the person's own address books. Another contact replaces the one it had.
	// A contact names one person: when it already names another of the
	// person's groups the two are one person, and the group already named
	// takes the faces of both and keeps its own cover. The group that answers
	// is the one left, and mergedPhotoFaceGroupId is the group that was put
	// into it, empty when nothing was merged. The group left is hidden only
	// when both were hidden.
	NamePhotoFaceGroup(userId, photoFaceGroupId, addressBookId, contactId string) (group *models.PhotoFaceGroup, mergedPhotoFaceGroupId string, err error)
	UnnamePhotoFaceGroup(userId, photoFaceGroupId string) (*models.PhotoFaceGroup, error)

	// MergePhotoFaceGroups moves the faces of the other groups into the
	// first and deletes them. The first keeps its own contact; when it has
	// none it takes the contact of the first other group that has one.
	// A group holds one face of a photo, so of the faces of a photo that two
	// groups each had, the one the person confirmed stays, else the one most
	// like the group; the others are in no group and not confirmed.
	MergePhotoFaceGroups(userId string, photoFaceGroupIds []string) (*models.PhotoFaceGroup, error)

	// RemovePhotoFaceFromGroup takes a face out of its group into a group of
	// its own, which the person has confirmed so that it is not grouped again.
	RemovePhotoFaceFromGroup(userId, photoFaceId string) (*models.PhotoFaceGroup, error)

	HidePhotoFaceGroup(userId, photoFaceGroupId string, isHidden bool) (*models.PhotoFaceGroup, error)
}

PhotoFaceOperation owns the faces found in photos and the groups they are put in: one group for each person the server believes it has seen. Every query is scoped by the owner, so a face or a group that is somebody else's is not found.

type PhotoFilter added in v0.171.0

type PhotoFilter struct {
	// BeforePhotoID continues after the last photo of the previous page, and
	// Offset skips that many photos instead, for a page reached by number.
	// Not both.
	BeforePhotoID string
	Offset        int

	PageSize int

	// IsFavorite keeps favorites when true and the rest when false.
	IsFavorite *bool

	// IsTrashed lists the trash instead of the library, newest moved to the
	// trash first rather than newest taken first (a search is still ordered
	// by how well it matches).
	IsTrashed bool

	PhotoKind models.PhotoKind

	// IsDocument keeps the photos kept as documents (a whiteboard, notes or
	// a paper document, transcribed) when true and the rest when false.
	IsDocument *bool

	// TakenAfter and TakenBefore bound the date a photo is placed at: when it
	// was taken, or when it arrived if nothing says when it was taken.
	TakenAfter  *time.Time
	TakenBefore *time.Time

	// SearchText keeps photos that match the words: a word of the place name,
	// the file name, the camera, an album's title, the description or the
	// words read in the picture, or, for the fixed fields, a part of one. The
	// result is ordered by how well it matches instead of by date, and holds
	// at most MaximumRankedPhotos photos, so a page is reached by Offset or
	// by BeforePhotoID in that order.
	SearchText string

	// SearchMeaning is SearchText as a vector, when the caller has an
	// embedding model. Described photos whose description means something
	// like it are found too, and ranked together with the matches by words.
	SearchMeaning *PhotoSearchMeaning

	// NearLatitude, NearLongitude and NearDistanceKilometers keep photos
	// taken within that distance of a point. All three or none.
	NearLatitude           *float64
	NearLongitude          *float64
	NearDistanceKilometers *float64

	// AlbumID keeps the photos of one album, whoever added them. An album the
	// person does not reach is not found. In an album the photos that are not
	// the person's come without their places, unless the share that reaches the
	// person includes them, and the trash and the favorites are the person's own.
	AlbumID string

	// FaceGroupID keeps the photos with a face in one group of faces; a group
	// that is not the person's is not found. ContactID keeps the photos with a
	// face in any group that contact names.
	FaceGroupID string
	ContactID   string

	// ContactAddressBookID, when set, narrows ContactID to the contact of
	// that address book: a contact's id is unique only within its book.
	ContactAddressBookID string
}

PhotoFilter narrows a page of the library.

type PhotoKnowledgeOperation added in v0.252.0

type PhotoKnowledgeOperation interface {
	// EnsurePhotoSource answers the agent's photos source, making it,
	// switched on, the first time. It has no schedule: nothing reads it from
	// anywhere, the documents are put in directly.
	EnsurePhotoSource(agentId string) (*models.AgentKnowledgeSource, error)

	// SetPhotoDocument keeps the transcription on a photo whose kind is kept
	// as a document, and files it as the document of the person's agent
	// named photo:<photoId>, replacing the one before. A photo in the trash
	// keeps the fields and has no document until it is put back. The photo's
	// search document is made again.
	SetPhotoDocument(userId, photoId string, document *PhotoDocument) error
}

PhotoKnowledgeOperation keeps the transcription of a photo kept as a document.

type PhotoLibraryCounts added in v0.171.0

type PhotoLibraryCounts struct {
	PhotoCount    int64
	VideoCount    int64
	FavoriteCount int64
	TrashedCount  int64
}

PhotoLibraryCounts are the totals a library page shows.

type PhotoLocation added in v0.179.0

type PhotoLocation struct {
	Latitude  float64
	Longitude float64
	PlaceName string
}

PhotoLocation is a place a person says a photo was taken. PlaceName is the text the photo shows for it, empty where no city is near.

type PhotoLocationChange added in v0.179.0

type PhotoLocationChange struct {
	ChangedPhotoIDs   []string
	DescribedPhotoIDs []string
}

PhotoLocationChange is what SetPhotoLocation changed: the photos it moved, and of those the ones whose description it cleared because their place changed.

type PhotoMetadata added in v0.171.0

type PhotoMetadata struct {
	// OwnerLocation is the owner's time zone, which gives an instant to a
	// date the file wrote as a wall clock, and an offset to a date that has
	// none. Nil is UTC.
	OwnerLocation *time.Location

	// IsTakenAtWallClock says TakenAt, which has no offset, is a reading of a
	// clock held as if it were UTC (a picture's EXIF date), and not an
	// instant that is UTC (a video container's creation time).
	IsTakenAtWallClock bool

	PhotoKind            models.PhotoKind
	WidthPixels          int
	HeightPixels         int
	DurationMS           int64
	TakenAt              *time.Time
	TakenAtOffsetMinutes *int
	Latitude             *float64
	Longitude            *float64
	PlaceName            string
	// PlaceNameLatitude and PlaceNameLongitude are the position PlaceName was
	// named from. A photo whose position is no longer that one, because the
	// person moved it while the file was read, is not given the name.
	PlaceNameLatitude  *float64
	PlaceNameLongitude *float64
	CameraMake         string
	CameraModel        string
}

PhotoMetadata is what is read from a photo's file. Zero values say the file did not say: the photo keeps what it has.

type PhotoOperation added in v0.171.0

type PhotoOperation interface {
	// CreatePhoto finds the photo with this uploader's name for it, or makes
	// it. The second value says it was made.
	CreatePhoto(photo *models.Photo) (*models.Photo, bool, error)
	GetPhoto(userId, photoId string) (*models.Photo, error)
	// LockPhoto is GetPhoto holding the photo's row until the transaction
	// ends, for a write that must not cross a change of the photo made
	// meanwhile.
	LockPhoto(userId, photoId string) (*models.Photo, error)
	// ListPhotos lists a page of the photos the filter keeps: newest first,
	// or best match first when the filter has search words.
	ListPhotos(userId string, filter *PhotoFilter) ([]*models.Photo, error)

	// ListVisitPhotos answers, per window, how many of the person's own
	// library photos sit in it (from its start, up to but not including its
	// end) and the first previewCount of them, earliest first. The key is the
	// window's VisitID; a window with no photos has an entry with a count of
	// zero. It reads what the library lists with no filter, in one query.
	ListVisitPhotos(userId string, windows []VisitPhotoWindow, previewCount int) (map[string]*VisitPhotos, error)

	// CountPhotos is how many photos the filter keeps, whatever page it
	// asks for. With search words it is at most the most a search ranks.
	CountPhotos(userId string, filter *PhotoFilter) (int, error)

	// CountUndescribedPhotos is how many of the photos the filter keeps have
	// no description yet. The filter's search words are ignored: a photo
	// nobody has described cannot be found by what is in it, so what this
	// answers is how much of the date or place range a search by words
	// cannot see into.
	CountUndescribedPhotos(userId string, filter *PhotoFilter) (int, error)

	// RequestPhotoDescription records that a description of the photo is
	// wanted, which is what a viewer shows as "describing" until it is
	// written. A photo that is not the person's is not found.
	RequestPhotoDescription(userId, photoId string) error

	// ClearPhotoDescriptionRequest records that the description is no longer
	// on its way, whether it was written or not.
	ClearPhotoDescriptionRequest(userId, photoId string) error

	// SetPhotoDescription keeps what a model said is in the picture,
	// replacing any description, and clears the request. The photo's vectors
	// are deleted, since they were made from the words it replaces, and its
	// search document is made again.
	SetPhotoDescription(userId, photoId string, description *PhotoDescription) error

	// PutPhotoVector keeps the meaning of the photo's description as one
	// model read it, replacing the vectors of other models.
	PutPhotoVector(userId, photoId, model string, vector []float32) error

	// FindPhotosByClientIDs is the photos the person has under those names: the
	// name a photo was made with, and the other names it was later recorded
	// under (see AddPhotoClientAlias). A photo found by another name comes with
	// that name as its ClientPhotoID, so that an uploader matching what it gets
	// to the names it asked for finds it.
	FindPhotosByClientIDs(userId string, clientPhotoIds []string) ([]*models.Photo, error)

	// FindPhotoByOriginalBlob is the person's oldest photo, in the library or
	// the Trash, whose original file is the blob. ErrNotFound when there is none.
	FindPhotoByOriginalBlob(userId, blobSha256 string) (*models.Photo, error)

	// AddPhotoClientAlias records another name an uploader has for the photo, so
	// that an upload of the same picture under that name is the photo. A name
	// that is taken already is left as it is.
	AddPhotoClientAlias(userId, photoId, clientPhotoId string) error

	// ReleasePhotoClientAlias takes a name off the photo it was recorded as
	// another name of, so that the name can be the own name of a photo made
	// for it. The value says there was such a name: a name that is the own
	// name of a photo, or is not an alias at all, is left as it is.
	ReleasePhotoClientAlias(userId, clientPhotoId string) (bool, error)

	// UpdatePhoto corrects a photo. A new date is stored with the offset that
	// came with it, in the same statement, so a date never keeps the offset of
	// the one it replaced.
	UpdatePhoto(userId, photoId string, update *PhotoUpdate) (*models.Photo, error)

	// SetPhotoLocation says where the named photos were taken, for the ones
	// the person owns that are not in the Trash, and says which it changed. A
	// nil location removes the location and remembers that it was removed, so
	// that reading the file again does not bring it back. A changed photo's
	// description is cleared, because it was written knowing the old place.
	SetPhotoLocation(userId string, photoIds []string, location *PhotoLocation) (*PhotoLocationChange, error)

	TrashPhotos(userId string, photoIds []string) (int, error)
	RestorePhotos(userId string, photoIds []string) (int, error)

	// MarkPhotosForDeletion deletes forever the named photos that are in the
	// trash, as far as the person can tell: they leave the trash and every
	// listing at once, and their name is freed for an upload of the same file.
	// The rows and the previews' bytes are deleted by cleanup, in batches, so
	// that a trash of thousands is not one request's transaction. It says
	// how many photos there were.
	MarkPhotosForDeletion(userId string, photoIds []string) (int, error)

	// MarkTrashForDeletion does the same to everything in the person's trash.
	MarkTrashForDeletion(userId string) (int, error)

	// ClaimPhotosForDeletion takes up to limit photos for cleanup to delete:
	// those marked, and those of any account that have been in the trash since
	// before expiredBefore, which it marks. A zero expiredBefore takes only
	// the marked. The photos stay readable by cleanup alone, so a crash in the
	// middle of deleting them is found and finished by the next pass.
	ClaimPhotosForDeletion(expiredBefore time.Time, limit int) ([]*models.Photo, error)

	// DeleteMarkedPhotos deletes the rows of marked photos, with their files
	// and previews, and says how many there were. A photo that is not marked is
	// left alone. The files' blobs are deleted by cleanup once nothing refers
	// to them. The groups of faces the photos' faces were in are worked out
	// again in the same transaction, so that a group does not keep the
	// vectors of faces that are gone, and a group left with no face is
	// deleted.
	DeleteMarkedPhotos(photoIds []string) (int, error)

	ReadPhotoLibraryCounts(userId string) (*PhotoLibraryCounts, error)

	// PhotoUsedBytes is the size of every file of every photo the account
	// has, those in the trash included and those being deleted not.
	PhotoUsedBytes(userId string) (int64, error)

	// PhotoOpenUploadBytes is how many bytes the account's uploads that are
	// still receiving hold, which count towards the account's limit before
	// they are photos. Only uploads a part arrived in after the time count: an
	// upload that has sat idle is not going to be finished soon, and cleanup
	// deletes it a week on, so it must not hold the room for a week. The
	// uploads of the named uploader photo and file role are left out when both
	// are given, because starting that upload again ends the ones before it.
	PhotoOpenUploadBytes(userId, exceptClientPhotoId string, exceptPhotoFileRole models.PhotoFileRole, updatedAfter time.Time) (int64, error)

	// PhotoOldestOpenUploadAt is when a part last arrived in the oldest of the
	// uploads PhotoOpenUploadBytes counts with the same arguments, which is
	// when its bytes stop being counted once it has sat idle for a while. The
	// value says there is one.
	PhotoOldestOpenUploadAt(userId, exceptClientPhotoId string, exceptPhotoFileRole models.PhotoFileRole, updatedAfter time.Time) (time.Time, bool, error)

	// SetPhotoFile records a file of a photo, replacing the one in that role.
	// The size is checked against the account's limit, the photo is queued for
	// processing when the file is one its previews are made from, and the
	// first value says the file differs from the one it replaced.
	SetPhotoFile(userId, photoId string, file *models.PhotoFile, maximumAccountBytes int64) (bool, error)
	GetPhotoFile(userId, photoId string, photoFileRole models.PhotoFileRole) (*models.PhotoFile, error)
	ListPhotoFiles(userId string, photoIds []string) ([]*models.PhotoFile, error)

	GetPhotoBlob(blobSha256 string) (*models.PhotoBlob, error)

	// InsertPhotoBlobIfAbsent records a blob whose bytes are stored. A blob
	// marked for deletion is unmarked and given a new age, so that cleanup
	// leaves it for the hour a file needs to name it. The value says a row was
	// made, as opposed to found.
	InsertPhotoBlobIfAbsent(blob *models.PhotoBlob) (bool, error)

	// MarkUnreferencedPhotoBlobDeleting finds the blob that no file has named
	// since before the time, oldest first, and marks it. Blobs in
	// exceptBlobSha256s are passed over: they are the ones a caller failed to
	// delete this time, so that one that cannot be deleted does not hold up the
	// rest. The mark is what a file arriving with the same bytes sees, and
	// stores them again for; the bytes are deleted after the mark is committed,
	// and the row by a second transaction, so that a crash between leaves a mark
	// and not a row whose bytes are gone.
	MarkUnreferencedPhotoBlobDeleting(unreferencedBefore time.Time, exceptBlobSha256s []string) (*models.PhotoBlob, error)

	// LockPhotoBlob takes, until the transaction ends, the lock that orders
	// everything that decides whether a blob's bytes are wanted: a file being
	// recorded against them, and cleanup deleting them. Whoever holds it sees
	// the blob, its mark, its files and its object as nobody else is changing
	// them.
	LockPhotoBlob(blobSha256 string) error

	// LockPhotoBlobForDeletion takes that lock, then locks a marked blob and
	// checks again that no file names it. A blob some file names after all, or
	// whose mark a file arriving with the same bytes cleared, comes back as nil
	// with its mark cleared; that is not an error, because an error would roll
	// the clearing back.
	LockPhotoBlobForDeletion(blobSha256 string) (*models.PhotoBlob, error)
	DeletePhotoBlob(blobSha256 string) error

	UpsertPhotoPreview(userId string, preview *models.PhotoPreview) (*models.PhotoPreview, error)
	GetPhotoPreview(userId, photoId string, photoPreviewSize models.PhotoPreviewSize) (*models.PhotoPreview, error)
	ListPhotoPreviews(userId string, photoIds []string) ([]*models.PhotoPreview, error)
	DeletePhotoPreview(userId, photoId string, photoPreviewSize models.PhotoPreviewSize) error

	// DeletePhotoPreviewMadeAt deletes the preview's row only if it is the one
	// made at that time, which is how a worker tells its own row from one that
	// a later worker wrote over it. The value says a row was deleted.
	DeletePhotoPreviewMadeAt(userId, photoId string, photoPreviewSize models.PhotoPreviewSize, madeAt time.Time) (bool, error)

	// UpdatePhotoMetadata records what reading a photo's file found. What the
	// photo already has wins over what the file says, because the uploader's
	// headers and the person's corrections were put there first, and the
	// answer to that is decided here, in the one statement that writes, so
	// that a correction made while the file was being read is not undone.
	// The one thing the file adds to a date the photo already has is its
	// offset, when the photo has none and the file's date is the same
	// moment.
	UpdatePhotoMetadata(photoId string, metadata *PhotoMetadata) error

	// ClaimPhotosForProcessing takes up to limit photos that wait for their
	// previews and are due: those nobody has claimed, and those whose claim is
	// older than the time, which the instance that made it did not finish,
	// except those that wait out a backoff. Claiming counts an attempt, so a
	// file that kills the process each time it is read runs out of attempts. A
	// photo that has used all of them and is claimed again (its last claim ran
	// out) is failed instead of returned. Each photo comes back with the time of
	// its claim in ProcessingClaimedAt, which is what the claim is known by: the
	// functions below that take it act only while the photo is still claimed at
	// that time, so work that was overtaken (the claim ran out and another
	// instance took the photo, or the photo's file was replaced) cannot record
	// its outcome over the newer work's.
	// A caller that cannot make videos at the moment (the program that does is
	// not installed) says so with isVideoSkipped, and is given no video.
	ClaimPhotosForProcessing(limit int, staleBefore time.Time, maximumAttemptCount int, isVideoSkipped bool) ([]*models.Photo, error)

	// MarkPhotoReady records that previews are made, and clears the attempts
	// and the failure. The value says the photo was still claimed at claimedAt;
	// when it is false nothing was recorded, and the photo is somebody else's
	// to finish. That is not an error.
	MarkPhotoReady(photoId string, claimedAt time.Time) (bool, error)

	// ReleasePhotoProcessingClaim gives up a claim without an outcome, as a
	// worker does that was stopped: the attempt claiming counted is given back
	// and the photo is claimable at once. The value says the photo was still
	// claimed at claimedAt.
	ReleasePhotoProcessingClaim(photoId string, claimedAt time.Time) (bool, error)

	// RetryPhotoProcessing puts the named photos that are failed, or ready (to
	// make their previews again), back to waiting with a fresh count of
	// attempts and no wait, and says how many it moved. Photos that are
	// waiting already, in the trash or somebody else's are left alone.
	RetryPhotoProcessing(userId string, photoIds []string) (int, error)

	// RenewPhotoProcessingClaim renews the claim made at claimedAt on a photo
	// an instance is still working on, so that a long video is not taken by
	// another instance while it is being made. A renewed claim is known by the
	// time it was renewed at, which the caller chooses and so knows even when
	// the answer to the renewal is lost; the value says the photo was still
	// claimed at claimedAt, and is false when the claim was lost.
	RenewPhotoProcessingClaim(photoId string, claimedAt, renewedAt time.Time) (bool, error)

	// RequeuePhotosWithoutPreviews puts up to limit photos that are ready
	// and have no small preview back to waiting, and says how many there
	// were: photos marked ready before previews were made, or whose previews
	// were lost. With isLiveVideoIncluded, a Live Photo with no video
	// preview is also put back when its video arrived after its previews
	// were last made, which is once for each video: a photo that is worked on
	// again and still has no video preview (the video is too long or cannot
	// be read) is not put back for it a second time.
	RequeuePhotosWithoutPreviews(limit int, isLiveVideoIncluded bool) (int, error)

	// MarkPhotoProcessingFailed records a failure of an attempt that claiming
	// has counted. A failure that is the file's fault keeps the count: after
	// the maximum the photo is failed and stays so, and before it the photo
	// waits for a backoff of 1, 5, 15 and then 60 minutes. A failure that is
	// not the file's (the store, the database or a program the server lacks)
	// gives the attempt back, so that an outage does not use up a photo's
	// attempts; the photo waits 1, 5, 15 and then 60 minutes, by how many such
	// failures there have been in a row. The message is kept as given and must
	// be plain: no path and no output of a tool. As with MarkPhotoReady, the value says the photo was
	// still claimed at claimedAt; when it is false nothing was recorded.
	MarkPhotoProcessingFailed(photoId string, claimedAt time.Time, errorMessage string, isFileAtFault bool, maximumAttemptCount int) (bool, error)
}

PhotoOperation owns the library: photos, their files and previews, and the blobs the files name. Every query is scoped by the owner, so a photo that is somebody else's is not found.

type PhotoReadingOperation added in v0.209.0

type PhotoReadingOperation interface {
	// IsPhotoReadingEnabled is the person's own switch for having their new
	// photos read; on until they turn it off.
	IsPhotoReadingEnabled(userId string) (bool, error)

	// SetPhotoReading switches it on or off. Off leaves what was read.
	SetPhotoReading(userId string, isEnabled bool) error

	// ListPhotosToRead lists up to limit pictures and videos of the person's
	// library, newest first, that are ready, were taken (or added, when they
	// carry no date) at or after since, and have been neither described,
	// asked to be, nor queued to be read. Photos saved from somebody else's
	// share are not read.
	ListPhotosToRead(userId string, since time.Time, limit int) ([]*models.Photo, error)

	// MarkPhotoReadingQueued records that a photo was queued to be read.
	MarkPhotoReadingQueued(userId, photoId string) error

	// GetPhotoDocumentsBackfilledAt answers when the one-time pass over the
	// person's described photos began (see ClaimPhotoDocumentsBackfill), nil
	// when it has not.
	GetPhotoDocumentsBackfilledAt(userId string) (*time.Time, error)

	// ClaimPhotoDocumentsBackfill records that the one-time pass over the
	// person's photos described before documents were kept begins at the
	// time. It answers whether this call made the claim: a person is claimed
	// once, however many instances ask.
	ClaimPhotoDocumentsBackfill(userId string, at time.Time) (bool, error)

	// ListPhotosToReadAgainAsDocuments lists up to limit pictures of the
	// person's library that were described before the time and might be a
	// whiteboard, notes or a paper document: their kind is none or unknown
	// and the words read in them are at least PhotoDocumentCandidateWordsLength
	// characters, or their description names such a thing. Newest first,
	// continuing after the photo afterPhotoId when it is given. Photos that
	// are waiting for a description, are in the trash, were saved from
	// somebody else's share or are videos are not listed.
	ListPhotosToReadAgainAsDocuments(userId string, describedBefore time.Time, afterPhotoId string, limit int) ([]*models.Photo, error)
}

PhotoReadingOperation is reading new photos as they arrive: the person's switch, and the photos waiting to be queued.

type PhotoSearchMeaning added in v0.171.0

type PhotoSearchMeaning struct {
	ModelName string
	Vector    []float32
}

PhotoSearchMeaning is some words as one embedding model read them.

type PhotoUpdate added in v0.171.0

type PhotoUpdate struct {
	IsFavorite *bool

	// TakenAt is the new date, and TakenAtOffsetMinutes the offset that came
	// with it; they are stored together. An offset needs a date.
	TakenAt              *time.Time
	TakenAtOffsetMinutes *int
}

PhotoUpdate is what a person may correct about a photo. Fields left nil are kept.

type PhotoUploadOperation added in v0.171.0

type PhotoUploadOperation interface {
	// CreatePhotoUpload starts an upload. Any upload of the same uploader's name
	// and file role that is still receiving is ended first (its parts are
	// deleted by cleanup): a client that starts again has no use for the one
	// it left, and restarts must not pile up towards the limit of open
	// uploads.
	CreatePhotoUpload(upload *models.PhotoUpload) (*models.PhotoUpload, error)
	GetPhotoUpload(userId, photoUploadId string) (*models.PhotoUpload, error)
	ListPhotoUploadParts(userId, photoUploadId string) ([]*models.PhotoUploadPart, error)

	// AppendPhotoUploadPart records a whole stored part. The offset is where
	// the caller believes the upload stands, and a different one is refused
	// with ErrAlreadyExists: somebody else appended in between.
	AppendPhotoUploadPart(userId string, part *models.PhotoUploadPart, expectedOffsetBytes int64) (*models.PhotoUpload, error)

	CompletePhotoUpload(userId, photoUploadId, photoId string) (*models.PhotoUpload, error)

	// FailPhotoUpload ends an upload that is still receiving. Its parts are
	// deleted by cleanup.
	FailPhotoUpload(userId, photoUploadId string) (*models.PhotoUpload, error)

	// LockPhotoUploadForCleanup finds one upload that has failed, or has not
	// moved since the time, and locks it. ErrNotFound says there is none.
	LockPhotoUploadForCleanup(idleBefore time.Time) (*models.PhotoUpload, error)
	ListPhotoUploadPartsForCleanup(photoUploadId string) ([]*models.PhotoUploadPart, error)
	DeletePhotoUpload(photoUploadId string) error

	// ListPhotoUploadsOfAccount lists a page of the account's uploads of any
	// state, in the order of their identifiers after the given one, for
	// deleting the objects they name before the account goes.
	ListPhotoUploadsOfAccount(userId, afterPhotoUploadId string, limit int) ([]*models.PhotoUpload, error)

	// ListPhotoIDsOfAccount lists a page of the identifiers of all the
	// account's photos, those in the trash and those being deleted included,
	// in order after the given one, for the same.
	ListPhotoIDsOfAccount(userId, afterPhotoId string, limit int) ([]string, error)
}

PhotoUploadOperation owns resumable uploads and the receipts of their parts.

type PlaceChanges added in v0.175.0

type PlaceChanges struct {
	// PlaceName is the person's name for the place. Empty, on a place the
	// person named, takes their name away: the OpenStreetMap name comes back,
	// or, with none, no name at all and the place waits to be named again.
	PlaceName *string

	// PlaceLabel is the label; the pointer to the empty label takes it off.
	PlaceLabel *models.PlaceLabel

	// LatitudeDegrees and LongitudeDegrees move the place and are changed
	// together.
	LatitudeDegrees  *float64
	LongitudeDegrees *float64

	RadiusMeters *float64

	// AddressText is an address the person typed; empty takes a typed address
	// away, and the place waits to be named again. Typing one drops what a
	// provider said about the spot (object, name, category) whether or not the
	// place moves: the person said the place is at this address, and the map's
	// name for the spot is not this place. With the coordinates of a match the
	// person picked, the place moves there; without, it stays where it is.
	// Either way the place keeps this address: it counts as named already, so
	// the naming job does not replace it. A place the person did not name is
	// called by the first part of the address.
	AddressText *string

	// MovedPlaceName is the name a place the person did not name takes when it
	// moves farther than its radius: what was learned about the old position is
	// dropped, and the place goes back to the name of its city until it is
	// named again. The caller looks the city up, since this package cannot.
	// Empty leaves the place with no name until the provider names it.
	MovedPlaceName string
}

PlaceChanges is what a person may change about a place. A nil field is left as it is.

type PlaceDistance added in v0.175.0

type PlaceDistance struct {
	Place          *models.Place
	DistanceMeters float64
}

PlaceDistance is one of the person's places and how far its center is from a point that was asked about.

type PlaceFilter added in v0.175.0

type PlaceFilter struct {
	// PlaceLabel keeps places with this label.
	PlaceLabel models.PlaceLabel

	// Query keeps places whose name, OpenStreetMap name or address contains
	// these words, whatever the case.
	Query string

	Offset     int
	LimitCount int
}

PlaceFilter narrows and pages a listing of places.

type PlaceVisitFilter added in v0.175.0

type PlaceVisitFilter struct {
	// From and Until keep visits that overlap the range: those that ended at
	// or after From and began before Until. A visit still in progress has not
	// ended.
	From  *time.Time
	Until *time.Time

	PlaceID    string
	PlaceLabel models.PlaceLabel

	Offset     int
	LimitCount int
}

PlaceVisitFilter narrows and pages a listing of visits.

type PlaceVisitSummary added in v0.175.0

type PlaceVisitSummary struct {
	VisitCount  int
	LastVisitAt *time.Time
}

PlaceVisitSummary is how often a place was visited and when last.

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)

	// ListRecordingsBetween is the person's recordings that were made from
	// from up to but not including until (by recordedAt, else by when it
	// arrived), earliest first and at most limit, not counting deleted ones.
	ListRecordingsBetween(userId string, from, until time.Time, 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 RecordingShareOperation added in v0.194.0

type RecordingShareOperation interface {
	// ShareRecording gives a person or a circle a level of access to one of
	// the sharer's own recordings, or changes the level they have, and answers
	// the share as stored. ErrNotFound unless the recording is the sharer's
	// and not deleted and, for a person, the two share a circle, or, for a
	// circle, the sharer is in it. ErrInvalidArguments for a level that cannot
	// be given, a grantee that is not exactly one, or the sharer themselves.
	ShareRecording(sharerUserId string, share *models.RecordingShare) (*models.RecordingShare, error)

	// ListRecordingShares are a recording's shares with who they are for,
	// oldest first.
	ListRecordingShares(recordingId string) ([]*models.RecordingShare, error)

	// ListRecordingSharesBy are the shares the person has made of their own
	// recordings, oldest first, with who each is for and which recording.
	ListRecordingSharesBy(ownerUserId string) ([]*models.RecordingShare, error)

	// ListRecordingSharesReaching are the shares that reach the person now,
	// oldest first, with whose recording each is. A share to a person reaches
	// them only while the two still share a circle, and a share to a circle
	// only while both are in it. Not the person's own.
	ListRecordingSharesReaching(userId string) ([]*models.RecordingShare, error)

	// DeleteRecordingShare takes one of the owner's shares back. ErrNotFound
	// when there is none, or it is of somebody else's recording.
	DeleteRecordingShare(ownerUserId, shareId string) error

	// GetRecordingShareLevel is the highest level the shares reaching the
	// reader give them for the recording, and the empty level when none does.
	// The owner is not asked about: a person reads their own recording without
	// a share.
	GetRecordingShareLevel(readerUserId, recordingId string) (models.RecordingShareLevel, error)

	// ListSharedRecordings are the recordings shared with the reader, newest
	// first, each as the reader's level shows it and without the speaker names
	// or the transcript, which a read of one gives. An owner narrows them to
	// one person's. beforeRecordingId continues a list.
	ListSharedRecordings(readerUserId, ownerUserId, beforeRecordingId string, limit int) ([]*models.SharedRecording, error)

	// ReadSharedRecording is one recording shared with the reader as their
	// level shows it, with, at the transcript level, a page of the transcript
	// from passageOffset. ErrNotFound when no share reaches the reader.
	ReadSharedRecording(readerUserId, recordingId string, passageOffset, pageSize int) (*models.SharedRecording, error)
}

RecordingShareOperation is who may read which recording, and how much: a person's recording shared with another person or with a circle at a level (summary or transcript), as a calendar is shared at a level.

"At what level may this person read this recording" has one answer, GetRecordingShareLevel, and every door asks it. What a level shows is made in one place, models.RedactRecording, which ReadSharedRecording and ListSharedRecordings use and nothing else does. A caller that compares a recording's UserID with the person itself is wrong for somebody who left the circle that made the share possible.

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
	// ContactAddressBookID and ContactID, both or neither, tie the confirmed
	// name to a contact of the person: a name already tied to another contact
	// is tied to this one instead. Neither leaves the name's tie as it is.
	ContactAddressBookID     string
	ContactID                string
	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)

	// ConfirmRecordingKnownSpeaker names, in every piece of a completed run,
	// the speaker of an original that is one person's microphone: the
	// person themselves when it is the owner's own. A run of an original of
	// several voices is left for the person to name.
	ConfirmRecordingKnownSpeaker(userId, runId string) error
	RenameRecordingSpeaker(userId, recordingId, speakerIdentityId, confirmedName string, expectedSourceGeneration int64) error
	SetRecordingSpeakerContact(userId, recordingId, speakerIdentityId, addressBookId, contactId string, expectedSourceGeneration int64) error
	ListRecordingsSpokenByContact(userId string, addressBookId string, contactId string, limit int) ([]*RecordingSpokenByContact, bool, 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 RecordingSpokenByContact added in v0.188.0

type RecordingSpokenByContact struct {
	Recording          *models.Recording
	SpokenPassageCount int
}

RecordingSpokenByContact is a recording with how many of its passages a speaker tied to the contact speaks.

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
	NameRecordingTemporarySpeakerAsContact(userId, recordingId, speakerLabel, confirmedName string, isAccountOwner bool, addressBookId, contactId string) 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 RelationshipOperation added in v0.178.0

type RelationshipOperation interface {
	// ListPersonRelationships returns every relationship a person is in with
	// somebody they share a circle with.
	ListPersonRelationships(userId string) ([]*models.PersonRelationship, error)

	// GetPersonRelationship returns the relationship between two people, or
	// nil when nothing was said or they share no circle.
	GetPersonRelationship(userId, otherUserId string) (*models.PersonRelationship, error)

	// SetPersonRelationship says, from userId's side, that relatedUserId is
	// their relationshipKind, replacing whatever either of them said before.
	// It does not check that they share a circle; the caller does.
	SetPersonRelationship(userId, relatedUserId string, relationshipKind models.RelationshipKind, relatedUserTermGender models.TermGender) (*models.PersonRelationship, error)

	// RemovePersonRelationship takes away the relationship between two
	// people, whichever of them said it, and says whether there was one.
	RemovePersonRelationship(userId, otherUserId string) (bool, error)

	// TakeRelationshipNotice says whether one person may tell another about
	// a relationship between them now, and if so records that they did: at
	// most once in each interval, whatever was said and taken back between.
	TakeRelationshipNotice(userId, toldUserId string, now time.Time, interval time.Duration) (bool, error)
}

RelationshipOperation is what people who share a circle are to each other. There is one row for a pair, from the side of whoever said it last; see migration 0243. It goes in the transaction in which the two stop sharing any circle (endRelationshipsOutsideCircles), and is read only while they share one all the same.

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 SharedFinanceTransactionFilter added in v0.194.0

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

	// Limit is at most FinanceTransactionLimitMost; zero is
	// FinanceTransactionLimitDefault. After is the NextCursor of the page
	// before, and Offset how many to pass over first, counted from the cursor
	// when both are given.
	Limit  int
	After  string
	Offset int
}

SharedFinanceTransactionFilter narrows a page of a shared account's transactions. Every field is optional.

type SharedFinanceTransactionPage added in v0.194.0

type SharedFinanceTransactionPage struct {
	FinanceTransactions []*models.SharedFinanceTransaction
	NextCursor          string
	TotalCount          int
}

SharedFinanceTransactionPage is one page of a shared account's transactions, the cursor for the next, empty on the last, and how many transactions the account has in the days asked for, on every page.

type SharingOperation added in v0.194.0

type SharingOperation interface {
	// ListCalendarSharesReaching are the shares of other people's calendars
	// that reach the person now, oldest first, each with the calendar's name
	// and its owner.
	ListCalendarSharesReaching(readerUserId string) ([]*models.ShareRow, error)

	// ListLocationSharesReaching are the shares of other people's location
	// that reach the person now, oldest first, with the owner.
	ListLocationSharesReaching(viewerUserId string) ([]*models.ShareRow, error)

	// ListPhotoAlbumSharesReaching are the shares of other people's albums
	// that reach the person now, oldest first, with the album's title and its
	// owner. An album the person owns or belongs to through a circle that
	// owns it is not a share.
	ListPhotoAlbumSharesReaching(readerUserId string) ([]*models.ShareRow, error)

	// ListPhotoAlbumSharesBy are the shares of all of the owner's albums,
	// oldest first, with the album's title and who each is for.
	ListPhotoAlbumSharesBy(ownerUserId string) ([]*models.ShareRow, error)

	// ListPasswordSharesBy are, for each person or circle the owner shares
	// items with, how many items that are not deleted. Never which: an item's
	// title is sealed. A row has no ShareID, since the shares are one for each
	// item.
	ListPasswordSharesBy(ownerUserId string) ([]*models.ShareRow, error)

	// ListPasswordSharesReaching are, for each owner and way of reaching
	// (direct, or through one circle), how many of the owner's items that are
	// not deleted reach the person now.
	ListPasswordSharesReaching(viewerUserId string) ([]*models.ShareRow, error)

	// ListCircleShareOwners are the members of the circle who have shared
	// something with it, with the kinds: calendar, location, Health, memory
	// pages, photo albums, recordings and finance accounts. A skill is shared
	// with one person, and passwords wait for a key, so neither is listed.
	ListCircleShareOwners(circleId string) ([]*models.CircleShareOwner, error)

	// GetPhotoAlbumShare is one share of an album the person manages, or
	// ErrNotFound: before it is changed, to tell whether the change widens it.
	GetPhotoAlbumShare(userId, photoAlbumShareId string) (*models.PhotoAlbumShare, error)

	// DeclineLocationShare ends a share of somebody's location that was made
	// to the person by name, and answers whose location it was. ErrNotFound
	// unless the share is to that person, which a share to a circle never is.
	DeclineLocationShare(granteeUserId, shareId string) (string, error)

	// DeclineHealthShare ends a share of somebody's Health that was made to
	// the person by name. ErrNotFound unless the share is to that person.
	DeclineHealthShare(granteeUserId, shareId string) error

	// DeclinePhotoAlbumShare ends a share of an album that was made to the
	// person by name, and takes out of the album the photos the person added.
	// ErrNotFound unless the share is to that person.
	DeclinePhotoAlbumShare(granteeUserId, shareId string) error

	// DeclineRecordingShare ends a share of somebody's recording that was
	// made to the person by name. ErrNotFound unless the share is to that
	// person, which a share to a circle never is.
	DeclineRecordingShare(granteeUserId, shareId string) error

	// DeclineFinanceShare ends a share of somebody's finance account, or of all
	// of their finance, that was made to the person by name. ErrNotFound unless the share is to that
	// person, which a share to a circle never is.
	DeclineFinanceShare(granteeUserId, shareId string) error
}

SharingOperation is what the one place that lists everything a person shares (the Sharing page) needs beyond the questions each kind of share answers for itself: the shares that reach a person, with the row each is, where the kind's own operation answers only the highest level, and the shares of the person's albums and passwords in one read. It also ends a share from the side of the person it is for.

Nothing here decides who may see what. Each reading query is the kind's own (reachingSharesQuery, reachingLocationSharesQuery, photoAlbumReachQuery, passwordReachSQL) with the columns that name the share added, so that the list and the access check cannot disagree about who is reached.

type ShoppingEvent added in v0.201.0

type ShoppingEvent struct {
	ShoppingListID string `json:"shoppingListId"`

	// EndedForUserIDs are people who could read the list until now and
	// cannot any longer (a share ended, the list was deleted), told so that
	// a screen they have open reads again and drops it.
	EndedForUserIDs []string `json:"endedForUserIds,omitempty"`
}

ShoppingEvent is what travels on ShoppingEventChannel: which list changed. What changed is read from the tables by whoever may.

type ShoppingItemOperation added in v0.201.0

type ShoppingItemOperation interface {
	// ListShoppingItems are a page of a list's items in the given states (all
	// of them when none is given), by aisle and then by their order, with how
	// many there are in all. A search text keeps the items whose description,
	// details, store or aisle hold every word of it, without case; the apps
	// filter a list they have loaded by the same rule.
	ListShoppingItems(userId, shoppingListId string, shoppingItemStates []models.ShoppingItemState, searchText string, offset, limit int) ([]*models.ShoppingItem, int64, error)

	// GetShoppingItem is one item on a list the person reaches.
	GetShoppingItem(userId, shoppingItemId string) (*models.ShoppingItem, error)

	// GetShoppingItemByID is one item whoever asks, for the server's own jobs.
	// ErrNotFound when there is none.
	GetShoppingItemByID(shoppingItemId string) (*models.ShoppingItem, error)

	// AddShoppingItems puts items on a list the person reaches. An item that
	// is already on it, by its description and store compared without case,
	// is needed again rather than added twice: its count needed becomes the
	// larger of the two and new details are added to its own. It answers the
	// items as stored, in the order given, and for each whether it was
	// merged into one already there.
	AddShoppingItems(userId, shoppingListId string, items []*models.ShoppingItem) ([]*models.ShoppingItem, []bool, error)

	// FindShoppingItemToMerge is the item on the list that an item of this
	// description and store would be merged into, or nil.
	FindShoppingItemToMerge(userId, shoppingListId, itemDescription, storeName string) (*models.ShoppingItem, error)

	// UpdateShoppingItem changes what the change sets on an item.
	UpdateShoppingItem(userId, shoppingItemId string, change *models.ShoppingItemChange) (*models.ShoppingItem, error)

	// RemoveShoppingItems takes items off the lists the person reaches and
	// answers the lists they were on. ErrNotFound when one of them is not an
	// item the person reaches; then nothing is removed.
	RemoveShoppingItems(userId string, shoppingItemIds []string) ([]string, error)

	// CheckShoppingItem puts an item in the cart (checked) or back to needed
	// (unchecked, only from the person's own cart). Checking clears out of
	// stock. Putting something in the cart is shopping: a person with no open
	// trip starts one at storeName (the item's store when empty), and an open
	// trip that does not name the item's list gains it. The trip it started,
	// if any, is answered, for the others to be told, with the lists that
	// changed when starting it ended a stale trip.
	CheckShoppingItem(userId, shoppingItemId string, isChecked bool, storeName string) (*models.ShoppingItem, *models.ShoppingTrip, []string, error)

	// SetShoppingItemNeed makes an item needed with a count (Need again), or,
	// with isNeeded false, not needed: bought when it was in the cart.
	SetShoppingItemNeed(userId, shoppingItemId string, isNeeded bool, neededQuantity string) (*models.ShoppingItem, error)

	// CheckOffShoppingItem is the check on a list, for a person who is not
	// shopping: a needed item (or one in their own cart) is bought now, with
	// no trip and nobody told. Unchecked, it is needed again, and when it was
	// bought within models.ShoppingPurchaseUndoableFor the purchase is taken
	// back, so it was last bought when it was before. An item in somebody
	// else's cart is left there.
	CheckOffShoppingItem(userId, shoppingItemId string, isCheckedOff bool) (*models.ShoppingItem, error)

	// SetShoppingItemOutOfStock marks an item out of stock at a store, or
	// takes the mark off.
	SetShoppingItemOutOfStock(userId, shoppingItemId string, isOutOfStock bool, storeName string) (*models.ShoppingItem, error)

	// SetShoppingItemPicture gives an item a picture kept in the file store,
	// and answers the file of the picture it had, for the caller to remove.
	// The server's own; the caller has checked the person may.
	// A picture found on the web is written only while the item still has
	// the picture it had when the search began (expectedPictureFileId) and
	// that picture is not one a person uploaded; otherwise
	// ErrShoppingPictureChanged and nothing is written.
	SetShoppingItemPicture(shoppingItemId, pictureFileId, picturePageUrl string, pictureSource models.ShoppingPictureSource, expectedPictureFileId string) (string, error)

	// MarkShoppingItemPictureSearched records that a search for the item's
	// picture was made now, found or not.
	MarkShoppingItemPictureSearched(shoppingItemId string) error

	// RecordShoppingItemPrice keeps a price seen for an item, and makes it the
	// item's price when it is the newest.
	RecordShoppingItemPrice(userId string, price *models.ShoppingItemPrice) (*models.ShoppingItemPrice, error)

	// ListShoppingItemPrices are an item's prices, newest first.
	ListShoppingItemPrices(userId, shoppingItemId string) ([]*models.ShoppingItemPrice, error)

	// ListSimilarShoppingItems are the items, on the list named and the other
	// lists the person reaches, that read like what is about to be added,
	// nearest first: a few, for somebody to go to one instead of adding it.
	ListSimilarShoppingItems(userId, shoppingListId, itemDescription string) ([]*models.ShoppingItem, error)

	// ListShoppingStores are the stores the items of the person's lists are
	// for, by name, with how many are needed at each and whether the person
	// is reminded there.
	ListShoppingStores(userId string) ([]*models.ShoppingStore, error)

	// ListShoppingStoreItems are the needed and in-cart items for a store on
	// the lists the person reaches (those named, or all), and, when asked,
	// the items for any store, by aisle; each says which list it is on.
	ListShoppingStoreItems(userId, storeName string, shoppingListIds []string, isAnyStoreIncluded bool) ([]*models.ShoppingItem, error)

	// ListShoppingItemsNeededAt are the needed items at a store for the
	// arrival reminder: on the lists the person reaches and is reminded of,
	// for that store, and for any store when asked.
	ListShoppingItemsNeededAt(userId, storeKey string, isAnyStoreIncluded bool) ([]*models.ShoppingItem, error)
}

ShoppingItemOperation is the items on shopping lists, their prices, and the stores they are for. Every operation that takes an item asks whether the person reaches the item's list (GetShoppingListAccess).

type ShoppingOperation added in v0.201.0

type ShoppingOperation interface {
	// GetShoppingListAccess is how the person reaches the list. ErrNotFound
	// when there is no such list or it does not reach them.
	GetShoppingListAccess(userId, shoppingListId string) (*models.ShoppingListAccess, error)

	// CreateShoppingList makes a list of the person's.
	CreateShoppingList(userId, listName string) (*models.ShoppingList, error)

	// RenameShoppingList renames a list the person reaches.
	RenameShoppingList(userId, shoppingListId, listName string) (*models.ShoppingList, error)

	// DeleteShoppingList deletes one of the person's own lists with its
	// items, prices and shares. ErrNotFound unless it is theirs.
	DeleteShoppingList(userId, shoppingListId string) error

	// ListShoppingLists are the lists the person reaches, their own first,
	// then by name, each with its counts.
	ListShoppingLists(userId string) ([]*models.ShoppingList, error)

	// GetShoppingList is one list the person reaches, with its counts.
	GetShoppingList(userId, shoppingListId string) (*models.ShoppingList, error)

	// ShareShoppingList gives a person or a circle one of the sharer's own
	// lists. ErrNotFound unless the list is the sharer's and, for a person,
	// the two share a circle, or, for a circle, the sharer is in it.
	// ErrInvalidArguments for a grantee that is not exactly one, or the
	// sharer themselves. Sharing again with the same grantee answers the
	// share there is.
	ShareShoppingList(sharerUserId string, share *models.ShoppingListShare) (*models.ShoppingListShare, error)

	// ListShoppingListShares are a list's shares, oldest first, with who each
	// is for. ErrNotFound unless the list is the person's.
	ListShoppingListShares(userId, shoppingListId string) ([]*models.ShoppingListShare, error)

	// ListShoppingListSharesBy are the shares the person has made of their
	// own lists, oldest first.
	ListShoppingListSharesBy(ownerUserId string) ([]*models.ShoppingListShare, error)

	// ListShoppingListSharesReaching are the shares that reach the person
	// now, oldest first: not their own lists.
	ListShoppingListSharesReaching(userId string) ([]*models.ShoppingListShare, error)

	// DeleteShoppingListShare takes one of the owner's shares back.
	// ErrNotFound when there is none, or it is of somebody else's list.
	DeleteShoppingListShare(ownerUserId, shoppingListShareId string) error

	// DeclineShoppingListShare ends a share made to the person by name.
	// ErrNotFound for any other.
	DeclineShoppingListShare(granteeUserId, shoppingListShareId string) error

	// ListShoppingListReaderUserIDs are everybody the list reaches now, its
	// owner included, once each.
	ListShoppingListReaderUserIDs(shoppingListId string) ([]string, error)

	// SetShoppingListReminder says whether the person is reminded of the
	// list when they arrive at a store. On until they turn it off.
	SetShoppingListReminder(userId, shoppingListId string, isReminded bool) error

	// ListShoppingListReminderMuters are the people who muted the list.
	ListShoppingListReminderMuters(shoppingListId string) ([]string, error)

	// SetShoppingStoreReminder says whether the person is reminded at a
	// store at all.
	SetShoppingStoreReminder(userId, storeName string, isReminded bool) error

	// ListShoppingStoreMuteKeys are the store keys the person asked never to
	// be reminded at.
	ListShoppingStoreMuteKeys(userId string) ([]string, error)

	ShoppingItemOperation
	ShoppingTripOperation
	ShoppingReceiptOperation
}

ShoppingOperation is shopping lists: a person's named lists of things to buy, shared with a person or a circle, checked off at the store and by a receipt, and remembered with their prices.

"May this person read and change this list" has one answer, GetShoppingListAccess, and every operation that takes a list or an item asks it. A list reaches its owner and the people its shares reach: a share to a person while the two share a circle, a share to a circle while both the reader and the owner are in it, and only while the owner is enabled and has shopping:use. Everybody it reaches may do everything to it except share it further and delete it, which are the owner's.

type ShoppingReceiptOperation added in v0.201.0

type ShoppingReceiptOperation interface {
	// ListShoppingReceiptCandidates are the items a receipt from this
	// merchant could have bought: needed, in the cart or bought within
	// models.ShoppingReceiptBoughtWithin, on the lists the
	// person reaches, for a store whose name the merchant's contains (or the
	// other way round), or for any store.
	ListShoppingReceiptCandidates(userId, merchantName string) ([]*models.ShoppingItem, error)

	// ApplyShoppingReceiptMatches writes what the matcher found for one of
	// the person's receipts: a sure tie checks its item off and writes its
	// price; an unsure one is proposed. A line or an item that already has a
	// match on this receipt is skipped, so running the matcher again changes
	// nothing that was decided. It answers the matches written and the lists
	// whose items changed.
	ApplyShoppingReceiptMatches(userId, financeReceiptId string, proposals []*models.ShoppingReceiptMatchProposal) ([]*models.ShoppingReceiptMatch, []string, error)

	// ListShoppingReceiptMatches are a receipt's matches to items the person
	// reaches, in the order of the receipt's lines.
	ListShoppingReceiptMatches(userId, financeReceiptId string) ([]*models.ShoppingReceiptMatch, error)

	// DecideShoppingReceiptMatch applies a proposed match, or dismisses one,
	// undoing it when it was applied. It answers the match and its item's list.
	DecideShoppingReceiptMatch(userId, shoppingReceiptMatchId string, isApplied bool) (*models.ShoppingReceiptMatch, string, error)

	// MatchShoppingReceiptLine ties a line of one of the person's receipts to
	// an item they reach, applied, as a person decides it.
	MatchShoppingReceiptLine(userId, financeReceiptLineId, shoppingItemId string) (*models.ShoppingReceiptMatch, string, error)

	// UndoShoppingReceipt undoes every applied match of one of the person's
	// receipts, and answers the lists whose items changed.
	UndoShoppingReceipt(userId, financeReceiptId string) ([]string, error)

	// AddShoppingItemFromReceiptLine puts what a line bought on a list the
	// person reaches, as bought, with the line's price.
	AddShoppingItemFromReceiptLine(userId, financeReceiptLineId, shoppingListId string) (*models.ShoppingItem, error)
}

ShoppingReceiptOperation ties the lines of a Finance receipt to the items of the shopping lists its owner reaches. A receipt is one system: however it arrived, its lines check items off and remember their price at the store, and what was applied can be undone.

The receipt is the person's own (its agent is theirs); the items are on lists they reach. A match is never written to an item they do not reach.

type ShoppingTripOperation added in v0.201.0

type ShoppingTripOperation interface {
	// StartShoppingTrip starts the person shopping a store for lists they
	// reach. It finishes their own trip that is still open, and every trip on
	// these lists that started more than models.ShoppingTripStaleAfter ago,
	// buying what those had in the cart. It answers the trip and the lists
	// whose items were bought by finishing the others.
	StartShoppingTrip(userId, storeName string, shoppingListIds []string) (*models.ShoppingTrip, []string, error)

	// FinishShoppingTrip ends one of the person's trips: what they put in
	// the cart on any list they reach is bought. It answers the trip as
	// finished and the lists whose items were bought. ErrNotFound unless the
	// trip is theirs and open. With no trip named it ends the person's own
	// open trip, however old; with none open, what they have in the cart is
	// bought all the same, recorded as a trip that starts and ends now, and
	// with nothing in the cart either it is ErrInvalidArguments.
	FinishShoppingTrip(userId, shoppingTripId string) (*models.ShoppingTrip, []string, error)

	// ResumeShoppingTrip opens again one of the person's trips that finished
	// within models.ShoppingPurchaseUndoableFor: what it bought and is still
	// bought goes back in their cart, last bought when it was before. It
	// answers the trip, open, and the lists whose items came back.
	// ErrNotFound unless the trip is theirs and finished; ErrInvalidArguments
	// when it finished too long ago or they are shopping another trip now.
	ResumeShoppingTrip(userId, shoppingTripId string) (*models.ShoppingTrip, []string, error)

	// GetResumableShoppingTrip is the person's latest trip, when it finished
	// within models.ShoppingPurchaseUndoableFor, something it bought is still
	// bought, and they have no trip open now; nil otherwise.
	GetResumableShoppingTrip(userId string) (*models.ShoppingTrip, error)

	// ListOpenShoppingTrips are the trips open now on the lists the person
	// reaches, theirs included, newest first, each with who is shopping.
	ListOpenShoppingTrips(userId string) ([]*models.ShoppingTrip, error)

	// ListShoppingTripsBetween are the person's own trips that started in
	// [from, until), oldest first, each naming only the lists the person
	// still reaches: the trips of a journal day. Past shoppingTripsOfADayMost
	// it keeps the latest ones, which a day's story is likelier to be about.
	ListShoppingTripsBetween(userId string, from, until time.Time) ([]*models.ShoppingTrip, error)

	// GetShoppingTrip is one of the person's own trips, naming only the lists
	// they still reach. ErrNotFound when it is somebody else's or gone.
	GetShoppingTrip(userId, shoppingTripId string) (*models.ShoppingTrip, error)
}

ShoppingTripOperation is somebody shopping a store now. A trip names the lists it is for; while it is open, what its shopper checks off on them is in the cart, and when it ends what they put in the cart is bought.

type SkillShareOperation added in v0.170.0

type SkillShareOperation interface {
	// ShareSkill shares the owner's skill tools with one person, or changes
	// the tools and limits when it is shared with them already. ErrNotFound
	// unless the owner has an agent, the grantee exists and is not the owner,
	// and the two share a circle. ErrInvalidArguments for no tools or a limit
	// with no currency. Whether the skill is installed and declares the tools
	// is the caller's to check.
	ShareSkill(ownerUserId string, share *models.SkillShare) (*models.SkillShare, error)

	// GetSkillShare is one share, or nil.
	GetSkillShare(shareId string) (*models.SkillShare, error)

	// ListSkillSharesOf are the shares of one installed skill, by whoever
	// made them. An installed skill that is saved again is checked against
	// them.
	ListSkillSharesOf(skillName string) ([]*models.SkillShare, error)

	// RequireSkillShareApproval makes every call of a share wait for the
	// owner, and says whether it changed anything: false when the share
	// already did or is gone.
	RequireSkillShareApproval(shareId string) (bool, error)

	// LockSkillShare is a share with its row held until the transaction ends,
	// so that two calls deciding at once against the month's limit take turns.
	// ErrNotFound when there is none.
	LockSkillShare(shareId string) (*models.SkillShare, error)

	// ListSkillSharesBy are the shares the person made, by skill and then by
	// who they are for.
	ListSkillSharesBy(ownerUserId string) ([]*models.SkillShare, error)

	// ListSkillSharesReaching are the shares made to the person by somebody
	// who still shares a circle with them, with the owner named.
	ListSkillSharesReaching(granteeUserId string) ([]*models.SkillShare, error)

	// DeleteSkillShare takes one back. Its calls stay, as the record of what
	// was asked of the owner's money, without a share; the ones that were
	// waiting for approval expire, since nobody can approve a call of a share
	// that is gone. ErrNotFound when there is none.
	DeleteSkillShare(shareId string) error

	// CreateSkillShareCall records one call of a share, which fills in whose
	// skill it was and for whom. The caller sets its state; a call that waits
	// has an ExpiresAt. ErrNotFound when the share is gone.
	CreateSkillShareCall(call *models.SkillShareCall) (*models.SkillShareCall, error)

	// GetSkillShareCall is one call, or nil.
	GetSkillShareCall(callId string) (*models.SkillShareCall, error)

	// ListSkillShareCalls are a share's calls, waiting ones first and then
	// newest first. A state narrows them; empty is every state.
	ListSkillShareCalls(shareId string, callState models.SkillShareCallState, limit int) ([]*models.SkillShareCall, error)

	// ListEndedSkillShareCalls are the calls of shares that have ended and
	// that the person made the share of (the owner, who sees all of them) or
	// made (the other person, who sees their own), newest first, with the
	// people named. A state narrows them; empty is every state.
	ListEndedSkillShareCalls(userId string, callState models.SkillShareCallState, limit int) ([]*models.SkillShareCall, error)

	// SkillShareMonthTotal is what the calls of one skill from one owner's
	// agent to one person, that ran and failed, come to, in the currency, for
	// those that ran from the moment to the moment (a call that waited ran when
	// it was approved), and no other calls: one that was refused, declined,
	// expired or still waits has paid nothing. A call that failed counts,
	// because a failure after the command acted cannot be told from one before
	// it, and the month's limit is the owner's bound on what could have been
	// spent. The calls are counted by who they were between and not by the
	// share, so a share made again between the same two people, after the
	// earlier one ended, starts the month where it was.
	SkillShareMonthTotal(ownerAgentId, granteeUserId, skillName, currencyCode string, from, until time.Time) (int64, error)

	// HasSkillShareOutputWith says whether an earlier call of the share that
	// ran answered with this identifier as a whole word in any text of its
	// output: the identifier of a request it made. One shorter than
	// SkillShareIdentifierShortestCharacters never is.
	HasSkillShareOutputWith(shareId, identifier string) (bool, error)

	// AnswerSkillShareCall moves a call out of waiting_for_approval to the
	// state given, once: it changes the row only if the call is waiting and,
	// for ran, has not expired, and says whether it did. Two answers at the
	// same moment change the row once. The call is returned as it now stands.
	AnswerSkillShareCall(callId string, callState models.SkillShareCallState, answerNote string, now time.Time) (*models.SkillShareCall, bool, error)

	// FinishSkillShareCall records how a call that was started came out: its
	// state and what it answered.
	FinishSkillShareCall(callId string, callState models.SkillShareCallState, toolOutput map[string]any) error

	// ExpireSkillShareCalls moves the calls whose time to wait is over to
	// expired, and returns them.
	ExpireSkillShareCalls(now time.Time) ([]*models.SkillShareCall, error)

	// ListSkillShareCallsToWake are the calls the owner or the clock answered
	// between the two moments whose conversation has not been told, and whose
	// claim, if any, is older than the third.
	ListSkillShareCallsToWake(answeredAfter, answeredBefore, claimedBefore time.Time, limit int) ([]*models.SkillShareCall, error)

	// ClaimSkillShareCallWake takes the telling of one call, and says whether
	// the caller has it: only one caller does, until the claim is older than
	// claimedBefore.
	ClaimSkillShareCallWake(callId string, now, claimedBefore time.Time) (bool, error)

	// ReleaseSkillShareCallWakes lets go of claims whose telling was given
	// up, for the next sweep to take.
	ReleaseSkillShareCallWakes(callIds []string) error

	// MarkSkillShareCallsWoken records that the conversation was told.
	MarkSkillShareCallsWoken(callIds []string, now time.Time) error
}

SkillShareOperation is who may call which tools of whose skill: a person's installed skill, some of its tools, shared with one person in a circle they share, with limits. And the calls made through it, each of which is a row whatever came of it.

This is only the tables and the questions about them. What a call is worth and whether it goes ahead is internal/skills/share.go, and carrying it out on the owner's computer is internal/agent/skill_share.go.

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

	// LearnSpamMail teaches the classifier one message, and is idempotent:
	// marking a message the way it is already marked does nothing, and
	// changing its label takes back what the previous label added and adds
	// the new one. The label is read, the counts applied and the label
	// written in one transaction under a lock on the message, so that two
	// instances marking the same message at once count it once.
	LearnSpamMail(mailId, label string, tokens []string) error

	// ForgetSpamMail takes back what LearnSpamMail added for a message, in
	// one transaction under the same lock. A message never marked is left
	// alone.
	ForgetSpamMail(mailId string, tokens []string) 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

	// RecordSpamRuleSetCounts writes how much of a channel's rules this
	// server could run, and nothing else about the set: the rules stay as
	// they are. Only while the stored set is still at the version the counts
	// were worked out from, so that a newer import is not marked with the
	// counts of the one before it.
	RecordSpamRuleSetCounts(channel, version string, rulesLoaded, rulesSkipped int) 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 StorageUsageOperation added in v0.234.0

type StorageUsageOperation interface {
	// MeasureDatabaseSizeBytes is the size of the whole database.
	MeasureDatabaseSizeBytes() (int64, error)

	// MeasureRelationSizes is the size of every table of the public schema
	// with its indexes and out-of-line storage, by table name.
	MeasureRelationSizes() ([]models.StorageRelationSize, error)

	// MeasureFileKindSizes is what the rows say the blob store holds of each
	// kind of file. A kind with nothing stored is 0, so the answer always
	// has every kind of models.StorageFileKinds.
	MeasureFileKindSizes() ([]models.StorageFileKindSize, error)

	// MeasurePersonFileSizes is the same, by owner: the files of a person
	// under their account. Mail is counted for the owner of each mailbox it
	// is filed in, once however many folders hold it.
	MeasurePersonFileSizes() ([]models.StoragePersonFileSize, error)

	// ListStorageUserNames is the display name and username of every
	// account, by id, to name the people a measure is for.
	ListStorageUserNames() (map[string][2]string, error)

	// InsertStorageUsageSamples writes samples, leaving alone one already
	// there for the same day, kind and key. It reports how many it wrote.
	InsertStorageUsageSamples(samples []models.StorageUsageSample) (int64, error)

	// HasStorageUsageSamples says whether anything was sampled on the UTC
	// day the time falls on.
	HasStorageUsageSamples(day time.Time) (bool, error)

	// ListStorageUsageSamples is the samples from the UTC day since falls on
	// up to and including the UTC day until falls on; a zero until has no
	// end. Oldest first.
	ListStorageUsageSamples(since, until time.Time) ([]models.StorageUsageSample, error)

	// DeleteStorageUsageSamplesBefore removes samples before the UTC day the
	// time falls on.
	DeleteStorageUsageSamplesBefore(day time.Time) error

	// GetStorageDiskWarning is the warning last sent about a disk, or nil.
	GetStorageDiskWarning(diskLabel string) (*models.StorageDiskWarning, error)

	// PutStorageDiskWarning records a warning sent, replacing the one before.
	PutStorageDiskWarning(warning *models.StorageDiskWarning) error

	// DeleteStorageDiskWarning forgets the warning about a disk, so the next
	// one is sent as a first.
	DeleteStorageDiskWarning(diskLabel string) error
}

StorageUsageOperation measures what the database and the blob store hold, and keeps the daily samples the operator's trend is drawn from.

The measures read sizes the database already keeps (pg_class and the size columns of the tables that describe files) and never read the files themselves. Per-person database size is not measured: it would count the rows of the largest tables one by one.

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 ThrottleOperation added in v0.206.2

type ThrottleOperation interface {
	TakeThrottle(throttleKey string, interval time.Duration, now time.Time) (bool, error)
	TakeThrottleWait(throttleKey string, interval time.Duration, now time.Time) (bool, error)
	DeleteThrottlesTakenBefore(before time.Time) (int64, error)
	TakeRateLimitToken(limiterKey string, ratePerSecond float64, capacity int64, now time.Time) (bool, error)
	SpendRateLimitTokens(limiterKey string, ratePerSecond float64, capacity, tokenCount int64, now time.Time) error
	CountRateLimitTokens(limiterKey string, ratePerSecond float64, capacity int64, now time.Time) (float64, error)
	DeleteRateLimitBucketsRefilledBefore(before time.Time) (int64, error)
}

ThrottleOperation is what every instance counts together: the turns of something that happens at most once in a while, and the token buckets of the limits that guard a password.

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 ends every token an account has and returns how
	// many it ended, keeping the one named by except when it is not empty:
	// the token a person is making the call with.
	RevokeTokensByUser(userId string, at time.Time, except string) (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)

	ThrottleOperation
	AcmeChallengeOperation
	McpHeldResultOperation
	LocationVisitNoticeOperation
	AgentProviderSignInOperation
	AgentTurnOperation
	OversightOperation
	AgentComputerAttachmentOperation

	DomainOperation
	AliasOperation
	CredentialOperation
	UserOperation
	RoleOperation
	GroupOperation
	CircleOperation
	RelationshipOperation
	CalendarShareOperation
	LocationOperation
	LocationLockOperation
	LocationPauseOperation
	LocationPermissionOperation
	TravelOperation
	LocationNotificationMuteOperation
	LocationKnowledgeOperation
	PhotoKnowledgeOperation
	LocationShareOperation
	HealthOperation
	JournalOperation
	JournalSourceOperation
	HealthLockOperation
	HealthShareOperation
	FinanceShareOperation
	AllFinanceShareOperation
	PasswordsOperation
	PageShareOperation
	SkillShareOperation
	RecordingShareOperation
	ShoppingOperation
	ChatOperation
	ChatAgentOperation
	AuditOperation
	SyncOperation
	MailboxOperation
	PersonCardOperation
	LinkPreviewOperation
	SubscriptionQuery
	BimiQuery
	IdentityOperation
	AgentOperation
	InsightOperation
	ReactionOperation
	AttachmentOperation
	RecordingTextCorrectionOperation
	RecordingReferenceOperation
	RecordingSpeakerOperation
	RecordingTemporarySpeakerOperation
	RecordingKnowledgeOperation
	RecordingTranscriptOperation
	RecordingLiveUtteranceOperation
	RecordingPreviewOperation
	RecordingOperation
	RecordingMetadataOperation
	PhotoOperation
	PhotoAlbumOperation
	PhotoAlbumShareOperation
	SharingOperation
	PhotoFaceOperation
	PhotoReadingOperation
	PhotoUploadOperation
	RecordingRetryOperation
	ReplyOperation
	EmbeddingOperation
	VectorOperation
	PlanUsageOperation
	AgentBillingOperation
	StorageUsageOperation
	OverviewSectionOperation
	GraphOperation
	KnowledgeOperation
	DreamOperation
	OverviewOperation
	ThemeOperation
	RevisionOperation
	MemoryOperation
	ConnectionOperation
	ChannelOperation
	PhoneOperation
	EvaluationOperation
	InteractionOperation
	IdeaOperation
	BackgroundWorkOperation
	GoalOperation
	FeedOperation
	WatchedItemOperation
	AlertOperation
	FinanceOperation
	FinanceImportOperation
	FinanceReceiptOperation
	FinanceTaxOperation
	TaxYearOperation
	ExchangeRateOperation
	NetWorthOperation
	BudgetOperation

	DomainUsageOperation
	AliasUsageOperation
	CredentialUsageOperation
	MailOperation
	SubmissionOperation
	CalendarRequestOperation
	MediaCompositionOperation
	DeliveryOperation
	ReportOperation
	LayoutOperation
	TemplateOperation
}

type TravelOperation added in v0.203.0

type TravelOperation interface {
	// PutMotionActivities stores the activities, in one statement for each
	// batch, and says how many were new. An activity at a start the person
	// already has one at is ignored.
	PutMotionActivities(userId string, activities []*models.MotionActivity) (newCount int, err error)

	// ListMotionActivities reads the activities that start from from up to,
	// not including, until, and the one in effect at from (the last one that
	// started before it), oldest first.
	ListMotionActivities(userId string, from, until time.Time) ([]*models.MotionActivity, error)

	// ReplaceTrips makes the person's trips that started in the window
	// [windowStart, windowEnd) the given trips, with their legs. A trip that
	// starts when a stored one does keeps its id, and so does a leg that
	// starts when a stored leg of that trip does, so that an id a person was
	// shown still names the same part of the day after a rebuild; a trip that
	// is the stored one again (same times, visits and legs, distances within
	// a meter) is not written. Stored trips that are not given are deleted
	// with their legs. Corrections are not touched.
	ReplaceTrips(userId string, windowStart, windowEnd time.Time, trips []*models.Trip) error

	// ListTrips reads the trips that overlap the range, newest first, each
	// with its legs oldest first. A leg's TravelMode and IsTravelModeCorrected
	// are resolved from the corrections: the one covering at least half of the
	// leg's time wins, and the one covering most when several do. nextOffset is
	// nil on the last page, like ListPlaceVisits' zero. limitCount is bounded
	// like a page of visits. No trip lasts TripLongestDuration, so trips that
	// started that long before the range are not looked at.
	ListTrips(userId string, from, until time.Time, offset, limitCount int) (trips []*models.Trip, nextOffset *int, err error)

	// GetTripLeg reads one leg, resolved as ListTrips does. It is nil when
	// there is no such leg or it is not the person's.
	GetTripLeg(userId, tripLegId string) (*models.TripLeg, error)

	// SetTravelModeCorrection takes the span out of the person's corrections
	// that overlap it (a correction that reaches past the span keeps the part
	// outside it, as two corrections when it reaches past both ends) and,
	// when travelMode is not nil, stores one for exactly the span. ErrInvalidArguments for a span that ends when or before it begins
	// and for a way that is not one of the eight.
	SetTravelModeCorrection(userId string, startedAt, endedAt time.Time, travelMode *string) error

	// ListTravelTotals adds up the legs that started in the periods [from,
	// until) touches, widened to whole periods in the zone, by the period they
	// started in and by their way of travel after corrections. period is day, week (starting on Monday), month or year.
	// Newest period first, then the ways in the order walk, run, bike, car,
	// bus, train, boat, plane. ErrInvalidArguments for another period and for
	// a range of more than TravelPeriodsMost periods.
	ListTravelTotals(userId string, location *time.Location, period string, from, until time.Time) ([]*models.TravelTotal, error)

	// GetLatestVisitDeparture is when the latest visit that departed before
	// the time departed, or nil when none did. A trip begins at a departure.
	GetLatestVisitDeparture(userId string, before time.Time) (*time.Time, error)

	// GetFirstVisitArrival is the first arrival of a visit after the time and
	// not after notAfter, or nil when there is none. A trip ends at an
	// arrival.
	GetFirstVisitArrival(userId string, after, notAfter time.Time) (*time.Time, error)

	// ListTripsMissingVisit lists the person's trips whose from_visit_id or
	// to_visit_id is NULL, which a visit deleted since the trip was built
	// leaves, oldest first, at most limitCount of them. Only the id and the
	// times of each are read.
	ListTripsMissingVisit(userId string, limitCount int) ([]*models.Trip, error)

	// ListUsersNeedingTripBackfill lists the people with visits whose past
	// days have not had their trips built (MarkTripsBackfilled), or had them
	// built before builtBefore, when the rules that build them last changed.
	ListUsersNeedingTripBackfill(builtBefore time.Time) ([]string, error)

	// MarkTripsBackfilled writes that the person's past days have had their
	// trips built.
	MarkTripsBackfilled(userId string, at time.Time) error

	// ListPlacesOfVisits is the place of each of the person's visits named,
	// by visit id, for saying where a trip began and ended. A visit that is
	// gone is not in the answer.
	ListPlacesOfVisits(userId string, visitIds []string) (map[string]*models.Place, error)
}

TravelOperation is how a person got from one place to the next: the motion activity the phone reported, the trips and legs built from it and from the visits, the person's corrections of a leg's way of travel, and the totals. The plan in docs/planning/location-travel-execplan.md says how trips are built; what is here is only the rows. Trips and legs are derived and are replaced whenever they are built again; corrections are kept apart as spans of time and applied when the legs are read.

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 VisitPhotoWindow added in v0.182.0

type VisitPhotoWindow struct {
	VisitID string
	// StartedAt is the arrival, EndedAt the departure (now, for a visit that
	// is still going). A photo taken at StartedAt is in the window, one taken
	// at EndedAt is not.
	StartedAt time.Time
	EndedAt   time.Time
}

VisitPhotoWindow is the span of one visit, to ask for its photos.

type VisitPhotos added in v0.182.0

type VisitPhotos struct {
	PhotoCount int
	Photos     []*models.Photo
}

VisitPhotos is the photos of one window: how many there are and the first few, earliest first.

type VisitRange added in v0.200.0

type VisitRange struct {
	UserID string    `gorm:"column:user_id"`
	From   time.Time `gorm:"column:range_from"`
	Until  time.Time `gorm:"column:range_until"`
}

VisitRange is a stretch of one person's visits.

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