github

package
v0.0.0-...-552835e Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: Apache-2.0 Imports: 39 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package github is bex-api's GitHub App integration (docs/ADR026-github-integration.md): a small client that signs the app JWT, mints short-lived installation tokens, and lists an installation's repositories — plus the workspace-connection service verbs over the control-plane store. The operator never imports this; bex-api mints tokens and writes them into a k8s Secret the build Job consumes.

Index

Constants

View Source
const (
	MergeMethodMerge  = "merge"
	MergeMethodSquash = "squash"
	MergeMethodRebase = "rebase"
)

The merge methods, in the order GitHub's settings and merge button list them; a merge that names none takes the first one the repository allows.

View Source
const (
	AsyncMergeMerged   = "merged"
	AsyncMergeEnqueued = "enqueued"
	AsyncMergePending  = "pending"
)

The results of an asynchronous merge (PUT …/pulls/{n}/merge-async and its GET …/merge-async/{uuid}) as GitHub names them.

View Source
const (
	CodeGitHubRateLimited  = "GITHUB_RATE_LIMITED"
	CodeGitHubUnavailable  = "GITHUB_UNAVAILABLE"
	CodeGitHubAccessDenied = "GITHUB_ACCESS_DENIED"
)

Codes for a repository check GitHub refused or could not answer (w4/528).

View Source
const (
	AsyncMergeWait = 15 * time.Second
)

AsyncMergeWait bounds how long MergePullRequestAsync waits for GitHub to finish an asynchronous merge, polling its result every asyncMergePause, before it answers that the merge is still pending (w10/053, ADR090 D3). The verb it serves answers within bex-api's 30-second write timeout, which the reads and calls before the merge share.

View Source
const CodeBlueprintHostUnsupported = "BLUEPRINT_HOST_UNSUPPORTED"

CodeBlueprintHostUnsupported refuses a Blueprint repository that bex does not read: one on a host Render reads no Blueprint from, or a URL form its host is not read in. Its message names the host from the caller's own URL.

View Source
const ReactionEyes = "eyes"

ReactionEyes is the reaction that acknowledges a `/bex` comment.

Variables

View Source
var (
	// ErrNotFastForward means from's head does not descend from branch's: the
	// branch moved on, so a merge into from has to come first.
	ErrNotFastForward = errors.New("github: the branch update is not a fast-forward")
	// ErrBranchUpdateRefused means GitHub refused a fast-forward itself: a
	// branch protection rule or ruleset forbids the App to update the branch.
	ErrBranchUpdateRefused = errors.New("github: a rule on the branch refused the update")
)

Refusals of FastForwardBranch.

View Source
var (
	// ErrAutoMergeNotAllowed is a repository whose "Allow auto-merge"
	// setting is off: GitHub answers "Auto merge is not allowed for this
	// repository", and bex reads allow_auto_merge false before asking.
	ErrAutoMergeNotAllowed = errors.New("github: the repository does not allow auto-merge")
	// ErrMergeableNow is a pull request GitHub would merge now, which it
	// refuses to arm ("Pull request is in clean status"); mergeStateStatus
	// lags behind checks that just settled, so the read alone misses it.
	ErrMergeableNow = errors.New("github: the pull request is mergeable now, so auto-merge cannot be armed")
)

The refusals of arming auto-merge, in GitHub's words or bex's pre-check.

View Source
var (
	// ErrHeadBranchNotFound means the head branch does not exist on GitHub —
	// the agent has not pushed it.
	ErrHeadBranchNotFound = errors.New("github: head branch does not exist")
	// ErrHeadNotAhead means the head branch has no commits that base lacks.
	ErrHeadNotAhead = errors.New("github: head branch is not ahead of base")
	// ErrDraftNotSupported means GitHub refused to open a draft because the
	// repository's plan has none (a private repository on GitHub Free or Pro).
	ErrDraftNotSupported = errors.New("github: draft pull requests are not supported in this repository")
)

Typed refusals of SyncPullRequest: the agent's PR request is refused, not failed, when there is nothing reviewable on its branch yet (ADR090), or when it asked for a draft the repository cannot have.

View Source
var (
	ErrBranchNotFound         = errors.New("blueprint branch not found")
	ErrRepoNotFoundOrNoAccess = errors.New("blueprint repository not found or not accessible")
)

ErrBranchNotFound and ErrRepoNotFoundOrNoAccess name which half of a blueprint commit lookup failed. GitHub answers 404 for a missing branch and for a repository the installation cannot see, and the status alone cannot tell them apart — so callers that want to say "check the branch name" rather than "check the repository" need this, and guessing from message text is not a contract (w2/m97 t001).

The two are distinguished by the upstream response BODY, which stays internal: it is read here to pick a sentinel and is never interpolated into any error that reaches a client (w6/005). A private repository and a missing repository are deliberately one sentinel — GitHub makes them indistinguishable on purpose, and so must bex.

View Source
var ErrPermissionNotGranted = errors.New("github: the installation has not granted the permissions this call needs")

ErrPermissionNotGranted refuses a mark-ready or merge whose token the installation cannot mint: it has not granted Contents or Pull requests write (GitHub answers the mint 422), which only an owner of the account can change.

MergeMethods is every method GitHub's merge endpoint accepts, in order.

Functions

func APIErrorMessage

func APIErrorMessage(err error) string

APIErrorMessage is GitHub's own explanation of a refusal: the "message" of its error body (or of its "details", as an asynchronous merge's answer carries it), followed by each entry of its "errors" list, or the message of an asynchronous merge it failed (w10/053), on one line and bounded. It is "" for an error that is neither or carries no message. Callers relay it to the agent whose own pull request GitHub refused (w10/m538), which is why Error() alone never carries it (w6/005).

func BexCommand

func BexCommand(body string) (task string, ok bool)

BexCommand reads a `/bex` comment: the text after the command word, which must open the comment (in any case) and stand alone. ok is false for any other comment. The webhook's prefilter and the PR intake share it.

func BlueprintHost

func BlueprintHost(repoURL string) string

BlueprintHost names the host a failed Blueprint read's wording names (w8/346): "" for a repository the GitHub API reads, whose wording names bex's GitHub app, else the host its URL names, read or refused.

func RefuseBlueprintHost

func RefuseBlueprintHost(repoURL string) error

RefuseBlueprintHost is the refusal a Blueprint read of repoURL gives before any request (CodeBlueprintHostUnsupported), or nil for a repository bex reads. A default-branch lookup asks it first, so a host bex reads no Blueprint from is refused by name with no branch too, never probed (w8/346).

Types

type APIClient

type APIClient interface {
	InstallURL() string
	GetInstallation(ctx context.Context, installationID int64) (Installation, error)
	ListRepos(ctx context.Context, installationID int64) ([]Repo, error)
	ListBranches(ctx context.Context, installationID int64, owner, repo string) ([]string, error)
	ListRepoTree(ctx context.Context, token, owner, repo, path, ref string) ([]RepoTreeEntry, error)
	MintInstallationToken(ctx context.Context, installationID int64) (InstallationToken, error)
	LookupRepo(ctx context.Context, token, owner, repo string) (Repo, bool, error)
	GetCommit(ctx context.Context, token, owner, repo, ref string) (Commit, error)
	GetFileContents(ctx context.Context, token, owner, repo, path, ref string) (FileContents, error)
	GetRepoCommitSHA(ctx context.Context, token, owner, repo, branch string) (string, error)
	MintChecksToken(ctx context.Context, installationID int64) (InstallationToken, bool, error)
	ListCheckRuns(ctx context.Context, token, owner, repo, sha string) ([]CheckRun, error)
}

APIClient is the GitHub REST surface the Service uses — *Client in production, a fake in tests. nil => the GitHub App is unconfigured (BEX_GITHUB_APP_* unset) and every verb reports core.ErrGitHubUnavailable.

type APIError

type APIError struct {
	Status int
	Body   string
	// RateLimited is GitHub refusing for budget, not permission: a 429, or a
	// 403 that carries x-ratelimit-remaining: 0 or Retry-After (w4/528).
	RateLimited bool
	// RetryAfter is GitHub's Retry-After in seconds, or the wait until
	// x-ratelimit-reset; 0 when it gave neither.
	RetryAfter int
}

APIError is a non-2xx GitHub response. Callers map it to a clean bex error (never a raw 500) so a GitHub outage surfaces as "GitHub said N", not a panic.

func (*APIError) Error

func (e *APIError) Error() string

type AsyncMergeFailedError

type AsyncMergeFailedError struct {
	Message string
}

AsyncMergeFailedError is an asynchronous merge GitHub failed, at once (its basic checks: closed, a draft) or once it ran (branch protection, rules, a conflict, a head that moved). APIErrorMessage reads Message, GitHub's own words; Error() never carries them (w6/005).

func (*AsyncMergeFailedError) Error

func (e *AsyncMergeFailedError) Error() string

type AsyncMergeResult

type AsyncMergeResult struct {
	Status string
	SHA    string
	Method string
}

AsyncMergeResult is what an asynchronous merge came to within AsyncMergeWait: Status AsyncMergeMerged with SHA, the commit it created on the base branch, AsyncMergeEnqueued when the pull request joined the merge queue its base requires, or AsyncMergePending when GitHub accepted it and is still landing it. Method is the method it asked for.

type CheckRun

type CheckRun struct {
	Name       string `json:"name"`
	HeadSHA    string `json:"head_sha"`
	Status     string `json:"status"`
	Conclusion string `json:"conclusion"`
	URL        string `json:"html_url"`
	Output     struct {
		Title   string `json:"title"`
		Summary string `json:"summary"`
	} `json:"output"`
}

CheckRun is one GitHub check run on a commit: status is queued, in_progress or completed; conclusion is set once completed (success, neutral, skipped, failure, cancelled, timed_out, action_required, stale).

type Claim

type Claim struct {
	ClaimURL string `json:"claimUrl"`
}

Claim is StartClaim's result: the GitHub OAuth authorize URL that starts the ADR078 §3a claim flow for an already-installed account.

type ClaimCandidate

type ClaimCandidate struct {
	InstallationID int64  `json:"installationId"`
	AccountLogin   string `json:"accountLogin"`
	// Connected reports that this installation is already bound to the
	// selection's workspace (ADR078 §3b): the chooser marks it rather than
	// offering it as a new bind. Computed on read from the workspace's own
	// bindings; it grants nothing, and selecting it stays idempotent.
	Connected bool `json:"connected"`
}

ClaimCandidate is one option the picker renders.

type ClaimOptions

type ClaimOptions struct {
	// InstallationID (0 = unspecified) is the start-time selector (ADR078 §3a):
	// it NARROWS the candidate set the callback proves. It is not trusted as an
	// input — an installation the authorizing GitHub user does not administer
	// never becomes a candidate no matter what is named here.
	InstallationID int64
	// Chooser is the single connect entry (ADR078 §3b, w1/m526): the callback
	// always hands the proved set to the account chooser — zero, one or several
	// candidates — and never binds on its own. Off, a sole candidate binds as
	// §3a describes, so existing claimGit clients are unchanged.
	Chooser bool
}

ClaimOptions are StartClaim's optional start-time choices. Both ride the server-side transaction row, never the signed state (w1/m67 F3).

type ClaimSelection

type ClaimSelection struct {
	ID         string           `json:"id"`
	Candidates []ClaimCandidate `json:"candidates"`
	ExpiresAt  string           `json:"expiresAt"`
}

ClaimSelection is the picker's view of an outstanding ambiguous claim.

type Client

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

Client talks to the GitHub REST API as a GitHub App. It is safe for concurrent use.

func NewClient

func NewClient(cfg Config) (*Client, error)

NewClient parses the config (numeric app id, PEM private key) and returns a ready client. It errors if any field is missing or malformed.

func (*Client) AddCommentReaction

func (c *Client) AddCommentReaction(ctx context.Context, installationID int64, owner, repo string, commentID int64, inline bool, content string) error

AddCommentReaction reacts with content to a pull request comment: an issue comment, or an inline review comment when inline is set. GitHub answers 200 instead of 201 when the App already reacted, which is not an error.

func (*Client) AuthorizeURL

func (c *Client) AuthorizeURL() string

AuthorizeURL is the GitHub OAuth user-authorization endpoint for this app — the one GitHub flow that always carries `state` through, which is what makes the ADR078 §3a claim flow possible for already-installed accounts (the install URL's Configure path strips state). The caller appends &state=<signed token>.

func (*Client) BranchCheckHistory

func (c *Client) BranchCheckHistory(ctx context.Context, installationID int64, owner, repo, branch string) iter.Seq2[[]CheckRun, error]

BranchCheckHistory yields the latest check runs of branch's newest commits, one commit at a time and newest first (CheckRun.HeadSHA is the commit), so a reader can look past a head whose check is still running, or that the check did not run on (w6/m399). It follows first parents, so the commits of a merged side branch, whose runs were a pull request's, are not read, and it stops after maxBranchHistory commits or when the reader does. A failed read yields its error and ends the walk. One token, checks and contents read, serves every request.

func (*Client) BranchHead

func (c *Client) BranchHead(ctx context.Context, installationID int64, owner, repo, branch string) (string, error)

BranchHead returns branch's head commit on owner/repo, read with a contents:read token. ErrHeadBranchNotFound means the branch does not exist.

func (*Client) BranchProtected

func (c *Client) BranchProtected(ctx context.Context, installationID int64, owner, repo, branch string) (bool, error)

BranchProtected reports whether GitHub marks branch of owner/repo protected.

func (*Client) ClaimableInstallations

func (c *Client) ClaimableInstallations(ctx context.Context, code string) ([]Installation, error)

ClaimableInstallations resolves the ADR078 §3a claim callback's missing installation id server-side: it exchanges the OAuth `code` for a user token, lists THIS app's installations the authorizing user can reach (GET /user/installations — the endpoint is app-scoped by the user-to-server token), and keeps only those the user ADMINISTERS — the same proof VerifyInstallationAdmin applies (exact personal-account owner, or active org membership with role admin). Reachability alone (an org member who can see the installation) is never an administration proof. A declined code exchange yields zero candidates (the flow must be restarted), not an error.

func (*Client) CollaboratorPermission

func (c *Client) CollaboratorPermission(ctx context.Context, installationID int64, owner, repo, login string) (string, error)

CollaboratorPermission returns login's permission on owner/repo as GitHub's legacy four levels: admin, write (which maintain maps to), read or none. A custom repository role maps onto them too, which role_name would not. A user who is not a collaborator is none.

func (*Client) CreateIssueComment

func (c *Client) CreateIssueComment(ctx context.Context, installationID int64, owner, repo string, number int, body string) (string, error)

CreateIssueComment posts body on issue or pull request number and returns the comment's URL. GitHub accepts pull_requests:write for a pull request.

func (*Client) DisablePullRequestAutoMerge

func (c *Client) DisablePullRequestAutoMerge(ctx context.Context, installationID int64, repo, nodeID string, state MergeState) error

DisablePullRequestAutoMerge stops GitHub merging the pull request whose node id is nodeID later, as state (its merge state) has it: it takes it out of the merge queue when queued (dequeuePullRequest), disarms the stack's auto-merge request covering it, for every pull request that request covers (disablePullRequestAutoMerge with includeStack, w10/048), and otherwise disables its own auto-merge, as Devin Review's merge button and gh pr merge --disable-auto do. A refusal is an *APIError.

func (*Client) EnablePullRequestAutoMerge

func (c *Client) EnablePullRequestAutoMerge(ctx context.Context, installationID int64, owner, repo, nodeID string, opts MergeOptions) (string, error)

EnablePullRequestAutoMerge arms GitHub auto-merge on the pull request whose node id is nodeID, in owner/repo, on a base branch without a merge queue: GitHub merges it once its required reviews and checks pass, and with opts.IncludeStack every unmerged pull request below it in its stack too. It is pinned to opts.SHA (expectedHeadOid) and uses the method rule of MergePullRequest, with the commit text when given. A repository whose allow_auto_merge is false is ErrAutoMergeNotAllowed before any mutation; GitHub's own refusals are ErrAutoMergeNotAllowed, ErrMergeableNow or an *APIError. It answers the method armed.

func (*Client) EnqueuePullRequest

func (c *Client) EnqueuePullRequest(ctx context.Context, installationID int64, repo, nodeID, headSHA string) error

EnqueuePullRequest takes the pull request whose node id is nodeID into its base branch's merge queue, pinned to headSHA, as gh pr merge does on a queue branch and GitHub's "Merge when ready" button: enablePullRequestAutoMerge adds a ready pull request to the queue and one whose checks are pending once they pass. The queue sets the method and the commit text, so none is sent. Where GitHub refuses that because the repository does not allow auto-merge or the pull request is ready now, it is enqueued directly (enqueuePullRequest), pinned the same way. A refusal is an *APIError.

func (*Client) FastForwardBranch

func (c *Client) FastForwardBranch(ctx context.Context, installationID int64, owner, repo, branch, from string) (string, error)

FastForwardBranch moves branch of owner/repo to from's head commit and returns that commit. It compares the two first, so only a real fast-forward is attempted (a branch already there is left as it is), and it sends force:false, so GitHub refuses anything else too; history on branch is never rewritten. ErrHeadBranchNotFound means from does not exist on GitHub. One repository write token (contents and, where the installation grants it, workflows: the session's commits may change a workflow file, as a push of its own branch may) serves every call.

func (*Client) GetCommit

func (c *Client) GetCommit(ctx context.Context, token, owner, repo, ref string) (Commit, error)

GetCommit resolves ref (a branch name, tag, or SHA) to the exact commit it points at (GET /repos/{owner}/{repo}/commits/{ref}). An unknown ref or an out-of-grant repo returns an *APIError (404/422) — callers treat those as "unresolvable", not a failure.

func (*Client) GetFileContents

func (c *Client) GetFileContents(ctx context.Context, token, owner, repo, path, ref string) (FileContents, error)

func (*Client) GetInstallation

func (c *Client) GetInstallation(ctx context.Context, installationID int64) (Installation, error)

GetInstallation fetches one installation by id (GET /app/installations/{id}), authenticated as the app. A non-existent or inaccessible id returns an *APIError (typically 404) — the authenticity check for the connect callback.

func (*Client) GetPullRequest

func (c *Client) GetPullRequest(ctx context.Context, installationID int64, owner, repo string, number int) (PullRequestDetail, error)

GetPullRequest reads pull request number of owner/repo.

func (*Client) GetRepoCommitSHA

func (c *Client) GetRepoCommitSHA(ctx context.Context, token, owner, repo, branch string) (string, error)

GetRepoCommitSHA resolves the HEAD commit SHA for a branch using the branch info endpoint. Used by the blueprint fetcher to stamp the commitID on each sync run when we already hold the file contents.

func (*Client) GetReview

func (c *Client) GetReview(ctx context.Context, installationID int64, owner, repo string, number int, reviewID int64) (Review, error)

GetReview reads review reviewID of pull request number.

func (*Client) InstallURL

func (c *Client) InstallURL() string

InstallURL is where a workspace admin installs the app (and grants repos).

func (*Client) InstallVerificationConfigured

func (c *Client) InstallVerificationConfigured() bool

InstallVerificationConfigured reports whether the OAuth credentials needed to verify installation administration are present (F2). The composition root wires the Service's Verifier only when this is true.

func (*Client) ListBranches

func (c *Client) ListBranches(ctx context.Context, installationID int64, owner, repo string) ([]string, error)

ListBranches returns a bounded branch inventory of owner/repo, following pagination (per_page=100, `Link` rel="next"). It mints a fresh installation token first. (w5/m54 — feeds the dashboard's searchable Branch combobox.)

func (*Client) ListCheckRuns

func (c *Client) ListCheckRuns(ctx context.Context, token, owner, repo, sha string) ([]CheckRun, error)

ListCheckRuns lists the latest check run of every check on sha (GET /repos/{owner}/{repo}/commits/{sha}/check-runs?filter=latest).

func (*Client) ListRepoTree

func (c *Client) ListRepoTree(ctx context.Context, token, owner, repo, path, ref string) ([]RepoTreeEntry, error)

ListRepoTree returns one non-recursive directory listing at path and ref. The contents response is bounded because this runs interactively from the create wizard and must not let one repository occupy an API worker with an unbounded body. A missing path remains an *APIError{Status: 404}; the service converts it (and other probe failures) to its typed unknown outcome.

func (*Client) ListRepos

func (c *Client) ListRepos(ctx context.Context, installationID int64) ([]Repo, error)

ListRepos returns the bounded repository inventory the installation can access, following pagination (per_page=100, GitHub `Link` header rel="next"). Page, item, byte, origin, cycle, and wall-clock limits prevent a connected installation from consuming an API worker or GitHub quota indefinitely.

func (*Client) LookupRepo

func (c *Client) LookupRepo(ctx context.Context, token, owner, repo string) (Repo, bool, error)

LookupRepo reads owner/repo (GET /repos/{owner}/{repo}) with the given installation token, or anonymously when token is "". An installation token only reaches repos in the installation's grant, so 404 => not reachable (ok=false, no error); 2xx => reachable, with the repository's metadata (default branch included); any other status is an *APIError.

func (*Client) MarkPullRequestReady

func (c *Client) MarkPullRequestReady(ctx context.Context, installationID int64, repo, nodeID string) error

MarkPullRequestReady undrafts the pull request whose GraphQL node id is nodeID, in repository repo of the installation. REST cannot undraft: `PATCH …/pulls/{n}` takes no draft field, and `gh pr ready` sends this same mutation. A GraphQL error comes back as an *APIError (gitHubGraphQL).

func (*Client) MergePullRequest

func (c *Client) MergePullRequest(ctx context.Context, installationID int64, owner, repo string, number int, opts MergeOptions) (MergeResult, error)

MergePullRequest merges pull request number of owner/repo with the synchronous REST merge (PUT …/pulls/{n}/merge), whose answer is final: 200 merged, 405 not mergeable (checks, reviews, conflicts, rules), 409 the head is not opts.SHA, 422 invalid, 403 not permitted. A branch that requires a merge queue takes the pull request through EnqueuePullRequest instead, and GitHub refuses this merge for a pull request in a stack, which lands through MergePullRequestAsync (w10/053). A method the repository does not allow is a *MergeMethodError before any merge is sent. The token is mergeToken's.

func (*Client) MergePullRequestAsync

func (c *Client) MergePullRequestAsync(ctx context.Context, installationID int64, owner, repo string, number int, opts MergeOptions) (AsyncMergeResult, error)

MergePullRequestAsync merges pull request number of owner/repo with GitHub's asynchronous merge (PUT …/pulls/{n}/merge-async), the only call that lands a pull request in a GitHub stack: atomically with every open pull request below it, or into the merge queue the stack's base (opts.Base) requires (merge_action default), as Devin's merge button does (w10/053). It is pinned to opts.SHA and uses the method rule of MergePullRequest with the commit text when given; GitHub applies them to a direct merge only. It waits for the result for AsyncMergeWait at most. GitHub's refusal is an *APIError, and a merge GitHub failed an *AsyncMergeFailedError. A merge of the pull request already pending answers 409 with its own pin: at the same head its result is waited for, and at another head the 409 is returned.

func (*Client) MintChecksToken

func (c *Client) MintChecksToken(ctx context.Context, installationID int64) (InstallationToken, bool, error)

MintChecksToken mints an installation token that may read check runs (w1/m181). GitHub refuses the mint with 422 when the installation has not granted Checks: read, which is reported as permitted=false rather than an error: it is the answer to "can this connection gate on checks".

func (*Client) MintInstallationToken

func (c *Client) MintInstallationToken(ctx context.Context, installationID int64) (InstallationToken, error)

MintInstallationToken exchanges the app JWT for a 1h installation access token for the given installation. The existing deploy/list/commit path needs all installation repositories but remains explicitly read-only even though the App itself now holds contents:write for agent sessions.

func (*Client) MintRepositoryAPIReadToken

func (c *Client) MintRepositoryAPIReadToken(ctx context.Context, installationID int64, repository string) (InstallationToken, error)

MintRepositoryAPIReadToken mints the read-only GitHub API credential of a session's `gh` route (ADR090 D4 amendment w10/m513): one repository and read permissions only (Actions runs and logs, check runs, commit statuses, pull requests, contents), so whatever the gateway lets through, the token can neither write nor reach another private repository. An installation that has not granted Actions or Commit statuses (an App from the older manifest) refuses that set with 422, so the mint retries with what that manifest holds; `gh run` then gets GitHub's own 403.

func (*Client) MintRepositoryAPIWriteToken

func (c *Client) MintRepositoryAPIWriteToken(ctx context.Context, installationID int64, repository string) (InstallationToken, error)

MintRepositoryAPIWriteToken mints the credential of one admitted write of a session's `gh` route (w10/m522), narrowed to the one repository. An installation that has not granted all of apiWritePermissions refuses the set with 422; the mint then reads what the installation holds and asks for the intersection, so a write the installation lacks gets GitHub's own 403 while the others still work.

func (*Client) MintRepositoryReadToken

func (c *Client) MintRepositoryReadToken(ctx context.Context, installationID int64, repository string) (InstallationToken, error)

MintRepositoryReadToken mints a repository environment build's clone credential (ADR111): contents read-only, so the token cannot push whatever the gateway lets through.

func (*Client) MintSessionInstallationToken

func (c *Client) MintSessionInstallationToken(ctx context.Context, installationID int64, repository string) (InstallationToken, error)

MintSessionInstallationToken mints the Git credential used by one agent session. GitHub's request accepts repository NAMES (the installation itself fixes the owner), so callers must separately bind owner/account before reaching this method. It is a repository write token (see mintRepositoryWriteToken); metadata stays read-only. The token expires after GitHub's fixed one-hour TTL.

func (*Client) PullRequestMergeState

func (c *Client) PullRequestMergeState(ctx context.Context, installationID int64, repo, nodeID string) (MergeState, error)

PullRequestMergeState reads the merge state of the pull request whose GraphQL node id is nodeID, in repository repo of the installation, with a Pull requests read token, as the PR read is.

func (*Client) ReviewComments

func (c *Client) ReviewComments(ctx context.Context, installationID int64, owner, repo string, number int, reviewID int64) ([]ReviewComment, error)

ReviewComments lists one review's inline comments (at most maxFeedbackItems).

func (*Client) Slug

func (c *Client) Slug() string

Slug is the configured app slug (used to build install URLs).

func (*Client) SuiteCheckRuns

func (c *Client) SuiteCheckRuns(ctx context.Context, installationID int64, owner, repo string, suiteID int64) ([]CheckRun, error)

SuiteCheckRuns lists a check suite's check runs (at most maxFeedbackItems).

func (*Client) SyncPullRequest

func (c *Client) SyncPullRequest(ctx context.Context, installationID int64, owner, repo, head, title, body string, draft bool) (PullRequestSyncResult, error)

SyncPullRequest opens a PR from head into the repository's default branch, ready for review unless draft asks for a draft (ADR090 D3, w10/040: Devin opens a regular pull request by default), or — when an open PR for head already exists — updates that PR's title and body (ADR090: one branch, one PR per session, so a steering turn updates the same PR). draft is read only when the PR is opened: it never changes draft state, base, or head of an existing PR. It refuses with ErrHeadBranchNotFound when head is not on GitHub, ErrHeadNotAhead when head has no commits base lacks, and ErrDraftNotSupported when GitHub refuses the draft. The installation token is minted per call, narrowed to the one repository with pull_requests:write + contents:read, and never returned to the caller.

func (*Client) VerifyInstallationAdmin

func (c *Client) VerifyInstallationAdmin(ctx context.Context, code string, installationID int64) (bool, error)

VerifyInstallationAdmin reports whether the GitHub user identified by the install-callback OAuth `code` actually administers installationID — the principal proof the connect callback needs so an App-JWT lookup is never mistaken for ownership (F2). It exchanges the code for a short-lived user token, resolves the installation's owning account, and requires either the exact personal-account owner or an active organization membership with role `admin`. Merely seeing an installation or one selected repository is not an administration proof.

type Commit

type Commit struct {
	SHA      string     `json:"sha"`
	Message  string     `json:"message"`
	AuthorAt *time.Time `json:"authorAt,omitempty"`
}

Commit is the resolved tip of a ref — the SHA plus its message and author timestamp (w9/001 + w2/m42). The subset of GitHub's commit object the deploy path stamps onto a deploy row as provenance.

type Config

type Config struct {
	AppID      string // numeric GitHub App id (the JWT `iss`)
	PrivateKey string // RSA private key, PEM (out-of-band secret)
	Slug       string // app slug, builds the install URL
	// ClientID / ClientSecret are the App's OAuth credentials, used ONLY to verify
	// that the user completing an install actually administers the installation
	// (F2, docs/ADR026-github-integration.md). Both empty leaves existing
	// connection reads/deploys available but makes every new binding fail closed;
	// exactly one set is invalid configuration. The App must enable "Request user
	// authorization (OAuth) during installation" so the callback carries a code.
	ClientID     string
	ClientSecret string
}

Config is the GitHub App configuration read once at startup from BEX_GITHUB_APP_ID / BEX_GITHUB_APP_PRIVATE_KEY / BEX_GITHUB_APP_SLUG. Any field empty (or an unparseable id/key) => NewClient errors and the caller leaves the github service unconfigured (503).

type Connection

type Connection struct {
	Connected      bool   `json:"connected"`
	AccountLogin   string `json:"accountLogin,omitempty"`
	InstallationID int64  `json:"installationId,omitempty"`
	CreatedAt      string `json:"createdAt,omitempty"`
	InstallURL     string `json:"installUrl"`
}

Connection is the neutral connection view every adapter renders. InstallURL is always populated (the connect CTA the human clicks); the rest are set only when Connected.

type ConnectionStore

type ConnectionStore interface {
	// BindGitConnection atomically enforces BOTH quotas — the workspace's
	// connection fan-in and the installation's workspace fan-out (ADR078 §2) —
	// while inserting or refreshing one binding.
	BindGitConnection(ctx context.Context, c store.GitConnection, maxConnections, maxWorkspaces int) (store.GitConnection, error)
	GetGitConnection(ctx context.Context, workspaceID string) (store.GitConnection, error)
	// ListGitConnections returns a workspace's full connection set, oldest first
	// (ADR078) — the multi-account aggregate the repo picker and list surface read.
	ListGitConnections(ctx context.Context, workspaceID string) ([]store.GitConnection, error)
	// GetGitConnectionByOwner resolves the connection whose account login matches a
	// repo's owner — the exact installation to mint that repo's token from (ADR078 §4).
	GetGitConnectionByOwner(ctx context.Context, workspaceID, accountLogin string) (store.GitConnection, error)
	// GitConnectionsByInstallation resolves every workspace that has proved a
	// binding for an installation (ADR078 §2, N:N). The push webhook's reverse
	// lookup; empty means act on nothing (§4a).
	GitConnectionsByInstallation(ctx context.Context, installationID int64) ([]store.GitConnection, error)
	// CountGitConnections backs the per-workspace connection quota (ADR078 §2).
	CountGitConnections(ctx context.Context, workspaceID string) (int, error)
	DeleteGitConnection(ctx context.Context, workspaceID string, installationID int64) error
	// The subject-bound, single-use connect transaction (w1/m67 F3): the record
	// that ties "who started this flow" to "who came back from GitHub".
	CreateGitHubConnectTransaction(ctx context.Context, t store.GitHubConnectTransaction) error
	ConsumeGitHubConnectTransaction(ctx context.Context, nonce string) (store.GitHubConnectTransaction, error)
	// The deferred claim selector (ADR078 §3a): an ambiguous claim's already-proved
	// candidate set, held single-use for the few minutes the human needs to choose.
	CreateGitHubClaimSelection(ctx context.Context, sel store.GitHubClaimSelection) error
	GetGitHubClaimSelection(ctx context.Context, id string) (store.GitHubClaimSelection, error)
	ConsumeGitHubClaimSelection(ctx context.Context, id string) (store.GitHubClaimSelection, error)
}

ConnectionStore is the Service's seam to the control-plane store — the narrow slice of Store it needs. *store.PGStore satisfies it; a fake backs the tests. nil => the control-plane store is off (BEX_CP_DB_URI unset) and every verb reports core.ErrGitHubUnavailable.

type FileContents

type FileContents struct {
	Contents string
}

FileContents is the decoded content of a repository file (w2/m62 — blueprint manifest fetch). The caller names the exact ref (branch or immutable commit) it wants; provenance comes from the ref it passed, never from this struct — w8/m36 removed the old blob-SHA-as-commit fallback, which fabricated sync provenance whenever branch resolution failed.

type Installation

type Installation struct {
	ID           int64  `json:"id"`
	AccountLogin string `json:"accountLogin"`
	AccountType  string `json:"accountType"`
	// Events are the webhook events this installation receives — the App's
	// subscriptions the installation has accepted (w1/m181 reads check_suite).
	Events []string `json:"events,omitempty"`
	// Permissions are the App permissions the installation has granted
	// (name → "read"/"write"); the `gh` write mint narrows to them (w10/m522).
	Permissions map[string]string `json:"-"`
}

Installation identifies a GitHub App installation and the account it belongs to. Fetched with the app JWT, so a forged/unknown id fails authentication — which is how Connect validates a browser-supplied installation_id.

type InstallationToken

type InstallationToken struct {
	Token     string    `json:"token"`
	ExpiresAt time.Time `json:"expiresAt"`
}

InstallationToken is a short-lived (1h) installation access token.

type InstallationVerifier

type InstallationVerifier interface {
	VerifyInstallationAdmin(ctx context.Context, code string, installationID int64) (bool, error)
	// AuthorizeURL is the app's OAuth user-authorization endpoint — the claim
	// flow's start, the one GitHub flow that always preserves `state` (§3a).
	AuthorizeURL() string
	// ClaimableInstallations resolves the claim callback's missing installation
	// id: this app's installations the code's user ADMINISTERS.
	ClaimableInstallations(ctx context.Context, code string) ([]Installation, error)
}

InstallationVerifier proves the user completing a browser flow actually administers the installation being bound (F2), and powers the ADR078 §3a claim flow for already-installed accounts. Implemented by *Client when the App's OAuth credentials are configured; nil => connect/claim starts refuse up front (§7) and the callback fails closed. Kept an interface so the fake in tests can drive accept/reject.

type MergeMethodError

type MergeMethodError struct {
	Method  string
	Allowed []string
}

MergeMethodError refuses a method the repository does not allow, before GitHub is asked to merge. Allowed lists the ones it does, in order.

func (*MergeMethodError) Error

func (e *MergeMethodError) Error() string

type MergeOptions

type MergeOptions struct {
	SHA           string
	Method        string
	CommitTitle   string
	CommitMessage string
	Base          string
	// IncludeStack arms auto-merge on the pull request's GitHub stack
	// (includeStack, w10/048): GitHub lands it with every unmerged pull
	// request below it once they are all ready, on the stack's base, which
	// Base then names.
	IncludeStack bool
}

MergeOptions is one merge of a pull request. SHA pins it to the head bex recorded: GitHub refuses with 409 when the head moved. Method "" takes the first method the repository and its base branch's rules allow. Base is the pull request's base branch, whose rules are read for that choice.

type MergeResult

type MergeResult struct {
	SHA    string
	Method string
}

MergeResult is a merged pull request: the commit its merge created on the base branch and the method that made it.

type MergeState

type MergeState struct {
	// MergeQueueEnabled is set when the base branch requires a merge queue
	// (GraphQL isMergeQueueEnabled, rulesets and classic protection alike).
	MergeQueueEnabled bool
	// InMergeQueue is set when the pull request is in the queue already.
	InMergeQueue bool
	// Status is GitHub's mergeStateStatus: CLEAN, UNSTABLE, HAS_HOOKS,
	// BLOCKED, BEHIND, DIRTY, DRAFT or UNKNOWN.
	Status string
	// AutoMerge is the auto-merge armed on the pull request, nil when none
	// is: its method in lower case, and who armed it when (w10/047). On a
	// stacked pull request it is the stack's auto-merge request covering it
	// when there is one (StackAutoMerge), armed on it or on one above it.
	AutoMerge *store.PRAutoMerge
	// Stacked is set when the pull request is in a GitHub stack, where each
	// pull request targets the branch of the one below it and StackBase is
	// the branch the stack lands on (w10/048).
	Stacked   bool
	StackBase string
	// StackAutoMerge is set when AutoMerge is the stack's auto-merge request,
	// which GitHub disarms for every pull request it covers at once.
	StackAutoMerge bool
	// StackLands is how many pull requests merging it lands: it and every
	// open pull request below it in its stack, which GitHub merges with it
	// (w10/053). It is 0 when it is in no stack, or when the read did not see
	// every pull request below it.
	StackLands int
}

MergeState is what tells merging now, arming GitHub auto-merge and the merge queue apart (w10/m577): the fields gh pr merge reads before it chooses.

func (MergeState) MergeableNow

func (s MergeState) MergeableNow() bool

MergeableNow is gh's isImmediatelyMergeable: GitHub would merge the pull request now, and refuses to arm auto-merge on it.

type PullRequest

type PullRequest struct {
	Number  int    `json:"number"`
	HTMLURL string `json:"htmlUrl"`
	State   string `json:"state"`
	Draft   bool   `json:"draft"`
}

PullRequest is the subset of a GitHub pull request the agent-session PR verb records (ADR047 D4, ADR090). JSON tags are bex-api's camelCase shape, not GitHub's snake_case wire shape.

type PullRequestDetail

type PullRequestDetail struct {
	PullRequest
	// NodeID is the pull request's GraphQL id, which undrafting it needs.
	NodeID string
	Title  string
	// Merged is set on a merged pull request, whose State is closed.
	Merged  bool
	HeadRef string
	HeadSHA string
	// HeadRepo is the head repository's owner/name, empty when the fork the
	// pull request came from was deleted. BaseRepo is the repository it
	// targets, whose default branch is DefaultBranch.
	HeadRepo      string
	BaseRepo      string
	DefaultBranch string
	// BaseRef is the branch the pull request merges into.
	BaseRef string
}

PullRequestDetail is what a `/bex` takeover and a takeover session's PR verb read of one pull request: its state, head and base.

type PullRequestSyncResult

type PullRequestSyncResult struct {
	PullRequest
	Created bool
	HeadSHA string
}

PullRequestSyncResult is the outcome of SyncPullRequest. HeadSHA is the remote head the PR now points at.

type Repo

type Repo struct {
	ID            int64  `json:"id"`
	FullName      string `json:"fullName"`
	Private       bool   `json:"private"`
	DefaultBranch string `json:"defaultBranch"`
	HTMLURL       string `json:"htmlUrl"`
	CloneURL      string `json:"cloneUrl"`
	// AccountLogin and InstallationID are set by the service when it aggregates
	// repos across a workspace's several connections (ADR078 §4), so the picker
	// can group repos by GitHub account. The client itself leaves them zero.
	AccountLogin   string `json:"accountLogin,omitempty"`
	InstallationID int64  `json:"installationId,omitempty"`
}

Repo is the subset of a GitHub repository the repo picker and deploy path need. JSON tags are the bex-api camelCase shape (identical across surfaces), not GitHub's snake_case wire shape (decoded via ghRepo below).

type RepoTreeEntry

type RepoTreeEntry struct {
	Name string `json:"name"`
	Type string `json:"type"`
}

RepoTreeEntry is one immediate child returned by GitHub's contents API. The service keeps only Type == "file" before runtime detection; retaining Type at this seam prevents a same-named directory from masquerading as a manifest.

type RepoTreeProbe

type RepoTreeProbe struct {
	Entries []RepoTreeEntry
	Unknown bool
}

RepoTreeProbe is the typed result of the best-effort repository listing used by runtime detection. Unknown is deliberately data, not an error: a missing directory, empty repository, rate limit, or GitHub outage must leave the create wizard on its existing manual runtime selection path.

type Review

type Review struct {
	Body  string
	State string
	URL   string
}

Review is one submitted pull request review. State is lowercase, as webhook payloads spell it (commented, changes_requested, approved).

type ReviewComment

type ReviewComment struct {
	Path string `json:"path"`
	Line int    `json:"line"`
	Body string `json:"body"`
	URL  string `json:"html_url"`
}

ReviewComment is one inline comment of a pull request review.

type RuntimeDetection

type RuntimeDetection struct {
	Runtime         string
	MatchedManifest string
}

RuntimeDetection is the dashboard-facing verdict for one repository directory. Empty fields mean unknown; GraphQL renders them as null.

func DetectRuntime

func DetectRuntime(entries []RepoTreeEntry) RuntimeDetection

DetectRuntime is a pure manifest-to-runtime mapping. Dockerfile wins; one unique native runtime wins; no signal or conflicting native signals are unknown. Multiple manifests for the same runtime (Python's two supported forms) are not ambiguous and retain the first table entry as evidence.

type Service

type Service struct {
	*core.Base
	GitHub APIClient       // nil => GitHub App unconfigured
	Store  ConnectionStore // nil => control-plane store off
	// Verifier proves installation administration on the browser connect callback
	// (F2). nil => not configured; the unique-binding gate still applies.
	Verifier InstallationVerifier
	// StateSecret signs the short-lived workspace credential carried through the
	// browser install redirect. Production reuses BEX_GITHUB_APP_PRIVATE_KEY's
	// PEM bytes, so no second platform secret or replica-local state is needed.
	StateSecret []byte
	// DashboardURL is BEX_DASHBOARD_URL — where the install callback redirects
	// the browser after success or with a bounded failure code. Empty => the
	// callback returns JSON instead of redirecting.
	DashboardURL string
	// MaxConnections caps how many GitHub installations ONE workspace may connect
	// (BEX_MAX_GIT_CONNECTIONS_PER_WORKSPACE, ADR078 §2; default 10, 0 disables).
	// Bounds one tenant's connection fan-in — and therefore the per-connection
	// GitHub round trips ListRepos makes.
	MaxConnections int
	// MaxWorkspacesPerInstallation is MaxConnections' mirror under N:N
	// (BEX_MAX_WORKSPACES_PER_GIT_INSTALLATION, ADR078 §2; default 10, 0
	// disables): how many workspaces ONE installation may serve, which is also
	// how wide a single push delivery can fan out (§4a).
	MaxWorkspacesPerInstallation int
	// contains filtered or unexported fields
}

Service manages a workspace's GitHub App connection and lists its repos over the injected client + store. Both seams must be present; either nil => 503.

func (*Service) BlueprintFileFetcher

func (s *Service) BlueprintFileFetcher() blueprintFetcher

BlueprintFileFetcher returns the blueprint-file-fetch seam wired in the composition root onto apps.Service.

func (*Service) DeployChecksSource

func (s *Service) DeployChecksSource() checksSource

DeployChecksSource returns the checksPass seam (wired onto apps.Service in the composition root).

func (*Service) DeployCommitSource

func (s *Service) DeployCommitSource() commitSource

DeployCommitSource returns the deploy path's commit-resolution seam (wired onto deploys.Service and apps.Service in the composition root).

func (*Service) DeployTokenSource

func (s *Service) DeployTokenSource() tokenSource

DeployTokenSource returns the deploy path's clone-token seam (wired onto apps.Service in the composition root).

func (*Service) DetectRepoRuntime

func (s *Service) DetectRepoRuntime(ctx context.Context, ownerID, repoURL, branch, rootDir string) (RuntimeDetection, error)

DetectRepoRuntime combines the authorized GitHub probe with the pure heuristic. Probe failures and unrecognized trees intentionally return an empty verdict without a transport error so the wizard remains manual.

func (*Service) Disconnect

func (s *Service) Disconnect(ctx context.Context, ownerID string, installationID int64) error

Disconnect removes one of ownerID's connections. installationID names the exact connection to remove; with no ownerID it acts in the workspace that connection is bound in (w4/m172, scopeInstallation) rather than the caller's default, so a member of several workspaces disconnects any of theirs by id. 0 targets the sole connection of ownerID's workspace ("" => the caller's default, w6/m18 — the singular-alias behavior) and is refused with ErrConflict when the workspace holds several — an ambiguous "disconnect" must not silently pick one. Idempotent: disconnecting when not connected is a no-op success, and an installation bound only in workspaces the caller is not a member of answers that SAME no-op (deleting nothing), so the verb is no existence oracle. Admin-only.

func (*Service) GetClaimSelection

func (s *Service) GetClaimSelection(ctx context.Context, ownerID, selectionID string) (ClaimSelection, error)

GetClaimSelection renders an outstanding selection for the picker WITHOUT consuming it. Admin-gated on ownerID's workspace — or, with no ownerID, on the workspace the selection itself was started for (w4/m172, scopeSelection) — and subject-matched on top: a selection id is a name, not a capability, so it reveals its candidates only to the bex user who started the claim, inside the workspace that claim was for. Unknown, expired, foreign-workspace and foreign-subject selections are all refused identically.

func (*Service) GetConnection

func (s *Service) GetConnection(ctx context.Context, ownerID string) (Connection, error)

GetConnection returns ownerID's connection status ("" => the caller's default workspace, w6/m18) — the singular compatibility alias over the workspace's oldest connection (ADR078). "Not connected" is a valid state, not an error, and (ADR078 §3) carries NO install URL: the bare, stateless URL is no longer advertised as a connect CTA — only the connectGit mutation mints a bindable (stateful) one. A connected row keeps its install URL as a "configure grants on GitHub" deep link. Member read.

func (*Service) GraphQLMutation

func (s *Service) GraphQLMutation() graphql.Fields

GraphQLMutation returns connectGit (returns the connection + install URL), claimGit (the ADR078 §3a claim flow for already-installed accounts), and disconnectGit.

func (*Service) GraphQLQuery

func (s *Service) GraphQLQuery() graphql.Fields

GraphQLQuery returns the gitConnections + gitConnection + repos queries.

func (*Service) InstallationResolver

func (s *Service) InstallationResolver() installationResolver

InstallationResolver returns the webhook's installation→workspace seam (wired onto apps.GitWebhook in the composition root, codex #7).

func (*Service) ListBranches

func (s *Service) ListBranches(ctx context.Context, ownerID, repoURL string) ([]string, error)

ListBranches returns the branch names of repoURL for ownerID's connected installation ("" => the caller's default workspace). It degrades to an empty list — never an error — for a non-github.com repo, no connection, or a repo the installation can't see, so the dashboard falls back to free-text branch entry (w5/m54). Developer and up, like ListRepos.

func (*Service) ListConnections

func (s *Service) ListConnections(ctx context.Context, ownerID string) ([]Connection, error)

ListConnections returns every GitHub installation ownerID's workspace has connected ("" => the caller's default workspace), oldest first — the multi-account surface (ADR078 §5). An empty slice (never an error) means no connection; the caller starts one through the connectGit mutation. Each row's InstallURL is the bare "configure grants on GitHub" deep link. Member read.

func (*Service) ListRepos

func (s *Service) ListRepos(ctx context.Context, ownerID string) ([]Repo, error)

ListRepos returns the repositories across ALL of ownerID's connected installations ("" => the caller's default workspace, w6/m18; private included), each annotated with the GitHub account it came from so the picker can group by account (ADR078 §4). With no connection the list is empty (not an error). One GitHub round trip per connection, run through a fixed worker pool; a single connection's failure degrades that account's slice (logged) rather than failing the whole list.

Developer and up (repoReadRelation): the list names every private repository the workspace's installations grant, deployed here or not.

func (*Service) ProbeRepoTree

func (s *Service) ProbeRepoTree(ctx context.Context, ownerID, repoURL, branch, rootDir string) (RepoTreeProbe, error)

ProbeRepoTree returns the immediate files at rootDir on branch for a repo in ownerID's connected GitHub installation. Developer and up, like ListRepos and ListBranches. Expected probe failures collapse to Unknown so transport adapters never need to understand GitHub's rate-limit or contents dialect.

func (*Service) RegisterMCP

func (s *Service) RegisterMCP(srv *mcp.Server)

RegisterMCP adds the git-connect tools to the shared MCP server.

func (*Service) RegisterREST

func (s *Service) RegisterREST(mux *http.ServeMux)

RegisterREST mounts the GitHub-connect surface. `GET /v1/repos` and the connection verbs are bex extensions (Render exposes repos only via its private dashboard API); naming follows Render's kebab-case noun style. The callback is GitHub's post-install "Setup URL" redirect target. Browser callbacks carry a short-lived signed state credential instead of a dashboard cookie. Every binding also carries GitHub's single-use user-authorization code; bearer authentication alone is never an installation-ownership proof.

func (*Service) SelectClaim

func (s *Service) SelectClaim(ctx context.Context, ownerID, selectionID string, installationID int64) (Connection, error)

SelectClaim completes an ambiguous claim by binding one installation the callback already proved. Admin-gated on ownerID's workspace, or with no ownerID on the selection's own workspace (w4/m172, scopeSelection).

SECURITY: this grants nothing the callback had not established. can_manage is re-checked NOW rather than inherited from the callback (a demotion inside the selection window must not still bind), the presenting subject must equal the initiator, the selection's workspace must be the authorized one, and the installation must be a member of the stored set — so the client chooses among proved options and can never introduce a new one. Every one of those checks runs on a PEEK; only once all pass is the selection consumed atomically (so a replay finds nothing). A refused call — wrong workspace, wrong subject, no can_manage, out-of-set choice — therefore never spends the caller's pending choice (w4/m172: consuming first let a call routed to the wrong workspace destroy the selection and then report it gone).

func (*Service) StartClaim

func (s *Service) StartClaim(ctx context.Context, ownerID string, opts ClaimOptions) (Claim, error)

StartClaim begins the ADR078 §3a claim flow: bind an installation that ALREADY exists on GitHub (the direct-install case) to ownerID's workspace ("" => the caller's default). GitHub strips the signed state from the install URL for already-installed accounts, so the claim rides the OAuth user-authorization flow instead — the one flow that always preserves state — and the callback resolves the installation server-side from the authorizing user's admin set. Admin-only, same transaction record as StartConnect (w1/m67 F3).

func (*Service) StartConnect

func (s *Service) StartConnect(ctx context.Context, ownerID string) (Connection, error)

StartConnect returns the current connection state plus the install URL the admin clicks to install the app (and grant repos). Admin-only — connecting a workspace's GitHub is an admin action even though the record lands at the callback. ownerID ("" => the caller's default workspace, w6/m18) names the workspace to check/connect, membership-checked via core.WithWorkspace like every other explicit-target verb. The returned install URL carries that resolved workspace in a short-lived signed state credential, so GitHub's identity-less callback can safely record against the same workspace.

Jump to

Keyboard shortcuts

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