Documentation
¶
Overview ¶
Package officers is muster's officer RUNTIME: the long-lived, queue-driven agents whose durable identity, work queue and claim lock live in an HQ server (the "officers" contract), and whose running sessions — instances — muster provisions, wakes and scales to zero.
What lives here is the part that knows nothing about muster's server: the declared configuration (config.go), the reserved agent slugs (slug.go), the HQ client (hq.go), the wake/scale decision and loop (wake.go), and the first message and re-prompt an instance is given (kickoff.go, wake.go). internal/api binds it to agents, the provisioner and the MCP tool registry; cmd/muster-server reads the environment and runs the loop.
🔴 THE OFFICER TOKEN NEVER LEAVES muster-server. It is read from the server's own environment (MUSTER_OFFICER_TOKEN_<NAME>), held in Officer behind a field JSON and fmt never print, and spent only by Client on the way to HQ. An instance's pod reaches HQ through muster's MCP tools, which attach the token server-side; the pod's spec, env, files and first message carry no trace of it. See docs/officers.md.
Index ¶
- Constants
- Variables
- func AllCapabilities() []string
- func AskFilename(name, ct string, n int) string
- func Backoff(o Officer, failures int) time.Duration
- func BodyFirstLine(officerID string, item int) string
- func BranchItem(prefix, officerID, branch string) (int, bool)
- func CapReason(used, limit int, reset time.Time) string
- func CapResetAt(now time.Time) time.Time
- func ChatHolder(instance string) string
- func ChatLaneUnavailableReply(refusals int) string
- func ChatOf(it Item) (chatID string, seq int64, ok bool)
- func ChatRateLimitedReply(detail string) string
- func ChatRateLimitedReplyFor(err error) string
- func ChatSessionKey(chatID string) string
- func ChatTurnText(o Officer, n int, chatName string, msgs []ChatMessage, first, retry bool) string
- func ChatUndeliveredReply(err error) string
- func CheckOwners(list []Officer, kindOf func(owner int64) (OwnerKind, error)) error
- func ClampLease(seconds int) int
- func ClaudePricesAsOf() string
- func CleanRepoPath(p string) bool
- func CompleteOutcomes(o Officer) []string
- func CompleteTakesInvestigation(o Officer) bool
- func CountSessions(entries []string, now time.Time) (int, map[ItemID]bool)
- func CountsRead(o Officer, tool string) bool
- func ErrorSlots() float64
- func EstimateClaudeUSD(model string, input, output, cacheRead, cacheWrite int64) (float64, bool)
- func GrantRerunKey(id int64) string
- func HQFaults() float64
- func ImageAllowed(ref string, allow []string) error
- func InstanceName(id string, n int) string
- func ItemTier(it Item) string
- func KickoffText(o Officer, n int) string
- func KickoffTextWith(o Officer, n int, g KickoffGrants) string
- func KubeReadDisabled(list []Officer) []string
- func MatchAllowed(pat, p string) bool
- func MatchForbidden(pat, p string) bool
- func MaxInstanceNameLen(namespacePrefix string) int
- func MayRequestConnector(o Officer, name string) bool
- func NewPublicBranch(prefix, slug string) (string, error)
- func ObsQueryArgs(raw []byte) (json.RawMessage, error)
- func ObsRawBody(args []byte, item ItemID, instance string) (json.RawMessage, error)
- func OperatorChatID(user, owner int64, officer string) string
- func OperatorChatUser(chatID string) (int64, bool)
- func OverrunSummary(o Officer, ov Overrun) string
- func OwnStateActs(tool string) bool
- func ParseForbiddenList(content string) ([]string, error)
- func PendingToken(now time.Time) string
- func ProviderModel(m string) bool
- func ReadCounted(err error) bool
- func Refusal(err error) (status int, msg, code string, ok bool)
- func ReleaseTagOf(version string) string
- func RepromptText(o Officer, n int) string
- func RoutineAgent(o Officer, name string) bool
- func SameShepherdSubject(subject, repo string, n int) bool
- func SensitiveMatch(pat, p string) bool
- func Serves[T any](b Backend, capability string) (T, error)
- func ShepherdSubject(repo string, n int) string
- func Slug(id string) string
- func SlugCandidates(owner int64, id string, maxLen int) []string
- func SlugMaxFor(namespacePrefix string, maxInstances int) int
- func SlugTag(owner int64, id string, n int) string
- func TaskGetID(raw []byte) (string, error)
- func TaskListQuery(raw []byte) (string, error)
- func TokenEnvSuffix(id string) string
- func ToolCapability(tool string) (capability string, known bool)
- func ToolOffered(o Officer, tool string) bool
- func ToolServed(o Officer, caps Capabilities, tool string) bool
- func TypeOf(id string) string
- func Unimplemented(b Backend) []string
- func ValidChatID(id string) bool
- func ValidHandoffHead(sha string) bool
- func ValidListFile(f string) bool
- func ValidPublicSlug(slug string) bool
- func ValidRefSuffix(s string) bool
- func ValidSlug(s string) bool
- type Admission
- type Ask
- type AsksBackend
- type AutoRestart
- type AutoRestartEvent
- type Backend
- type Backends
- func (h *Backends) AllItems(ctx context.Context, o Officer, status string) ([]Item, error)
- func (h *Backends) Backend(o Officer) Backend
- func (h *Backends) Complete(ctx context.Context, o Officer, item ItemID, instance string, done Completion) error
- func (h *Backends) Forget(key string)
- func (h *Backends) Heartbeat(ctx context.Context, o Officer, item ItemID, instance string, leaseSeconds int) error
- func (h *Backends) RaisedCapToday(ctx context.Context, o Officer, now time.Time) (float64, error)
- func (h *Backends) Release(ctx context.Context, o Officer, item ItemID, instance string) error
- func (h *Backends) Retain(live []Officer)
- func (h *Backends) SpentToday(ctx context.Context, o Officer, now time.Time) (spent float64, served bool, err error)
- func (h *Backends) SwitchedOff(ctx context.Context, o Officer) (bool, error)
- type Budget
- type BudgetAlert
- type BudgetBackend
- type CILogs
- type CapHold
- type Capabilities
- type CaptainBackend
- type CaptainEvaluation
- type CaptainMonitor
- type CaptainPost
- type CharterGated
- type ChatLanes
- type ChatMarks
- type ChatMessage
- type ChatOutcome
- type ChatPage
- type ChatPlan
- type ChatRunner
- func (r *ChatRunner) Dispatch(ctx context.Context, o Officer, obs Observation, now time.Time)
- func (r *ChatRunner) On(o Officer) bool
- func (r *ChatRunner) Run(ctx context.Context, o Officer, n int, it Item) ChatOutcome
- func (r *ChatRunner) Wait()
- func (r *ChatRunner) Want(ctx context.Context, o Officer, obs Observation, now time.Time) (ChatPlan, map[ItemID]bool)
- type ChatRunnerConfig
- type ChatsBackend
- type ClaudePrice
- type Client
- func (c *Client) AllItems(ctx context.Context, status string) ([]Item, error)
- func (c *Client) AttachRolloutEvidence(ctx context.Context, instance string, e RolloutEvidence) ([]byte, error)
- func (c *Client) Brief(ctx context.Context) ([]byte, error)
- func (c *Client) Capabilities() Capabilities
- func (c *Client) ChatMessages(ctx context.Context, chat string, after int64) (ChatPage, error)
- func (c *Client) ChatReply(ctx context.Context, chat, text string, inReplyTo int64) (int64, error)
- func (c *Client) Claim(ctx context.Context, item ItemID, instance string, leaseSeconds int, ...) ([]byte, error)
- func (c *Client) ClaimNext(ctx context.Context, instance string, leaseSeconds int, tier string) ([]byte, error)
- func (c *Client) Complete(ctx context.Context, item ItemID, instance string, done Completion) ([]byte, error)
- func (c *Client) CreateAsk(ctx context.Context, item ItemID, instance string, a Ask) ([]byte, error)
- func (c *Client) CreateTaskAsk(ctx context.Context, instance string, a TaskAskArgs) ([]byte, error)
- func (c *Client) Do(ctx context.Context, method, path string, body any) ([]byte, error)
- func (c *Client) Enabled(ctx context.Context) (bool, error)
- func (c *Client) FileGapTask(ctx context.Context, instance string, a GapTaskArgs) ([]byte, error)
- func (c *Client) Heartbeat(ctx context.Context, item ItemID, instance string, leaseSeconds int) ([]byte, error)
- func (c *Client) Items(ctx context.Context, q ItemsQuery) (ItemsPage, error)
- func (c *Client) MergeAsk(ctx context.Context, item ItemID, body []byte) ([]byte, error)
- func (c *Client) ObsQueries(ctx context.Context) ([]byte, error)
- func (c *Client) ObsQuery(ctx context.Context, args json.RawMessage) ([]byte, error)
- func (c *Client) ObsRaw(ctx context.Context, body json.RawMessage) ([]byte, error)
- func (c *Client) Officer() Officer
- func (c *Client) PRContext(ctx context.Context, a PRContextArgs) ([]byte, error)
- func (c *Client) PROpened(ctx context.Context, p PROpened) (PROpenedAnswer, error)
- func (c *Client) PostNotice(ctx context.Context, path string, n Notice) error
- func (c *Client) PostTranscript(ctx context.Context, item ItemID, instance string, events []TranscriptEvent) (TranscriptAck, error)
- func (c *Client) Preflight(ctx context.Context) (Preflight, error)
- func (c *Client) ProposeFloodBlock(ctx context.Context, instance string, p FloodBlockProposal) ([]byte, error)
- func (c *Client) PutPools(ctx context.Context, r PoolsReport) error
- func (c *Client) PutUsage(ctx context.Context, r UsageReport) error
- func (c *Client) Release(ctx context.Context, item ItemID, instance string) ([]byte, error)
- func (c *Client) ReleaseCaptain(ctx context.Context, instance string, p CaptainPost) ([]byte, error)
- func (c *Client) RerunItem(ctx context.Context, item ItemID, r RerunRequest) (RerunAnswer, error)
- func (c *Client) Scrub(s string) string
- func (c *Client) Shadow(ctx context.Context) (bool, error)
- func (c *Client) TaskGet(ctx context.Context, id string) ([]byte, error)
- func (c *Client) TaskList(ctx context.Context, query string) ([]byte, error)
- func (c *Client) UploadAskImage(ctx context.Context, filename, contentType string, data []byte) (askimage.Record, error)
- type CloseOldestDraft
- type Completion
- type Config
- type ConnectorBlock
- type ConnectorBlockStore
- type Decision
- type Declaration
- type DocsOnly
- type ErrorClass
- type FieldError
- type FieldErrors
- type Fleet
- type FloodBlockProposal
- type FloodBlocksBackend
- type GapTaskArgs
- type GapTasksBackend
- type HQ
- type HQError
- type Handoff
- type HostSpawn
- type HostSpawnLender
- type HostSpawnStore
- type InstanceState
- type InternalPattern
- type Investigation
- type InvestigationFix
- type InvestigationRule
- type Item
- type ItemCost
- type ItemID
- type ItemsPage
- type ItemsQuery
- type JudgementLedger
- func (l *JudgementLedger) Reserve(ctx context.Context, o Officer, item ItemID, now time.Time) (undo func(), err error)
- func (l *JudgementLedger) ReserveNext(ctx context.Context, o Officer, now time.Time) (done func(item ItemID, known bool), err error)
- func (l *JudgementLedger) Usage(ctx context.Context, o Officer, now time.Time) (int, map[ItemID]bool, error)
- type KickoffGrants
- type Kube
- type KubeCluster
- type LLM
- type MemConnectorBlockStore
- func (m *MemConnectorBlockStore) BlocksForGrant(_ context.Context, officer string, grant int64, since time.Time, limit int) ([]ConnectorBlock, error)
- func (m *MemConnectorBlockStore) RecordBlock(_ context.Context, b ConnectorBlock) error
- func (m *MemConnectorBlockStore) SettleBlock(_ context.Context, officer string, grant int64, item ItemID, _ time.Time) error
- func (m *MemConnectorBlockStore) SettleBlocks(_ context.Context, officer string, grant int64, before, _ time.Time) (int, error)
- func (m *MemConnectorBlockStore) UnsettledGrants(_ context.Context, officer string, limit int) ([]int64, error)
- type MemHostSpawnStore
- func (m *MemHostSpawnStore) All() []HostSpawn
- func (m *MemHostSpawnStore) CountHostSpawnsSince(_ context.Context, officer string, since time.Time) (int, error)
- func (m *MemHostSpawnStore) HostSpawnByID(_ context.Context, id int64) (HostSpawn, error)
- func (m *MemHostSpawnStore) HostSpawnForSession(_ context.Context, host, session string) (HostSpawn, error)
- func (m *MemHostSpawnStore) HostSpawnIDs(_ context.Context, host string, ids []int64) (map[int64]bool, error)
- func (m *MemHostSpawnStore) HostSpawnsInWindows(_ context.Context, host string, windows []string) ([]HostSpawn, error)
- func (m *MemHostSpawnStore) InsertHostSpawn(_ context.Context, officer, instance, host string) (HostSpawn, error)
- func (m *MemHostSpawnStore) LatestHostSpawns(_ context.Context, officer string) (map[string]HostSpawn, error)
- func (m *MemHostSpawnStore) MarkHostSpawnClaimed(_ context.Context, id int64, host string) (bool, error)
- func (m *MemHostSpawnStore) ObserveHostListing(_ context.Context, host string, windows []string, settled time.Time) error
- func (m *MemHostSpawnStore) OpenUnclaimedNotices(_ context.Context) ([]HostSpawn, error)
- func (m *MemHostSpawnStore) RecordHostSpawnRefusal(_ context.Context, id int64, host, refusal string) (bool, error)
- func (m *MemHostSpawnStore) RecordHostSpawnSession(_ context.Context, id int64, host, window, session string) (bool, error)
- func (m *MemHostSpawnStore) RecordHostSpawnWindow(_ context.Context, id int64, host, window, session string) (bool, error)
- func (m *MemHostSpawnStore) SetUnclaimedNotice(_ context.Context, id, notice int64) (bool, error)
- func (m *MemHostSpawnStore) SettleUnclaimedNotice(_ context.Context, id int64) (bool, error)
- type MemPRLoopStore
- func (m *MemPRLoopStore) PRLoopAnnounced(_ context.Context, officer, repo string, pr int, head string) error
- func (m *MemPRLoopStore) PRLoopSettle(_ context.Context, officer, repo string, pr int, state string) error
- func (m *MemPRLoopStore) PRLoopState(_ context.Context, officer, repo string, pr int) (string, error)
- func (m *MemPRLoopStore) PRLoopsClaim(_ context.Context, officer string, notBefore time.Time) (claimed, expired []PRLoop, err error)
- func (m *MemPRLoopStore) PRLoopsInLoop(_ context.Context, officer string) ([]PRLoop, error)
- type MemPRQueueStore
- func (m *MemPRQueueStore) PRQueueAdd(_ context.Context, officer string, q QueuedPR) (QueuedPR, error)
- func (m *MemPRQueueStore) PRQueueList(_ context.Context, officer, repo string) ([]QueuedPR, error)
- func (m *MemPRQueueStore) PRQueueMark(_ context.Context, officer string, id int64, head, note string) (bool, error)
- func (m *MemPRQueueStore) PRQueueSettle(_ context.Context, officer string, id int64, head, state string, pr int, ...) (bool, error)
- type MemPublicBranchStore
- func (m *MemPublicBranchStore) PublicBranchItem(_ context.Context, officer, repo, branch string) (int, bool, error)
- func (m *MemPublicBranchStore) PublicBranchMint(_ context.Context, officer, repo string, item int, branch string) (string, error)
- func (m *MemPublicBranchStore) PublicBranches(_ context.Context, officer, repo string) ([]string, error)
- type Notice
- type ObsBackend
- type ObsRawBackend
- type Observation
- type Officer
- func (o Officer) AgentSlug() string
- func (o Officer) ApprovalReadRepos() []string
- func (o Officer) BackendKind() string
- func (o Officer) BypassesBudget(it Item) bool
- func (o Officer) ChatIdleStop() time.Duration
- func (o Officer) ChatMaxInstances() int
- func (o Officer) ChatOnly(n int) bool
- func (o Officer) ChatSessions() int
- func (o Officer) ChatsPool() bool
- func (o Officer) DeclaredChatSessions() int
- func (o Officer) FreshSessionPerItem() bool
- func (o Officer) FromDB() bool
- func (o Officer) GoString() string
- func (o Officer) HasSessionCap() bool
- func (o Officer) InstanceLabel(n int) string
- func (o Officer) InstanceName(n int) string
- func (o Officer) IsBuiltin() bool
- func (o Officer) IsRoutineKind(kind string) bool
- func (o Officer) ItemCap() time.Duration
- func (o Officer) Key() string
- func (o Officer) KubeCluster(name string) (KubeCluster, bool)
- func (o Officer) KubeClusters() []KubeCluster
- func (o Officer) OnHost() bool
- func (o Officer) OverBudget(spent float64) bool
- func (o Officer) Pool(tier string) Officer
- func (o Officer) PoolLLM() *LLM
- func (o Officer) Pools() []Officer
- func (o Officer) RoutineDue(kind string, now time.Time) *time.Time
- func (o Officer) RunsChatInstances() bool
- func (o Officer) RuntimeKind() string
- func (o Officer) SessionCap() int
- func (o Officer) Slots() int
- func (o Officer) StandingReadRepos() []string
- func (o Officer) String() string
- func (o Officer) Token() string
- func (o Officer) TranscriptEnabled() bool
- func (o Officer) Type() string
- func (o Officer) UsesLLMProxy() bool
- func (o Officer) WithChatIdleStop(d time.Duration) Officer
- func (o Officer) WithChatMaxInstances(n int) Officer
- func (o Officer) WithChatSessions(n int) Officer
- func (o Officer) WithRaisedCap(usd float64) Officer
- func (o Officer) WithToken(token string) Officer
- type Overrun
- type OwnerKind
- type PGConnectorBlockStore
- func (s *PGConnectorBlockStore) BlocksForGrant(ctx context.Context, officer string, grant int64, since time.Time, limit int) ([]ConnectorBlock, error)
- func (s *PGConnectorBlockStore) RecordBlock(ctx context.Context, b ConnectorBlock) error
- func (s *PGConnectorBlockStore) SettleBlock(ctx context.Context, officer string, grant int64, item ItemID, at time.Time) error
- func (s *PGConnectorBlockStore) SettleBlocks(ctx context.Context, officer string, grant int64, before, at time.Time) (int, error)
- func (s *PGConnectorBlockStore) UnsettledGrants(ctx context.Context, officer string, limit int) ([]int64, error)
- type PGHostSpawnStore
- func (s *PGHostSpawnStore) CountHostSpawnsSince(ctx context.Context, officer string, since time.Time) (int, error)
- func (s *PGHostSpawnStore) HostSpawnByID(ctx context.Context, id int64) (HostSpawn, error)
- func (s *PGHostSpawnStore) HostSpawnForSession(ctx context.Context, host, session string) (HostSpawn, error)
- func (s *PGHostSpawnStore) HostSpawnIDs(ctx context.Context, host string, ids []int64) (map[int64]bool, error)
- func (s *PGHostSpawnStore) HostSpawnsInWindows(ctx context.Context, host string, windows []string) ([]HostSpawn, error)
- func (s *PGHostSpawnStore) InsertHostSpawn(ctx context.Context, officer, instance, host string) (HostSpawn, error)
- func (s *PGHostSpawnStore) LatestHostSpawns(ctx context.Context, officer string) (map[string]HostSpawn, error)
- func (s *PGHostSpawnStore) LendHostSpawn(ctx context.Context, id, team int64) (HostSpawn, error)
- func (s *PGHostSpawnStore) MarkHostSpawnClaimed(ctx context.Context, id int64, host string) (bool, error)
- func (s *PGHostSpawnStore) ObserveHostListing(ctx context.Context, host string, windows []string, settled time.Time) error
- func (s *PGHostSpawnStore) OpenUnclaimedNotices(ctx context.Context) ([]HostSpawn, error)
- func (s *PGHostSpawnStore) RecordHostSpawnRefusal(ctx context.Context, id int64, host, refusal string) (bool, error)
- func (s *PGHostSpawnStore) RecordHostSpawnSession(ctx context.Context, id int64, host, window, session string) (bool, error)
- func (s *PGHostSpawnStore) RecordHostSpawnWindow(ctx context.Context, id int64, host, window, session string) (bool, error)
- func (s *PGHostSpawnStore) SetUnclaimedNotice(ctx context.Context, id, notice int64) (bool, error)
- func (s *PGHostSpawnStore) SettleUnclaimedNotice(ctx context.Context, id int64) (bool, error)
- func (s *PGHostSpawnStore) VisibleHostSpawns(ctx context.Context, w SpawnWindow, limit int) ([]HostSpawn, error)
- type PGPRLoopStore
- func (s *PGPRLoopStore) PRLoopAnnounced(ctx context.Context, officer, repo string, pr int, head string) error
- func (s *PGPRLoopStore) PRLoopSettle(ctx context.Context, officer, repo string, pr int, state string) error
- func (s *PGPRLoopStore) PRLoopState(ctx context.Context, officer, repo string, pr int) (string, error)
- func (s *PGPRLoopStore) PRLoopsClaim(ctx context.Context, officer string, notBefore time.Time) (claimed, expired []PRLoop, err error)
- func (s *PGPRLoopStore) PRLoopsInLoop(ctx context.Context, officer string) ([]PRLoop, error)
- type PGPRQueueStore
- func (s *PGPRQueueStore) PRQueueAdd(ctx context.Context, officer string, q QueuedPR) (QueuedPR, error)
- func (s *PGPRQueueStore) PRQueueList(ctx context.Context, officer, repo string) ([]QueuedPR, error)
- func (s *PGPRQueueStore) PRQueueMark(ctx context.Context, officer string, id int64, head, note string) (bool, error)
- func (s *PGPRQueueStore) PRQueueSettle(ctx context.Context, officer string, id int64, head, state string, pr int, ...) (bool, error)
- type PGPublicBranchStore
- func (s *PGPublicBranchStore) PublicBranchItem(ctx context.Context, officer, repo, branch string) (int, bool, error)
- func (s *PGPublicBranchStore) PublicBranchMint(ctx context.Context, officer, repo string, item int, branch string) (string, error)
- func (s *PGPublicBranchStore) PublicBranches(ctx context.Context, officer, repo string) ([]string, error)
- type PGRestartStore
- func (s *PGRestartStore) RecordRestart(ctx context.Context, officer, day, instance string, at time.Time, ...) error
- func (s *PGRestartStore) RestartDay(ctx context.Context, officer, day string) (map[string]RestartRecord, error)
- func (s *PGRestartStore) SetRestartHeld(ctx context.Context, officer, day, instance string, held bool, errText string) error
- type PGSessionStore
- func (s *PGSessionStore) AdmitSession(ctx context.Context, officer, day, entry string, limit int, now time.Time) (Admission, error)
- func (s *PGSessionStore) ReleaseSession(ctx context.Context, officer, day, entry string) error
- func (s *PGSessionStore) ResolveSession(ctx context.Context, officer, day, token, entry string) error
- func (s *PGSessionStore) Sessions(ctx context.Context, officer, day string) ([]string, error)
- type PRContextArgs
- type PRContextBackend
- type PRContextRouteUnavailableError
- type PRLoop
- type PRLoopStore
- type PROpened
- type PROpenedAnswer
- type PRQueueStore
- type PassResult
- type PoolReport
- type PoolReset
- type PoolsBackend
- type PoolsPoster
- type PoolsReport
- type PoolsReporter
- type PoolsReporterConfig
- type Preflight
- type PublicBranchStore
- type QueuedPR
- type QuietHours
- type RaisedCapBackend
- type ReadBudget
- type Reconciler
- func (r *Reconciler) Check(ctx context.Context, key string, force bool) PassResult
- func (r *Reconciler) Done() <-chan struct{}
- func (r *Reconciler) Due(key string)
- func (r *Reconciler) Refresh(ctx context.Context, key string, between func(context.Context) error) (RefreshResult, error)
- func (r *Reconciler) Run(ctx context.Context)
- type RefreshResult
- type Registry
- type RerunAnswer
- type RerunBackend
- type RerunRequest
- type Restart
- type RestartRecord
- type RestartStore
- type RetryableError
- type Rollout
- type RolloutEvidence
- type RolloutEvidenceBackend
- type SessionStore
- type Shepherd
- type ShepherdAuthor
- type ShepherdRule
- type Ship
- func (s *Ship) AppKey() *rsa.PrivateKey
- func (s *Ship) EscalateWebhook() string
- func (s *Ship) ForRepo(r ShipRepo) *Ship
- func (s *Ship) GoString() string
- func (s *Ship) InternalPatterns() ([]InternalPattern, error)
- func (s *Ship) IsDraft() bool
- func (s *Ship) IsShepherd() bool
- func (s *Ship) MayMarkReady() bool
- func (s *Ship) MayMerge() bool
- func (s *Ship) MayRelease() bool
- func (s *Ship) NewPRsPerDay() int
- func (s *Ship) NoticeURLPath(officerID string) string
- func (s *Ship) RepoFor(primary, repo string) (ShipRepo, bool)
- func (s *Ship) RepoList(primary string) []ShipRepo
- func (s *Ship) String() string
- func (s *Ship) WithEscalateWebhook(u string) *Ship
- type ShipBackend
- type ShipRepo
- type SpawnBudget
- type SpawnWindow
- type StatusRead
- type SwitchGated
- type TaskAskArgs
- type TaskAsksBackend
- type TaskRouteUnavailableError
- type TasksBackend
- type TierPool
- type Tiers
- type Transcript
- type TranscriptAck
- type TranscriptBackend
- type TranscriptEvent
- type UsageBackend
- type UsageReport
Constants ¶
const ( DefaultAutoRestartAfter = 5 * time.Minute DefaultAutoRestartMaxPerDay = 4 // MaxAutoRestartDelay bounds Delay: one restart's wait is never longer // than a day. MaxAutoRestartDelay = 24 * time.Hour )
Defaults for AutoRestart (cmd/muster-server: MUSTER_OFFICER_AUTO_RESTART_*).
const ( CapTiers = "tiers" // routine/judgement claims, ?tier=, needs_judgement CapInvestigation = "investigation" // the investigation block on complete CapCost = "cost" // cost_usd + cost_from on complete CapTranscript = "transcript" CapUsage = "usage" CapPools = "pools" CapAsks = "asks" CapTaskAsks = "task-asks" CapFloodBlocks = "flood-blocks" CapRollout = "rollout-evidence" CapGapTasks = "gap-tasks" CapTasksRead = "tasks-read" CapPRContext = "pr-context" CapObs = "obs" CapObsRaw = "obs.raw" CapCaptain = "x-captain" CapShip = "ship" // notices + preflight, for the ship gates CapRerun = "rerun" // re-run a finished item (connector_blocks.go) )
The capabilities: the optional verbs, plus the core-verb features a backend may lack. Each optional verb's capability names the interface above that serves it (capabilityInterface).
const ( // DefaultChatSessions is how many chat lanes an instance runs at once // when the officer declares none: ccd's own default for CCD_MAX_SESSIONS // (cmd/ccd defaultMaxLanes; TestTheChatSessionDefaultIsCcdsLaneDefault). DefaultChatSessions = 3 // MaxChatSessions bounds `chat_sessions`. Each lane is a Claude Code CLI, // ~250-550 MiB, beside the primary in the instance pod's memory. MaxChatSessions = 5 )
Chat-session sizing (`chat_sessions`).
const ( // DefaultChatMaxInstances is how many instances a pool may run for its // chats when the officer declares no `chat_max_instances`. DefaultChatMaxInstances = 3 // MaxChatMaxInstances bounds `chat_max_instances`: an instance number is // never above MaxInstancesCap, whichever setting asks for it. MaxChatMaxInstances = MaxInstancesCap // DefaultChatIdleStop is how long an instance with no chat turn, no // claim and no prompt stays up before it is stopped (`chat_idle_stop`). DefaultChatIdleStop = 15 * time.Minute // MinChatIdleStop and MaxChatIdleStop bound `chat_idle_stop`. MinChatIdleStop = time.Minute MaxChatIdleStop = 24 * time.Hour )
Chat-instance autoscaling (`chat_max_instances`, `chat_idle_stop`).
const ( ChatRoleMember = "member" ChatRoleOfficer = "officer" ChatRoleSystem = "system" )
The chat message roles.
const ( // DefaultCICommitLabel is the PipelineRun label the trigger operator // (pipeline.jquad.rocks) sets to the pull request's head commit. DefaultCICommitLabel = "pipeline.jquad.rocks/pr.branch.commit" // DefaultCIPRParam is the PipelineRun param holding the pull request number. DefaultCIPRParam = "PR_NUMBER" // DefaultCIMaxBytes bounds the excerpt text one call returns. DefaultCIMaxBytes = 16 << 10 // MaxCIMaxBytes is the most max_bytes may be. MaxCIMaxBytes = 64 << 10 )
Defaults and bounds of a `ci_logs` block.
const ( DefaultMaxInstances = 1 DefaultIdleAfter = 30 * time.Minute DefaultPollInterval = time.Minute // MinPollInterval bounds how often muster asks HQ, whatever is declared: // a typo of "1s" for "1m" must not become sixty requests a minute per // officer. MinPollInterval = 10 * time.Second // MaxInstancesCap bounds max_instances. Each instance is a pod, a PVC and a // Claude account for life, so a fat-fingered 100 is refused at boot. MaxInstancesCap = 8 // MaxReadRepos bounds read_repos. Each entry is one more repository an // approval of the officer's `github` grant reaches, so the list is kept // short enough to read on the approve card. MaxReadRepos = 5 )
Defaults applied to a declared officer that leaves a field out.
const ( ManagedByEnv = "env" ManagedByDB = "db" )
Where an officer is declared (Officer.ManagedBy).
const ( // RuntimePod runs each instance as a pod through the provisioner: the // default, and the only runtime before officers-on-hosts. RuntimePod = "pod" // RuntimeHost runs each instance as a host-spawned Claude Code window on // the mirror host `host` (docs/design/officers-on-hosts.md). RuntimeHost = "host" )
The runtimes a declaration may name (`runtime`).
const ( // BackendHQ is an external HQ over HTTPS with the officer's token: the // default, and the only backend before officer-backend/v1. BackendHQ = "hq" // BackendBuiltin is muster's own Postgres (internal/officers/builtin): // the officer's type, charter, switch and queue live in muster's database, // written through the owner-scoped admin API (#503 slice 7). BackendBuiltin = "builtin" )
The officer backends a declaration may name (`backend`).
const ( // ReadGrantStanding serves read_repos with no approval: anonymously, reads // only, each verified public (Officer.ReadGrant). ReadGrantStanding = "standing" // ReadAtRelease points a standing read at muster's own release tag // (Officer.ReadAt, Officer.ReleaseTag). ReadAtRelease = "release" )
The values of an officer's `read_grant` and `read_at`.
const ( StatusOpen = "open" StatusClaimed = "claimed" StatusDone = "done" StatusEscalated = "escalated" )
Item statuses, as the contract names them.
const ( MinLeaseSeconds = 30 MaxLeaseSeconds = 3600 DefaultLeaseSeconds = 600 )
Lease bounds, from the contract (30..3600 seconds).
const ( MaxTranscriptEvents = 100 MaxTranscriptText = 8 << 10 // bytes )
Transcript route bounds, as HQ enforces them.
const ( TranscriptUser = "user" TranscriptAssistant = "assistant" TranscriptToolUse = "tool_use" TranscriptToolResult = "tool_result" TranscriptSystem = "system" )
Transcript event kinds, as the contract names them.
const ( MaxUsageBuckets = 1000 MaxUsageBody = 256 << 10 // bytes )
Usage route bounds, as HQ enforces them.
const ( MaxCaptainSummary = 10000 // characters MaxCaptainReport = 20000 // characters MaxCaptainMonitors = 50 MaxCaptainMonitorName = 200 // characters MaxCaptainMonitorURL = 2048 MaxCaptainField = 200 // service / tag: a local sanity bound )
Captain route bounds, as HQ enforces them.
const ( // ToolTaskAsk is a task-reconciler officer's: ask HQ to ask a finding's // task owner to approve one action (HQ picks the person and the options). ToolTaskAsk = "officer_task_ask" // ToolFloodBlockPropose is a web-performance officer's: propose a // Cloudflare managed challenge on a bot surge's flood units, for a person // to approve. ToolFloodBlockPropose = "officer_flood_block_propose" )
The two tools.
const ( ToolBrief = "officer_brief" ToolItems = "officer_items" ToolClaim = "officer_claim" ToolHeartbeat = "officer_heartbeat" ToolComplete = "officer_complete" ToolRelease = "officer_release" // ToolReleaseEvaluation posts a release evaluation to HQ's captain route // (POST /releases/captain). Offered to `release:*` officers only // (ToolOffered). ToolReleaseEvaluation = "officer_release_evaluation" // ToolMergePR, ToolTagRelease and ToolRolloutStatus are a SHIPPING // officer's (Officer.Ship != nil): squash-merge its own pull request, tag a // release, and read the rollout watch — each gated in muster-server // (internal/officership), never in the instance. ToolMergePR = "officer_merge_pr" ToolTagRelease = "officer_tag_release" ToolRolloutStatus = "officer_rollout_status" // ToolMarkReady is a shipping officer's too: draft -> ready for review on // its own pull request (GitHub's GraphQL mutation; REST PATCH pulls takes // no `draft`, and the push gate refuses that field). ToolMarkReady = "officer_mark_ready" // ToolCILogs reads why the officer's OWN pull request's CI failed (the // failed Tekton TaskRuns' failing tests and error lines). Offered to a // shipping officer with a `ci_logs` block only; read-only. ToolCILogs = "officer_ci_logs" // ToolPublicBranch names (and muster records) the branch a draft // officer's item is pushed to in a ship repository marked public: a // neutral name with no officer id and no item number // (officers.NewPublicBranch). Offered to a draft officer with at least one // public repository only. ToolPublicBranch = "officer_public_branch" // ToolAskPerson asks a named HQ member a question about an item (HQ's // asks route); asking ends the instance's lease on it. Every officer's. ToolAskPerson = "officer_ask_person" // ToolObsQueries and ToolObsQuery read HQ's NAMED observability queries // through HQ's officer obs route (obs.go): the registry, and one entry // run with its declared arguments — never a raw query. Every officer's; // HQ decides whether its route is on (503 obs_unconfigured when off). ToolObsQueries = "officer_obs_queries" ToolObsQuery = "officer_obs_query" // ToolObsRaw runs the instance's OWN PromQL / LogQL through HQ's raw obs // route (POST /officers/{id}/obs/raw, obs.go) for the item it holds: // offered to both pools of a tiered officer (the routine pool by operator // decision), refused by HQ unless the officer's type // investigates — and, on today's HQ, unless the item is judgement tier. // Read-only; it spends the item's read budget (reads.go). ToolObsRaw = "officer_obs_raw" // ToolPostDraft files an OUTBOUND draft through the plugin bound to the // officer (internal/plugins outbound.go): a post or a reply its owner // approves, exact text and media, before the plugin sends it. Offered to a // BUILTIN officer only, and only while its type grants outbound_drafts // (checked at call time by internal/api); never to an HQ officer. ToolPostDraft = "officer_post_draft" // ToolContactGet, ToolContactsList and ToolContactNote read and annotate // the people a builtin officer's bound plugin reported engaging with its // owner's posts (internal/officers/builtin contacts.go). Offered to a // BUILTIN officer only, and only while its type grants contacts (checked // at call time by internal/api); never to an HQ officer. ToolContactGet = "officer_contact_get" ToolContactsList = "officer_contacts_list" ToolContactNote = "officer_contact_note" // The OWN-STATE tools (officers UX PR 2/4; internal/api // officer_own_state.go): what a builtin officer reads and does about its // OWN state when its owner chats with it on its page. ToolMyState reads // (its open asks, pending drafts and outreach batches, refusals waiting // on its owner, today's spend against its budget, its schedules); the // other three ACT and are refused outside an operator chat (chat.go // OperatorChatID): ToolConfirmCard asks muster to draw a confirm card // for one of its pending drafts or batches — the OWNER approves it, never // the officer — and ToolRefusalRefile / ToolRefusalDrop are the officer // page's Re-file and Drop of a refusal waiting on its owner. Offered to a // BUILTIN pod officer only (ToolOffered). ToolMyState = "officer_my_state" ToolConfirmCard = "officer_confirm_card" ToolRefusalRefile = "officer_refusal_refile" ToolRefusalDrop = "officer_refusal_drop" )
The MCP tool names muster serves to officer instances.
const ( // ToolKubeRead is the judgement instances' cluster read tool. ToolKubeRead = "officer_kube_read" // KubeConnector is the connector officer_kube_read's grant is filed for // (connectors.KubeReadName). KubeConnector = "kube-read" // The sealed environment each declared cluster is read from. KubeEndpointEnvPrefix = "MUSTER_KUBE_READ_ENDPOINT_" KubeCAEnvPrefix = "MUSTER_KUBE_READ_CA_" KubeMinterEnvPrefix = "MUSTER_KUBE_READ_MINTER_TOKEN_" KubeAllowlistEnvPrefix = "MUSTER_KUBE_READ_ALLOWLIST_" // MaxKubeClusters bounds kube.clusters. MaxKubeClusters = 8 )
const ( // MaxLLMDailyBudgetUSD bounds daily_budget_usd. MaxLLMDailyBudgetUSD = 1000.0 // DefaultLLMMaxTokensPerItem is max_tokens_per_item when it is left out. DefaultLLMMaxTokensPerItem = 400_000 // MinLLMMaxTokensPerItem and MaxLLMMaxTokensPerItem bound it. MinLLMMaxTokensPerItem = 1_000 MaxLLMMaxTokensPerItem = 20_000_000 )
Bounds on an `llm` block, so a typo is a boot refusal rather than an unbounded bill.
const ( // PRQueueQueued: waiting for a slot. PRQueueQueued = "queued" // PRQueueOpened: muster opened it (QueuedPR.PR is its number). PRQueueOpened = "opened" // PRQueueSkipped: muster dropped it (QueuedPR.Note says why). PRQueueSkipped = "skipped" )
The states of a queued create.
const ( // PRLoopSending: one process is announcing it now (or lost its answer): // never claimed by the sweep. PRLoopSending = "sending" // PRLoopPending: HQ was unreachable (an outage muster recorded): the sweep // claims and re-sends it, within its age bound. PRLoopPending = "pending" // PRLoopInLoop: HQ's 200 named a loop item for it. PRLoopInLoop = "in_loop" // PRLoopNoTaker: HQ's 200 named no item (no shepherd takes it). PRLoopNoTaker = "no_taker" // PRLoopClosed: never re-announced — HQ answered 409 officer_shadow (a // shadow officer's pull request is never shepherded), or the pull request // was seen closed or merged. PRLoopClosed = "closed" // PRLoopFailed: never re-announced — HQ refused it with a permanent 4xx (a // decision, not an outage), or it stayed pending past the sweep's age // bound. PRLoopFailed = "failed" )
The states of an announcement.
const ( // StageShadow: push and open pull requests only. Both gated tools refuse. StageShadow = "shadow" // StageMerge: also merge its own pull requests (officer_merge_pr). StageMerge = "merge" // StageRelease: also tag releases (officer_tag_release). StageRelease = "release" )
Ship stages. Each includes what the one before it may do.
const ( // RollbackOff: report and escalate; touch nothing. RollbackOff = "off" // RollbackPR: open the revert pull request, report and escalate. RollbackPR = "pr" // RollbackAuto: open the revert pull request, merge it and tag it through // the same gates, then watch that release too. RollbackAuto = "auto" )
Rollback policies for a release whose rollout fails.
const ( // AppKeyEnvPrefix: the PEM private key of the officer's OWN GitHub App. AppKeyEnvPrefix = "MUSTER_OFFICER_GITHUB_APP_KEY_" // EscalateWebhookEnvPrefix: an https webhook OUTSIDE HQ (a Discord-style // `{"content": …}` endpoint) that a failed rollout escalates to, because the // failing service may be HQ itself. EscalateWebhookEnvPrefix = "MUSTER_OFFICER_ESCALATE_WEBHOOK_" )
Environment-variable prefixes of a shipping officer's secrets, each followed by TokenEnvSuffix of its id, like its HQ token.
const ( DefaultShipBase = "main" DefaultBranchPrefix = "officer/" DefaultNoticePath = "/officers/{id}/notices" DefaultReleasesPerDay = 6 DefaultMinReleaseGap = 30 * time.Minute DefaultLiveReads = 10 DefaultLiveWithin = 20 * time.Minute DefaultHealthyFor = 15 * time.Minute DefaultHealthInterval = 30 * time.Second DefaultRollbackWithin = 60 * time.Minute DefaultHealthVersionKey = "version" )
Defaults for the fields that have one. None widens what the officer may do.
const ( DefaultDocsMaxDiffLines = 300 DefaultDocsMaxFiles = 10 )
Defaults and bounds of a docs_only block. None widens: each is a cap.
const ( // MaxShipRepos is how many repositories `ship.repos` may list. MaxShipRepos = 3 // MaxOpenPRsPerRepo is how many of the officer's own pull requests may be // open in one repository at once. MaxOpenPRsPerRepo = 4 // MaxNewPRsPerDay is how many pull requests the officer may open per UTC // day, across its repositories. MaxNewPRsPerDay = 3 // MaxPRsPerItem is how many pull requests one HQ item may have, in any // state, across the officer's repositories. MaxPRsPerItem = 1 // OrphanBranchAge is how old an officer branch with no pull request must be // before the daily report lists it. OrphanBranchAge = 7 * 24 * time.Hour )
Limits of a draft-stage officer.
const ( SpawnBudgetShort = 10 * time.Minute SpawnBudgetLong = 24 * time.Hour )
The budget's windows and bounds.
const ( ToolTaskList = "officer_task_list" ToolTaskGet = "officer_task_get" )
The task read tools. Offered to a task-reconciler officer only (ToolOffered).
const ( TierRoutine = "routine" TierJudgement = "judgement" )
Instance tiers, as HQ names an item's `tier`.
const CapChats = "chats"
CapChats is the chat routes: an officer's chat messages and its reply.
const ChatCharterReloadLine = "Your charter changed since your last turn here: call " + ToolBrief + " again and follow the new charter before you answer.\n"
ChatCharterReloadLine is added to a lane's turn when the officer's charter version moved since the lane's last turn.
const ChatNoTextReply = "(The officer's turn ended without a text reply.)"
ChatNoTextReply is the reply posted for a lane turn that ended with no text. Any other reply is posted as the lane wrote it: the HQ server caps it.
const ChatReplyCutMarker = "\n\n[reply cut by muster at 64 KiB]"
ChatReplyCutMarker ends a reply cut to MaxChatReplyBytes.
const ChatRequestRateLimitedReply = "(The officer is being rate-limited right now. Ask again later.)"
ChatRequestRateLimitedReply is the reply posted for a chat whose turns keep coming back rate-limited by something other than the accounts' usage limit (a rate_limited without ErrChatUsageLimit: a transient 429).
⚠ IT NAMES NO WAIT. A ccd from before the usage_limit field sends a typed usage limit unmarked, so a weekly limit can reach this reply too; "ask again later" is true of both, "in a few minutes" would not be.
const ChatSessionKeyPrefix = "officer-chat:"
ChatSessionKeyPrefix prefixes every chat lane's muster session key.
const CodeNotInvestigating = "not_investigating"
CodeNotInvestigating is HQ's code on a 403 refusing a read for the item outright: the officer's type does not investigate, or HQ takes no raw read of an item of that tier.
const ConfidenceLow = "low"
ConfidenceLow is the investigation confidence of no conclusion.
const ContractV1 = "officer-backend/v1"
ContractV1 is the contract version this muster speaks.
const CostFromLLMProxy = "muster:llm-proxy"
CostFromLLMProxy is cost_from for a cost muster's LLM proxy metered: the provider-reported cost of every request the item's routine hold made. A hold with a request booked from the proxy's estimate (a response that reported no cost) has no known cost, and sends none.
const DatastoreOfficerType = "datastore"
DatastoreOfficerType is the officer type whose instances file gap tasks.
const DefaultHQTimeout = 15 * time.Second
DefaultHQTimeout bounds one HQ request.
const (
DefaultIdleDraftDays = 2
)
Bounds of a close_oldest_draft block.
const DefaultPoolsInterval = 10 * time.Minute
DefaultPoolsInterval is the pools push's cadence: the usage collector's.
const DefaultRefreshEvery = 15 * time.Second
DefaultRefreshEvery is how often Run re-reads the roster (Config.Refresh) when nothing else asks: what bounds how late another replica's create, pause or delete reaches this one.
const FaultStrikes = 2
FaultStrikes is how many consecutive passes must see a permanent HQ refusal before it is treated as a configuration fault (scale to zero).
const FloodBlockAction = "managed_challenge"
FloodBlockAction is the only action HQ's flood route takes. muster sends it; the tool does not take it as an argument.
const FloodNotConfiguredCode = "flood_actuator_not_configured"
FloodNotConfiguredCode is the flood route's 503 code for an HQ whose Cloudflare credential is unset: a FINAL refusal (a deployment's decision, not an outage), so it is passed back as one, never "retry in a minute".
const GitHubConnector = "github"
GitHubConnector is the connector an officer with a repository reads it through: the GitHub App's virtual connector (githubapp.ConnectorName), named here because this package does not import the App. Besides the connectors the officer declares (Officer.Connectors), it is the only connector an officer instance may request or use (MayRequestConnector).
const HandoffToAuthor = "author"
HandoffToAuthor is the one `handoff.to` value: a shepherd hands a clean round's fixes to the pull request's AUTHORING officer (HQ enqueues its *.pr_fix item).
const HostSpawnMissingToClose = 2
HostSpawnMissingToClose is how many listings in a row must miss a recorded window before it is gone for good: one transient miss closes nothing (the host-dispatch reconciler's hostMissingToEnd, for the same reason).
const ImageRegistriesEnv = "MUSTER_OFFICER_IMAGE_REGISTRIES"
ImageRegistriesEnv is the deployment's allowlist of the image repositories an officer's `image` may name: comma-separated `<registry host>[/<path>]`.
const InstanceNamePrefix = "officer-"
InstanceNamePrefix starts every officer instance's agent name. It is reserved in practice: muster's name generator (agents.BuildUniqueAgentName) draws from an adjective-noun pool that cannot produce it (internal/api's TestTheOfficerNamePrefixCannotBeGenerated), and only the officer runtime passes a fixed name starting with it. A routine instance's `-r<n>` name (Officer.InstanceName) starts with it too, so the same rule reserves it.
const ItemKindChat = "chat"
ItemKindChat is the kind of an officer item that carries a chat turn.
const LLMKeyEnvPrefix = "MUSTER_OFFICER_OPENROUTER_KEY_"
LLMKeyEnvPrefix is the prefix of the variable an officer's own provider key is read from: MUSTER_OFFICER_OPENROUTER_KEY_<NAME>, NAME as for the HQ token (TokenEnvSuffix).
const MaxAskImageBytes = askimage.MaxBytes
MaxAskImageBytes is HQ's bound on one ask image (askimage.MaxBytes).
const (
MaxBackoff = 10 * time.Minute
)
Backoff bounds.
const MaxChatReplyBytes = 64 << 10
MaxChatReplyBytes is the HQ server's cap on an officer reply; muster cuts a longer one to it, ending with ChatReplyCutMarker, rather than have it refused.
const MaxConcurrentPasses = maxConcurrentPasses
MaxConcurrentPasses is maxConcurrentPasses, for what sizes a budget the passes share (the officer fleet-read test in internal/api models its rate-limiter waits on it).
const MaxItemCostUSD = 10000
MaxItemCostUSD is HQ's bound on an item's cost_usd (civ-hq store/officer_cost.go): anything above it is a reporting error HQ refuses.
const MaxItemMinutesCap = 24 * 60
MaxItemMinutesCap bounds tiers.judgement.max_item_minutes: a day.
const MaxLinks = 10
MaxLinks is HQ's bound on a completion's links (civ-hq docs/OFFICERS.md).
const MaxNamespaceLen = 63
MaxNamespaceLen is a Kubernetes namespace name's limit (a DNS label). An instance's agent name becomes its namespace with the deployment's prefix (MUSTER_AGENT_NAMESPACE_PREFIX) in front, so the name may use what the prefix leaves: MaxInstanceNameLen.
const MaxNoticePaths = 50
MaxNoticePaths bounds a notice's path list; the rest are counted in Summary.
const MaxObsQueryBody = 256 << 10
MaxObsQueryBody bounds the arguments object muster sends: HQ's own cap on an officer route's body (civ-hq internal/api MaxOfficerBody, 256 KiB). A larger one is refused before it leaves muster.
const MaxRestartErrorText = 1000
MaxRestartErrorText bounds the error text a RestartStore keeps (migration 0170's CHECK is 2,000 characters).
const MaxRoutineKinds = 32
MaxRoutineKinds bounds routine_kinds.
const MaxSessionsPerDayCap = 100
MaxSessionsPerDayCap bounds tiers.judgement.max_sessions_per_day.
const MaxSlugLen = 54
MaxSlugLen bounds an instance slug: officer_defs' CHECK (0136) holds it too.
const MaxStatusPages = 400
MaxStatusPages bounds the pages StatusesOf reads per status: well past any queue an officer holds, so in practice the list is read to its end. A read that stops at it is reported (StatusRead.Bounded), never taken for the end of the list.
const MaxSummaryChars = 24576
MaxSummaryChars is HQ's bound on a completion summary, in CHARACTERS (civ-hq: 24,576). A shadow officer puts a whole evaluation (≤10,000) or report (≤20,000) there, so the contract's original 4 KB is long gone; HQ's 128 KiB body cap holds even at 4 bytes a character.
const OriginOwner = "owner"
OriginOwner is Item.Origin for an item the officer's owner enqueued.
const OutcomeNeedsJudgement = "needs_judgement"
OutcomeNeedsJudgement hands a ROUTINE item to the judgement pool: HQ promotes it to judgement in place (open again, no holder, the summary kept for the judgement claimer, links refused) and closes nothing. HQ refuses it on a judgement item.
const PRContextNotVisibleCode = "pr_not_visible"
PRContextNotVisibleCode is HQ's 404 code for a PR outside every range.
PRContextRouteUnavailableCode names the refusal of a 404 that is NOT PRContextNotVisibleCode: this HQ has no PR context route.
const PRFixKindSuffix = ".pr_fix"
PRFixKindSuffix ends the kind of every pull-request fix item HQ hands an AUTHORING officer (`<its type>.pr_fix`, subject `<repo>#<pr>`): the fix goes to that pull request's existing branch (officership's fixpush.go).
const PendingTTL = 2 * DefaultHQTimeout
PendingTTL is how long a claim-next's pending entry holds its session: two HQ request timeouts. A claim-next is answered (or has failed) well within one; an entry older than this was left by a server that died mid-claim.
const PublicBodyFirstLine = "Authored from untrusted inputs by an automated agent; review as such"
PublicBodyFirstLine is the first line a draft-stage officer's pull request body must be, exactly, in a repository marked public: the same warning to the reviewer, naming neither the officer nor the item (muster keeps both in its own record of the branch: PublicBranchStore).
const PublicTokenLen = 12
PublicTokenLen is how many letters a public branch's token has (26^12, about 56 bits).
const QueuedCreateDropRule = "You may complete your item (done or no_action) once its create is queued: muster still opens it. muster drops a queued " +
"create only when its item is gone from HQ (cancelled or removed), its branch is gone, its change or text is refused, or GitHub refuses " +
"it for good (such as a branch with no commits ahead of the base); HQ is told."
QueuedCreateDropRule is what a draft officer is told about a create the open limit queued, in its charter (draftShipNote) and in the 202 answer itself (officership's queueCreate): THE one statement of when muster drops a queued create, which the drain (officership.drainOne, with the api package's itemGone) implements. 🔴 Completing the item does NOT drop it.
const ReadBudgetNote = "200 reads per item, ONE count shared by officer_kube_read, officer_obs_raw and officer_obs_query " +
"(every officer_obs_raw call counts, a routine instance's too; a judgement instance's officer_obs_query counts against the item it holds, " +
"and is not counted while it holds none; a routine instance's is never counted); " +
"the 201st read of an item is refused, whichever tool makes it. The count is the item's, not the instance's: " +
"reads a routine instance made of an item before it handed the item on to the judgement pool count toward the same 200. " +
"An officer_obs_raw or officer_obs_query call HQ answers with 429, a 5xx or a 403 not_investigating, or that gets no answer from HQ, " +
"is not counted; HQ's other refusals are"
ReadBudgetNote states the budget, exactly, wherever the instance is told it (the kickoff and each counted tool's description).
const ReadsPerItem = 200
ReadsPerItem is the per-item read budget.
const ReleaseOfficerType = "release"
ReleaseOfficerType is the officer type whose instances evaluate releases.
const RepromptAfter = 5 * time.Minute
RepromptAfter is the least time between two prompts of one instance while it has claimable work and holds no claim.
const RerunMaxPerApproval = 10
RerunMaxPerApproval caps the re-runs one approval asks for: a grant pending for days can collect many blocks (an instance that claims item after item and is refused on each), and a burst of re-runs would wake the whole pool at once against the officer's budget. Ten covers the largest batch measured (five items on one grant) twice over; the rest are logged and left unsettled, and the block sweep sends up to ten more on each later pass.
const RerunWindow = 7 * 24 * time.Hour
RerunWindow is how far back a block is re-run when its grant is approved. Seven days: an operator approves a pending grant within a working week (the grant that motivated this waited about 40 hours over a weekend), and a block older than that is work whose subject has moved on — a newer event re-opens it through its own trigger.
const RolloutOfficerType = "rollout"
RolloutOfficerType is the officer type whose instances attach rollout evidence.
const RuntimeAuto = "auto"
RuntimeAuto is a DB-declared officer's "pick for me" runtime: a pod when this server can run one, else the first of its owner's hosts that qualifies (internal/api resolves it on every roster load, and says why when nothing qualifies). Never a MUSTER_OFFICERS value.
const StageDraft = "draft"
StageDraft: open DRAFT pull requests only (in one to MaxShipRepos repositories). No tool converts, merges or tags; required_checks and review_check are not required.
const StageShepherd = "shepherd"
StageShepherd: push (fast-forward only), comment, update-branch and mark ready, on other officers' pull requests only. No merge, no tag.
const StatusPageLimit = 25
StatusPageLimit is the page size StatusesOf asks for. An item's payload is HQ's, of any size: a page of 100 escalated items measured over muster's 1 MiB answer cap (ErrHQAnswerTooLarge), so a grant's re-run read none of them. A smaller page fits typical items, and a page still over the cap is asked again at half the size (down to one item).
const StatusWaiting = "waiting"
StatusWaiting is the status HQ gives an item with an open ask.
const TaskNotVisibleCode = "task_not_visible"
TaskNotVisibleCode is HQ's 404 code for a task that is absent or private.
const TaskReconcilerOfficerType = "task-reconciler"
TaskReconcilerOfficerType is the officer type whose instances read tasks.
TaskRouteUnavailableCode names the refusal of a 404 that is NOT TaskNotVisibleCode: this HQ has no task route.
const TokenEnvPrefix = "MUSTER_OFFICER_TOKEN_"
TokenEnvPrefix is the prefix of the variable each officer's HQ token is read from: MUSTER_OFFICER_TOKEN_<NAME>, where NAME is TokenEnvSuffix of its id.
const ToolGapTask = "officer_gap_task"
ToolGapTask is a datastore officer's: file one gap task.
const ToolPRContext = "officer_pr_context"
ToolPRContext is the PR context read tool.
const ToolPostgresQuery = "postgres_query"
ToolPostgresQuery is the connector tool that runs read-only SQL against a postgres connector (internal/api connector_tools.go), named here because this package does not import the API.
const ToolRolloutEvidenceAttach = "officer_rollout_evidence_attach"
ToolRolloutEvidenceAttach is a rollout officer's: attach its soak evidence for one tag to HQ, for the person who starts the rollout.
const ToolShepherdMergeAsk = "officer_shepherd_merge_ask"
ToolShepherdMergeAsk is the shepherd's merge-ask tool: HQ's merge ask for a pull request it shepherds, under the item it holds (officership.ShepherdGates.MergeAsk). A shepherd's only; it merges nothing.
const ToolShepherdReady = "officer_shepherd_mark_ready"
ToolShepherdReady is the shepherd's mark-ready tool: draft -> ready for review on a pull request it shepherds (officership.ShepherdGates.MarkReady).
const WebPerformanceOfficerType = "web-performance"
WebPerformanceOfficerType is the officer type whose instances may propose flood blocks.
Variables ¶
var BodySections = []string{"## Root cause", "## Evidence", "## Test", "## Rollback"}
BodySections are the headings a draft-stage pull request body must carry, each as a line of its own.
var BuiltinCapabilities = NewCapabilities(CapTiers, CapInvestigation, CapCost, CapAsks, CapUsage)
BuiltinCapabilities is what the built-in backend (internal/officers/builtin) serves beyond the core verbs. It is defined HERE, beside HQ's, so that what an instance is TOLD (KickoffText, which cannot import the backend) and what it is OFFERED and served (the backend's Capabilities, read through Backends) are one value: builtin.Backend.Capabilities returns exactly this, and a test there pins it.
CapUsage: the usage collector (internal/officers/usage) pushes a builtin instance's Claude usage to its own backend, which books it into officer_llm_usage (builtin.Backend.PutUsage) — without it a builtin officer's model spend was read by nothing and recorded nowhere.
var CaptainLevels = []string{"low", "medium", "high", "severe"}
CaptainLevels are HQ's risk levels.
var ContactTools = []string{ToolContactGet, ToolContactsList, ToolContactNote}
ContactTools are the three contact tools (ToolContactGet …).
DefaultPoolsBackoff is the waits before each retry of a pools push HQ did not take (a 5xx, a timeout, no answer).
var ErrChatLaneBroken = errors.New("officers: the chat's lane cannot take a turn")
ErrChatLaneBroken is a chat turn refused before anything was typed for a reason that will not pass by itself (the runtime could not be resolved, refused muster's credential or the request, or was never reached): a failure, retried only after a backoff.
var ErrChatLaneBusy = errors.New("officers: the chat's lane is mid-turn")
ErrChatLaneBusy is the ErrChatLaneUnavailable that is ccd's 409 `busy` (awaiting_approval included): a turn is running in the lane's CLI. A lane is one chat's, so that is usually the chat's OWN earlier turn — one a restarted muster lost track of, or one that ran past the turn deadline — whose answer the retry delivers once it ends. While the chat has such a typed-but-unanswered turn, a busy streak is bounded by time (chatMaxBusyWait), never by chatMaxLaneRefusals.
ErrChatLaneUnavailable is a chat turn the lane refused before anything was typed (ccd's 409 busy, 503 not_ready or capacity): not a failure — the item waits for a later pass.
var ErrChatRateLimited = errors.New("officers: the officer's Claude account is rate-limited")
ErrChatRateLimited is a chat turn the lane's Claude account was rate-limited on: ccd's typed `rate_limited` — a 429 for a turn that was typed and failed, or a 409 from a pane parked on the CLI's usage-limit menu, before anything was typed (then wrapped with ErrChatLaneUnavailable too). The runner backs off, and at chatRateLimitedAttempts such turns since the chat's last answer answers the member (ChatRateLimitedReplyFor) rather than retry the chat for as long as the limit lasts.
var ErrChatUsageLimit = errors.New("officers: the officer's Claude account is at its usage limit")
ErrChatUsageLimit is the ErrChatRateLimited (and always wrapped with it) that the runtime said is the account's USAGE LIMIT (ccd's `usage_limit`: the CLI's limit text, or its usage-limit menu) — not a transient request rate limit, which the CLI types and codes the same. Only this one is answered with ChatRateLimitedReply ("at their usage limit", with the stated reset); any other rate limit gets ChatRequestRateLimitedReply.
var ErrHQAnswerTooLarge = fmt.Errorf("officers: HQ's answer is over muster's %d-byte cap", maxHQBody)
ErrHQAnswerTooLarge is a 2xx answer over maxHQBody: muster read only the first maxHQBody bytes, so it is refused as a whole (never passed on cut, where it reads as "not JSON"). Final for that request: the caller must ask for less (a smaller page, a narrower filter), not retry.
ErrHQUnavailable is HQ not answering usefully: a transport failure, a timeout, or a 5xx. The wake loop backs off on it and changes nothing; an MCP tool reports it as "HQ is unavailable, try again".
var ErrHostSpawnNotFound = errors.New("officers: no such host spawn")
ErrHostSpawnNotFound: no row of the principal's matches.
var ErrInstanceBusy = errors.New("officers: a turn holds the instance's session")
ErrInstanceBusy is a re-prompt the fleet did not send because a turn holds the instance's session (its session claim is taken). It is not a failure and not a prompt: the loop tries again on its next pass.
var ErrLendRefused = errors.New("officers: only a spawn's owner lends it, and only to a team they operate")
ErrLendRefused: the database refused the lend (0130's lend_target): the row is not the acting person's, or they do not operate the team.
var ErrNotServed = errors.New("officers: this officer's backend does not serve that verb")
ErrNotServed is a verb the officer's backend does not serve: it does not advertise the capability, or does not implement it. A decision (never retried), reported to an instance as a refusal.
var ErrOwnerUnknown = errors.New("officers: an officer's owner names no user")
ErrOwnerUnknown: an officer's owner names no user.
var ErrReadBudget = errors.New("officers: the item's read budget is spent")
ErrReadBudget is a read refused because its item's budget is spent.
var ErrSessionCap = errors.New("officers: judgement session cap reached")
ErrSessionCap is a claim the day's cap refuses; the error's text says so.
var ErrTeamHostOfficerConnectors = errors.New(`officers: a team's "runtime": "host" officer cannot declare connectors: ` +
`a team's connector requests have no one to decide them (team sharing, decision G3); remove connectors, or run it in pods`)
ErrTeamHostOfficerConnectors: a team owns a host officer that declares connectors (operator decision G3).
var ErrUnknownOfficer = errors.New("officers: no such officer")
ErrUnknownOfficer is a lookup of an id no declared officer has.
var HQModelPattern = regexp.MustCompile(`^[A-Za-z0-9._:/-]{1,128}$`)
HQModelPattern is THE model id HQ takes on an officer's routes (a pool's model, a usage bucket's): HQ refuses the whole request over any other.
var ItemStatuses = []string{StatusOpen, StatusClaimed, StatusWaiting, StatusDone, StatusEscalated}
ItemStatuses are the statuses officer_items' schema offers, as HQ names them. HQ decides what it accepts; muster passes the filter through.
var Outcomes = []string{"done", "escalated", "no_action"}
Outcomes the contract accepts from every instance.
var OwnStateTools = []string{ToolMyState, ToolConfirmCard, ToolRefusalRefile, ToolRefusalDrop}
OwnStateTools are the four own-state tools (ToolMyState …).
var RunTick = time.Second
RunTick is how often Run looks for a due officer.
Functions ¶
func AllCapabilities ¶ added in v0.209.0
func AllCapabilities() []string
AllCapabilities is every capability this muster knows, sorted.
func AskFilename ¶ added in v0.144.0
AskFilename is the base name sent to HQ: name with anything but letters, digits, '.', '_' and '-' replaced, at most 100 bytes, ending in an extension of type ct; image-<n> when name gives nothing usable.
func Backoff ¶
Backoff is how long to wait after the failures'th consecutive failed pass: PollInterval doubled per failure, capped at MaxBackoff. A pass that failed reading its fleet (fleetUnread) waits PollInterval instead.
func BodyFirstLine ¶ added in v0.156.0
BodyFirstLine is the first line a draft-stage officer's pull request body must be, exactly — in a repository NOT marked public (PublicBodyFirstLine is a public one's).
func BranchItem ¶ added in v0.156.0
BranchItem is the HQ item a draft-stage officer branch is for: branch must be <prefix><officer slug>/<item>-<slug>. ok false for any other shape.
func CapReason ¶ added in v0.161.0
CapReason is the one-line reason a judgement pool at its cap is not woken: "judgement cap reached (used/limit until HH:MM UTC)", resetting at reset.
func CapResetAt ¶ added in v0.161.0
CapResetAt is when the daily session cap in force at now resets: the next UTC midnight.
func ChatHolder ¶ added in v0.247.0
ChatHolder is the `instance` a chat item is claimed as on instance agent instance: never the instance's own name. HQ refuses a claim, heartbeat, release and complete from any holder but the claim's, so the primary (which acts as its agent name) can never release or complete a chat's claim, and a chat claim never reads, to the wake loop, as the primary's.
func ChatLaneUnavailableReply ¶ added in v0.251.0
ChatLaneUnavailableReply is the reply posted for a chat whose lane refused chatMaxLaneRefusals turns in a row.
func ChatOf ¶ added in v0.247.0
ChatOf is chat item it's chat id and the member seq it was enqueued for: the payload's {chat_id, seq}, or — a payload without chat_id — the id from its subject "chat:<chat_id>" and seq 0. ok is false for an item that is not a chat item or names no chat.
func ChatRateLimitedReply ¶ added in v0.251.0
ChatRateLimitedReply is the reply posted for a chat whose turns keep coming back at the account's usage limit (ErrChatUsageLimit, chatRateLimitedAttempts): the member is told why and, when the CLI stated it, when the limit resets (detail is the failure's text, read for "resets …").
func ChatRateLimitedReplyFor ¶ added in v0.253.0
ChatRateLimitedReplyFor is the reply for a chat that gave up on rate-limited turns (chatRateLimitedAttempts), chosen by err, the last one: a usage limit (ErrChatUsageLimit) says so, with a reset; any other rate limit says only that the officer is being rate-limited, and quotes no reset — a transient limit states none, and must not read as the accounts' limit.
The reset of a usage limit is, in order:
- the pool's earliest (a PoolReset in err, at a non-zero time): when the first account of the officer's pool is back, formatted by ccpool.ResetPhraseAt, never compared as text;
- else the reset the CLI stated in err (ChatRateLimitedReply), as before the pool was read — the fallback whenever the pool named no time or could not be read;
- else none.
func ChatSessionKey ¶ added in v0.247.0
ChatSessionKey is the muster session key of chat chatID's lane: the key ccd names its CLI by (X-Muster-CC-Session), and the chat_sessions row the lane's turns are recorded on.
func ChatTurnText ¶ added in v0.247.0
ChatTurnText is the one user turn a chat lane is sent: the frame line, then each message muster has not given the lane yet, each under who wrote it.
- first: the lane's conversation is new, so it is told which officer and instance it is and to load its charter (officer_brief) before answering;
- retry: the lane already has every member message (its last reply was lost to a restart or a failed post): it is asked to answer again, and no message is re-sent.
func ChatUndeliveredReply ¶ added in v0.247.0
ChatUndeliveredReply is the fallback posted in place of a reply HQ refused for good (chatReplyUndeliverable), naming HQ's refusal.
func CheckOwners ¶ added in v0.225.0
CheckOwners checks every officer's owner, read through kindOf (one call per distinct owner).
func ClampLease ¶
ClampLease is seconds within the contract's bounds; 0 is the default.
func ClaudePricesAsOf ¶ added in v0.233.0
func ClaudePricesAsOf() string
ClaudePricesAsOf is the date of the price list EstimateClaudeUSD reads.
func CleanRepoPath ¶ added in v0.229.0
CleanRepoPath reports whether p is a clean repository-relative path: not empty, no leading or trailing '/', no empty, '.' or '..' segment, no backslash and no control character. git stores no other kind, so anything else is a trick and is refused rather than interpreted.
func CompleteOutcomes ¶ added in v0.159.0
CompleteOutcomes is THE rule for which outcomes officer o's instances may complete an item with (officer_complete's schema and its dispatch both ask it): Outcomes, plus needs_judgement for a routine pool — the only pool whose items HQ takes it for.
func CompleteTakesInvestigation ¶ added in v0.159.0
CompleteTakesInvestigation is THE rule for whether officer o's instances may send officer_complete an `investigation` block: every pool but a routine one. A routine instance that finds an item needs investigating hands it to judgement (OutcomeNeedsJudgement); the investigation is the judgement pool's.
func CountSessions ¶ added in v0.146.0
CountSessions is THE counting rule: of a day's entries, how many sessions they hold at now — every item, every unknown: entry, and every pending entry younger than PendingTTL (a stale or unparseable one holds nothing) — and which of them are items (still work for the pool at the cap).
func CountsRead ¶ added in v0.157.0
CountsRead reports whether a call of tool by an instance of pool o spends its item's read budget: THE rule (see above).
func ErrorSlots ¶
func ErrorSlots() float64
ErrorSlots is muster_officer_error_slots' last published value.
func EstimateClaudeUSD ¶ added in v0.233.0
EstimateClaudeUSD is what input (uncached), output, cache-read and cache-write tokens of model cost at list price, and whether model was priced from its own row (false: the pessimistic row).
func GrantRerunKey ¶ added in v0.245.0
GrantRerunKey is HQ's idempotency key for re-runs caused by approving grant id: one re-run per (item, key) however often it is asked.
func ImageAllowed ¶ added in v0.170.0
ImageAllowed is THE rule for an officer's `image`: nil when ref is a digest-pinned, well-formed reference with a real registry host whose repository is an entry of allow or lies under one. Every refusal names the reason.
func InstanceName ¶
InstanceName is the agent name of instance n (1-based) of officer id: `officer-<slug>-<n>` — an untiered officer's instance, or a tiered one's judgement instance. A routine instance's is Officer.InstanceName.
func ItemTier ¶ added in v0.141.0
ItemTier is the tier item it is worked by: routine when HQ says routine, and judgement otherwise — an HQ without tiers sends none, and a value muster does not know fails toward judgement, as HQ's own default does.
func KickoffText ¶
KickoffText is the first message instance n of officer o is given when the wake loop starts it.
🔴 IT CARRIES NO CHARTER AND NO CREDENTIAL. The charter lives in the officer's backend (HQ, or muster's own database for a builtin officer) and reaches the instance through officer_brief, so the kickoff never holds a second copy that can drift from the backend's versioned one; and an HQ officer's token is spent by muster on the instance's behalf, so it has nothing to put here. Tests assert the token is absent from this text.
🔴 IT IS WRITTEN FROM THE BACKEND'S CAPABILITIES (DeclaredCapabilities), so an instance is never told about a tool its backend does not serve — the same rule (ToolServed) the tool listing, the allow-list and dispatch apply. An HQ officer's text is pinned byte for byte by internal/api's golden.
func KickoffTextWith ¶ added in v0.238.0
func KickoffTextWith(o Officer, n int, g KickoffGrants) string
KickoffTextWith is KickoffText for an officer whose type grants g.
func KubeReadDisabled ¶ added in v0.153.0
KubeReadDisabled is one line per declared cluster whose kube-read is disabled because the deployment set no allowlist for it, for the server to log at startup. An officer is named once, whatever its pools.
func MatchAllowed ¶ added in v0.229.0
MatchAllowed reports whether repository path p matches allowed-path glob pat. The glob syntax is MatchForbidden's, with ONE difference that matters for an allowlist: a pattern with no '/' matches the LAST segment only (the file's own name), never any segment — so `*.md` allows `docs/a.md` and not `notes.md/main.go`. A pattern ending in '/' is a directory: anything under it. A path that is not clean (CleanRepoPath) matches nothing.
func MatchForbidden ¶ added in v0.156.0
MatchForbidden reports whether repository path p matches forbidden-path glob pat:
- `*` is any run of characters but '/', `?` one such character, and `{a,b}` either alternative (no nesting);
- `**` as a whole segment is any number of segments, none included (`**/secrets/**`, `clusters/x/**`);
- a pattern ending in '/' is a directory: anything under it;
- a pattern with no '/' is matched against EVERY segment of p, so `.sops.yaml` and `*.enc.yaml` catch the file in any directory.
A pattern that does not compile matches everything: a forbidden list is a wall, and a broken brick is not a gap (Parse refuses one anyway).
func MaxInstanceNameLen ¶
MaxInstanceNameLen is how long an instance agent name may be under a namespace prefix.
func MayRequestConnector ¶ added in v0.118.0
MayRequestConnector is THE rule for which connectors officer o's instances may request and use: `github`, plus the ones o declares in `connectors`.
func NewPublicBranch ¶ added in v0.237.0
NewPublicBranch mints a public repository's draft branch: <prefix>fix/<slug>-<token>, the token PublicTokenLen letters from crypto/rand. An invalid slug is an error.
func ObsQueryArgs ¶ added in v0.146.0
func ObsQueryArgs(raw []byte) (json.RawMessage, error)
ObsQueryArgs checks the obs query tool's arguments for what muster owns — one JSON object, at most MaxObsQueryBody bytes — and returns them unchanged for HQ.
func ObsRawBody ¶ added in v0.157.0
ObsRawBody is the POST /obs/raw body: the tool's arguments object args (item_id already split off by the caller), each value as sent (re-encoded compactly, never decoded into a struct), plus item_id (HQ's int64) and instance.
func OperatorChatID ¶ added in v0.252.0
OperatorChatID is the chat id of person user's operator chat with owner's officer officer: "operator-<user>-<16 hex>", the hex the first 8 bytes of the SHA-256 of the officer's (owner, id). Its lane's session key is ChatSessionKey(OperatorChatID(…)).
🔴 ONE CHAT PER (OFFICER, PERSON). chat_sessions.session_key is unique across every agent, so a key per person alone collided as soon as the same person chatted with a second officer — of the same owner, or a personal and a team officer of the same id. A team's managers never read each other's.
func OperatorChatUser ¶ added in v0.252.0
OperatorChatUser is the person whose operator chat chatID is; ok false for any other chat id (an HQ chat's included). It does not say WHICH officer's: a caller compares chatID with OperatorChatID for the officer it acts for.
func OverrunSummary ¶ added in v0.155.0
OverrunSummary is the escalation summary of a claim stopped at the cap.
func OwnStateActs ¶ added in v0.252.0
OwnStateActs reports whether tool is one of the own-state tools that ACT (refused outside an operator chat).
func ParseForbiddenList ¶ added in v0.156.0
ParseForbiddenList reads a forbidden_paths_file's content: one glob per line, surrounding space trimmed, blank lines and lines starting with '#' skipped. Any line that is not a valid glob (MatchForbidden) is an error naming its line number: the caller refuses rather than guesses.
func PendingToken ¶ added in v0.146.0
PendingToken is a fresh pending entry for a claim-next started at now.
func ProviderModel ¶ added in v0.141.0
ProviderModel reports whether m is a provider model id (`<vendor>/<model>`, optionally `:variant`): the only kind of model a routine pool may run when its officer declares `llm`, and a kind it may run ONLY then.
func ReadCounted ¶ added in v0.157.0
ReadCounted reports whether an HQ read tool's call that HQ answered with err (nil: a 2xx) spends its item's read: THE rule for which answers count (see above). Only HQ's 2xx and its 4xx other than 429 and a 403 not_investigating do.
func Refusal ¶ added in v0.144.0
Refusal is an HQ 4xx as muster hands it on: HQ's status, and its own {error, code} when its body carries them. ok is false for anything that is not an *HQError.
func ReleaseTagOf ¶ added in v0.221.0
ReleaseTagOf is the git tag of the muster release whose version is version ("0.221.0" -> "v0.221.0"), "" for a build that is not a release ("dev").
func RepromptText ¶
RepromptText is the turn an up, idle instance is given when its officer has claimable work. Like KickoffText it carries no credential.
🔴 A FRESH POOL'S IS THE KICKOFF (Officer.FreshSessionPerItem): its turn starts a NEW conversation (internal/api OfficerTurnContext), which has no "as before" to refer to — it must call officer_brief and load the charter like a first start.
func RoutineAgent ¶ added in v0.141.0
RoutineAgent reports whether name is a ROUTINE-pool instance of o on the LLM proxy (ProxyAgent answering the routine pool).
func SameShepherdSubject ¶ added in v0.170.0
SameShepherdSubject reports whether an HQ item's subject_key names pull request n of repo (the repository compared without case, the number exactly; surrounding space ignored).
func SensitiveMatch ¶ added in v0.110.0
SensitiveMatch reports whether repository path p matches sensitive-path pattern pat:
- pat ending in '/' is a directory: p is anywhere under it;
- pat holding a '/' is matched against the whole path (path.Match: `*` never crosses a '/');
- pat with no '/' is matched against EVERY segment of p, so `*token*` catches `internal/api/api_tokens.go` and `Dockerfile*` a Dockerfile in any directory.
func Serves ¶ added in v0.209.0
Serves is b as the optional interface T when b advertises capability and implements T; ErrNotServed (naming the capability) otherwise.
func ShepherdSubject ¶ added in v0.170.0
ShepherdSubject is the HQ item subject_key a shepherd must hold to act on pull request n of repo: `<owner>/<name>#<n>`, the repository lower-cased.
func Slug ¶
Slug is an officer id as an agent-name fragment: the `:` written as `-` (`release:example-web` -> `release-example-web`). It is an ENV officer's agent slug; a DB-declared officer's is its server-allocated InstanceSlug (Officer.AgentSlug).
func SlugCandidates ¶ added in v0.236.0
SlugCandidates are the instance slugs the create of owner's officer id tries, in order: Slug(id), cut to fit maxLen, then `-` and a short tag DERIVED FROM (owner, id, n) for n = 1…9 (SlugTag). A candidate equal to an env officer's slug, one whose instance agents exist, or one another officer holds (the 0136 unique index refuses it) is passed over by the caller.
🔴 EVERY CANDIDATE CARRIES ITS OWNER. Round 0 found two consequences of the old `scout-main`, `scout-main-2`, … sequence: a slug freed by one owner's delete was the next owner's first candidate (F1: with a backend cached for the old owner, the new one read the old owner's queue), and the suffix a create got told its caller how many OTHER owners had declared the same id (F10). A tag from (owner, id) is the same for one owner's re-create of one id and differs between owners, so a slug never passes from one owner to another, and a collision moves the create to its next tag without the tag saying anything about whose slug was in the way.
func SlugMaxFor ¶ added in v0.236.0
SlugMaxFor is the longest instance slug whose highest instance name (`officer-<slug>-<maxInstances>`) fits a namespace under namespacePrefix.
func SlugTag ¶ added in v0.236.0
SlugTag is candidate n's tag for owner's officer id: slugTagLen base-36 characters of SHA-256 over (owner, id, n). Deterministic, so a test (and a person reading a log) can name the slug a create gets.
func TaskGetID ¶ added in v0.178.0
TaskGetID is the get tool's task id: {task_id} and nothing else, the id an HQ task id.
func TaskListQuery ¶ added in v0.178.0
TaskListQuery turns the list tool's arguments into HQ's query string ("" or "?…"): strictly — see the top of this file.
func TokenEnvSuffix ¶
TokenEnvSuffix is the officer id as an environment-variable suffix: upper-cased, with every non-alphanumeric byte written as '_' (`release:example-web` -> `RELEASE_EXAMPLE_WEB`).
func ToolCapability ¶ added in v0.209.0
ToolCapability is THE map from an officer MCP tool to the backend capability it needs: "" for a core-verb tool or one muster serves without the backend (kube reads; CI logs, though muster reads them, ride the ship capability like every ship tool). known is false for a name this map does not classify — a new tool must be added here deliberately (internal/api's ledger test fails on an unclassified one).
func ToolOffered ¶
ToolOffered is THE rule for which officer tools officer o's instances get: the six queue tools, officer_ask_person and the two obs tools for every officer, and the captain route's tool for a release officer only; officer_obs_raw for either pool of a tiered officer (never an untiered one), officer_kube_read for a judgement pool whose officer declares a readable cluster. internal/api's listing and dispatch both ask it.
func ToolServed ¶ added in v0.209.0
func ToolServed(o Officer, caps Capabilities, tool string) bool
ToolServed is THE rule for whether officer o's instances get tool when o's backend advertises caps: ToolOffered (the officer's shape) AND the backend serving the tool's capability. internal/api's listing, session allow-list and dispatch all ask it. An unclassified tool is never served.
func Unimplemented ¶ added in v0.209.0
Unimplemented is every capability b advertises without implementing the interface that serves it (none: nil): a backend that does is broken, and Unimplemented names it.
func ValidChatID ¶ added in v0.247.0
ValidChatID is a chat id muster will put in a URL path segment, a session key and a log line: 1..128 bytes of letters, digits and "._-".
func ValidHandoffHead ¶ added in v0.210.0
ValidHandoffHead reports whether sha is a hand-off head (40 lower-case hex).
func ValidListFile ¶ added in v0.156.0
ValidListFile reports whether f may name a forbidden_paths_file: a repository-relative file path with no empty, '.' or '..' segment, no trailing '/', and no glob character (it is forbidden itself, by its exact path).
func ValidPublicSlug ¶ added in v0.237.0
ValidPublicSlug reports whether slug may name a public branch: 1..40 lower-case letters in hyphen-separated words, no digit.
func ValidRefSuffix ¶ added in v0.110.0
ValidRefSuffix reports whether s may follow refs/heads/ (or a prefix of it): git's check-ref-format rules, plus no empty component.
Types ¶
type Admission ¶ added in v0.146.0
Admission is AdmitSession's answer: Admitted, the claim may go ahead; Inserted, THIS call added the entry — so only it may release it.
type Ask ¶ added in v0.144.0
type Ask struct {
To string `json:"to"`
Question string `json:"question"`
Options []string `json:"options,omitempty"`
// Multi: the options are checkboxes — the person may pick more than one
// (internal/attention.Ask.Multi, migration 0175). Sent to HQ as the body's
// `multi` only when true; omitted for every ordinary ask.
Multi bool `json:"multi,omitempty"`
Images []string `json:"images,omitempty"`
ContextURL string `json:"context_url,omitempty"`
// DeadlineSeconds is passed through verbatim (absent: HQ's default).
DeadlineSeconds json.RawMessage `json:"deadline_seconds,omitempty"`
}
Ask is POST …/items/{item}/asks's body, less the instance: the tool's arguments as the instance gave them.
type AsksBackend ¶ added in v0.209.0
type AsksBackend interface {
CreateAsk(ctx context.Context, item ItemID, instance string, a Ask) ([]byte, error)
UploadAskImage(ctx context.Context, filename, contentType string, data []byte) (askimage.Record, error)
}
AsksBackend asks a named person about a held item (with images).
type AutoRestart ¶ added in v0.257.0
type AutoRestart struct {
// After is how long an instance is in error before its first restart of
// the UTC day; each later restart that day waits twice the one before.
// 0 is off.
After time.Duration
// MaxPerDay is how many restarts one officer (all its pools) may have
// per UTC day; past it an instance in error is held. 0 is off.
MaxPerDay int
}
AutoRestart is the loop's restart policy (Config.AutoRestart). The zero value is off: an instance in error holds its slot until an operator acts.
func (AutoRestart) Delay ¶ added in v0.257.0
func (a AutoRestart) Delay(prior int) time.Duration
Delay is how long an instance must have been in error before its restart when it was already restarted prior times today: After doubled per prior restart, at most MaxAutoRestartDelay.
func (AutoRestart) On ¶ added in v0.257.0
func (a AutoRestart) On() bool
On reports whether the policy restarts anything.
type AutoRestartEvent ¶ added in v0.257.0
type AutoRestartEvent struct {
// Instance is the instance's label (Officer.InstanceLabel) and Name its
// agent name.
Instance, Name string
Class ErrorClass
// ErrorText is the error recorded for it (InstanceState.ErrorText).
ErrorText string
InError time.Duration
// Restarted: the instance was stopped and started (Attempt of Max).
Restarted bool
Attempt, Max int
// Held: it would be restarted now but is not (HeldWhy): its class is not
// restartable, or the day's cap is spent. Told once per error episode
// (per UTC day: the record is the day's).
Held bool
HeldWhy string
// Recovered: an instance a Held event was told of left error; the
// notice can be withdrawn.
Recovered bool
}
AutoRestartEvent is what Config.AutoRestartNotice is told.
type Backend ¶ added in v0.209.0
type Backend interface {
// Officer is the officer this backend acts for.
Officer() Officer
// Capabilities is what this backend serves beyond the core verbs.
Capabilities() Capabilities
Items(ctx context.Context, q ItemsQuery) (ItemsPage, error)
// AllItems reads up to maxItemPages pages of items in status.
AllItems(ctx context.Context, status string) ([]Item, error)
Brief(ctx context.Context) ([]byte, error)
Claim(ctx context.Context, item ItemID, instance string, leaseSeconds int, tier string) ([]byte, error)
ClaimNext(ctx context.Context, instance string, leaseSeconds int, tier string) ([]byte, error)
Heartbeat(ctx context.Context, item ItemID, instance string, leaseSeconds int) ([]byte, error)
Complete(ctx context.Context, item ItemID, instance string, done Completion) ([]byte, error)
Release(ctx context.Context, item ItemID, instance string) ([]byte, error)
// Enabled is the officer's on/off switch; an unreadable switch is an
// error, never "enabled".
Enabled(ctx context.Context) (bool, error)
// Scrub is s with every credential this backend holds for the officer
// removed (HQ: its token). A backend that holds none returns s.
Scrub(s string) string
}
Backend is the officer-backend contract (officer-backend/v1, docs/design/officers-first-class.md): the CORE verbs that run an officer — its queue, leases, brief and on/off switch — for ONE officer. Every caller in muster (the wake loop, the MCP tools, the ship gates, the transcript, usage and pools pushers) reaches an officer's backend through this interface and the optional ones below, never through a concrete client.
*Client (HQ over HTTPS with the officer's token) is one implementation; a built-in one in muster's own Postgres (internal/officers/builtin, for an officer declared "backend": "builtin") is the other. internal/officers/backendtest is the conformance suite both pass.
Errors are the contract's three kinds, whatever the implementation: a decision is *HQError (status + the backend's {code, …} JSON body: 404 no such item, 409 held / lease_lost / wrong_tier / blocked, 410 gone, 400 a refused argument); a failure the route says to retry is *RetryableError; an outage wraps ErrHQUnavailable. Callers branch on those, never on a message.
Bodies ([]byte) are the backend's JSON, passed to the instance unchanged.
type Backends ¶ added in v0.209.0
type Backends struct {
// contains filtered or unexported fields
}
Backends is every officer's Backend, built once per officer and cached. It is THE way muster reaches an officer's backend: the wake loop (as HQ), the MCP tools, the ship gates and the transcript, usage and pools pushers all go through Backend(o).
🔴 CACHED BY THE OFFICER'S WHOLE IDENTITY — (owner, id, key) — NEVER BY ITS KEY ALONE. A backend holds the officer it was built from, and the built-in one runs every statement AS THAT OFFICER'S OWNER. A DB-declared officer's key is its instance slug, and a deleted officer's slug is not the cache's to know about: Forget on the roster swap cannot win against a pass that read the roster BEFORE the swap and calls Backend with the old officer after it (round 0's F1, reproduced by that interleaving). Keyed by slug alone, that late call re-cached the old owner's backend, and another owner's officer given the same slug then read the first owner's queue. Keyed by identity, a late call can only re-cache a backend for ITS OWN officer, and every get checks the entry it found was built for the officer asked about (TestABackendCachedForOneOwnerIsNeverServedToAnother).
func NewBackends ¶ added in v0.209.0
NewBackends returns the backends built by build. build nil talks to each officer's own HQ with its own token (NewClient(o, nil)).
func (*Backends) Backend ¶ added in v0.209.0
Backend returns the cached backend for o, keyed on o's identity (owner, id, key): two owners' DB-declared officers may share an id, and — one deleted, the other created — even a slug, never an identity. An entry whose backend says it acts for another officer (a builder that ignored its argument) is rebuilt, never served.
func (*Backends) Complete ¶ added in v0.209.0
func (h *Backends) Complete(ctx context.Context, o Officer, item ItemID, instance string, done Completion) error
Complete implements HQ.
func (*Backends) Forget ¶ added in v0.236.0
Forget drops every cached backend of an officer keyed key (whoever owns it), so the next Backend builds one from the officer as it is now: a DB-declared officer changed or deleted through the admin API (its backend holds the Officer it was built from).
func (*Backends) Heartbeat ¶ added in v0.209.0
func (h *Backends) Heartbeat(ctx context.Context, o Officer, item ItemID, instance string, leaseSeconds int) error
Heartbeat implements HQ.
func (*Backends) RaisedCapToday ¶ added in v0.251.0
RaisedCapToday is o's raised cap for now's UTC day through its backend; 0 when the backend has none or raises nothing.
func (*Backends) Retain ¶ added in v0.236.0
Retain drops every cached backend whose officer is not in live, so an entry a late call re-cached for an officer that is gone does not outlive the next roster load.
func (*Backends) SpentToday ¶ added in v0.242.0
func (h *Backends) SpentToday(ctx context.Context, o Officer, now time.Time) (spent float64, served bool, err error)
SpentToday is o's spend on now's UTC day through its backend; served false when the backend has no BudgetBackend.
func (*Backends) SwitchedOff ¶ added in v0.210.0
SwitchedOff reports whether o's backend is SwitchGated and switched off. A backend that is not SwitchGated is never off (no request is made); an unreadable switch is an error, never "on".
type Budget ¶ added in v0.242.0
type Budget struct {
// DailyUSD is the spend cap per UTC day; 0 is none.
DailyUSD float64
// RoutineKinds is the item kinds batched into the daily routine wake,
// sorted and distinct; empty batches nothing.
RoutineKinds []string
// WakeAt is the routine wake's time of day, from UTC midnight. Set exactly
// when RoutineKinds is.
WakeAt time.Duration
}
Budget is an officer's `daily_budget_usd`, `routine_kinds` and `routine_wake_at`. The zero value caps nothing and batches nothing.
type BudgetAlert ¶ added in v0.242.0
type BudgetAlert struct {
// Unreadable: not "the budget is reached" but "the spend could not be
// read" — the cap's work is held back (fail closed) until it can be;
// Spent and ResetAt are then zero. Told once per UTC day, apart from the
// reached notice.
Unreadable bool
// Spent and Budget are the day's spend as read and the cap, in USD.
Spent, Budget float64
// Waiting is the items held back by the cap when it was reached.
Waiting int
// ResetAt is when the cap resets: the next UTC midnight.
ResetAt time.Time
}
BudgetAlert is the once-per-UTC-day notice that an officer reached its daily budget (Config.BudgetAlert).
type BudgetBackend ¶ added in v0.242.0
BudgetBackend is a backend that can say what its officer has spent on now's UTC day (builtin.Backend). A backend without it has no budget.
type CILogs ¶ added in v0.125.0
type CILogs struct {
// Namespace is the one Kubernetes namespace the PipelineRuns live in.
Namespace string
// Pipeline is the PipelineRuns' `tekton.dev/pipeline` label value.
Pipeline string
// CommitLabel is the PipelineRun label whose value is the head sha.
CommitLabel string
// PRParam is the PipelineRun param whose value is the pull request number.
PRParam string
// ServiceAccount is the dedicated read-only ServiceAccount, in muster's
// own namespace, whose token muster mints (TokenRequest, 600 s) for each
// call and reads the cluster with.
ServiceAccount string
// MaxBytes caps the excerpt text one call returns.
MaxBytes int
}
CILogs is an officer's CI-log source, parsed from its `ci_logs` block.
type CapHold ¶ added in v0.155.0
type CapHold struct {
Item ItemID
// N is the holder's instance number, withheld from the pool.
N int
// Refusal is HQ's refusal, as muster got it, when the episode began.
Refusal string
// Waiting is the pool's claimable items when the episode began.
Waiting int
// Ended: the episode is over (the escalation landed, HQ answered 409, or
// the item is no longer held over its cap).
Ended bool
}
CapHold is one episode of a refused wall-time cap escalation (Config. CapHold): HQ refuses to take capped item Item, so muster keeps it held as its stopped holder and never starts that instance number (N) again until the escalation lands. The pool is withheld that instance meanwhile; at max_instances 1, the whole pool.
type Capabilities ¶ added in v0.209.0
type Capabilities struct {
Contract string
// Verbs are the capability names, sorted.
Verbs []string
}
Capabilities is what a backend serves beyond the core verbs.
func DeclaredCapabilities ¶ added in v0.210.0
func DeclaredCapabilities(o Officer) Capabilities
DeclaredCapabilities is what officer o's DECLARED backend serves: BuiltinCapabilities for a builtin officer, HQ's (every capability) for any other. THE rule for the kickoff, which is written before any backend is built; the tool listing, allow-list and dispatch read the built backend's own Capabilities, which equal it.
func NewCapabilities ¶ added in v0.209.0
func NewCapabilities(verbs ...string) Capabilities
NewCapabilities is the v1 capabilities naming verbs (sorted, deduplicated).
func (Capabilities) Has ¶ added in v0.209.0
func (c Capabilities) Has(v string) bool
Has reports whether c advertises capability v.
type CaptainBackend ¶ added in v0.209.0
type CaptainBackend interface {
ReleaseCaptain(ctx context.Context, instance string, p CaptainPost) ([]byte, error)
}
CaptainBackend takes a release officer's evaluation (extension x-captain).
type CaptainEvaluation ¶
type CaptainEvaluation struct {
Level string `json:"level"`
Summary string `json:"summary"`
Monitors []CaptainMonitor `json:"monitors,omitempty"`
}
CaptainEvaluation is the captain's risk evaluation of a release.
type CaptainMonitor ¶
CaptainMonitor is one thing to watch after a release.
type CaptainPost ¶
type CaptainPost struct {
Service string `json:"service"`
Tag string `json:"tag"`
Evaluation *CaptainEvaluation `json:"evaluation,omitempty"`
Report *string `json:"report,omitempty"`
}
CaptainPost is what the release officer posts: the release, and an evaluation and/or a post-release report.
func ParseCaptainPost ¶
func ParseCaptainPost(raw []byte) (CaptainPost, error)
ParseCaptainPost decodes and validates the tool's arguments. Unknown fields are refused at every level — release_id, an agent-sent instance, the inner evaluation sent as the whole body — as HQ would refuse them, but before HQ.
type CharterGated ¶ added in v0.241.0
type CharterGated interface {
// BriefFor is Brief for instance, recording the charter_version answered.
BriefFor(ctx context.Context, instance string) ([]byte, error)
// CharterCurrent is nil when instance was last briefed with the current
// charter_version, and a 409 charter_changed *HQError when it was not
// (or never was).
CharterCurrent(ctx context.Context, instance string) error
}
CharterGated is a backend that keeps which charter_version each instance was last briefed with, so muster can hold an instance to its type's CURRENT charter: an instance is one long conversation resumed across scale-to-zero, and the charter reaches it only through officer_brief. internal/api answers officer_brief with BriefFor, and refuses officer_claim (by id and claim-next) and officer_complete with CharterCurrent's error until the instance is briefed again. It is not a capability (Serves): it adds no verb, only a precondition on core ones. The built-in backend implements it; HQ's client does not — HQ holds its charters, and officer-backend/v1 gives muster no read of the current charter_version short of a whole brief.
type ChatLanes ¶ added in v0.247.0
type ChatLanes interface {
// Home is the instance number chatID's lane lives on (its session row's
// agent), 0 when it has none yet — a number past the pool's slots too
// (the ceiling lowered since). A lane's conversation is on its
// instance's volume, so a chat stays there: a stopped home is started
// for it, and it moves (Rehome) only when its home is in error, past the
// ceiling, holds a capped claim or is not up within chatHomeUpWithin
// (rehomeWhy).
Home(ctx context.Context, o Officer, chatID string) (int, error)
// Open finds or makes chatID's lane session on instance n and answers its
// marks.
Open(ctx context.Context, o Officer, n int, chatID string) (ChatMarks, error)
// Mark persists the marks of chatID's lane on instance n.
Mark(ctx context.Context, o Officer, n int, chatID string, m ChatMarks) error
// Supports reports whether instance n's runtime names a chat session's
// MCP calls (its ccd advertises it): a chat runs on no other.
Supports(ctx context.Context, o Officer, n int) (bool, error)
// Turn sends text as one user turn to chatID's lane on instance n and
// answers the lane's final assistant text. ErrChatLaneUnavailable (wrapped)
// when the lane refused it before anything was typed.
Turn(ctx context.Context, o Officer, n int, chatID, text string) (string, error)
// Rehome sets aside chatID's lane session on instance from (in error,
// past the chat ceiling, holding a capped claim or not up within
// chatHomeUpWithin: rehomeWhy), so its next Open on another instance
// makes a new session there: one with no marks, which starts after the
// officer's last reply. Its history stays readable where it was. Nothing
// to set aside is no error.
Rehome(ctx context.Context, o Officer, chatID string, from int) error
}
ChatLanes is how the runner reaches the chat lanes of an officer's instances: internal/api implements it over the agents store and the agent gateway.
type ChatMarks ¶ added in v0.247.0
type ChatMarks struct {
// Seen is the highest chat seq the lane knows: the last member turn sent
// to it, or its own reply once posted.
Seen int64
// Answered is the seq of the lane's last reply HQ took; Seen > Answered
// is a turn whose reply never reached HQ.
Answered int64
// Charter is the officer's charter version as the lane last loaded it
// ("" before its first turn): a different one on HQ's brief adds the
// reload line to the lane's next turn.
Charter string
}
ChatMarks is what a chat's lane has been given, persisted with its session row so a restart of muster, or an evicted lane, neither re-sends a message nor skips one.
type ChatMessage ¶ added in v0.247.0
type ChatMessage struct {
Seq int64 `json:"seq"`
// Role is "member", "officer" or "system".
Role string `json:"role"`
// AuthorLogin and AuthorName are who typed a member turn.
AuthorLogin string `json:"author_login"`
AuthorName string `json:"author_name"`
Text string `json:"text"`
}
ChatMessage is one message of a chat as HQ answers it.
type ChatOutcome ¶ added in v0.247.0
type ChatOutcome string
ChatOutcome is how one chat turn ended (Run), for logs and tests.
const ( ChatReplied ChatOutcome = "replied" ChatNotClaimed ChatOutcome = "not_claimed" ChatLaneBusy ChatOutcome = "lane_unavailable" ChatTurnFailed ChatOutcome = "turn_failed" ChatReplyFailed ChatOutcome = "reply_failed" // ChatReplyDropped: HQ refused the reply for good (409 chat_closed or // stale_turn): the turn is dropped, never retried. ChatReplyDropped ChatOutcome = "reply_dropped" // ChatLaneBroken: the lane refused the turn for a reason that does not // pass (ErrChatLaneBroken): released, and the chat backs off. ChatLaneBroken ChatOutcome = "lane_broken" // ChatUnsupported: the instance's runtime does not say it names a chat // session's MCP calls (ChatLanes.Supports): nothing claimed. ChatUnsupported ChatOutcome = "unsupported" // ChatRateLimited: the lane's Claude account is rate-limited // (ErrChatRateLimited): released, and the chat backs off. ChatRateLimited ChatOutcome = "rate_limited" // ChatGaveUp: the chat could not be answered within its bound // (chatRateLimitedAttempts, chatMaxLaneRefusals), so the member was // answered with why (ChatRateLimitedReply, ChatRequestRateLimitedReply, ChatLaneUnavailableReply) and // HQ completed the item. ChatGaveUp ChatOutcome = "gave_up" ChatNothingNew ChatOutcome = "nothing_new" ChatReadFailed ChatOutcome = "read_failed" ChatNotServed ChatOutcome = "not_served" )
The outcomes of Run.
type ChatPage ¶ added in v0.247.0
type ChatPage struct {
Name string
Messages []ChatMessage
// More: HQ left later messages out of this page; read again after the
// last one's seq.
More bool
}
ChatPage is a chat's messages after a seq, and the chat's name when HQ sends it ("" when not).
type ChatPlan ¶ added in v0.249.0
type ChatPlan struct {
// Need is how many more instances the unplaced chats need beyond Homes:
// the unplaced chats no up instance has a free lane for, less the lanes
// Homes leave free once up, ChatSessions to an instance, rounded up. 0
// while a lane is free.
Need int
// Homes is the stopped instances to start for the chats homed on them,
// whatever Need says: a chat whose home is stopped (not in error, within
// the ceiling, no capped claim) waits for it, because its conversation
// is on that instance's volume. In the order the chats came.
Homes []int
// Waiting is how many pending chats have no free lane now.
Waiting int
// Unplaced is how many pending chats have no home to wait for (none yet,
// or one to re-home from): each goes to an up instance with a free lane,
// or waits for one Homes or Need starts.
Unplaced int
// Busy is the chat turns running on each instance, by number.
Busy map[int]int
// PendingOn is the pending chats whose home is up, by its number.
PendingOn map[int]int
// ActiveAt is when each up instance was last seen active (a chat turn
// started or ended on it, a live claim of its own or its chat holder's,
// or first seen up by this process), by number.
ActiveAt map[int]time.Time
}
ChatPlan is what pool o's chats need of its instances at one pass (ChatRunner.Want; Observation.ChatPlan). Decide reads it, purely.
type ChatRunner ¶ added in v0.247.0
type ChatRunner struct {
// contains filtered or unexported fields
}
ChatRunner runs officers' chat turns (the package comment above). One per muster-server.
func NewChatRunner ¶ added in v0.247.0
func NewChatRunner(cfg ChatRunnerConfig) (*ChatRunner, error)
NewChatRunner returns a runner over cfg.
func (*ChatRunner) Dispatch ¶ added in v0.247.0
func (r *ChatRunner) Dispatch(ctx context.Context, o Officer, obs Observation, now time.Time)
Dispatch starts a turn for every pending chat of pool o that this process is not already running, on its home instance — or, for a chat with no home yet or one re-homed (rehomeWhy), the up instance running the fewest chats (lowest number first) — when that instance is up, not in error, and has a free lane (o.ChatSessions()). A chat whose instance has no free lane, or whose home is stopped (Want has it started), is left UNCLAIMED for a later pass. It returns at once; each turn runs on its own goroutine.
func (*ChatRunner) On ¶ added in v0.247.0
func (r *ChatRunner) On(o Officer) bool
On reports whether muster runs officer o's chats (Observation.Chats): a runner is wired and o's backend serves CapChats — for every pool of o, the routine pool too (it runs none, but must not take a chat item for queue work either). nil: off.
func (*ChatRunner) Run ¶ added in v0.247.0
func (r *ChatRunner) Run(ctx context.Context, o Officer, n int, it Item) ChatOutcome
Run is one chat turn of item it on instance n of pool o, start to end (claim, read, turn, reply), synchronously. Dispatch runs it on a goroutine; tests call it directly.
func (*ChatRunner) Wait ¶ added in v0.247.0
func (r *ChatRunner) Wait()
Wait blocks until every turn this runner started has ended.
func (*ChatRunner) Want ¶ added in v0.247.0
func (r *ChatRunner) Want(ctx context.Context, o Officer, obs Observation, now time.Time) (ChatPlan, map[ItemID]bool)
Want is what pool o's chats need of its instances at now (Observation.ChatPlan), and the pending chats it cannot serve now (Observation.ChatHeldBack), which keep nothing up: every chat of a pool that runs none here (cannotRun), a chat whose home cannot be read, and a chat waiting out a backoff. Zero for a pool that runs no chats.
- A pending chat whose home is up (up, not in error, within the chat ceiling) counts against its home's lanes and waits for one there: its conversation is on that instance's volume.
- 🔴 A pending chat whose home is STOPPED — not in error, within the chat ceiling, holding no capped claim (rehomeWhy "") — waits for it: its home is in Homes, which Decide starts, and the chat continues its same session there once it is up. It is never moved for a stop that comes up within chatHomeUpWithin.
- Every other pending chat — no home yet, or a home in error, past chat_max_instances, holding a capped claim or not up within chatHomeUpWithin — is UNPLACED: Dispatch puts it on an up instance with a free lane (re-homing it when it had a home).
- The unplaced chats no free lane takes, less the lanes Homes leave free, need ceil(left / chat_sessions) more instances (Need). Decide starts them, within chat_max_instances.
It also records when each instance was last active (ChatRunner.active) and answers it as ActiveAt, with the turns running on each (Busy) and the pending chats homed on each up instance (PendingOn): Decide's chat-idle stop reads them.
type ChatRunnerConfig ¶ added in v0.247.0
type ChatRunnerConfig struct {
Lanes ChatLanes
// Backend is each officer's backend (Backends.Backend).
Backend func(Officer) Backend
Logger *log.Logger
// Context bounds every turn; nil is context.Background().
Context context.Context
// HeartbeatEvery and ReplyRetries replace the defaults (tests).
HeartbeatEvery time.Duration
ReplyRetries []time.Duration
// Now is the clock a chat's backoff is read on; nil is time.Now.
Now func() time.Time
}
ChatRunnerConfig is NewChatRunner's input.
type ChatsBackend ¶ added in v0.247.0
type ChatsBackend interface {
// ChatMessages is chat's messages with seq > after, ascending.
ChatMessages(ctx context.Context, chat string, after int64) (ChatPage, error)
// ChatReply posts text as the officer's reply to member seq inReplyTo and
// answers the reply's seq. Idempotent on inReplyTo (HQ answers the seq of
// the reply it already holds).
ChatReply(ctx context.Context, chat, text string, inReplyTo int64) (int64, error)
}
ChatsBackend is the chat routes.
type ClaudePrice ¶ added in v0.233.0
type ClaudePrice struct {
Input, Output, CacheRead, CacheWrite float64
}
ClaudePrice is one model's price, USD per million tokens.
func ClaudePriceOf ¶ added in v0.233.0
func ClaudePriceOf(model string) (ClaudePrice, bool)
ClaudePriceOf is model's row and whether the table knows it; an unknown model (or "") answers the pessimistic row and false.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client talks to one officer's HQ with that officer's token.
🔴 IT IS THE ONLY CODE THAT READS Officer.Token(). The token goes in the Authorization header of requests to the officer's own HQ base URL, and nowhere else: not in an error, not in a log line (HQError carries HQ's body, never the request). (Scrub reads it too, only to REMOVE it from text.)
func NewClient ¶
NewClient returns a client for o. hc nil uses a client with DefaultHQTimeout.
⚠ REDIRECTS ARE NOT FOLLOWED. Go's client re-sends the Authorization header to a same-host redirect, and a misconfigured proxy answering 30x would otherwise decide where the officer token goes next.
func (*Client) AttachRolloutEvidence ¶ added in v0.251.0
func (c *Client) AttachRolloutEvidence(ctx context.Context, instance string, e RolloutEvidence) ([]byte, error)
AttachRolloutEvidence is POST …/items/{item}/rollout-evidence, HQ's JSON passed through (its 201 {evidence}); every refusal is a 4xx.
func (*Client) Capabilities ¶ added in v0.209.0
func (c *Client) Capabilities() Capabilities
Capabilities implements Backend: HQ advertises everything (hqCapabilities).
func (*Client) ChatMessages ¶ added in v0.247.0
ChatMessages is GET /officers/{id}/chats/{chat}/messages?after=<seq>, answered {chat: {name, …}, messages: [{seq, role, author_login, author_name, text, in_reply_to?, at}], more, state}; muster reads the messages' seq, role, author_login, author_name and text, the chat's name and more.
func (*Client) ChatReply ¶ added in v0.247.0
ChatReply is POST /officers/{id}/chats/{chat}/reply {text, in_reply_to}, answered {seq}.
func (*Client) Claim ¶
func (c *Client) Claim(ctx context.Context, item ItemID, instance string, leaseSeconds int, tier string) ([]byte, error)
Claim is POST …/items/{item}/claim. tier, when set, is sent as the claim's `tier` (HQ then takes only an item of that tier: 409 wrong_tier otherwise); "" sends no tier key at all — an untiered officer's claim, as before tiers.
func (*Client) ClaimNext ¶ added in v0.143.0
func (c *Client) ClaimNext(ctx context.Context, instance string, leaseSeconds int, tier string) ([]byte, error)
ClaimNext is POST /officers/{id}/claim-next: HQ claims the next item in its queue order (priority, then due, then age; never a blocked one) for instance. tier, when set, is sent as the claim's `tier` (HQ then takes only an item of that tier); "" sends no tier key. HQ answers {item, lease_expires_at}, item null when nothing is claimable. An HQ from before claim-next answers 404 (*HQError): the caller falls back to listing and claiming by id.
func (*Client) Complete ¶
func (c *Client) Complete(ctx context.Context, item ItemID, instance string, done Completion) ([]byte, error)
Complete is POST …/items/{item}/complete. A done.Cost is sent as HQ's cost_usd + cost_from; nil sends neither (an HQ from before item cost refuses the fields: the caller retries without them, the package-level CompleteDroppingCost).
func (*Client) CreateAsk ¶ added in v0.144.0
func (c *Client) CreateAsk(ctx context.Context, item ItemID, instance string, a Ask) ([]byte, error)
CreateAsk is POST …/items/{item}/asks, HQ's JSON passed through.
func (*Client) CreateTaskAsk ¶ added in v0.186.0
CreateTaskAsk is POST …/items/{item}/task-asks, HQ's JSON passed through.
func (*Client) Do ¶
Do sends one request to path under the officer's HQ base (path starts with '/'), with body JSON-encoded when non-nil, and returns HQ's body on a 2xx. A 4xx is *HQError; a transport failure, a 3xx or a 5xx wraps ErrHQUnavailable.
func (*Client) Enabled ¶ added in v0.110.0
Enabled reads GET /officers/{id} and reports HQ's `enabled` for the officer. A body without a boolean `enabled` is an error, never "enabled": a shipping gate that cannot read the switch fails closed.
func (*Client) FileGapTask ¶ added in v0.203.0
FileGapTask is POST …/items/{item}/gap-tasks, HQ's JSON passed through.
func (*Client) Heartbeat ¶
func (c *Client) Heartbeat(ctx context.Context, item ItemID, instance string, leaseSeconds int) ([]byte, error)
Heartbeat is POST …/items/{item}/heartbeat.
func (*Client) Items ¶
Items reads one page of the officer's items.
The body is HQ's `{"items":[…],"next":…}`.
func (*Client) MergeAsk ¶ added in v0.210.0
MergeAsk POSTs body (already validated and encoded JSON) to /officers/{id}/items/{item}/merge-asks with the officer's own token and returns HQ's 201 body. A 4xx is *HQError (HQ's body kept verbatim); HQ's 502 github_unavailable is *RetryableError; any other failure wraps ErrHQUnavailable.
func (*Client) ObsQueries ¶ added in v0.146.0
ObsQueries is GET /officers/{id}/obs/queries with the officer token.
func (*Client) ObsQuery ¶ added in v0.146.0
ObsQuery is POST /officers/{id}/obs/query with the officer token: args, byte for byte (ObsQueryArgs) — never re-encoded.
func (*Client) ObsRaw ¶ added in v0.157.0
ObsRaw is POST /officers/{id}/obs/raw with the officer token: body (ObsRawBody) as given. The answer is HQ's, unchanged.
func (*Client) PRContext ¶ added in v0.190.0
PRContext is GET /officers/{id}/prs/{pr}/context?item={item} with the officer token, HQ's JSON passed through.
func (*Client) PROpened ¶ added in v0.210.0
PROpened POSTs p to /officers/{id}/pr-opened with the officer's own token. A 4xx (409 officer_shadow / officer_disabled / pr_opened_ambiguous, 400, 403, 404) is *HQError; an outage wraps ErrHQUnavailable. It is called by muster itself, never by an instance (no tool reaches it).
func (*Client) PostNotice ¶ added in v0.110.0
PostNotice POSTs n to path (under hq_url; ship.NoticeURLPath). Any failure — a 4xx, a 5xx, no answer — is an error: the caller refuses the merge.
func (*Client) PostTranscript ¶ added in v0.127.0
func (c *Client) PostTranscript(ctx context.Context, item ItemID, instance string, events []TranscriptEvent) (TranscriptAck, error)
PostTranscript is POST …/items/{item}/transcript.
func (*Client) ProposeFloodBlock ¶ added in v0.186.0
func (c *Client) ProposeFloodBlock(ctx context.Context, instance string, p FloodBlockProposal) ([]byte, error)
ProposeFloodBlock is POST …/items/{item}/flood-blocks, HQ's JSON passed through; a 503 flood_actuator_not_configured is an *HQError (final).
func (*Client) PutPools ¶ added in v0.198.0
func (c *Client) PutPools(ctx context.Context, r PoolsReport) error
PutPools is PUT /officers/{id}/pools.
func (*Client) PutUsage ¶ added in v0.194.0
func (c *Client) PutUsage(ctx context.Context, r UsageReport) error
PutUsage is PUT /officers/{id}/usage.
func (*Client) ReleaseCaptain ¶
func (c *Client) ReleaseCaptain(ctx context.Context, instance string, p CaptainPost) ([]byte, error)
ReleaseCaptain is POST /releases/captain with the officer token: p, with instance set to the calling instance (HQ records officer + instance).
func (*Client) RerunItem ¶ added in v0.245.0
func (c *Client) RerunItem(ctx context.Context, item ItemID, r RerunRequest) (RerunAnswer, error)
RerunItem is POST /officers/{id}/items/{item_id}/rerun with the officer token. An HQ older than the route answers 404, as for an item it does not have: the caller logs it and goes on (*HQError, status 404).
func (*Client) Scrub ¶ added in v0.127.0
Scrub is s with every occurrence of the officer's own token replaced — and every word a cap cut short ("…" right after it) that ends in the token's first 4 or more bytes. It is how text built from an instance's session (which could echo anything) is cleared of the one credential this client holds, without the token leaving the client: a shape-based secret filter cannot know an opaque token's shape. (officership.RedactCutTail is the same cut rule for the token SHAPES; it cannot be given this token.)
func (*Client) Shadow ¶ added in v0.210.0
Shadow reads HQ's officer row (GET /officers/{id}) for its `shadow`: true when HQ runs the officer in shadow. A row without a boolean `shadow` is an error, and every caller treats an error as shadow (fail closed).
func (*Client) TaskGet ¶ added in v0.178.0
TaskGet is GET /officers/{id}/tasks/{task_id} with the officer token; id must be TaskGetID's (checked again here: it goes into the path).
type CloseOldestDraft ¶ added in v0.257.0
type CloseOldestDraft struct {
// IdleDays is how many whole days without activity the oldest draft must
// have before it is closed.
IdleDays int
}
CloseOldestDraft is a draft officer's cap-triggered close, enabled.
func (*CloseOldestDraft) After ¶ added in v0.257.0
func (c *CloseOldestDraft) After() time.Duration
After is the idle time at or past which the oldest draft is closed.
type Completion ¶
type Completion struct {
Outcome string `json:"outcome"`
Summary string `json:"summary"`
Links []string `json:"links,omitempty"`
// Investigation is HQ's `investigation` block, sent only when set (an HQ
// from before the block refuses the field, even as null).
Investigation *Investigation `json:"investigation,omitempty"`
// InvestigationJSON is an instance's `investigation` argument, sent to HQ
// AS SENT when Investigation is nil: HQ's decoder is the one schema for
// it, so it is never decoded into Investigation (whose omitempty lists
// would reshape it). Empty or JSON null sends none.
InvestigationJSON json.RawMessage `json:"-"`
// AuthorsJSON, AttributedPRsJSON, AttributionJSON and TicketsJSON are an
// instance's `authors`, `attributed_prs`, `attribution` and `tickets`
// arguments (civ-hq docs/OFFICERS.md §5i author mail, §5b "Attributed
// PRs", and the release-ticket kind's links), each sent to HQ AS SENT —
// HQ's decoder is the one schema for them. Empty (the instance sent no
// such key) sends no key: an HQ that predates a field refuses it, even as
// null. Anything else the instance sent — null and [] included — is
// forwarded unchanged, for HQ to judge.
AuthorsJSON json.RawMessage `json:"-"`
AttributedPRsJSON json.RawMessage `json:"-"`
AttributionJSON json.RawMessage `json:"-"`
TicketsJSON json.RawMessage `json:"-"`
// AskJSON is an instance's `ask` argument ({kind, ref}: the single thing
// an escalation asks a person to do), sent to HQ AS SENT under the same
// rules: HQ owns the kinds and validates both, and empty sends no key.
AskJSON json.RawMessage `json:"-"`
// Cost is what working the item cost, sent as HQ's cost_usd + cost_from
// (civ-hq docs/OFFICERS.md "Item cost") only when set: nil is an unknown
// cost, and sends neither field.
Cost *ItemCost `json:"-"`
// Handoff is HQ's `handoff` (the review loop's next step, e.g. the next
// audit round of a pull request at HeadSHA). nil: not sent.
Handoff *Handoff `json:"-"`
}
Completion is POST …/items/{item}/complete's body, less the instance.
type Config ¶
type Config struct {
Registry *Registry
HQ HQ
Fleet Fleet
Logger *log.Logger
// Now is the clock; nil is time.Now.
Now func() time.Time
// Observed, when set, is told every pass's claimed items for o, read no
// earlier than at (the transcript forwarder's Sync). It runs only after
// a SUCCESSFUL read — a pass that saw nothing tells it nothing, so an HQ
// outage never reads as "no item is held". It must not block.
Observed func(o Officer, claimed []Item, at time.Time)
// Judgement is the judgement-session ledger officer_claim keeps
// (sessions.go): a judgement pool whose day's cap is spent is not woken
// for new work; a ledger that cannot be read leaves that pool as capped
// for the pass (logged) and the other pool unaffected. nil caps nothing.
Judgement *JudgementLedger
// CapHold, when set, is told once when an episode of a refused cap
// escalation begins (a capped item HQ will not take, whose instance
// number is withheld from its pool) and once when it ends (h.Ended), with
// o the item's pool. It is how a withheld pool reaches a human: nothing
// else says the judgement pool is waiting. Called outside the loop's
// lock, from the pass; it must not block. A restarted muster begins a
// new episode for a refusal still in force.
CapHold func(o Officer, h CapHold)
// BudgetAlert, when set, is told once per UTC day (per process) when an
// officer's spend read on a pass has reached its daily_budget_usd. It is
// how the owner learns the officer stopped being woken. Called outside
// the loop's lock, from the pass; it must not block.
BudgetAlert func(o Officer, a BudgetAlert)
// Kickoff is the first message instance n of officer o starts with: nil
// is KickoffText. internal/api reads a builtin officer's type grants into
// it (KickoffTextWith), so a granted tool is listed.
Kickoff func(ctx context.Context, o Officer, n int) string
// Refresh, when set, re-reads the roster into Registry (internal/api: the
// DB-declared officers, migration 0136). Run calls it on its first tick
// and then at most every RefreshEvery (DefaultRefreshEvery when 0), so an
// officer another replica created, changed or deleted reaches this one's
// loop with no restart. It must not block for long; it is called from
// Run's goroutine.
Refresh func(ctx context.Context)
RefreshEvery time.Duration
// Chats runs the officers' chat turns (chat.go): nil runs none, and a
// chat item then only keeps its pool busy.
Chats *ChatRunner
// AutoRestart is the bounded restart of an instance in error
// (autorestart.go). The zero value is off: an instance in error holds
// its slot until an operator acts.
AutoRestart AutoRestart
// AutoRestartNotice, when set, is told each auto-restart, each restart
// held (once per error episode: its class is not restartable or the
// day's cap is spent) and the recovery of a held one. Called outside the
// loop's lock, from the pass; it must not block.
AutoRestartNotice func(o Officer, e AutoRestartEvent)
// Restarts persists the auto-restart book (officer_auto_restarts,
// PGRestartStore), so a restarted muster keeps the day's cap, backoff and
// held notices; RestartContext is the context it is called under for an
// officer (its owner's). nil Restarts keeps the book in memory.
Restarts RestartStore
RestartContext func(ctx context.Context, o Officer) context.Context
}
Config is NewReconciler's input.
type ConnectorBlock ¶ added in v0.245.0
ConnectorBlock is one item an officer instance held while a connector refused it for want of an approved grant.
type ConnectorBlockStore ¶ added in v0.245.0
type ConnectorBlockStore interface {
// RecordBlock records b, unless (officer, grant, item) is already
// recorded: the first refusal's time stands.
RecordBlock(ctx context.Context, b ConnectorBlock) error
// BlocksForGrant is officer's UNSETTLED blocks on grant recorded at or
// after since, newest first, at most limit.
BlocksForGrant(ctx context.Context, officer string, grant int64, since time.Time, limit int) ([]ConnectorBlock, error)
// SettleBlock marks (officer, grant, item) settled at at — re-run, or
// skipped for good — so it is never read again. A block already settled
// keeps its first time.
SettleBlock(ctx context.Context, officer string, grant int64, item ItemID, at time.Time) error
// SettleBlocks settles, at at, every unsettled block of (officer, grant)
// recorded before before — every one when before is zero — and says how
// many: a denied grant's blocks, or an approved grant's past RerunWindow.
SettleBlocks(ctx context.Context, officer string, grant int64, before, at time.Time) (int, error)
// UnsettledGrants is the grants officer has an unsettled block on,
// ascending, at most limit: what the block sweep reads.
UnsettledGrants(ctx context.Context, officer string, limit int) ([]int64, error)
}
ConnectorBlockStore keeps the blocks. ctx acts as the officer's owner (the database store is under row-level security).
type Decision ¶
type Decision struct {
// Start, Stop and Reprompt are instance numbers, ascending.
Start []int
Stop []int
Reprompt []int
// StopReason is why Stop stops ("" = the officer was idle for its window).
StopReason string
// StopWhy is why each instance in Stop stops when it is not StopReason:
// a chat-idle stop of a busy pool (chatIdleStops), by instance number.
StopWhy map[int]string
// ChatWhy is why each instance in Start was started for chats (a chat
// home a waiting chat needs, or a chat scale-up), by instance number.
ChatWhy map[int]string
// StartWhy is why each instance in Start was down (InstanceState.Down;
// "" when the fleet did not say), by instance number.
StartWhy map[int]string
// Release is live claims held by an instance that is not up.
Release []Item
// Restart is the instances in error this pass restarts (stop, release
// what each held, start: autorestart.go), ascending. Each was counted up
// by Decide, so none is in Start; none is in Stop or Overrun.
Restart []Restart
// Overrun is live claims held past the pool's wall-time cap: each holder
// is stopped (when up) and the item completed escalated. An overrun claim
// is never in Release, Held or Stop.
Overrun []Overrun
// Unclocked is live claims of a capped pool that HQ gave no claimed_at:
// with no clock they are not capped (logged once per officer).
Unclocked []ItemID
// Idle reports the officer idle at this pass: nothing claimable, no live
// claim held by any of its instances.
Idle bool
// Claimable is how many items an instance could claim now.
Claimable int
// CapWaiting is how many items would be Claimable but for the day's
// judgement session cap (obs.Capped): work held back by the cap.
CapWaiting int
// BudgetWaiting is how many items would be Claimable but for the
// officer's spent daily budget (obs.OverBudget). An item held back by
// both caps counts here, not in CapWaiting.
BudgetWaiting int
// Held is how many live claims its instances hold.
Held int
// ChatPending is how many chat items wait for a chat turn, and ChatHeld
// how many a chat turn holds now (chat.go). Counted for a pool that runs
// chats (Officer.ChatsPool) only; never in Claimable or Held — a chat is
// not queue work.
ChatPending int
ChatHeld int
}
Decision is what one pass decided.
func Decide ¶
func Decide(o Officer, obs Observation, idleSince, now time.Time, promptedAt map[int]time.Time) Decision
Decide is the loop's whole policy, as a pure function, for ONE POOL of instances: o is an untiered officer, or one pool of a tiered one (Officer.Pools), and obs.Instances that pool's instances.
- Claimable = open items, plus claimed items whose lease has expired (the contract makes those claimable by anyone) — less any item HQ marks Blocked: its claim is refused, so it is not work, and an instance woken or kept up for it would claim nothing. A tiered pool counts only the items of its own tier as HQ reads them (ItemTier): its instances' claims name the tier, so another tier's item is not work for them either (HQ answers 409 wrong_tier).
- A judgement pool that has spent its day's session cap (obs.Capped) counts as Claimable only the items it already claimed today (obs.Counted): officer_claim refuses it any other.
- Held = claimed items with a live lease whose holder is one of this pool's instances — whatever the item's tier: a claim belongs to the pool that holds it.
- Busy (Claimable > 0 or Held > 0, or chat work): want min(MaxInstances, held-by-up + Claimable) of the queue's instances (1..MaxInstances) up; start the lowest-numbered down ones to reach it. A pool that runs chats also starts the stopped homes its waiting chats wait for (ChatPlan.Homes) and the instances its other waiting chats need (ChatPlan.Need), up to chat_max_instances, and stops an instance quiet for chat_idle_stop (chatIdleStops) — never one doing queue work. Nothing else is stopped while busy.
- Idle (neither): once idle has lasted IdleAfter (now - idleSince), stop every up instance. idleSince zero means "idle only now", so nothing is stopped on the first idle pass.
- A live claim held by an instance that is NOT up is released, busy or idle: its holder cannot heartbeat it, and releasing returns the item to the queue now rather than when the lease lapses.
- A live claim held for the pool's wall-time cap (ItemCap, measured from HQ's claimed_at) is an Overrun instead, up or not: its holder is stopped and the item escalated. A claim without claimed_at has no clock and is not capped (Unclocked). Released, a judgement item would be claimed again and run another cap. The holder is not counted busy, so it is neither re-prompted nor kept up for that claim.
- 🔴 AN INSTANCE NUMBER HOLDING A CAPPED CLAIM IS NEVER STARTED, for as long as HQ shows it holding one (an escalation HQ refuses keeps the item held in that NAME): a new session under the name would claim other work, and the next pass would stop it for the old item's cap, killing that work every few polls without bound. Other work starts the next free number, or waits. A holder that is up still counts as up on the pass that stops it, so a failed stop never puts more than MaxInstances up; the next pass, seeing it down, starts another number.
type Declaration ¶ added in v0.236.0
type Declaration struct {
ID string
Owner int64
// Runtime is RuntimePod, RuntimeHost or RuntimeAuto.
Runtime string
// Host is the mirror host of a RuntimeHost officer; "" otherwise.
Host string
// Repo is the officer's own repository ("" for none).
Repo string
// Connectors are the connectors besides github its instances may request.
Connectors []string
// ReadRepos are public repositories its instances read with no approval
// (the standing public read, Officer.StandingReadRepos).
ReadRepos []string
// MaxInstances, IdleAfter and PollInterval are 0 for the defaults.
MaxInstances int
IdleAfter time.Duration
PollInterval time.Duration
// Model is the pod's model ("" for the account default).
Model string
// InstanceSlug is the server-allocated agent slug (SlugCandidates).
InstanceSlug string
}
Declaration is a DB-declared officer's runtime fields, as officer_defs stores them (0136).
func (Declaration) Officer ¶ added in v0.236.0
func (d Declaration) Officer(runtime, host, namespacePrefix string) (Officer, error)
Officer is d as the officer it declares, with runtime and host the runtime it runs on (a RuntimeAuto declaration's resolution; for RuntimePod or RuntimeHost, d's own), validated by the one declaration check (declared.officer). namespacePrefix is the deployment's MUSTER_AGENT_NAMESPACE_PREFIX: the instance names must fit a namespace under it. A refusal carries its fields (Fields).
func (Declaration) Validate ¶ added in v0.236.0
func (d Declaration) Validate(namespacePrefix string) error
Validate checks d as declared: a RuntimeAuto declaration must be runnable on at least one runtime (a pod, or a host — checked with a placeholder host name, since auto picks the host), and its own host must be empty.
type DocsOnly ¶ added in v0.229.0
type DocsOnly struct {
// AllowedPaths are globs; every path a pull request touches must match
// one (MatchAllowed).
AllowedPaths []string
// MaxDiffLines caps the comparison's added+removed lines; MaxFiles its
// changed files; MaxPRsPerDay the pull requests opened per UTC day
// (never above MaxNewPRsPerDay).
MaxDiffLines int
MaxFiles int
MaxPRsPerDay int
}
DocsOnly is a draft officer's docs-only policy (its `docs_only` block).
type ErrorClass ¶ added in v0.257.0
type ErrorClass string
ErrorClass is why an instance is in error, as the fleet classifies it (internal/api classifyInstanceError). The zero value is ErrorUnknown.
const ( // ErrorUnknown: a cause muster does not recognise (or none recorded). // Held: a new error writer must not default to a restart loop. ErrorUnknown ErrorClass = "" // ErrorKickoffStuck: its first turn never landed — the instance dwelt // past the kickoff deliverer's bound without a ready session taking it. // Nothing was sent, so a restart cannot pay for a turn twice. ErrorKickoffStuck ErrorClass = "kickoff_stuck" // ErrorCrashLoop: the live instance is crash-looping or its pod failed. ErrorCrashLoop ErrorClass = "crash_loop" // ErrorApplyFailed: a write to the backend (apply, scale, create, a // store write beside them) failed — the transient half of a start. ErrorApplyFailed ErrorClass = "apply_failed" // ErrorConfig: a configuration a restart re-reads unchanged — the spec // could not be built, the image cannot be pulled, an instance of that // name already exists differently, the deployment cannot deliver a first // turn. Held. ErrorConfig ErrorClass = "config" // ErrorAuth: a credential problem — the account's credential could not // be read or a token minted, or the model account rejected it // (auth_failed) or its billing (billing_error). Held: a new credential // is a human's step. ErrorAuth ErrorClass = "auth" // ErrorCheckoutWait: its first turn waited for a repository checkout // that never arrived (a grant nobody approved, a clone that never // finished). Held: the approval is a human's. ErrorCheckoutWait ErrorClass = "checkout_wait" // ErrorRateLimited: the model account answered rate_limited (its usage // limit). Held: a restart sends the next first turn into the same limit, // and muster does not know here when it resets. ErrorRateLimited ErrorClass = "rate_limited" // ErrorSidecar: the instance reads error because a container OTHER than // its agent's (a sidecar, a key holder) is failing, while the agent's own // is not. Held: a restart would end a live session over a container it // does not run in. ErrorSidecar ErrorClass = "sidecar" )
func (ErrorClass) Restartable ¶ added in v0.257.0
func (c ErrorClass) Restartable() bool
Restartable reports whether a restart can fix an instance in error of class c. THE one predicate: the loop reads nothing else.
func (ErrorClass) String ¶ added in v0.257.0
func (c ErrorClass) String() string
String names the class in a log line ("unknown" for the zero value).
type FieldError ¶ added in v0.236.0
FieldError is a declaration refused for one field (Field, the JSON name a declaration spells it with): what the admin API answers per field. Its Error is the refusal's own text, so an env declaration's boot refusal reads exactly as it always has.
func Fields ¶ added in v0.236.0
func Fields(err error) []FieldError
Fields is err as per-field refusals: every refusal a FieldErrors holds (each prefixed with its Prefix), else the one FieldError, else err as one refusal of no particular field (Field "").
func (*FieldError) Error ¶ added in v0.236.0
func (e *FieldError) Error() string
func (*FieldError) Unwrap ¶ added in v0.236.0
func (e *FieldError) Unwrap() error
type FieldErrors ¶ added in v0.236.0
type FieldErrors struct {
Prefix string
List []FieldError
}
FieldErrors is several refusals at once (a host officer's): Error is Prefix then each refusal's text, joined with "; ".
func (*FieldErrors) Error ¶ added in v0.236.0
func (e *FieldErrors) Error() string
type Fleet ¶
type Fleet interface {
// Instances returns the state of instances 1..o.Slots() — chat-only
// instances included, so one started for chats is seen up. An error
// means the fleet could not be SEEN; the pass then changes nothing.
Instances(ctx context.Context, o Officer) ([]InstanceState, error)
// Start brings instance n up — creating its agent when it does not exist
// — with kickoff as its first message.
Start(ctx context.Context, o Officer, n int, kickoff string) error
// Stop scales instance n to zero, keeping its agent and volume.
Stop(ctx context.Context, o Officer, n int) error
// Reprompt gives up instance n a new turn with text, delivered when its
// session can take one (internal/api: the kickoff deliverer, which never
// types into a turn already running).
Reprompt(ctx context.Context, o Officer, n int, text string) error
}
Fleet is how the loop observes and moves an officer's instances. internal/api implements it over the agents store and the provisioner.
type FloodBlockProposal ¶ added in v0.186.0
FloodBlockProposal is officer_flood_block_propose's arguments: {item_id, unit_ids, ttl_hours, to?}. The action is muster's (FloodBlockAction).
func ParseFloodBlockProposal ¶ added in v0.186.0
func ParseFloodBlockProposal(raw []byte) (FloodBlockProposal, error)
ParseFloodBlockProposal decodes officer_flood_block_propose's arguments strictly. It checks TYPES only: the values (how many units, which, the ttl range, who may approve) are HQ's to refuse.
type FloodBlocksBackend ¶ added in v0.209.0
type FloodBlocksBackend interface {
ProposeFloodBlock(ctx context.Context, instance string, p FloodBlockProposal) ([]byte, error)
}
FloodBlocksBackend files a web-performance officer's flood-block proposal.
type GapTaskArgs ¶ added in v0.203.0
type GapTaskArgs struct {
Item ItemID
Store string
Kind string
Namespace string
Tier string
Affected []string
}
GapTaskArgs is officer_gap_task's arguments: {item_id, store, kind, namespace?, tier?, affected?}.
func ParseGapTaskArgs ¶ added in v0.203.0
func ParseGapTaskArgs(raw []byte) (GapTaskArgs, error)
ParseGapTaskArgs decodes officer_gap_task's arguments strictly. It checks TYPES and presence only: the values (which kinds, the slug patterns, the caps) are HQ's to refuse.
type GapTasksBackend ¶ added in v0.209.0
type GapTasksBackend interface {
FileGapTask(ctx context.Context, instance string, a GapTaskArgs) ([]byte, error)
}
GapTasksBackend files a datastore officer's gap task.
type HQ ¶
type HQ interface {
AllItems(ctx context.Context, o Officer, status string) ([]Item, error)
Release(ctx context.Context, o Officer, item ItemID, instance string) error
// Complete completes item as instance (its holder): the wall-time cap's
// escalation (Decision.Overrun).
Complete(ctx context.Context, o Officer, item ItemID, instance string, done Completion) error
// Heartbeat renews instance's lease on item: a capped item whose
// escalation HQ refused is kept held, so it is never re-claimed.
Heartbeat(ctx context.Context, o Officer, item ItemID, instance string, leaseSeconds int) error
}
HQ is the part of the officer-backend contract the loop uses, for any officer. Backends adapts a per-officer Backend factory to it.
type HQError ¶
type HQError struct {
Status int
Body []byte
// Builtin: muster's built-in backend refused (internal/officers/builtin),
// not an HQ — so the text never says HQ answered.
Builtin bool
}
HQError is HQ answering with a 4xx: a decision, not an outage. Body is HQ's own JSON (bounded), passed back to the instance verbatim — a 409 on a claim carries `held_by` and `lease_expires_at`, which is what the instance needs to move on.
func CompleteDroppingCost ¶ added in v0.209.0
func CompleteDroppingCost(ctx context.Context, b Backend, item ItemID, instance string, done Completion) (body []byte, refused *HQError, err error)
CompleteDroppingCost is b.Complete, sent once more WITHOUT done.Cost when the backend refuses the complete that carried it with a 400 — an HQ from before item cost refuses the unknown fields, and one with it a cost it will not store — so a cost never fails a complete. refused is the refusal of the costed complete when the cost-free one then succeeded (the caller says the cost was dropped); when that one is refused too, its answer is returned, as a complete without a cost always was.
type Handoff ¶ added in v0.210.0
type Handoff struct {
HeadSHA string `json:"head_sha"`
// To is HandoffToAuthor on a shepherd's hand-off of a clean round's
// fixes to the pull request's authoring officer; "" (not sent) otherwise.
To string `json:"to,omitempty"`
}
Handoff is a completion's `handoff`: {"head_sha": <40 lower-case hex>}, and on a shepherd's complete optionally "to": "author". HQ decides which items and outcomes take one (it refuses it on any outcome but done) and where it goes; muster checks only its shape (ValidHandoffHead) and that the outcome is done.
type HostSpawn ¶ added in v0.223.0
type HostSpawn struct {
ID int64
// Officer is the officer id, Instance the instance agent name
// (InstanceName) the spawn is for, Host the mirror host it was sent to.
Officer, Instance, Host string
// Window and AgentSession are what the host's reply named: the tmux window
// id and the Claude session id it chose. "" until the reply.
Window, AgentSession string
// Refusal is the host's refusal ("code: detail"), "" for none.
Refusal string
CreatedAt time.Time
// OwnerID is the row's owner: the officer's owner (a person, or a team
// for a team officer).
OwnerID int64
// sharing phase 3), 0 for none: that team's members read the row, and
// only its owner writes it. Personal by default.
SharedTeam int64
// MissingListings is how many of its host's listings in a row have not
// listed its recorded window (migration 0136, ObserveHostListing). At
// HostSpawnMissingToClose the window is GONE for good: the count no longer
// moves, and HostSpawnsInWindows never answers the row again, so a tmux
// window id the host later reissues to another window is not this one.
MissingListings int
// ClaimedAt is when the instance this spawn started first claimed an
// item (migration 0139, MarkHostSpawnClaimed); nil until it has.
ClaimedAt *time.Time
// UnclaimedNotice is the Attention notice raised because the instance
// had not claimed its item in time (SetUnclaimedNotice), 0 for none;
// NoticeSettled reports it withdrawn (SettleUnclaimedNotice).
UnclaimedNotice int64
NoticeSettled bool
}
HostSpawn is one row.
type HostSpawnLender ¶ added in v0.225.0
type HostSpawnLender interface {
// VisibleHostSpawns is the newest limit rows the principal reads — its
// own, those lent to a team it is a member of, and its teams' own rows
// (team_owner_read; a person's own doors only: the others carry no
// teams) — narrowed by w.
VisibleHostSpawns(ctx context.Context, w SpawnWindow, limit int) ([]HostSpawn, error)
// LendHostSpawn lends row id of the principal's own to team (0: unlends
// it) and returns the row. ErrHostSpawnNotFound when no row of the
// principal's OWN has that id (a row only lent to them included);
// ErrLendRefused when the database refuses the team.
LendHostSpawn(ctx context.Context, id, team int64) (HostSpawn, error)
// HostSpawnByID is row id, as the principal reads it (the team a lend is
// taken back from, for its audit row).
HostSpawnByID(ctx context.Context, id int64) (HostSpawn, error)
}
HostSpawnLender lends and lists host spawns for a person.
type HostSpawnStore ¶ added in v0.223.0
type HostSpawnStore interface {
// InsertHostSpawn records a spawn about to be sent and returns its row.
InsertHostSpawn(ctx context.Context, officer, instance, host string) (HostSpawn, error)
// RecordHostSpawnWindow records the host's reply on row id of host,
// reporting whether it wrote (false: a window or refusal is already
// recorded, or the row is not host's).
RecordHostSpawnWindow(ctx context.Context, id int64, host, window, session string) (bool, error)
// RecordHostSpawnRefusal records the host's refusal on row id of host,
// under the same rule.
RecordHostSpawnRefusal(ctx context.Context, id int64, host, refusal string) (bool, error)
// RecordHostSpawnSession re-records the Claude session of row id, ONLY on
// its host and its recorded window (never a first record, never another
// window): the recorded window now runs another conversation (a /clear in
// it), and the instance is that window's.
RecordHostSpawnSession(ctx context.Context, id int64, host, window, session string) (bool, error)
// LatestHostSpawns is officer's newest row per instance name.
LatestHostSpawns(ctx context.Context, officer string) (map[string]HostSpawn, error)
// HostSpawnByID is row id.
HostSpawnByID(ctx context.Context, id int64) (HostSpawn, error)
// HostSpawnForSession is the newest row of host whose recorded Claude
// session is session: how a mirrored caller is found (never by its
// window's tag, which anything in the window can set).
HostSpawnForSession(ctx context.Context, host, session string) (HostSpawn, error)
// HostSpawnIDs is which of ids are host spawns of the principal's on host.
HostSpawnIDs(ctx context.Context, host string, ids []int64) (map[int64]bool, error)
// HostSpawnsInWindows is the principal's spawns on host whose RECORDED
// window (the id from the host's own spawn reply, never a tag) is one of
// windows, and is not closed (ObserveHostListing): the officer windows
// among a host's listing.
HostSpawnsInWindows(ctx context.Context, host string, windows []string) ([]HostSpawn, error)
// ObserveHostListing applies one listing of host (its window ids) to the
// principal's rows there: a row whose recorded window is listed has its
// count of missing listings reset; one whose window is not listed, and
// that was created before settled (a younger row's window may not be
// listed yet), has it counted up — until HostSpawnMissingToClose, after
// which the row is closed and neither moves again (round 2's second
// finding: a reissued window id).
ObserveHostListing(ctx context.Context, host string, windows []string, settled time.Time) error
// CountHostSpawnsSince is how many of officer's spawns were recorded at
// or after since: the officer's own spawn budget (SpawnBudgetFor).
CountHostSpawnsSince(ctx context.Context, officer string, since time.Time) (int, error)
// MarkHostSpawnClaimed records, once, that row id's instance on host
// claimed an item, reporting whether it wrote (false: already recorded,
// or not host's row).
MarkHostSpawnClaimed(ctx context.Context, id int64, host string) (bool, error)
// SetUnclaimedNotice records notice as row id's unclaimed notice, ONLY
// while it has none (a compare-and-swap from none): false means another
// writer raised one first, and the caller withdraws its own.
SetUnclaimedNotice(ctx context.Context, id, notice int64) (bool, error)
// SettleUnclaimedNotice marks row id's notice withdrawn, once.
SettleUnclaimedNotice(ctx context.Context, id int64) (bool, error)
// OpenUnclaimedNotices is the principal's rows whose unclaimed notice is
// raised and not settled.
OpenUnclaimedNotices(ctx context.Context) ([]HostSpawn, error)
}
HostSpawnStore keeps the host spawns. Every call acts as the principal on ctx, and reads ONLY that principal's own rows (ownRowSQL) — never a team's, which row-level security alone would admit (VisibleHostSpawns, the HostSpawnLender's, is the one read that includes them).
type InstanceState ¶
type InstanceState struct {
// N is the instance number, 1..Slots (Officer.Slots: max_instances, or
// the chat ceiling past it).
N int
// Name is the agent name (InstanceName(officer, N)).
Name string
// Exists reports whether muster has an agent row for it.
Exists bool
// Up reports whether its workload is running or on its way up
// (provisioning, pending). A stopped, absent or never-started instance is
// not up. An instance in error counts as up: it holds its slot.
Up bool
// Error reports the instance in error (crash-looping, a failed apply). It
// holds its slot, so the loop logs and counts it rather than starting it
// — until the bounded auto-restart (autorestart.go) restarts it, when
// ErrorClass is one a restart fixes.
Error bool
// ErrorClass is why it is in error (meaningful only with Error):
// ErrorUnknown when the fleet cannot say, which is never restarted.
ErrorClass ErrorClass
// ErrorText is the error recorded for it, as the agent's card shows it
// (scrubbed of its pending note; bounded): the auto-restart logs and
// keeps it, since a restart's Stop clears the agent row's.
ErrorText string
// Down is why the instance is not up, as the fleet sees it ("" when up,
// or when the fleet cannot say): "no agent yet", "its window @23 on h1
// is gone", "its last start was refused: …". The start line names it, so
// every start — and every RESTART — says why it happened.
Down string
// PromptPending reports a prompt (a kickoff or a re-prompt) owed to the
// instance and not yet delivered. Such an instance is not re-prompted.
PromptPending bool
// LimitParked is why the instance's pane is on a STALE usage-limit menu
// ("" when it is not): ccd refuses its turns from the CLI's limit menu,
// it has been parked there since before a newer live reading showed its
// account usable, and it was still seen there after that reading
// (internal/limitpark Board.Stuck). The loop restarts such an instance
// (restartLimitParked): nothing else ends the menu.
LimitParked string
// LimitHeld is why the instance is stuck on a stale menu but NOT to be
// restarted again today (limitpark.MaxRestartsPerDay, the backstop): the
// loop logs it once that UTC day and leaves it; its refusals mark the
// account again. "" when not held. Never set with LimitParked.
LimitHeld string
// Spent, for an instance of a fresh_session_per_item pool: its current
// conversation has claimed its one item (Officer.FreshSessionPerItem).
// Held by no live claim, it is done with that item however the hold
// ended, and is prompted (into a new conversation) without waiting out
// RepromptAfter. Always false for every other pool.
Spent bool
}
InstanceState is one instance agent of an officer as the fleet sees it.
type InternalPattern ¶ added in v0.229.0
InternalPattern is one compiled line of an internal-details pattern file; Line is its 1-based line number (what a refusal names: never the pattern, never the text it matched).
func ParseInternalPatterns ¶ added in v0.229.0
func ParseInternalPatterns(content string) ([]InternalPattern, error)
ParseInternalPatterns reads an internal-details pattern file: one RE2 regular expression per line, surrounding space trimmed, blank lines and lines starting with '#' skipped. Matching is case-insensitive. A line that does not compile, or matches the empty string (it would match everything), is an error naming its line number; so is a file with no pattern.
type Investigation ¶ added in v0.155.0
type Investigation struct {
Hypotheses []string `json:"hypotheses"`
Eliminated []InvestigationRule `json:"eliminated"`
RootCause string `json:"root_cause"`
// Confidence: low, medium or high. Low gives Fix.OperatorSteps only.
Confidence string `json:"confidence"`
Fix InvestigationFix `json:"fix"`
NotChecked []string `json:"not_checked"`
}
Investigation is HQ's investigation block on an `escalated` complete (civ-hq docs/OFFICERS.md "Investigation"). HQ REQUIRES it to escalate an item of an officer type whose policy sets `investigation: true` (else 400 naming `investigation`), and takes it on `escalated` for any type. Every list is sent, empty when there is nothing.
func OverrunInvestigation ¶ added in v0.155.0
func OverrunInvestigation(o Officer) Investigation
OverrunInvestigation is the investigation block of a claim stopped at the cap: low confidence (operator steps only), nothing concluded, re-investigate.
type InvestigationFix ¶ added in v0.155.0
type InvestigationFix struct {
PRURLs []string `json:"pr_urls,omitempty"`
OperatorSteps []string `json:"operator_steps,omitempty"`
}
InvestigationFix is EXACTLY ONE of: draft PRs, or operator steps.
type InvestigationRule ¶ added in v0.155.0
type InvestigationRule struct {
Hypothesis string `json:"hypothesis"`
Evidence string `json:"evidence"`
AuditIDs []int64 `json:"audit_ids"`
}
InvestigationRule is one hypothesis ruled out, with its evidence and the audit ids of the reads it came from.
type Item ¶
type Item struct {
ID ItemID `json:"id"`
OfficerID string `json:"officer_id"`
Kind string `json:"kind"`
SubjectKey string `json:"subject_key"`
Status string `json:"status"`
ClaimedBy string `json:"claimed_by"`
LeaseExpiresAt *time.Time `json:"lease_expires_at"`
UpdatedAt *time.Time `json:"updated_at"`
// Blocked is HQ's task ordering: the item's task waits on unfinished
// tasks, so HQ refuses to claim it (409 blocked). Absent — an unblocked
// item, or an HQ without ordering — is false: the item is claimable.
Blocked bool `json:"blocked"`
// Tier is HQ's `tier` as the item reads now: routine or judgement. Absent
// (an HQ without tiers) reads as judgement (ItemTier).
Tier string `json:"tier"`
// ClaimedAt is HQ's `claimed_at`: when the current (or last) claim was
// made. HQ sets it on every claim and a heartbeat keeps it, so it is the
// wall-time cap's clock (Officer.ItemCap), and it survives a restart of
// muster. Absent (an HQ without it): the item has no clock, and is not
// capped.
ClaimedAt *time.Time `json:"claimed_at"`
// Payload is HQ's `payload`, raw: what the item's producer attached. A
// pull-request loop item carries `pr_loop` (and a findings item `from`,
// the auditor's report written by HQ): officership.LoopPayload reads it.
// Absent: nil.
Payload json.RawMessage `json:"payload,omitempty"`
// Shadow is HQ's `shadow`: true when HQ runs this item in shadow (a write
// it asks for is only recorded, never made), false when not. ABSENT (nil)
// when the officer's type has no shadow policy for items: the officer
// row's `shadow` decides (Client.Shadow).
Shadow *bool `json:"shadow,omitempty"`
// NotBefore is the item's `not_before`: it is not claimable before then
// (the claim answers 409 not_due), so it is not work before then either
// (Due). Absent: due now.
NotBefore *time.Time `json:"not_before,omitempty"`
// Origin is who put the item in the queue, as the built-in backend
// records it: OriginOwner for an item the officer's owner enqueued (the
// admin API behind `muster officer item enqueue`, "Run now", the owner's rejection of a
// draft), "" for everything else. Only OriginOwner bypasses the daily
// budget (Officer.BypassesBudget). HQ sends none: "".
Origin string `json:"origin,omitempty"`
}
Item is the part of an HQ item the wake loop decides on. The MCP tools pass HQ's full JSON through instead of this struct.
func NonChat ¶ added in v0.247.0
NonChat is items less the chat items: what the transcript forwarder and the LLM proxy's claim sync are told (Config.Observed). A chat claim is held as ChatHolder, which names no instance's primary session.
func PageAll ¶ added in v0.209.0
func PageAll(ctx context.Context, items func(context.Context, ItemsQuery) (ItemsPage, error), status string) ([]Item, error)
PageAll is THE AllItems of every backend: up to maxItemPages pages of 100 items in status, read through items (a backend's Items).
func PendingChats ¶ added in v0.247.0
func PendingChats(obs Observation, now time.Time) []Item
PendingChats is the chat items of obs that a chat turn could claim at now: open, or claimed with a lapsed lease — less a blocked item or one not due (its claim is refused) and one that names no chat. Pure.
func (Item) Due ¶ added in v0.242.0
Due reports whether item it may be claimed at now: it has no not_before, or not_before has passed. THE wake loop's rule for an item that is not yet work (Decide); the built-in backend's claim refuses the same items (409 not_due, and claim-next's `claimable`).
type ItemCost ¶ added in v0.175.0
ItemCost is an item's cost as HQ takes it: USD, and who computed it.
type ItemID ¶
type ItemID string
ItemID is an item id as HQ spells it. The contract does not say whether ids are numbers or strings, so both decode; it is always used as a path segment.
func (*ItemID) UnmarshalJSON ¶
UnmarshalJSON accepts a JSON string or number.
type ItemsPage ¶
type ItemsPage struct {
Items []Item
NextCursor string
// Raw is HQ's body, for the MCP tool that passes it through.
Raw json.RawMessage
}
ItemsPage is one page of an officer's items.
type ItemsQuery ¶
type ItemsQuery struct {
Status string
Limit int
Cursor string
// Tier filters by the item's tier (`?tier=`); "" lists every tier.
Tier string
}
ItemsQuery is GET /officers/{id}/items's query.
type JudgementLedger ¶ added in v0.146.0
type JudgementLedger struct {
// contains filtered or unexported fields
}
JudgementLedger applies the cap over a SessionStore. scope gives the store call the principal of o's owner (the table is owner-scoped); logf reports a release or resolve that failed (the count is then high until it is fixed or the day ends). A nil ledger, or an uncapped pool, admits everything.
func NewJudgementLedger ¶ added in v0.146.0
func NewJudgementLedger(store SessionStore, scope func(context.Context, Officer) context.Context, logf func(string, ...any)) *JudgementLedger
NewJudgementLedger is the ledger over store; scope and logf may be nil.
func (*JudgementLedger) Reserve ¶ added in v0.146.0
func (l *JudgementLedger) Reserve(ctx context.Context, o Officer, item ItemID, now time.Time) (undo func(), err error)
Reserve admits a claim of item by pool o at now. undo releases the session and is to be called ONLY when the claim definitely did not happen (HQ refused it); it releases nothing unless this admission inserted the item, so a claim that lost a race for the same item never releases the winner's. The cap's refusal wraps ErrSessionCap; a store failure is returned as is.
func (*JudgementLedger) ReserveNext ¶ added in v0.146.0
func (l *JudgementLedger) ReserveNext(ctx context.Context, o Officer, now time.Time) (done func(item ItemID, known bool), err error)
ReserveNext admits a claim-next (officer_claim with no item_id: HQ picks the item) by pool o at now, holding one session under a pending entry. done(item, known) settles it: known with an item counts that item, known with "" (HQ claimed nothing) gives the session back, and NOT known (HQ's answer was lost: it may have claimed one) keeps it as an unknown: entry.
func (*JudgementLedger) Usage ¶ added in v0.161.0
func (l *JudgementLedger) Usage(ctx context.Context, o Officer, now time.Time) (int, map[ItemID]bool, error)
Usage is how many sessions pool o has used on now's UTC day, by CountSessions, and the items it counted (still work for it at the cap). The pool is capped when that is at least o.SessionCap(). An uncapped pool (or a nil ledger) reads 0 and reads no store. A store failure is returned.
type KickoffGrants ¶ added in v0.238.0
type KickoffGrants struct {
// OutboundDrafts: the type grants outbound_drafts (officer_post_draft).
OutboundDrafts bool
// Contacts: the type grants contacts (the contact tools).
Contacts bool
}
KickoffGrants is what a builtin officer's TYPE grants (its policy's capabilities, read when the instance starts): the tools offered on a grant are listed in the kickoff only when granted, as officer_post_draft and the contact tools are served only then (internal/api, at call time).
type Kube ¶ added in v0.153.0
type Kube struct {
// Clusters is every declared cluster, an allowlist-less one included
// (Allow nil); KubeClusters is the readable ones.
Clusters []KubeCluster
}
Kube is an officer's `kube` block.
type KubeCluster ¶ added in v0.153.0
type KubeCluster struct {
// Name is the cluster's name, as the instance names it.
Name string
// ServiceAccount is the officer's own read-only ServiceAccount there,
// "<namespace>/<name>": the identity each call's token is minted for.
ServiceAccount string
// Endpoint is the API server's host:port, from the sealed environment.
Endpoint string
// CA is the PEM bundle its certificate chains to, from the sealed
// environment.
CA []byte
// Allow is the cluster's read allowlist, from the deployment's
// configuration; nil when none is set, which disables the cluster.
Allow *kuberead.Allowlist
// contains filtered or unexported fields
}
KubeCluster is one cluster an officer's judgement instances may read.
func (KubeCluster) GoString ¶ added in v0.153.0
func (k KubeCluster) GoString() string
GoString is String.
func (KubeCluster) MinterToken ¶ added in v0.153.0
func (k KubeCluster) MinterToken() string
MinterToken is the cluster's minter token. Its only caller builds the cluster reader (internal/api); tests assert where it must not appear.
func (KubeCluster) String ¶ added in v0.153.0
func (k KubeCluster) String() string
String names the cluster without its token.
type LLM ¶ added in v0.141.0
type LLM struct {
// DailyBudgetUSD is the officer's spend cap per UTC day, summed over its
// routine instances and metered from the provider's own reported cost.
DailyBudgetUSD float64 `json:"daily_budget_usd"`
// MaxTokensPerItem ends a runaway turn: once an instance has used this
// many tokens (input, cache and output together) on the item it holds,
// its next request is refused until it holds a different item. It does
// not apply while the instance holds no item: DailyBudgetUSD bounds that.
MaxTokensPerItem int64 `json:"max_tokens_per_item"`
// contains filtered or unexported fields
}
LLM is an officer's `llm` block: what the LLM proxy may SPEND for the officer. The model it pins a routine instance to is the routine pool's (tiers.routine.model), and who may use it is the routine pool's instances (RoutineAgent) — one source each, so neither is repeated here.
func (*LLM) Key ¶ added in v0.141.0
Key returns the provider key. Its only caller is the proxy, on the way to the provider, and tests asserting it appears nowhere else.
type MemConnectorBlockStore ¶ added in v0.245.0
type MemConnectorBlockStore struct {
// contains filtered or unexported fields
}
MemConnectorBlockStore is ConnectorBlockStore in this process's memory.
func NewMemConnectorBlockStore ¶ added in v0.245.0
func NewMemConnectorBlockStore() *MemConnectorBlockStore
NewMemConnectorBlockStore is an empty memory store.
func (*MemConnectorBlockStore) BlocksForGrant ¶ added in v0.245.0
func (m *MemConnectorBlockStore) BlocksForGrant(_ context.Context, officer string, grant int64, since time.Time, limit int) ([]ConnectorBlock, error)
BlocksForGrant implements ConnectorBlockStore.
func (*MemConnectorBlockStore) RecordBlock ¶ added in v0.245.0
func (m *MemConnectorBlockStore) RecordBlock(_ context.Context, b ConnectorBlock) error
RecordBlock implements ConnectorBlockStore.
func (*MemConnectorBlockStore) SettleBlock ¶ added in v0.245.0
func (m *MemConnectorBlockStore) SettleBlock(_ context.Context, officer string, grant int64, item ItemID, _ time.Time) error
SettleBlock implements ConnectorBlockStore.
func (*MemConnectorBlockStore) SettleBlocks ¶ added in v0.284.0
func (m *MemConnectorBlockStore) SettleBlocks(_ context.Context, officer string, grant int64, before, _ time.Time) (int, error)
SettleBlocks implements ConnectorBlockStore.
func (*MemConnectorBlockStore) UnsettledGrants ¶ added in v0.284.0
func (m *MemConnectorBlockStore) UnsettledGrants(_ context.Context, officer string, limit int) ([]int64, error)
UnsettledGrants implements ConnectorBlockStore.
type MemHostSpawnStore ¶ added in v0.223.0
type MemHostSpawnStore struct {
NextID int64
Now func() time.Time
// contains filtered or unexported fields
}
MemHostSpawnStore is HostSpawnStore in memory, for tests (one owner). NextID is the next id it hands out (it starts at 1000, well clear of the small ids a test's chief dispatches use).
func NewMemHostSpawnStore ¶ added in v0.223.0
func NewMemHostSpawnStore() *MemHostSpawnStore
NewMemHostSpawnStore returns an empty store.
func (*MemHostSpawnStore) All ¶ added in v0.223.0
func (m *MemHostSpawnStore) All() []HostSpawn
All is every row, by id (tests).
func (*MemHostSpawnStore) CountHostSpawnsSince ¶ added in v0.238.0
func (m *MemHostSpawnStore) CountHostSpawnsSince(_ context.Context, officer string, since time.Time) (int, error)
CountHostSpawnsSince implements HostSpawnStore.
func (*MemHostSpawnStore) HostSpawnByID ¶ added in v0.223.0
HostSpawnByID implements HostSpawnStore.
func (*MemHostSpawnStore) HostSpawnForSession ¶ added in v0.223.0
func (m *MemHostSpawnStore) HostSpawnForSession(_ context.Context, host, session string) (HostSpawn, error)
HostSpawnForSession implements HostSpawnStore.
func (*MemHostSpawnStore) HostSpawnIDs ¶ added in v0.223.0
func (m *MemHostSpawnStore) HostSpawnIDs(_ context.Context, host string, ids []int64) (map[int64]bool, error)
HostSpawnIDs implements HostSpawnStore.
func (*MemHostSpawnStore) HostSpawnsInWindows ¶ added in v0.236.0
func (m *MemHostSpawnStore) HostSpawnsInWindows(_ context.Context, host string, windows []string) ([]HostSpawn, error)
HostSpawnsInWindows implements HostSpawnStore.
func (*MemHostSpawnStore) InsertHostSpawn ¶ added in v0.223.0
func (m *MemHostSpawnStore) InsertHostSpawn(_ context.Context, officer, instance, host string) (HostSpawn, error)
InsertHostSpawn implements HostSpawnStore.
func (*MemHostSpawnStore) LatestHostSpawns ¶ added in v0.223.0
func (m *MemHostSpawnStore) LatestHostSpawns(_ context.Context, officer string) (map[string]HostSpawn, error)
LatestHostSpawns implements HostSpawnStore.
func (*MemHostSpawnStore) MarkHostSpawnClaimed ¶ added in v0.238.0
func (m *MemHostSpawnStore) MarkHostSpawnClaimed(_ context.Context, id int64, host string) (bool, error)
MarkHostSpawnClaimed implements HostSpawnStore.
func (*MemHostSpawnStore) ObserveHostListing ¶ added in v0.236.0
func (m *MemHostSpawnStore) ObserveHostListing(_ context.Context, host string, windows []string, settled time.Time) error
ObserveHostListing implements HostSpawnStore.
func (*MemHostSpawnStore) OpenUnclaimedNotices ¶ added in v0.238.0
func (m *MemHostSpawnStore) OpenUnclaimedNotices(_ context.Context) ([]HostSpawn, error)
OpenUnclaimedNotices implements HostSpawnStore.
func (*MemHostSpawnStore) RecordHostSpawnRefusal ¶ added in v0.223.0
func (m *MemHostSpawnStore) RecordHostSpawnRefusal(_ context.Context, id int64, host, refusal string) (bool, error)
RecordHostSpawnRefusal implements HostSpawnStore.
func (*MemHostSpawnStore) RecordHostSpawnSession ¶ added in v0.223.0
func (m *MemHostSpawnStore) RecordHostSpawnSession(_ context.Context, id int64, host, window, session string) (bool, error)
RecordHostSpawnSession implements HostSpawnStore.
func (*MemHostSpawnStore) RecordHostSpawnWindow ¶ added in v0.223.0
func (m *MemHostSpawnStore) RecordHostSpawnWindow(_ context.Context, id int64, host, window, session string) (bool, error)
RecordHostSpawnWindow implements HostSpawnStore.
func (*MemHostSpawnStore) SetUnclaimedNotice ¶ added in v0.238.0
SetUnclaimedNotice implements HostSpawnStore.
func (*MemHostSpawnStore) SettleUnclaimedNotice ¶ added in v0.238.0
SettleUnclaimedNotice implements HostSpawnStore.
type MemPRLoopStore ¶ added in v0.210.0
type MemPRLoopStore struct {
// Now is its clock (AnnouncedAt); nil is time.Now. For tests.
Now func() time.Time
// contains filtered or unexported fields
}
MemPRLoopStore is PRLoopStore in this process's memory.
func NewMemPRLoopStore ¶ added in v0.210.0
func NewMemPRLoopStore() *MemPRLoopStore
NewMemPRLoopStore is an empty memory store.
func (*MemPRLoopStore) PRLoopAnnounced ¶ added in v0.210.0
func (m *MemPRLoopStore) PRLoopAnnounced(_ context.Context, officer, repo string, pr int, head string) error
PRLoopAnnounced implements PRLoopStore.
func (*MemPRLoopStore) PRLoopSettle ¶ added in v0.210.0
func (m *MemPRLoopStore) PRLoopSettle(_ context.Context, officer, repo string, pr int, state string) error
PRLoopSettle implements PRLoopStore.
func (*MemPRLoopStore) PRLoopState ¶ added in v0.210.0
func (m *MemPRLoopStore) PRLoopState(_ context.Context, officer, repo string, pr int) (string, error)
PRLoopState implements PRLoopStore.
func (*MemPRLoopStore) PRLoopsClaim ¶ added in v0.210.0
func (m *MemPRLoopStore) PRLoopsClaim(_ context.Context, officer string, notBefore time.Time) (claimed, expired []PRLoop, err error)
PRLoopsClaim implements PRLoopStore.
func (*MemPRLoopStore) PRLoopsInLoop ¶ added in v0.210.0
PRLoopsInLoop implements PRLoopStore.
type MemPRQueueStore ¶ added in v0.257.0
type MemPRQueueStore struct {
// contains filtered or unexported fields
}
MemPRQueueStore is PRQueueStore in this process's memory.
func NewMemPRQueueStore ¶ added in v0.257.0
func NewMemPRQueueStore() *MemPRQueueStore
NewMemPRQueueStore is an empty memory queue.
func (*MemPRQueueStore) PRQueueAdd ¶ added in v0.257.0
func (m *MemPRQueueStore) PRQueueAdd(_ context.Context, officer string, q QueuedPR) (QueuedPR, error)
PRQueueAdd implements PRQueueStore.
func (*MemPRQueueStore) PRQueueList ¶ added in v0.257.0
PRQueueList implements PRQueueStore.
func (*MemPRQueueStore) PRQueueMark ¶ added in v0.259.0
func (m *MemPRQueueStore) PRQueueMark(_ context.Context, officer string, id int64, head, note string) (bool, error)
PRQueueMark implements PRQueueStore.
type MemPublicBranchStore ¶ added in v0.237.0
type MemPublicBranchStore struct {
// contains filtered or unexported fields
}
MemPublicBranchStore is PublicBranchStore in this process's memory.
func NewMemPublicBranchStore ¶ added in v0.237.0
func NewMemPublicBranchStore() *MemPublicBranchStore
NewMemPublicBranchStore is an empty memory store.
func (*MemPublicBranchStore) PublicBranchItem ¶ added in v0.237.0
func (m *MemPublicBranchStore) PublicBranchItem(_ context.Context, officer, repo, branch string) (int, bool, error)
PublicBranchItem implements PublicBranchStore.
func (*MemPublicBranchStore) PublicBranchMint ¶ added in v0.237.0
func (m *MemPublicBranchStore) PublicBranchMint(_ context.Context, officer, repo string, item int, branch string) (string, error)
PublicBranchMint implements PublicBranchStore.
func (*MemPublicBranchStore) PublicBranches ¶ added in v0.237.0
func (m *MemPublicBranchStore) PublicBranches(_ context.Context, officer, repo string) ([]string, error)
PublicBranches implements PublicBranchStore.
type Notice ¶ added in v0.110.0
type Notice struct {
PR int `json:"pr"`
HeadSHA string `json:"head_sha"`
Paths []string `json:"paths"`
Summary string `json:"summary"`
Channel string `json:"channel"`
}
Notice is the body a shipping officer's notice is POSTed with (the sensitive-path notice before a merge). Kept small: HQ renders and signs it.
type ObsBackend ¶ added in v0.209.0
type ObsBackend interface {
ObsQueries(ctx context.Context) ([]byte, error)
ObsQuery(ctx context.Context, args json.RawMessage) ([]byte, error)
}
ObsBackend runs the backend's NAMED observability queries.
type ObsRawBackend ¶ added in v0.209.0
ObsRawBackend runs an instance's own PromQL / LogQL for a held item.
type Observation ¶
type Observation struct {
Open []Item
Claimed []Item
Instances []InstanceState
// Capped: the pool is a judgement pool that has spent its day's session
// cap (JudgementLedger.Usage); then only Counted items — those it
// already claimed today — are work for it.
Capped bool
Counted map[ItemID]bool
// Used is how many judgement sessions the pool has used today
// (JudgementLedger.Usage); 0 for an uncapped pool or an unreadable ledger.
Used int
// OverBudget: the officer has a daily budget (daily_budget_usd) and it is
// spent, or its spend could not be read (fail closed); then only items
// that bypass the budget (Officer.BypassesBudget) are work for it.
OverBudget bool
// BudgetRead: the spend was read (Spent is it), as opposed to an
// unreadable spend that reads as OverBudget. Always false with no budget.
BudgetRead bool
// Spent is the officer's spend today in USD, when BudgetRead.
Spent float64
// Budget is the daily budget the pass held it to, in USD: the declared
// daily_budget_usd, or its owner's raise for today
// (Officer.WithRaisedCap). 0 with no budget.
Budget float64
// SpendUnreadable: the officer has a daily budget and its spend could not
// be read this pass (then OverBudget, fail closed).
SpendUnreadable bool
// Chats: the officer's backend serves chats and muster runs them
// (ChatRunner.On). Only then is a chat item set apart from queue work; a
// muster that runs no chats sees every item as before.
Chats bool
// ChatPlan is what the pool's chats need of its instances
// (ChatRunner.Want). Zero for a pool that runs no chats.
ChatPlan ChatPlan
// ChatHeldBack is the pending chats the pool cannot serve now
// (ChatRunner.Want): not counted in ChatPending, so a chat that cannot
// run never keeps the pool up.
ChatHeldBack map[ItemID]bool
}
Observation is what one pass read.
type Officer ¶
type Officer struct {
// ID is HQ's officer id, `<type>:<area>` (e.g. `release:example-web`).
ID string `json:"id"`
// HQURL is HQ's API base, including `/api/v1` (e.g.
// `https://hq.example.com/api/v1`). Paths are appended to it.
HQURL string `json:"hq_url"`
// MaxInstances is how many instances may run at once (1..MaxInstancesCap).
MaxInstances int `json:"max_instances"`
// IdleAfter is how long the officer must be idle — no claimable item and
// no live claim held by any of its instances — before its instances are
// scaled to zero.
IdleAfter time.Duration `json:"-"`
// PollInterval is how often HQ's open-items list is read when nothing
// else wakes the loop.
PollInterval time.Duration `json:"-"`
// Owner is the muster user the instance agents belong to (default 1, the
// operator). Row-level security scopes the agents to that user.
Owner int64 `json:"owner"`
// CCAccount optionally pins the Claude account instances run on; empty
// lets the account pool choose (an instance keeps its account until an
// account failover moves it, internal/ccfailover).
CCAccount string `json:"cc_account,omitempty"`
// CCFailover opts instances pinned by CCAccount in to account failover
// (internal/ccfailover): without it a pinned instance stays on its
// account when that account hits its limit. Unpinned instances fail over
// whatever it says (unless MUSTER_AGENT_CC_FAILOVER=off).
CCFailover bool `json:"cc_failover,omitempty"`
// Model is the model the instances' Claude Code sessions run ("opus", a
// full model id); "" leaves the account's default.
Model string `json:"model,omitempty"`
// Image, when set, is the runner image the instances' pods run instead of
// the deployment's claude-code image (image.go): pinned, and in a
// repository ImageRegistriesEnv allows. For a tiered officer it is the
// pool's (tiers.<pool>.image), as Model is. "" runs the deployment's.
Image string `json:"image,omitempty"`
// Repo is the GitHub repository (owner/name) the officer's instances act
// on as their OWN repository for connectors; "" for none. It is what the
// GitHub App connector mints a token for (internal/api Server.agentRepo
// feeds it to connectors.Caller.Repo), so an approved `github` grant gives
// an instance exactly this one repository — read-only on a deployment
// with MUSTER_GITHUB_APP_ACCESS=read. It is NOT checked out: the instance
// reads it through muster's connector proxy.
Repo string `json:"repo,omitempty"`
// ReadRepos are further GitHub repositories (owner/name) the officer's
// instances may READ through the same `github` connector: a proxied request
// that targets one of them is served with a READ-ONLY installation token
// minted for that one repository (internal/githubapp App.Credential),
// whatever MUSTER_GITHUB_APP_ACCESS says. Lowercased, sorted and unique —
// so a reordered or re-cased declaration is the same set and does not
// re-open an approved grant (connectors.RepoScope). Requires Repo, never
// holds it, at most MaxReadRepos, and accepted beside any ship stage (never
// one of ship.repos).
ReadRepos []string `json:"read_repos,omitempty"`
// ReadGrant is how ReadRepos are granted: "" (the default) is the
// per-instance `github` approval above; ReadGrantStanding serves them with
// NO approval, anonymously, reads only, each verified PUBLIC with GitHub
// (connectors' standing public read). Standing is accepted only on a
// builtin officer, never beside ship, and does not need Repo.
// StandingReadRepos and ApprovalReadRepos are the one read of it.
ReadGrant string `json:"read_grant,omitempty"`
// ReadAt is where a standing read is pointed: "" names no ref (the
// default branch), ReadAtRelease names muster's own release tag
// (ReleaseTag). Accepted only with ReadGrantStanding.
ReadAt string `json:"read_at,omitempty"`
// ReleaseTag is the git tag of the muster release this server runs
// ("v0.221.0"), stamped by StampReleaseTag for an officer with ReadAt
// ReadAtRelease; "" when the build's version is not a release.
ReleaseTag string `json:"-"`
// Ship, when set, lets the officer push branches, open pull requests, and
// (by stage) merge its own pull requests and tag releases in Repo — every
// write filtered or performed by muster (ship.go). nil for every other
// officer, whose GitHub access stays read-only.
Ship *Ship `json:"-"`
// CILogs, when set (a shipping officer only), offers officer_ci_logs: the
// failing tests and error lines of the officer's own pull request's CI,
// read by muster-server from a Tekton namespace (cilogs.go).
CILogs *CILogs `json:"-"`
// Transcript, when set and enabled, forwards each instance's live session
// transcript to HQ while it holds a claimed item
// (internal/officers/transcript). nil (the default) forwards nothing.
Transcript *Transcript `json:"-"`
// Connectors are the connectors, besides `github`, the officer's instances
// may REQUEST (internal/api officerConnectorRefusal), by name — e.g. a
// postgres connector for read-only SQL. Declaring one grants nothing: each
// instance's request is still decided explicitly by the owner, and is never
// approved from a shared approval. Sorted and deduplicated.
Connectors []string `json:"connectors,omitempty"`
// Tiers, when set, splits the officer's instances into two pools — routine
// and judgement — each with its own model and max instances (tiers.go).
// nil (no `tiers` block) is one untiered pool: today's behaviour.
Tiers *Tiers `json:"-"`
// Tier is the pool this value describes: "" for an untiered officer, else
// TierJudgement or TierRoutine (Officer.Pool). Parse returns a tiered
// officer as its judgement pool.
Tier string `json:"-"`
// LLM, when set, lets the officer's ROUTINE pool reach its model
// (tiers.routine.model) through muster's LLM proxy (llm.go,
// internal/llmproxy), within the daily USD budget and per-item token cap
// it holds. It needs Tiers. nil (the default) refuses every proxy request
// of the routine pool. The judgement pool's own block is
// Tiers.Judgement.LLM (tiers.judgement.llm); Officer.PoolLLM answers either.
LLM *LLM `json:"-"`
// Kube, when set, offers the officer's JUDGEMENT instances
// officer_kube_read over the clusters it names (kube.go). It needs Tiers.
// nil (the default) offers no cluster read.
Kube *Kube `json:"-"`
// Backend is which officer backend serves the officer: BackendHQ (an
// external HQ over HTTPS with the officer's token, the default) or
// BackendBuiltin (muster's own Postgres, internal/officers/builtin).
// Parse sets it; "" reads as BackendHQ (Officer.BackendKind).
Backend string `json:"-"`
// Runtime is where the officer's instances run: RuntimePod (a pod per
// instance, through the provisioner: the default) or RuntimeHost (a
// host-spawned Claude Code window per instance on the mirror host Host,
// docs/design/officers-on-hosts.md). Parse sets it; "" reads as RuntimePod
// (Officer.OnHost).
Runtime string `json:"-"`
// Host is the mirror host (its token's name) a RuntimeHost officer's
// instances are spawned on; "" for a pod officer.
Host string `json:"-"`
// InstanceSlug is a DB-declared officer's server-allocated agent slug
// (officer_defs.instance_slug, migration 0136): globally unique, so two
// owners' `marketing:main` never build the same agent name. "" for an env
// officer, whose slug is Slug(ID). Read it through AgentSlug.
InstanceSlug string `json:"instance_slug,omitempty"`
// ManagedBy is where the officer is declared: ManagedByEnv
// (MUSTER_OFFICERS, read-only through the API) or ManagedByDB (officer_defs,
// created, changed and deleted through the admin API with no restart).
// "" reads as ManagedByEnv.
ManagedBy string `json:"managed_by,omitempty"`
// Budget is a builtin officer's daily spend cap and routine batching
// (`daily_budget_usd`, `routine_kinds`, `routine_wake_at`; budget.go).
// The zero value caps nothing and batches nothing.
Budget Budget `json:"-"`
// contains filtered or unexported fields
}
Officer is one declared officer: the HQ identity muster runs instances for.
func Parse ¶
Parse reads MUSTER_OFFICERS — a JSON array of officer declarations — and each declared officer's token through getenv. Empty raw is no officers.
It refuses (and names the reason) rather than guessing: an unknown field, an id that is not `<type>:<area>`, two officers whose slugs collide, a missing token, a base URL that is not http(s), a repo that is not a GitHub owner/name (github.ValidRepoName, the task repositories' own check), a bad read_repos (parseReadRepos). Instances always run on the claude-code kind; there is no kind field.
namespacePrefix is the deployment's resolved MUSTER_AGENT_NAMESPACE_PREFIX: an officer whose highest instance name would not fit a namespace under it is refused here, at boot, rather than when its first instance is created.
func ParseInstance ¶ added in v0.233.0
ParseInstance is parseInstance, for a backend outside this package that books per instance (builtin.Backend.PutUsage).
func ProxyAgent ¶ added in v0.192.0
ProxyAgent is THE rule for whether agent name may use officer o's LLM proxy: name is an instance of one of o's pools that has an `llm` block (Officer.PoolLLM) — the routine pool with the officer's top-level `llm`, the judgement pool with tiers.judgement.llm — by the registry's own naming rule (parseInstance). It answers that pool (whose model the proxy pins and whose block it spends) and the instance's number in it. An untiered officer's instance, an instance of a pool without a block, or any other name is not. o may be the officer or either of its pools.
func StampReleaseTag ¶ added in v0.221.0
StampReleaseTag returns list with ReleaseTag set, from version (the server's build version), on every officer whose standing read is pointed at muster's release (ReadAt ReadAtRelease).
func (Officer) AgentSlug ¶ added in v0.236.0
AgentSlug is the fragment o's instance agent names are built on (`officer-<slug>-<n>`): its InstanceSlug when it is DB-declared (allocated by the server, globally unique across owners: agents.name is UNIQUE, and two owners may each declare `marketing:main`), else Slug(o.ID).
🔴 NAMES CANNOT COLLIDE BETWEEN TWO DISTINCT SLUGS. An instance name is `officer-` + slug + `-` + digits (or `r` + digits). If two slugs S1 ≠ S2 built the same name, one would be the other plus `-<x>`, and the shorter's number would then contain a `-` — which a number never does. So distinct slugs (unique within env, unique within the DB, and a DB slug never equal to an env one: SlugCandidates) are all ForAgentName needs.
func (Officer) ApprovalReadRepos ¶ added in v0.221.0
ApprovalReadRepos are o's read_repos served under the per-instance `github` grant (connectors.Caller.ReadRepos, part of the grant's RepoScope): all of them, unless they are standing (StandingReadRepos), when none are.
func (Officer) BackendKind ¶ added in v0.210.0
BackendKind is the officer's backend: BackendBuiltin, or BackendHQ (also for an Officer built outside Parse with no Backend). THE one read of Officer.Backend.
func (Officer) BypassesBudget ¶ added in v0.242.0
BypassesBudget reports whether item it is work for o even with its daily budget spent: its owner enqueued it, and its kind is not routine. THE rule; the built-in claim-next spells the same in SQL (builtin.overBudgetClaimable).
func (Officer) ChatIdleStop ¶ added in v0.249.0
ChatIdleStop is how long an instance of o may go with no chat turn, claim or prompt before it is stopped: its declared `chat_idle_stop`, or DefaultChatIdleStop.
func (Officer) ChatMaxInstances ¶ added in v0.249.0
ChatMaxInstances is the chat ceiling of pool o: chats run on its instances 1..ChatMaxInstances — its declared `chat_max_instances`, or DefaultChatMaxInstances.
func (Officer) ChatOnly ¶ added in v0.249.0
ChatOnly reports whether instance n of pool o serves chats only: numbered past max_instances, within the chat ceiling. Its primary takes no queue work (officer_claim refuses it).
func (Officer) ChatSessions ¶ added in v0.247.0
ChatSessions is how many chat lanes each of o's instances runs at once: its declared `chat_sessions`, or DefaultChatSessions.
func (Officer) ChatsPool ¶ added in v0.247.0
ChatsPool reports whether pool o runs its officer's chats: an untiered officer, or a tiered officer's judgement pool. A routine pool never does — a chat has the officer's whole charter and access.
func (Officer) DeclaredChatSessions ¶ added in v0.247.0
DeclaredChatSessions is o's `chat_sessions` as declared, 0 when it declares none: what the instance pod's CCD_MAX_SESSIONS is set to (internal/api OfficerClaudeCodeSession) — 0 leaves the pod's spec, and ccd's default, as they were.
func (Officer) FreshSessionPerItem ¶ added in v0.163.0
FreshSessionPerItem is THE rule for whether pool o works each item in a NEW Claude Code conversation (tiers.<pool>.fresh_session_per_item): false for an untiered officer, and for a tiered officer not read as one of its pools.
Everything the option changes branches here, and nowhere else:
- RepromptText: the wake loop's prompt of an idle instance is the kickoff, never "as before" (a new conversation has no "before");
- KickoffText: the kickoff ends with the one-item note (freshNote);
- internal/api OfficerTurnContext: every turn muster sends the instance — the wake loop's prompt and the kickoff deliverer's first turn — carries agents.HeaderCCNewConversation, on which the pod's ccd starts a new conversation (the old transcript kept) before it pastes the turn;
- internal/api officer_claim: one item per conversation — the conversation is marked at its first successful claim and refused any other item before HQ, however that hold ends, until ccd confirms a new conversation took a turn muster sent;
- InstanceState.Spent (internal/api Instances): such an instance, holding nothing, is prompted without waiting out RepromptAfter.
🔴 AN UNTIERED OFFICER IS NOT OFFERED IT. An officer without `tiers` is exactly today's officer (see the top of this file); the option lives with the pool settings it sits beside.
func (Officer) FromDB ¶ added in v0.236.0
FromDB reports whether o is DB-declared (officer_defs, migration 0136).
func (Officer) HasSessionCap ¶ added in v0.146.0
HasSessionCap reports whether any pool of o is capped.
func (Officer) InstanceLabel ¶ added in v0.141.0
InstanceLabel is how instance n of this pool is named in text: "r<n>" in the routine pool, "<n>" otherwise.
func (Officer) InstanceName ¶ added in v0.141.0
InstanceName is the agent name of instance n of this pool: `-r<n>` for the routine pool, `-<n>` otherwise (InstanceName).
func (Officer) IsBuiltin ¶ added in v0.210.0
IsBuiltin reports whether muster's built-in backend serves o.
func (Officer) IsRoutineKind ¶ added in v0.242.0
IsRoutineKind reports whether kind is one of o's routine_kinds: listed, exactly.
func (Officer) ItemCap ¶ added in v0.155.0
ItemCap is the pool's wall-time cap on one item: 0 (none) unless o is the judgement pool of a tiered officer that declares max_item_minutes.
func (Officer) Key ¶ added in v0.236.0
Key is o's registry key: unique across every officer the registry holds, env and DB alike. An env officer's is its ID (always `<type>:<area>`, so it contains a `:`); a DB-declared officer's is its InstanceSlug (never a `:`), because two owners may each declare the same ID. The wake loop's state, the backend cache and Registry.Get are keyed on it.
func (Officer) KubeCluster ¶ added in v0.153.0
func (o Officer) KubeCluster(name string) (KubeCluster, bool)
KubeCluster is the declared cluster named name, for o's instances.
func (Officer) KubeClusters ¶ added in v0.153.0
func (o Officer) KubeClusters() []KubeCluster
KubeClusters is the clusters o's instances may read: the `kube` block's clusters that have an allowlist, for the judgement pool of an officer that declares one; nil otherwise.
func (Officer) OnHost ¶ added in v0.223.0
OnHost reports whether o's instances run as host-spawned sessions (RuntimeHost) rather than pods. THE one read of Officer.Runtime: the fleet, the tool rule, the kickoff and the boot lines all ask it.
func (Officer) OverBudget ¶ added in v0.242.0
OverBudget reports whether spent has reached o's daily budget. An officer with no budget is never over it.
func (Officer) Pool ¶ added in v0.141.0
Pool is o as tier's pool: Tier, Model and MaxInstances are the pool's, everything else the officer's. An untiered officer is its only pool, whatever tier says.
func (Officer) PoolLLM ¶ added in v0.192.0
PoolLLM is the `llm` block of the pool o is: the officer's top-level `llm` for the routine pool, tiers.judgement.llm for the judgement pool, nil for an untiered officer. o read as the officer itself is its judgement pool.
func (Officer) Pools ¶ added in v0.141.0
Pools is the officer's instance pools: the officer itself when it is untiered, else its judgement pool then its routine pool.
func (Officer) RoutineDue ¶ added in v0.242.0
RoutineDue is the not_before an item of kind enqueued for o at now is given: nil for a kind that is not routine; for a routine kind, the next routine_wake_at — today's when now is before it, else tomorrow's. Every routine item enqueued between two wakes thus gets the SAME not_before.
func (Officer) RunsChatInstances ¶ added in v0.249.0
RunsChatInstances reports whether pool o may run chat instances: a pool that runs chats (ChatsPool: an untiered officer or the judgement pool), on pods (a host instance has no ccd) and of an HQ officer (the built-in backend serves no chat routes).
func (Officer) RuntimeKind ¶ added in v0.223.0
RuntimeKind is o's runtime: RuntimeHost, or RuntimePod (also for an Officer built outside Parse with no Runtime).
func (Officer) SessionCap ¶ added in v0.146.0
SessionCap is a pool's daily judgement-session cap: 0 (no cap) unless o is the judgement pool of a tiered officer that declares one.
func (Officer) Slots ¶ added in v0.249.0
Slots is how many instance numbers pool o has: 1..Slots. Queue work uses 1..MaxInstances of them; chats 1..ChatMaxInstances. 🔴 ONE NUMBERING: a chat instance is the pool's own instance n, so its agent name, volume and pod are the queue's instance n's; the numbers past max_instances are chat-only (ChatOnly). Only a pool that may run chats has them (RunsChatInstances); every other pool's slots are its max_instances.
func (Officer) StandingReadRepos ¶ added in v0.221.0
StandingReadRepos are the repositories o's instances READ through the standing public read (connectors.Caller.PublicReadRepos): its read_repos when it is a builtin officer that declares read_grant "standing" and does not ship; nil for every other officer. 🔴 THE ONE RULE for who gets a standing read: internal/api reads it, and nothing else decides it.
func (Officer) Token ¶
Token returns the officer's HQ token. Its only callers are the HQ client and tests asserting it does not appear where it must not.
func (Officer) TranscriptEnabled ¶ added in v0.127.0
TranscriptEnabled reports whether o's instances' transcripts are forwarded to HQ. THE one switch: the forwarder asks it before every read and post.
func (Officer) UsesLLMProxy ¶ added in v0.192.0
UsesLLMProxy reports whether any of o's pools reaches its model through the LLM proxy.
func (Officer) WithChatIdleStop ¶ added in v0.249.0
WithChatIdleStop returns o declaring a chat-idle stop of d (tests, and wiring outside Parse).
func (Officer) WithChatMaxInstances ¶ added in v0.249.0
WithChatMaxInstances returns o declaring a chat ceiling of n (tests, and wiring outside Parse).
func (Officer) WithChatSessions ¶ added in v0.247.0
WithChatSessions returns o declaring n chat sessions (tests, and wiring outside Parse).
func (Officer) WithRaisedCap ¶ added in v0.251.0
WithRaisedCap is o with its daily budget for one UTC day raised to usd (its owner's "Raise cap for today", builtin.Store.RaiseCapToday). THE rule for a raise: it only ever RAISES — usd at or below the declared budget changes nothing, and an officer with no budget (0, uncapped) is never given one. Every reader of a raise (the wake loop, the claim, the pages) applies it through here, then asks OverBudget.
type Overrun ¶ added in v0.155.0
type Overrun struct {
Item Item
// N is the holder's instance number; Up whether it is up (then stopped).
N int
Up bool
// Held is how long the item has been held: now less HQ's claimed_at.
Held time.Duration
}
Overrun is a live claim past its pool's wall-time cap (Officer.ItemCap).
type PGConnectorBlockStore ¶ added in v0.245.0
type PGConnectorBlockStore struct {
// contains filtered or unexported fields
}
PGConnectorBlockStore is ConnectorBlockStore on officer_connector_blocks (migration 0148), under row-level security: ctx must act as the officer's owner.
func NewPGConnectorBlockStore ¶ added in v0.245.0
func NewPGConnectorBlockStore(pool *pgxpool.Pool) *PGConnectorBlockStore
NewPGConnectorBlockStore is the store over pool.
func (*PGConnectorBlockStore) BlocksForGrant ¶ added in v0.245.0
func (s *PGConnectorBlockStore) BlocksForGrant(ctx context.Context, officer string, grant int64, since time.Time, limit int) ([]ConnectorBlock, error)
BlocksForGrant implements ConnectorBlockStore.
func (*PGConnectorBlockStore) RecordBlock ¶ added in v0.245.0
func (s *PGConnectorBlockStore) RecordBlock(ctx context.Context, b ConnectorBlock) error
RecordBlock implements ConnectorBlockStore.
func (*PGConnectorBlockStore) SettleBlock ¶ added in v0.245.0
func (s *PGConnectorBlockStore) SettleBlock(ctx context.Context, officer string, grant int64, item ItemID, at time.Time) error
SettleBlock implements ConnectorBlockStore.
func (*PGConnectorBlockStore) SettleBlocks ¶ added in v0.284.0
func (s *PGConnectorBlockStore) SettleBlocks(ctx context.Context, officer string, grant int64, before, at time.Time) (int, error)
SettleBlocks implements ConnectorBlockStore.
func (*PGConnectorBlockStore) UnsettledGrants ¶ added in v0.284.0
func (s *PGConnectorBlockStore) UnsettledGrants(ctx context.Context, officer string, limit int) ([]int64, error)
UnsettledGrants implements ConnectorBlockStore.
type PGHostSpawnStore ¶ added in v0.223.0
type PGHostSpawnStore struct {
// contains filtered or unexported fields
}
PGHostSpawnStore is HostSpawnStore over muster's Postgres.
func NewPGHostSpawnStore ¶ added in v0.223.0
func NewPGHostSpawnStore(pool *pgxpool.Pool) *PGHostSpawnStore
NewPGHostSpawnStore is the store over pool.
func (*PGHostSpawnStore) CountHostSpawnsSince ¶ added in v0.238.0
func (s *PGHostSpawnStore) CountHostSpawnsSince(ctx context.Context, officer string, since time.Time) (int, error)
CountHostSpawnsSince implements HostSpawnStore.
func (*PGHostSpawnStore) HostSpawnByID ¶ added in v0.223.0
HostSpawnByID implements HostSpawnStore.
func (*PGHostSpawnStore) HostSpawnForSession ¶ added in v0.223.0
func (s *PGHostSpawnStore) HostSpawnForSession(ctx context.Context, host, session string) (HostSpawn, error)
HostSpawnForSession implements HostSpawnStore.
func (*PGHostSpawnStore) HostSpawnIDs ¶ added in v0.223.0
func (s *PGHostSpawnStore) HostSpawnIDs(ctx context.Context, host string, ids []int64) (map[int64]bool, error)
HostSpawnIDs implements HostSpawnStore.
func (*PGHostSpawnStore) HostSpawnsInWindows ¶ added in v0.236.0
func (s *PGHostSpawnStore) HostSpawnsInWindows(ctx context.Context, host string, windows []string) ([]HostSpawn, error)
HostSpawnsInWindows implements HostSpawnStore.
func (*PGHostSpawnStore) InsertHostSpawn ¶ added in v0.223.0
func (s *PGHostSpawnStore) InsertHostSpawn(ctx context.Context, officer, instance, host string) (HostSpawn, error)
InsertHostSpawn implements HostSpawnStore.
func (*PGHostSpawnStore) LatestHostSpawns ¶ added in v0.223.0
func (s *PGHostSpawnStore) LatestHostSpawns(ctx context.Context, officer string) (map[string]HostSpawn, error)
LatestHostSpawns implements HostSpawnStore.
func (*PGHostSpawnStore) LendHostSpawn ¶ added in v0.225.0
LendHostSpawn implements HostSpawnLender. The WHERE names the acting person as the owner, so a row only LENT to them is not theirs to re-lend (the UPDATE would be refused by owner_isolation anyway; this says "no such row").
func (*PGHostSpawnStore) MarkHostSpawnClaimed ¶ added in v0.238.0
func (s *PGHostSpawnStore) MarkHostSpawnClaimed(ctx context.Context, id int64, host string) (bool, error)
MarkHostSpawnClaimed implements HostSpawnStore.
func (*PGHostSpawnStore) ObserveHostListing ¶ added in v0.236.0
func (s *PGHostSpawnStore) ObserveHostListing(ctx context.Context, host string, windows []string, settled time.Time) error
ObserveHostListing implements HostSpawnStore. Two statements, each its own rule: a listed window resets its row (a closed row never reopens), an unlisted one counts its settled row up to the close. 🔴 windows is never passed as NULL: `= ANY(NULL)` is NULL, and NOT NULL would skip every row.
func (*PGHostSpawnStore) OpenUnclaimedNotices ¶ added in v0.238.0
func (s *PGHostSpawnStore) OpenUnclaimedNotices(ctx context.Context) ([]HostSpawn, error)
OpenUnclaimedNotices implements HostSpawnStore.
func (*PGHostSpawnStore) RecordHostSpawnRefusal ¶ added in v0.223.0
func (s *PGHostSpawnStore) RecordHostSpawnRefusal(ctx context.Context, id int64, host, refusal string) (bool, error)
RecordHostSpawnRefusal implements HostSpawnStore.
func (*PGHostSpawnStore) RecordHostSpawnSession ¶ added in v0.223.0
func (s *PGHostSpawnStore) RecordHostSpawnSession(ctx context.Context, id int64, host, window, session string) (bool, error)
RecordHostSpawnSession implements HostSpawnStore.
func (*PGHostSpawnStore) RecordHostSpawnWindow ¶ added in v0.223.0
func (s *PGHostSpawnStore) RecordHostSpawnWindow(ctx context.Context, id int64, host, window, session string) (bool, error)
RecordHostSpawnWindow implements HostSpawnStore.
func (*PGHostSpawnStore) SetUnclaimedNotice ¶ added in v0.238.0
SetUnclaimedNotice implements HostSpawnStore.
func (*PGHostSpawnStore) SettleUnclaimedNotice ¶ added in v0.238.0
SettleUnclaimedNotice implements HostSpawnStore.
func (*PGHostSpawnStore) VisibleHostSpawns ¶ added in v0.225.0
func (s *PGHostSpawnStore) VisibleHostSpawns(ctx context.Context, w SpawnWindow, limit int) ([]HostSpawn, error)
VisibleHostSpawns implements HostSpawnLender.
type PGPRLoopStore ¶ added in v0.210.0
type PGPRLoopStore struct {
// contains filtered or unexported fields
}
PGPRLoopStore is PRLoopStore on officer_pr_loops (migration 0119), under row-level security: ctx must act as the officer's owner.
func NewPGPRLoopStore ¶ added in v0.210.0
func NewPGPRLoopStore(pool *pgxpool.Pool) *PGPRLoopStore
NewPGPRLoopStore is the store over pool.
func (*PGPRLoopStore) PRLoopAnnounced ¶ added in v0.210.0
func (s *PGPRLoopStore) PRLoopAnnounced(ctx context.Context, officer, repo string, pr int, head string) error
PRLoopAnnounced implements PRLoopStore.
func (*PGPRLoopStore) PRLoopSettle ¶ added in v0.210.0
func (s *PGPRLoopStore) PRLoopSettle(ctx context.Context, officer, repo string, pr int, state string) error
PRLoopSettle implements PRLoopStore.
func (*PGPRLoopStore) PRLoopState ¶ added in v0.210.0
func (s *PGPRLoopStore) PRLoopState(ctx context.Context, officer, repo string, pr int) (string, error)
PRLoopState implements PRLoopStore.
func (*PGPRLoopStore) PRLoopsClaim ¶ added in v0.210.0
func (s *PGPRLoopStore) PRLoopsClaim(ctx context.Context, officer string, notBefore time.Time) (claimed, expired []PRLoop, err error)
PRLoopsClaim implements PRLoopStore: each UPDATE takes the row locks of the rows it changes and re-reads `state = 'pending'` after waiting for a concurrent claimer, so of two replicas sweeping at once only one claims a row.
func (*PGPRLoopStore) PRLoopsInLoop ¶ added in v0.210.0
PRLoopsInLoop implements PRLoopStore.
type PGPRQueueStore ¶ added in v0.257.0
type PGPRQueueStore struct {
// contains filtered or unexported fields
}
PGPRQueueStore is PRQueueStore on officer_pr_queue (migration 0169), under row-level security: ctx must act as the officer's owner.
func NewPGPRQueueStore ¶ added in v0.257.0
func NewPGPRQueueStore(pool *pgxpool.Pool) *PGPRQueueStore
NewPGPRQueueStore is the store over pool.
func (*PGPRQueueStore) PRQueueAdd ¶ added in v0.257.0
func (s *PGPRQueueStore) PRQueueAdd(ctx context.Context, officer string, q QueuedPR) (QueuedPR, error)
PRQueueAdd implements PRQueueStore: ONE upsert on the (owner, officer, repository, branch) key. A queued row keeps queued_at; a settled one is queued again with queued_at now. Fresh is an INSERT (xmax = 0), or an update of a row the statement's snapshot (prev) shows settled: a concurrent Add that lost the insert race to a new row reads it as a refresh, not fresh.
func (*PGPRQueueStore) PRQueueList ¶ added in v0.257.0
PRQueueList implements PRQueueStore.
func (*PGPRQueueStore) PRQueueMark ¶ added in v0.259.0
func (s *PGPRQueueStore) PRQueueMark(ctx context.Context, officer string, id int64, head, note string) (bool, error)
PRQueueMark implements PRQueueStore: one conditional UPDATE.
type PGPublicBranchStore ¶ added in v0.237.0
type PGPublicBranchStore struct {
// contains filtered or unexported fields
}
PGPublicBranchStore is PublicBranchStore on officer_public_branches (migration 0138), under row-level security: ctx must act as the officer's owner.
func NewPGPublicBranchStore ¶ added in v0.237.0
func NewPGPublicBranchStore(pool *pgxpool.Pool) *PGPublicBranchStore
NewPGPublicBranchStore is the store over pool.
func (*PGPublicBranchStore) PublicBranchItem ¶ added in v0.237.0
func (s *PGPublicBranchStore) PublicBranchItem(ctx context.Context, officer, repo, branch string) (int, bool, error)
PublicBranchItem implements PublicBranchStore.
func (*PGPublicBranchStore) PublicBranchMint ¶ added in v0.237.0
func (s *PGPublicBranchStore) PublicBranchMint(ctx context.Context, officer, repo string, item int, branch string) (string, error)
PublicBranchMint implements PublicBranchStore: an INSERT that keeps an existing row for the item (the unique key), then the row that holds.
func (*PGPublicBranchStore) PublicBranches ¶ added in v0.237.0
func (s *PGPublicBranchStore) PublicBranches(ctx context.Context, officer, repo string) ([]string, error)
PublicBranches implements PublicBranchStore.
type PGRestartStore ¶ added in v0.257.0
type PGRestartStore struct {
// contains filtered or unexported fields
}
PGRestartStore is RestartStore on officer_auto_restarts (migration 0170), under row-level security: ctx must act as the officer's owner (Config.RestartContext).
func NewPGRestartStore ¶ added in v0.257.0
func NewPGRestartStore(pool *pgxpool.Pool) *PGRestartStore
NewPGRestartStore is the store over pool.
func (*PGRestartStore) RecordRestart ¶ added in v0.257.0
func (s *PGRestartStore) RecordRestart(ctx context.Context, officer, day, instance string, at time.Time, errText string) error
RecordRestart implements RestartStore: one more restart, in one statement (an upsert adding 1), so two replicas restarting at once both count.
func (*PGRestartStore) RestartDay ¶ added in v0.257.0
func (s *PGRestartStore) RestartDay(ctx context.Context, officer, day string) (map[string]RestartRecord, error)
RestartDay implements RestartStore.
func (*PGRestartStore) SetRestartHeld ¶ added in v0.257.0
func (s *PGRestartStore) SetRestartHeld(ctx context.Context, officer, day, instance string, held bool, errText string) error
SetRestartHeld implements RestartStore. Clearing keeps the row's last error: it is the record of the episode that ended.
type PGSessionStore ¶ added in v0.146.0
type PGSessionStore struct {
// contains filtered or unexported fields
}
PGSessionStore is SessionStore on officer_judgement_sessions (migration 0082), under row-level security: ctx must act as the officer's owner.
func NewPGSessionStore ¶ added in v0.146.0
func NewPGSessionStore(pool *pgxpool.Pool) *PGSessionStore
NewPGSessionStore is the store over pool.
func (*PGSessionStore) AdmitSession ¶ added in v0.146.0
func (s *PGSessionStore) AdmitSession(ctx context.Context, officer, day, entry string, limit int, now time.Time) (Admission, error)
AdmitSession implements SessionStore in ONE transaction: make sure the day's row exists, LOCK it (SELECT … FOR UPDATE reads its latest committed version, after any concurrent admission commits), and decide on that: already there → admitted, not inserted; under the cap → append (dropping stale pending entries while the row is held), admitted and inserted; otherwise refused.
func (*PGSessionStore) ReleaseSession ¶ added in v0.146.0
func (s *PGSessionStore) ReleaseSession(ctx context.Context, officer, day, entry string) error
ReleaseSession implements SessionStore.
func (*PGSessionStore) ResolveSession ¶ added in v0.146.0
func (s *PGSessionStore) ResolveSession(ctx context.Context, officer, day, token, entry string) error
ResolveSession implements SessionStore.
type PRContextArgs ¶ added in v0.190.0
PRContextArgs is officer_pr_context's arguments: {item_id, pr}.
func ParsePRContextArgs ¶ added in v0.190.0
func ParsePRContextArgs(raw []byte) (PRContextArgs, error)
ParsePRContextArgs decodes officer_pr_context's arguments strictly.
type PRContextBackend ¶ added in v0.209.0
type PRContextBackend interface {
PRContext(ctx context.Context, a PRContextArgs) ([]byte, error)
}
PRContextBackend reads a pull request's context for attribution.
type PRContextRouteUnavailableError ¶ added in v0.190.0
PRContextRouteUnavailableError: HQ answered the PR context route 404 without PRContextNotVisibleCode (an HQ older than the route). Final: retrying will not help until HQ is upgraded; it says nothing about the PR.
func (*PRContextRouteUnavailableError) Error ¶ added in v0.190.0
func (e *PRContextRouteUnavailableError) Error() string
type PRLoop ¶ added in v0.210.0
type PRLoop struct {
Repo string
PR int
HeadSHA string
State string
// AnnouncedAt is when the pull request was first announced (the sweep
// re-sends a pending one only within its age bound).
AnnouncedAt time.Time
}
PRLoop is one pull request's announcement.
type PRLoopStore ¶ added in v0.210.0
type PRLoopStore interface {
// PRLoopAnnounced records repo#pr (at head) as 'sending' — the announcing
// process's claim — unless it is already recorded, which keeps its state.
PRLoopAnnounced(ctx context.Context, officer, repo string, pr int, head string) error
// PRLoopSettle sets repo#pr's state.
PRLoopSettle(ctx context.Context, officer, repo string, pr int, state string) error
// PRLoopsClaim fails officer's pending announcements first made before
// notBefore (returned as expired), and CLAIMS the rest — pending ->
// sending, atomically, so a concurrent claimer gets none of them —
// returning them as claimed.
PRLoopsClaim(ctx context.Context, officer string, notBefore time.Time) (claimed, expired []PRLoop, err error)
// PRLoopState is repo#pr's state ("" when it was never announced).
PRLoopState(ctx context.Context, officer, repo string, pr int) (string, error)
// PRLoopsInLoop lists officer's pull requests in a loop.
PRLoopsInLoop(ctx context.Context, officer string) ([]PRLoop, error)
}
PRLoopStore keeps the announcements, per officer. ctx acts as the officer's owner (the database store is under row-level security).
type PROpened ¶ added in v0.210.0
type PROpened struct {
// Repo is owner/name; PR the number; HeadSHA the 40-hex head the pull
// request was created on; HeadRef its branch; Base its base branch;
// Author its author's login as GitHub reports it (an App's bot is
// `<slug>[bot]`).
Repo string `json:"repo"`
PR int `json:"pr"`
HeadSHA string `json:"head_sha"`
HeadRef string `json:"head_ref"`
Base string `json:"base"`
Author string `json:"author"`
}
PROpened is the body of POST /officers/{id}/pr-opened: a pull request the officer just opened, which HQ may start a review loop for. Exactly these fields (HQ refuses unknown ones).
type PROpenedAnswer ¶ added in v0.210.0
type PROpenedAnswer struct {
Items []struct {
OfficerID string `json:"officer_id"`
ItemID ItemID `json:"item_id"`
Created bool `json:"created"`
} `json:"items"`
Skipped []json.RawMessage `json:"skipped"`
}
PROpenedAnswer is HQ's 200 to pr-opened: the loop items it created, and the officers it skipped (each with HQ's reason, kept raw).
type PRQueueStore ¶ added in v0.257.0
type PRQueueStore interface {
// PRQueueAdd queues q for officer (q's Repo, Branch, HeadSHA, Title, Body,
// Item and Instance; repo compared without case) and returns the row: a
// branch already queued keeps its place and takes q's head, title, body,
// item and instance; one settled before is queued again at the back.
PRQueueAdd(ctx context.Context, officer string, q QueuedPR) (QueuedPR, error)
// PRQueueList is officer's QUEUED rows in repo ("" for every repository),
// oldest first (queued_at, then id): the order the drain opens them in.
PRQueueList(ctx context.Context, officer, repo string) ([]QueuedPR, error)
// PRQueueSettle settles officer's row id to state (PRQueueOpened or
// PRQueueSkipped) with pr and note — only while it is still queued AT
// head: a create that refreshed it since is not settled by a decision
// made on the older head. ok false when nothing was settled.
PRQueueSettle(ctx context.Context, officer string, id int64, head, state string, pr int, note string) (bool, error)
// PRQueueMark sets note on officer's row id while it is still queued AT
// head and its note is still empty: ok true only for the call that set
// it, so a caller that tells HQ only on ok tells it once per row and
// head. A create that refreshes the row (PRQueueAdd) clears the note.
PRQueueMark(ctx context.Context, officer string, id int64, head, note string) (bool, error)
}
PRQueueStore keeps the queue, per officer. ctx acts as the officer's owner (the database store is under row-level security).
type PassResult ¶
type PassResult struct {
// Decision is the pass's decision for an untiered officer, or for a
// tiered officer's judgement pool.
Decision Decision
// Routine is a tiered officer's routine pool's decision (nil: untiered).
Routine *Decision
// Skipped is set when the pass read nothing because the officer is in
// backoff.
Skipped bool
// Err is the read failure that made the pass change nothing.
Err error
// ActErrs are failures acting on the decision (each logged).
ActErrs []error
}
PassResult is one pass's outcome, for logs and tests.
type PoolReport ¶ added in v0.198.0
type PoolReport struct {
Pool string `json:"pool"`
Model string `json:"model"`
MaxInstances int `json:"max_instances"`
MaxSessionsPerDay *int `json:"max_sessions_per_day"`
SessionsToday int `json:"sessions_today"`
SessionsDayResetsAt string `json:"sessions_day_resets_at"`
}
PoolReport is one pool on the wire.
- Pool is the pool's tier: TierRoutine, TierJudgement, or "" for an untiered officer (its one pool).
- Model is the pool's configured model ("" = the CLI's default).
- MaxInstances is the pool's max_instances.
- MaxSessionsPerDay is the judgement pool's daily session cap, null for a pool without one.
- SessionsToday is how many sessions the pool used on the current UTC day by THE counter that enforces the cap (JudgementLedger.Usage, the count the "judgement cap reached (N/M …)" line prints); 0 for an uncapped pool, which keeps no count.
- SessionsDayResetsAt is when that day ends: the next UTC midnight.
type PoolReset ¶ added in v0.257.0
PoolReset is a chat turn's usage-limit failure (Err, an ErrChatUsageLimit) with the earliest time an account in the officer's own pool stops being at its limit (At, ccpool.EarliestReset): ChatRateLimitedReplyFor quotes At, not the reset the CLI stated for the account the turn last tried. The failover tries the accounts in turn, so that one is often the one that resets LATEST. Err is unchanged for every errors.Is the runner makes.
type PoolsBackend ¶ added in v0.209.0
type PoolsBackend interface {
PutPools(ctx context.Context, r PoolsReport) error
}
PoolsBackend takes the officer's declared pools.
type PoolsPoster ¶ added in v0.198.0
type PoolsPoster interface {
PutPools(ctx context.Context, o Officer, r PoolsReport) error
}
PoolsPoster is the HQ side of the pools push.
func NewBackendPoolsPoster ¶ added in v0.209.0
func NewBackendPoolsPoster(b *Backends) PoolsPoster
NewBackendPoolsPoster is a PoolsPoster over each officer's own backend. A backend that does not serve pools answers ErrNotServed.
type PoolsReport ¶ added in v0.198.0
type PoolsReport struct {
Pools []PoolReport `json:"pools"`
ReportedAt string `json:"reported_at"`
// Dropped are the configured models sent as "" because HQ would refuse
// them (HQModelPattern); not on the wire.
Dropped []string `json:"-"`
}
PoolsReport is the pools route's body; Pools is never null.
func PoolsReportFor ¶ added in v0.198.0
func PoolsReportFor(ctx context.Context, o Officer, ledger *JudgementLedger, now time.Time) (PoolsReport, error)
PoolsReportFor is officer o's pools report at now: every pool of o (Officer.Pools: an untiered officer's one, else judgement then routine), each day's session count read through ledger (nil: none counted). A ledger read failure is returned: a report with a wrong sessions_today is not sent.
type PoolsReporter ¶ added in v0.198.0
type PoolsReporter struct {
// contains filtered or unexported fields
}
PoolsReporter pushes every declared officer's pools to its HQ: once when it starts (boot — MUSTER_OFFICERS is read only at boot, so a configuration change is a restart and this push carries it), then every Interval, so sessions_today stays fresh.
🔴 NO RETRY STORM: a 4xx is not retried (the same body would be refused again) and is logged once per officer until HQ's answer changes; a 5xx or no answer is retried after each Backoff wait, then left to the next tick.
func NewPoolsReporter ¶ added in v0.198.0
func NewPoolsReporter(cfg PoolsReporterConfig) (*PoolsReporter, error)
NewPoolsReporter builds a reporter.
func (*PoolsReporter) Run ¶ added in v0.198.0
func (r *PoolsReporter) Run(ctx context.Context)
Run pushes at once, then every Interval until ctx ends.
func (*PoolsReporter) Tick ¶ added in v0.198.0
func (r *PoolsReporter) Tick(ctx context.Context)
Tick pushes every officer's pools once.
type PoolsReporterConfig ¶ added in v0.198.0
type PoolsReporterConfig struct {
Officers []Officer
Poster PoolsPoster
Ledger *JudgementLedger
Logger *log.Logger
Now func() time.Time
Interval time.Duration
Backoff []time.Duration
Sleep func(ctx context.Context, d time.Duration) error
// RequestTimeout bounds one PUT (DefaultHQTimeout).
RequestTimeout time.Duration
}
PoolsReporterConfig is NewPoolsReporter's input. Zero values take the defaults; a nil Backoff is DefaultPoolsBackoff, an empty one no retry.
type Preflight ¶ added in v0.110.0
type Preflight struct {
WAL struct {
LastArchivedTime *time.Time `json:"last_archived_time"`
LastFailedTime *time.Time `json:"last_failed_time"`
FailedCount *int64 `json:"failed_count"`
} `json:"wal"`
LastBackupTime *time.Time `json:"last_backup_time"`
}
Preflight is HQ's view of its database's backup health before a release that adds a migration (POST /officers/{id}/preflight).
type PublicBranchStore ¶ added in v0.237.0
type PublicBranchStore interface {
// PublicBranchMint records branch as officer's for item in repo and
// returns it — or, when officer already has a branch for item in repo,
// returns THAT one and records nothing (one branch per item and
// repository).
PublicBranchMint(ctx context.Context, officer, repo string, item int, branch string) (string, error)
// PublicBranchItem is the item officer's branch in repo is for; ok false
// when muster holds no such record.
PublicBranchItem(ctx context.Context, officer, repo, branch string) (item int, ok bool, err error)
// PublicBranches lists officer's branches in repo.
PublicBranches(ctx context.Context, officer, repo string) ([]string, error)
}
PublicBranchStore keeps the public branches, per officer. ctx acts as the officer's owner (the database store is under row-level security).
type QueuedPR ¶ added in v0.257.0
type QueuedPR struct {
ID int64
Repo string
Branch string
// HeadSHA is the branch's head when the create was (last) asked for: the
// drain opens the pull request only while the branch is still there.
HeadSHA string
Title string
Body string
// Item is the HQ item the branch is for; Instance the officer instance
// that asked.
Item int
Instance string
State string
// PR is the pull request muster opened (state opened); Note why it was
// skipped — or, on a row still queued, what HQ was told about why it
// waits (PRQueueMark), so it is told once.
PR int
Note string
QueuedAt time.Time
// Fresh is set on PRQueueAdd's answer only: true when that Add made the
// row queued — a new row, or a settled one queued again — and false when
// it refreshed a row that was already queued (the cap-triggered close
// runs for a fresh one only).
Fresh bool
}
QueuedPR is one create the open cap held back.
type QuietHours ¶ added in v0.110.0
type QuietHours struct {
Loc *time.Location
// Start and End are minutes after local midnight; Start > End wraps
// midnight (22:00-08:00).
Start, End int
Weekends bool
}
QuietHours are local hours (and optionally weekends) with no officer tag.
type RaisedCapBackend ¶ added in v0.251.0
type RaisedCapBackend interface {
RaisedCapToday(ctx context.Context, now time.Time) (float64, error)
}
RaisedCapBackend is a backend whose officer's daily budget its owner may raise for one UTC day (builtin.Backend): the raised cap for now's UTC day, 0 for none.
type ReadBudget ¶ added in v0.153.0
type ReadBudget struct {
// contains filtered or unexported fields
}
ReadBudget counts reads per (officer, item).
func NewReadBudget ¶ added in v0.153.0
func NewReadBudget(perItem int, now func() time.Time) *ReadBudget
NewReadBudget is a budget of perItem reads per item; now nil is time.Now.
func (*ReadBudget) Refund ¶ added in v0.157.0
func (b *ReadBudget) Refund(officer string, item ItemID)
Refund gives back one read Spend counted of item by officer (a reserved read whose answer does not count, ReadCounted); never below 0.
type Reconciler ¶
type Reconciler struct {
// contains filtered or unexported fields
}
Reconciler runs the wake loop.
func NewReconciler ¶
func NewReconciler(cfg Config) (*Reconciler, error)
NewReconciler returns a loop over cfg's officers.
func (*Reconciler) Check ¶
func (r *Reconciler) Check(ctx context.Context, key string, force bool) PassResult
Check runs one pass for the officer keyed key (Officer.Key: an env officer's id) NOW, whatever its schedule, unless it is backing off and force is false.
func (*Reconciler) Done ¶
func (r *Reconciler) Done() <-chan struct{}
Done is closed once Run has returned: the shutdown drain joins the loop on it before waiting for re-prompt sends, so no pass can start one meanwhile.
func (*Reconciler) Due ¶ added in v0.236.0
func (r *Reconciler) Due(key string)
Due makes the officer keyed key due now: Run passes it on its next tick (RunTick) — and never while a pass for the same officer is still running (Reconciler.passing), so a pass it asks for never runs beside another pass for that officer. The admin API asks it after a pause or a resume, so the switch acts within a tick rather than a poll interval, and on every "run now" (an already-queued one included). Asked while a pass of the officer is running, it takes effect when that pass ends (officerState.dueAfterPass): one pass follows it. A Due-made officer is due "now", not first: Run orders it by when it was first seen due (passOrder), so asking again and again cannot jump officers that have waited longer.
func (*Reconciler) Refresh ¶ added in v0.288.0
func (r *Reconciler) Refresh(ctx context.Context, key string, between func(context.Context) error) (RefreshResult, error)
Refresh stops every up instance of the officer keyed key, releases what each held, runs between once, and starts each again with its first turn. The error is only a read that stopped it before it did anything, or between's failure (nothing stopped is then started); everything else that did not happen is in the result, never folded into an error, so a caller says exactly what failed.
func (*Reconciler) Run ¶
func (r *Reconciler) Run(ctx context.Context)
Run drives the loop until ctx ends. Call it at most once.
type RefreshResult ¶ added in v0.288.0
type RefreshResult struct {
// Restarted are the instances stopped and started again.
Restarted []string
// NotStopped are up instances whose stop failed: still running, in the
// conversation they had, and not started again.
NotStopped []string
// NotStarted are instances stopped and then not started again (their
// start failed, or the briefs could not be forgotten): the next pass
// starts what the queue needs.
NotStarted []string
// Unreleased are items a stopped instance held whose release failed: they
// go back to the queue when their claim lapses.
Unreleased []ItemID
}
RefreshResult is what Refresh did, exactly: which instances it restarted, and each thing that did not happen.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry is the declared officers, looked up by key or by instance agent name.
🔴 IT IS MUTABLE, BY ONE ATOMIC SWAP (Swap): every read takes one immutable snapshot, so a reader never sees half a roster, and every consumer — the wake loop (re-read every tick), hostOfficersOn, the mirror door's step-up gate, the tool binding (ForAgentName) — reads the roster LIVE. The env officers are fixed at boot; the DB-declared ones (migration 0136) are swapped in by internal/api's loader whenever they change, with no restart.
func NewRegistry ¶
NewRegistry indexes list. It does not re-validate: Parse did (and Declaration.Officer, for a DB-declared one).
func (*Registry) All ¶
All returns the declared officers, sorted by key (an env officer's key is its id).
func (*Registry) ForAgentName ¶
ForAgentName answers which declared officer an agent named name is an instance of, and which instance (1..its pool's MaxInstances). It is THE binding rule: the MCP tools act for the officer this returns and no other, and an agent whose name it does not parse is not an officer instance at all.
The officer returned is the instance's POOL (Officer.Pool): for a tiered officer's routine instance, Tier routine with the routine model and max; for an untiered officer, the officer itself, as before.
func (*Registry) ForOwner ¶ added in v0.236.0
ForOwner returns owner's officer with id: the env officer declared for that owner, or that owner's DB-declared one. An id another owner declares is not owner's.
type RerunAnswer ¶ added in v0.245.0
RerunAnswer is HQ's answer: Rerun is created (a new item now), already (this key re-ran it), live (the item or a live item of its subject carries the work) or superseded (a later item of its subject finished since); Item is the item that carries the work.
type RerunBackend ¶ added in v0.245.0
type RerunBackend interface {
RerunItem(ctx context.Context, item ItemID, r RerunRequest) (RerunAnswer, error)
}
RerunBackend re-runs one of the officer's finished items (CapRerun).
type RerunRequest ¶ added in v0.245.0
RerunRequest is POST /officers/{id}/items/{item_id}/rerun's body.
type Restart ¶ added in v0.257.0
type Restart struct {
// N is the instance number restarted (stopped, then started).
N int
// Class is why it was in error, and ErrorText the error recorded for it
// (InstanceState.ErrorText).
Class ErrorClass
ErrorText string
// InError is how long this process has seen it in error.
InError time.Duration
// Attempt is this restart's number among the officer's today (1-based),
// of Max.
Attempt, Max int
// Release is the live claims it held: released after its stop, before
// its start.
Release []Item
}
Restart is one auto-restart a pass decided (Decision.Restart).
type RestartRecord ¶ added in v0.257.0
RestartRecord is one instance's auto-restart day in a RestartStore.
type RestartStore ¶ added in v0.257.0
type RestartStore interface {
// RestartDay is the officer's rows for day, by instance (none: empty).
RestartDay(ctx context.Context, officer, day string) (map[string]RestartRecord, error)
// RecordRestart adds one restart of instance at at, with its error text.
RecordRestart(ctx context.Context, officer, day, instance string, at time.Time, errText string) error
// SetRestartHeld sets (held) or clears whether the instance's held
// notice was told, keeping errText when held.
SetRestartHeld(ctx context.Context, officer, day, instance string, held bool, errText string) error
}
RestartStore persists the auto-restart book (officer_auto_restarts, PGRestartStore), per officer id, UTC day ("2006-01-02") and instance agent name. ctx is Config.RestartContext's: it acts as the officer's owner.
type RetryableError ¶ added in v0.146.0
RetryableError is HQ answering a 5xx that its route documents as retryable (e.g. the obs route's 502 upstream): HQ's own JSON body, passed back so the instance sees the code, with "retry" — never a final refusal.
func (*RetryableError) Code ¶ added in v0.146.0
func (e *RetryableError) Code() string
Code is HQ's `code` in the body ("" when it has none).
func (*RetryableError) Error ¶ added in v0.146.0
func (e *RetryableError) Error() string
type Rollout ¶ added in v0.110.0
type Rollout struct {
// HealthURL is fetched by muster-server (never the instance). A release is
// LIVE once LiveReads consecutive answers report VersionKey == the tag, and
// HEALTHY once it has answered 200 (with OKKey == OKValue when OKKey is
// set) every Interval for HealthyFor after that.
HealthURL string
VersionKey string
OKKey string
OKValue string
LiveReads int
LiveWithin time.Duration
HealthyFor time.Duration
Interval time.Duration
// Rollback is RollbackOff, RollbackPR or RollbackAuto; RollbackWithin bounds
// how long an automatic rollback waits for its revert's gates.
Rollback string
RollbackWithin time.Duration
}
Rollout is how a tagged release is watched and, if it fails, rolled back.
type RolloutEvidence ¶ added in v0.251.0
type RolloutEvidence struct {
Item ItemID
Repo string
Tag string
// Evidence is the evidence object exactly as the instance gave it. muster
// forwards it whole, so nothing in it is ever silently dropped; HQ's
// decoder refuses an unknown or ill-typed field inside it (400 invalid).
// The tool's SCHEMA (internal/api rolloutEvidenceToolDef) mirrors HQ's
// §5r evidence shape and must change with it.
Evidence json.RawMessage
}
RolloutEvidence is officer_rollout_evidence_attach's arguments: {item_id, repo, tag, evidence}.
func ParseRolloutEvidence ¶ added in v0.251.0
func ParseRolloutEvidence(raw []byte) (RolloutEvidence, error)
ParseRolloutEvidence decodes officer_rollout_evidence_attach's arguments strictly. It checks TYPES and presence only: the values (which repository, the tag's form, the evidence's limits) are HQ's to refuse.
type RolloutEvidenceBackend ¶ added in v0.251.0
type RolloutEvidenceBackend interface {
AttachRolloutEvidence(ctx context.Context, instance string, e RolloutEvidence) ([]byte, error)
}
RolloutEvidenceBackend attaches a rollout officer's soak evidence.
type SessionStore ¶ added in v0.146.0
type SessionStore interface {
// AdmitSession admits entry as one of officer's sessions on day when it
// is already there (free, Inserted false) or the day's sessions at now
// (CountSessions) are fewer than limit (Inserted true) — atomically
// under the day's row lock.
AdmitSession(ctx context.Context, officer, day, entry string, limit int, now time.Time) (Admission, error)
// ReleaseSession removes entry (its claim definitely did not happen).
ReleaseSession(ctx context.Context, officer, day, entry string) error
// ResolveSession replaces pending token with entry, or drops the token
// when entry is "" or already there.
ResolveSession(ctx context.Context, officer, day, token, entry string) error
// Sessions is the day's entries, in admission order.
Sessions(ctx context.Context, officer, day string) ([]string, error)
}
SessionStore is the cap's durable ledger. day is a UTC date (2006-01-02).
type Shepherd ¶ added in v0.170.0
type Shepherd struct {
// Authors are whose pull requests the shepherd may act on.
Authors []ShepherdAuthor
}
Shepherd is a shepherd-stage officer's `ship.shepherd` block.
type ShepherdAuthor ¶ added in v0.170.0
type ShepherdAuthor struct {
// Login is the pull request author's GitHub login (an App's bot is
// `<slug>[bot]`), compared without case.
Login string
// Officer is the id of an officer declared on THIS muster whose App the
// login is (required: a shepherd acts on officers' pull requests only):
// its ship.repos entry for a repository is where the forbidden paths a
// shepherd push there must pass are looked up (ShepherdRules), and the
// gates check, at call time, that its App's bot login is Login.
Officer string
}
ShepherdAuthor is one entry of ship.shepherd.authors.
type ShepherdRule ¶ added in v0.170.0
type ShepherdRule struct {
// Repo is the shepherd's ship repository; Login the author.
Repo, Login string
// AuthorOfficer is the authoring officer's id (always set: every authors
// entry names one; Admit refuses a rule without it).
AuthorOfficer string
// ForbiddenPaths are the globs (MatchForbidden) no shepherd push may touch;
// ForbiddenPathsFiles the repository files listing more, each read from the
// pull request's TARGET branch at every check (and each forbidden itself).
ForbiddenPaths []string
ForbiddenPathsFiles []string
}
ShepherdRule is what a shepherd may do on one author's pull requests in one repository: the wall a push there must pass.
func ShepherdRules ¶ added in v0.170.0
func ShepherdRules(o Officer, all []Officer) []ShepherdRule
ShepherdRules are shepherd o's rules: one per (ship repository, author) the author can open pull requests in. 🔴 THE ONE PLACE A SHEPHERD'S WALL IS DECIDED: the union of the shepherd's own forbidden_paths for the repository (ship.repos[].forbidden_paths and forbidden_paths_file) and — for an author that names an officer — that officer's own forbidden paths for the same repository, LOOKED UP from its ship block, never copied. An author officer that does not ship to a repository has no rule there (its App opens no pull request there, so the shepherd acts on none). An entry with no officer (Parse refuses one) has no rule. all is every declared officer. Boot refuses a rule whose wall is empty (validateShepherds).
func (ShepherdRule) Empty ¶ added in v0.170.0
func (r ShepherdRule) Empty() bool
Empty reports whether the rule's wall forbids nothing.
type Ship ¶ added in v0.110.0
type Ship struct {
// Stage is StageShadow, StageMerge or StageRelease.
Stage string
// Base is the branch merges land on and releases are cut from.
Base string
// BranchPrefix is the only branch namespace the instance may push to and
// the only one a merged pull request may come from (`officer/`).
BranchPrefix string
// App is the officer's OWN GitHub App: its id and the one account
// (login:id, matched by id) whose installation is used.
AppID int64
AppAccount githubapp.Account
// RequiredChecks are the commit-status contexts (or check-run names) that
// must be success on the head commit. At least one.
RequiredChecks []string
// ReviewCheck is the check run that must be completed+success on the head
// commit (neutral does not pass). ReviewApp, when set, is the slug of the
// GitHub App that must have posted it.
ReviewCheck string
ReviewApp string
// Migrations is the directory (with trailing slash) whose added files are
// linted for destructive DDL and make a release need the backup check; ""
// for a repository without migrations.
Migrations string
// SensitivePaths are path patterns whose change makes officer_merge_pr post
// a notice to HQ before merging (it never blocks on the pattern itself).
SensitivePaths []string
// NoticePath is the HQ route (under hq_url, `{id}` replaced by the officer
// id) the notice is POSTed to; NoticeChannel is the mail channel HQ is
// asked to post it to.
NoticePath string
NoticeChannel string
// ReleasesPerDay caps officer tags per rolling 24 h; MinReleaseGap is the
// least time between two officer tags.
ReleasesPerDay int
MinReleaseGap time.Duration
// Quiet, when set, are hours no officer tag is cut.
Quiet *QuietHours
// Rollout, when set, is how a release is watched. Required for StageRelease.
Rollout *Rollout
// Repos are the repositories the officer ships to (ship_v2.go): one for
// every stage but draft, one to MaxShipRepos for draft. Base,
// BranchPrefix, AppID and AppAccount above are the officer `repo`'s entry.
Repos []ShipRepo
// Shepherd is a StageShepherd officer's `shepherd` block (shepherd.go):
// whose pull requests it acts on. nil on every other stage.
Shepherd *Shepherd
// DocsOnly is a draft officer's `docs_only` block (ship_docs.go): nil
// for an officer whose pull requests may touch any path its forbidden
// list allows.
DocsOnly *DocsOnly
// InternalPatternsFile is the local file of internal-details patterns
// that repositories marked public are scanned with (ship_docs.go).
InternalPatternsFile string
// CloseOldestDraft is a draft officer's cap-triggered close of its oldest
// idle draft (`close_oldest_draft`, ship_stale.go): ON by default for the
// draft stage; nil when the block disables it, and on every other stage.
CloseOldestDraft *CloseOldestDraft
// contains filtered or unexported fields
}
Ship is an officer's shipping policy, parsed from its `ship` block.
func (*Ship) AppKey ¶ added in v0.110.0
func (s *Ship) AppKey() *rsa.PrivateKey
AppKey is the officer App's private key. Its only reader is the App construction in internal/api.
func (*Ship) EscalateWebhook ¶ added in v0.110.0
EscalateWebhook is the out-of-HQ escalation URL ("" when unset).
func (*Ship) ForRepo ¶ added in v0.156.0
ForRepo is a copy of s whose Base, BranchPrefix and App are r's: the policy every single-repository rule (the own-pull-request rule, the ref rule) is asked with for r.
func (*Ship) InternalPatterns ¶ added in v0.229.0
func (s *Ship) InternalPatterns() ([]InternalPattern, error)
InternalPatterns reads the officer's internal_patterns_file FRESH (an operator may update it in place) and compiles it. An unset file, one that cannot be read, a line that is not a pattern, or a file with none is an error: the caller refuses rather than scans with nothing.
func (*Ship) IsShepherd ¶ added in v0.170.0
IsShepherd reports whether the stage is StageShepherd.
func (*Ship) MayMarkReady ¶ added in v0.156.0
MayMarkReady reports whether officer_mark_ready (the officer's OWN draft) is the officer's: every stage but draft and shepherd (a shepherd marks ready with officer_shepherd_mark_ready, on pull requests it shepherds).
func (*Ship) MayMerge ¶ added in v0.110.0
MayMerge reports whether the stage allows officer_merge_pr.
func (*Ship) MayRelease ¶ added in v0.110.0
MayRelease reports whether the stage allows officer_tag_release.
func (*Ship) NewPRsPerDay ¶ added in v0.229.0
NewPRsPerDay is how many pull requests the officer may open per UTC day: docs_only's max_prs_per_day when set, else MaxNewPRsPerDay.
func (*Ship) NoticeURLPath ¶ added in v0.110.0
NoticeURLPath is NoticePath with the officer id substituted (path-escaped).
func (*Ship) RepoFor ¶ added in v0.156.0
RepoFor is the ship repository named repo (compared without case), ok false when the officer does not ship to it.
func (*Ship) RepoList ¶ added in v0.156.0
RepoList is the officer's ship repositories: Repos when parsed, else the one repository primary described by the Ship's own fields (a Ship built outside Parse, as tests do).
func (*Ship) WithEscalateWebhook ¶ added in v0.110.0
WithEscalateWebhook returns a copy of s escalating to u. For tests and for wiring that builds a Ship outside Parse.
type ShipBackend ¶ added in v0.209.0
type ShipBackend interface {
PostNotice(ctx context.Context, path string, n Notice) error
Preflight(ctx context.Context) (Preflight, error)
Shadow(ctx context.Context) (bool, error)
PROpened(ctx context.Context, p PROpened) (PROpenedAnswer, error)
MergeAsk(ctx context.Context, item ItemID, body []byte) ([]byte, error)
}
ShipBackend is what a shipping officer's gates need of the backend beyond the switch: the sensitive-path notice and the backup preflight; and for the PR review loop, the officer's shadow switch (the fallback when an item carries no shadow of its own), the "PR opened" report muster makes after a clean draft create, and a shepherd's merge ask.
type ShipRepo ¶ added in v0.156.0
type ShipRepo struct {
// Repo is owner/name.
Repo string
// Base and BranchPrefix are as Ship's, for this repository.
Base string
BranchPrefix string
// AppID and AppAccount are the officer App and the installation account
// (the repository's owner) its token for Repo is minted from.
AppID int64
AppAccount githubapp.Account
// ForbiddenPaths are globs (MatchForbidden) no pull request of the officer
// may change, add, remove or rename from. Draft stage only.
ForbiddenPaths []string
// ForbiddenPathsFile, when set, is a repository file listing more
// forbidden globs, one per line; the draft gate reads it from the pull
// request's TARGET branch at every check (draftgate.go).
ForbiddenPathsFile string
// Public marks a public repository: the draft gate scans its pull
// requests with the officer's internal-details patterns (ship_docs.go).
Public bool
}
ShipRepo is one repository a shipping officer writes to.
type SpawnBudget ¶ added in v0.238.0
type SpawnBudget struct {
Per10m int
PerDay int
// Cycle is the shortest legitimate interval between two starts of one
// instance the budget was sized from.
Cycle time.Duration
}
SpawnBudget is how many starts an officer's instances may make, together, in the last 10 minutes and the last 24 hours.
func SpawnBudgetFor ¶ added in v0.238.0
func SpawnBudgetFor(o Officer, shortestSchedule time.Duration) SpawnBudget
SpawnBudgetFor is officer o's budget, given the shortest interval between two fires of any of its schedules (0 for none).
func (SpawnBudget) Refusal ¶ added in v0.238.0
func (b SpawnBudget) Refusal(inShort, inLong int) string
Refusal is why one more start is refused given the starts already made in the short and the long window, or "" when it is not.
type SpawnWindow ¶ added in v0.238.0
type SpawnWindow struct {
// Team, when set, is that owner's rows only (a team's own spawns).
Team int64
// NotOwnedBy leaves out the rows owned by any of these (the viewer's
// teams, for the personal section).
NotOwnedBy []int64
}
SpawnWindow narrows a VisibleHostSpawns read, so that each section of a page gets its own bounded window: a busy team host officer's rows never push a member's own spawns (and their lends) out of the newest limit rows. The zero value is every visible row.
type StatusRead ¶ added in v0.259.0
type StatusRead struct {
// Of is the status of each wanted item seen. An item absent from it was
// listed under no status read — unless Bounded is non-empty.
Of map[ItemID]string
// Bounded names each status whose read stopped at MaxStatusPages with
// pages still left: an item absent from Of may be beyond the bound, so
// its absence does not say HQ lacks it.
Bounded []string
}
StatusRead is StatusesOf's answer.
func StatusesOf ¶ added in v0.259.0
func StatusesOf(ctx context.Context, items func(context.Context, ItemsQuery) (ItemsPage, error), statuses []string, want map[ItemID]bool) (StatusRead, error)
StatusesOf is how each of want stands in the officer's backend: for every status in statuses, in order, it pages the items list (items, a backend's Items) to its END — following each page's cursor, not stopping at a page count the way PageAll does for the wake loop — and records the status of each wanted item it sees. It stops as soon as every wanted item is found, so a caller lists its short statuses first and a long one (done) last.
- A page over the answer cap (ErrHQAnswerTooLarge) is asked again, from the same cursor, at half the page size, down to one item; once a smaller page is read, the next page is asked at double its size, back up to StatusPageLimit. One item alone over the cap is an error naming it as such.
- A status with pages still left after MaxStatusPages is named in Bounded, and the next status is read.
- Any other read failure is returned (nil Of): the caller retries later.
type SwitchGated ¶ added in v0.210.0
type SwitchGated interface {
// SwitchGatesWake marks the backend; it does nothing.
SwitchGatesWake()
}
SwitchGated is a backend whose on/off switch (Backend.Enabled) the wake loop honours: while it answers false, the officer's instances are stopped and none is started, whatever its queue holds. The built-in backend is one — its switch (officer_defs.enabled) is the only "off" a builtin officer has. HQ is NOT: the loop has always read only an HQ officer's items, and an HQ officer's switch is HQ's to honour (its queue and its routes), so an HQ officer's passes make no extra request.
type TaskAskArgs ¶ added in v0.186.0
TaskAskArgs is officer_task_ask's arguments: {item_id, note?}.
func ParseTaskAskArgs ¶ added in v0.186.0
func ParseTaskAskArgs(raw []byte) (TaskAskArgs, error)
ParseTaskAskArgs decodes officer_task_ask's arguments strictly.
type TaskAsksBackend ¶ added in v0.209.0
type TaskAsksBackend interface {
CreateTaskAsk(ctx context.Context, instance string, a TaskAskArgs) ([]byte, error)
}
TaskAsksBackend files a task-reconciler's derived ask.
type TaskRouteUnavailableError ¶ added in v0.178.0
TaskRouteUnavailableError: HQ answered the task route 404 without TaskNotVisibleCode (an HQ older than the route). Final: retrying will not help until HQ is upgraded; the task may well exist.
func (*TaskRouteUnavailableError) Error ¶ added in v0.178.0
func (e *TaskRouteUnavailableError) Error() string
type TasksBackend ¶ added in v0.209.0
type TasksBackend interface {
TaskList(ctx context.Context, query string) ([]byte, error)
TaskGet(ctx context.Context, id string) ([]byte, error)
}
TasksBackend reads tasks (a task-reconciler's).
type TierPool ¶ added in v0.141.0
type TierPool struct {
// Model is the model the pool's Claude Code sessions run (podagent.ValidModel).
Model string `json:"model"`
// MaxInstances is how many of the pool's instances may run at once.
MaxInstances int `json:"max_instances"`
// Image, when set, is the runner image the pool's pods run (image.go);
// checked by the officer's parse, which holds the allowlist.
Image string `json:"image,omitempty"`
// MaxSessionsPerDay, on the judgement pool only, caps the distinct items
// it claims per UTC day (sessions.go); 0 is no cap. The routine pool is
// bounded by the `llm` budget instead.
MaxSessionsPerDay int `json:"max_sessions_per_day,omitempty"`
// MaxItemMinutes, on the judgement pool only, is the wall-time cap on ONE
// item: once an instance of the pool has held an item this long, the wake
// loop stops the instance and completes the item escalated (Decide,
// Overrun). 0 is no cap.
MaxItemMinutes int `json:"max_item_minutes,omitempty"`
// FreshSessionPerItem, on either pool: every item an instance of the pool
// claims is worked in a NEW Claude Code conversation
// (Officer.FreshSessionPerItem).
FreshSessionPerItem bool `json:"fresh_session_per_item,omitempty"`
// LLM, on the judgement pool only (tiers.judgement.llm), puts the pool on
// muster's LLM proxy with its own budget (llm.go, Officer.PoolLLM); its
// model is then a provider model id. The routine pool's block is the
// officer's top-level `llm` (Officer.LLM). Parsed by parseJudgementLLM.
LLM *LLM `json:"-"`
// contains filtered or unexported fields
}
TierPool is one tier's pool of instances.
type Transcript ¶ added in v0.127.0
type Transcript struct {
Enabled bool `json:"enabled"`
}
Transcript is an officer's `transcript` block: whether its instances' live session transcripts are forwarded to HQ (POST …/items/{item}/transcript) while they hold a claimed item.
type TranscriptAck ¶ added in v0.127.0
TranscriptAck is HQ's answer to a transcript post.
type TranscriptBackend ¶ added in v0.209.0
type TranscriptBackend interface {
PostTranscript(ctx context.Context, item ItemID, instance string, events []TranscriptEvent) (TranscriptAck, error)
}
TranscriptBackend stores an instance's transcript of a held item.
type TranscriptEvent ¶ added in v0.127.0
type TranscriptEvent struct {
Seq int64 `json:"seq"`
At string `json:"at"`
Kind string `json:"kind"`
Text string `json:"text"`
}
TranscriptEvent is one transcript event posted to HQ.
type UsageBackend ¶ added in v0.209.0
type UsageBackend interface {
PutUsage(ctx context.Context, r UsageReport) error
}
UsageBackend takes an instance's Claude usage per session and hour.
type UsageReport ¶ added in v0.194.0
type UsageReport struct {
Instance string `json:"instance"`
Pool string `json:"pool"`
Account string `json:"account"`
GeneratedAt string `json:"generated_at"`
Buckets []cctranscript.UsageBucket `json:"buckets"`
}
UsageReport is the usage route's body.
- Instance is the instance's muster agent name.
- Pool is the instance's pool: TierRoutine, TierJudgement, or "" for an untiered officer.
- Account is the pooled Claude account the instance is on NOW (its agent row's), "" for a pool on the LLM proxy: an account failover moves the instance, and every hour pushed after it is reported on the new one.
- GeneratedAt is when muster built the report (RFC 3339, UTC).
- Buckets are what the instance's ccd counted (cctranscript.UsageBucket), never null.
Source Files
¶
- asks.go
- autorestart.go
- backend.go
- budget.go
- chat.go
- cilogs.go
- config.go
- connector_blocks.go
- declared_db.go
- gap_tasks.go
- hostspawns.go
- hq.go
- image.go
- item_asks.go
- item_status.go
- kickoff.go
- kube.go
- limitrestart.go
- llm.go
- obs.go
- owners.go
- pools.go
- pr_context.go
- pr_queue.go
- pricing.go
- prloops.go
- public_branches.go
- reads.go
- refresh.go
- restarts_pg.go
- rollout_evidence.go
- sessions.go
- shepherd.go
- ship.go
- ship_close_oldest.go
- ship_docs.go
- ship_v2.go
- slug.go
- spawnbudget.go
- tasks.go
- tiers.go
- wake.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package backendtest is the officer-backend conformance suite (officer-backend/v1, docs/design/officers-first-class.md): the lease, queue, tier and refusal rules every officers.Backend must keep, as named checks over a small World.
|
Package backendtest is the officer-backend conformance suite (officer-backend/v1, docs/design/officers-first-class.md): the lease, queue, tier and refusal rules every officers.Backend must keep, as named checks over a small World. |
|
Package builtin is the built-in officer backend: officer-backend/v1 (officers.Backend) kept in muster's own Postgres (migration 0118), so a deployment can run officers with no external HQ (docs/design/officers-first-class.md).
|
Package builtin is the built-in officer backend: officer-backend/v1 (officers.Backend) kept in muster's own Postgres (migration 0118), so a deployment can run officers with no external HQ (docs/design/officers-first-class.md). |
|
Package hqtest is an in-process fake of the HQ officers API (the officers contract, v1), for tests in internal/officers and internal/api.
|
Package hqtest is an in-process fake of the HQ officers API (the officers contract, v1), for tests in internal/officers and internal/api. |
|
Package transcript forwards an officer instance's LIVE session transcript to HQ while the instance holds a claimed item (docs/officers.md, "Transcript to HQ"), so HQ's officer pages can show what the officer is doing.
|
Package transcript forwards an officer instance's LIVE session transcript to HQ while the instance holds a claimed item (docs/officers.md, "Transcript to HQ"), so HQ's officer pages can show what the officer is doing. |
|
Package usage pushes each officer instance's Claude usage — API calls, tokens and turns per session and UTC hour — to the officer's HQ (docs/officers.md, "Claude usage to HQ").
|
Package usage pushes each officer instance's Claude usage — API calls, tokens and turns per session and UTC hour — to the officer's HQ (docs/officers.md, "Claude usage to HQ"). |