officers

package
v0.167.0 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: MIT Imports: 33 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package 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

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

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

View Source
const (
	StatusOpen      = "open"
	StatusClaimed   = "claimed"
	StatusDone      = "done"
	StatusEscalated = "escalated"
)

Item statuses, as the contract names them.

View Source
const (
	MinLeaseSeconds     = 30
	MaxLeaseSeconds     = 3600
	DefaultLeaseSeconds = 600
)

Lease bounds, from the contract (30..3600 seconds).

View Source
const (
	MaxTranscriptEvents = 100
	MaxTranscriptText   = 8 << 10 // bytes
)

Transcript route bounds, as HQ enforces them.

View Source
const (
	TranscriptUser       = "user"
	TranscriptAssistant  = "assistant"
	TranscriptToolUse    = "tool_use"
	TranscriptToolResult = "tool_result"
	TranscriptSystem     = "system"
)

Transcript event kinds, as the contract names them.

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

View Source
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"
	// 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"
)

The MCP tool names muster serves to officer instances.

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

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

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

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

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

View Source
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 = 2
	// 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.

View Source
const (
	TierRoutine   = "routine"
	TierJudgement = "judgement"
)

Instance tiers, as HQ names an item's `tier`.

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

View Source
const ConfidenceLow = "low"

ConfidenceLow is the investigation confidence of no conclusion.

View Source
const DefaultHQTimeout = 15 * time.Second

DefaultHQTimeout bounds one HQ request.

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

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

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

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

View Source
const MaxAskImageBytes = askimage.MaxBytes

MaxAskImageBytes is HQ's bound on one ask image (askimage.MaxBytes).

View Source
const (
	MaxBackoff = 10 * time.Minute
)

Backoff bounds.

View Source
const MaxItemMinutesCap = 24 * 60

MaxItemMinutesCap bounds tiers.judgement.max_item_minutes: a day.

View Source
const MaxLinks = 10

MaxLinks is HQ's bound on a completion's links (civ-hq docs/OFFICERS.md).

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

View Source
const MaxNoticePaths = 50

MaxNoticePaths bounds a notice's path list; the rest are counted in Summary.

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

View Source
const MaxSessionsPerDayCap = 100

MaxSessionsPerDayCap bounds tiers.judgement.max_sessions_per_day.

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

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

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

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

View Source
const ReadsPerItem = 200

ReadsPerItem is the per-item read budget.

View Source
const ReleaseOfficerType = "release"

ReleaseOfficerType is the officer type whose instances evaluate releases.

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

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

View Source
const StatusWaiting = "waiting"

StatusWaiting is the status HQ gives an item with an open ask.

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

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

Variables

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

View Source
var CaptainLevels = []string{"low", "medium", "high", "severe"}

CaptainLevels are HQ's risk levels.

View Source
var ErrHQUnavailable = errors.New("officers: HQ unavailable")

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

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

View Source
var ErrReadBudget = errors.New("officers: the item's read budget is spent")

ErrReadBudget is a read refused because its item's budget is spent.

View Source
var ErrSessionCap = errors.New("officers: judgement session cap reached")

ErrSessionCap is a claim the day's cap refuses; the error's text says so.

View Source
var ErrUnknownOfficer = errors.New("officers: no such officer")

ErrUnknownOfficer is a lookup of an id no declared officer has.

ItemStatuses are the statuses officer_items' schema offers, as HQ names them. HQ decides what it accepts; muster passes the filter through.

View Source
var Outcomes = []string{"done", "escalated", "no_action"}

Outcomes the contract accepts from every instance.

View Source
var RunTick = time.Second

RunTick is how often Run looks for a due officer.

Functions

func AskFilename added in v0.144.0

func AskFilename(name, ct string, n int) string

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

func Backoff(o Officer, failures int) time.Duration

Backoff is how long to wait after the failures'th consecutive failed pass: PollInterval doubled per failure, capped at MaxBackoff.

func BodyFirstLine added in v0.156.0

func BodyFirstLine(officerID string, item int) string

BodyFirstLine is the first line a draft-stage officer's pull request body must be, exactly.

func BranchItem added in v0.156.0

func BranchItem(prefix, officerID, branch string) (int, bool)

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

func CapReason(used, limit int, reset time.Time) string

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

func CapResetAt(now time.Time) time.Time

CapResetAt is when the daily session cap in force at now resets: the next UTC midnight.

func ClampLease

func ClampLease(seconds int) int

ClampLease is seconds within the contract's bounds; 0 is the default.

func CompleteOutcomes added in v0.159.0

func CompleteOutcomes(o Officer) []string

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

func CompleteTakesInvestigation(o Officer) bool

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

func CountSessions(entries []string, now time.Time) (int, map[ItemID]bool)

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

func CountsRead(o Officer, tool string) bool

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 HQFaults

func HQFaults() float64

HQFaults is muster_officer_hq_faults' last published value.

func InstanceName

func InstanceName(id string, n int) string

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

func ItemTier(it Item) string

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

func KickoffText(o Officer, n int) string

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 HQ and reaches the instance through officer_brief, so muster never holds a second copy that can drift from HQ's versioned one; and the officer 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.

func KubeReadDisabled added in v0.153.0

func KubeReadDisabled(list []Officer) []string

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 MatchForbidden added in v0.156.0

func MatchForbidden(pat, p string) bool

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

func MaxInstanceNameLen(namespacePrefix string) int

MaxInstanceNameLen is how long an instance agent name may be under a namespace prefix.

func MayRequestConnector added in v0.118.0

func MayRequestConnector(o Officer, name string) bool

MayRequestConnector is THE rule for which connectors officer o's instances may request and use: `github`, plus the ones o declares in `connectors`.

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

func ObsRawBody(args []byte, item ItemID, instance string) (json.RawMessage, error)

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 OverrunSummary added in v0.155.0

func OverrunSummary(o Officer, ov Overrun) string

OverrunSummary is the escalation summary of a claim stopped at the cap.

func ParseForbiddenList added in v0.156.0

func ParseForbiddenList(content string) ([]string, error)

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

func PendingToken(now time.Time) string

PendingToken is a fresh pending entry for a claim-next started at now.

func ProviderModel added in v0.141.0

func ProviderModel(m string) bool

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

func ReadCounted(err error) bool

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

func Refusal(err error) (status int, msg, code string, ok bool)

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 RepromptText

func RepromptText(o Officer, n int) string

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

func RoutineAgent(o Officer, name string) bool

RoutineAgent is THE rule for whether agent name may use officer o's LLM proxy: o declares `llm`, and name is an instance of o's ROUTINE pool — an `-r<n>` within tiers.routine.max_instances, by the registry's own naming rule (parseInstance). o may be either of the officer's pools. A judgement instance, an untiered officer's instance, or any other name is not.

func SensitiveMatch added in v0.110.0

func SensitiveMatch(pat, p string) bool

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 Slug

func Slug(id string) string

Slug is an officer id as an agent-name fragment: the `:` written as `-` (`release:example-web` -> `release-example-web`).

func TokenEnvSuffix

func TokenEnvSuffix(id string) string

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 ToolOffered

func ToolOffered(o Officer, tool string) bool

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 ValidListFile added in v0.156.0

func ValidListFile(f string) bool

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 ValidRefSuffix added in v0.110.0

func ValidRefSuffix(s string) bool

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

type Admission struct {
	Admitted bool
	Inserted bool
}

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"`
	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 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.

func (*CILogs) String added in v0.125.0

func (c *CILogs) String() string

String describes the source.

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

type CaptainMonitor struct {
	Name string `json:"name"`
	URL  string `json:"url"`
}

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

func NewClient(o Officer, hc *http.Client) *Client

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

func (c *Client) AllItems(ctx context.Context, status string) ([]Item, error)

AllItems reads up to maxItemPages pages of items in status.

func (*Client) Brief

func (c *Client) Brief(ctx context.Context) ([]byte, error)

Brief is GET /officers/{id}/brief, HQ's JSON passed through.

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.

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

func (c *Client) Do(ctx context.Context, method, path string, body any) ([]byte, error)

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

func (c *Client) Enabled(ctx context.Context) (bool, error)

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

func (c *Client) Items(ctx context.Context, q ItemsQuery) (ItemsPage, error)

Items reads one page of the officer's items.

The body is HQ's `{"items":[…],"next":…}`.

func (*Client) ObsQueries added in v0.146.0

func (c *Client) ObsQueries(ctx context.Context) ([]byte, error)

ObsQueries is GET /officers/{id}/obs/queries with the officer token.

func (*Client) ObsQuery added in v0.146.0

func (c *Client) ObsQuery(ctx context.Context, args json.RawMessage) ([]byte, error)

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

func (c *Client) ObsRaw(ctx context.Context, body json.RawMessage) ([]byte, error)

ObsRaw is POST /officers/{id}/obs/raw with the officer token: body (ObsRawBody) as given. The answer is HQ's, unchanged.

func (*Client) Officer

func (c *Client) Officer() Officer

Officer is the officer this client acts for.

func (*Client) PostNotice added in v0.110.0

func (c *Client) PostNotice(ctx context.Context, path string, n Notice) error

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) Preflight added in v0.110.0

func (c *Client) Preflight(ctx context.Context) (Preflight, error)

Preflight calls POST /officers/{id}/preflight.

func (*Client) Release

func (c *Client) Release(ctx context.Context, item ItemID, instance string) ([]byte, error)

Release is POST …/items/{item}/release.

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) Scrub added in v0.127.0

func (c *Client) Scrub(s string) string

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) UploadAskImage added in v0.144.0

func (c *Client) UploadAskImage(ctx context.Context, filename, contentType string, data []byte) (askimage.Record, error)

UploadAskImage is POST /officers/{id}/ask-images: data as the raw body.

type ClientHQ

type ClientHQ struct {
	// contains filtered or unexported fields
}

ClientHQ is HQ over one Client per officer, built by NewClient.

func NewClientHQ

func NewClientHQ(build func(Officer) *Client) *ClientHQ

NewClientHQ returns an HQ that talks to each officer's own HQ with its own token. build nil uses NewClient(o, nil).

func (*ClientHQ) AllItems

func (h *ClientHQ) AllItems(ctx context.Context, o Officer, status string) ([]Item, error)

AllItems implements HQ.

func (*ClientHQ) Client

func (h *ClientHQ) Client(o Officer) *Client

Client returns the cached client for o.

func (*ClientHQ) Complete added in v0.155.0

func (h *ClientHQ) Complete(ctx context.Context, o Officer, item ItemID, instance string, done Completion) error

Complete implements HQ.

func (*ClientHQ) Heartbeat added in v0.155.0

func (h *ClientHQ) Heartbeat(ctx context.Context, o Officer, item ItemID, instance string, leaseSeconds int) error

Heartbeat implements HQ.

func (*ClientHQ) Release

func (h *ClientHQ) Release(ctx context.Context, o Officer, item ItemID, instance string) error

Release implements HQ.

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:"-"`
}

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

Config is NewReconciler's input.

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
	// Release is live claims held by an instance that is not up.
	Release []Item
	// 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
	// Held is how many live claims its instances hold.
	Held 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): want min(MaxInstances, held-by-up + Claimable) instances up; start the lowest-numbered down instances to reach it. Never stop anything 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 Fleet

type Fleet interface {
	// Instances returns the state of instances 1..o.MaxInstances. 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 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 HQ API the loop uses. *Client satisfies it (per officer); ClientHQ adapts a client factory to it.

type HQError

type HQError struct {
	Status int
	Body   []byte
}

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 (*HQError) Code added in v0.159.0

func (e *HQError) Code() string

Code is HQ's `code` in the body ("" when it has none).

func (*HQError) Error

func (e *HQError) Error() string

type InstanceState

type InstanceState struct {
	// N is the instance number, 1..MaxInstances.
	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.
	Error bool
	// 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
	// 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 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"`
}

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 (Item) LeaseLive

func (it Item) LeaseLive(now time.Time) bool

LeaseLive reports whether the item's lease is unexpired at now. An item with no lease time has no live lease.

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

func (id *ItemID) UnmarshalJSON(b []byte) error

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 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) GoString added in v0.141.0

func (l LLM) GoString() string

GoString is String, so %#v cannot print the key either.

func (*LLM) Key added in v0.141.0

func (l *LLM) Key() string

Key returns the provider key. Its only caller is the proxy, on the way to the provider, and tests asserting it appears nowhere else.

func (LLM) String added in v0.141.0

func (l LLM) String() string

String describes l without its key.

func (LLM) WithKey added in v0.141.0

func (l LLM) WithKey(key string) *LLM

WithKey returns a copy of l carrying key (tests, and wiring outside Parse).

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 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
}

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"`
	// 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"`
	// 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
	// for the officer.
	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:"-"`
	// contains filtered or unexported fields
}

Officer is one declared officer: the HQ identity muster runs instances for.

func Parse

func Parse(raw string, getenv func(string) string, namespacePrefix string) ([]Officer, error)

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 (Officer) FreshSessionPerItem added in v0.163.0

func (o Officer) FreshSessionPerItem() bool

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

func (o Officer) GoString() string

GoString is String, so %#v cannot print the token either.

func (Officer) HasSessionCap added in v0.146.0

func (o Officer) HasSessionCap() bool

HasSessionCap reports whether any pool of o is capped.

func (Officer) InstanceLabel added in v0.141.0

func (o Officer) InstanceLabel(n int) string

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

func (o Officer) InstanceName(n int) string

InstanceName is the agent name of instance n of this pool: `-r<n>` for the routine pool, `-<n>` otherwise (InstanceName).

func (Officer) ItemCap added in v0.155.0

func (o Officer) ItemCap() time.Duration

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) 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) Pool added in v0.141.0

func (o Officer) Pool(tier string) Officer

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) Pools added in v0.141.0

func (o Officer) Pools() []Officer

Pools is the officer's instance pools: the officer itself when it is untiered, else its judgement pool then its routine pool.

func (Officer) SessionCap added in v0.146.0

func (o Officer) SessionCap() int

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

func (o Officer) String() string

String names the officer without its token.

func (Officer) Token

func (o Officer) Token() string

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

func (o Officer) TranscriptEnabled() bool

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

func (o Officer) Type() string

Type is the officer's type: the part of its id before the colon.

func (Officer) WithToken

func (o Officer) WithToken(token string) Officer

WithToken returns o carrying token. Exported for tests and for wiring that builds an Officer outside Parse.

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

func (*PGSessionStore) Sessions added in v0.146.0

func (s *PGSessionStore) Sessions(ctx context.Context, officer, day string) ([]string, error)

Sessions implements SessionStore.

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

func (*QuietHours) Quiet added in v0.110.0

func (q *QuietHours) Quiet(t time.Time) bool

Quiet reports whether t falls in the quiet hours.

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.

func (*ReadBudget) Spend added in v0.153.0

func (b *ReadBudget) Spend(officer string, item ItemID) (int, error)

Spend counts one read of item by officer and returns how many it has made, or refuses (ErrReadBudget, nothing counted) once perItem are spent.

func (*ReadBudget) Spent added in v0.157.0

func (b *ReadBudget) Spent(officer string, item ItemID) int

Spent is how many counted reads of item officer has made.

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, id string, force bool) PassResult

Check runs one pass for officer 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) Run

func (r *Reconciler) Run(ctx context.Context)

Run drives the loop until ctx ends. Call it at most once.

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry is the declared officers, looked up by id or by instance agent name. It is immutable after NewRegistry.

func NewRegistry

func NewRegistry(list []Officer) *Registry

NewRegistry indexes list. It does not re-validate: Parse did.

func (*Registry) All

func (r *Registry) All() []Officer

All returns the declared officers, sorted by id.

func (*Registry) ForAgentName

func (r *Registry) ForAgentName(name string) (Officer, int, bool)

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

func (r *Registry) Get(id string) (Officer, error)

Get returns the officer with id.

type RetryableError added in v0.146.0

type RetryableError struct {
	Status int
	Body   []byte
}

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 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 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
	// 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

func (s *Ship) EscalateWebhook() string

EscalateWebhook is the out-of-HQ escalation URL ("" when unset).

func (*Ship) ForRepo added in v0.156.0

func (s *Ship) ForRepo(r ShipRepo) *Ship

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) GoString added in v0.110.0

func (s *Ship) GoString() string

GoString is String.

func (*Ship) IsDraft added in v0.156.0

func (s *Ship) IsDraft() bool

IsDraft reports whether the stage is StageDraft.

func (*Ship) MayMarkReady added in v0.156.0

func (s *Ship) MayMarkReady() bool

MayMarkReady reports whether officer_mark_ready is the officer's: every stage but draft.

func (*Ship) MayMerge added in v0.110.0

func (s *Ship) MayMerge() bool

MayMerge reports whether the stage allows officer_merge_pr.

func (*Ship) MayRelease added in v0.110.0

func (s *Ship) MayRelease() bool

MayRelease reports whether the stage allows officer_tag_release.

func (*Ship) NoticeURLPath added in v0.110.0

func (s *Ship) NoticeURLPath(officerID string) string

NoticeURLPath is NoticePath with the officer id substituted (path-escaped).

func (*Ship) RepoFor added in v0.156.0

func (s *Ship) RepoFor(primary, repo string) (ShipRepo, bool)

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

func (s *Ship) RepoList(primary string) []ShipRepo

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) String added in v0.110.0

func (s *Ship) String() string

String describes the policy without its secrets.

func (*Ship) WithEscalateWebhook added in v0.110.0

func (s *Ship) WithEscalateWebhook(u string) *Ship

WithEscalateWebhook returns a copy of s escalating to u. For tests and for wiring that builds a Ship outside Parse.

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
}

ShipRepo is one repository a shipping officer writes to.

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"`
	// 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"`
}

TierPool is one tier's pool of instances.

type Tiers added in v0.141.0

type Tiers struct {
	Routine   TierPool `json:"routine"`
	Judgement TierPool `json:"judgement"`
}

Tiers is an officer's `tiers` block: both pools.

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

type TranscriptAck struct {
	Stored  int   `json:"stored"`
	LastSeq int64 `json:"last_seq"`
}

TranscriptAck is HQ's answer to a transcript post.

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.

Directories

Path Synopsis
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.

Jump to

Keyboard shortcuts

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