pkg

package
v0.27.0 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: BSD-2-Clause Imports: 40 Imported by: 1 module, 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 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.

Index

Constants

View Source
const DefaultCursorPath = "/data/cursor.json"

DefaultCursorPath is the default path for cursor state persistence.

View Source
const DefaultMaxSlugLen = 80

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

View Source
const DefaultMaxTitleLen = 200

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

Variables

View Source
var AvailableMergeStates = []MergeState{MergeStateBehind, MergeStateDirty}

AvailableMergeStates lists every merge state the watcher acts on.

View Source
var ErrPermanent = stderrors.New("permanent github error")

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

Functions

func BuildCreateCommand

func BuildCreateCommand(
	pr PullRequest,
	details PRDetails,
	taskIDStr string,
	stage string,
	maxSlugLen int,
	maxTitleLen int,
	taskSuffix string,
	targetVault string,
	trustResult trust.Result,
	forced bool,
	maxAdditions int,
	maxChangedFiles int,
	exclusion Exclusion,
) task.CreateCommand

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

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

func BuildMechanicalOverrideCommand added in v0.15.0

func BuildMechanicalOverrideCommand(
	pr PullRequest,
	details PRDetails,
	taskIDStr string,
	stage string,
	maxSlugLen int,
	maxTitleLen int,
	taskSuffix string,
	targetVault string,
) task.CreateCommand

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

func BuildOverrideCommand added in v0.3.0

func BuildOverrideCommand(
	pr PullRequest,
	details PRDetails,
	taskIDStr string,
	stage string,
	maxSlugLen int,
	maxTitleLen int,
	taskSuffix string,
	targetVault string,
) task.CreateCommand

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

func ClassifyTrivial added in v0.7.0

func ClassifyTrivial(files []PRFile) bool

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

func DeriveTaskID

func DeriveTaskID(owner, repo string, number int, sha string) uuid.UUID

DeriveTaskID returns a deterministic task identifier for a (PR, SHA) pair. Input: "<owner>/<repo>#<number>@<sha>", e.g. "bborbe/maintainer#42@abc123...". The full SHA is used (not truncated) to keep the dedup keyspace collision-free.

func DeriveTaskIDForce

func DeriveTaskIDForce(owner, repo string, number int, sha, nonce string) uuid.UUID

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

For the same (owner, repo, number, sha) the result is always different from DeriveTaskID(...): the key includes the nonce segment "<nonce>", e.g. "bborbe/maintainer#42@abc123...!1700000000000000000".

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

func DeriveTaskIDOverride added in v0.3.0

func DeriveTaskIDOverride(owner, repo string, number int, sha string) uuid.UUID

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

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

func GitHubAPIBucket added in v0.20.0

func GitHubAPIBucket(req *http.Request) string

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

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

func NewMemDB

func NewMemDB() libkv.DB

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

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

func NewRetryGuardOutcomeConsumer added in v0.23.3

func NewRetryGuardOutcomeConsumer(
	saramaClientProvider libkafka.SaramaClientProvider,
	db libkv.DB,
	prefix base.TopicPrefix,
	guard RetryGuard,
	ledger DispatchLedger,
) run.Func

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

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

func NewRetryGuardOutcomeMessageHandler added in v0.23.3

func NewRetryGuardOutcomeMessageHandler(
	guard RetryGuard,
	ledger DispatchLedger,
) libkafka.MessageHandlerTx

NewRetryGuardOutcomeMessageHandler returns a transaction message handler that clears the retry guard record for a task that reached a terminal status.

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

func ParseBotAllowlist

func ParseBotAllowlist(raw string) []string

ParseBotAllowlist splits a comma-separated allowlist string into a slice of trimmed, non-empty entries.

func ParseMechanicalOverrideAuthors added in v0.15.0

func ParseMechanicalOverrideAuthors(raw string) []string

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

func ParseTrustedAuthors

func ParseTrustedAuthors(raw string) []string

ParseTrustedAuthors splits a comma-separated trusted-authors string into a slice of trimmed, non-empty entries. Mirrors ParseBotAllowlist in behavior.

func SaveCursor

func SaveCursor(ctx context.Context, path string, state Cursor) error

SaveCursor persists cursor state to path atomically via a temp file + rename.

Types

type CommitState added in v0.22.0

type CommitState string

CommitState is a GitHub commit-status state. Only the two values the do-not-merge gate uses are modelled; the API also accepts pending and error, which this watcher never posts.

const (
	// CommitStateSuccess reports that the PR carries no blocking label.
	CommitStateSuccess CommitState = "success"
	// CommitStateFailure reports that the PR carries the blocking label.
	CommitStateFailure CommitState = "failure"
)

type Cursor

type Cursor struct {
	LastUpdatedAt libtime.DateTime  `json:"last_updated_at"`
	HeadSHAs      map[string]string `json:"head_shas"`
	// Deferrals counts how many consecutive polls a (PR, head SHA) has been left
	// unsettled because its mechanical-override gate could not be evaluated. A
	// deferral deliberately writes no HeadSHAs entry, so this count is the only
	// record that the PR is owed another attempt — and the only thing that bounds
	// the retry, so a permanently unreadable gate cannot pin the cursor forever.
	Deferrals map[string]int `json:"deferrals,omitempty"`
}

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

func LoadCursor

func LoadCursor(ctx context.Context, path string, startTime libtime.DateTime) (Cursor, error)

LoadCursor reads cursor state from path. Returns cold-start state with startTime if the file is missing or corrupt.

type DispatchLedger added in v0.25.0

type DispatchLedger interface {
	// Mark records that taskID was observed dispatched.
	Mark(taskID string)
	// Seen reports whether taskID was observed dispatched by this process.
	Seen(taskID string) bool
}

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

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

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

func NewDispatchLedger added in v0.25.0

func NewDispatchLedger() DispatchLedger

NewDispatchLedger returns an empty in-process ledger.

type Exclusion added in v0.10.0

type Exclusion struct {
	// Additions is the sum of added lines across matched files.
	Additions int
	// Files is the number of matched files.
	Files int
}

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

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

func ComputeExclusion added in v0.10.0

func ComputeExclusion(files []PRFile, matcher reviewignore.Matcher) Exclusion

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

func ReviewIgnoreExclusion added in v0.10.0

func ReviewIgnoreExclusion(
	ctx context.Context,
	ghClient GitHubClient,
	owner, repo string,
	number int,
	prURL string,
) Exclusion

ReviewIgnoreExclusion reads the repo's `.reviewignore` and computes what it excludes from a PR's size-gate counts. prURL is used only for log context.

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

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

func (Exclusion) Empty added in v0.10.0

func (e Exclusion) Empty() bool

Empty reports whether the exclusion removed nothing, so callers can skip reporting a line that would read "0 additions across 0 files excluded".

type GitHubAPIMetrics added in v0.20.0

type GitHubAPIMetrics interface {
	// IncGitHubAPICall counts one round trip. outcome: "success", "error".
	IncGitHubAPICall(bucket string, outcome string)
	// IncGitHubAPIRateLimited counts one rate-limited response. class: "unclassified".
	IncGitHubAPIRateLimited(bucket string, class string)
}

GitHubAPIMetrics records per-caller GitHub API counters. The service, credential and cluster labels are bound at construction.

func NewGitHubAPIMetrics added in v0.20.0

func NewGitHubAPIMetrics(credential string, cluster string) GitHubAPIMetrics

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

type GitHubClient

type GitHubClient interface {
	// SearchPRs issues a GitHub Search query for open PRs updated since cursor.
	// page=1 for the first call; use SearchResult.NextPage for subsequent calls.
	// PullRequest.HeadSHA in the result is empty — call GetPRDetails to fetch it.
	SearchPRs(
		ctx context.Context,
		scope string,
		since libtime.DateTime,
		page int,
	) (SearchResult, error)

	// SearchLabeledPRs issues a GitHub Search query for open PRs carrying
	// label, with NO `updated:>=` bound. page=1 for the first call; use
	// SearchResult.NextPage for subsequent calls.
	//
	// The absence of an updated bound is the point: SearchPRs is scoped by a
	// monotonic cursor, so a PR that has stopped being updated — which is what
	// a stale branch IS — drops out of its window permanently. The side-effect
	// paths (update-branch, auto-merge, supersede) exist precisely for those
	// PRs, so they query by label instead and stay reachable for as long as
	// the label is present. See processLabeledPRs.
	//
	// PullRequest.HeadSHA in the result is empty — call GetPRDetails to fetch it.
	SearchLabeledPRs(
		ctx context.Context,
		scope string,
		label string,
		page int,
	) (SearchResult, error)

	// SearchOpenPRs issues a GitHub Search query for every open PR in scope,
	// with NO `updated:` bound. Used by the unreviewed-PR scan, which must see
	// a PR whose review was lost long ago and whose updated-at has since
	// fallen behind the cursor. page=1 for the first call; use
	// SearchResult.NextPage for subsequent calls.
	//
	// PullRequest.HeadSHA in the result is empty — call GetPRDetails to fetch it.
	SearchOpenPRs(ctx context.Context, scope string, page int) (SearchResult, error)

	// GetPRDetails fetches the head SHA, clone URL, and base ref for a single PR.
	// The Search API does NOT return any of these, so the poll loop must call
	// this for every PR before publishing a task command.
	GetPRDetails(ctx context.Context, owner, repo string, number int) (PRDetails, error)

	// ListReviews returns the PR's reviews, paginated to exhaustion. Used by
	// the unreviewed-PR scan to decide whether a configured reviewer bot has
	// reviewed the PR's current head SHA. A review in any state counts.
	ListReviews(ctx context.Context, owner, repo string, number int) ([]Review, error)

	// GetCommitState returns the merge-blocking state of ref as one of
	// "success", "pending" or "failure". It merges BOTH signals GitHub uses:
	// the legacy combined commit-status state AND the check runs. The combined
	// status alone excludes GitHub Actions check runs, so a repo whose CI is an
	// Actions workflow would read success while its test run failed.
	//
	// It is the read the checks-not-green escalation is built on — the watcher
	// arms auto-merge and GitHub holds the PR, so this is the only place the
	// watcher can observe that the hold is not clearing.
	GetCommitState(ctx context.Context, owner, repo, ref string) (string, error)

	// EnableAutoMerge arms GitHub-native auto-merge on a PR: when all merge
	// requirements (required status checks + required reviews per the repo
	// ruleset) are met, GitHub merges the PR automatically. Re-arming an
	// already-armed PR succeeds. Arming a PR that is ALREADY mergeable fails
	// with UNPROCESSABLE "Pull request is in clean status" — auto-merge only
	// applies while something still blocks the merge. Requires the
	// authenticating identity to hold Pull requests: Write on the repo.
	EnableAutoMerge(ctx context.Context, owner, repo string, number int) error

	// UpdateBranch merges the PR's base branch into its head branch —
	// GitHub-native update-branch, a merge and never a force-push. Used to
	// clear the `behind` state that strands an otherwise-mergeable PR once
	// master moves. A conflicting merge fails (GitHub answers 422), so a
	// `dirty` PR is NOT resolvable this way — update-branch fixes staleness,
	// not conflicts. Requires the authenticating identity to hold
	// Contents: Write on the repo.
	UpdateBranch(ctx context.Context, owner, repo string, number int) error

	// ClosePR closes the PR without merging it, optionally posting a comment
	// first explaining why. This is the abort half of the update-go
	// abort-and-reemit policy: a dep-bump PR whose CHANGELOG hunk conflicts
	// with a release cannot be refreshed by UpdateBranch — that merges base
	// into head, and a conflicting merge fails — so it is retired and the
	// update-go pipeline produces a fresh one off current master.
	//
	// This is NOT a merge route and the never-merge boundary holds: closing is
	// strictly weaker than merging, and the watcher still cannot land a
	// change. Requires Pull requests: Write.
	ClosePR(ctx context.Context, owner, repo string, number int, comment string) error

	// GetMaintainerConfig fetches and parses the repo's `.maintainer.yaml`
	// trust file via maintainerconfig. An absent file (404) returns the
	// zero-value config with nil error — matching the "opt-in, never
	// defaulted-on" trust-gate contract. Other errors are wrapped.
	GetMaintainerConfig(
		ctx context.Context,
		owner, repo string,
	) (maintainerconfig.MaintainerConfig, error)

	// ListPRFiles returns the PR's changed files with their patches, used by
	// the mechanical triviality classifier.
	ListPRFiles(ctx context.Context, owner, repo string, number int) ([]PRFile, error)

	// GetReviewIgnore fetches the repo's root `.reviewignore` and returns a
	// matcher for the paths it excludes from the size gate. An absent file
	// (404) returns a matcher that excludes nothing, with a nil error —
	// matching the "opt-in, never defaulted-on" contract GetMaintainerConfig
	// uses. Other errors are wrapped.
	GetReviewIgnore(
		ctx context.Context,
		owner, repo string,
	) (reviewignore.Matcher, error)

	// AddLabel adds a label to a PR (a no-op when already present). Requires
	// the authenticating identity to hold Pull requests: Write on the repo.
	AddLabel(ctx context.Context, owner, repo string, number int, label string) error

	// PostCommitStatus posts a commit status on sha under the given context.
	// This is the reporter that replaces the per-repo `check-do-not-merge`
	// bridge workflows: the `do-not-merge` context is a required status check
	// in the master-protection ruleset of nine repos, so a missing reporter
	// blocks every merge there. Requires the authenticating identity to hold
	// Commit statuses: Write on the repo.
	PostCommitStatus(
		ctx context.Context,
		owner, repo, sha string,
		state CommitState,
		statusContext string,
	) error

	// SubmitReview posts a review on commitID. The do-not-merge gate uses it to
	// submit a CHANGES_REQUESTED review, which blocks the merge on every
	// ruleset that requires an approving review — the mechanism the fleet's
	// held-PR route depends on, because the reviewer App declares no
	// Commit statuses: Write and so cannot post the equivalent commit status.
	// Requires Pull requests: Write.
	SubmitReview(
		ctx context.Context,
		owner, repo string,
		number int,
		commitID, body string,
		event ReviewEvent,
	) error

	// DismissReview dismisses one review by id, removing its standing verdict
	// from the PR's review decision. The do-not-merge gate uses it to release
	// its own CHANGES_REQUESTED review when the label is removed, which
	// restores whatever verdict the reviewer held before the label appeared.
	// Requires Pull requests: Write, and — where a ruleset restricts dismissals
	// to authorized actors — membership of that list.
	DismissReview(
		ctx context.Context,
		owner, repo string,
		number int,
		reviewID int64,
		message string,
	) error

	// RateLimitRemaining returns the requests remaining in the current primary
	// rate-limit window, as reported by the last API response's
	// X-RateLimit-Remaining header. Zero until the first request populates it.
	// Both watchers share the same App installation token, so this watcher's
	// reading reflects the shared 12,500/hour budget — the metric built from
	// this is the alert surface that catches quota exhaustion BEFORE the
	// fleet-wide 403 stall (2026-08-23 incident).
	RateLimitRemaining() int

	// GetRateLimitCoreRemaining returns the shared token's primary (core)
	// rate-limit remaining via the GET /rate_limit endpoint. Used to populate
	// the gauge on poll cycles where no core-API call happens (search-only
	// cycles with no open PRs would otherwise leave the gauge at 0 — the
	// "unpopulated" sentinel — which falsely reads as quota exhaustion).
	GetRateLimitCoreRemaining(ctx context.Context) (int, error)
}

GitHubClient abstracts the GitHub API calls.

func NewGitHubClient

func NewGitHubClient(httpClient *http.Client, apiMetrics GitHubAPIMetrics) GitHubClient

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

type MergeState added in v0.11.0

type MergeState string

MergeState is a GitHub REST merge-state value, typed so a state-name typo is caught by the compiler rather than silently never matching.

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

const (
	// MergeStateBehind is a head branch behind its base with no conflict —
	// the case update-branch resolves.
	MergeStateBehind MergeState = "behind"
	// MergeStateDirty is a PR whose merge commit cannot be created (a real
	// conflict). update-branch does not resolve it.
	MergeStateDirty MergeState = "dirty"
)

type Metrics

type Metrics interface {
	// IncPollCycle increments the poll cycle counter with the given result label.
	// result: "success", "rate_limited", "github_error"
	IncPollCycle(result string)
	// IncPRPublished increments the PR-published counter with the given command label.
	// command: "create", "update_frontmatter", "skipped", "error", "override",
	// "override_skipped", "override_mechanical", "inflight_skipped",
	// "override_owns_sha"
	IncPRPublished(command string)
	// IncWebhookDelivery increments the webhook delivery counter with the given result label.
	// result: "success", "skip"
	IncWebhookDelivery(result string)
	// IncWebhookSignatureRejected increments the webhook signature-rejection counter.
	IncWebhookSignatureRejected()
	// ObserveWebhookDispatchLatency records the dispatch latency of a webhook delivery.
	ObserveWebhookDispatchLatency(seconds float64)
	// SetRateLimitRemaining records the primary rate-limit window's remaining
	// requests (shared App token). The alert rule on this gauge fires BEFORE
	// quota exhaustion, catching the 2026-08-23 silent fleet-wide stall.
	SetRateLimitRemaining(remaining int)
	// SetUnreviewedPRs replaces the set of PRs reported on the
	// github_pr_watcher_unreviewed_prs gauge and records scannedAt on the
	// last-successful-scan timestamp gauge. The slice is the complete result
	// of one scan, so an empty slice clears the gauge.
	SetUnreviewedPRs(prs []UnreviewedPR, scannedAt libtime.DateTime)
	// IncUnreviewedRetry increments the retry counter with the given repo label.
	// repo: `owner/repo`
	IncUnreviewedRetry(repo string)
	// IncEscalation increments the auto-merge refusal escalation counter.
	// class: "untrusted-author", "trust-check-error", "enable-auto-merge-error",
	// "checks-not-green", "review-request-changes".
	// result: "published", "duplicate", "error".
	IncEscalation(class, result string)
}

Metrics exposes counters for observable watcher behaviour.

func NewMetrics

func NewMetrics() Metrics

NewMetrics returns a Metrics implementation backed by Prometheus counters.

type OverrideLedger added in v0.18.1

type OverrideLedger interface {
	// Record notes that an override was published for pr. A failure is logged,
	// never returned: the override command has already been sent, and a
	// bookkeeping error must not turn that into a retry.
	Record(ctx context.Context, pr RetryGuardPR, taskID string)
	// Suppressed reports whether a review for pr's head SHA must not be
	// published because a fresh override owns it. A ledger that cannot be read
	// fails OPEN — the pre-change behaviour is to publish the review, and losing
	// a review is worse than a duplicate.
	Suppressed(ctx context.Context, pr RetryGuardPR) bool
	// SuppressedTx is the same check inside a caller-held transaction. The
	// command executor runs inside the consumer's already-held transaction and
	// memDB's mutex is not re-entrant, so it cannot open one of its own.
	SuppressedTx(ctx context.Context, tx libkv.Tx, pr RetryGuardPR) (bool, error)
}

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

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

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

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

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

func NewOverrideLedger added in v0.18.1

func NewOverrideLedger(
	db libkv.DB,
	currentDateTime libtime.CurrentDateTimeGetter,
) OverrideLedger

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

type PRDetails

type PRDetails struct {
	// HeadSHA is the commit hash of the PR's head branch. Used for force-push
	// detection and as the `ref` the agent checks out for review.
	HeadSHA string

	// CloneURL is the HTTPS clone URL of the base repo (e.g.
	// `https://github.com/owner/repo.git`). Used as the `clone_url` the
	// agent's execution phase passes to git clone. It must name the base
	// repo, not the head: on a fork PR the head repo is the contributor's
	// fork, which carries no PR of that number and cannot be resolved by a
	// reader holding only the PR number.
	CloneURL string

	// BaseRef is the base branch name (e.g. `master`, `main`). Used as
	// the `base_ref` the execution phase diffs against.
	BaseRef string

	// HeadRef is the head branch name (e.g. `fix/update-go-c0cf2ac`). Used to
	// recognise the update-go agent's dep-bump PRs, which it names
	// `fix/update-go-<sha>` — see isSupersededDepBump.
	HeadRef string

	// HeadRepoFullName is the head repository's `owner/repo` full name. Empty
	// when GitHub no longer reports a head repo (a deleted fork). It feeds the
	// same-repo trust check, so an empty value denies.
	HeadRepoFullName string

	// BaseRepoFullName is the base repository's `owner/repo` full name. Empty
	// when unknown. It feeds the same-repo trust check, so an empty value
	// denies.
	BaseRepoFullName string

	// AuthorLogin is the GitHub author login; empty for deleted accounts.
	AuthorLogin string

	// Title is the PR title.
	Title string

	// IsDraft indicates whether the PR is a draft.
	IsDraft bool

	// UpdatedAt is the PR last-updated timestamp; required for AgeFilter.
	UpdatedAt libtime.DateTime

	// Labels holds the PR's label names (e.g. `override-review`). Used to
	// route a labeled PR to the override task type.
	Labels []string

	// Additions is the PR's added-line count (diff size). Used to park
	// oversized PRs at human_review before spawning a review pod whose
	// prompt would overflow the reviewer's context window.
	Additions int

	// ChangedFiles is the number of files the PR touches. Used alongside
	// Additions for the same oversized-PR park decision.
	ChangedFiles int

	// MergeableState is GitHub's REST merge-state for the PR. Used by
	// tryUpdateBranch to decide whether the head branch is stale against its
	// base.
	//
	// `behind` means the base moved with no conflict; that is the case
	// update-branch resolves. `dirty` means the merge commit cannot be created
	// (a real conflict), which update-branch does NOT fix — it merges base
	// into head, so a conflicting merge fails. GraphQL exposes the same
	// concept as `mergeStateStatus` with upper-cased values.
	MergeableState MergeState
}

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

type PRFile added in v0.7.0

type PRFile struct {
	Filename string
	Patch    string
	// Additions is the file's added-line count, as reported by the GitHub
	// files API. Used to compute how many additions a repo's `.reviewignore`
	// excludes from the size gate, so the park decision counts only
	// reviewable content.
	Additions int
}

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

type PublishRecorder added in v0.17.0

type PublishRecorder interface {
	RecordPublish(ctx context.Context, pr RetryGuardPR, taskID string)
}

PublishRecorder records that a review task was published for one head SHA, so the guard's Check can suppress a duplicate forced retry.

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

func NewPublishRecorder added in v0.17.0

func NewPublishRecorder(db libkv.DB, guard RetryGuard) PublishRecorder

NewPublishRecorder returns a PublishRecorder that writes into the same ledger Check reads, one transaction per record.

type PublishTracker added in v0.23.2

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

PublishTracker records the last successful review-task publish, so the watcher can tell an idle publish path from a stopped one.

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

func NewPublishTracker added in v0.23.2

func NewPublishTracker(currentDateTime libtime.CurrentDateTimeGetter) *PublishTracker

NewPublishTracker returns a PublishTracker reading the injected clock.

func (*PublishTracker) Record added in v0.23.2

func (t *PublishTracker) Record()

Record notes one successful publish. Nil-tolerant, so a publisher or watcher built without a tracker behaves exactly as before.

func (*PublishTracker) Snapshot added in v0.23.2

func (t *PublishTracker) Snapshot() (int64, libtime.DateTime)

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

type PullRequest

type PullRequest struct {
	GlobalID    int64
	Number      int
	Owner       string
	Repo        string
	Title       string
	HTMLURL     string
	HeadSHA     string
	AuthorLogin string
	IsDraft     bool
	UpdatedAt   libtime.DateTime
	// Labels holds the PR's label names (e.g. `override-review`). Populated
	// from the Search API's issue labels.
	Labels []string
}

PullRequest holds the fields the watcher needs from a GitHub PR.

type RetryGuard added in v0.17.0

type RetryGuard interface {
	// Check decides whether a forced re-review may be published. It never
	// writes to the ledger; only Record does.
	Check(ctx context.Context, tx libkv.Tx, pr RetryGuardPR) (RetryGuardDecision, error)
	// Record stores that a review was published for pr, so a later Check
	// suppresses a duplicate while it is fresh.
	Record(ctx context.Context, tx libkv.Tx, pr RetryGuardPR, taskID string) error
	// ClearByTaskID scans the in-memory ledger for the record whose stored task
	// identifier equals taskID, deletes it if present, and logs the fixed clear
	// line at default verbosity. It reports whether a record was deleted; an
	// unknown identifier is a silent no-op.
	ClearByTaskID(
		ctx context.Context,
		tx libkv.Tx,
		taskID string,
		outcome string,
	) (bool, error)
}

RetryGuard suppresses a forced re-review whose review for the same head SHA is still in flight.

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

func NewRetryGuard added in v0.17.0

func NewRetryGuard(
	ghClient GitHubClient,
	metrics Metrics,
	reviewerLogins []string,
	currentDateTime libtime.CurrentDateTimeGetter,
) RetryGuard

NewRetryGuard returns a RetryGuard backed by the in-process ledger.

type RetryGuardAction added in v0.17.0

type RetryGuardAction string

RetryGuardAction is what the guard wants the caller to do.

const (
	RetryGuardActionCreate RetryGuardAction = "create"
	RetryGuardActionSkip   RetryGuardAction = "skip"
)

type RetryGuardDecision added in v0.17.0

type RetryGuardDecision struct {
	Action         RetryGuardAction
	Reason         RetryGuardReason
	ExistingTaskID string
	RecordAge      libtime.Duration
}

RetryGuardDecision is the guard's verdict for one forced re-review.

type RetryGuardPR added in v0.17.0

type RetryGuardPR struct {
	Owner   string
	Repo    string
	Number  int
	HeadSHA string
}

RetryGuardPR identifies one publishable review target.

type RetryGuardReason added in v0.17.0

type RetryGuardReason string

RetryGuardReason is why the guard chose its action.

const (
	RetryGuardReasonCreate                     RetryGuardReason = "create"
	RetryGuardReasonCreateForceOverrodeVerdict RetryGuardReason = "create_force_overrode_verdict"
	RetryGuardReasonCreateStaleRecordIgnored   RetryGuardReason = "create_stale_record_ignored"
	RetryGuardReasonSkipInflight               RetryGuardReason = "skip_inflight"
)

type Review added in v0.14.0

type Review struct {
	// ID is the review's GitHub id. Required to dismiss it; zero when the API
	// reported none.
	ID int64
	// AuthorLogin is the reviewer's GitHub login; empty for a deleted account.
	AuthorLogin string
	// CommitID is the head SHA the review was posted against.
	CommitID string
	// Body is the review's body text. The do-not-merge gate reads its own
	// marker here so it can tell its reviews from the bot's genuine verdicts
	// and never dismiss a real finding.
	Body string
	// State is the review's verdict. Only a CHANGES_REQUESTED review on the
	// current head SHA blocks the merge and escalates.
	State ReviewState
}

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

type ReviewEvent added in v0.27.0

type ReviewEvent string

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

const (
	// ReviewEventApprove submits an approving review.
	ReviewEventApprove ReviewEvent = "APPROVE"
	// ReviewEventRequestChanges submits a blocking review. The resulting
	// ReviewState is CHANGES_REQUESTED, not this value.
	ReviewEventRequestChanges ReviewEvent = "REQUEST_CHANGES"
	// ReviewEventComment submits a comment-only review.
	ReviewEventComment ReviewEvent = "COMMENT"
)

type ReviewState added in v0.23.0

type ReviewState string

ReviewState is a GitHub review verdict, typed so a state-name typo is caught by the compiler rather than silently never matching.

const (
	// ReviewStateApproved clears a previous CHANGES_REQUESTED for that reviewer.
	ReviewStateApproved ReviewState = "APPROVED"
	// ReviewStateChangesRequested blocks the merge until the same reviewer
	// approves or the review is dismissed — a later push does not clear it.
	ReviewStateChangesRequested ReviewState = "CHANGES_REQUESTED"
	// ReviewStateCommented is a comment-only review; it does not change the
	// reviewer's standing verdict.
	ReviewStateCommented ReviewState = "COMMENTED"
	// ReviewStateDismissed removes the reviewer's standing verdict.
	ReviewStateDismissed ReviewState = "DISMISSED"
	// ReviewStatePending is a review not yet submitted.
	ReviewStatePending ReviewState = "PENDING"
)

type SearchResult

type SearchResult struct {
	PullRequests  []PullRequest
	HasNextPage   bool
	NextPage      int
	RateRemaining int
	RateResetAt   libtime.DateTime
}

SearchResult is the result of a single paginated search call.

type TaskConfig

type TaskConfig struct {
	Stage       string
	MaxSlugLen  int
	MaxTitleLen int
	TaskSuffix  string
	// TargetVault routes the CreateTaskCommand to a specific vault controller
	// (matched verbatim against the controller's VAULT_NAME). Empty leaves
	// TargetVault unset, so the controller's legacy default-vault fallback
	// applies — preserving pre-TARGET_VAULT behaviour.
	TargetVault string
	// MaxAdditions parks PRs with more than this many added lines at
	// human_review instead of spawning a review pod. 0 disables the check.
	MaxAdditions int
	// MaxChangedFiles parks PRs touching more than this many files at
	// human_review instead of spawning a review pod. 0 disables the check.
	MaxChangedFiles int
}

TaskConfig groups the per-task publishing configuration.

type TaskPublisher

type TaskPublisher interface {
	PublishCreate(ctx context.Context, pr PullRequest, taskIDStr string, details PRDetails) bool
	// PublishRedrive publishes a review task for a record that has outlived the
	// retry guard's staleness bound with no verdict at its head SHA. It differs
	// from PublishCreate in exactly two ways, both required for the command to
	// do anything:
	//
	//   - The title carries a `retry-<token>` segment. The agent controller
	//     dedups on the TITLE PATH, not on task_identifier, so a salted id with
	//     an unchanged title is rejected with ErrTaskAlreadyExists and re-runs
	//     nothing — see computePRTitle.
	//   - The publish is NOT recorded in the retry guard's ledger. Recording it
	//     would keep the ledger permanently fresh while re-drives continue, and
	//     an operator's forced /trigger on the same PR would then be suppressed
	//     as in-flight for an hour after every re-drive, which is the manual
	//     lever's whole purpose gone.
	PublishRedrive(ctx context.Context, pr PullRequest, taskIDStr string, details PRDetails) bool
	// PublishOverride publishes a `pr-override` task for a labeled PR. It is
	// trusted-authors-only. Returns (handled, emitted):
	//   - handled=true: this is a trusted-author override case; the caller must
	//     NOT emit a review task for this SHA (even when the send failed —
	//     retry on the next poll). This preserves the override-only invariant
	//     that prevents an APPROVE-vs-CHANGES_REQUESTED race.
	//   - emitted=true: the override task was actually sent; the caller records
	//     it in the cursor so the override fires at most once per head SHA.
	//   - untrusted author (or trust-check error) → (false, false): the caller
	//     falls through to the normal review path (which routes untrusted →
	//     human_review).
	PublishOverride(
		ctx context.Context,
		pr PullRequest,
		taskIDStr string,
		details PRDetails,
	) (handled, emitted bool)
	// PublishMechanicalOverride publishes the mechanical `pr-override` task for
	// a qualifying trivial bot bump. The caller (the watcher's mechanical gate)
	// has already evaluated the author list, trust, the repo's two opt-in flags
	// and the file classifier, so this method performs no trust check of its
	// own. Returns true when the command was sent; false when the send failed,
	// in which case the caller records nothing so the emission is retried on
	// the next poll.
	PublishMechanicalOverride(
		ctx context.Context,
		pr PullRequest,
		taskIDStr string,
		details PRDetails,
	) bool
}

TaskPublisher publishes create-task commands for a given PR + details pair. Returns true on successful publish, false on trust check failure or send failure.

func NewTaskPublisher

func NewTaskPublisher(
	createSender task.CreateCommandSender,
	trustDecision trust.Trust,
	metrics Metrics,
	cfg TaskConfig,
	ghClient GitHubClient,
	opts ...TaskPublisherOption,
) TaskPublisher

NewTaskPublisher returns a TaskPublisher that performs trust evaluation then publishes a CreateTaskCommand via the given CreateCommandSender.

type TaskPublisherOption added in v0.17.0

type TaskPublisherOption func(*taskPublisher)

TaskPublisherOption configures optional TaskPublisher behaviour.

func WithOverrideLedger added in v0.18.1

func WithOverrideLedger(ledger OverrideLedger) TaskPublisherOption

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

func WithPublishRecorder added in v0.17.0

func WithPublishRecorder(recorder PublishRecorder) TaskPublisherOption

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

func WithPublishTracker added in v0.23.2

func WithPublishTracker(tracker *PublishTracker) TaskPublisherOption

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

type UnreviewedConfig added in v0.14.0

type UnreviewedConfig struct {
	// Logins are the GitHub logins whose reviews count as "the reviewer
	// looked at this PR". Matching ignores casing and a trailing `[bot]`
	// suffix, so `octopus-pr-reviewer` matches the App login
	// `octopus-pr-reviewer[bot]`. An empty list disables the scan entirely.
	Logins []string
	// Threshold is how long a publishable PR must have gone without a
	// reviewer-bot review on its current head SHA before it is reported, and
	// how long to wait between retries of an unreviewed PR.
	Threshold libtime.Duration
	// RetryMax is the most review tasks the scan re-publishes for one
	// (PR, head SHA) pair before it gives up and marks the PR exhausted. 0
	// disables retrying — every unreviewed PR is reported as exhausted.
	RetryMax int
}

UnreviewedConfig configures the unreviewed-PR scan.

func ParseUnreviewedConfig added in v0.14.0

func ParseUnreviewedConfig(
	ctx context.Context,
	rawLogins, rawThreshold string,
	retryMax int,
) (UnreviewedConfig, error)

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

type UnreviewedPR added in v0.14.0

type UnreviewedPR struct {
	// Repo is the `owner/repo` pair, matching the gauge's repo label.
	Repo string
	// Number is the pull-request number, rendered as the gauge's pr label.
	Number int
	// RetriesExhausted marks a PR whose bounded retry budget is spent. The
	// scan keeps re-driving such a PR once per stale hour, so the label means
	// "the budget is gone", not "nothing is being tried", and it stays true
	// through those re-drives rather than flapping every threshold. Rendered
	// as the gauge's retries_exhausted label.
	RetriesExhausted bool
}

UnreviewedPR identifies one open pull request reported as unreviewed.

type UnreviewedScanner added in v0.14.0

type UnreviewedScanner interface {
	Scan(ctx context.Context)
	// LastCandidates returns how many PRs the last complete scan found still
	// owed a review. It is the population the watcher's silence line needs:
	// the raw search count is not it, because a PR sitting at the cursor
	// boundary is listed on every cycle and legitimately produces nothing.
	// Zero before the first complete scan and after a scan that aborted.
	LastCandidates() int
}

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

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

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

func NewUnreviewedScanner added in v0.14.0

func NewUnreviewedScanner(
	ghClient GitHubClient,
	publisher TaskPublisher,
	dispatchLedger DispatchLedger,
	metrics Metrics,
	currentDateTime libtime.CurrentDateTimeGetter,
	scope string,
	taskCreationFilter filter.TaskCreationFilter,
	trustDecision trust.Trust,
	overrideLabel string,
	maxAdditions, maxChangedFiles int,
	cfg UnreviewedConfig,
) UnreviewedScanner

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

type Watcher

type Watcher interface {
	Poll(ctx context.Context) error
}

Watcher polls GitHub and publishes task commands to Kafka.

func NewWatcher

func NewWatcher(
	ghClient GitHubClient,
	publisher TaskPublisher,
	metrics Metrics,
	cursorPath string,
	startTime libtime.DateTime,
	scope string,
	taskCreationFilter filter.TaskCreationFilter,
	sideEffectFilter filter.TaskCreationFilter,
	overrideLabel string,
	autoMergeLabel string,
	trivialAutoMergeEnabled bool,
	mechanicalOverrideAuthors []string,
	trustDecision trust.Trust,
	unreviewedScanner UnreviewedScanner,
	coalescer coalesce.Coalescer,
	currentDateTime libtime.CurrentDateTimeGetter,
	opts ...WatcherOption,
) Watcher

NewWatcher returns a Watcher that polls GitHub and publishes commands.

type WatcherOption added in v0.23.0

type WatcherOption func(*watcher)

WatcherOption configures optional watcher dependencies without widening the positional constructor every caller (and every test) has to restate.

func WithEscalator added in v0.23.0

func WithEscalator(escalator escalate.Escalator) WatcherOption

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

func WithWatcherPublishTracker added in v0.23.2

func WithWatcherPublishTracker(tracker *PublishTracker) WatcherOption

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

Directories

Path Synopsis
Package coalesce bounds how many review records a burst of pushes to one pull request can create.
Package coalesce bounds how many review records a burst of pushes to one pull request can create.
Package command defines the TriggerPRReviewCommand payload and its Kafka sender for the github-pr watcher's request topic.
Package command defines the TriggerPRReviewCommand payload and its Kafka sender for the github-pr watcher's request topic.
Package escalate routes auto-merge refusals to the operator through the shared generic notification system, so a refused PR is never held in silence.
Package escalate routes auto-merge refusals to the operator through the shared generic notification system, so a refused PR is never held in silence.
Package factory wires concrete dependencies for the maintainer-watcher-github-pr binary.
Package factory wires concrete dependencies for the maintainer-watcher-github-pr binary.
Package filter implements the TaskCreationFilter chain.
Package filter implements the TaskCreationFilter chain.
Package reviewignore parses a repo's root `.reviewignore` file — gitignore syntax — into a matcher the size gate uses to exclude non-reviewable paths (vendored deps, generated mocks, dark-factory pipeline state) from the added-line and changed-file counts that decide whether a PR parks at human_review.
Package reviewignore parses a repo's root `.reviewignore` file — gitignore syntax — into a matcher the size gate uses to exclude non-reviewable paths (vendored deps, generated mocks, dark-factory pipeline state) from the added-line and changed-file counts that decide whether a PR parks at human_review.
Package trust provides the boolean-combinator trust-decision framework for the maintainer-watcher-github-pr.
Package trust provides the boolean-combinator trust-decision framework for the maintainer-watcher-github-pr.

Jump to

Keyboard shortcuts

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