asklog

package
v0.275.0 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 17 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 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

View Source
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).

View Source
const (
	RuntimeClaudeCode = "claude-code"
	RuntimeOpenCode   = "opencode"
	RuntimeAgent      = "agent"
)

The runtimes (asks.runtime).

View Source
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).

View Source
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".

View Source
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.

View Source
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).

View Source
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.

View Source
const (
	DefaultPageSize = 50
	MaxPageSize     = 200
	// DefaultTopQuestions is how many repeated questions Summarize returns.
	DefaultTopQuestions = 10
)

Page limits.

View Source
const (
	StageRead     = "read"
	StageClassify = "classify"
	StageWrite    = "write"
)

The stages a capture can fail at (muster_ask_capture_errors_total's stage).

View Source
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.

View Source
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.

View Source
const DropLogEvery = time.Minute

DropLogEvery bounds the "capture queue is full" log line to one per period.

View Source
const OutcomeOpen = "open"

OutcomeOpen is how a filter and the summary name an ask that has not ended (asks.outcome = ”).

Variables

View Source
var ErrBadAsk = errors.New("asklog: not a valid ask")

ErrBadAsk: a write refused before it reached the database.

FilterOutcomes is every value Filter.Outcome takes, in the order a picker lists them.

Kinds is every kind, in the order the design lists them.

OpenCodeKinds is the two opencode kinds: an opencode ask is resolved by its prompt id whichever it is.

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

func Answered(outcome string) bool

Answered reports whether outcome is one the owner (or the chief) gave: the row's answered_at is set only for these.

func AnsweredByFor

func AnsweredByFor(prov string) string

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

func AtStage(stage string, err error) error

AtStage marks err as a failure at stage (nil stays nil). An unmarked error a capture returns counts as StageWrite.

func Failed

func Failed(logger *log.Logger, kind string, err error)

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

func LastParagraph(text string) string

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

func Normalise(q string) string

Normalise is q as a rule's pattern is compared with it (asks.question_norm), in this order:

  1. NFC, lower case, the last paragraph only (LastParagraph);
  2. a backticked span to {code};
  3. a GitHub pull-request URL, or #<digits>, to {pr};
  4. a token holding a '/' and no space to {path} (sentence punctuation it ends with is kept after it);
  5. 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;
  6. any other run of digits to {n};
  7. 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;
  8. "" 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.

func Prefilter

func Prefilter(text string) bool

Prefilter reports whether text — a turn's last assistant message — looks like it asks the owner something: its last paragraph holds a '?', or begins (after leading markdown and punctuation) with one of prefilterStarts. In code, no model: a turn end that fails it writes no row.

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.

func (Ask) Latency

func (a Ask) Latency() time.Duration

Latency is how long the ask waited for its answer; 0 when unanswered.

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.

func (Filter) Validate added in v0.238.0

func (f Filter) Validate() error

Validate reports why f is not a filter the reader takes, or nil.

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 NewPG

func NewPG(pool *pgxpool.Pool) *PG

NewPG is Store over pool.

func (*PG) CloseStale

func (p *PG) CloseStale(ctx context.Context, before time.Time) (int, error)

CloseStale implements Store.

func (*PG) Get

func (p *PG) Get(ctx context.Context, id int64) (Ask, bool, error)

Get implements Store.

func (*PG) List

func (p *PG) List(ctx context.Context, limit int) ([]Ask, error)

List implements Store.

func (*PG) Open

func (p *PG) Open(ctx context.Context, a Ask) (int64, bool, error)

Open 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.

func (*PG) Resolve

func (p *PG) Resolve(ctx context.Context, id int64, r Resolution) (Ask, bool, error)

Resolve implements Store.

func (*PG) ResolveRef

func (p *PG) ResolveRef(ctx context.Context, kinds []string, ref string, r Resolution) (Ask, bool, error)

ResolveRef implements Store.

func (*PG) Summarize added in v0.238.0

func (p *PG) Summarize(ctx context.Context, f Filter, top int) (Summary, error)

Summarize is the summary of the caller's rows matching f, with at most top repeated questions (DefaultTopQuestions when <= 0).

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

func NewRecorder(logger *log.Logger) *Recorder

NewRecorder is a Recorder logging to logger.

func (*Recorder) Do

func (r *Recorder) Do(ctx context.Context, kind string, fn func(context.Context) error)

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

func (r *Recorder) Flush(ctx context.Context) error

Flush waits until every capture queued before it has run, or ctx ends.

func (*Recorder) SetClock

func (r *Recorder) SetClock(now func() time.Time)

SetClock replaces the recorder's clock (tests).

func (*Recorder) SetQueueBound

func (r *Recorder) SetQueueBound(n int)

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

type StageError struct {
	Stage string
	Err   error
}

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
	// P90Within is the DISCRETE 90th percentile (Postgres percentile_disc):
	// the shortest answer time at least 9 in 10 answered rows took no longer
	// than — one row's own time, so "9 in 10 answered within P90Within" is
	// true for every n, where P90Answer (interpolated) is not. Zero when
	// Answered is 0.
	P90Within 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): what the rows are
	// grouped by.
	Norm string
	// Question is one of its rows' question text as the owner saw it
	// (redacted, like every stored question): the newest one, so a reader is
	// shown a sentence, not the lower-cased normal form.
	Question 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.

Jump to

Keyboard shortcuts

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