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
- Variables
- type Asker
- type Option
- type Poster
- type Posters
- type Posture
- type PurgeTarget
- type Purger
- type PurgerOption
- type Question
- type Record
- type Recorder
- func (r *Recorder) Answer(ctx context.Context, id int64) (Saved, error)
- func (r *Recorder) Count(ctx context.Context) (int, error)
- func (r *Recorder) DB() *store.DB
- func (r *Recorder) FeedbackFor(ctx context.Context, answerID int64) (int, int, error)
- func (r *Recorder) Forget(ctx context.Context, userID chatplatform.ID) (int64, error)
- func (r *Recorder) Purge(ctx context.Context, olderThan time.Duration) (int64, error)
- func (r *Recorder) PurgeAnswers(ctx context.Context, olderThan time.Duration) (int64, error)
- func (r *Recorder) RecentThreads(ctx context.Context, since time.Time) ([]ThreadActivity, error)
- func (r *Recorder) Record(ctx context.Context, rec Record) (Saved, error)
- func (r *Recorder) RecordFeedback(ctx context.Context, messageID, userID chatplatform.ID, helpful bool) error
- func (r *Recorder) Topics(ctx context.Context, limit int) ([]Topic, error)
- type Result
- type Saved
- type Service
- type ThreadActivity
- type ThreadSet
- type ThreadSetOption
- type ThreadSource
- type Threads
- type Topic
Constants ¶
const ( ReactionHelpful = "👍" ReactionNotHelpful = "👎" )
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.
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.
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.
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.
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).
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.
const SelfUser chatplatform.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 ¶
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 ¶
This section is empty.
Types ¶
type Asker ¶
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 Option ¶
type Option func(*Service)
Option configures a Service.
func PostIn ¶ added in v0.7.0
func PostIn(spaces ...chatplatform.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 WithBudget ¶ added in v0.5.0
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 WithRecorder ¶ added in v0.4.0
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 ¶
WithThreads overrides where opened threads are recorded.
type Poster ¶ added in v0.5.0
type Poster interface {
ReplyInThread(ctx context.Context, to chatplatform.Ref, threadName, content string) (chatplatform.Ref, error)
React(ctx context.Context, to chatplatform.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[chatplatform.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" // 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" )
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
Live always reports healthy: a failed purge is retried on the next interval, and a restart would not unlock the database either.
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 {
Question string
UserID chatplatform.ID
ChannelID chatplatform.ID
ThreadID chatplatform.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 chatplatform.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
}
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
NewRecorder loads the deployment salt, generating it on first use.
func (*Recorder) Count ¶ added in v0.4.0
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
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
FeedbackFor returns the helpful and not-helpful counts for an answer.
func (*Recorder) Forget ¶ added in v0.4.0
Forget removes everything recorded for one person.
The published policy says deletion covers every store. The user hash is the only handle on their rows, which is why it is a stable pseudonym rather than a value regenerated per call.
Questions are anonymised rather than deleted: a question is not personal data once it is detached from who asked it, it was volunteered in a public channel, and deleting it would silently revise a documentation-gap count that nothing else can reconstruct.
func (*Recorder) Purge ¶ added in v0.4.0
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
PurgeAnswers clears the text and citations 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
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) RecordFeedback ¶ added in v0.4.0
func (r *Recorder) RecordFeedback( ctx context.Context, messageID, userID chatplatform.ID, helpful bool, ) error
RecordFeedback stores a verdict against the answer posted as messageID.
NOTHING CALLS THIS YET, and one of the two upstream gaps is now closed. chat-platform v0.9.0 made Actor.ReplyInThread return a Ref carrying the posted message, so the join key exists and Record stores it. What remains is inbound: Reader delivers only messages, and there is no reaction event, so the bot offers the affordance and never learns that anybody used it.
It is written and tested now because the semantics are the part worth getting right, and they are decided by D9 rather than by the platform: one verdict per person, replaced on a change of mind, and the bot's own reactions excluded.
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) Topics ¶ added in v0.4.0
Topics returns the subjects people have asked about, 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.
type Result ¶
type Result struct {
// Posture is what was decided. PostureSilent means not addressed.
Posture Posture
// 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 chatplatform.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 chatplatform.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
}
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.
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 and Cited are empty once AnswerRetention has passed.
Body string
Cited []answer.Citation
}
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 (*Service) Deliver ¶ added in v0.5.0
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) Handle ¶
func (s *Service) Handle(ctx context.Context, space chatplatform.ID, msg chatplatform.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 ThreadActivity ¶ added in v0.5.0
type ThreadActivity struct {
ID chatplatform.ID
Last time.Time
}
ThreadActivity is one thread and when the bot last acted in it.
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) Len ¶ added in v0.5.0
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 chatplatform.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 chatplatform.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 chatplatform.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 chatplatform.ID) bool
// MarkOpened records a thread the bot has just started.
MarkOpened(id chatplatform.ID)
// Touch refreshes a thread on activity in it, so an active thread does not
// age out on the clock alone.
Touch(id chatplatform.ID)
}
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
First time.Time
Last time.Time
}
Topic is a subject people ask about.