{"modulePath":"github.com/bborbe/github-pr-watcher","version":"v0.31.1","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package pkg\n\nPackage pkg provides the core domain types and logic for the maintainer-watcher-github-pr service: GitHub API integration, pull-request filtering, cursor persistence, and Kafka command publishing.\n\n## Constants\n\n```go\nconst DefaultCursorPath = \"/data/cursor.json\"\n```\nDefaultCursorPath is the default path for cursor state persistence.\n\n```go\nconst DefaultMaxSlugLen = 80\n```\nDefaultMaxSlugLen is the default cap for the slugified PR-title segment alone. Bumped from 50 to 80 (2026-05-08) — 50 cut typical PR titles mid-word. Override via MAX\\_SLUG\\_LEN.\n\n```go\nconst DefaultMaxTitleLen = 200\n```\nDefaultMaxTitleLen is the default safety cap for the whole title, including segments and separators. Crosses Windows MAX\\_PATH=260 and ext4 NAME\\_MAX=255 with margin. Override via MAX\\_TITLE\\_LEN.\n\n## Variables\n\n```go\nvar AvailableMergeStates = []MergeState{MergeStateBehind, MergeStateDirty}\n```\nAvailableMergeStates lists every merge state the watcher acts on.\n\n```go\nvar ErrPermanent = stderrors.New(\"permanent github error\")\n```\nErrPermanent marks a GitHub error that a redelivery cannot fix — a 401/403 (credential or permission) or a 404 (repo or ref gone). The command consumer maps it to a skip rather than a retry: without the distinction one missing App permission (Commit statuses: Write) turns every webhook delivery into an endless redelivery loop, and the failure looks like a Kafka problem.\n\n## Functions\n\n```go\nfunc AgeSeconds(now, start libtime.DateTime) float64\n```\nAgeSeconds reports how many seconds have elapsed from start to now, clamped at 0 so a host clock skew never publishes a negative age.\n\n```go\nfunc BuildCreateCommand(\n\tpr PullRequest,\n\tdetails PRDetails,\n\ttaskIDStr string,\n\tstage string,\n\tmaxSlugLen int,\n\tmaxTitleLen int,\n\ttaskSuffix string,\n\ttargetVault string,\n\ttrustResult trust.Result,\n\tforced bool,\n\tmaxAdditions int,\n\tmaxChangedFiles int,\n\texclusion Exclusion,\n) task.CreateCommand\n```\nBuildCreateCommand builds a CreateTaskCommand for a PR given its details and trust result. It is used by both the poll path (via PublishCreate) and the single-PR trigger handler.\n\nforced marks an operator-requested re-review (trigger with force=true). The caller has already salted taskIDStr via DeriveTaskIDForce; forced makes the TITLE differ too, which is what actually matters — the agent controller dedupes on title path, so a salted task\\_identifier alone lands on the existing review task's filename and is silently rejected with ErrTaskAlreadyExists (confirmed in prod, bborbe/coding#90, 2026-08-09).\n\n```go\nfunc BuildMechanicalOverrideCommand(\n\tpr PullRequest,\n\tdetails PRDetails,\n\ttaskIDStr string,\n\tstage string,\n\tmaxSlugLen int,\n\tmaxTitleLen int,\n\ttaskSuffix string,\n\ttargetVault string,\n) task.CreateCommand\n```\nBuildMechanicalOverrideCommand builds the \\`pr-override\\` CreateTaskCommand for a qualifying mechanical override. It reuses BuildOverrideCommand for the title, task identifier, phase and clone fields — so the task path stays identical to the label override and the controller's title-path dedupe collapses the two — then stamps the reason and replaces the body.\n\n```go\nfunc BuildOverrideCommand(\n\tpr PullRequest,\n\tdetails PRDetails,\n\ttaskIDStr string,\n\tstage string,\n\tmaxSlugLen int,\n\tmaxTitleLen int,\n\ttaskSuffix string,\n\ttargetVault string,\n) task.CreateCommand\n```\nBuildOverrideCommand builds a \\`pr-override\\` CreateTaskCommand for a labeled, trusted-author PR. The caller (PublishOverride) guarantees trust, so there is no untrusted branch here. The title uses the \"Override\" kind so it never collides with the review task's vault file for the same (PR, SHA).\n\n```go\nfunc ClassifyTrivial(files []PRFile) bool\n```\nClassifyTrivial returns true when every changed file in the PR is mechanical per the Mechanical Bump PR Pipeline allow-list: go.mod toolchain/version bumps, go.sum hash bumps, Dockerfile base-image/GO\\_VERSION bumps, append-only CHANGELOG, workflow go-version bumps, and single-hash homebrew cask version/sha256 bumps. Any out-of-pattern file (or an empty file list) returns false — conservative on edge cases: a false-positive auto-merge (silent behavior change shipped) costs more than a false-negative (waiting human merge).\n\n```go\nfunc DeriveTaskID(owner, repo string, number int, sha string) uuid.UUID\n```\nDeriveTaskID returns a deterministic task identifier for a (PR, SHA) pair. Input: \"\\\u003cowner\u003e/\\\u003crepo\u003e#\\\u003cnumber\u003e@\\\u003csha\u003e\", e.g. \"bborbe/maintainer#42@abc123...\". The full SHA is used (not truncated) to keep the dedup keyspace collision-free.\n\n```go\nfunc DeriveTaskIDForce(owner, repo string, number int, sha, nonce string) uuid.UUID\n```\nDeriveTaskIDForce returns a salted task identifier for a (PR, SHA) pair plus an extra nonce. Used when an operator explicitly requests a forced re-review (HTTP /trigger?force=true) so the executor can publish a CreateTaskCommand with a TaskIdentifier that the controller has not already seen — bypassing the dedup-skip in the agent controller.\n\nFor the same (owner, repo, number, sha) the result is always different from DeriveTaskID(...): the key includes the nonce segment \"\\\u003cnonce\u003e\", e.g. \"bborbe/maintainer#42@abc123...!1700000000000000000\".\n\nThe nonce resolution is the caller's responsibility. Callers should derive it from an injected libtime.CurrentDateTimeGetter; the helper itself is a pure function over its inputs.\n\n```go\nfunc DeriveTaskIDOverride(owner, repo string, number int, sha string) uuid.UUID\n```\nDeriveTaskIDOverride returns a deterministic task identifier for the override action on a (PR, SHA) pair. It appends a fixed \"#override\" segment to the key so the result never collides with DeriveTaskID(...) for the same (owner, repo, number, sha) — the override task and the review task coexist in the cursor without deduplicating each other.\n\nBecause the segment is fixed (not a nonce), the override fires at most once per head SHA while the label stays applied; a new commit produces a new SHA and, if still labeled, a fresh override.\n\n```go\nfunc GitHubAPIBucket(req *http.Request) string\n```\nGitHubAPIBucket returns the GitHub rate-limit bucket a request spends, derived from the request path only: /search/ and /api/v3/search/ are \"search\", /graphql and /api/graphql are \"graphql\", everything else is \"core\". A nil request or URL is \"core\".\n\nThe bucket must never be read from a response header. X-RateLimit-Resource belongs to the response and arrives only after the call, so deriving the bucket from it (or from state left by a previous response) misattributes interleaved search and core calls to whichever bucket answered last.\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-pr watcher's command consumer needs an offset store; this in-memory implementation gives it one without requiring a PVC (see spec 066 AC 9 rationale: replay-from-OffsetOldest on restart is safe because the downstream CreateTaskCommand is idempotent via derived task\\_id).\n\nThe implementation is intentionally minimal — it implements only the methods the offset-store / consumer wiring touches: Update, View, Sync, Close, Remove, Stats, StatsDetailed. Iteration over a bucket is real (forward and reverse, with Rewind and Seek), because the retry guard's ledger prunes its own records on write.\n\n```go\nfunc NewRetryGuardOutcomeConsumer(\n\tsaramaClientProvider libkafka.SaramaClientProvider,\n\tdb libkv.DB,\n\tprefix base.TopicPrefix,\n\tguard RetryGuard,\n\tledger DispatchLedger,\n) run.Func\n```\nNewRetryGuardOutcomeConsumer returns a run.Func that consumes the task lifecycle event stream and clears the retry guard record for a task that reached a terminal status.\n\nIt never returns on a recoverable error: main.go composes it with run.CancelOnFirstFinish, so a return would cancel the poll loop, the HTTP server and the command consumer. It retries internally and returns only when ctx is cancelled.\n\n```go\nfunc NewRetryGuardOutcomeMessageHandler(\n\tguard RetryGuard,\n\tledger DispatchLedger,\n) libkafka.MessageHandlerTx\n```\nNewRetryGuardOutcomeMessageHandler returns a transaction message handler that clears the retry guard record for a task that reached a terminal status.\n\nA delete event carries no payload and is ignored explicitly. A non-terminal status is ignored, so a running review keeps suppressing. The task identifier is the Kafka message key (the sender writes EventObject.ID, which is base.EventID(task.TaskIdentifier), there).\n\n```go\nfunc ParseBotAllowlist(raw string) []string\n```\nParseBotAllowlist splits a comma-separated allowlist string into a slice of trimmed, non-empty entries.\n\n```go\nfunc ParseMechanicalOverrideAuthors(raw string) []string\n```\nParseMechanicalOverrideAuthors splits a comma-separated MECHANICAL\\_OVERRIDE\\_AUTHORS string into trimmed, non-empty logins. The splitting rules are deliberately identical to ParseTrustedAuthors; the distinct name marks the distinct meaning — these logins may be approved without a review, which is stronger than \"trusted\" and must never be conflated with BOT\\_ALLOWLIST (skip) or TRUSTED\\_AUTHORS (may be reviewed).\n\n```go\nfunc ParseTrustedAuthors(raw string) []string\n```\nParseTrustedAuthors splits a comma-separated trusted-authors string into a slice of trimmed, non-empty entries. Mirrors ParseBotAllowlist in behavior.\n\n```go\nfunc SaveCursor(ctx context.Context, path string, state Cursor) error\n```\nSaveCursor persists cursor state to path atomically via a temp file + rename.\n\n## Types\n\n```go\ntype CommitState string\n```\nCommitState is a GitHub commit-status state. Only the two values the watcher's commit-status checks use are modelled; the API also accepts pending and error, which this watcher never posts.\n\n```go\nconst (\n\t// CommitStateSuccess reports that the check passes.\n\tCommitStateSuccess CommitState = \"success\"\n\t// CommitStateFailure reports that the check fails.\n\tCommitStateFailure CommitState = \"failure\"\n)\n```\n\n```go\ntype Cursor struct {\n\tLastUpdatedAt libtime.DateTime  `json:\"last_updated_at\"`\n\tHeadSHAs      map[string]string `json:\"head_shas\"`\n\t// Deferrals counts how many consecutive polls a (PR, head SHA) has been left\n\t// unsettled because its mechanical-override gate could not be evaluated. A\n\t// deferral deliberately writes no HeadSHAs entry, so this count is the only\n\t// record that the PR is owed another attempt — and the only thing that bounds\n\t// the retry, so a permanently unreadable gate cannot pin the cursor forever.\n\tDeferrals map[string]int `json:\"deferrals,omitempty\"`\n}\n```\nCursor holds the watcher's persisted poll state, including the last-seen update time and a map of task-identifier to head SHA for force-push detection.\n\n```go\nfunc LoadCursor(ctx context.Context, path string, startTime libtime.DateTime) (Cursor, error)\n```\nLoadCursor reads cursor state from path. Returns cold-start state with startTime if the file is missing or corrupt.\n\n```go\ntype DispatchLedger interface {\n\t// Mark records that taskID was observed dispatched.\n\tMark(taskID string)\n\t// Seen reports whether taskID was observed dispatched by this process.\n\tSeen(taskID string) bool\n}\n```\nDispatchLedger records which review task ids this process has observed being dispatched — that is, a task event carrying job\\_started\\_at, which the executor writes when it spawns the Job.\n\nIt exists to separate two outcomes the scanner could not previously tell apart. A publish that the executor never picks up and a publish whose review simply has not finished both leave the PR unreviewed, so the retry loop re-published both and reported success either way. That is the silent half of the defect this instrument exists to close: the scanner's own success signal said \"published\", and nothing anywhere said \"and nothing ever ran\".\n\nThe ledger is deliberately in-process and never persisted. A restarted pod must not inherit another process's publishes as undispatched, or the count manufactures the same false positive from the other side — reporting a healthy pipeline as broken, which is the failure mode the original defect had in reverse. The scoping therefore lives in the CALLER: a candidate is only counted undispatched when this process also published it (retryState holds an attempt), so a cold start reports zero until it publishes something itself.\n\n```go\nfunc NewDispatchLedger() DispatchLedger\n```\nNewDispatchLedger returns an empty in-process ledger.\n\n```go\ntype Exclusion struct {\n\t// Additions is the sum of added lines across matched files.\n\tAdditions int\n\t// Files is the number of matched files.\n\tFiles int\n}\n```\nExclusion is a computed result, not a constructed dependency, so the functions producing it (ComputeExclusion, ReviewIgnoreExclusion) are named for the computation rather than carrying a \\`New\\` constructor prefix.\n\nExclusion is what a repo's \\`.reviewignore\\` removed from the size-gate counts. The zero value means nothing was excluded — the state for a repo with no \\`.reviewignore\\`, and the safe default on any fetch error, so a failure to read the file can only ever park more, never less.\n\n```go\nfunc ComputeExclusion(files []PRFile, matcher reviewignore.Matcher) Exclusion\n```\nComputeExclusion sums the additions and file count that matcher excludes across the PR's changed files. \\`.reviewignore\\` can never match itself (the guard lives in reviewignore.Parse), so the file's own edits always count toward the gate and never appear here.\n\n```go\nfunc ReviewIgnoreExclusion(\n\tctx context.Context,\n\tghClient GitHubClient,\n\towner, repo string,\n\tnumber int,\n\tprURL string,\n) Exclusion\n```\nReviewIgnoreExclusion reads the repo's \\`.reviewignore\\` and computes what it excludes from a PR's size-gate counts. prURL is used only for log context.\n\nEvery failure path returns the zero Exclusion — nothing excluded. That is the safe direction: an unreadable \\`.reviewignore\\` can then only park a PR that would otherwise review, never review a PR that should have parked.\n\nThe per-file GitHub call is made only when the repo actually has patterns, so a repo that never opted in costs exactly one extra API call per PR (the contents lookup, which 404s) rather than two.\n\n```go\nfunc (e Exclusion) Empty() bool\n```\nEmpty reports whether the exclusion removed nothing, so callers can skip reporting a line that would read \"0 additions across 0 files excluded\".\n\n```go\ntype GitHubAPIMetrics interface {\n\t// IncGitHubAPICall counts one round trip. outcome: \"success\", \"error\".\n\tIncGitHubAPICall(bucket string, outcome string)\n\t// IncGitHubAPIRateLimited counts one rate-limited response. class: \"unclassified\".\n\tIncGitHubAPIRateLimited(bucket string, class string)\n}\n```\nGitHubAPIMetrics records per-caller GitHub API counters. The service, credential and cluster labels are bound at construction.\n\n```go\nfunc NewGitHubAPIMetrics(credential string, cluster string) GitHubAPIMetrics\n```\nNewGitHubAPIMetrics returns a GitHubAPIMetrics that stamps every series with the constant service name, the given credential and the given cluster. credential is the GitHub App id as a decimal string; it must never be a token or any other secret. Every bounded label combination is pre-initialised to zero so alert rules see a flat zero from startup rather than missing data.\n\n```go\ntype GitHubClient interface {\n\t// SearchPRs issues a GitHub Search query for open PRs updated since cursor.\n\t// page=1 for the first call; use SearchResult.NextPage for subsequent calls.\n\t// PullRequest.HeadSHA in the result is empty — call GetPRDetails to fetch it.\n\tSearchPRs(\n\t\tctx context.Context,\n\t\tscope string,\n\t\tsince libtime.DateTime,\n\t\tpage int,\n\t) (SearchResult, error)\n\n\t// SearchLabeledPRs issues a GitHub Search query for open PRs carrying\n\t// label, with NO `updated:\u003e=` bound. page=1 for the first call; use\n\t// SearchResult.NextPage for subsequent calls.\n\t//\n\t// The absence of an updated bound is the point: SearchPRs is scoped by a\n\t// monotonic cursor, so a PR that has stopped being updated — which is what\n\t// a stale branch IS — drops out of its window permanently. The side-effect\n\t// paths (update-branch, auto-merge, supersede) exist precisely for those\n\t// PRs, so they query by label instead and stay reachable for as long as\n\t// the label is present. See processLabeledPRs.\n\t//\n\t// PullRequest.HeadSHA in the result is empty — call GetPRDetails to fetch it.\n\tSearchLabeledPRs(\n\t\tctx context.Context,\n\t\tscope string,\n\t\tlabel string,\n\t\tpage int,\n\t) (SearchResult, error)\n\n\t// SearchOpenPRs issues a GitHub Search query for every open PR in scope,\n\t// with NO `updated:` bound. Used by the unreviewed-PR scan, which must see\n\t// a PR whose review was lost long ago and whose updated-at has since\n\t// fallen behind the cursor. page=1 for the first call; use\n\t// SearchResult.NextPage for subsequent calls.\n\t//\n\t// PullRequest.HeadSHA in the result is empty — call GetPRDetails to fetch it.\n\tSearchOpenPRs(ctx context.Context, scope string, page int) (SearchResult, error)\n\n\t// GetPRDetails fetches the head SHA, clone URL, and base ref for a single PR.\n\t// The Search API does NOT return any of these, so the poll loop must call\n\t// this for every PR before publishing a task command.\n\tGetPRDetails(ctx context.Context, owner, repo string, number int) (PRDetails, error)\n\n\t// ListReviews returns the PR's reviews, paginated to exhaustion. Used by\n\t// the unreviewed-PR scan to decide whether a configured reviewer bot has\n\t// reviewed the PR's current head SHA. A review in any state counts.\n\tListReviews(ctx context.Context, owner, repo string, number int) ([]Review, error)\n\n\t// GetCommitState returns the merge-blocking state of ref as one of\n\t// \"success\", \"pending\" or \"failure\". It merges BOTH signals GitHub uses:\n\t// the legacy combined commit-status state AND the check runs. The combined\n\t// status alone excludes GitHub Actions check runs, so a repo whose CI is an\n\t// Actions workflow would read success while its test run failed.\n\t//\n\t// It is the read the checks-not-green escalation is built on — the watcher\n\t// arms auto-merge and GitHub holds the PR, so this is the only place the\n\t// watcher can observe that the hold is not clearing.\n\tGetCommitState(ctx context.Context, owner, repo, ref string) (string, error)\n\n\t// EnableAutoMerge arms GitHub-native auto-merge on a PR: when all merge\n\t// requirements (required status checks + required reviews per the repo\n\t// ruleset) are met, GitHub merges the PR automatically. Re-arming an\n\t// already-armed PR succeeds. Arming a PR that is ALREADY mergeable fails\n\t// with UNPROCESSABLE \"Pull request is in clean status\" — auto-merge only\n\t// applies while something still blocks the merge. Requires the\n\t// authenticating identity to hold Pull requests: Write on the repo.\n\tEnableAutoMerge(ctx context.Context, owner, repo string, number int) error\n\n\t// UpdateBranch merges the PR's base branch into its head branch —\n\t// GitHub-native update-branch, a merge and never a force-push. Used to\n\t// clear the `behind` state that strands an otherwise-mergeable PR once\n\t// master moves. A conflicting merge fails (GitHub answers 422), so a\n\t// `dirty` PR is NOT resolvable this way — update-branch fixes staleness,\n\t// not conflicts. Requires the authenticating identity to hold\n\t// Contents: Write on the repo.\n\tUpdateBranch(ctx context.Context, owner, repo string, number int) error\n\n\t// ClosePR closes the PR without merging it, optionally posting a comment\n\t// first explaining why. This is the abort half of the update-go\n\t// abort-and-reemit policy: a dep-bump PR whose CHANGELOG hunk conflicts\n\t// with a release cannot be refreshed by UpdateBranch — that merges base\n\t// into head, and a conflicting merge fails — so it is retired and the\n\t// update-go pipeline produces a fresh one off current master.\n\t//\n\t// This is NOT a merge route and the never-merge boundary holds: closing is\n\t// strictly weaker than merging, and the watcher still cannot land a\n\t// change. Requires Pull requests: Write.\n\tClosePR(ctx context.Context, owner, repo string, number int, comment string) error\n\n\t// GetMaintainerConfig fetches and parses the repo's `.maintainer.yaml`\n\t// trust file via maintainerconfig. An absent file (404) returns the\n\t// zero-value config with nil error — matching the \"opt-in, never\n\t// defaulted-on\" trust-gate contract. Other errors are wrapped.\n\tGetMaintainerConfig(\n\t\tctx context.Context,\n\t\towner, repo string,\n\t) (maintainerconfig.MaintainerConfig, error)\n\n\t// ListPRFiles returns the PR's changed files with their patches, used by\n\t// the mechanical triviality classifier.\n\tListPRFiles(ctx context.Context, owner, repo string, number int) ([]PRFile, error)\n\n\t// GetReviewIgnore fetches the repo's root `.reviewignore` and returns a\n\t// matcher for the paths it excludes from the size gate. An absent file\n\t// (404) returns a matcher that excludes nothing, with a nil error —\n\t// matching the \"opt-in, never defaulted-on\" contract GetMaintainerConfig\n\t// uses. Other errors are wrapped.\n\tGetReviewIgnore(\n\t\tctx context.Context,\n\t\towner, repo string,\n\t) (reviewignore.Matcher, error)\n\n\t// AddLabel adds a label to a PR (a no-op when already present). Requires\n\t// the authenticating identity to hold Pull requests: Write on the repo.\n\tAddLabel(ctx context.Context, owner, repo string, number int, label string) error\n\n\t// PostCommitStatus posts a commit status on sha under the given context.\n\t// This is the reporter that replaces the per-repo bridge workflows: the\n\t// `do-not-merge` and `task-link` contexts are required status checks in\n\t// the master-protection rulesets, so a missing reporter blocks every merge\n\t// there. Requires the authenticating identity to hold Commit statuses:\n\t// Write on the repo.\n\tPostCommitStatus(\n\t\tctx context.Context,\n\t\towner, repo, sha string,\n\t\tstate CommitState,\n\t\tstatusContext string,\n\t) error\n\n\t// SubmitReview posts a review on commitID. The do-not-merge gate uses it to\n\t// submit a CHANGES_REQUESTED review, which blocks the merge on every\n\t// ruleset that requires an approving review — the mechanism the fleet's\n\t// held-PR route depends on. It was added while the reviewer App lacked\n\t// Commit statuses: Write; the App holds it now, and the commit-status\n\t// route posts alongside. Requires Pull requests: Write.\n\tSubmitReview(\n\t\tctx context.Context,\n\t\towner, repo string,\n\t\tnumber int,\n\t\tcommitID, body string,\n\t\tevent ReviewEvent,\n\t) error\n\n\t// DismissReview dismisses one review by id, removing its standing verdict\n\t// from the PR's review decision. The do-not-merge gate uses it to release\n\t// its own CHANGES_REQUESTED review when the label is removed, which\n\t// restores whatever verdict the reviewer held before the label appeared.\n\t// Requires Pull requests: Write, and — where a ruleset restricts dismissals\n\t// to authorized actors — membership of that list.\n\tDismissReview(\n\t\tctx context.Context,\n\t\towner, repo string,\n\t\tnumber int,\n\t\treviewID int64,\n\t\tmessage string,\n\t) error\n\n\t// RateLimitRemaining returns the requests remaining in the current primary\n\t// rate-limit window, as reported by the last API response's\n\t// X-RateLimit-Remaining header. Zero until the first request populates it.\n\t// Both watchers share the same App installation token, so this watcher's\n\t// reading reflects the shared 12,500/hour budget — the metric built from\n\t// this is the alert surface that catches quota exhaustion BEFORE the\n\t// fleet-wide 403 stall (2026-08-23 incident).\n\tRateLimitRemaining() int\n\n\t// GetRateLimitCoreRemaining returns the shared token's primary (core)\n\t// rate-limit remaining via the GET /rate_limit endpoint. Used to populate\n\t// the gauge on poll cycles where no core-API call happens (search-only\n\t// cycles with no open PRs would otherwise leave the gauge at 0 — the\n\t// \"unpopulated\" sentinel — which falsely reads as quota exhaustion).\n\tGetRateLimitCoreRemaining(ctx context.Context) (int, error)\n}\n```\nGitHubClient abstracts the GitHub API calls.\n\n```go\nfunc NewGitHubClient(httpClient *http.Client, apiMetrics GitHubAPIMetrics) GitHubClient\n```\nNewGitHubClient returns a GitHubClient backed by the real GitHub API. The httpClient must already carry authentication (App auth via lib/githubapp.NewClient). The client's transport is wrapped to observe X-RateLimit-Remaining on every response, so RateLimitRemaining() reflects the shared App token's live quota. The wrapped transport also counts every call into the per-caller github\\_api\\_\\* counters via apiMetrics; a nil apiMetrics disables that counting.\n\n```go\ntype MergeState string\n```\nMergeState is a GitHub REST merge-state value, typed so a state-name typo is caught by the compiler rather than silently never matching.\n\nThe set below is deliberately partial: it names only the states the watcher reasons about, not GitHub's full vocabulary (\\`clean\\`, \\`blocked\\`, \\`unstable\\`, and \\`unknown\\` are all real values that simply never drive a decision here). An unrecognized value is never stale, which is the safe default.\n\n```go\nconst (\n\t// MergeStateBehind is a head branch behind its base with no conflict —\n\t// the case update-branch resolves.\n\tMergeStateBehind MergeState = \"behind\"\n\t// MergeStateDirty is a PR whose merge commit cannot be created (a real\n\t// conflict). update-branch does not resolve it.\n\tMergeStateDirty MergeState = \"dirty\"\n)\n```\n\n```go\ntype Metrics interface {\n\t// IncPollCycle increments the poll cycle counter with the given result label.\n\t// result: \"success\", \"rate_limited\", \"github_error\"\n\tIncPollCycle(result string)\n\t// IncPRPublished increments the PR-published counter with the given command label.\n\t// command: \"create\", \"update_frontmatter\", \"skipped\", \"error\", \"override\",\n\t// \"override_skipped\", \"override_mechanical\", \"inflight_skipped\",\n\t// \"override_owns_sha\"\n\tIncPRPublished(command string)\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// SetRateLimitRemaining records the primary rate-limit window's remaining\n\t// requests (shared App token). The alert rule on this gauge fires BEFORE\n\t// quota exhaustion, catching the 2026-08-23 silent fleet-wide stall.\n\tSetRateLimitRemaining(remaining int)\n\t// SetUnreviewedPRs replaces the set of PRs reported on the\n\t// github_pr_watcher_unreviewed_prs gauge and records scannedAt on the\n\t// last-successful-scan timestamp gauge. The slice is the complete result\n\t// of one scan, so an empty slice clears the gauge.\n\tSetUnreviewedPRs(prs []UnreviewedPR, scannedAt libtime.DateTime)\n\t// SetParkedPRs replaces the set of oversized PRs reported on the\n\t// github_pr_watcher_parked_prs gauge. The slice is the complete result of\n\t// one scan, so an empty slice clears the gauge.\n\tSetParkedPRs(prs []ParkedPR)\n\t// IncUnreviewedRetry increments the retry counter with the given repo label.\n\t// repo: `owner/repo`\n\tIncUnreviewedRetry(repo string)\n\t// IncEscalation increments the auto-merge refusal escalation counter.\n\t// class: \"untrusted-author\", \"trust-check-error\", \"enable-auto-merge-error\",\n\t// \"checks-not-green\", \"review-request-changes\".\n\t// result: \"published\", \"duplicate\", \"error\".\n\tIncEscalation(class, result string)\n}\n```\nMetrics exposes counters for observable watcher behaviour.\n\n```go\nfunc NewMetrics() Metrics\n```\nNewMetrics returns a Metrics implementation backed by Prometheus counters.\n\n```go\ntype OverrideLedger interface {\n\t// Record notes that an override was published for pr. A failure is logged,\n\t// never returned: the override command has already been sent, and a\n\t// bookkeeping error must not turn that into a retry.\n\tRecord(ctx context.Context, pr RetryGuardPR, taskID string)\n\t// Suppressed reports whether a review for pr's head SHA must not be\n\t// published because a fresh override owns it. A ledger that cannot be read\n\t// fails OPEN — the pre-change behaviour is to publish the review, and losing\n\t// a review is worse than a duplicate.\n\tSuppressed(ctx context.Context, pr RetryGuardPR) bool\n\t// SuppressedTx is the same check inside a caller-held transaction. The\n\t// command executor runs inside the consumer's already-held transaction and\n\t// memDB's mutex is not re-entrant, so it cannot open one of its own.\n\tSuppressedTx(ctx context.Context, tx libkv.Tx, pr RetryGuardPR) (bool, error)\n}\n```\nOverrideLedger records which head SHAs already carry a published pr-override, so that no review is published for them while the override is still in flight.\n\nIt exists because the watcher has three independent producers of review tasks — the poll loop, the unreviewed scanner and the trigger executor — and only the poll loop owns the mechanical decision. A producer that cannot see that decision spends exactly the reviewer pod the override exists to save. Both observed cases came from a producer that had no way to ask:\n\n  - bborbe/kafka-topic-reader#26: the trigger executor published a review 44 s after the override, on a command whose Webhook flag was false, so the deferral gated on cmd.Webhook never applied.\n  - bborbe/alert#29: the unreviewed scanner published one 30 min after the override, because the PR still showed no review while the override's APPROVE was pending.\n\nThe gate is on STATE, not on origin. \"Has an override been published for this SHA\" covers every producer that exists and every one added later; an allow-list of producers, command shapes or entry points would be re-opened by the next one, and the #26 producer could not even be identified — it arrived on the command topic with no inbound HTTP request logged anywhere.\n\nThe ledger is in-memory and lost on restart, the same trade-off RetryGuard documents: a restart can only widen the window in which one duplicate slips through. The StatefulSet runs one replica, so it is not correct across replicas either.\n\n```go\nfunc NewOverrideLedger(\n\tdb libkv.DB,\n\tcurrentDateTime libtime.CurrentDateTimeGetter,\n) OverrideLedger\n```\nNewOverrideLedger returns an OverrideLedger backed by the in-process store. A nil db yields a ledger that records nothing and suppresses nothing, which is the pre-change behaviour.\n\n```go\ntype PRDetails struct {\n\t// HeadSHA is the commit hash of the PR's head branch. Used for force-push\n\t// detection and as the `ref` the agent checks out for review.\n\tHeadSHA string\n\n\t// CloneURL is the HTTPS clone URL of the base repo (e.g.\n\t// `https://github.com/owner/repo.git`). Used as the `clone_url` the\n\t// agent's execution phase passes to git clone. It must name the base\n\t// repo, not the head: on a fork PR the head repo is the contributor's\n\t// fork, which carries no PR of that number and cannot be resolved by a\n\t// reader holding only the PR number.\n\tCloneURL string\n\n\t// BaseRef is the base branch name (e.g. `master`, `main`). Used as\n\t// the `base_ref` the execution phase diffs against.\n\tBaseRef string\n\n\t// HeadRef is the head branch name (e.g. `fix/update-go-c0cf2ac`). Used to\n\t// recognise the update-go agent's dep-bump PRs, which it names\n\t// `fix/update-go-\u003csha\u003e` — see isSupersededDepBump.\n\tHeadRef string\n\n\t// HeadRepoFullName is the head repository's `owner/repo` full name. Empty\n\t// when GitHub no longer reports a head repo (a deleted fork). It feeds the\n\t// same-repo trust check, so an empty value denies.\n\tHeadRepoFullName string\n\n\t// BaseRepoFullName is the base repository's `owner/repo` full name. Empty\n\t// when unknown. It feeds the same-repo trust check, so an empty value\n\t// denies.\n\tBaseRepoFullName string\n\n\t// AuthorLogin is the GitHub author login; empty for deleted accounts.\n\tAuthorLogin string\n\n\t// Title is the PR title.\n\tTitle string\n\n\t// IsDraft indicates whether the PR is a draft.\n\tIsDraft bool\n\n\t// UpdatedAt is the PR last-updated timestamp; required for AgeFilter.\n\tUpdatedAt libtime.DateTime\n\n\t// Labels holds the PR's label names (e.g. `override-review`). Used to\n\t// route a labeled PR to the override task type.\n\tLabels []string\n\n\t// Additions is the PR's added-line count (diff size). Used to park\n\t// oversized PRs at human_review before spawning a review pod whose\n\t// prompt would overflow the reviewer's context window.\n\tAdditions int\n\n\t// ChangedFiles is the number of files the PR touches. Used alongside\n\t// Additions for the same oversized-PR park decision.\n\tChangedFiles int\n\n\t// MergeableState is GitHub's REST merge-state for the PR. Used by\n\t// tryUpdateBranch to decide whether the head branch is stale against its\n\t// base.\n\t//\n\t// `behind` means the base moved with no conflict; that is the case\n\t// update-branch resolves. `dirty` means the merge commit cannot be created\n\t// (a real conflict), which update-branch does NOT fix — it merges base\n\t// into head, so a conflicting merge fails. GraphQL exposes the same\n\t// concept as `mergeStateStatus` with upper-cased values.\n\tMergeableState MergeState\n}\n```\nPRDetails holds the per-PR fields the watcher needs to materialize a task the execution phase can act on. The Search API does not expose any of these; they require a follow-up PullRequests.Get call.\n\n```go\ntype PRFile struct {\n\tFilename string\n\tPatch    string\n\t// Additions is the file's added-line count, as reported by the GitHub\n\t// files API. Used to compute how many additions a repo's `.reviewignore`\n\t// excludes from the size gate, so the park decision counts only\n\t// reviewable content.\n\tAdditions int\n}\n```\nPRFile is a single changed file in a PR with its patch, as returned by the pull-request files endpoint. Patch may be empty for large/binary files.\n\n```go\ntype ParkLedger interface {\n\t// Read loads the file into memory. A missing file leaves the ledger\n\t// empty and logs at INFO; a corrupt file logs an error naming the path\n\t// and keeps the entries already in memory. It never returns an error:\n\t// ledger I/O must never fail a scan.\n\tRead(ctx context.Context)\n\t// Has reports whether key (\"\u003cowner\u003e/\u003crepo\u003e#\u003cpr\u003e\") is currently in the\n\t// in-memory ledger.\n\tHas(key string) bool\n\t// Reconcile seeds a new entry from the observation's UpdatedAt, keeps an\n\t// unchanged entry's Start, restarts a changed-SHA entry at UpdatedAt,\n\t// drops every entry absent from observations, persists the result\n\t// atomically, and returns the reconciled starts. A write failure is\n\t// logged and the in-memory result stays authoritative.\n\tReconcile(ctx context.Context, observations []ParkObservation) []ParkedPRStart\n}\n```\nParkLedger persists the start of each currently-parked oversized PR.\n\n```go\nfunc NewParkLedger(path string) ParkLedger\n```\nNewParkLedger returns a ParkLedger backed by the file at path.\n\n```go\ntype ParkLedgerEntry struct {\n\tStart libtime.DateTime `json:\"start\"`\n\tSHA   string           `json:\"sha\"`\n}\n```\nParkLedgerEntry is one persisted park: when it started and the head SHA it started at. The SHA is what makes a comment harmless and a push a restart.\n\n```go\ntype ParkObservation struct {\n\tRepo      string // \"owner/repo\"\n\tNumber    int\n\tSHA       string\n\tUpdatedAt libtime.DateTime\n}\n```\nParkObservation is one PR this complete scan evaluated and found parked. UpdatedAt is the PR's search-result updated-at, the clock the scan already treats as reviewable-since.\n\n```go\ntype ParkedPR struct {\n\tRepo       string\n\tNumber     int\n\tAgeSeconds float64\n}\n```\nParkedPR identifies one oversized PR parked at human\\_review, with how long it has been parked.\n\n```go\ntype ParkedPRStart struct {\n\tRepo   string\n\tNumber int\n\tStart  libtime.DateTime\n}\n```\nParkedPRStart is a reconciled ledger entry with its identity restored, so the caller can publish an age without parsing the ledger key.\n\n```go\ntype PublishRecorder interface {\n\tRecordPublish(ctx context.Context, pr RetryGuardPR, taskID string)\n}\n```\nPublishRecorder records that a review task was published for one head SHA, so the guard's Check can suppress a duplicate forced retry.\n\nIt exists for the publish paths that hold no transaction of their own — the poll loop and the unreviewed scanner both publish through TaskPublisher. The command executor must NOT use a recorder: it runs inside the consumer's already-held transaction and memDB's mutex is not re-entrant, so it records through its own tx instead.\n\n```go\nfunc NewPublishRecorder(db libkv.DB, guard RetryGuard) PublishRecorder\n```\nNewPublishRecorder returns a PublishRecorder that writes into the same ledger Check reads, one transaction per record.\n\n```go\ntype PublishTracker struct {\n\t// contains filtered or unexported fields\n}\n```\nPublishTracker records the last successful review-task publish, so the watcher can tell an idle publish path from a stopped one.\n\nA publish path that logs only what it publishes reports nothing when it publishes nothing, and that is exactly what a dead path looks like: measured 2026-11-07 on bborbe/nuke#1104, the watcher's publish line was silent for a 30-minute window while the unreviewed scanner kept listing the PR on every cycle. The tracker makes the silence itself observable — the watcher compares the count before and after a cycle and logs the zero together with the population the cycle saw, so \"no work to do\" and \"nothing happened\" read differently.\n\n```go\nfunc NewPublishTracker(currentDateTime libtime.CurrentDateTimeGetter) *PublishTracker\n```\nNewPublishTracker returns a PublishTracker reading the injected clock.\n\n```go\nfunc (t *PublishTracker) Record()\n```\nRecord notes one successful publish. Nil-tolerant, so a publisher or watcher built without a tracker behaves exactly as before.\n\n```go\nfunc (t *PublishTracker) Snapshot() (int64, libtime.DateTime)\n```\nSnapshot returns the number of publishes recorded so far and the time of the last one. The time is the zero DateTime when nothing has been published yet.\n\n```go\ntype PullRequest struct {\n\tGlobalID    int64\n\tNumber      int\n\tOwner       string\n\tRepo        string\n\tTitle       string\n\tHTMLURL     string\n\tHeadSHA     string\n\tAuthorLogin string\n\tIsDraft     bool\n\tUpdatedAt   libtime.DateTime\n\t// Labels holds the PR's label names (e.g. `override-review`). Populated\n\t// from the Search API's issue labels.\n\tLabels []string\n}\n```\nPullRequest holds the fields the watcher needs from a GitHub PR.\n\n```go\ntype RedriveLedger interface {\n\t// Record notes that a re-drive superseded originalTaskID for pr's head SHA.\n\t// A failure is logged, never returned: the re-drive command has already been\n\t// sent, and a bookkeeping error must not turn that into a retry.\n\tRecord(ctx context.Context, pr RetryGuardPR, originalTaskID string)\n\t// Pending returns the original task id a re-drive superseded for pr's head\n\t// SHA, and whether one is outstanding. A ledger that cannot be read reports\n\t// nothing pending: the pre-change behaviour is to close no record, and a\n\t// read failure must never fabricate a close.\n\tPending(ctx context.Context, pr RetryGuardPR) (string, bool)\n\t// Clear forgets the entry once the original has been closed, so the close is\n\t// attempted at most once per re-drive.\n\tClear(ctx context.Context, pr RetryGuardPR)\n}\n```\nRedriveLedger records the original record a re-drive superseded, keyed on the pull request and head SHA the re-drive was published for.\n\nIt exists because a re-drive cannot close the record it replaces at publish time. \\`PublishRedrive\\` lands the review on a SIBLING record — the title must change or the controller's title-path dedup drops the command — so the original stays parked at human\\_review with no verdict, which is the shape that keeps the unreviewed queue red.\n\nClosing it at publish time would be worse than leaving it open: the queue would drain whether or not the sibling ever ran, so a re-drive that never produced a pod would read as a cleared review. The close is therefore gated on the only evidence that the review actually happened — a reviewer verdict at the head SHA, which the unreviewed scanner already computes every cycle. This ledger is what carries the original's task id from the publish to that verdict.\n\nThe ledger is in-memory and lost on restart, the same trade-off RetryGuard and OverrideLedger document: a restart between the re-drive and its verdict leaves the original open, so the failure is a stuck record rather than a false clean one. That direction is deliberate — this ledger exists to stop a record reading clean before its review exists.\n\n```go\nfunc NewRedriveLedger(\n\tdb libkv.DB,\n\tcurrentDateTime libtime.CurrentDateTimeGetter,\n) RedriveLedger\n```\nNewRedriveLedger returns a RedriveLedger backed by the in-process store. A nil db yields a ledger that records nothing and reports nothing pending, which is the pre-change behaviour.\n\n```go\ntype RetryGuard interface {\n\t// Check decides whether a forced re-review may be published. It never\n\t// writes to the ledger; only Record does.\n\tCheck(ctx context.Context, tx libkv.Tx, pr RetryGuardPR) (RetryGuardDecision, error)\n\t// Record stores that a review was published for pr, so a later Check\n\t// suppresses a duplicate while it is fresh.\n\tRecord(ctx context.Context, tx libkv.Tx, pr RetryGuardPR, taskID string) error\n\t// ClearByTaskID scans the in-memory ledger for the record whose stored task\n\t// identifier equals taskID, deletes it if present, and logs the fixed clear\n\t// line at default verbosity. It reports whether a record was deleted; an\n\t// unknown identifier is a silent no-op.\n\tClearByTaskID(\n\t\tctx context.Context,\n\t\ttx libkv.Tx,\n\t\ttaskID string,\n\t\toutcome string,\n\t) (bool, error)\n}\n```\nRetryGuard suppresses a forced re-review whose review for the same head SHA is still in flight.\n\nThe ledger of published reviews is in-memory and lost on restart. That limitation is accepted: a restart can only widen the window in which one duplicate slips through, and a restart is also the only immediate way to clear a stuck record. The restart-independent backstop is the reviewer verdict check — a commit that already carries a verdict from a configured reviewer is allowed to re-run even when a record survives. The StatefulSet runs one replica, so the ledger is not correct across replicas.\n\n```go\nfunc NewRetryGuard(\n\tghClient GitHubClient,\n\tmetrics Metrics,\n\treviewerLogins []string,\n\tcurrentDateTime libtime.CurrentDateTimeGetter,\n) RetryGuard\n```\nNewRetryGuard returns a RetryGuard backed by the in-process ledger.\n\n```go\ntype RetryGuardAction string\n```\nRetryGuardAction is what the guard wants the caller to do.\n\n```go\nconst (\n\tRetryGuardActionCreate RetryGuardAction = \"create\"\n\tRetryGuardActionSkip   RetryGuardAction = \"skip\"\n)\n```\n\n```go\ntype RetryGuardDecision struct {\n\tAction         RetryGuardAction\n\tReason         RetryGuardReason\n\tExistingTaskID string\n\tRecordAge      libtime.Duration\n}\n```\nRetryGuardDecision is the guard's verdict for one forced re-review.\n\n```go\ntype RetryGuardPR struct {\n\tOwner   string\n\tRepo    string\n\tNumber  int\n\tHeadSHA string\n}\n```\nRetryGuardPR identifies one publishable review target.\n\n```go\ntype RetryGuardReason string\n```\nRetryGuardReason is why the guard chose its action.\n\n```go\nconst (\n\tRetryGuardReasonCreate                     RetryGuardReason = \"create\"\n\tRetryGuardReasonCreateForceOverrodeVerdict RetryGuardReason = \"create_force_overrode_verdict\"\n\tRetryGuardReasonCreateStaleRecordIgnored   RetryGuardReason = \"create_stale_record_ignored\"\n\tRetryGuardReasonSkipInflight               RetryGuardReason = \"skip_inflight\"\n)\n```\n\n```go\ntype Review struct {\n\t// ID is the review's GitHub id. Required to dismiss it; zero when the API\n\t// reported none.\n\tID int64\n\t// AuthorLogin is the reviewer's GitHub login; empty for a deleted account.\n\tAuthorLogin string\n\t// CommitID is the head SHA the review was posted against.\n\tCommitID string\n\t// Body is the review's body text. The do-not-merge gate reads its own\n\t// marker here so it can tell its reviews from the bot's genuine verdicts\n\t// and never dismiss a real finding.\n\tBody string\n\t// State is the review's verdict. Only a CHANGES_REQUESTED review on the\n\t// current head SHA blocks the merge and escalates.\n\tState ReviewState\n}\n```\nReview is a single PR review, reduced to the fields the unreviewed-PR scan and the do-not-merge gate need: who reviewed, which commit they reviewed, what verdict they left, and — for the gate's dismissal path — which review to dismiss and whether this mechanism wrote it.\n\n```go\ntype ReviewEvent string\n```\nReviewEvent is the value the reviews API accepts in the \\`event\\` field when SUBMITTING a review. It is deliberately a different type from ReviewState because the two vocabularies do not match: the API takes REQUEST\\_CHANGES and reports back CHANGES\\_REQUESTED. Passing the state name as the event is a 422 (\"Variable $event of type PullRequestReviewEvent was provided invalid value\") — measured live on bborbe/go-skeleton#127, 2026-11-13, on the first dev deploy of the do-not-merge gate.\n\n```go\nconst (\n\t// ReviewEventApprove submits an approving review.\n\tReviewEventApprove ReviewEvent = \"APPROVE\"\n\t// ReviewEventRequestChanges submits a blocking review. The resulting\n\t// ReviewState is CHANGES_REQUESTED, not this value.\n\tReviewEventRequestChanges ReviewEvent = \"REQUEST_CHANGES\"\n\t// ReviewEventComment submits a comment-only review.\n\tReviewEventComment ReviewEvent = \"COMMENT\"\n)\n```\n\n```go\ntype ReviewState string\n```\nReviewState is a GitHub review verdict, typed so a state-name typo is caught by the compiler rather than silently never matching.\n\n```go\nconst (\n\t// ReviewStateApproved clears a previous CHANGES_REQUESTED for that reviewer.\n\tReviewStateApproved ReviewState = \"APPROVED\"\n\t// ReviewStateChangesRequested blocks the merge until the same reviewer\n\t// approves or the review is dismissed — a later push does not clear it.\n\tReviewStateChangesRequested ReviewState = \"CHANGES_REQUESTED\"\n\t// ReviewStateCommented is a comment-only review; it does not change the\n\t// reviewer's standing verdict.\n\tReviewStateCommented ReviewState = \"COMMENTED\"\n\t// ReviewStateDismissed removes the reviewer's standing verdict.\n\tReviewStateDismissed ReviewState = \"DISMISSED\"\n\t// ReviewStatePending is a review not yet submitted.\n\tReviewStatePending ReviewState = \"PENDING\"\n)\n```\n\n```go\ntype SearchResult struct {\n\tPullRequests  []PullRequest\n\tHasNextPage   bool\n\tNextPage      int\n\tRateRemaining int\n\tRateResetAt   libtime.DateTime\n}\n```\nSearchResult is the result of a single paginated search call.\n\n```go\ntype TaskConfig struct {\n\tStage       string\n\tMaxSlugLen  int\n\tMaxTitleLen int\n\tTaskSuffix  string\n\t// TargetVault routes the CreateTaskCommand to a specific vault controller\n\t// (matched verbatim against the controller's VAULT_NAME). Empty leaves\n\t// TargetVault unset, so the controller's legacy default-vault fallback\n\t// applies — preserving pre-TARGET_VAULT behaviour.\n\tTargetVault string\n\t// MaxAdditions parks PRs with more than this many added lines at\n\t// human_review instead of spawning a review pod. 0 disables the check.\n\tMaxAdditions int\n\t// MaxChangedFiles parks PRs touching more than this many files at\n\t// human_review instead of spawning a review pod. 0 disables the check.\n\tMaxChangedFiles int\n}\n```\nTaskConfig groups the per-task publishing configuration.\n\n```go\ntype TaskPublisher interface {\n\tPublishCreate(ctx context.Context, pr PullRequest, taskIDStr string, details PRDetails) bool\n\t// PublishRedrive publishes a review task for a record that has outlived the\n\t// retry guard's staleness bound with no verdict at its head SHA. It differs\n\t// from PublishCreate in exactly two ways, both required for the command to\n\t// do anything:\n\t//\n\t//   - The title carries a `retry-\u003ctoken\u003e` segment. The agent controller\n\t//     dedups on the TITLE PATH, not on task_identifier, so a salted id with\n\t//     an unchanged title is rejected with ErrTaskAlreadyExists and re-runs\n\t//     nothing — see computePRTitle.\n\t//   - The publish is NOT recorded in the retry guard's ledger. Recording it\n\t//     would keep the ledger permanently fresh while re-drives continue, and\n\t//     an operator's forced /trigger on the same PR would then be suppressed\n\t//     as in-flight for an hour after every re-drive, which is the manual\n\t//     lever's whole purpose gone.\n\t//\n\t// supersededTaskID names the record this re-drive replaces — the\n\t// deterministic DeriveTaskID the spent run was published under. Because the\n\t// re-drive lands on a SIBLING record (the salted taskIDStr), the original\n\t// would otherwise stay parked at human_review forever with no verdict, and\n\t// that parked record is what keeps the unreviewed queue from draining. It is\n\t// recorded in the RedriveLedger so CompleteRedriven can close it once a\n\t// reviewer verdict at the head SHA proves the re-drive actually ran. An empty\n\t// supersededTaskID records nothing, which is the pre-change behaviour.\n\tPublishRedrive(\n\t\tctx context.Context,\n\t\tpr PullRequest,\n\t\ttaskIDStr string,\n\t\tsupersededTaskID string,\n\t\tdetails PRDetails,\n\t) bool\n\t// CompleteRedriven closes the original record a re-drive superseded, once a\n\t// reviewer verdict at pr's head SHA proves the re-drive produced a review.\n\t//\n\t// The close is deliberately NOT done at publish time. Closing the original\n\t// when its sibling is merely published would drain the queue whether or not\n\t// the sibling ever ran, so a re-drive that produced no pod would read as a\n\t// cleared review — the hollow-green shape this whole change exists to avoid.\n\t// The verdict at the head SHA is the only evidence the review happened, and\n\t// it is what the caller passes here.\n\t//\n\t// Returns nil when nothing was outstanding for the head SHA, or when the\n\t// close succeeded; a non-nil error when a close WAS attempted and failed.\n\t//\n\t// The caller must not treat a failure as settled. The ledger entry is only\n\t// cleared on success, so the next scan retries it — but only if the caller\n\t// refrains from caching the PR as reviewed. A discarded error would strand\n\t// the superseded record permanently on the first transient send failure.\n\t// Idempotent: a second call after a successful close finds nothing\n\t// outstanding and returns nil.\n\tCompleteRedriven(ctx context.Context, pr PullRequest, details PRDetails) error\n\t// PublishOverride publishes a `pr-override` task for a labeled PR. It is\n\t// trusted-authors-only. Returns (handled, emitted):\n\t//   - handled=true: this is a trusted-author override case; the caller must\n\t//     NOT emit a review task for this SHA (even when the send failed —\n\t//     retry on the next poll). This preserves the override-only invariant\n\t//     that prevents an APPROVE-vs-CHANGES_REQUESTED race.\n\t//   - emitted=true: the override task was actually sent; the caller records\n\t//     it in the cursor so the override fires at most once per head SHA.\n\t//   - untrusted author (or trust-check error) → (false, false): the caller\n\t//     falls through to the normal review path (which routes untrusted →\n\t//     human_review).\n\tPublishOverride(\n\t\tctx context.Context,\n\t\tpr PullRequest,\n\t\ttaskIDStr string,\n\t\tdetails PRDetails,\n\t) (handled, emitted bool)\n\t// PublishMechanicalOverride publishes the mechanical `pr-override` task for\n\t// a qualifying trivial bot bump. The caller (the watcher's mechanical gate)\n\t// has already evaluated the author list, trust, the repo's two opt-in flags\n\t// and the file classifier, so this method performs no trust check of its\n\t// own. Returns true when the command was sent; false when the send failed,\n\t// in which case the caller records nothing so the emission is retried on\n\t// the next poll.\n\tPublishMechanicalOverride(\n\t\tctx context.Context,\n\t\tpr PullRequest,\n\t\ttaskIDStr string,\n\t\tdetails PRDetails,\n\t) bool\n}\n```\nTaskPublisher publishes create-task commands for a given PR + details pair. Returns true on successful publish, false on trust check failure or send failure.\n\n```go\nfunc NewTaskPublisher(\n\tcreateSender task.CreateCommandSender,\n\ttrustDecision trust.Trust,\n\tmetrics Metrics,\n\tcfg TaskConfig,\n\tghClient GitHubClient,\n\topts ...TaskPublisherOption,\n) TaskPublisher\n```\nNewTaskPublisher returns a TaskPublisher that performs trust evaluation then publishes a CreateTaskCommand via the given CreateCommandSender.\n\n```go\ntype TaskPublisherOption func(*taskPublisher)\n```\nTaskPublisherOption configures optional TaskPublisher behaviour.\n\n```go\nfunc WithCompleteSender(sender task.CompleteCommandSender) TaskPublisherOption\n```\nWithCompleteSender gives the publisher a CompleteCommandSender, which is what actually closes a superseded record. Nil-tolerant: a publisher built without one publishes re-drives but closes no original, which is the pre-change behaviour and is logged as such.\n\n```go\nfunc WithOverrideLedger(ledger OverrideLedger) TaskPublisherOption\n```\nWithOverrideLedger makes the publisher record every pr-override it sends and refuse to publish a review for a head SHA that a fresh override owns. It is what keeps the two override-only invariants from being broken by a producer that does not own the mechanical decision — see OverrideLedger.\n\n```go\nfunc WithPublishRecorder(recorder PublishRecorder) TaskPublisherOption\n```\nWithPublishRecorder makes the publisher record every review task it sends in the retry guard's ledger, so a later forced retry for the same head SHA is suppressed while that review is still in flight. Without it the publisher records nothing.\n\n```go\nfunc WithPublishTracker(tracker *PublishTracker) TaskPublisherOption\n```\nWithPublishTracker makes the publisher note every successful send on the shared PublishTracker, so the watcher can report a cycle that published nothing instead of staying silent about it.\n\n```go\nfunc WithRedriveLedger(ledger RedriveLedger) TaskPublisherOption\n```\nWithRedriveLedger makes the publisher record the original task id a re-drive superseded, so CompleteRedriven can close that record once a verdict proves the re-drive ran. Nil-tolerant: a publisher built without one records nothing, so no original is ever closed — the pre-change behaviour.\n\n```go\ntype UnreviewedConfig struct {\n\t// Logins are the GitHub logins whose reviews count as \"the reviewer\n\t// looked at this PR\". Matching ignores casing and a trailing `[bot]`\n\t// suffix, so `octopus-pr-reviewer` matches the App login\n\t// `octopus-pr-reviewer[bot]`. An empty list disables the scan entirely.\n\tLogins []string\n\t// Threshold is how long a publishable PR must have gone without a\n\t// reviewer-bot review on its current head SHA before it is reported, and\n\t// how long to wait between retries of an unreviewed PR.\n\tThreshold libtime.Duration\n\t// RetryMax is the most review tasks the scan re-publishes for one\n\t// (PR, head SHA) pair before it gives up and marks the PR exhausted. 0\n\t// disables retrying — every unreviewed PR is reported as exhausted.\n\tRetryMax int\n}\n```\nUnreviewedConfig configures the unreviewed-PR scan.\n\n```go\nfunc ParseUnreviewedConfig(\n\tctx context.Context,\n\trawLogins, rawThreshold string,\n\tretryMax int,\n) (UnreviewedConfig, error)\n```\nParseUnreviewedConfig parses the raw REVIEWER\\_BOT\\_LOGINS, UNREVIEWED\\_THRESHOLD and UNREVIEWED\\_RETRY\\_MAX values into an UnreviewedConfig. Logins are split like BOT\\_ALLOWLIST (trimmed, empties dropped). No logins after parsing means the feature is disabled: the threshold is neither parsed nor validated and RetryMax is not range-validated — both are ignored and the returned Threshold is zero. With logins configured the threshold must parse as a positive duration.\n\n```go\ntype UnreviewedPR struct {\n\t// Repo is the `owner/repo` pair, matching the gauge's repo label.\n\tRepo string\n\t// Number is the pull-request number, rendered as the gauge's pr label.\n\tNumber int\n\t// RetriesExhausted marks a PR whose bounded retry budget is spent. The\n\t// scan keeps re-driving such a PR once per stale hour, so the label means\n\t// \"the budget is gone\", not \"nothing is being tried\", and it stays true\n\t// through those re-drives rather than flapping every threshold. Rendered\n\t// as the gauge's retries_exhausted label.\n\tRetriesExhausted bool\n}\n```\nUnreviewedPR identifies one open pull request reported as unreviewed.\n\n```go\ntype UnreviewedScanner interface {\n\tScan(ctx context.Context)\n\t// LastCandidates returns how many PRs the last complete scan found still\n\t// owed a review. It is the population the watcher's silence line needs:\n\t// the raw search count is not it, because a PR sitting at the cursor\n\t// boundary is listed on every cycle and legitimately produces nothing.\n\t// Zero before the first complete scan and after a scan that aborted.\n\tLastCandidates() int\n}\n```\nUnreviewedScanner reports, once per poll cycle, the open pull requests the watcher would hand to the reviewer whose current head SHA still has no review from a configured reviewer bot, and re-publishes the original review task for those still unreviewed — a bounded number of retries, then one salted stale re-drive per hour for as long as no verdict arrives.\n\nIt publishes only through the shared TaskPublisher — a bounded retry as PublishCreate with the deterministic DeriveTaskID, and a stale re-drive as PublishRedrive with a salted one — and never mutates GitHub. The scan is a read plus a re-send of an existing command, nothing more.\n\nScan deliberately returns no error: a failed or interrupted scan must never fail the poll cycle. It leaves the previous gauge values in place instead, so a scan that keeps failing is visible through the separate last-successful-scan timestamp rather than through a broken poll.\n\n```go\nfunc NewUnreviewedScanner(\n\tghClient GitHubClient,\n\tpublisher TaskPublisher,\n\tdispatchLedger DispatchLedger,\n\tmetrics Metrics,\n\tcurrentDateTime libtime.CurrentDateTimeGetter,\n\tscope string,\n\ttaskCreationFilter filter.TaskCreationFilter,\n\ttrustDecision trust.Trust,\n\toverrideLabel string,\n\tmaxAdditions, maxChangedFiles int,\n\tcfg UnreviewedConfig,\n\topts ...UnreviewedScannerOption,\n) UnreviewedScanner\n```\nNewUnreviewedScanner returns an UnreviewedScanner backed by the shared GitHub client, publisher, metrics and decision chains the watcher already holds, so the scan applies exactly the same filters, trust check and park decision as the publish path, and re-publishes through the same publisher — never a second one, whose TaskConfig could drift and change the title path.\n\n```go\ntype UnreviewedScannerOption func(*unreviewedScanner)\n```\nUnreviewedScannerOption configures optional scanner dependencies.\n\n```go\nfunc WithParkLedger(ledger ParkLedger) UnreviewedScannerOption\n```\nWithParkLedger wires the park ledger the scan records parked oversized PRs into and reads their start times from. Without it the parked-PR metric is not published, which is the pre-change behaviour.\n\n```go\ntype Watcher interface {\n\tPoll(ctx context.Context) error\n}\n```\nWatcher polls GitHub and publishes task commands to Kafka.\n\n```go\nfunc NewWatcher(\n\tghClient GitHubClient,\n\tpublisher TaskPublisher,\n\tmetrics Metrics,\n\tcursorPath string,\n\tstartTime libtime.DateTime,\n\tscope string,\n\ttaskCreationFilter filter.TaskCreationFilter,\n\tsideEffectFilter filter.TaskCreationFilter,\n\toverrideLabel string,\n\tautoMergeLabel string,\n\ttrivialAutoMergeEnabled bool,\n\tmechanicalOverrideAuthors []string,\n\ttrustDecision trust.Trust,\n\tunreviewedScanner UnreviewedScanner,\n\tcoalescer coalesce.Coalescer,\n\tcurrentDateTime libtime.CurrentDateTimeGetter,\n\topts ...WatcherOption,\n) Watcher\n```\nNewWatcher returns a Watcher that polls GitHub and publishes commands.\n\n```go\ntype WatcherOption func(*watcher)\n```\nWatcherOption configures optional watcher dependencies without widening the positional constructor every caller (and every test) has to restate.\n\n```go\nfunc WithEscalator(escalator escalate.Escalator) WatcherOption\n```\nWithEscalator wires the auto-merge refusal escalator. Without it, a refusal is logged and counted but never reaches the operator — the silent hold this change exists to remove.\n\n```go\nfunc WithWatcherPublishTracker(tracker *PublishTracker) WatcherOption\n```\nWithWatcherPublishTracker wires the tracker the publisher records on, so the watcher can log a cycle that published nothing for any PR. Without it no liveness line is emitted.\n\n","path":"github.com/bborbe/github-pr-watcher/pkg","name":"pkg","synopsis":"Package pkg provides the core domain types and logic for the maintainer-watcher-github-pr service: GitHub API integration, pull-request filtering, cursor persistence, and Kafka command publishing.","isRedistributable":true}
