Documentation
¶
Overview ¶
Package pkg implements the GitHub build watcher service. It polls the GitHub Actions API for failed CI workflow runs on default branches, derives a per-repo green/red state, and publishes CreateTaskCommand to Kafka on green → red transitions.
Index ¶
- Constants
- Variables
- func DeriveTaskID(owner, repo, episodeSHA string) uuid.UUID
- func DeriveTaskIDForce(owner, repo, episodeSHA, nonce string) uuid.UUID
- func NewMemDB() libkv.DB
- func NewResetCursorHandler(cursorPath string) http.Handler
- func SaveCursor(ctx context.Context, path string, c *Cursor) error
- type AllowlistSnapshot
- type Cursor
- type GitHubClient
- type Metrics
- type RepoState
- type StaticSnapshot
- type Watcher
- type WorkflowJobInfo
- type WorkflowRun
Constants ¶
const DefaultCursorPath = "/data/cursor.json"
DefaultCursorPath is the default path for cursor state persistence.
const DefaultMaxTitleLen = 200
DefaultMaxTitleLen is the default safety cap for build-failure filenames. Override via MAX_TITLE_LEN.
Variables ¶
var DependabotGraphUpdatePrefixes = []string{
"Graph Update:",
"Dependabot Updates",
}
DependabotGraphUpdatePrefixes are workflow-name prefixes used by Dependabot for internal graph-maintenance jobs. These are NOT real CI failures — their HTTP 503s are Dependabot's own service being temporarily flaky. The real CI workflows on the same commits succeed. These runs must not trigger OpenClaw build-failure tasks.
var ErrRateLimited = stderrors.New("github rate limited")
ErrRateLimited is returned when the GitHub API responds with a rate-limit or abuse-rate-limit error.
Functions ¶
func DeriveTaskID ¶
DeriveTaskID returns a deterministic task identifier for a build-failure episode. Input: "<owner>/<repo>#build-<episodeSHA>", e.g. "bborbe/maintainer#build-abc123".
func DeriveTaskIDForce ¶
DeriveTaskIDForce returns a salted task identifier for an operator-forced re-publish of a build-failure episode (spec 069). The salt is a caller-supplied nonce — typically a microsecond timestamp from libtime.CurrentDateTimeGetter — so successive forced re-publishes for the same (owner, repo, episodeSHA) produce distinct identifiers and the agent controller's deterministic-ID dedup-skip does NOT fire. Pure function; nonce uniqueness is the caller's responsibility.
Key format: "<owner>/<repo>#build-<episodeSHA>!<nonce>". The "!" separator is invalid in GitHub owners/repos and in hex SHAs, so the salted keyspace cannot collide with the canonical DeriveTaskID keyspace for any (owner, repo, sha) tuple.
func NewMemDB ¶
NewMemDB returns a session-scoped, in-process libkv.DB implementation. It exists because libkv itself does not ship a public NewMemDB constructor (the upstream bborbe/kv package exposes only NewDBWithMetrics). The github-release watcher's command consumer needs an offset store; this in-memory implementation gives it one without requiring a PVC.
The implementation is intentionally minimal — it implements only the methods the offset-store / consumer wiring touches: Update, View, Sync, Close, Remove, Stats, StatsDetailed. Iterator / ListBucketNames return empty results because no caller in this package uses them.
func NewResetCursorHandler ¶
NewResetCursorHandler returns an HTTP handler that clears the cursor entry for one repo. Repo is taken from the {repo} URL variable (e.g. "github.com/bborbe/maintainer"). Releases an episode lock so the next poll detects the build state from scratch and may publish a fresh create-task.
Wrap with libhttp.NewDangerousHandlerWrapper at the call site to require a passphrase — the bare handler does not enforce auth.
Race: a concurrent Poll may overwrite the reset; operator should retry if the next poll log doesn't show a state transition for the target repo.
Types ¶
type AllowlistSnapshot ¶
type AllowlistSnapshot interface {
Snapshot() []string
}
AllowlistSnapshot returns the current set of concrete "host/owner/repo" entries the poll loop should iterate. Implementations MUST be safe to call from a goroutine concurrent with a refresh writer.
type GitHubClient ¶
type GitHubClient interface {
// GetWorkflowRuns returns completed workflow runs for a repo branch.
// In-progress runs (empty Conclusion) are filtered out.
GetWorkflowRuns(ctx context.Context, owner, repo, branch string) ([]WorkflowRun, error)
// GetDefaultBranch returns the default branch name for a repository.
GetDefaultBranch(ctx context.Context, owner, repo string) (string, error)
// GetFileContent fetches the raw content of a file at the given ref.
// Returns (nil, nil) if the file does not exist (HTTP 404 — the common case).
// Returns (nil, ErrRateLimited) when rate-limited.
// Returns (nil, err) for any other API error.
GetFileContent(ctx context.Context, owner, repo, path, ref string) ([]byte, error)
// GetJobsForRun returns info about failed jobs in a run.
// Returns an empty slice (not an error) when the run has no failed jobs.
// Returns (nil, ErrRateLimited) when rate-limited.
// Returns (nil, err) for other API errors.
GetJobsForRun(ctx context.Context, owner, repo string, runID int64) ([]WorkflowJobInfo, error)
// GetJobLog fetches the plain-text log for a workflow job by following GitHub's
// redirect to an Azure storage URL. Returns (nil, nil) when the URL is unavailable.
// Returns (nil, err) for a non-nil error where the log should be omitted.
// Rejects payloads > 1 MiB before truncation (returns (nil, err)).
GetJobLog(ctx context.Context, owner, repo string, jobID int64) ([]byte, error)
// ListOwnerRepos returns the names of every non-archived, non-fork
// repository owned by `owner`. Owner kind (User vs Organization) is
// detected via GET /users/<owner>; the method then calls ListByUser
// or ListByOrg respectively, paginating with PerPage=100 until done.
// Returns (nil, ErrRateLimited) when rate-limited.
// Returns (nil, err) for any other API error (network, 401/403, 404).
// Returns ([]string{}, nil) when the owner has zero eligible repos.
ListOwnerRepos(ctx context.Context, owner string) ([]string, error)
}
GitHubClient abstracts the GitHub Actions API calls.
func NewGitHubClient ¶
func NewGitHubClient(httpClient *http.Client) GitHubClient
NewGitHubClient returns a GitHubClient backed by the real GitHub API.
type Metrics ¶
type Metrics interface {
// IncPollCycle increments the poll cycle counter.
// result: "success" | "error"
IncPollCycle(result string)
// IncReposChecked increments the repos-checked counter for each repo polled.
IncReposChecked()
// IncStateTransition increments the state-transition counter.
// transition: "green_to_red" | "red_to_green"
IncStateTransition(transition string)
// IncTaskPublished increments the published-task counter.
IncTaskPublished()
// IncPollError increments the poll-error counter.
// reason: "rate_limited" | "github_error" | "kafka_error"
IncPollError(reason string)
// SetCurrentRedRepos sets the gauge to the current number of repos in red state.
SetCurrentRedRepos(count float64)
}
Metrics defines Prometheus counters and gauges for the build watcher.
func NewMetrics ¶
func NewMetrics() Metrics
NewMetrics returns a Metrics implementation backed by Prometheus counters.
type RepoState ¶
type RepoState struct {
LastKnownState string `json:"last_known_state"` // "green" | "red" | ""
CurrentEpisodeSHA string `json:"current_episode_sha"` // empty when green
DefaultBranch string `json:"default_branch"` // cached; fetched via API if empty
}
RepoState holds the persisted build state for one repository.
func GetOrCreateRepoState ¶
GetOrCreateRepoState returns the existing state for key or inserts a new zero-value RepoState. A zero-value LastKnownState ("") is treated as green by the state machine.
type StaticSnapshot ¶
type StaticSnapshot struct {
// contains filtered or unexported fields
}
StaticSnapshot is an AllowlistSnapshot backed by an immutable slice. Used by the pure-literal binary path so no wildcard machinery runs.
func NewStaticSnapshot ¶
func NewStaticSnapshot(entries []string) *StaticSnapshot
NewStaticSnapshot returns a snapshot holding a defensive copy of entries.
func (*StaticSnapshot) Snapshot ¶
func (s *StaticSnapshot) Snapshot() []string
Snapshot returns the held entry slice. Callers MUST NOT mutate it.
type Watcher ¶
Watcher polls GitHub Actions for build status changes.
When force is true, the red×red episode-lock arm of the state machine publishes a salted CreateTaskCommand instead of skipping (spec 069), so operators can force a re-publish for a still-red build via the /trigger HTTP path. The poll-interval loop always passes false.
func NewWatcher ¶
func NewWatcher( githubClient GitHubClient, createSender task.CreateCommandSender, metrics Metrics, repoFilter filter.RepoFilter, allowlist AllowlistSnapshot, cursorPath string, assignee string, taskStatus string, taskPhase string, maintenanceLoader maintenance.Loader, maxTitleLen int, taskSuffix string, currentDateTime libtime.CurrentDateTimeGetter, ) Watcher
NewWatcher returns a Watcher that polls GitHub Actions and publishes commands.
type WorkflowJobInfo ¶
type WorkflowJobInfo struct {
JobID int64
JobName string
FailedStepName string // first failed step's name; empty when not determinable
}
WorkflowJobInfo holds the failed job and step names for one failing workflow run. If no failed job is found in the response, JobName and FailedStepName are empty strings.
type WorkflowRun ¶
type WorkflowRun struct {
WorkflowID int64
RunID int64 // run instance ID — used by jobs API (GET /actions/runs/{id}/jobs)
Name string
HeadSHA string
Conclusion string
HTMLURL string
CreatedAt time.Time
DisplayTitle string // display_title: commit message shown in GitHub UI
HeadBranch string // head_branch: branch that triggered the run
Event string // event: push / pull_request / schedule / workflow_dispatch / etc.
StartedAt time.Time // run_started_at: when execution began (not queuing time)
UpdatedAt time.Time // updated_at: last status change — completion time for done runs
}
WorkflowRun holds the fields the watcher needs from a GitHub Actions workflow run.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package auth resolves a GitHub App HTTP client for the watcher binaries.
|
Package auth resolves a GitHub App HTTP client for the watcher binaries. |
|
Package command defines the TriggerBuildCheckCommand payload and its Kafka sender for the github-build watcher's request topic.
|
Package command defines the TriggerBuildCheckCommand payload and its Kafka sender for the github-build watcher's request topic. |
|
Package factory wires concrete dependencies for the maintainer-watcher-github-build binary.
|
Package factory wires concrete dependencies for the maintainer-watcher-github-build binary. |
|
Package handler contains the HTTP handlers for the github-build watcher.
|
Package handler contains the HTTP handlers for the github-build watcher. |
|
Package maintenance loads per-repo config from .maintenance.yaml on GitHub.
|
Package maintenance loads per-repo config from .maintenance.yaml on GitHub. |
|
Package wildcard expands owner-level wildcard allowlist entries (e.g.
|
Package wildcard expands owner-level wildcard allowlist entries (e.g. |