loop

package
v0.175.0-rc.509 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: Apache-2.0 Imports: 48 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 loop is the supervisor loop: the pass that reads the desk's events and pull requests, plans with superloop and takes each transition once, the ordered streams its actions run in, the refill that starts the next board items, and the alarms on what stalls.

The command package runs it (beekeeper supervisor loop) and is its Host. What the loop still needs of the command crosses three seams, each named in one file:

  • host.go: Host, the app's configuration, state, clock and output and the app's own steps; and Cmd, the command package's functions.
  • vocabulary.go: the command's names, flags, verbs and exit codes the loop writes and reads, kept equal by the command's TestLoopVocabulary.
  • the forwarders that say "runs in the command": steps whose bodies need the command's own types (timers, the roster's chores, harnesses) stay there as functions over the Loop.

A seam entry goes when what it names has moved to a package the loop can import.

Index

Constants

View Source
const (
	LoopFillKey      = "next capacity "
	LoopFillStream   = "stream:workers"
	RefillZeroFormat = "SUPERVISOR REFILL started 0: %s\n"

	// OpenPullRefusal is how agents start refuses an item whose pull
	// request is open: its delivery is in flight.
	OpenPullRefusal = "already has an open pull request"
	// StaleNextAfter is the age past which a done event's next action is
	// left to the refill instead of starting a board item itself.
	StaleNextAfter = time.Hour
	// StaleNextWhat is what a stale next action is recorded as.
	StaleNextWhat = "superseded by the capacity refill: the done event is stale"
)
View Source
const (
	LoopLifecycleFile = "supervisor-loop-lifecycle.json"
	LoopPhaseStartup  = "startup"
	LoopPhaseBetween  = "between passes"
	LoopPhaseObserve  = "observe workers and pull requests"
	LoopPhaseRecover  = "recover quota and parks"
)
View Source
const (
	LoopClaimVerb    = "supervisor.claim"
	LoopGoVerb       = "supervisor." + superloop.KindGo
	LoopMergeVerb    = "supervisor." + superloop.KindMerge
	LoopEndVerb      = "supervisor." + superloop.KindEnd
	LoopFileVerb     = "supervisor." + superloop.KindFile
	LoopClaimEndVerb = "supervisor.unclaim"
	LoopStageVerb    = "supervisor.stage"
	LoopUnstageVerb  = "supervisor.unstage"
	LoopFailureVerb  = "supervisor.failure"
	// LoopOwnerlessVerb logs since when an open pull request has had no
	// live owner ("[<ref>] since <time>"), and its end ("[<ref>] owned"),
	// so a restarted loop's sweep keeps the stretch.
	LoopOwnerlessVerb = "supervisor.ownerless"
)

LoopClaimVerb logs an action the loop is about to take, before its side effect; LoopStageVerb a finished stage of a release; LoopUnstageVerb a stage found obsolete, which no later pass resumes. LoopGoVerb logs a merge go given to a worker, LoopMergeVerb a merge the loop ran itself.

View Source
const (
	CheckCompleted = "COMPLETED"
	CheckSuccess   = "SUCCESS"
	CheckFailure   = "FAILURE"
)

The states of a check run and a commit status the loop reads.

View Source
const (
	LoopStuckAfter  = 30 * time.Minute
	LoopStuckRecent = 3 * loopFailureBackoff
)

A step failing the same way for LoopStuckAfter, or on more than one item, is stuck: the guide hears of it once (stuck). Failures missing their scheduled retry by LoopStuckRecent drop out.

View Source
const (
	LoopCapacity = "capacity"
	LoopRemove   = "remove"
	LoopStop     = bgStopCmd
	LoopRecover  = "recover"
	LoopBoard    = "board"
	LoopTimer    = "timer"
	LoopAdd      = "add"
	LoopNote     = "note"
	// The placement flags a remote start names on its agents start line.
	LoopHostFlag = "--host"
	LoopRepoFlag = "--repo"
	LoopRefFlag  = "--ref"
)

The subcommands the loop runs that no other constant names.

View Source
const (
	LoopPullShort = 30 * time.Second
	LoopPullLong  = 2 * time.Minute

	LoopPullMaxAge = 5 * time.Minute

	// LoopPullMinBatch is the smallest batch a fault of GitHub's halves the
	// watch's batches to: below it, the failure is GitHub's, not the
	// batch's size.
	LoopPullMinBatch = 5

	LoopPullWatchFile = "supervisor-pull-observations.json"
)
View Source
const (
	PullContexts  = "contexts"
	PullSuites    = "checkSuites"
	PullNodes     = "nodes"
	PullPageInfo  = "pageInfo"
	PullHasNext   = "hasNextPage"
	PullEndCursor = "endCursor"
	PullHeadField = "headRefOid"

	JsonNullLiteral = "null"
)
View Source
const (
	WaitHold = "hold"

	WaitUnread = "unread"
)

The classes of what holds a merge decision. The stall alarm rings once per pending head and class, so a decision whose hold changes is named again.

View Source
const (
	// SweepListLimit is the most results GitHub's search returns: a list
	// that long may stop short of the desk's open pull requests.
	SweepListLimit = 1000
	// SweepReadsPerPass bounds issue detail reads in delivery discovery.
	// PR observations are batched by the independent watcher.
	SweepReadsPerPass = 50

	// LoopSweepFile is the side file supervisor status reads the count from.
	LoopSweepFile = "loop-sweep.json"
)
View Source
const (
	// SweepRepoBatch bounds the --repo flags in a single gh search prs call so a
	// desk with many team repositories stays within GitHub's search query limits.
	SweepRepoBatch = 25
	SweepOwnerFlag = "--owner"
)
View Source
const (
	OwnerlessSince = "since "
	OwnerlessEnd   = "owned"
)

OwnerlessSince opens the detail of a LoopOwnerlessVerb line that starts a stretch without an owner; OwnerlessEnd is the one that ends it.

View Source
const (
	ExitError    = 1
	ExitOutdated = 125
	ExitRefused  = 3
)

The command's names the loop writes and reads: its commands and flags, the verbs and files it shares, its exit codes. They are the command's; its TestLoopVocabulary keeps each equal to the command's own.

View Source
const AlertParkPrefix = "alert:"
View Source
const AsFlag = "as"

AsFlag is the global flag that names the party a command acts as.

View Source
const BoardTidyName = "tidy"

BoardTidyName is the board tidy subcommand.

View Source
const DefaultReviewBrief = `Review {{.URL}} at head {{.Head}}, review round {{.Round}}, the work of {{.Worker}}.
CI green at {{.Head}}.
{{.Context}}

You are an independent reviewer in a fresh session. Read the shipped beekeeper review skill.
Read the PR, its closing issues and their parent epic, including acceptance lines and comments.
Check fulfilment in full, not just correctness or the minimum that passes CI. Nothing may be
narrowed or deferred without a linked follow-up allowed by the issue. Check behaviour tests,
including failure paths; dead paths; unsupported claims in code, docs and the PR; and changes
that a later epic sub-issue would need to undo. Behaviour the PR adds or changes is documented
in its docs/ topic page, not appended to README.md.

Trust green CI on the exact reviewed head. Do not run local tests, lints, builds or probes.
Inspect the code and tests. For a full review use your own worktree at the pinned head;
for a light review read the diff, issue and CI. Never merge.

This is the pull request's one desk review: no second review runs for it.
Every finding is blocking or a nit to fix in this round; drop anything else. Fix your own
findings yourself in your worktree at the pinned head (a light review creates one only for its
fixes): fix them in code, tests or docs, commit them as one commit and push it once to the pull request's branch (git push origin
HEAD:refs/heads/{{.Branch}}; never force-push), then approve the head you pushed at once,
without waiting for its CI: the loop waits for green CI on that head and merges it. Never merge the base into the branch or rebase it to bring it up to date: the loop
merges the approved head as it is, and its merge-result check against the current base is the
gate. Request changes only for a finding that needs a product or design decision or cannot be
fixed on the branch, or when your publication is refused: the
worker fixes those, and the loop merges its green fix without another review. Open an issue
only for a real gap outside this PR or an explicitly permitted deferral, label it follow-up,
leave it unranked in the backlog and do not attach it as an epic sub-issue.

Post exactly one review comment (gh pr review {{.Number}} --repo {{.Repo}} --comment --body-file <file>).
First line exactly "Desk review (opus): approved" or "Desk review (opus): changes requested",
regardless of your configured model. Second line "Head reviewed: ` + "`{{.Head}}`" + `" (or, when you
pushed fixes, the full SHA of the head you pushed, in backticks, even while its CI runs).
Each finding: <file>:<line>: <what is wrong> → <what would be right>; say which you fixed.
Never use gh pr review --approve. Report to the supervisor:
beekeeper agents idle --done --report "<the same Desk review (opus): verdict line, a newline,
and the exact review URL>" --problem none (or --problem "<finding, evidence, owning repo>"
for each problem encountered). The supervisor gives the merge go after your approval once CI
is green, or relays the findings you could not fix to the worker.
A real conflict or red CI after your approval returns to you for a repair turn, never a
second review verdict. Push the repair and park for the loop to wait for CI and merge.
`

DefaultReviewBrief is the review brief without supervisor.reviewBrief.

View Source
const DeliveryNextCommand = "next"
View Source
const DeliveryReleaseEvery = 5 * time.Minute
View Source
const DeliveryReleaseReads = 2
View Source
const EpicAcceptanceProven = "Epic acceptance proven: "
View Source
const FileReportSeparator = "; file in the owning repositories:\n"

FileReportSeparator identifies reports stored in the event itself. Older file transitions only summarized delivery to a note and must not be replayed.

View Source
const HostBehindBound = time.Hour

HostBehindBound is how long an execution host may stay behind the coordinator's release, draining or waiting, before the supervisor loop hands it on as a fault.

View Source
const HostUpdateRetry = time.Hour

HostUpdateRetry paces a held host's or a busy host's next update attempt.

View Source
const LoopAlertKind = "alert"
View Source
const LoopAlertVerb = "supervisor." + LoopAlertKind
View Source
const LoopCacheFile = "supervisor-loop-cache.json"
View Source
const LoopDiskKind = "disk"
View Source
const LoopFailureAbandoned = "pass abandoned at shutdown deadline"

LoopFailureAbandoned is the lifecycle failure of a loop that exited at its shutdown deadline with a pass still running.

View Source
const LoopGraphQLReserve = 500

Keep room for an admitted query and for concurrent callers. The large board regression checks a whole walk below this per-request reserve.

View Source
const LoopLockFile = "supervisor-loop.lock"

LoopLockFile is the lock one running loop holds, beside the state.

View Source
const LoopMergeFailed = "merge.failed"
View Source
const LoopMergeFailureDropped = "merge.failure-dropped"
View Source
const LoopPIDFile = "supervisor-loop-pid.json"

LoopPIDFile is the running loop's PID marker, beside the state: 0 once it stopped.

View Source
const LoopPhaseStartupHistory = "read loop startup history"
View Source
const LoopPlanningObservationTimeout = 20 * time.Second

Optional remote observations must leave time for planning and cancellation.

View Source
const LoopPullStallAfter = 30 * time.Minute

LoopPullStallAfter is how long the pull watch may go without a poll that read every pull request it asked for before the loop raises the alarm.

View Source
const LoopPullStallKey = "stall pulls "
View Source
const LoopPullStep = "pull"
View Source
const (
	LoopRecordInputFile = "input.json"
)
View Source
const LoopReviewStallKey = "stall reviews "
View Source
const LoopStallAfter = 15 * time.Minute

LoopStallAfter is how long the refill may not run, or a start wait with room, before the loop raises the alarm; the alarm is raised once per episode until the flow moves again.

View Source
const LoopStallKey = "stall starts "
View Source
const LoopStartVerb = "supervisor.loop"

LoopStartVerb logs each start of the loop; the first one bounds the events it acts on.

View Source
const LoopSweepStep = "sweep"
View Source
const LoopVersionFile = "supervisor-loop-version.json"

LoopVersionFile is the running loop's version marker, beside the state.

View Source
const LoopWorkerMergeGo = "merge go given"
View Source
const MergeableConflicting = "CONFLICTING"
View Source
const (
	ReviewRecoveryFirst = time.Minute
)

The first retry of a review request that did not verify comes after ReviewRecoveryFirst; each further one waits twice as long, up to reviewRecoveryMax.

View Source
const ReviewedMergeQueued = "queued"
View Source
const SweepListEvery = superloop.OrphanWait / 3

SweepListEvery is how often the loop lists the desk's open pull requests for the orphan sweep: a third of superloop.OrphanWait, so one without an owner is seen well within it.

View Source
const ThroughputStartFailed = "start-command-failed"
View Source
const UnmergedCacheTTL = 5 * time.Minute
View Source
const WatchDiskStateVerb = "watch.disk-state"

Variables

View Source
var (
	LoopShutdownGrace    = 10 * time.Second
	LoopShutdownLockWait = 2 * time.Second
	LoopShutdownExit     = os.Exit
)

A SIGTERM cancels the pass, but work that does not watch its context (a state lock wait of minutes, a slow read) would hold the exit past the service manager's stop timeout and end in SIGKILL. After LoopShutdownGrace the loop abandons that work: it quiesces its state writes, waiting at most LoopShutdownLockWait for the state lock and a few seconds for a commit, and exits. Grace plus waits stay well under systemd's default 90 s.

View Source
var BeekeeperRun = func(ctx context.Context, args ...string) (string, int, error) {
	bin, err := ExecutablePath()
	if err != nil {
		return "", 0, err
	}
	out, errOut, code, err := RunArgv(ctx, "", append([]string{bin}, args...))
	return out + errOut, code, err
}

BeekeeperRun runs this beekeeper binary with args for the loop: its output (stdout, then stderr) and exit code. An error is a run that did not exit.

View Source
var ClosePullIssue = func(ctx context.Context, issue github.PR, pullURL string) error {
	ctx, cancel := context.WithTimeout(ctx, time.Minute)
	defer cancel()
	_, err := github.RunGH(github.ActingOn(ctx, issue.Repo), "issue", "close", strconv.Itoa(issue.N), "--repo", issue.Repo, "--reason", "completed", "--comment", fmt.Sprintf("Closed by %s.", pullURL))
	return err
}
View Source
var ContinuationUnpublished = func(ctx context.Context, dir string) string {
	if dir == "" {
		return ""
	}
	if info, err := os.Stat(dir); err != nil || !info.IsDir() {
		return ""
	}
	out, err := Cmd.RunGit(ctx, dir, "status", "--porcelain", "--untracked-files=no")
	if err != nil {
		return ""
	}
	if strings.TrimSpace(string(out)) != "" {
		return "uncommitted changes"
	}
	out, err = Cmd.RunGit(ctx, dir, "rev-list", "--count", "HEAD", "--not", "--remotes")
	if err != nil {
		return ""
	}
	switch n := strings.TrimSpace(string(out)); n {
	case "", "0":
	case "1":
		return "a commit on no remote branch"
	default:
		return n + " commits on no remote branch"
	}
	return ""
}

ContinuationUnpublished names what a previous worker's workspace on this machine holds that no remote has: uncommitted changes to tracked files, or commits on no remote-tracking branch. "" when it holds none, or there is no checkout here to read.

View Source
var EditPullBody = func(ctx context.Context, pull github.PR, body string) error {
	ctx, cancel := context.WithTimeout(ctx, time.Minute)
	defer cancel()
	_, err := github.RunGH(github.ActingOn(ctx, pull.Repo), "pr", "edit", strconv.Itoa(pull.N), "--repo", pull.Repo, "--body", body)
	return err
}
View Source
var EpicGitHub = github.RunGH
View Source
var ErrDeliveryObservationChanged = errors.New("delivery records changed during observation")
View Source
var ErrLoopLater = errors.New("later")

ErrLoopLater is an action that waits for a later pass, quietly: no room for a start yet.

View Source
var GhDefaultBranch = func(ctx context.Context, repo string) (string, error) {
	ctx, cancel := context.WithTimeout(ctx, time.Minute)
	defer cancel()
	out, err := github.RunGH(ctx, "api", "repos/"+repo, "--jq", ".default_branch")
	return strings.TrimSpace(string(out)), err
}

GhDefaultBranch reads a repository's default branch.

View Source
var LoopBinary = func() Replaceable {
	if b := platform.RunningBinary(); b != nil {
		return b
	}
	return nil
}

LoopBinary is the binary the loop runs; nil where it cannot tell.

View Source
var LoopCommand = RunArgv

LoopCommand runs a configured command (the classifier, the post-install) with stdin: its stdout, its stderr and its exit code.

View Source
var LoopLifecycleNow = clk.Now
View Source
var LoopParty = state.Party{Name: "supervisor loop"}

LoopParty is the party the supervisor loop acts and logs as.

View Source
var LoopReleaseContains = func(ctx context.Context, ref, commit, version string) (bool, error) {
	r, ok := Cmd.ParseRef(ref)
	if !ok || r.Repo != "giantswarm/beekeeper" {
		return false, nil
	}
	return ReleaseTagContains(ctx, ref, commit, version)
}

LoopReleaseContains keeps self-update wakes scoped to this program's repository. Delivery release recovery uses the general containment check independently.

View Source
var LoopRunningVersion = project.Version

LoopRunningVersion returns the binary version of the current process.

View Source
var PassChangeGap = 5 * time.Second

PassChangeGap is the shortest time between the end of a supervisor pass and a pass a state change wakes. Every session, runner and command writes the state; without a floor a busy desk keeps the loop passing back to back, each pass re-reading the state and the event log.

View Source
var PollOncePullWatcher = func(ctx context.Context, l *Loop) {
	var schedule LoopPullSchedule
	next, err := l.PullWatcher().Poll(ctx, l)
	schedule.After(l, next, err)
}
View Source
var ReadBaseMerge = func(ctx context.Context, p superloop.Pull, approved string) (bool, error) {
	r, ok := Cmd.ParseRef(p.Ref)
	if !ok || p.Base == "" {
		return false, fmt.Errorf("%s names no pull request with a base", p.Ref)
	}
	ctx, cancel := context.WithTimeout(ctx, time.Minute)
	defer cancel()
	covered, _, err := github.ApprovalCovers(ctx, github.RunGH, r.Repo, p.Base, approved, p.Head)
	return covered, err
}

ReadBaseMerge reads whether the approval of approved covers p's head: it only brings its base into approved (github.ApprovalCovers), by a merge, a merge whose conflicts it resolves, or a rebase, with no change of its own. A pull request gets one desk review (https://github.com/giantswarm/beekeeper/issues/3861): the merge-result check against the current base is such a head's gate, never a new review.

View Source
var ReadDeliveryRelease = func(ctx context.Context, p superloop.Pull) (string, string, error) {
	r, ok := Cmd.ParseRef(p.Ref)
	if !ok || p.MergeCommit == "" || p.Base == "" {
		return "", "", nil
	}
	ctx, cancel := context.WithTimeout(ctx, time.Minute)
	defer cancel()
	branch, err := github.ReadBranchRelease(ctx, github.RunGH, r.Repo, p.Base)
	if err != nil {
		return "", "", err
	}
	if !branch.Auto && !branch.Plugins && !branch.ReleasePR {

		raw, err := github.RunGH(ctx, "api", "repos/"+r.Repo+"/branches/"+url.PathEscape(p.Base), "--jq", ".name")
		if err != nil {
			return "", "", err
		}
		if strings.TrimSpace(string(raw)) != p.Base {
			return "", "", fmt.Errorf("release branch observation is incomplete")
		}
		return state.DeliveryNoRelease, "", nil
	}
	raw, err := github.RunGH(ctx, "api", "repos/"+r.Repo+"/tags?per_page=1", "--jq", ".[0].name // empty")
	if err != nil {
		return "", "", err
	}
	tag := strings.TrimSpace(string(raw))
	if tag == "" {
		return "", "", nil
	}
	contains, err := ReleaseTagContains(ctx, p.Ref, p.MergeCommit, tag)
	if err != nil || !contains {
		return "", "", err
	}
	return gate.VerdictAvailable, tag, nil
}

ReadDeliveryRelease uses REST only. The newest tag may be a prerelease; existence alone is insufficient: compare must prove it contains this merge.

View Source
var ReadDeskLogin = func(ctx context.Context) (string, error) {
	ctx, cancel := context.WithTimeout(ctx, time.Minute)
	defer cancel()
	return github.ViewerLogin(ctx, github.RunGH)
}

ReadDeskLogin is the login gh acts as: the one the desk's agents open their pull requests as, unless supervisor.ownership.authors names them.

View Source
var ReadLoopPull = func(ctx context.Context, ref string) (superloop.Pull, error) {
	r, ok := Cmd.ParseRef(ref)
	if !ok {
		return superloop.Pull{}, fmt.Errorf("%s names no pull request", ref)
	}
	ctx, cancel := context.WithTimeout(ctx, time.Minute)
	defer cancel()
	out, err := github.RunGH(ctx, "pr", "view", strconv.Itoa(r.N), "--repo", r.Repo, "--json", "state,url,headRefOid,baseRefName,statusCheckRollup,reviews,author,title,body,headRefName,files,changedFiles,additions,deletions,mergeCommit,isDraft,mergeable,mergeStateStatus,reviewDecision,closingIssuesReferences,updatedAt")
	if err != nil {
		return superloop.Pull{}, fmt.Errorf("gh pr view %d --repo %s: %w", r.N, r.Repo, err)
	}
	p, err := ParseLoopPull(ref, out)
	if err != nil || p.State != "OPEN" {
		return p, err
	}

	runs, err := github.RunGH(ctx, "api", "--paginate", fmt.Sprintf("repos/%s/actions/runs?head_sha=%s&per_page=100", r.Repo, p.Head))
	if err != nil {
		return superloop.Pull{}, fmt.Errorf("read workflow runs for %s: %w", ref, err)
	}
	var snapshot LoopPullJSON
	if err := json.Unmarshal(out, &snapshot); err != nil {
		return superloop.Pull{}, err
	}
	if err := ApplyLoopWorkflowRuns(&p, runs, snapshot.Rollup); err != nil {
		return superloop.Pull{}, err
	}
	return p, nil
}

ReadLoopPull reads a tracked pull request (owner/repo#n): its state, head, the checks on the head and its reviews.

View Source
var ReadLoopPullBatch = FetchLoopPullBatch

ReadLoopPullBatch uses one light query (including details on first sight), followed only when needed by one query for heads/updatedAt that moved. Sixty ordinary PRs therefore cost at most two requests, including a cold start.

View Source
var ReadLoopSweep = func(l *Loop, _ context.Context, _ superloop.Input) {
	s := l.PullWatcher().View()
	l.OpenPulls, l.OpenPullsAt, l.SweepIncomplete = s.Open, s.ListedAt, s.Incomplete
}

Discovery shares the watcher's timer; a slow listing cannot stall a pass.

View Source
var ReadObservedLoopPull = func(l *Loop, ctx context.Context, ref string, _ time.Time, _ string) (LoopPullObservation, error) {
	if err := ctx.Err(); err != nil {
		return LoopPullObservation{}, err
	}
	now := l.Host.TimeNow()
	if l.Host.LoopNow() != nil {
		now = clk.Now()
	}
	p, err := l.PullWatcher().Read(ref, now)
	return LoopPullObservation{Pull: p.Pull, At: p.At}, err
}

ReadObservedLoopPull is a seam for planner/action fixtures. Production always reads the watcher, including --once and --dry-run, which use its saved snapshot.

View Source
var ReadOpenPulls = func(ctx context.Context, authors func() ([]string, error), scopes []string) ([]string, error) {
	logins, err := authors()
	if err != nil {
		return nil, err
	}
	batches := SweepFlagBatches(scopes)
	var out []string
	for _, login := range logins {
		for _, flags := range batches {
			args := append(strings.Fields("search prs --state open --json repository,number"), "--limit", strconv.Itoa(SweepListLimit), "--author", login)
			args = append(args, flags...)
			c, cancel := context.WithTimeout(ctx, time.Minute)
			b, err := github.RunGH(c, args...)
			cancel()
			if err != nil {
				return nil, fmt.Errorf("gh search prs --author %s: %w", login, err)
			}
			var found []struct {
				Number     int `json:"number"`
				Repository struct {
					NameWithOwner string `json:"nameWithOwner"`
				} `json:"repository"`
			}
			if err := json.Unmarshal(b, &found); err != nil {
				return nil, fmt.Errorf("gh search prs --author %s: %w", login, err)
			}
			for _, f := range found {
				if f.Repository.NameWithOwner != "" && f.Number > 0 {
					out = append(out, fmt.Sprintf("%s#%d", f.Repository.NameWithOwner, f.Number))
				}
			}
		}
	}
	slices.Sort(out)
	return slices.Compact(out), nil
}

ReadOpenPulls lists the open pull requests (owner/repo#n) the logins authors opened, in scopes (owners without a slash, repositories with one) when any are named: REST searches per login that spend no GraphQL budget.

View Source
var ReadRedJobLog = func(ctx context.Context, repo string, job int64) (string, error) {
	return github.JobLog(ctx, github.RunGH, repo, job)
}
View Source
var ReadRepoPullRevision = func(ctx context.Context, repo, etag string) (string, bool, error) {
	return ReadRepoPullRevisionWithGH(ctx, github.RunGH, repo, etag)
}

A 304 reuses an authenticated response without spending REST core budget. Read all states ordered by update so closing a pull invalidates the cache.

View Source
var ReadTeams = func(ctx context.Context, own config.Ownership) (map[string]string, error) {
	ctx, cancel := context.WithTimeout(ctx, 2*time.Minute)
	defer cancel()
	repo, dir := own.TeamFilesRepo()
	return github.Teams(ctx, github.RunGH, repo, dir)
}

ReadTeams reads supervisor.ownership.teamFiles: the team that owns each repository (owner/name, lower-cased).

View Source
var RecoverParkReviewHead = func(ctx context.Context, on, dir string) string {
	if info, err := os.Stat(dir); err != nil || !info.IsDir() {
		return ""
	}
	return publishedParkHead(ctx, on, dir, Cmd.RunGit, github.RunGH)
}

RecoverParkReviewHead starts no git in a worktree that is gone: it cannot verify there.

View Source
var SelfUpdateCheck = []string{selfUpdateCmdName, "--check"}

SelfUpdateCheck is the look for a newer release.

View Source
var StartLoopPullWatcher = func(ctx context.Context, l *Loop) func() {
	ctx, cancel := context.WithCancel(ctx)
	w := l.PullWatcher()
	w.Set(nil, l.Host.Cfg().Supervisor.Ownership.Authors, l.Host.Cfg().GitHub.AllowedOrgs, l.Host.Cfg().GitHub.Floor, l.Host.Cfg().Supervisor.Ownership.Never)
	own := l.Host.Cfg().Supervisor.Ownership
	w.SetBots(own.Bots, superloop.Desk{Orgs: l.Host.Cfg().GitHub.AllowedOrgs, Team: own.Team, Review: own.Review, Never: own.Never}, nil, false)
	w.Mu.Lock()
	w.Started = clk.Now()
	w.Mu.Unlock()
	done := make(chan struct{})
	go func() {
		defer close(done)
		timer := clk.NewTimer(0)
		defer timer.Stop()
		schedule := LoopPullSchedule{}
		var lastPoll time.Time
		for {
			select {
			case <-ctx.Done():
				return
			case <-w.changed:

				if schedule.Failures > 0 {
					continue
				}

				if delay := clk.Until(lastPoll.Add(LoopPullShort)); delay > 0 {
					timer.Reset(delay)
					continue
				}
			case <-timer.C:
			}
			lastPoll = clk.Now()
			next, err := w.Poll(ctx, l)
			if ctx.Err() != nil {
				return
			}
			next = schedule.After(l, next, err)
			timer.Reset(next)
		}
	}()
	return func() { cancel(); <-done }
}

StartLoopPullWatcher owns one cancellable timer and one fetch at a time. Its independent clock does not stop at the beginning of a supervisor pass.

Functions

func AbsorbedClosingIssues

func AbsorbedClosingIssues(ctx context.Context, st *state.State, absorbs []string) ([]string, error)

func AgentRef

func AgentRef(st *state.State, name string) string

AgentRef is the issue or pull request the agent works: what it is parked on, else its serve record, else the first one its task names.

func ApplyLoopWorkflowRuns

func ApplyLoopWorkflowRuns(p *superloop.Pull, raw []byte, rollup []LoopCheck) error

func AttachRedLogs

func AttachRedLogs(ctx context.Context, act superloop.Action) superloop.Action

Attach bounded failure output at the handoff, once per planned red wake. Non-Actions checks and unavailable logs retain their original check links.

func BoardBudgetLow

func BoardBudgetLow(b *state.Budget, floor int, now time.Time) bool

BoardBudgetLow reports whether a board walk, which costs a large share of the GraphQL budget, must wait: the REST budget is under floor until its reset, GraphQL refuses, or the last GraphQL reading is under floor until its window resets (its reset, else an hour after the reading).

func BoundLoopShutdown

func BoundLoopShutdown(ctx context.Context, done <-chan struct{}, store state.Store, out io.Writer)

BoundLoopShutdown exits the process LoopShutdownGrace after ctx ends unless done closes first, the loop having returned. It writes the lifecycle, PID and version records the loop's own deferred cleanup would have written, reading the lifecycle from its file, never from the running loop's memory. A store that cannot quiesce its writes is exited without: an unfinished write is recovered by the next reader, as after a SIGKILL, only sooner.

func CloseMergedPullIssues

func CloseMergedPullIssues(ctx context.Context, st *state.State, p superloop.Pull) ([]string, error)

func CommitDeliveryObservation

func CommitDeliveryObservation(ctx context.Context, store state.Store, now time.Time, complete bool, derive func([]state.Delivery) []state.Delivery) error

Ownership classification and event derivation can be expensive on a large desk. Do both without the exclusive state lock, then compare only the records they depended on. Other state writers (agents, timers, notes) never invalidate the result and their changes are retained by the commit. A concurrent delivery writer requires a fresh derivation, never an overwrite of its verdict/identity.

func DeliveryTrackedPulls

func DeliveryTrackedPulls(tracked []string, deliveries []state.Delivery, desk superloop.Desk) []string

DeliveryTrackedPulls adds the pull requests of active deliveries to the pass's tracked references. A pull request the desk leaves unread (outside github.allowedOrgs or in supervisor.ownership.never) stays out: the watcher never observes it, so tracking it would leave it unread in every pass and no delivery observation would ever complete ("wip stale").

func DeskVerdicts

func DeskVerdicts(reviews []superloop.Review, authors []string) []superloop.Review

DeskVerdicts is reviews with the verdict of each one the desk does not trust cleared: a verdict counts only from a member or collaborator of the repository's owner or from one of authors, the logins the desk opens and reviews its pull requests as. On a public repository anyone can post "Review: approved": the planner and the merge gate both read verdicts through this, so neither merges nor holds on an outsider's word.

func DryRunLoop

func DryRunLoop(ctx context.Context, a Host, recordDirs ...string) error

DryRunLoop is one pass that says what it would take: it runs only read-only queries, logs nothing, fires no timer and takes no lock, so it can run beside the loop.

func EnsureCombinedPullCloses

func EnsureCombinedPullCloses(ctx context.Context, st *state.State, p *superloop.Pull) error

func EventProgressFilter

func EventProgressFilter(keep func(state.Event) bool, checkpoint func(), now func() time.Time) func(state.Event) bool

func ExecutablePath

func ExecutablePath() (string, error)

ExecutablePath returns the running binary's filesystem path, stripping the Linux " (deleted)" marker when an in-place update or rollback replaced it.

func FetchLoopPullBatch

func FetchLoopPullBatch(ctx context.Context, refs []string, previous map[string]WatchedLoopPull, floor int) (map[string]WatchedLoopPull, error)

func GhMergePolicyRefused

func GhMergePolicyRefused(reason string) bool

A branch policy refusal belongs to the coordinator, even when GitHub's merge state also says BEHIND. A branch edit cannot supply missing review.

func HostCapacityReason

func HostCapacityReason(out string, code int, err error) string

func HostDrains

func HostDrains(pin state.HostPin, version string, b *state.Budget, now time.Time) bool

HostDrains says the execution host pinned by pin drains for the coordinator's release version: it is pinned to another release, so it takes no new start until its update succeeds, and the executions on it reach the turn boundary the update waits for. A host never pinned to a release is not behind one, and a host whose update waits on the coordinator's failed lookup of version keeps taking starts until that lookup is due again. The caller checks that the coordinator runs a release that is ready for its hosts (CoordinatorHostUpdateReady).

func HostHoldBlocks

func HostHoldBlocks(pin state.HostPin) bool

Legacy lookup and probation holds never changed the installed host. Actual installation, preparation and policy failures remain start-blocking.

func HostHoldWait

func HostHoldWait(pin state.HostPin, b *state.Budget, now time.Time) bool

func Keyed

func Keyed(detail string) (key, rest string, ok bool)

Keyed reads a loop line's detail: "[<key>] <rest>".

func LatestReviewRequestsChanges

func LatestReviewRequestsChanges(p superloop.Pull) bool

LatestReviewRequestsChanges reports whether the latest review verdict on p requests changes on its current head, overriding any earlier approval. A different head still needs the loop's exact-head decision; the executor's authority check rejects any go overtaken by a later change request. A review of a replaced head (MarkReplaced) is no verdict.

func LockBusy

func LockBusy(err error) bool

LockBusy says err is a wait for the state lock that ended before its holder released it.

func LoopBudgetHold

func LoopBudgetHold(b *state.Budget, floor, reserve int, now time.Time) (cause string, until time.Time, fresh bool)

LoopBudgetHold says why a GitHub budget reading holds the loop's GitHub reads, "" when it admits them: LoopBudgetUnknownOrLow, or less GraphQL budget than reserve above github.floor for a read that keeps one. until is when the hold ends on its own, the reset of a low or refused window; fresh says a fresh reading may end it now: the reading is missing, failed, stale or of a window that has reset (#3841).

func LoopBudgetUnknownOrLow

func LoopBudgetUnknownOrLow(b *state.Budget, floor int, now time.Time) bool

A reset is not evidence of recovery: wait for a reading from the new window, the watch's or the held pass's own (refreshLoopBudget). Unknown and stale observations fail closed.

func LoopFailureDelay

func LoopFailureDelay(count int) time.Duration

LoopFailureDelay is the deferral after count identical failures.

func LoopFailureKind

func LoopFailureKind(err error) string

func LoopParkOn

func LoopParkOn(p *state.Park) string

LoopParkOn preserves explicit wait owners. Older workers sometimes omit --on and name the pull request in their wait instead. Only an unambiguous pull URL supplies that missing owner; issue URLs and prose do not.

func LoopPullChanged

func LoopPullChanged(in superloop.Input, ref string) time.Time

func LoopServes

func LoopServes(st *state.State, ag state.Agent) string

LoopServes is the issue ag's active sessions serve record names, as owner/repo#n: "" without one, once its session ended or once it waits for "done".

func LoopTaskServes

func LoopTaskServes(ag state.Agent, parkedOn string) string

func MarkReplaced

func MarkReplaced(ctx context.Context, p superloop.Pull) superloop.Pull

MarkReplaced is p with its reviews of a head their author had replaced when they came (superloop.Replaced) marked, as the planner reads them: no verdict, neither for a merge nor against one. A superseded reviewer's late request for changes on the head it was given holds no go the next round's verdict earned. A base merge that cannot be read keeps the review standing. The reviews of the p passed in stay as they are.

func MergeHeld

func MergeHeld(class, format string, args ...any) error

MergeHeld is a wait of class for a later pass, with its cause.

func NormalizeLoopVersion

func NormalizeLoopVersion(ver string) string

func PaceYield

func PaceYield(local, host string) string

PaceYield is why a host with room does not take a start under supervisor.hostsFirst: the coordinator's own pick (local, its capacity --json) is a subscription behind its weekly pace and the host's pick (host, capacity --host … --json) spends another provider, such as a subscription whose harness no host runs. Placed there, the start would leave the subscription furthest behind its pace unspent while the coordinator has room for it. "" when the host spends the coordinator's provider, or the coordinator's pick is not behind its pace.

func ParseLoopPull

func ParseLoopPull(ref string, out []byte) (superloop.Pull, error)

ParseLoopPull reads gh pr view's JSON of ref.

func PullConnection

func PullConnection(p map[string]any, name string) map[string]any

func PullNeedsBranchRepair

func PullNeedsBranchRepair(p superloop.Pull) bool

func PullRefURL

func PullRefURL(ref string) string

func PullWatchRetry

func PullWatchRetry(failures int) time.Duration

func ReadRepoPullRevisionWithGH

func ReadRepoPullRevisionWithGH(ctx context.Context, run github.GH, repo, etag string) (string, bool, error)

func ReleaseTagContains

func ReleaseTagContains(ctx context.Context, ref, commit, version string) (bool, error)

ReleaseTagContains proves the actual merge is an ancestor of the tag using REST.

func RemovedAgent

func RemovedAgent(detail, name string) bool

RemovedAgent reports whether detail, an agents.remove line's, names name.

func RepoName

func RepoName(repo string) string

RepoName is owner/repo's repo.

func ReviewParkEnded

func ReviewParkEnded(taken []superloop.Taken, rp state.ReviewPark) bool

ReviewParkEnded reports a park whose own pull request the loop already ended. A park is per pull request: nothing about its worker ends it, since a worker finishing one pull request can have others waiting for review.

func ReviewParkServes

func ReviewParkServes(st *state.State, ag state.Agent, on string) string

func RunArgv

func RunArgv(ctx context.Context, stdin string, argv []string) (string, string, int, error)

RunArgv runs argv with stdin: its stdout, its stderr and its exit code.

func RunLoop

func RunLoop(ctx context.Context, a Host, once bool) (runErr error)

RunLoop runs the loop: every pass until ctx ends, or one with once.

func SameCommit

func SameCommit(a, b string) bool

func SelfHostedModel

func SelfHostedModel(k config.Capacity, model string) bool

SelfHostedModel reports whether model is a choice of a self-hosted provider; an omp agent's recorded provider/id is the choice that names its bare id.

func ShouldEndReviewWorker

func ShouldEndReviewWorker(st *state.State, ag state.Agent) bool

func SortTrackedPulls

func SortTrackedPulls(in superloop.Input, tracked []string)

func StaleMergeResultFailure

func StaleMergeResultFailure(reason, head string) bool

Older repair records have only the checker's diagnostic. Its head must agree with the decision even if a surrounding gate record names that decision. Check every diagnostic, since a tool response can contain several lines.

func SweepFlagBatches

func SweepFlagBatches(scopes []string) [][]string

SweepFlagBatches splits scopes (owners without a slash, owner/repo with one) into gh search prs flag slices. Owners and repositories are searched in separate calls because gh ANDs --owner with --repo when both are given.

func Vocabulary

func Vocabulary() map[string]any

Vocabulary is the constants above by name, for the command's test.

func WriteLoopRecording

func WriteLoopRecording(dir string, in LoopRecording) error

Types

type Answered

type Answered struct {
	About    string
	Comment  string
	ID       int
	For      string
	Via      string
	Answer   string
	Asker    string
	Question string
	Audience string // original note audience; empty in older audit events.
	At       time.Time
	By       string
}

answered is a person's answer recorded: the answer.recorded event read back; Comment is its comment's URL, "" when none was posted. ID is the note it answered, 0 for none.

type BriefData

type BriefData struct {
	URL, Repo, Head, Branch, Worker, Task, ServesURL, PostMerge string
	Number, Round                                               int
	Context                                                     string
}

BriefData is what a brief template renders.

type Command

type Command struct {
	About                      func(e state.Event, ref string) state.Event
	AgyAgentStartID            func(ag state.Agent) string
	AgyQuotaError              func(cfg *config.Config, ag state.Agent) *agy.QuotaError
	AlertOwnerKey              func(o state.AlertOwner) string
	ApplyDeliveryVerdict       func(d *state.Delivery, verdict string, tag string, now time.Time)
	BudgetGateArgs             func() []string
	ClassifyDelivery           func(st *state.State, d state.Delivery, now time.Time, p any) DeliveryFlow
	ClearRecords               func(st *state.State, p state.Party) []state.Record
	Clock                      func(now time.Time, t time.Time) string
	CloseSupersededPulls       func(ctx context.Context, st *state.State, merged superloop.Pull) ([]string, error)
	Code                       func(err error) int
	ContinuationName           func(ag state.Agent) string
	CoordinatorHostUpdateReady func(version string) error
	CoordinatorVersion         func() string
	DeliveryAgent              func(st *state.State, d state.Delivery, ag state.Agent) bool
	DeliveryExempt             func(st *state.State, now time.Time, ref string, exempt bool) bool
	DeliveryURL                func(ref string, pull bool) string
	DevctlCommandEnv           func(configPath string) []string
	EndNotes                   func(st *state.State, worker state.Party, now time.Time)
	EndedParkCandidate         func(ag state.Agent) bool
	EpicChildStatus            func(st *state.State, child board.Item, now time.Time, policy any) string
	EpicOwner                  func(st *state.State, ref string) *state.Agent
	ErrGone                    func() error
	EscapedLine                func(s string) string
	Event                      func(by state.Party, verb string, format string, a ...any) state.Event
	ExecutionCannotContinue    func(r *state.ExecutionRecord) string
	ExecutionRecord            func(st *state.State, ref execution.Ref) (*state.ExecutionRecord, int)
	FreshPark                  func(st *state.State, ag state.Agent) bool
	FreshSessions              func(p0 Host) ([]*claude.Session, *proc.Table, error)
	HeldBy                     func(notes []state.Note, ref string, except int) (*state.Note, *state.ItemHold)
	HostExecutions             func(st *state.State, selector string) int
	IncidentExempt             func(st *state.State, now time.Time, refs ...string) bool
	IsDeskReviewWait           func(waits string) bool
	IssueURL                   func(ref string) string
	LoopBroker                 func(ctx context.Context) (string, error)
	LoopEpicStart              func(l *Loop, next LoopBoardItem) error
	LoopFiledIssues            func(l *Loop, st *state.State) []superloop.FiledIssue
	LoopFinishContinuation     func(l *Loop, old state.Agent, name string) error
	LoopFireTimers             func(l *Loop, ctx context.Context, st *state.State) error
	LoopInTurn                 func(a Host, p state.Party) bool
	LoopRecoverUnfinishedTurns func(l *Loop, ctx context.Context, st *state.State) error
	LoopResumable              func(a Host, st *state.State, ag state.Agent) bool
	LoopResumePark             func(a Host, ctx context.Context, by state.Party, q string) error
	LoopRoster                 func(l *Loop, ctx context.Context, planned map[string]bool) error
	LoopSessions               func(a Host) ([]*claude.Session, *proc.Table, error)
	LoopSettleOverrides        func(l *Loop, ctx context.Context, st *state.State)
	LowBudget                  func(b *state.Budget, floor int, now time.Time) bool
	NamedRefs                  func(text string, owner string) []string
	NewExitError               func(code int, msg string, err error) error
	OneLine                    func(s string) string
	ParkMessage                func(p *state.Park, by string) string
	ParkedBetweenTurns         func(st *state.State, x *state.ExecutionRecord) bool
	ParseAnswered              func(e state.Event) (Answered, bool)
	ParseRef                   func(s string) (github.PR, bool)
	PauseChangeFor             func(ctx context.Context, d time.Duration) bool
	PublicPullURL              func(raw string) string
	PublishedParkVerification  func(ctx context.Context, on string, dir string, git worktrees.Git, gh github.GH) (string, string)
	ReadDeliveryWIP            func(st *state.State, limit int, interval time.Duration, now time.Time, policies ...any) *DeliveryWIP
	ReadIntakeAnchor           func(ctx context.Context, a Host, ref string, from string) (string, error)
	ReadLoopAlerts             func(p0 context.Context, a Host) ([]alerts.Firing, error)
	ReadRepoOpenPulls          func(ctx context.Context, repo string) ([]UnmergedPull, error)
	RecentUnmergedPulls        func(repo string, pulls []UnmergedPull, now time.Time, window time.Duration) []UnmergedPull
	RecordAgentReviewPark      func(st *state.State, ag state.Agent)
	RefName                    func(r github.PR) string
	RefStates                  func(ctx context.Context, refs []github.PR) (map[github.PR]github.RefState, error)
	RefURL                     func() *regexp.Regexp
	RefreshLoopBudget          func(a Host, ctx context.Context) (*state.Budget, error)
	Refused                    func(format string, a ...any) error
	ReleaseVersion             func(v string) bool
	RemoveAgent                func(st *state.State, i int)
	ReportIdle                 func(ag *state.Agent, now time.Time)
	RepositoryStartReason      func(st *state.State, now time.Time, ref string) string
	ReviewContext              func(ctx context.Context, p superloop.Pull, threshold int) (string, error)
	RoleRun                    func(st *state.State, p state.Party) bool
	RunGit                     func(ctx context.Context, dir string, args ...string) ([]byte, error)
	ShortDur                   func(d time.Duration) string
	StopMerges                 func(store state.Store, by state.Party, pick func(state.Merge) bool, keepSeeded bool, how func(state.Merge) string) ([]string, error)
	TakeOverReviewPark         func(a Host, st *state.State, rp state.ReviewPark, name string) ([]state.Event, error)
	Truncate                   func(s string, n int) string
	Unactivated                func(r *state.ExecutionRecord) bool
	UnmergedHoldReason         func(repo string, recent []UnmergedPull, limit int, window time.Duration) string
	UnmergedWindowLabel        func(d time.Duration) string
}

Command is the command package's functions the loop calls. They stay there until their own packages exist; a field goes when its function has moved to a package the loop can import.

var Cmd Command

Cmd is the command's functions, set by the command before any loop runs.

type DeliveryFlow

type DeliveryFlow struct {
	Class       string `json:"class"`
	Reason      string `json:"reason,omitempty"`
	MissingNote bool   `json:"missingNote,omitempty"`
}

type DeliveryWIP

type DeliveryWIP struct {
	Limit      int              `json:"limit"`
	Count      int              `json:"count"`
	Items      []state.Delivery `json:"items"`
	CompleteAt time.Time        `json:"complete_at"`
	Reason     string           `json:"reason,omitempty"`
}

type DiskHolding

type DiskHolding struct {
	At   time.Time `json:"at"`
	Text string    `json:"text"`
}

type EligibleWait

type EligibleWait struct {
	Head, URL string
	Since     time.Time
}

type EpicDelivery

type EpicDelivery struct {
	Item     board.Item   `json:"item"`
	Ref      string       `json:"ref"`
	URL      string       `json:"url"`
	Children []board.Item `json:"children"`
	Missing  []string     `json:"missing,omitempty"`
}

type EpicSnapshot

type EpicSnapshot struct {
	At    time.Time      `json:"at"`
	Epics []EpicDelivery `json:"epics"`
}

type FillPause

type FillPause struct {
	Capacity string

	Until time.Time
	// contains filtered or unexported fields
}

FillPause holds the refill's board reads after an unproductive one: the capacity limits it saw and the agents then live (on the roster, not done).

func (FillPause) Changed

func (p FillPause) Changed(capacity string, live []string) bool

Changed reports whether capacity is not as it was or an agent the pause saw live has since been done or removed. An agent joining makes no room and changes nothing.

func (FillPause) Holds

func (p FillPause) Holds(now time.Time, capacity string, live []string) bool

Holds reports whether the pause still defers a board read: its interval runs and nothing it saw changed (changed).

type Host

type Host interface {
	AllowMonitoredIssue(ctx context.Context, ref string) error
	AssignExecutionReview(ctx context.Context, act superloop.Action) error
	BoardClient() *board.Client
	Cfg() *config.Config
	CfgPath() string
	CheckDeliveries(now time.Time) (string, error)
	CheckThroughput(now time.Time, held bool, progress ...func()) (string, error)
	CleanRemovedWorktree(ctx context.Context, dir string, publishedHead string)
	ClearLoopVersion()
	ConsumeReports(ctx context.Context) error
	DeliveryExemptIntake(st *state.State) bool
	DeliveryPolicy() any
	EndAgy(ctx context.Context, id string) string
	ExecutionHost(selector string) (execution.Host, error)
	ExecutionMergeDecisionLive(ctx context.Context, st *state.State, use execution.MergeUse, loopDecision bool) error
	FatalAdmission(name string, review bool) error
	FatalPublicationBarrier(ctx context.Context, st *state.State, repo string, pr int) error
	FinishReviewRequest(act superloop.Action, started bool)
	HoldOn(ctx context.Context, notes []state.Note, ref string) (*state.ItemHold, error)
	HostPinToolsCurrent(pin state.HostPin, h execution.Host) bool
	HostPlacementViews(st *state.State) []capacity.HostPlacementView
	LastNoteContext(ctx context.Context, p state.Party, since time.Time, progress ...func()) (string, bool, error)
	LoadedCfg() string
	LoopGitHub(ctx context.Context, step string, run func() error) error
	LoopNow() *atomic.Pointer[time.Time]
	MonitoredIssueStarted(ctx context.Context, ref string) error
	NextMonitoredIssue(ctx context.Context, skip ...string) (*LoopBoardItem, error)
	Now() time.Time
	OperationOutcome(operation string, reason string, rawURL string, success bool) error
	// OtherDeskClaim is another desk's live claim on issue (owner/repo#n)
	// in a line ("desk <name> (session …) since …"), "" when none holds it
	// or the desk reads no claims (board.claims.off).
	OtherDeskClaim(ctx context.Context, issue string) (string, error)
	Out() io.Writer
	ParkIsPull(ctx context.Context, st *state.State, ref string) bool
	PrepareEventSegmentation() error
	ReadWatchLevel(kind string, value any) (time.Time, error)
	RecordAgyQuotaExhaustedForID(id string, model string, qerr *agy.QuotaError, now time.Time)
	RecordFatalRepair(owner string, ref string) error
	RecoveryHeld() string
	ReserveReview(act superloop.Action) error
	ResetFirst(st *state.State) bool
	RuleModel(name string, kind string) string
	Sessions() ([]*claude.Session, *proc.Table, error)
	SetCfg(v *config.Config)
	SetLoopNow(v *atomic.Pointer[time.Time])
	SetNow(v time.Time)
	SetOut(v io.Writer)
	SnapshotAtNow() Host
	StartLoopWatch(ctx context.Context) func()
	Store() state.Store
	SyncClaims(ctx context.Context) error
	TimeNow() time.Time
	UnmergedPolicy() (int, time.Duration)
	WriteLoopVersion() error
}

Host is the command the loop runs in: its configuration, state, clock and output, and the command's own steps the loop takes. The command's app is the one implementation; the loop holds no other reference to it.

type Loop

type Loop struct {
	Recording *LoopRecording
	Lifecycle *LoopLifecycle
	ReviewDir string // explicit agents review checkout
	Mu        sync.Mutex
	Host      Host
	Since     time.Time
	// startedAt is when this process's loop started: a next action for a
	// done event before it is settled by the refill (staleNext).
	StartedAt time.Time
	Once      bool
	// said are the failures already printed, by key.
	Said map[string]bool

	StartsHeld bool
	StopWatch  func()

	StopRefill     func()
	RefillConfigMu sync.RWMutex
	// tidyAt is when the loop last ran board tidy.
	TidyAt time.Time
	// stages are the release or intake stages finished, by key; stageDetail
	// is the recorded detail of each stage.
	Stages      map[string]bool
	StageDetail map[string]string
	PostMerge   []superloop.Action
	// FillPause defers an unproductive board read until capacity changes,
	// an agent is done or removed, or the configured retry interval passes.
	FillPause FillPause
	// fillEmpty counts the refill's unproductive board reads since its last
	// start or a change that ended its pause; each one doubles the next
	// pause, up to fillBackoff times.
	FillEmpty   int
	FillRetries map[string]fillRetry

	IndependentFill bool

	// boardNone is this pass's empty or failed board next answer: every
	// later start of the pass takes it instead of walking the board again.
	BoardNone *loopBoardNone
	// stall is the refill's flow: when it last ran and since when a start
	// waits with room (checkStall alarms on it).
	Stall     startStall
	FlowWaits map[string]flowWait
	// mergeNotes are the holds the pending merge decisions' last runs read,
	// mergeRuns the decisions dispatched to their lane's stream, both by key:
	// the stall alarm names them (checkFlowWaits).
	MergeNotes map[string]mergeNote

	// timerActs are timer side effects; shutdown and re-exec await them.
	TimerActs sync.WaitGroup

	MergeActions sync.WaitGroup
	PassActions  sync.WaitGroup

	// login is the login gh acts as, once read; teams the team files'
	// owners, read at teamsAt.
	Login   string
	Teams   map[string]string
	TeamsAt time.Time
	// dryRun prints a pass's transitions and takes none.
	DryRun bool
	// bin is the loop's running executable, checked at quiet points so an
	// install replaces this process as soon as no claim is in flight.
	Bin        Replaceable
	Reexecuted bool

	// merged are the merged pull requests read, by reference.
	Merged map[string]superloop.Pull
	// pulls holds the dated observations consumed by the pass. pullWatch
	// owns their refresh independently of the pass and desk events.
	Pulls map[string]LoopPullObservation

	// fillPreview is the dry-run projection, used only by synchronous previews.
	FillPreview *state.State
	// openPulls are the desk's open pull requests the sweep last listed,
	// at openPullsAt.
	OpenPulls       []string
	OpenPullsAt     time.Time
	SweepIncomplete bool
	Unmerged        map[string]LoopUnmergedObservation
	UnmergedCursor  string
	DefaultBranches map[string]string
	// contains filtered or unexported fields
}

Loop is one run of the loop: what it said once.

func NewLoop

func NewLoop(a Host, dryRun bool, progress ...func()) (*Loop, error)

NewLoop logs the loop's start, unless it is a dry run, and bounds its events by its first.

func (*Loop) As

func (l *Loop) As(args ...string) []string

As is a beekeeper command line the loop runs as itself.

func (*Loop) BackgroundContext

func (l *Loop) BackgroundContext(ctx context.Context) context.Context

func (*Loop) BeginInFlight

func (l *Loop) BeginInFlight(key string) bool

func (*Loop) Brief

func (l *Loop) Brief(file, def, key string, d BriefData) (string, error)

Brief renders the template in file (def when file is empty) with d into a file under the state's directory, named after key.

func (*Loop) CachePull

func (l *Loop) CachePull(ref string, p superloop.Pull)

func (*Loop) CancelBackgroundActions

func (l *Loop) CancelBackgroundActions()

func (*Loop) CheckFlowWaits

func (l *Loop) CheckFlowWaits(in superloop.Input, actions []superloop.Action, failures map[string]LoopFailure) error

CheckFlowWaits measures the planner's pending merge decisions every pass. Holds and in-flight commands remain pending, so they cannot silently turn a stalled lane into a healthy one. A new head starts a new episode; a settled decision clears it. Unread pulls retain their episodes and are alarmed as unread: no pass plans or runs their decision.

func (*Loop) CheckHostUtilization

func (l *Loop) CheckHostUtilization(snapshot *state.State) error

CheckHostUtilization retains one starvation episode across loop restarts and coordinator releases. Successful remote starts end it; an idle desk without local worker starts never opens one. No audit-history replay is needed.

func (*Loop) CheckPullStall

func (l *Loop) CheckPullStall() error

CheckPullStall raises one alarm, through the loop's file channel that guide watch says as GUIDE PROBLEM, when the continuous pull watch has not completed a poll for LoopPullStallAfter, measured from its start after a restart: no parked pull request gets its desk review, merge decision or CI wake until it does. A watch that kept failing went unnoticed for a day (#3809). The alarm names the failed tries and the last error, once per episode; SUPERVISOR STALL ENDED says when a poll completes again.

func (*Loop) CheckStall

func (l *Loop) CheckStall() error

CheckStall raises one alarm, through the loop's file channel that guide watch says as GUIDE PROBLEM, when worker starts do not move: the refill has not run for LoopStallAfter (the worker stream is stuck ahead of it), or it had room and a board item for LoopStallAfter yet started nothing. The alarm names the cause it read, once per episode.

func (*Loop) CheckUnmergedBacklogs

func (l *Loop) CheckUnmergedBacklogs(ctx context.Context, in superloop.Input) error

CheckUnmergedBacklogs inspects active repositories in the pass so a repository that accumulates supervisor.unmergedLimit open pull requests in supervisor.unmergedWindow escalates to the guide even when board next skips it before startItem, and clears its stage once the backlog drains.

func (*Loop) CheckpointThroughput

func (l *Loop) CheckpointThroughput(now time.Time) error

CheckpointThroughput reports bounded pass progress before expensive history loading. Keep eligibility ages intact until planning can observe them afresh. Use wall time: the pass snapshot can already be minutes old after handover. This is not a background keepalive; a stuck pass stops refreshing it.

func (*Loop) Classify

func (l *Loop) Classify(ctx context.Context, st *state.State, act superloop.Action) (string, error)

Classify routes an event the rules cannot place to the guide, with the classifier's class when it is sure enough.

func (*Loop) ClearSaid

func (l *Loop) ClearSaid(key string)

func (*Loop) CompleteEpics

func (l *Loop) CompleteEpics(ctx context.Context, st *state.State) error

Completion requires the owner's explicit proof report and a fresh GitHub observation that no child remains open. A merge alone is never acceptance.

func (*Loop) ContinueParks

func (l *Loop) ContinueParks(ctx context.Context, st *state.State) error

ContinueParks consumes durable events only after a fresh start is accepted. A stable replacement name makes a coordinator restart after launch idempotent. Failed placement or delivery leaves the task and all its events parked.

func (*Loop) DeferFill

func (l *Loop) DeferFill(ref string)

func (*Loop) DeliveryFillRoom

func (l *Loop) DeliveryFillRoom(room int, st *state.State, reserved ...[]string) int

func (*Loop) DeliveryReservations

func (l *Loop) DeliveryReservations(st *state.State) ([]string, deliverySkips)

DeliveryReservations identifies existing deliveries before new work competes with the independent review and transition streams. Read durable observations so a pending start from an earlier pass reserves room too. A delivery reserves only a start the loop will make: in a repository the desk works on and no hold stops, for a review not yet requested at its head, and only for supervisor.reserveFor after its step began. Older ones are stalled deliveries, not slots held from new work.

func (*Loop) DeliveryReservedRefs

func (l *Loop) DeliveryReservedRefs(st *state.State, reserved ...[]string) ([]string, deliverySkips)

Keep earlier reservations even after their starts register, and include observations committed by an older stream since this pass was planned.

func (*Loop) DeliveryRoom

func (l *Loop) DeliveryRoom(room int, st *state.State, reserved ...[]string) int

DeliveryRoom is room less the slots the deliveries reserve, which are at most half of room: a pile of deliveries never stops every new start.

func (*Loop) DropInvalidMergeRepairs

func (l *Loop) DropInvalidMergeRepairs(taken []superloop.Taken, stages map[string]bool, stageDetail map[string]string) ([]superloop.Taken, error)

DropInvalidMergeRepairs also retires persisted repairs whose merge-result head contradicts the decision. It undoes a branch repair an older loop requested for a merge refused by base branch policy: no branch change repairs that refusal. Its repair stage and the go it completed are closed durably, so the unchanged approved head is merged again on this pass without a new review or the worker's action. A repair stage for any other reason stands.

func (*Loop) EndInFlight

func (l *Loop) EndInFlight(key string)

func (*Loop) EndMerged

func (l *Loop) EndMerged(ctx context.Context, st *state.State, act superloop.Action) (string, error)

EndMerged closes tasks that explicitly declared no post-merge work and wakes only tasks with a remaining release, rollout or proof. Older parks retain the existing release-containment and retirement behavior.

func (*Loop) EndReviewWorkers

func (l *Loop) EndReviewWorkers(ctx context.Context, st *state.State) error

func (*Loop) ExecAction

func (l *Loop) ExecAction(ctx context.Context, st *state.State, claims map[string]LoopClaim, failures map[string]LoopFailure, act superloop.Action, reserved ...[]string) error

func (*Loop) Failed

func (l *Loop) Failed(act superloop.Action, failures map[string]LoopFailure, cause error) error

Failed logs act's failure and keeps it in failures, by key.

func (*Loop) Fill

func (l *Loop) Fill(ctx context.Context, st *state.State, claims map[string]LoopClaim, taken []superloop.Taken, reserved ...[]string) (result error)

Fill fills every free slot up to capacity.ceiling without waiting for a done event. Each start checks live capacity again; the first pass room also bounds this pass if a capacity read has not yet caught up with a start. The local room bounds the pass only when no start can be placed on an execution host: with supervisor.hosts each start's placement judges the local machine and every host itself, so a full coordinator still fills onto hosts. Claims are per board item, so an interrupted start is reconciled before another start.

func (*Loop) FillCapacity

func (l *Loop) FillCapacity(ctx context.Context) *capacity.View

func (*Loop) FillRan

func (l *Loop) FillRan()

FillRan marks a run of the refill: the worker stream reached it.

func (*Loop) FillRoom

func (l *Loop) FillRoom(cap *capacity.View) int

FillRoom is how many worker slots this pass can fill toward capacity.ceiling. Local room bounds the pass only when no start can be placed on an execution host; with supervisor.hosts, a hold across all providers (no choice picked and no local machine headroom block) also yields 0 so the pass does not query the board while every provider is held by pace, usage or its ceiling.

func (*Loop) FillSkipped

func (l *Loop) FillSkipped() []string

func (*Loop) FinishContinuation

func (l *Loop) FinishContinuation(old state.Agent, name string) error

FinishContinuation runs in the command, which holds what it needs (loopFinishContinuation).

func (*Loop) HoldStarts

func (l *Loop) HoldStarts(held bool)

func (*Loop) HoldingStarts

func (l *Loop) HoldingStarts() bool

func (*Loop) Install

func (l *Loop) Install(ctx context.Context, act superloop.Action) (string, error)

Install takes release act.Version through its stages, each resumed on a later pass while the release's claim stands: the install (self-update, while --check still finds it newer), the broker on the installed binary, supervisor.postInstall (once), then --check finding it the latest.

func (*Loop) IsCompleted

func (l *Loop) IsCompleted(key string) bool

func (*Loop) LifecyclePhase

func (l *Loop) LifecyclePhase(phase string)

func (*Loop) LoadCache

func (l *Loop) LoadCache()

func (*Loop) MergePull

func (l *Loop) MergePull(ctx context.Context, _ *state.State, act superloop.Action) (result string, resultErr error)

MergePull executes the planner's exact-head decision in the coordinator, including for workers on an execution host. Failed or unreadable validation never delegates a direct merge around the required server-side queue.

func (*Loop) MergeStarted

func (l *Loop) MergeStarted(acts []superloop.Action, i int)

MergeStarted marks acts[i] running and the rest of its stream behind it.

func (*Loop) MergeStreamEnded

func (l *Loop) MergeStreamEnded(acts []superloop.Action)

MergeStreamEnded forgets the runs of a lane's stream that ended.

func (*Loop) MergeWaited

func (l *Loop) MergeWaited(act superloop.Action, err error)

MergeWaited keeps why a merge decision's run did not settle it.

func (*Loop) NewerRelease

func (l *Loop) NewerRelease(ctx context.Context) string

NewerRelease is a newer release's version, "" when this is the latest or the look failed; a failed look is said, once until it succeeds again, so the desk does not stay on an old release unnoticed.

func (*Loop) NextItem

func (l *Loop) NextItem(ctx context.Context) (*LoopBoardItem, error)

NextItem is the board's first free ranked item, or nil when none is free. A walk costs a large share of the GraphQL budget: an empty or failed one answers the rest of the pass. No walk runs while the GitHub budget is under github.floor: the pass answers ErrLoopLater, so a done event waits unsettled and costs nothing.

func (*Loop) ObserveDeliveries

func (l *Loop) ObserveDeliveries(ctx context.Context, in superloop.Input, unread map[string]bool) error

func (*Loop) ObservePull

func (l *Loop) ObservePull(ctx context.Context, ref string, changed time.Time) (superloop.Pull, error)

func (*Loop) ObservePullStep

func (l *Loop) ObservePullStep(ctx context.Context, ref string, changed time.Time, step string) (superloop.Pull, error)

Observation lookup performs no IO against GitHub. Keep the original read time when copying a watcher's observation into this pass's action cache.

func (*Loop) ObserveThroughput

func (l *Loop) ObserveThroughput(in superloop.Input, actions []superloop.Action, unknown bool) error

func (*Loop) Pass

func (l *Loop) Pass(ctx context.Context) (result error)

Pass is one look: gather, plan, act.

func (*Loop) PauseFill

func (l *Loop) PauseFill(capacity string, live []string)

PauseFill defers the refill's next board read by supervisor.fillRetryEvery, doubled for each unproductive read before it since the last start or change (fillBackoff), so an empty board is walked less and less often.

func (*Loop) PauseForReexec

func (l *Loop) PauseForReexec() bool

PauseForReexec lets outstanding streams drain without launching more work on a replaced binary. Only the main loop calls reexec at the quiet point.

func (*Loop) PlacesRemotely

func (l *Loop) PlacesRemotely() bool

PlacesRemotely says whether the loop's starts may be placed on an execution host: supervisor.hosts names one and capacity.choices gives a remote start its model name. Then the local room alone never stops a start; startPlacement judges each host's too.

func (*Loop) PreviewFill

func (l *Loop) PreviewFill(ctx context.Context) error

func (*Loop) PullWatcher

func (l *Loop) PullWatcher() *loopPullWatcher

func (*Loop) ReadFillCapacity

func (l *Loop) ReadFillCapacity(ctx context.Context) (*capacity.View, error)

func (*Loop) ReadNextItem

func (l *Loop) ReadNextItem(ctx context.Context, onlyExempt ...bool) (*LoopBoardItem, error)

ReadNextItem reads board next --json. With nothing free board next exits 3 after printing its document with no pick: that is the board's answer, nothing free, never a failure to retry.

func (*Loop) Reconcile

func (l *Loop) Reconcile(ctx context.Context, st *state.State, act superloop.Action, c LoopClaim) (string, bool, error)

Reconcile decides a claimed action from the log since its claim: done when the command it ran left its line (agents start, agents wake, agents remove, note add, all logged as the loop), else not, and it runs. A start on an execution host logs its line at the reservation; one whose reservation was released after it, unacknowledged by the host, started nothing.

func (*Loop) Record

func (l *Loop) Record(act superloop.Action, what string) error

Record logs act taken, which no pass takes again, and says it.

func (*Loop) RecordHostPlacement

func (l *Loop) RecordHostPlacement(selector, repo, reason string)

func (*Loop) RecoverParks

func (l *Loop) RecoverParks(ctx context.Context, st *state.State) error

RecoverParks repairs settled waits whose local worker no longer exists. Discovery failure is not evidence that a worker ended. Managed executions have their own lifecycle and must never be replaced by a local start.

func (*Loop) RecoverQuota

func (l *Loop) RecoverQuota(ctx context.Context, st *state.State) error

RecoverQuota re-queues the task of any local agy worker or reviewer whose run ended with a quota error on another choice. Its bucket is marked full until reset, which goneAgent already frees the slot for. The entry and its quota marker stay until a replacement started: a held, refused or failed start leaves them for the next pass, so no task is lost.

func (*Loop) RecoverReviewRequests

func (l *Loop) RecoverReviewRequests(ctx context.Context, st *state.State) error

RecoverReviewRequests upgrades explicit review waits only after re-proving their published worktree. Older parks omitted Worktree; their recorded start directory supplies it. An API failure leaves the request pending for a later pass after budget recovery, never granting authority from the wait text alone.

func (*Loop) Reexec

func (l *Loop) Reexec(ctx context.Context) (bool, error)

Reexec re-executes the loop on the binary installed over its path at a quiet point (no claim in flight). It returns true when the replacement binary was executed, so the caller ends the pass on the old binary.

func (*Loop) ReexecBusy

func (l *Loop) ReexecBusy() bool

func (*Loop) RefillTick

func (l *Loop) RefillTick(ctx context.Context) error

func (*Loop) ReloadConfig

func (l *Loop) ReloadConfig()

ReloadConfig refreshes l.a.cfg from disk when the configured file changed since startup or the last pass, so live config edits and settled overrides take effect without restarting the loop process.

func (*Loop) Remove

func (l *Loop) Remove(ctx context.Context, name, reason string) error

Remove takes name off the roster, saying why in the log. An agent already gone is removed: the doctor or a person can take it off between the pass's reading and this call, and a step must not fail forever on work done.

func (*Loop) RepoRecentUnmerged

func (l *Loop) RepoRecentUnmerged(ctx context.Context, repo string) ([]UnmergedPull, string, error)

func (*Loop) RepositoryStart

func (l *Loop) RepositoryStart(ref string) error

RepositoryStart rereads immediately before dispatch, so a hold set while the board or GitHub was being read cannot launch another worker.

func (*Loop) RestartPark

func (l *Loop) RestartPark(ctx context.Context, ag state.Agent, ref string) error

func (*Loop) RestartWaits

func (l *Loop) RestartWaits() bool

RestartWaits says the restart into the replaced binary waits for the claims in flight (Reexec), the state not fenced: the passes go on planning and run the merge decisions only, so no merge waits on a restart that waits on a merge.

func (*Loop) Roster

func (l *Loop) Roster(ctx context.Context, planned map[string]bool) error

Roster runs in the command, which holds what it needs (loopRoster).

func (*Loop) Run

func (l *Loop) Run(ctx context.Context, args ...string) (string, error)

Run runs a beekeeper command as the loop; a non-zero exit is an error with its output.

func (*Loop) RunPassActions

func (l *Loop) RunPassActions(ctx context.Context, st *state.State, claims map[string]LoopClaim, failures map[string]LoopFailure, taken []superloop.Taken, actions []superloop.Action) (result error)

RunPassActions runs merges, review starts, intake, worker starts and PR/worker transitions independently so a merge waiting on CI or in a lane queue never delays a review or worker start, and the reverse.

func (*Loop) RunRefillCadence

func (l *Loop) RunRefillCadence(ctx context.Context, ticks <-chan time.Time)

func (*Loop) RunStart

func (l *Loop) RunStart(ctx context.Context, act superloop.Action, args ...string) (string, error)

Keep retry/backoff decisions out of this ledger. Only a command actually attempted contributes; capacity and budget refusals are intentional holds.

func (*Loop) SaveCache

func (l *Loop) SaveCache()

func (*Loop) SayOnce

func (l *Loop) SayOnce(key, format string, args ...any)

SayOnce prints a failure once per key and run.

func (*Loop) SetFillPhase

func (l *Loop) SetFillPhase(phase string)

func (*Loop) SettleAlertWake

func (l *Loop) SettleAlertWake(act superloop.Action, ag state.Agent) error

End exactly the park whose wake was delivered, and record completion in the same save. A fast worker may already have parked on a new event.

func (*Loop) SettleStaleNext

func (l *Loop) SettleStaleNext(stale []superloop.Action) error

SettleStaleNext records the stale next actions as taken, in one write and without a board read or a start, so no later plan holds them, and says how many once.

func (*Loop) StaleNext

func (l *Loop) StaleNext(act superloop.Action) bool

StaleNext reports whether act is a next action for a done event older than StaleNextAfter or than the start of this running loop. The refill fills every free slot without a done event, so such an action has nothing left to start; a backlog of them only kept the refill from running.

func (*Loop) StallClear

func (l *Loop) StallClear()

StallClear ends a start wait: a worker started, the board offers nothing or no slot is free.

func (*Loop) StallWait

func (l *Loop) StallWait(ref, why string)

StallWait records that the refill had room yet started nothing, and why. The episode keeps its first time; the item and cause are the latest.

func (*Loop) StartFixer

func (l *Loop) StartFixer(ctx context.Context, st *state.State, act superloop.Action) error

func (*Loop) StartItem

func (l *Loop) StartItem(ctx context.Context, act superloop.Action, next LoopBoardItem, reserved ...[]string) (string, error)

func (*Loop) StartNext

func (l *Loop) StartNext(ctx context.Context, act superloop.Action, reserved ...[]string) (string, error)

StartNext starts the next ranked item with the worker brief, when capacity has room — on an execution host when supervisor.hosts names one with room (and the board item's repository is mapped there), else on the coordinator's own machine.

func (*Loop) StartReviewer

func (l *Loop) StartReviewer(ctx context.Context, act superloop.Action) (string, error)

StartReviewer starts the reviewer of act's head.

func (*Loop) Stuck

func (l *Loop) Stuck(failures map[string]LoopFailure, filed map[string]time.Time) error

Stuck files each step failing the same way for LoopStuckAfter or on more than one item, once per episode: the guide's feed says it as GUIDE PROBLEM. An episode filed before it began (filed, by step and error) is a new one.

func (*Loop) StuckGroup

func (l *Loop) StuckGroup(failures map[string]LoopFailure, kind, message string) map[string]LoopFailure

StuckGroup are the failures of kind with message attempted recently, by key.

func (*Loop) SweepPulls

func (l *Loop) SweepPulls(ctx context.Context, in superloop.Input, tracked []string) []string

SweepPulls are the desk's open pull requests the pass reads beside tracked, for the orphan sweep: listed every SweepListEvery, less those tracked already, outside the desk, or owned by an agent the roster names for them (parked on one, or its worker by name), which need no read.

func (*Loop) SyncDeliveryHolds

func (l *Loop) SyncDeliveryHolds(ctx context.Context) error

The single supervisor writer reconciles at most one board transition per pass. A recorded hold survives restarts and retains the prior Status. Note holds share that Status: neither releases the other's outstanding blocker.

func (*Loop) Tidy

func (l *Loop) Tidy(ctx context.Context, st *state.State)

Tidy runs board tidy every board.tidyEvery while a board is configured and the GitHub budget is above its floor, and says what it did.

func (*Loop) UnmergedStart

func (l *Loop) UnmergedStart(ctx context.Context, nextRef string) error

UnmergedStart checks whether nextRef's repository is held back by an unmerged pull request backlog, escalating to the guide once per episode.

func (*Loop) UpdateHosts

func (l *Loop) UpdateHosts(ctx context.Context, st *state.State)

UpdateHosts brings every execution host (agents.hosts) to the release this coordinator runs, with agents hosts update, once the coordinator runs a newer one than the host's pin or the host's entry names a policy digest the pin does not answer (hostPinPolicyCurrent): a host on which executions are in a turn drains first (a parked worker's execution between turns does not hold it back), taking no new start (HostDrains), so it updates at the first pass that finds them between turns; a held host is tried again hourly, and a development build updates none. Nothing is updated while beekeeper stop stands. Each new hold is handed on once as the loop's finding, and so is a host that stays behind for more than one release or for longer than HostBehindBound, with why.

func (*Loop) WaitNextPass

func (l *Loop) WaitNextPass(ctx context.Context) bool

WaitNextPass waits for LoopInterval, ctx.Done(), or a replaced binary so an external self-update during the idle sleep triggers re-execution without waiting the full LoopInterval on the old binary.

func (*Loop) WakeEpicOwners

func (l *Loop) WakeEpicOwners(ctx context.Context, st *state.State) error

Parked owners are woken only when their children's durable observations change. A saved signature survives loop restarts, while an unsuccessful wake retries.

func (*Loop) WakeOrStartFixer

func (l *Loop) WakeOrStartFixer(ctx context.Context, st *state.State, act superloop.Action) error

WakeOrStartFixer tells act's worker, or starts one for it. Each wait for a later pass names its cause: a merge decision's stall alarm reads it.

func (*Loop) WakeReleased

func (l *Loop) WakeReleased(ctx context.Context, release superloop.Action) error

func (*Loop) WatchConditions

func (l *Loop) WatchConditions(ctx context.Context) error

Watch conditions are lasting levels, reconstructed after a restart. Budget readings expire rather than treating a dead watch as permission to start workers. Thresholds and all source reads stay in watch.

type LoopBoardItem

type LoopBoardItem struct {
	EpicOwner bool   `json:"epic_owner,omitempty"`
	Epic      string `json:"epic,omitempty"`
	WIPExempt bool   `json:"wip_exempt,omitempty"`
	Ref       string `json:"ref"`
	URL       string `json:"url"`
}

type LoopCheck

type LoopCheck struct {
	StartedAt    time.Time `json:"startedAt"`
	WorkflowName string    `json:"workflowName"`
	Status       string    `json:"status"`
	Conclusion   string    `json:"conclusion"`
	State        string    `json:"state"`
	// A check run's name and details URL, a commit status's context and
	// target URL.
	Name       string `json:"name"`
	DetailsURL string `json:"detailsUrl"`
	Context    string `json:"context"`
	TargetURL  string `json:"targetUrl"`
}

LoopCheck is one entry of a pull request's check rollup: a check run reports a status and a conclusion, a commit status a state.

func (LoopCheck) Concluded

func (c LoopCheck) Concluded() bool

Concluded reports whether the check reached a terminal state.

type LoopClaim

type LoopClaim struct {
	At     time.Time
	Target string
}

LoopClaim is a claim read back: when, and what its side effect names (the session started, the agent woken or removed, the note's question).

type LoopFailure

type LoopFailure struct {
	Message string    `json:"message"`
	Count   int       `json:"count"`
	RetryAt time.Time `json:"retryAt"`
	Kind    string    `json:"kind,omitempty"`
	Ref     string    `json:"ref,omitempty"`
	Since   time.Time `json:"since,omitempty"`
	At      time.Time `json:"at,omitempty"`
}

LoopFailure persists identical failures across passes and restarts. Two consecutive failures defer the action for five minutes, keeping it pending; each further identical failure doubles the deferral up to an hour, so a refusal that does not change is not retried every five minutes all day. Since is when the step began failing this way, on this item or on another item still failing the same way; At is the latest attempt.

type LoopLifecycle

type LoopLifecycle struct {
	Version string    `json:"version"`
	Started time.Time `json:"started"`
	At      time.Time `json:"at"`
	Phase   string    `json:"phase"`
	Exited  bool      `json:"exited"`
	Code    int       `json:"code"`
	Failure string    `json:"failure,omitempty"`
}

Phase transitions are bounded progress evidence. Only the loop holding the exclusive loop lock writes it; failed contenders cannot overwrite it. No command output, paths, configuration or lock-holder identities are saved.

type LoopPullFailing

type LoopPullFailing struct {
	Since time.Time `json:"since"`
	Tries int       `json:"tries"`
	Error string    `json:"error"`
}

LoopPullFailing is an episode of failed polls: since when, how many tries, and what the last one failed on.

type LoopPullJSON

type LoopPullJSON struct {
	Additions, Deletions int
	Closes               []struct {
		URL string `json:"url"`
	} `json:"closingIssuesReferences"`
	Updated        time.Time `json:"updatedAt"`
	Draft          bool      `json:"isDraft"`
	Mergeable      string    `json:"mergeable"`
	MergeState     string    `json:"mergeStateStatus"`
	ReviewDecision string    `json:"reviewDecision"`
	MergeCommit    struct {
		OID string `json:"oid"`
	} `json:"mergeCommit"`
	State  string      `json:"state"`
	URL    string      `json:"url"`
	Head   string      `json:"headRefOid"`
	Base   string      `json:"baseRefName"`
	Rollup []LoopCheck `json:"statusCheckRollup"`
	Author loopLogin   `json:"author"`
	Title  string      `json:"title"`
	Body   string      `json:"body"`
	Branch string      `json:"headRefName"`
	Files  []struct {
		Path string `json:"path"`
	} `json:"files"`
	ChangedFiles int `json:"changedFiles"`
	Reviews      []struct {
		ID          string    `json:"id"`
		Author      loopLogin `json:"author"`
		Association string    `json:"authorAssociation"`
		Body        string    `json:"body"`
		State       string    `json:"state"`
		At          time.Time `json:"submittedAt"`
		Commit      struct {
			OID string `json:"oid"`
		} `json:"commit"`
	} `json:"reviews"`
}

LoopPullJSON is gh pr view's answer.

type LoopPullObservation

type LoopPullObservation struct {
	Pull    superloop.Pull
	At      time.Time
	Changed time.Time
}

type LoopPullSchedule

type LoopPullSchedule struct {
	Failures int
	// contains filtered or unexported fields
}

LoopPullSchedule is the watch's episode of failed polls: how many, since when.

func (*LoopPullSchedule) After

func (s *LoopPullSchedule) After(l *Loop, next time.Duration, err error) time.Duration

After schedules the next poll. A failed poll is said at every try, with its count and the next try, and the poll that ends the episode says so: a watch whose later failures went unsaid looked dead for a day while it retried (#3809). A budget hold, which ends on its own, is said once.

type LoopPullSnapshot

type LoopPullSnapshot struct {
	Pulls      map[string]WatchedLoopPull `json:"pulls"`
	Open       []string                   `json:"open,omitempty"`
	ListedAt   time.Time                  `json:"listedAt"`
	Incomplete bool                       `json:"incomplete,omitempty"`
	// PolledAt is when a poll last read every pull request it asked for.
	PolledAt time.Time `json:"polledAt,omitzero"`
	// Failing is the episode of failed polls the watch is in, nil once a
	// poll succeeds.
	Failing *LoopPullFailing `json:"failing,omitempty"`
}

func (LoopPullSnapshot) AgeLine

func (s LoopPullSnapshot) AgeLine(now time.Time) string

func (LoopPullSnapshot) FailingLine

func (s LoopPullSnapshot) FailingLine(now time.Time) string

FailingLine says the watch's episode of failed polls, "" while it reads.

type LoopRecording

type LoopRecording struct {
	Planner    superloop.Input
	Facts      []loopRecordedFact
	Agents     []state.Agent
	Deliveries []state.Delivery
	Room       int
}

LoopRecording includes the data for the pure planner and the separate continuation/reservation planners. No configuration or credentials are copied.

func (*LoopRecording) Capture

func (r *LoopRecording) Capture(in superloop.Input) superloop.Input

func (*LoopRecording) ReplayInput

func (r *LoopRecording) ReplayInput() superloop.Input

type LoopSweepCount

type LoopSweepCount struct {
	At time.Time `json:"at"`
	// Listed is the open pull requests the last list held; AtLimit says the
	// list may have stopped short of them.
	Listed  int  `json:"listed"`
	AtLimit bool `json:"atLimit,omitempty"`
	// Ownerless is how many have no live owner, the oldest since Oldest.
	Ownerless int       `json:"ownerless"`
	Oldest    time.Time `json:"oldest,omitzero"`
	// Unread is how many the pass left for a later one.
	Unread int `json:"unread,omitempty"`
}

LoopSweepCount is what the last pass knew of the desk's open pull requests: a growing pile nobody owns is visible, not silent.

func (LoopSweepCount) Line

func (c LoopSweepCount) Line(a Host) string

Line says the count in one line, "" when no pull request lacks an owner.

type LoopUnmergedObservation

type LoopUnmergedObservation struct {
	Pulls  []UnmergedPull
	Etag   string
	At     time.Time
	FullAt time.Time
	// contains filtered or unexported fields
}

type LoopVersionRecord

type LoopVersionRecord struct {
	PID     int    `json:"pid"`
	Version string `json:"version"`
}

type LoopWorkflowRun

type LoopWorkflowRun struct {
	ID         uint64 `json:"id"`
	WorkflowID uint64 `json:"workflow_id"`
	Attempt    int    `json:"run_attempt"`
	Head       string `json:"head_sha"`
	Name       string `json:"name"`
	URL        string `json:"html_url"`
	Status     string `json:"status"`
	Conclusion string `json:"conclusion"`
}

LoopWorkflowRun identifies a workflow independently of its display name. Run IDs order new suites; run attempts order reruns of the same suite.

type PullBatchFault

type PullBatchFault struct{ Err error }

PullBatchFault is GitHub failing a pull batch rather than refusing it: a 5xx, no answer in time, or a body that is not JSON (GitHub's HTML error page, an empty or a cut-off body). A smaller batch may pass where this one failed.

func (*PullBatchFault) Error

func (f *PullBatchFault) Error() string

func (*PullBatchFault) Unwrap

func (f *PullBatchFault) Unwrap() error

type PullBudgetHold

type PullBudgetHold struct {
	Cause string
	Until time.Time
}

PullBudgetHold is the pull watch held by the GitHub budget: its cause, and when the hold ends on its own (the reset of a low or refused window). An unknown or stale reading has no end of its own: the next poll takes a fresh reading.

func (*PullBudgetHold) Error

func (h *PullBudgetHold) Error() string

func (*PullBudgetHold) Unwrap

func (h *PullBudgetHold) Unwrap() error

type RefillStartError

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

Command refusals and repository observation failures are item-specific; global admission gates remain pass-wide waits.

func (*RefillStartError) Error

func (e *RefillStartError) Error() string

func (*RefillStartError) Unwrap

func (e *RefillStartError) Unwrap() error

type Replaceable

type Replaceable interface {
	Replaced() bool
	Exec(env ...string) error
}

Replaceable is the running binary as the loop sees it: whether an install renamed another file over its path, and its re-execution.

type TakenFold

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

TakenFold is the loop's own history folded into what a pass plans from: steps taken, claims, finished stages, ownerless and failing steps. The history only grows, so a pass folds the events appended since the last one instead of parsing every supervisor.* event again.

func (*TakenFold) Fold

func (f *TakenFold) Fold(history []state.Event) foldedTaken

Fold takes in history, the loop's supervisor.* events oldest first, and returns a copy of the result. A history shorter than the one folded, or one that differs at its last folded event, is folded from the start.

type ThroughputObservation

type ThroughputObservation struct {
	Candidate string
	At        time.Time
	Unknown   bool
	Eligible  map[string]EligibleWait
}

type UnmergedPull

type UnmergedPull struct {
	Number      int       `json:"number"`
	URL         string    `json:"url"`
	State       string    `json:"state"`
	CreatedAt   time.Time `json:"createdAt"`
	IsDraft     bool      `json:"isDraft"`
	HeadRefName string    `json:"headRefName"`
	Title       string    `json:"title"`
	Body        string    `json:"body"`
	Closing     []struct {
		Number     int `json:"number"`
		Repository struct {
			NameWithOwner string `json:"nameWithOwner"`
		} `json:"repository"`
	} `json:"closingIssuesReferences"`
}

UnmergedPull is an open pull request in a repository, read to check whether recent unmerged work exceeds supervisor.unmergedLimit or whether an open pull request already closes an issue.

type WatchedLoopPull

type WatchedLoopPull struct {
	Pull    superloop.Pull `json:"pull"`
	At      time.Time      `json:"at"`
	Pending bool           `json:"pending,omitempty"`
	Error   string         `json:"error,omitempty"`
}

Only the watcher writes these observations. Consumers never renew a read's timestamp by reusing it, and never fall back to a synchronous GitHub read.

Jump to

Keyboard shortcuts

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