respond

package
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: MIT Imports: 29 Imported by: 0

Documentation

Overview

Package respond decides whether to speak, and how.

It sits between pkg/ingest, which knows about a socket, and pkg/answer, which knows about a corpus. Neither knows about the other: ingest reading a gateway is the thing that most needs to stay boring, and answering must remain usable from the CLI with no Discord anywhere near it. The decision to speak belongs to neither, so it lives here (spec 0010 D1).

Nothing posts by default. Shadow mode is the shipping state, not a test mode: everything runs, the answer is composed and recorded, and the thread stays empty until a person has read 30 answers to real questions and agreed they are worth posting (D6, D12).

Index

Constants

View Source
const (
	DefaultFollowUpChecks  = 200
	DefaultMaxThreadChecks = 20
)

DefaultFollowUpChecks is each server's hourly allowance of classifier calls, and DefaultMaxThreadChecks the cap in one thread (spec 0031 D4, D6).

View Source
const (
	ReactionHelpful    = events.FeedbackHelpful
	ReactionNotHelpful = events.FeedbackNotHelpful
)

Feedback reactions (D9). Universally understood, need no explanation, and read as feedback on the message rather than on its subject — which ✅/❌ do not, since people already use those to mark a task done or a fact wrong.

View Source
const (
	DecisionAnswered  = "answered"
	DecisionClarified = "clarified"
)

Clarification decisions, as ClarifyEvidence records them.

View Source
const (
	DefaultHistoryMessages = 20
	DefaultHistoryChars    = 8000
)

How much of a thread is read for a follow-up (spec 0031 D9): the most recent messages, up to either bound, whichever comes first.

View Source
const AnswerRetention = 120 * 24 * time.Hour

AnswerRetention is how long an answer's text and citations are kept.

120 days, set by the maintainer 2026-09-23 (spec 0010 D6, amended 2026-09-24). Expiry clears the text and keeps the record.

View Source
const DefaultClassifyTimeout = 15 * time.Second

DefaultClassifyTimeout bounds one classifier call. A reply that waits on a slow provider is worth less than silence.

View Source
const DefaultMaxReplies = 5

DefaultMaxReplies is how many posts the bot makes in one thread, the opening answer included (spec 0031 D6).

View Source
const DefaultPurgeInterval = 24 * time.Hour

DefaultPurgeInterval is how often expired questions are deleted.

The published retention is counted in days, so a daily sweep keeps every question within a day of its promised lifetime without touching the database more than it needs to.

View Source
const DefaultRetention = 180 * 24 * time.Hour

DefaultRetention is how long a question is kept.

180 days rather than the 30 the rest of the policy uses (spec 0010 D5a). Low volume is exactly when a short window destroys the signal: a handful of questions a week expiring at 30 days never accumulates enough to rank a documentation gap. It reduces to 30 once traffic makes the shorter window sufficient, and the published policy commits to that reduction rather than leaving 180 to become permanent by default.

View Source
const DefaultThreadWindow = 24 * time.Hour

DefaultThreadWindow is how long a thread stays the bot's after its last activity: Discord's default auto-archive (0018 OQ10).

View Source
const MaxMessageRunes = 1600

MaxMessageRunes is the largest message that will be posted.

Discord's own limit is 2000 characters; this sits under it so the citation block, which is appended after the prose is bounded, cannot push a message over. R-ANS-12 asks for a Discord-sane size with a link out rather than a wall of pasted code — the link is the citation, and it is never the part that gets truncated.

View Source
const SelfUser comms.ID = "__self__"

SelfUser is the user id standing for the bot itself.

The bot reacts to its own answers to offer the feedback affordance, and those reactions arrive back through the same path a person's do. Counting them would give every answer one vote from itself.

Variables

View Source
var (
	// ErrNoPoster means no space has a way to post. Failing here fails at
	// wiring, where an operator is watching, rather than at the first attempt
	// to answer in front of a public server (D7).
	ErrNoPoster = errors.NewSentinel("respond.no_poster", "respond: no poster to post through")

	// ErrUnknownSpace means a message arrived for a space respond has no
	// Poster for, which no correct wiring produces.
	ErrUnknownSpace = errors.NewSentinel("respond.unknown_space", "respond: no poster for this space")
)

Construction and dispatch errors.

Functions

func ThreadTitle added in v0.8.0

func ThreadTitle(question string, resp answer.Response) (string, bool)

ThreadTitle names the thread an answer opens, and reports whether the name is the composer's own title rather than a fallback (spec 0026 D3).

Types

type Asker

type Asker interface {
	Ask(ctx context.Context, question string) (answer.Response, error)
}

Asker is the answering path. pkg/answer.Service satisfies it.

An interface rather than the concrete service so this package can be tested without an index or a model, and so answering stays substitutable.

type ClarifyEvidence added in v0.15.0

type ClarifyEvidence struct {
	Readings     map[string]int      `json:"readings"`
	TopShares    []float64           `json:"top_shares"`
	Names        map[string][]string `json:"names,omitempty"`
	SplitShare   float64             `json:"split_share"`
	NamePassages int                 `json:"name_passages"`
	Reason       string              `json:"reason,omitempty"`
	Offer        []string            `json:"offer,omitempty"`
	Decision     string              `json:"decision"`
}

ClarifyEvidence is what a record keeps of the clarification decision, so a threshold can be judged by replaying records (spec 0031 D5). Module names and counts, never text. Tagged here so renaming a field of answer.Evidence cannot silently change stored JSON.

type Classifier added in v0.15.0

type Classifier interface {
	Classify(ctx context.Context, message string) (answer.Label, error)
}

Classifier tells a follow-up question from commentary (spec 0031 D4). answer.ChatClassifier is the production one.

type Forgotten added in v0.13.0

type Forgotten struct {
	Answers int64
	Votes   int64
}

Forgotten is how many of a person's records Forget disconnected from them.

type Held added in v0.13.0

type Held struct {
	Answers []HeldAnswer
	Votes   []HeldVote
}

Held is everything recorded for one person (spec 0032 D12).

type HeldAnswer added in v0.13.0

type HeldAnswer struct {
	Question string
	Outcome  answer.Outcome
	Body     string
	At       time.Time
}

HeldAnswer is one answer given to a person, with the question it answered.

type HeldVote added in v0.13.0

type HeldVote struct {
	Question string
	Helpful  bool
	At       time.Time
}

HeldVote is one reaction a person gave, with the question of the answer it judged.

type Option

type Option func(*Service)

Option configures a Service.

func AskerFor added in v0.11.0

func AskerFor(space comms.ID, a Asker) Option

AskerFor answers one server's questions with its own asker, which carries that server's corpus, provider and model (spec 0029 D9). A server without one uses the asker New was given.

func BudgetFor added in v0.11.0

func BudgetFor(space comms.ID, b *budget.Budget) Option

BudgetFor bounds one server with its own budget, so its spending never blocks another (spec 0029 D6). A server without one uses WithBudget's.

func ClassifierFor added in v0.15.0

func ClassifierFor(space comms.ID, c Classifier) Option

ClassifierFor sets the classifier for one server, which has its own AI provider or model (spec 0029 D7, 0031 D4).

func ForumScopes added in v0.12.0

func ForumScopes(space comms.ID, scopes map[comms.ID][]string) Option

ForumScopes names, for one server, the corpus prefixes each support forum is about. A question asked there is retrieved as being about them unless it names a module itself (spec 0030 D8).

func PostIn added in v0.7.0

func PostIn(spaces ...comms.ID) Option

PostIn lets the bot post its answers in the named spaces, and nowhere else (spec 0025). Every other space stays in shadow mode: the answer is composed and recorded, and nothing is posted.

Deliberately an option naming spaces rather than a switch. A misconfigured deployment that silently posts is worse than one that silently does not, so posting is something a space is given, never something it has by default.

func ReadThreadsIn added in v0.15.0

func ReadThreadsIn(space comms.ID, r ThreadReader) Option

ReadThreadsIn gives a server the reader its follow-ups' threads are read with. Without one, a follow-up is answered with no thread context, and a shadow server claims no thread for a channel question (D10).

func WithBudget added in v0.5.0

func WithBudget(b *budget.Budget) Option

WithBudget bounds how often the bot will answer. Nil, the default, is no ceiling, so a deployment that does not set one sees no change.

func WithClassifier added in v0.15.0

func WithClassifier(c Classifier) Option

WithClassifier sets what tells a follow-up from commentary in a conversation thread (spec 0031 D4).

func WithClassifyTimeout added in v0.15.0

func WithClassifyTimeout(d time.Duration) Option

WithClassifyTimeout bounds one classifier call. One that runs over is silence.

func WithFollowUpChecks added in v0.15.0

func WithFollowUpChecks(perHour int) Option

WithFollowUpChecks sets each server's hourly allowance of classifier calls.

func WithHistoryLimits added in v0.15.0

func WithHistoryLimits(messages, chars int) Option

WithHistoryLimits sets how many messages and characters of a thread are read for a follow-up (spec 0031 D9).

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger sets the logger.

func WithMaxReplies added in v0.15.0

func WithMaxReplies(n int) Option

WithMaxReplies caps the bot's posts in one thread (spec 0031 D6).

func WithMaxThreadChecks added in v0.15.0

func WithMaxThreadChecks(n int) Option

WithMaxThreadChecks caps classifier calls in one thread (spec 0031 D6).

func WithRecorder added in v0.4.0

func WithRecorder(r *Recorder) Option

WithRecorder persists every answer and the feedback on it.

Optional, so this package stays usable without a database — but a deployment without one cannot clear D12's gate, because there is nothing to review.

func WithThreads

func WithThreads(t Threads) Option

WithThreads overrides where opened threads are recorded.

type Pending added in v0.15.0

type Pending struct {
	// RecordID is the clarifying question's own record.
	RecordID int64

	// QuestionID and Question are the question that was asked back.
	QuestionID int64
	Question   string
	Offer      []string
}

Pending is a clarifying question awaiting its asker's reply (spec 0031 D5).

type Poster added in v0.5.0

type Poster interface {
	ReplyInThread(ctx context.Context, to comms.Ref, threadName, content string) (comms.Ref, error)
	React(ctx context.Context, to comms.Ref, emoji string) error
}

Poster is the write path back to one space: the two Actor methods respond uses and nothing else (D4). transport.Poster satisfies it, and does so through a lease so respond never holds an Actor that could go stale (0018 D8b).

type Posters added in v0.5.0

type Posters map[comms.ID]Poster

Posters is one Poster per space. The space travels beside the message, and a post for a space with no Poster is a wiring error at construction rather than a runtime miss.

type Posture

type Posture string

Posture is how an answer is presented, or that there is nothing to present.

Derived from the composer's outcome and its citation count (D4), never from a retrieval score — see answer.Outcome for why that signal was abandoned.

const (
	// PostureSilent means the bot was not addressed. Nothing was asked of it,
	// so nothing is composed and nothing is posted.
	PostureSilent Posture = "silent"

	// PostureThreadLimit is the one notice a thread gets when the bot has
	// replied as often as it will there (spec 0031 D6).
	PostureThreadLimit Posture = "thread_limit"

	// PosturePlain states the answer without qualification: either it rests on
	// more than one source, or it is a refutation, which the documentation
	// makes certain.
	PosturePlain Posture = "plain"

	// PostureHedged states the answer and says it rests on a single source.
	// Not a disclaimer bolted on — the reader is told what to go and check.
	PostureHedged Posture = "hedged"

	// PostureDecline says the corpus does not answer this, and what was
	// searched (D8). It posts: the bot was addressed directly, so silence
	// reads as broken.
	PostureDecline Posture = "decline"

	// PostureOverBudget says the bot has answered as often as it is allowed to
	// this hour (0019 D19). It posts, for the same reason a decline does, and
	// it is distinct from a decline because the question may be perfectly
	// answerable — nothing was wrong with it except its timing.
	PostureOverBudget Posture = "over-budget"

	// PostureClarify asks which of a few readings the question meant, rather
	// than answering it (spec 0031 D5). A template, so it costs no model call.
	PostureClarify Posture = "clarify"
)

The postures.

type PurgeTarget added in v0.6.0

type PurgeTarget interface {
	// Purge deletes questions.
	Purge(ctx context.Context, olderThan time.Duration) (int64, error)

	// PurgeAnswers clears answer text and citations.
	PurgeAnswers(ctx context.Context, olderThan time.Duration) (int64, error)
}

PurgeTarget deletes what is older than a retention window. *Recorder is one.

type Purger added in v0.6.0

type Purger struct {
	// contains filtered or unexported fields
}

Purger enforces the published retention on a schedule: questions at 180 days (0010 D5a) and answer text at 120 (D6).

Recorder.Purge is the mechanism; this is what makes it run. Without it the retention the policy publishes is a promise nothing keeps.

func NewPurger added in v0.6.0

func NewPurger(target PurgeTarget, opts ...PurgerOption) *Purger

NewPurger builds a purger over a target, keeping DefaultRetention.

func (*Purger) Live added in v0.6.0

func (p *Purger) Live() error

Live always reports healthy: a failed purge is retried on the next interval, and a restart would not unlock the database either.

func (*Purger) Start added in v0.6.0

func (p *Purger) Start(ctx context.Context) error

Start purges once immediately and then on every interval, in the background.

func (*Purger) Stop added in v0.6.0

func (p *Purger) Stop(ctx context.Context)

Stop ends the schedule and waits for a purge already running, bounded by the shutdown deadline in ctx. Safe unstarted and safe to call twice.

type PurgerOption added in v0.6.0

type PurgerOption func(*Purger)

PurgerOption configures a Purger.

func WithPurgeInterval added in v0.6.0

func WithPurgeInterval(d time.Duration) PurgerOption

WithPurgeInterval sets how often the purge runs.

func WithPurgeLogger added in v0.6.0

func WithPurgeLogger(l *slog.Logger) PurgerOption

WithPurgeLogger sets the logger.

type Question added in v0.4.0

type Question struct {
	ID      int64
	TopicID int64
	Text    string
	Lang    string
	// MatchScore is the BM25 score this question's topic was decided on, and
	// zero where nothing was compared. Recorded so matchFloor can eventually be
	// chosen from evidence instead of measurement on a handful of rows.
	MatchScore float64
	AskedAt    time.Time
}

Question is one asking, as stored.

type Record added in v0.4.0

type Record struct {
	// Space is the server the question was asked in (spec 0029 D3).
	Space comms.ID

	Question  string
	UserID    comms.ID
	ChannelID comms.ID
	ThreadID  comms.ID

	// MessageID is the bot's own posted message, which is what a reaction
	// arrives against. Empty in shadow mode, where nothing was posted and so
	// nothing can be reacted to.
	MessageID comms.ID

	Outcome   answer.Outcome
	Posture   Posture
	Citations int
	Posted    bool

	// Body is the message posted, or that would have been, and Cited the
	// citations behind it (0010 D6). Body is redacted before it is stored.
	Body  string
	Cited []answer.Citation

	// Title is the thread's title, purged with Body (spec 0026 D4).
	Title string

	// TopicLabel labels the question's topic if the question opens a new one.
	// Empty means the question's opening words (0026 D9).
	TopicLabel string

	// QuestionID, when set, links the record to a question already stored
	// rather than storing Question again: the answer to a clarification is
	// the answer to the question that was asked back (spec 0031 D5).
	QuestionID int64

	// Evidence is what clarification judged, nil when nothing was.
	Evidence *answer.Evidence
}

Record is one answer, as the caller describes it.

Question and UserID are the raw values. They are hashed on the way in and never stored — see Recorder.Record.

type Recorder added in v0.4.0

type Recorder struct {
	// contains filtered or unexported fields
}

Recorder persists answers and the feedback on them.

It holds the deployment salt, which is why it is constructed rather than being a set of free functions over a database.

func NewRecorder added in v0.4.0

func NewRecorder(ctx context.Context, db *store.DB) (*Recorder, error)

NewRecorder loads the deployment salt, generating it on first use.

func (*Recorder) AdoptUnassigned added in v0.11.0

func (r *Recorder) AdoptUnassigned(ctx context.Context, space comms.ID) (int64, error)

AdoptUnassigned gives every row recorded before servers were recorded to space, and reports how many questions it adopted (spec 0029 D3). Only right when space is the one server ever configured, which serve checks.

func (*Recorder) Answer added in v0.4.0

func (r *Recorder) Answer(ctx context.Context, id int64) (Saved, error)

Answer reads one stored record back.

func (*Recorder) Count added in v0.4.0

func (r *Recorder) Count(ctx context.Context) (int, error)

Count returns how many answers have been recorded.

D12 gates graduation on a count of reviewed answers, so the denominator has to be readable.

func (*Recorder) DB added in v0.4.0

func (r *Recorder) DB() *store.DB

DB exposes the underlying database, for tests and for callers that share one store across components (R-ANS-5a keeps everything in a single database).

func (*Recorder) FeedbackFor added in v0.4.0

func (r *Recorder) FeedbackFor(ctx context.Context, answerID int64) (int, int, error)

FeedbackFor returns the helpful and not-helpful counts for an answer.

func (*Recorder) FirstQuestion added in v0.15.0

func (r *Recorder) FirstQuestion(ctx context.Context, thread comms.ID) (string, error)

FirstQuestion is the question linked from a thread's first answer record, "" when that record links none (spec 0031 D8).

func (*Recorder) Forget added in v0.4.0

func (r *Recorder) Forget(ctx context.Context, userID comms.ID) (Forgotten, error)

Forget disconnects a person from everything recorded for them (spec 0032 D3). Their questions, the answers and the verdicts stay, because they were public when asked and every count is built on them. What goes is the hash, and the Discord IDs on their answers, since those lead to a thread that names them. A vote's hash becomes random rather than empty because the hash is part of its key.

Each statement selects by the hash, so a run interrupted between them is finished by running it again (D4).

func (*Recorder) Held added in v0.13.0

func (r *Recorder) Held(ctx context.Context, userID comms.ID) (Held, error)

Held lists everything recorded for a person, oldest first.

func (*Recorder) PendingClarification added in v0.15.0

func (r *Recorder) PendingClarification(ctx context.Context, thread, user comms.ID) (Pending, bool, error)

PendingClarification reports the clarification awaiting user's reply in a thread: the newest record there is a clarifying question, asked of them.

func (*Recorder) PostedIn added in v0.15.0

func (r *Recorder) PostedIn(ctx context.Context, thread comms.ID) (map[comms.ID]bool, error)

PostedIn is the IDs of the messages the bot posted in a thread, as its answer records hold them.

func (*Recorder) Purge added in v0.4.0

func (r *Recorder) Purge(ctx context.Context, olderThan time.Duration) (int64, error)

Purge deletes questions older than the retention window.

A retention promise with no purge is a false statement rather than a missing feature, and the policy publishes this one. Topics are deliberately NOT deleted with their questions: the count is the product, and a subject that was asked about six months ago is still evidence of a gap even once the wording of the asking is gone.

func (*Recorder) PurgeAnswers added in v0.6.0

func (r *Recorder) PurgeAnswers(ctx context.Context, olderThan time.Duration) (int64, error)

PurgeAnswers clears the text, citations and title of answers older than the retention window, and keeps the records: their outcome and posture are aggregate facts that outlive the wording (spec 0010 D6).

func (*Recorder) RecentThreads added in v0.5.0

func (r *Recorder) RecentThreads(ctx context.Context, since time.Time) ([]ThreadActivity, error)

RecentThreads lists the threads the bot has answered in since a time, each with its latest activity, for restoring the ThreadSet at start (0018 OQ10).

Grouped in SQL rather than in Go, so a thread with a long conversation costs one row rather than one per answer.

func (*Recorder) Record added in v0.4.0

func (r *Recorder) Record(ctx context.Context, rec Record) (Saved, error)

Record stores one answer and returns what was stored.

func (*Recorder) RecordFeedback added in v0.4.0

func (r *Recorder) RecordFeedback(
	ctx context.Context, messageID, userID comms.ID, helpful bool,
) (bool, error)

RecordFeedback stores a verdict against the answer posted as messageID, with the semantics of spec 0010 D9: one verdict per person, replaced on a change of mind, and the bot's own reactions excluded. It reports whether a verdict was stored.

Unknown messages are ignored rather than refused. People react to arbitrary messages constantly, and the overwhelming majority of reactions the bot sees are nothing to do with it — treating those as errors would make the normal case an error path.

func (*Recorder) Regroup added in v0.9.1

func (r *Recorder) Regroup(ctx context.Context) (int, error)

Regroup refiles every stored question under the current comparison rule, oldest first, and returns how many topics result (spec 0010 D5d).

It replaces every topic, so hand merges, labels and guide slugs do not survive it. Run it with serve stopped: a question recorded mid-regroup could join a topic about to be deleted.

func (*Recorder) ThreadReplies added in v0.15.0

func (r *Recorder) ThreadReplies(ctx context.Context, thread comms.ID) (replies int, notified bool, err error)

ThreadReplies counts the bot's posts in a thread and reports whether the limit notice is among them (spec 0031 D6).

func (*Recorder) Topics added in v0.4.0

func (r *Recorder) Topics(ctx context.Context, space comms.ID, limit int) ([]Topic, error)

Topics returns one server's subjects, most-asked first.

This is D14's product: a topic asked eleven times that declines every time is a documentation gap ranked by demand, which is better evidence than any individual decline and needs no volunteer action from anybody.

func (*Recorder) WithdrawFeedback added in v0.9.0

func (r *Recorder) WithdrawFeedback(
	ctx context.Context, messageID, userID comms.ID, helpful bool,
) (bool, error)

WithdrawFeedback removes a person's verdict when they take their reaction off, but only if it is the verdict that reaction gave (spec 0027 D4). It reports whether a verdict was removed.

type Result

type Result struct {
	// Posture is what was decided. PostureSilent means not addressed, or
	// screened out.
	Posture Posture

	// Screened names what silenced a message in a conversation thread: a
	// rule, a classifier label, or an exhausted allowance (spec 0031 D4).
	// Empty when nothing did.
	Screened string

	// Response is what the answering path produced. Zero when the bot was not
	// addressed, because nothing was asked.
	Response answer.Response

	// ThreadID is the thread the answer went in, empty in shadow mode where no
	// thread is created.
	ThreadID comms.ID

	// MessageID is the bot's own posted message, empty in shadow mode. It is
	// the id a reaction arrives against, and so the key feedback joins to —
	// which is why it is carried separately from ThreadID rather than being
	// recovered from it. They are different values (D9).
	MessageID comms.ID

	// Posted reports whether anything actually reached the platform. False in
	// shadow mode however complete the rest of the work was.
	Posted bool

	// Body is the message posted, or in shadow mode the message that would have
	// been. Empty when the bot was not addressed.
	Body string

	// Title names the thread the answer opens, or would have (spec 0026).
	Title string

	// TitleComposed reports that Title is the composer's own rather than a
	// fallback, which is what lets it label a new topic (0026 D9).
	TitleComposed bool
	// contains filtered or unexported fields
}

Result is what Handle did, and why.

Returned rather than logged so a caller — the observer wiring, a test, the shadow review — can see the decision without parsing prose.

func (Result) Answered

func (r Result) Answered() bool

Answered reports whether this produced prose, as opposed to a decline or silence.

type Saved added in v0.4.0

type Saved struct {
	ID int64
	// QuestionID links to the stored question, zero where there was nothing to
	// store or the question could not be recorded.
	QuestionID int64
	UserHash   string
	Outcome    answer.Outcome
	Posture    Posture
	Citations  int
	Posted     bool
	CreatedAt  time.Time

	// Body, Cited, Title and Evidence are empty once AnswerRetention has
	// passed.
	Body     string
	Cited    []answer.Citation
	Title    string
	Evidence *ClarifyEvidence
}

Saved is a stored answer record.

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service decides whether to answer a message, and answers it.

func New

func New(a Asker, posters Posters, opts ...Option) (*Service, error)

New builds a responder over one Poster per space.

func (*Service) Deliver added in v0.5.0

func (s *Service) Deliver(ctx context.Context, d messaging.Delivery) error

Deliver is the bus subscriber (0019): it decodes the event and handles the message against the space the event names.

A decode failure is returned so the bus counts it against this subscription; a Handle error is returned for the same reason. Neither is retried, because delivery is at most once (0019 D5) and an answer that failed to post has already been recorded as unposted.

func (*Service) DeliverReaction added in v0.9.0

func (s *Service) DeliverReaction(ctx context.Context, d messaging.Delivery) error

DeliverReaction is the feedback subscriber (spec 0027): a vote put on an answer is recorded, and one taken off is withdrawn.

The log line names the answer's message and the verdict, never the voter (0027 D5).

func (*Service) Handle

func (s *Service) Handle(ctx context.Context, space comms.ID, msg comms.Message) (Result, error)

Handle decides whether to answer a message, and answers it.

This is the seam spec 0010 names for testing: one function taking a message and returning what was decided. Every decision the spec makes is observable through it — trigger matching, posture selection and the shadow split — so a test needs no other hook into this package.

An error means something broke. A question the corpus cannot answer is a Result with PostureDecline and no error, because a knowledge gap is an outcome rather than an incident (R-ANS-6c) and the gap backlog depends on telling them apart.

type StagedAsker added in v0.15.0

type StagedAsker interface {
	Retrieve(ctx context.Context, question string) (answer.Retrieval, error)
	Compose(ctx context.Context, r answer.Retrieval) (answer.Response, error)
}

StagedAsker answers in two stages, so a question can be asked back between retrieving and composing (spec 0031 D5). pkg/answer.Service satisfies it; an Asker that does not is always answered.

type ThreadActivity added in v0.5.0

type ThreadActivity struct {
	ID   comms.ID
	Last time.Time
}

ThreadActivity is one thread and when the bot last acted in it.

type ThreadReader added in v0.15.0

type ThreadReader interface {
	ThreadHistory(ctx context.Context, thread comms.ID, limit int) ([]comms.Message, error)

	// ThreadSharesMessageID reports whether a thread started from a message
	// has that message's ID, which D10's shadow claim depends on.
	ThreadSharesMessageID() bool
}

ThreadReader reads the threads of one server (spec 0031 D2). transport.Threads is the production one.

type ThreadSet

type ThreadSet struct {
	// contains filtered or unexported fields
}

ThreadSet is an in-memory Threads with an inactivity window.

func NewThreadSet

func NewThreadSet(window time.Duration, opts ...ThreadSetOption) *ThreadSet

NewThreadSet returns an in-memory record of the threads the bot opened, bounded by an inactivity window.

A thread stays the bot's for the window after its LAST activity, not after it was opened. Discord archives on inactivity rather than age, so an active 25-hour-old thread is still open and the bot must keep answering in it. The previous set stored ID → bool and never expired, so a thread opened during the process lifetime stayed open for ever (0018 OQ10).

In-memory, and loaded at start from the answer records by serve, which owns the loaded one; this default exists so the package is usable on its own.

func (*ThreadSet) CountCheck added in v0.15.0

func (t *ThreadSet) CountCheck(id comms.ID) int

CountCheck records one classifier call in a thread and returns how many it has had. Counts are dropped with the thread when it ages out (spec 0031 D6).

func (*ThreadSet) Len added in v0.5.0

func (t *ThreadSet) Len() int

Len is how many threads are recorded, pruned or not, for a test that wants to see the bound hold.

func (*ThreadSet) Load added in v0.5.0

func (t *ThreadSet) Load(ctx context.Context, src ThreadSource) error

Load restores the threads the bot opened before a restart, bounded by the window (0018 OQ10). Without it a restart forgets every thread and a follow-up in one stops being recognised as addressed to the bot.

func (*ThreadSet) MarkOpened

func (t *ThreadSet) MarkOpened(id comms.ID)

MarkOpened records a thread the bot started, as of now.

Stale entries are pruned here rather than on a timer: a thread that has aged out is unreachable through Opened already, and this is the one write that grows the set, so it is the one place the set is kept bounded.

func (*ThreadSet) Opened

func (t *ThreadSet) Opened(id comms.ID) bool

Opened reports whether the bot started this thread and it is still active.

func (*ThreadSet) Touch added in v0.5.0

func (t *ThreadSet) Touch(id comms.ID)

Touch refreshes a thread the bot opened, on activity in it. A thread the bot did not open is not adopted: that is somebody else's conversation.

type ThreadSetOption added in v0.5.0

type ThreadSetOption func(*ThreadSet)

ThreadSetOption configures a ThreadSet.

func WithThreadClock added in v0.5.0

func WithThreadClock(now func() time.Time) ThreadSetOption

WithThreadClock sets the clock, so ageing is testable. Injected rather than a package-level var a test swaps, which races under t.Parallel.

type ThreadSource added in v0.5.0

type ThreadSource interface {
	// RecentThreads lists every thread with activity at or after since, each
	// with its latest activity.
	RecentThreads(ctx context.Context, since time.Time) ([]ThreadActivity, error)
}

ThreadSource is where a ThreadSet restores its threads from. The Recorder satisfies it; an interface so the set can be loaded without a database.

type Threads

type Threads interface {
	// Opened reports whether the bot started this thread.
	Opened(id comms.ID) bool

	// MarkOpened records a thread the bot has just started.
	MarkOpened(id comms.ID)

	// Touch refreshes a thread on activity in it, so an active thread does not
	// age out on the clock alone.
	Touch(id comms.ID)

	// CountCheck records a classifier call in a thread and returns how many it
	// has had (spec 0031 D6).
	CountCheck(id comms.ID) int
}

Threads records which threads the bot opened.

It exists because D2's third trigger — a follow-up in a thread the bot started — cannot be answered from a message alone. A thread the bot did not open is somebody else's conversation, and replying in it uninvited is exactly the volunteering this spec declined.

type Topic added in v0.4.0

type Topic struct {
	ID    int64
	Label string
	// GuideSlug is the published guided topic page this corresponds to, empty
	// where no guide has been written. Empty on a topic asked often is the
	// backlog entry (spec 0008 §3.7).
	GuideSlug string
	// Asked is how many questions belong to this topic — the count D14 calls
	// the product of the answering path.
	Asked int
	// Gaps is how many of those questions were declined or answered only in
	// part, so a subject the docs half-cover ranks as a gap too (spec 0030 D3).
	Gaps  int
	First time.Time
	Last  time.Time
}

Topic is a subject people ask about.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL