Documentation
¶
Overview ¶
Package chiefnudge is the chief's stall nudges (docs/chief-nudges.md): the rules that decide which of an owner's sessions has stalled, what the chief may answer about one, and which of its answers muster accepts — plus the decisions table (migration 0064, chief_nudges).
It holds no I/O but the store. The sweep that reads windows, transcripts and the chief lives in internal/api (chief_nudge.go); everything here is a pure function of what that sweep read, so each guard is testable on its own and none of them lives in a prompt.
🔴 THE GUARDS ARE CODE, NOT INSTRUCTIONS. The chief is told the rules, but a nudge is accepted only when CheckQuote finds its quote, byte for byte, inside one of the OWNER's own messages to that session (OwnerMessages decides which those are); a session's own output can never authorise its own nudge, however it is worded.
Index ¶
- Constants
- Variables
- func AgentKey(agentID, chatSessionID int64) string
- func Anchor(owner []Msg) string
- func AskStall(r Result, threshold float64) bool
- func BuildJevRequest(text string) ([]byte, error)
- func CleanOptions(in []string) []string
- func Cut(s string, n int) string
- func EscalationNoTimes(title string) string
- func EscalationPartial(title string) string
- func EscalationQuestion(title string) string
- func Exclude(s Session, idle time.Duration) string
- func GenericAskQuestion(title string) string
- func IsGenericAsk(options []string) bool
- func IsGenericChoice(options []string, answer string) bool
- func NudgeText(ownerName string, m Msg, quote string, loc *time.Location) string
- func Object(id int64) string
- func ParseJevResponse(body []byte) (string, map[string]float64, string, error)
- func Prompt(s Session, last Msg, owner []Msg, idle time.Duration, hint Hint, nonce string) string
- func Shown(text string) string
- func Suppressed(guard string) string
- func TailBytes(s string, limit int) string
- func Untimed(msgs []Msg) int
- type Classifier
- type Decision
- type Hint
- type Move
- type Msg
- type Owner
- type PG
- func (p *PG) ByAsk(ctx context.Context, askID int64) (Decision, error)
- func (p *PG) Decided(ctx context.Context, kind, key, streak string) (bool, error)
- func (p *PG) Get(ctx context.Context, id int64) (Decision, error)
- func (p *PG) Injected(ctx context.Context, kind, key string) ([]string, error)
- func (p *PG) Insert(ctx context.Context, d Decision, action string) (Decision, bool, error)
- func (p *PG) List(ctx context.Context, limit int) ([]Decision, error)
- func (p *PG) Move(ctx context.Context, id int64, from []string, m Move, action string) (bool, error)
- func (p *PG) NudgesForAnchor(ctx context.Context, kind, key, anchor string) (int, error)
- func (p *PG) NudgesSince(ctx context.Context, since time.Time) (int, error)
- func (p *PG) Owners(ctx context.Context) ([]Owner, error)
- func (p *PG) Pending(ctx context.Context, limit int) ([]Decision, error)
- type Proposal
- type Result
- type Session
- type Store
Constants ¶
const ( KindMirror = "mirror" // a mirrored Claude Code window; Key is its Claude session id KindAgent = "agent" // one of the owner's dispatched agents; Key is its id )
Session kinds.
const ( DecisionNudge = "nudge" DecisionAsk = "ask" DecisionLeave = "leave" DecisionInvalid = "invalid" )
Decisions the chief may return, plus Invalid for an answer muster could not read.
const ( ModeShadow = "shadow" ModeLive = "live" )
Modes.
const ( OutcomeWouldSend = "would_send" // shadow: a nudge that passed every guard OutcomeWouldAsk = "would_ask" // shadow: an ask muster would have raised OutcomeLeft = "left" // the chief said leave it OutcomeQueued = "queued" // live: a mirrored nudge waits in the send queue OutcomeSent = "sent" // live: the nudge reached the session OutcomeAsked = "asked" // live: an attention ask is open OutcomeRelayQueued = "relay_queued" // live: the owner's answer waits in the send queue OutcomeRelayed = "relayed" // live: the owner's answer reached the session OutcomeFailed = "failed" // live: the send or relay did not happen (Detail says why) OutcomeAskClosed = "ask_closed" // live: the ask ended with nothing to relay (Detail says how) SuppressedPrefix = "suppressed:" )
Outcomes: what became of a decision. A suppressed one is SuppressedPrefix + the guard's name.
const ( GuardQuote = "quote_unverified" // the nudge's quote is not in an owner message GuardHourlyCap = "hourly_cap" // the global hourly cap is reached GuardInvalid = "invalid_answer" // the chief's answer did not parse GuardNoQuestion = "no_question" // an ask with no question GuardAskFailed = "ask_not_created" // the attention ask could not be raised GuardMovedOn = "moved_on" // the session left its idle streak before muster acted GuardAskCap = "ask_cap" // the owner's open asks are at attention's cap GuardChiefError = "chief_error" // the chief's call failed (Detail says how); the next streak is judged again GuardSuperseded = "superseded" // a queued nudge or relay was refused at its paste: the session had moved on GuardPartial = "partial_read" // reason text only: the transcript read was incomplete, so no owner message authorises a nudge )
Guard names (the part after SuppressedPrefix).
const ( // DefaultIdle is how long a session must have been idle to be a candidate // (MUSTER_CHIEF_NUDGE_IDLE). DefaultIdle = 10 * time.Minute MinIdle = 2 * time.Minute MaxIdle = 24 * time.Hour // DefaultHourlyCap is the global cap on nudges per hour, shadow and live // together (MUSTER_CHIEF_NUDGE_HOURLY_CAP). DefaultHourlyCap = 6 // MaxNudgesPerAnchor: after this many nudges since the owner's latest // message to a session, the next "nudge" becomes an ask. MaxNudgesPerAnchor = 2 // OwnerWindow is how far back the owner's own messages are read. OwnerWindow = 6 * time.Hour // MaxOwnerMessages is how many of them (the newest) the chief is shown. MaxOwnerMessages = 20 // MaxOwnerMessageRunes cuts each one; MaxLastRunes the session's last message. MaxOwnerMessageRunes = 2000 MaxLastRunes = 4000 // MinQuoteRunes and MinQuoteWords are the shortest quote accepted: a // fragment ("make", "ok go") matches almost any message and authorises // nothing in particular. A quote must be a phrase of the owner's. MinQuoteRunes = 12 MinQuoteWords = 3 // MaxQuoteRunes bounds a quote (the nudge carries it). MaxQuoteRunes = 500 // MinOptions/MaxOptions bound an ask's options. MinOptions = 2 MaxOptions = 4 // RelayMaxAge bounds how long a claimed relay is retried (an agent that // stays busy): past it the relay is dropped and recorded failed. RelayMaxAge = 2 * time.Hour // QueueRepairAfter: a live nudge recorded queued whose send_queue row was // never written (a crash between the two) is failed after this. QueueRepairAfter = 10 * time.Minute )
Defaults and bounds.
const ( ExclNotIdle = "not_idle" ExclTooSoon = "idle_too_short" ExclShell = "background_work" ExclTurnError = "turn_error" ExclOfficer = "officer" ExclChief = "chief" ExclOtherUser = "other_user" ExclOpenAsk = "open_ask" ExclDecided = "already_decided" ExclNoStreak = "no_streak" ExclLastOwner = "last_message_owner" ExclNoMessages = "no_messages" )
Exclusion reasons (Exclude's answers).
const ( LabelNeedsInput = "needs_input" LabelAsksPermission = "asks_permission" LabelNeither = "neither" )
The labels.
const DecisionsURL = "https://openrouter.ai/api/alpha/decisions"
DecisionsURL is OpenRouter's Decisions API (not chat completions).
const DefaultAskThreshold = 0.9
DefaultAskThreshold is the backtested ask-score line (MUSTER_CHIEF_NUDGE_ASK_THRESHOLD).
const DefaultClassifyTimeout = 5 * time.Second
DefaultClassifyTimeout is a hard cap on one classification.
const JevModel = "~typesafe/jev-latest"
JevModel is the model asked; the response names the model actually served (Result.Model), which is what a decision records.
const MaxClassifyBytes = 8 * 1024
MaxClassifyBytes caps the text sent: its TAIL, where the ask is (Jev runs long inputs in a slower, less accurate mode).
const NudgeLabel = "[Chief nudge]"
NudgeLabel opens every nudge: the session reads a labelled message from the chief quoting its owner, never a message in the owner's voice.
Variables ¶
var ( ErrNoQuote = errors.New("the nudge quotes nothing") ErrQuoteShort = fmt.Errorf("the quote is not a phrase: it needs at least %d words and %d characters", MinQuoteWords, MinQuoteRunes) ErrQuoteLong = fmt.Errorf("the quote is longer than %d characters", MaxQuoteRunes) ErrNoCover = errors.New("the nudge names no pending action its quote covers") ErrQuoteUnknown = errors.New("the quote names no owner message of this session") ErrQuoteNotIn = errors.New("the quote is not, byte for byte and on word boundaries, in the owner message it names") )
Quote guard errors.
var ErrNotFound = errors.New("chiefnudge: no such decision")
ErrNotFound: no such decision among the caller's.
var ErrUnparseable = errors.New("chiefnudge: the chief's answer is not a decision")
ErrUnparseable: the chief's answer holds no JSON object with a known decision.
var GenericAskOptions = []string{"Open session", "Dismiss"}
GenericAskOptions are the generic ask's options.
var JevRubrics = map[string]string{ LabelNeedsInput: "Does the assistant end by asking the human a question, requesting " + "information or a decision it needs, or stating that progress is waiting on " + "a decision or an action only the human can take (e.g. 'still waiting on your " + "call', 'next step for you: …', 'once you've merged and run the SQL I'll…') — " + "other than asking permission to proceed with a step it has already proposed?", LabelAsksPermission: "Is the assistant holding its own next planned step until the human approves " + "it (e.g. 'shall I…', 'want me to start…', 'say proceed and I'll…', 'your call " + "to proceed')?", LabelNeither: "Is this a finished report, summary or status update — including waiting on a " + "background job, narrating work in progress, or ending with an OPTIONAL extra " + "offer after the requested work is done (e.g. 'I can look into it if you " + "want') — that needs nothing from the human to continue?", }
JevRubrics is THE one place the three rubric strings live — copied VERBATIM from ask_classifier.py's RUBRICS, which the operator approved and backtested. A reword is a different classifier: TestTheRubricsAreTheApprovedOnes pins every byte.
Functions ¶
func AgentKey ¶
AgentKey is a dispatched agent's conversation as a Session.Key: the agent and the chat session, so each conversation of an agent stalls (and is decided, capped and relayed to) on its own.
func Anchor ¶
Anchor is the owner's latest message's id among owner ("" for none): the nudge cap counts nudges per anchor, so a fresh instruction from the owner resets it.
func AskStall ¶
AskStall reports the backtested rule: the classification says the session stopped on an unasked question or permission request — its ask score is at least threshold.
func BuildJevRequest ¶
BuildJevRequest is the Decisions request for text: the reference's body.
func CleanOptions ¶
CleanOptions is an ask's options: trimmed, one line, deduplicated, cut, at most MaxOptions; when fewer than MinOptions remain, the defaults fill in.
func EscalationNoTimes ¶
EscalationNoTimes is the ask raised in place of a nudge for a session whose host sends no prompt times: no instruction of the owner's can be checked.
func EscalationPartial ¶
EscalationPartial is the ask raised in place of a nudge when the transcript read was incomplete: no instruction of the owner's can be checked.
func EscalationQuestion ¶
EscalationQuestion is the ask raised in place of a third nudge.
func Exclude ¶
Exclude is why s is NOT a candidate, "" when it is: idle for at least idle, no background work, no turn error, not an officer, the chief or another user's, no open ask, and this idle streak not already decided. Coverage (officers, the chief, other users) is decided here as well as by what the sweep lists, so a new source of sessions cannot widen it by accident.
func GenericAskQuestion ¶
GenericAskQuestion is the generic ask's text for a session titled title.
func IsGenericAsk ¶
IsGenericAsk reports whether options are the generic ask's.
func IsGenericChoice ¶
IsGenericChoice reports whether answer, to a decision whose options are options, is one of the generic ask's options — which is not an answer to forward to the session.
func NudgeText ¶
NudgeText is the nudge pasted into the session (operator decision: a labelled message quoting the owner). ownerName is who said it ("your owner" when unknown); m.At, when set, is when, in loc.
func ParseJevResponse ¶
ParseJevResponse is (label, scores, served model) from a response. The label is the argmax over OUR labels, never the response's own `choice`, so a response cannot steer the rule with a label it was not asked about.
func Shown ¶
Shown is text as the chief is shown it in the stall check's fenced block: each line through fence.Sanitize. A quote is matched against THIS form, so a tab or a control character the chief saw replaced does not make a true quote fail.
Types ¶
type Classifier ¶
type Classifier struct {
Key func(ctx context.Context, owner int64) (string, error)
Missing func(error) bool
URL string // "" = DecisionsURL
Client *http.Client
Timeout time.Duration // 0 = DefaultClassifyTimeout
}
Classifier is the Jev call. Key is the owner's OpenRouter key (the focus summarizer's resolution); Missing tells "no key" from a lookup failure.
type Decision ¶
type Decision struct {
ID int64
Owner int64
Kind string
Key string
Host string
TmuxSession string
Window string
AgentID int64
// ChatSessionID is the agent's conversation the decision is about (0 for a
// mirrored session): where its nudge or relay goes.
ChatSessionID int64
Title string
StreakKey string
AnchorKey string
IdleSince time.Time
DecidedAt time.Time
Decision string
Message string
QuoteID string
QuoteAt time.Time
QuoteText string
Covered string
Question string
Options []string
Reason string
Mode string
Outcome string
Detail string
AskID int64
SendQueueID int64
RelayText string
UpdatedAt time.Time
// The stall classifier's result on the session's last message (jev.go):
// zero values with JevError "" mean it was not run.
JevLabel string
JevNeedsInput float64
JevAsksPermission float64
JevNeither float64
JevAskScore float64
JevModel string
JevLatencyMS int
JevError string
}
Decision is one row of chief_nudges.
func (Decision) Suppressed ¶
Suppressed reports whether d's outcome is a guard's.
type Hint ¶
Prompt is the chief's turn for one stalled session: muster's instructions (outside the fence), then — fenced, as data — the session's focus title, its last message and the owner's own messages to it, each with the id a nudge must quote it by.
🔴 EVERY WORD OF THE SESSION'S IS INSIDE THE FENCE, and the owner's messages too (they are quoted back, so they must be the exact bytes CheckQuote matches against: the caller passes them already redacted, and the chief is shown exactly those). Hint is what the stall classifier told the sweep, passed on to the chief.
type Msg ¶
type Msg struct {
Role string // "user" or "assistant" (anything else is ignored)
Text string
// ID names it within its session: a chat message id (agent) or a prompt's
// byte offset in the transcript (mirror). "" for an assistant message.
ID string
// At is when it was written; zero when the source does not say (a
// mirrored transcript from a muster-mirror older than the PromptAt field).
At time.Time
}
Msg is one transcript message, oldest first in a slice.
func CheckQuote ¶
CheckQuote is the nudge guard: p's quote must be a phrase (MinQuoteWords words, MinQuoteRunes characters), name a covered action, and appear BYTE FOR BYTE — starting and ending on word boundaries — inside the one owner message p.QuoteID names (as Shown), which must be one of owner (OwnerMessages' set: never the session's own output, never injected text, never older than the window). It returns that message.
⚠ WHAT IT GUARANTEES, AND WHAT IT DOES NOT: the quote is the owner's own recent words, verbatim. Whether those words COVER the pending action is the chief's judgement (covered_action is its claim), not something code checks.
func LastIsAssistant ¶
LastIsAssistant reports whether the newest user-or-assistant message of msgs is the assistant's, and returns it.
func OwnerMessages ¶
OwnerMessages is the owner's OWN messages among msgs — user-role, written at or after since, at most MaxOwnerMessages, newest last — leaving out:
a message with NO time: its age cannot be checked against since, so it authorises nothing (an older muster-mirror sends prompts without one; Untimed counts them, so the caller can say why there is no nudge);
any message carrying a muster fence (fenceOpen): text muster injected, whose words are an outside party's or muster's, never the owner's;
any message equal (after trimming) to one of injected: what muster itself pasted into this session (a routed message, a nudge, a relay — the send_queue rows muster queued and the chief_nudges rows' texts);
any message starting with one of prefixes: the openings muster's own pastes are written with (the routed preface, NudgeLabel), passed in from the constants the senders use — a second line behind injected, for a paste whose row is gone;
skipFirst: the session's very first message, when the caller knows it is a dispatched agent's kickoff (the task's text, which can be a plugin's).
🔴 THIS IS THE AUTHORITY SET FOR CheckQuote. A message that should not authorise a nudge must not get past here; a message wrongly left out only costs a nudge that becomes an ask.
type PG ¶
type PG struct {
// contains filtered or unexported fields
}
PG is Store on Postgres, under row-level security.
func (*PG) Move ¶
func (p *PG) Move(ctx context.Context, id int64, from []string, m Move, action string) (bool, error)
Move implements Store.
func (*PG) NudgesForAnchor ¶
NudgesForAnchor implements Store.
func (*PG) NudgesSince ¶
NudgesSince implements Store.
type Proposal ¶
type Proposal struct {
Decision string `json:"decision"`
Reason string `json:"reason"`
QuoteID string `json:"quote_id"`
Quote string `json:"quote"`
CoveredAction string `json:"covered_action"`
Question string `json:"question"`
Options []string `json:"options"`
}
Proposal is the chief's answer, as parsed.
func ParseProposal ¶
ParseProposal reads the first JSON object in raw (a model may wrap it in prose or a code fence) and checks its decision is one of nudge, ask, leave.
type Result ¶
type Result struct {
Label string
Scores map[string]float64
AskScore float64 // P(needs_input) + P(asks_permission)
Model string // the model the response says it served
LatencyMS int
Err string
}
Result is one classification. On any failure Err is a short class (never a body or a key) and Label is "".
type Session ¶
type Session struct {
Kind string
Key string // Claude session id (mirror) or agent id (agent)
// Mirror address (KindMirror).
Host, TmuxSession, Window, Label string
// AgentID and ChatSessionID (KindAgent): the agent and the ONE conversation
// of it that stalled — an agent can hold several.
AgentID int64
ChatSessionID int64
Title string // its focus title, "" for none
// Status is "idle", "busy", "waiting" or "" (unknown).
Status string
// IdleFor is how long it has been idle, on muster's clock.
IdleFor time.Duration
IdleSince time.Time
// StreakKey names this idle streak: a new turn starts a new one.
StreakKey string
// Exclusion inputs.
Shell bool // a background shell or subagent of its own is running
TurnError bool // its last turn ended in a usage limit, auth or API error
Officer bool
Chief bool
OtherUser bool // not the owner's (never reaches here through row-level security; checked anyway)
OpenAsk bool // an open attention ask or chief question of its own, or an open nudge ask
Decided bool // this idle streak already has a decision
}
Session is one of an owner's sessions as the sweep saw it, before any transcript is read: everything candidate selection decides on.
type Store ¶
type Store interface {
// Owners is every user who is not disabled (system scope).
Owners(ctx context.Context) ([]Owner, error)
// Decided reports whether the caller's session (kind, key) already has a
// decision for streak.
Decided(ctx context.Context, kind, key, streak string) (bool, error)
// Insert records d for the caller, with its audit row; inserted false (and
// nothing written) when another decision for the same streak won.
Insert(ctx context.Context, d Decision, action string) (Decision, bool, error)
// NudgesForAnchor counts the caller's nudges (would_send, queued, sent) to
// (kind, key) since the owner message anchor.
NudgesForAnchor(ctx context.Context, kind, key, anchor string) (int, error)
// NudgesSince counts every owner's LIVE nudges (queued, sent) decided at
// or after since: the global hourly cap, which bounds what is sent and
// never holds shadow mode back (system scope).
NudgesSince(ctx context.Context, since time.Time) (int, error)
// Injected is what the sweep pasted into the caller's session (kind, key):
// every live nudge and relay text.
Injected(ctx context.Context, kind, key string) ([]string, error)
// Pending is every owner's live decision still in flight (queued, asked,
// relay_queued), system scope.
Pending(ctx context.Context, limit int) ([]Decision, error)
// Get is the caller's decision id.
Get(ctx context.Context, id int64) (Decision, error)
// ByAsk is the caller's decision that raised ask id.
ByAsk(ctx context.Context, askID int64) (Decision, error)
// Move sets the caller's decision id from one of from to outcome, with its
// detail and (when non-zero/non-empty) its ask, queued row and relay text,
// writing action's audit row when action is not ""; moved false when the
// row was not in one of from.
Move(ctx context.Context, id int64, from []string, m Move, action string) (bool, error)
// List is the caller's newest decisions.
List(ctx context.Context, limit int) ([]Decision, error)
}
Store is chief_nudges.