{"modulePath":"github.com/bborbe/github-build-watcher","version":"v0.9.3","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package pkg\n\nPackage 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.\n\n## Constants\n\n```go\nconst (\n\tGitHubAPIBucketCore    = \"core\"\n\tGitHubAPIBucketSearch  = \"search\"\n\tGitHubAPIBucketGraphQL = \"graphql\"\n)\n```\nGitHub rate-limit buckets. Each is an independent quota: core is the installation token's hourly budget, search is 30/min, graphql is metered in points.\n\n```go\nconst DefaultCursorPath = \"/data/cursor.json\"\n```\nDefaultCursorPath is the default path for cursor state persistence.\n\n```go\nconst DefaultMaxTitleLen = 200\n```\nDefaultMaxTitleLen is the default safety cap for build-failure filenames. Override via MAX\\_TITLE\\_LEN.\n\n```go\nconst GitHubAPIClassUnclassified = \"unclassified\"\n```\nGitHubAPIClassUnclassified is the only rate-limit class emitted until a classification rule separating primary exhaustion from secondary rate limiting exists. The label is always present; no other value is guessed.\n\n## Variables\n\n```go\nvar DependabotGraphUpdatePrefixes = []string{\n\t\"Graph Update:\",\n\t\"Dependabot Updates\",\n}\n```\nDependabotGraphUpdatePrefixes 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.\n\n```go\nvar ErrRateLimited = stderrors.New(\"github rate limited\")\n```\nErrRateLimited is returned when the GitHub API responds with a rate-limit or abuse-rate-limit error.\n\n## Functions\n\n```go\nfunc DeriveTaskID(owner, repo, episodeSHA string) uuid.UUID\n```\nDeriveTaskID returns a deterministic task identifier for a build-failure episode. Input: \"\\\u003cowner\u003e/\\\u003crepo\u003e#build-\\\u003cepisodeSHA\u003e\", e.g. \"bborbe/maintainer#build-abc123\".\n\n```go\nfunc DeriveTaskIDForce(owner, repo, episodeSHA, nonce string) uuid.UUID\n```\nDeriveTaskIDForce 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.\n\nKey format: \"\\\u003cowner\u003e/\\\u003crepo\u003e#build-\\\u003cepisodeSHA\u003e!\\\u003cnonce\u003e\". 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.\n\n```go\nfunc GitHubAPIBucket(req *http.Request) string\n```\nGitHubAPIBucket derives the rate-limit bucket from the request path. It never reads a response: the response's X-RateLimit headers describe whichever bucket answered, which is how a search response once masqueraded as core.\n\n```go\nfunc IsGitHubAPIRequest(req *http.Request) bool\n```\nIsGitHubAPIRequest reports whether req targets the GitHub API and so spends quota. Redirect hops to other hosts (e.g. job logs served from Azure blob storage) share the transport but spend no GitHub quota and are not counted.\n\n```go\nfunc IsGitHubRateLimited(resp *http.Response) bool\n```\nIsGitHubRateLimited reports whether resp is a rate-limit rejection: a 429, or a 403 carrying an exhausted X-RateLimit-Remaining or a Retry-After.\n\n```go\nfunc NewMemDB() libkv.DB\n```\nNewMemDB 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.\n\nThe 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.\n\n```go\nfunc NewResetCursorHandler(cursorPath string) http.Handler\n```\nNewResetCursorHandler 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.\n\nWrap with libhttp.NewDangerousHandlerWrapper at the call site to require a passphrase — the bare handler does not enforce auth.\n\nRace: 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.\n\n```go\nfunc SaveCursor(ctx context.Context, path string, c *Cursor) error\n```\nSaveCursor persists cursor state to path atomically via a temp file + rename. On error: logs warning and returns error; caller logs and continues.\n\n## Types\n\n```go\ntype AllowlistSnapshot interface {\n\tSnapshot() []string\n}\n```\nAllowlistSnapshot 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.\n\n```go\ntype Cursor struct {\n\tRepos map[string]*RepoState `json:\"repos\"` // key: \"owner/repo\"\n}\n```\nCursor is the full persisted state for the build watcher.\n\n```go\nfunc LoadCursor(ctx context.Context, path string) (*Cursor, error)\n```\nLoadCursor reads cursor state from path. Missing file returns a fresh empty cursor (cold start is valid). Corrupt file returns an error; caller should refuse to proceed.\n\n```go\ntype Debouncer interface {\n\t// Allow reports whether a trigger for key is permitted now. Returns false\n\t// (deny) when a previous trigger for the same key happened less than the\n\t// configured interval ago; records the trigger time on approval. The\n\t// caller records the deny reason for traceability (the webhook handler\n\t// increments webhook_skipped_total{reason=\"debounced\"}).\n\tAllow(key string) bool\n}\n```\nDebouncer collapses repeated triggers for the same key within a minimum interval, so a burst of events (e.g. a CI-heavy repo with many workflow runs finishing around the same time) produces at most one accepted trigger per interval.\n\n```go\nfunc NewDebouncer(interval time.Duration, clock libtime.CurrentDateTimeGetter) Debouncer\n```\nNewDebouncer returns a Debouncer that allows a trigger for key at most once per interval. The clock is injected so tests can fix the current time (libtime go-time rule: never time.Now() in business logic).\n\n```go\ntype GitHubAPILabels struct {\n\tService    string\n\tCredential string\n\tCluster    string\n}\n```\nGitHubAPILabels are the per-process label values stamped on every GitHub API counter. Credential carries the App id, never a token.\n\n```go\ntype GitHubAPIRecorder interface {\n\t// Record counts the round trip of req. resp is nil and err non-nil on a\n\t// transport error.\n\tRecord(req *http.Request, resp *http.Response, err error)\n}\n```\nGitHubAPIRecorder counts one GitHub API round trip.\n\n```go\nfunc NewGitHubAPIRecorder(labels GitHubAPILabels) GitHubAPIRecorder\n```\nNewGitHubAPIRecorder returns a recorder that stamps labels on every count. Every bounded label combination is pre-initialised to zero so rate() and absent() queries see the series before the first call of that kind.\n\n```go\ntype GitHubClient interface {\n\t// GetWorkflowRuns returns completed workflow runs for a repo branch.\n\t// In-progress runs (empty Conclusion) are filtered out.\n\tGetWorkflowRuns(ctx context.Context, owner, repo, branch string) ([]WorkflowRun, error)\n\n\t// GetDefaultBranch returns the default branch name for a repository.\n\tGetDefaultBranch(ctx context.Context, owner, repo string) (string, error)\n\n\t// GetDefaultBranchHeadSHA returns the 40-char hex SHA of the branch tip.\n\t// Used as recovery_sha on a red→green transition (default-branch HEAD at close time).\n\tGetDefaultBranchHeadSHA(ctx context.Context, owner, repo, branch string) (string, error)\n\n\t// GetFileContent fetches the raw content of a file at the given ref.\n\t// Returns (nil, nil) if the file does not exist (HTTP 404 — the common case).\n\t// Returns (nil, ErrRateLimited) when rate-limited.\n\t// Returns (nil, err) for any other API error.\n\tGetFileContent(ctx context.Context, owner, repo, path, ref string) ([]byte, error)\n\n\t// GetJobsForRun returns info about failed jobs in a run.\n\t// Returns an empty slice (not an error) when the run has no failed jobs.\n\t// Returns (nil, ErrRateLimited) when rate-limited.\n\t// Returns (nil, err) for other API errors.\n\tGetJobsForRun(ctx context.Context, owner, repo string, runID int64) ([]WorkflowJobInfo, error)\n\n\t// GetJobLog fetches the plain-text log for a workflow job by following GitHub's\n\t// redirect to an Azure storage URL. Returns (nil, nil) when the URL is unavailable.\n\t// Returns (nil, err) for a non-nil error where the log should be omitted.\n\t// Rejects payloads \u003e 1 MiB before truncation (returns (nil, err)).\n\tGetJobLog(ctx context.Context, owner, repo string, jobID int64) ([]byte, error)\n\n\t// ListOwnerRepos returns the names of every non-archived, non-fork\n\t// repository owned by `owner`. Owner kind (User vs Organization) is\n\t// detected via GET /users/\u003cowner\u003e; the method then calls ListByUser\n\t// or ListByOrg respectively, paginating with PerPage=100 until done.\n\t// Returns (nil, ErrRateLimited) when rate-limited.\n\t// Returns (nil, err) for any other API error (network, 401/403, 404).\n\t// Returns ([]string{}, nil) when the owner has zero eligible repos.\n\tListOwnerRepos(ctx context.Context, owner string) ([]string, error)\n\n\t// RateLimitRemaining returns the requests remaining in the current primary\n\t// rate-limit window, as reported by the last core-bucket API response's\n\t// X-RateLimit-Remaining header, and whether such a response has been\n\t// observed at all. The bool is false until the first core-bucket header\n\t// arrives; a caller must not publish the zero value as a reading, because\n\t// \"not measured yet\" is not \"quota exhausted\".\n\t//\n\t// The build watcher runs its own GitHub App (APP_ID 4748047 dev / 4748049\n\t// prod), not the shared App used by the pr/release watchers, so this\n\t// reading covers only this watcher's bucket.\n\tRateLimitRemaining() (remaining int, measured bool)\n}\n```\nGitHubClient abstracts the GitHub Actions API calls.\n\n```go\nfunc NewGitHubClient(\n\thttpClient *http.Client,\n\trecorder GitHubAPIRecorder,\n\tapiBaseURL string,\n) GitHubClient\n```\nNewGitHubClient returns a GitHubClient backed by the real GitHub API. The httpClient must already carry authentication (App auth). The client's transport is wrapped to observe the core-bucket X-RateLimit-Remaining on every response, so RateLimitRemaining() reflects the shared App token's live quota. Every round trip is also counted by recorder (per-caller github\\_api\\_calls\\_total / github\\_api\\_rate\\_limited\\_total).\n\n```go\ntype Metrics interface {\n\t// IncPollCycle increments the poll cycle counter.\n\t// result: \"success\" | \"error\"\n\tIncPollCycle(result string)\n\t// IncReposChecked increments the repos-checked counter for each repo polled.\n\tIncReposChecked()\n\t// IncStateTransition increments the state-transition counter.\n\t// transition: \"green_to_red\" | \"red_to_green\"\n\tIncStateTransition(transition string)\n\t// IncTaskPublished increments the published-task counter.\n\tIncTaskPublished()\n\t// IncTaskClosed increments the published-closure counter.\n\tIncTaskClosed()\n\t// IncPollError increments the poll-error counter.\n\t// reason: \"rate_limited\" | \"github_error\" | \"kafka_error\"\n\tIncPollError(reason string)\n\t// SetCurrentRedRepos sets the gauge to the current number of repos in red state.\n\tSetCurrentRedRepos(count float64)\n\t// SetRateLimitRemaining records the primary rate-limit window's remaining\n\t// for the shared GitHub App installation token, as read from the last\n\t// core-bucket API response's X-RateLimit-Remaining header.\n\tSetRateLimitRemaining(remaining int)\n\t// SetRateLimitUnmeasured records that no core-bucket response has been\n\t// observed yet, by publishing NaN. NaN is the only value that keeps a\n\t// `remaining \u003c N` alert quiet without claiming a reading; the gauge is\n\t// registered at init and therefore exports 0 until something sets it.\n\tSetRateLimitUnmeasured()\n\t// IncWebhookDelivery increments the webhook delivery counter with the given result label.\n\t// result: \"success\", \"skip\"\n\tIncWebhookDelivery(result string)\n\t// IncWebhookSignatureRejected increments the webhook signature-rejection counter.\n\tIncWebhookSignatureRejected()\n\t// ObserveWebhookDispatchLatency records the dispatch latency of a webhook delivery.\n\tObserveWebhookDispatchLatency(seconds float64)\n\t// IncWebhookSkipped increments the webhook skip counter.\n\t// reason: \"not_completed\" | \"not_failure\" | \"not_default_branch\" | \"debounced\"\n\tIncWebhookSkipped(reason string)\n}\n```\nMetrics defines Prometheus counters and gauges for the build watcher.\n\n```go\nfunc NewMetrics() Metrics\n```\nNewMetrics returns a Metrics implementation backed by Prometheus counters.\n\n```go\ntype RepoState struct {\n\tLastKnownState    string `json:\"last_known_state\"`    // \"green\" | \"red\" | \"\"\n\tCurrentEpisodeSHA string `json:\"current_episode_sha\"` // empty when green\n\tDefaultBranch     string `json:\"default_branch\"`      // cached; fetched via API if empty\n}\n```\nRepoState holds the persisted build state for one repository.\n\n```go\nfunc GetOrCreateRepoState(c *Cursor, key string) *RepoState\n```\nGetOrCreateRepoState 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.\n\n```go\ntype StaticSnapshot struct {\n\t// contains filtered or unexported fields\n}\n```\nStaticSnapshot is an AllowlistSnapshot backed by an immutable slice. Used by the pure-literal binary path so no wildcard machinery runs.\n\n```go\nfunc NewStaticSnapshot(entries []string) *StaticSnapshot\n```\nNewStaticSnapshot returns a snapshot holding a defensive copy of entries.\n\n```go\nfunc (s *StaticSnapshot) Snapshot() []string\n```\nSnapshot returns the held entry slice. Callers MUST NOT mutate it.\n\n```go\ntype Watcher interface {\n\tPoll(ctx context.Context, force bool, scope string) error\n}\n```\nWatcher polls GitHub Actions for build status changes.\n\nWhen 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.\n\nWhen scope is non-empty (\"owner/repo\"), only that single repo is scanned — the webhook path — so one workflow\\_run delivery costs ~3 API calls, not a full fleet scan. Empty scope runs the full allowlist.\n\n```go\nfunc NewWatcher(\n\tgithubClient GitHubClient,\n\tcreateSender task.CreateCommandSender,\n\tcompleteSender task.CompleteCommandSender,\n\tmetrics Metrics,\n\trepoFilter filter.RepoFilter,\n\tallowlist AllowlistSnapshot,\n\tcursorPath string,\n\tassignee string,\n\ttaskStatus string,\n\ttaskPhase string,\n\tstage string,\n\tmaintenanceLoader maintenance.Loader,\n\tmaxTitleLen int,\n\ttaskSuffix string,\n\tcurrentDateTime libtime.CurrentDateTimeGetter,\n) Watcher\n```\nNewWatcher returns a Watcher that polls GitHub Actions and publishes commands.\n\n```go\ntype WorkflowJobInfo struct {\n\tJobID          int64\n\tJobName        string\n\tFailedStepName string // first failed step's name; empty when not determinable\n}\n```\nWorkflowJobInfo 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.\n\n```go\ntype WorkflowRun struct {\n\tWorkflowID   int64\n\tRunID        int64 // run instance ID — used by jobs API (GET /actions/runs/{id}/jobs)\n\tName         string\n\tHeadSHA      string\n\tConclusion   string\n\tHTMLURL      string\n\tCreatedAt    time.Time\n\tDisplayTitle string    // display_title: commit message shown in GitHub UI\n\tHeadBranch   string    // head_branch: branch that triggered the run\n\tEvent        string    // event: push / pull_request / schedule / workflow_dispatch / etc.\n\tStartedAt    time.Time // run_started_at: when execution began (not queuing time)\n\tUpdatedAt    time.Time // updated_at: last status change — completion time for done runs\n}\n```\nWorkflowRun holds the fields the watcher needs from a GitHub Actions workflow run.\n\n","path":"github.com/bborbe/github-build-watcher/pkg","name":"pkg","synopsis":"Package pkg implements the GitHub build watcher service.","isRedistributable":true}
