Documentation
¶
Overview ¶
Package asklog is the ask log: one row (table asks, migration 0089) for every question an agent put to its owner, whatever kind it was, with the answer the owner gave, who gave it and how long it took. It is phase 1 of the design "ask telemetry, review, and progressive auto-approval" (see docs/asks.md): telemetry only. Nothing here answers an ask, proposes an answer or evaluates a rule.
The kinds:
- KindPlainText: a question in the last assistant message of a turn — a mirrored Claude Code window going from busy to idle, or a dispatched agent's turn ending — kept only when it passes the pre-filter (Prefilter, in code, no model). Its answer is the first user message after it, with what muster can prove of who wrote it (Provenance).
- KindAskUserQuestion: a Claude Code AskUserQuestion picker, from the moment the question store accepts it to how it ended.
- KindAttention: an attention_ask (an ask, never a notice).
- KindOpenCodeQuestion, KindOpenCodePermission: an opencode form or permission request a mirrored opencode window waits on.
🔴 TEXT IS REDACTED ON THE WAY IN, BY THE STORE. Every text column passes through redact.Secrets inside PG.Open and PG.Resolve — the one redactor, and the one writer — so no caller can store a raw secret by forgetting to.
🔴 CAPTURE NEVER BLOCKS OR FAILS THE FLOW IT WATCHES. Callers hand their writes to a Recorder, which runs them off the caller's goroutine, in order, and turns every failure (and a panic) into a log line and a count (muster_ask_capture_errors_total) — never an error returned to the agent or the owner.
Index ¶
- Constants
- Variables
- func Answered(outcome string) bool
- func AnsweredByFor(prov string) string
- func AtStage(stage string, err error) error
- func Failed(logger *log.Logger, kind string, err error)
- func LastParagraph(text string) string
- func Normalise(q string) string
- func Prefilter(text string) bool
- type Ask
- type Filter
- type Jev
- type PG
- func (p *PG) CloseStale(ctx context.Context, before time.Time) (int, error)
- func (p *PG) Get(ctx context.Context, id int64) (Ask, bool, error)
- func (p *PG) List(ctx context.Context, limit int) ([]Ask, error)
- func (p *PG) Open(ctx context.Context, a Ask) (int64, bool, error)
- func (p *PG) Page(ctx context.Context, f Filter, before int64, limit int) (rows []Ask, next int64, err error)
- func (p *PG) Purge(ctx context.Context, now time.Time, textTTL, rowTTL time.Duration) (int, int, error)
- func (p *PG) Resolve(ctx context.Context, id int64, r Resolution) (Ask, bool, error)
- func (p *PG) ResolveRef(ctx context.Context, kinds []string, ref string, r Resolution) (Ask, bool, error)
- func (p *PG) Summarize(ctx context.Context, f Filter, top int) (Summary, error)
- type Recorder
- type Resolution
- type StageError
- type Store
- type Summary
- type TopQuestion
Constants ¶
const ( KindPlainText = "plain_text" KindAskUserQuestion = "ask_user_question" KindAttention = "attention_ask" KindOpenCodeQuestion = "opencode_question" KindOpenCodePermission = "opencode_permission" )
The kinds of ask (asks.kind, asks_kind_check).
const ( RuntimeClaudeCode = "claude-code" RuntimeOpenCode = "opencode" RuntimeAgent = "agent" )
The runtimes (asks.runtime).
const ( OutcomeAnswered = "answered" OutcomeAnsweredInSession = "answered_in_session" OutcomeDeclined = "declined" OutcomeExpired = "expired" OutcomeCancelled = "cancelled" OutcomeSuperseded = "superseded" // OutcomeMovedOn: the session went on without a recorded answer (a new // assistant turn with no user message in between; an opencode ask that // left the host's list unanswered from here). OutcomeMovedOn = "moved_on" // OutcomeGone: the window was gone before any reply (or now shows another // session). OutcomeGone = "gone" // OutcomeUnknown: muster restarted before it saw how the ask ended // (PG.CloseStale). An answer seen later replaces it. OutcomeUnknown = "unknown" )
How an ask ended (asks.outcome).
const ( ByOwner = "owner" // ByChief: the chief — its answer to a question put to it, or a nudge or // relayed answer it queued into a session (provenance nudge). 🔴 Never // counted as the owner's approval. ByChief = "chief" // ByOther: neither the owner nor the chief — a routed message (a // plugin's, another session's). ByOther = "other" )
Who answered (asks.answered_by). The later phases add "auto:<rule id>" and "shadow".
const ( // ProvMusterSend: a body muster pasted from the owner's own send queue // (or, for a dispatched agent, a line the owner typed into muster's chat). ProvMusterSend = "muster_send" // ProvPane: a user message muster did not put there and cannot attribute // (the owner typing in the terminal — or anything else that can type). ProvPane = "pane" // ProvNudge: a chief nudge or relayed answer muster queued. ProvNudge = "nudge" // ProvRoute: a routed message (a plugin's, another session's). ProvRoute = "route" )
Where a plain-text reply came from (asks.answer_provenance): what muster can prove, never a guess.
const ( MaxQuestionRunes = 4000 MaxQuestionNormRunes = 500 MaxAnswerRunes = 8000 MaxProposedAnswerRunes = 500 MaxCwdRunes = 300 MaxRefRunes = 200 MaxNameRunes = 200 MaxWindowRunes = 32 )
The columns' bounds (each also a CHECK in 0089).
const ( DefaultTextTTL = 30 * 24 * time.Hour RowTTL = 180 * 24 * time.Hour )
Retention: question and answer text is cleared after DefaultTextTTL (MUSTER_ASK_LOG_TEXT_TTL), the row deleted after RowTTL.
const ( DefaultPageSize = 50 MaxPageSize = 200 // DefaultTopQuestions is how many repeated questions Summarize returns. DefaultTopQuestions = 10 )
Page limits.
const ( StageRead = "read" StageClassify = "classify" StageWrite = "write" )
The stages a capture can fail at (muster_ask_capture_errors_total's stage).
const ( // DefaultQueue is how many captures may wait at once; past it a capture // is dropped (and counted). DefaultQueue = 4096 // DefaultCaptureTimeout bounds one capture (a transcript read and a write). DefaultCaptureTimeout = 30 * time.Second )
The Recorder's bounds.
const AnsweredByNone = "none"
AnsweredByNone is how a filter and the summary name an ask nobody answered (asks.answered_by = ”): the same word as the answer histogram's label.
const DropLogEvery = time.Minute
DropLogEvery bounds the "capture queue is full" log line to one per period.
const OutcomeOpen = "open"
OutcomeOpen is how a filter and the summary name an ask that has not ended (asks.outcome = ”).
Variables ¶
var ErrBadAsk = errors.New("asklog: not a valid ask")
ErrBadAsk: a write refused before it reached the database.
var FilterOutcomes = []string{OutcomeOpen, OutcomeAnswered, OutcomeAnsweredInSession, OutcomeDeclined, OutcomeMovedOn, OutcomeExpired, OutcomeCancelled, OutcomeSuperseded, OutcomeGone, OutcomeUnknown}
FilterOutcomes is every value Filter.Outcome takes, in the order a picker lists them.
var Kinds = []string{KindPlainText, KindAskUserQuestion, KindAttention, KindOpenCodeQuestion, KindOpenCodePermission}
Kinds is every kind, in the order the design lists them.
var OpenCodeKinds = []string{KindOpenCodeQuestion, KindOpenCodePermission}
OpenCodeKinds is the two opencode kinds: an opencode ask is resolved by its prompt id whichever it is.
var StaleKinds = []string{KindPlainText, KindOpenCodeQuestion, KindOpenCodePermission}
StaleKinds are the kinds whose resolution lives only in the process that opened them (a plain-text question's reply link; an opencode ask's leaving the window): after a restart nothing can resolve them, so CloseStale closes them unknown. An AskUserQuestion and an attention ask resolve by their source id from any process, and are left open.
Functions ¶
func Answered ¶
Answered reports whether outcome is one the owner (or the chief) gave: the row's answered_at is set only for these.
func AnsweredByFor ¶
AnsweredByFor is who answered a plain-text question whose reply had provenance prov: a nudge is the chief's, a routed message another's, and a message muster pasted for the owner or one it cannot attribute (pane) the owner's.
func AtStage ¶
AtStage marks err as a failure at stage (nil stays nil). An unmarked error a capture returns counts as StageWrite.
func Failed ¶
Failed counts and logs one capture failure of kind at its stage. Every capture failure goes through here (the Recorder's own, and a caller's that failed before it queued anything).
func LastParagraph ¶
LastParagraph is text's last paragraph: the text after its last blank line, trimmed ("" for none). What a session ASKED, not the report before it.
func Normalise ¶
Normalise is q as a rule's pattern is compared with it (asks.question_norm), in this order:
- NFC, lower case, the last paragraph only (LastParagraph);
- a backticked span to {code};
- a GitHub pull-request URL, or #<digits>, to {pr};
- a token holding a '/' and no space to {path} (sentence punctuation it ends with is kept after it);
- a 7–40 character run of hex holding at least one digit AND one letter a–f, to {sha} — so neither a number nor a word like "defaced" is a sha;
- any other run of digits to {n};
- runs of white space to one space, and leading and trailing punctuation, symbols and white space stripped together (the braces of a placeholder excepted) — so "? , ?" loses its comma too, not just the outer marks;
- "" when what is left holds no letter or digit outside a placeholder (only punctuation, symbols or placeholders: "," or "{code} {path}"). That is no question to compare or group by — every such question would share the one normal form — so it gets none, as an empty question does.
It is tested with literal input/output pairs, never with its own output.
Types ¶
type Ask ¶
type Ask struct {
ID int64
Owner int64
Kind string
// Runtime is RuntimeClaudeCode, RuntimeOpenCode or RuntimeAgent.
Runtime string
// Where it was asked: a mirrored window (Host, TmuxSession, Window), its
// Claude Code or opencode session (ClaudeSession), or a dispatched agent's
// conversation (AgentID, ChatSessionID).
Host, TmuxSession, Window string
ClaudeSession string
AgentID, ChatSessionID int64
// Repo is owner/name when known, else ""; Cwd the working directory the
// host reported.
Repo, Cwd string
// EpisodeID is the session_episodes row the ask was raised in (0: none).
EpisodeID int64
// SourceRef is the source's own id ("" for plain text).
SourceRef string
// Question is the redacted question; QuestionNorm its normalised form
// (Normalise). Both "" once purged.
Question, QuestionNorm string
// Options is the offered options as JSON (an array; nil stores []).
Options json.RawMessage
Jev Jev
// Answer is what it was answered with ("" once purged); AnsweredBy,
// Provenance and Outcome as their constants.
Answer, AnsweredBy, Provenance, Outcome string
AskedAt time.Time
AnsweredAt time.Time // zero: not answered
TextPurgedAt time.Time // zero: text held
}
Ask is one row of asks.
type Filter ¶ added in v0.238.0
type Filter struct {
// Kind, Runtime: one of Kinds, one of the Runtime constants ("" = any).
Kind, Runtime string
// Outcome is one of the Outcome constants, OutcomeOpen for an ask not yet
// ended, or "" (any).
Outcome string
// AnsweredBy is ByOwner, ByChief, ByOther, AnsweredByNone (nobody: the ask
// did not end in an answer) or "" (any).
AnsweredBy string
// Host is the mirror host; Repo owner/name; Session a tmux session name or
// a Claude Code / opencode session id. Each matched exactly ("" = any).
Host, Repo, Session string
// Since and Until bound asked_at: Since <= asked_at < Until (zero = open).
Since, Until time.Time
}
Filter narrows a read. The zero value is every one of the caller's rows.
type Jev ¶
type Jev struct {
Label string
NeedsInput, AsksPermission, Neither float64
AskScore float64
Model string
Err string
}
Jev is the stall classifier's answer (chiefnudge.Result) as a row keeps it, as on session_episodes. The zero value: it did not run.
type PG ¶
type PG struct {
// contains filtered or unexported fields
}
PG is Store on Postgres.
func (*PG) CloseStale ¶
CloseStale implements Store.
func (*PG) Page ¶ added in v0.238.0
func (p *PG) Page(ctx context.Context, f Filter, before int64, limit int) (rows []Ask, next int64, err error)
Page is the caller's rows matching f, newest first (asked_at, then id), at most limit (DefaultPageSize when <= 0, MaxPageSize at most), starting after the row before (0: from the newest). next is the id to pass as before for the following page, 0 when there is none.
before names one of the caller's own rows; another owner's id (or none) matches nothing under row-level security, so the page is empty.
func (*PG) Purge ¶
func (p *PG) Purge(ctx context.Context, now time.Time, textTTL, rowTTL time.Duration) (int, int, error)
Purge implements Store.
🔴 THE TEXT TTL IS STRICT: a row asked exactly textTTL ago keeps its text until the next sweep; one asked a moment earlier loses it. The rest of the row (kind, where, scores, who answered, latency, outcome) is kept until rowTTL, so the metrics and rule statistics outlive the text.
type Recorder ¶
type Recorder struct {
// contains filtered or unexported fields
}
Recorder runs captures off their caller's goroutine, IN ORDER, one at a time: an ask's open is always written before its resolution, because both are queued here and the queue is drained by one worker.
🔴 IT NEVER BLOCKS AND NEVER FAILS ITS CALLER. Do returns at once; a full queue drops the capture (counted, StageWrite); a capture's error — and a capture's panic — is counted and logged (Failed), and the next one runs. The worker runs only while there is work, so an idle Recorder holds no goroutine.
func NewRecorder ¶
NewRecorder is a Recorder logging to logger.
func (*Recorder) Do ¶
Do queues fn, a capture of kind, to run as ctx's principal (ctx's deadline and cancellation are not inherited: the caller's request may end first).
func (*Recorder) SetQueueBound ¶
SetQueueBound sets how many captures may wait (tests).
type Resolution ¶
type Resolution struct {
// Outcome is one of the Outcome constants.
Outcome string
// Answer is the answer's text (redacted by the store); AnsweredBy ByOwner,
// ByChief or ""; Provenance one of the Prov constants or "".
Answer, AnsweredBy, Provenance string
// At is when it ended (the reply's own time when the source says).
At time.Time
}
Resolution is how an ask ended.
type StageError ¶
StageError is a capture failure at one stage.
func (*StageError) Error ¶
func (e *StageError) Error() string
func (*StageError) Unwrap ¶
func (e *StageError) Unwrap() error
type Store ¶
type Store interface {
// Open records a. created is false, and nothing is written, when the
// caller already has a row of a.Kind for a.SourceRef (asks_one_per_source);
// id is then that row's. A plain-text ask (SourceRef "") is always new.
Open(ctx context.Context, a Ask) (id int64, created bool, err error)
// Resolve records how ask id ended. ok is false, and nothing is written,
// when the row is not the caller's, has already ended, or ended softly
// (moved on, expired, superseded, gone) and r is not an answer.
Resolve(ctx context.Context, id int64, r Resolution) (Ask, bool, error)
// ResolveRef is Resolve for the caller's row of one of kinds whose
// source_ref is ref.
ResolveRef(ctx context.Context, kinds []string, ref string, r Resolution) (Ask, bool, error)
// Get is the caller's row id; ok false when it is none of theirs.
Get(ctx context.Context, id int64) (Ask, bool, error)
// List is the caller's newest rows, at most limit.
List(ctx context.Context, limit int) ([]Ask, error)
// Page is the caller's rows matching f, newest first, after the row
// before (read.go); next is the following page's before, 0 at the end.
Page(ctx context.Context, f Filter, before int64, limit int) (rows []Ask, next int64, err error)
// Summarize is the summary of the caller's rows matching f (read.go).
Summarize(ctx context.Context, f Filter, top int) (Summary, error)
// Purge is the retention sweep, for every owner (the system scope): it
// clears the text — every text column and options — of rows asked before
// now-textTTL (text_purged_at) and deletes rows asked before now-rowTTL.
// It returns how many of each.
Purge(ctx context.Context, now time.Time, textTTL, rowTTL time.Duration) (purged, deleted int, err error)
// CloseStale closes, for every owner (the system scope), the open rows of
// StaleKinds asked before before: outcome unknown. It returns how many.
CloseStale(ctx context.Context, before time.Time) (int, error)
}
Store is the ask log, under row-level security: every method but Purge acts as ctx's principal, on its rows only.
type Summary ¶ added in v0.238.0
type Summary struct {
// Total is how many of the caller's rows match the filter.
Total int
// ByKind, ByOutcome, ByAnsweredBy count them by asks.kind, asks.outcome
// (OutcomeOpen for ”) and asks.answered_by (AnsweredByNone for ”). A
// value no row holds is absent.
ByKind, ByOutcome, ByAnsweredBy map[string]int
// Answered is how many of them have an answer time (Answered outcomes):
// the rows the latencies are computed over.
Answered int
// MedianAnswer and P90Answer are the median and 90th percentile of
// answered_at - asked_at over the Answered rows, CONTINUOUS percentiles
// (Postgres percentile_cont: linear between the two nearest rows). Zero
// when Answered is 0.
MedianAnswer, P90Answer time.Duration
// Top is the normal forms (question_norm) asked at least twice, most often
// first. Only rows whose text is still held have one.
Top []TopQuestion
}
Summary is what Summarize answers.
type TopQuestion ¶ added in v0.238.0
type TopQuestion struct {
// Norm is the question's normal form (Normalise).
Norm string
// Count is how many rows have it; ByOwner how many of those the owner
// answered (answered_by = owner).
Count, ByOwner int
// MedianAnswer is the median time to an answer over its answered rows
// (zero: none answered).
MedianAnswer time.Duration
// TopAnswer is its most frequent answer text, trimmed and lower-cased (""
// when none of its rows holds answer text), and TopAnswerCount how many of
// its rows gave it.
TopAnswer string
TopAnswerCount int
// LastAsked is its newest row's asked_at.
LastAsked time.Time
}
TopQuestion is one repeated question in a Summary.